Skip to content

[BTY-36] Add MAESTRO model for multimodal time series to pyhealth.models - #1549

Merged
github-actions[bot] merged 5 commits into
sunlabuiuc:masterfrom
Chinmaykatpatal:bty-36-maestro
Nov 19, 2026
Merged

github-actions[bot] merged 5 commits into
sunlabuiuc:masterfrom
Chinmaykatpatal:bty-36-maestro

Conversation

@Chinmaykatpatal

@Chinmaykatpatal Chinmaykatpatal commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Contributor: Chinmaykatpatal
Contribution Type: New model (closes BTY-36)

Summary

Adds MAESTRO to pyhealth.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 M modalities, each shaped (batch, time, variates_m):

  1. Projection: each modality is linearly projected to d_model.
  2. Positional encoding: fixed sinusoidal temporal encoding is added.
  3. Per-modality encoder: num_layers_per_modal InformerEncoderLayer blocks. Each block uses ProbSparse self-attention (only the top factor * ceil(log L) queries attend fully), a distilling convolution that halves the time length, and a dense feed-forward.
  4. Modality encoding: a learned temporal embedding and a learned per-modality embedding are added.
  5. Fusion: the modality sequences are concatenated along time and passed through num_layers fusion blocks. These use the same attention, with a sparse mixture-of-experts feed-forward (top-1 routing over num_experts).
  6. Head: mean-pool over time, then a two-layer classifier sized from the dataset's label processor. Losses and activations come from the label processor, as in 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

  • One tensor input feature per modality, each (time, variates) per sample. Feature keys are the modality names.
  • All modalities in a batch must share the same batch size and time length.
  • Time length must be at most input_length (default 256). Longer inputs raise ValueError.
  • Missing sensors are represented by zeros for that feature.

Hyperparameters (defaults)

Argument Default Meaning
d_model 64 model width (must be divisible by n_heads)
n_heads 8 attention heads
num_layers_per_modal 2 encoder blocks per modality
num_layers 2 fusion blocks
num_experts 4 experts per fusion block
dropout 0.1 dropout rate
modality_dropout 0.2 probability of dropping each modality per training batch
base_factor 5 maximum ProbSparse factor
input_length 256 longest supported time length

Differences from the official implementation

Reference: https://github.com/payalmohapatra/MAESTRO (models/our_models.py).

  • The per-forward expert-ID logging is removed. The official code appends to a list on every forward pass, so memory grows during training.
  • ProbSparse always keeps at least one query, so length-1 inputs no longer produce an empty selection.
  • The in-place index assignment is replaced by an out-of-place scatter, which keeps autograd straightforward.
  • Only the CrossAttnTransformerClf path is ported. The separate InformerClf and the ProbSparseAttention dropout (declared but unused in the official code) are not carried over. Dropout is applied to the attention output here.
  • The output is a dictionary (logit, y_prob, and loss/y_true when labels are given), matching the other PyHealth models.

Verification

  • Unit tests (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).
  • Doctests: the class and helper docstring examples run under python -m doctest.
  • Equivalence check, run locally: the official model's weights were mapped onto the port and both were run in eval mode on the same random inputs. Outputs matched exactly (max absolute difference 0.0). Changing one weight in the port made the check fail, so the check is sensitive. This script is not part of the PR.
  • Repo checks: tools/check_pr_rules.py passes locally. CI build on commit e6bec056 (core and NLP test suites) passed. The later commits (35a7279b lint cleanup, a36963a6 MIMIC-IV task and example) are awaiting their CI runs.

Known limitations

  • MIMIC example uses the MIMIC-IV demo, not MIMIC-III. The official MIMIC loader needs a preprocessed im.pk file 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.
  • Not benchmarked against the paper. I did not reproduce the paper's WESAD, DSADS, DaliaHAR, or MIMIC numbers.
  • Missing-modality handling. Dropped or missing modalities are zeroed at the input, as in the official code. Attention is not masked for them.
  • Randomness. ProbSparse samples query candidates randomly, so repeated forward passes differ unless the seed is fixed. Tests fix the seed where outputs are compared.
  • Factor gate. Because the gate's output is rounded with 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 layers
  • pyhealth/models/__init__.py: export
  • tests/core/test_maestro.py: unit tests
  • docs/api/models.rst and docs/api/models/pyhealth.models.MAESTRO.rst: docs index and API page
  • pyhealth/tasks/maestro_mortality_mimic4.py and pyhealth/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 task
  • examples/maestro_mimic4_mortality.py: end-to-end example on the MIMIC-IV demo (--root points at the demo folder)

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).
@github-actions github-actions Bot mentioned this pull request Nov 18, 2026
- 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.
@github-actions

github-actions Bot commented Nov 18, 2026 •

Copy link
Copy Markdown

Test Coverage

Total: 85.12% (40704 / 47819 lines)

Modified file Coverage Lines
pyhealth/models/__init__.py 100.00% 82 / 82
pyhealth/models/maestro.py 95.14% 176 / 185
pyhealth/tasks/__init__.py 97.30% 72 / 74
pyhealth/tasks/maestro_mortality_mimic4.py 95.00% 38 / 40

Workflow run · 205c969

Apply ruff's safe and unsafe fixes to tests/core/test_maestro.py.
No behavior change.
@Chinmaykatpatal
Chinmaykatpatal marked this pull request as ready for review November 19, 2026 02:33
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.
@Chinmaykatpatal

Copy link
Copy Markdown
Contributor Author

/review

@jhnwu3 jhnwu3 added the status: automatic The PR will go through automatic review process. label Nov 19, 2026
@jhnwu3

jhnwu3 commented Nov 19, 2026

Copy link
Copy Markdown
Collaborator

/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 205c969

import polars as pl

from .base_task import BaseTask
from .ehr_cxr_mimic4 import (

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] 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):

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] 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.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[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.

@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: 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_training reseeds 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 with EHRCXRMortalityMIMIC4, would make it explicit.
  • Task docs: There is no docs/api/tasks entry for MAESTROMortalityMIMIC4. 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

@Chinmaykatpatal

Copy link
Copy Markdown
Contributor Author

/merge

@github-actions
github-actions Bot merged commit 58cd085 into sunlabuiuc:master Nov 19, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

status: automatic The PR will go through automatic review process.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants