From 02710efe40eacd8b0824f563906cad45ef8fd63f Mon Sep 17 00:00:00 2001 From: Rian Date: Thu, 5 Nov 2026 20:36:45 -0500 Subject: [PATCH 1/6] Fail fast on --num-workers 0 when the runner builds the dataset. Building the dataset with --num-workers below 1 cannot work: a zero-worker distributed Dask cluster never computes, so the build hangs; the local-scheduler path avoids the hang but set_task then divides the patient list by the worker count; a negative count dies inside Dask/torch loader construction with an error that never names the flag. The guard refuses below 1 up front. --no-dask-distributed does not make 0 workers work. Upstream behaviour is left alone: a workerless cluster and a zero divisor are the caller's mistake, and clamping inside BaseDataset would change shared semantics for every dataset. Zero is still allowed for loading a prebuilt sample dataset, which never touches the Dask path. Sources: DaskCluster/set_task code paths in pyhealth/datasets/base_dataset.py (read-only; unchanged). Tests: tests/core/test_unified_e2e_runner.py::TestUnifiedE2ERunner::test_num_workers_zero_refused_when_building (new;... Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95 --- .../unified_embedding_e2e_mimic4.py | 44 ++++++++++++++++++- tests/core/test_unified_e2e_runner.py | 20 +++++++++ 2 files changed, 63 insertions(+), 1 deletion(-) diff --git a/examples/mortality_prediction/unified_embedding_e2e_mimic4.py b/examples/mortality_prediction/unified_embedding_e2e_mimic4.py index c4a0617d4f..d19fc4ef90 100644 --- a/examples/mortality_prediction/unified_embedding_e2e_mimic4.py +++ b/examples/mortality_prediction/unified_embedding_e2e_mimic4.py @@ -110,6 +110,36 @@ def finish(self) -> None: self._run.finish() +def _require_build_workers( + args: argparse.Namespace, sample_dataset: Any = None +) -> None: + """Refuse ``--num-workers < 1`` when the runner builds the dataset itself. + + A zero-worker distributed cluster never computes (no workers run the + tasks), so the build hangs; the local-scheduler path avoids the hang + but ``set_task`` then divides the patient list by the worker count. + A negative count fails even earlier inside the Dask/torch loader + construction, with an error that never names the flag. Either way + fewer than one worker cannot build. Zero is still fine for loading + a prebuilt ``sample_dataset`` (plain main-process torch loading). + + Example: + >>> _require_build_workers( + ... argparse.Namespace(num_workers=1), sample_dataset=None) + >>> _require_build_workers( + ... argparse.Namespace(num_workers=0), sample_dataset=object()) + """ + if sample_dataset is None and args.num_workers < 1: + raise RuntimeError( + f"--num-workers {args.num_workers} cannot build the dataset: " + "the distributed Dask cluster would start with no workers and " + "never compute, and the local-scheduler path " + "(--no-dask-distributed) still divides by the worker count in " + "set_task. Pass --num-workers 1 or more when the runner builds " + "the dataset itself." + ) + + def _build_base_dataset(args: argparse.Namespace) -> MIMIC4Dataset: ehr_tables = ["labevents"] note_tables = None @@ -492,6 +522,7 @@ def run(args: argparse.Namespace, sample_dataset: Any = None) -> Path: args.task, ) set_seed(args.seed) + _require_build_workers(args, sample_dataset) if sample_dataset is None: base_dataset = _build_base_dataset(args) @@ -763,7 +794,18 @@ def parse_args(argv: Optional[list] = None) -> argparse.Namespace: default=1, help="Gradient accumulation steps (default 1, no accumulation).", ) - parser.add_argument("--num-workers", type=int, default=1) + parser.add_argument( + "--num-workers", + type=int, + default=1, + help=( + "Dask build workers and loader workers. Below 1 is refused " + "when the runner builds the dataset itself (a zero-worker " + "build hangs or divides by zero; a negative count dies " + "inside loader construction); a prebuilt sample dataset may " + "still load with 0." + ), + ) parser.add_argument( "--no-dask-distributed", dest="use_dask_distributed", diff --git a/tests/core/test_unified_e2e_runner.py b/tests/core/test_unified_e2e_runner.py index 2f09785662..d911cda38b 100644 --- a/tests/core/test_unified_e2e_runner.py +++ b/tests/core/test_unified_e2e_runner.py @@ -70,6 +70,26 @@ def test_no_cache_flag(self): ) self.assertFalse(args.cache_frozen_text) + def test_num_workers_zero_refused_when_building(self): + # Tests the guard directly (not via run(), which would hang in the + # zero-worker Dask cluster without the fix). Fails without the fix + # because _require_build_workers does not exist. + runner = _runner() + for bad in ("0", "-1"): + args = runner.parse_args( + ["--ehr-root", "/tmp/does-not-exist", + "--num-workers", bad] + ) + with self.assertRaisesRegex( + RuntimeError, f"--num-workers {bad}" + ): + runner._require_build_workers(args, sample_dataset=None) + # A prebuilt dataset may still load with 0 (main-process loading). + runner._require_build_workers(args, sample_dataset=object()) + # nonzero workers always pass, with or without a prebuilt dataset. + args = runner.parse_args(["--ehr-root", "/tmp/does-not-exist"]) + runner._require_build_workers(args, sample_dataset=None) + def test_synthetic_end_to_end(self): from pyhealth.datasets import create_sample_dataset From d06c98eaefe3e93f0ba3e96db8bc8d57c7894379 Mon Sep 17 00:00:00 2001 From: Rian Date: Thu, 5 Nov 2026 17:39:47 -0500 Subject: [PATCH 2/6] Refuse --dev values other than 0 or 1000. BaseDataset treats dev as a flag and hardcodes the 1000-patient cap in both the distributed and local paths, so --dev 5000 silently behaved as --dev 1000 while the help text promised N patients. The dataset is left alone; the runner refuses anything but 0 (off) and 1000 and the help text now says what the flag does. Sources: BaseDataset dev handling in pyhealth/datasets/base_dataset.py (read-only; unchanged). Tests: tests/core/test_unified_e2e_runner.py::TestUnifiedE2ERunner::test_dev_other_values_refused (new; fails without this commit). Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95 --- .../unified_embedding_e2e_mimic4.py | 19 ++++++++++++++++--- tests/core/test_unified_e2e_runner.py | 17 +++++++++++++++++ 2 files changed, 33 insertions(+), 3 deletions(-) diff --git a/examples/mortality_prediction/unified_embedding_e2e_mimic4.py b/examples/mortality_prediction/unified_embedding_e2e_mimic4.py index d19fc4ef90..00da07383d 100644 --- a/examples/mortality_prediction/unified_embedding_e2e_mimic4.py +++ b/examples/mortality_prediction/unified_embedding_e2e_mimic4.py @@ -851,9 +851,11 @@ def parse_args(argv: Optional[list] = None) -> argparse.Namespace: const=1000, default=0, help=( - "Dev mode: limit dataset to N patients for fast iteration. " - "--dev (no value) defaults to 1000 patients. " - "--dev 5000 limits to 5000. Omit for full dataset." + "Dev mode: cap the cohort at 1000 patients for fast iteration " + "(bare --dev means 1000). Only 0 (off, full dataset) and 1000 " + "are accepted: the dataset treats dev as a flag and always " + "caps at 1000, so any other value would silently behave as " + "1000. Omit for the full dataset." ), ) parser.add_argument( @@ -968,6 +970,17 @@ def parse_args(argv: Optional[list] = None) -> argparse.Namespace: if args.amp_dtype is None: args.amp_dtype = "bf16" + # The dataset treats dev as a flag and hardcodes the 1000-patient cap, + # so any other value would silently behave as --dev 1000. Refuse + # rather than mislead; the dataset itself is left alone. + if args.dev not in (0, 1000): + parser.error( + f"--dev {args.dev} is not supported. Only 0 (off, full " + "dataset) and 1000 are accepted: the dataset caps at 1000 " + "patients whatever positive value it gets, so any other value " + "would silently behave as --dev 1000." + ) + return args diff --git a/tests/core/test_unified_e2e_runner.py b/tests/core/test_unified_e2e_runner.py index d911cda38b..6cdf1ecd8c 100644 --- a/tests/core/test_unified_e2e_runner.py +++ b/tests/core/test_unified_e2e_runner.py @@ -90,6 +90,23 @@ def test_num_workers_zero_refused_when_building(self): args = runner.parse_args(["--ehr-root", "/tmp/does-not-exist"]) runner._require_build_workers(args, sample_dataset=None) + def test_dev_other_values_refused(self): + # Fails without the fix: --dev 5000 used to parse and then behave + # as --dev 1000. + runner = _runner() + for bad in ("5000", "2000", "100", "1"): + with self.assertRaises(SystemExit, msg=bad): + runner.parse_args( + ["--ehr-root", "/tmp/does-not-exist", "--dev", bad] + ) + args = runner.parse_args(["--ehr-root", "/tmp/does-not-exist"]) + self.assertEqual(args.dev, 0) + for good, want in ((["0"], 0), (["1000"], 1000), ([], 1000)): + args = runner.parse_args( + ["--ehr-root", "/tmp/does-not-exist", "--dev", *good] + ) + self.assertEqual(args.dev, want) + def test_synthetic_end_to_end(self): from pyhealth.datasets import create_sample_dataset From 832743433f58ef2a34652a932780310cc0c69635 Mon Sep 17 00:00:00 2001 From: Rian Date: Thu, 5 Nov 2026 17:41:27 -0500 Subject: [PATCH 3/6] Add --drop-modality to remove input fields at the model stage. Ablating a modality by switching --task changes the cohort and the split with it, so the arms are not comparable. --drop-modality (labs, notes; repeatable) instead filters the task input schema before set_task: same task, same samples, same split, same seed. Labs drops with its observation mask, notes drops the admission-note field; the cohort keeps every patient and a patient with nothing left in the remaining modality stays as an empty sequence, which the unified model already supports. Cohort selection, time origin, splits, and --note-root are unchanged -- the task still reads every table -- so dropping notes still needs --note-root. The run directory gains a _nolabs/_nonotes suffix so a drop arm cannot overwrite its reference. Dropping everything is refused. Sources: task input_schema/set_task wiring in pyhealth (read-only; unchanged). Tests: test_drop_modality_refusals and test_drop_modality_filters_task_schema (new; both fail without this commit). Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95 --- .../unified_embedding_e2e_mimic4.py | 92 ++++++++++++++++++- tests/core/test_unified_e2e_runner.py | 65 +++++++++++++ 2 files changed, 152 insertions(+), 5 deletions(-) diff --git a/examples/mortality_prediction/unified_embedding_e2e_mimic4.py b/examples/mortality_prediction/unified_embedding_e2e_mimic4.py index 00da07383d..b095964021 100644 --- a/examples/mortality_prediction/unified_embedding_e2e_mimic4.py +++ b/examples/mortality_prediction/unified_embedding_e2e_mimic4.py @@ -231,14 +231,69 @@ def _nondefault_inert_flags(args: argparse.Namespace) -> List[str]: return set_flags +# Modality -> task input fields removed at the model stage. Siblings drop +# together: labs goes with its observation mask, notes with the single +# admission-note field that carries both text and note times. +_DROP_MODALITY_FIELDS = { + "labs": ("labs", "labs_mask"), + "notes": ("admission_note_times",), +} + + +def _check_drop_modality(args: argparse.Namespace) -> None: + """Refuse a ``--drop-modality`` combination that drops nothing or all. + + Needs only ``task`` and ``drop_modality``, so the experiment driver + uses it to refuse bad ablations before running anything. Raises + ``ValueError``; the CLI turns it into a parse error. + + Example: + >>> _check_drop_modality( + ... argparse.Namespace(task="notes_labs", drop_modality=["notes"])) + >>> _check_drop_modality( + ... argparse.Namespace(task="labs", drop_modality=["labs"])) + Traceback (most recent call last): + ... + ValueError: --drop-modality ['labs'] leaves no input modality: ... + """ + drop = args.drop_modality or [] + if len(set(drop)) != len(drop): + raise ValueError(f"--drop-modality contains duplicates: {drop}.") + available = { + "labs": {"labs", "labs_mask"}, + "notes_labs": {"admission_note_times", "labs", "labs_mask"}, + }[args.task] + dropped = {f for m in drop for f in _DROP_MODALITY_FIELDS[m]} + if dropped - available: + raise ValueError( + f"--drop-modality {drop} has no fields to remove for --task " + f"{args.task}: it only has {sorted(available)}." + ) + if not (set(available) - dropped) & {"labs", "admission_note_times"}: + raise ValueError( + f"--drop-modality {drop} leaves no input modality: dropping " + "everything is refused." + ) + + def _build_task(args: argparse.Namespace): if args.task == "notes_labs": - return NotesLabsMIMIC4( + task = NotesLabsMIMIC4( window_hours=args.observation_window_hours, ) - if args.task == "labs": - return LabsMIMIC4(window_hours=args.observation_window_hours) - raise ValueError(f"Unknown task: {args.task}") + elif args.task == "labs": + task = LabsMIMIC4(window_hours=args.observation_window_hours) + else: + raise ValueError(f"Unknown task: {args.task}") + drop = getattr(args, "drop_modality", None) or [] + if drop: + dropped = {f for m in drop for f in _DROP_MODALITY_FIELDS[m]} + task.input_schema = { + key: value + for key, value in task.input_schema.items() + if key not in dropped + } + return task def _is_mortality_task(task: str) -> bool: @@ -579,13 +634,15 @@ def run(args: argparse.Namespace, sample_dataset: Any = None) -> Path: # suffixes they would collide with the full run. dev_suffix = f"_dev{args.dev}" if args.dev else "" window_suffix = _window_suffix(args.observation_window_hours) + drop = getattr(args, "drop_modality", None) or [] + drop_suffix = "".join(f"_no{m}" for m in sorted(drop)) # The flag marks the config, not the outcome: a run that splits # cleanly by patient keeps the suffix, so the opt-in stays visible # in the directory name. leaky_suffix = "_allow_leaky" if args.allow_leaky_split else "" exp_name = ( f"{args.task}_{args.model}_seed{args.seed}" - f"{dev_suffix}{window_suffix}{leaky_suffix}" + f"{dev_suffix}{window_suffix}{drop_suffix}{leaky_suffix}" ) output_dir = Path(args.output_dir) @@ -867,6 +924,23 @@ def parse_args(argv: Optional[list] = None) -> argparse.Namespace: "Default 0 means no cap: full stay through discharge." ), ) + parser.add_argument( + "--drop-modality", + action="append", + choices=["labs", "notes"], + default=None, + help=( + "Drop a modality's input fields at the model stage; repeat for " + "both (but dropping everything is refused). labs removes labs " + "and labs_mask, notes removes admission_note_times. Same task, " + "same samples, same split, same seed: the cohort keeps every " + "patient, and a patient with nothing left in the remaining " + "modality stays as an empty sequence. Cohort selection, time " + "origin, and splits are unchanged -- the task still reads every " + "table -- so dropping notes still needs --note-root for --task " + "notes_labs, and discharge timing still bounds the windows." + ), + ) parser.add_argument( "--freeze-encoder", action="store_true", @@ -981,6 +1055,14 @@ def parse_args(argv: Optional[list] = None) -> argparse.Namespace: "would silently behave as --dev 1000." ) + # A modality ablation must keep at least one input modality and may + # only drop fields the task has. Checked here so a bad combination + # fails before any dataset build. + try: + _check_drop_modality(args) + except ValueError as exc: + parser.error(str(exc)) + return args diff --git a/tests/core/test_unified_e2e_runner.py b/tests/core/test_unified_e2e_runner.py index 6cdf1ecd8c..a234475c89 100644 --- a/tests/core/test_unified_e2e_runner.py +++ b/tests/core/test_unified_e2e_runner.py @@ -90,6 +90,71 @@ def test_num_workers_zero_refused_when_building(self): args = runner.parse_args(["--ehr-root", "/tmp/does-not-exist"]) runner._require_build_workers(args, sample_dataset=None) + def test_drop_modality_refusals(self): + # Fails without the fix: every one of these used to parse. + runner = _runner() + base = ["--ehr-root", "/tmp/does-not-exist"] + # Duplicates refused. + with self.assertRaises(SystemExit): + runner.parse_args( + base + ["--task", "notes_labs", "--drop-modality", "notes", + "--drop-modality", "notes"] + ) + # Dropping everything refused (both orders, both tasks). + with self.assertRaises(SystemExit): + runner.parse_args( + base + ["--task", "notes_labs", "--drop-modality", "labs", + "--drop-modality", "notes"] + ) + with self.assertRaises(SystemExit): + runner.parse_args( + base + ["--task", "labs", "--drop-modality", "labs"] + ) + # The labs task has no note fields to drop. + with self.assertRaises(SystemExit): + runner.parse_args( + base + ["--task", "labs", "--drop-modality", "notes"] + ) + # Unknown values rejected by argparse choices. + with self.assertRaises(SystemExit): + runner.parse_args( + base + ["--task", "notes_labs", "--drop-modality", "image"] + ) + # Each single drop parses on notes_labs. + for modality in ("labs", "notes"): + args = runner.parse_args( + base + ["--task", "notes_labs", "--drop-modality", modality] + ) + self.assertEqual(args.drop_modality, [modality]) + args = runner.parse_args(base + ["--task", "labs"]) + self.assertIsNone(args.drop_modality) + + def test_drop_modality_filters_task_schema(self): + # No dataset needed: only the task's input schema is filtered. + runner = _runner() + args = runner.parse_args( + ["--ehr-root", "/tmp/does-not-exist", "--task", "notes_labs", + "--drop-modality", "notes"] + ) + self.assertEqual( + sorted(runner._build_task(args).input_schema), ["labs", "labs_mask"] + ) + args = runner.parse_args( + ["--ehr-root", "/tmp/does-not-exist", "--task", "notes_labs", + "--drop-modality", "labs"] + ) + self.assertEqual( + sorted(runner._build_task(args).input_schema), + ["admission_note_times"], + ) + args = runner.parse_args( + ["--ehr-root", "/tmp/does-not-exist", "--task", "notes_labs"] + ) + self.assertEqual( + sorted(runner._build_task(args).input_schema), + ["admission_note_times", "labs", "labs_mask"], + ) + def test_dev_other_values_refused(self): # Fails without the fix: --dev 5000 used to parse and then behave # as --dev 1000. From bbddf585419db4b1ebaf3feb4cf12a1fc2b4b2d5 Mon Sep 17 00:00:00 2001 From: Rian Date: Thu, 5 Nov 2026 20:38:18 -0500 Subject: [PATCH 4/6] Rework the experiment driver around same-task ablations. Ablate-by-task-switch compared different cohorts (626 vs 737 samples at --dev 1000), the unpaired cross-task trap. ablate --modalities now uses the runner's --drop-modality: same task, same samples, same split, same seed, with the dropped arm's fields removed at the model stage. Dropping labs works now; dropping everything is refused by the runner's rule before any run. The unconditional 'seeds and splits identical' line is gone: the summary now checks seed, split sizes, and inference-split sample ids across arms and prints what matches, naming the arms that differ. The identity line reports what it compares: unique inference-split patient ids, with train/val splits and labels not compared; an empty predictions file reports not recorded, not "0 ids match". A passed-through --drop-modality is refused under ablate (the arms would silently replace it); the hardcoded toy-magnitudes line is gone from summary.md (it was false on real data); and the runner module loads once per driver run through a single cached loader. Backbone reachability comes from the runner's own wiring map instead of a mirrored table: --heads on JambaEHR is now correctly allowed (the runner passes it) and --num-layers on JambaEHR correctly refused (the runner never passes it). Sources: runner --drop-modality and _ARCH_FLAGS_USED (same branch). Tests: doctests in the module (5 passed); full driver suite in the next commit. Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95 --- .../unified_embedding_experiments.py | 457 ++++++++++++++++++ 1 file changed, 457 insertions(+) create mode 100644 examples/mortality_prediction/unified_embedding_experiments.py diff --git a/examples/mortality_prediction/unified_embedding_experiments.py b/examples/mortality_prediction/unified_embedding_experiments.py new file mode 100644 index 0000000000..59306cb89a --- /dev/null +++ b/examples/mortality_prediction/unified_embedding_experiments.py @@ -0,0 +1,457 @@ +"""One-knob experiment driver over the unified-embedding e2e runner. + +Three modes build arms that differ in exactly one declared knob, run +each through the existing runner's ``run()``, and write ``summary.csv`` +and ``summary.md`` (arm, the one differing knob, seconds per phase, +cache counters, scores):: + + experiments.py ab --flag cache-frozen-text -- + experiments.py sweep --flag window-hours --values 0 24 48 -- + experiments.py ablate --modalities notes -- + +``ablate`` drops each modality at the model stage via the runner's +``--drop-modality``: same task, same samples, same split, same seed. +Extra arguments pass through to every arm unchanged. Each arm gets its +own output directory under ``--output-root``. The driver refuses to run +when the flag does not exist, is inert for the chosen backbone or task, +or the arms would differ in more than the declared knob, or a +passed-through ``--drop-modality`` would be silently replaced by the +ablation arms. The summary checks (not asserts) that seed, split sizes, +and sample identity match across arms and says which differ. +""" + +from __future__ import annotations + +import argparse +import csv +import importlib.util +import json +import sys +from functools import lru_cache +from pathlib import Path +from typing import Any, Callable, Dict, List, Optional, Tuple + +_RUNNER_PATH = Path(__file__).resolve().parent / "unified_embedding_e2e_mimic4.py" + +ALIASES = {"window-hours": "observation-window-hours"} + + +def _bool(value: str) -> bool: + text = value.strip().lower() + if text in ("1", "true", "on", "yes"): + return True + if text in ("0", "false", "off", "no"): + return False + raise ValueError(f"Not a boolean value: {value!r} (use on/off).") + + +# dest -> converter for --values parsing. Reachability (which backbone or +# task a flag is live for) comes from the runner, not from here: task +# scope below, backbone scope from the runner's own wiring map, so the +# two can never disagree about what the runner passes to the model. +_CONVERTERS: Dict[str, Callable[[str], Any]] = { + "ehr_root": str, "note_root": str, + "cache_dir": str, "task": str, + "model": str, "embedding_dim": int, + "hidden_dim": int, + "dropout": float, "epochs": int, "batch_size": int, + "lr": float, "adam_eps": float, + "weight_decay": float, "device": str, + "use_amp": _bool, "amp_dtype": str, + "accumulation_steps": int, "num_workers": int, + "pin_memory": _bool, "persistent_workers": _bool, + "prefetch_factor": int, "seed": int, + "patience": int, "dev": int, + "observation_window_hours": float, + "freeze_encoder": _bool, + "cache_frozen_text": _bool, + "max_frozen_text_cache": int, + "rnn_type": str, "rnn_layers": int, + "bidirectional": _bool, + "heads": int, + "num_layers": int, + "bottlenecks_n": int, + "fusion_startidx": int, + "max_grad_norm": float, + "wandb": _bool, "wandb_project": str, + "wandb_entity": str, "wandb_run_name": str, + "wandb_tags": str, + "mamba_state_size": int, + "mamba_conv_kernel": int, + "jamba_transformer_layers": int, + "jamba_mamba_layers": int, +} + +# dest -> tasks it is live for. Everything else applies to every task. +_TASK_ONLY: Dict[str, set] = { + "note_root": {"notes_labs"}, + "freeze_encoder": {"notes_labs"}, + "cache_frozen_text": {"notes_labs"}, + "max_frozen_text_cache": {"notes_labs"}, +} + + +@lru_cache(maxsize=1) +def _load_runner() -> Any: + """Load the runner module once; arms of one driver run share it.""" + spec = importlib.util.spec_from_file_location("unified_e2e_runner", _RUNNER_PATH) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def resolve_flag(name: str) -> str: + """Resolve a ``--flag`` name to the runner argparse dest. + + Accepts leading dashes and either spelling, plus the + ``window-hours`` alias for ``observation-window-hours``. + + Example: + >>> resolve_flag("window-hours") + 'observation_window_hours' + """ + key = ALIASES.get(name.lstrip("-"), name.lstrip("-")).replace("-", "_") + if key in _CONVERTERS: + return key + raise ValueError( + f"Unknown --flag {name!r}. See " + "unified_embedding_e2e_mimic4.py --help for the flag list." + ) + + +def _check_live(dest: str, task: str, model: str) -> None: + tasks = _TASK_ONLY.get(dest) + if tasks is not None and task not in tasks: + raise ValueError( + f"--flag {dest} is inert for --task {task} " + f"(reaches only {sorted(tasks)}). Refusing." + ) + arch_used = _load_runner()._ARCH_FLAGS_USED + if dest in _load_runner()._ARCH_FLAGS_ALL: + if model not in arch_used or dest not in arch_used[model]: + raise ValueError( + f"--flag {dest} is inert for --model {model} " + "(the runner never passes it to that backbone). Refusing." + ) + + +def build_arms( + mode: str, + base: argparse.Namespace, + flag: Optional[str] = None, + values: Optional[List[str]] = None, + modalities: Optional[List[str]] = None, + offs: Optional[List[str]] = None, +) -> List[Tuple[str, str, Dict[str, Any]]]: + """Build ``(arm_name, differs, overrides)`` triples for one mode. + + Pure function (no runs): ``ab`` gives two arms, ``sweep`` gives one + per value, ``ablate`` gives full plus one arm per dropped modality + or switched-off boolean component. ``ablate`` drops modalities at the + model stage (same task, samples, split, seed); dropping everything is + refused. Raises ``ValueError`` on unknown flags, inert flags, or arms + that would not differ in exactly one knob. + + Example: + >>> import argparse + >>> base = argparse.Namespace(task="labs", model="rnn") + >>> [a[0] for a in build_arms("ab", base, flag="bidirectional")] + ['ab_bidirectional_off', 'ab_bidirectional_on'] + """ + if mode == "ab": + dest = resolve_flag(flag or "") + _check_live(dest, base.task, base.model) + converter = _CONVERTERS[dest] + if values: + if len(values) != 2: + raise ValueError("ab takes exactly 2 --values (or none for booleans).") + pair = [converter(v) for v in values] + elif converter is _bool: + pair = [False, True] + else: + raise ValueError(f"ab --flag {dest} needs --values (not a boolean).") + if pair[0] == pair[1]: + raise ValueError("ab arms would be identical. Refusing.") + return [ + (f"ab_{dest}_{'on' if v is True else 'off' if v is False else v}", + f"{dest}={v}", {dest: v}) + for v in pair + ] + if mode == "sweep": + dest = resolve_flag(flag or "") + _check_live(dest, base.task, base.model) + converter = _CONVERTERS[dest] + if not values or len(values) < 2: + raise ValueError("sweep needs --values with at least 2 entries.") + seen = [converter(v) for v in values] + if len(set(map(repr, seen))) != len(seen): + raise ValueError("sweep --values contains duplicates. Refusing.") + return [(f"sweep_{dest}_{v}", f"{dest}={v}", {dest: v}) for v in seen] + if mode == "ablate": + runner = _load_runner() + modalities = modalities or [] + if len(set(modalities)) != len(modalities): + raise ValueError("ablate --modalities contains duplicates. Refusing.") + for modality in modalities: + if modality not in runner._DROP_MODALITY_FIELDS: + raise ValueError( + f"Cannot drop modality {modality!r}: " + f"droppable modalities are " + f"{sorted(runner._DROP_MODALITY_FIELDS)}." + ) + if len(set(offs or [])) != len(offs or []): + raise ValueError("ablate --off contains duplicates. Refusing.") + arms = [("ablate_full", "none (reference)", {"drop_modality": []})] + for modality in modalities: + arms.append( + (f"ablate_no_{modality}", f"drop {modality}", + {"drop_modality": [modality]}) + ) + for name in offs or []: + dest = resolve_flag(name) + _check_live(dest, base.task, base.model) + if _CONVERTERS[dest] is not _bool: + raise ValueError(f"--off {dest} is not a boolean component. Refusing.") + if getattr(base, dest, False) is not True: + raise ValueError( + f"--off {dest}: base run already has it off, " + "the arm would be identical. Refusing." + ) + arms.append((f"ablate_no_{dest}", f"{dest}=False", {dest: False})) + if len(arms) < 2: + raise ValueError("ablate needs --modalities and/or --off. Refusing.") + for _, _, overrides in arms[1:]: + if "drop_modality" in overrides: + probe = argparse.Namespace( + task=base.task, drop_modality=overrides["drop_modality"]) + try: + runner._check_drop_modality(probe) + except ValueError as exc: + raise ValueError(str(exc)) + return arms + raise ValueError(f"Unknown mode {mode!r} (ab, sweep, ablate).") + + +def assert_single_knob( + base: Dict[str, Any], + arm: Dict[str, Any], + declared: str, +) -> None: + """Refuse when an arm differs from base in more than the declared knob. + + ``output_dir`` is always per-arm and excluded. An arm may match base + on the knob (it still differs from its siblings); distinctness of the + declared values is enforced in :func:`build_arms`. + + Example: + >>> assert_single_knob({"a": 1, "seed": 2}, {"a": 9, "seed": 2}, "a") + """ + extra = { + key for key in arm + if key != "output_dir" and arm[key] != base.get(key) + } + allowed = {declared} if declared is not None else set() + if not extra <= allowed: + raise ValueError( + f"Arm differs in {sorted(extra)}, not only {declared!r}. Refusing." + ) + + +def _summarize_arm(output_csv: Path) -> Dict[str, Any]: + metrics = json.loads((output_csv.parent / "metrics.json").read_text()) + inference_patient_ids = None + try: + with output_csv.open(newline="") as handle: + ids = sorted( + {row["patient_id"] for row in csv.DictReader(handle) + if row.get("patient_id")} + ) + inference_patient_ids = ids or None + except OSError: + inference_patient_ids = None + return { + "train_s": round(sum(metrics["epoch_train_seconds"]), 3), + "eval_s": round(metrics["eval_seconds"], 3), + "infer_s": round(metrics["inference_seconds"], 3), + "cache": metrics["frozen_text_cache"], + "split": metrics["split"], + "inference_patient_ids": inference_patient_ids, + "scores": metrics["test_scores"], + "seed": metrics["config"]["seed"], + } + + +def _checked_lines(rows: List[Dict[str, Any]]) -> List[str]: + """Seed, split-size, and sample-identity comparison lines. + + The identity check compares unique inference-split patient ids only: + train/val splits and labels are not compared. Each check states what + is true; when arms differ it names which arms differ and how, instead + of asserting identity unconditionally. + """ + by_seed: Dict[Any, List[str]] = {} + by_split: Dict[str, List[str]] = {} + by_ids: Dict[Any, List[str]] = {} + for row in rows: + by_seed.setdefault(row["seed"], []).append(row["arm"]) + by_split.setdefault( + json.dumps(row["split"], sort_keys=True), []).append(row["arm"]) + ids = (None if row["inference_patient_ids"] is None + else tuple(row["inference_patient_ids"])) + by_ids.setdefault(ids, []).append(row["arm"]) + if len(by_seed) == 1: + lines = [f"Seeds identical across arms: all {len(rows)} use " + f"seed {rows[0]['seed']}."] + else: + detail = "; ".join( + f"{', '.join(arms)} use seed {seed}" + for seed, arms in by_seed.items()) + lines = [f"Seeds DIFFER across arms: {detail}."] + if len(by_split) == 1: + split = rows[0]["split"] + lines.append( + f"Split sizes identical across arms: train {split['train']}, " + f"val {split['val']}, test {split['test']}.") + else: + detail = "; ".join( + f"{', '.join(arms)}: {split}" + for split, arms in by_split.items()) + lines.append(f"Split sizes DIFFER across arms: {detail}.") + if len(by_ids) == 1 and rows[0]["inference_patient_ids"] is not None: + lines.append( + f"Sample identity identical across arms: " + f"{len(rows[0]['inference_patient_ids'])} unique " + f"inference-split patient ids match (train/val splits and " + f"labels not compared).") + elif len(by_ids) == 1: + lines.append("Sample identity not recorded: no inference-split " + "patient ids recorded for the arms.") + else: + detail = "; ".join( + f"{', '.join(arms)}: " + f"{'not recorded' if ids is None else f'{len(ids)} ids'}" + for ids, arms in by_ids.items()) + lines.append(f"Sample identity DIFFERS across arms " + f"(unique inference-split ids; train/val splits and " + f"labels not compared): {detail}.") + return lines + + +def write_summary(root: Path, rows: List[Dict[str, Any]]) -> None: + """Write ``summary.csv`` and ``summary.md`` for the finished arms. + + Example: + >>> import tempfile + >>> d = tempfile.mkdtemp() + >>> write_summary(Path(d), [{"arm": "a", "differs": "x=1", + ... "train_s": 1.0, "eval_s": 0.5, "infer_s": 0.5, + ... "cache": {"hits": 0, "misses": 0, "size": 0}, + ... "split": {"train": 1, "val": 0, "test": 0}, + ... "inference_patient_ids": ["p1"], + ... "scores": {"pr_auc": 0.5}, "seed": 2}]) + >>> (Path(d) / "summary.csv").is_file() + True + """ + score_keys = sorted({k for r in rows for k in r["scores"]}) + fieldnames = (["arm", "differs", "seed", "train_s", "eval_s", "infer_s", + "cache_hits", "cache_misses", "cache_size"] + + [f"score_{k}" for k in score_keys]) + with (root / "summary.csv").open("w", newline="") as f: + writer = csv.DictWriter(f, fieldnames=fieldnames) + writer.writeheader() + for r in rows: + writer.writerow({ + "arm": r["arm"], "differs": r["differs"], "seed": r["seed"], + "train_s": r["train_s"], "eval_s": r["eval_s"], + "infer_s": r["infer_s"], + "cache_hits": r["cache"]["hits"], + "cache_misses": r["cache"]["misses"], + "cache_size": r["cache"]["size"], + **{f"score_{k}": r["scores"].get(k) for k in score_keys}, + }) + lines = ["# Experiment summary", "", + "| " + " | ".join(fieldnames) + " |", + "|" + "|".join(["---"] * len(fieldnames)) + "|"] + with (root / "summary.csv").open() as f: + reader = csv.DictReader(f) + for row in reader: + lines.append("| " + " | ".join(row[c] for c in fieldnames) + " |") + lines += [""] + _checked_lines(rows) + (root / "summary.md").write_text("\n".join(lines) + "\n") + + +def _driver_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--output-root", default="./output/unified_experiments") + sub = parser.add_subparsers(dest="mode", required=True) + ab = sub.add_parser("ab") + ab.add_argument("--flag", required=True) + ab.add_argument("--values", nargs=2, default=None) + sweep = sub.add_parser("sweep") + sweep.add_argument("--flag", required=True) + sweep.add_argument("--values", nargs="+", required=True) + ablate = sub.add_parser("ablate") + ablate.add_argument("--modalities", nargs="*", default=[]) + ablate.add_argument("--off", nargs="*", default=[], dest="offs") + return parser + + +def main(argv: Optional[List[str]] = None, run_fn: Optional[Callable] = None) -> Path: + """Entry point (``argv`` injectable for tests). + + Driver options come first, then ``--``, then the runner arguments:: + + experiments.py --output-root ./out ab --flag bidirectional -- + + Example: + >>> main(["--help"]) # doctest: +SKIP + """ + parser = _driver_parser() + argv = list(sys.argv[1:] if argv is None else argv) + if "--" in argv: + cut = argv.index("--") + driver_argv, passthrough = argv[:cut], argv[cut + 1:] + else: + driver_argv, passthrough = argv, [] + if any(a.startswith("--ehr-root") for a in driver_argv): + parser.error("put runner arguments after '--'.") + args = parser.parse_args(driver_argv) + if any(a == "--output-dir" or a.startswith("--output-dir=") for a in passthrough): + parser.error("pass --output-root instead; each arm gets its own --output-dir.") + runner = _load_runner() + base = runner.parse_args(passthrough) + if args.mode == "ablate" and (getattr(base, "drop_modality", None) or []): + parser.error( + "ablate sets --drop-modality per arm; a passed-through value " + "would be silently replaced by the arm overrides. Drop it from " + "the runner arguments." + ) + try: + arms = build_arms(args.mode, base, getattr(args, "flag", None), + getattr(args, "values", None), + getattr(args, "modalities", None), + getattr(args, "offs", None)) + except ValueError as exc: + parser.error(str(exc)) + root = Path(args.output_root) + root.mkdir(parents=True, exist_ok=True) + run = run_fn or runner.run + rows = [] + for name, differs, overrides in arms: + arm_args = argparse.Namespace(**{**vars(base), **overrides}) + declared = next(iter(overrides)) if overrides else None + arm_args.output_dir = str(root / name) + try: + assert_single_knob(vars(base), vars(arm_args), declared) + except ValueError as exc: + parser.error(str(exc)) + output_csv = Path(run(arm_args)) + rows.append({"arm": name, "differs": differs, + **_summarize_arm(output_csv)}) + write_summary(root, rows) + print(f"Wrote {root / 'summary.csv'} and {root / 'summary.md'}") + return root + + +if __name__ == "__main__": + main() From 6b598432b518c5b0b78ad37844df99f20e773787 Mon Sep 17 00:00:00 2001 From: Rian Date: Thu, 5 Nov 2026 20:38:53 -0500 Subject: [PATCH 5/6] Cover the experiment driver with unit and demo-fixture tests. Sixteen pure checks (converters, arm construction, refusal paths, fake-run summaries with identical, differing, and empty predictions, the single cached runner loader) plus four real demo-fixture cases: one per mode on labs, and a notes ablation on notes_labs asserting identical splits and sample ids across arms with zero frozen-cache traffic in the dropped arm. Tests: tests/core/test_unified_experiments.py (20 passed: 16 unit and 4 demo-fixture, CPU; the notes case needs the t... Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95 --- tests/core/test_unified_experiments.py | 544 +++++++++++++++++++++++++ 1 file changed, 544 insertions(+) create mode 100644 tests/core/test_unified_experiments.py diff --git a/tests/core/test_unified_experiments.py b/tests/core/test_unified_experiments.py new file mode 100644 index 0000000000..17b1084390 --- /dev/null +++ b/tests/core/test_unified_experiments.py @@ -0,0 +1,544 @@ +"""Tests for the one-knob experiment driver. + +Pure arm-construction checks run in milliseconds. The demo-data cases +drive the real runner on the public MIMIC-IV demo fixture (CPU, 1 epoch, +seed 2) -- slower, but no downloads except the notes_labs ablation case, +which is skipped unless the text model is already in the local cache. +""" + +import csv +import importlib.util +import json +import unittest +from pathlib import Path +from tempfile import TemporaryDirectory + + +def _module(name, relative): + path = Path(__file__).resolve().parents[2] / relative + spec = importlib.util.spec_from_file_location(name, path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def _driver(): + return _module( + "unified_experiments", + Path("examples") / "mortality_prediction" / "unified_embedding_experiments.py", + ) + + +def _runner(): + return _module( + "unified_e2e_runner", + Path("examples") / "mortality_prediction" / "unified_embedding_e2e_mimic4.py", + ) + + +def _base(driver, runner, **overrides): + base = runner.parse_args(["--ehr-root", "/tmp/does-not-exist"]) + base.task = "labs" + base.model = "rnn" + for key, value in overrides.items(): + setattr(base, key, value) + return base + + +def _fake_run_factory(calls, arm_specs=None): + """Fake arm runs cycling through per-arm specs. + + Each spec holds ``split``, ``seed``, and ``ids`` (inference-split + patient ids written to a predictions file, as the real runner does). + """ + specs = arm_specs or [{}] + + def _fake_run(args): + spec = specs[len(calls) % len(specs)] + calls.append(vars(args)) + outdir = Path(args.output_dir) / "fake" + outdir.mkdir(parents=True, exist_ok=True) + metrics = { + "config": {"seed": spec.get("seed", 2)}, + "split": spec.get("split", {"train": 10, "val": 1, "test": 2}), + "epoch_train_seconds": [1.0], + "eval_seconds": 0.5, + "inference_seconds": 0.5, + "frozen_text_cache": {"hits": 0, "misses": 0, "size": 0}, + "test_scores": {"pr_auc": 0.5}, + } + (outdir / "metrics.json").write_text(json.dumps(metrics)) + with (outdir / "predictions.csv").open("w", newline="") as handle: + writer = csv.writer(handle) + writer.writerow(["patient_id", "y_true", "y_prob", + "y_pred_threshold_0_5"]) + for pid in spec.get("ids", ["p1", "p2"]): + writer.writerow([pid, 0, 0.5, 1]) + return str(outdir / "predictions.csv") + + return _fake_run + + +class TestFlagTable(unittest.TestCase): + def test_every_dest_exists_in_runner(self): + driver = _driver() + runner = _runner() + probe = runner.parse_args(["--ehr-root", "/tmp/does-not-exist"]) + for dest in driver._CONVERTERS: + self.assertTrue( + hasattr(probe, dest), f"converter entry {dest!r} missing from runner" + ) + + def test_alias(self): + self.assertEqual(_driver().resolve_flag("window-hours"), + "observation_window_hours") + + def test_unknown_flag_refused(self): + driver = _driver() + with self.assertRaises(ValueError): + driver.resolve_flag("learning-rate-warmup") + + def test_model_scope_comes_from_runner(self): + # The driver reuses the runner's own wiring map. JambaEHR receives + # --heads from the runner, so it is a live knob (the old driver + # table refused it); --num-layers never reaches JambaEHR, so it is + # refused (the old table allowed the no-op arm). + driver = _driver() + runner = _runner() + base = _base(driver, runner, task="notes_labs", model="jambaehr") + arms = driver.build_arms("ab", base, flag="heads", values=["2", "4"]) + self.assertEqual([a[2]["heads"] for a in arms], [2, 4]) + with self.assertRaises(ValueError): + driver.build_arms("ab", base, flag="num-layers", + values=["1", "2"]) + + +class TestBuildArms(unittest.TestCase): + def test_ab_boolean_defaults_to_on_off(self): + driver = _driver() + arms = driver.build_arms("ab", _base(driver, _runner()), flag="bidirectional") + self.assertEqual([a[0] for a in arms], + ["ab_bidirectional_off", "ab_bidirectional_on"]) + self.assertEqual([a[2] for a in arms], + [{"bidirectional": False}, {"bidirectional": True}]) + + def test_ab_values(self): + driver = _driver() + arms = driver.build_arms("ab", _base(driver, _runner()), + flag="batch-size", values=["8", "4"]) + self.assertEqual([a[2]["batch_size"] for a in arms], [8, 4]) + + def test_ab_refusals(self): + driver = _driver() + runner = _runner() + with self.assertRaises(ValueError): # identical arms + driver.build_arms("ab", _base(driver, runner), + flag="batch-size", values=["8", "8"]) + with self.assertRaises(ValueError): # non-boolean needs values + driver.build_arms("ab", _base(driver, runner), flag="batch-size") + with self.assertRaises(ValueError): # unknown flag + driver.build_arms("ab", _base(driver, runner), flag="frobnicate") + with self.assertRaises(ValueError): # inert for task + driver.build_arms("ab", _base(driver, runner), + flag="cache-frozen-text") + with self.assertRaises(ValueError): # inert for backbone + driver.build_arms( + "ab", _base(driver, runner, model="transformer"), + flag="hidden-dim", values=["8", "16"]) + + def test_sweep(self): + driver = _driver() + arms = driver.build_arms("ab", _base(driver, _runner()), + flag="bidirectional", values=["0", "1"]) + self.assertEqual([a[2]["bidirectional"] for a in arms], [False, True]) + arms = driver.build_arms("sweep", _base(driver, _runner()), + flag="window-hours", values=["0", "24", "48"]) + self.assertEqual([a[2]["observation_window_hours"] for a in arms], + [0.0, 24.0, 48.0]) + with self.assertRaises(ValueError): # duplicates + driver.build_arms("sweep", _base(driver, _runner()), + flag="window-hours", values=["0", "0"]) + with self.assertRaises(ValueError): # single value + driver.build_arms("sweep", _base(driver, _runner()), + flag="window-hours", values=["0"]) + + def test_ablate_modalities(self): + driver = _driver() + runner = _runner() + arms = driver.build_arms( + "ablate", _base(driver, runner, task="notes_labs"), + modalities=["notes"]) + self.assertEqual([a[0] for a in arms], ["ablate_full", "ablate_no_notes"]) + self.assertEqual(arms[0][2], {"drop_modality": []}) + self.assertEqual(arms[1][2], {"drop_modality": ["notes"]}) + arms = driver.build_arms( + "ablate", _base(driver, runner, task="notes_labs"), + modalities=["labs"]) + self.assertEqual([a[0] for a in arms], ["ablate_full", "ablate_no_labs"]) + self.assertEqual(arms[1][2], {"drop_modality": ["labs"]}) + arms = driver.build_arms( + "ablate", _base(driver, runner, task="notes_labs"), + modalities=["notes", "labs"]) + self.assertEqual([a[0] for a in arms], + ["ablate_full", "ablate_no_notes", "ablate_no_labs"]) + with self.assertRaises(ValueError): # unknown modality + driver.build_arms("ablate", _base(driver, runner, task="notes_labs"), + modalities=["image"]) + with self.assertRaises(ValueError): # duplicates + driver.build_arms("ablate", _base(driver, runner, task="notes_labs"), + modalities=["notes", "notes"]) + with self.assertRaises(ValueError): # labs task has no notes + driver.build_arms("ablate", _base(driver, runner, task="labs"), + modalities=["notes"]) + with self.assertRaises(ValueError): # nothing left on labs either + driver.build_arms("ablate", _base(driver, runner, task="labs"), + modalities=["labs"]) + with self.assertRaises(ValueError): # nothing to drop + driver.build_arms("ablate", _base(driver, runner)) + + def test_ablate_off(self): + driver = _driver() + runner = _runner() + arms = driver.build_arms( + "ablate", _base(driver, runner, model="rnn", bidirectional=True), + offs=["bidirectional"]) + self.assertEqual([a[0] for a in arms], + ["ablate_full", "ablate_no_bidirectional"]) + self.assertEqual(arms[0][2], {"drop_modality": []}) + self.assertEqual(arms[1][2], {"bidirectional": False}) + with self.assertRaises(ValueError): # already off: no-op arm + driver.build_arms("ablate", _base(driver, runner), + offs=["bidirectional"]) + with self.assertRaises(ValueError): # not a boolean component + driver.build_arms( + "ablate", _base(driver, runner, model="rnn", bidirectional=True), + offs=["hidden-dim"]) + + def test_single_knob_guard(self): + driver = _driver() + base = {"batch_size": 8, "seed": 2, "output_dir": "root"} + arm = {"batch_size": 4, "seed": 2, "output_dir": "root/arm"} + driver.assert_single_knob(base, arm, "batch_size") + bad = dict(arm, seed=3) + with self.assertRaises(ValueError): + driver.assert_single_knob(base, bad, "batch_size") + + def test_main_fake_run_writes_summary(self): + driver = _driver() + calls = [] + with TemporaryDirectory() as tmp: + root = driver.main( + ["--output-root", str(Path(tmp) / "exp"), + "ab", "--flag", "batch-size", "--values", "8", "4", "--", + "--ehr-root", "/tmp/does-not-exist", "--seed", "2", + "--batch-size", "8"], + run_fn=_fake_run_factory(calls), + ) + self.assertEqual(len(calls), 2) + # Extra args pass through to every arm unchanged. + self.assertTrue(all(c["seed"] == 2 for c in calls)) + self.assertEqual([c["batch_size"] for c in calls], [8, 4]) + # Each arm gets its own output directory. + self.assertEqual(len({c["output_dir"] for c in calls}), 2) + summary = Path(root) / "summary.csv" + self.assertTrue(summary.is_file()) + md = (Path(root) / "summary.md").read_text() + with summary.open() as f: + rows = list(csv.DictReader(f)) + self.assertEqual(len(rows), 2) + self.assertEqual(rows[0]["seed"], "2") + self.assertIn("identical across arms", md) + + def test_main_summary_reports_differences(self): + # The summary computes identity; it never asserts it. Arms with + # different seeds, splits, and samples say so, naming the arms. + driver = _driver() + calls = [] + specs = [ + {"seed": 2, "split": {"train": 10, "val": 1, "test": 2}, + "ids": ["p1", "p2"]}, + {"seed": 3, "split": {"train": 9, "val": 1, "test": 2}, + "ids": ["p1", "p3"]}, + ] + with TemporaryDirectory() as tmp: + root = driver.main( + ["--output-root", str(Path(tmp) / "exp"), + "ab", "--flag", "batch-size", "--values", "8", "4", "--", + "--ehr-root", "/tmp/does-not-exist", "--seed", "2", + "--batch-size", "8"], + run_fn=_fake_run_factory(calls, specs), + ) + md = (Path(root) / "summary.md").read_text() + self.assertIn("Seeds DIFFER across arms", md) + self.assertIn("Split sizes DIFFER across arms", md) + self.assertIn("Sample identity DIFFERS across arms", md) + + def test_main_refuses_before_running(self): + driver = _driver() + with TemporaryDirectory() as tmp: + with self.assertRaises(SystemExit): + driver.main( + ["ab", "--flag", "cache-frozen-text", "--", + "--ehr-root", "/tmp/does-not-exist"], + run_fn=lambda args: (_ for _ in ()).throw( + AssertionError("must refuse before running")), + ) + with self.assertRaises(SystemExit): + driver.main( + ["sweep", "--flag", "batch-size", "--values", "8", "--", + "--ehr-root", "/tmp/does-not-exist", + "--output-dir", str(Path(tmp) / "x")], + run_fn=lambda args: (_ for _ in ()).throw( + AssertionError("must refuse before running")), + ) + with self.assertRaises(SystemExit): # runner args need '--' + driver.main( + ["ab", "--flag", "batch-size", "--values", "8", "4", + "--ehr-root", "/tmp/does-not-exist"], + run_fn=lambda args: (_ for _ in ()).throw( + AssertionError("must refuse before running")), + ) + with self.assertRaises(SystemExit): # nothing left on labs + driver.main( + ["ablate", "--modalities", "labs", "--", + "--ehr-root", "/tmp/does-not-exist", + "--task", "labs"], + run_fn=lambda args: (_ for _ in ()).throw( + AssertionError("must refuse before running")), + ) + with self.assertRaises(SystemExit): # ablate owns --drop-modality + driver.main( + ["ablate", "--modalities", "notes", "--", + "--ehr-root", "/tmp/does-not-exist", + "--task", "notes_labs", + "--drop-modality", "notes"], + run_fn=lambda args: (_ for _ in ()).throw( + AssertionError("must refuse before running")), + ) + + def test_single_cached_runner_loader(self): + # One cached _load_runner(); no _cached_runner or _CACHED_RUNNER. + driver = _driver() + self.assertFalse(hasattr(driver, "_cached_runner")) + self.assertFalse(hasattr(driver, "_CACHED_RUNNER")) + self.assertIs(driver._load_runner(), driver._load_runner()) + + def test_main_summary_empty_predictions_not_recorded(self): + # An empty predictions file (header only) reports identity as + # not recorded, not "0 ids match". + driver = _driver() + calls = [] + specs = [{"seed": 2, "ids": []}] + with TemporaryDirectory() as tmp: + root = driver.main( + ["--output-root", str(Path(tmp) / "exp"), + "ab", "--flag", "batch-size", "--values", "8", "4", "--", + "--ehr-root", "/tmp/does-not-exist", "--seed", "2", + "--batch-size", "8"], + run_fn=_fake_run_factory(calls, specs), + ) + md = (Path(root) / "summary.md").read_text() + self.assertIn("Sample identity not recorded", md) + + +DEMO_ROOT = ( + Path(__file__).resolve().parents[2] / "test-resources" / "core" / "mimic4demo" +) + + +def _demo_argv(mode_args, tmp, root, cache, model="rnn", extra=()): + return ["--output-root", str(Path(tmp) / root)] + mode_args + [ + "--", + "--ehr-root", str(DEMO_ROOT), + "--task", "labs", "--model", model, + "--epochs", "1", "--batch-size", "8", + "--embedding-dim", "8", "--hidden-dim", "8", + "--device", "cpu", "--seed", "2", + "--no-cache-frozen-text", + "--cache-dir", cache, + "--num-workers", "1", + *extra, + ] + + +def _summaries(testcase, root, arms): + summary = Path(root) / "summary.csv" + testcase.assertTrue(summary.is_file()) + md = (Path(root) / "summary.md").read_text() + with summary.open() as f: + rows = list(csv.DictReader(f)) + testcase.assertEqual(len(rows), arms) + # Same seed across arms; splits checked against metrics.json below. + testcase.assertEqual({row["seed"] for row in rows}, {"2"}) + testcase.assertIn("identical across arms", md) + return rows + + +def _check_same_split(testcase, root, rows): + splits = set() + for row in rows: + for metrics_path in (Path(root) / row["arm"]).rglob("metrics.json"): + metrics = json.loads(metrics_path.read_text()) + splits.add(json.dumps(metrics["split"], sort_keys=True)) + testcase.assertEqual(metrics["config"]["seed"], 2) + testcase.assertEqual(len(splits), 1, f"splits differ: {splits}") + + +class TestDriverDemoData(unittest.TestCase): + """One real demo-fixture case per mode (labs, CPU, seconds each).""" + + @classmethod + def setUpClass(cls): + cls._tmp = TemporaryDirectory() + cls.cache = str(Path(cls._tmp.name) / "cache") + + @classmethod + def tearDownClass(cls): + cls._tmp.cleanup() + + def _run(self, mode_args, root, model="rnn", extra=()): + driver = _driver() + with TemporaryDirectory() as tmp: + out = driver.main( + _demo_argv(mode_args, tmp, root, self.cache, model, extra), + ) + rows = _summaries(self, out, 2) + _check_same_split(self, out, rows) + return rows + + def test_ab_bidirectional(self): + rows = self._run(["ab", "--flag", "bidirectional"], "ab", extra=()) + self.assertEqual([r["differs"] for r in rows], + ["bidirectional=False", "bidirectional=True"]) + + def test_sweep_window(self): + rows = self._run( + ["sweep", "--flag", "window-hours", "--values", "0", "24"], + "sweep", model="mlp") + self.assertEqual([r["differs"] for r in rows], + ["observation_window_hours=0.0", + "observation_window_hours=24.0"]) + + def test_ablate_off(self): + rows = self._run(["ablate", "--off", "bidirectional"], "ablate", + extra=("--bidirectional",)) + self.assertEqual(rows[0]["differs"], "none (reference)") + self.assertEqual(rows[1]["differs"], "bidirectional=False") + + +def _write_note_csvs(note_dir): + import gzip + + def _write(path, rows): + with gzip.open(path, "wt", encoding="utf-8", newline="") as handle: + writer = csv.writer(handle) + writer.writerow( + ["subject_id", "charttime", "note_id", "hadm_id", "note_type", + "note_seq", "storetime", "text"] + ) + writer.writerows(rows) + + _write( + note_dir / "discharge.csv.gz", + [ + (10008, "2151-10-05", 1, 20012, "discharge", 1, + "2151-10-25 12:00:00", "Chief Complaint:\n\nshortness of breath\n\n"), + (10008, "2151-12-15", 2, 20013, "discharge", 1, + "2151-12-20 12:00:00", "Chief Complaint:\n\nchest pain\n\n"), + ], + ) + _write( + note_dir / "radiology.csv.gz", + [ + (10008, "2151-10-06 09:00:00", 3, 20012, "radiology", 1, + "2151-10-06 10:00:00", "Impression:\n\nno acute findings\n\n"), + ], + ) + + +class TestDriverDemoAblate(unittest.TestCase): + """Real same-task modality ablation on the demo fixture. + + notes_labs reference plus the arm with notes dropped: identical split + sizes and sample ids across arms, and zero frozen-cache traffic in + the drop arm. The labs drop is covered at the arm-construction level + (`test_ablate_modalities`) and against the real cohort in the + cluster ablation run: on this 13-sample toy fixture the notes-only + arm leaves batches the RNN backbone cannot pack (pre-existing + all-empty-batch limit, also present on the labs task), so the demo + run keeps the arms that hold labs. Needs the text model in the local + HF cache; tests never download. + """ + + @classmethod + def setUpClass(cls): + try: + from transformers import AutoTokenizer + + AutoTokenizer.from_pretrained( + "emilyalsentzer/Bio_ClinicalBERT", local_files_only=True + ) + except Exception as exc: # noqa: BLE001 -- any load failure means skip + raise unittest.SkipTest(f"text model not in local HF cache: {exc}") + cls._tmp = TemporaryDirectory() + cls.cache = str(Path(cls._tmp.name) / "cache") + + @classmethod + def tearDownClass(cls): + cls._tmp.cleanup() + + def test_ablate_modalities_same_task(self): + driver = _driver() + with TemporaryDirectory() as tmp: + note_dir = Path(tmp) / "notes" / "note" + note_dir.mkdir(parents=True, exist_ok=True) + _write_note_csvs(note_dir) + out = driver.main( + ["--output-root", str(Path(tmp) / "ablate"), + "ablate", "--modalities", "notes", "--", + "--ehr-root", str(DEMO_ROOT), + "--note-root", str(Path(tmp) / "notes"), + "--task", "notes_labs", "--model", "rnn", + "--epochs", "1", "--batch-size", "8", + "--embedding-dim", "8", "--hidden-dim", "8", + "--device", "cpu", "--seed", "2", + "--freeze-encoder", + "--cache-dir", self.cache, + "--num-workers", "1"], + ) + rows = _summaries(self, out, 2) + self.assertEqual( + [r["arm"] for r in rows], + ["ablate_full", "ablate_no_notes"]) + by_arm = {} + expected_drop = {"ablate_full": [], + "ablate_no_notes": ["notes"]} + for row in rows: + matches = list((Path(out) / row["arm"]).rglob("metrics.json")) + self.assertEqual(len(matches), 1) + metrics = json.loads(matches[0].read_text()) + by_arm[row["arm"]] = metrics + self.assertEqual(metrics["config"]["seed"], 2) + self.assertEqual(metrics["config"]["drop_modality"], + expected_drop[row["arm"]]) + splits = {json.dumps(m["split"], sort_keys=True) + for m in by_arm.values()} + self.assertEqual(len(splits), 1, f"splits differ: {splits}") + ids = {} + for row in rows: + preds = list((Path(out) / row["arm"]).rglob("predictions*.csv")) + self.assertEqual(len(preds), 1) + with preds[0].open() as handle: + ids[row["arm"]] = sorted( + r["patient_id"] for r in csv.DictReader(handle)) + self.assertEqual(ids["ablate_full"], ids["ablate_no_notes"]) + full_cache = by_arm["ablate_full"]["frozen_text_cache"] + self.assertGreater(full_cache["misses"] + full_cache["size"], 0) + no_notes_cache = by_arm["ablate_no_notes"]["frozen_text_cache"] + self.assertEqual( + (no_notes_cache["hits"], no_notes_cache["misses"], + no_notes_cache["size"]), (0, 0, 0)) + + +if __name__ == "__main__": + unittest.main() From 8f77dbb8e72d91e439e69cab7c549ab087f04eee Mon Sep 17 00:00:00 2001 From: Rian Date: Thu, 5 Nov 2026 18:22:06 -0500 Subject: [PATCH 6/6] Document the experiment driver with pasted demo output. Three modes, same-task ablations through --drop-modality, the computed seed/split/identity check in summary.md, and the small utilities a user reaches for (cache counters, worker and Dask options, dev-mode honesty). The pasted numbers are a real demo-fixture sweep, labeled toy magnitudes. Tests: README only; the pasted CSV schema is pinned by the driver summary tests. Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95 --- .../README_unified_embedding.md | 113 ++++++++++++++++++ 1 file changed, 113 insertions(+) create mode 100644 examples/mortality_prediction/README_unified_embedding.md diff --git a/examples/mortality_prediction/README_unified_embedding.md b/examples/mortality_prediction/README_unified_embedding.md new file mode 100644 index 0000000000..25f97c164c --- /dev/null +++ b/examples/mortality_prediction/README_unified_embedding.md @@ -0,0 +1,113 @@ +# Unified-embedding experiments: A/B, sweeps, ablations + +`unified_embedding_experiments.py` drives the existing runner +(`unified_embedding_e2e_mimic4.py::run`) one arm at a time. Each arm +gets its own directory under `--output-root`; together they write +`summary.csv` and `summary.md` (arm, the one differing knob, seconds +per phase, frozen-text cache counters, test scores). + +Driver options come first, then `--`, then the runner arguments +(passed through to every arm unchanged): + +``` +# A/B: two arms, one flag differs (booleans need no --values) +python examples/mortality_prediction/unified_embedding_experiments.py \ + --output-root ./output/xp_ab \ + ab --flag cache-frozen-text -- \ + --ehr-root /data/mimic-iv/2.2 --note-root /data/mimic-iv/note \ + --task notes_labs --model transformer --epochs 3 --device cuda:0 --seed 2 + +# Sweep: N values of one flag (--flag window-hours is an alias) +python examples/mortality_prediction/unified_embedding_experiments.py \ + --output-root ./output/xp_win \ + sweep --flag window-hours --values 0 24 48 -- \ + --ehr-root /data/mimic-iv/2.2 --task labs --model mlp --epochs 1 --seed 2 + +# Ablate: reference plus one arm per dropped modality / switched-off component +python examples/mortality_prediction/unified_embedding_experiments.py \ + --output-root ./output/xp_abl \ + ablate --modalities notes labs --off cache-frozen-text -- \ + --ehr-root /data/mimic-iv/2.2 --note-root /data/mimic-iv/note \ + --task notes_labs --model transformer --epochs 3 --device cuda:0 --seed 2 +``` + +`ablate --modalities` drops each modality at the model stage through the +runner's `--drop-modality`: same task, same samples, same split, same +seed. `labs` drops the lab values and their observation mask, `notes` +drops the admission-note field; the cohort keeps every patient either +way. Dropping everything is refused, as is dropping a modality the +task does not have. + +Rules the driver enforces (it exits 2 instead of running): unknown +`--flag`; a flag inert for the chosen backbone or task (e.g. +`--hidden-dim` with `--model transformer`, the text-cache flags with +`--task labs` — backbone reachability comes from the runner's own +wiring map, so the two cannot disagree); arms that would differ in more +than the declared knob; duplicate values; `ablate` with nothing to drop +or nothing left after the drop; `ablate` with a passed-through +`--drop-modality` (the arms set it themselves, so a passed value would +be silently replaced). Sweeping `--seed` is allowed but +changes the split by design. Seed, split sizes, and sample identity are +checked across arms and reported in `summary.md` — identical when they +match, naming the arms that differ when they do not. The identity check +compares unique inference-split patient ids; train/val splits and labels +are not compared, and an empty predictions file reports not recorded. +Pass `--output-root`, not `--output-dir` (each arm gets its own +`--output-dir` underneath it). + +## Equivalent Python API + +```python +from examples.mortality_prediction import unified_embedding_experiments as xp + +runner = xp._load_runner() +base = runner.parse_args(["--ehr-root", "/data/mimic-iv/2.2", + "--task", "labs", "--model", "mlp", + "--epochs", "1", "--seed", "2"]) +arms = xp.build_arms("sweep", base, flag="window-hours", + values=["0", "24", "48"]) +xp.main(["--output-root", "./output/xp_win", "sweep", + "--flag", "window-hours", "--values", "0", "24", "48", + "--", "--ehr-root", "/data/mimic-iv/2.2", + "--task", "labs", "--model", "mlp", + "--epochs", "1", "--seed", "2"]) +``` + +## Small utilities you will actually use + +- Cache counters: every `metrics.json` carries + `frozen_text_cache: {hits, misses, size}`; the summary rolls them + up per arm. Compare the on/off arms of + `ab --flag cache-frozen-text` to see the timing effect. + `UnifiedMultimodalEmbeddingModel.reset_frozen_text_cache_stats()` + zeroes them mid-session. +- DataLoader workers: `--num-workers 1` (below 1 is refused when the + runner builds the dataset itself: a zero-worker Dask cluster never + computes, the local path divides by the worker count in + `set_task`, and a negative count dies inside loader construction; + a prebuilt sample dataset may still load with 0). + `--no-dask-distributed` builds the cache with the local Dask + scheduler instead of starting a cluster. `--pin-memory`, + `--persistent-workers` (needs workers > 0), `--prefetch-factor` + (needs workers > 0). On CPU, workers 1 with `OMP_NUM_THREADS` + pinned is the stable setting. +- Cache dir: share one `--cache-dir` across arms of a sweep; the + task cache key already includes task + window, so arms reuse each + other's dataset builds. A killed run can leave a stale + `tasks//build.lock`; delete the task dir and rerun. + +## Real output (public demo fixture, toy magnitudes, no scientific claim) + +`sweep --flag window-hours --values 0 24` on +`test-resources/core/mimic4demo`, labs, mlp, 1 epoch, CPU: + +``` +arm,differs,seed,train_s,eval_s,infer_s,cache_hits,cache_misses,cache_size,score_accuracy,score_f1,score_loss,score_pr_auc,score_roc_auc +sweep_observation_window_hours_0.0,observation_window_hours=0.0,2,16.934,8.491,8.727,0,0,0,0.5,0.0,0.6831296682357788,1.0,1.0 +sweep_observation_window_hours_24.0,observation_window_hours=24.0,2,16.913,8.432,8.743,0,0,0,0.5,0.0,0.6831296682357788,1.0,1.0 +``` + +Both arms agree to all digits: the 13-patient demo stays are short +enough that a 24 h window never binds. On real MIMIC-IV the same +command separates the arms; treat every number above as a timing +smoke test, not a result.