Skip to content

Multimodal stack 1/3: mixed-precision training, empty-modality processors and collate pad masks - #1595

Draft
jhnwu3 wants to merge 10 commits into
masterfrom
mm/01-foundations
Draft

jhnwu3 wants to merge 10 commits into
masterfrom
mm/01-foundations

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: core changes (Trainer, BaseDataset, collation, shared processors) that the multimodal models need.

This is PR 1 of 3 that bring the Multimodal-PyHealth design into PyHealth. It replaces #1185, which had grown to 50 files and is in conflict.

  1. This PR: training and data-path foundations.
  2. Multimodal stack 2/3: unified embedding, frozen text cache, unified mode in five backbones, BottleneckTransformer #1596: unified embedding, frozen text cache, unified mode in five backbones, BottleneckTransformer.
  3. Multimodal stack 3/3: NotesLabsMIMIC4 and LabsMIMIC4 tasks, end-to-end runner and run records #1597: NotesLabsMIMIC4 and LabsMIMIC4 tasks, end-to-end runner, run records.

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

Commit Change Earlier review What an existing user sees with no new arguments
11bed91 Trainer.train(accumulation_steps, use_amp, amp_dtype): mixed precision and gradient accumulation approved in part Nothing
29104e4 Attention masks are filled with finfo(dtype).min, and ordinary forwards use fused scaled-dot-product attention waiting on @joshuasteier Fused attention on ordinary forwards; outputs equal at valid positions
1903dce BaseDataset(use_dask_distributed=True); False builds the event cache with the local Dask scheduler not reviewed Nothing
424caaa Empty modalities give zero-length tensors (StageNet and time-image processors) approved Empty inputs give length-0 tensors instead of a placeholder or an error
494bdca TupleTimeTextProcessor drops null and blank notes and pads to the longest note in the sample approved Padding width is per sample; default max_length goes from 128 to 512
f437842 StageNetTensorProcessor(forward_fill=True); False is for observation masks not reviewed Nothing
f38178b StageNet processors keep scanning past empty samples when fitting not reviewed Bug fix: fitting no longer stops at the first sample
82888df The collator pads every ragged dimension when it stacks a pair's tensors. The original commit also stacked longer tuples; the port fix below takes that back out not reviewed None
dcc3f02 The collator emits {field}__pad_mask when samples in a batch differ in length asked for another reviewer Batches gain {field}__pad_mask keys
769a813 Port fix: the shared collator stacks pairs only, as on master; TupleTimeTextProcessor.collate() stacks tokenized text new Tokenized text batches are stacked tuples; every other non-pair tuple stays a list, as on master

Why these are together

They are everything PR 2 and PR 3 need from the rest of the library. Without the pad masks, padded zeros look like real measurements taken at admission time. Without the dtype-min fill, -1e9 overflows in fp16 under AMP.

