From 976fe148002c64dbf5cf130c506098d3c8dc48ea Mon Sep 17 00:00:00 2001 From: Rian Date: Tue, 3 Nov 2026 12:36:09 -0500 Subject: [PATCH 01/15] Add NotesLabsMIMIC4 and LabsMIMIC4 multimodal tasks. One timeline across stays, full stay by default, and admission-context discharge sections stamped at admit. No ICDLabsMIMIC4. The CXR classes are NOT in this commit; they go to the CXR owner set. The emitted_data_version field stays without the cache-history comments. New synthetic tests port the time-axis and observation-window proofs; adds the task docs page per the task checklist. Sources: #1185 49c87c63 task file, minus the CXR classes. New in v4: regression tests the original series lacked. test_p3_task_schema_specs instantiates every input/output processor spec for both task classes through SampleBuilder._get_processor_instance; test_p3_multimodal_set_task runs real dataset.set_task on MIMIC-IV demo data. Both fail on v3 and pass with the forward_fill fix. New in v5: the fitted-width assertion on the real demo set_task moved here from the empty-first fit commit, so this commit tests what it needs. Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95 --- docs/api/tasks.rst | 1 + .../pyhealth.tasks.multimodal_mimic4.rst | 19 + pyhealth/tasks/__init__.py | 5 + pyhealth/tasks/multimodal_mimic4.py | 648 ++++++++++++++++++ tests/core/test_p1_observation_window.py | 122 ++++ tests/core/test_p1_time_axis.py | 130 ++++ tests/core/test_p3_multimodal_set_task.py | 226 ++++++ tests/core/test_p3_task_schema_specs.py | 56 ++ 8 files changed, 1207 insertions(+) create mode 100644 docs/api/tasks/pyhealth.tasks.multimodal_mimic4.rst create mode 100644 pyhealth/tasks/multimodal_mimic4.py create mode 100644 tests/core/test_p1_observation_window.py create mode 100644 tests/core/test_p1_time_axis.py create mode 100644 tests/core/test_p3_multimodal_set_task.py create mode 100644 tests/core/test_p3_task_schema_specs.py diff --git a/docs/api/tasks.rst b/docs/api/tasks.rst index f681224253..ea129c1b1a 100644 --- a/docs/api/tasks.rst +++ b/docs/api/tasks.rst @@ -312,3 +312,4 @@ Available Tasks Value Set Completion (VSAC) Time-to-event survival (GBSG and SUPPORT) TCGA RNA-seq Survival Prediction + Multimodal Mortality Prediction (MIMIC-IV) diff --git a/docs/api/tasks/pyhealth.tasks.multimodal_mimic4.rst b/docs/api/tasks/pyhealth.tasks.multimodal_mimic4.rst new file mode 100644 index 0000000000..8a61cc5c22 --- /dev/null +++ b/docs/api/tasks/pyhealth.tasks.multimodal_mimic4.rst @@ -0,0 +1,19 @@ +pyhealth.tasks.multimodal_mimic4 +================================ + +Mortality prediction from MIMIC-IV labs and admission-context notes. + +.. autoclass:: pyhealth.tasks.multimodal_mimic4.BaseMultimodalMIMIC4Task + :members: + :undoc-members: + :show-inheritance: + +.. autoclass:: pyhealth.tasks.multimodal_mimic4.NotesLabsMIMIC4 + :members: + :undoc-members: + :show-inheritance: + +.. autoclass:: pyhealth.tasks.multimodal_mimic4.LabsMIMIC4 + :members: + :undoc-members: + :show-inheritance: diff --git a/pyhealth/tasks/__init__.py b/pyhealth/tasks/__init__.py index 554aa3d8f5..224f418f7f 100644 --- a/pyhealth/tasks/__init__.py +++ b/pyhealth/tasks/__init__.py @@ -167,6 +167,11 @@ DearLLMMortalityPredictionMIMIC3 as DearLLMMortalityPredictionMIMIC3, DearLLMMortalityPredictionMIMIC4 as DearLLMMortalityPredictionMIMIC4, ) +from .multimodal_mimic4 import ( + BaseMultimodalMIMIC4Task as BaseMultimodalMIMIC4Task, + LabsMIMIC4 as LabsMIMIC4, + NotesLabsMIMIC4 as NotesLabsMIMIC4, +) from .generate_ehr import ( EHRCodeSetGenerationMIMIC3 as EHRCodeSetGenerationMIMIC3, EHRCodeSetGenerationMIMIC4 as EHRCodeSetGenerationMIMIC4, diff --git a/pyhealth/tasks/multimodal_mimic4.py b/pyhealth/tasks/multimodal_mimic4.py new file mode 100644 index 0000000000..523b52cbae --- /dev/null +++ b/pyhealth/tasks/multimodal_mimic4.py @@ -0,0 +1,648 @@ +import logging +import re +from datetime import datetime, timedelta +from typing import Any, ClassVar + +from pyhealth.tasks.base_task import BaseTask + +logger = logging.getLogger(__name__) + + +class BaseMultimodalMIMIC4Task(BaseTask): + """Base class for multimodal MIMIC-IV tasks. + + Provides shared constants and utility methods used across all multimodal + task variants (notes, ICD codes, lab values). CXR task classes build on + this base in a follow-up commit: they add a ``cxr_image_times`` field + and bound per-admission ``metadata`` CXR events with + :meth:`_admission_window_end`. + + Example: + >>> from pyhealth.tasks.multimodal_mimic4 import LabsMIMIC4 + >>> task = LabsMIMIC4() + >>> task.window_hours is None + True + """ + + MISSING_TEXT_TOKEN: ClassVar[str] = "" + MISSING_CODE_TOKEN: ClassVar[str] = "" + MISSING_FLOAT_TOKEN: ClassVar[float] = 0.0 + + LAB_CATEGORIES: ClassVar[dict[str, list[str]]] = { + "Sodium": ["50824", "52455", "50983", "52623"], + "Potassium": ["50822", "52452", "50971", "52610"], + "Chloride": ["50806", "52434", "50902", "52535"], + "Bicarbonate": ["50803", "50804"], + "Glucose": ["50809", "52027", "50931", "52569"], + "Calcium": ["50808", "51624"], + "Magnesium": ["50960"], + "Anion Gap": ["50868", "52500"], + "Osmolality": ["52031", "50964", "51701"], + "Phosphate": ["50970"], + } + + LAB_CATEGORY_NAMES: ClassVar[list[str]] = [ + "Sodium", + "Potassium", + "Chloride", + "Bicarbonate", + "Glucose", + "Calcium", + "Magnesium", + "Anion Gap", + "Osmolality", + "Phosphate", + ] + + LABITEMS: ClassVar[list[str]] = [ + item for itemids in LAB_CATEGORIES.values() for item in itemids + ] + + RADIOLOGY_CLINICAL_HEADERS: ClassVar[list[str]] = [ + "indication", + "impression", + # "findings", + # "clinical history", + # "history", + # "comparison", + # "technique", + # "conclusion", + # "summary" + ] + + DISCHARGE_CLINICAL_HEADERS: ClassVar[list[str]] = [ + "chief complaint", + # "history of present illness", + # "hpi", + # "past medical history", + # "past medical and surgical history", + # "past medical/surgical history", + # "past surgical history", + # "medications on admission", + # "admission medications", + # "home medications", + # "social history", + # "family history", + # "allergies", + # "review of systems", + ] + + def __init__( + self, + window_hours: float | None = None, + ): + self.window_hours = window_hours + # The task cache key is uuid5 over {**vars(task), schemas}, so this + # field participates in it. Bump it whenever the emitted samples + # change so stale caches cannot be reused. + self.emitted_data_version = 1 + + @staticmethod + def _clean_text(text: str | None) -> str | None: + """Return text if non-empty, otherwise None.""" + return text if text else None + + @staticmethod + def _parse_note_sections(text: str, note_type: str) -> dict[str, str]: + """Split a note into {lowercased_header: content_text} pairs.""" + ext_text = text + '\n\n' + if note_type == "radiology": + section_re = re.compile(r'([a-zA-Z ]+):[ \t\n]+(.+?)\n{2,}', re.DOTALL) + elif note_type == "discharge": + section_re = re.compile(r'([a-zA-Z ]+):\n+(.+?)\n{2,}', re.DOTALL) + else: + raise ValueError(f"Note Type '{note_type}' not supported.") + return { + m.group(1).strip().lower(): m.group(2).strip() + for m in section_re.finditer(ext_text) + if m.end() - m.start() > 0 + } + + @staticmethod + def _parse_datetime(value: Any) -> datetime | None: + if isinstance(value, datetime): + return value + if isinstance(value, str): + for fmt in ("%Y-%m-%d %H:%M:%S", "%Y-%m-%d"): + try: + return datetime.strptime(value, fmt) + except ValueError: + continue + return None + + @staticmethod + def _to_hours(delta_seconds: float) -> float: + return delta_seconds / 3600.0 + + @classmethod + def _hours_since(cls, timestamp: datetime, origin: datetime) -> float: + """Hours from ``origin`` to ``timestamp``. + + Collection windows stay per admission (full stay, or admit+window + when ``window_hours`` is set). The value written onto the unified + timeline is hours from the first stay in this sample, so a later + stay at +6h does not sort with the first stay at +6h. + """ + return cls._to_hours((timestamp - origin).total_seconds()) + + def _compute_effective_window( + self, + admissions_to_process: list[Any], + ) -> tuple[datetime, datetime | None]: + """Compute effective start/end from the global span of processed admissions. + + Returns: + Tuple of (effective_start, effective_end). + """ + global_start = admissions_to_process[0].timestamp + global_end: datetime | None = None + + for a in admissions_to_process: + dt = self._parse_datetime(getattr(a, "dischtime", None)) + if dt is not None and (global_end is None or dt > global_end): + global_end = dt + + if self.window_hours is not None: + effective_start = global_start + effective_end = effective_start + timedelta(hours=self.window_hours) + return effective_start, effective_end + + effective_start = global_start + effective_end = global_end + + return effective_start, effective_end + + def _admission_window_end( + self, + admission_time: datetime, + admission_dischtime: datetime, + ) -> datetime: + """End of the observation window for one admission. + + Callers previously passed ``admission_dischtime`` directly, so + ``window_hours`` was inert and labs were collected through discharge. + For a mortality label that reads the outcome. Re-anchor per admission + and clamp to discharge so a later stay cannot inherit the first + admission's window. + """ + if self.window_hours is None: + return admission_dischtime + end = admission_time + timedelta(hours=self.window_hours) + return min(end, admission_dischtime) if admission_dischtime else end + + def _build_admissions_to_process(self, patient: Any) -> tuple[list[Any], int]: + """Build admissions to process and derive mortality label. + + Includes all admissions up to and including the first death admission. + Patients who die in their first (and only) admission are included as + positives — previously they were dropped, which silently discarded most + ICU mortality positives and collapsed positive rate from ~10% to ~2.7%. + This now matches stagenet's semantics: use all available admission data + and label as positive if any admission has hospital_expire_flag=1. + """ + admissions = patient.get_events(event_type="admissions") + if len(admissions) == 0: + return [], 0 + + admissions_to_process: list[Any] = [] + mortality_label = 0 + + for admission in admissions: + admissions_to_process.append(admission) + if admission.hospital_expire_flag in [1, "1"]: + mortality_label = 1 + break + + return admissions_to_process, mortality_label + + def _collect_icd_codes(self, patient: Any, hadm_id: Any) -> list[str]: + """Collect ICD diagnosis and procedure codes for one admission. + + Returns: + List of ICD code strings, or an empty list if none found. + """ + diagnoses_icd = patient.get_events( + event_type="diagnoses_icd", filters=[("hadm_id", "==", hadm_id)] + ) + procedures_icd = patient.get_events( + event_type="procedures_icd", filters=[("hadm_id", "==", hadm_id)] + ) + return [ + e.icd_code for e in diagnoses_icd if hasattr(e, "icd_code") and e.icd_code + ] + [ + e.icd_code for e in procedures_icd if hasattr(e, "icd_code") and e.icd_code + ] + + def _collect_labs( + self, + patient: Any, + admission_time: datetime, + end_time: datetime, + time_origin: datetime, + ) -> tuple[list[float], list[list[float]], list[list[bool]]]: + """Collect lab values and observation masks for one admission. + + Args: + patient: Patient object. + admission_time: Start of this stay's collection window. + end_time: End of the window (inclusive). + time_origin: First stay in this sample. Event times are hours + from here, not from ``admission_time``. + + Returns: + Tuple of (lab_times, lab_values, lab_masks). ``lab_masks`` is a + parallel boolean tensor where ``True`` means observed and ``False`` + means imputed with 0.0. Returns empty lists when no valid lab + events are found; do not invent a placeholder row. + """ + try: + import polars as pl + except ImportError as exc: + raise ImportError("Polars is required for lab collection.") from exc + + labevents_df = patient.get_events( + event_type="labevents", + start=admission_time, + end=end_time, + return_df=True, + ) + + lab_times: list[float] = [] + lab_values: list[list[float]] = [] + lab_masks: list[list[bool]] = [] + + labevents_df = labevents_df.filter( + pl.col("labevents/itemid").is_in(self.LABITEMS) + ) + if labevents_df.height > 0: + labevents_df = labevents_df.with_columns( + pl.col("labevents/storetime").str.strptime( + pl.Datetime, "%Y-%m-%d %H:%M:%S" + ) + ) + labevents_df = labevents_df.filter( + pl.col("labevents/storetime") <= end_time + ) + if labevents_df.height > 0: + labevents_df = labevents_df.select( + pl.col("timestamp"), + pl.col("labevents/itemid"), + pl.col("labevents/valuenum").cast(pl.Float64), + ) + for lab_ts in sorted(labevents_df["timestamp"].unique().to_list()): + ts_labs = labevents_df.filter(pl.col("timestamp") == lab_ts) + lab_vector: list[float] = [] + lab_mask: list[bool] = [] + for category_name in self.LAB_CATEGORY_NAMES: + category_value = self.MISSING_FLOAT_TOKEN + observed = False + for itemid in self.LAB_CATEGORIES[category_name]: + matching = ts_labs.filter( + pl.col("labevents/itemid") == itemid + ) + if matching.height > 0: + category_value = matching["labevents/valuenum"][0] + observed = True + break + lab_vector.append(category_value) + lab_mask.append(observed) + lab_times.append(self._hours_since(lab_ts, time_origin)) + lab_values.append(lab_vector) + lab_masks.append(lab_mask) + return lab_times, lab_values, lab_masks + + def _collect_notes( + self, + patient: Any, + note_event_type: str, + hadm_id: Any, + admission_time: datetime, + start_time: datetime | None = None, + end_time: datetime | None = None, + section_headers: list[str] | None = None, + fallback_to_full_note: bool = False, + time_origin: datetime | None = None, + event_time: datetime | None = None, + ) -> tuple[list[str], list[float]]: + """Collect notes of a given type for one admission. + + Args: + patient: Patient object. + note_event_type: Event type string (e.g. "discharge", "radiology"). + hadm_id: Admission ID to filter by. + admission_time: This stay's admit time. Used as the timeline + origin when ``time_origin`` is omitted. + start_time: Optional start of the time window. + end_time: Optional end of the time window. + section_headers: When provided, extract only these named sections + from each note (lowercased match against parsed headers). + fallback_to_full_note: When True, falls back to the full note text + if no matching sections are found. When False, notes with no + matching sections are dropped entirely. + time_origin: Timeline origin. Hours are measured from here. + event_time: If set, stamp every collected note at this instant. + Discharge-section text is admission-context and should pass + this stay's admit. Radiology omits it and uses exam + ``charttime``. + + Returns: + Tuple of (texts, hours from the sample's first stay). Empty lists + when the events list is empty; do not invent a placeholder note. + """ + notes = patient.get_events( + event_type=note_event_type, + start=start_time, + end=end_time, + filters=[("hadm_id", "==", hadm_id)], + ) + + texts: list[str] = [] + note_times: list[float] = [] + for note in notes: + try: + note_text = self._clean_text(note.text) + if note_text: + if section_headers is not None: + parsed = self._parse_note_sections(note_text, note_type=note_event_type) + extracted = [f"{k}: {v}" for k, v in parsed.items() if k in section_headers and v] + if extracted: + note_text = " [SEP] ".join(extracted) + elif not fallback_to_full_note: + continue + + origin = time_origin if time_origin is not None else admission_time + stamp = event_time if event_time is not None else note.timestamp + texts.append(note_text) + note_times.append(self._hours_since(stamp, origin)) + except ( + AttributeError + ): # note object is missing .text or .timestamp attribute (e.g. malformed note) + pass + + return texts, note_times + + +class NotesLabsMIMIC4(BaseMultimodalMIMIC4Task): + """Mortality prediction from admission-context notes and lab values. + + Follows the approach of Lee et al. (2023): use text that is clinically + available *at admission* rather than discharge notes. ICD codes are + excluded by default but can be re-enabled for ablation experiments. + + Text is extracted from the MIMIC-IV discharge note by parsing the Chief + Complaint, History of Present Illness, Past Medical History, and Medications + on Admission sections — all of which describe the patient's state at the + start of the stay. The extracted text is stamped at that stay's admit. + + Radiology reports are also included, parsed for their Indication and + Impression sections and bounded to the same observation window as labs + (rather than that stay's admit), since — unlike the discharge summary — they + are written at exam time and describe findings from later in the stay. + + Fields: + admission_note_times: Admission-context discharge-note text stamped + at that stay's admit (hours from the first stay), plus in-window + radiology note text at exam time. + labs: 10-dim lab vectors at each measurement timestamp. + labs_mask: Boolean observation mask parallel to ``labs``. + icd_codes: (only when ``include_icd=True``) Diagnosis + procedure codes + per admission with inter-admission time offsets. + + Args: + window_hours: Hours from admission for lab collection. ``None`` + collects for the full admission span. Default: ``None``. + include_icd: When ``True``, collect discharge-coded ICD codes and add + ``icd_codes`` to the sample dict / input schema. Default: ``False``. + MIMIC-IV timestamps those codes at ``dischtime``, so this leaks + the in-hospital mortality label. Keep it off except as an + explicit leaky ablation. + + Example: + >>> from pyhealth.tasks.multimodal_mimic4 import NotesLabsMIMIC4 + >>> task = NotesLabsMIMIC4() + >>> (task.task_name, task.window_hours, task.include_icd) + ('NotesLabsMIMIC4', None, False) + """ + + PADDING: int = 0 + + task_name: str = "NotesLabsMIMIC4" + + _BASE_INPUT_SCHEMA: ClassVar[dict] = { + "admission_note_times": ( + "tuple_time_text", + { + "tokenizer_model": "emilyalsentzer/Bio_ClinicalBERT", + "type_tag": "note", + "max_length": 512, + }, + ), + "labs": ("stagenet_tensor", {}), + "labs_mask": ("stagenet_tensor", {"forward_fill": False}), + } + + input_schema: ClassVar[dict[str, str | tuple[str, dict]]] = _BASE_INPUT_SCHEMA + output_schema: ClassVar[dict[str, str]] = {"mortality": "binary"} + + def __init__( + self, + window_hours: float | None = None, + include_icd: bool = False, + ) -> None: + super().__init__(window_hours=window_hours) + self.include_icd = include_icd + schema = dict(self._BASE_INPUT_SCHEMA) + if include_icd: + schema["icd_codes"] = ("stagenet", {"padding": self.PADDING}) + self.input_schema = schema + logger.info( + "NotesLabsMIMIC4: filtering discharge notes to sections: %s; " + "radiology notes to sections: %s", + self.DISCHARGE_CLINICAL_HEADERS, + self.RADIOLOGY_CLINICAL_HEADERS, + ) + + def __call__(self, patient: Any) -> list[dict[str, Any]]: + if not patient.get_events(event_type="patients"): + return [] + + admissions_to_process, mortality_label = self._build_admissions_to_process( + patient + ) + if not admissions_to_process: + return [] + + effective_start, effective_end = self._compute_effective_window( + admissions_to_process + ) + time_origin = admissions_to_process[0].timestamp + + all_note_texts: list[str] = [] + all_note_times: list[float] = [] + all_lab_values: list[list[float]] = [] + all_lab_masks: list[list[bool]] = [] + all_lab_times: list[float] = [] + all_icd_codes: list[list[str]] = [] + all_icd_times: list[float] = [] + + for admission in admissions_to_process: + admission_time = admission.timestamp + + try: + admission_dischtime = datetime.strptime( + admission.dischtime, "%Y-%m-%d %H:%M:%S" + ) + except (ValueError, AttributeError): + admission_dischtime = admission_time + admission_dischtime = max(admission_dischtime, admission_time) + + note_texts, note_times = self._collect_notes( + patient, + "discharge", + admission.hadm_id, + admission_time, + section_headers=self.DISCHARGE_CLINICAL_HEADERS, + time_origin=time_origin, + event_time=admission_time, + ) + all_note_texts.extend(note_texts) + all_note_times.extend(note_times) + + # Labs within the observation window of THIS admission. + lab_end = self._admission_window_end(admission_time, admission_dischtime) + lab_times, lab_values, lab_masks = self._collect_labs( + patient=patient, + admission_time=admission_time, + end_time=lab_end, + time_origin=time_origin, + ) + all_lab_times.extend(lab_times) + all_lab_values.extend(lab_values) + all_lab_masks.extend(lab_masks) + + # Radiology notes within the observation window. Unlike the + # discharge note (a retrospective summary parsed for its + # admission-context sections), radiology reports are written at + # exam time, so they're bounded to the same window as labs + # to avoid pulling in findings from later in the stay. + radiology_texts, radiology_times = self._collect_notes( + patient, + "radiology", + admission.hadm_id, + admission_time, + start_time=admission_time, + end_time=lab_end, + section_headers=self.RADIOLOGY_CLINICAL_HEADERS, + time_origin=time_origin, + ) + all_note_texts.extend(radiology_texts) + all_note_times.extend(radiology_times) + + if self.include_icd: + visit_icd_codes = self._collect_icd_codes(patient, admission.hadm_id) + if visit_icd_codes: + all_icd_codes.append(visit_icd_codes) + all_icd_times.append( + self._hours_since(admission_time, time_origin) + ) + + record: dict[str, Any] = { + "patient_id": patient.patient_id, + "admission_note_times": (all_note_texts, all_note_times), + "labs": (all_lab_times, all_lab_values), + "labs_mask": (all_lab_times, all_lab_masks), + "mortality": mortality_label, + "window_start": effective_start, + "window_end": effective_end, + } + + if self.include_icd: + record["icd_codes"] = (all_icd_times, all_icd_codes) + + return [record] + + +class LabsMIMIC4(BaseMultimodalMIMIC4Task): + """EHR-only mortality prediction using lab values — no notes, no ICD codes. + + Serves as the structured-EHR reference baseline for multimodal ablations. + Collecting only ``labevents`` keeps the dataset loader fast and avoids any + leakage from discharge-coded ICD tables. + + Schema mirrors the ``labs`` / ``labs_mask`` fields from ``NotesLabsMIMIC4`` + so the same backbone models (MLP, RNN, Transformer, etc.) work unchanged. + + Args: + window_hours: Hours from admission to collect lab measurements. + ``None`` collects for the full admission span. Default: ``None``. + + Example: + >>> from pyhealth.tasks.multimodal_mimic4 import LabsMIMIC4 + >>> task = LabsMIMIC4() + >>> (task.task_name, task.window_hours) + ('LabsMIMIC4', None) + """ + + PADDING: int = 0 + + task_name: str = "LabsMIMIC4" + + input_schema: ClassVar[dict] = { + "labs": ("stagenet_tensor", {}), + "labs_mask": ("stagenet_tensor", {"forward_fill": False}), + } + output_schema: ClassVar[dict] = {"mortality": "binary"} + + def __init__(self, window_hours: float | None = None) -> None: + super().__init__(window_hours=window_hours) + + def __call__(self, patient: Any) -> list[dict[str, Any]]: # type: ignore[override] + admissions_to_process, mortality_label = self._build_admissions_to_process( + patient + ) + if not admissions_to_process: + return [] + + effective_start, effective_end = self._compute_effective_window( + admissions_to_process + ) + time_origin = admissions_to_process[0].timestamp + + all_lab_times: list[float] = [] + all_lab_values: list[list[float]] = [] + all_lab_masks: list[list[bool]] = [] + + for admission in admissions_to_process: + admission_time = admission.timestamp + + try: + admission_dischtime = datetime.strptime( + admission.dischtime, "%Y-%m-%d %H:%M:%S" + ) + except (ValueError, AttributeError): + admission_dischtime = admission_time + admission_dischtime = max(admission_dischtime, admission_time) + + lab_times, lab_values, lab_masks = self._collect_labs( + patient=patient, + admission_time=admission_time, + end_time=self._admission_window_end( + admission_time, admission_dischtime + ), + time_origin=time_origin, + ) + all_lab_times.extend(lab_times) + all_lab_values.extend(lab_values) + all_lab_masks.extend(lab_masks) + + single_patient_longitudinal_record = { + "patient_id": patient.patient_id, + "labs": (all_lab_times, all_lab_values), + "labs_mask": (all_lab_times, all_lab_masks), + "mortality": mortality_label, + "window_start": effective_start, + "window_end": effective_end, + } + + return [single_patient_longitudinal_record] + diff --git a/tests/core/test_p1_observation_window.py b/tests/core/test_p1_observation_window.py new file mode 100644 index 0000000000..d9fdfd811e --- /dev/null +++ b/tests/core/test_p1_observation_window.py @@ -0,0 +1,122 @@ +"""Proof that every lab task honours a per-admission observation window. + +Four task bodies computed a window from ``window_hours`` and then collected +labs through discharge. For a mortality label that reads the outcome. + +Measured on MIMIC-IV ``labs_only``: + + collection through discharge PR-AUC 0.6204 ROC 0.90 + window honoured PR-AUC 0.2137 ROC 0.7136 + +A sweep over 24, 48, and 96 hours produced three identical datasets, because +``window_hours`` was inert. The window also anchored on the patient's first +admission globally, so a later stay received a span that had already closed. + +``emitted_data_version`` is 1 so future emitted-data changes invalidate +old caches. The table protocol default is full stay +(``window_hours=None``). Passing ``window_hours=24`` still caps collection +per admission; the cap is anchored at each admission, not at the first +admission's clock. (The CXR task classes, with their per-stay CXR window, +land in a follow-up commit.) + +Repro:: + + PYTEST_DISABLE_PLUGIN_AUTOLOAD=1 PYTHONPATH=. \\ + python -m pytest tests/test_p1_observation_window.py -q +""" + +from __future__ import annotations + +import json +import unittest +import uuid +from datetime import datetime, timedelta + + +LAB_TASKS = [ + "LabsMIMIC4", + "NotesLabsMIMIC4", +] + + +class TestP1ObservationWindow(unittest.TestCase): + def test_every_task_honours_a_24h_window(self): + from pyhealth.tasks import multimodal_mimic4 as m + + admit = datetime(2180, 5, 6, 8, 0, 0) + discharge = admit + timedelta(days=9) + for name in LAB_TASKS: + task = getattr(m, name)(window_hours=24) + end = task._admission_window_end(admit, discharge) + horizon = (end - admit).total_seconds() / 3600.0 + self.assertAlmostEqual( + horizon, + 24.0, + places=2, + msg=f"{name} collects {horizon:.0f}h past admission", + ) + self.assertLess(end, discharge) + + def test_window_is_anchored_per_admission(self): + from pyhealth.tasks import multimodal_mimic4 as m + + first = datetime(2180, 5, 6, 8, 0, 0) + later = first + timedelta(days=400) + for name in LAB_TASKS: + task = getattr(m, name)(window_hours=24) + self.assertEqual( + task._admission_window_end(first, first + timedelta(days=9)), + first + timedelta(hours=24), + ) + self.assertEqual( + task._admission_window_end(first, first + timedelta(hours=6)), + first + timedelta(hours=6), + ) + end = task._admission_window_end(later, later + timedelta(days=5)) + self.assertEqual(end, later + timedelta(hours=24)) + self.assertGreater(end, later, msg=f"{name} expired before later stay") + + def test_window_change_invalidates_the_cache(self): + from pyhealth.tasks import multimodal_mimic4 as m + + task = m.LabsMIMIC4(window_hours=24) + self.assertIsNotNone(vars(task).get("emitted_data_version")) + self.assertEqual(task.emitted_data_version, 1) + + def cache_key(t, drop_version=False): + v = dict(vars(t)) + if drop_version: + v.pop("emitted_data_version", None) + params = json.dumps( + { + **v, + "input_schema": t.input_schema, + "output_schema": t.output_schema, + }, + sort_keys=True, + default=str, + ) + return str(uuid.uuid5(uuid.NAMESPACE_DNS, params)) + + self.assertNotEqual(cache_key(task), cache_key(task, drop_version=True)) + + def test_window_none_still_collects_through_discharge(self): + from pyhealth.tasks.multimodal_mimic4 import LabsMIMIC4 + + task = LabsMIMIC4(window_hours=None) + admit = datetime(2180, 5, 6, 8, 0, 0) + discharge = admit + timedelta(days=9) + self.assertEqual(task._admission_window_end(admit, discharge), discharge) + + def test_protocol_default_is_full_stay(self): + from pyhealth.tasks.multimodal_mimic4 import LabsMIMIC4, NotesLabsMIMIC4 + + self.assertIsNone(NotesLabsMIMIC4().window_hours) + self.assertIsNone(LabsMIMIC4().window_hours) + + def test_discharge_coded_icd_is_not_a_mortality_task(self): + from pyhealth.tasks import multimodal_mimic4 as m + from pyhealth.tasks.multimodal_mimic4 import NotesLabsMIMIC4 + + self.assertFalse(hasattr(m, "ICDLabsMIMIC4")) + self.assertFalse(NotesLabsMIMIC4().include_icd) diff --git a/tests/core/test_p1_time_axis.py b/tests/core/test_p1_time_axis.py new file mode 100644 index 0000000000..3447bd704a --- /dev/null +++ b/tests/core/test_p1_time_axis.py @@ -0,0 +1,130 @@ +"""Proof that concatenated stays share one time origin. + +The sample is patient-level: every admission up to the first death is one +sequence. Event times were hours from *that stay's* admit, then concatenated, +so stay 2 at +6h sorted with stay 1 at +6h. Collection is still per stay +(admit through discharge, or admit+window if ``window_hours`` is set). Times +are hours from the first stay in the sample. + +Admission-context discharge sections are stamped at that stay's admit, not +at the discharge note's ``charttime``. Radiology stays at exam time. + +Single-stay patients are unchanged. Time embeddings use geometric +wavelengths from 1 hour to 10 years so a later stay at +9606h does not +alias with +6h. + +Repro:: + + PYTEST_DISABLE_PLUGIN_AUTOLOAD=1 PYTHONPATH=. \\ + python -m pytest tests/test_p1_time_axis.py -q +""" + +from __future__ import annotations + +import inspect +import unittest +from datetime import datetime, timedelta + +import torch + + +class TestP1TimeAxis(unittest.TestCase): + def test_hours_since_does_not_reset_per_stay(self): + from pyhealth.tasks.multimodal_mimic4 import BaseMultimodalMIMIC4Task + + first = datetime(2180, 5, 6, 8, 0, 0) + later = first + timedelta(days=400) + stay1_event = first + timedelta(hours=6) + stay2_event = later + timedelta(hours=6) + + self.assertEqual(BaseMultimodalMIMIC4Task._hours_since(stay1_event, first), 6.0) + # Old convention: both events were 6.0 and collided after concat. + self.assertEqual(BaseMultimodalMIMIC4Task._hours_since(stay2_event, later), 6.0) + self.assertAlmostEqual( + BaseMultimodalMIMIC4Task._hours_since(stay2_event, first), + 400 * 24 + 6.0, + ) + self.assertGreater( + BaseMultimodalMIMIC4Task._hours_since(stay2_event, first), + BaseMultimodalMIMIC4Task._hours_since(stay1_event, first), + ) + + def test_collectors_write_hours_from_the_sample_origin(self): + from pyhealth.tasks.multimodal_mimic4 import ( + BaseMultimodalMIMIC4Task, + LabsMIMIC4, + NotesLabsMIMIC4, + ) + + for cls in (LabsMIMIC4, NotesLabsMIMIC4): + src = inspect.getsource(cls.__call__) + self.assertIn( + "time_origin = admissions_to_process[0].timestamp", + src, + msg=cls.__name__, + ) + self.assertNotIn( + "event.timestamp - admission_time", + src, + msg=f"{cls.__name__} still resets times per stay", + ) + + labs_src = inspect.getsource(BaseMultimodalMIMIC4Task._collect_labs) + self.assertIn("time_origin", labs_src) + self.assertIn("_hours_since", labs_src) + self.assertNotIn("lab_ts - admission_time", labs_src) + + def test_sinusoid_does_not_wrap_every_thirty_days(self): + from pyhealth.models.unified_embedding import SinusoidalTimeEmbedding + + emb = SinusoidalTimeEmbedding(dim=32) + t6 = emb(torch.tensor([6.0])) + t726 = emb(torch.tensor([6.0 + 720.0])) + t9606 = emb(torch.tensor([9606.0])) + self.assertFalse(torch.allclose(t6, t726, atol=1e-5)) + self.assertFalse(torch.allclose(t6, t9606, atol=1e-5)) + + def test_discharge_sections_are_stamped_at_admit_not_charttime(self): + from types import SimpleNamespace + + from pyhealth.tasks.multimodal_mimic4 import NotesLabsMIMIC4 + + first = datetime(2180, 5, 6, 8, 0, 0) + stay2_admit = first + timedelta(days=400) + charttime = stay2_admit + timedelta(days=9) + note = SimpleNamespace( + text="Chief Complaint:\n\nshortness of breath\n\n", + timestamp=charttime, + ) + + class FakePatient: + def get_events(self, event_type, start=None, end=None, filters=None): + return [note] + + task = NotesLabsMIMIC4() + _texts, times = task._collect_notes( + FakePatient(), + "discharge", + hadm_id=1, + admission_time=stay2_admit, + section_headers=task.DISCHARGE_CLINICAL_HEADERS, + time_origin=first, + event_time=stay2_admit, + ) + self.assertEqual(times, [400 * 24.0]) + + _texts, rad_times = task._collect_notes( + FakePatient(), + "radiology", + hadm_id=1, + admission_time=stay2_admit, + time_origin=first, + ) + self.assertAlmostEqual(rad_times[0], 400 * 24.0 + 9 * 24.0) + + for cls in (NotesLabsMIMIC4,): + self.assertIn( + "event_time=admission_time", + inspect.getsource(cls.__call__), + msg=cls.__name__, + ) diff --git a/tests/core/test_p3_multimodal_set_task.py b/tests/core/test_p3_multimodal_set_task.py new file mode 100644 index 0000000000..6cada7d082 --- /dev/null +++ b/tests/core/test_p3_multimodal_set_task.py @@ -0,0 +1,226 @@ +"""Real ``dataset.set_task(task)`` integration tests on MIMIC-IV demo data. + +Regression tests for the W5 cache-A/B blocker: ``set_task`` is the only +code path that instantiates every ``input_schema``/``output_schema`` +processor spec, so only a real ``set_task`` exercises the +``labs_mask`` / ``forward_fill`` combination (and the note tokenizer, +tables, and mask numerics) end to end. + +``LabsMIMIC4`` runs on upstream's ``test-resources/core/mimic4demo`` +fixture, the same demo data other MIMIC-IV task tests use. +``NotesLabsMIMIC4`` additionally needs discharge/radiology notes, which the +demo does not ship, so the test stages a minimal note root (same +``note/*.csv.gz`` layout ``mimic4_note.yaml`` expects) with notes for the +demo patient who has two stays and dies in the second one. +""" + +import gzip +import os +import tempfile +import unittest +from pathlib import Path + +import torch + +DEMO_ROOT = ( + Path(__file__).resolve().parents[2] + / "test-resources" + / "core" + / "mimic4demo" +) + +# Demo patient 10008: stay 20012 (2151-10-05 -> 2151-10-25, survived), +# stay 20013 (2151-12-15 -> 2151-12-20, died) -> mortality label 1. +NOTES_PATIENT = 10008 + + +def _write_note_csv(path, rows): + import csv + + with gzip.open(path, "wt", encoding="utf-8", newline="") as f: + writer = csv.writer(f) + writer.writerow( + [ + "subject_id", + "charttime", + "note_id", + "hadm_id", + "note_type", + "note_seq", + "storetime", + "text", + ] + ) + writer.writerows(rows) + + +def _stage_note_root(root): + note_dir = Path(root) / "note" + note_dir.mkdir(parents=True, exist_ok=True) + _write_note_csv( + note_dir / "discharge.csv.gz", + [ + ( + NOTES_PATIENT, + "2151-10-05", + 1, + 20012, + "discharge", + 1, + "2151-10-25 12:00:00", + "Chief Complaint:\n\nshortness of breath\n\n", + ), + ( + NOTES_PATIENT, + "2151-12-15", + 2, + 20013, + "discharge", + 1, + "2151-12-20 12:00:00", + "Chief Complaint:\n\nchest pain\n\n", + ), + ], + ) + _write_note_csv( + note_dir / "radiology.csv.gz", + [ + ( + NOTES_PATIENT, + "2151-10-06 09:00:00", + 3, + 20012, + "radiology", + 1, + "2151-10-06 10:00:00", + "Indication:\n\nearly film\n\nImpression:\n\nno acute findings\n\n", + ), + ], + ) + + +def _processed_tensors(value): + """Unwrap one processed field into a flat list of tensors.""" + if isinstance(value, torch.Tensor): + return [value] + if isinstance(value, (tuple, list)): + out = [] + for v in value: + out.extend(_processed_tensors(v)) + return [t for t in out if isinstance(t, torch.Tensor)] + return [] + + +class TestLabsMIMIC4SetTask(unittest.TestCase): + @classmethod + def setUpClass(cls): + from pyhealth.datasets import MIMIC4Dataset + from pyhealth.tasks.multimodal_mimic4 import LabsMIMIC4 + + cls._tmp = tempfile.TemporaryDirectory() + dataset = MIMIC4Dataset( + ehr_root=str(DEMO_ROOT), + # Same table list the e2e runner uses; patients/admissions + # are auto-added by MIMIC4EHRDataset. + ehr_tables=["labevents"], + cache_dir=os.path.join(cls._tmp.name, "cache"), + ) + cls.sample_dataset = dataset.set_task(LabsMIMIC4()) + + @classmethod + def tearDownClass(cls): + cls._tmp.cleanup() + + def test_set_task_returns_samples(self): + self.assertGreater(len(self.sample_dataset), 0) + + def test_labels_cover_both_classes(self): + labels = set() + for i in range(len(self.sample_dataset)): + labels.add(int(self.sample_dataset[i]["mortality"])) + # Demo patient 10008 dies in the second stay; most survive. + self.assertEqual(labels, {0, 1}) + + def test_processors_fit_feature_width(self): + # The labs stream starts with patients who have no lab events; fit + # must scan past them. value_dim() sizes the unified numeric + # encoder, so an unfitted processor (width 1) would break the first + # forward with a matmul shape error. + self.assertEqual(self.sample_dataset.input_processors["labs"].value_dim(), 10) + self.assertEqual( + self.sample_dataset.input_processors["labs_mask"].value_dim(), 10 + ) + + def test_labs_mask_is_parallel_and_unimputed(self): + saw_unobserved = False + for i in range(len(self.sample_dataset)): + sample = self.sample_dataset[i] + # Coupled (time, value) fields process to (time, value) tensors. + _labs_time, values = _processed_tensors(sample["labs"]) + _mask_time, mask = _processed_tensors(sample["labs_mask"]) + self.assertEqual(values.shape, mask.shape) + self.assertTrue(torch.isfinite(values).all()) + unique = set(mask.reshape(-1).tolist()) + self.assertLessEqual(unique, {0.0, 1.0}) + if 0.0 in unique: + saw_unobserved = True + # The demo labs only cover a subset of the 10 categories, so some + # mask entry must be unobserved (0.0, never forward-filled to 1.0). + self.assertTrue(saw_unobserved) + + +class TestNotesLabsMIMIC4SetTask(unittest.TestCase): + @classmethod + def setUpClass(cls): + from pyhealth.datasets import MIMIC4Dataset + from pyhealth.tasks.multimodal_mimic4 import NotesLabsMIMIC4 + + cls._tmp = tempfile.TemporaryDirectory() + _stage_note_root(os.path.join(cls._tmp.name, "notes")) + cls.dataset = MIMIC4Dataset( + ehr_root=str(DEMO_ROOT), + ehr_tables=["labevents"], + note_root=os.path.join(cls._tmp.name, "notes"), + note_tables=["discharge", "radiology"], + cache_dir=os.path.join(cls._tmp.name, "cache"), + ) + cls.sample_dataset = cls.dataset.set_task(NotesLabsMIMIC4()) + + @classmethod + def tearDownClass(cls): + cls._tmp.cleanup() + + def test_set_task_returns_samples(self): + self.assertGreater(len(self.sample_dataset), 0) + + def test_note_text_survives_processing(self): + # Raw task records (pre-processor) carry the extracted sections. + from pyhealth.tasks.multimodal_mimic4 import NotesLabsMIMIC4 + + task = NotesLabsMIMIC4() + patient = self.dataset.get_patient(str(NOTES_PATIENT)) + record = task(patient)[0] + texts, _times = record["admission_note_times"] + joined = " [SEP] ".join(texts) + self.assertIn("shortness of breath", joined) + self.assertIn("chest pain", joined) + self.assertIn("early film", joined) + + def test_processed_sample_has_notes_labs_and_mask(self): + found_notes = False + for i in range(len(self.sample_dataset)): + sample = self.sample_dataset[i] + self.assertIn("labs", sample) + self.assertIn("labs_mask", sample) + note_tensors = [ + t + for t in _processed_tensors(sample["admission_note_times"]) + if t.numel() > 0 + ] + if note_tensors: + found_notes = True + self.assertTrue(found_notes) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/core/test_p3_task_schema_specs.py b/tests/core/test_p3_task_schema_specs.py new file mode 100644 index 0000000000..fe0783f6d6 --- /dev/null +++ b/tests/core/test_p3_task_schema_specs.py @@ -0,0 +1,56 @@ +"""Every series task schema spec must instantiate like SampleDataset does. + +Regression tests for the W5 cache-A/B blocker: the multimodal MIMIC-IV +tasks declared ``"labs_mask": ("stagenet_tensor", {"forward_fill": False})`` +while ``StageNetTensorProcessor`` took no kwargs, so ``set_task`` raised +``TypeError`` on every real cohort. The existing series tests only called +the task ``__call__`` (which never touches processor specs), so nothing +caught it. These tests instantiate each ``input_schema``/``output_schema`` +spec through the exact resolution helper ``SampleDataset``/``SampleBuilder`` +use, for every task class in the series. +""" + +import unittest + + +def _all_specs(task): + return list(task.input_schema.items()) + list(task.output_schema.items()) + + +def _instantiate(spec): + from pyhealth.datasets.sample_dataset import SampleBuilder + + # Same resolution logic SampleDataset.fit / SampleBuilder.fit use to + # build processors (string alias, (alias-or-class, kwargs), class, + # or instance). `self` is unused by the helper. + return SampleBuilder._get_processor_instance(None, spec) + + +class TestMultimodalTaskSchemaSpecs(unittest.TestCase): + def _check_task(self, task): + specs = _all_specs(task) + self.assertGreater(len(specs), 0) + for field, spec in specs: + with self.subTest(task=type(task).__name__, field=field): + processor = _instantiate(spec) + self.assertIsNotNone(processor) + + def test_notes_labs_specs_instantiate(self): + from pyhealth.tasks.multimodal_mimic4 import NotesLabsMIMIC4 + + self._check_task(NotesLabsMIMIC4()) + + def test_notes_labs_icd_specs_instantiate(self): + from pyhealth.tasks.multimodal_mimic4 import NotesLabsMIMIC4 + + # The leaky-ICD ablation variant adds the ("stagenet", {...}) spec. + self._check_task(NotesLabsMIMIC4(include_icd=True)) + + def test_labs_specs_instantiate(self): + from pyhealth.tasks.multimodal_mimic4 import LabsMIMIC4 + + self._check_task(LabsMIMIC4()) + + +if __name__ == "__main__": + unittest.main() From 70e8b4f0d32137cbe5c45426a1440415798f81e9 Mon Sep 17 00:00:00 2001 From: Rian Date: Tue, 3 Nov 2026 05:04:09 -0500 Subject: [PATCH 02/15] Share one observation window across modalities, default 0 = off. One parameter, window_hours = 0, on the base task, applied through the single _admission_window_end helper to labs and radiology notes in NotesLabsMIMIC4 and LabsMIMIC4. 0 means no cap (full stay through discharge); a positive value caps each admission at min(admit + N h, discharge), anchored at each admission, not at the first admission's clock. Negative or None raises ValueError. Discharge notes stay unbounded by design (admission-context sections stamped at admit); there is deliberately no switch for them. Tests: 0 equals the full-stay output exactly; N h drops later labs/radiology per admission; negative and None raise. Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95 --- pyhealth/tasks/multimodal_mimic4.py | 36 +++-- tests/core/test_p1_observation_window.py | 10 +- tests/core/test_p2_observation_window.py | 179 +++++++++++++++++++++++ 3 files changed, 208 insertions(+), 17 deletions(-) create mode 100644 tests/core/test_p2_observation_window.py diff --git a/pyhealth/tasks/multimodal_mimic4.py b/pyhealth/tasks/multimodal_mimic4.py index 523b52cbae..8f09054f38 100644 --- a/pyhealth/tasks/multimodal_mimic4.py +++ b/pyhealth/tasks/multimodal_mimic4.py @@ -17,11 +17,18 @@ class BaseMultimodalMIMIC4Task(BaseTask): and bound per-admission ``metadata`` CXR events with :meth:`_admission_window_end`. + The shared observation window is ``window_hours``: ``0`` (default) + means no cap (full stay through discharge); a positive value caps each + admission at ``min(admit + N h, discharge)``. Discharge notes stay + unbounded by design: the collected sections are admission context + stamped at admit, so windowing them would drop context without + removing any post-admit information. + Example: >>> from pyhealth.tasks.multimodal_mimic4 import LabsMIMIC4 >>> task = LabsMIMIC4() - >>> task.window_hours is None - True + >>> task.window_hours + 0 """ MISSING_TEXT_TOKEN: ClassVar[str] = "" @@ -89,8 +96,13 @@ class BaseMultimodalMIMIC4Task(BaseTask): def __init__( self, - window_hours: float | None = None, + window_hours: float = 0, ): + if window_hours is None or window_hours < 0: + raise ValueError( + "window_hours must be a non-negative number of hours " + f"(0 = full stay through discharge); got {window_hours!r}." + ) self.window_hours = window_hours # The task cache key is uuid5 over {**vars(task), schemas}, so this # field participates in it. Bump it whenever the emitted samples @@ -162,7 +174,7 @@ def _compute_effective_window( if dt is not None and (global_end is None or dt > global_end): global_end = dt - if self.window_hours is not None: + if self.window_hours > 0: effective_start = global_start effective_end = effective_start + timedelta(hours=self.window_hours) return effective_start, effective_end @@ -185,7 +197,7 @@ def _admission_window_end( and clamp to discharge so a later stay cannot inherit the first admission's window. """ - if self.window_hours is None: + if self.window_hours == 0: return admission_dischtime end = admission_time + timedelta(hours=self.window_hours) return min(end, admission_dischtime) if admission_dischtime else end @@ -409,8 +421,8 @@ class NotesLabsMIMIC4(BaseMultimodalMIMIC4Task): per admission with inter-admission time offsets. Args: - window_hours: Hours from admission for lab collection. ``None`` - collects for the full admission span. Default: ``None``. + window_hours: Hours from admission for lab collection. ``0`` + (default) collects for the full admission span. include_icd: When ``True``, collect discharge-coded ICD codes and add ``icd_codes`` to the sample dict / input schema. Default: ``False``. MIMIC-IV timestamps those codes at ``dischtime``, so this leaks @@ -421,7 +433,7 @@ class NotesLabsMIMIC4(BaseMultimodalMIMIC4Task): >>> from pyhealth.tasks.multimodal_mimic4 import NotesLabsMIMIC4 >>> task = NotesLabsMIMIC4() >>> (task.task_name, task.window_hours, task.include_icd) - ('NotesLabsMIMIC4', None, False) + ('NotesLabsMIMIC4', 0, False) """ PADDING: int = 0 @@ -446,7 +458,7 @@ class NotesLabsMIMIC4(BaseMultimodalMIMIC4Task): def __init__( self, - window_hours: float | None = None, + window_hours: float = 0, include_icd: bool = False, ) -> None: super().__init__(window_hours=window_hours) @@ -574,13 +586,13 @@ class LabsMIMIC4(BaseMultimodalMIMIC4Task): Args: window_hours: Hours from admission to collect lab measurements. - ``None`` collects for the full admission span. Default: ``None``. + ``0`` (default) collects for the full admission span. Example: >>> from pyhealth.tasks.multimodal_mimic4 import LabsMIMIC4 >>> task = LabsMIMIC4() >>> (task.task_name, task.window_hours) - ('LabsMIMIC4', None) + ('LabsMIMIC4', 0) """ PADDING: int = 0 @@ -593,7 +605,7 @@ class LabsMIMIC4(BaseMultimodalMIMIC4Task): } output_schema: ClassVar[dict] = {"mortality": "binary"} - def __init__(self, window_hours: float | None = None) -> None: + def __init__(self, window_hours: float = 0) -> None: super().__init__(window_hours=window_hours) def __call__(self, patient: Any) -> list[dict[str, Any]]: # type: ignore[override] diff --git a/tests/core/test_p1_observation_window.py b/tests/core/test_p1_observation_window.py index d9fdfd811e..5320b18476 100644 --- a/tests/core/test_p1_observation_window.py +++ b/tests/core/test_p1_observation_window.py @@ -14,7 +14,7 @@ ``emitted_data_version`` is 1 so future emitted-data changes invalidate old caches. The table protocol default is full stay -(``window_hours=None``). Passing ``window_hours=24`` still caps collection +(``window_hours=0``). Passing ``window_hours=24`` still caps collection per admission; the cap is anchored at each admission, not at the first admission's clock. (The CXR task classes, with their per-stay CXR window, land in a follow-up commit.) @@ -100,10 +100,10 @@ def cache_key(t, drop_version=False): self.assertNotEqual(cache_key(task), cache_key(task, drop_version=True)) - def test_window_none_still_collects_through_discharge(self): + def test_window_zero_still_collects_through_discharge(self): from pyhealth.tasks.multimodal_mimic4 import LabsMIMIC4 - task = LabsMIMIC4(window_hours=None) + task = LabsMIMIC4(window_hours=0) admit = datetime(2180, 5, 6, 8, 0, 0) discharge = admit + timedelta(days=9) self.assertEqual(task._admission_window_end(admit, discharge), discharge) @@ -111,8 +111,8 @@ def test_window_none_still_collects_through_discharge(self): def test_protocol_default_is_full_stay(self): from pyhealth.tasks.multimodal_mimic4 import LabsMIMIC4, NotesLabsMIMIC4 - self.assertIsNone(NotesLabsMIMIC4().window_hours) - self.assertIsNone(LabsMIMIC4().window_hours) + self.assertEqual(NotesLabsMIMIC4().window_hours, 0) + self.assertEqual(LabsMIMIC4().window_hours, 0) def test_discharge_coded_icd_is_not_a_mortality_task(self): from pyhealth.tasks import multimodal_mimic4 as m diff --git a/tests/core/test_p2_observation_window.py b/tests/core/test_p2_observation_window.py new file mode 100644 index 0000000000..05d0b61b96 --- /dev/null +++ b/tests/core/test_p2_observation_window.py @@ -0,0 +1,179 @@ +"""Observation window default 0 = off, on synthetic two-stay patients. + +Commit scope: the shared window lives on the base class and applies through +the single ``_admission_window_end`` helper to labs and radiology notes. +``0`` means no cap (full stay through discharge). A positive value caps each +admission at ``min(admit + N h, discharge)``. Negative or ``None`` raises. + +Discharge notes stay unbounded by design: the collected sections are +admission context stamped at admit, so windowing them would drop context +without removing any post-admit information. +""" + +from __future__ import annotations + +import unittest +from datetime import datetime, timedelta +from types import SimpleNamespace + +import polars as pl + + +T0 = datetime(2180, 5, 6, 8, 0, 0) +STAY2 = T0 + timedelta(days=400) + + +def _lab_df(rows): + """Rows: (timestamp, itemid, value). Storetime == charttime here.""" + return pl.DataFrame( + { + "timestamp": [r[0] for r in rows], + "labevents/itemid": [r[1] for r in rows], + "labevents/valuenum": [float(r[2]) for r in rows], + "labevents/storetime": [r[0].strftime("%Y-%m-%d %H:%M:%S") for r in rows], + } + ) + + +def _admission(admits, days=9, hadm_id=1, died=0): + return SimpleNamespace( + timestamp=admits, + dischtime=(admits + timedelta(days=days)).strftime("%Y-%m-%d %H:%M:%S"), + hadm_id=hadm_id, + hospital_expire_flag=died, + ) + + +class _FakePatient: + patient_id = "P0" + + def __init__(self, admissions, lab_rows, notes): + self._admissions = admissions + self._lab_rows = lab_rows + self._notes = notes + + def get_events( + self, event_type, start=None, end=None, filters=None, return_df=None + ): + if event_type == "patients": + return [object()] + if event_type == "admissions": + return self._admissions + if event_type == "labevents": + df = _lab_df(self._lab_rows) + if start is not None: + df = df.filter(pl.col("timestamp") >= start) + if end is not None: + df = df.filter(pl.col("timestamp") <= end) + return df + if event_type in ("discharge", "radiology"): + out = list(self._notes.get(event_type, [])) + if start is not None: + out = [n for n in out if n.timestamp >= start] + if end is not None: + out = [n for n in out if n.timestamp <= end] + if filters: + for key, op, value in filters: + assert op == "==" + out = [n for n in out if getattr(n, key) == value] + return out + return [] + + +def _two_stay_patient(): + admissions = [_admission(T0, hadm_id=1), _admission(STAY2, hadm_id=2)] + lab_rows = [ + (T0 + timedelta(hours=6), "50824", 140.0), + (T0 + timedelta(hours=30), "50824", 141.0), + (STAY2 + timedelta(hours=6), "50824", 139.0), + (STAY2 + timedelta(hours=30), "50824", 138.0), + ] + notes = { + "discharge": [ + SimpleNamespace( + text="Chief Complaint:\n\nshortness of breath\n\n", + timestamp=T0 + timedelta(hours=30), + hadm_id=1, + ), + SimpleNamespace( + text="Chief Complaint:\n\nchest pain\n\n", + timestamp=STAY2 + timedelta(hours=30), + hadm_id=2, + ), + ], + "radiology": [ + SimpleNamespace( + text="Indication:\n\nearly film\n\n", + timestamp=T0 + timedelta(hours=6), + hadm_id=1, + ), + SimpleNamespace( + text="Indication:\n\nlate film\n\n", + timestamp=T0 + timedelta(hours=30), + hadm_id=1, + ), + SimpleNamespace( + text="Indication:\n\nsecond stay film\n\n", + timestamp=STAY2 + timedelta(hours=6), + hadm_id=2, + ), + ], + } + return _FakePatient(admissions, lab_rows, notes) + + +class TestObservationWindowDefaultZero(unittest.TestCase): + def test_zero_equals_full_stay_exactly(self): + from pyhealth.tasks.multimodal_mimic4 import LabsMIMIC4 + + patient = _two_stay_patient() + default_record = LabsMIMIC4()(patient)[0] + explicit_record = LabsMIMIC4(window_hours=0)(patient)[0] + huge_record = LabsMIMIC4(window_hours=10**6)(patient)[0] + for key in ("labs", "labs_mask"): + self.assertEqual(default_record[key], explicit_record[key]) + self.assertEqual(default_record[key], huge_record[key]) + # All four lab events, both stays. + self.assertEqual(len(default_record["labs"][0]), 4) + + def test_positive_window_drops_late_events_per_admission(self): + from pyhealth.tasks.multimodal_mimic4 import LabsMIMIC4 + + record = LabsMIMIC4(window_hours=24)(_two_stay_patient())[0] + times, _values = record["labs"] + # +6h of each stay kept; +30h of each stay dropped. The second + # stay's +6h is ~9606h on the sample clock, so a first-admission + # clock would have dropped it. + self.assertEqual(times, [6.0, 400 * 24.0 + 6.0]) + + def test_window_bounds_radiology_but_not_discharge_sections(self): + from pyhealth.tasks.multimodal_mimic4 import NotesLabsMIMIC4 + + record = NotesLabsMIMIC4(window_hours=24)(_two_stay_patient())[0] + texts, times = record["admission_note_times"] + joined = " [SEP] ".join(texts) + # Radiology at +6h kept (both stays); radiology at +30h dropped. + self.assertIn("early film", joined) + self.assertIn("second stay film", joined) + self.assertNotIn("late film", joined) + # Discharge sections are stamped at admit and unbounded: both stays + # present even though their charttimes (+30h) are past the window. + self.assertIn("shortness of breath", joined) + self.assertIn("chest pain", joined) + self.assertEqual( + times[texts.index(next(t for t in texts if "shortness of breath" in t))], + 0.0, + ) + + def test_negative_and_none_raise(self): + from pyhealth.tasks.multimodal_mimic4 import LabsMIMIC4, NotesLabsMIMIC4 + + for cls in (LabsMIMIC4, NotesLabsMIMIC4): + with self.assertRaises(ValueError): + cls(window_hours=-1) + with self.assertRaises(ValueError): + cls(window_hours=None) + + +if __name__ == "__main__": + unittest.main() From 0b472b45a7d76c1dd2b5c8254020e0bca26a2b2c Mon Sep 17 00:00:00 2001 From: Rian Date: Tue, 3 Nov 2026 12:56:34 -0500 Subject: [PATCH 03/15] Add unified-embedding e2e runner with cache and timing flags. Wires the NotesLabsMIMIC4/LabsMIMIC4 tasks and the unified-mode backbones in this series (MLP, RNN, Transformer, BottleneckTransformer, EHRMamba, JambaEHR). Flags: Trainer AMP, loader options, observation-window-hours default 0, freeze-encoder, cache-frozen-text with max-frozen-text-cache, --no-dask-distributed to skip the distributed cluster. No hardcoded MIMIC roots. run() takes injectable sample_dataset for tests; main(argv) injectable for CLI tests. Per-epoch train time, eval/inference time, frozen-text cache stats printed and written to metrics.json for the cache A/B. Tests: CLI help/defaults/no-cache flag, tiny synthetic end-to-end (MLP, 1 epoch, CPU), plus committed demo-data real-path tests (TestUnifiedE2ERunnerDemoData): labs with mlp+rnn on the MIMIC-IV demo fixture (1 epoch, CPU, shared set_task, seed 2 so val/test have no all-empty batch for the RNN pack), asserting metrics.json key set and finite losses; notes_labs skipped unless Bio_ClinicalBERT is in the local HF cache (never downloads). New in v5: demo-data runner test added here so the runner commit proves the real path it wires. Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95 --- .../unified_embedding_e2e_mimic4.py | 663 ++++++++++++++++++ tests/core/test_unified_e2e_runner.py | 322 +++++++++ 2 files changed, 985 insertions(+) create mode 100644 examples/mortality_prediction/unified_embedding_e2e_mimic4.py create mode 100644 tests/core/test_unified_e2e_runner.py diff --git a/examples/mortality_prediction/unified_embedding_e2e_mimic4.py b/examples/mortality_prediction/unified_embedding_e2e_mimic4.py new file mode 100644 index 0000000000..8a83d76dc5 --- /dev/null +++ b/examples/mortality_prediction/unified_embedding_e2e_mimic4.py @@ -0,0 +1,663 @@ +"""End-to-end protocol runner for unified-embedding mortality models on MIMIC-IV. + +Trains and evaluates a unified-embedding model (MLP / RNN / Transformer / +BottleneckTransformer / EHRMamba / JambaEHR) on a MIMIC-IV mortality task, +then writes per-sample predictions to CSV and run metrics to JSON. + +Tasks +----- +--task labs (default) + LabsMIMIC4: 10-dim lab vectors only. + +--task notes_labs (recommended for multimodal) + NotesLabsMIMIC4: notes + 10-dim lab vectors. + +(The CXR task classes land in a follow-up commit, which will add a +``notes_labs_cxr`` choice here.) + +At the end of a run the runner prints and writes ``metrics.json`` with the +per-epoch train time, evaluation/inference time, and frozen-text cache +stats (hits, misses, size). That file is what the cache on/off A/B reads. + +Example +------- + python examples/mortality_prediction/unified_embedding_e2e_mimic4.py \\ + --ehr-root /path/to/mimiciv/2.2 \\ + --task labs \\ + --model transformer \\ + --heads 4 --num-layers 2 \\ + --dev --device cpu \\ + --epochs 1 --batch-size 32 --lr 1e-3 \\ + --output-dir ./output/unified_e2e + + # Notes + labs with the text cache disabled (cache A/B, off arm): + python examples/mortality_prediction/unified_embedding_e2e_mimic4.py \\ + --ehr-root /data/mimic-iv/2.2 --note-root /data/mimic-iv/note \\ + --task notes_labs --model transformer \\ + --no-cache-frozen-text --max-frozen-text-cache 0 +""" + +from __future__ import annotations + +import argparse +import csv +import json +import time +from pathlib import Path +from typing import Any, Dict, List, Optional, Tuple + +import numpy as np + +from pyhealth.datasets import ( + MIMIC4Dataset, + get_dataloader, + split_by_patient, + split_by_sample, +) +from pyhealth.models import ( + MLP, + RNN, + Transformer, + UnifiedMultimodalEmbeddingModel, +) +from pyhealth.models.bottleneck_transformer import BottleneckTransformer +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.utils import set_seed + + +class WandbLogger: + def __init__( + self, + enabled: bool, + project: str, + entity: Optional[str], + run_name: str, + tags: list[str], + config: Dict[str, Any], + ) -> None: + self.enabled = enabled + self._run = None + if self.enabled: + import wandb + + self._run = wandb.init( + project=project, + entity=entity, + name=run_name, + tags=tags, + config=config, + ) + + def log(self, data: Dict[str, Any], step: Optional[int] = None) -> None: + if self.enabled: + self._run.log(data, step=step) + + def finish(self) -> None: + if self.enabled: + self._run.finish() + + +def _build_base_dataset(args: argparse.Namespace) -> MIMIC4Dataset: + ehr_tables = ["labevents"] + note_tables = None + + if args.task == "notes_labs": + if not args.note_root: + raise ValueError("--task notes_labs requires --note-root.") + note_tables = ["discharge", "radiology"] + + return MIMIC4Dataset( + ehr_root=args.ehr_root, + ehr_tables=ehr_tables, + note_root=args.note_root if note_tables else None, + note_tables=note_tables, + cache_dir=args.cache_dir, + dev=args.dev if args.dev else False, + num_workers=args.num_workers, + use_dask_distributed=args.use_dask_distributed, + ) + + +def _build_task(args: argparse.Namespace): + if args.task == "notes_labs": + return NotesLabsMIMIC4( + window_hours=args.observation_window_hours, + ) + if args.task == "labs": + return LabsMIMIC4(window_hours=args.observation_window_hours) + raise ValueError(f"Unknown task: {args.task}") + + +def _split_dataset(dataset: Any, seed: int) -> Tuple[Any, Any, Any]: + 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: + 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 + + +def _build_unified_embedding( + args: argparse.Namespace, sample_dataset: Any +) -> UnifiedMultimodalEmbeddingModel: + return UnifiedMultimodalEmbeddingModel( + processors=sample_dataset.input_processors, + embedding_dim=args.embedding_dim, + freeze_text_encoder=args.freeze_encoder, + cache_frozen_text=args.cache_frozen_text, + max_frozen_text_cache=args.max_frozen_text_cache, + ) + + +def _build_model(args: argparse.Namespace, sample_dataset: Any, unified): + if args.model == "mlp": + return MLP( + dataset=sample_dataset, + embedding_dim=args.embedding_dim, + hidden_dim=args.hidden_dim, + unified_embedding=unified, + ) + if args.model == "rnn": + return RNN( + dataset=sample_dataset, + embedding_dim=args.embedding_dim, + hidden_dim=args.hidden_dim, + unified_embedding=unified, + rnn_type=args.rnn_type, + num_layers=args.rnn_layers, + dropout=args.dropout, + bidirectional=args.bidirectional, + ) + if args.model == "transformer": + return Transformer( + dataset=sample_dataset, + embedding_dim=args.embedding_dim, + heads=args.heads, + num_layers=args.num_layers, + dropout=args.dropout, + unified_embedding=unified, + ) + if args.model == "bottleneck_transformer": + return BottleneckTransformer( + dataset=sample_dataset, + embedding_dim=args.embedding_dim, + bottlenecks_n=args.bottlenecks_n, + fusion_startidx=args.fusion_startidx, + num_layers=args.num_layers, + heads=args.heads, + dropout=args.dropout, + unified_embedding=unified, + ) + if args.model == "ehrmamba": + return EHRMamba( + dataset=sample_dataset, + embedding_dim=args.embedding_dim, + num_layers=args.num_layers, + state_size=args.mamba_state_size, + conv_kernel=args.mamba_conv_kernel, + dropout=args.dropout, + unified_embedding=unified, + ) + if args.model == "jambaehr": + return JambaEHR( + dataset=sample_dataset, + embedding_dim=args.embedding_dim, + num_transformer_layers=args.jamba_transformer_layers, + num_mamba_layers=args.jamba_mamba_layers, + heads=args.heads, + dropout=args.dropout, + state_size=args.mamba_state_size, + conv_kernel=args.mamba_conv_kernel, + unified_embedding=unified, + ) + raise ValueError(f"Unknown model: {args.model}") + + +def _write_predictions( + output_csv: Path, + patient_ids: list[str], + y_true: np.ndarray, + y_prob: np.ndarray, +) -> None: + output_csv.parent.mkdir(parents=True, exist_ok=True) + + y_true_flat = y_true.reshape(-1).tolist() + y_prob_flat = y_prob.reshape(-1).tolist() + + 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"], + ) + writer.writeheader() + for idx, prob in enumerate(y_prob_flat): + writer.writerow( + { + "patient_id": patient_ids[idx], + "y_true": int(y_true_flat[idx]), + "y_prob": float(prob), + "y_pred_threshold_0_5": int(float(prob) >= 0.5), + } + ) + + +class _EpochTimedLoader: + """Wrap a training loader to record per-epoch wall time. + + ``Trainer.train`` returns ``None`` and its epoch loop lives inside the + Trainer, so the runner cannot time epochs without changing the Trainer. + The training loop calls ``iter(loader)`` once per epoch (initially, then + again each time the iterator is exhausted), so each ``__iter__`` call + marks an epoch boundary. Everything else delegates to the wrapped + loader, so shuffling and seeding behavior is unchanged. + """ + + def __init__(self, loader: Any) -> None: + self._loader = loader + self.epoch_boundaries: List[float] = [] + + def __getattr__(self, name: str) -> Any: + return getattr(self._loader, name) + + def __len__(self) -> int: + return len(self._loader) + + def __iter__(self): + self.epoch_boundaries.append(time.perf_counter()) + return iter(self._loader) + + def epoch_seconds(self) -> List[float]: + """Per-epoch durations; the last epoch ends when training returns.""" + ends = self.epoch_boundaries[1:] + [time.perf_counter()] + return [end - start for start, end in zip(self.epoch_boundaries, ends)] + + +def run(args: argparse.Namespace, sample_dataset: Any = None) -> Path: + """Run the end-to-end protocol and write predictions + metrics. + + Args: + args: Parsed CLI flags (see :func:`parse_args`). + sample_dataset: Optional prebuilt sample dataset (e.g. synthetic in + tests). When ``None`` (the CLI path), the MIMIC-IV dataset is + loaded from ``args`` roots and the task is applied to it. + """ + set_seed(args.seed) + + if sample_dataset is None: + base_dataset = _build_base_dataset(args) + task = _build_task(args) + sample_dataset = base_dataset.set_task(task, num_workers=args.num_workers) + if len(sample_dataset) == 0: + raise RuntimeError( + "Task produced zero samples. Check roots/tables or adjust settings." + ) + + train_ds, val_ds, test_ds = _split_dataset(sample_dataset, seed=args.seed) + + unified = _build_unified_embedding(args, sample_dataset) + model = _build_model(args, sample_dataset, unified) + + loader_kwargs: Dict[str, Any] = { + "num_workers": args.num_workers, + "pin_memory": args.pin_memory, + "persistent_workers": args.persistent_workers, + "prefetch_factor": (args.prefetch_factor if args.num_workers > 0 else None), + } + timed_train_loader = _EpochTimedLoader( + get_dataloader( + train_ds, batch_size=args.batch_size, shuffle=True, **loader_kwargs + ) + ) + val_loader = ( + get_dataloader( + val_ds, batch_size=args.batch_size, shuffle=False, **loader_kwargs + ) + if len(val_ds) > 0 + else None + ) + test_loader = ( + get_dataloader( + test_ds, batch_size=args.batch_size, shuffle=False, **loader_kwargs + ) + if len(test_ds) > 0 + else None + ) + + exp_name = f"{args.model}_seed{args.seed}" + output_dir = Path(args.output_dir) + + wandb_logger = WandbLogger( + enabled=args.wandb, + project=args.wandb_project, + entity=args.wandb_entity, + 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), + ) + + trainer = Trainer( + model=model, + metrics=["pr_auc", "roc_auc", "f1", "accuracy"], + device=args.device, + enable_logging=True, + output_path=str(output_dir), + 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 + + epoch_train_seconds: List[float] = [] + if args.epochs > 0 and len(train_ds) > 0: + trainer.train( + train_dataloader=timed_train_loader, + val_dataloader=val_loader, + epochs=args.epochs, + optimizer_params=optimizer_params, + weight_decay=args.weight_decay, + max_grad_norm=effective_max_grad_norm, + monitor="pr_auc", + load_best_model_at_last=True, + patience=args.patience, + accumulation_steps=args.accumulation_steps, + use_amp=args.use_amp, + amp_dtype=args.amp_dtype, + ) + epoch_train_seconds = timed_train_loader.epoch_seconds() + + eval_seconds = 0.0 + test_scores: Dict[str, float] = {} + if test_loader is not None: + eval_start = time.perf_counter() + test_scores = trainer.evaluate(test_loader) + 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 + ) + 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) + + metrics = { + "config": vars(args), + "split": { + "train": len(train_ds), + "val": len(val_ds), + "test": len(test_ds) if test_ds is not None else 0, + }, + "epoch_train_seconds": epoch_train_seconds, + "eval_seconds": eval_seconds, + "inference_seconds": inference_seconds, + "frozen_text_cache": unified.frozen_text_cache_stats, + "test_scores": test_scores, + } + metrics_path = output_dir / exp_name / "metrics.json" + metrics_path.parent.mkdir(parents=True, exist_ok=True) + metrics_path.write_text(json.dumps(metrics, indent=2, sort_keys=True, default=str)) + + print(f"Saved predictions to: {output_csv}") + print(f"Saved metrics to: {metrics_path}") + print( + "epoch_train_seconds=" + f"{[round(t, 3) for t in epoch_train_seconds]} " + f"eval_seconds={eval_seconds:.3f} " + f"inference_seconds={inference_seconds:.3f} " + f"frozen_text_cache={metrics['frozen_text_cache']}" + ) + + wandb_logger.finish() + + return output_csv + + +def parse_args(argv: Optional[list] = None) -> argparse.Namespace: + parser = argparse.ArgumentParser( + description="Run E2E unified embedding on MIMIC-IV mortality tasks." + ) + parser.add_argument("--ehr-root", type=str, required=True) + parser.add_argument("--note-root", type=str, default=None) + parser.add_argument("--cache-dir", type=str, default=None) + parser.add_argument("--output-dir", type=str, default="./output/unified_e2e") + + parser.add_argument( + "--task", + type=str, + choices=["labs", "notes_labs"], + default="labs", + help=( + "notes_labs: admission-context text + labs (needs --note-root). " + "labs: 10-dim lab vectors only." + ), + ) + parser.add_argument( + "--model", + type=str, + choices=[ + "mlp", + "rnn", + "transformer", + "bottleneck_transformer", + "ehrmamba", + "jambaehr", + ], + default="rnn", + ) + + parser.add_argument("--embedding-dim", type=int, default=64) + parser.add_argument("--hidden-dim", type=int, default=64) + parser.add_argument("--dropout", type=float, default=0.1) + parser.add_argument("--epochs", type=int, default=1) + parser.add_argument("--batch-size", type=int, default=32) + parser.add_argument( + "--lr", + type=float, + default=None, + help="Learning rate. Default is 1e-4 for all models.", + ) + 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." + ), + ) + parser.add_argument("--weight-decay", type=float, default=0.0) + parser.add_argument("--device", type=str, default=None) + parser.add_argument( + "--use-amp", + action="store_true", + help="Enable automatic mixed precision training to reduce GPU memory usage.", + ) + parser.add_argument( + "--amp-dtype", + type=str, + default="bf16", + choices=["bf16", "fp16"], + help="AMP dtype when --use-amp is set. bf16 is more stable (default).", + ) + parser.add_argument( + "--accumulation-steps", + type=int, + default=1, + help="Gradient accumulation steps (default 1, no accumulation).", + ) + parser.add_argument("--num-workers", type=int, default=1) + parser.add_argument( + "--no-dask-distributed", + dest="use_dask_distributed", + action="store_false", + default=True, + help=( + "Skip the Dask distributed cluster for event caching and use " + "the local scheduler instead." + ), + ) + parser.add_argument( + "--pin-memory", + action="store_true", + help="Copy CPU tensors into page-locked memory in the loaders.", + ) + parser.add_argument( + "--persistent-workers", + action="store_true", + help="Keep loader workers alive between epochs (needs --num-workers > 0).", + ) + parser.add_argument( + "--prefetch-factor", + type=int, + default=None, + help="Batches each loader worker prefetches (needs --num-workers > 0).", + ) + parser.add_argument("--seed", type=int, default=42) + parser.add_argument("--patience", type=int, default=None) + parser.add_argument( + "--dev", + nargs="?", + type=int, + const=1000, + default=0, + help=( + "Dev mode: limit dataset to N patients for fast iteration. " + "--dev (no value) defaults to 1000 patients. " + "--dev 5000 limits to 5000. Omit for full dataset." + ), + ) + parser.add_argument( + "--observation-window-hours", + type=float, + default=0, + help=( + "Hours from each admission to collect labs/radiology notes. " + "Default 0 means no cap: full stay through discharge." + ), + ) + parser.add_argument( + "--freeze-encoder", + action="store_true", + default=False, + help=( + "Freeze pretrained BERT text encoder weights and train only the " + "downstream backbone (RNN/Transformer head + projection layer). " + ), + ) + parser.add_argument( + "--cache-frozen-text", + action=argparse.BooleanOptionalAction, + default=True, + help=( + "Reuse frozen text-encoder [CLS] vectors across forwards " + "(default on). Pass --no-cache-frozen-text for the cache-off arm " + "of the A/B timing run." + ), + ) + parser.add_argument( + "--max-frozen-text-cache", + type=int, + default=1_000_000, + help="Maximum cached frozen [CLS] vectors; rows past the cap are re-encoded.", + ) + parser.add_argument("--rnn-type", type=str, default="GRU") + parser.add_argument("--rnn-layers", type=int, default=1) + parser.add_argument("--bidirectional", action="store_true") + + parser.add_argument("--heads", type=int, default=4) + parser.add_argument("--num-layers", type=int, default=2) + + parser.add_argument("--bottlenecks-n", type=int, default=4) + parser.add_argument("--fusion-startidx", type=int, default=1) + + 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." + ), + ) + + parser.add_argument( + "--wandb", + action="store_true", + default=False, + help="Log training/eval metrics to Weights & Biases.", + ) + parser.add_argument("--wandb-project", type=str, default="pyhealth-mortality") + parser.add_argument("--wandb-entity", type=str, default=None) + parser.add_argument( + "--wandb-run-name", + type=str, + default=None, + help="Defaults to '{model}_seed{seed}' if unset.", + ) + parser.add_argument( + "--wandb-tags", + type=str, + default=None, + help="Comma-separated wandb tags, e.g. 'labs,rnn'. Defaults to '{task},{model}' if unset.", + ) + + parser.add_argument( + "--mamba-state-size", + type=int, + default=16, + help="SSM state size for EHRMamba and JambaEHR blocks.", + ) + parser.add_argument( + "--mamba-conv-kernel", + type=int, + default=4, + help="Causal conv kernel size for EHRMamba and JambaEHR blocks.", + ) + parser.add_argument( + "--jamba-transformer-layers", + type=int, + default=2, + help="Number of Transformer (attention) layers in JambaEHR.", + ) + parser.add_argument( + "--jamba-mamba-layers", + type=int, + default=2, + help="Number of Mamba (SSM) layers in JambaEHR.", + ) + + return parser.parse_args(argv) + + +def main(argv: Optional[list] = None) -> Path: + """CLI entry point (``argv`` injectable for tests).""" + args = parse_args(argv) + return run(args) + + +if __name__ == "__main__": + output_csv_path = main() + print(f"Saved predictions to: {output_csv_path}") diff --git a/tests/core/test_unified_e2e_runner.py b/tests/core/test_unified_e2e_runner.py new file mode 100644 index 0000000000..d7e8d14a59 --- /dev/null +++ b/tests/core/test_unified_e2e_runner.py @@ -0,0 +1,322 @@ +"""Smoke tests for the unified-embedding e2e runner (no MIMIC data). + +Covers the CLI surface the cache A/B depends on (--help, the cache flags, +the window default) plus one tiny synthetic end-to-end run through model +training, evaluation, inference, and ``metrics.json``. +""" + +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", path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def _samples(n=20): + samples = [] + for i in range(n): + 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 TestUnifiedE2ERunner(unittest.TestCase): + def test_help(self): + runner = _runner() + with self.assertRaises(SystemExit) as ctx: + runner.main(["--help"]) + self.assertEqual(ctx.exception.code, 0) + + def test_defaults(self): + runner = _runner() + args = runner.parse_args(["--ehr-root", "/tmp/does-not-exist"]) + self.assertEqual(args.task, "labs") + self.assertEqual(args.observation_window_hours, 0) + self.assertTrue(args.cache_frozen_text) + self.assertEqual(args.max_frozen_text_cache, 1_000_000) + self.assertEqual(args.accumulation_steps, 1) + self.assertFalse(args.use_amp) + + def test_no_cache_flag(self): + runner = _runner() + args = runner.parse_args( + ["--ehr-root", "/tmp/does-not-exist", "--no-cache-frozen-text"] + ) + self.assertFalse(args.cache_frozen_text) + + def test_synthetic_end_to_end(self): + from pyhealth.datasets import create_sample_dataset + + runner = _runner() + dataset = create_sample_dataset( + samples=_samples(), + input_schema={"labs": "stagenet_tensor"}, + output_schema={"label": "binary"}, + dataset_name="test_e2e_runner_synthetic", + ) + with TemporaryDirectory() as tmp: + args = Namespace( + **{ + **vars( + runner.parse_args( + [ + "--ehr-root", + "/tmp/does-not-exist", + "--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.assertTrue(Path(output_csv).is_file()) + metrics_path = Path(output_csv).parent / "metrics.json" + self.assertTrue(metrics_path.is_file()) + metrics = json.loads(metrics_path.read_text()) + for key in ( + "config", + "split", + "epoch_train_seconds", + "eval_seconds", + "inference_seconds", + "frozen_text_cache", + "test_scores", + ): + self.assertIn(key, metrics) + self.assertEqual(len(metrics["epoch_train_seconds"]), 1) + self.assertGreaterEqual(metrics["inference_seconds"], 0.0) + self.assertEqual( + sorted(metrics["frozen_text_cache"]), + ["hits", "misses", "size"], + ) + self.assertTrue(torch.isfinite(torch.tensor(metrics["eval_seconds"]))) + + +DEMO_ROOT = ( + Path(__file__).resolve().parents[2] / "test-resources" / "core" / "mimic4demo" +) + +_EXPECTED_METRICS_KEYS = ( + "config", + "split", + "epoch_train_seconds", + "eval_seconds", + "inference_seconds", + "frozen_text_cache", + "test_scores", +) + + +def _demo_args(runner, tmp, model, task="labs", extra=()): + # Seed 2: split_by_patient gives val=[1 event]/test=[2,2] (no empty + # val/test batches). Seed 42 gives val=[0 events], and the RNN's + # pack_padded_sequence cannot pack an all-empty batch. + return Namespace( + **vars( + runner.parse_args( + [ + "--ehr-root", + str(DEMO_ROOT), + "--task", + task, + "--model", + model, + "--epochs", + "1", + "--batch-size", + "8", + "--embedding-dim", + "8", + "--hidden-dim", + "8", + "--device", + "cpu", + "--seed", + "2", + "--no-cache-frozen-text", + "--output-dir", + str(Path(tmp) / "out"), + "--cache-dir", + str(Path(tmp) / "cache"), + "--num-workers", + "0", + *extra, + ] + ) + ) + ) + + +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()) + metrics = json.loads(metrics_path.read_text()) + testcase.assertEqual(set(metrics.keys()), set(_EXPECTED_METRICS_KEYS)) + 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.assertTrue( + torch.isfinite(torch.tensor(float(metrics["eval_seconds"]))).item() + ) + testcase.assertTrue( + torch.isfinite(torch.tensor(float(metrics["inference_seconds"]))).item() + ) + testcase.assertEqual( + sorted(metrics["frozen_text_cache"]), ["hits", "misses", "size"] + ) + testcase.assertGreater(metrics["split"]["train"], 0) + for v in metrics["test_scores"].values(): + testcase.assertTrue(torch.isfinite(torch.tensor(float(v))).item()) + + +class TestUnifiedE2ERunnerDemoData(unittest.TestCase): + """Real-path runner test on the MIMIC-IV demo fixture (seconds, CPU). + + Drives ``run`` end to end on demo data for ``labs`` (no text model + needed) with two backbones. The ``notes_labs`` case needs the + Bio_ClinicalBERT weights; it is skipped unless they are already in the + local HF cache -- tests never download. + """ + + @classmethod + def setUpClass(cls): + # One real set_task shared by both backbones: run() splits/trains + # on these demo samples (seed 2 in _demo_args). Separated so the + # slow base build happens once, not per backbone. + import os + + from pyhealth.datasets import MIMIC4Dataset + from pyhealth.tasks.multimodal_mimic4 import LabsMIMIC4 + + cls._tmp = TemporaryDirectory() + dataset = MIMIC4Dataset( + ehr_root=str(DEMO_ROOT), + ehr_tables=["labevents"], + cache_dir=os.path.join(cls._tmp.name, "cache"), + ) + cls.sample_dataset = dataset.set_task(LabsMIMIC4()) + + @classmethod + def tearDownClass(cls): + cls._tmp.cleanup() + + def test_labs_mlp_and_rnn_finish_with_finite_scores(self): + runner = _runner() + for model in ("mlp", "rnn"): + with self.subTest(model=model): + with TemporaryDirectory() as tmp: + args = _demo_args(runner, tmp, model, task="labs") + output_csv = runner.run(args, sample_dataset=self.sample_dataset) + _assert_demo_metrics(self, output_csv) + + def test_notes_labs_skipped_without_cached_text_model(self): + try: + from transformers import AutoTokenizer + + AutoTokenizer.from_pretrained( + "emilyalsentzer/Bio_ClinicalBERT", local_files_only=True + ) + except Exception as exc: # noqa: BLE001 -- any load failure means skip + self.skipTest(f"text model not in local HF cache: {exc}") + import gzip + + runner = _runner() + with TemporaryDirectory() as tmp: + note_dir = Path(tmp) / "notes" / "note" + note_dir.mkdir(parents=True, exist_ok=True) + import csv + + def _write(path, rows): + with gzip.open(path, "wt", encoding="utf-8", newline="") as f: + w = csv.writer(f) + w.writerow( + [ + "subject_id", + "charttime", + "note_id", + "hadm_id", + "note_type", + "note_seq", + "storetime", + "text", + ] + ) + w.writerows(rows) + + _write( + note_dir / "discharge.csv.gz", + [ + (10008, "2151-10-05", 1, 20012, "discharge", 1, + "2151-10-25 12:00:00", "Chief Complaint:\n\nshortness of breath\n\n"), + (10008, "2151-12-15", 2, 20013, "discharge", 1, + "2151-12-20 12:00:00", "Chief Complaint:\n\nchest pain\n\n"), + ], + ) + _write( + note_dir / "radiology.csv.gz", + [ + (10008, "2151-10-06 09:00:00", 3, 20012, "radiology", 1, + "2151-10-06 10:00:00", "Impression:\n\nno acute findings\n\n"), + ], + ) + args = _demo_args( + runner, + tmp, + "rnn", + task="notes_labs", + extra=( + "--note-root", str(Path(tmp) / "notes"), + "--freeze-encoder", + # run() builds the base dataset + set_task inside, and + # set_task(num_workers=0) is invalid upstream + # (ZeroDivisionError); loaders are still fast enough. + "--num-workers", "1", + ), + ) + output_csv = runner.run(args) + _assert_demo_metrics(self, output_csv) + + +if __name__ == "__main__": + unittest.main() From e8d24e10c9bcff50138d241a1d187c5024d7d623 Mon Sep 17 00:00:00 2001 From: Rian354 Date: Thu, 5 Nov 2026 15:30:20 -0500 Subject: [PATCH 04/15] 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 daaa1fc70339ea527e3b03b8953c8f332f904e56 Mon Sep 17 00:00:00 2001 From: Rian Date: Thu, 5 Nov 2026 20:29:24 -0500 Subject: [PATCH 05/15] 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 14ffbce5675be7d1fc8046d161c8c85d52e8e3fc Mon Sep 17 00:00:00 2001 From: Rian Date: Thu, 5 Nov 2026 15:38:37 -0500 Subject: [PATCH 06/15] 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 e4a1ef108206f7afb64cd71d0c39a58d95dafd51 Mon Sep 17 00:00:00 2001 From: Rian Date: Thu, 5 Nov 2026 15:42:11 -0500 Subject: [PATCH 07/15] 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 34417245d2ddae8541e5c9742dafc68c2c7ff78b Mon Sep 17 00:00:00 2001 From: Rian Date: Thu, 5 Nov 2026 15:44:10 -0500 Subject: [PATCH 08/15] 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 75cd60ce7ac8071263487a70ebd008fb6ba3f0f1 Mon Sep 17 00:00:00 2001 From: Rian Date: Thu, 5 Nov 2026 20:31:49 -0500 Subject: [PATCH 09/15] 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 576890e882e3d56d9407a3352d0ae7948944355a Mon Sep 17 00:00:00 2001 From: Rian Date: Thu, 5 Nov 2026 15:49:36 -0500 Subject: [PATCH 10/15] 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 1223a1ea46216e7935f0b0e5f75d9a0bc193f1f7 Mon Sep 17 00:00:00 2001 From: Rian Date: Thu, 5 Nov 2026 20:32:28 -0500 Subject: [PATCH 11/15] 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 93b2dd88e50e5bb81348a1118fac88532a84cc8b Mon Sep 17 00:00:00 2001 From: Rian Date: Thu, 5 Nov 2026 20:33:19 -0500 Subject: [PATCH 12/15] 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 974f0f94da264b1eae6f9f390105ffe1686b80ea Mon Sep 17 00:00:00 2001 From: Rian Date: Sun, 8 Nov 2026 21:31:10 -0500 Subject: [PATCH 13/15] 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) From 30d40ffb7c0148144775590b173b011c6404f240 Mon Sep 17 00:00:00 2001 From: Rian354 Date: Thu, 5 Nov 2026 20:31:30 -0500 Subject: [PATCH 14/15] 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 not a PSS total, so the column is left empty for the run rather than holding RSS. A denied process drops the sample instead of undercounting it, while an exited one is skipped; the peak_pss reset runs inside the sampler lock. Additive: peak_rss_bytes keeps its meaning, so numbers already collected stay interpretable. Adapted only for this series drift (the open_fds field the source predates). Sources: fork #55 07355aed (verbatim hunk in all 16 files). Tests: tests/core/test_benchmark_pss.py (new; fails without this commit -- tracker exercised where importable, structural markers elsewhere since meds_reader is unavailable here, plus fake-process cases: denied drops the sample, exited is skipped). Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95 --- .../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 15c6aba75c8f722ba8d3c78d2fbd1aad9a986672 Mon Sep 17 00:00:00 2001 From: jhnwu3 Date: Mon, 23 Nov 2026 20:57:54 -0500 Subject: [PATCH 15/15] Name the dataset in the multimodal task docstrings and keep persistent workers off the shuffled loader. Task docstrings reference MIMIC4Dataset so the docs list these tasks on the dataset page. get_dataloader rejects persistent_workers=True with shuffle=True, so the runner applies --persistent-workers to the validation and test loaders only. Co-Authored-By: Claude Fable 5.2 --- .../unified_embedding_e2e_mimic4.py | 12 ++++++++++-- pyhealth/tasks/multimodal_mimic4.py | 10 ++++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/examples/mortality_prediction/unified_embedding_e2e_mimic4.py b/examples/mortality_prediction/unified_embedding_e2e_mimic4.py index c4a0617d4f..bbb42bfbb0 100644 --- a/examples/mortality_prediction/unified_embedding_e2e_mimic4.py +++ b/examples/mortality_prediction/unified_embedding_e2e_mimic4.py @@ -515,9 +515,13 @@ def run(args: argparse.Namespace, sample_dataset: Any = None) -> Path: "persistent_workers": args.persistent_workers, "prefetch_factor": (args.prefetch_factor if args.num_workers > 0 else None), } + # get_dataloader refuses persistent workers on a shuffled loader: they + # keep the first epoch's dataset copy, so reshuffling would not reach + # them. Only the unshuffled validation and test loaders keep theirs. + train_loader_kwargs = {**loader_kwargs, "persistent_workers": False} timed_train_loader = _EpochTimedLoader( get_dataloader( - train_ds, batch_size=args.batch_size, shuffle=True, **loader_kwargs + train_ds, batch_size=args.batch_size, shuffle=True, **train_loader_kwargs ) ) val_loader = ( @@ -782,7 +786,11 @@ def parse_args(argv: Optional[list] = None) -> argparse.Namespace: parser.add_argument( "--persistent-workers", action="store_true", - help="Keep loader workers alive between epochs (needs --num-workers > 0).", + help=( + "Keep validation and test loader workers alive between epochs " + "(needs --num-workers > 0). The shuffled training loader always " + "restarts its workers." + ), ) parser.add_argument( "--prefetch-factor", diff --git a/pyhealth/tasks/multimodal_mimic4.py b/pyhealth/tasks/multimodal_mimic4.py index 8f09054f38..615b8d9116 100644 --- a/pyhealth/tasks/multimodal_mimic4.py +++ b/pyhealth/tasks/multimodal_mimic4.py @@ -11,6 +11,9 @@ class BaseMultimodalMIMIC4Task(BaseTask): """Base class for multimodal MIMIC-IV tasks. + Subclasses run on the composite + :class:`~pyhealth.datasets.MIMIC4Dataset`. + Provides shared constants and utility methods used across all multimodal task variants (notes, ICD codes, lab values). CXR task classes build on this base in a follow-up commit: they add a ``cxr_image_times`` field @@ -397,6 +400,10 @@ def _collect_notes( class NotesLabsMIMIC4(BaseMultimodalMIMIC4Task): """Mortality prediction from admission-context notes and lab values. + Runs on the composite :class:`~pyhealth.datasets.MIMIC4Dataset`, loaded + with the EHR ``labevents`` table and the ``discharge`` and ``radiology`` + note tables. + Follows the approach of Lee et al. (2023): use text that is clinically available *at admission* rather than discharge notes. ICD codes are excluded by default but can be re-enabled for ablation experiments. @@ -577,6 +584,9 @@ def __call__(self, patient: Any) -> list[dict[str, Any]]: class LabsMIMIC4(BaseMultimodalMIMIC4Task): """EHR-only mortality prediction using lab values — no notes, no ICD codes. + Runs on :class:`~pyhealth.datasets.MIMIC4Dataset` loaded with the EHR + ``labevents`` table. + Serves as the structured-EHR reference baseline for multimodal ablations. Collecting only ``labevents`` keeps the dataset loader fast and avoids any leakage from discharge-coded ICD tables.