diff --git a/docs/api/models.rst b/docs/api/models.rst index e2a110e9d2..b634b25a23 100644 --- a/docs/api/models.rst +++ b/docs/api/models.rst @@ -298,6 +298,7 @@ API Reference models/pyhealth.models.Transformer models/pyhealth.models.BEHRT models/pyhealth.models.BiteNet + models/pyhealth.models.BottleneckTransformer models/pyhealth.models.TransformersModel models/pyhealth.models.LLMEHREncoder models/pyhealth.models.HFEHRFoundationModel diff --git a/docs/api/models/pyhealth.models.BottleneckTransformer.rst b/docs/api/models/pyhealth.models.BottleneckTransformer.rst new file mode 100644 index 0000000000..470563c303 --- /dev/null +++ b/docs/api/models/pyhealth.models.BottleneckTransformer.rst @@ -0,0 +1,15 @@ +pyhealth.models.BottleneckTransformer +====================================== + + +The shared bottleneck encoder and the complete Bottleneck Transformer model. + +.. autoclass:: pyhealth.models.MultimodalBottleneckTransformerEncoder + :members: + :undoc-members: + :show-inheritance: + +.. autoclass:: pyhealth.models.BottleneckTransformer + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/api/tasks.rst b/docs/api/tasks.rst index c63e551044..264875ae4f 100644 --- a/docs/api/tasks.rst +++ b/docs/api/tasks.rst @@ -289,3 +289,4 @@ Available Tasks YAIB Tasks (eICU) Value Set Completion (VSAC) Time-to-event survival (GBSG and SUPPORT) + 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/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/pyhealth/datasets/base_dataset.py b/pyhealth/datasets/base_dataset.py index ba0648245f..40815af674 100644 --- a/pyhealth/datasets/base_dataset.py +++ b/pyhealth/datasets/base_dataset.py @@ -516,6 +516,7 @@ def __init__( cache_dir: str | Path | None = None, num_workers: int = 1, dev: bool = False, + use_dask_distributed: bool = True, ): """Initializes the BaseDataset. @@ -533,6 +534,10 @@ def __init__( is appended to the provided path to capture dataset configuration. num_workers (int): Number of worker processes for parallel operations. dev (bool): Whether to run in dev mode (limits to 1000 patients). + use_dask_distributed (bool): Whether event caching uses the Dask + distributed cluster. ``False`` writes the cache with the local + Dask scheduler instead, for sandboxes where the cluster cannot + start. Defaults to ``True``. It does not affect the cache key. """ if len(set(tables)) != len(tables): logger.warning("Duplicate table names in tables list. Removing duplicates.") @@ -542,6 +547,7 @@ def __init__( self.dataset_name = dataset_name or self.__class__.__name__ self.num_workers = num_workers self.dev = dev + self.use_dask_distributed = use_dask_distributed self.config = load_yaml_config(config_path) if config_path else None logger.info( @@ -861,17 +867,42 @@ def _event_transform(self, output_dir: Path) -> None: compute_ok = False try: df = self.load_data() - with DaskCluster( - n_workers=self.num_workers, - threads_per_worker=1, - processes=not in_notebook(), - # Use cache_dir for Dask's scratch space to avoid filling up /tmp or home directory - local_directory=str(self.create_tmpdir()), - # No dashboard: its bokeh server fails to stop on cluster close and - # leaks sockets, hitting "Too many open files" after repeated builds. - dashboard_address=None, - ) as cluster: - with DaskClient(cluster) as client: + if not self.use_dask_distributed: + logger.info( + "use_dask_distributed=False; caching " + "with the local Dask scheduler." + ) + if self.dev: + logger.info("Dev mode enabled: limiting to 1000 patients") + # head() reads only the first partition unless told + # otherwise (see the distributed branch below). + unique = df["patient_id"].unique() + patients = unique.head(1000, npartitions=-1).tolist() + patient_filter = df["patient_id"].isin(patients) + df = df[patient_filter] + logger.info(f"Caching event dataframe to {output_dir}...") + df.sort_values("patient_id").to_parquet( + output_dir, + write_index=False, + compute=True, + ) + compute_ok = True + else: + with ( + DaskCluster( + n_workers=self.num_workers, + threads_per_worker=1, + processes=not in_notebook(), + # Use cache_dir for Dask's scratch space to avoid + # filling up /tmp or home directory + local_directory=str(self.create_tmpdir()), + # No dashboard: its bokeh server fails to stop on + # cluster close and leaks sockets, hitting "Too many + # open files" after repeated builds. + dashboard_address=None, + ) as cluster, + DaskClient(cluster) as client, + ): if self.dev: logger.info("Dev mode enabled: limiting to 1000 patients") # head() reads only the first partition unless told diff --git a/pyhealth/datasets/collate.py b/pyhealth/datasets/collate.py index 9e4c113c06..90da379f35 100644 --- a/pyhealth/datasets/collate.py +++ b/pyhealth/datasets/collate.py @@ -17,14 +17,98 @@ from typing import Any import torch -from torch.nn.utils.rnn import pad_sequence +import torch.nn.functional as F + + +def _pad_stack(tensors: list[torch.Tensor]) -> torch.Tensor: + """Right-pad same-rank tensors to the per-dimension max, then stack. + + ``pad_sequence`` only pads dimension 0 and requires every trailing dimension + to already match. Tokenized notes are ``(n_notes, seq_len)`` and, once the + text processor pads to the longest note in a sample rather than to a fixed + ``max_length``, BOTH dimensions vary across samples. + """ + if len({t.dim() for t in tensors}) != 1: + raise ValueError("cannot pad tensors of differing rank") + target = [max(t.shape[d] for t in tensors) for d in range(tensors[0].dim())] + padded = [] + for t in tensors: + spec: list[int] = [] + for d in range(t.dim() - 1, -1, -1): + spec.extend([0, target[d] - t.shape[d]]) + padded.append(F.pad(t, spec) if any(spec) else t) + return torch.stack(padded) + + +def _stack_positions(values: list[tuple]) -> tuple: + """Collates same-length tuples one position at a time. + + Tensor positions stack when their shapes match and pad every ragged + dimension otherwise. A position that is None in every sample stays None, + and one that is None in only some samples is dropped to None. Other + positions, such as a text tag, stay lists. + + Example: + >>> import torch + >>> from pyhealth.datasets.collate import _stack_positions + >>> _stack_positions([(torch.ones(2), "a"), (torch.ones(1), "b")])[1] + ['a', 'b'] + """ + stacked = [] + for pos in range(len(values[0])): + elems = [v[pos] for v in values] + if all(e is None for e in elems): + stacked.append(None) + elif all(e is None or isinstance(e, torch.Tensor) for e in elems): + if any(e is None for e in elems): + stacked.append(None) + elif elems[0].dim() == 0: + stacked.append(torch.stack(elems)) + else: + stacked.append(_pad_stack(elems)) + else: + stacked.append(elems) + return tuple(stacked) + + +def _event_pad_mask(values: list[tuple]) -> torch.Tensor | None: + """Event-level validity of a batch of tuples, or None if nothing is ragged. + + Read from the first position holding non-scalar tensors. Those tensors + share dimension 0 (the event count), so their lengths give the mask. + """ + for pos in range(len(values[0])): + elems = [v[pos] for v in values] + if all(isinstance(e, torch.Tensor) for e in elems) and elems[0].dim() > 0: + if all(e.shape == elems[0].shape for e in elems): + return None + lengths = torch.tensor([e.shape[0] for e in elems]) + return torch.arange(int(lengths.max()))[None, :] < lengths[:, None] + return None def _stack_or_pad(tensors: list[torch.Tensor]) -> torch.Tensor: - """Stack if all shapes match; pad along dim-0 otherwise.""" + """Stack if all shapes match; pad every ragged dimension otherwise.""" if all(t.shape == tensors[0].shape for t in tensors): return torch.stack(tensors) - return pad_sequence(tensors, batch_first=True) + return _pad_stack(tensors) + + +def _pad_mask(tensors: list[torch.Tensor]) -> torch.Tensor: + """Event-level validity for the tensor :func:`_stack_or_pad` just built. + + Batch padding is created here and nowhere else, so it has to be recorded + here. A padded slot carries value 0.0 and time 0.0, which is + indistinguishable from a real measurement taken at admission time, so a + model given no mask treats padding as data. + + This is deliberately NOT called ``mask``. A field may carry its own + ``{field}_mask`` meaning "was this value observed", which is a different + question from "is this slot real". + """ + lengths = torch.tensor([t.shape[0] for t in tensors]) + width = int(lengths.max()) + return torch.arange(width)[None, :] < lengths[:, None] def collate_temporal(batch: list[dict[str, Any]]) -> dict[str, Any]: @@ -43,6 +127,13 @@ def collate_temporal(batch: list[dict[str, Any]]) -> dict[str, Any]: Returns: A single collated dict ready for model ``forward(**batch)``. + + Example: + >>> import torch + >>> batch = [{"x": {"value": torch.ones(2, 2), "time": torch.zeros(2)}}] + >>> out = collate_temporal(batch) + >>> out["x"]["pad_mask"].tolist() + [[True, True]] """ if not batch: return {} @@ -62,6 +153,8 @@ def collate_temporal(batch: list[dict[str, Any]]) -> dict[str, Any]: sub_result[sub_key] = [None] * len(sub_vals) elif isinstance(sub_vals[0], torch.Tensor): sub_result[sub_key] = _stack_or_pad(sub_vals) + if sub_key == "time": + sub_result["pad_mask"] = _pad_mask(sub_vals) else: sub_result[sub_key] = sub_vals result[key] = sub_result diff --git a/pyhealth/datasets/mimic4.py b/pyhealth/datasets/mimic4.py index e06aee4ec1..afcba95298 100644 --- a/pyhealth/datasets/mimic4.py +++ b/pyhealth/datasets/mimic4.py @@ -373,6 +373,9 @@ class MIMIC4Dataset(BaseDataset): ed_config_path: Path to the ED config file dataset_name: Name of the dataset dev: Whether to enable dev mode (limit to 1000 patients) + use_dask_distributed: Whether event caching uses the Dask + distributed cluster. ``False`` takes the local-scheduler path. + It does not affect the cache key. Examples: >>> from pyhealth.datasets import MIMIC4Dataset @@ -422,6 +425,7 @@ def __init__( ed_root: str | None = None, ed_tables: list[str] | None = None, ed_config_path: str | None = None, + use_dask_distributed: bool = True, ): log_memory_usage("Starting MIMIC4Dataset init") @@ -451,6 +455,7 @@ def __init__( dev=dev, cache_dir=cache_dir, num_workers=num_workers, + use_dask_distributed=use_dask_distributed, ) # Initialize child datasets @@ -468,6 +473,7 @@ def __init__( cache_dir=str(self.cache_dir), dev=dev, num_workers=num_workers, + use_dask_distributed=use_dask_distributed, ) log_memory_usage("After EHR dataset initialization") @@ -483,6 +489,7 @@ def __init__( cache_dir=str(self.cache_dir), dev=dev, num_workers=num_workers, + use_dask_distributed=use_dask_distributed, ) log_memory_usage("After Note dataset initialization") @@ -498,6 +505,7 @@ def __init__( cache_dir=str(self.cache_dir), dev=dev, num_workers=num_workers, + use_dask_distributed=use_dask_distributed, ) log_memory_usage("After CXR dataset initialization") @@ -512,6 +520,7 @@ def __init__( cache_dir=str(self.cache_dir), dev=dev, num_workers=num_workers, + use_dask_distributed=use_dask_distributed, ) log_memory_usage("After ED dataset initialization") diff --git a/pyhealth/datasets/utils.py b/pyhealth/datasets/utils.py index e0e596d7be..7ea4890608 100644 --- a/pyhealth/datasets/utils.py +++ b/pyhealth/datasets/utils.py @@ -9,11 +9,11 @@ import litdata import torch from dateutil.parser import parse as dateutil_parse -from torch.nn.utils.rnn import pad_sequence from torch.utils.data import DataLoader from pyhealth import BASE_CACHE_PATH from pyhealth.utils import create_directory +from pyhealth.datasets.collate import _event_pad_mask, _pad_stack, _stack_positions MODULE_CACHE_PATH = os.path.join(BASE_CACHE_PATH, "datasets") create_directory(MODULE_CACHE_PATH) @@ -240,6 +240,9 @@ def _restore_from_cache(sample: Dict[str, Any]) -> Dict[str, Any]: return restored +PAD_MASK_SUFFIX = "__pad_mask" + + def collate_fn_dict(batch: List[dict]) -> dict: """Collates a batch of data into a dictionary of lists. @@ -286,39 +289,19 @@ def collate_fn_dict_with_padding( if collators is not None and key in collators: collated[key] = collators[key](values) - # Check if this is a temporal feature tuple (time, values) + # A collator that sets emits_pad_mask (see TupleTimeTextProcessor) + # also gets the event mask of its batch. + owner = getattr(collators[key], "__self__", None) + if getattr(owner, "emits_pad_mask", False): + mask = _event_pad_mask(values) + if mask is not None: + collated[f"{key}{PAD_MASK_SUFFIX}"] = mask + # Check if this is a temporal feature tuple: (time, values) elif isinstance(values[0], tuple) and len(values[0]) == 2: - # Handle (time, values) tuples from processors - time_tensors = [v[0] for v in values] - value_tensors = [v[1] for v in values] - - # Collate values - if value_tensors[0].dim() == 0: - # Scalars - collated_values = torch.stack(value_tensors) - elif all(v.shape == value_tensors[0].shape for v in value_tensors): - # All same shape - collated_values = torch.stack(value_tensors) - else: - # Variable shapes, use pad_sequence - collated_values = pad_sequence( - value_tensors, batch_first=True, padding_value=0 - ) - - # Collate times (if present) - collated_times = None - # Check if ALL samples have time (not just some) - if all(t is not None for t in time_tensors): - time_tensors_all = [t for t in time_tensors if t is not None] - if all(t.shape == time_tensors_all[0].shape for t in time_tensors_all): - collated_times = torch.stack(time_tensors_all) - else: - collated_times = pad_sequence( - time_tensors_all, batch_first=True, padding_value=0 - ) - - # Return as tuple (time, values) - collated[key] = (collated_times, collated_values) + collated[key] = _stack_positions(values) + mask = _event_pad_mask(values) + if mask is not None: + collated[f"{key}{PAD_MASK_SUFFIX}"] = mask # PyG Data objects (graph processor output) elif HAS_PYG and isinstance(values[0], PyGData): collated[key] = PyGBatch.from_data_list(values) @@ -335,9 +318,7 @@ def collate_fn_dict_with_padding( # Scalars, treat as stackable collated[key] = torch.stack(values) elif values[0].dim() >= 1: - collated[key] = pad_sequence( - values, batch_first=True, padding_value=0 - ) + collated[key] = _pad_stack(values) else: raise ValueError(f"Unsupported tensor shape: {values[0].shape}") else: diff --git a/pyhealth/models/__init__.py b/pyhealth/models/__init__.py index 9442d0f2ad..5443ba5038 100644 --- a/pyhealth/models/__init__.py +++ b/pyhealth/models/__init__.py @@ -30,6 +30,7 @@ ) from .transformer_deid import TransformerDeID from .biot import BIOT +from .bottleneck_transformer import BottleneckTransformer as BottleneckTransformer from .cnn import CNN, CNNLayer from .concare import ConCare, ConCareLayer from .contrawr import ContraWR, ResBlock2D diff --git a/pyhealth/models/bottleneck_transformer.py b/pyhealth/models/bottleneck_transformer.py new file mode 100644 index 0000000000..3df7098215 --- /dev/null +++ b/pyhealth/models/bottleneck_transformer.py @@ -0,0 +1,540 @@ +from typing import Any, cast + +import torch +from torch import nn + +from pyhealth.datasets import SampleDataset +from pyhealth.datasets.utils import PAD_MASK_SUFFIX +from pyhealth.models import BaseModel +from pyhealth.models.embedding import EmbeddingModel +from pyhealth.models.unified_embedding import UnifiedMultimodalEmbeddingModel + + +class MultimodalBottleneckTransformerEncoder(nn.Module): + """ + Generalized Bottleneck Transformer Encoder for N modalities. + Based on "Attention Bottlenecks for Multimodal Fusion" (Nagrani et al., NeurIPS 2021). + + Example: + >>> import torch + >>> from pyhealth.models.bottleneck_transformer import ( + ... MultimodalBottleneckTransformerEncoder, + ... ) + >>> encoder = MultimodalBottleneckTransformerEncoder( + ... n_modality=2, bottlenecks_n=2, fusion_startidx=1, + ... n_layers=2, n_head=2, d_model=8, d_ff=16, + ... ) + >>> masks = [ + ... torch.ones(1, 3, dtype=torch.bool), + ... torch.ones(1, 2, dtype=torch.bool), + ... ] + >>> out = encoder([torch.zeros(1, 3, 8), torch.zeros(1, 2, 8)], masks) + >>> [o.shape for o in out] + [torch.Size([1, 3, 8]), torch.Size([1, 2, 8])] + """ + + def __init__( + self, + n_modality: int, + bottlenecks_n: int, + fusion_startidx: int, + n_layers: int, + n_head: int, + d_model: int, + d_ff: int, + dropout: float = 0.1, + ): + super().__init__() + + self.n_modality = n_modality + self.fusion_startidx = fusion_startidx + self.n_layers = n_layers + self.n_fusion_layers = n_layers - fusion_startidx + self.n_prefusion = fusion_startidx + self.d_model = d_model + self.n_bottlenecks = bottlenecks_n + + # Shared Bottleneck Tokens — small init to avoid early gradient explosion + self.bottlenecks = nn.Parameter(torch.randn(1, bottlenecks_n, d_model) * 0.02) + + # Prefusion Stacks: independent layers per modality + self.prefusion_stacks = nn.ModuleList([ + nn.ModuleList([ + nn.TransformerEncoderLayer( + d_model=d_model, + nhead=n_head, + dim_feedforward=d_ff, + dropout=dropout, + batch_first=True + ) for _ in range(n_modality) + ]) for _ in range(self.n_prefusion) + ]) + + # Fusion Stacks: processes [bottleneck_tokens || modality_tokens] + self.fusion_stacks = nn.ModuleList([ + nn.ModuleList([ + nn.TransformerEncoderLayer( + d_model=d_model, + nhead=n_head, + dim_feedforward=d_ff, + dropout=dropout, + batch_first=True + ) for _ in range(n_modality) + ]) for _ in range(self.n_fusion_layers) + ]) + + def forward_prefusion(self, enc_inputs: list[torch.Tensor], masks: list[torch.Tensor]) -> list[torch.Tensor]: + for enc_layers in self.prefusion_stacks: + enc_outputs = [] + for modal_idx, enc_layer in enumerate(enc_layers): + # Apply mask to padding tokens (src_key_padding_mask requires True for ignoring) + # True in mask = invalid/padding + enc_out = enc_layer(enc_inputs[modal_idx], src_key_padding_mask=~masks[modal_idx] if masks[modal_idx] is not None else None) + enc_outputs.append(enc_out) + enc_inputs = enc_outputs + return enc_inputs + + def forward_fusion(self, enc_inputs: list[torch.Tensor], masks: list[torch.Tensor], bottleneck_tokens: torch.Tensor, valid_modalities: list[torch.Tensor]) -> list[torch.Tensor]: + # valid_modalities: [B] list of boolean/float tensors indicating if modality is present + batch_size = enc_inputs[0].size(0) + + for modality_encoders in self.fusion_stacks: + enc_outputs = [] + bottleneck_tokens_modality_sum = torch.zeros_like(bottleneck_tokens) + sum_of_modalities = torch.zeros(batch_size, 1, 1, device=bottleneck_tokens.device) + + for idx, enc_layer in enumerate(modality_encoders): + # Concatenate bottleneck tokens with modality tokens + # bottleneck_tokens: [B, num_bottlenecks, d_model] + # enc_inputs[idx]: [B, seq_len, d_model] + fused_input = torch.cat([bottleneck_tokens, enc_inputs[idx]], dim=1) + + # Padding mask for bottleneck tokens is always False (i.e. valid) + # [B, num_bottlenecks] of False + b_mask = torch.zeros(batch_size, self.n_bottlenecks, dtype=torch.bool, device=fused_input.device) + + # Modality padding mask + m_mask = ~masks[idx] if masks[idx] is not None else torch.zeros(batch_size, enc_inputs[idx].size(1), dtype=torch.bool, device=fused_input.device) + + combined_mask = torch.cat([b_mask, m_mask], dim=1) + + # Pass through the layer + enc_out = enc_layer(fused_input, src_key_padding_mask=combined_mask) + + # The output consists of processed bottleneck tokens and modality tokens + # [B, num_bottlenecks, d_model] and [B, seq_len, d_model] + bottleneck_hidden_tokens = enc_out[:, :self.n_bottlenecks, :] + modality_hidden_tokens = enc_out[:, self.n_bottlenecks:, :] + enc_outputs.append(modality_hidden_tokens) + + # Average updated bottlenecks from valid modalities + modality_is_valid = valid_modalities[idx].view(batch_size, 1, 1) + bottleneck_tokens_modality_sum += bottleneck_hidden_tokens * modality_is_valid + sum_of_modalities += modality_is_valid + + # Prevent division by zero if all modalities are missing + # If sum_of_modalities is 0, just pass zeros (or keep previous bottleneck_tokens) + # sum_of_modalities = torch.clamp(sum_of_modalities, min=1.0) + avg_divisor = sum_of_modalities.clone() + avg_divisor[avg_divisor == 0] = 1.0 + + bottleneck_tokens = bottleneck_tokens_modality_sum / avg_divisor + enc_inputs = enc_outputs + + return enc_inputs + + def forward(self, enc_inputs: list[torch.Tensor], masks: list[torch.Tensor]) -> list[torch.Tensor]: + batch_size = enc_inputs[0].size(0) + + # Determine if a modality is valid for each instance in the batch + # A modality is valid if it has at least one True in its mask + valid_modalities = [] + for mask, inp in zip(masks, enc_inputs): + if mask is not None: + # [B] - True if there's any valid token (1/True) + valid = mask.any(dim=1).float() + else: + valid = torch.ones(batch_size, device=inp.device) + valid_modalities.append(valid) + + bottleneck_tokens = self.bottlenecks.expand(batch_size, -1, -1) + + enc_inputs = self.forward_prefusion(enc_inputs, masks) + enc_inputs = self.forward_fusion(enc_inputs, masks, bottleneck_tokens, valid_modalities) + + return enc_inputs + + +class BottleneckTransformer(BaseModel): + """Bottleneck Transformer model for PyHealth datasets. + + Per-field mode: each feature stream is embedded with :class:`EmbeddingModel`, + prefixed with a learnable per-modality ``[CLS]`` token, processed by + independent prefusion layers, then fused via shared bottleneck tokens. + The per-modality ``[CLS]`` embeddings are averaged and fed to the + classification head. + + Unified mode (``unified_embedding`` supplied): all temporal fields are + jointly embedded and time-sorted by + :class:`~pyhealth.models.embedding.unified.UnifiedMultimodalEmbeddingModel` + into a single interleaved sequence. A single ``[CLS]`` token is prepended + and the encoder runs with ``n_modality=1``, so the bottleneck tokens attend + over the full cross-modal timeline. + + Args: + dataset (SampleDataset): dataset providing processed inputs. + embedding_dim (int): shared embedding dimension. + bottlenecks_n (int): number of shared bottleneck tokens. + fusion_startidx (int): layer index at which bottleneck fusion starts. + Must satisfy ``0 <= fusion_startidx <= num_layers``. + num_layers (int): total transformer layers (prefusion + fusion). + heads (int): number of attention heads per transformer block. + dropout (float): dropout rate inside transformer blocks. + unified_embedding (UnifiedMultimodalEmbeddingModel, optional): when + provided, switches to unified mode. + + Examples: + >>> from pyhealth.datasets import create_sample_dataset, get_dataloader + >>> samples = [ + ... { + ... "patient_id": "patient-0", + ... "visit_id": "visit-0", + ... "conditions": ["A", "B", "C"], + ... "procedures": ["X", "Y"], + ... "label": 1, + ... }, + ... { + ... "patient_id": "patient-1", + ... "visit_id": "visit-0", + ... "conditions": ["D"], + ... "procedures": ["Z", "Y"], + ... "label": 0, + ... }, + ... ] + >>> input_schema = {"conditions": "sequence", "procedures": "sequence"} + >>> output_schema = {"label": "binary"} + >>> dataset = create_sample_dataset( + ... samples, + ... input_schema, + ... output_schema, + ... dataset_name="demo", + ... ) + >>> model = BottleneckTransformer(dataset=dataset, num_layers=3, fusion_startidx=1, bottlenecks_n=4) + >>> loader = get_dataloader(dataset, batch_size=2, shuffle=True) + >>> batch = next(iter(loader)) + >>> output = model(**batch) + >>> sorted(output.keys()) + ['logit', 'loss', 'y_prob', 'y_true'] + """ + + def __init__( + self, + dataset: SampleDataset, + embedding_dim: int = 128, + bottlenecks_n: int = 4, + fusion_startidx: int = 1, + num_layers: int = 3, + heads: int = 4, + dropout: float = 0.5, + unified_embedding: UnifiedMultimodalEmbeddingModel | None = None, + ): + super().__init__(dataset=dataset) + self.embedding_dim = embedding_dim + self.bottlenecks_n = bottlenecks_n + self.fusion_startidx = fusion_startidx + self.num_layers = num_layers + self.heads = heads + self.dropout = dropout + self._use_unified = unified_embedding is not None + + assert ( + len(self.label_keys) == 1 + ), "Only one label key is supported if BottleneckTransformer is initialized" + self.label_key = self.label_keys[0] + + assert 0 <= fusion_startidx <= num_layers, ( + f"fusion_startidx must be in [0, num_layers], got {fusion_startidx}" + ) + + output_size = self.label_processor.output_size() + + if self._use_unified: + self.embedding_model = unified_embedding + # Single CLS token for the unified interleaved sequence + self.cls_token = nn.Parameter(torch.randn(1, 1, embedding_dim) * 0.02) + self.encoder = MultimodalBottleneckTransformerEncoder( + n_modality=1, + bottlenecks_n=bottlenecks_n, + fusion_startidx=fusion_startidx, + n_layers=num_layers, + n_head=heads, + d_model=embedding_dim, + d_ff=embedding_dim * 4, + dropout=dropout, + ) + else: + self.embedding_model = EmbeddingModel(dataset, embedding_dim) + self.n_modality = len(self.feature_keys) + # Per-modality CLS tokens + self.cls_token_per_modality = nn.ParameterList([ + nn.Parameter(torch.randn(1, 1, embedding_dim) * 0.02) + for _ in range(self.n_modality) + ]) + self.encoder = MultimodalBottleneckTransformerEncoder( + n_modality=self.n_modality, + bottlenecks_n=bottlenecks_n, + fusion_startidx=fusion_startidx, + n_layers=num_layers, + n_head=heads, + d_model=embedding_dim, + d_ff=embedding_dim * 4, + dropout=dropout, + ) + + # fc input is embedding_dim in both modes (CLS token, not concat) + self.fc = nn.Linear(embedding_dim, output_size) + + def _build_unified_inputs( + self, kwargs: dict[str, Any] + ) -> dict[str, dict[str, torch.Tensor]]: + """Extract value/time/mask tensors for UnifiedMultimodalEmbeddingModel.""" + inputs: dict[str, dict[str, torch.Tensor]] = {} + for field_name in self.feature_keys: + feature = kwargs[field_name] + if isinstance(feature, torch.Tensor): + feature = (feature,) + schema = self.dataset.input_processors[field_name].schema() + field_dict: dict[str, torch.Tensor] = {} + if "value" in schema: + field_dict["value"] = feature[schema.index("value")].to(self.device) + if "time" in schema: + field_dict["time"] = feature[schema.index("time")].to(self.device) + if "mask" in schema: + field_dict["mask"] = feature[schema.index("mask")].to(self.device) + pad_mask = kwargs.get(f"{field_name}{PAD_MASK_SUFFIX}") + if pad_mask is not None: + field_dict["pad_mask"] = pad_mask.to(self.device) + inputs[field_name] = field_dict + return inputs + + def _forward_unified( + self, + **kwargs: torch.Tensor | tuple[torch.Tensor, ...], + ) -> dict[str, torch.Tensor]: + """Forward pass in unified-embedding mode. + + Calls UnifiedMultimodalEmbeddingModel to produce a single time-sorted + sequence, prepends a CLS token, encodes with the bottleneck encoder + (n_modality=1), and classifies from the CLS output. + """ + inputs = self._build_unified_inputs(kwargs) + out = self.embedding_model(inputs) + sequence = out["sequence"] # (B, S, E) + event_mask = out["mask"].bool() # (B, S) + + # Prepend CLS token + batch_size = sequence.size(0) + cls = self.cls_token.expand(batch_size, -1, -1) + sequence = torch.cat([cls, sequence], dim=1) + cls_mask = torch.ones(batch_size, 1, dtype=torch.bool, device=sequence.device) + event_mask = torch.cat([cls_mask, event_mask], dim=1) + + enc_outputs = self.encoder([sequence], [event_mask]) + patient_emb = enc_outputs[0][:, 0, :] # CLS token output + + logits = self.fc(patient_emb) + y_prob = self.label_processor.activation(logits) + results: dict[str, torch.Tensor] = {"logit": logits, "y_prob": y_prob} + if self.label_key in kwargs: + y_true = cast(torch.Tensor, kwargs[self.label_key]).to(self.device) + results["loss"] = self.label_processor.loss(logits, y_true) + results["y_true"] = y_true + return results + + @staticmethod + def _pool_embedding(x: torch.Tensor) -> torch.Tensor: + if x.dim() == 4: + x = x.sum(dim=2) + if x.dim() == 2: + x = x.unsqueeze(1) + return x + + @staticmethod + def _mask_from_embeddings(x: torch.Tensor) -> torch.Tensor: + mask = torch.any(torch.abs(x) > 0, dim=-1) + if mask.dim() == 1: + mask = mask.unsqueeze(1) + invalid_rows = ~mask.any(dim=1) + if invalid_rows.any(): + mask[invalid_rows, 0] = True + return mask.bool() + + def forward( + self, + **kwargs: torch.Tensor | tuple[torch.Tensor, ...], + ) -> dict[str, torch.Tensor]: + """Forward propagation. + + In unified mode dispatches to :meth:`_forward_unified`. Otherwise runs + per-field embedding + bottleneck fusion. + + Args: + **kwargs: keyword arguments for the model. + + Returns: + A dictionary with the following keys: + loss: a scalar tensor representing the final loss. + y_prob: a tensor of predicted probabilities. + y_true: a tensor representing the true labels. + logit: the raw logits before activation. + """ + if self._use_unified: + return self._forward_unified(**kwargs) + + enc_inputs = [] + masks = [] + + for idx, feature_key in enumerate(self.feature_keys): + feature = kwargs[feature_key] + + if isinstance(feature, torch.Tensor): + feature = (feature,) + + schema = self.dataset.input_processors[feature_key].schema() + + value = feature[schema.index("value")] if "value" in schema else None + mask = feature[schema.index("mask")] if "mask" in schema else None + + if len(feature) == len(schema) + 1 and mask is None: + mask = feature[-1] + + if value is None: + raise ValueError( + f"Feature '{feature_key}' must contain 'value' " + f"in the schema." + ) + else: + value = value.to(self.device) + + if mask is not None: + mask = mask.to(self.device) + value = self.embedding_model({feature_key: value}, masks={feature_key: mask})[feature_key] + else: + value = self.embedding_model({feature_key: value})[feature_key] + + value = self._pool_embedding(value) + + if mask is not None: + mask = mask.bool() + if mask.dim() == value.dim(): + mask = mask.any(dim=-1) + else: + mask = self._mask_from_embeddings(value) + + # Prepend Modality CLS token + batch_size = value.size(0) + cls_token = self.cls_token_per_modality[idx].expand(batch_size, -1, -1) + value = torch.cat([cls_token, value], dim=1) + + # Update mask for CLS token (always valid) + cls_mask = torch.ones(batch_size, 1, dtype=torch.bool, device=value.device) + mask = torch.cat([cls_mask, mask], dim=1) + + enc_inputs.append(value) + masks.append(mask) + + # Pass through Bottleneck Transformer Encoder + enc_outputs = self.encoder(enc_inputs, masks) + + # Extract CLS tokens + cls_tokens = [out[:, 0, :].unsqueeze(1) for out in enc_outputs] + cls_tokens = torch.cat(cls_tokens, dim=1) # [B, n_modality, embedding_dim] + + # Average CLS tokens across valid modalities + b_size = cls_tokens.size(0) + valid_modalities = [] + for mask in masks: + # We check if there's any valid token aside from the CLS token (index 0) + if mask.size(1) > 1: + valid = mask[:, 1:].any(dim=1).float() + else: + valid = mask[:, 0].float() # fallback + valid_modalities.append(valid.view(b_size, 1, 1)) + + valid_modality_tensor = torch.cat(valid_modalities, dim=1) # [B, n_modality, 1] + + # Apply valid mask + masked_cls = cls_tokens * valid_modality_tensor + sum_valid = valid_modality_tensor.sum(dim=1) # [B, 1] + + # Avoid division by zero + sum_valid[sum_valid == 0] = 1.0 + patient_emb = masked_cls.sum(dim=1) / sum_valid # [B, embedding_dim] + + logits = self.fc(patient_emb) + y_prob = self.label_processor.activation(logits) + + results = { + "logit": logits, + "y_prob": y_prob, + } + + if self.label_key in kwargs: + y_true = cast(torch.Tensor, kwargs[self.label_key]).to(self.device) + loss = self.label_processor.loss(logits, y_true) + results["loss"] = loss + results["y_true"] = y_true + + return results + +if __name__ == "__main__": + from pyhealth.datasets import create_sample_dataset, get_dataloader + + samples = [ + { + "patient_id": "patient-0", + "visit_id": "visit-0", + "conditions": ["A", "B", "C"], + "procedures": ["X", "Y"], + "label": 1, + }, + { + "patient_id": "patient-1", + "visit_id": "visit-0", + "conditions": ["D"], + "procedures": ["Z", "Y"], + "label": 0, + }, + ] + + input_schema = { + "conditions": "sequence", + "procedures": "sequence", + } + output_schema = {"label": "binary"} + + dataset = create_sample_dataset( + samples=samples, + input_schema=input_schema, + output_schema=output_schema, + dataset_name="test", + ) + + train_loader = get_dataloader(dataset, batch_size=2, shuffle=True) + + model = BottleneckTransformer( + dataset=dataset, + embedding_dim=64, + bottlenecks_n=2, + fusion_startidx=1, + num_layers=3, + heads=2 + ) + + data_batch = next(iter(train_loader)) + + result = model(**data_batch) + print(result) + + result["loss"].backward() + print("Test completed successfully.") \ No newline at end of file diff --git a/pyhealth/models/ehrmamba.py b/pyhealth/models/ehrmamba.py index a81a4b81e6..67fa4ba52c 100644 --- a/pyhealth/models/ehrmamba.py +++ b/pyhealth/models/ehrmamba.py @@ -6,6 +6,8 @@ from pyhealth.datasets import SampleDataset from pyhealth.models import BaseModel from pyhealth.models.embedding import EmbeddingModel +from pyhealth.datasets.utils import PAD_MASK_SUFFIX +from pyhealth.models.unified_embedding import UnifiedMultimodalEmbeddingModel from pyhealth.models.utils import get_last_visit from pyhealth.processors import ( MultiHotProcessor, @@ -111,6 +113,11 @@ class EHRMamba(BaseModel): Electronic Health Records (arxiv 2405.14567). Uses Mamba (SSM) for linear complexity in sequence length; supports long EHR sequences. + When ``unified_embedding`` is supplied the model switches to **unified + mode**: all temporal fields are jointly embedded and time-sorted by + :class:`UnifiedMultimodalEmbeddingModel`, then processed by a *single* + stack of :class:`MambaBlock` layers rather than one stack per field. + Args: dataset: SampleDataset for token/embedding setup. embedding_dim: Embedding and hidden dimension. Default 128. @@ -118,6 +125,8 @@ class EHRMamba(BaseModel): state_size: SSM state size per channel. Default 16. conv_kernel: Causal conv kernel size in block. Default 4. dropout: Dropout before classification head. Default 0.1. + unified_embedding: Optional pre-built UnifiedMultimodalEmbeddingModel. + When provided, enables unified multi-modal mode. Examples: >>> from pyhealth.datasets import create_sample_dataset, get_dataloader @@ -140,6 +149,7 @@ def __init__( state_size: int = 16, conv_kernel: int = 4, dropout: float = 0.1, + unified_embedding: UnifiedMultimodalEmbeddingModel | None = None, ): super().__init__(dataset=dataset) self.embedding_dim = embedding_dim @@ -147,18 +157,17 @@ def __init__( self.state_size = state_size self.conv_kernel = conv_kernel self.dropout_rate = dropout + self._use_unified = unified_embedding is not None assert len(self.label_keys) == 1, "EHRMamba supports single label key only" self.label_key = self.label_keys[0] - self.embedding_model = EmbeddingModel(dataset, embedding_dim) - self.feature_processors = { - k: self.dataset.input_processors[k] for k in self.feature_keys - } + output_size = self.label_processor.output_size() + self.dropout = nn.Dropout(dropout) - self.blocks = nn.ModuleDict() - for feature_key in self.feature_keys: - self.blocks[feature_key] = nn.ModuleList( + if self._use_unified: + self.embedding_model = unified_embedding + self._unified_blocks = nn.ModuleList( [ MambaBlock( d_model=embedding_dim, @@ -168,10 +177,76 @@ def __init__( for _ in range(num_layers) ] ) - - output_size = self.label_processor.output_size() - self.dropout = nn.Dropout(dropout) - self.fc = nn.Linear(len(self.feature_keys) * embedding_dim, output_size) + self.fc = nn.Linear(embedding_dim, output_size) + else: + self.embedding_model = EmbeddingModel(dataset, embedding_dim) + self.feature_processors = { + k: self.dataset.input_processors[k] for k in self.feature_keys + } + self.blocks = nn.ModuleDict() + for feature_key in self.feature_keys: + self.blocks[feature_key] = nn.ModuleList( + [ + MambaBlock( + d_model=embedding_dim, + state_size=state_size, + conv_kernel=conv_kernel, + ) + for _ in range(num_layers) + ] + ) + self.fc = nn.Linear(len(self.feature_keys) * embedding_dim, output_size) + + def _build_unified_inputs( + self, kwargs: dict[str, Any] + ) -> dict[str, dict[str, torch.Tensor]]: + """Build the inputs dict required by UnifiedMultimodalEmbeddingModel.""" + inputs: dict[str, dict[str, torch.Tensor]] = {} + for field_name in self.feature_keys: + feature = kwargs[field_name] + if isinstance(feature, torch.Tensor): + feature = (feature,) + schema = self.dataset.input_processors[field_name].schema() + field_dict: dict[str, torch.Tensor] = {} + if "value" in schema: + field_dict["value"] = feature[schema.index("value")].to(self.device) + if "time" in schema: + field_dict["time"] = feature[schema.index("time")].to(self.device) + if "mask" in schema: + field_dict["mask"] = feature[schema.index("mask")].to(self.device) + pad_mask = kwargs.get(f"{field_name}{PAD_MASK_SUFFIX}") + if pad_mask is not None: + field_dict["pad_mask"] = pad_mask.to(self.device) + inputs[field_name] = field_dict + return inputs + + def _forward_unified(self, **kwargs) -> dict[str, torch.Tensor]: + """Forward pass in unified-embedding mode. + + Calls UnifiedMultimodalEmbeddingModel to produce a single + temporally-sorted event sequence, then encodes it with one shared + MambaBlock stack and pools to the last valid event. + """ + inputs = self._build_unified_inputs(kwargs) + out = self.embedding_model(inputs) + x = out["sequence"] # (B, S_total, E) + mask = out["mask"].bool() # (B, S_total) + + for blk in self._unified_blocks: + x = blk(x) + + last_h = get_last_visit(x, mask) + logits = self.fc(self.dropout(last_h)) + y_prob = self.label_processor.activation(logits) + results: dict[str, torch.Tensor] = {"y_prob": y_prob, "logit": logits} + # The label is optional, so the model can predict without it. + if self.label_key in kwargs: + y_true = kwargs[self.label_key].to(self.device) + results["loss"] = self.label_processor.loss(logits, y_true) + results["y_true"] = y_true + if kwargs.get("embed", False): + results["embed"] = last_h + return results @staticmethod def _split_temporal(feature: Any) -> Tuple[Optional[torch.Tensor], Any]: @@ -222,6 +297,9 @@ def _pool_embedding(x: torch.Tensor) -> torch.Tensor: return x def forward(self, **kwargs) -> Dict[str, torch.Tensor]: + if self._use_unified: + return self._forward_unified(**kwargs) + patient_emb = [] embedding_inputs: Dict[str, torch.Tensor] = {} masks: Dict[str, torch.Tensor] = {} diff --git a/pyhealth/models/jamba_ehr.py b/pyhealth/models/jamba_ehr.py index c392dd0ed6..1c212c8e07 100644 --- a/pyhealth/models/jamba_ehr.py +++ b/pyhealth/models/jamba_ehr.py @@ -15,6 +15,8 @@ from pyhealth.datasets import SampleDataset from pyhealth.models import BaseModel from pyhealth.models.embedding import EmbeddingModel +from pyhealth.datasets.utils import PAD_MASK_SUFFIX +from pyhealth.models.unified_embedding import UnifiedMultimodalEmbeddingModel from pyhealth.models.transformer import TransformerBlock from pyhealth.models.ehrmamba import MambaBlock from pyhealth.models.utils import get_last_visit @@ -177,6 +179,11 @@ class JambaEHR(BaseModel): by an independent :class:`JambaLayer`. The resulting patient embeddings are concatenated and projected through a classification head. + When ``unified_embedding`` is supplied the model switches to **unified + mode**: all temporal fields are jointly embedded and time-sorted by + :class:`UnifiedMultimodalEmbeddingModel`, then processed by a *single* + :class:`JambaLayer` rather than one layer per field. + Args: dataset (SampleDataset): Dataset providing processed inputs. embedding_dim (int): Embedding and hidden dimension. Default 128. @@ -186,6 +193,8 @@ class JambaEHR(BaseModel): dropout (float): Dropout rate. Default 0.3. state_size (int): SSM state size in Mamba blocks. Default 16. conv_kernel (int): Causal conv kernel in Mamba blocks. Default 4. + unified_embedding (UnifiedMultimodalEmbeddingModel, optional): when + provided, enables unified multi-modal mode with a single JambaLayer. Examples: >>> from pyhealth.datasets import create_sample_dataset, get_dataloader @@ -234,6 +243,7 @@ def __init__( dropout: float = 0.3, state_size: int = 16, conv_kernel: int = 4, + unified_embedding: UnifiedMultimodalEmbeddingModel | None = None, ): super(JambaEHR, self).__init__(dataset=dataset) self.embedding_dim = embedding_dim @@ -243,17 +253,19 @@ def __init__( self.dropout_rate = dropout self.state_size = state_size self.conv_kernel = conv_kernel + self._use_unified = unified_embedding is not None assert ( len(self.label_keys) == 1 ), "Only one label key is supported if JambaEHR is initialized" self.label_key = self.label_keys[0] - self.embedding_model = EmbeddingModel(dataset, embedding_dim) + output_size = self.label_processor.output_size() + self.dropout = nn.Dropout(dropout) - self.jamba: nn.ModuleDict = nn.ModuleDict() - for feature_key in self.feature_keys: - self.jamba[feature_key] = JambaLayer( + if self._use_unified: + self.embedding_model = unified_embedding + self._unified_jamba = JambaLayer( feature_size=embedding_dim, num_transformer_layers=num_transformer_layers, num_mamba_layers=num_mamba_layers, @@ -262,12 +274,62 @@ def __init__( state_size=state_size, conv_kernel=conv_kernel, ) + self.fc = nn.Linear(embedding_dim, output_size) + else: + self.embedding_model = EmbeddingModel(dataset, embedding_dim) + self.jamba: nn.ModuleDict = nn.ModuleDict() + for feature_key in self.feature_keys: + self.jamba[feature_key] = JambaLayer( + feature_size=embedding_dim, + num_transformer_layers=num_transformer_layers, + num_mamba_layers=num_mamba_layers, + heads=heads, + dropout=dropout, + state_size=state_size, + conv_kernel=conv_kernel, + ) + self.fc = nn.Linear(len(self.feature_keys) * embedding_dim, output_size) + + def _build_unified_inputs( + self, kwargs: dict[str, Any] + ) -> dict[str, dict[str, torch.Tensor]]: + inputs: dict[str, dict[str, torch.Tensor]] = {} + for field_name in self.feature_keys: + feature = kwargs[field_name] + if isinstance(feature, torch.Tensor): + feature = (feature,) + schema = self.dataset.input_processors[field_name].schema() + field_dict: dict[str, torch.Tensor] = {} + if "value" in schema: + field_dict["value"] = feature[schema.index("value")].to(self.device) + if "time" in schema: + field_dict["time"] = feature[schema.index("time")].to(self.device) + if "mask" in schema: + field_dict["mask"] = feature[schema.index("mask")].to(self.device) + pad_mask = kwargs.get(f"{field_name}{PAD_MASK_SUFFIX}") + if pad_mask is not None: + field_dict["pad_mask"] = pad_mask.to(self.device) + inputs[field_name] = field_dict + return inputs + + def _forward_unified(self, **kwargs: Any) -> dict[str, torch.Tensor]: + inputs = self._build_unified_inputs(kwargs) + out = self.embedding_model(inputs) + sequence = out["sequence"] + mask = out["mask"] + + _, cls_emb = self._unified_jamba(sequence, mask) + logits = self.fc(self.dropout(cls_emb)) + y_prob = self.label_processor.activation(logits) - output_size = self.label_processor.output_size() - self.dropout = nn.Dropout(dropout) - self.fc = nn.Linear( - len(self.feature_keys) * embedding_dim, output_size - ) + results: dict[str, torch.Tensor] = {"logit": logits, "y_prob": y_prob} + if self.label_key in kwargs: + y_true = cast(torch.Tensor, kwargs[self.label_key]).to(self.device) + results["loss"] = self.label_processor.loss(logits, y_true) + results["y_true"] = y_true + if kwargs.get("embed", False): + results["embed"] = cls_emb + return results @staticmethod def _pool_embedding(x: torch.Tensor) -> torch.Tensor: @@ -318,7 +380,9 @@ def forward( Embeds each feature stream, encodes through the hybrid Transformer-Mamba stack, concatenates per-stream patient - representations, and projects to label space. + representations, and projects to label space. In **unified mode** + (when ``unified_embedding`` was supplied at init) all temporal + fields share one time-sorted sequence through a single backbone. Args: **kwargs: Must include all feature keys (tensors or tuples @@ -329,6 +393,9 @@ def forward( ``y_prob``, ``y_true``, ``logit``, and optionally ``embed`` if ``kwargs["embed"] is True``. """ + if self._use_unified: + return self._forward_unified(**kwargs) + patient_emb = [] for feature_key in self.feature_keys: @@ -477,4 +544,4 @@ def forward( out = model_m(**batch) print("keys:", sorted(out.keys())) out["loss"].backward() - print("backward OK") \ No newline at end of file + print("backward OK") diff --git a/pyhealth/models/mlp.py b/pyhealth/models/mlp.py index 4b86a5b939..09303685bf 100644 --- a/pyhealth/models/mlp.py +++ b/pyhealth/models/mlp.py @@ -1,13 +1,15 @@ -from typing import Dict, cast +from typing import Any, cast import torch import torch.nn as nn from pyhealth.datasets import SampleDataset -from pyhealth.models import BaseModel +from pyhealth.datasets.utils import PAD_MASK_SUFFIX from pyhealth.interpret.api import Interpretable +from pyhealth.models import BaseModel from .embedding import EmbeddingModel +from .unified_embedding import UnifiedMultimodalEmbeddingModel from .utils import get_step_mask, masked_mean_pooling @@ -61,6 +63,9 @@ class MLP(BaseModel, Interpretable): hidden_dim: the hidden dimension. Default is 128. n_layers: the number of layers. Default is 2. activation: the activation function. Default is "relu". + unified_embedding (UnifiedMultimodalEmbeddingModel, optional): when + provided, the model mean-pools one unified event sequence through + a single MLP instead of per-field MLPs. **kwargs: other parameters for the MLP layer. Examples: @@ -118,12 +123,14 @@ def __init__( hidden_dim: int = 128, n_layers: int = 2, activation: str = "relu", + unified_embedding: UnifiedMultimodalEmbeddingModel | None = None, **kwargs, ): super(MLP, self).__init__(dataset) self.embedding_dim = embedding_dim self.hidden_dim = hidden_dim self.n_layers = n_layers + self._use_unified = unified_embedding is not None # validate kwargs for MLP layer if "input_size" in kwargs: @@ -134,9 +141,6 @@ def __init__( assert len(self.label_keys) == 1, "Only one label key is supported" self.label_key = self.label_keys[0] - # Use the EmbeddingModel to handle embedding logic - self.embedding_model = EmbeddingModel(dataset, embedding_dim) - # Set up activation function if activation == "relu": self.activation = nn.ReLU() @@ -151,18 +155,73 @@ def __init__( else: raise ValueError(f"Unsupported activation function {activation}") - # Create MLP layers for each feature - self.mlp = nn.ModuleDict() - for feature_key in self.feature_keys: - Modules = [] - Modules.append(nn.Linear(self.embedding_dim, self.hidden_dim)) - for _ in range(self.n_layers - 1): - Modules.append(self.activation) - Modules.append(nn.Linear(self.hidden_dim, self.hidden_dim)) - self.mlp[feature_key] = nn.Sequential(*Modules) - output_size = self.label_processor.output_size() - self.fc = nn.Linear(len(self.feature_keys) * self.hidden_dim, output_size) + + if self._use_unified: + self.embedding_model = unified_embedding + modules = [nn.Linear(embedding_dim, hidden_dim)] + for _ in range(n_layers - 1): + modules.extend([self.activation, nn.Linear(hidden_dim, hidden_dim)]) + self.mlp = nn.ModuleDict({"unified": nn.Sequential(*modules)}) + self.fc = nn.Linear(hidden_dim, output_size) + else: + # Use the EmbeddingModel to handle embedding logic + self.embedding_model = EmbeddingModel(dataset, embedding_dim) + # Create MLP layers for each feature + self.mlp = nn.ModuleDict() + for feature_key in self.feature_keys: + Modules = [] + Modules.append(nn.Linear(self.embedding_dim, self.hidden_dim)) + for _ in range(self.n_layers - 1): + Modules.append(self.activation) + Modules.append(nn.Linear(self.hidden_dim, self.hidden_dim)) + self.mlp[feature_key] = nn.Sequential(*Modules) + self.fc = nn.Linear(len(self.feature_keys) * self.hidden_dim, output_size) + + def _build_unified_inputs( + self, kwargs: dict[str, Any] + ) -> dict[str, dict[str, torch.Tensor]]: + inputs: dict[str, dict[str, torch.Tensor]] = {} + for field_name in self.feature_keys: + feature = kwargs[field_name] + if isinstance(feature, torch.Tensor): + feature = (feature,) + schema = self.dataset.input_processors[field_name].schema() + field_dict: dict[str, torch.Tensor] = {} + if "value" in schema: + field_dict["value"] = feature[schema.index("value")].to(self.device) + if "time" in schema: + field_dict["time"] = feature[schema.index("time")].to(self.device) + if "mask" in schema: + field_dict["mask"] = feature[schema.index("mask")].to(self.device) + pad_mask = kwargs.get(f"{field_name}{PAD_MASK_SUFFIX}") + if pad_mask is not None: + field_dict["pad_mask"] = pad_mask.to(self.device) + inputs[field_name] = field_dict + return inputs + + def _forward_unified(self, **kwargs: Any) -> dict[str, torch.Tensor]: + inputs = self._build_unified_inputs(kwargs) + out = self.embedding_model(inputs) + sequence = out["sequence"] + mask = out["mask"].float() + + # Masked mean-pool over the event sequence + x = (sequence * mask.unsqueeze(-1)).sum(dim=1) + x = x / mask.sum(dim=1, keepdim=True).clamp(min=1) + + x = self.mlp["unified"](x) + logits = self.fc(x) + y_prob = self.label_processor.activation(logits) + + results: dict[str, torch.Tensor] = {"logit": logits, "y_prob": y_prob} + if self.label_key in kwargs: + y_true = cast(torch.Tensor, kwargs[self.label_key]).to(self.device) + results["loss"] = self.label_processor.loss(logits, y_true) + results["y_true"] = y_true + if kwargs.get("embed", False): + results["embed"] = x + return results @staticmethod def mean_pooling(x, mask): @@ -208,7 +267,7 @@ def sum_pooling(x): def forward_from_embedding( self, **kwargs: torch.Tensor | tuple[torch.Tensor, ...], - ) -> Dict[str, torch.Tensor]: + ) -> dict[str, torch.Tensor]: """Forward pass starting from feature embeddings. This method bypasses the embedding layers and processes @@ -327,9 +386,14 @@ def forward_from_embedding( def forward( self, **kwargs: torch.Tensor | tuple[torch.Tensor, ...] - ) -> Dict[str, torch.Tensor]: + ) -> dict[str, torch.Tensor]: """Forward propagation. + In **unified mode** (when ``unified_embedding`` was supplied at init) + the model jointly embeds all temporal fields, mean-pools the event + sequence, and processes it with a single MLP. Otherwise each field + is embedded and encoded independently. + Args: **kwargs: keyword arguments for the model. @@ -347,6 +411,9 @@ def forward( logit: the raw logits before activation. embed: (if embed=True in kwargs) the patient embedding. """ + if self._use_unified: + return self._forward_unified(**kwargs) + for feature_key in self.feature_keys: feature = kwargs[feature_key] diff --git a/pyhealth/models/rnn.py b/pyhealth/models/rnn.py index 7c29708697..02ecfd57f2 100644 --- a/pyhealth/models/rnn.py +++ b/pyhealth/models/rnn.py @@ -25,6 +25,8 @@ from .embedding import EmbeddingModel from .utils import mask_lengths +from pyhealth.datasets.utils import PAD_MASK_SUFFIX +from .unified_embedding import UnifiedMultimodalEmbeddingModel from .sequence_embedding import ( LevelEmbedding, MaskMode, @@ -174,6 +176,10 @@ class RNN(BaseModel): embedding_dim (int): the embedding dimension. Default is 128. hidden_dim (int): the hidden dimension. Default is 128. **kwargs: other parameters for the RNN layer (e.g., rnn_type, num_layers, dropout, bidirectional). + unified_embedding (UnifiedMultimodalEmbeddingModel, optional): when + provided, the model jointly embeds all temporal fields as a single + time-sorted sequence through one RNN. Defaults to None + (per-field mode). Examples: >>> from pyhealth.datasets import create_sample_dataset @@ -222,6 +228,7 @@ def __init__( dataset: SampleDataset, embedding_dim: int = 128, hidden_dim: int = 128, + unified_embedding: UnifiedMultimodalEmbeddingModel | None = None, **kwargs ): super(RNN, self).__init__( @@ -229,6 +236,7 @@ def __init__( ) self.embedding_dim = embedding_dim self.hidden_dim = hidden_dim + self._use_unified = unified_embedding is not None # validate kwargs for RNN layer if "input_size" in kwargs: raise ValueError("input_size is determined by embedding_dim") @@ -243,21 +251,74 @@ def __init__( "RNN_V2 with jagged inputs." ) - self.embedding_model = EmbeddingModel(dataset, embedding_dim) - - self.rnn = nn.ModuleDict() - for feature_key in self.dataset.input_processors.keys(): - self.rnn[feature_key] = RNNLayer( - input_size=embedding_dim, hidden_size=hidden_dim, **kwargs - ) output_size = self.label_processor.output_size() - self.fc = nn.Linear(len(self.feature_keys) * self.hidden_dim, output_size) + + if self._use_unified: + self.embedding_model = unified_embedding + self.rnn = nn.ModuleDict({ + "unified": RNNLayer(input_size=embedding_dim, hidden_size=hidden_dim, **kwargs) + }) + self.fc = nn.Linear(hidden_dim, output_size) + else: + self.embedding_model = EmbeddingModel(dataset, embedding_dim) + self.rnn = nn.ModuleDict() + for feature_key in self.dataset.input_processors: + self.rnn[feature_key] = RNNLayer( + input_size=embedding_dim, hidden_size=hidden_dim, **kwargs + ) + self.fc = nn.Linear(len(self.feature_keys) * self.hidden_dim, output_size) + + def _build_unified_inputs( + self, kwargs: dict[str, Any] + ) -> dict[str, dict[str, torch.Tensor]]: + inputs: dict[str, dict[str, torch.Tensor]] = {} + for field_name in self.feature_keys: + feature = kwargs[field_name] + if isinstance(feature, torch.Tensor): + feature = (feature,) + schema = self.dataset.input_processors[field_name].schema() + field_dict: dict[str, torch.Tensor] = {} + if "value" in schema: + field_dict["value"] = feature[schema.index("value")].to(self.device) + if "time" in schema: + field_dict["time"] = feature[schema.index("time")].to(self.device) + if "mask" in schema: + field_dict["mask"] = feature[schema.index("mask")].to(self.device) + pad_mask = kwargs.get(f"{field_name}{PAD_MASK_SUFFIX}") + if pad_mask is not None: + field_dict["pad_mask"] = pad_mask.to(self.device) + inputs[field_name] = field_dict + return inputs + + def _forward_unified(self, **kwargs: Any) -> dict[str, torch.Tensor]: + inputs = self._build_unified_inputs(kwargs) + out = self.embedding_model(inputs) + sequence = out["sequence"] + mask = out["mask"].int() + + _, last_hidden = self.rnn["unified"](sequence, mask) + logits = self.fc(last_hidden) + y_prob = self.label_processor.activation(logits) + results = {"y_prob": y_prob, "logit": logits} + # The label is optional, so the model can predict without it. + if self.label_key in kwargs: + y_true = kwargs[self.label_key].to(self.device) + results["loss"] = self.label_processor.loss(logits, y_true) + results["y_true"] = y_true + if kwargs.get("embed", False): + results["embed"] = last_hidden + return results def forward(self, **kwargs) -> dict[str, torch.Tensor]: """Forward propagation. The label `kwargs[self.label_key]` is a list of labels for each patient. + In **unified mode** (when ``unified_embedding`` was supplied at init) + the model jointly embeds all temporal fields as a single time-sorted + sequence and processes it with one RNN. Otherwise each field is + embedded and encoded independently. + Args: **kwargs: keyword arguments for the model. The keys must contain all the feature keys and the label key. @@ -270,6 +331,9 @@ def forward(self, **kwargs) -> dict[str, torch.Tensor]: - logit: a tensor representing the logits. - embed (optional): a tensor representing the patient embeddings if requested. """ + if self._use_unified: + return self._forward_unified(**kwargs) + patient_emb = [] # We need to preprocess kwargs to extract values and masks for EmbeddingModel diff --git a/pyhealth/models/transformer.py b/pyhealth/models/transformer.py index 9b483375eb..685ac114a6 100644 --- a/pyhealth/models/transformer.py +++ b/pyhealth/models/transformer.py @@ -7,18 +7,33 @@ from typing import Any, Dict, Optional, Tuple, Union, cast import torch +import torch.nn.functional as F from torch import nn from pyhealth.datasets import SampleDataset from pyhealth.models import BaseModel from pyhealth.models.embedding import EmbeddingModel +from pyhealth.datasets.utils import PAD_MASK_SUFFIX +from pyhealth.models.unified_embedding import UnifiedMultimodalEmbeddingModel from pyhealth.interpret.api import CheferInterpretable # VALID_OPERATION_LEVEL = ["visit", "event"] class Attention(nn.Module): - """Scaled dot-product attention helper.""" + """Scaled dot-product attention helper. + + Example: + Called inside :class:`MultiHeadedAttention` for each head. + + >>> import torch + >>> from pyhealth.models.transformer import Attention + >>> attn = Attention() + >>> q = k = torch.zeros(1, 1, 2, 4) + >>> out, weights = attn(q, k, torch.ones(1, 1, 2, 4)) + >>> out.shape + torch.Size([1, 1, 2, 4]) + """ def __init__(self): super().__init__() @@ -51,11 +66,13 @@ def forward( scores = torch.matmul(query, key.transpose(-2, -1)) / math.sqrt(query.size(-1)) if mask is not None: - # Use -inf so softmax produces exact zeros on padded positions, - # avoiding a second masked_fill after softmax (saves one full - # [B, H, S, S] boolean allocation and an extra copy). - pad_mask = (mask == 0) - scores = scores.masked_fill(pad_mask, -1e9) + # Fill with the dtype minimum (not -1e9, which is outside the + # fp16 range and overflows under AMP) so softmax produces exact + # zeros on padded positions, avoiding a second masked_fill + # after softmax (saves one full [B, H, S, S] boolean allocation + # and an extra copy). + pad_mask = mask == 0 + scores = scores.masked_fill(pad_mask, torch.finfo(scores.dtype).min) p_attn = self.softmax(scores) if dropout is not None: p_attn = dropout(p_attn) @@ -64,7 +81,15 @@ def forward( class MultiHeadedAttention(nn.Module): - """Multi-head attention wrapper used by the Transformer block.""" + """Multi-head attention wrapper used by the Transformer block. + + Example: + >>> import torch + >>> from pyhealth.models.transformer import MultiHeadedAttention + >>> mha = MultiHeadedAttention(h=2, d_model=8) + >>> mha(torch.zeros(2, 5, 8), torch.zeros(2, 5, 8), torch.zeros(2, 5, 8)).shape + torch.Size([2, 5, 8]) + """ def __init__(self, h: int, d_model: int, dropout: float = 0.1): """Initialize the attention module. @@ -149,19 +174,45 @@ def forward( ] # 2) Apply attention on all the projected vectors in batch. - if mask is not None: - mask = mask.unsqueeze(1) - x, attn = self.attention(query, key, value, mask=mask, dropout=self.dropout) - - if register_hook: - # Only store attn_map and hook during interpretability passes. - # Using .detach() gives an independent copy whose storage - # is NOT shared with the live graph, so the graph can be freed - # normally after .backward() without leaking GPU memory. + # Ordinary training uses fused SDPA. The explicit path stays behind + # register_hook=True for interpretability. + if not register_hook: + query_mask = None + attn_mask = None + if mask is not None: + valid = mask.bool() + if mask.dim() == 2: + query_mask = valid[:, None, :, None] + attn_mask = valid[:, None, None, :] + else: + query_mask = valid.any(dim=-1)[:, None, :, None] + attn_mask = valid.unsqueeze(1) + # A fully-masked query row attends to nothing, which is NaN + # or garbage depending on backend and dtype. Let such rows + # attend uniformly, then zero their outputs below. + attn_mask = attn_mask | ~attn_mask.any(dim=-1, keepdim=True) + x = F.scaled_dot_product_attention( + query, + key, + value, + attn_mask=attn_mask, + dropout_p=self.dropout.p if self.training else 0.0, + ) + if query_mask is not None: + x = x * query_mask.to(x.dtype) + self.attn_map = None + self.attn_gradients = None + else: + if mask is not None: + mask = mask.unsqueeze(1) + x, attn = self.attention( + query, key, value, mask=mask, dropout=self.dropout + ) + # .detach() gives a copy whose storage is NOT shared with the + # live graph, so the graph can be freed normally after + # .backward() without leaking GPU memory. self.attn_map = attn.detach() attn.register_hook(self.save_attn_grad) - else: - self.attn_map = None # 3) "Concat" using a view and apply a final linear. x = x.transpose(1, 2).contiguous().view(batch_size, -1, self.h * self.d_k) @@ -328,12 +379,21 @@ class Transformer(BaseModel, CheferInterpretable): an independent :class:`TransformerLayer`. The resulting [CLS]-style embeddings are concatenated and passed to a classification head. + When ``unified_embedding`` is supplied the model switches to **unified + mode**: all temporal fields are jointly embedded and time-sorted by + :class:`UnifiedMultimodalEmbeddingModel`, then processed by a *single* + :class:`TransformerLayer` rather than one layer per field. This allows + full cross-modal attention over the interleaved event sequence. + Args: dataset (SampleDataset): dataset providing processed inputs. embedding_dim (int): shared embedding dimension. heads (int): number of attention heads per transformer block. dropout (float): dropout rate applied inside transformer blocks. num_layers (int): number of transformer blocks per feature stream. + unified_embedding (UnifiedMultimodalEmbeddingModel, optional): when + provided, the model uses a single backbone over the unified + multi-modal sequence instead of per-field transformers. Examples: >>> from pyhealth.datasets import create_sample_dataset, get_dataloader @@ -377,6 +437,7 @@ def __init__( dropout: float = 0.5, num_layers: int = 1, max_seq_len: int = 1024, + unified_embedding: UnifiedMultimodalEmbeddingModel | None = None, ): super().__init__(dataset=dataset) self.embedding_dim = embedding_dim @@ -385,25 +446,35 @@ def __init__( self.num_layers = num_layers self.max_seq_len = max_seq_len self._attention_hooks_enabled = False + self._use_unified = unified_embedding is not None assert ( len(self.label_keys) == 1 ), "Only one label key is supported if Transformer is initialized" self.label_key = self.label_keys[0] - self.embedding_model = EmbeddingModel(dataset, embedding_dim) + output_size = self.label_processor.output_size() - self.transformer: nn.ModuleDict = nn.ModuleDict() - for feature_key in self.feature_keys: - self.transformer[feature_key] = TransformerLayer( + if self._use_unified: + self.embedding_model = unified_embedding + self._unified_backbone = TransformerLayer( feature_size=embedding_dim, heads=heads, dropout=dropout, num_layers=num_layers, ) - - output_size = self.label_processor.output_size() - self.fc = nn.Linear(len(self.feature_keys) * embedding_dim, output_size) + self.fc = nn.Linear(embedding_dim, output_size) + else: + self.embedding_model = EmbeddingModel(dataset, embedding_dim) + self.transformer: nn.ModuleDict = nn.ModuleDict() + for feature_key in self.feature_keys: + self.transformer[feature_key] = TransformerLayer( + feature_size=embedding_dim, + heads=heads, + dropout=dropout, + num_layers=num_layers, + ) + self.fc = nn.Linear(len(self.feature_keys) * embedding_dim, output_size) def _pool_embedding(self, x: torch.Tensor) -> torch.Tensor: """Pool nested embeddings to ``[batch, seq_len, hidden]`` format. @@ -442,6 +513,62 @@ def _mask_from_embeddings(x: torch.Tensor) -> torch.Tensor: mask[invalid_rows, 0] = True return mask.bool() + def _build_unified_inputs( + self, kwargs: dict[str, Any] + ) -> dict[str, dict[str, torch.Tensor]]: + """Build inputs expected by UnifiedMultimodalEmbeddingModel.""" + inputs: dict[str, dict[str, torch.Tensor]] = {} + for field_name in self.feature_keys: + feature = kwargs[field_name] + if isinstance(feature, torch.Tensor): + feature = (feature,) + + schema = self.dataset.input_processors[field_name].schema() + field_dict: dict[str, torch.Tensor] = {} + if "value" in schema: + field_dict["value"] = feature[schema.index("value")].to(self.device) + if "time" in schema: + field_dict["time"] = feature[schema.index("time")].to(self.device) + if "mask" in schema: + field_dict["mask"] = feature[schema.index("mask")].to(self.device) + pad_mask = kwargs.get(f"{field_name}{PAD_MASK_SUFFIX}") + if pad_mask is not None: + field_dict["pad_mask"] = pad_mask.to(self.device) + inputs[field_name] = field_dict + + return inputs + + def _forward_unified( + self, + **kwargs: torch.Tensor | tuple[torch.Tensor, ...], + ) -> dict[str, torch.Tensor]: + """Forward pass in unified-embedding mode.""" + register_hook = self._attention_hooks_enabled + inputs = self._build_unified_inputs(cast(dict[str, Any], kwargs)) + out = self.embedding_model(inputs) + sequence = cast(torch.Tensor, out["sequence"]) + event_mask = cast(torch.Tensor, out["mask"]).bool() + + _, patient_emb = self._unified_backbone(sequence, event_mask, register_hook) + + logits = self.fc(patient_emb) + y_prob = self.label_processor.activation(logits) + + results: dict[str, torch.Tensor] = { + "logit": logits, + "y_prob": y_prob, + } + + if self.label_key in kwargs: + y_true = cast(torch.Tensor, kwargs[self.label_key]).to(self.device) + loss = self.label_processor.loss(logits, y_true) + results["loss"] = loss + results["y_true"] = y_true + + if kwargs.get("embed", False): + results["embed"] = patient_emb + return results + def forward_from_embedding( self, **kwargs: torch.Tensor | tuple[torch.Tensor, ...], @@ -541,9 +668,14 @@ def forward_from_embedding( def forward( self, **kwargs: torch.Tensor | tuple[torch.Tensor, ...], - ) -> Dict[str, torch.Tensor]: + ) -> dict[str, torch.Tensor]: """Forward propagation. + In **unified mode** (when ``unified_embedding`` was supplied at init) + the model jointly embeds all temporal fields and processes them with a + single transformer backbone. Otherwise each field is embedded and + encoded independently. + Args: **kwargs: keyword arguments for the model. @@ -561,6 +693,9 @@ def forward( logit: the raw logits before activation. embed: (if embed=True in kwargs) the patient embedding. """ + if self._use_unified: + return self._forward_unified(**kwargs) + for feature_key in self.feature_keys: feature = kwargs[feature_key] diff --git a/pyhealth/models/unified_embedding.py b/pyhealth/models/unified_embedding.py index 7619d2de53..623013fbd5 100644 --- a/pyhealth/models/unified_embedding.py +++ b/pyhealth/models/unified_embedding.py @@ -22,23 +22,38 @@ """ from __future__ import annotations +import logging import math +import warnings +from contextlib import nullcontext from typing import Any import torch +import torch.nn.functional as F import torch.nn as nn from pyhealth.processors.base_processor import ModalityType, TemporalFeatureProcessor +from pyhealth.models.vision_embedding import PatchEmbedding + +logger = logging.getLogger(__name__) + +# Frozen [CLS] is 768-d float32 on CPU. Python tensor objects add overhead; +# treat 8 KB/entry as a conservative host-RAM estimate when logging. +_CLS_BYTES = 768 * 4 +_CACHE_LOG_SIZES = {1, 10_000, 50_000, 100_000, 200_000, 500_000, 1_000_000, 2_000_000} # ── Helpers ─────────────────────────────────────────────────────────────────── class SinusoidalTimeEmbedding(nn.Module): - """Continuous sinusoidal embedding for scalar time values (in hours). + """Multi-scale sinusoidal embedding for times in hours. - Identical in spirit to the positional encoding in "Attention is All You - Need" but operating on real-valued timestamps rather than integer positions. + Wavelengths are spaced geometrically from ``min_hours`` (within-stay + resolution) to ``max_hours`` (longitudinal span). The previous encoding + mapped ``t / 720 * 2π``, so every frequency wrapped every 30 days: a later + stay at +9606h produced the same embedding as +6h even after the task + stopped resetting the clock. Examples: >>> embedding = SinusoidalTimeEmbedding(dim=2, max_hours=24.0) @@ -50,55 +65,52 @@ class SinusoidalTimeEmbedding(nn.Module): Args: dim: Output embedding dimension (must be even). - max_hours: Maximum expected time value in hours. Values are normalised - to ``[0, 2π]`` before the sin/cos projection. Default 720 (30 days). + max_hours: Longest wavelength in hours. Default 87600 (10 years). + min_hours: Shortest wavelength in hours. Default 1.0. Shape: Input: ``(*, )`` float tensor of times in hours Output: ``(*, dim)`` """ - def __init__(self, dim: int, max_hours: float = 720.0): + def __init__( + self, + dim: int, + max_hours: float = 87600.0, + min_hours: float = 1.0, + ): super().__init__() assert dim % 2 == 0, f"dim must be even, got {dim}" + if min_hours <= 0 or max_hours <= min_hours: + raise ValueError( + f"need 0 < min_hours < max_hours, got min={min_hours}, max={max_hours}" + ) self.dim = dim - self.max_hours = max_hours + self.max_hours = float(max_hours) + self.min_hours = float(min_hours) half = dim // 2 - freqs = torch.exp( - -math.log(10000.0) * torch.arange(half, dtype=torch.float32) / max(half - 1, 1) + periods = torch.exp( + torch.linspace( + math.log(self.min_hours), + math.log(self.max_hours), + half, + dtype=torch.float32, + ) ) - self.register_buffer("freqs", freqs) # (dim//2,) + self.register_buffer("freqs", 2 * math.pi / periods) def forward(self, t: torch.Tensor) -> torch.Tensor: """:param t: ``(...,)`` float, times in hours.""" - t_norm = t / self.max_hours * 2 * math.pi # (...,) - args = t_norm.unsqueeze(-1) * self.freqs # (..., dim//2) - return torch.cat([args.sin(), args.cos()], dim=-1) # (..., dim) + args = t.unsqueeze(-1).to(dtype=self.freqs.dtype) * self.freqs + return torch.cat([args.sin(), args.cos()], dim=-1) -def _build_image_encoder(embedding_dim: int) -> nn.Module: - """Lightweight 5-layer CNN encoder: C × H × W → embedding_dim. +class _MeanPool(nn.Module): + """Pool a sequence of patch embeddings to a single vector via global mean.""" - Uses ``torchvision.models.resnet18`` pre-trained backbone, strips the - final FC layer, and adds a projection to ``embedding_dim``. Falls back to - a toy Conv-pool-flatten network if torchvision is not installed. - """ - try: - import torchvision.models as tv - - backbone = tv.resnet18(weights=None) - in_features = backbone.fc.in_features - backbone.fc = nn.Linear(in_features, embedding_dim) - return backbone - except ImportError: - # Minimal fallback: single conv → global avg pool → linear - return nn.Sequential( - nn.Conv2d(3, 32, 3, padding=1), - nn.ReLU(), - nn.AdaptiveAvgPool2d(1), - nn.Flatten(), - nn.Linear(32, embedding_dim), - ) + def forward(self, x: torch.Tensor) -> torch.Tensor: + # (B, num_patches, E) -> (B, E) + return x.mean(dim=1) # ── Main model ─────────────────────────────────────────────────────────────── @@ -130,14 +142,60 @@ class UnifiedMultimodalEmbeddingModel(nn.Module): 6. Add ``SinusoidalTimeEmbedding(time)`` + ``type_embedding(modality_idx)``. 7. Return ``{"sequence", "time", "mask", "type_ids"}``. + Unimodal model reuse via ``field_embeddings``:: + + vision_model = VisionEmbeddingModel(dataset, embedding_dim=128) + unified = UnifiedMultimodalEmbeddingModel( + processors=dataset.input_processors, + embedding_dim=128, + field_embeddings={"chest_xray": vision_model}, + ) + Args: processors: ``dict[field_name, TemporalFeatureProcessor]`` — the processors for each temporal field in the dataset. Pass ``dataset.input_processors`` directly. embedding_dim: Shared embedding dimension ``E'``. time_embedding: ``"sinusoidal"`` (default) or ``"learned"``. - max_time_hours: Normalisation constant for the time embedding. - Defaults to 720 h (30 days). + max_time_hours: Longest wavelength of the time embedding, in hours. + Defaults to 87600 (10 years). Shortest wavelength is 1 hour. + image_size: Image size (H=W) assumed for IMAGE fields when using + PatchEmbedding. Defaults to 224. + image_channels: Number of input channels for IMAGE fields. Defaults to 3. + patch_size: Patch size for IMAGE PatchEmbedding encoder. Defaults to 16. + image_pool: Pooling strategy applied to IMAGE patch tokens to produce + one vector per image event. Only ``"mean"`` (global mean pooling) + is currently implemented. Defaults to ``"mean"``. + field_embeddings: Optional mapping of field names to pre-built unimodal + embedding models (``EmbeddingModel``, ``VisionEmbeddingModel``, or + ``TextEmbedding``). The core encoder module is extracted from each + pre-built model; fields not present here use internally-built + encoders. Defaults to None. + freeze_text_encoder: If True, freeze TEXT encoder weights + (``requires_grad=False``) so notes encode deterministically. + Defaults to False. + normalize_content: If True, apply parameter-free layer norm to the + content term so one modality's raw magnitude cannot drown out the + time/type terms. Defaults to True. This CHANGES outputs versus the + previous unnormalized sum (content + time + type): the content + term is rescaled to unit variance per event before the time and + type terms are added. The default is True because raw feature + magnitude is an accident of feature scaling, not a modelling + decision. + cache_frozen_text: If True, reuse frozen ``[CLS]`` vectors across + forwards instead of re-running the text encoder. Defaults to True. + max_frozen_text_cache: Maximum cached ``[CLS]`` vectors + (``None`` or ``<= 0`` means no cap). Rows past the cap are + re-encoded each forward; notes are never dropped. The cap is a + RAM fuse, not a speedup knob: speedup needs cap >= unique notes. + Defaults to 1000000. + numeric_standardizers: Optional mapping of NUMERIC/SIGNAL field names + to modules called as ``standardizer(value, observed)`` BEFORE the + projection, where ``observed`` comes from the sibling + ``{field}_mask`` field. Defaults to None. A ``{field}_mask`` input + is skipped as a modality ONLY when ``field`` has a registered + entry here; a field merely named ``x_mask`` with no standardizer + stays a normal modality. Example:: @@ -149,6 +207,23 @@ class UnifiedMultimodalEmbeddingModel(nn.Module): out = model(inputs) seq = out["sequence"] # (B, S_total, 128) mask = out["mask"] # (B, S_total) float, 1=valid 0=pad + + Minimal example: + + >>> import torch + >>> from pyhealth.processors import StageNetProcessor + >>> from pyhealth.models.unified_embedding import ( + ... UnifiedMultimodalEmbeddingModel, + ... ) + >>> proc = StageNetProcessor() + >>> proc.fit([{"codes": ([0.0], ["A"])}], "codes") + >>> model = UnifiedMultimodalEmbeddingModel({"codes": proc}, embedding_dim=8) + >>> out = model({"codes": { + ... "value": torch.zeros(1, 1, dtype=torch.long), + ... "time": torch.zeros(1, 1), + ... }}) + >>> out["sequence"].shape + torch.Size([1, 1, 8]) """ def __init__( @@ -156,10 +231,37 @@ def __init__( processors: dict[str, Any], embedding_dim: int = 128, time_embedding: str = "sinusoidal", - max_time_hours: float = 720.0, + max_time_hours: float = 87600.0, + image_size: int = 224, + image_channels: int = 3, + patch_size: int = 16, + image_pool: str = "mean", + field_embeddings: dict[str, Any] | None = None, + freeze_text_encoder: bool = False, + normalize_content: bool = True, + cache_frozen_text: bool = True, + max_frozen_text_cache: int | None = 1_000_000, + numeric_standardizers: dict[str, Any] | None = None, ): super().__init__() - self.embedding_dim = embedding_dim + if image_pool != "mean": + raise NotImplementedError( + f"Only image_pool='mean' is implemented, got {image_pool!r}." + ) + self._embedding_dim = embedding_dim + self._freeze_text_encoder = freeze_text_encoder + self._frozen_text_fields: set[str] = set() + self.cache_frozen_text = cache_frozen_text + self.max_frozen_text_cache = max_frozen_text_cache + self._frozen_text_cache: dict[str, dict[tuple[int, int], torch.Tensor]] = {} + self._frozen_text_cache_hits = 0 + self._frozen_text_cache_misses = 0 + self.image_pool = image_pool + self.normalize_content = normalize_content + # Statistics live in buffers, so they travel in state_dict. A checkpoint + # therefore applies at inference the same transform it trained under. + self.numeric_standardizers = nn.ModuleDict(numeric_standardizers or {}) + _field_embeddings = field_embeddings or {} self.encoders: nn.ModuleDict = nn.ModuleDict() self.projections: nn.ModuleDict = nn.ModuleDict() @@ -176,35 +278,35 @@ def __init__( m = processor.modality() self.modality_types[field_name] = m + pre_built = _field_embeddings.get(field_name) if m == ModalityType.CODE: - vocab_size = processor.value_dim() - self.encoders[field_name] = nn.Embedding( - vocab_size, embedding_dim, padding_idx=0 + self.encoders[field_name] = self._build_code_encoder( + field_name, processor, pre_built, embedding_dim ) elif m == ModalityType.TEXT: - if processor.is_token(): - from transformers import AutoModel - - bert = AutoModel.from_pretrained(processor.tokenizer_model) - self.encoders[field_name] = bert - hidden = bert.config.hidden_size - if hidden != embedding_dim: - self.projections[field_name] = nn.Linear(hidden, embedding_dim) - else: - raise ValueError( - f"TEXT processor '{field_name}' must use a tokenizer " - f"(set tokenizer_model=...) to be used with " - f"UnifiedMultimodalEmbeddingModel." - ) + self._build_text_encoder( + field_name, processor, pre_built, embedding_dim, + freeze=freeze_text_encoder, + ) elif m == ModalityType.IMAGE: - self.encoders[field_name] = _build_image_encoder(embedding_dim) + self.encoders[field_name] = self._build_image_encoder( + field_name, + processor, + pre_built, + embedding_dim, + image_size, + image_channels, + patch_size, + image_pool, + ) elif m in (ModalityType.NUMERIC, ModalityType.SIGNAL): - in_features = processor.value_dim() - self.encoders[field_name] = nn.Linear(in_features, embedding_dim) + self.encoders[field_name] = self._build_numeric_encoder( + field_name, processor, pre_built, embedding_dim + ) else: raise NotImplementedError( @@ -217,6 +319,7 @@ def __init__( mod: i for i, mod in enumerate(unique_modalities) } self.type_embedding = nn.Embedding(len(unique_modalities), embedding_dim) + self._warned_nested_code_flatten = False # Time embedding if time_embedding == "sinusoidal": @@ -224,6 +327,310 @@ def __init__( else: raise NotImplementedError("Only 'sinusoidal' time embedding is implemented.") + # ── Encoder builders ────────────────────────────────────────────────────── + + def _build_code_encoder( + self, + field_name: str, + processor: TemporalFeatureProcessor, + pre_built: Any, + embedding_dim: int, + ) -> nn.Module: + """Build CODE encoder: nn.Embedding, optionally from a pre-built EmbeddingModel.""" + if ( + pre_built is not None + and hasattr(pre_built, "embedding_layers") + and field_name in pre_built.embedding_layers + ): + layer = pre_built.embedding_layers[field_name] + pre_dim = getattr(pre_built, "embedding_dim", embedding_dim) + if pre_dim != embedding_dim: + return nn.Sequential(layer, nn.Linear(pre_dim, embedding_dim)) + return layer + + vocab_size = processor.value_dim() + return nn.Embedding(vocab_size, embedding_dim, padding_idx=0) + + def _build_text_encoder( + self, + field_name: str, + processor: TemporalFeatureProcessor, + pre_built: Any, + embedding_dim: int, + freeze: bool = False, + ) -> None: + """Build TEXT encoder: BERT + projection, optionally from TextEmbedding.""" + + def _set_projection( + pre_dim: int, proj_source: nn.Module | None = None + ) -> None: + if pre_dim != embedding_dim: + if proj_source is not None: + self.projections[field_name] = nn.Sequential( + proj_source, + nn.Linear(pre_dim, embedding_dim), + ) + else: + self.projections[field_name] = nn.Linear(pre_dim, embedding_dim) + elif proj_source is not None: + self.projections[field_name] = proj_source + + if ( + pre_built is not None + and hasattr(pre_built, "transformer") + and hasattr(pre_built, "fc") + ): + self.encoders[field_name] = pre_built.transformer + if freeze: + for p in pre_built.transformer.parameters(): + p.requires_grad = False + self._frozen_text_fields.add(field_name) + pre_dim = getattr(pre_built, "embedding_dim", embedding_dim) + _set_projection(pre_dim, pre_built.fc) + return + + if processor.is_token(): + from transformers import AutoModel + + bert = AutoModel.from_pretrained(processor.tokenizer_model) + if freeze: + for p in bert.parameters(): + p.requires_grad = False + self._frozen_text_fields.add(field_name) + self.encoders[field_name] = bert + hidden = bert.config.hidden_size + if hidden != embedding_dim: + self.projections[field_name] = nn.Linear(hidden, embedding_dim) + else: + raise ValueError( + f"TEXT processor '{field_name}' must either supply a pre-built " + f"TextEmbedding via field_embeddings or use a tokenizer " + f"(set tokenizer_model=...) to be used with " + f"UnifiedMultimodalEmbeddingModel." + ) + + def _build_image_encoder( + self, + field_name: str, + processor: TemporalFeatureProcessor, + pre_built: Any, + embedding_dim: int, + image_size: int, + image_channels: int, + patch_size: int, + image_pool: str, + ) -> nn.Module: + """Build IMAGE encoder: backbone + pool, optionally from VisionEmbeddingModel.""" + pool_layers: dict[str, nn.Module] = {"mean": _MeanPool()} + pool_layer = pool_layers[image_pool] + + if ( + pre_built is not None + and hasattr(pre_built, "embedding_layers") + and field_name in pre_built.embedding_layers + ): + backbone = pre_built.embedding_layers[field_name] + pre_dim = getattr(pre_built, "embedding_dim", embedding_dim) + if pre_dim != embedding_dim: + return nn.Sequential( + backbone, pool_layer, nn.Linear(pre_dim, embedding_dim) + ) + return nn.Sequential(backbone, pool_layer) + + _image_size = getattr(processor, "image_size", image_size) + _in_channels = getattr(processor, "in_channels", image_channels) + return nn.Sequential( + PatchEmbedding(_image_size, patch_size, _in_channels, embedding_dim), + pool_layer, + ) + + def _build_numeric_encoder( + self, + field_name: str, + processor: TemporalFeatureProcessor, + pre_built: Any, + embedding_dim: int, + ) -> nn.Module: + """Build NUMERIC/SIGNAL encoder: nn.Linear, optionally from EmbeddingModel.""" + if ( + pre_built is not None + and hasattr(pre_built, "embedding_layers") + and field_name in pre_built.embedding_layers + ): + layer = pre_built.embedding_layers[field_name] + pre_dim = getattr(pre_built, "embedding_dim", embedding_dim) + if pre_dim != embedding_dim: + return nn.Sequential(layer, nn.Linear(pre_dim, embedding_dim)) + return layer + + in_features = processor.value_dim() + return nn.Linear(in_features, embedding_dim) + + @property + def embedding_dim(self) -> int: + return self._embedding_dim + + @property + def frozen_text_cache_size(self) -> int: + """Number of cached frozen ``[CLS]`` vectors across fields. + + Example: + >>> model.frozen_text_cache_size + 0 + """ + return sum(len(c) for c in self._frozen_text_cache.values()) + + @property + def frozen_text_cache_stats(self) -> dict[str, int]: + """Cache ``hits``, ``misses``, and ``size`` for the A/B timing run. + + Misses count rows not cached before this forward (including + duplicates and overflow rows served from the current forward); + hits count rows served from the cache. + + Example: + >>> sorted(model.frozen_text_cache_stats) + ['hits', 'misses', 'size'] + """ + return { + "hits": self._frozen_text_cache_hits, + "misses": self._frozen_text_cache_misses, + "size": self.frozen_text_cache_size, + } + + def reset_frozen_text_cache_stats(self) -> None: + """Zero the ``hits``/``misses`` counters (cache entries are kept).""" + self._frozen_text_cache_hits = 0 + self._frozen_text_cache_misses = 0 + + def _encode_text_cls( + self, + field_name: str, + encoder: nn.Module, + flat_ids: torch.Tensor, + flat_mask: torch.Tensor | None, + ) -> torch.Tensor: + """Return the ``[CLS]`` vector for each row, from a cache when possible. + + A frozen encoder gives the same output for the same tokens, so a run of + 50 epochs would otherwise repeat the identical 110M-parameter forward + pass 50 times. + + The cache has three conditions. It is used only for a field in + ``_frozen_text_fields``, so a trainable encoder can never read it. The + key is ``(hash, real-token length)`` over the token identifiers under + the attention mask, so a change of tokenizer or truncation budget + gives a different key; the length is a cheap guard so a hash + collision alone cannot silently return the wrong embedding. ``None`` or + ``<= 0`` means no size cap. Default is 1_000_000 (~3 GB of fp32 + ``[CLS]`` vectors): a RAM fuse, not a speedup knob. A smaller cap + than the unique-note count makes overflow notes re-run BERT every + epoch. Notes are never dropped from the sequence. + + Key on the REAL tokens only. The collator pads each row to the widest + note in its batch, and batch composition changes every epoch because + the loader shuffles, so a key over the padded row gives the same note + a different key each epoch and the cache never hits. Measured on the + full-scale notes run: epoch time did not fall after epoch 1 + (3458s, 3936s, 4048s, 3835s) because every lookup missed. + """ + if flat_ids.shape[0] == 0: + hidden = encoder.config.hidden_size + first_param = next(encoder.parameters(), None) + dtype = ( + first_param.dtype if first_param is not None + else torch.get_default_dtype() + ) + return flat_ids.new_zeros((0, hidden), dtype=dtype) + + if not (self.cache_frozen_text and field_name in self._frozen_text_fields): + ctx = torch.no_grad() if field_name in self._frozen_text_fields else nullcontext() + with ctx: + out = encoder(input_ids=flat_ids, attention_mask=flat_mask) + return out.last_hidden_state[:, 0, :] + + cache = self._frozen_text_cache.setdefault(field_name, {}) + pre_cached = set(cache) + ids_cpu = flat_ids.detach().cpu() + mask_cpu = ( + flat_mask.detach().cpu().to(torch.int8) + if flat_mask is not None + else torch.ones_like(ids_cpu, dtype=torch.int8) + ) + # Key on (hash, real-token length): hash() alone could silently + # return a wrong [CLS] on collision. Storing the length is a cheap + # guard — a collision then needs the same hash AND the same length. + keys: list[tuple[int, int]] = [] + for i, m in zip(ids_cpu, mask_cpu): + n_real = int(m.sum()) + if m.any(): + h = hash(tuple(i[m.bool()].tolist())) + else: + h = hash(tuple(i.tolist())) + keys.append((h, n_real)) + + first_row_of_key: dict[tuple[int, int], int] = {} + for k, key in enumerate(keys): + if key not in cache and key not in first_row_of_key: + first_row_of_key[key] = k + missing = list(first_row_of_key.values()) + # Rows encoded in this forward, kept even when the cache is full so a + # miss is never encoded twice in one call. + fresh_rows: dict[tuple[int, int], torch.Tensor] = {} + if missing: + index = torch.tensor(missing, device=flat_ids.device) + with torch.no_grad(): + out = encoder( + input_ids=flat_ids.index_select(0, index), + attention_mask=( + flat_mask.index_select(0, index) + if flat_mask is not None + else None + ), + ) + fresh = out.last_hidden_state[:, 0, :].detach() + for slot, row in zip(missing, fresh): + fresh_rows[keys[slot]] = row + cap = self.max_frozen_text_cache + if cap is None or cap <= 0 or len(cache) < cap: + cache[keys[slot]] = row.cpu() + n = len(cache) + if n in _CACHE_LOG_SIZES or (n > 0 and n % 250_000 == 0): + logger.info( + "frozen text cache field=%s size=%d " + "(~%.2f GB fp32 [CLS] tensors, ~%.2f GB with " + "Python overhead). Overflow is re-encoded next " + "forward; notes are never dropped.", + field_name, + n, + n * _CLS_BYTES / 1e9, + n * 8e3 / 1e9, + ) + + rows = [] + for key in keys: + hit = cache.get(key) + if key in pre_cached and hit is not None: + self._frozen_text_cache_hits += 1 + rows.append(hit.to(flat_ids.device)) + else: + self._frozen_text_cache_misses += 1 + rows.append(fresh_rows[key]) + return torch.stack(rows).to(dtype=self.type_embedding.weight.dtype) + + def train(self, mode: bool = True) -> UnifiedMultimodalEmbeddingModel: + """Keep a frozen text encoder in eval mode. + + ``nn.Module.train()`` would enable dropout inside the encoder. Its + output would then change between passes even though every weight has + ``requires_grad=False``. That makes cached embeddings incorrect, and + it also makes a frozen encoder give a different answer to the same input. + """ + super().train(mode) + for field_name in self._frozen_text_fields: + self.encoders[field_name].eval() + return self + # ── Forward ─────────────────────────────────────────────────────────────── def forward( @@ -245,6 +652,8 @@ def forward( * ``"time"`` — ``(B, S_total)`` timestamps (hours) * ``"mask"`` — ``(B, S_total)`` 1=real event, 0=padding * ``"type_ids"`` — ``(B, S_total)`` modality index per event + * ``"token_emb"`` — ``(B, S_total, E')`` content-only event embedding + (before time/type are added); the target for masked modeling. """ all_embeddings: list[torch.Tensor] = [] all_times: list[torch.Tensor] = [] @@ -252,9 +661,24 @@ def forward( all_types: list[torch.Tensor] = [] for field_name, feat_dict in inputs.items(): - value = feat_dict["value"] # (B, N_i, ...) or (B, S, F) - time = feat_dict["time"] # (B, N_i) - mask = feat_dict.get("mask") + if field_name.endswith("_mask") and field_name[: -len("_mask")] in self.numeric_standardizers: + # Observation-flag sibling consumed by the standardiser; not a + # modality of its own. Encoding it would duplicate every lab + # timestamp with a 0/1 vector. Skipped ONLY when the base + # field registered a standardiser: a field merely named + # ``x_mask`` with no standardiser stays a normal modality. + continue + value = feat_dict["value"] # (B, N_i, ...) or (B, S, F) + time = feat_dict["time"] # (B, N_i) + # Three different masks meet here and must not be conflated. + # mask token level, from the processor schema; this is the + # attention mask a text encoder needs. + # pad_mask event level, from the collator; which slots are real + # events rather than batch padding. + # {field}_mask a separate FIELD meaning "was this value + # observed", consumed by the standardiser below. + mask = feat_dict.get("mask") + pad_mask = feat_dict.get("pad_mask") if time is None: # Fallback: treat every event as occurring at t=0 @@ -265,29 +689,160 @@ def forward( # ── Encode ──────────────────────────────────────────────────── if modality == ModalityType.CODE: - emb = encoder(value) # (B, S, E') + # CODE values may be either: + # - flat indices: (B, S) + # - nested indices: (B, S, C) where C is codes-per-event + # For nested indices, flatten to (B, S*C, E') so code-level + # detail is preserved, and expand time/mask to match. + if value.dim() == 2: + emb = encoder(value) # (B, S, E') + elif value.dim() == 3: + bsz, seq_len, per_event_codes = value.shape + token_emb = encoder(value.long()) # (B, S, C, E') + emb = token_emb.reshape(bsz, seq_len * per_event_codes, -1) + + if not self._warned_nested_code_flatten: + warnings.warn( + ( + "UnifiedMultimodalEmbeddingModel detected " + f"nested CODE input for '{field_name}' with " + f"shape={tuple(value.shape)}. Flattening to " + f"(B, S*C, E) and repeating time along C." + ), + stacklevel=2, + ) + self._warned_nested_code_flatten = True + + if time is not None: + time = ( + time.unsqueeze(-1) + .expand(-1, -1, per_event_codes) + .reshape(bsz, seq_len * per_event_codes) + ) + + if mask is not None: + if mask.dim() == 2: + mask = ( + mask.unsqueeze(-1) + .expand(-1, -1, per_event_codes) + .reshape(bsz, seq_len * per_event_codes) + ) + elif mask.dim() == 3: + mask = mask.reshape(bsz, seq_len * per_event_codes) + else: + raise ValueError( + f"Unsupported CODE value rank for '{field_name}': " + f"shape={tuple(value.shape)}" + ) elif modality == ModalityType.TEXT: + # Collate pads note slots to the longest sample in the batch. + # Running BERT on those empty rows is what OOM'd batch-32 + # notes_labs on a 48 GB GPU (~B*N=full pad width, L=512). b, n, l = value.shape - flat_ids = value.view(b * n, l) - flat_mask = mask.view(b * n, l) if mask is not None else None - out = encoder(input_ids=flat_ids, attention_mask=flat_mask) - cls_emb = out.last_hidden_state[:, 0, :] # (B*N, H) + flat_ids = value.reshape(b * n, l) + flat_attn = mask.reshape(b * n, l) if mask is not None else None + if pad_mask is not None: + valid = pad_mask.reshape(b * n).bool() + elif flat_attn is not None: + valid = flat_attn.any(dim=-1) + else: + valid = torch.ones( + b * n, dtype=torch.bool, device=value.device + ) + hidden = encoder.config.hidden_size + first_param = next(encoder.parameters(), None) + param_dtype = ( + first_param.dtype if first_param is not None + else torch.get_default_dtype() + ) + cls_emb = value.new_zeros((b * n, hidden), dtype=param_dtype) + if valid.any(): + h = self._encode_text_cls( + field_name, + encoder, + flat_ids[valid], + flat_attn[valid] if flat_attn is not None else None, + ) + cls_emb = cls_emb.to(dtype=h.dtype) + cls_emb[valid] = h if field_name in self.projections: cls_emb = self.projections[field_name](cls_emb) - emb = cls_emb.view(b, n, -1) # (B, N, E') + # cls_emb.shape[-1] instead of -1: when b*n == 0 (no note + # slots in this batch), the -1 is ambiguous for a 0-element + # tensor and torch raises. + emb = cls_emb.view(b, n, cls_emb.shape[-1]) # (B, N, E') elif modality == ModalityType.IMAGE: + # encoder = Sequential(PatchEmbedding, _MeanPool) -> (B*N, E') b, n, c, h, w = value.shape - flat_imgs = value.view(b * n, c, h, w) - img_emb = encoder(flat_imgs) # (B*N, E') - emb = img_emb.view(b, n, -1) + flat_imgs = value.reshape(b * n, c, h, w) + if b * n == 0: + # No image slots in this batch. reshape(0, -1) is + # ambiguous since -1 can be any value for 0 elements. + valid = torch.zeros(b * n, dtype=torch.bool, device=value.device) + elif pad_mask is not None: + valid = pad_mask.reshape(b * n).bool() + else: + valid = flat_imgs.reshape(b * n, -1).abs().sum(dim=-1) > 0 + if valid.any(): + img_valid = encoder(flat_imgs[valid]) + emb_dim = img_valid.shape[-1] + img_emb = img_valid.new_zeros((b * n, emb_dim)) + img_emb[valid] = img_valid + else: + emb_dim = self._embedding_dim + img_emb = value.new_zeros((b * n, emb_dim)) + # Explicit dim instead of -1: same 0-element ambiguity. + emb = img_emb.view(b, n, emb_dim) # (B, N, E') else: # NUMERIC / SIGNAL - emb = encoder(value) # (B, T, E') + # Standardise BEFORE the projection. The projection mixes the + # features, so a transform after it cannot correct a feature + # whose physical unit gives it 300 times the magnitude of + # another. + # nn.ModuleDict has no .get(), so the ternary stays. + standardizer = ( + self.numeric_standardizers[field_name] # noqa: SIM401 + if field_name in self.numeric_standardizers + else None + ) + if standardizer is not None: + # Observation flags live in the sibling ``{field}_mask`` + # FIELD, not in this field's dict. Reading the padding mask + # here would tell the standardiser that every real event + # was measured, which is exactly the distinction the + # standardiser exists to preserve. + sibling = inputs.get(f"{field_name}_mask") + obs = sibling["value"] if isinstance(sibling, dict) else None + if obs is None: + raise ValueError( + f"The standardiser for {field_name!r} needs a paired " + f"{field_name}_mask field in the batch." + ) + if obs.shape != value.shape: + raise ValueError( + f"{field_name}_mask has shape {tuple(obs.shape)}, " + f"which does not match {field_name} " + f"{tuple(value.shape)}." + ) + value = standardizer(value, obs.bool()) + emb = encoder(value) # (B, T, E') # ── Build event-level validity mask ─────────────────────────── - if mask is None: + if pad_mask is not None: + # The collator is authoritative about batch padding. + event_mask = pad_mask.to(emb.device).float() + if event_mask.shape[1] != emb.shape[1]: + # A nested CODE field was flattened to (B, S*C); repeat the + # event flags along the same axis. + repeat = emb.shape[1] // event_mask.shape[1] + event_mask = ( + event_mask.unsqueeze(-1) + .expand(-1, -1, repeat) + .reshape(emb.shape[0], -1) + ) + elif mask is None: event_mask = torch.ones(emb.shape[:2], device=emb.device) else: if mask.dim() > time.dim(): @@ -314,22 +869,45 @@ def forward( cat_types = torch.cat(all_types, dim=1) # (B, S_total) # ── Sort by time ────────────────────────────────────────────────── - sort_idx = cat_time.argsort(dim=1) - cat_emb = cat_emb.gather( - 1, sort_idx.unsqueeze(-1).expand_as(cat_emb) - ) - cat_time = cat_time.gather(1, sort_idx) - cat_mask = cat_mask.gather(1, sort_idx) - cat_types = cat_types.gather(1, sort_idx) + # Padding carries time 0.0, so a plain ascending sort places it BEFORE + # every real event. Push invalid slots past every real one to keep the + # sequence left-aligned, which is what all consumers assume. + # + # Stable, because the key is heavily tied: all padding shares time 0.0 + # and events from one admission share offsets. An unstable sort makes + # event order differ between torch builds and between CPU and CUDA, + # silently changing RNN and Mamba outputs. + sort_key = cat_time.masked_fill(~cat_mask.bool(), float("inf")) + sort_idx = sort_key.argsort(dim=1, stable=True) + cat_emb = cat_emb.gather(1, sort_idx.unsqueeze(-1).expand_as(cat_emb)) + cat_time = cat_time.gather(1, sort_idx) + cat_mask = cat_mask.gather(1, sort_idx) + cat_types = cat_types.gather(1, sort_idx) # ── Add time + type embeddings ──────────────────────────────────── - time_emb = self.time_embed(cat_time) # (B, S_total, E') - type_emb = self.type_embedding(cat_types) # (B, S_total, E') - final = cat_emb + time_emb + type_emb # (B, S_total, E') + time_emb = self.time_embed(cat_time) # (B, S_total, E') + type_emb = self.type_embedding(cat_types) # (B, S_total, E') + if self.normalize_content: + # Put the content term on the scale of the additive terms. Without + # this the sum is decided by whichever modality has the larger + # magnitude, which is an accident of feature scaling and not a + # modelling decision. F.layer_norm without weight or bias adds NO + # parameters, so an existing checkpoint still loads. + cat_emb = F.layer_norm(cat_emb, (cat_emb.shape[-1],)) + final = cat_emb + time_emb + type_emb + # Zero the padded slots so a consumer that ignores the mask, such as a + # mean pool, still cannot pick them up. + final = final * cat_mask.unsqueeze(-1).to(final.dtype) # (B, S_total, E') return { "sequence": final, # (B, S_total, E') "time": cat_time, # (B, S_total) "mask": cat_mask, # (B, S_total) "type_ids": cat_types, # (B, S_total) + # Per-event content embedding BEFORE time/type are added (same sort + # order as ``sequence``). Masked-modeling pretrainers should + # reconstruct THIS rather than ``sequence``: the time/type + # components are largely recoverable from event position, so + # including them in the target dilutes the content signal. + "token_emb": cat_emb, # (B, S_total, E') } diff --git a/pyhealth/processors/stagenet_processor.py b/pyhealth/processors/stagenet_processor.py index bd61822e74..90e5488981 100644 --- a/pyhealth/processors/stagenet_processor.py +++ b/pyhealth/processors/stagenet_processor.py @@ -69,7 +69,9 @@ def fit(self, samples: Iterable[Dict[str, Any]], field: str) -> None: samples: List of sample dictionaries key: The key in samples that contains tuple (time, values) """ - # Examine first non-None sample to determine structure + # Scan for the first sample that determines the structure. Empty + # samples (e.g. a stay with no codes) carry no structural + # information, so they are skipped, not stopping the scan. for sample in samples: if field in sample and sample[field] is not None: # Unpack tuple: (time, values) @@ -82,11 +84,12 @@ def fit(self, samples: Iterable[Dict[str, Any]], field: str) -> None: if isinstance(first_elem, str): # Case 1: ["code1", "code2", ...] self._is_nested = False + break elif isinstance(first_elem, list): if len(first_elem) > 0 and isinstance(first_elem[0], str): # Case 2: [["A", "B"], ["C"], ...] self._is_nested = True - break + break # Build vocabulary for codes and find max nested length max_inner_len = 0 @@ -181,9 +184,9 @@ def process( def _encode_codes(self, codes: List[str]) -> torch.Tensor: """Encode flat code list to indices.""" - # Handle empty code list - return single padding token + # Handle empty code list — zero events, not a fake pad token. if len(codes) == 0: - return torch.tensor([self.code_vocab[""]], dtype=torch.long) + return torch.zeros((0,), dtype=torch.long) indices = [] for code in codes: @@ -200,11 +203,10 @@ def _encode_nested_codes(self, nested_codes: List[List[str]]) -> torch.Tensor: """ assert self._max_nested_len is not None, "Max nested length must be set during fit()" - # Handle empty nested codes (no visits/events) - # Return single padding token with shape (1, max_len) + # Handle empty nested codes (no visits/events) — zero events. if len(nested_codes) == 0: - pad_token = self.code_vocab[""] - return torch.tensor([[pad_token] * self._max_nested_len], dtype=torch.long) + max_len = self._max_nested_len if self._max_nested_len is not None else 1 + return torch.zeros((0, max_len), dtype=torch.long) encoded_sequences = [] # Use global max length determined during fit @@ -328,8 +330,13 @@ class StageNetTensorProcessor(TemporalFeatureProcessor): - List of lists of numbers -> nested numeric sequences (feature vectors) Imputation Strategy: - - Forward-fill: Missing values (NaN/None) are filled with the last observed - value for that feature dimension. If no prior value exists, 0.0 is used. + - Forward-fill (default, ``forward_fill=True``): Missing values (NaN/None) + are filled with the last observed value for that feature dimension. + If no prior value exists, 0.0 is used. + - No fill (``forward_fill=False``): Missing values are set to 0.0 in + place and never propagate earlier rows. Use this for observation-mask + fields, where forward-filling a 0/1 mask would turn later missing + values into observed ones. - Applied per feature dimension independently Returns: @@ -348,9 +355,10 @@ class StageNetTensorProcessor(TemporalFeatureProcessor): >>> time.shape # (3,) """ - def __init__(self): + def __init__(self, forward_fill: bool = True): self._size = None # Feature dimension (set during fit) self._is_nested = None + self.forward_fill = forward_fill def fit(self, samples: Iterable[Dict[str, Any]], field: str) -> None: """Determine input structure. @@ -359,7 +367,9 @@ def fit(self, samples: Iterable[Dict[str, Any]], field: str) -> None: samples: List of sample dictionaries key: The key in samples that contains tuple (time, values) """ - # Examine first non-None sample to determine structure + # Scan for the first sample that determines the structure. Empty + # samples (e.g. a stay with no lab events) carry no structural + # information, so they are skipped, not stopping the scan. for sample in samples: if field in sample and sample[field] is not None: # Unpack tuple: (time, values) @@ -373,20 +383,23 @@ def fit(self, samples: Iterable[Dict[str, Any]], field: str) -> None: # Flat numeric: [1.5, 2.0, ...] self._is_nested = False self._size = 1 + break elif isinstance(first_elem, list): if len(first_elem) > 0: if isinstance(first_elem[0], (int, float)): # Nested numerics: [[1.0, 2.0], [3.0, 4.0]] self._is_nested = True self._size = len(first_elem) - break + break def process( self, value: Tuple[Optional[List], List] ) -> Tuple[Optional[torch.Tensor], torch.Tensor]: """Process tuple format numeric data into tensors. - Applies forward-fill imputation to handle NaN/None values. + Applies forward-fill imputation to handle NaN/None values, unless + the processor was built with ``forward_fill=False`` (observation + masks), in which case missing values become 0.0 in place. For each feature dimension, missing values are filled with the last observed value (or 0.0 if no prior value exists). @@ -398,14 +411,32 @@ def process( """ # Unpack tuple: (time, values) time_data, value_data = value + value_data = list(value_data or []) - # Convert to numpy for easier imputation handling import numpy as np + if len(value_data) == 0: + n_feat = self._size if self._size is not None else 1 + nested = True if self._is_nested is None else self._is_nested + if nested: + value_tensor = torch.zeros((0, n_feat), dtype=torch.float) + else: + value_tensor = torch.zeros((0,), dtype=torch.float) + time_tensor = ( + torch.zeros((0,), dtype=torch.float) if time_data is not None else None + ) + return time_tensor, value_tensor + + # Convert to numpy for easier imputation handling value_array = np.array(value_data, dtype=float) + # Observation-mask fields must preserve false after a true observation; + # forward-filling a 0/1 mask would turn later missing labs into observed + # values. Ordinary numeric time-series retain the historical behaviour. + if not self.forward_fill: + value_array = np.nan_to_num(value_array, nan=0.0, posinf=0.0, neginf=0.0) # Apply forward-fill imputation - if value_array.ndim == 1: + elif value_array.ndim == 1: # Flat numeric: [1.5, 2.0, nan, 3.0, ...] last_value = 0.0 for i in range(len(value_array)): diff --git a/pyhealth/processors/time_image_processor.py b/pyhealth/processors/time_image_processor.py index 9d313e6bc5..451e996f72 100644 --- a/pyhealth/processors/time_image_processor.py +++ b/pyhealth/processors/time_image_processor.py @@ -75,6 +75,11 @@ class TimeImageProcessor(TemporalFeatureProcessor): patient has more images, the most recent (by timestamp) are kept. If None, all images are kept. Defaults to None. + padding: Sentinel string that marks a missing image. When + a path equals this value, a zero tensor of shape + (C, H, W) is returned instead of loading from disk. + If None, all paths are treated as real file paths. + Defaults to None. Raises: ValueError: If normalize is True but mean or std is missing. @@ -107,6 +112,7 @@ def __init__( std: Optional[List[float]] = None, mode: Optional[str] = None, max_images: Optional[int] = None, + padding: str | None = None, ) -> None: self.image_size = image_size self.to_tensor = to_tensor @@ -115,6 +121,7 @@ def __init__( self.std = std self.mode = mode self.max_images = max_images + self.padding = padding self.n_channels = None if self.normalize and ( @@ -166,16 +173,41 @@ def _build_transform(self) -> transforms.Compose: ) return transforms.Compose(transform_list) + def _zero_image_tensor(self) -> torch.Tensor: + """Return a zero tensor matching the expected image shape (C, H, W). + + Used as a placeholder when an image path is an empty string. + Channel count is inferred from self.n_channels if available, + otherwise derived from self.mode ("L"->1, "RGBA"->4, else 3). + + Returns: + Zero tensor of shape (C, image_size, image_size). + """ + if self.n_channels is not None: + c = self.n_channels + elif self.mode == "L": + c = 1 + elif self.mode == "RGBA": + c = 4 + else: + c = 3 + return torch.zeros(c, self.image_size, self.image_size) + def _load_single_image( self, path: Union[str, Path] ) -> torch.Tensor: """Load and transform a single image from disk. + If path equals the padding sentinel, returns a zero tensor of + the same shape as a normal image (C, H, W) via _zero_image_tensor. + Called internally by process() for each image path in the input list. Args: - path: Path to the image file. + path: Path to the image file. If this equals the padding + sentinel, a zero-filled placeholder tensor is returned + instead. Returns: Transformed image tensor of shape (C, H, W). @@ -183,6 +215,8 @@ def _load_single_image( Raises: FileNotFoundError: If the image file does not exist. """ + if self.padding is not None and str(path) == self.padding: + return self._zero_image_tensor() image_path = Path(path) if not image_path.exists(): raise FileNotFoundError( @@ -214,8 +248,10 @@ def fit( for sample in samples: if field in sample and sample[field] is not None: image_paths, _ = sample[field] - if len(image_paths) > 0: - path = Path(image_paths[0]) + for raw_path in image_paths: + if self.padding is not None and str(raw_path) == self.padding: + continue + path = Path(raw_path) if path.exists(): with Image.open(path) as img: if img.mode == "L": @@ -225,6 +261,8 @@ def fit( else: self.n_channels = 3 break + if self.n_channels is not None: + break if self.n_channels is None: self.n_channels = 3 @@ -264,7 +302,6 @@ def process( Raises: ValueError: If image_paths and time_diffs have different lengths. - ValueError: If image_paths is empty. FileNotFoundError: If any image file does not exist. """ image_paths, time_diffs = value @@ -276,7 +313,19 @@ def process( f"match." ) if len(image_paths) == 0: - raise ValueError("image_paths must be non-empty.") + if self.n_channels is not None: + c = self.n_channels + elif self.mode == "L": + c = 1 + elif self.mode == "RGBA": + c = 4 + else: + c = 3 + images = torch.zeros( + (0, c, self.image_size, self.image_size), dtype=torch.float32 + ) + timestamps = torch.zeros((0,), dtype=torch.float32) + return images, timestamps, "image" paired = sorted( zip(time_diffs, image_paths), key=lambda x: x[0] @@ -344,5 +393,6 @@ def __repr__(self) -> str: f"mean={self.mean}, " f"std={self.std}, " f"mode={self.mode}, " - f"max_images={self.max_images})" + f"max_images={self.max_images}, " + f"padding={self.padding!r})" ) \ No newline at end of file diff --git a/pyhealth/processors/tuple_time_text_processor.py b/pyhealth/processors/tuple_time_text_processor.py index bbe74c4e66..305d7ccc06 100644 --- a/pyhealth/processors/tuple_time_text_processor.py +++ b/pyhealth/processors/tuple_time_text_processor.py @@ -3,6 +3,7 @@ import logging from .base_processor import FeatureProcessor, ModalityType, TemporalFeatureProcessor from . import register_processor +from pyhealth.datasets.collate import _stack_positions logger = logging.getLogger(__name__) @@ -15,24 +16,34 @@ class TupleTimeTextProcessor(TemporalFeatureProcessor): If `tokenizer_model` is provided, the text will be tokenized using a HuggingFace AutoTokenizer, and the output will differ from the raw text version. + + Example: + >>> proc = TupleTimeTextProcessor() + >>> texts, times, tag = proc.process((["note one"], [0.0])) + >>> tag + 'note' """ - + + # Batches of this processor's field also get {field}__pad_mask. + emits_pad_mask = True + def __init__( self, type_tag: str = "note", tokenizer_model: Optional[str] = None, - max_length: int = 128, + max_length: int = 512, padding: bool = True, truncation: bool = True, ): """Initialize the processor. - + Args: type_tag: Modality identifier for automatic routing. Default: "note" tokenizer_model: Name or path of the HuggingFace tokenizer to use. If None, texts are returned as raw strings. Default: None - max_length: Maximum sequence length for tokenization. Default: 128 - padding: Whether to pad sequences to max_length. Default: True + max_length: Maximum sequence length for tokenization. Default: 512 + padding: Whether to pad sequences to the longest note in the sample. + Default: True truncation: Whether to truncate sequences to max_length. Default: True """ super().__init__() @@ -81,28 +92,65 @@ def process(self, value: Tuple[List[str], List[float]]) -> Union[Tuple[List[str] - str: Type tag """ texts, time_diffs = value + texts = list(texts or []) + time_diffs = list(time_diffs or []) + + # Keep text/time aligned and filter malformed text entries. + pair_count = min(len(texts), len(time_diffs)) + cleaned_texts: list[str] = [] + cleaned_times: list[float] = [] + for i in range(pair_count): + raw_text = texts[i] + raw_time = time_diffs[i] + + # Normalize text; skip null/whitespace-only entries. + if raw_text is None: + continue + text = str(raw_text).strip() + if text == "": + continue + + # Best-effort float normalization; skip unparseable timestamps. + try: + t = float(raw_time) + except (TypeError, ValueError): + continue + + cleaned_texts.append(text) + cleaned_times.append(t) + + texts = cleaned_texts + time_diffs = cleaned_times time_tensor = torch.tensor(time_diffs, dtype=torch.float32) if self.tokenizer is not None: - # Tokenize the list of texts + # Fast tokenizers crash on tokenizer([]). Build empty tensors + # ourselves so a patient with no notes is zero events, not a + # fake "[MISSING_TEXT]" row whose BERT embedding is a constant + # the classifier can use as a mortality feature. + if len(texts) == 0: + empty = torch.zeros((0, 1), dtype=torch.long) + return empty, empty.clone(), empty.clone(), time_tensor, self.type_tag encoded = self.tokenizer( texts, - padding="max_length" if self.padding else False, + padding="longest" if self.padding else False, truncation=self.truncation, max_length=self.max_length, return_tensors="pt" ) - - input_ids = encoded["input_ids"] - attention_mask = encoded["attention_mask"] - + + input_ids = encoded.get("input_ids") + if input_ids is None: + raise ValueError("Tokenizer output is missing required `input_ids`.") + + attention_mask = encoded.get("attention_mask") + if attention_mask is None: + attention_mask = torch.ones_like(input_ids) + # Not all tokenizers return token_type_ids (e.g. RoBERTa might not, BERT does) - if "token_type_ids" in encoded: - token_type_ids = encoded["token_type_ids"] - else: - # meaningful text usually 0, padding 0? BERT uses 0 for sent A. - # If not provided, we can just use zeros or omit. - # For consistency with schema, let's provide zeros if expected. + token_type_ids = encoded.get("token_type_ids") + if token_type_ids is None: + # Some tokenizers do not return token_type_ids. token_type_ids = torch.zeros_like(input_ids) return input_ids, attention_mask, token_type_ids, time_tensor, self.type_tag @@ -169,6 +217,24 @@ def process_temporal(self, value) -> dict: "time": result[3], # time tensor (N,) } + def collate(self, values: list[tuple]) -> tuple: + """Collates a batch of processed tuples, one tuple position at a time. + + Ragged note counts and note lengths pad to the batch maximum, and the + type tag stays a list. ``get_dataloader`` batches the field with this + method and adds the ``{field}__pad_mask`` event mask for the batch. + + Examples: + >>> import torch + >>> proc = TupleTimeTextProcessor() + >>> batch = [(torch.ones(2, 3), torch.ones(2), "note"), + ... (torch.ones(1, 3), torch.ones(1), "note")] + >>> value, time, tag = proc.collate(batch) + >>> value.shape, time.shape, tag + (torch.Size([2, 2, 3]), torch.Size([2, 2]), ['note', 'note']) + """ + return _stack_positions(values) + def __repr__(self): if self.tokenizer_model: return f"TupleTimeTextProcessor(type_tag='{self.type_tag}', tokenizer='{self.tokenizer_model}')" diff --git a/pyhealth/tasks/__init__.py b/pyhealth/tasks/__init__.py index a26d757e83..c79a28dcc6 100644 --- a/pyhealth/tasks/__init__.py +++ b/pyhealth/tasks/__init__.py @@ -143,6 +143,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..8f09054f38 --- /dev/null +++ b/pyhealth/tasks/multimodal_mimic4.py @@ -0,0 +1,660 @@ +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`. + + 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 + 0 + """ + + 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 = 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 + # 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 > 0: + 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 == 0: + 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. ``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 + 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', 0, 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 = 0, + 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. + ``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', 0) + """ + + 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 = 0) -> 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/pyhealth/trainer.py b/pyhealth/trainer.py index abf44efad2..5271e8b3e0 100644 --- a/pyhealth/trainer.py +++ b/pyhealth/trainer.py @@ -23,6 +23,77 @@ logger = logging.getLogger(__name__) +_AMP_DTYPES = { + "bf16": torch.bfloat16, + "bfloat16": torch.bfloat16, + "fp16": torch.float16, + "float16": torch.float16, +} + + +def resolve_amp_dtype(amp_dtype: str, use_amp: bool = False) -> torch.dtype: + """Validate the mixed-precision dtype and return it. + + The previous expression was ``bfloat16 if amp_dtype == "bf16" else + float16``, so every other spelling silently selected fp16 and, through + GradScaler, changed gradient behaviour too. + + Args: + amp_dtype: Dtype name, one of ``"bf16"``, ``"bfloat16"``, + ``"fp16"`` or ``"float16"`` (case-insensitive). + use_amp: Whether mixed precision will be used. When True and the + resolved dtype is bf16, a CUDA device without bf16 support + raises instead of silently running an unsupported mode. + + Returns: + The matching ``torch.dtype``. + + Examples: + >>> from pyhealth.trainer import resolve_amp_dtype + >>> import torch + >>> resolve_amp_dtype("bfloat16") is torch.bfloat16 + True + """ + name = str(amp_dtype).lower() + if name not in _AMP_DTYPES: + raise ValueError( + f"amp_dtype must be one of {sorted(_AMP_DTYPES)}, got {amp_dtype!r}." + ) + dtype = _AMP_DTYPES[name] + if ( + use_amp + and dtype == torch.bfloat16 + and torch.cuda.is_available() + and not torch.cuda.is_bf16_supported() + ): + raise RuntimeError( + "bf16 mixed precision was requested, but this CUDA device does " + "not support bf16." + ) + return dtype + + +def autocast_device_type(device) -> str: + """Device type string for ``torch.autocast``, from the trainer device. + + Args: + device: Device or device string used by the trainer, e.g. + ``"cuda:0"``, ``"cpu"`` or ``"mps"``. + + Returns: + One of ``"cuda"``, ``"cpu"`` or ``"mps"``; anything else falls + back to ``"cpu"``. + + Examples: + >>> from pyhealth.trainer import autocast_device_type + >>> autocast_device_type("cuda:0") + 'cuda' + """ + name = str(device).split(":", 1)[0].lower() + if name in ("cuda", "cpu", "mps"): + return name + return "cpu" + def _cpu_state_dict(model: nn.Module) -> dict: """A detached CPU copy of the model's state, safe from later updates.""" @@ -211,6 +282,9 @@ def train( load_best_model_at_last: bool = True, patience=None, keep_best_in_memory: bool = True, + accumulation_steps: int = 1, + use_amp: bool = False, + amp_dtype: str = "bf16", ): """Trains the model. @@ -238,6 +312,12 @@ def train( last epoch's weights are kept (with a warning). With an output directory the best weights are saved to ``best.ckpt`` instead. Default is True. + accumulation_steps: Gradient accumulation steps to simulate a larger + effective batch size. Default is 1 (no accumulation). + use_amp: Whether to use automatic mixed precision. Default is False. + amp_dtype: AMP dtype — "bf16" (stable, recommended) or "fp16". + Unknown spellings raise instead of silently using fp16. + Default is "bf16". Raises: TypeError: If the model is fit outside the trainer (it sets @@ -253,10 +333,24 @@ def train( ) if optimizer_params is None: optimizer_params = {"lr": 1e-3} + if accumulation_steps < 1: + raise ValueError( + f"accumulation_steps must be at least 1, got {accumulation_steps}." + ) + + _amp_dtype = resolve_amp_dtype(amp_dtype, use_amp=use_amp) + # GradScaler only needed for fp16; bf16 has fp32 dynamic range + scaler = ( + torch.amp.GradScaler("cuda") + if (use_amp and _amp_dtype == torch.float16) + else None + ) # logging logger.info("Training:") logger.info(f"Batch size: {train_dataloader.batch_size}") + logger.info(f"Accumulation steps: {accumulation_steps}") + logger.info(f"AMP: {use_amp} (dtype={amp_dtype})") logger.info(f"Optimizer: {optimizer_class}") logger.info(f"Optimizer params: {optimizer_params}") logger.info(f"Weight decay: {weight_decay}") @@ -310,7 +404,7 @@ def train( self.model.train() # batch training loop logger.info("") - for _ in trange( + for step_idx in trange( steps_per_epoch, desc=f"Epoch {epoch} / {epochs}", smoothing=0.05, @@ -320,20 +414,46 @@ def train( except StopIteration: data_iterator = iter(train_dataloader) data = next(data_iterator) - # forward - output = self.model(**data) - loss = output["loss"] + # forward (with optional AMP) + if use_amp: + with torch.autocast( + device_type=autocast_device_type(self.device), + dtype=_amp_dtype, + ): + output = self.model(**data) + loss = output["loss"] / accumulation_steps + else: + output = self.model(**data) + loss = output["loss"] / accumulation_steps # backward - loss.backward() - if max_grad_norm is not None: - torch.nn.utils.clip_grad_norm_( - self.model.parameters(), max_grad_norm - ) - # update - optimizer.step() - optimizer.zero_grad() - training_loss.append(loss.item()) - global_step += 1 + if scaler is not None: + scaler.scale(loss).backward() + else: + loss.backward() + training_loss.append(loss.item() * accumulation_steps) + # optimizer step every accumulation_steps batches or epoch end + is_update_step = ( + (step_idx + 1) % accumulation_steps == 0 + or (step_idx + 1) == steps_per_epoch + ) + if is_update_step: + if scaler is not None: + # Unscale before clipping; step() then skips + # non-finite gradients itself. + scaler.unscale_(optimizer) + # Clip only when configured: the default path matches + # upstream exactly (no unconditional grad-norm pass). + if max_grad_norm is not None: + torch.nn.utils.clip_grad_norm_( + self.model.parameters(), max_grad_norm + ) + if scaler is not None: + scaler.step(optimizer) + scaler.update() + else: + optimizer.step() + optimizer.zero_grad() + global_step += 1 # log and save logger.info(f"--- Train epoch-{epoch}, step-{global_step} ---") logger.info(f"loss: {sum(training_loss) / len(training_loss):.4f}") diff --git a/tests/core/test_attention_mask_dtype_min.py b/tests/core/test_attention_mask_dtype_min.py new file mode 100644 index 0000000000..1b855b4980 --- /dev/null +++ b/tests/core/test_attention_mask_dtype_min.py @@ -0,0 +1,132 @@ +"""Attention mask fill is fp16-safe and ordinary forwards use fused SDPA. + +``-1e9`` is outside the fp16 range, so padding an fp16 forward raised +``value cannot be converted to type ... without overflow``. Ordinary +training forwards now use fused ``scaled_dot_product_attention``; the +explicit path stays behind ``register_hook=True`` for interpretability +and fills with ``finfo(dtype).min``. + +A fully-masked query row attends to nothing, which is NaN or garbage +depending on backend and dtype. The fused path lets such rows attend +uniformly and then zeroes their outputs, so an all-padded sample (reachable +once empty modalities become zero-length fields) stays finite. + +Repro:: + + PYTEST_DISABLE_PLUGIN_AUTOLOAD=1 PYTHONPATH=. \\ + python -m pytest tests/core/test_attention_mask_dtype_min.py -q +""" + +from __future__ import annotations + +import unittest +from unittest import mock + +import torch + + +class TestAttentionMaskDtypeMin(unittest.TestCase): + def test_fp16_attention_mask_fill_does_not_overflow(self): + from pyhealth.models.transformer import Attention + + attn = Attention() + q = torch.zeros(1, 1, 2, 4, dtype=torch.float16) + k = torch.zeros(1, 1, 2, 4, dtype=torch.float16) + v = torch.ones(1, 1, 2, 4, dtype=torch.float16) + mask = torch.tensor([[[[1, 0], [1, 0]]]], dtype=torch.float16) + out, weights = attn(q, k, v, mask=mask) + self.assertTrue(torch.isfinite(out).all()) + self.assertTrue(torch.isfinite(weights).all()) + self.assertEqual(float(weights[0, 0, 0, 1]), 0.0) + + def test_explicit_path_finite_for_all_padded_row(self): + from pyhealth.models.transformer import Attention + + attn = Attention() + q = torch.randn(1, 1, 4, 8) + k = torch.randn(1, 1, 4, 8) + v = torch.randn(1, 1, 4, 8) + mask = torch.ones(1, 1, 4, 4) + mask[:, :, 0, :] = 0 # first query row fully masked + out, weights = attn(q, k, v, mask=mask) + self.assertTrue(torch.isfinite(out).all()) + self.assertTrue(torch.isfinite(weights).all()) + + def test_raw_minus_1e9_still_overflows_fp16(self): + scores = torch.zeros(2, 2, dtype=torch.float16) + with self.assertRaises(RuntimeError): + scores.masked_fill(torch.tensor([[True, False], [False, True]]), -1e9) + + def test_ordinary_forward_uses_fused_sdpa(self): + from pyhealth.models import transformer as transformer_module + + torch.manual_seed(0) + mha = transformer_module.MultiHeadedAttention(h=2, d_model=8).eval() + q = k = v = torch.zeros(2, 5, 8) + mask = torch.ones(2, 5) + real_sdpa = transformer_module.F.scaled_dot_product_attention + with mock.patch.object( + transformer_module.F, + "scaled_dot_product_attention", + wraps=real_sdpa, + ) as sdpa: + mha(q, k, v, mask=mask, register_hook=False) + self.assertEqual(sdpa.call_count, 1) + with mock.patch.object( + transformer_module.F, + "scaled_dot_product_attention", + wraps=real_sdpa, + ) as sdpa: + mha(q, k, v, mask=mask, register_hook=True) + sdpa.assert_not_called() + + def test_fused_and_explicit_paths_agree(self): + from pyhealth.models.transformer import TransformerLayer + + torch.manual_seed(0) + layer = TransformerLayer(feature_size=128, heads=4, num_layers=2).eval() + x = torch.randn(4, 32, 128, requires_grad=True) + mask = torch.ones(4, 32) + fused, _ = layer(x, mask, register_hook=False) + explicit, _ = layer(x, mask, register_hook=True) + self.assertLessEqual(float((fused - explicit).abs().max()), 1e-5) + + mask_pad = torch.cat([torch.ones(4, 20), torch.zeros(4, 12)], dim=1) + fused_pad, _ = layer(x, mask_pad, register_hook=False) + explicit_pad, _ = layer(x, mask_pad, register_hook=True) + # Padded query outputs are discarded downstream (the feed-forward + # zeroes them), so the paths must agree at valid positions. + self.assertLessEqual( + float((fused_pad[:, :20] - explicit_pad[:, :20]).abs().max()), 1e-5 + ) + + def test_all_padded_sample_stays_finite(self): + from pyhealth.models.transformer import MultiHeadedAttention + + torch.manual_seed(0) + for mask_2d in (True, False): + mha = MultiHeadedAttention(h=2, d_model=8).eval() + q = k = v = torch.randn(3, 6, 8) + valid = torch.ones(3, 6) + valid[0, :] = 0 # one all-padded sample + mask = valid if mask_2d else torch.einsum("ab,ac->abc", valid, valid) + out = mha(q, k, v, mask=mask, register_hook=False) + self.assertTrue(torch.isfinite(out).all()) + # Padded query rows produce exact zeros in the fused path. + self.assertTrue(torch.equal(out[0], torch.zeros_like(out[0]))) + self.assertFalse(torch.equal(out[1], torch.zeros_like(out[1]))) + + def test_all_padded_sample_layer_forward(self): + from pyhealth.models.transformer import TransformerLayer + + torch.manual_seed(0) + layer = TransformerLayer(feature_size=64, heads=4, num_layers=2).eval() + x = torch.randn(3, 16, 64) + x[0] = 0.0 # all-padded sample carries no signal + mask = torch.ones(3, 16) + mask[0, :] = 0 + fused, _ = layer(x, mask, register_hook=False) + explicit, _ = layer(x, mask, register_hook=True) + self.assertTrue(torch.isfinite(fused).all()) + self.assertTrue(torch.isfinite(explicit).all()) + self.assertTrue(torch.equal(fused[0], torch.zeros_like(fused[0]))) diff --git a/tests/core/test_bottleneck_transformer.py b/tests/core/test_bottleneck_transformer.py new file mode 100644 index 0000000000..d98b503d03 --- /dev/null +++ b/tests/core/test_bottleneck_transformer.py @@ -0,0 +1,89 @@ +"""BottleneckTransformer per-field and unified modes on a tiny two-field dataset.""" + +import unittest + +import torch + +from pyhealth.datasets import create_sample_dataset, get_dataloader +from pyhealth.models import BottleneckTransformer +from pyhealth.models.unified_embedding import UnifiedMultimodalEmbeddingModel + + +def _dataset(): + samples = [ + { + "patient_id": "patient-0", + "visit_id": "visit-0", + "codes": ([0.0, 2.0], ["A", "B"]), + "labs": ([0.0, 2.0], [[1.0, 2.0], [3.0, 4.0]]), + "label": 1, + }, + { + "patient_id": "patient-1", + "visit_id": "visit-0", + "codes": ([0.0], ["C"]), + "labs": ([0.0], [[5.0, 6.0]]), + "label": 0, + }, + ] + return create_sample_dataset( + samples=samples, + input_schema={"codes": "stagenet", "labs": "stagenet_tensor"}, + output_schema={"label": "binary"}, + dataset_name="test_bottleneck_transformer", + ) + + +def _batch(dataset): + return next(iter(get_dataloader(dataset, batch_size=2, shuffle=False))) + + +class TestBottleneckTransformer(unittest.TestCase): + def test_per_field_forward_backward_finite(self): + dataset = _dataset() + model = BottleneckTransformer( + dataset=dataset, + embedding_dim=8, + bottlenecks_n=2, + fusion_startidx=1, + num_layers=2, + heads=2, + dropout=0.0, + ) + self.assertFalse(model._use_unified) + out = model(**_batch(dataset)) + self.assertEqual(out["logit"].shape, (2, 1)) + self.assertTrue(torch.isfinite(out["loss"])) + out["loss"].backward() + self.assertTrue( + any(p.grad is not None for p in model.parameters() if p.requires_grad) + ) + + def test_unified_forward_backward_finite(self): + dataset = _dataset() + unified = UnifiedMultimodalEmbeddingModel( + dataset.input_processors, embedding_dim=8 + ) + model = BottleneckTransformer( + dataset=dataset, + embedding_dim=8, + bottlenecks_n=2, + fusion_startidx=1, + num_layers=2, + heads=2, + dropout=0.0, + unified_embedding=unified, + ) + self.assertTrue(model._use_unified) + out = model(**_batch(dataset)) + self.assertEqual(out["logit"].shape, (2, 1)) + self.assertTrue(torch.isfinite(out["loss"])) + self.assertTrue(torch.isfinite(out["y_prob"]).all()) + out["loss"].backward() + self.assertTrue( + any(p.grad is not None for p in model.parameters() if p.requires_grad) + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/core/test_collate_pad_mask.py b/tests/core/test_collate_pad_mask.py new file mode 100644 index 0000000000..fab7cb3a61 --- /dev/null +++ b/tests/core/test_collate_pad_mask.py @@ -0,0 +1,52 @@ +"""Collators emit {field}__pad_mask for legacy tuple fields.""" + +import unittest + +import torch + +from pyhealth.datasets.collate import collate_temporal +from pyhealth.datasets.utils import PAD_MASK_SUFFIX, collate_fn_dict_with_padding + + +class TestCollatePadMask(unittest.TestCase): + def test_temporal_collator_marks_time_padding(self): + batch = [ + {"labs": {"value": torch.ones(3, 2), "time": torch.tensor([0.0, 1.0, 2.0])}}, + {"labs": {"value": torch.ones(1, 2), "time": torch.tensor([0.0])}}, + ] + out = collate_temporal(batch) + self.assertEqual(out["labs"]["value"].shape, (2, 3, 2)) + self.assertEqual( + out["labs"]["pad_mask"].tolist(), + [[True, True, True], [True, False, False]], + ) + + def test_dict_collator_emits_suffix_mask(self): + batch = [ + {"notes": (torch.ones(3, 4, dtype=torch.long), torch.ones(3, 4))}, + {"notes": (torch.ones(1, 4, dtype=torch.long), torch.ones(1, 4))}, + ] + collated = collate_fn_dict_with_padding(batch) + self.assertEqual(tuple(collated["notes"][1].shape), (2, 3, 4)) + self.assertEqual( + collated[f"notes{PAD_MASK_SUFFIX}"].tolist(), + [[True, True, True], [True, False, False]], + ) + + def test_equal_shapes_emit_no_mask(self): + batch = [ + {"labs": (torch.tensor([0.0, 1.0]), torch.ones(2, 2))}, + {"labs": (torch.tensor([0.0, 2.0]), torch.ones(2, 2))}, + ] + collated = collate_fn_dict_with_padding(batch) + self.assertNotIn(f"labs{PAD_MASK_SUFFIX}", collated) + + def test_collator_keys_skip_padding_and_mask(self): + batch = [{"x": torch.tensor([1, 2])}, {"x": torch.tensor([3])}] + out = collate_fn_dict_with_padding(batch, collators={"x": len}) + self.assertEqual(out["x"], 2) + self.assertNotIn(f"x{PAD_MASK_SUFFIX}", out) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/core/test_dask_distributed_flag.py b/tests/core/test_dask_distributed_flag.py new file mode 100644 index 0000000000..d849e5b2d4 --- /dev/null +++ b/tests/core/test_dask_distributed_flag.py @@ -0,0 +1,141 @@ +"""Opt out of the Dask distributed cluster for event caching. + +``BaseDataset(use_dask_distributed=False)`` makes ``_event_transform`` write +the cache with the local Dask scheduler instead of starting a distributed +cluster, for sandboxes where the cluster cannot start. The default ``True`` +keeps the distributed path (with ``dashboard_address=None``) unchanged, and +the flag does not affect the cache key or the written contents. + +Repro:: + + PYTEST_DISABLE_PLUGIN_AUTOLOAD=1 PYTHONPATH=. \ + python -m pytest tests/core/test_dask_distributed_flag.py -q +""" + +from __future__ import annotations + +import tempfile +import unittest +from pathlib import Path +from unittest.mock import patch + +import dask.dataframe as dd +import pandas as pd + + +class TestDaskDistributedFlag(unittest.TestCase): + def _dataset(self, cache_root: str, use_dask_distributed: bool = True, dev=False): + from pyhealth.datasets.base_dataset import BaseDataset + + class MockDataset(BaseDataset): + def __init__(self, data: dd.DataFrame, **kwargs): + self._data = data + super().__init__(**kwargs) + + def load_data(self) -> dd.DataFrame: + return self._data + + data = dd.from_pandas( + pd.DataFrame( + { + # Unsorted on purpose, and "2" repeats: both paths sort + # by patient_id, but the two schedulers may order the + # tied rows of one patient differently. + "patient_id": ["2", "1", "3", "2"], + "event_type": ["test", "test", "test", "test"], + "timestamp": [None, None, None, None], + "test/value": [2, 0, 1, 3], + # Table loading adds this column; the test's frame stands + # in for a loaded table, so it carries it too. + "_source_row": [0, 1, 2, 3], + } + ), + npartitions=2, + ) + with patch( + "pyhealth.datasets.base_dataset.platformdirs.user_cache_dir", + return_value=cache_root, + ): + dataset = MockDataset( + data=data, + root="/data/root_a", + tables=["table_a"], + dataset_name="FlagDataset", + dev=dev, + num_workers=2, + use_dask_distributed=use_dask_distributed, + ) + return dataset + + def _cached_frame(self, out): + # Both paths write sorted by patient_id. Check that here instead of + # re-sorting, so a missing sort on either path is caught. + frame = dd.read_parquet(out).compute().reset_index(drop=True) + self.assertTrue(frame["patient_id"].is_monotonic_increasing) + return frame.astype({"test/value": "int64"}) + + def test_flag_defaults_to_distributed(self): + import inspect + + from pyhealth.datasets.base_dataset import BaseDataset + + sig = inspect.signature(BaseDataset.__init__) + self.assertIn("use_dask_distributed", sig.parameters) + self.assertTrue(sig.parameters["use_dask_distributed"].default) + + def test_false_bypasses_cluster(self): + with tempfile.TemporaryDirectory() as cache_root: + dataset = self._dataset(cache_root, use_dask_distributed=False) + self.assertFalse(dataset.use_dask_distributed) + with tempfile.TemporaryDirectory() as tmp: + out = Path(tmp) / "events.parquet" + with patch( + "pyhealth.datasets.base_dataset.DaskCluster", + side_effect=AssertionError("cluster must not start"), + ): + dataset._event_transform(out) + self.assertTrue(out.exists()) + + def test_true_uses_cluster(self): + with tempfile.TemporaryDirectory() as cache_root: + dataset = self._dataset(cache_root, use_dask_distributed=True) + with tempfile.TemporaryDirectory() as tmp: + out = Path(tmp) / "events.parquet" + with patch( + "pyhealth.datasets.base_dataset.DaskCluster", + side_effect=RuntimeError("cluster entry reached"), + ): + with self.assertRaises(RuntimeError): + dataset._event_transform(out) + + def test_flag_does_not_change_cache_key(self): + with tempfile.TemporaryDirectory() as cache_root: + on = self._dataset(cache_root, use_dask_distributed=True) + off = self._dataset(cache_root, use_dask_distributed=False) + self.assertEqual(on.cache_dir, off.cache_dir) + + def test_flag_path_matches_distributed_contents(self): + for dev in (False, True): + with tempfile.TemporaryDirectory() as cache_root: + local = self._dataset( + cache_root, use_dask_distributed=False, dev=dev + ) + dist = self._dataset( + cache_root, use_dask_distributed=True, dev=dev + ) + # Same key so the same directory would be reused; write the + # two arms to separate output dirs to compare contents. + with tempfile.TemporaryDirectory() as tmp: + flag_out = Path(tmp) / "flag.parquet" + dist_out = Path(tmp) / "dist.parquet" + local._event_transform(flag_out) + dist._event_transform(dist_out) + # Rows of one patient may come out in either order from + # the two schedulers, so compare in source-row order. + key = ["patient_id", "_source_row"] + flag = self._cached_frame(flag_out) + dist = self._cached_frame(dist_out) + pd.testing.assert_frame_equal( + flag.sort_values(key, kind="stable").reset_index(drop=True), + dist.sort_values(key, kind="stable").reset_index(drop=True), + ) diff --git a/tests/core/test_dataloader_worker_options.py b/tests/core/test_dataloader_worker_options.py new file mode 100644 index 0000000000..cda8c8ad76 --- /dev/null +++ b/tests/core/test_dataloader_worker_options.py @@ -0,0 +1,103 @@ +"""get_dataloader exposes DataLoader worker options. + +``num_workers``, ``pin_memory``, ``persistent_workers`` and +``prefetch_factor`` pass through upstream's seeded loader (#1280), so +reproducible shuffling is kept while batch loading can use workers. +Invalid combinations are rejected by PyTorch's DataLoader. + +Repro:: + + PYTEST_DISABLE_PLUGIN_AUTOLOAD=1 PYTHONPATH=. \\ + python -m pytest tests/core/test_dataloader_worker_options.py -q +""" + +from __future__ import annotations + +import unittest + + +def _dataset(n=8): + from pyhealth.datasets import create_sample_dataset + + samples = [ + {"patient_id": f"p{i}", "x": [float(i)], "y": i % 2} for i in range(n) + ] + return create_sample_dataset(samples, {"x": "tensor"}, {"y": "binary"}) + + +class TestDataloaderWorkerOptions(unittest.TestCase): + def test_defaults_match_plain_loader(self): + from pyhealth.datasets import get_dataloader + + loader = get_dataloader(_dataset(), batch_size=4) + self.assertEqual(loader.num_workers, 0) + self.assertFalse(loader.pin_memory) + batches = list(loader) + self.assertEqual(len(batches), 2) + + def test_options_pass_through_seeded_loader(self): + from pyhealth.datasets import get_dataloader + + loader = get_dataloader( + _dataset(), + batch_size=4, + num_workers=1, + pin_memory=False, + persistent_workers=True, + prefetch_factor=2, + ) + self.assertEqual(loader.num_workers, 1) + self.assertTrue(loader.persistent_workers) + self.assertEqual(loader.prefetch_factor, 2) + batches = list(loader) + self.assertEqual(len(batches), 2) + + def test_shuffle_still_reproducible_with_workers(self): + from pyhealth.datasets import get_dataloader + + ds = _dataset() + order = lambda loader: [ # noqa: E731 + pid for b in loader for pid in b["patient_id"] + ] + first = order( + get_dataloader(ds, 4, shuffle=True, seed=1, num_workers=1) + ) + second = order( + get_dataloader(ds, 4, shuffle=True, seed=1, num_workers=1) + ) + self.assertEqual(first, second) + + def test_two_workers_cover_every_sample_once(self): + from pyhealth.datasets import get_dataloader + + expected = {f"p{i}" for i in range(8)} + for seed in (1, 2): + loader = get_dataloader( + _dataset(), 4, shuffle=True, seed=seed, num_workers=2 + ) + first_pass = [pid for b in loader for pid in b["patient_id"]] + # Seeded: a fresh loader replays the same shuffle. + replay = [ + pid + for b in get_dataloader( + _dataset(), 4, shuffle=True, seed=seed, num_workers=2 + ) + for pid in b["patient_id"] + ] + self.assertEqual(first_pass, replay) + # No duplication or loss across workers: every sample exactly once. + self.assertEqual(sorted(first_pass), sorted(expected)) + # The next epoch reshuffles but still covers every sample once. + second_pass = [pid for b in loader for pid in b["patient_id"]] + self.assertEqual(sorted(second_pass), sorted(expected)) + + def test_invalid_combinations_raise(self): + from pyhealth.datasets import get_dataloader + + ds = _dataset() + with self.assertRaises(ValueError): + get_dataloader(ds, 4, num_workers=-1) + with self.assertRaises(ValueError): + get_dataloader(ds, 4, persistent_workers=True) + with self.assertRaises(ValueError): + get_dataloader(ds, 4, prefetch_factor=2) diff --git a/tests/core/test_ehrmamba_unified.py b/tests/core/test_ehrmamba_unified.py new file mode 100644 index 0000000000..78152b4670 --- /dev/null +++ b/tests/core/test_ehrmamba_unified.py @@ -0,0 +1,69 @@ +"""EHRMamba unified mode over a tiny two-field temporal dataset.""" + +import unittest + +import torch + +from pyhealth.datasets import create_sample_dataset, get_dataloader +from pyhealth.models import EHRMamba +from pyhealth.models.unified_embedding import UnifiedMultimodalEmbeddingModel + + +def _dataset(): + samples = [ + { + "patient_id": "patient-0", + "visit_id": "visit-0", + "codes": ([0.0, 2.0], ["A", "B"]), + "labs": ([0.0, 2.0], [[1.0, 2.0], [3.0, 4.0]]), + "label": 1, + }, + { + "patient_id": "patient-1", + "visit_id": "visit-0", + "codes": ([0.0], ["C"]), + "labs": ([0.0], [[5.0, 6.0]]), + "label": 0, + }, + ] + return create_sample_dataset( + samples=samples, + input_schema={"codes": "stagenet", "labs": "stagenet_tensor"}, + output_schema={"label": "binary"}, + dataset_name="test_ehrmamba_unified", + ) + + +class TestEHRMambaUnified(unittest.TestCase): + def test_unified_forward_backward_loss_finite(self): + dataset = _dataset() + unified = UnifiedMultimodalEmbeddingModel( + dataset.input_processors, embedding_dim=8 + ) + model = EHRMamba( + dataset=dataset, embedding_dim=8, num_layers=1, + unified_embedding=unified, + ) + batch = next(iter(get_dataloader(dataset, batch_size=2, shuffle=False))) + out = model(**batch) + self.assertTrue(torch.isfinite(out["loss"])) + out["loss"].backward() + self.assertTrue( + any( + p.grad is not None + for p in model.parameters() + if p.requires_grad + ) + ) + + def test_per_field_mode_unchanged(self): + dataset = _dataset() + model = EHRMamba(dataset=dataset, embedding_dim=8, num_layers=1) + self.assertFalse(model._use_unified) + batch = next(iter(get_dataloader(dataset, batch_size=2, shuffle=False))) + out = model(**batch) + self.assertTrue(torch.isfinite(out["loss"])) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/core/test_jamba_unified.py b/tests/core/test_jamba_unified.py new file mode 100644 index 0000000000..5e1fc09754 --- /dev/null +++ b/tests/core/test_jamba_unified.py @@ -0,0 +1,73 @@ +"""JambaEHR unified mode over a tiny two-field temporal dataset.""" + +import unittest + +import torch + +from pyhealth.datasets import create_sample_dataset, get_dataloader +from pyhealth.models import JambaEHR +from pyhealth.models.unified_embedding import UnifiedMultimodalEmbeddingModel + + +def _dataset(): + samples = [ + { + "patient_id": "patient-0", + "visit_id": "visit-0", + "codes": ([0.0, 2.0], ["A", "B"]), + "labs": ([0.0, 2.0], [[1.0, 2.0], [3.0, 4.0]]), + "label": 1, + }, + { + "patient_id": "patient-1", + "visit_id": "visit-0", + "codes": ([0.0], ["C"]), + "labs": ([0.0], [[5.0, 6.0]]), + "label": 0, + }, + ] + return create_sample_dataset( + samples=samples, + input_schema={"codes": "stagenet", "labs": "stagenet_tensor"}, + output_schema={"label": "binary"}, + dataset_name="test_jamba_unified", + ) + + +class TestJambaUnified(unittest.TestCase): + def test_unified_forward_backward_loss_finite(self): + dataset = _dataset() + unified = UnifiedMultimodalEmbeddingModel( + dataset.input_processors, embedding_dim=8 + ) + model = JambaEHR( + dataset=dataset, embedding_dim=8, + num_transformer_layers=1, num_mamba_layers=1, heads=1, + unified_embedding=unified, + ) + batch = next(iter(get_dataloader(dataset, batch_size=2, shuffle=False))) + out = model(**batch) + self.assertTrue(torch.isfinite(out["loss"])) + out["loss"].backward() + self.assertTrue( + any( + p.grad is not None + for p in model.parameters() + if p.requires_grad + ) + ) + + def test_per_field_mode_unchanged(self): + dataset = _dataset() + model = JambaEHR( + dataset=dataset, embedding_dim=8, + num_transformer_layers=1, num_mamba_layers=1, heads=1, + ) + self.assertFalse(model._use_unified) + batch = next(iter(get_dataloader(dataset, batch_size=2, shuffle=False))) + out = model(**batch) + self.assertTrue(torch.isfinite(out["loss"])) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/core/test_p1_observation_window.py b/tests/core/test_p1_observation_window.py new file mode 100644 index 0000000000..5320b18476 --- /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=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.) + +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_zero_still_collects_through_discharge(self): + from pyhealth.tasks.multimodal_mimic4 import LabsMIMIC4 + + 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) + + def test_protocol_default_is_full_stay(self): + from pyhealth.tasks.multimodal_mimic4 import LabsMIMIC4, NotesLabsMIMIC4 + + 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 + from pyhealth.tasks.multimodal_mimic4 import NotesLabsMIMIC4 + + self.assertFalse(hasattr(m, "ICDLabsMIMIC4")) + self.assertFalse(NotesLabsMIMIC4().include_icd) diff --git a/tests/core/test_p1_pad_masks.py b/tests/core/test_p1_pad_masks.py new file mode 100644 index 0000000000..504ca4bbbb --- /dev/null +++ b/tests/core/test_p1_pad_masks.py @@ -0,0 +1,237 @@ +"""Batch padding is recorded and skipped by the unified path. + +The collator padded short samples with 0.0 and nothing recorded that padding, +so padded slots looked like real measurements at admission time. +""" + +from __future__ import annotations + +import unittest + +import torch +import torch.nn as nn + + +class TestP1RnnClamp(unittest.TestCase): + def test_all_pad_mask_forward_is_finite(self): + from pyhealth.models.rnn import RNNLayer + + layer = RNNLayer(input_size=4, hidden_size=8, dropout=0.0).eval() + x = torch.zeros(2, 5, 4) + mask = torch.zeros(2, 5) + with torch.no_grad(): + outputs, last = layer(x, mask) + self.assertEqual(outputs.shape[0], 2) + self.assertEqual(tuple(last.shape), (2, 8)) + self.assertTrue(torch.isfinite(last).all()) + + +class TestP1BertPadSkip(unittest.TestCase): + def test_collate_emits_false_pad_mask_on_empty_note_slots(self): + from pyhealth.datasets.utils import PAD_MASK_SUFFIX, collate_fn_dict_with_padding + + batch = [ + {"notes": (torch.ones(3, 4, dtype=torch.long), torch.ones(3, 4))}, + {"notes": (torch.ones(1, 4, dtype=torch.long), torch.ones(1, 4))}, + ] + collated = collate_fn_dict_with_padding(batch) + ids = collated["notes"][1] + pad = collated[f"notes{PAD_MASK_SUFFIX}"] + self.assertEqual(tuple(ids.shape), (2, 3, 4)) + self.assertEqual(pad.tolist(), [[True, True, True], [True, False, False]]) + + def test_padded_events_sort_last_and_are_zeroed(self): + from pyhealth.models.unified_embedding import UnifiedMultimodalEmbeddingModel + from pyhealth.processors.stagenet_processor import StageNetTensorProcessor + + proc = StageNetTensorProcessor() + proc.fit([{"labs": ([0.0], [[1.0, 2.0]])}], "labs") + model = UnifiedMultimodalEmbeddingModel( + processors={"labs": proc}, + embedding_dim=8, + normalize_content=True, + ) + model.eval() + value = torch.tensor([[[3.0, 4.0], [0.0, 0.0]]]) + time = torch.tensor([[6.0, 0.0]]) + pad_mask = torch.tensor([[True, False]]) + with torch.no_grad(): + out = model({"labs": {"value": value, "time": time, "pad_mask": pad_mask}}) + self.assertEqual(out["mask"].tolist(), [[1.0, 0.0]]) + self.assertAlmostEqual(out["time"][0, 0].item(), 6.0) + self.assertTrue(torch.allclose(out["sequence"][0, 1], torch.zeros(8), atol=1e-6)) + + def test_text_encoder_skips_padded_note_slots(self): + from types import SimpleNamespace + + from pyhealth.models.unified_embedding import UnifiedMultimodalEmbeddingModel + from pyhealth.processors import TupleTimeTextProcessor + + class CountingEnc(nn.Module): + def __init__(self): + super().__init__() + self.calls = 0 + self.lin = nn.Linear(4, 8) + self.config = type("C", (), {"hidden_size": 8})() + + def forward(self, input_ids, attention_mask=None): + self.calls += 1 + h = self.lin(input_ids.float()) + return type("O", (), {"last_hidden_state": h.unsqueeze(1)})() + + proc = TupleTimeTextProcessor() + enc = CountingEnc() + pre = SimpleNamespace(transformer=enc, fc=nn.Identity(), embedding_dim=8) + model = UnifiedMultimodalEmbeddingModel( + {"notes": proc}, embedding_dim=8, field_embeddings={"notes": pre} + ) + model.eval() + with torch.no_grad(): + out = model( + { + "notes": { + "value": torch.ones(1, 3, 4, dtype=torch.long), + "time": torch.tensor([[2.0, 0.0, 1.0]]), + "pad_mask": torch.tensor([[True, False, True]]), + } + } + ) + # One batched call over the 2 valid rows; the padded slot sorts last. + self.assertEqual(enc.calls, 1) + self.assertEqual(out["sequence"].shape, (1, 3, 8)) + self.assertEqual(out["mask"].tolist(), [[1.0, 1.0, 0.0]]) + self.assertEqual(out["time"].tolist(), [[1.0, 2.0, 0.0]]) + + def test_unified_heads_thread_pad_mask(self): + import inspect + + from pyhealth.models.ehrmamba import EHRMamba + from pyhealth.models.jamba_ehr import JambaEHR + from pyhealth.models.rnn import RNN + from pyhealth.models.transformer import Transformer + + for cls in (RNN, Transformer, EHRMamba, JambaEHR): + src = inspect.getsource(cls._build_unified_inputs) + self.assertIn("PAD_MASK_SUFFIX", src, msg=cls.__name__) + self.assertIn("pad_mask", src, msg=cls.__name__) + + +class TestP1TextTupleCollate(unittest.TestCase): + """Ragged text tuples collate through the processor's collate(). + + Regression tests: tokenized note fields collate as one 5-tuple per + sample ``(value, mask, token_type_ids, time, tag)`` with a ragged note + count, which the 2-tuple-only batch branch kept as a nested list. Every + unified backbone then crashed in ``_build_unified_inputs`` indexing + into per-sample tuples (``'tuple' object has no attribute 'to'``). + """ + + @staticmethod + def _collate(batch): + # get_dataloader batches a field with its processor's collate() + from pyhealth.datasets.utils import collate_fn_dict_with_padding + from pyhealth.processors import TupleTimeTextProcessor + + collate = TupleTimeTextProcessor().collate + return collate_fn_dict_with_padding(batch, collators={"notes": collate}) + + @staticmethod + def _note(n, l, t0): + return ( + torch.ones(n, l, dtype=torch.long), + torch.ones(n, l, dtype=torch.long), + torch.zeros(n, l, dtype=torch.long), + torch.tensor([t0 + i for i in range(n)], dtype=torch.float), + "note", + ) + + def test_ragged_text_tuples_stack_with_pad_mask(self): + from pyhealth.datasets.utils import PAD_MASK_SUFFIX + + batch = [ + {"notes": self._note(2, 4, 0.0)}, + {"notes": self._note(1, 4, 5.0)}, + {"notes": self._note(0, 1, 0.0)}, + ] + collated = self._collate(batch) + value, mask, type_ids, time, tag = collated["notes"] + self.assertEqual(tuple(value.shape), (3, 2, 4)) + self.assertEqual(tuple(mask.shape), (3, 2, 4)) + self.assertEqual(tuple(type_ids.shape), (3, 2, 4)) + self.assertEqual(tuple(time.shape), (3, 2)) + self.assertEqual(tag, ["note", "note", "note"]) + self.assertEqual( + collated[f"notes{PAD_MASK_SUFFIX}"].tolist(), + [[True, True], [True, False], [False, False]], + ) + + def test_build_unified_inputs_consumes_stacked_text(self): + from types import SimpleNamespace + + from pyhealth.datasets.utils import collate_fn_dict_with_padding + from pyhealth.models.rnn import RNN + from pyhealth.processors import StageNetTensorProcessor, TupleTimeTextProcessor + + notes_proc = TupleTimeTextProcessor( + tokenizer_model="emilyalsentzer/Bio_ClinicalBERT", + type_tag="note", + max_length=8, + ) + labs_proc = StageNetTensorProcessor() + labs_proc.fit([{"labs": ([0.0], [[1.0, 2.0]])}], "labs") + dataset = SimpleNamespace( + input_processors={"notes": notes_proc, "labs": labs_proc} + ) + batch = collate_fn_dict_with_padding( + [ + { + "notes": notes_proc.process( + (["note one", "second note"], [0.0, 1.0]) + ), + "labs": labs_proc.process(([0.0], [[1.0, 2.0]])), + }, + { + "notes": notes_proc.process(([], [])), + "labs": labs_proc.process(([0.0, 1.0], [[3.0, 4.0], [5.0, 6.0]])), + }, + ], + collators={"notes": notes_proc.collate}, + ) + stub = SimpleNamespace( + feature_keys=["notes", "labs"], dataset=dataset, device="cpu" + ) + inputs = RNN._build_unified_inputs(stub, batch) + # Tokenizer pads to the longest note in the batch (4 tokens here). + self.assertEqual(tuple(inputs["notes"]["value"].shape), (2, 2, 4)) + self.assertEqual(tuple(inputs["notes"]["mask"].shape), (2, 2, 4)) + self.assertEqual(tuple(inputs["notes"]["time"].shape), (2, 2)) + self.assertEqual( + inputs["notes"]["pad_mask"].tolist(), [[True, True], [False, False]] + ) + self.assertEqual(tuple(inputs["labs"]["value"].shape), (2, 2, 2)) + + def test_two_tuple_contract_unchanged(self): + from pyhealth.datasets.utils import PAD_MASK_SUFFIX, collate_fn_dict_with_padding + + same = [ + {"x": (torch.tensor([1.0, 2.0]), torch.tensor([[1.0], [2.0]]))}, + {"x": (torch.tensor([3.0, 4.0]), torch.tensor([[3.0], [4.0]]))}, + ] + collated = collate_fn_dict_with_padding(same) + self.assertEqual(tuple(collated["x"][0].shape), (2, 2)) + self.assertEqual(tuple(collated["x"][1].shape), (2, 2, 1)) + self.assertNotIn(f"x{PAD_MASK_SUFFIX}", collated) + + ragged = [ + {"x": (torch.tensor([1.0, 2.0]), torch.tensor([[1.0], [2.0]]))}, + {"x": (torch.tensor([3.0]), torch.tensor([[3.0]]))}, + ] + collated = collate_fn_dict_with_padding(ragged) + self.assertEqual(tuple(collated["x"][1].shape), (2, 2, 1)) + self.assertEqual( + collated[f"x{PAD_MASK_SUFFIX}"].tolist(), [[True, True], [True, False]] + ) + + +if __name__ == "__main__": + unittest.main() 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_p2_mlp_pad_mask.py b/tests/core/test_p2_mlp_pad_mask.py new file mode 100644 index 0000000000..6f96a97ab1 --- /dev/null +++ b/tests/core/test_p2_mlp_pad_mask.py @@ -0,0 +1,85 @@ +"""Unified MLP threads collate pad_mask like the other heads.""" + +from __future__ import annotations + +import unittest +from types import SimpleNamespace + +import torch + + +class TestP2MlpPadMask(unittest.TestCase): + def test_mlp_threads_pad_mask_into_unified_inputs(self): + from pyhealth.datasets.utils import PAD_MASK_SUFFIX, collate_fn_dict_with_padding + from pyhealth.models.mlp import MLP + from pyhealth.processors.stagenet_processor import StageNetTensorProcessor + + batch = [ + {"labs": (torch.tensor([6.0, 12.0, 24.0]), torch.ones(3, 2))}, + {"labs": (torch.tensor([6.0]), torch.ones(1, 2))}, + ] + collated = collate_fn_dict_with_padding(batch) + self.assertIn(f"labs{PAD_MASK_SUFFIX}", collated) + + host = SimpleNamespace( + feature_keys=["labs"], + device="cpu", + dataset=SimpleNamespace( + input_processors={"labs": StageNetTensorProcessor()} + ), + ) + inputs = MLP._build_unified_inputs(host, collated) + self.assertEqual( + inputs["labs"]["pad_mask"].tolist(), + [[True, True, True], [True, False, False]], + ) + + def test_unified_forward_ignores_padded_slots(self): + from pyhealth.datasets import create_sample_dataset, get_dataloader + from pyhealth.models.mlp import MLP + from pyhealth.models.unified_embedding import UnifiedMultimodalEmbeddingModel + + samples = [ + { + "patient_id": "patient-0", + "visit_id": "visit-0", + "codes": ([0.0, 2.0], ["A", "B"]), + "labs": ([0.0, 2.0], [[1.0, 2.0], [3.0, 4.0]]), + "label": 1, + }, + { + "patient_id": "patient-1", + "visit_id": "visit-0", + "codes": ([0.0], ["C"]), + "labs": ([0.0], [[5.0, 6.0]]), + "label": 0, + }, + ] + dataset = create_sample_dataset( + samples=samples, + input_schema={"codes": "stagenet", "labs": "stagenet_tensor"}, + output_schema={"label": "binary"}, + dataset_name="test_mlp_unified", + ) + unified = UnifiedMultimodalEmbeddingModel( + dataset.input_processors, embedding_dim=8 + ) + model = MLP( + dataset=dataset, embedding_dim=8, hidden_dim=8, + unified_embedding=unified, + ) + batch = next(iter(get_dataloader(dataset, batch_size=2, shuffle=False))) + out = model(**batch) + self.assertTrue(torch.isfinite(out["loss"])) + out["loss"].backward() + self.assertTrue( + any( + p.grad is not None + for p in model.parameters() + if p.requires_grad + ) + ) + + +if __name__ == "__main__": + unittest.main() 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() 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() diff --git a/tests/core/test_rnn_unified.py b/tests/core/test_rnn_unified.py new file mode 100644 index 0000000000..5a7ce25d5e --- /dev/null +++ b/tests/core/test_rnn_unified.py @@ -0,0 +1,75 @@ +"""RNN unified mode over a tiny two-field temporal dataset.""" + +import unittest + +import torch + +from pyhealth.datasets import create_sample_dataset, get_dataloader +from pyhealth.models import RNN +from pyhealth.models.unified_embedding import UnifiedMultimodalEmbeddingModel + + +def _dataset(): + samples = [ + { + "patient_id": "patient-0", + "visit_id": "visit-0", + "codes": ([0.0, 2.0], ["A", "B"]), + "labs": ([0.0, 2.0], [[1.0, 2.0], [3.0, 4.0]]), + "label": 1, + }, + { + "patient_id": "patient-1", + "visit_id": "visit-0", + "codes": ([0.0], ["C"]), + "labs": ([0.0], [[5.0, 6.0]]), + "label": 0, + }, + ] + return create_sample_dataset( + samples=samples, + input_schema={"codes": "stagenet", "labs": "stagenet_tensor"}, + output_schema={"label": "binary"}, + dataset_name="test_rnn_unified", + ) + + +class TestRNNUnified(unittest.TestCase): + def test_unified_forward_backward_loss_finite(self): + dataset = _dataset() + unified = UnifiedMultimodalEmbeddingModel( + dataset.input_processors, embedding_dim=8 + ) + model = RNN( + dataset=dataset, embedding_dim=8, hidden_dim=8, + unified_embedding=unified, + ) + batch = next(iter(get_dataloader(dataset, batch_size=2, shuffle=False))) + out = model(**batch) + self.assertTrue(torch.isfinite(out["loss"])) + out["loss"].backward() + self.assertTrue( + any( + p.grad is not None + for p in model.parameters() + if p.requires_grad + ) + ) + + def test_per_field_mode_unchanged(self): + dataset = _dataset() + model = RNN(dataset=dataset, embedding_dim=8, hidden_dim=8) + self.assertFalse(model._use_unified) + batch = next(iter(get_dataloader(dataset, batch_size=2, shuffle=False))) + out = model(**batch) + self.assertTrue(torch.isfinite(out["loss"])) + + def test_rnn_v2_untouched(self): + from pyhealth.models.rnn import RNN_V2 + import inspect + + self.assertNotIn("unified_embedding", inspect.signature(RNN_V2.__init__).parameters) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/core/test_stagenet_processor.py b/tests/core/test_stagenet_processor.py index 6e217dc7d7..25dd3feb9c 100644 --- a/tests/core/test_stagenet_processor.py +++ b/tests/core/test_stagenet_processor.py @@ -199,9 +199,8 @@ def test_empty_codes_flat(self): time, values = processor.process((None, [])) - # Should return single padding token - self.assertEqual(values.shape, (1,)) - self.assertEqual(values[0].item(), processor.code_vocab[""]) + # Empty codes are zero events, not a fake pad token + self.assertEqual(values.shape, (0,)) def test_empty_codes_nested(self): """Test processing empty nested codes.""" @@ -211,10 +210,8 @@ def test_empty_codes_nested(self): time, values = processor.process((None, [])) - # Should return single row of padding tokens - self.assertEqual(values.shape, (1, 2)) - self.assertEqual(values[0, 0].item(), processor.code_vocab[""]) - self.assertEqual(values[0, 1].item(), processor.code_vocab[""]) + # Empty nested codes are zero events + self.assertEqual(values.shape, (0, 2)) def test_vocab_size_method(self): """Test vocab_size() returns correct size.""" @@ -370,6 +367,16 @@ def test_no_time_tensor(self): self.assertIsNone(time) self.assertEqual(values.shape, (2, 2)) + def test_empty_values_returns_zero_length(self): + """Empty values are zero events, not imputed rows.""" + processor = StageNetTensorProcessor() + samples = [{"data": ([0.0], [[1.0, 2.0]])}] + processor.fit(samples, "data") + + time, values = processor.process(([0.0], [])) + self.assertEqual(values.shape, (0, 2)) + self.assertEqual(time.shape, (0,)) + def test_repr_tensor(self): """Test string representation for tensor processor.""" processor = StageNetTensorProcessor() @@ -461,5 +468,103 @@ def test_vocab_size_for_embedding_layer(self): self.assertLess(max_idx, vocab_size) +class TestStageNetTensorProcessorForwardFill(unittest.TestCase): + """Tests for the ``forward_fill`` switch (observation masks). + + Regression tests: the multimodal MIMIC-IV tasks declare + ``"labs_mask": ("stagenet_tensor", {"forward_fill": False})``, which + raised ``TypeError`` before ``StageNetTensorProcessor`` accepted the + kwarg, and would silently corrupt masks if the flag were ignored. + """ + + def test_spec_instantiation_with_forward_fill_kwarg(self): + """The task schema spec instantiates through the processor registry.""" + from pyhealth.processors import get_processor + + default = get_processor("stagenet_tensor")() + self.assertTrue(default.forward_fill) + no_fill = get_processor("stagenet_tensor")(forward_fill=False) + self.assertFalse(no_fill.forward_fill) + + def test_default_still_forward_fills(self): + """Default construction keeps the historical forward-fill behaviour.""" + processor = StageNetTensorProcessor() + samples = [{"data": ([0.0], [1.0, 2.0])}] + processor.fit(samples, "data") + _, values = processor.process(([0.0, 1.0, 2.0], [1.0, None, 3.0])) + self.assertEqual(values.tolist(), [1.0, 1.0, 3.0]) + + def test_no_forward_fill_keeps_missing_as_zero(self): + """With ``forward_fill=False`` missing values never propagate.""" + processor = StageNetTensorProcessor(forward_fill=False) + samples = [{"data": ([0.0], [[1.0, 2.0]])}] + processor.fit(samples, "data") + _, values = processor.process( + ([0.0, 1.0, 2.0], [[1.0, None, 3.0], [None, 5.0, 6.0], [7.0, 8.0, None]]) + ) + self.assertEqual( + values.tolist(), + [[1.0, 0.0, 3.0], [0.0, 5.0, 6.0], [7.0, 8.0, 0.0]], + ) + + def test_no_forward_fill_preserves_observation_mask(self): + """A mask with gaps round-trips instead of filling gaps with 1s.""" + observed = [[True, None], [None, True], [True, True]] + filled = StageNetTensorProcessor() # default: forward_fill=True + samples = [{"data": ([0.0], observed)}] + filled.fit(samples, "data") + _, filled_values = filled.process(([0.0, 1.0, 2.0], observed)) + # Forward-filling the mask corrupts it: the gap at [1, 0] becomes + # the earlier observed True. + self.assertEqual(filled_values.tolist(), [[1.0, 0.0], [1.0, 1.0], [1.0, 1.0]]) + + masked = StageNetTensorProcessor(forward_fill=False) + masked.fit(samples, "data") + _, masked_values = masked.process(([0.0, 1.0, 2.0], observed)) + self.assertEqual(masked_values.tolist(), [[1.0, 0.0], [0.0, 1.0], [1.0, 1.0]]) + + +class TestStageNetFitSkipsEmptySamples(unittest.TestCase): + """``fit`` must scan past samples with no structural information. + + Regression tests: real task streams start with whatever patient sorts + first, and empty-lab stays are legitimate records (the series emits no + placeholder rows). The old ``fit`` stopped after the first non-None + sample even when it was empty, leaving ``_size``/``_is_nested`` unset; + downstream ``value_dim()`` then reported 1 and the unified numeric + encoder was built with the wrong input width. + """ + + def test_tensor_fit_skips_empty_first_sample(self): + processor = StageNetTensorProcessor() + processor.fit( + [ + {"data": ([], [])}, + {"data": ([0.0, 1.0], [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])}, + ], + "data", + ) + self.assertTrue(processor._is_nested) + self.assertEqual(processor.size(), 3) + self.assertEqual(processor.value_dim(), 3) + + def test_tensor_fit_all_empty_stays_unfitted(self): + processor = StageNetTensorProcessor() + processor.fit([{"data": ([], [])}, {"data": ([], [])}], "data") + self.assertIsNone(processor._size) + self.assertEqual(processor.value_dim(), 1) + + def test_code_fit_skips_empty_first_sample(self): + processor = StageNetProcessor() + processor.fit( + [ + {"data": ([], [])}, + {"data": ([0.0], [["A", "B"], ["C"]])}, + ], + "data", + ) + self.assertTrue(processor._is_nested) + + if __name__ == "__main__": unittest.main() diff --git a/tests/core/test_time_image_processor.py b/tests/core/test_time_image_processor.py index 51467aa5ce..52cc1e6539 100644 --- a/tests/core/test_time_image_processor.py +++ b/tests/core/test_time_image_processor.py @@ -207,11 +207,21 @@ def test_process_mismatched_lengths_raises(self): (self.rgb_paths[:3], self.times[:2]) ) - def test_process_empty_paths_raises(self): - """ValueError for empty image list.""" - proc = TimeImageProcessor() - with self.assertRaises(ValueError): - proc.process(([], [])) + def test_process_empty_paths_returns_zero_length(self): + """Empty image list is zero events, not an error.""" + proc = TimeImageProcessor(image_size=32) + images, timestamps, tag = proc.process(([], [])) + self.assertEqual(images.shape, (0, 3, 32, 32)) + self.assertEqual(timestamps.shape, (0,)) + self.assertEqual(tag, "image") + + def test_padding_sentinel_returns_zero_tensor(self): + """Sentinel paths decode to zero tensors without disk access.""" + proc = TimeImageProcessor(image_size=32, padding="MISSING") + images, timestamps, tag = proc.process((["MISSING"], [1.0])) + self.assertEqual(images.shape, (1, 3, 32, 32)) + self.assertTrue(bool((images == 0).all())) + self.assertEqual(tag, "image") def test_process_invalid_path_raises(self): """FileNotFoundError for nonexistent image.""" diff --git a/tests/core/test_trainer_amp.py b/tests/core/test_trainer_amp.py new file mode 100644 index 0000000000..ce77f15c6c --- /dev/null +++ b/tests/core/test_trainer_amp.py @@ -0,0 +1,243 @@ +"""Trainer mixed precision and gradient accumulation. + +``amp_dtype`` used to fall through to fp16 for any unknown spelling, and the +autocast context was hardcoded to CUDA. Accumulation lets small synthetic +batches simulate a larger effective batch size. + +With ``use_amp=False`` the step matches ``upstream/master`` exactly: clip only +when ``max_grad_norm`` is set, no unconditional grad-norm pass, no skipping. +``accumulation_steps=1`` is bit-identical in effect to upstream. + +Repro:: + + PYTEST_DISABLE_PLUGIN_AUTOLOAD=1 PYTHONPATH=. \\ + python -m pytest tests/core/test_trainer_amp.py -q +""" + +from __future__ import annotations + +import unittest +from unittest import mock + +import torch +from torch import nn +from torch.utils.data import DataLoader, TensorDataset + + +class _TinyModel(nn.Module): + mode = None + + def __init__(self): + super().__init__() + self.fc = nn.Linear(4, 1) + + def forward(self, x, y): + logit = self.fc(x).squeeze(-1) + loss = nn.functional.binary_cross_entropy_with_logits(logit, y) + return {"loss": loss} + + +def _loader(n=16, batch_size=4, seed=0): + torch.manual_seed(seed) + xs = torch.randn(n, 4) + ys = (xs.sum(dim=1) > 0).float() + ds = TensorDataset(xs, ys) + + def collate(batch): + xs_b, ys_b = zip(*batch) + return {"x": torch.stack(list(xs_b)), "y": torch.stack(list(ys_b))} + + return DataLoader(ds, batch_size=batch_size, shuffle=False, collate_fn=collate) + + +def _upstream_reference_train(model, loader, epochs, max_grad_norm, lr=1e-3): + """The upstream/master batch loop, copied for equivalence checking.""" + no_decay = ["bias", "LayerNorm.bias", "LayerNorm.weight"] + param = list(model.named_parameters()) + optimizer = torch.optim.Adam( + [ + { + "params": [p for n, p in param if not any(nd in n for nd in no_decay)], + "weight_decay": 0.0, + }, + { + "params": [p for n, p in param if any(nd in n for nd in no_decay)], + "weight_decay": 0.0, + }, + ], + lr=lr, + ) + data_iterator = iter(loader) + steps_per_epoch = len(loader) + for _ in range(epochs): + model.zero_grad() + model.train() + for _ in range(steps_per_epoch): + try: + data = next(data_iterator) + except StopIteration: + data_iterator = iter(loader) + data = next(data_iterator) + output = model(**data) + loss = output["loss"] + loss.backward() + if max_grad_norm is not None: + torch.nn.utils.clip_grad_norm_(model.parameters(), max_grad_norm) + optimizer.step() + optimizer.zero_grad() + + +class TestTrainerAmp(unittest.TestCase): + def test_known_spellings_map_to_the_named_dtype(self): + from pyhealth.trainer import resolve_amp_dtype + + self.assertIs(resolve_amp_dtype("bf16"), torch.bfloat16) + self.assertIs(resolve_amp_dtype("bfloat16"), torch.bfloat16) + self.assertIs(resolve_amp_dtype("fp16"), torch.float16) + self.assertIs(resolve_amp_dtype("float16"), torch.float16) + + def test_unknown_spelling_raises(self): + from pyhealth.trainer import resolve_amp_dtype + + for bad in ("bfloat_16", "f16", "int8", ""): + with self.assertRaises(ValueError): + resolve_amp_dtype(bad) + + def test_train_rejects_unknown_amp_dtype(self): + from pyhealth.trainer import Trainer + + trainer = Trainer(_TinyModel(), enable_logging=False, device="cpu") + with self.assertRaises(ValueError): + trainer.train(_loader(), epochs=1, amp_dtype="f16") + + def test_invalid_accumulation_steps_raises(self): + from pyhealth.trainer import Trainer + + trainer = Trainer(_TinyModel(), enable_logging=False, device="cpu") + for bad in (0, -2): + with self.assertRaises(ValueError): + trainer.train(_loader(), epochs=1, accumulation_steps=bad) + + def test_autocast_device_follows_the_trainer_device(self): + from pyhealth.trainer import autocast_device_type + + self.assertEqual(autocast_device_type("cuda:0"), "cuda") + self.assertEqual(autocast_device_type("cpu"), "cpu") + self.assertEqual(autocast_device_type("mps"), "mps") + self.assertEqual(autocast_device_type("xpu"), "cpu") + + def test_default_path_clips_only_when_configured(self): + from pyhealth.trainer import Trainer + + with mock.patch( + "torch.nn.utils.clip_grad_norm_", wraps=torch.nn.utils.clip_grad_norm_ + ) as clip: + trainer = Trainer(_TinyModel(), enable_logging=False, device="cpu") + trainer.train(_loader(), epochs=1, max_grad_norm=None) + clip.assert_not_called() + with mock.patch( + "torch.nn.utils.clip_grad_norm_", wraps=torch.nn.utils.clip_grad_norm_ + ) as clip: + trainer = Trainer(_TinyModel(), enable_logging=False, device="cpu") + trainer.train(_loader(), epochs=1, max_grad_norm=1.0) + self.assertEqual(clip.call_count, len(_loader())) + + def test_accumulation_one_matches_upstream_bit_identical(self): + from pyhealth.trainer import Trainer + + torch.manual_seed(123) + model_new = _TinyModel() + torch.manual_seed(123) + model_ref = _TinyModel() + loader = _loader() + Trainer(model_new, enable_logging=False, device="cpu").train( + loader, epochs=2, accumulation_steps=1, max_grad_norm=1.0 + ) + _upstream_reference_train(model_ref, _loader(), 2, max_grad_norm=1.0) + for p_new, p_ref in zip( + model_new.parameters(), model_ref.parameters(), strict=True + ): + self.assertTrue(torch.equal(p_new, p_ref)) + + def test_accumulated_halves_match_full_batch(self): + from pyhealth.trainer import Trainer + + torch.manual_seed(7) + model_full = _TinyModel() + torch.manual_seed(7) + model_acc = _TinyModel() + Trainer(model_full, enable_logging=False, device="cpu").train( + _loader(n=8, batch_size=8), + epochs=1, + accumulation_steps=1, + optimizer_class=torch.optim.SGD, + optimizer_params={"lr": 0.1}, + ) + Trainer(model_acc, enable_logging=False, device="cpu").train( + _loader(n=8, batch_size=4), + epochs=1, + accumulation_steps=2, + optimizer_class=torch.optim.SGD, + optimizer_params={"lr": 0.1}, + ) + for p_full, p_acc in zip( + model_full.parameters(), model_acc.parameters(), strict=True + ): + self.assertTrue(torch.allclose(p_full, p_acc, atol=1e-6)) + + def test_trailing_partial_window_still_steps(self): + from pyhealth.trainer import Trainer + + counts = [] + + class CountingSGD(torch.optim.SGD): + def step(self, *args, **kwargs): + counts.append(1) + return super().step(*args, **kwargs) + + trainer = Trainer(_TinyModel(), enable_logging=False, device="cpu") + trainer.train( + _loader(n=12, batch_size=4), + epochs=1, + steps_per_epoch=3, + accumulation_steps=2, + optimizer_class=CountingSGD, + optimizer_params={"lr": 0.1}, + ) + # batches 1-2 form one update, batch 3 is flushed at epoch end + self.assertEqual(len(counts), 2) + + def test_steps_per_epoch_shorter_than_loader(self): + from pyhealth.trainer import Trainer + + trainer = Trainer(_TinyModel(), enable_logging=False, device="cpu") + before = [p.detach().clone() for p in trainer.model.parameters()] + trainer.train(_loader(n=16, batch_size=4), epochs=2, steps_per_epoch=2) + after = [p.detach().clone() for p in trainer.model.parameters()] + self.assertTrue(any(not torch.equal(b, a) for b, a in zip(before, after))) + + def test_accumulation_trains_on_cpu(self): + from pyhealth.trainer import Trainer + + for accumulation_steps in (1, 2): + trainer = Trainer(_TinyModel(), enable_logging=False, device="cpu") + before = [p.detach().clone() for p in trainer.model.parameters()] + trainer.train( + _loader(), epochs=1, accumulation_steps=accumulation_steps + ) + after = [p.detach().clone() for p in trainer.model.parameters()] + self.assertTrue( + any(not torch.equal(b, a) for b, a in zip(before, after)) + ) + + def test_amp_bf16_trains_on_cpu(self): + from pyhealth.trainer import Trainer + + trainer = Trainer(_TinyModel(), enable_logging=False, device="cpu") + trainer.train(_loader(), epochs=1, use_amp=True, amp_dtype="bf16") + + def test_amp_fp16_trains_on_cpu(self): + from pyhealth.trainer import Trainer + + trainer = Trainer(_TinyModel(), enable_logging=False, device="cpu") + trainer.train(_loader(), epochs=1, use_amp=True, amp_dtype="fp16") diff --git a/tests/core/test_transformer_unified.py b/tests/core/test_transformer_unified.py new file mode 100644 index 0000000000..be4ef3a210 --- /dev/null +++ b/tests/core/test_transformer_unified.py @@ -0,0 +1,69 @@ +"""Transformer unified mode over a tiny two-field temporal dataset.""" + +import unittest + +import torch + +from pyhealth.datasets import create_sample_dataset, get_dataloader +from pyhealth.models import Transformer +from pyhealth.models.unified_embedding import UnifiedMultimodalEmbeddingModel + + +def _dataset(): + samples = [ + { + "patient_id": "patient-0", + "visit_id": "visit-0", + "codes": ([0.0, 2.0], ["A", "B"]), + "labs": ([0.0, 2.0], [[1.0, 2.0], [3.0, 4.0]]), + "label": 1, + }, + { + "patient_id": "patient-1", + "visit_id": "visit-0", + "codes": ([0.0], ["C"]), + "labs": ([0.0], [[5.0, 6.0]]), + "label": 0, + }, + ] + return create_sample_dataset( + samples=samples, + input_schema={"codes": "stagenet", "labs": "stagenet_tensor"}, + output_schema={"label": "binary"}, + dataset_name="test_transformer_unified", + ) + + +class TestTransformerUnified(unittest.TestCase): + def test_unified_forward_backward_loss_finite(self): + dataset = _dataset() + unified = UnifiedMultimodalEmbeddingModel( + dataset.input_processors, embedding_dim=8 + ) + model = Transformer( + dataset=dataset, embedding_dim=8, heads=1, num_layers=1, + unified_embedding=unified, + ) + batch = next(iter(get_dataloader(dataset, batch_size=2, shuffle=False))) + out = model(**batch) + self.assertTrue(torch.isfinite(out["loss"])) + out["loss"].backward() + self.assertTrue( + any( + p.grad is not None + for p in model.parameters() + if p.requires_grad + ) + ) + + def test_per_field_mode_unchanged(self): + dataset = _dataset() + model = Transformer(dataset=dataset, embedding_dim=8, heads=1, num_layers=1) + self.assertFalse(model._use_unified) + batch = next(iter(get_dataloader(dataset, batch_size=2, shuffle=False))) + out = model(**batch) + self.assertTrue(torch.isfinite(out["loss"])) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/core/test_tuple_time_text_processor.py b/tests/core/test_tuple_time_text_processor.py index 7a8dfd5b59..539349d083 100644 --- a/tests/core/test_tuple_time_text_processor.py +++ b/tests/core/test_tuple_time_text_processor.py @@ -29,3 +29,69 @@ def test_tuple_time_text_processor(): from pyhealth.processors import get_processor ProcessorClass = get_processor("tuple_time_text") assert ProcessorClass is TupleTimeTextProcessor + + +def test_tuple_time_text_cleans_malformed_entries(): + """Null, blank, and misaligned entries are dropped with their times.""" + from pyhealth.processors import TupleTimeTextProcessor + + processor = TupleTimeTextProcessor() + texts = [" real note ", None, " ", "second note"] + time_diffs = [0.0, 1.0, 2.0, 3.0] + result_texts, time_tensor, tag = processor.process((texts, time_diffs)) + + assert result_texts == ["real note", "second note"] + assert torch.equal(time_tensor, torch.tensor([0.0, 3.0])) + assert tag == "note" + + +def test_tuple_time_text_empty_is_zero_events_with_stub_tokenizer(): + """Tokenizer path returns (0, 1) empties instead of a fake row.""" + from pyhealth.processors import TupleTimeTextProcessor + + processor = TupleTimeTextProcessor() + calls = [] + + def fake_tokenizer(texts, **kwargs): + calls.append((list(texts), kwargs.get("padding"), kwargs.get("max_length"))) + raise AssertionError("tokenizer must not run on zero notes") + + processor.tokenizer = fake_tokenizer + input_ids, attn, token_types, time_tensor, tag = processor.process(([], [])) + + assert calls == [] + assert input_ids.shape == (0, 1) + assert attn.shape == (0, 1) + assert token_types.shape == (0, 1) + assert time_tensor.shape == (0,) + assert tag == "note" + + +def test_tuple_time_text_longest_padding_bounded_by_max_length(): + """Padding follows the longest note in the sample, capped at max_length.""" + from pyhealth.processors import TupleTimeTextProcessor + + processor = TupleTimeTextProcessor(max_length=16) + seen = {} + + def fake_tokenizer(texts, **kwargs): + seen["padding"] = kwargs.get("padding") + seen["max_length"] = kwargs.get("max_length") + width = max(len(t.split()) + 2 for t in texts) + n = len(texts) + return { + "input_ids": torch.ones((n, width), dtype=torch.long), + "attention_mask": torch.ones((n, width), dtype=torch.long), + } + + processor.tokenizer = fake_tokenizer + input_ids, attn, token_types, time_tensor, tag = processor.process( + (["hi", "a much longer note here"], [0.0, 1.0]) + ) + + assert seen["padding"] == "longest" + assert seen["max_length"] == 16 + assert input_ids.shape == (2, 7) + assert attn.shape == (2, 7) + assert token_types.shape == (2, 7) + assert torch.equal(time_tensor, torch.tensor([0.0, 1.0])) diff --git a/tests/core/test_tuple_time_text_tokenizer.py b/tests/core/test_tuple_time_text_tokenizer.py index 3a5eeb5998..1e58aa2f6b 100644 --- a/tests/core/test_tuple_time_text_tokenizer.py +++ b/tests/core/test_tuple_time_text_tokenizer.py @@ -86,18 +86,18 @@ def test_tuple_time_text_processor_with_tokenizer(): input_ids, attention_mask, token_type_ids, time_tensor, tag = result - # Check shapes + # Check shapes: per-sample longest padding bounded by max_length N = 2 # number of sentences - L = 16 # max_length - + assert isinstance(input_ids, torch.Tensor) - assert input_ids.shape == (N, L) - + assert input_ids.shape[0] == N + assert input_ids.shape[1] <= 16 + assert isinstance(attention_mask, torch.Tensor) - assert attention_mask.shape == (N, L) - + assert attention_mask.shape == input_ids.shape + assert isinstance(token_type_ids, torch.Tensor) - assert token_type_ids.shape == (N, L) + assert token_type_ids.shape == input_ids.shape assert isinstance(time_tensor, torch.Tensor) assert time_tensor.shape == (N,) @@ -177,8 +177,9 @@ def test_tuple_in_schema_canonical_form(): assert isinstance(sample["notes"], tuple) assert len(sample["notes"]) == 5 input_ids, mask, type_ids, time, tag = sample["notes"] - assert input_ids.shape == (2, 16) # (N_notes, L) - assert mask.shape == (2, 16) + assert input_ids.shape[0] == 2 + assert input_ids.shape[1] <= 16 + assert mask.shape == input_ids.shape assert time.shape == (2,) assert tag == "note" diff --git a/tests/core/test_unified_cache.py b/tests/core/test_unified_cache.py new file mode 100644 index 0000000000..7c03a15b90 --- /dev/null +++ b/tests/core/test_unified_cache.py @@ -0,0 +1,174 @@ +"""Frozen [CLS] cache keyed on real tokens, with an on/off switch.""" + +from __future__ import annotations + +import builtins +import unittest +from unittest import mock + +import torch +import torch.nn as nn + +from pyhealth.models.unified_embedding import UnifiedMultimodalEmbeddingModel +from pyhealth.processors.stagenet_processor import StageNetTensorProcessor + + +def _numeric_model(**kwargs) -> UnifiedMultimodalEmbeddingModel: + proc = StageNetTensorProcessor() + proc.fit([{"labs": ([0.0], [[1.0] * 10])}], "labs") + kwargs.setdefault("cache_frozen_text", True) + return UnifiedMultimodalEmbeddingModel( + {"labs": proc}, embedding_dim=8, freeze_text_encoder=True, **kwargs + ) + + +class CountingEnc(nn.Module): + def __init__(self): + super().__init__() + self.calls = 0 + self.lin = nn.Linear(1, 8) + self.config = type("C", (), {"hidden_size": 8})() + + def forward(self, input_ids, attention_mask=None): + self.calls += 1 + b, l = input_ids.shape + scale = input_ids[:, :1, None].float() + h = torch.ones(b, l, 8) * scale + return type("O", (), {"last_hidden_state": h})() + + +class TestFrozenTextCache(unittest.TestCase): + def _cached(self, **kwargs): + model = _numeric_model(**kwargs) + enc = CountingEnc() + model.encoders["notes"] = enc + model._frozen_text_fields.add("notes") + return model, enc + + def test_cache_keys_ignore_padding_tokens(self): + model, enc = self._cached() + ids_a = torch.tensor([[1, 2, 3, 0, 0], [1, 2, 3, 9, 9]]) + mask_a = torch.tensor([[1, 1, 1, 0, 0], [1, 1, 1, 0, 0]]) + h1 = model._encode_text_cls("notes", enc, ids_a, mask_a) + self.assertEqual(enc.calls, 1) + h2 = model._encode_text_cls("notes", enc, ids_a, mask_a) + self.assertEqual(enc.calls, 1) + self.assertTrue(torch.equal(h1, h2)) + # Same real tokens under a wider pad width still hits. + ids_b = torch.tensor([[1, 2, 3, 7, 7, 7]]) + mask_b = torch.tensor([[1, 1, 1, 0, 0, 0]]) + h3 = model._encode_text_cls("notes", enc, ids_b, mask_b) + self.assertEqual(enc.calls, 1) + self.assertEqual(h1.shape[0], 2) + self.assertEqual(h3.shape[0], 1) + self.assertTrue(torch.equal(h3[0], h1[0])) + + def test_switch_off_runs_encoder_every_forward(self): + model, enc = self._cached(cache_frozen_text=False) + ids_a = torch.tensor([[1, 2, 3, 0, 0], [1, 2, 3, 9, 9]]) + mask_a = torch.tensor([[1, 1, 1, 0, 0], [1, 1, 1, 0, 0]]) + model._encode_text_cls("notes", enc, ids_a, mask_a) + model._encode_text_cls("notes", enc, ids_a, mask_a) + self.assertEqual(enc.calls, 2) + self.assertEqual(model._frozen_text_cache, {}) + + def test_unfrozen_field_never_caches(self): + model = _numeric_model() + enc = CountingEnc() + model.encoders["notes"] = enc + # Deliberately NOT added to _frozen_text_fields: trainable encoder. + ids_a = torch.tensor([[1, 2, 3]]) + h1 = model._encode_text_cls("notes", enc, ids_a, None) + h2 = model._encode_text_cls("notes", enc, ids_a, None) + self.assertEqual(enc.calls, 2) + self.assertTrue(torch.equal(h1, h2)) + + def test_full_cache_encodes_each_miss_once(self): + model, enc = self._cached(max_frozen_text_cache=1) + ids = torch.tensor([[1, 2, 3], [4, 5, 6]]) + h1 = model._encode_text_cls("notes", enc, ids, None) + # One batched encoder call serves both misses; only the first fits. + self.assertEqual(enc.calls, 1) + self.assertEqual(h1.shape, (2, 8)) + self.assertEqual( + sum(len(c) for c in model._frozen_text_cache.values()), 1 + ) + h2 = model._encode_text_cls("notes", enc, ids, None) + # The cached row hits; the overflow row re-encodes exactly once. + self.assertEqual(enc.calls, 2) + self.assertTrue(torch.equal(h1, h2)) + + def test_counters_track_hits_and_misses(self): + model, enc = self._cached() + ids = torch.tensor([[1, 2, 3], [4, 5, 6]]) + model._encode_text_cls("notes", enc, ids, None) + self.assertEqual( + model.frozen_text_cache_stats, + {"hits": 0, "misses": 2, "size": 2}, + ) + model._encode_text_cls("notes", enc, ids, None) + self.assertEqual( + model.frozen_text_cache_stats, + {"hits": 2, "misses": 2, "size": 2}, + ) + model.reset_frozen_text_cache_stats() + self.assertEqual( + model.frozen_text_cache_stats, + {"hits": 0, "misses": 0, "size": 2}, + ) + + def test_shuffled_row_order_still_hits(self): + model, enc = self._cached() + ids = torch.tensor([[1, 2, 3], [4, 5, 6]]) + h1 = model._encode_text_cls("notes", enc, ids, None) + calls_after_first = enc.calls + h2 = model._encode_text_cls("notes", enc, ids.flip(0), None) + self.assertEqual(enc.calls, calls_after_first) + self.assertTrue(torch.equal(h2[0], h1[1])) + self.assertTrue(torch.equal(h2[1], h1[0])) + + def test_none_cap_is_uncapped(self): + model, enc = self._cached(max_frozen_text_cache=None) + ids = torch.tensor([[1], [2], [3]]) + model._encode_text_cls("notes", enc, ids, None) + self.assertEqual(model.frozen_text_cache_size, 3) + + def test_zero_cap_is_uncapped(self): + model, enc = self._cached(max_frozen_text_cache=0) + ids = torch.tensor([[1], [2]]) + model._encode_text_cls("notes", enc, ids, None) + self.assertEqual(model.frozen_text_cache_size, 2) + + def test_default_cap_is_one_million(self): + model, _ = self._cached() + self.assertEqual(model.max_frozen_text_cache, 1_000_000) + + def test_empty_rows_return_zeros_without_encoding(self): + model, enc = self._cached() + out = model._encode_text_cls( + "notes", enc, torch.zeros(0, 4, dtype=torch.long), None + ) + self.assertEqual(out.shape, (0, 8)) + self.assertEqual(enc.calls, 0) + + def test_hash_collision_does_not_return_wrong_embedding(self): + # Keys use Python hash(); a collision must not silently return the + # wrong [CLS]. The key carries the real-token length as a cheap + # guard, so two sequences with the same hash but different lengths + # still miss. Simulate a total collision by forcing hash() to 42. + model, enc = self._cached() + ids1 = torch.tensor([[1, 2, 3]]) + mask1 = torch.tensor([[1, 1, 1]]) + ids2 = torch.tensor([[9, 8]]) + mask2 = torch.tensor([[1, 1]]) + with mock.patch.object(builtins, "hash", return_value=42): + h1 = model._encode_text_cls("notes", enc, ids1, mask1) + h2 = model._encode_text_cls("notes", enc, ids2, mask2) + # Different first tokens -> different [CLS]; a collision would + # have returned h1 for both rows. + self.assertFalse(torch.equal(h1, h2)) + self.assertEqual(model.frozen_text_cache_size, 2) + + +if __name__ == "__main__": + unittest.main() 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() diff --git a/tests/core/test_unified_embedding.py b/tests/core/test_unified_embedding.py index 1b34c0d5ac..4c1033b005 100644 --- a/tests/core/test_unified_embedding.py +++ b/tests/core/test_unified_embedding.py @@ -16,14 +16,27 @@ def test_dim_two_is_finite(self): self.assertTrue(torch.isfinite(result).all()) def test_standard_dimension_values_are_unchanged(self): + # Wavelengths run 1h..24h here; the old t/720 formulation wrapped + # every frequency every 30 days, aliasing later stays onto earlier ones. embedding = SinusoidalTimeEmbedding(dim=6, max_hours=24.0) time = torch.tensor([6.0]) - frequencies = torch.tensor([1.0, 0.01, 0.0001]) - arguments = time.unsqueeze(-1) / 24.0 * 2 * math.pi * frequencies + periods = torch.exp(torch.linspace(math.log(1.0), math.log(24.0), 3)) + arguments = time.unsqueeze(-1) * (2 * math.pi / periods) expected = torch.cat([arguments.sin(), arguments.cos()], dim=-1) self.assertTrue(torch.allclose(embedding(time), expected)) + def test_long_span_stays_monotonic_in_phase(self): + embedding = SinusoidalTimeEmbedding(dim=6) + early = embedding(torch.tensor([6.0])) + late = embedding(torch.tensor([9606.0])) + + self.assertFalse(torch.allclose(early, late)) + + def test_invalid_span_raises(self): + with self.assertRaises(ValueError): + SinusoidalTimeEmbedding(dim=6, max_hours=1.0, min_hours=24.0) + if __name__ == "__main__": unittest.main() diff --git a/tests/core/test_unified_empty_batch.py b/tests/core/test_unified_empty_batch.py new file mode 100644 index 0000000000..826cc77cb3 --- /dev/null +++ b/tests/core/test_unified_empty_batch.py @@ -0,0 +1,60 @@ +"""Zero-slot text/image batches must not hit the ambiguous -1 reshape.""" + +import unittest + +import torch +import torch.nn as nn +from types import SimpleNamespace + +from pyhealth.processors import TimeImageProcessor, TupleTimeTextProcessor +from pyhealth.models.unified_embedding import UnifiedMultimodalEmbeddingModel + + +class TinyEnc(nn.Module): + def __init__(self): + super().__init__() + self.config = type("C", (), {"hidden_size": 8})() + + def forward(self, input_ids, attention_mask=None): + return type( + "O", (), {"last_hidden_state": torch.zeros(input_ids.shape[0], 4, 8)} + )() + + +class TestEmptyBatchReshape(unittest.TestCase): + def test_empty_note_slots_return_zero_length(self): + proc = TupleTimeTextProcessor() + pre = SimpleNamespace( + transformer=TinyEnc(), fc=nn.Identity(), embedding_dim=8 + ) + model = UnifiedMultimodalEmbeddingModel( + {"notes": proc}, embedding_dim=8, field_embeddings={"notes": pre} + ) + out = model( + { + "notes": { + "value": torch.zeros(1, 0, 4, dtype=torch.long), + "time": torch.zeros(1, 0), + } + } + ) + self.assertEqual(out["sequence"].shape, (1, 0, 8)) + + def test_empty_image_slots_return_zero_length(self): + proc = TimeImageProcessor(image_size=16) + model = UnifiedMultimodalEmbeddingModel( + {"cxr": proc}, embedding_dim=8, image_size=16, patch_size=8 + ) + out = model( + { + "cxr": { + "value": torch.zeros(1, 0, 3, 16, 16), + "time": torch.zeros(1, 0), + } + } + ) + self.assertEqual(out["sequence"].shape, (1, 0, 8)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/core/test_unified_field_reuse.py b/tests/core/test_unified_field_reuse.py new file mode 100644 index 0000000000..e32f3369d1 --- /dev/null +++ b/tests/core/test_unified_field_reuse.py @@ -0,0 +1,107 @@ +"""Field-embedding reuse and patch image encoder for the unified model.""" + +import unittest +from types import SimpleNamespace + +import torch +import torch.nn as nn + +from pyhealth.processors import ( + StageNetProcessor, + StageNetTensorProcessor, + TimeImageProcessor, + TupleTimeTextProcessor, +) +from pyhealth.models.unified_embedding import UnifiedMultimodalEmbeddingModel + + +def _code_processor(): + proc = StageNetProcessor() + proc.fit([{"codes": ([0.0], ["A", "B"])}], "codes") + return proc + + +class TestFieldEmbeddingReuse(unittest.TestCase): + def test_code_encoder_reuses_prebuilt_layer(self): + proc = _code_processor() + layer = nn.Embedding(proc.value_dim(), 8, padding_idx=0) + pre = SimpleNamespace( + embedding_layers=nn.ModuleDict({"codes": layer}), embedding_dim=8 + ) + model = UnifiedMultimodalEmbeddingModel( + {"codes": proc}, embedding_dim=8, field_embeddings={"codes": pre} + ) + self.assertIs(model.encoders["codes"], layer) + + def test_code_reuse_projects_when_dims_differ(self): + proc = _code_processor() + layer = nn.Embedding(proc.value_dim(), 4, padding_idx=0) + pre = SimpleNamespace( + embedding_layers=nn.ModuleDict({"codes": layer}), embedding_dim=4 + ) + model = UnifiedMultimodalEmbeddingModel( + {"codes": proc}, embedding_dim=8, field_embeddings={"codes": pre} + ) + out = model( + { + "codes": { + "value": torch.zeros(1, 2, dtype=torch.long), + "time": torch.zeros(1, 2), + } + } + ) + self.assertEqual(out["sequence"].shape, (1, 2, 8)) + + def test_vision_reuse_wraps_backbone_with_mean_pool(self): + proc = TimeImageProcessor(image_size=16) + backbone = nn.Identity() + pre = SimpleNamespace( + embedding_layers=nn.ModuleDict({"cxr": backbone}), embedding_dim=8 + ) + model = UnifiedMultimodalEmbeddingModel( + {"cxr": proc}, embedding_dim=8, field_embeddings={"cxr": pre} + ) + encoder = model.encoders["cxr"] + self.assertIsInstance(encoder, nn.Sequential) + self.assertIs(encoder[0], backbone) + + def test_text_freeze_marks_field_frozen(self): + proc = TupleTimeTextProcessor() + transformer = nn.Linear(4, 4) + pre = SimpleNamespace(transformer=transformer, fc=nn.Linear(4, 8)) + model = UnifiedMultimodalEmbeddingModel( + {"notes": proc}, + embedding_dim=8, + field_embeddings={"notes": pre}, + freeze_text_encoder=True, + ) + self.assertIn("notes", model._frozen_text_fields) + self.assertTrue( + all(not p.requires_grad for p in transformer.parameters()) + ) + + def test_default_image_encoder_is_patch_plus_mean_pool(self): + proc = TimeImageProcessor(image_size=16) + model = UnifiedMultimodalEmbeddingModel( + {"cxr": proc}, embedding_dim=8, image_size=16, patch_size=8 + ) + out = model( + { + "cxr": { + "value": torch.zeros(1, 2, 3, 16, 16), + "time": torch.zeros(1, 2), + } + } + ) + self.assertEqual(out["sequence"].shape, (1, 2, 8)) + + def test_unknown_image_pool_raises(self): + proc = TimeImageProcessor(image_size=16) + with self.assertRaises(NotImplementedError): + UnifiedMultimodalEmbeddingModel( + {"cxr": proc}, embedding_dim=8, image_pool="max" + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/core/test_unified_frozen_eval.py b/tests/core/test_unified_frozen_eval.py new file mode 100644 index 0000000000..baf4bbadf9 --- /dev/null +++ b/tests/core/test_unified_frozen_eval.py @@ -0,0 +1,58 @@ +"""Frozen text encoders stay in eval when Trainer calls train().""" + +from __future__ import annotations + +import unittest + +import torch +import torch.nn as nn + +from pyhealth.models.unified_embedding import UnifiedMultimodalEmbeddingModel +from pyhealth.processors.stagenet_processor import StageNetTensorProcessor + + +def _numeric_model(**kwargs) -> UnifiedMultimodalEmbeddingModel: + proc = StageNetTensorProcessor() + proc.fit([{"labs": ([0.0], [[1.0] * 10])}], "labs") + return UnifiedMultimodalEmbeddingModel( + {"labs": proc}, embedding_dim=8, freeze_text_encoder=True, **kwargs + ) + + +class TinyEnc(nn.Module): + def __init__(self): + super().__init__() + self.drop = nn.Dropout(p=0.9) + self.lin = nn.Linear(1, 8) + self.config = type("C", (), {"hidden_size": 8})() + + def forward(self, input_ids, attention_mask=None): + b, l = input_ids.shape + h = self.drop(torch.ones(b, l, 8)) + return type("O", (), {"last_hidden_state": h})() + + +class TestFrozenEncoderEval(unittest.TestCase): + def test_train_keeps_frozen_text_encoder_in_eval(self): + model = _numeric_model() + enc = TinyEnc() + model.encoders["notes"] = enc + model._frozen_text_fields.add("notes") + model.train() + self.assertTrue(model.training) + self.assertFalse(enc.training) + model.eval() + self.assertFalse(enc.training) + model.train() + self.assertFalse(enc.training) + + def test_unfrozen_fields_follow_train_mode(self): + model = _numeric_model() + enc = TinyEnc() + model.encoders["notes"] = enc + model.train() + self.assertTrue(enc.training) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/core/test_unified_nested_codes.py b/tests/core/test_unified_nested_codes.py new file mode 100644 index 0000000000..bfc4a8942b --- /dev/null +++ b/tests/core/test_unified_nested_codes.py @@ -0,0 +1,84 @@ +"""Nested CODE flattening and content-embedding output for the unified model.""" + +import unittest +import warnings + +import torch + +from pyhealth.processors import StageNetProcessor +from pyhealth.models.unified_embedding import UnifiedMultimodalEmbeddingModel + + +class TestNestedCodes(unittest.TestCase): + def _model(self): + proc = StageNetProcessor() + proc.fit([{"codes": ([0.0], [["A", "B"]])}], "codes") + return UnifiedMultimodalEmbeddingModel({"codes": proc}, embedding_dim=8) + + def test_nested_codes_flatten_with_time_expansion(self): + model = self._model() + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + out = model( + { + "codes": { + "value": torch.zeros(1, 2, 3, dtype=torch.long), + "time": torch.tensor([[0.0, 5.0]]), + } + } + ) + self.assertEqual(out["sequence"].shape, (1, 6, 8)) + self.assertEqual(out["time"].shape, (1, 6)) + # Each visit time repeats along its codes after the time sort. + self.assertTrue( + torch.equal( + out["time"], torch.tensor([[0.0, 0.0, 0.0, 5.0, 5.0, 5.0]]) + ) + ) + + def test_warns_once_about_flattening(self): + model = self._model() + inputs = { + "codes": { + "value": torch.zeros(1, 1, 2, dtype=torch.long), + "time": torch.zeros(1, 1), + } + } + with warnings.catch_warnings(record=True) as seen: + warnings.simplefilter("always") + model(inputs) + model(inputs) + flatten = [w for w in seen if "Flattening" in str(w.message)] + self.assertEqual(len(flatten), 1) + + def test_token_emb_is_content_before_time_and_type(self): + model = self._model() + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + out = model( + { + "codes": { + "value": torch.zeros(1, 2, dtype=torch.long), + "time": torch.zeros(1, 2), + } + } + ) + self.assertEqual(out["token_emb"].shape, out["sequence"].shape) + # token_emb differs from sequence: time/type terms are added on top. + self.assertFalse(torch.equal(out["token_emb"], out["sequence"])) + + def test_unsupported_code_rank_raises(self): + model = self._model() + with self.assertRaises(ValueError): + model( + { + "codes": { + "value": torch.zeros(1, 1, 1, 1, dtype=torch.long), + "time": torch.zeros(1, 1), + } + } + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/core/test_unified_standardize.py b/tests/core/test_unified_standardize.py new file mode 100644 index 0000000000..d277fde4ea --- /dev/null +++ b/tests/core/test_unified_standardize.py @@ -0,0 +1,139 @@ +"""Content norm, mask zeroing, and numeric standardizers for the unified model.""" + +import unittest + +import torch +import torch.nn as nn + +from pyhealth.processors import StageNetTensorProcessor +from pyhealth.models.unified_embedding import UnifiedMultimodalEmbeddingModel + + +class _Double(nn.Module): + """Test standardizer: records its inputs, doubles unobserved-safe values.""" + + def __init__(self): + super().__init__() + self.calls = [] + + def forward(self, value, observed): + self.calls.append((value.shape, observed.dtype)) + return value * 2.0 + + +def _labs_processor(): + proc = StageNetTensorProcessor() + proc.fit([{"labs": ([0.0], [[1.0, 2.0]])}], "labs") + return proc + + +class TestContentAssembly(unittest.TestCase): + def test_padded_slots_are_zeroed(self): + model = UnifiedMultimodalEmbeddingModel( + {"labs": _labs_processor()}, embedding_dim=8 + ) + out = model( + { + "labs": { + "value": torch.zeros(1, 2, 2), + "time": torch.zeros(1, 2), + "mask": torch.tensor([[1.0, 0.0]]), + } + } + ) + self.assertTrue(torch.equal(out["mask"], torch.tensor([[1.0, 0.0]]))) + self.assertTrue(bool((out["sequence"][0, 1] == 0).all())) + + def test_normalize_content_bounds_large_magnitudes(self): + proc = _labs_processor() + loud = UnifiedMultimodalEmbeddingModel( + {"labs": proc}, embedding_dim=8, normalize_content=True + ) + quiet = UnifiedMultimodalEmbeddingModel( + {"labs": proc}, embedding_dim=8, normalize_content=False + ) + quiet.load_state_dict(loud.state_dict()) + big = torch.full((1, 2, 2), 1000.0) + times = torch.zeros(1, 2) + seq_norm = loud({"labs": {"value": big, "time": times}})["sequence"] + seq_raw = quiet({"labs": {"value": big, "time": times}})["sequence"] + self.assertLess( + seq_norm.abs().max().item(), seq_raw.abs().max().item() / 100 + ) + + def test_standardizer_runs_before_projection(self): + std = _Double() + model = UnifiedMultimodalEmbeddingModel( + {"labs": _labs_processor()}, + embedding_dim=8, + numeric_standardizers={"labs": std}, + ) + out = model( + { + "labs": { + "value": torch.ones(1, 2, 2), + "time": torch.zeros(1, 2), + }, + "labs_mask": { + "value": torch.ones(1, 2, 2), + "time": torch.zeros(1, 2), + }, + } + ) + # The mask sibling is not a modality: only the 2 lab events surface. + self.assertEqual(out["sequence"].shape, (1, 2, 8)) + self.assertEqual(std.calls, [((1, 2, 2), torch.bool)]) + + def test_standardizer_without_sibling_raises(self): + model = UnifiedMultimodalEmbeddingModel( + {"labs": _labs_processor()}, + embedding_dim=8, + numeric_standardizers={"labs": _Double()}, + ) + with self.assertRaises(ValueError): + model( + {"labs": {"value": torch.ones(1, 1, 2), "time": torch.zeros(1, 1)}} + ) + + def test_standardizer_shape_mismatch_raises(self): + model = UnifiedMultimodalEmbeddingModel( + {"labs": _labs_processor()}, + embedding_dim=8, + numeric_standardizers={"labs": _Double()}, + ) + with self.assertRaises(ValueError): + model( + { + "labs": {"value": torch.ones(1, 2, 2), "time": torch.zeros(1, 2)}, + "labs_mask": { + "value": torch.ones(1, 3, 2), + "time": torch.zeros(1, 3), + }, + } + ) + + + def test_mask_field_without_standardizer_stays_a_modality(self): + model = UnifiedMultimodalEmbeddingModel( + {"labs": _labs_processor(), "labs_mask": _labs_processor()}, + embedding_dim=8, + ) + out = model( + { + "labs": { + "value": torch.ones(1, 2, 2), + "time": torch.zeros(1, 2), + }, + "labs_mask": { + "value": torch.zeros(1, 1, 2), + "time": torch.ones(1, 1), + }, + } + ) + # No standardizer registered for "labs": the "labs_mask" field is not + # consumed by anyone, so both fields encode (2 + 1 events). + self.assertEqual(out["sequence"].shape, (1, 3, 8)) + + +if __name__ == "__main__": + unittest.main()