From 8aa75c2302685f872952e89ab4a6b523bf3b4011 Mon Sep 17 00:00:00 2001 From: Rian354 Date: Thu, 5 Nov 2026 15:30:20 -0500 Subject: [PATCH 01/11] Write run_config.json next to the metrics of a finished run. 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: 224e7f4d (utils part verbatim); provenance half matches the utils part of fork #53 d45e3ccd; 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 --- .../unified_embedding_e2e_mimic4.py | 12 +- pyhealth/utils.py | 129 +++++++++++++++++- tests/core/test_run_config.py | 52 +++++++ tests/core/test_unified_e2e_runner.py | 6 + 4 files changed, 196 insertions(+), 3 deletions(-) create mode 100644 tests/core/test_run_config.py diff --git a/examples/mortality_prediction/unified_embedding_e2e_mimic4.py b/examples/mortality_prediction/unified_embedding_e2e_mimic4.py index 8a83d76dc5..96c1662f29 100644 --- a/examples/mortality_prediction/unified_embedding_e2e_mimic4.py +++ b/examples/mortality_prediction/unified_embedding_e2e_mimic4.py @@ -65,7 +65,7 @@ from pyhealth.models.jamba_ehr import JambaEHR from pyhealth.tasks.multimodal_mimic4 import LabsMIMIC4, NotesLabsMIMIC4 from pyhealth.trainer import Trainer -from pyhealth.utils import set_seed +from pyhealth.utils import set_seed, write_run_config class WandbLogger: @@ -367,6 +367,16 @@ def run(args: argparse.Namespace, sample_dataset: Any = None) -> Path: optimizer_params["lr"] = effective_lr + write_run_config( + str(output_dir / exp_name), + { + **vars(args), + "n_train": len(train_ds), + "n_val": len(val_ds), + "n_test": len(test_ds), + }, + ) + epoch_train_seconds: List[float] = [] if args.epochs > 0 and len(train_ds) > 0: trainer.train( diff --git a/pyhealth/utils.py b/pyhealth/utils.py index 8af089b1a9..400a4fbc8f 100644 --- a/pyhealth/utils.py +++ b/pyhealth/utils.py @@ -1,10 +1,12 @@ +import contextlib +import functools +import hashlib import json import os import pickle import random -import contextlib -import functools import shutil +import subprocess import urllib.request import numpy as np @@ -162,24 +164,147 @@ def create_directory(directory): def load_pickle(filename): + """Load pickled data from a file. + + Example: + >>> import tempfile + >>> path = os.path.join(tempfile.mkdtemp(), "x.pkl") + >>> _ = open(path, "wb").write(pickle.dumps({"a": 1})) + >>> load_pickle(path) + {'a': 1} + """ with open(filename, "rb") as f: return pickle.load(f) def save_pickle(data, filename): + """Write data as pickle to a file. + + Example: + >>> import tempfile + >>> path = os.path.join(tempfile.mkdtemp(), "x.pkl") + >>> save_pickle({"a": 1}, path) is None + True + >>> load_pickle(path) + {'a': 1} + """ with open(filename, "wb") as f: pickle.dump(data, f) def load_json(filename): + """Load JSON data from a file. + + Example: + >>> import tempfile + >>> path = os.path.join(tempfile.mkdtemp(), "x.json") + >>> _ = open(path, "w").write('{"a": 1}') + >>> load_json(path) + {'a': 1} + """ with open(filename, "r") as f: return json.load(f) def save_json(data, filename): + """Write data as JSON to a file. + + Example: + >>> import tempfile + >>> path = os.path.join(tempfile.mkdtemp(), "x.json") + >>> save_json({"a": 1}, path) is None + True + >>> load_json(path) + {'a': 1} + """ with open(filename, "w") as f: json.dump(data, f) + +def _git_revision(): + repo = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + try: + commit = subprocess.check_output( + ["git", "rev-parse", "HEAD"], cwd=repo, stderr=subprocess.DEVNULL + ).decode().strip() + dirty = bool(subprocess.check_output( + ["git", "status", "--porcelain"], cwd=repo, stderr=subprocess.DEVNULL + ).decode().strip()) + return {"commit": commit, "dirty": dirty} + except Exception: # noqa: BLE001 - provenance must never break a run + return {"commit": None, "dirty": None} + + +def _source_digest(): + """Hash the package's ``.py`` sources so code identity survives deploy. + + Only ``.py`` files under the package are hashed: YAML configs, SQL, + shell launchers, and tokenizer/model artifacts are not covered (an + edited config in a no-git tarball is undetectable beyond its recorded + path). Cluster runs typically execute from an unpacked tarball rather + than a clone, so the git lookup returns nothing exactly where + provenance matters most. Hashing the sources keeps "which code + produced this result" answerable either way. + """ + package = os.path.dirname(os.path.abspath(__file__)) + digest = hashlib.sha256() + try: + for root, dirs, files in os.walk(package): + dirs[:] = sorted(d for d in dirs if d != "__pycache__") + for name in sorted(files): + if not name.endswith(".py"): + continue + path = os.path.join(root, name) + digest.update(os.path.relpath(path, package).encode()) + with open(path, "rb") as f: + digest.update(f.read()) + return digest.hexdigest() + except OSError: + return None + + +def _jsonable(value): + if isinstance(value, (str, int, float, bool)) or value is None: + return value + if isinstance(value, (list, tuple)): + return [_jsonable(v) for v in value] + if isinstance(value, dict): + return {str(k): _jsonable(v) for k, v in value.items()} + return str(value) + + +def write_run_config(exp_path, config): + """Persist the resolved run configuration next to the run's metrics. + + ``metrics_history.json`` records what a run scored but not the conditions + that produced it. Record the resolved settings, not the raw flags, so + derived conditions (lr, split mode, eval split) are recoverable. + + Examples: + >>> import json, tempfile + >>> path = write_run_config(tempfile.mkdtemp(), {"lr": 1e-4}) + >>> sorted(json.load(open(path))["config"]) + ['lr'] + """ + record = { + "config": {str(k): _jsonable(v) for k, v in config.items()}, + "git": _git_revision(), + "source_sha256": _source_digest(), + "torch": torch.__version__, + } + os.makedirs(exp_path, exist_ok=True) + path = os.path.join(exp_path, "run_config.json") + tmp = f"{path}.tmp.{os.getpid()}" + try: + with open(tmp, "w") as f: + json.dump(record, f, indent=2, sort_keys=True) + os.replace(tmp, path) + finally: + if os.path.exists(tmp): + os.remove(tmp) + return path + + @contextlib.contextmanager def set_env(**environ): """ diff --git a/tests/core/test_run_config.py b/tests/core/test_run_config.py new file mode 100644 index 0000000000..549a6171d8 --- /dev/null +++ b/tests/core/test_run_config.py @@ -0,0 +1,52 @@ +"""run_config.json next to the metrics of a finished run. + +``metrics.json`` stores the score but not the conditions, so a run that +changed one flag is indistinguishable from one that did not after the job +log is gone. The provenance half (git revision + source digest) keeps +"which code produced this result" answerable when the run executes from an +unpacked tarball with no git metadata. +""" + +from __future__ import annotations + +import json +import unittest +from pathlib import Path +from tempfile import TemporaryDirectory + + +class TestWriteRunConfig(unittest.TestCase): + def test_records_config_provenance_and_torch(self): + from pyhealth.utils import write_run_config + + with TemporaryDirectory() as tmp: + path = write_run_config(tmp, {"lr": 1e-4, "split": "by_patient"}) + self.assertTrue(path.endswith("run_config.json")) + data = json.loads(Path(path).read_text()) + self.assertEqual( + set(data), {"config", "git", "source_sha256", "torch"} + ) + self.assertEqual(data["config"]["lr"], 0.0001) + self.assertIn("commit", data["git"]) + self.assertEqual(len(data["source_sha256"]), 64) + self.assertTrue(data["torch"]) + + def test_non_jsonable_values_become_strings(self): + from pyhealth.utils import write_run_config + + with TemporaryDirectory() as tmp: + path = write_run_config(tmp, {"tags": ("a", "b"), "obj": object()}) + data = json.loads(Path(path).read_text()) + self.assertEqual(data["config"]["tags"], ["a", "b"]) + self.assertIsInstance(data["config"]["obj"], str) + + def test_no_partial_file_left_behind(self): + from pyhealth.utils import write_run_config + + with TemporaryDirectory() as tmp: + write_run_config(tmp, {"lr": 1e-4}) + leftovers = [ + p for p in Path(tmp).iterdir() if p.suffix.startswith(".tmp") + ] + self.assertEqual(leftovers, []) + self.assertTrue((Path(tmp) / "run_config.json").is_file()) diff --git a/tests/core/test_unified_e2e_runner.py b/tests/core/test_unified_e2e_runner.py index d7e8d14a59..802d0aef3e 100644 --- a/tests/core/test_unified_e2e_runner.py +++ b/tests/core/test_unified_e2e_runner.py @@ -191,6 +191,12 @@ def _assert_demo_metrics(testcase, output_csv): testcase.assertTrue(Path(output_csv).is_file()) metrics_path = Path(output_csv).parent / "metrics.json" testcase.assertTrue(metrics_path.is_file()) + run_config_path = Path(output_csv).parent / "run_config.json" + testcase.assertTrue(run_config_path.is_file()) + run_config = json.loads(run_config_path.read_text()) + testcase.assertEqual( + set(run_config), {"config", "git", "source_sha256", "torch"} + ) metrics = json.loads(metrics_path.read_text()) testcase.assertEqual(set(metrics.keys()), set(_EXPECTED_METRICS_KEYS)) testcase.assertEqual(len(metrics["epoch_train_seconds"]), 1) From db10bfd3e5c5a2798b1b87cc4998745b624e6491 Mon Sep 17 00:00:00 2001 From: Rian Date: Thu, 5 Nov 2026 20:29:24 -0500 Subject: [PATCH 02/11] Keep paired runs from overwriting each other or reporting train as test. 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 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: 5def4ea2 (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 d45e3ccd. Tests: tests/core/test_paired_runs_eval_split.py (new; all 6 fail without this commit). Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95 --- .../unified_embedding_e2e_mimic4.py | 82 +++++- tests/core/test_paired_runs_eval_split.py | 243 ++++++++++++++++++ 2 files changed, 317 insertions(+), 8 deletions(-) create mode 100644 tests/core/test_paired_runs_eval_split.py diff --git a/examples/mortality_prediction/unified_embedding_e2e_mimic4.py b/examples/mortality_prediction/unified_embedding_e2e_mimic4.py index 96c1662f29..9b13d51a20 100644 --- a/examples/mortality_prediction/unified_embedding_e2e_mimic4.py +++ b/examples/mortality_prediction/unified_embedding_e2e_mimic4.py @@ -43,6 +43,7 @@ import csv import json import time +import warnings from pathlib import Path from typing import Any, Dict, List, Optional, Tuple @@ -131,11 +132,54 @@ def _build_task(args: argparse.Namespace): raise ValueError(f"Unknown task: {args.task}") -def _split_dataset(dataset: Any, seed: int) -> Tuple[Any, Any, Any]: +def _split_dataset(dataset: Any, seed: int) -> Tuple[Any, Any, Any, str]: + """Split by patient, falling back to by-sample only if that yields nothing. + + The fallback is leaky: a patient with several admissions can then land in + both train and test, which inflates the metrics. It only triggers on tiny + cohorts, but it must not trigger silently, so the mode is returned and + recorded alongside the run's results. + """ train_ds, val_ds, test_ds = split_by_patient(dataset, [0.8, 0.1, 0.1], seed=seed) if len(train_ds) == 0 or len(test_ds) == 0: + warnings.warn( + "split_by_patient produced an empty split, falling back to " + "split_by_sample. The same patient may now appear in train and " + "test, so these metrics are optimistic and not comparable to " + "patient-split runs.", + RuntimeWarning, + stacklevel=2, + ) train_ds, val_ds, test_ds = split_by_sample(dataset, [0.8, 0.1, 0.1], seed=seed) - return train_ds, val_ds, test_ds + return train_ds, val_ds, test_ds, "by_sample_fallback_leaky" + return train_ds, val_ds, test_ds, "by_patient" + + +def _select_inference_loader(test_loader, val_loader, train_loader): + """Name the split predictions come from, warning when it is not test. + + The old ``test_loader or val_loader or train_loader`` chain could report + training metrics as test with nothing saying so. The split is now named, + warned about, and recorded. + """ + if test_loader is not None: + return test_loader, "test" + if val_loader is not None: + warnings.warn( + "No test split available; reporting predictions from the VALIDATION " + "split. These are not test metrics.", + RuntimeWarning, + stacklevel=2, + ) + return val_loader, "val" + warnings.warn( + "No test or validation split available; reporting predictions from " + "the TRAINING split. These metrics are held-in and meaningless as a " + "generalisation estimate.", + RuntimeWarning, + stacklevel=2, + ) + return train_loader, "train" def _build_unified_embedding( @@ -219,6 +263,7 @@ def _write_predictions( patient_ids: list[str], y_true: np.ndarray, y_prob: np.ndarray, + eval_split: str, ) -> None: output_csv.parent.mkdir(parents=True, exist_ok=True) @@ -228,7 +273,13 @@ def _write_predictions( with output_csv.open("w", newline="", encoding="utf-8") as f: writer = csv.DictWriter( f, - fieldnames=["patient_id", "y_true", "y_prob", "y_pred_threshold_0_5"], + fieldnames=[ + "patient_id", + "y_true", + "y_prob", + "y_pred_threshold_0_5", + "eval_split", + ], ) writer.writeheader() for idx, prob in enumerate(y_prob_flat): @@ -238,6 +289,7 @@ def _write_predictions( "y_true": int(y_true_flat[idx]), "y_prob": float(prob), "y_pred_threshold_0_5": int(float(prob) >= 0.5), + "eval_split": eval_split, } ) @@ -293,7 +345,9 @@ def run(args: argparse.Namespace, sample_dataset: Any = None) -> Path: "Task produced zero samples. Check roots/tables or adjust settings." ) - train_ds, val_ds, test_ds = _split_dataset(sample_dataset, seed=args.seed) + train_ds, val_ds, test_ds, split_mode = _split_dataset( + sample_dataset, seed=args.seed + ) unified = _build_unified_embedding(args, sample_dataset) model = _build_model(args, sample_dataset, unified) @@ -324,7 +378,18 @@ def run(args: argparse.Namespace, sample_dataset: Any = None) -> Path: else None ) - exp_name = f"{args.model}_seed{args.seed}" + # Name the split predictions come from up front: it is recorded in + # run_config.json alongside split_mode and the split sizes. + inference_loader, eval_split = _select_inference_loader( + test_loader, val_loader, timed_train_loader + ) + + # The task MUST be in the name. Without it, two arms of the same comparison + # at the same seed, for example --task labs and --task notes_labs, resolve + # to one directory and the second run overwrites the first. Same for a + # --dev smoke check: without the suffix it would overwrite the full run. + dev_suffix = f"_dev{args.dev}" if args.dev else "" + exp_name = f"{args.task}_{args.model}_seed{args.seed}{dev_suffix}" output_dir = Path(args.output_dir) wandb_logger = WandbLogger( @@ -371,6 +436,8 @@ def run(args: argparse.Namespace, sample_dataset: Any = None) -> Path: str(output_dir / exp_name), { **vars(args), + "split_mode": split_mode, + "eval_split": eval_split, "n_train": len(train_ds), "n_val": len(val_ds), "n_test": len(test_ds), @@ -403,7 +470,6 @@ def run(args: argparse.Namespace, sample_dataset: Any = None) -> Path: eval_seconds = time.perf_counter() - eval_start wandb_logger.log({f"test_{k}": v for k, v in test_scores.items()}) - inference_loader = test_loader or val_loader or timed_train_loader inference_start = time.perf_counter() y_true, y_prob, _, patient_ids = trainer.inference( inference_loader, return_patient_ids=True @@ -411,7 +477,7 @@ def run(args: argparse.Namespace, sample_dataset: Any = None) -> Path: inference_seconds = time.perf_counter() - inference_start output_csv = output_dir / exp_name / f"predictions_{args.model}.csv" - _write_predictions(output_csv, patient_ids, y_true, y_prob) + _write_predictions(output_csv, patient_ids, y_true, y_prob, eval_split) metrics = { "config": vars(args), @@ -625,7 +691,7 @@ def parse_args(argv: Optional[list] = None) -> argparse.Namespace: "--wandb-run-name", type=str, default=None, - help="Defaults to '{model}_seed{seed}' if unset.", + help="Defaults to '{task}_{model}_seed{seed}' if unset.", ) parser.add_argument( "--wandb-tags", diff --git a/tests/core/test_paired_runs_eval_split.py b/tests/core/test_paired_runs_eval_split.py new file mode 100644 index 0000000000..c8b905fd64 --- /dev/null +++ b/tests/core/test_paired_runs_eval_split.py @@ -0,0 +1,243 @@ +"""Paired runs keep their own directories; test is never reported as train. + +Two arms of one comparison (``--task labs`` vs ``--task notes_labs`` at one +seed) used to resolve to one directory, so the second run destroyed the +first. And predictions came from ``test or val or train`` with nothing +saying which, so a run without a test split reported training metrics as +test. The split mode and the eval split are now named, warned about, and +recorded in ``run_config.json``. +""" + +from __future__ import annotations + +import json +import unittest +import warnings +from argparse import Namespace +from pathlib import Path +from tempfile import TemporaryDirectory + + +def _runner(): + import importlib.util + + path = ( + Path(__file__).resolve().parents[2] + / "examples" + / "mortality_prediction" + / "unified_embedding_e2e_mimic4.py" + ) + spec = importlib.util.spec_from_file_location("unified_e2e_runner_paired", path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def _single_patient_samples(): + return [ + { + "patient_id": "only", + "visit_id": "v0", + "labs": ( + [0.0, 2.0], + [[140.0, 1.0], [141.0, 1.1]], + ), + "label": 0, + }, + { + "patient_id": "only", + "visit_id": "v1", + "labs": ( + [0.0, 2.0], + [[142.0, 1.0], [143.0, 1.1]], + ), + "label": 1, + }, + ] + + +def _twenty_patient_samples(): + samples = [] + for i in range(20): + samples.append( + { + "patient_id": f"patient-{i}", + "visit_id": "visit-0", + "labs": ( + [0.0, 2.0], + [[140.0 + i, 1.0], [141.0 + i, 1.1]], + ), + "label": i % 2, + } + ) + return samples + + +class TestPairedRunsAndEvalSplit(unittest.TestCase): + def test_split_warns_and_labels_leaky_fallback(self): + from pyhealth.datasets import create_sample_dataset + + runner = _runner() + dataset = create_sample_dataset( + samples=_single_patient_samples(), + input_schema={"labs": "stagenet_tensor"}, + output_schema={"label": "binary"}, + in_memory=True, + ) + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + train, _val, _test, mode = runner._split_dataset(dataset, seed=1) + self.assertEqual(mode, "by_sample_fallback_leaky") + self.assertTrue( + any("split_by_sample" in str(w.message) for w in caught) + ) + self.assertGreater(len(train), 0) + + def test_patient_split_mode_is_clean(self): + from pyhealth.datasets import create_sample_dataset + + runner = _runner() + dataset = create_sample_dataset( + samples=_twenty_patient_samples(), + input_schema={"labs": "stagenet_tensor"}, + output_schema={"label": "binary"}, + in_memory=True, + ) + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + _train, _val, _test, mode = runner._split_dataset(dataset, seed=42) + self.assertEqual(mode, "by_patient") + self.assertEqual( + [w for w in caught if "split_by_sample" in str(w.message)], [] + ) + + def test_select_inference_loader_names_each_split(self): + runner = _runner() + test_loader, val_loader, train_loader = object(), object(), object() + + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + loader, split = runner._select_inference_loader( + test_loader, val_loader, train_loader + ) + self.assertIs(loader, test_loader) + self.assertEqual(split, "test") + self.assertEqual(caught, []) + + with self.assertWarns(RuntimeWarning): + loader, split = runner._select_inference_loader( + None, val_loader, train_loader + ) + self.assertIs(loader, val_loader) + self.assertEqual(split, "val") + + with self.assertWarns(RuntimeWarning): + loader, split = runner._select_inference_loader( + None, None, train_loader + ) + self.assertIs(loader, train_loader) + self.assertEqual(split, "train") + + def test_run_directory_includes_task_and_records_eval_split(self): + import csv + + from pyhealth.datasets import create_sample_dataset + + runner = _runner() + dataset = create_sample_dataset( + samples=_twenty_patient_samples(), + input_schema={"labs": "stagenet_tensor"}, + output_schema={"label": "binary"}, + dataset_name="test_paired_runs", + ) + with TemporaryDirectory() as tmp: + args = Namespace( + **{ + **vars( + runner.parse_args( + [ + "--ehr-root", + "/tmp/does-not-exist", + "--task", + "labs", + "--model", + "mlp", + "--epochs", + "1", + "--batch-size", + "4", + "--device", + "cpu", + "--seed", + "42", + "--no-cache-frozen-text", + "--output-dir", + tmp, + ] + ) + ), + "embedding_dim": 8, + "hidden_dim": 8, + } + ) + output_csv = runner.run(args, sample_dataset=dataset) + self.assertIn("labs_mlp_seed42", str(output_csv)) + self.assertNotIn("_dev", str(output_csv)) + run_config = json.loads( + (Path(output_csv).parent / "run_config.json").read_text() + ) + self.assertEqual(run_config["config"]["task"], "labs") + self.assertEqual(run_config["config"]["split_mode"], "by_patient") + self.assertEqual(run_config["config"]["eval_split"], "test") + with open(output_csv, newline="") as handle: + rows = list(csv.DictReader(handle)) + self.assertTrue(rows) + self.assertIn("eval_split", rows[0]) + self.assertEqual( + {row["eval_split"] for row in rows}, {"test"} + ) + + def test_run_directory_gains_dev_suffix(self): + from pyhealth.datasets import create_sample_dataset + + runner = _runner() + dataset = create_sample_dataset( + samples=_twenty_patient_samples(), + input_schema={"labs": "stagenet_tensor"}, + output_schema={"label": "binary"}, + dataset_name="test_dev_suffix", + ) + with TemporaryDirectory() as tmp: + args = Namespace( + **{ + **vars( + runner.parse_args( + [ + "--ehr-root", + "/tmp/does-not-exist", + "--task", + "labs", + "--model", + "mlp", + "--epochs", + "0", + "--batch-size", + "4", + "--device", + "cpu", + "--seed", + "42", + "--dev", + "1000", + "--no-cache-frozen-text", + "--output-dir", + tmp, + ] + ) + ), + "embedding_dim": 8, + "hidden_dim": 8, + } + ) + output_csv = runner.run(args, sample_dataset=dataset) + self.assertIn("labs_mlp_seed42_dev1000", str(output_csv)) From 91e741f75c805cc7d3d509c8ec373461bbbfa48b Mon Sep 17 00:00:00 2001 From: Rian Date: Thu, 5 Nov 2026 15:38:37 -0500 Subject: [PATCH 03/11] Persist test metrics to disk on every run with a test split. 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 f4b37072 (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 --- .../unified_embedding_e2e_mimic4.py | 8 ++ pyhealth/utils.py | 14 ++- tests/core/test_persist_test_metrics.py | 113 ++++++++++++++++++ tests/core/test_unified_e2e_runner.py | 7 ++ 4 files changed, 140 insertions(+), 2 deletions(-) create mode 100644 tests/core/test_persist_test_metrics.py diff --git a/examples/mortality_prediction/unified_embedding_e2e_mimic4.py b/examples/mortality_prediction/unified_embedding_e2e_mimic4.py index 9b13d51a20..ee2b71e992 100644 --- a/examples/mortality_prediction/unified_embedding_e2e_mimic4.py +++ b/examples/mortality_prediction/unified_embedding_e2e_mimic4.py @@ -476,6 +476,14 @@ def run(args: argparse.Namespace, sample_dataset: Any = None) -> Path: ) inference_seconds = time.perf_counter() - inference_start + # metrics.json carries validation only, so without this the test numbers + # worth reporting live nowhere on disk: only in stdout and W&B, and + # recoverable afterwards only by re-scoring predictions by hand. + if test_scores: + test_path = output_dir / exp_name / "test_metrics.json" + with open(test_path, "w") as handle: + json.dump({"eval_split": eval_split, **test_scores}, handle, indent=2) + output_csv = output_dir / exp_name / f"predictions_{args.model}.csv" _write_predictions(output_csv, patient_ids, y_true, y_prob, eval_split) diff --git a/pyhealth/utils.py b/pyhealth/utils.py index 400a4fbc8f..8c361f4392 100644 --- a/pyhealth/utils.py +++ b/pyhealth/utils.py @@ -159,8 +159,18 @@ def wrapper(self, *args, **kwargs): def create_directory(directory): - if not os.path.exists(directory): - os.makedirs(directory) + """Create ``directory``, including parents, if it does not exist. + + Calling it on an existing directory is a no-op, so concurrent first + imports cannot lose an exists()-then-makedirs race with FileExistsError. + + Examples: + >>> import tempfile, os + >>> d = tempfile.mkdtemp() + >>> create_directory(os.path.join(d, "a", "b")) is None + True + """ + os.makedirs(directory, exist_ok=True) def load_pickle(filename): diff --git a/tests/core/test_persist_test_metrics.py b/tests/core/test_persist_test_metrics.py new file mode 100644 index 0000000000..176c5ec6fa --- /dev/null +++ b/tests/core/test_persist_test_metrics.py @@ -0,0 +1,113 @@ +"""Test metrics persist to disk whether or not W&B logging is on. + +``metrics.json`` carries validation only, so the test numbers worth reporting +used to live nowhere on disk: only in stdout and W&B, recoverable +afterwards only by re-scoring predictions by hand. +""" + +from __future__ import annotations + +import json +import unittest +from argparse import Namespace +from pathlib import Path +from tempfile import TemporaryDirectory + + +def _runner(): + import importlib.util + + path = ( + Path(__file__).resolve().parents[2] + / "examples" + / "mortality_prediction" + / "unified_embedding_e2e_mimic4.py" + ) + spec = importlib.util.spec_from_file_location( + "unified_e2e_runner_metrics", path + ) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def _twenty_patient_samples(): + samples = [] + for i in range(20): + samples.append( + { + "patient_id": f"patient-{i}", + "visit_id": "visit-0", + "labs": ( + [0.0, 2.0], + [[140.0 + i, 1.0], [141.0 + i, 1.1]], + ), + "label": i % 2, + } + ) + return samples + + +class TestPersistTestMetrics(unittest.TestCase): + def test_test_metrics_json_written_next_to_predictions(self): + from pyhealth.datasets import create_sample_dataset + + runner = _runner() + dataset = create_sample_dataset( + samples=_twenty_patient_samples(), + input_schema={"labs": "stagenet_tensor"}, + output_schema={"label": "binary"}, + dataset_name="test_persist_test_metrics", + ) + with TemporaryDirectory() as tmp: + args = Namespace( + **{ + **vars( + runner.parse_args( + [ + "--ehr-root", + "/tmp/does-not-exist", + "--task", + "labs", + "--model", + "mlp", + "--epochs", + "1", + "--batch-size", + "4", + "--device", + "cpu", + "--seed", + "42", + "--no-cache-frozen-text", + "--output-dir", + tmp, + ] + ) + ), + "embedding_dim": 8, + "hidden_dim": 8, + } + ) + output_csv = runner.run(args, sample_dataset=dataset) + test_path = Path(output_csv).parent / "test_metrics.json" + self.assertTrue(test_path.is_file()) + test_metrics = json.loads(test_path.read_text()) + self.assertEqual(test_metrics["eval_split"], "test") + scores = { + k: v for k, v in test_metrics.items() if k != "eval_split" + } + self.assertGreater(len(scores), 0) + metrics = json.loads( + (Path(output_csv).parent / "metrics.json").read_text() + ) + self.assertEqual(scores.keys(), metrics["test_scores"].keys()) + + def test_create_directory_survives_existing_dirs(self): + from pyhealth.utils import create_directory + + with TemporaryDirectory() as tmp: + create_directory(tmp) + create_directory(tmp) + create_directory(str(Path(tmp) / "new" / "nested")) + self.assertTrue((Path(tmp) / "new" / "nested").is_dir()) diff --git a/tests/core/test_unified_e2e_runner.py b/tests/core/test_unified_e2e_runner.py index 802d0aef3e..92a6f01f07 100644 --- a/tests/core/test_unified_e2e_runner.py +++ b/tests/core/test_unified_e2e_runner.py @@ -197,6 +197,13 @@ def _assert_demo_metrics(testcase, output_csv): testcase.assertEqual( set(run_config), {"config", "git", "source_sha256", "torch"} ) + test_metrics_path = Path(output_csv).parent / "test_metrics.json" + testcase.assertTrue(test_metrics_path.is_file()) + test_metrics = json.loads(test_metrics_path.read_text()) + testcase.assertEqual( + test_metrics["eval_split"], + run_config["config"]["eval_split"], + ) metrics = json.loads(metrics_path.read_text()) testcase.assertEqual(set(metrics.keys()), set(_EXPECTED_METRICS_KEYS)) testcase.assertEqual(len(metrics["epoch_train_seconds"]), 1) From e37808573e99f44011bbfedeeb4506ef0209cd1c Mon Sep 17 00:00:00 2001 From: Rian Date: Thu, 5 Nov 2026 15:42:11 -0500 Subject: [PATCH 04/11] Log per-epoch CPU seconds alongside wall time. 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 f4b37072 (_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 --- .../unified_embedding_e2e_mimic4.py | 34 ++++- pyhealth/trainer.py | 32 +++++ tests/core/test_trainer_cpu.py | 123 ++++++++++++++++++ tests/core/test_unified_e2e_runner.py | 13 ++ 4 files changed, 200 insertions(+), 2 deletions(-) create mode 100644 tests/core/test_trainer_cpu.py diff --git a/examples/mortality_prediction/unified_embedding_e2e_mimic4.py b/examples/mortality_prediction/unified_embedding_e2e_mimic4.py index ee2b71e992..044b55dd89 100644 --- a/examples/mortality_prediction/unified_embedding_e2e_mimic4.py +++ b/examples/mortality_prediction/unified_embedding_e2e_mimic4.py @@ -65,7 +65,7 @@ from pyhealth.models.ehrmamba import EHRMamba from pyhealth.models.jamba_ehr import JambaEHR from pyhealth.tasks.multimodal_mimic4 import LabsMIMIC4, NotesLabsMIMIC4 -from pyhealth.trainer import Trainer +from pyhealth.trainer import Trainer, _cpu_seconds from pyhealth.utils import set_seed, write_run_config @@ -295,7 +295,7 @@ def _write_predictions( class _EpochTimedLoader: - """Wrap a training loader to record per-epoch wall time. + """Wrap a training loader to record per-epoch wall and CPU time. ``Trainer.train`` returns ``None`` and its epoch loop lives inside the Trainer, so the runner cannot time epochs without changing the Trainer. @@ -308,6 +308,7 @@ class _EpochTimedLoader: def __init__(self, loader: Any) -> None: self._loader = loader self.epoch_boundaries: List[float] = [] + self.cpu_boundaries: List[Any] = [] def __getattr__(self, name: str) -> Any: return getattr(self._loader, name) @@ -317,6 +318,7 @@ def __len__(self) -> int: def __iter__(self): self.epoch_boundaries.append(time.perf_counter()) + self.cpu_boundaries.append(_cpu_seconds()) return iter(self._loader) def epoch_seconds(self) -> List[float]: @@ -324,6 +326,16 @@ def epoch_seconds(self) -> List[float]: ends = self.epoch_boundaries[1:] + [time.perf_counter()] return [end - start for start, end in zip(self.epoch_boundaries, ends)] + def epoch_cpu_seconds(self) -> List[Any]: + """Per-epoch CPU seconds; ``None`` where the clock is unavailable.""" + ends = self.cpu_boundaries[1:] + [_cpu_seconds()] + return [ + None + if start is None or end is None + else max(end - start, 0.0) + for start, end in zip(self.cpu_boundaries, ends) + ] + def run(args: argparse.Namespace, sample_dataset: Any = None) -> Path: """Run the end-to-end protocol and write predictions + metrics. @@ -445,6 +457,7 @@ def run(args: argparse.Namespace, sample_dataset: Any = None) -> Path: ) epoch_train_seconds: List[float] = [] + epoch_train_cpu_seconds: List[Any] = [] if args.epochs > 0 and len(train_ds) > 0: trainer.train( train_dataloader=timed_train_loader, @@ -461,6 +474,18 @@ def run(args: argparse.Namespace, sample_dataset: Any = None) -> Path: amp_dtype=args.amp_dtype, ) epoch_train_seconds = timed_train_loader.epoch_seconds() + epoch_train_cpu_seconds = timed_train_loader.epoch_cpu_seconds() + + train_cpu_seconds = ( + round(sum(v for v in epoch_train_cpu_seconds if v is not None), 2) + if any(v is not None for v in epoch_train_cpu_seconds) + else None + ) + train_cpu_util_pct = ( + round(100.0 * train_cpu_seconds / max(sum(epoch_train_seconds), 1e-9), 1) + if train_cpu_seconds is not None and epoch_train_seconds + else None + ) eval_seconds = 0.0 test_scores: Dict[str, float] = {} @@ -495,6 +520,9 @@ def run(args: argparse.Namespace, sample_dataset: Any = None) -> Path: "test": len(test_ds) if test_ds is not None else 0, }, "epoch_train_seconds": epoch_train_seconds, + "epoch_train_cpu_seconds": epoch_train_cpu_seconds, + "train_cpu_seconds": train_cpu_seconds, + "train_cpu_util_pct": train_cpu_util_pct, "eval_seconds": eval_seconds, "inference_seconds": inference_seconds, "frozen_text_cache": unified.frozen_text_cache_stats, @@ -509,6 +537,8 @@ def run(args: argparse.Namespace, sample_dataset: Any = None) -> Path: print( "epoch_train_seconds=" f"{[round(t, 3) for t in epoch_train_seconds]} " + f"train_cpu_seconds={train_cpu_seconds} " + f"train_cpu_util_pct={train_cpu_util_pct} " f"eval_seconds={eval_seconds:.3f} " f"inference_seconds={inference_seconds:.3f} " f"frozen_text_cache={metrics['frozen_text_cache']}" diff --git a/pyhealth/trainer.py b/pyhealth/trainer.py index 5271e8b3e0..337860844c 100644 --- a/pyhealth/trainer.py +++ b/pyhealth/trainer.py @@ -103,6 +103,38 @@ def _cpu_state_dict(model: nn.Module) -> dict: } +def _cpu_seconds() -> float | None: + """Cumulative CPU seconds for this process and its dataloader workers. + + Self-only time badly understates a run whose cost is data loading, since + workers are separate processes. psutil is already available via wandb; the + resource fallback only counts children that have been reaped, so it reads + low while persistent workers are still alive. + """ + try: + import psutil + + proc = psutil.Process() + times = proc.cpu_times() + total = times.user + times.system + for child in proc.children(recursive=True): + try: + ctimes = child.cpu_times() + total += ctimes.user + ctimes.system + except (psutil.NoSuchProcess, psutil.AccessDenied): + continue + return total + except Exception: # noqa: BLE001 - fall back to resource usage + try: + import resource + + me = resource.getrusage(resource.RUSAGE_SELF) + kids = resource.getrusage(resource.RUSAGE_CHILDREN) + return me.ru_utime + me.ru_stime + kids.ru_utime + kids.ru_stime + except Exception: # noqa: BLE001 - no clock anywhere; caller gets None + return None + + def is_best(best_score: float, score: float, monitor_criterion: str) -> bool: if monitor_criterion == "max": return score > best_score diff --git a/tests/core/test_trainer_cpu.py b/tests/core/test_trainer_cpu.py new file mode 100644 index 0000000000..eaedac0212 --- /dev/null +++ b/tests/core/test_trainer_cpu.py @@ -0,0 +1,123 @@ +"""Per-epoch CPU accounting next to the existing wall-time accounting. + +Self-only CPU time badly understates a run whose cost is data loading, +since workers are separate processes, so the clock counts the process tree. +The series records wall time per epoch in the runner (the Trainer returns +``None``), so CPU rides the same epoch boundaries. +""" + +from __future__ import annotations + +import json +import unittest +from argparse import Namespace +from pathlib import Path +from tempfile import TemporaryDirectory + +import torch + + +def _runner(): + import importlib.util + + path = ( + Path(__file__).resolve().parents[2] + / "examples" + / "mortality_prediction" + / "unified_embedding_e2e_mimic4.py" + ) + spec = importlib.util.spec_from_file_location( + "unified_e2e_runner_cpu", path + ) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def _twenty_patient_samples(): + samples = [] + for i in range(20): + samples.append( + { + "patient_id": f"patient-{i}", + "visit_id": "visit-0", + "labs": ( + [0.0, 2.0], + [[140.0 + i, 1.0], [141.0 + i, 1.1]], + ), + "label": i % 2, + } + ) + return samples + + +class TestTrainerCpuAccounting(unittest.TestCase): + def test_cpu_seconds_is_monotonic(self): + from pyhealth.trainer import _cpu_seconds + + first = _cpu_seconds() + total = 0 + for i in range(1000): + total += i * i + second = _cpu_seconds() + self.assertIsNotNone(first) + self.assertIsNotNone(second) + self.assertGreaterEqual(first, 0.0) + self.assertGreaterEqual(second, first) + self.assertGreater(total, 0) + + def test_run_records_per_epoch_cpu(self): + from pyhealth.datasets import create_sample_dataset + + runner = _runner() + dataset = create_sample_dataset( + samples=_twenty_patient_samples(), + input_schema={"labs": "stagenet_tensor"}, + output_schema={"label": "binary"}, + dataset_name="test_cpu", + ) + with TemporaryDirectory() as tmp: + args = Namespace( + **{ + **vars( + runner.parse_args( + [ + "--ehr-root", + "/tmp/does-not-exist", + "--task", + "labs", + "--model", + "mlp", + "--epochs", + "1", + "--batch-size", + "4", + "--device", + "cpu", + "--seed", + "42", + "--no-cache-frozen-text", + "--output-dir", + tmp, + ] + ) + ), + "embedding_dim": 8, + "hidden_dim": 8, + } + ) + output_csv = runner.run(args, sample_dataset=dataset) + metrics = json.loads( + (Path(output_csv).parent / "metrics.json").read_text() + ) + self.assertEqual( + len(metrics["epoch_train_cpu_seconds"]), + len(metrics["epoch_train_seconds"]), + ) + for value in metrics["epoch_train_cpu_seconds"]: + self.assertTrue(torch.isfinite(torch.tensor(value)).item()) + self.assertGreaterEqual(value, 0.0) + self.assertTrue( + torch.isfinite(torch.tensor(metrics["train_cpu_seconds"])) + ) + self.assertGreaterEqual(metrics["train_cpu_util_pct"], 0.0) diff --git a/tests/core/test_unified_e2e_runner.py b/tests/core/test_unified_e2e_runner.py index 92a6f01f07..2f09785662 100644 --- a/tests/core/test_unified_e2e_runner.py +++ b/tests/core/test_unified_e2e_runner.py @@ -140,6 +140,9 @@ def test_synthetic_end_to_end(self): "config", "split", "epoch_train_seconds", + "epoch_train_cpu_seconds", + "train_cpu_seconds", + "train_cpu_util_pct", "eval_seconds", "inference_seconds", "frozen_text_cache", @@ -209,6 +212,16 @@ def _assert_demo_metrics(testcase, output_csv): testcase.assertEqual(len(metrics["epoch_train_seconds"]), 1) for v in metrics["epoch_train_seconds"]: testcase.assertTrue(torch.isfinite(torch.tensor(float(v))).item()) + testcase.assertEqual( + len(metrics["epoch_train_cpu_seconds"]), + len(metrics["epoch_train_seconds"]), + ) + for v in metrics["epoch_train_cpu_seconds"]: + testcase.assertTrue(torch.isfinite(torch.tensor(float(v))).item()) + for key in ("train_cpu_seconds", "train_cpu_util_pct"): + testcase.assertTrue( + torch.isfinite(torch.tensor(float(metrics[key]))).item() + ) testcase.assertTrue( torch.isfinite(torch.tensor(float(metrics["eval_seconds"]))).item() ) From b6e631c60b6f5b284a03b87aa26b4e71b33f97da Mon Sep 17 00:00:00 2001 From: Rian Date: Thu, 5 Nov 2026 15:44:10 -0500 Subject: [PATCH 05/11] Make run identity window-aware. 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 f4b37072 (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 --- .../unified_embedding_e2e_mimic4.py | 29 ++++- tests/core/test_run_identity_window.py | 120 ++++++++++++++++++ 2 files changed, 147 insertions(+), 2 deletions(-) create mode 100644 tests/core/test_run_identity_window.py diff --git a/examples/mortality_prediction/unified_embedding_e2e_mimic4.py b/examples/mortality_prediction/unified_embedding_e2e_mimic4.py index 044b55dd89..610203c7d3 100644 --- a/examples/mortality_prediction/unified_embedding_e2e_mimic4.py +++ b/examples/mortality_prediction/unified_embedding_e2e_mimic4.py @@ -78,8 +78,12 @@ def __init__( run_name: str, tags: list[str], config: Dict[str, Any], + group: Optional[str] = None, + job_type: Optional[str] = None, ) -> None: self.enabled = enabled + self.group = group + self.job_type = job_type self._run = None if self.enabled: import wandb @@ -90,6 +94,8 @@ def __init__( name=run_name, tags=tags, config=config, + group=group, + job_type=job_type, ) def log(self, data: Dict[str, Any], step: Optional[int] = None) -> None: @@ -155,6 +161,16 @@ def _split_dataset(dataset: Any, seed: int) -> Tuple[Any, Any, Any, str]: return train_ds, val_ds, test_ds, "by_patient" +def _window_suffix(observation_window_hours: float) -> str: + """Directory/name suffix for the observation-window arm. + + An observation-window arm is a different experiment from the full-stay + run at the same task/model/seed; without the suffix the two share an + output directory and a W&B run name. + """ + return f"_w{observation_window_hours:g}" if observation_window_hours else "" + + def _select_inference_loader(test_loader, val_loader, train_loader): """Name the split predictions come from, warning when it is not test. @@ -399,9 +415,14 @@ def run(args: argparse.Namespace, sample_dataset: Any = None) -> Path: # The task MUST be in the name. Without it, two arms of the same comparison # at the same seed, for example --task labs and --task notes_labs, resolve # to one directory and the second run overwrites the first. Same for a - # --dev smoke check: without the suffix it would overwrite the full run. + # --dev smoke check and an observation-window arm: without their + # suffixes they would collide with the full run. dev_suffix = f"_dev{args.dev}" if args.dev else "" - exp_name = f"{args.task}_{args.model}_seed{args.seed}{dev_suffix}" + window_suffix = _window_suffix(args.observation_window_hours) + exp_name = ( + f"{args.task}_{args.model}_seed{args.seed}" + f"{dev_suffix}{window_suffix}" + ) output_dir = Path(args.output_dir) wandb_logger = WandbLogger( @@ -411,6 +432,10 @@ def run(args: argparse.Namespace, sample_dataset: Any = None) -> Path: run_name=args.wandb_run_name or exp_name, tags=args.wandb_tags.split(",") if args.wandb_tags else [args.task, args.model], config=vars(args), + # Group by arm and split by backbone so a many-cell sweep is + # navigable instead of one flat list of runs. + group=f"{args.task}{window_suffix}", + job_type=args.model, ) trainer = Trainer( diff --git a/tests/core/test_run_identity_window.py b/tests/core/test_run_identity_window.py new file mode 100644 index 0000000000..125f5d0901 --- /dev/null +++ b/tests/core/test_run_identity_window.py @@ -0,0 +1,120 @@ +"""Run identity covers the observation window. + +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. +""" + +from __future__ import annotations + +import unittest +from argparse import Namespace +from pathlib import Path +from tempfile import TemporaryDirectory + + +def _runner(): + import importlib.util + + path = ( + Path(__file__).resolve().parents[2] + / "examples" + / "mortality_prediction" + / "unified_embedding_e2e_mimic4.py" + ) + spec = importlib.util.spec_from_file_location( + "unified_e2e_runner_window", path + ) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def _twenty_patient_samples(): + samples = [] + for i in range(20): + samples.append( + { + "patient_id": f"patient-{i}", + "visit_id": "visit-0", + "labs": ( + [0.0, 2.0], + [[140.0 + i, 1.0], [141.0 + i, 1.1]], + ), + "label": i % 2, + } + ) + return samples + + +class TestWindowAwareRunIdentity(unittest.TestCase): + def test_window_suffix(self): + runner = _runner() + self.assertEqual(runner._window_suffix(0), "") + self.assertEqual(runner._window_suffix(0.0), "") + self.assertEqual(runner._window_suffix(24), "_w24") + self.assertEqual(runner._window_suffix(24.0), "_w24") + self.assertEqual(runner._window_suffix(24.5), "_w24.5") + self.assertEqual(runner._window_suffix(0.5), "_w0.5") + + def test_wandb_logger_carries_group_and_job_type(self): + runner = _runner() + logger = runner.WandbLogger( + enabled=False, + project="p", + entity=None, + run_name="r", + tags=["labs"], + config={}, + group="labs_w24", + job_type="mlp", + ) + self.assertEqual(logger.group, "labs_w24") + self.assertEqual(logger.job_type, "mlp") + + def test_window_arm_lands_in_its_own_directory(self): + from pyhealth.datasets import create_sample_dataset + + runner = _runner() + dataset = create_sample_dataset( + samples=_twenty_patient_samples(), + input_schema={"labs": "stagenet_tensor"}, + output_schema={"label": "binary"}, + dataset_name="test_window", + ) + with TemporaryDirectory() as tmp: + args = Namespace( + **{ + **vars( + runner.parse_args( + [ + "--ehr-root", + "/tmp/does-not-exist", + "--task", + "labs", + "--model", + "mlp", + "--epochs", + "0", + "--batch-size", + "4", + "--device", + "cpu", + "--seed", + "42", + "--observation-window-hours", + "24", + "--no-cache-frozen-text", + "--output-dir", + tmp, + ] + ) + ), + "embedding_dim": 8, + "hidden_dim": 8, + } + ) + output_csv = runner.run(args, sample_dataset=dataset) + self.assertIn("labs_mlp_seed42_w24", str(output_csv)) + full_stay = str(output_csv).replace("_w24", "") + self.assertNotEqual(str(output_csv), full_stay) From 7dd49ecd6f5beaee66971b915a016eefd152ff75 Mon Sep 17 00:00:00 2001 From: Rian354 Date: Thu, 5 Nov 2026 20:31:30 -0500 Subject: [PATCH 06/11] Report PSS alongside summed RSS in benchmark_perf. 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 None, 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. Based on fork PR #55 (07355aed), not a verbatim copy. The PR falls back to RSS when PSS is unavailable, resets the PSS peak outside the lock, and undercounts denied processes. This commit does none of those. Sources: fork #55 07355aed (adapted; see above). 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 --- .../benchmark_perf/benchmark_workers_n.py | 38 ++++ ...benchmark_workers_n_drug_recommendation.py | 38 ++++ .../benchmark_workers_n_length_of_stay.py | 38 ++++ .../legacy_ver/benchmark_legacy_drug_rec.py | 38 ++++ .../legacy_ver/benchmark_legacy_los.py | 38 ++++ .../legacy_ver/benchmark_legacy_mortality.py | 38 ++++ .../benchmark_meds_reader_drug_rec.py | 38 ++++ ...hmark_meds_reader_drug_rec_pyhealth_etl.py | 39 ++++ .../benchmark_meds_reader_los.py | 38 ++++ .../benchmark_meds_reader_los_pyhealth_etl.py | 39 ++++ .../benchmark_meds_reader_mortality.py | 38 ++++ ...mark_meds_reader_mortality_pyhealth_etl.py | 39 ++++ .../benchmark_patient_access_legacy.py | 39 ++++ .../benchmark_patient_access_meds_reader.py | 39 ++++ .../benchmark_patient_access_pandas.py | 39 ++++ .../benchmark_patient_access_pyhealth2.py | 39 ++++ tests/core/test_benchmark_pss.py | 170 ++++++++++++++++++ 17 files changed, 785 insertions(+) create mode 100644 tests/core/test_benchmark_pss.py diff --git a/examples/benchmark_perf/benchmark_workers_n.py b/examples/benchmark_perf/benchmark_workers_n.py index d6e4409b30..8fd6560ad6 100644 --- a/examples/benchmark_perf/benchmark_workers_n.py +++ b/examples/benchmark_perf/benchmark_workers_n.py @@ -55,6 +55,7 @@ class RunResult: base_cache_bytes: int task_cache_bytes: int peak_rss_bytes: int + peak_pss_bytes: int | None # None where PSS is unavailable open_fds: int # after the run; should stay flat across runs (-1 if unsupported) @@ -110,6 +111,7 @@ def __init__(self, poll_interval_s: float = 0.1) -> None: self._stop = threading.Event() self._lock = threading.Lock() self._peak = 0 + self._peak_pss = None # no valid PSS sample yet self._thread = threading.Thread(target=self._run, daemon=True) def start(self) -> None: @@ -118,14 +120,44 @@ def start(self) -> None: def reset(self) -> None: with self._lock: self._peak = 0 + self._peak_pss = None def stop(self) -> None: self._stop.set() + def peak_pss_bytes(self) -> int | None: + with self._lock: + return self._peak_pss + def peak_bytes(self) -> int: with self._lock: return self._peak + def _total_pss_bytes(self) -> int | None: + """Proportional set size across the process tree. + + Summing RSS over forked workers counts every shared page once per + process; PSS divides it among the mappers, so the total is additive. + Returns None where PSS is unavailable for any process in the tree + (non-Linux, or no perms): that sample is not a PSS total, so the + peak column is left empty for the run rather than holding RSS. + """ + total = 0 + try: + procs = [self._proc] + self._proc.children(recursive=True) + except (psutil.NoSuchProcess, psutil.AccessDenied): + return None + for p in procs: + try: + total += p.memory_full_info().pss + except AttributeError: + return None + except psutil.NoSuchProcess: + pass + except psutil.AccessDenied: + return None + return total + def _total_rss_bytes(self) -> int: total = 0 try: @@ -142,9 +174,14 @@ def _total_rss_bytes(self) -> int: def _run(self) -> None: while not self._stop.is_set(): rss = self._total_rss_bytes() + pss = self._total_pss_bytes() with self._lock: if rss > self._peak: self._peak = rss + if pss is not None and ( + self._peak_pss is None or pss > self._peak_pss + ): + self._peak_pss = pss time.sleep(self._poll_interval_s) @@ -335,6 +372,7 @@ def main() -> None: base_cache_bytes=base_cache_bytes, task_cache_bytes=task_cache_bytes, peak_rss_bytes=peak_rss_bytes, + peak_pss_bytes=tracker.peak_pss_bytes(), open_fds=open_fds, ) ) diff --git a/examples/benchmark_perf/benchmark_workers_n_drug_recommendation.py b/examples/benchmark_perf/benchmark_workers_n_drug_recommendation.py index 2d12f746e5..27d2496306 100644 --- a/examples/benchmark_perf/benchmark_workers_n_drug_recommendation.py +++ b/examples/benchmark_perf/benchmark_workers_n_drug_recommendation.py @@ -54,6 +54,7 @@ class RunResult: base_cache_bytes: int task_cache_bytes: int peak_rss_bytes: int + peak_pss_bytes: int | None # None where PSS is unavailable def format_size(size_bytes: int) -> str: @@ -108,6 +109,7 @@ def __init__(self, poll_interval_s: float = 0.1) -> None: self._stop = threading.Event() self._lock = threading.Lock() self._peak = 0 + self._peak_pss = None # no valid PSS sample yet self._thread = threading.Thread(target=self._run, daemon=True) def start(self) -> None: @@ -116,14 +118,44 @@ def start(self) -> None: def reset(self) -> None: with self._lock: self._peak = 0 + self._peak_pss = None def stop(self) -> None: self._stop.set() + def peak_pss_bytes(self) -> int | None: + with self._lock: + return self._peak_pss + def peak_bytes(self) -> int: with self._lock: return self._peak + def _total_pss_bytes(self) -> int | None: + """Proportional set size across the process tree. + + Summing RSS over forked workers counts every shared page once per + process; PSS divides it among the mappers, so the total is additive. + Returns None where PSS is unavailable for any process in the tree + (non-Linux, or no perms): that sample is not a PSS total, so the + peak column is left empty for the run rather than holding RSS. + """ + total = 0 + try: + procs = [self._proc] + self._proc.children(recursive=True) + except (psutil.NoSuchProcess, psutil.AccessDenied): + return None + for p in procs: + try: + total += p.memory_full_info().pss + except AttributeError: + return None + except psutil.NoSuchProcess: + pass + except psutil.AccessDenied: + return None + return total + def _total_rss_bytes(self) -> int: total = 0 try: @@ -140,9 +172,14 @@ def _total_rss_bytes(self) -> int: def _run(self) -> None: while not self._stop.is_set(): rss = self._total_rss_bytes() + pss = self._total_pss_bytes() with self._lock: if rss > self._peak: self._peak = rss + if pss is not None and ( + self._peak_pss is None or pss > self._peak_pss + ): + self._peak_pss = pss time.sleep(self._poll_interval_s) @@ -331,6 +368,7 @@ def main() -> None: base_cache_bytes=base_cache_bytes, task_cache_bytes=task_cache_bytes, peak_rss_bytes=peak_rss_bytes, + peak_pss_bytes=tracker.peak_pss_bytes(), ) ) diff --git a/examples/benchmark_perf/benchmark_workers_n_length_of_stay.py b/examples/benchmark_perf/benchmark_workers_n_length_of_stay.py index 79c2a6f23c..9420121bfb 100644 --- a/examples/benchmark_perf/benchmark_workers_n_length_of_stay.py +++ b/examples/benchmark_perf/benchmark_workers_n_length_of_stay.py @@ -54,6 +54,7 @@ class RunResult: base_cache_bytes: int task_cache_bytes: int peak_rss_bytes: int + peak_pss_bytes: int | None # None where PSS is unavailable def format_size(size_bytes: int) -> str: @@ -108,6 +109,7 @@ def __init__(self, poll_interval_s: float = 0.1) -> None: self._stop = threading.Event() self._lock = threading.Lock() self._peak = 0 + self._peak_pss = None # no valid PSS sample yet self._thread = threading.Thread(target=self._run, daemon=True) def start(self) -> None: @@ -116,14 +118,44 @@ def start(self) -> None: def reset(self) -> None: with self._lock: self._peak = 0 + self._peak_pss = None def stop(self) -> None: self._stop.set() + def peak_pss_bytes(self) -> int | None: + with self._lock: + return self._peak_pss + def peak_bytes(self) -> int: with self._lock: return self._peak + def _total_pss_bytes(self) -> int | None: + """Proportional set size across the process tree. + + Summing RSS over forked workers counts every shared page once per + process; PSS divides it among the mappers, so the total is additive. + Returns None where PSS is unavailable for any process in the tree + (non-Linux, or no perms): that sample is not a PSS total, so the + peak column is left empty for the run rather than holding RSS. + """ + total = 0 + try: + procs = [self._proc] + self._proc.children(recursive=True) + except (psutil.NoSuchProcess, psutil.AccessDenied): + return None + for p in procs: + try: + total += p.memory_full_info().pss + except AttributeError: + return None + except psutil.NoSuchProcess: + pass + except psutil.AccessDenied: + return None + return total + def _total_rss_bytes(self) -> int: total = 0 try: @@ -140,9 +172,14 @@ def _total_rss_bytes(self) -> int: def _run(self) -> None: while not self._stop.is_set(): rss = self._total_rss_bytes() + pss = self._total_pss_bytes() with self._lock: if rss > self._peak: self._peak = rss + if pss is not None and ( + self._peak_pss is None or pss > self._peak_pss + ): + self._peak_pss = pss time.sleep(self._poll_interval_s) @@ -331,6 +368,7 @@ def main() -> None: base_cache_bytes=base_cache_bytes, task_cache_bytes=task_cache_bytes, peak_rss_bytes=peak_rss_bytes, + peak_pss_bytes=tracker.peak_pss_bytes(), ) ) diff --git a/examples/benchmark_perf/legacy_ver/benchmark_legacy_drug_rec.py b/examples/benchmark_perf/legacy_ver/benchmark_legacy_drug_rec.py index 780e762a5b..96d783c05e 100644 --- a/examples/benchmark_perf/legacy_ver/benchmark_legacy_drug_rec.py +++ b/examples/benchmark_perf/legacy_ver/benchmark_legacy_drug_rec.py @@ -96,6 +96,7 @@ class RunResult: total_s: float base_cache_bytes: int peak_rss_bytes: int + peak_pss_bytes: int | None # None where PSS is unavailable num_samples: int @@ -186,6 +187,7 @@ def __init__(self, poll_interval_s: float = 0.1) -> None: self._stop = threading.Event() self._lock = threading.Lock() self._peak = 0 + self._peak_pss = None # no valid PSS sample yet self._thread = threading.Thread(target=self._run, daemon=True) def start(self) -> None: @@ -194,14 +196,44 @@ def start(self) -> None: def reset(self) -> None: with self._lock: self._peak = 0 + self._peak_pss = None def stop(self) -> None: self._stop.set() + def peak_pss_bytes(self) -> int | None: + with self._lock: + return self._peak_pss + def peak_bytes(self) -> int: with self._lock: return self._peak + def _total_pss_bytes(self) -> int | None: + """Proportional set size across the process tree. + + Summing RSS over forked workers counts every shared page once per + process; PSS divides it among the mappers, so the total is additive. + Returns None where PSS is unavailable for any process in the tree + (non-Linux, or no perms): that sample is not a PSS total, so the + peak column is left empty for the run rather than holding RSS. + """ + total = 0 + try: + procs = [self._proc] + self._proc.children(recursive=True) + except (psutil.NoSuchProcess, psutil.AccessDenied): + return None + for p in procs: + try: + total += p.memory_full_info().pss + except AttributeError: + return None + except psutil.NoSuchProcess: + pass + except psutil.AccessDenied: + return None + return total + def _total_rss_bytes(self) -> int: total = 0 try: @@ -218,9 +250,14 @@ def _total_rss_bytes(self) -> int: def _run(self) -> None: while not self._stop.is_set(): rss = self._total_rss_bytes() + pss = self._total_pss_bytes() with self._lock: if rss > self._peak: self._peak = rss + if pss is not None and ( + self._peak_pss is None or pss > self._peak_pss + ): + self._peak_pss = pss time.sleep(self._poll_interval_s) @@ -411,6 +448,7 @@ def main() -> None: total_s=total_s, base_cache_bytes=base_cache_bytes, peak_rss_bytes=peak_rss_bytes, + peak_pss_bytes=tracker.peak_pss_bytes(), num_samples=num_samples, ) ) diff --git a/examples/benchmark_perf/legacy_ver/benchmark_legacy_los.py b/examples/benchmark_perf/legacy_ver/benchmark_legacy_los.py index 7d036f40bb..3dfccb48d7 100644 --- a/examples/benchmark_perf/legacy_ver/benchmark_legacy_los.py +++ b/examples/benchmark_perf/legacy_ver/benchmark_legacy_los.py @@ -96,6 +96,7 @@ class RunResult: total_s: float base_cache_bytes: int peak_rss_bytes: int + peak_pss_bytes: int | None # None where PSS is unavailable num_samples: int @@ -186,6 +187,7 @@ def __init__(self, poll_interval_s: float = 0.1) -> None: self._stop = threading.Event() self._lock = threading.Lock() self._peak = 0 + self._peak_pss = None # no valid PSS sample yet self._thread = threading.Thread(target=self._run, daemon=True) def start(self) -> None: @@ -194,14 +196,44 @@ def start(self) -> None: def reset(self) -> None: with self._lock: self._peak = 0 + self._peak_pss = None def stop(self) -> None: self._stop.set() + def peak_pss_bytes(self) -> int | None: + with self._lock: + return self._peak_pss + def peak_bytes(self) -> int: with self._lock: return self._peak + def _total_pss_bytes(self) -> int | None: + """Proportional set size across the process tree. + + Summing RSS over forked workers counts every shared page once per + process; PSS divides it among the mappers, so the total is additive. + Returns None where PSS is unavailable for any process in the tree + (non-Linux, or no perms): that sample is not a PSS total, so the + peak column is left empty for the run rather than holding RSS. + """ + total = 0 + try: + procs = [self._proc] + self._proc.children(recursive=True) + except (psutil.NoSuchProcess, psutil.AccessDenied): + return None + for p in procs: + try: + total += p.memory_full_info().pss + except AttributeError: + return None + except psutil.NoSuchProcess: + pass + except psutil.AccessDenied: + return None + return total + def _total_rss_bytes(self) -> int: total = 0 try: @@ -218,9 +250,14 @@ def _total_rss_bytes(self) -> int: def _run(self) -> None: while not self._stop.is_set(): rss = self._total_rss_bytes() + pss = self._total_pss_bytes() with self._lock: if rss > self._peak: self._peak = rss + if pss is not None and ( + self._peak_pss is None or pss > self._peak_pss + ): + self._peak_pss = pss time.sleep(self._poll_interval_s) @@ -412,6 +449,7 @@ def main() -> None: total_s=total_s, base_cache_bytes=base_cache_bytes, peak_rss_bytes=peak_rss_bytes, + peak_pss_bytes=tracker.peak_pss_bytes(), num_samples=num_samples, ) ) diff --git a/examples/benchmark_perf/legacy_ver/benchmark_legacy_mortality.py b/examples/benchmark_perf/legacy_ver/benchmark_legacy_mortality.py index 21db0053d1..aa2f02ade7 100644 --- a/examples/benchmark_perf/legacy_ver/benchmark_legacy_mortality.py +++ b/examples/benchmark_perf/legacy_ver/benchmark_legacy_mortality.py @@ -247,6 +247,7 @@ class RunResult: total_s: float base_cache_bytes: int peak_rss_bytes: int + peak_pss_bytes: int | None # None where PSS is unavailable num_samples: int @@ -337,6 +338,7 @@ def __init__(self, poll_interval_s: float = 0.1) -> None: self._stop = threading.Event() self._lock = threading.Lock() self._peak = 0 + self._peak_pss = None # no valid PSS sample yet self._thread = threading.Thread(target=self._run, daemon=True) def start(self) -> None: @@ -345,14 +347,44 @@ def start(self) -> None: def reset(self) -> None: with self._lock: self._peak = 0 + self._peak_pss = None def stop(self) -> None: self._stop.set() + def peak_pss_bytes(self) -> int | None: + with self._lock: + return self._peak_pss + def peak_bytes(self) -> int: with self._lock: return self._peak + def _total_pss_bytes(self) -> int | None: + """Proportional set size across the process tree. + + Summing RSS over forked workers counts every shared page once per + process; PSS divides it among the mappers, so the total is additive. + Returns None where PSS is unavailable for any process in the tree + (non-Linux, or no perms): that sample is not a PSS total, so the + peak column is left empty for the run rather than holding RSS. + """ + total = 0 + try: + procs = [self._proc] + self._proc.children(recursive=True) + except (psutil.NoSuchProcess, psutil.AccessDenied): + return None + for p in procs: + try: + total += p.memory_full_info().pss + except AttributeError: + return None + except psutil.NoSuchProcess: + pass + except psutil.AccessDenied: + return None + return total + def _total_rss_bytes(self) -> int: total = 0 try: @@ -369,9 +401,14 @@ def _total_rss_bytes(self) -> int: def _run(self) -> None: while not self._stop.is_set(): rss = self._total_rss_bytes() + pss = self._total_pss_bytes() with self._lock: if rss > self._peak: self._peak = rss + if pss is not None and ( + self._peak_pss is None or pss > self._peak_pss + ): + self._peak_pss = pss time.sleep(self._poll_interval_s) @@ -589,6 +626,7 @@ def main() -> None: total_s=total_s, base_cache_bytes=base_cache_bytes, peak_rss_bytes=peak_rss_bytes, + peak_pss_bytes=tracker.peak_pss_bytes(), num_samples=num_samples, ) ) diff --git a/examples/benchmark_perf/meds_reader_ver/benchmark_meds_reader_drug_rec.py b/examples/benchmark_perf/meds_reader_ver/benchmark_meds_reader_drug_rec.py index a9b719cb0f..b8dd4ea72d 100644 --- a/examples/benchmark_perf/meds_reader_ver/benchmark_meds_reader_drug_rec.py +++ b/examples/benchmark_perf/meds_reader_ver/benchmark_meds_reader_drug_rec.py @@ -487,6 +487,7 @@ class RunResult: task_process_s: float # Time to run the ML task total_s: float # Total time (conversion + task) peak_rss_bytes: int + peak_pss_bytes: int | None # None where PSS is unavailable num_samples: int conversion_cached: bool # True if conversion was skipped @@ -518,6 +519,7 @@ def __init__(self, poll_interval_s: float = 0.1) -> None: self._stop = threading.Event() self._lock = threading.Lock() self._peak = 0 + self._peak_pss = None # no valid PSS sample yet self._thread = threading.Thread(target=self._run, daemon=True) def start(self) -> None: @@ -526,14 +528,44 @@ def start(self) -> None: def reset(self) -> None: with self._lock: self._peak = 0 + self._peak_pss = None def stop(self) -> None: self._stop.set() + def peak_pss_bytes(self) -> int | None: + with self._lock: + return self._peak_pss + def peak_bytes(self) -> int: with self._lock: return self._peak + def _total_pss_bytes(self) -> int | None: + """Proportional set size across the process tree. + + Summing RSS over forked workers counts every shared page once per + process; PSS divides it among the mappers, so the total is additive. + Returns None where PSS is unavailable for any process in the tree + (non-Linux, or no perms): that sample is not a PSS total, so the + peak column is left empty for the run rather than holding RSS. + """ + total = 0 + try: + procs = [self._proc] + self._proc.children(recursive=True) + except (psutil.NoSuchProcess, psutil.AccessDenied): + return None + for p in procs: + try: + total += p.memory_full_info().pss + except AttributeError: + return None + except psutil.NoSuchProcess: + pass + except psutil.AccessDenied: + return None + return total + def _total_rss_bytes(self) -> int: total = 0 try: @@ -550,9 +582,14 @@ def _total_rss_bytes(self) -> int: def _run(self) -> None: while not self._stop.is_set(): rss = self._total_rss_bytes() + pss = self._total_pss_bytes() with self._lock: if rss > self._peak: self._peak = rss + if pss is not None and ( + self._peak_pss is None or pss > self._peak_pss + ): + self._peak_pss = pss time.sleep(self._poll_interval_s) @@ -767,6 +804,7 @@ def main() -> None: task_process_s=task_process_s, total_s=total_s, peak_rss_bytes=peak_rss_bytes, + peak_pss_bytes=tracker.peak_pss_bytes(), num_samples=num_samples, conversion_cached=conversion.was_cached, ) diff --git a/examples/benchmark_perf/meds_reader_ver/benchmark_meds_reader_drug_rec_pyhealth_etl.py b/examples/benchmark_perf/meds_reader_ver/benchmark_meds_reader_drug_rec_pyhealth_etl.py index 1f98335ade..24bb125f86 100644 --- a/examples/benchmark_perf/meds_reader_ver/benchmark_meds_reader_drug_rec_pyhealth_etl.py +++ b/examples/benchmark_perf/meds_reader_ver/benchmark_meds_reader_drug_rec_pyhealth_etl.py @@ -509,6 +509,7 @@ class RunResult: task_process_s: float total_s: float peak_rss_bytes: int + peak_pss_bytes: int | None # None where PSS is unavailable num_samples: int conversion_cached: bool @@ -528,6 +529,7 @@ def __init__(self, poll_interval_s: float = 0.1): self._stop = threading.Event() self._lock = threading.Lock() self._peak = 0 + self._peak_pss = None # no valid PSS sample yet self._thread = threading.Thread(target=self._run, daemon=True) def start(self): @@ -536,11 +538,41 @@ def start(self): def reset(self): with self._lock: self._peak = 0 + self._peak_pss = None + + def peak_pss_bytes(self) -> int | None: + with self._lock: + return self._peak_pss def peak_bytes(self) -> int: with self._lock: return self._peak + def _total_pss_bytes(self) -> int | None: + """Proportional set size across the process tree. + + Summing RSS over forked workers counts every shared page once per + process; PSS divides it among the mappers, so the total is additive. + Returns None where PSS is unavailable for any process in the tree + (non-Linux, or no perms): that sample is not a PSS total, so the + peak column is left empty for the run rather than holding RSS. + """ + total = 0 + try: + procs = [self._proc] + self._proc.children(recursive=True) + except (psutil.NoSuchProcess, psutil.AccessDenied): + return None + for p in procs: + try: + total += p.memory_full_info().pss + except AttributeError: + return None + except psutil.NoSuchProcess: + pass + except psutil.AccessDenied: + return None + return total + def _total_rss_bytes(self) -> int: total = 0 try: @@ -557,9 +589,14 @@ def _total_rss_bytes(self) -> int: def _run(self): while not self._stop.is_set(): rss = self._total_rss_bytes() + pss = self._total_pss_bytes() with self._lock: if rss > self._peak: self._peak = rss + if pss is not None and ( + self._peak_pss is None or pss > self._peak_pss + ): + self._peak_pss = pss time.sleep(self._poll_interval_s) @@ -702,6 +739,7 @@ def main(): task_process_s = time.time() - task_start total_s = time.time() - run_start peak_rss = tracker.peak_bytes() + peak_pss = tracker.peak_pss_bytes() results.append(RunResult( num_threads=t, @@ -711,6 +749,7 @@ def main(): task_process_s=task_process_s, total_s=total_s, peak_rss_bytes=peak_rss, + peak_pss_bytes=peak_pss, num_samples=len(dataset), conversion_cached=conversion.was_cached, )) diff --git a/examples/benchmark_perf/meds_reader_ver/benchmark_meds_reader_los.py b/examples/benchmark_perf/meds_reader_ver/benchmark_meds_reader_los.py index 5acbd076e5..f3098ba99e 100644 --- a/examples/benchmark_perf/meds_reader_ver/benchmark_meds_reader_los.py +++ b/examples/benchmark_perf/meds_reader_ver/benchmark_meds_reader_los.py @@ -479,6 +479,7 @@ class RunResult: task_process_s: float # Time to run the ML task total_s: float # Total time (conversion + task) peak_rss_bytes: int + peak_pss_bytes: int | None # None where PSS is unavailable num_samples: int conversion_cached: bool # True if conversion was skipped @@ -510,6 +511,7 @@ def __init__(self, poll_interval_s: float = 0.1) -> None: self._stop = threading.Event() self._lock = threading.Lock() self._peak = 0 + self._peak_pss = None # no valid PSS sample yet self._thread = threading.Thread(target=self._run, daemon=True) def start(self) -> None: @@ -518,14 +520,44 @@ def start(self) -> None: def reset(self) -> None: with self._lock: self._peak = 0 + self._peak_pss = None def stop(self) -> None: self._stop.set() + def peak_pss_bytes(self) -> int | None: + with self._lock: + return self._peak_pss + def peak_bytes(self) -> int: with self._lock: return self._peak + def _total_pss_bytes(self) -> int | None: + """Proportional set size across the process tree. + + Summing RSS over forked workers counts every shared page once per + process; PSS divides it among the mappers, so the total is additive. + Returns None where PSS is unavailable for any process in the tree + (non-Linux, or no perms): that sample is not a PSS total, so the + peak column is left empty for the run rather than holding RSS. + """ + total = 0 + try: + procs = [self._proc] + self._proc.children(recursive=True) + except (psutil.NoSuchProcess, psutil.AccessDenied): + return None + for p in procs: + try: + total += p.memory_full_info().pss + except AttributeError: + return None + except psutil.NoSuchProcess: + pass + except psutil.AccessDenied: + return None + return total + def _total_rss_bytes(self) -> int: total = 0 try: @@ -542,9 +574,14 @@ def _total_rss_bytes(self) -> int: def _run(self) -> None: while not self._stop.is_set(): rss = self._total_rss_bytes() + pss = self._total_pss_bytes() with self._lock: if rss > self._peak: self._peak = rss + if pss is not None and ( + self._peak_pss is None or pss > self._peak_pss + ): + self._peak_pss = pss time.sleep(self._poll_interval_s) @@ -759,6 +796,7 @@ def main() -> None: task_process_s=task_process_s, total_s=total_s, peak_rss_bytes=peak_rss_bytes, + peak_pss_bytes=tracker.peak_pss_bytes(), num_samples=num_samples, conversion_cached=conversion.was_cached, ) diff --git a/examples/benchmark_perf/meds_reader_ver/benchmark_meds_reader_los_pyhealth_etl.py b/examples/benchmark_perf/meds_reader_ver/benchmark_meds_reader_los_pyhealth_etl.py index 9dc787f876..90e0b31e6a 100644 --- a/examples/benchmark_perf/meds_reader_ver/benchmark_meds_reader_los_pyhealth_etl.py +++ b/examples/benchmark_perf/meds_reader_ver/benchmark_meds_reader_los_pyhealth_etl.py @@ -538,6 +538,7 @@ class RunResult: task_process_s: float total_s: float peak_rss_bytes: int + peak_pss_bytes: int | None # None where PSS is unavailable num_samples: int conversion_cached: bool @@ -557,6 +558,7 @@ def __init__(self, poll_interval_s: float = 0.1): self._stop = threading.Event() self._lock = threading.Lock() self._peak = 0 + self._peak_pss = None # no valid PSS sample yet self._thread = threading.Thread(target=self._run, daemon=True) def start(self): @@ -565,11 +567,41 @@ def start(self): def reset(self): with self._lock: self._peak = 0 + self._peak_pss = None + + def peak_pss_bytes(self) -> int | None: + with self._lock: + return self._peak_pss def peak_bytes(self) -> int: with self._lock: return self._peak + def _total_pss_bytes(self) -> int | None: + """Proportional set size across the process tree. + + Summing RSS over forked workers counts every shared page once per + process; PSS divides it among the mappers, so the total is additive. + Returns None where PSS is unavailable for any process in the tree + (non-Linux, or no perms): that sample is not a PSS total, so the + peak column is left empty for the run rather than holding RSS. + """ + total = 0 + try: + procs = [self._proc] + self._proc.children(recursive=True) + except (psutil.NoSuchProcess, psutil.AccessDenied): + return None + for p in procs: + try: + total += p.memory_full_info().pss + except AttributeError: + return None + except psutil.NoSuchProcess: + pass + except psutil.AccessDenied: + return None + return total + def _total_rss_bytes(self) -> int: total = 0 try: @@ -586,9 +618,14 @@ def _total_rss_bytes(self) -> int: def _run(self): while not self._stop.is_set(): rss = self._total_rss_bytes() + pss = self._total_pss_bytes() with self._lock: if rss > self._peak: self._peak = rss + if pss is not None and ( + self._peak_pss is None or pss > self._peak_pss + ): + self._peak_pss = pss time.sleep(self._poll_interval_s) @@ -736,6 +773,7 @@ def main(): task_process_s = time.time() - task_start total_s = time.time() - run_start peak_rss = tracker.peak_bytes() + peak_pss = tracker.peak_pss_bytes() results.append(RunResult( num_threads=t, @@ -745,6 +783,7 @@ def main(): task_process_s=task_process_s, total_s=total_s, peak_rss_bytes=peak_rss, + peak_pss_bytes=peak_pss, num_samples=len(dataset), conversion_cached=conversion.was_cached, )) diff --git a/examples/benchmark_perf/meds_reader_ver/benchmark_meds_reader_mortality.py b/examples/benchmark_perf/meds_reader_ver/benchmark_meds_reader_mortality.py index cceda55c82..3b782ea797 100644 --- a/examples/benchmark_perf/meds_reader_ver/benchmark_meds_reader_mortality.py +++ b/examples/benchmark_perf/meds_reader_ver/benchmark_meds_reader_mortality.py @@ -491,6 +491,7 @@ class RunResult: task_process_s: float # Time to run the ML task total_s: float # Total time (conversion + task) peak_rss_bytes: int + peak_pss_bytes: int | None # None where PSS is unavailable num_samples: int conversion_cached: bool # True if conversion was skipped @@ -522,6 +523,7 @@ def __init__(self, poll_interval_s: float = 0.1) -> None: self._stop = threading.Event() self._lock = threading.Lock() self._peak = 0 + self._peak_pss = None # no valid PSS sample yet self._thread = threading.Thread(target=self._run, daemon=True) def start(self) -> None: @@ -530,14 +532,44 @@ def start(self) -> None: def reset(self) -> None: with self._lock: self._peak = 0 + self._peak_pss = None def stop(self) -> None: self._stop.set() + def peak_pss_bytes(self) -> int | None: + with self._lock: + return self._peak_pss + def peak_bytes(self) -> int: with self._lock: return self._peak + def _total_pss_bytes(self) -> int | None: + """Proportional set size across the process tree. + + Summing RSS over forked workers counts every shared page once per + process; PSS divides it among the mappers, so the total is additive. + Returns None where PSS is unavailable for any process in the tree + (non-Linux, or no perms): that sample is not a PSS total, so the + peak column is left empty for the run rather than holding RSS. + """ + total = 0 + try: + procs = [self._proc] + self._proc.children(recursive=True) + except (psutil.NoSuchProcess, psutil.AccessDenied): + return None + for p in procs: + try: + total += p.memory_full_info().pss + except AttributeError: + return None + except psutil.NoSuchProcess: + pass + except psutil.AccessDenied: + return None + return total + def _total_rss_bytes(self) -> int: total = 0 try: @@ -554,9 +586,14 @@ def _total_rss_bytes(self) -> int: def _run(self) -> None: while not self._stop.is_set(): rss = self._total_rss_bytes() + pss = self._total_pss_bytes() with self._lock: if rss > self._peak: self._peak = rss + if pss is not None and ( + self._peak_pss is None or pss > self._peak_pss + ): + self._peak_pss = pss time.sleep(self._poll_interval_s) @@ -770,6 +807,7 @@ def main() -> None: task_process_s=task_process_s, total_s=total_s, peak_rss_bytes=peak_rss_bytes, + peak_pss_bytes=tracker.peak_pss_bytes(), num_samples=num_samples, conversion_cached=conversion.was_cached, ) diff --git a/examples/benchmark_perf/meds_reader_ver/benchmark_meds_reader_mortality_pyhealth_etl.py b/examples/benchmark_perf/meds_reader_ver/benchmark_meds_reader_mortality_pyhealth_etl.py index 754c482a00..c5258594b8 100644 --- a/examples/benchmark_perf/meds_reader_ver/benchmark_meds_reader_mortality_pyhealth_etl.py +++ b/examples/benchmark_perf/meds_reader_ver/benchmark_meds_reader_mortality_pyhealth_etl.py @@ -512,6 +512,7 @@ class RunResult: task_process_s: float total_s: float peak_rss_bytes: int + peak_pss_bytes: int | None # None where PSS is unavailable num_samples: int conversion_cached: bool @@ -531,6 +532,7 @@ def __init__(self, poll_interval_s: float = 0.1): self._stop = threading.Event() self._lock = threading.Lock() self._peak = 0 + self._peak_pss = None # no valid PSS sample yet self._thread = threading.Thread(target=self._run, daemon=True) def start(self): @@ -539,11 +541,41 @@ def start(self): def reset(self): with self._lock: self._peak = 0 + self._peak_pss = None + + def peak_pss_bytes(self) -> int | None: + with self._lock: + return self._peak_pss def peak_bytes(self) -> int: with self._lock: return self._peak + def _total_pss_bytes(self) -> int | None: + """Proportional set size across the process tree. + + Summing RSS over forked workers counts every shared page once per + process; PSS divides it among the mappers, so the total is additive. + Returns None where PSS is unavailable for any process in the tree + (non-Linux, or no perms): that sample is not a PSS total, so the + peak column is left empty for the run rather than holding RSS. + """ + total = 0 + try: + procs = [self._proc] + self._proc.children(recursive=True) + except (psutil.NoSuchProcess, psutil.AccessDenied): + return None + for p in procs: + try: + total += p.memory_full_info().pss + except AttributeError: + return None + except psutil.NoSuchProcess: + pass + except psutil.AccessDenied: + return None + return total + def _total_rss_bytes(self) -> int: total = 0 try: @@ -560,9 +592,14 @@ def _total_rss_bytes(self) -> int: def _run(self): while not self._stop.is_set(): rss = self._total_rss_bytes() + pss = self._total_pss_bytes() with self._lock: if rss > self._peak: self._peak = rss + if pss is not None and ( + self._peak_pss is None or pss > self._peak_pss + ): + self._peak_pss = pss time.sleep(self._poll_interval_s) @@ -704,6 +741,7 @@ def main(): task_process_s = time.time() - task_start total_s = time.time() - run_start peak_rss = tracker.peak_bytes() + peak_pss = tracker.peak_pss_bytes() results.append(RunResult( num_threads=t, @@ -713,6 +751,7 @@ def main(): task_process_s=task_process_s, total_s=total_s, peak_rss_bytes=peak_rss, + peak_pss_bytes=peak_pss, num_samples=len(dataset), conversion_cached=conversion.was_cached, )) diff --git a/examples/benchmark_perf/patient_exploration/benchmark_patient_access_legacy.py b/examples/benchmark_perf/patient_exploration/benchmark_patient_access_legacy.py index 50a2807972..b83b90e9e5 100644 --- a/examples/benchmark_perf/patient_exploration/benchmark_patient_access_legacy.py +++ b/examples/benchmark_perf/patient_exploration/benchmark_patient_access_legacy.py @@ -63,6 +63,7 @@ class BenchmarkResult: patient_access_2nd_s: float # Second access (warm cache) total_s: float peak_rss_bytes: int + peak_pss_bytes: int | None # None where PSS is unavailable patient_found: bool num_events: int num_visits: int @@ -85,6 +86,7 @@ def __init__(self, poll_interval_s: float = 0.05) -> None: self._stop = threading.Event() self._lock = threading.Lock() self._peak = 0 + self._peak_pss = None # no valid PSS sample yet self._thread = threading.Thread(target=self._run, daemon=True) def start(self) -> None: @@ -93,14 +95,44 @@ def start(self) -> None: def reset(self) -> None: with self._lock: self._peak = 0 + self._peak_pss = None def stop(self) -> None: self._stop.set() + def peak_pss_bytes(self) -> int | None: + with self._lock: + return self._peak_pss + def peak_bytes(self) -> int: with self._lock: return self._peak + def _total_pss_bytes(self) -> int | None: + """Proportional set size across the process tree. + + Summing RSS over forked workers counts every shared page once per + process; PSS divides it among the mappers, so the total is additive. + Returns None where PSS is unavailable for any process in the tree + (non-Linux, or no perms): that sample is not a PSS total, so the + peak column is left empty for the run rather than holding RSS. + """ + total = 0 + try: + procs = [self._proc] + self._proc.children(recursive=True) + except (psutil.NoSuchProcess, psutil.AccessDenied): + return None + for p in procs: + try: + total += p.memory_full_info().pss + except AttributeError: + return None + except psutil.NoSuchProcess: + pass + except psutil.AccessDenied: + return None + return total + def _total_rss_bytes(self) -> int: total = 0 try: @@ -117,9 +149,14 @@ def _total_rss_bytes(self) -> int: def _run(self) -> None: while not self._stop.is_set(): rss = self._total_rss_bytes() + pss = self._total_pss_bytes() with self._lock: if rss > self._peak: self._peak = rss + if pss is not None and ( + self._peak_pss is None or pss > self._peak_pss + ): + self._peak_pss = pss time.sleep(self._poll_interval_s) @@ -270,6 +307,7 @@ def main() -> None: total_s = data_load_s + patient_access_1st_s + patient_access_2nd_s peak_rss = tracker.peak_bytes() + peak_pss = tracker.peak_pss_bytes() tracker.stop() @@ -280,6 +318,7 @@ def main() -> None: patient_access_2nd_s=patient_access_2nd_s, total_s=total_s, peak_rss_bytes=peak_rss, + peak_pss_bytes=peak_pss, patient_found=patient_found, num_events=num_events, num_visits=num_visits, diff --git a/examples/benchmark_perf/patient_exploration/benchmark_patient_access_meds_reader.py b/examples/benchmark_perf/patient_exploration/benchmark_patient_access_meds_reader.py index 961615ddfa..7850e62875 100644 --- a/examples/benchmark_perf/patient_exploration/benchmark_patient_access_meds_reader.py +++ b/examples/benchmark_perf/patient_exploration/benchmark_patient_access_meds_reader.py @@ -61,6 +61,7 @@ class BenchmarkResult: patient_access_2nd_s: float # Second access (warm cache) total_s: float peak_rss_bytes: int + peak_pss_bytes: int | None # None where PSS is unavailable patient_found: bool num_events: int used_cached_db: bool @@ -83,6 +84,7 @@ def __init__(self, poll_interval_s: float = 0.05) -> None: self._stop = threading.Event() self._lock = threading.Lock() self._peak = 0 + self._peak_pss = None # no valid PSS sample yet self._thread = threading.Thread(target=self._run, daemon=True) def start(self) -> None: @@ -91,14 +93,44 @@ def start(self) -> None: def reset(self) -> None: with self._lock: self._peak = 0 + self._peak_pss = None def stop(self) -> None: self._stop.set() + def peak_pss_bytes(self) -> int | None: + with self._lock: + return self._peak_pss + def peak_bytes(self) -> int: with self._lock: return self._peak + def _total_pss_bytes(self) -> int | None: + """Proportional set size across the process tree. + + Summing RSS over forked workers counts every shared page once per + process; PSS divides it among the mappers, so the total is additive. + Returns None where PSS is unavailable for any process in the tree + (non-Linux, or no perms): that sample is not a PSS total, so the + peak column is left empty for the run rather than holding RSS. + """ + total = 0 + try: + procs = [self._proc] + self._proc.children(recursive=True) + except (psutil.NoSuchProcess, psutil.AccessDenied): + return None + for p in procs: + try: + total += p.memory_full_info().pss + except AttributeError: + return None + except psutil.NoSuchProcess: + pass + except psutil.AccessDenied: + return None + return total + def _total_rss_bytes(self) -> int: total = 0 try: @@ -115,9 +147,14 @@ def _total_rss_bytes(self) -> int: def _run(self) -> None: while not self._stop.is_set(): rss = self._total_rss_bytes() + pss = self._total_pss_bytes() with self._lock: if rss > self._peak: self._peak = rss + if pss is not None and ( + self._peak_pss is None or pss > self._peak_pss + ): + self._peak_pss = pss time.sleep(self._poll_interval_s) @@ -354,6 +391,7 @@ def main() -> None: total_s = data_load_s + patient_access_1st_s + patient_access_2nd_s peak_rss = tracker.peak_bytes() + peak_pss = tracker.peak_pss_bytes() tracker.stop() @@ -366,6 +404,7 @@ def main() -> None: patient_access_2nd_s=patient_access_2nd_s, total_s=total_s, peak_rss_bytes=peak_rss, + peak_pss_bytes=peak_pss, patient_found=patient_found, num_events=num_events, used_cached_db=used_cached_db, diff --git a/examples/benchmark_perf/patient_exploration/benchmark_patient_access_pandas.py b/examples/benchmark_perf/patient_exploration/benchmark_patient_access_pandas.py index 47fd434bfb..0bb06e2a55 100644 --- a/examples/benchmark_perf/patient_exploration/benchmark_patient_access_pandas.py +++ b/examples/benchmark_perf/patient_exploration/benchmark_patient_access_pandas.py @@ -51,6 +51,7 @@ class BenchmarkResult: patient_access_2nd_s: float # Second access (warm cache) total_s: float peak_rss_bytes: int + peak_pss_bytes: int | None # None where PSS is unavailable patient_found: bool num_events: int num_visits: int @@ -75,6 +76,7 @@ def __init__(self, poll_interval_s: float = 0.05) -> None: self._stop = threading.Event() self._lock = threading.Lock() self._peak = 0 + self._peak_pss = None # no valid PSS sample yet self._thread = threading.Thread(target=self._run, daemon=True) def start(self) -> None: @@ -83,14 +85,44 @@ def start(self) -> None: def reset(self) -> None: with self._lock: self._peak = 0 + self._peak_pss = None def stop(self) -> None: self._stop.set() + def peak_pss_bytes(self) -> int | None: + with self._lock: + return self._peak_pss + def peak_bytes(self) -> int: with self._lock: return self._peak + def _total_pss_bytes(self) -> int | None: + """Proportional set size across the process tree. + + Summing RSS over forked workers counts every shared page once per + process; PSS divides it among the mappers, so the total is additive. + Returns None where PSS is unavailable for any process in the tree + (non-Linux, or no perms): that sample is not a PSS total, so the + peak column is left empty for the run rather than holding RSS. + """ + total = 0 + try: + procs = [self._proc] + self._proc.children(recursive=True) + except (psutil.NoSuchProcess, psutil.AccessDenied): + return None + for p in procs: + try: + total += p.memory_full_info().pss + except AttributeError: + return None + except psutil.NoSuchProcess: + pass + except psutil.AccessDenied: + return None + return total + def _total_rss_bytes(self) -> int: total = 0 try: @@ -107,9 +139,14 @@ def _total_rss_bytes(self) -> int: def _run(self) -> None: while not self._stop.is_set(): rss = self._total_rss_bytes() + pss = self._total_pss_bytes() with self._lock: if rss > self._peak: self._peak = rss + if pss is not None and ( + self._peak_pss is None or pss > self._peak_pss + ): + self._peak_pss = pss time.sleep(self._poll_interval_s) @@ -523,6 +560,7 @@ def main() -> None: # Calculate total time total_s = csv_load_s + parquet_write_s + parquet_read_s + patient_access_1st_s + patient_access_2nd_s peak_rss = tracker.peak_bytes() + peak_pss = tracker.peak_pss_bytes() finally: tracker.stop() @@ -541,6 +579,7 @@ def main() -> None: patient_access_2nd_s=patient_access_2nd_s, total_s=total_s, peak_rss_bytes=peak_rss, + peak_pss_bytes=peak_pss, patient_found=patient_found, num_events=num_events, num_visits=num_visits, diff --git a/examples/benchmark_perf/patient_exploration/benchmark_patient_access_pyhealth2.py b/examples/benchmark_perf/patient_exploration/benchmark_patient_access_pyhealth2.py index 736ae3023f..ba18f1dff4 100644 --- a/examples/benchmark_perf/patient_exploration/benchmark_patient_access_pyhealth2.py +++ b/examples/benchmark_perf/patient_exploration/benchmark_patient_access_pyhealth2.py @@ -43,6 +43,7 @@ class BenchmarkResult: patient_access_2nd_s: float # Second access (warm cache) total_s: float peak_rss_bytes: int + peak_pss_bytes: int | None # None where PSS is unavailable patient_found: bool num_events: int @@ -64,6 +65,7 @@ def __init__(self, poll_interval_s: float = 0.05) -> None: self._stop = threading.Event() self._lock = threading.Lock() self._peak = 0 + self._peak_pss = None # no valid PSS sample yet self._thread = threading.Thread(target=self._run, daemon=True) def start(self) -> None: @@ -72,14 +74,44 @@ def start(self) -> None: def reset(self) -> None: with self._lock: self._peak = 0 + self._peak_pss = None def stop(self) -> None: self._stop.set() + def peak_pss_bytes(self) -> int | None: + with self._lock: + return self._peak_pss + def peak_bytes(self) -> int: with self._lock: return self._peak + def _total_pss_bytes(self) -> int | None: + """Proportional set size across the process tree. + + Summing RSS over forked workers counts every shared page once per + process; PSS divides it among the mappers, so the total is additive. + Returns None where PSS is unavailable for any process in the tree + (non-Linux, or no perms): that sample is not a PSS total, so the + peak column is left empty for the run rather than holding RSS. + """ + total = 0 + try: + procs = [self._proc] + self._proc.children(recursive=True) + except (psutil.NoSuchProcess, psutil.AccessDenied): + return None + for p in procs: + try: + total += p.memory_full_info().pss + except AttributeError: + return None + except psutil.NoSuchProcess: + pass + except psutil.AccessDenied: + return None + return total + def _total_rss_bytes(self) -> int: total = 0 try: @@ -96,9 +128,14 @@ def _total_rss_bytes(self) -> int: def _run(self) -> None: while not self._stop.is_set(): rss = self._total_rss_bytes() + pss = self._total_pss_bytes() with self._lock: if rss > self._peak: self._peak = rss + if pss is not None and ( + self._peak_pss is None or pss > self._peak_pss + ): + self._peak_pss = pss time.sleep(self._poll_interval_s) @@ -219,6 +256,7 @@ def main() -> None: total_s = data_load_s + patient_access_1st_s + patient_access_2nd_s peak_rss = tracker.peak_bytes() + peak_pss = tracker.peak_pss_bytes() tracker.stop() @@ -234,6 +272,7 @@ def main() -> None: patient_access_2nd_s=patient_access_2nd_s, total_s=total_s, peak_rss_bytes=peak_rss, + peak_pss_bytes=peak_pss, patient_found=patient_found, num_events=num_events, ) diff --git a/tests/core/test_benchmark_pss.py b/tests/core/test_benchmark_pss.py new file mode 100644 index 0000000000..32a13418c6 --- /dev/null +++ b/tests/core/test_benchmark_pss.py @@ -0,0 +1,170 @@ +"""PSS next to summed RSS in benchmark_perf. + +Summing RSS over forked workers counts every shared page once per process; +PSS divides it among the mappers, so the total is additive. Each harness +tracks both and records ``peak_pss_bytes`` alongside ``peak_rss_bytes``. +Where PSS is unavailable for any process in the tree the sample is not a +PSS total, so the column is left empty for the run (no RSS fallback, and +the reset runs inside the sampler lock). + +Some harnesses do not import in every environment (``meds_reader`` is an +optional dependency; one legacy file names a task helper this tree no +longer exports). Those get a structural check of the added lines; the +importable ones also run the tracker. +""" + +from __future__ import annotations + +import dataclasses +import importlib.util +import time +import unittest +from pathlib import Path + +import psutil + +HARNESSES = [ + "benchmark_workers_n.py", + "benchmark_workers_n_drug_recommendation.py", + "benchmark_workers_n_length_of_stay.py", + "legacy_ver/benchmark_legacy_drug_rec.py", + "legacy_ver/benchmark_legacy_los.py", + "legacy_ver/benchmark_legacy_mortality.py", + "meds_reader_ver/benchmark_meds_reader_drug_rec.py", + "meds_reader_ver/benchmark_meds_reader_drug_rec_pyhealth_etl.py", + "meds_reader_ver/benchmark_meds_reader_los.py", + "meds_reader_ver/benchmark_meds_reader_los_pyhealth_etl.py", + "meds_reader_ver/benchmark_meds_reader_mortality.py", + "meds_reader_ver/benchmark_meds_reader_mortality_pyhealth_etl.py", + "patient_exploration/benchmark_patient_access_legacy.py", + "patient_exploration/benchmark_patient_access_meds_reader.py", + "patient_exploration/benchmark_patient_access_pandas.py", + "patient_exploration/benchmark_patient_access_pyhealth2.py", +] + +PSS_MARKERS = ( + "peak_pss_bytes", + "_total_pss_bytes", + "memory_full_info().pss", +) + + +def _path(name): + return ( + Path(__file__).resolve().parents[2] / "examples" / "benchmark_perf" / name + ) + + +def _load(name): + import sys + + mod_name = "bench_pss_" + name.replace("/", "_").replace(".py", "") + spec = importlib.util.spec_from_file_location(mod_name, _path(name)) + module = importlib.util.module_from_spec(spec) + sys.modules[mod_name] = module + spec.loader.exec_module(module) + return module + + +def _result_class(module): + for value in vars(module).values(): + if ( + isinstance(value, type) + and dataclasses.is_dataclass(value) + and any(f.name == "peak_rss_bytes" for f in dataclasses.fields(value)) + ): + return value + raise AssertionError(f"no peak_rss_bytes dataclass in {module.__name__}") + + +class TestBenchmarkPss(unittest.TestCase): + def test_all_harnesses_report_pss(self): + self.assertEqual(len(HARNESSES), 16) + exercised = 0 + for name in HARNESSES: + with self.subTest(harness=name): + src = _path(name).read_text() + for marker in PSS_MARKERS: + self.assertIn(marker, src) + try: + module = _load(name) + except ImportError as exc: + self.skipTest(f"{name} does not import here: {exc}") + cls = _result_class(module) + self.assertIn( + "peak_pss_bytes", {f.name for f in dataclasses.fields(cls)} + ) + tracker = module.PeakMemoryTracker(poll_interval_s=0.01) + self.assertIsNone(tracker.peak_pss_bytes()) + sample = tracker._total_pss_bytes() + self.assertTrue(sample is None or sample >= 0) + tracker.start() + time.sleep(0.05) + tracker.stop() + peak = tracker.peak_pss_bytes() + self.assertTrue(peak is None or peak >= 0) + self.assertGreaterEqual(tracker.peak_bytes(), 0) + tracker.reset() + self.assertIsNone(tracker.peak_pss_bytes()) + self.assertEqual(tracker.peak_bytes(), 0) + exercised += 1 + self.assertGreater(exercised, 0) + + +class _FakeMemory: + """Stand-in for the object ``memory_full_info()`` returns.""" + + def __init__(self, pss): + self.pss = pss + + +class _FakeProcess: + """Minimal ``psutil.Process`` stand-in for PSS sampling tests.""" + + def __init__(self, pss=None, error=None, children=()): + self._pss = pss + self._error = error + self._children = list(children) + + def children(self, recursive=False): + return list(self._children) + + def memory_full_info(self): + if self._error is not None: + raise self._error + return _FakeMemory(self._pss) + + +class TestTotalPssProcessErrors(unittest.TestCase): + """Denied processes drop the sample; exited ones are skipped.""" + + def _tracker(self): + for name in HARNESSES: + try: + module = _load(name) + except ImportError: + continue + return module.PeakMemoryTracker(poll_interval_s=3600) + self.skipTest("no harness imports here") + + def test_access_denied_drops_sample(self): + tracker = self._tracker() + tracker._proc = _FakeProcess( + pss=50, + children=[ + _FakeProcess(pss=100), + _FakeProcess(error=psutil.AccessDenied()), + ], + ) + self.assertIsNone(tracker._total_pss_bytes()) + + def test_no_such_process_skipped(self): + tracker = self._tracker() + tracker._proc = _FakeProcess( + pss=50, + children=[ + _FakeProcess(pss=100), + _FakeProcess(error=psutil.NoSuchProcess(9999)), + ], + ) + self.assertEqual(tracker._total_pss_bytes(), 150) From 0a606720bb4da35be80d1a04dbcdc27b9a14ea00 Mon Sep 17 00:00:00 2001 From: Rian Date: Thu, 5 Nov 2026 20:31:49 -0500 Subject: [PATCH 07/11] Resolve optimizer settings from the CLI only. 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 --- .../unified_embedding_e2e_mimic4.py | 54 +++++-------- tests/core/test_optimizer_cli_only.py | 79 +++++++++++++++++++ 2 files changed, 100 insertions(+), 33 deletions(-) create mode 100644 tests/core/test_optimizer_cli_only.py diff --git a/examples/mortality_prediction/unified_embedding_e2e_mimic4.py b/examples/mortality_prediction/unified_embedding_e2e_mimic4.py index 610203c7d3..cf74da1425 100644 --- a/examples/mortality_prediction/unified_embedding_e2e_mimic4.py +++ b/examples/mortality_prediction/unified_embedding_e2e_mimic4.py @@ -171,6 +171,18 @@ def _window_suffix(observation_window_hours: float) -> str: return f"_w{observation_window_hours:g}" if observation_window_hours else "" +def _optimizer_settings(args: argparse.Namespace): + """Resolve optimizer settings from the CLI only. + + There used to be a per-model branch here that 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. If a model needs different optimizer settings, + the launcher has to say so. + """ + return args.lr, args.max_grad_norm, {"lr": args.lr, "eps": args.adam_eps} + + def _select_inference_loader(test_loader, val_loader, train_loader): """Name the split predictions come from, warning when it is not test. @@ -447,27 +459,9 @@ def run(args: argparse.Namespace, sample_dataset: Any = None) -> Path: exp_name=exp_name, ) - # BottleneckTransformer is more fragile on full MIMIC-IV with no warmup. - # Use safer defaults unless explicitly overridden from CLI. - effective_lr = args.lr - effective_max_grad_norm = args.max_grad_norm - optimizer_params = {} - - if args.model == "bottleneck_transformer": - if effective_lr is None: - effective_lr = 1e-4 - if effective_max_grad_norm is None: - effective_max_grad_norm = 0.5 - optimizer_params["eps"] = args.adam_eps if args.adam_eps is not None else 1e-6 - else: - if effective_lr is None: - effective_lr = 1e-4 - if effective_max_grad_norm is None: - effective_max_grad_norm = 1.0 - if args.adam_eps is not None: - optimizer_params["eps"] = args.adam_eps - - optimizer_params["lr"] = effective_lr + effective_lr, effective_max_grad_norm, optimizer_params = _optimizer_settings( + args + ) write_run_config( str(output_dir / exp_name), @@ -615,17 +609,14 @@ def parse_args(argv: Optional[list] = None) -> argparse.Namespace: parser.add_argument( "--lr", type=float, - default=None, - help="Learning rate. Default is 1e-4 for all models.", + default=1e-4, + help="Learning rate, same for every model.", ) parser.add_argument( "--adam-eps", type=float, - default=None, - help=( - "Adam epsilon. Default is model-specific: 1e-8 for non-BT models, " - "1e-6 for bottleneck_transformer." - ), + default=1e-8, + help="Adam epsilon, same for every model (torch default).", ) parser.add_argument("--weight-decay", type=float, default=0.0) parser.add_argument("--device", type=str, default=None) @@ -735,11 +726,8 @@ def parse_args(argv: Optional[list] = None) -> argparse.Namespace: parser.add_argument( "--max-grad-norm", type=float, - default=None, - help=( - "Gradient clipping max norm. Default is model-specific: None for " - "non-BT models, 0.5 for bottleneck_transformer." - ), + default=1.0, + help="Gradient clipping max norm, same for every model.", ) parser.add_argument( diff --git a/tests/core/test_optimizer_cli_only.py b/tests/core/test_optimizer_cli_only.py new file mode 100644 index 0000000000..ce49665d76 --- /dev/null +++ b/tests/core/test_optimizer_cli_only.py @@ -0,0 +1,79 @@ +"""Optimizer settings come from the CLI only. + +A per-model branch used to give 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. +""" + +from __future__ import annotations + +import unittest +from pathlib import Path + +MODELS = [ + "mlp", + "rnn", + "transformer", + "bottleneck_transformer", + "ehrmamba", + "jambaehr", +] + + +def _runner(): + import importlib.util + + path = ( + Path(__file__).resolve().parents[2] + / "examples" + / "mortality_prediction" + / "unified_embedding_e2e_mimic4.py" + ) + spec = importlib.util.spec_from_file_location( + "unified_e2e_runner_optimizer", path + ) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +class TestOptimizerCliOnly(unittest.TestCase): + def test_defaults_are_model_independent(self): + runner = _runner() + args = runner.parse_args(["--ehr-root", "/tmp/does-not-exist"]) + self.assertEqual(args.lr, 1e-4) + self.assertEqual(args.adam_eps, 1e-8) + self.assertEqual(args.max_grad_norm, 1.0) + + def test_every_backbone_resolves_the_same_settings(self): + runner = _runner() + seen = set() + for model in MODELS: + args = runner.parse_args( + ["--ehr-root", "/tmp/does-not-exist", "--model", model] + ) + lr, clip, params = runner._optimizer_settings(args) + self.assertEqual((lr, clip), (1e-4, 1.0)) + self.assertEqual(params, {"lr": 1e-4, "eps": 1e-8}) + seen.add((lr, clip, params["eps"])) + self.assertEqual(len(seen), 1) + + def test_explicit_flags_still_win(self): + runner = _runner() + args = runner.parse_args( + [ + "--ehr-root", + "/tmp/does-not-exist", + "--model", + "bottleneck_transformer", + "--lr", + "3e-4", + "--adam-eps", + "1e-7", + "--max-grad-norm", + "0.5", + ] + ) + lr, clip, params = runner._optimizer_settings(args) + self.assertEqual((lr, clip, params["eps"]), (3e-4, 0.5, 1e-7)) From 844cd2307a8e34cce08196c66f20fe701c18bf86 Mon Sep 17 00:00:00 2001 From: Rian Date: Thu, 5 Nov 2026 15:49:36 -0500 Subject: [PATCH 08/11] Refuse --amp-dtype without --use-amp. 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 --- .../unified_embedding_e2e_mimic4.py | 24 +++++++- tests/core/test_amp_dtype_flag.py | 58 +++++++++++++++++++ 2 files changed, 79 insertions(+), 3 deletions(-) create mode 100644 tests/core/test_amp_dtype_flag.py diff --git a/examples/mortality_prediction/unified_embedding_e2e_mimic4.py b/examples/mortality_prediction/unified_embedding_e2e_mimic4.py index cf74da1425..f617a8e0cd 100644 --- a/examples/mortality_prediction/unified_embedding_e2e_mimic4.py +++ b/examples/mortality_prediction/unified_embedding_e2e_mimic4.py @@ -628,9 +628,12 @@ def parse_args(argv: Optional[list] = None) -> argparse.Namespace: parser.add_argument( "--amp-dtype", type=str, - default="bf16", + default=None, choices=["bf16", "fp16"], - help="AMP dtype when --use-amp is set. bf16 is more stable (default).", + help=( + "AMP dtype. Requires --use-amp; passing this alone is an error " + "rather than a silently fp32 run. Defaults to bf16 with --use-amp." + ), ) parser.add_argument( "--accumulation-steps", @@ -776,7 +779,22 @@ def parse_args(argv: Optional[list] = None) -> argparse.Namespace: help="Number of Mamba (SSM) layers in JambaEHR.", ) - return parser.parse_args(argv) + args = parser.parse_args(argv) + + # The spec lists --amp-dtype "bf16" and never mentions --use-amp, so + # following it literally used to give a silently fp32 run while the + # config claimed bf16. + if args.amp_dtype is not None and not args.use_amp: + parser.error( + f"--amp-dtype {args.amp_dtype} was passed without --use-amp, so " + "mixed precision would be off and the run would be fp32 while " + "the config claimed otherwise. Pass --use-amp, or drop " + "--amp-dtype." + ) + if args.amp_dtype is None: + args.amp_dtype = "bf16" + + return args def main(argv: Optional[list] = None) -> Path: diff --git a/tests/core/test_amp_dtype_flag.py b/tests/core/test_amp_dtype_flag.py new file mode 100644 index 0000000000..669aa6ba16 --- /dev/null +++ b/tests/core/test_amp_dtype_flag.py @@ -0,0 +1,58 @@ +"""--amp-dtype without --use-amp is a hard error, not a silent fp32 run. + +The flag list says --amp-dtype "bf16" and never mentions --use-amp, so +following it literally ran fp32 while the recorded config claimed bf16. +Passing a dtype alone now fails parsing; omitting it defaults to bf16 for +the run that does pass --use-amp. +""" + +from __future__ import annotations + +import unittest +from pathlib import Path + + +def _runner(): + import importlib.util + + path = ( + Path(__file__).resolve().parents[2] + / "examples" + / "mortality_prediction" + / "unified_embedding_e2e_mimic4.py" + ) + spec = importlib.util.spec_from_file_location( + "unified_e2e_runner_amp", path + ) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +class TestAmpDtypeRequiresUseAmp(unittest.TestCase): + def test_dtype_alone_is_an_error(self): + runner = _runner() + with self.assertRaises(SystemExit): + runner.parse_args( + ["--ehr-root", "/tmp/does-not-exist", "--amp-dtype", "fp16"] + ) + + def test_dtype_defaults_to_bf16(self): + runner = _runner() + args = runner.parse_args(["--ehr-root", "/tmp/does-not-exist"]) + self.assertEqual(args.amp_dtype, "bf16") + self.assertFalse(args.use_amp) + + def test_dtype_with_use_amp_is_accepted(self): + runner = _runner() + args = runner.parse_args( + [ + "--ehr-root", + "/tmp/does-not-exist", + "--use-amp", + "--amp-dtype", + "fp16", + ] + ) + self.assertTrue(args.use_amp) + self.assertEqual(args.amp_dtype, "fp16") From 39456c7ee2d15272c0775fa850efd41fedecebae Mon Sep 17 00:00:00 2001 From: Rian Date: Thu, 5 Nov 2026 20:32:28 -0500 Subject: [PATCH 09/11] Refuse the leaky by-sample fallback unless --allow-leaky-split. 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 --- .../unified_embedding_e2e_mimic4.py | 65 +++++++++----- tests/core/test_paired_runs_eval_split.py | 88 ++++++++++++++++++- 2 files changed, 131 insertions(+), 22 deletions(-) diff --git a/examples/mortality_prediction/unified_embedding_e2e_mimic4.py b/examples/mortality_prediction/unified_embedding_e2e_mimic4.py index f617a8e0cd..c8b3efba93 100644 --- a/examples/mortality_prediction/unified_embedding_e2e_mimic4.py +++ b/examples/mortality_prediction/unified_embedding_e2e_mimic4.py @@ -138,27 +138,38 @@ def _build_task(args: argparse.Namespace): raise ValueError(f"Unknown task: {args.task}") -def _split_dataset(dataset: Any, seed: int) -> Tuple[Any, Any, Any, str]: - """Split by patient, falling back to by-sample only if that yields nothing. - - The fallback is leaky: a patient with several admissions can then land in - both train and test, which inflates the metrics. It only triggers on tiny - cohorts, but it must not trigger silently, so the mode is returned and - recorded alongside the run's results. +def _split_dataset( + dataset: Any, seed: int, allow_leaky_split: bool = False +) -> Tuple[Any, Any, Any, str]: + """Split by patient. Refuse the leaky by-sample fallback unless asked. + + The fallback puts a patient with several admissions in both train and + test, which inflates every metric. A run that cannot be split correctly + stops rather than quietly producing numbers nobody can use. The mode is + returned and recorded alongside the run's results. """ train_ds, val_ds, test_ds = split_by_patient(dataset, [0.8, 0.1, 0.1], seed=seed) - if len(train_ds) == 0 or len(test_ds) == 0: - warnings.warn( - "split_by_patient produced an empty split, falling back to " - "split_by_sample. The same patient may now appear in train and " - "test, so these metrics are optimistic and not comparable to " - "patient-split runs.", - RuntimeWarning, - stacklevel=2, + if len(train_ds) > 0 and len(test_ds) > 0: + return train_ds, val_ds, test_ds, "by_patient" + + if not allow_leaky_split: + raise RuntimeError( + f"split_by_patient produced an empty split (train={len(train_ds)}, " + f"test={len(test_ds)}) on {len(dataset)} samples. The by-sample " + "fallback would put the same patient in train and test, so this " + "run is refused. Widen the cohort, or pass --allow-leaky-split if " + "you are running a smoke test and know the metrics are garbage." ) - train_ds, val_ds, test_ds = split_by_sample(dataset, [0.8, 0.1, 0.1], seed=seed) - return train_ds, val_ds, test_ds, "by_sample_fallback_leaky" - return train_ds, val_ds, test_ds, "by_patient" + + warnings.warn( + "Falling back to split_by_sample at your request. The same patient " + "may now appear in train and test, so these metrics are optimistic " + "and not comparable to patient-split runs.", + RuntimeWarning, + stacklevel=2, + ) + train_ds, val_ds, test_ds = split_by_sample(dataset, [0.8, 0.1, 0.1], seed=seed) + return train_ds, val_ds, test_ds, "by_sample_fallback_leaky" def _window_suffix(observation_window_hours: float) -> str: @@ -386,7 +397,7 @@ def run(args: argparse.Namespace, sample_dataset: Any = None) -> Path: ) train_ds, val_ds, test_ds, split_mode = _split_dataset( - sample_dataset, seed=args.seed + sample_dataset, seed=args.seed, allow_leaky_split=args.allow_leaky_split ) unified = _build_unified_embedding(args, sample_dataset) @@ -431,9 +442,13 @@ 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) + # 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}" + f"{dev_suffix}{window_suffix}{leaky_suffix}" ) output_dir = Path(args.output_dir) @@ -668,6 +683,16 @@ def parse_args(argv: Optional[list] = None) -> argparse.Namespace: default=None, help="Batches each loader worker prefetches (needs --num-workers > 0).", ) + parser.add_argument( + "--allow-leaky-split", + action="store_true", + default=False, + help=( + "Permit the by-sample split fallback when the patient split is " + "empty. The same patient can then land in train and test. Smoke " + "tests only -- the metrics are not usable." + ), + ) parser.add_argument("--seed", type=int, default=42) parser.add_argument("--patience", type=int, default=None) parser.add_argument( diff --git a/tests/core/test_paired_runs_eval_split.py b/tests/core/test_paired_runs_eval_split.py index c8b905fd64..a5b184dd39 100644 --- a/tests/core/test_paired_runs_eval_split.py +++ b/tests/core/test_paired_runs_eval_split.py @@ -74,7 +74,20 @@ def _twenty_patient_samples(): class TestPairedRunsAndEvalSplit(unittest.TestCase): - def test_split_warns_and_labels_leaky_fallback(self): + def test_empty_patient_split_is_refused_by_default(self): + from pyhealth.datasets import create_sample_dataset + + runner = _runner() + dataset = create_sample_dataset( + samples=_single_patient_samples(), + input_schema={"labs": "stagenet_tensor"}, + output_schema={"label": "binary"}, + in_memory=True, + ) + with self.assertRaises(RuntimeError): + runner._split_dataset(dataset, seed=1) + + def test_split_warns_and_labels_allowed_leaky_fallback(self): from pyhealth.datasets import create_sample_dataset runner = _runner() @@ -86,7 +99,9 @@ def test_split_warns_and_labels_leaky_fallback(self): ) with warnings.catch_warnings(record=True) as caught: warnings.simplefilter("always") - train, _val, _test, mode = runner._split_dataset(dataset, seed=1) + train, _val, _test, mode = runner._split_dataset( + dataset, seed=1, allow_leaky_split=True + ) self.assertEqual(mode, "by_sample_fallback_leaky") self.assertTrue( any("split_by_sample" in str(w.message) for w in caught) @@ -197,6 +212,75 @@ def test_run_directory_includes_task_and_records_eval_split(self): {row["eval_split"] for row in rows}, {"test"} ) + def test_run_directory_marks_allow_leaky_split(self): + # The suffix marks the config, not the outcome: it is present + # whenever --allow-leaky-split is passed, whether the patient + # split succeeds (no fallback) or the fallback fires. + import warnings + + from pyhealth.datasets import create_sample_dataset + + runner = _runner() + with TemporaryDirectory() as tmp: + argv = [ + "--ehr-root", + "/tmp/does-not-exist", + "--task", + "labs", + "--model", + "mlp", + "--epochs", + "0", + "--batch-size", + "4", + "--device", + "cpu", + "--seed", + "42", + "--allow-leaky-split", + "--no-cache-frozen-text", + "--output-dir", + tmp, + ] + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + # Single patient: the patient split is empty, fallback fires. + dataset = create_sample_dataset( + samples=_single_patient_samples(), + input_schema={"labs": "stagenet_tensor"}, + output_schema={"label": "binary"}, + dataset_name="test_allow_leaky", + ) + args = Namespace( + **{ + **vars(runner.parse_args(argv)), + "embedding_dim": 8, + "hidden_dim": 8, + } + ) + output_csv = runner.run(args, sample_dataset=dataset) + self.assertIn( + "labs_mlp_seed42_allow_leaky", str(output_csv) + ) + # Twenty patients: the patient split succeeds, no fallback. + dataset = create_sample_dataset( + samples=_twenty_patient_samples(), + input_schema={"labs": "stagenet_tensor"}, + output_schema={"label": "binary"}, + dataset_name="test_allow_leaky_clean", + ) + args = Namespace( + **{ + **vars(runner.parse_args(argv)), + "embedding_dim": 8, + "hidden_dim": 8, + } + ) + output_csv = runner.run(args, sample_dataset=dataset) + self.assertIn( + "labs_mlp_seed42_allow_leaky", str(output_csv) + ) + def test_run_directory_gains_dev_suffix(self): from pyhealth.datasets import create_sample_dataset From d54772de11c346ff7f8e8a5758261fa62d6fefaa Mon Sep 17 00:00:00 2001 From: Rian Date: Thu, 5 Nov 2026 20:33:19 -0500 Subject: [PATCH 10/11] Warn about architecture flags a backbone ignores, and record them. 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 --- .../unified_embedding_e2e_mimic4.py | 83 +++++++++ tests/core/test_inert_arch_flags.py | 164 ++++++++++++++++++ 2 files changed, 247 insertions(+) create mode 100644 tests/core/test_inert_arch_flags.py diff --git a/examples/mortality_prediction/unified_embedding_e2e_mimic4.py b/examples/mortality_prediction/unified_embedding_e2e_mimic4.py index c8b3efba93..66655e4e88 100644 --- a/examples/mortality_prediction/unified_embedding_e2e_mimic4.py +++ b/examples/mortality_prediction/unified_embedding_e2e_mimic4.py @@ -42,6 +42,7 @@ import argparse import csv import json +import logging import time import warnings from pathlib import Path @@ -68,6 +69,8 @@ from pyhealth.trainer import Trainer, _cpu_seconds from pyhealth.utils import set_seed, write_run_config +logger = logging.getLogger(__name__) + class WandbLogger: def __init__( @@ -128,6 +131,76 @@ def _build_base_dataset(args: argparse.Namespace) -> MIMIC4Dataset: ) +# Architecture flags each backbone actually consumes. Anything else the parser +# accepts is inert for that model and is warned about at startup, so a launcher +# can never appear to set something that never reached the model. --dropout is +# absent for mlp on purpose: pyhealth.models.mlp.MLP has no dropout parameter, +# and it takes **kwargs, so passing one is swallowed rather than rejected. +_ARCH_FLAGS_USED: Dict[str, Tuple[str, ...]] = { + "mlp": ("embedding_dim", "hidden_dim"), + "rnn": ( + "embedding_dim", + "hidden_dim", + "dropout", + "rnn_type", + "rnn_layers", + "bidirectional", + ), + "transformer": ("embedding_dim", "dropout", "heads", "num_layers"), + "bottleneck_transformer": ( + "embedding_dim", + "dropout", + "heads", + "num_layers", + "bottlenecks_n", + "fusion_startidx", + ), + "ehrmamba": ( + "embedding_dim", + "dropout", + "num_layers", + "mamba_state_size", + "mamba_conv_kernel", + ), + "jambaehr": ( + "embedding_dim", + "dropout", + "heads", + "mamba_state_size", + "mamba_conv_kernel", + "jamba_transformer_layers", + "jamba_mamba_layers", + ), +} + +_ARCH_FLAGS_ALL: Tuple[str, ...] = tuple( + sorted({flag for flags in _ARCH_FLAGS_USED.values() for flag in flags}) +) + + +def _inert_arch_flags(model: str) -> List[str]: + """Architecture flags this backbone ignores, as CLI spellings.""" + used = set(_ARCH_FLAGS_USED[model]) + return ["--" + f.replace("_", "-") for f in _ARCH_FLAGS_ALL if f not in used] + + +def _nondefault_inert_flags(args: argparse.Namespace) -> List[str]: + """Inert flags the user set to a non-default value, as CLI spellings. + + Compared against a fresh defaults namespace from the same parser, so + only an explicitly (or programmatically) changed value warns. The + full inert list is still recorded in ``run_config.json``. + """ + defaults = vars(parse_args(["--ehr-root", "probe"])) + current = vars(args) + set_flags = [] + for flag in _inert_arch_flags(args.model): + dest = flag[2:].replace("-", "_") + if current.get(dest) != defaults.get(dest): + set_flags.append(flag) + return set_flags + + def _build_task(args: argparse.Namespace): if args.task == "notes_labs": return NotesLabsMIMIC4( @@ -234,6 +307,15 @@ def _build_unified_embedding( def _build_model(args: argparse.Namespace, sample_dataset: Any, unified): + set_inert = _nondefault_inert_flags(args) + if set_inert: + logger.warning( + "%s ignores these flags: %s. Do not read them as settings that " + "took effect.", + args.model, + " ".join(set_inert), + ) + if args.model == "mlp": return MLP( dataset=sample_dataset, @@ -484,6 +566,7 @@ def run(args: argparse.Namespace, sample_dataset: Any = None) -> Path: **vars(args), "split_mode": split_mode, "eval_split": eval_split, + "inert_flags": _inert_arch_flags(args.model), "n_train": len(train_ds), "n_val": len(val_ds), "n_test": len(test_ds), diff --git a/tests/core/test_inert_arch_flags.py b/tests/core/test_inert_arch_flags.py new file mode 100644 index 0000000000..b6513bbbfc --- /dev/null +++ b/tests/core/test_inert_arch_flags.py @@ -0,0 +1,164 @@ +"""Flags a backbone ignores are warned about and recorded. + +A launcher could appear to set something that never reached the model: +MLP has no ``dropout`` parameter and takes ``**kwargs`` (swallowed +silently); JambaEHR ignores ``--num-layers``; transformer/bottleneck/ +ehrmamba/jamba ignore ``--hidden-dim``. The ignored flags are now logged at +startup and stored in ``run_config.json`` next to the resolved settings. +""" + +from __future__ import annotations + +import json +import unittest +from argparse import Namespace +from pathlib import Path +from tempfile import TemporaryDirectory + + +def _runner(): + import importlib.util + + path = ( + Path(__file__).resolve().parents[2] + / "examples" + / "mortality_prediction" + / "unified_embedding_e2e_mimic4.py" + ) + spec = importlib.util.spec_from_file_location( + "unified_e2e_runner_inert", path + ) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def _twenty_patient_samples(): + samples = [] + for i in range(20): + samples.append( + { + "patient_id": f"patient-{i}", + "visit_id": "visit-0", + "labs": ( + [0.0, 2.0], + [[140.0 + i, 1.0], [141.0 + i, 1.1]], + ), + "label": i % 2, + } + ) + return samples + + +class TestInertArchFlags(unittest.TestCase): + def test_map_matches_what_each_backbone_consumes(self): + runner = _runner() + inert = { + model: runner._inert_arch_flags(model) + for model in runner._ARCH_FLAGS_USED + } + self.assertEqual(set(inert), { + "mlp", + "rnn", + "transformer", + "bottleneck_transformer", + "ehrmamba", + "jambaehr", + }) + # Spot-check against the verified model wiring. + self.assertIn("--dropout", inert["mlp"]) + self.assertNotIn("--dropout", inert["rnn"]) + self.assertIn("--num-layers", inert["jambaehr"]) + self.assertNotIn("--num-layers", inert["transformer"]) + self.assertIn("--hidden-dim", inert["transformer"]) + self.assertNotIn("--hidden-dim", inert["mlp"]) + # Every named flag is a real CLI option, so the map cannot drift + # from the parser. + args = runner.parse_args(["--ehr-root", "/tmp/does-not-exist"]) + for flag in runner._ARCH_FLAGS_ALL: + self.assertTrue( + hasattr(args, flag.lstrip("-").replace("-", "_")), flag + ) + + def test_build_model_warns_about_ignored_flags(self): + from pyhealth.datasets import create_sample_dataset + + runner = _runner() + dataset = create_sample_dataset( + samples=_twenty_patient_samples(), + input_schema={"labs": "stagenet_tensor"}, + output_schema={"label": "binary"}, + dataset_name="test_inert", + ) + args = runner.parse_args( + ["--ehr-root", "/tmp/does-not-exist", "--model", "mlp", + "--dropout", "0.5"] + ) + unified = runner._build_unified_embedding(args, dataset) + with self.assertLogs(level="WARNING") as logs: + runner._build_model(args, dataset, unified) + self.assertTrue(any("--dropout" in line for line in logs.output)) + + def test_build_model_stays_silent_at_defaults(self): + # Every backbone ignores some flag, but a user who set nothing + # gets no warning: only non-default inert values warn. + from pyhealth.datasets import create_sample_dataset + + runner = _runner() + dataset = create_sample_dataset( + samples=_twenty_patient_samples(), + input_schema={"labs": "stagenet_tensor"}, + output_schema={"label": "binary"}, + dataset_name="test_inert_silent", + ) + for model in runner._ARCH_FLAGS_USED: + args = runner.parse_args( + ["--ehr-root", "/tmp/does-not-exist", "--model", model] + ) + unified = runner._build_unified_embedding(args, dataset) + with self.assertNoLogs(level="WARNING"): + runner._build_model(args, dataset, unified) + + def test_run_config_records_inert_flags(self): + from pyhealth.datasets import create_sample_dataset + + runner = _runner() + dataset = create_sample_dataset( + samples=_twenty_patient_samples(), + input_schema={"labs": "stagenet_tensor"}, + output_schema={"label": "binary"}, + dataset_name="test_inert_run", + ) + with TemporaryDirectory() as tmp: + args = Namespace( + **{ + **vars( + runner.parse_args( + [ + "--ehr-root", + "/tmp/does-not-exist", + "--model", + "mlp", + "--epochs", + "0", + "--device", + "cpu", + "--seed", + "42", + "--no-cache-frozen-text", + "--output-dir", + tmp, + ] + ) + ), + "embedding_dim": 8, + "hidden_dim": 8, + } + ) + output_csv = runner.run(args, sample_dataset=dataset) + run_config = json.loads( + (Path(output_csv).parent / "run_config.json").read_text() + ) + self.assertIn( + "--dropout", run_config["config"]["inert_flags"] + ) From 4edd18ba2dfa4af97f2adfbf11df68878c92289a Mon Sep 17 00:00:00 2001 From: Rian Date: Sun, 8 Nov 2026 21:31:10 -0500 Subject: [PATCH 11/11] Warn when a mortality run keeps the full stay. 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 --- .../unified_embedding_e2e_mimic4.py | 24 +++ .../core/test_mortality_full_stay_warning.py | 143 ++++++++++++++++++ 2 files changed, 167 insertions(+) create mode 100644 tests/core/test_mortality_full_stay_warning.py diff --git a/examples/mortality_prediction/unified_embedding_e2e_mimic4.py b/examples/mortality_prediction/unified_embedding_e2e_mimic4.py index 66655e4e88..c4a0617d4f 100644 --- a/examples/mortality_prediction/unified_embedding_e2e_mimic4.py +++ b/examples/mortality_prediction/unified_embedding_e2e_mimic4.py @@ -211,6 +211,18 @@ def _build_task(args: argparse.Namespace): raise ValueError(f"Unknown task: {args.task}") +def _is_mortality_task(task: str) -> bool: + """Whether this --task value predicts in-hospital mortality. + + Derived from each task class's ``output_schema`` (both declare + ``{"mortality": "binary"}``), not from the task name alone, so a + future non-mortality task stays silent. + """ + task_classes = {"labs": LabsMIMIC4, "notes_labs": NotesLabsMIMIC4} + task_cls = task_classes.get(task) + return task_cls is not None and "mortality" in task_cls.output_schema + + def _split_dataset( dataset: Any, seed: int, allow_leaky_split: bool = False ) -> Tuple[Any, Any, Any, str]: @@ -467,6 +479,18 @@ def run(args: argparse.Namespace, sample_dataset: Any = None) -> Path: tests). When ``None`` (the CLI path), the MIMIC-IV dataset is loaded from ``args`` roots and the task is applied to it. """ + # A window of 0 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. Warning only: driver arms share this path, so + # they warn here too. + if args.observation_window_hours == 0 and _is_mortality_task(args.task): + logger.warning( + "Task '%s' predicts in-hospital mortality with an observation " + "window of 0: features cover the full stay through discharge, " + "so the label can leak into the inputs. Pass " + "--observation-window-hours to cap collection per admission.", + args.task, + ) set_seed(args.seed) if sample_dataset is None: diff --git a/tests/core/test_mortality_full_stay_warning.py b/tests/core/test_mortality_full_stay_warning.py new file mode 100644 index 0000000000..8fc94ce27a --- /dev/null +++ b/tests/core/test_mortality_full_stay_warning.py @@ -0,0 +1,143 @@ +"""Warn when a mortality run keeps the full stay. + +``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 logs one warning naming the flag that sets +a window. A positive window stays silent, and so does a non-mortality task +(the runner currently offers only mortality tasks, so that case runs +through ``run()`` with a non-mortality task name on a synthetic dataset). +""" + +from __future__ import annotations + +import unittest +from argparse import Namespace +from pathlib import Path +from tempfile import TemporaryDirectory + + +def _runner(): + import importlib.util + + path = ( + Path(__file__).resolve().parents[2] + / "examples" + / "mortality_prediction" + / "unified_embedding_e2e_mimic4.py" + ) + spec = importlib.util.spec_from_file_location( + "unified_e2e_runner_full_stay", path + ) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def _twenty_patient_samples(): + samples = [] + for i in range(20): + samples.append( + { + "patient_id": f"patient-{i}", + "visit_id": "visit-0", + "labs": ( + [0.0, 2.0], + [[140.0 + i, 1.0], [141.0 + i, 1.1]], + ), + "label": i % 2, + } + ) + return samples + + +def _run_args(runner, tmp, task, window_hours): + argv = [ + "--ehr-root", + "/tmp/does-not-exist", + "--model", + "mlp", + "--task", + task, + "--epochs", + "0", + "--device", + "cpu", + "--seed", + "42", + "--no-cache-frozen-text", + "--output-dir", + tmp, + ] + if window_hours != 0: + argv += ["--observation-window-hours", str(window_hours)] + return Namespace( + **{ + **vars(runner.parse_args(argv)), + "embedding_dim": 8, + "hidden_dim": 8, + } + ) + + +class TestMortalityFullStayWarning(unittest.TestCase): + def test_mortality_tasks_come_from_output_schema(self): + runner = _runner() + self.assertTrue(runner._is_mortality_task("labs")) + self.assertTrue(runner._is_mortality_task("notes_labs")) + self.assertFalse(runner._is_mortality_task("length_of_stay")) + + def test_warns_at_zero_for_each_mortality_task(self): + from pyhealth.datasets import create_sample_dataset + + runner = _runner() + for task in ("labs", "notes_labs"): + dataset = create_sample_dataset( + samples=_twenty_patient_samples(), + input_schema={"labs": "stagenet_tensor"}, + output_schema={"label": "binary"}, + dataset_name=f"test_full_stay_{task}", + ) + with TemporaryDirectory() as tmp: + args = _run_args(runner, tmp, task, 0) + with self.assertLogs(level="WARNING") as logs: + runner.run(args, sample_dataset=dataset) + output = "\n".join(logs.output) + self.assertIn("full stay through discharge", output) + self.assertIn("--observation-window-hours", output) + + def test_silent_at_positive_window(self): + from pyhealth.datasets import create_sample_dataset + + runner = _runner() + self.assertTrue(runner._is_mortality_task("labs")) + dataset = create_sample_dataset( + samples=_twenty_patient_samples(), + input_schema={"labs": "stagenet_tensor"}, + output_schema={"label": "binary"}, + dataset_name="test_full_stay_window", + ) + with TemporaryDirectory() as tmp: + args = _run_args(runner, tmp, "labs", 24) + with self.assertNoLogs(level="WARNING"): + runner.run(args, sample_dataset=dataset) + + def test_silent_for_non_mortality_task_at_zero(self): + from pyhealth.datasets import create_sample_dataset + + runner = _runner() + self.assertFalse(runner._is_mortality_task("length_of_stay")) + dataset = create_sample_dataset( + samples=_twenty_patient_samples(), + input_schema={"labs": "stagenet_tensor"}, + output_schema={"label": "binary"}, + dataset_name="test_full_stay_other_task", + ) + with TemporaryDirectory() as tmp: + # No --task value outside the parser choices can reach run() + # from the CLI today; a future non-mortality task would arrive + # as a task name whose class lacks "mortality". + args = _run_args(runner, tmp, "labs", 0) + args.task = "length_of_stay" + with self.assertNoLogs(level="WARNING"): + runner.run(args, sample_dataset=dataset)