Skip to content

Multimodal stack 3/3: NotesLabsMIMIC4 and LabsMIMIC4 tasks, end-to-end runner and run records - #1597

Draft
jhnwu3 wants to merge 15 commits into
mm/02-unified-modelsfrom
mm/03-tasks-runner
Draft

jhnwu3 wants to merge 15 commits into
mm/02-unified-modelsfrom
mm/03-tasks-runner

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: two tasks, one example runner, run-record utilities.

PR 3 of 3 that bring the Multimodal-PyHealth design into PyHealth. It is stacked on #1596 (which is stacked on #1595), so the diff here holds only this PR's commits.

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 and Multimodal-PyHealth#57.

Commits

Tasks

Commit Change
976fe14 NotesLabsMIMIC4 and LabsMIMIC4 in pyhealth/tasks/multimodal_mimic4.py, with a docs page
70e8b4f One observation window, window_hours, shared by labs and radiology notes; 0 means off

How these differ from MultimodalMortalityPredictionMIMIC4, which master already has:

  • Notes are the admission-context sections of the discharge note (stamped at admit) plus radiology notes at exam time. Master's task takes the discharge and radiology notes as raw text.
  • Labs come with a separate observation-mask field (labs_mask, no forward fill).
  • One window caps every time-stamped modality at the same point.
  • ICD codes are off by default (include_icd=False), because they are coded at discharge.

Please read before reviewing the window. window_hours=0 keeps the full stay through discharge, so mortality features can include data up to discharge or death. That is the agreed default, but it is not prediction from a fixed point, and any result from it has to say so. A positive window_hours caps each admission at min(admit + N hours, discharge).

Runner

Commit Change
0b472b4 examples/mortality_prediction/unified_embedding_e2e_mimic4.py: one script for MLP, RNN, Transformer, EHRMamba, JambaEHR and BottleneckTransformer on the two tasks, with cache and timing flags

Run records and guards