Changes made while porting to current master

  • Dropped from the fork series: the commit that added worker options to get_dataloader. Master already forwards **loader_kwargs to DataLoader (feat(imaging): add medical image IO layer #1386).

  • use_dask_distributed=False now uses master's dev-mode fix (head(1000, npartitions=-1), Fix dev mode keeping far fewer than 1000 patients #1434) and master's parquet options (_event_parquet_options), the same as the cluster path. MIMIC4Dataset passes the flag to its ED sub-dataset too. The flag is not part of the cache key.

  • Tuple collation. The fork made the shared collator stack tuples of any length. On master, DiPro, TimeRegionImageProcessor and the time-image UnifiedBridge read non-pair tuples as a list of per-sample tuples, and 30 of their tests failed. The shared collator now stacks pairs only, as master does, and TupleTimeTextProcessor stacks its own tokenized tuples through the processor collate() hook. Text gets no {field}__pad_mask key; a padded note is the one with an all-zero attention mask, which the unified model already falls back to. Without a tokenizer the text batch stays a list, as on master.

Files to review

  • pyhealth/trainer.py
  • pyhealth/models/transformer.py (attention only)
  • pyhealth/datasets/base_dataset.py, pyhealth/datasets/mimic4.py
  • pyhealth/datasets/utils.py, pyhealth/datasets/collate.py
  • pyhealth/processors/stagenet_processor.py, time_image_processor.py, tuple_time_text_processor.py
  • 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 alone: the test files it adds or changes, plus the DiPro, time-region image, disease progression and UnifiedBridge tests, pass. The full suite was not rerun on this branch by itself after the tuple collation fix.
  • Not run for this port: GPU, AMP on a real device, real MIMIC-IV. The fork's earlier GPU checks (fp16 and bf16 with gradient accumulation stay finite) were on an earlier build.

rianfyi and others added 10 commits November 23, 2026 20:46
Validates amp_dtype (unknown spellings raise), follows the trainer device
for autocast, and steps every accumulation_steps batches with GradScaler
for fp16. With use_amp=False the step matches upstream: clip only when
max_grad_norm is set, with no unconditional grad-norm pass and no skipping.

Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95
The -1e9 fill overflows fp16 under AMP; the explicit path behind
register_hook fills with finfo(dtype).min instead. Ordinary forwards
use scaled_dot_product_attention; rows whose keys are all masked (an
all-padded sample) attend uniformly and are zeroed by the query mask,
so the fused path stays finite. Interpretability readers only see the
explicit path, where attn_map and gradients are still captured.

Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95
BaseDataset takes use_dask_distributed=True. False writes the event cache
with the local Dask scheduler instead of starting a distributed cluster,
for sandboxes where the cluster cannot start. True keeps the distributed
path unchanged. The flag does not affect the cache key. A synthetic
end-to-end run shows both paths write the same cache contents.

Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95
Empty code lists, lab series, and image lists now encode as zero-length tensors instead of a fake pad token, pad visit, or black frame, so missingness is visible to the mask logic instead of looking like a real event.

Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95
Malformed texts and unparseable timestamps are dropped with their times, empty note lists return zero-length tensors, tokenization pads to the longest note in the sample bounded by max_length (default now 512), and missing tokenizer fields fall back instead of raising KeyError.

Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95
The multimodal MIMIC-IV tasks declare labs_mask as
("stagenet_tensor", {"forward_fill": False}), but the processor took no
kwargs, so set_task raised TypeError. Port #1185's forward_fill switch
(reference 49c87c6): default True keeps the historical forward-fill;
False writes missing values as 0.0 in place so a 0/1 observation mask can
never turn a later gap into an observed value after an earlier True.

Tests: TestStageNetTensorProcessorForwardFill (spec instantiation through
get_processor, default still fills, no-fill keeps gaps, mask round-trip).

Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95
Both StageNet fits stopped after the first non-None sample even when it
carried no structural information (an empty lab stay or an empty code
list). Real task streams start with whatever patient sorts first, and
the multimodal tasks emit empty-lab records by design, so the labs and
mask processors routinely stayed unfitted: value_dim() reported 1 and
the unified numeric encoder was built with the wrong input width (first
forward dies with a matmul shape error). The codes fit was worse: an
empty-first stream left _is_nested unset and the vocab loop then crashed
with TypeError on the first nested list. Break only once a sample
determines the structure, matching #1185 fit.

Tests: TestStageNetFitSkipsEmptySamples. The empty-first unit tests
fail or crash without it. The fitted-width assertion on the real demo
set_task lands with the tasks commit, which is what needs it.

Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95
collate_fn_dict_with_padding only recognized 2-tuples, so a tokenized
note field -- one 5-tuple (value, mask, token_type_ids, time, tag) per
sample with a ragged note count -- fell through to the keep-as-list
branch. Every unified backbone then crashed in _build_unified_inputs
indexing into per-sample tuples ('tuple' object has no attribute 'to'),
so no notes_labs forward ever ran. Collate each tuple position
independently (tensors pad-stack via _pad_stack, the tag stays a list),
emit the event pad mask from the first non-scalar tensor position, and
keep the 2-tuple contract unchanged.

Tests: TestP1TextTupleCollate (ragged stack + pad mask, 2-tuple
contract). The builder-consumption test lands with the unified
pad-mask threading commit. The two collation tests fail on the old
branch; the contract test passes before and after.

Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95
collate_temporal and collate_fn_dict_with_padding now record {field}__pad_mask wherever they pad, after the collators dispatch so packed sequence_v2 fields never see one. Ragged batching pads every varying dimension, which tokenized notes need.

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

DiPro, TimeRegionImageProcessor and the time-image UnifiedBridge read
non-pair tuples as a list of per-sample tuples, so the shared collator
stacks pairs only, as before. Tokenized text opts into positional
stacking through the processor's collate() hook. A padded note is
recognised by its all-zero attention mask.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@github-actions

Copy link
Copy Markdown

Test Coverage

Total: 86.25% (45524 / 52784 lines)

Modified file Coverage Lines
pyhealth/datasets/base_dataset.py 93.32% 545 / 584
pyhealth/datasets/collate.py 85.42% 41 / 48
pyhealth/datasets/mimic4.py 94.96% 113 / 119
pyhealth/datasets/utils.py 50.97% 105 / 206
pyhealth/models/transformer.py 90.00% 207 / 230
pyhealth/processors/stagenet_processor.py 88.37% 190 / 215
pyhealth/processors/time_image_processor.py 87.80% 108 / 123
pyhealth/processors/tuple_time_text_processor.py 83.65% 87 / 104
pyhealth/trainer.py 79.10% 246 / 311

Workflow run · 769a813

@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 769a813

# Handle empty code list — zero events, not a fake pad token.
if len(codes) == 0:
return torch.tensor([self.code_vocab["<pad>"]], dtype=torch.long)
return torch.zeros((0,), dtype=torch.long)

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] Zero-length StageNet inputs crash an all-empty batch

