Repository navigation
Conversation
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>
Test CoverageTotal: 86.34% (46127 / 53422 lines)
|
|
/review |
|
|
||
| The shared bottleneck encoder and the complete Bottleneck Transformer model. | ||
|
|
||
| .. autoclass:: pyhealth.models.MultimodalBottleneckTransformerEncoder |
There was a problem hiding this comment.
[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 |
There was a problem hiding this comment.
[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), |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
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:
- The new
docs/api/models/pyhealth.models.BottleneckTransformer.rstautodocspyhealth.models.MultimodalBottleneckTransformerEncoder.pyhealth/models/__init__.pydoesn't export that class, so the docs entry won't resolve. Either export it, or point the directive atpyhealth.models.bottleneck_transformer.MultimodalBottleneckTransformerEncoder. unified_embedding.pynow importsPatchEmbeddingfromvision_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 keepunified_embedding.pyself-contained.- The default IMAGE encoder changed from a torchvision resnet18 to
PatchEmbeddingplus mean pooling. The description's default-change column says "None" for the commit that introduced it. Image sizes not divisible bypatch_size(16) now fail at construction. Please state this default change and its consequence in the description and docstring.
Optional suggestions:
field_embeddingsfreezes a reusedTextEmbeddingin place, which changes the caller's object. Consider documenting that.- The frozen-text cache isn't invalidated by
load_state_dicton 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.pyhas a trailing__main__demo block that could be removed.
Reviewed commit bcb47f9
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
UnifiedMultimodalEmbeddingModelfield_embeddingslets a field reuse a pre-builtEmbeddingModel,VisionEmbeddingModelorTextEmbedding; patch image tokens are mean-pooled(B, S, C)are flattened; the output gainstoken_emb(content only)numeric_standardizershook before projection;normalize_contentlayer-norms contentnormalize_content=True; padded slots are zeroedTrainercallstrain()-1reshapes on batches with no note or image slotsFrozen text cache
[CLS]embeddings are cached, keyed on the real tokens and not the padded row, so a note hits after a shufflemax_frozen_text_cachecaps the cache;frozen_text_cache_statsreports hits, misses and sizeThe cache lives in memory, per process. It is not in
state_dictand nothing is written to disk. It applies only to fields whose text encoder is frozen.Measured in the fork on the full
notes_labstask (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 losses matched to 4 decimals in every epoch, and test PR-AUC differed by 0.0003.
Backbones
Transformer(unified_embedding=...)EHRMamba(unified_embedding=...)JambaEHR(unified_embedding=...)RNN(unified_embedding=...){field}__pad_maskfrom PR 1)MLP(unified_embedding=...)with the pad maskBottleneckTransformer, with a per-field mode and a unified modeBottleneckTransformerusesBaseModel.modeWith
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
JaggedFeatureProcessor. This work extendsUnifiedMultimodalEmbeddingModelandTemporalFeatureProcessor, which master already ships (Smart Processor + Unified Multimodal Embedding Support + HF Tokenization #863), and the measured results were produced on that path. AUnifiedBridgeforTupleTimeTextProcessoris not part of this stack._build_unified_inputsis repeated in each backbone on purpose, so that each model file stays self-contained.Changes made while porting to current master
BottleneckTransformeruse the label processor API from Add LabelProcessor: label semantics live on the label processor #1389 (label_processor.output_size(),.activation,.loss).losskey without a label.{field}__pad_maskkey (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.Files to review
pyhealth/models/unified_embedding.pypyhealth/models/transformer.py,rnn.py,mlp.py,ehrmamba.py,jamba_ehr.pypyhealth/models/bottleneck_transformer.py,docs/api/models/pyhealth.models.BottleneckTransformer.rsttests/core/Verification
b74a6a38), same environment, CPU:pytest tests/coregives 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 loadprajjwal1/bert-tinyin that local environment.tools/check_pr_rules.pypasses for this PR against its base.tests/core/test_unified_cache.py, the unified tests for each backbone andtests/core/test_bottleneck_transformer.pypass, along with the existing RNN, MLP and Transformer tests.