Skip to content

Multimodal stack 2/3: unified embedding, frozen text cache, unified mode in five backbones, BottleneckTransformer - #1596

Draft
jhnwu3 wants to merge 17 commits into
mm/01-foundationsfrom
mm/02-unified-models
Draft

jhnwu3 wants to merge 17 commits into
mm/01-foundationsfrom
mm/02-unified-models

Conversation

@jhnwu3

@jhnwu3 jhnwu3 commented Nov 24, 2026 •

Copy link
Copy Markdown
Collaborator

Contributor: Rian (@rianfyi) wrote the commits; John Wu (@jhnwu3) ported them onto current master.
Contribution type: model changes and one new model.

PR 2 of 3 that bring the Multimodal-PyHealth design into PyHealth. It is stacked on #1595, so the diff here holds only this PR's commits. #1597 sits on top.

Each commit makes one change and has its own tests, so the Commits tab is the easiest way to review. The commits come from Multimodal-PyHealth#56. "Earlier review" is the verdict the same change got in #1185.

Commits

UnifiedMultimodalEmbeddingModel

Commit Change Earlier review Default change
5ac1caa Time embedding spans 1 hour to 10 years on geometric wavelengths; the old one wrapped every 30 days approved New time embedding; existing test values updated
c6ca07f field_embeddings lets a field reuse a pre-built EmbeddingModel, VisionEmbeddingModel or TextEmbedding; patch image tokens are mean-pooled not reviewed None
3f3c3f2 Nested code events (B, S, C) are flattened; the output gains token_emb (content only) not reviewed None
50e0e60 numeric_standardizers hook before projection; normalize_content layer-norms content approved in part normalize_content=True; padded slots are zeroed
b2e67cb Frozen text encoders stay in eval mode when Trainer calls train() approved None
ad3c39c No ambiguous -1 reshapes on batches with no note or image slots not reviewed None

Frozen text cache

Commit Change Earlier review
81964b0 Frozen [CLS] embeddings are cached, keyed on the real tokens and not the padded row, so a note hits after a shuffle approved
f382bd7 A miss is encoded once per forward, even when the cache is full not reviewed
61a3019 max_frozen_text_cache caps the cache; frozen_text_cache_stats reports hits, misses and size not reviewed

The cache lives in memory, per process. It is not in state_dict and nothing is written to disk. It applies only to fields whose text encoder is frozen.

Measured in the fork on the full notes_labs task (180,733 samples, Transformer with 128 dims and 2 layers, frozen Bio_ClinicalBERT, bf16, one seed, one RTX 6000 Ada per arm, on an earlier build of this code):

Train epoch 1 (cold) Train epoch 2 Train epoch 3 Test inference
Cache off 1712 s 1718 s 1708 s 530 s
Cache on 1682 s 439 s 429 s 45 s

Train losses matched to 4 decimals in every epoch, and test PR-AUC differed by 0.0003.

Backbones

Commit Change
e9a3e5f Transformer(unified_embedding=...)
88e5c4c EHRMamba(unified_embedding=...)
3f1703d JambaEHR(unified_embedding=...)
7748336 RNN(unified_embedding=...)
441306c The unified sequence skips slots that collation padded (uses {field}__pad_mask from PR 1)
a66e17f MLP(unified_embedding=...) with the pad mask
73608f0 New model BottleneckTransformer, with a per-field mode and a unified mode
bcb47f9 Port fix: BottleneckTransformer uses BaseModel.mode

With unified_embedding=None (the default) every backbone behaves as it does on master. With it, the model embeds all temporal fields as one time-sorted sequence and runs one encoder over it.

