diff --git a/examples/mortality_prediction/unified_embedding_e2e_mimic4.py b/examples/mortality_prediction/unified_embedding_e2e_mimic4.py index b095964021..2d2a59508c 100644 --- a/examples/mortality_prediction/unified_embedding_e2e_mimic4.py +++ b/examples/mortality_prediction/unified_embedding_e2e_mimic4.py @@ -41,14 +41,26 @@ import argparse import csv +import gc import json import logging +import math +import os +import resource +import sys +import threading import time import warnings from pathlib import Path from typing import Any, Dict, List, Optional, Tuple import numpy as np +import torch + +try: + import psutil +except ImportError: # pragma: no cover - psutil ships with wandb + psutil = None from pyhealth.datasets import ( MIMIC4Dataset, @@ -391,6 +403,78 @@ def _select_inference_loader(test_loader, val_loader, train_loader): return train_loader, "train" +def _peak_rss_mb() -> float: + """Peak resident set size of this process so far, in MiB. + + ``ru_maxrss`` is in bytes on macOS and in KiB on Linux. + + Example: + >>> isinstance(_peak_rss_mb(), float) + True + """ + peak = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss + return round(peak / 2**20 if sys.platform == "darwin" else peak / 2**10, 1) + + +class _PeakPss: + """Sample the process tree's PSS every ``interval_s`` and keep the peak. + + PSS needs ``memory_full_info().pss`` from psutil, which Linux has and + macOS does not; there ``peak_mb`` stays ``None``. Children are summed + so dataloader workers count, with shared pages split between them. + """ + + def __init__(self, interval_s: float = 0.2) -> None: + self.interval_s = interval_s + self.peak_mb = None + self._stop = threading.Event() + self._thread = threading.Thread(target=self._sample, daemon=True) + + def start(self) -> None: + self._thread.start() + + def stop(self) -> None: + self._stop.set() + self._thread.join() + + def _sample(self) -> None: + if psutil is None: + return + try: + proc = psutil.Process() + while True: + total = 0 + for p in [proc, *proc.children(recursive=True)]: + try: + total += p.memory_full_info().pss + except psutil.NoSuchProcess: + continue + mb = round(total / 2**20, 1) + if self.peak_mb is None or mb > self.peak_mb: + self.peak_mb = mb + if self._stop.wait(self.interval_s): + return + except (AttributeError, psutil.Error): + return + + +def _positive_rate(samples: Any, label_key: str) -> Optional[float]: + """Fraction of positive labels over every sample, to 4 decimals. + + The runner counts the whole cohort before the train/val/test split, so + this is the cohort rate, not a split rate. + + Example: + >>> _positive_rate([{"y": 1}, {"y": 0}, {"y": 0}, {"y": 0}], "y") + 0.25 + """ + total = len(samples) + if total == 0: + return None + positives = sum(float(samples[i][label_key]) for i in range(total)) + return round(positives / total, 4) + + def _build_unified_embedding( args: argparse.Namespace, sample_dataset: Any ) -> UnifiedMultimodalEmbeddingModel: @@ -555,6 +639,72 @@ def epoch_cpu_seconds(self) -> List[Any]: ] +def _reset_cuda_peak_stats(device=None) -> None: + """Reset CUDA peak counters so this run owns its VRAM peaks. + + The experiment driver runs several arms in one process, so the peaks + must be reset at the start of each run: without this, the second arm + would inherit the first arm's maxima. + + Args: + device: The run's ``--device`` flag. The peaks are reset on + that device; ``None`` (or a non-CUDA flag) keeps the + current device. + """ + if torch.cuda.is_available(): + if device is None or str(device).split(":")[0] == "cuda": + cuda_device = device + else: + cuda_device = None + torch.cuda.reset_peak_memory_stats(cuda_device) + + +def _collect_hardware(device: Optional[str]) -> Dict[str, Any]: + """Record GPU identity, thread pinning, and peak VRAM for this run. + + Args: + device: The runner's ``--device`` flag. ``None`` means the + Trainer picks cuda when available, cpu otherwise. + + Returns: + A ``hardware`` mapping for ``metrics.json``: ``gpu_model`` (the + device name from torch, or ``"cpu"``), ``gpu_count`` (1 on GPU, 0 + on CPU — the run uses one device, not every visible one), + ``thread_pinning`` (the ``OMP_NUM_THREADS`` value, or + ``"unset"``), and the CUDA allocated/reserved peaks in MB (null + on CPU). Peaks come from ``torch.cuda`` counters, never + nvidia-smi. + + Example: + >>> hw = _collect_hardware("cpu") + >>> (hw["gpu_model"], hw["gpu_count"], hw["vram_allocated_peak_mb"]) + ('cpu', 0, None) + """ + thread_pinning = os.environ.get("OMP_NUM_THREADS", "unset") + use_cuda = torch.cuda.is_available() and ( + device is None or str(device).split(":")[0] == "cuda" + ) + if not use_cuda: + return { + "gpu_model": "cpu", + "gpu_count": 0, + "thread_pinning": thread_pinning, + "vram_allocated_peak_mb": None, + "vram_reserved_peak_mb": None, + } + return { + "gpu_model": torch.cuda.get_device_name(device), + "gpu_count": 1, + "thread_pinning": thread_pinning, + "vram_allocated_peak_mb": round( + torch.cuda.max_memory_allocated(device) / 2**20, 2 + ), + "vram_reserved_peak_mb": round( + torch.cuda.max_memory_reserved(device) / 2**20, 2 + ), + } + + def run(args: argparse.Namespace, sample_dataset: Any = None) -> Path: """Run the end-to-end protocol and write predictions + metrics. @@ -578,6 +728,13 @@ def run(args: argparse.Namespace, sample_dataset: Any = None) -> Path: ) set_seed(args.seed) _require_build_workers(args, sample_dataset) + gc.collect() + if torch.cuda.is_available(): + torch.cuda.empty_cache() + _reset_cuda_peak_stats(args.device) + # Record "no drop" as an empty list (not null) so collected rows can + # compare on it; the driver full arm already means it this way. + args.drop_modality = args.drop_modality or [] if sample_dataset is None: base_dataset = _build_base_dataset(args) @@ -687,6 +844,9 @@ def run(args: argparse.Namespace, sample_dataset: Any = None) -> Path: epoch_train_seconds: List[float] = [] epoch_train_cpu_seconds: List[Any] = [] + val_pr_auc_best = None + pss = _PeakPss() + pss.start() if args.epochs > 0 and len(train_ds) > 0: trainer.train( train_dataloader=timed_train_loader, @@ -704,6 +864,8 @@ def run(args: argparse.Namespace, sample_dataset: Any = None) -> Path: ) epoch_train_seconds = timed_train_loader.epoch_seconds() epoch_train_cpu_seconds = timed_train_loader.epoch_cpu_seconds() + if math.isfinite(trainer.best_score): + val_pr_auc_best = trainer.best_score train_cpu_seconds = ( round(sum(v for v in epoch_train_cpu_seconds if v is not None), 2) @@ -729,6 +891,7 @@ def run(args: argparse.Namespace, sample_dataset: Any = None) -> Path: inference_loader, return_patient_ids=True ) inference_seconds = time.perf_counter() - inference_start + pss.stop() # metrics.json carries validation only, so without this the test numbers # worth reporting live nowhere on disk: only in stdout and W&B, and @@ -741,8 +904,19 @@ def run(args: argparse.Namespace, sample_dataset: Any = None) -> Path: output_csv = output_dir / exp_name / f"predictions_{args.model}.csv" _write_predictions(output_csv, patient_ids, y_true, y_prob, eval_split) + note_processor = sample_dataset.input_processors.get("admission_note_times") + label_key = next(iter(sample_dataset.output_processors)) metrics = { "config": vars(args), + "hardware": { + **_collect_hardware(args.device), + "peak_rss_mb": _peak_rss_mb(), + "peak_pss_mb": pss.peak_mb, + }, + "note_length": getattr(note_processor, "max_length", None), + "text_encoder": getattr(note_processor, "tokenizer_model", None), + "positive_rate": _positive_rate(sample_dataset, label_key), + "val_pr_auc_best": val_pr_auc_best, "split": { "train": len(train_ds), "val": len(val_ds), diff --git a/pyhealth/models/unified_embedding.py b/pyhealth/models/unified_embedding.py index 623013fbd5..a29e73a5c5 100644 --- a/pyhealth/models/unified_embedding.py +++ b/pyhealth/models/unified_embedding.py @@ -482,20 +482,26 @@ def frozen_text_cache_size(self) -> int: @property def frozen_text_cache_stats(self) -> dict[str, int]: - """Cache ``hits``, ``misses``, and ``size`` for the A/B timing run. + """Cache ``hits``, ``misses``, ``size``, and ``bytes`` for the A/B run. Misses count rows not cached before this forward (including duplicates and overflow rows served from the current forward); - hits count rows served from the cache. + hits count rows served from the cache. ``bytes`` is the tensor + storage of the cached vectors (0 when the cache is empty). Example: >>> sorted(model.frozen_text_cache_stats) - ['hits', 'misses', 'size'] + ['bytes', 'hits', 'misses', 'size'] """ return { "hits": self._frozen_text_cache_hits, "misses": self._frozen_text_cache_misses, "size": self.frozen_text_cache_size, + "bytes": sum( + v.element_size() * v.nelement() + for c in self._frozen_text_cache.values() + for v in c.values() + ), } def reset_frozen_text_cache_stats(self) -> None: diff --git a/pyhealth/trainer.py b/pyhealth/trainer.py index 337860844c..24116833d2 100644 --- a/pyhealth/trainer.py +++ b/pyhealth/trainer.py @@ -521,6 +521,8 @@ def train( ) break + self.best_score = best_score + # load best model if load_best_model_at_last and self.exp_path is not None and os.path.isfile( os.path.join(self.exp_path, "best.ckpt")): diff --git a/pyhealth/utils.py b/pyhealth/utils.py index 8c361f4392..5045a4380e 100644 --- a/pyhealth/utils.py +++ b/pyhealth/utils.py @@ -232,6 +232,16 @@ def save_json(data, filename): def _git_revision(): + """Return the ``commit`` (HEAD) and ``dirty`` flags of the package's checkout. + + Both are ``None`` when the package is not inside a git checkout (a tarball + or an installed copy). ``run_config.json`` then records them as null, and + the run-stats collector leaves ``tree_sha`` and ``dirty`` missing. + + Example: + >>> sorted(_git_revision()) + ['commit', 'dirty'] + """ repo = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) try: commit = subprocess.check_output( diff --git a/tests/core/test_collect_run_stats.py b/tests/core/test_collect_run_stats.py new file mode 100644 index 0000000000..a14ad7de13 --- /dev/null +++ b/tests/core/test_collect_run_stats.py @@ -0,0 +1,291 @@ +"""Synthetic run-directory tests for tools/collect_run_stats.py (CPU, seconds).""" + +import csv +import json +import os +import sys +import tempfile +import unittest + +REPO_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +sys.path.insert(0, os.path.join(REPO_ROOT, "tools")) + +import collect_run_stats as crs + + +def _rich_run(root, seed=1): + os.makedirs(root, exist_ok=True) + with open(os.path.join(root, "run_config.json"), "w") as f: + json.dump({ + "config": { + "task": "notes_labs", "backbone": "transformer", + "embedding_dim": 128, "hidden_dim": 128, "num_layers": 2, + "heads": 4, "batch_size": 32, "use_amp": True, + "amp_dtype": "bf16", "freeze_encoder": True, + "seed": seed, "window_hours": 0, + "thread_pinning": "OMP_NUM_THREADS=8", + "drop_modality": [], "lr": 1e-4, "adam_eps": 1e-8, + "max_grad_norm": 1.0, "dev": 0, + "split_mode": "by_patient", "eval_split": "test", + "cache_frozen_text": True, + }, + "git": {"commit": "0" * 40, "dirty": False}, + "source_sha256": "abc", + "torch": "2.7.1+cu126", + }, f) + with open(os.path.join(root, "metrics.json"), "w") as f: + json.dump({ + "split": {"train": 144586, "val": 18073, "test": 18074}, + "epoch_train_seconds": [1712.2, 438.6, 428.6], + "eval_seconds": 484.7, + "inference_seconds": 45.1, + "frozen_text_cache": {"hits": 2110152, "misses": 922908, + "size": 921814}, + "gpu_model": "NVIDIA RTX 6000 Ada Generation", + "gpu_count": 1, + }, f) + with open(os.path.join(root, "test_metrics.json"), "w") as f: + json.dump({"pr_auc": 0.58939, "roc_auc": 0.90715}, f) + with open(os.path.join(root, "metrics_history.json"), "w") as f: + json.dump([ + {"train_cpu_seconds": 4000.0, "train_cpu_util_pct": 233.0, + "train_vram_allocated_mb": 6500.0, "train_vram_peak_mb": 6900.0}, + {"train_cpu_seconds": 1000.0, "train_cpu_util_pct": 228.0, + "train_vram_allocated_mb": 6600.0, "train_vram_peak_mb": 6950.0}, + ], f) + return root + + +def _thin_run(root): + # Older-style aggregates only: no run_config, no test persistence. + os.makedirs(root, exist_ok=True) + with open(os.path.join(root, "metrics.json"), "w") as f: + json.dump({ + "split": {"train": 144586, "val": 18073, "test": 18074}, + "epoch_train_seconds": [1681.6, 1717.7, 1707.7], + "inference_seconds": 530.0, + "test_scores": {"pr_auc": 0.58968, "roc_auc": 0.90714}, + }, f) + return root + + +class TestCollectRunStats(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.rich = _rich_run(os.path.join(self.tmp.name, "on")) + self.thin = _thin_run(os.path.join(self.tmp.name, "off")) + + def tearDown(self): + self.tmp.cleanup() + + def test_rich_row_filled_and_throughput(self): + row = crs.collect_run(self.rich) + self.assertEqual(row["tree_sha"], "0" * 40) + self.assertEqual(row["source_sha256"], "abc") + self.assertEqual(row["dirty"], False) + self.assertEqual(row["cache_hits"], 2110152) + self.assertEqual(row["test_pr_auc"], 0.58939) + self.assertEqual(row["vram_allocated_peak_mb"], 6600.0) + self.assertEqual(row["train_cpu_seconds_total"], 5000.0) + # Train throughput uses the train split over summed epoch walls. + self.assertAlmostEqual(row["throughput_train_pts_per_s"], + 144586 / (1712.2 + 438.6 + 428.6), places=6) + self.assertAlmostEqual(row["throughput_infer_pts_per_s"], + 18074 / 45.1, places=6) + + def test_thin_row_missing_listed_never_inferred(self): + row = crs.collect_run(self.thin) + missing = row["missing_fields"].split(";") + for field in ("tree_sha", "source_sha256", "seed", "task", + "backbone", "gpu_model", + "cache_hits", "eval_s", "peak_pss_mb", + "train_cpu_seconds_total"): + self.assertIn(field, missing) + self.assertIsNone(row[field]) + # Present aggregates still collected. + self.assertEqual(row["test_pr_auc"], 0.58968) + self.assertEqual(row["split_test"], 18074) + + def test_nested_config_read(self): + # Older metrics.json nests the protocol under "config". + nested = os.path.join(self.tmp.name, "nested") + os.makedirs(nested, exist_ok=True) + with open(os.path.join(nested, "metrics.json"), "w") as f: + json.dump({"config": {"task": "labs", "model": "rnn", + "seed": 2, "use_amp": False}, + "split": {"train": 10, "val": 2, "test": 2}, + "epoch_train_seconds": [5.0], + "inference_seconds": 1.0}, f) + row = crs.collect_run(nested) + self.assertEqual(row["task"], "labs") + self.assertEqual(row["backbone"], "rnn") + self.assertEqual(row["seed"], 2) + self.assertEqual(row["use_amp"], False) + + def test_pairs_flagged(self): + rich = crs.collect_run(self.rich) + same = crs.collect_run(self.rich) + self.assertEqual(crs.check_pair(rich, same), "comparable") + other_seed = crs.collect_run( + _rich_run(os.path.join(self.tmp.name, "on2"), seed=2)) + verdict = crs.check_pair(rich, other_seed) + self.assertTrue(verdict.startswith("NON-COMPARABLE")) + self.assertIn("seed", verdict) + thin = crs.collect_run(self.thin) + self.assertTrue(crs.check_pair(rich, thin).startswith("UNVERIFIABLE")) + + def test_write_outputs_roundtrip(self): + rows = [crs.collect_run(self.rich), crs.collect_run(self.thin)] + prefix = os.path.join(self.tmp.name, "rows") + csv_path, md_path = crs.write_outputs(rows, prefix) + with open(csv_path) as f: + read = list(csv.DictReader(f)) + self.assertEqual(len(read), 2) + self.assertEqual(read[0]["test_pr_auc"], "0.58939") + with open(md_path) as f: + md = f.read() + self.assertIn("## Pairwise comparability", md) + # Rich vs thin share no compare-field coverage: unverifiable. + self.assertIn("UNVERIFIABLE", md) + + +def _runner(): + import importlib.util + from pathlib import Path + + path = (Path(REPO_ROOT) / "examples" / "mortality_prediction" + / "unified_embedding_e2e_mimic4.py") + spec = importlib.util.spec_from_file_location("unified_e2e_runner", path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +class TestCollectRealRun(unittest.TestCase): + """Collector against a real demo-fixture run directory (labs, mlp, CPU). + + The synthetic tests above pin the schema; this one proves the field + names the runner actually writes land in the right columns, and + records which standard fields a real run still leaves missing. + """ + + def test_real_run_fields_and_missing(self): + from pathlib import Path as _Path + + runner = _runner() + demo = _Path(REPO_ROOT) / "test-resources" / "core" / "mimic4demo" + with tempfile.TemporaryDirectory() as tmp: + args = runner.parse_args( + ["--ehr-root", str(demo), "--task", "labs", "--model", "mlp", + "--epochs", "1", "--batch-size", "8", "--embedding-dim", "8", + "--hidden-dim", "8", "--device", "cpu", "--seed", "2", + "--no-cache-frozen-text", + "--cache-dir", str(_Path(tmp) / "cache"), + "--num-workers", "1", + "--output-dir", str(_Path(tmp) / "out")] + ) + run_dir = _Path(runner.run(args)).parent + row = crs.collect_run(str(run_dir)) + # Runner-written fields land in their columns. + self.assertEqual(row["task"], "labs") + self.assertEqual(row["backbone"], "mlp") + self.assertEqual(row["seed"], 2) + if (_Path(REPO_ROOT) / ".git").exists(): + self.assertIsNotNone(row["tree_sha"]) + self.assertIn(row["dirty"], (True, False)) + else: + # Archived trees carry no git metadata: the collector + # reports the fields missing instead of inventing them. + self.assertIsNone(row["tree_sha"]) + self.assertIsNone(row["dirty"]) + self.assertGreater(row["split_train"], 0) + self.assertIsNotNone(row["train_cpu_seconds_total"]) + self.assertIsNotNone(row["train_cpu_util_pct_mean"]) + self.assertEqual( + (row["cache_hits"], row["cache_misses"], row["cache_entries"]), + (0, 0, 0)) + self.assertIsNotNone(row["test_pr_auc"]) + # Hardware now comes from the runner's hardware object. + self.assertEqual(row["gpu_model"], "cpu") + self.assertEqual(row["gpu_count"], 0) + self.assertIsNotNone(row["thread_pinning"]) + # New protocol fields land from a real run. + self.assertEqual(row["drop_modality"], []) + self.assertEqual(row["lr"], 1e-4) + self.assertEqual(row["split_mode"], "by_patient") + self.assertEqual(row["eval_split"], "test") + # Standard fields a labs run on CPU still leaves missing: the + # note-text fields (no note processor) and the GPU VRAM peaks. + missing = row["missing_fields"].split(";") + expected = ["note_length", "text_encoder", + "vram_allocated_peak_mb", "vram_reserved_peak_mb"] + present = ["positive_rate", "val_pr_auc_best", "peak_rss_mb", + "cache_bytes"] + # PSS needs psutil's memory_full_info().pss, which macOS lacks. + (expected if sys.platform == "darwin" else present).append( + "peak_pss_mb") + if not (_Path(REPO_ROOT) / ".git").exists(): + expected += ["tree_sha", "dirty"] + for field in expected: + self.assertIn(field, missing, field) + for field in present: + self.assertNotIn(field, missing, field) + for field in ("gpu_model", "gpu_count", "thread_pinning", + "drop_modality", "lr", "adam_eps", + "max_grad_norm", "dev", "split_mode", + "eval_split", "cache_frozen_text", + "source_sha256"): + self.assertNotIn(field, missing, field) + + +class TestCollectRealPair(unittest.TestCase): + """Comparability on two real demo-fixture run directories. + + Same config compares; an --lr change is NON-COMPARABLE naming lr. + Code identity travels with the runs (run_config.json's + source_sha256, written on git and archive trees alike), so the + pair verdicts run on every tree. + """ + + def test_real_pair_same_config_comparable_lr_names_field(self): + from pathlib import Path as _Path + + runner = _runner() + demo = _Path(REPO_ROOT) / "test-resources" / "core" / "mimic4demo" + + def _run(tmp, name, extra=()): + args = runner.parse_args( + ["--ehr-root", str(demo), "--task", "labs", "--model", "mlp", + "--epochs", "1", "--batch-size", "8", "--embedding-dim", "8", + "--hidden-dim", "8", "--device", "cpu", "--seed", "2", + "--no-cache-frozen-text", + "--cache-dir", str(_Path(tmp) / "cache"), + "--num-workers", "1", + "--output-dir", str(_Path(tmp) / name), *extra] + ) + return str(_Path(runner.run(args)).parent) + + with tempfile.TemporaryDirectory() as tmp: + run_a = _run(tmp, "a") + run_b = _run(tmp, "b") + run_c = _run(tmp, "c", ("--lr", "0.001")) + row_a = crs.collect_run(run_a) + row_b = crs.collect_run(run_b) + row_c = crs.collect_run(run_c) + fields = ("drop_modality", "lr", "adam_eps", "max_grad_norm", + "dev", "split_mode", "eval_split", + "cache_frozen_text", "gpu_model", "gpu_count", + "thread_pinning", "source_sha256") + for field in fields: + self.assertEqual(row_a[field], row_b[field], field) + self.assertIsNotNone(row_a[field], field) + self.assertNotEqual(row_a["lr"], row_c["lr"]) + self.assertEqual(crs.check_pair(row_a, row_b), "comparable") + verdict = crs.check_pair(row_a, row_c) + self.assertTrue(verdict.startswith("NON-COMPARABLE"), verdict) + differed = verdict.split("differ ", 1)[1].split(",") + self.assertIn("lr", differed) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/core/test_run_stats_fields.py b/tests/core/test_run_stats_fields.py new file mode 100644 index 0000000000..ffe63469b7 --- /dev/null +++ b/tests/core/test_run_stats_fields.py @@ -0,0 +1,50 @@ +"""Run-stats fields recorded by the unified cache and the run config.""" + +import unittest +from types import SimpleNamespace + +import torch + +from pyhealth.models.unified_embedding import UnifiedMultimodalEmbeddingModel +from pyhealth.utils import _git_revision + + +class FrozenTextCacheBytesTest(unittest.TestCase): + def test_bytes_is_the_storage_of_cached_vectors(self): + # The property reads only these attributes, so a stub stands in for + # the model and the test builds no encoder. + cache = SimpleNamespace( + _frozen_text_cache={ + "notes": { + (0, 0): torch.zeros(4), # float32: 4 * 4 bytes + (0, 1): torch.zeros(2, dtype=torch.float16), # 2 * 2 bytes + } + }, + _frozen_text_cache_hits=3, + _frozen_text_cache_misses=2, + frozen_text_cache_size=2, + ) + stats = UnifiedMultimodalEmbeddingModel.frozen_text_cache_stats.fget(cache) + self.assertEqual(stats["bytes"], 20) + self.assertEqual(stats["size"], 2) + + def test_empty_cache_has_zero_bytes(self): + cache = SimpleNamespace( + _frozen_text_cache={}, + _frozen_text_cache_hits=0, + _frozen_text_cache_misses=0, + frozen_text_cache_size=0, + ) + stats = UnifiedMultimodalEmbeddingModel.frozen_text_cache_stats.fget(cache) + self.assertEqual(stats["bytes"], 0) + + +class GitRevisionFieldsTest(unittest.TestCase): + def test_commit_and_dirty_are_recorded_as_keys(self): + revision = _git_revision() + self.assertEqual(set(revision), {"commit", "dirty"}) + self.assertTrue(revision["commit"] is None or len(revision["commit"]) == 40) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/core/test_unified_cache.py b/tests/core/test_unified_cache.py index 7c03a15b90..8f28317f65 100644 --- a/tests/core/test_unified_cache.py +++ b/tests/core/test_unified_cache.py @@ -104,17 +104,17 @@ def test_counters_track_hits_and_misses(self): model._encode_text_cls("notes", enc, ids, None) self.assertEqual( model.frozen_text_cache_stats, - {"hits": 0, "misses": 2, "size": 2}, + {"hits": 0, "misses": 2, "size": 2, "bytes": 64}, ) model._encode_text_cls("notes", enc, ids, None) self.assertEqual( model.frozen_text_cache_stats, - {"hits": 2, "misses": 2, "size": 2}, + {"hits": 2, "misses": 2, "size": 2, "bytes": 64}, ) model.reset_frozen_text_cache_stats() self.assertEqual( model.frozen_text_cache_stats, - {"hits": 0, "misses": 0, "size": 2}, + {"hits": 0, "misses": 0, "size": 2, "bytes": 64}, ) def test_shuffled_row_order_still_hits(self): diff --git a/tests/core/test_unified_e2e_runner.py b/tests/core/test_unified_e2e_runner.py index a234475c89..ac6b7b6bb0 100644 --- a/tests/core/test_unified_e2e_runner.py +++ b/tests/core/test_unified_e2e_runner.py @@ -10,6 +10,7 @@ from argparse import Namespace from pathlib import Path from tempfile import TemporaryDirectory +from unittest import mock import torch @@ -229,9 +230,14 @@ def test_synthetic_end_to_end(self): self.assertGreaterEqual(metrics["inference_seconds"], 0.0) self.assertEqual( sorted(metrics["frozen_text_cache"]), - ["hits", "misses", "size"], + ["bytes", "hits", "misses", "size"], ) self.assertTrue(torch.isfinite(torch.tensor(metrics["eval_seconds"]))) + self.assertGreater(metrics["hardware"]["peak_rss_mb"], 0) + self.assertEqual(metrics["positive_rate"], round( + sum(s["label"] for s in _samples()) / len(_samples()), 4)) + if metrics["split"]["val"] > 0: + self.assertIsInstance(metrics["val_pr_auc_best"], float) DEMO_ROOT = ( @@ -240,6 +246,7 @@ def test_synthetic_end_to_end(self): _EXPECTED_METRICS_KEYS = ( "config", + "hardware", "split", "epoch_train_seconds", "epoch_train_cpu_seconds", @@ -248,7 +255,10 @@ def test_synthetic_end_to_end(self): "eval_seconds", "inference_seconds", "frozen_text_cache", - "test_scores", + "test_scores", "note_length", + "text_encoder", + "positive_rate", + "val_pr_auc_best", ) @@ -331,7 +341,7 @@ def _assert_demo_metrics(testcase, output_csv): torch.isfinite(torch.tensor(float(metrics["inference_seconds"]))).item() ) testcase.assertEqual( - sorted(metrics["frozen_text_cache"]), ["hits", "misses", "size"] + sorted(metrics["frozen_text_cache"]), ["bytes", "hits", "misses", "size"] ) testcase.assertGreater(metrics["split"]["train"], 0) for v in metrics["test_scores"].values(): @@ -448,3 +458,139 @@ def _write(path, rows): if __name__ == "__main__": unittest.main() + + +class TestCudaPeakDevice(unittest.TestCase): + """VRAM peaks are read and reset on the run's device. + + ``torch.cuda`` is mocked here: the device must reach + ``max_memory_allocated``, ``max_memory_reserved`` and + ``reset_peak_memory_stats``, and the allocator cache (``empty_cache``) + must be cleared before the reset so arms sharing one process do not + inherit reserved peaks. + """ + + def test_peaks_read_on_run_device(self): + runner = _runner() + cuda = runner.torch.cuda + with ( + mock.patch.object(cuda, "is_available", return_value=True), + mock.patch.object( + cuda, "get_device_name", return_value="cuda:2"), + mock.patch.object( + cuda, "max_memory_allocated", + return_value=2**20) as max_a, + mock.patch.object( + cuda, "max_memory_reserved", + return_value=2 * 2**20) as max_r, + ): + hw = runner._collect_hardware("cuda:2") + max_a.assert_called_once_with("cuda:2") + max_r.assert_called_once_with("cuda:2") + self.assertEqual(hw["vram_allocated_peak_mb"], 1.0) + self.assertEqual(hw["vram_reserved_peak_mb"], 2.0) + + def test_reset_uses_run_device(self): + runner = _runner() + cuda = runner.torch.cuda + with ( + mock.patch.object(cuda, "is_available", return_value=True), + mock.patch.object( + cuda, "reset_peak_memory_stats") as reset, + ): + runner._reset_cuda_peak_stats("cuda:2") + reset.assert_called_once_with("cuda:2") + reset.reset_mock() + runner._reset_cuda_peak_stats(None) + reset.assert_called_once_with(None) + reset.reset_mock() + runner._reset_cuda_peak_stats("cpu") + reset.assert_called_once_with(None) + + def test_empty_cache_runs_before_reset(self): + from pyhealth.datasets import create_sample_dataset + + runner = _runner() + cuda = runner.torch.cuda + with ( + mock.patch.object(cuda, "is_available", return_value=True), + mock.patch.object(cuda, "manual_seed"), + mock.patch.object(cuda, "manual_seed_all"), + mock.patch.object(cuda, "empty_cache") as empty, + mock.patch.object(cuda, "reset_peak_memory_stats") as reset, + mock.patch.object( + cuda, "max_memory_allocated", return_value=2**20), + mock.patch.object( + cuda, "max_memory_reserved", return_value=2**20), + mock.patch.object( + cuda, "get_device_name", return_value="cpu"), + ): + calls = mock.Mock() + calls.attach_mock(empty, "empty_cache") + calls.attach_mock(reset, "reset_peak_memory_stats") + dataset = create_sample_dataset( + samples=_samples(), + input_schema={"labs": "stagenet_tensor"}, + output_schema={"label": "binary"}, + dataset_name="test_vram_order_synthetic", + ) + with TemporaryDirectory() as tmp: + args = Namespace( + **{ + **vars( + runner.parse_args( + [ + "--ehr-root", + "/tmp/does-not-exist", + "--model", + "mlp", + # No training: the order check needs + # only run()'s setup, and no optimizer + # step means no CUDA health check. + "--epochs", + "0", + "--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.assertTrue(Path(output_csv).is_file()) + order = [c[0] for c in calls.mock_calls] + self.assertIn("empty_cache", order) + self.assertIn("reset_peak_memory_stats", order) + self.assertLess( + order.index("empty_cache"), + order.index("reset_peak_memory_stats"), + ) + reset.assert_called_with(None) + + +class RunStatsHelperTest(unittest.TestCase): + def test_positive_rate_counts_the_whole_cohort(self): + runner = _runner() + samples = [{"y": 1}, {"y": 0}, {"y": 0}, {"y": 0}, {"y": 0}] + self.assertEqual(runner._positive_rate(samples, "y"), 0.2) + self.assertIsNone(runner._positive_rate([], "y")) + + def test_peak_rss_is_positive_mib(self): + runner = _runner() + self.assertGreater(runner._peak_rss_mb(), 0) + + def test_peak_pss_is_none_or_a_positive_sample(self): + runner = _runner() + sampler = runner._PeakPss(interval_s=0.01) + sampler.start() + sampler.stop() + self.assertTrue(sampler.peak_mb is None or sampler.peak_mb > 0) diff --git a/tools/collect_run_stats.py b/tools/collect_run_stats.py new file mode 100644 index 0000000000..777751207a --- /dev/null +++ b/tools/collect_run_stats.py @@ -0,0 +1,330 @@ +"""Collect one standard-schema stats row per run directory. + +Reads run directories (metrics.json, run_config.json, test_metrics.json, +metrics_history.json — whichever are present) and writes one row per run +in the standard run-stats schema, as CSV and Markdown. A field that is +absent stays missing and is listed; nothing is defaulted or inferred. +Code identity comes from ``run_config.json``'s ``source_sha256``, +written on git and archive trees alike; the digest covers the +``pyhealth`` package only, not ``examples/``. ``tree_sha`` is still +collected when git metadata exists, but it is not compared. + +Comparability follows the run-identity rule: every pair of runs is +checked on the protocol and hardware fields both runs record, and pairs +that fail (or cannot be checked) are flagged with the reason. + +Examples: + >>> import collect_run_stats as c + >>> row = c.collect_run("output/arm_on/transformer_seed1") + >>> isinstance(row["missing_fields"], str) + True + +Usage: + python tools/collect_run_stats.py RUN_DIR [RUN_DIR ...] --out PREFIX +""" + +from __future__ import annotations + +import argparse +import csv +import json +import sys +from pathlib import Path + +# Run-identity and protocol fields two runs must share to be comparable. +COMPARE_FIELDS = [ + "source_sha256", + "task", + "backbone", + "window_hours", + "embedding_dim", + "hidden_dim", + "n_layers", + "heads", + "batch_size", + "use_amp", + "amp_dtype", + "freeze_encoder", + "seed", + "gpu_model", + "thread_pinning", + "drop_modality", + "lr", + "adam_eps", + "max_grad_norm", + "dev", + "split_mode", + "eval_split", + "cache_frozen_text", +] + + +def _read_json(path: Path): + try: + with open(path) as f: + return json.load(f) + except (OSError, ValueError): + return None + + +def _get(mapping, *keys, default=None): + for key in keys: + if isinstance(mapping, dict) and key in mapping: + return mapping[key] + return default + + +def _num(value): + try: + return float(value) + except (TypeError, ValueError): + return None + + +def collect_run(run_dir: str | Path) -> dict: + """Collect one schema row from a run directory. + + Args: + run_dir: path to a run directory holding metrics.json and, + when the runner records them, run_config.json, + test_metrics.json, and metrics_history.json. + + Returns: + A dict with one entry per schema field; absent fields hold + None and are named in ``missing_fields`` (semicolon-joined). + No field is defaulted or inferred. + + Examples: + >>> row = collect_run("output/arm_on/transformer_seed1") + >>> isinstance(row["missing_fields"], str) + True + >>> row["missing_fields"].split(";")[0] in row + True + """ + root = Path(run_dir) + metrics = _read_json(root / "metrics.json") or {} + run_config = _read_json(root / "run_config.json") or {} + test_metrics = _read_json(root / "test_metrics.json") or {} + history = _read_json(root / "metrics_history.json") + if isinstance(history, dict): + history = history.get("epochs", history.get("history", [])) + if not isinstance(history, list): + history = [] + + config = run_config.get("config", {}) if isinstance(run_config, dict) else {} + git = run_config.get("git", {}) if isinstance(run_config, dict) else {} + blob = metrics if isinstance(metrics, dict) else {} + # Older runs nest the protocol under their own "config" key. + blob_config = blob.get("config") if isinstance(blob.get("config"), dict) else {} + # The runner records GPU identity, thread pinning, and VRAM peaks in a + # nested hardware object; older layouts only have flat keys, which the + # same picks below still find. + hw = blob.get("hardware") if isinstance(blob.get("hardware"), dict) else {} + + def pick(*names): + for source in (hw, blob, blob_config, config): + value = _get(source, *names) + if value is not None: + return value + return None + + split = pick("split") or {} + cache = pick("frozen_text_cache", "text_cache") or {} + scores = pick("test_scores", "test") or {} + if not isinstance(scores, dict) and isinstance(test_metrics, dict): + scores = test_metrics + elif isinstance(test_metrics, dict): + scores = {**scores, **{k: v for k, v in test_metrics.items() if k not in scores}} + + epochs = pick("epoch_train_seconds", "train_epoch_s") or [] + if not isinstance(epochs, list): + epochs = [] + warm = [_num(e) for e in epochs[1:]] + warm = [e for e in warm if e is not None] + eval_s = _num(pick("eval_seconds", "eval_s")) + infer_s = _num(pick("inference_seconds", "inference_s")) + n_train = _num(split.get("train")) if isinstance(split, dict) else None + n_test = _num(split.get("test")) if isinstance(split, dict) else None + + train_cpu, cpu_utils, vram_alloc, vram_res = [], [], [], [] + for e in history: + if not isinstance(e, dict): + continue + for target, keys in ( + (train_cpu, ("train_cpu_seconds",)), + (cpu_utils, ("train_cpu_util_pct",)), + (vram_alloc, ("train_vram_allocated_mb", "vram_allocated_mb")), + (vram_res, ("train_vram_peak_mb", "vram_peak_mb")), + ): + for k in keys: + v = _num(e.get(k)) + if v is not None: + target.append(v) + break + + pin = pick("thread_pinning", "omp_num_threads", "OMP_NUM_THREADS") + + # The runner records CPU totals at the metrics top level (plus per-epoch + # lists and a frozen-cache cap in the recorded config); per-epoch + # history files are an older layout and only fill in when present. + cache_cap = cache.get("cap", cache.get("max_entries")) \ + if isinstance(cache, dict) else None + + row = { + "run_dir": str(root), + "tree_sha": _get(git, "commit", "sha") or pick("tree_sha", "git_sha"), + "source_sha256": run_config.get("source_sha256"), + "dirty": _get(git, "dirty"), + "seed": pick("seed"), + "task": pick("task"), + "backbone": pick("backbone", "model"), + "window_hours": pick("window_hours", "observation_window_hours"), + "embedding_dim": pick("embedding_dim"), + "hidden_dim": pick("hidden_dim"), + "n_layers": pick("n_layers", "num_layers"), + "heads": pick("heads"), + "batch_size": pick("batch_size"), + "use_amp": pick("use_amp"), + "amp_dtype": pick("amp_dtype"), + "freeze_encoder": pick("freeze_encoder", "freeze_text_encoder"), + "drop_modality": pick("drop_modality"), + "lr": pick("lr"), + "adam_eps": pick("adam_eps"), + "max_grad_norm": pick("max_grad_norm"), + "dev": pick("dev"), + "split_mode": pick("split_mode"), + "eval_split": pick("eval_split"), + "cache_frozen_text": pick("cache_frozen_text"), + "note_length": pick("note_length", "max_length"), + "text_encoder": pick("text_encoder", "tokenizer_model"), + "split_train": split.get("train") if isinstance(split, dict) else None, + "split_val": split.get("val", split.get("valid")) if isinstance(split, dict) else None, + "split_test": split.get("test") if isinstance(split, dict) else None, + "positive_rate": pick("positive_rate", "prevalence"), + "train_epoch_s": json.dumps(epochs) if epochs else None, + "train_epoch_mean_warm_s": (sum(warm) / len(warm)) if warm else None, + "eval_s": eval_s, + "inference_s": infer_s, + "throughput_train_pts_per_s": (n_train / sum(_f for _f in + [_num(e) for e in epochs] if _f is not None)) if (n_train and epochs + and all(_num(e) is not None for e in epochs)) else None, + "throughput_infer_pts_per_s": (n_test / infer_s) if (n_test and infer_s) else None, + "gpu_model": pick("gpu_model"), + "gpu_count": pick("gpu_count", "n_gpus"), + "thread_pinning": pin, + "vram_allocated_peak_mb": max(vram_alloc) if vram_alloc else pick( + "vram_allocated_peak_mb", "peak_vram_allocated_mb"), + "vram_reserved_peak_mb": max(vram_res) if vram_res else pick( + "vram_reserved_peak_mb", "peak_vram_reserved_mb"), + "peak_rss_mb": pick("peak_rss_mb", "peak_rss"), + "peak_pss_mb": pick("peak_pss_mb", "peak_pss_bytes"), + "train_cpu_seconds_total": sum(train_cpu) if train_cpu + else _num(pick("train_cpu_seconds")), + "train_cpu_util_pct_mean": sum(cpu_utils) / len(cpu_utils) + if cpu_utils else _num(pick("train_cpu_util_pct")), + "cache_hits": cache.get("hits") if isinstance(cache, dict) else None, + "cache_misses": cache.get("misses") if isinstance(cache, dict) else None, + "cache_entries": cache.get("size", cache.get("entries")) if isinstance(cache, dict) else None, + "cache_bytes": cache.get("bytes") if isinstance(cache, dict) else None, + "cache_cap": cache_cap if cache_cap is not None + else _num(pick("max_frozen_text_cache")), + "val_pr_auc_best": pick("val_pr_auc_best", "best_val_pr_auc"), + "test_pr_auc": _get(scores, "pr_auc") if isinstance(scores, dict) else None, + "test_roc_auc": _get(scores, "roc_auc") if isinstance(scores, dict) else None, + } + missing = sorted(k for k, v in row.items() if v is None and k != "run_dir") + row["missing_fields"] = ";".join(missing) + return row + + + +def check_pair(a: dict, b: dict) -> str: + """Judge whether two collected rows are comparable. + + Args: + a: first row from :func:`collect_run`. + b: second row from :func:`collect_run`. + + Returns: + ``"comparable"``, ``"NON-COMPARABLE: "`` listing + shared fields that differ, or ``"UNVERIFIABLE: "`` + listing compare fields missing on either side. + + Examples: + >>> a = {f: 1 for f in COMPARE_FIELDS} + >>> check_pair(a, dict(a)) + 'comparable' + """ + unknown = [f for f in COMPARE_FIELDS if a.get(f) is None or b.get(f) is None] + if unknown: + return "UNVERIFIABLE: missing " + ",".join(unknown) + differed = [f for f in COMPARE_FIELDS if a.get(f) != b.get(f)] + if differed: + return "NON-COMPARABLE: differ " + ",".join(differed) + return "comparable" + + +def write_outputs(rows: list[dict], prefix: str) -> tuple[str, str]: + """Write collected rows as CSV and Markdown. + + Args: + rows: rows from :func:`collect_run`. + prefix: output path prefix; writes ``prefix.csv`` and ``prefix.md``. + + Returns: + The (csv_path, md_path) pair that was written. + + Examples: + >>> write_outputs([], "/tmp/empty_stats") + ('/tmp/empty_stats.csv', '/tmp/empty_stats.md') + """ + csv_path, md_path = prefix + ".csv", prefix + ".md" + fields = [k for k in rows[0] if k != "missing_fields"] + ["missing_fields"] \ + if rows else ["run_dir", "missing_fields"] + with open(csv_path, "w", newline="") as f: + writer = csv.DictWriter(f, fieldnames=fields) + writer.writeheader() + writer.writerows(rows) + lines = ["# Collected run stats", ""] + if rows: + lines.append("| " + " | ".join(fields) + " |") + lines.append("| " + " | ".join(["---"] * len(fields)) + " |") + for row in rows: + lines.append("| " + " | ".join( + "" if row.get(k) is None else str(row.get(k)) for k in fields) + " |") + lines += ["", "## Pairwise comparability", ""] + if len(rows) < 2: + lines.append("Fewer than two runs: no pairs to check.") + else: + lines.append("| run_a | run_b | verdict |") + lines.append("| --- | --- | --- |") + for i in range(len(rows)): + for j in range(i + 1, len(rows)): + lines.append( + f"| {rows[i]['run_dir']} | {rows[j]['run_dir']} " + f"| {check_pair(rows[i], rows[j])} |") + with open(md_path, "w") as f: + f.write("\n".join(lines) + "\n") + return csv_path, md_path + + +def main(argv=None) -> int: + """CLI entry point: collect run dirs and write CSV + Markdown. + + Examples: + >>> main(["only_arg_check"]) # doctest: +SKIP + """ + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("run_dirs", nargs="+", help="run directories to collect") + parser.add_argument("--out", required=True, help="output path prefix") + args = parser.parse_args(argv) + rows = [collect_run(d) for d in args.run_dirs] + csv_path, md_path = write_outputs(rows, args.out) + print(f"wrote {csv_path} and {md_path} ({len(rows)} runs)") + for row in rows: + print(f"- {row['run_dir']} missing: {row['missing_fields'] or 'none'}") + return 0 + + +if __name__ == "__main__": + sys.exit(main())