Commit Change Behaviour change
e8d24e1 write_run_config writes run_config.json next to a finished run's metrics New file in each run directory
daaa1fc Paired runs no longer overwrite each other or report train as test Run directories include the task, plus _dev<N>
14ffbce Test metrics are saved for every run with a test split New test_metrics.json
e4a1ef1 Per-epoch CPU seconds logged next to wall time New metrics.json keys
3441724 Run identity includes the window Run directories gain _w<N> for a nonzero window
75cd60c Optimizer settings come from the CLI only BottleneckTransformer loses its hardcoded clip of 0.5 and Adam eps of 1e-6 and gets 1.0 and 1e-8 like every other backbone
576890e --amp-dtype without --use-amp is refused Parse error
1223a1e The by-sample split fallback is refused unless --allow-leaky-split A run whose patient split comes up empty now stops
93b2dd8 Architecture flags a backbone ignores are warned about and recorded Warning only
974f0f9 A mortality run at the default window logs a warning Warning only
30d40ff examples/benchmark_perf/* report peak_pss_bytes next to summed RSS New column
15c6aba Port fix: dataset named in the task docstrings; persistent workers kept off the shuffled loader See below

run_config.json records a source digest of the .py files in the pyhealth package. It does not cover examples/, configs or launchers.

Changes made while porting to current master

Files to review

  • pyhealth/tasks/multimodal_mimic4.py, docs/api/tasks/pyhealth.tasks.multimodal_mimic4.rst
  • examples/mortality_prediction/unified_embedding_e2e_mimic4.py
  • pyhealth/utils.py, pyhealth/trainer.py (CPU seconds only)
  • examples/benchmark_perf/ (16 files with the same edit)
  • 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: the runner tests run the labs and notes_labs tasks end to end on the MIMIC-IV demo data in test-resources, on CPU, with Bio_ClinicalBERT for the notes.
  • Not run for this port: real MIMIC-IV and GPU. The fork ran a 1,000-patient real-data pass for both tasks on an earlier build.

rianfyi and others added 15 commits November 23, 2026 21:22
One timeline across stays, full stay by default, and admission-context discharge sections stamped at admit. No ICDLabsMIMIC4. The CXR classes are NOT in this commit; they go to the CXR owner set. The emitted_data_version field stays without the cache-history comments. New synthetic tests port the time-axis and observation-window proofs; adds the task docs page per the task checklist.

Sources: #1185 49c87c6 task file, minus the CXR classes.

New in v4: regression tests the original series lacked. test_p3_task_schema_specs instantiates every input/output processor spec for both task classes through SampleBuilder._get_processor_instance; test_p3_multimodal_set_task runs real dataset.set_task on MIMIC-IV demo data. Both fail on v3 and pass with the forward_fill fix.

New in v5: the fitted-width assertion on the real demo set_task moved here from the empty-first fit commit, so this commit tests what it needs.

Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95
One parameter, window_hours = 0, on the base task, applied through the single _admission_window_end helper to labs and radiology notes in NotesLabsMIMIC4 and LabsMIMIC4. 0 means no cap (full stay through discharge); a positive value caps each admission at min(admit + N h, discharge), anchored at each admission, not at the first admission's clock. Negative or None raises ValueError. Discharge notes stay unbounded by design (admission-context sections stamped at admit); there is deliberately no switch for them.

Tests: 0 equals the full-stay output exactly; N h drops later labs/radiology per admission; negative and None raise.

Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95
Wires the NotesLabsMIMIC4/LabsMIMIC4 tasks and the unified-mode backbones in this series (MLP, RNN, Transformer, BottleneckTransformer, EHRMamba, JambaEHR). Flags: Trainer AMP, loader options, observation-window-hours default 0, freeze-encoder, cache-frozen-text with max-frozen-text-cache, --no-dask-distributed to skip the distributed cluster. No hardcoded MIMIC roots. run() takes injectable sample_dataset for tests; main(argv) injectable for CLI tests. Per-epoch train time, eval/inference time, frozen-text cache stats printed and written to metrics.json for the cache A/B.

Tests: CLI help/defaults/no-cache flag, tiny synthetic end-to-end (MLP, 1 epoch, CPU), plus committed demo-data real-path tests (TestUnifiedE2ERunnerDemoData): labs with mlp+rnn on the MIMIC-IV demo fixture (1 epoch, CPU, shared set_task, seed 2 so val/test have no all-empty batch for the RNN pack), asserting metrics.json key set and finite losses; notes_labs skipped unless Bio_ClinicalBERT is in the local HF cache (never downloads).

New in v5: demo-data runner test added here so the runner commit proves the real path it wires.

Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95
metrics.json stores the score but not the conditions, so a frozen-encoder
run and a fine-tuned run were indistinguishable after the job log was gone.
write_run_config records the resolved settings plus git revision and a
source-tree digest, which keeps code identity answerable from an unpacked
cluster tarball. The runner calls it before training so the config lands
even when training crashes.

Fork-only for now, per the review discussion: it lives in pyhealth/utils.py
but is not proposed upstream.

Sources: 224e7f4 (utils part verbatim); provenance half matches the utils
part of fork #53 d45e3cc; runner call is new wiring for this series.
Tests: tests/core/test_run_config.py (new); demo-data runner test now
asserts run_config.json and its keys.
Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95
The run directory was {model}_seed{seed}, so --task labs and --task
notes_labs at one seed resolved to one path and the second run destroyed
the first. Predictions came from "test or val or train" with nothing
saying which, and the patient-split fallback was silent. The task is now
in the directory name, a nonzero --dev adds a _dev<N> suffix to the same
name, the split that predictions come from is named and warned about when
it is not test, and both the split mode and the eval split are recorded
in run_config.json next to the metrics. The predictions CSV carries the
eval split as a constant column, so collected files say which split they
hold.

Sources: 5def4ea (paired-run dirs, leaky-split warning, eval split; MLP,
lab-standardizer, loader and default changes left out -- the series
already carries them or they belong to Later); the eval-split naming
matches the runner half of fork #53 d45e3cc.
Tests: tests/core/test_paired_runs_eval_split.py (new; all 6 fail without
this commit).
Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95
metrics.json carries validation only, so the test numbers worth reporting
live nowhere on disk: only in stdout and W&B, recoverable afterwards only
by re-scoring predictions by hand. test_metrics.json now lands next to the
metrics with the eval split named. The series already evaluates test
without W&B (its logger no-ops when disabled), so only the persist step
was missing. create_directory uses exist_ok: the prior exists()-then-makedirs
lost a race between concurrent first imports.

Sources: fork #54 f4b3707 (test-metrics half verbatim; ungating already
satisfied by this series; wandb group/job_type rides with the
window-identity commit).
Tests: tests/core/test_persist_test_metrics.py (new; the write test fails
without this commit -- the makedirs-race half is not deterministically
testable and rides along); demo-data runner test now asserts
test_metrics.json and its eval split.
Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95
Self-only CPU time badly understates a data-loading-bound run, since
workers are separate processes, so the clock counts the process tree
(psutil, resource fallback). metrics.json gains epoch_train_cpu_seconds
plus train_cpu_seconds and train_cpu_util_pct next to
epoch_train_seconds. Adapted to this series: its Trainer returns None and
epoch wall time is measured by the runners loader, so CPU rides the same
epoch boundaries instead of a trainer epoch record.

Sources: fork #54 f4b3707 (_cpu_seconds verbatim; the per-epoch record
half reworked onto this series loader timing).
Tests: tests/core/test_trainer_cpu.py (new; both fail without this
commit); demo-data runner test asserts the new metrics.json keys.
Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95
An observation-window arm is a different experiment from the full-stay run
at the same task/model/seed; without the window in the name the two share
an output directory and collide in W&B. The directory and default W&B run
name gain a _wN suffix when the window is nonzero, and runs set the W&B
group (arm) and job_type (backbone) so a many-cell sweep stays navigable.

Sources: fork #54 f4b3707 (window half, adapted: this series logger and
naming differ; group/job_type stored on the logger for tests).
Tests: tests/core/test_run_identity_window.py (new; all 3 fail without
this commit).
Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95
A per-model branch gave bottleneck_transformer max_grad_norm=0.5 and
Adam eps=1e-6 while every other backbone got 1.0 and 1e-8, so a
six-backbone table that read as compute-matched was not, and the recorded
config stored the raw flag (null) instead of the value the optimizer
used. Defaults are now lr=1e-4, eps=1e-8, clip=1.0 for every model; a
backbone that needs different settings must be passed them.

Behaviour change in the runner: bottleneck_transformer loses its 0.5
clip / 1e-6 eps hardcode (it scored slightly lower in a single-seed
rerun); restore it with --max-grad-norm 0.5 --adam-eps 1e-6.

Sources: the per-model branch was found by comparing the runner against
the reference launcher configurations.
Tests: tests/core/test_optimizer_cli_only.py (new; all 3 fail without
this commit).
Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95
The flag list says --amp-dtype "bf16" and never mentions --use-amp, so
following it literally ran fp32 while the recorded config claimed bf16.
A bare --amp-dtype is now a parse error; omitting it resolves to bf16
for the run that does pass --use-amp.

Sources: the flag/config mismatch was found against the reference
launcher configurations.
Tests: tests/core/test_amp_dtype_flag.py (new; the error case fails
without this commit, the other two pin the default).
Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95
The fallback puts a patient with several admissions in both train and
test, inflating every metric, and used to happen with no warning at all.
A run that cannot be split correctly now stops instead of quietly
producing numbers nobody can use; smoke tests opt in explicitly. The
opt-in is marked in the run directory (_allow_leaky): it records the
config, not whether the fallback fired. Silence was the last way a run
could disagree with its own split config.

Sources: the silent patient-split fallback was found against the
reference launcher configurations.
Tests: the paired-run split tests now pin refuse-by-default plus the
allowed fallback path (both fail without this commit), and the opt-in
run directory gains _allow_leaky (fails without this commit).
Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95
A launcher could appear to set something that never reached the model:
MLP has no dropout parameter and swallows it in **kwargs, JambaEHR
ignores --num-layers, and transformer/bottleneck/ehrmamba/jamba ignore
--hidden-dim. An ignored flag the user set to a non-default value is now
logged at startup (compared against the parser defaults, so a run at
defaults stays silent); the full ignored list is still stored as
inert_flags in run_config.json, so a table cannot misread the set flags
as settings that took effect.

Sources: map derived from this series' runner wiring; ignored flags are
recorded in run_config.json next to the metrics.
Tests: tests/core/test_inert_arch_flags.py (new; the warn and record tests
fail without this commit, and the at-defaults silence test fails on the
old always-warn code).
Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95
window_hours=0 (the default) keeps the full stay through discharge, so
mortality features can include data up to discharge or death and the
label can leak into the inputs. A run that starts with an effective
observation window of 0 on a mortality task now logs one warning naming
--observation-window-hours; a positive window and non-mortality tasks
stay silent. Warning only: no refusal, no new flags, and no new
run_config field.

Sources: mortality --task values derived from the task classes'
output_schema (pyhealth/tasks/multimodal_mimic4.py:457 and :606, both
{"mortality": "binary"}); window semantics from the shared base task.
Tests: tests/core/test_mortality_full_stay_warning.py (new; all four
fail without this commit).
Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95
Summing RSS over forked workers counts every shared page once per
process; PSS divides it among the mappers, so the total stays additive.
peak_pss_bytes lands next to peak_rss_bytes in all 16 harnesses. Where
PSS is unavailable for any process in the tree that sample is not a PSS
total, so the column is left empty for the run rather than holding RSS.
A denied process drops the sample instead of undercounting it, while an
exited one is skipped; the peak_pss reset runs inside the sampler lock.
Additive: peak_rss_bytes keeps its meaning, so numbers already
collected stay interpretable. Adapted only
for this series drift (the open_fds field the source predates).

Sources: fork #55 07355ae (verbatim hunk in all 16 files).
Tests: tests/core/test_benchmark_pss.py (new; fails without this
commit -- tracker exercised where importable, structural markers
elsewhere since meds_reader is unavailable here, plus fake-process
cases: denied drops the sample, exited is skipped).
Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95
…t workers off the shuffled loader.

Task docstrings reference MIMIC4Dataset so the docs list these tasks on
the dataset page. get_dataloader rejects persistent_workers=True with
shuffle=True, so the runner applies --persistent-workers to the
validation and test loaders only.

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

jhnwu3 commented Nov 24, 2026

Copy link
Copy Markdown
Collaborator Author

/review

@github-actions

Copy link
Copy Markdown

Test Coverage

Total: 86.38% (46396 / 53714 lines)

Modified file Coverage Lines
pyhealth/tasks/__init__.py 98.04% 100 / 102
pyhealth/tasks/multimodal_mimic4.py 88.00% 198 / 225
pyhealth/trainer.py 77.41% 257 / 332
pyhealth/utils.py 87.40% 111 / 127

Workflow run · 15c6aba

@github-actions

Copy link
Copy Markdown

AI Review

suggestion: not available
decision: not available

This PR is too large for AI review (over 300 files or 200000 diff characters). The label stays as it is: you can make the PR smaller, for example by clearing notebook outputs or splitting it, and comment /review again, or a maintainer can review it as it is.

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.

3 participants