Design notes for reviewers

  • Why not JaggedFeatureProcessor. This work extends UnifiedMultimodalEmbeddingModel and TemporalFeatureProcessor, which master already ships (Smart Processor + Unified Multimodal Embedding Support + HF Tokenization #863), and the measured results were produced on that path. A UnifiedBridge for TupleTimeTextProcessor is not part of this stack.
  • Shared code. _build_unified_inputs is repeated in each backbone on purpose, so that each model file stays self-contained.
  • No existing component is duplicated. Master has no bottleneck-fusion model.

Changes made while porting to current master

  • Every unified forward and BottleneckTransformer use the label processor API from Add LabelProcessor: label semantics live on the label processor #1389 (label_processor.output_size(), .activation, .loss).
  • The label is optional in every unified forward, as in Let common models predict without a label in the batch #1442. The fork's RNN required it and EHRMamba returned a placeholder loss; both now return no loss key without a label.
  • Text fields arrive without a {field}__pad_mask key (see the tuple collation note in PR 1). The unified model then takes a note slot as real when its attention mask has any nonzero entry, a fallback the fork code already had.
  • Conflicts in the five backbone files were resolved by keeping master's per-field path unchanged and adding the unified path beside it.

Files to review

  • pyhealth/models/unified_embedding.py
  • pyhealth/models/transformer.py, rnn.py, mlp.py, ehrmamba.py, jamba_ehr.py
  • pyhealth/models/bottleneck_transformer.py, docs/api/models/pyhealth.models.BottleneckTransformer.rst
  • tests under tests/core/

Verification

  • Full suite, tip of the three-PR stack against master (b74a6a38), same environment, CPU: pytest tests/core gives 4804 passed on the stack and 4644 on master, with the same 5 failures on both. The failing-ID diff is empty in both directions. Three of the five are tokenizer tests that cannot load prajjwal1/bert-tiny in that local environment.
  • Rules: tools/check_pr_rules.py passes for this PR against its base.
  • This PR: tests/core/test_unified_cache.py, the unified tests for each backbone and tests/core/test_bottleneck_transformer.py pass, along with the existing RNN, MLP and Transformer tests.
  • Not run for this port: GPU and real MIMIC-IV. The cache timings above are the fork's, from an earlier build.

rianfyi and others added 17 commits November 23, 2026 21:21
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
…del.

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
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
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
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
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
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
…ull.

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
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
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
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
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
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
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
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
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 a92c25a (model) + 7c4c056 (pad-skip hunk); imports adapted from the embedding/ package to the flat unified_embedding module.

Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95
…neckTransformer.

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 <noreply@anthropic.com>
@github-actions

Copy link
Copy Markdown

Test Coverage

Total: 86.34% (46127 / 53422 lines)

Modified file Coverage Lines
pyhealth/models/__init__.py 100.00% 90 / 90
pyhealth/models/bottleneck_transformer.py 86.85% 185 / 213
pyhealth/models/ehrmamba.py 88.37% 190 / 215
pyhealth/models/jamba_ehr.py 78.76% 152 / 193
pyhealth/models/mlp.py 86.46% 166 / 192
pyhealth/models/rnn.py 93.67% 385 / 411
pyhealth/models/transformer.py 90.58% 250 / 276
pyhealth/models/unified_embedding.py 87.22% 273 / 313

Workflow run · bcb47f9

@jhnwu3

jhnwu3 commented Nov 24, 2026

Copy link
Copy Markdown
Collaborator Author

/review

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed commit bcb47f9


The shared bottleneck encoder and the complete Bottleneck Transformer model.

.. autoclass:: pyhealth.models.MultimodalBottleneckTransformerEncoder

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[medium] Autodoc target for the encoder is not exported from pyhealth.models

The page autodocs pyhealth.models.MultimodalBottleneckTransformerEncoder, but pyhealth/models/init.py only exports BottleneckTransformer (from .bottleneck_transformer import BottleneckTransformer as BottleneckTransformer). Sphinx will not resolve the class, so this part of the API page will be broken. Fix: point the autoclass at pyhealth.models.bottleneck_transformer.MultimodalBottleneckTransformerEncoder, or export the encoder from pyhealth/models/init.py and describe that export in the PR.

import torch.nn as nn

from pyhealth.processors.base_processor import ModalityType, TemporalFeatureProcessor
from pyhealth.models.vision_embedding import PatchEmbedding

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[medium] Unified embedding now depends on VisionEmbeddingModel's PatchEmbedding (not described)

This new import makes UnifiedMultimodalEmbeddingModel depend on the PatchEmbedding layer of vision_embedding.py. The PR description names the field_embeddings reuse but not this import. Either confirm this sharing in the description and say why it is wanted, or keep unified_embedding.py self-contained, for example with its own patch projection. Choose whichever fits the design.

_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),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[medium] Default IMAGE encoder changed without a stated default change

With no field_embeddings entry, IMAGE fields used to get a torchvision resnet18 (with its fc replaced). They now get PatchEmbedding plus mean pooling, and the torchvision fallback is gone. The description's default-change column for c6ca07f says 'None'. Existing callers' image outputs change, and image_size values not divisible by patch_size (default 16) now raise ValueError at construction, which resnet18 accepted. Either state this default change in the description and the docstring, or keep the old default.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI Review

suggestion: need change
decision: human review

Thank you for this contribution. It adds a unified multimodal mode to five backbones, a frozen-text [CLS] cache, and a new BottleneckTransformer model. The per-commit structure and the tests are helpful, and coverage meets the bar: 86.34% overall, and every changed file is at or above about 79%. jamba_ehr.py, at 78.76%, is just under 80%.

This change touches shared code. UnifiedMultimodalEmbeddingModel is used by the unified modes of Transformer, RNN, MLP, EHRMamba, JambaEHR and BottleneckTransformer. The PR changes its defaults: the time embedding scale, normalize_content=True, zeroing of padded slots, and the default image encoder. It also adds a token_emb output key. Every unified-mode caller therefore gets different results, so a maintainer needs to review this and it can't be approved automatically. I can't promise how that review will go.

To get this merged:

  1. The new docs/api/models/pyhealth.models.BottleneckTransformer.rst autodocs pyhealth.models.MultimodalBottleneckTransformerEncoder. pyhealth/models/__init__.py doesn't export that class, so the docs entry won't resolve. Either export it, or point the directive at pyhealth.models.bottleneck_transformer.MultimodalBottleneckTransformerEncoder.
  2. unified_embedding.py now imports PatchEmbedding from vision_embedding.py, which is a new link between components. The description doesn't mention it. Please either confirm in the description that the sharing is intended and say why, or keep unified_embedding.py self-contained.
  3. The default IMAGE encoder changed from a torchvision resnet18 to PatchEmbedding plus mean pooling. The description's default-change column says "None" for the commit that introduced it. Image sizes not divisible by patch_size (16) now fail at construction. Please state this default change and its consequence in the description and docstring.

Optional suggestions:

  • field_embeddings freezes a reused TextEmbedding in place, which changes the caller's object. Consider documenting that.
  • The frozen-text cache isn't invalidated by load_state_dict on the same instance. Consider documenting that too.
  • The BottleneckTransformer tests only check shapes and finiteness. A test for padded or missing modalities would be a useful addition.
  • bottleneck_transformer.py has a trailing __main__ demo block that could be removed.

Reviewed commit bcb47f9

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

status: manual Pending maintainer's review

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants