Repository navigation
Multimodal stack 1/3: mixed-precision training, empty-modality processors and collate pad masks - #1595
Multimodal stack 1/3: mixed-precision training, empty-modality processors and collate pad masks#1595jhnwu3 wants to merge 10 commits into
Conversation
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>
Test CoverageTotal: 86.25% (45524 / 52784 lines)
|
|
/review |
| # 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) |
There was a problem hiding this comment.
[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. |
There was a problem hiding this comment.
[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 |
There was a problem hiding this comment.
[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 |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
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:
- Empty StageNet inputs now give zero-length tensors, and I think an all-empty batch can crash StageNet. Its layer calls
torch.stackon an empty list (aroundstagenet.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. - The
_zero_image_tensordocstring intime_image_processor.pysays it is used for an empty path string. The code triggers it only on thepaddingsentinel. Please fix the docstring. - Sharing between components needs to be explained in the description.
TupleTimeTextProcessor.collateanddatasets/utils.pyboth import the private_pad_stackfromdatasets/collate.py. Please either confirm this sharing is intended and say why in the description, or keep each component self-contained. - The new
paddingoption onTimeImageProcessorisn'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
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.
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
Trainer.train(accumulation_steps, use_amp, amp_dtype): mixed precision and gradient accumulationfinfo(dtype).min, and ordinary forwards use fused scaled-dot-product attentionBaseDataset(use_dask_distributed=True);Falsebuilds the event cache with the local Dask schedulerTupleTimeTextProcessordrops null and blank notes and pads to the longest note in the samplemax_lengthgoes from 128 to 512StageNetTensorProcessor(forward_fill=True);Falseis for observation masks{field}__pad_maskwhen samples in a batch differ in length{field}__pad_maskkeysTupleTimeTextProcessor.collate()stacks tokenized textWhy 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,
-1e9overflows 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_kwargstoDataLoader(feat(imaging): add medical image IO layer #1386).use_dask_distributed=Falsenow 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.MIMIC4Datasetpasses 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,
TimeRegionImageProcessorand the time-imageUnifiedBridgeread 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, andTupleTimeTextProcessorstacks its own tokenized tuples through the processorcollate()hook. Text gets no{field}__pad_maskkey; 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.pypyhealth/models/transformer.py(attention only)pyhealth/datasets/base_dataset.py,pyhealth/datasets/mimic4.pypyhealth/datasets/utils.py,pyhealth/datasets/collate.pypyhealth/processors/stagenet_processor.py,time_image_processor.py,tuple_time_text_processor.pytests/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.UnifiedBridgetests, pass. The full suite was not rerun on this branch by itself after the tuple collation fix.