_encode_codes now returns a zero-length tensor for empty input, and StageNetTensorProcessor.process does the same. If every sample in a batch has an empty field, the padded width is 0. StageNet's layer then loops over zero steps and calls torch.stack(origin_h) on an empty list (pyhealth/models/stagenet.py:228), which raises. The old single-pad placeholder avoided this. Fix: keep zero events in the processor output but have the collator or model handle width 0 (for example, pad the batch to at least one step), and add a test that runs StageNet forward on an all-empty batch.

def _zero_image_tensor(self) -> torch.Tensor:
"""Return a zero tensor matching the expected image shape (C, H, W).

Used as a placeholder when an image path is an empty string.

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] _zero_image_tensor docstring describes a trigger the code does not use

The docstring says the placeholder is used when an image path is an empty string. The code in _load_single_image returns it only when the path equals self.padding, and an empty string is not checked (Path('').exists() is True and Image.open on a directory fails). Fix: change the docstring to say the placeholder is returned when the path equals the padding sentinel.

"""
if self.tokenizer is None:
return list(values)
from pyhealth.datasets.collate import _pad_stack

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] Processor imports private _pad_stack from the collate module without a description of the link

TupleTimeTextProcessor.collate imports the underscore-prefixed helper _pad_stack from pyhealth.datasets.collate. An underscore suggests the helper is not meant to be shared across components, and the PR description does not name this link. Either confirm the sharing and explain it in the description, or keep the processor self-contained by writing its own padding loop. Both are reasonable; the description should say which.


from pyhealth import BASE_CACHE_PATH
from pyhealth.utils import create_directory
from pyhealth.datasets.collate import _pad_stack

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] Dataset collation imports private _pad_stack from collate.py without a description of the link

datasets/utils.py now imports the underscore-prefixed _pad_stack from datasets/collate.py, replacing pad_sequence. The description calls collate.py the shared collator but does not mention this import or why the helper is shared. Either confirm the sharing and explain it in the description, or make the helper public or keep a local copy. Both are reasonable; the description should say which.

@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 PR. It adds mixed-precision and gradient-accumulation training, fp16-safe fused attention, empty-modality processors, a Dask opt-out, and collate pad masks. The commit-by-commit table and the port notes make it much easier to review. It is close, but a few items need fixing first.

This change touches core code. It changes Trainer.train, BaseDataset.__init__ and _event_transform, and the shared collation contract in datasets/utils.py and collate.py. Batches now gain {field}__pad_mask keys. It also changes the default max_length of the shared TupleTimeTextProcessor. These shared contracts affect every model and dataset, so a maintainer needs to review it and it can't be approved automatically.

To get this merged:

  1. Empty StageNet inputs now give zero-length tensors, and I think an all-empty batch can crash StageNet. Its layer calls torch.stack on an empty list (around stagenet.py:228), which the old single-pad-token placeholder avoided. Please handle that case in StageNet, or show with a test that it can't happen, and add a test for it.
  2. The _zero_image_tensor docstring in time_image_processor.py says it is used for an empty path string. The code triggers it only on the padding sentinel. Please fix the docstring.
  3. Sharing between components needs to be explained in the description. TupleTimeTextProcessor.collate and datasets/utils.py both import the private _pad_stack from datasets/collate.py. Please either confirm this sharing is intended and say why in the description, or keep each component self-contained.
  4. The new padding option on TimeImageProcessor isn't mentioned in the description. Please add a line on it.

Optional suggestions:

  • The tokenizer tests now check bounds (<= 16) instead of exact shapes. A stub-tokenizer test already covers the exact width, so this is fine, but you could say so in a comment.
  • torch.amp.GradScaler("cuda") is always CUDA-specific. fp16 on CPU or MPS would skip the scaler anyway, so you could note that in the docs.

Coverage: the repository total is 86.25%, above the 60% bar. Most changed files are above 80%. pyhealth/trainer.py is at 79.1%, just under the bar, because the CUDA/fp16 scaler paths aren't run on CPU. pyhealth/datasets/utils.py is at 50.97%, well under 80%. Please add tests that cover the changed collate branches there, such as scalar and None time handling, and the tensor padding path.

Reviewed commit 769a813

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