Repository navigation
Conversation
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>
This was referenced Nov 24, 2026
Closed
Collaborator
Author
|
/review |
Test CoverageTotal: 86.38% (46396 / 53714 lines)
|
AI Reviewsuggestion: 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 |
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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
NotesLabsMIMIC4andLabsMIMIC4inpyhealth/tasks/multimodal_mimic4.py, with a docs pagewindow_hours, shared by labs and radiology notes; 0 means offHow these differ from
MultimodalMortalityPredictionMIMIC4, which master already has:labs_mask, no forward fill).include_icd=False), because they are coded at discharge.Please read before reviewing the window.
window_hours=0keeps 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 positivewindow_hourscaps each admission atmin(admit + N hours, discharge).Runner
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 flagsRun records and guards
write_run_configwritesrun_config.jsonnext to a finished run's metrics_dev<N>test_metrics.jsonmetrics.jsonkeys_w<N>for a nonzero window--amp-dtypewithout--use-ampis refused--allow-leaky-splitexamples/benchmark_perf/*reportpeak_pss_bytesnext to summed RSSrun_config.jsonrecords a source digest of the.pyfiles in thepyhealthpackage. It does not coverexamples/, configs or launchers.Changes made while porting to current master
MIMIC4Dataset, so the docs list the tasks on the dataset page (Docs: say where to get every dataset, and link tasks to their datasets #1456, Say which dataset each remaining task works with #1548).get_dataloaderrejectspersistent_workers=Truewithshuffle=True(feat(imaging): add medical image IO layer #1386). The runner's--persistent-workersnow applies to the validation and test loaders only.Files to review
pyhealth/tasks/multimodal_mimic4.py,docs/api/tasks/pyhealth.tasks.multimodal_mimic4.rstexamples/mortality_prediction/unified_embedding_e2e_mimic4.pypyhealth/utils.py,pyhealth/trainer.py(CPU seconds only)examples/benchmark_perf/(16 files with the same edit)tests/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.labsandnotes_labstasks end to end on the MIMIC-IV demo data intest-resources, on CPU, with Bio_ClinicalBERT for the notes.