Repository navigation
[BTY-36] Add MAESTRO model for multimodal time series to pyhealth.models - #1549
Conversation
Adds MAESTRO (Mohapatra et al., NeurIPS 2025, https://arxiv.org/abs/2509.25278): ProbSparse attention per modality, distilling convolutions, and a fusion stack with a sparse mixture-of-experts feed-forward layer. Whole modalities are randomly dropped during training for robustness to missing sensors. Each input feature is one modality with shape (batch, time, variates).
- Export MAESTRO with a redundant alias so ruff F401 does not flag it. - Use built-in dict/list annotations and drop the unused Optional import. - Add >>> usage examples to the public helper classes.
Test CoverageTotal: 85.12% (40704 / 47819 lines)
|
Apply ruff's safe and unsafe fixes to tests/core/test_maestro.py. No behavior change.
Adds MAESTROMortalityMIMIC4, an in-hospital mortality task on the first 48 ICU hours that splits the 16 MedFuse variables into four modalities (vitals, neuro, labs, anthropometrics), each with value and mask columns. It uses only the EHR tables, so it runs on the open MIMIC-IV demo without credentialing. Adds examples/maestro_mimic4_mortality.py, which trains MAESTRO on the demo dataset end to end (task, split, training, evaluation). The demo is too small for meaningful metrics; it shows the pipeline. Adds 8 synthetic-data unit tests for the task.
|
/review |
|
/review |
| import polars as pl | ||
|
|
||
| from .base_task import BaseTask | ||
| from .ehr_cxr_mimic4 import ( |
There was a problem hiding this comment.
[medium] Undocumented link to private helpers of ehr_cxr_mimic4
The task imports six underscore-prefixed names from pyhealth/tasks/ehr_cxr_mimic4.py (_EVENT_TABLES, _MEASURED_NAMES, _eligible_stays, _measurements, _pre_filter, _time_series), and tests/core/test_maestro_mortality_mimic4.py also imports _MEASURED_NAMES from there. The PR description only says the task splits the MedFuse variables; it does not name this link or why it is needed. PyHealth keeps components self-contained, so changes to EHRCXRMortalityMIMIC4's helpers, binning or variable list would silently change this task. Either confirm the sharing and state the reason in the PR description, or keep the task self-contained without importing these private helpers.
| with self.assertRaises(ValueError): | ||
| self._build(self.binary_dataset, input_length=0) | ||
|
|
||
| def test_modality_dropout_only_in_training(self): |
There was a problem hiding this comment.
[medium] Training-only modality dropout is not actually tested
test_modality_dropout_only_in_training runs two eval-mode forward passes with the same seed and asserts they match. That holds whether or not modality dropout runs in eval, because both passes drop the same modalities, so the test cannot catch the bug it names. Fix it by comparing an eval-mode model with modality_dropout=0.99 against a clone with modality_dropout=0.0 and the same state_dict; the logits must be identical. Also check that training-mode outputs differ from eval-mode outputs.
| distilling), the encoded sequences are concatenated along time, and a fusion | ||
| stack with a sparse mixture-of-experts feed-forward layer combines them. During | ||
| training, whole modalities are randomly dropped; the model's per-modality | ||
| factor gate then adapts the sparsity of each modality's attention. |
There was a problem hiding this comment.
[low] Factor gate described as adaptive but never trained
The docstring says the factor gate adapts the sparsity of each modality's attention. The gate output goes through ceil on a detached tensor (line 515), so self.factor_gate (line 430) gets no gradients and only varies with the presence mask. Say in the docstring that the gate is fixed, or drop its parameters so model.parameters() does not include weights that never train.
There was a problem hiding this comment.
AI Review
suggestion: approve
decision: approve
Thank you for adding MAESTRO. It brings sparse-attention multimodal time-series classification to pyhealth.models, and it comes with a MIMIC-IV mortality task, an example and an API page. The description is clear, and the comparison with the official implementation is helpful. This looks ready to merge.
Coverage is above the bar. The whole repository is at 85.12%, against the 60% bar. maestro.py is at 95.14% and maestro_mortality_mimic4.py is at 95%, against the 80% bar.
Optional suggestions:
- Modality dropout test:
test_modality_dropout_only_in_trainingreseeds before both passes. Because the seed is shared, the two outputs would match even if dropout ran in eval mode. Comparing eval output with train output would make the test able to fail. - Task link: The new task imports private helpers from
pyhealth/tasks/ehr_cxr_mimic4.py. The module docstring explains this, and the description mentions reusing the MedFuse variables. One sentence in the description saying the reuse is intentional, so the EHR inputs stay consistent withEHRCXRMortalityMIMIC4, would make it explicit. - Task docs: There is no
docs/api/tasksentry forMAESTROMortalityMIMIC4. Adding one would help users find it. - Factor gate wording: The module docstring says the factor gate "adapts" sparsity. Since the gate gets no gradients, you could say it sets the factor but isn't trained.
Reviewed commit 205c969
|
/merge |
Contributor: Chinmaykatpatal
Contribution Type: New model (closes BTY-36)
Summary
Adds
MAESTROtopyhealth.models, a multimodal time-series classifier from Mohapatra et al., "MAESTRO: Adaptive Sparse Attention and Robust Learning for Multimodal Dynamic Time Series" (NeurIPS 2025, https://arxiv.org/abs/2509.25278).Each dataset input feature is treated as one modality. Every modality is encoded on its own with sparse attention, the encoded sequences are concatenated along time, and a fusion stack combines them. During training, whole modalities are randomly dropped so the model stays usable when a sensor is missing.
How it works
For a batch with
Mmodalities, each shaped(batch, time, variates_m):d_model.num_layers_per_modalInformerEncoderLayerblocks. Each block uses ProbSparse self-attention (only the topfactor * ceil(log L)queries attend fully), a distilling convolution that halves the time length, and a dense feed-forward.num_layersfusion blocks. These use the same attention, with a sparse mixture-of-experts feed-forward (top-1 routing overnum_experts).MedFuse.A small factor gate, driven by the modality presence mask, sets the ProbSparse factor for each modality. Its output is rounded to an integer with
ceil, so it does not receive gradients.Input contract
tensorinput feature per modality, each(time, variates)per sample. Feature keys are the modality names.input_length(default 256). Longer inputs raiseValueError.Hyperparameters (defaults)
d_modeln_heads)n_headsnum_layers_per_modalnum_layersnum_expertsdropoutmodality_dropoutbase_factorinput_lengthDifferences from the official implementation
Reference: https://github.com/payalmohapatra/MAESTRO (
models/our_models.py).scatter, which keeps autograd straightforward.CrossAttnTransformerClfpath is ported. The separateInformerClfand theProbSparseAttentiondropout (declared but unused in the official code) are not carried over. Dropout is applied to the attention output here.logit,y_prob, andloss/y_truewhen labels are given), matching the other PyHealth models.Verification
tests/core/test_maestro.py, 17 tests, synthetic data only): output shapes for binary and multiclass labels, loss backpropagation, missing and mismatched modalities, variate-count and time-length checks, invalid hyperparameters, modality dropout running only in training, state-dict round trip, and the building blocks (ProbSparse attention, distilling layer, mixture-of-experts routing).python -m doctest.tools/check_pr_rules.pypasses locally. CI build on commite6bec056(core and NLP test suites) passed. The later commits (35a7279blint cleanup,a36963a6MIMIC-IV task and example) are awaiting their CI runs.Known limitations
im.pkfile that is not in the repo or publicly available (request still open at How to obtain the MIMIC-III im.pk file used in MAESTRO? payalmohapatra/MAESTRO#1). So the example in this PR uses the open MIMIC-IV demo (100 patients) and PyHealth's own MIMIC-IV tables. It is a pipeline demonstration; the demo is too small for meaningful metrics. Unit tests use synthetic data only.ceil, it does not learn. This matches the official code. A learnable alternative would be a change in design, so I left it as is.Files to Review:
pyhealth/models/maestro.py: the model and helper layerspyhealth/models/__init__.py: exporttests/core/test_maestro.py: unit testsdocs/api/models.rstanddocs/api/models/pyhealth.models.MAESTRO.rst: docs index and API pagepyhealth/tasks/maestro_mortality_mimic4.pyandpyhealth/tasks/__init__.py: MIMIC-IV mortality task that splits the MedFuse variables into MAESTRO modalities (EHR only, no CXR)tests/core/test_maestro_mortality_mimic4.py: 8 synthetic-data tests for the taskexamples/maestro_mimic4_mortality.py: end-to-end example on the MIMIC-IV demo (--rootpoints at the demo folder)