Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
174 changes: 174 additions & 0 deletions examples/mortality_prediction/unified_embedding_e2e_mimic4.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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.

Expand All @@ -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)
Expand Down Expand Up @@ -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,
Expand All @@ -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)
Expand All @@ -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
Expand All @@ -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),
Expand Down
12 changes: 9 additions & 3 deletions pyhealth/models/unified_embedding.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
2 changes: 2 additions & 0 deletions pyhealth/trainer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")):
Expand Down
10 changes: 10 additions & 0 deletions pyhealth/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
Loading
Loading