diff --git a/docs/api/models.rst b/docs/api/models.rst index e67ee03503..d0c72850fe 100644 --- a/docs/api/models.rst +++ b/docs/api/models.rst @@ -321,6 +321,7 @@ API Reference models/pyhealth.models.EHRMambaCEHR models/pyhealth.models.ETHOS models/pyhealth.models.Delphi + models/pyhealth.models.ECGJEPA models/pyhealth.models.JambaEHR models/pyhealth.models.ContraWR models/pyhealth.models.EEGNet diff --git a/docs/api/models/pyhealth.models.ECGJEPA.rst b/docs/api/models/pyhealth.models.ECGJEPA.rst new file mode 100644 index 0000000000..056b7f16c0 --- /dev/null +++ b/docs/api/models/pyhealth.models.ECGJEPA.rst @@ -0,0 +1,38 @@ +pyhealth.models.ECGJEPA +======================= + +Overview +-------- + +ECG-JEPA is a ViT encoder for 12-lead ECGs pretrained with a joint-embedding +predictive objective. It reads 8 leads (I, II, V1-V6) of 10 s at 250 Hz +(2,500 samples), cuts each lead into 50 patches of 50 samples, and uses +cross-pattern attention (CroPA): a patch attends to the patches of its own lead +and to the patches of every lead at the same time. ``ECGJEPA`` puts a linear +head on the mean token and can be fine-tuned or, with ``freeze_encoder=True``, +used as a linear probe. The encoder is ported from the authors' code (MIT +licence) with its parameter names, so the published checkpoints load as they +are. CLIMB (Dai et al., ICML 2025) uses it as its ECG encoder; see +:class:`~pyhealth.tasks.CLIMBECGClassification`. + +Paper: S. Kim, `ECG-JEPA: Learning General Representation of 12-Lead +Electrocardiogram With a Joint-Embedding Predictive Architecture +`_, 2024. Code and checkpoints: +https://github.com/sehunfromdaegu/ECG_JEPA. + +API Reference +------------- + +.. autoclass:: pyhealth.models.ECGJEPA + :members: + :undoc-members: + :show-inheritance: + +.. autoclass:: pyhealth.models.ECGJEPAEncoder + :members: + :undoc-members: + :show-inheritance: + +.. autofunction:: pyhealth.models.ecg_jepa.sincos_pos_embed + +.. autofunction:: pyhealth.models.ecg_jepa.cross_pattern_mask diff --git a/docs/api/tasks.rst b/docs/api/tasks.rst index 64b79d0122..84df53e947 100644 --- a/docs/api/tasks.rst +++ b/docs/api/tasks.rst @@ -236,6 +236,7 @@ Available Tasks PTB-XL HeartLang Classification PTB-XL Heartbeat MI Chapman-Shaoxing ECG Classification + CLIMB ECG Classification PhysioNet 2012 Forecasting PhysioNet 2012 Mortality Disease Progression (MIMIC-IV + Chest ImaGenome) diff --git a/docs/api/tasks/pyhealth.tasks.CLIMBECGClassification.rst b/docs/api/tasks/pyhealth.tasks.CLIMBECGClassification.rst new file mode 100644 index 0000000000..bca15480ee --- /dev/null +++ b/docs/api/tasks/pyhealth.tasks.CLIMBECGClassification.rst @@ -0,0 +1,24 @@ +pyhealth.tasks.CLIMBECGClassification +===================================== + +CLIMB's multi-label ECG diagnosis task (Dai et al., `CLIMB: Data Foundations +for Large Scale Multimodal Clinical Foundation Models +`_, ICML 2025) over PTB-XL, CPSC 2018 and +Georgia (:class:`~pyhealth.datasets.CardiologyDataset`) and Chapman-Shaoxing +(:class:`~pyhealth.datasets.ChapmanShaoxingDataset`), with CLIMB's seven +classes. Labels and the train / validation split of each recording come from +CLIMB's split files (https://github.com/DDVD233/CLIMB, ``src/datasets/ecg``), +read by :func:`~pyhealth.tasks.read_climb_ecg_splits`. + +.. autoclass:: pyhealth.tasks.CLIMBECGClassification + :members: + :undoc-members: + :show-inheritance: + +.. autofunction:: pyhealth.tasks.read_climb_ecg_splits + +.. autodata:: pyhealth.tasks.climb_ecg.CLIMB_ECG_CLASSES + +.. autodata:: pyhealth.tasks.climb_ecg.ECG_JEPA_LEADS + +.. autodata:: pyhealth.tasks.climb_ecg.ECG_LEADS diff --git a/examples/ecg/climb_ecg_benchmark.py b/examples/ecg/climb_ecg_benchmark.py new file mode 100644 index 0000000000..c986b993ba --- /dev/null +++ b/examples/ecg/climb_ecg_benchmark.py @@ -0,0 +1,290 @@ +"""CLIMB's ECG benchmark: ECG-JEPA and a Transformer on four 12-lead datasets. + +Reproduces the ECG rows of Table 25 of Dai et al., "CLIMB: Data Foundations +for Large Scale Multimodal Clinical Foundation Models" (ICML 2025, +https://arxiv.org/abs/2503.07667): one model is trained on the training sets +of PTB-XL, CPSC 2018, Georgia and Chapman-Shaoxing together, on CLIMB's seven +classes, and scored on each validation set (CLIMB has no test split) with +macro AUROC, sensitivity and specificity. + +- Labels and the 80/20 splits come from CLIMB's split files, downloaded from + its repository at a fixed commit and checked against their SHA-256 (CLIMB's + code has no licence, so nothing of it is copied here; its splits are random + and unseeded, so they cannot be regenerated). +- ``--model ecg_jepa`` fine-tunes :class:`~pyhealth.models.ECGJEPA` from a + published checkpoint (``--checkpoint``, from + https://github.com/sehunfromdaegu/ECG_JEPA) on 8 leads x 2,500 samples + (10 s at 250 Hz). +- ``--model transformer`` trains CLIMB's Transformer baseline (dim 256, 12 + blocks, 8 heads, 25-sample segments of all 12 leads at 500 Hz) from scratch; + it is written here from the paper's description. + +Data (open, CC BY 4.0): the ``training/`` folder of the PhysioNet/CinC +Challenge 2020 or 2021 (``cpsc_2018``, ``georgia``, ``ptb-xl``) for +:class:`~pyhealth.datasets.CardiologyDataset`, and the Challenge 2021 +``chapman_shaoxing`` folder (or PhysioNet ``ecg-arrhythmia``) for +:class:`~pyhealth.datasets.ChapmanShaoxingDataset`. + +Usage:: + + # A few minutes: dev mode (1,000 patients per dataset object, so PTB-XL, CPSC and + # Georgia share one limit and Chapman-Shaoxing has its own), tiny models, one epoch. + python examples/ecg/climb_ecg_benchmark.py --root .../training \\ + --chapman-root .../training/chapman_shaoxing --tiny + + python examples/ecg/climb_ecg_benchmark.py --root .../training \\ + --chapman-root .../training/chapman_shaoxing --model ecg_jepa \\ + --checkpoint multiblock_epoch100.pth --epochs 3 --max-hours 2.15 +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import math +import time +import urllib.request +from pathlib import Path + +import numpy as np +import torch +from sklearn.metrics import roc_auc_score +from torch import nn + +from pyhealth.datasets import CardiologyDataset, ChapmanShaoxingDataset, get_dataloader +from pyhealth.models import ECGJEPA +from pyhealth.tasks import ( + CLIMB_ECG_CLASSES, + CLIMBECGClassification, + read_climb_ecg_splits, +) +from pyhealth.tasks.climb_ecg import ECG_LEADS + +CLIMB = ( + "https://raw.githubusercontent.com/DDVD233/CLIMB/" + "0f767b1ea168810b998981078dc27e7f9a4e4675/src/datasets/ecg/" +) +SPLIT_SHA256 = { + "ptbxl": "e48f07e91d6b2616707483bfff3863d4c3bd02866274ccf935d8363269713ba9", + "CPSC": "e008e2ba52280c568d986fa34e4a46c751c633cb67afb73e367ce890015440b1", + "Ga": "6e47ca14de188d0a5086e2759f8019d5560a529516c39f1ad3183722c3ec306a", + "ChapmanShaoxing": "b3ec97578d4f780c7f01c61383194a8780734b286523c8411e2c685795406be9", +} +# Record-name prefix of each dataset, in the column order of Table 25. +DATASETS = {"HR": "PTB-XL", "JS": "Chapman", "A": "CPSC", "E": "Georgia"} +PAPER = { # Table 25, AUROC + "ecg_jepa": {"PTB-XL": 0.906, "Chapman": 0.858, "CPSC": 0.979, "Georgia": 0.767, "overall": 0.877}, + "transformer": {"PTB-XL": 0.785, "Chapman": 0.797, "CPSC": 0.579, "Georgia": 0.671, "overall": 0.708}, +} + + +def climb_labels(cache: Path) -> dict[str, tuple[str, list[str]]]: + """Split and classes of every recording, from CLIMB's four split files.""" + cache.mkdir(parents=True, exist_ok=True) + labels = {} + for name, sha in SPLIT_SHA256.items(): + path = cache / f"{name}_splits.csv" + if not path.exists(): + urllib.request.urlretrieve(f"{CLIMB}{name}_splits.csv", path) + if hashlib.sha256(path.read_bytes()).hexdigest() != sha: + raise ValueError(f"{path} is not CLIMB's file; delete it and rerun.") + labels.update(read_climb_ecg_splits(path)) + return labels + + +def dataset_of(record_id: str) -> str: + return DATASETS[record_id.rstrip("0123456789")] + + +def load_tensors(samples) -> dict: + """All samples in memory: float16 signals, labels, dataset and split.""" + parts = {"signal": [], "label": [], "dataset": [], "train": []} + for batch in get_dataloader(samples, batch_size=256): + parts["signal"].append(batch["signal"].half()) + parts["label"].append(batch["label"].float()) + parts["dataset"] += [dataset_of(r) for r in batch["record_id"]] + parts["train"] += [s == "train" for s in batch["split"]] + return { + "signal": torch.cat(parts["signal"]), + "label": torch.cat(parts["label"]), + "dataset": np.array(parts["dataset"]), + "train": torch.tensor(parts["train"]), + } + + +def build_samples(args, labels, task): + """Sample datasets of the three Challenge sources and of Chapman-Shaoxing.""" + common = {"cache_dir": args.cache_dir, "dev": args.tiny} + cardiology = CardiologyDataset( + root=args.root, sources=["ptb-xl", "cpsc_2018", "georgia"], **common + ) + chapman = ChapmanShaoxingDataset(root=args.chapman_root, subset="climb", **common) + return [cardiology.set_task(task), chapman.set_task(task)] + + +class SegmentTransformer(nn.Module): + """CLIMB's Transformer baseline, from the paper's description. + + The signal (``[B, leads, length]``) is cut into segments of ``segment`` + samples of all leads, each linearly embedded into one token; a class + token and learned position embeddings are added, ``depth`` pre-norm + blocks follow, and the mean token is classified. + """ + + def __init__(self, leads, length, n_out, dim=256, depth=12, heads=8, mlp=512, segment=25): + super().__init__() + self.segment = segment + self.embed = nn.Linear(leads * segment, dim) + self.cls = nn.Parameter(torch.randn(1, 1, dim)) + self.pos = nn.Parameter(torch.randn(1, length // segment + 1, dim)) + layer = nn.TransformerEncoderLayer( + dim, heads, mlp, dropout=0.0, activation="gelu", batch_first=True, norm_first=True + ) + self.blocks = nn.TransformerEncoder(layer, depth, enable_nested_tensor=False) + self.head = nn.Sequential(nn.LayerNorm(dim), nn.Linear(dim, n_out)) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + b, c, n = x.shape + tokens = self.embed(x.reshape(b, c, n // self.segment, self.segment).permute(0, 2, 1, 3).reshape(b, n // self.segment, -1)) + h = torch.cat([self.cls.expand(b, -1, -1), tokens], dim=1) + self.pos + return self.head(self.blocks(h).mean(dim=1)) + + +def scores(y: np.ndarray, p: np.ndarray) -> dict[str, float]: + """Macro AUROC, and macro sensitivity / specificity at 0.5, over classes + that have both positives and negatives.""" + keep = [k for k in range(y.shape[1]) if 0 < y[:, k].sum() < len(y)] + pred = p >= 0.5 + sens = [pred[y[:, k] == 1, k].mean() for k in keep] + spec = [(~pred[y[:, k] == 0, k]).mean() for k in keep] + return { + "auroc": float(np.mean([roc_auc_score(y[:, k], p[:, k]) for k in keep])), + "sens": float(np.mean(sens)), + "spec": float(np.mean(spec)), + } + + +@torch.no_grad() +def evaluate(logits_fn, data, index, device, batch_size): + probs = [] + for start in range(0, len(index), batch_size): + x = data["signal"][index[start : start + batch_size]].to(device).float() + probs.append(torch.sigmoid(logits_fn(x)).float().cpu()) + p = torch.cat(probs).numpy() + y = data["label"][index].numpy() + names = data["dataset"][index.numpy()] + present = [name for name in DATASETS.values() if (names == name).any()] + out = {name: scores(y[names == name], p[names == name]) for name in present} + # Table 25's "Overall" is the mean over the datasets. + out["overall"] = {m: float(np.mean([out[n][m] for n in present])) for m in ("auroc", "sens", "spec")} + return out + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + parser.add_argument("--root", required=True, help="Challenge training/ folder.") + parser.add_argument("--chapman-root", required=True, help="Chapman-Shaoxing records.") + parser.add_argument("--cache-dir", default=None) + parser.add_argument("--output", default="climb_ecg") + parser.add_argument("--model", choices=["ecg_jepa", "transformer"], default="ecg_jepa") + parser.add_argument("--checkpoint", default=None, help="ECG-JEPA checkpoint (.pth).") + parser.add_argument("--freeze-encoder", action="store_true", help="Linear probe.") + parser.add_argument("--epochs", type=int, default=3) + parser.add_argument("--batch-size", type=int, default=32) + parser.add_argument("--lr", type=float, default=None, + help="Default: 1e-3 (transformer, CLIMB); 1e-5 (ecg_jepa).") + parser.add_argument("--weight-decay", type=float, default=1e-2) + parser.add_argument("--warmup", type=float, default=0.1, help="Fraction of steps.") + parser.add_argument("--max-hours", type=float, default=None, help="Stop training after this.") + parser.add_argument("--seed", type=int, default=0) + parser.add_argument("--device", default=None) + parser.add_argument("--tiny", action="store_true", help="Smoke test: dev mode (1,000 patients per dataset object), tiny models, one epoch.") + args = parser.parse_args() + torch.manual_seed(args.seed) + device = args.device or ( + "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu" + ) + output = Path(args.output) + output.mkdir(parents=True, exist_ok=True) + jepa = args.model == "ecg_jepa" + lr = args.lr or (1e-5 if jepa else 1e-3) + + labels = climb_labels(output / "climb_splits") + task = ( + CLIMBECGClassification(labels) + if jepa + else CLIMBECGClassification(labels, num_samples=5000, leads=ECG_LEADS) + ) + parts = build_samples(args, labels, task) + loaded = [load_tensors(part) for part in parts] + data = {k: (np.concatenate if k == "dataset" else torch.cat)([d[k] for d in loaded]) for k in loaded[0]} + train_idx = torch.nonzero(data["train"]).view(-1) + val_idx = torch.nonzero(~data["train"]).view(-1) + counts = {n: int((data["dataset"] == n).sum()) for n in DATASETS.values()} + print(f"recordings {counts}; train {len(train_idx)}, val {len(val_idx)}", flush=True) + + n_out = len(CLIMB_ECG_CLASSES) + if jepa: + tiny = {"dim": 32, "depth": 2, "num_heads": 2} if args.tiny else {} + model = ECGJEPA(parts[0], checkpoint=None if args.tiny else args.checkpoint, + freeze_encoder=args.freeze_encoder, **tiny).to(device) + + def logits_fn(x): + return model.fc(model.embed(x)) + else: + tiny = {"dim": 32, "depth": 2, "heads": 2, "mlp": 64} if args.tiny else {} + model = SegmentTransformer(len(ECG_LEADS), 5000, n_out, **tiny).to(device) + logits_fn = model + params = [p for p in model.parameters() if p.requires_grad] + optimizer = torch.optim.AdamW(params, lr=lr, weight_decay=args.weight_decay) + epochs = 1 if args.tiny else args.epochs + steps = epochs * math.ceil(len(train_idx) / args.batch_size) + warmup = max(1, int(args.warmup * steps)) + scheduler = torch.optim.lr_scheduler.LambdaLR( + optimizer, + lambda s: (s + 1) / warmup if s < warmup else 0.5 * (1 + math.cos(math.pi * (s - warmup) / max(1, steps - warmup))), + ) + loss_fn = nn.BCEWithLogitsLoss() + generator = torch.Generator().manual_seed(args.seed) + start, history, step, stopped = time.time(), [], 0, False + for epoch in range(epochs): + model.train() + order = train_idx[torch.randperm(len(train_idx), generator=generator)] + losses = [] + for i in range(0, len(order), args.batch_size): + index = order[i : i + args.batch_size] + x = data["signal"][index].to(device).float() + loss = loss_fn(logits_fn(x), data["label"][index].to(device)) + optimizer.zero_grad() + loss.backward() + optimizer.step() + scheduler.step() + losses.append(loss.item()) + step += 1 + if step % 100 == 0: + rate = step * args.batch_size / (time.time() - start) + print(f"epoch {epoch} step {step}/{steps} loss {np.mean(losses[-100:]):.4f} " + f"{rate:.1f} samples/s", flush=True) + if args.max_hours and time.time() - start > args.max_hours * 3600: + stopped = True + break + model.eval() + val = evaluate(logits_fn, data, val_idx, device, 2 * args.batch_size) + record = {"epoch": epoch, "steps": step, "minutes": (time.time() - start) / 60, + "loss": float(np.mean(losses)), "val": val, "stopped_early": stopped} + history.append(record) + print(json.dumps(record), flush=True) + if stopped: + break + + name = f"{args.model}{'_probe' if args.freeze_encoder else ''}_seed{args.seed}" + result = {"final": history[-1]["val"], "paper_auroc": PAPER[args.model], "history": history, + "args": vars(args), "lr": lr, "counts": counts} + (output / f"{name}.json").write_text(json.dumps(result, indent=2)) + print("final AUROC", {k: round(v["auroc"], 3) for k, v in history[-1]["val"].items()}) + print("paper AUROC", PAPER[args.model]) + + +if __name__ == "__main__": + main() diff --git a/pyhealth/datasets/cardiology.py b/pyhealth/datasets/cardiology.py index 3369fa90cb..70fcc5f4e6 100644 --- a/pyhealth/datasets/cardiology.py +++ b/pyhealth/datasets/cardiology.py @@ -94,7 +94,8 @@ def parse_header(header_path: str | Path) -> dict: comments[key.strip().lower()] = value.strip() age = comments.get("age", "") return { - "record_id": fields[0], + # Some copies of the Georgia headers write "E00001.mat" here. + "record_id": Path(fields[0]).stem, "n_leads": int(fields[1]), # WFDB allows "fs/counter_freq"; only fs is used. "fs": float(fields[2].split("/")[0]), diff --git a/pyhealth/models/__init__.py b/pyhealth/models/__init__.py index 161ef1ed49..7ddb8fda9a 100644 --- a/pyhealth/models/__init__.py +++ b/pyhealth/models/__init__.py @@ -36,6 +36,7 @@ from .deepsleepnet import DeepSleepNet as DeepSleepNet from .deepr import Deepr, DeeprLayer from .delphi import Delphi as Delphi +from .ecg_jepa import ECGJEPA as ECGJEPA, ECGJEPAEncoder as ECGJEPAEncoder from .eegnet import EEGNet as EEGNet from .embedding import EmbeddingModel from .sequence_embedding import ( diff --git a/pyhealth/models/ecg_jepa.py b/pyhealth/models/ecg_jepa.py new file mode 100644 index 0000000000..f07f0605a2 --- /dev/null +++ b/pyhealth/models/ecg_jepa.py @@ -0,0 +1,336 @@ +"""ECG-JEPA encoder with a classification head (Kim, 2024). + +ECG-JEPA ("Learning General Representation of 12-Lead Electrocardiogram With a +Joint-Embedding Predictive Architecture", https://arxiv.org/abs/2410.08559) +is a ViT over 8 leads x 50 patches of 50 samples (10 s at 250 Hz), with +cross-pattern attention (CroPA): a patch attends only to patches of its own +lead and to the patches of every lead at the same time step. CLIMB (Dai et +al., ICML 2025) fine-tunes it as its ECG encoder. + +The encoder is ported from the authors' code +(https://github.com/sehunfromdaegu/ECG_JEPA, MIT licence, copyright (c) 2024 +Sehun Kim), keeping its parameter names so that the published checkpoints +(``ckpt["encoder"]``) load as they are. Only the encoder's representation +path is ported; pretraining (masking and the predictor) is not. +""" + +from __future__ import annotations + +from collections.abc import Sequence +from pathlib import Path +from typing import Any + +import numpy as np +import torch +import torch.nn.functional as F +from torch import nn + +from ..datasets import SampleDataset +from .base_model import BaseModel + + +def sincos_pos_embed(dim: int, rows: int, cols: int) -> torch.Tensor: + """2-D sine-cosine position embedding of a ``rows x cols`` grid. + + Half of the dimensions encode the column and half the row, as in MAE and + ECG-JEPA; row ``r`` (lead) and column ``c`` (time patch) is position + ``r * cols + c``. + + Args: + dim: Embedding size, a multiple of 4. + rows: Number of leads. + cols: Number of patches per lead. + + Returns: + A ``[rows * cols, dim]`` float tensor. + + Examples: + >>> sincos_pos_embed(8, 2, 3).shape + torch.Size([6, 8]) + """ + if dim % 4: + raise ValueError("dim must be a multiple of 4.") + + def one_axis(pos: np.ndarray) -> np.ndarray: + omega = 1.0 / 10000 ** (np.arange(dim // 4, dtype=float) / (dim / 4)) + out = np.outer(pos.reshape(-1), omega) + return np.concatenate([np.sin(out), np.cos(out)], axis=1) + + col, row = np.meshgrid(np.arange(cols, dtype=float), np.arange(rows, dtype=float)) + return torch.from_numpy(np.concatenate([one_axis(col), one_axis(row)], axis=1)).float() + + +def cross_pattern_mask(leads: int, patches: int) -> torch.Tensor: + """CroPA: which of the ``leads * patches`` tokens each token attends to. + + A token attends to the tokens of its own lead and to those at its own + time patch on every lead. + + Args: + leads: Number of leads. + patches: Number of patches per lead. + + Returns: + A ``[n, n]`` boolean tensor, ``n = leads * patches``; ``True`` where + attention is allowed. + + Examples: + >>> cross_pattern_mask(2, 2).int() + tensor([[1, 1, 1, 0], + [1, 1, 0, 1], + [1, 0, 1, 1], + [0, 1, 1, 1]], dtype=torch.int32) + """ + lead = torch.arange(leads).repeat_interleave(patches) + patch = torch.arange(patches).repeat(leads) + return (lead[:, None] == lead[None, :]) | (patch[:, None] == patch[None, :]) + + +class _Attention(nn.Module): + def __init__(self, dim: int, num_heads: int, dropout: float) -> None: + super().__init__() + self.num_heads = num_heads + self.qkv = nn.Linear(dim, dim * 3, bias=False) + self.proj = nn.Linear(dim, dim) + self.dropout = dropout + + def forward(self, x: torch.Tensor, mask: torch.Tensor) -> torch.Tensor: + b, n, d = x.shape + q, k, v = self.qkv(x).view(b, n, 3, self.num_heads, d // self.num_heads).permute(2, 0, 3, 1, 4) + drop = self.dropout if self.training else 0.0 + x = F.scaled_dot_product_attention(q, k, v, attn_mask=mask, dropout_p=drop) + return F.dropout(self.proj(x.transpose(1, 2).reshape(b, n, d)), drop) + + +class _Mlp(nn.Module): + def __init__(self, dim: int, hidden: int, dropout: float) -> None: + super().__init__() + self.fc1 = nn.Linear(dim, hidden) + self.fc2 = nn.Linear(hidden, dim) + self.drop = nn.Dropout(dropout) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return self.drop(self.fc2(self.drop(F.gelu(self.fc1(x))))) + + +class _Block(nn.Module): + def __init__(self, dim: int, num_heads: int, mlp_ratio: float, dropout: float) -> None: + super().__init__() + self.norm1 = nn.LayerNorm(dim) + self.attn = _Attention(dim, num_heads, dropout) + self.norm2 = nn.LayerNorm(dim) + self.mlp = _Mlp(dim, int(dim * mlp_ratio), dropout) + + def forward(self, x: torch.Tensor, mask: torch.Tensor) -> torch.Tensor: + x = x + self.attn(self.norm1(x), mask) + return x + self.mlp(self.norm2(x)) + + +class _Blocks(nn.Module): + """Holds the blocks under ``blocks``, the checkpoints' key layout.""" + + def __init__(self, blocks: list[_Block]) -> None: + super().__init__() + self.blocks = nn.ModuleList(blocks) + + +class ECGJEPAEncoder(nn.Module): + """The ECG-JEPA encoder: ``[B, leads, 2500]`` signal to ``[B, dim]``. + + Each lead is cut into patches of ``patch_size`` samples, linearly + embedded, and passed through ``depth`` pre-norm transformer blocks with + the CroPA mask (:func:`cross_pattern_mask`); the fixed sine-cosine + position embedding is added before every block, as in the original. The + output is the mean of the final, layer-normed tokens. + + Args: + num_leads: Leads the position grid has (8 in the checkpoints). + num_patches: Patches per lead (50). + patch_size: Samples per patch (50). + dim: Token size (768). + depth: Number of blocks (12). + num_heads: Attention heads (16). + mlp_ratio: Hidden size of the MLPs relative to ``dim`` (4). + dropout: Dropout in attention and MLPs (0, as in the original). + + Examples: + >>> import torch + >>> encoder = ECGJEPAEncoder(num_leads=2, num_patches=4, patch_size=5, + ... dim=16, depth=1, num_heads=2) + >>> encoder(torch.randn(3, 2, 20)).shape + torch.Size([3, 16]) + """ + + def __init__( + self, + num_leads: int = 8, + num_patches: int = 50, + patch_size: int = 50, + dim: int = 768, + depth: int = 12, + num_heads: int = 16, + mlp_ratio: float = 4.0, + dropout: float = 0.0, + ) -> None: + super().__init__() + self.num_leads, self.num_patches, self.patch_size = num_leads, num_patches, patch_size + self.W_P = nn.Linear(patch_size, dim) + self.pos_embed = nn.Parameter( + sincos_pos_embed(dim, num_leads, num_patches), requires_grad=False + ) + self.encoder_blocks = _Blocks( + [_Block(dim, num_heads, mlp_ratio, dropout) for _ in range(depth)] + ) + self.norm = nn.LayerNorm(dim) + self.register_buffer( + "attention_mask", cross_pattern_mask(num_leads, num_patches), persistent=False + ) + self.dim = dim + + def forward(self, x: torch.Tensor, leads: Sequence[int] | None = None) -> torch.Tensor: + """Encodes ``x`` (``[B, len(leads), num_patches * patch_size]``). + + Args: + x: The signals. + leads: Which rows of the position grid the leads of ``x`` are + (all, in order, by default). + + Returns: + The ``[B, dim]`` representation. + """ + b, n_leads, length = x.shape + if length != self.num_patches * self.patch_size: + raise ValueError( + f"Expected {self.num_patches * self.patch_size} samples per lead, got {length}." + ) + index = torch.arange(self.num_leads, device=x.device) if leads is None else torch.as_tensor( + list(leads), device=x.device + ) + if len(index) != n_leads: + raise ValueError(f"x has {n_leads} leads but {len(index)} were named.") + if index.min() < 0 or index.max() >= self.num_leads: + raise ValueError(f"leads must be rows 0..{self.num_leads - 1} of the grid, got {list(leads)}.") + tokens = (index[:, None] * self.num_patches + torch.arange(self.num_patches, device=x.device)).reshape(-1) + pos = self.pos_embed[tokens] + mask = self.attention_mask[tokens][:, tokens] + h = self.W_P(x.reshape(b, n_leads * self.num_patches, self.patch_size)) + for block in self.encoder_blocks.blocks: + h = block(h + pos, mask) + return self.norm(h).mean(dim=1) + + +class ECGJEPA(BaseModel): + """ECG-JEPA with a linear classification head. + + Reads one signal field of shape ``[B, leads, 2500]``, such as + :class:`~pyhealth.tasks.CLIMBECGClassification` produces with its default + eight leads (I, II, V1-V6, the order of the checkpoints' position grid), + and predicts the task's labels with a linear layer on the mean token, + as the authors' fine-tuning does. + + Args: + dataset: The samples; gives the signal field and the label type. + checkpoint: Path of a published ECG-JEPA checkpoint (a dict whose + ``"encoder"`` entry is the encoder's state dict), or ``None`` for + a randomly initialised encoder. + freeze_encoder: Train only the head (linear probing). + num_leads: Rows of the position grid (8 in the checkpoints). + lead_indices: Rows of the position grid the signal's leads are; + defaults to ``0..leads-1``. + dim: Token size (768 in the checkpoints). + depth: Number of blocks (12). + num_heads: Attention heads (16). + num_patches: Patches per lead (50). + patch_size: Samples per patch (50). + dropout: Dropout inside the encoder. + feature_key: The signal field; defaults to the only input field. + + Examples: + >>> import torch + >>> from pyhealth.datasets import create_sample_dataset, get_dataloader + >>> samples = [ + ... {"patient_id": str(i), "signal": torch.randn(2, 20), "label": ["a"] if i % 2 else ["b"]} + ... for i in range(4) + ... ] + >>> dataset = create_sample_dataset(samples, {"signal": "tensor"}, {"label": "multilabel"}) + >>> model = ECGJEPA(dataset, num_leads=2, dim=16, depth=1, num_heads=2, + ... num_patches=4, patch_size=5) + >>> out = model(**next(iter(get_dataloader(dataset, batch_size=4)))) + >>> out["y_prob"].shape + torch.Size([4, 2]) + """ + + def __init__( + self, + dataset: SampleDataset, + checkpoint: str | Path | None = None, + freeze_encoder: bool = False, + num_leads: int = 8, + lead_indices: Sequence[int] | None = None, + dim: int = 768, + depth: int = 12, + num_heads: int = 16, + num_patches: int = 50, + patch_size: int = 50, + dropout: float = 0.0, + feature_key: str | None = None, + ) -> None: + super().__init__(dataset) + if feature_key is None: + if len(self.feature_keys) != 1: + raise ValueError("Pass feature_key: the dataset has several input fields.") + feature_key = self.feature_keys[0] + self.feature_key = feature_key + self.label_key = self.label_keys[0] + n_leads = int(torch.as_tensor(dataset[0][feature_key]).shape[0]) + self.lead_indices = list(range(n_leads)) if lead_indices is None else list(lead_indices) + if ( + len(self.lead_indices) != n_leads + or min(self.lead_indices) < 0 + or max(self.lead_indices) >= num_leads + ): + raise ValueError( + f"The signal has {n_leads} leads; lead_indices must name {n_leads} " + f"rows of the {num_leads}-lead grid, got {self.lead_indices}." + ) + self.encoder = ECGJEPAEncoder( + num_leads=num_leads, + num_patches=num_patches, + patch_size=patch_size, + dim=dim, + depth=depth, + num_heads=num_heads, + dropout=dropout, + ) + if checkpoint is not None: + state = torch.load(checkpoint, map_location="cpu", weights_only=True) + self.encoder.load_state_dict(state.get("encoder", state)) + self.freeze_encoder = freeze_encoder + if freeze_encoder: + self.encoder.requires_grad_(False) + self.fc = nn.Linear(dim, self.label_processor.output_size()) + + def embed(self, signal: torch.Tensor) -> torch.Tensor: + """The encoder's ``[B, dim]`` representation of ``signal``.""" + signal = signal.to(self.device).float() + if self.freeze_encoder: + self.encoder.eval() + with torch.no_grad(): + return self.encoder(signal, self.lead_indices) + return self.encoder(signal, self.lead_indices) + + def forward(self, **kwargs: Any) -> dict[str, torch.Tensor]: + """Classifies the batch. + + Returns: + A dict with ``logit``, ``y_prob`` and the representation + ``embed``; with labels also ``loss`` and ``y_true``. + """ + embed = self.embed(kwargs[self.feature_key]) + logit = self.fc(embed) + out = {"logit": logit, "y_prob": self.label_processor.activation(logit), "embed": embed} + if self.label_key in kwargs: + y_true = kwargs[self.label_key].to(self.device) + out["loss"] = self.label_processor.loss(logit, y_true) + out["y_true"] = y_true + return out diff --git a/pyhealth/tasks/__init__.py b/pyhealth/tasks/__init__.py index 73e542a7ed..db2d9ab07c 100644 --- a/pyhealth/tasks/__init__.py +++ b/pyhealth/tasks/__init__.py @@ -17,6 +17,11 @@ cardiology_isCD_fn, cardiology_isWA_fn, ) +from .climb_ecg import ( + CLIMB_ECG_CLASSES as CLIMB_ECG_CLASSES, + CLIMBECGClassification as CLIMBECGClassification, + read_climb_ecg_splits as read_climb_ecg_splits, +) from .chestxray14_binary_classification import ChestXray14BinaryClassification from .isic2019_classification import ( ISIC2019Classification as ISIC2019Classification, diff --git a/pyhealth/tasks/climb_ecg.py b/pyhealth/tasks/climb_ecg.py new file mode 100644 index 0000000000..5448519441 --- /dev/null +++ b/pyhealth/tasks/climb_ecg.py @@ -0,0 +1,212 @@ +"""CLIMB's 12-lead ECG diagnosis task (Dai et al., ICML 2025). + +CLIMB ("Data Foundations for Large Scale Multimodal Clinical Foundation +Models", https://arxiv.org/abs/2503.07667) groups the ECGs of PTB-XL, CPSC +2018, Georgia and Chapman-Shaoxing into seven diagnostic classes and splits +each source 80/20 into train and validation sets. Its split files +(``_splits.csv`` in https://github.com/DDVD233/CLIMB) give each +recording's split and classes, so :func:`read_climb_ecg_splits` reads both from +them, and :class:`CLIMBECGClassification` turns the recordings into +fixed-length signals with those labels: PTB-XL, CPSC 2018 and Georgia from +:class:`~pyhealth.datasets.CardiologyDataset`, and Chapman-Shaoxing from +:class:`~pyhealth.datasets.ChapmanShaoxingDataset`. +""" + +from __future__ import annotations + +import csv +from collections.abc import Mapping, Sequence +from fractions import Fraction +from pathlib import Path +from typing import Any, ClassVar + +import numpy as np +import torch +from scipy.io import loadmat +from scipy.signal import resample, resample_poly + +from .base_task import BaseTask + +#: CLIMB's seven ECG classes, in the column order of its split files. +CLIMB_ECG_CLASSES: tuple[str, ...] = ("normal", "cd", "mi", "sttc", "other", "afib", "hyp") + +#: The 12 leads of the Challenge recordings, in file order. +ECG_LEADS: tuple[str, ...] = ( + "I", "II", "III", "aVR", "aVL", "aVF", "V1", "V2", "V3", "V4", "V5", "V6", +) + +#: The eight independent leads ECG-JEPA reads (the other four are linear +#: combinations of I and II). +ECG_JEPA_LEADS: tuple[str, ...] = ("I", "II", "V1", "V2", "V3", "V4", "V5", "V6") + + +def read_climb_ecg_splits(path: str | Path) -> dict[str, tuple[str, list[str]]]: + """Reads one of CLIMB's ECG split files. + + Each row of ``_splits.csv`` has the recording name (column + ``patient``), its split (``train`` or ``val``) and one 0/1 column per class + of :data:`CLIMB_ECG_CLASSES`. + + Args: + path: The split file, such as ``ptbxl_splits.csv``. + + Returns: + A dict from recording name (such as ``"HR00001"``) to its split and + the names of its classes (possibly none). + + Examples: + >>> import tempfile + >>> from pathlib import Path + >>> from pyhealth.tasks.climb_ecg import read_climb_ecg_splits + >>> path = Path(tempfile.mkdtemp()) / "ptbxl_splits.csv" + >>> _ = path.write_text( + ... ",file_name,normal,cd,mi,sttc,other,afib,hyp,patient,split,label\\n" + ... "0,x/HR00001.hea,1,0,0,0,1,0,0,HR00001,train,0\\n" + ... ) + >>> read_climb_ecg_splits(path) + {'HR00001': ('train', ['normal', 'other'])} + """ + splits = {} + with open(path, newline="") as f: + for row in csv.DictReader(f): + classes = [c for c in CLIMB_ECG_CLASSES if int(float(row[c]))] + splits[row["patient"]] = (row["split"], classes) + return splits + + +class CLIMBECGClassification(BaseTask): + """Multi-label ECG diagnosis with CLIMB's seven classes. + + Works with :class:`~pyhealth.datasets.CardiologyDataset` and + :class:`~pyhealth.datasets.ChapmanShaoxingDataset` (both read the + Challenge ``.mat`` files). For each recording that has an entry in + ``labels`` it, as CLIMB does: + + 1. reads the ``.mat`` signal and resamples it to ``fs`` (500 Hz), + 2. keeps the first ``duration`` seconds, padding shorter recordings with + zeros at the end, + 3. drops the recording if its first 15 samples are zero on every lead, + 4. resamples the window to ``num_samples`` points (2,500 for ECG-JEPA, + that is 10 s at 250 Hz) and keeps ``leads``, and + 5. scales it by its range, ``x / (max(x) - min(x))`` over all leads. + + Each sample contains: + + - ``signal``: float tensor, shape ``(len(leads), num_samples)`` + - ``label``: the recording's classes (a subset of + :data:`CLIMB_ECG_CLASSES`, possibly empty); the label processor keeps + the order of :data:`CLIMB_ECG_CLASSES` + - ``record_id``, ``source`` (the dataset table) and ``split`` (CLIMB's + ``train`` or ``val``) + + Args: + labels: Split and classes of each recording, as returned by + :func:`read_climb_ecg_splits`. Recordings without an entry are + skipped. + duration: Seconds of signal kept. Default is 10. + fs: Sampling rate before the final resampling. Default is 500. + num_samples: Length of the output signal. Default is 2,500. + leads: Leads to keep, by name (see :data:`ECG_LEADS`). Default is + :data:`ECG_JEPA_LEADS`. + normalize: Scale each recording by its range. Default is True. + + Raises: + ValueError: If a length or rate is not positive, or a lead is unknown. + + Examples: + >>> from pyhealth.tasks import CLIMBECGClassification + >>> task = CLIMBECGClassification({"HR00001": ("train", ["normal"])}) + >>> task.input_schema + {'signal': 'tensor'} + >>> task.output_schema["label"][1]["labels"] + ['normal', 'cd', 'mi', 'sttc', 'other', 'afib', 'hyp'] + """ + + task_name: str = "CLIMBECGClassification" + input_schema: ClassVar[dict[str, str]] = {"signal": "tensor"} + output_schema: ClassVar[dict[str, Any]] = { + "label": ("multilabel", {"labels": list(CLIMB_ECG_CLASSES)}) + } + + def __init__( + self, + labels: Mapping[str, tuple[str, Sequence[str]]], + duration: float = 10.0, + fs: float = 500.0, + num_samples: int = 2500, + leads: Sequence[str] = ECG_JEPA_LEADS, + normalize: bool = True, + ) -> None: + super().__init__() + if min(duration, fs, num_samples) <= 0: + raise ValueError("duration, fs and num_samples must be positive.") + unknown = [lead for lead in leads if lead not in ECG_LEADS] + if unknown: + raise ValueError(f"Unknown leads {unknown}; choose from {ECG_LEADS}.") + self.labels = {k: (split, list(classes)) for k, (split, classes) in labels.items()} + self.duration = float(duration) + self.fs = float(fs) + self.num_samples = int(num_samples) + self.leads = tuple(leads) + self.normalize = normalize + + def signal(self, signal_file: str, fs: float) -> np.ndarray | None: + """The processed ``(len(leads), num_samples)`` signal, or ``None``. + + ``None`` means the recording starts with 15 all-zero samples, which + CLIMB drops. + """ + # ChapmanShaoxingDataset stores the record path without ".mat"; + # loadmat adds it. + x = loadmat(signal_file)["val"].astype(np.float64) + if fs != self.fs: + ratio = Fraction(self.fs / fs).limit_denominator(1000) + x = resample_poly(x, ratio.numerator, ratio.denominator, axis=1) + width = round(self.duration * self.fs) + x = x[:, :width] + if x.shape[1] < width: + x = np.pad(x, ((0, 0), (0, width - x.shape[1]))) + if not np.any(x[:, :15]): + return None + if self.num_samples != width: + x = resample(x, self.num_samples, axis=1) + x = x[[ECG_LEADS.index(lead) for lead in self.leads]] + if self.normalize: + spread = x.max() - x.min() + x = x / spread if spread > 0 else x + return x.astype(np.float32) + + def __call__(self, patient: Any) -> list[dict[str, Any]]: + """Builds the sample of each labeled recording of one patient. + + Args: + patient: A patient of either dataset; each event is a recording. + + Returns: + One sample per recording that is in ``labels`` and not dropped. + """ + samples = [] + for event in patient.get_events(): + # A metadata CSV indexed before the parse_header fix may still + # hold "E00001.mat"; match it on the bare record name. + record_id = Path(str(event.record_id)).stem + entry = self.labels.get(record_id) + if entry is None: + continue + attrs = event.attr_dict + fs = attrs["fs"] if "fs" in attrs else attrs["sampling_rate"] + x = self.signal(attrs["signal_file"], float(fs)) + if x is None: + continue + split, classes = entry + samples.append( + { + "patient_id": patient.patient_id, + "record_id": record_id, + "source": event.event_type, + "split": split, + "signal": torch.from_numpy(x), + "label": classes, + } + ) + return samples diff --git a/tests/core/test_cardiology.py b/tests/core/test_cardiology.py index 14d6cb0826..13bdeeeb5c 100644 --- a/tests/core/test_cardiology.py +++ b/tests/core/test_cardiology.py @@ -79,6 +79,13 @@ def test_reads_rate_demographics_and_codes(self): self.assertEqual(header["age"], "") self.assertEqual(header["dx"], f"{AR_CODE},{WA_CODE}") + def test_record_name_drops_a_file_extension(self): + # Some copies of the Georgia headers name the record "E00001.mat". + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp) / "E00001.hea" + path.write_text("E00001.mat 12 500 5000 05-May-2020 14:50:55\n#Dx: 426783006\n") + self.assertEqual(parse_header(path)["record_id"], "E00001") + class TestCardiologyDetection(unittest.TestCase): @classmethod diff --git a/tests/core/test_climb_ecg.py b/tests/core/test_climb_ecg.py new file mode 100644 index 0000000000..7f5b842673 --- /dev/null +++ b/tests/core/test_climb_ecg.py @@ -0,0 +1,156 @@ +"""CLIMBECGClassification and read_climb_ecg_splits, on synthetic Challenge files.""" + +import shutil +import tempfile +import unittest +from pathlib import Path + +import numpy as np +import torch +from scipy.io import savemat + +from pyhealth.datasets import CardiologyDataset, ChapmanShaoxingDataset +from pyhealth.tasks import ( + CLIMB_ECG_CLASSES, + CLIMBECGClassification, + read_climb_ecg_splits, +) +from pyhealth.tasks.climb_ecg import ECG_JEPA_LEADS, ECG_LEADS + +HEADER = "{name}.mat 16x1+24 1000.0(0)/mV 16 0 0 0 0 {lead}" + + +def write_record(folder, name, fs=500, n_samples=5000, signal=None, chapman=False): + """A 12-lead Challenge record (MATLAB ``.mat`` + ``.hea``); lead i is i + 1.""" + folder.mkdir(parents=True, exist_ok=True) + if signal is None: + signal = np.tile(np.arange(1, 13, dtype=np.int16)[:, None], (1, n_samples)) + savemat(folder / f"{name}.mat", {"val": signal}) + lines = [f"{name} 12 {fs} {signal.shape[1]}"] + lines += [HEADER.format(name=name, lead=lead) for lead in ECG_LEADS] + sep = "#" if chapman else "# " + lines += [f"{sep}Age: 60", f"{sep}Sex: Male", f"{sep}Dx: 426783006"] + (folder / f"{name}.hea").write_text("\n".join(lines) + "\n") + + +def write_splits(path, rows): + header = ",file_name," + ",".join(CLIMB_ECG_CLASSES) + ",patient,split,label\n" + body = "".join( + f"{i},x/{name}.hea,{','.join(str(int(c in classes)) for c in CLIMB_ECG_CLASSES)},{name},{split},0\n" + for i, (name, split, classes) in enumerate(rows) + ) + path.write_text(header + body) + + +class TestReadSplits(unittest.TestCase): + def test_reads_split_and_classes(self): + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp) / "Ga_splits.csv" + write_splits(path, [("E00001", "train", ["cd", "hyp"]), ("E00002", "val", [])]) + self.assertEqual( + read_climb_ecg_splits(path), + {"E00001": ("train", ["cd", "hyp"]), "E00002": ("val", [])}, + ) + + +class TestSignal(unittest.TestCase): + def setUp(self): + self.tmp = Path(tempfile.mkdtemp()) + + def tearDown(self): + shutil.rmtree(self.tmp, ignore_errors=True) + + def _signal(self, task, **kwargs): + write_record(self.tmp, "R", **kwargs) + return task.signal(str(self.tmp / "R.mat"), kwargs.get("fs", 500)) + + def test_default_is_eight_leads_of_2500_scaled_by_range(self): + x = self._signal(CLIMBECGClassification({})) + self.assertEqual(x.shape, (8, 2500)) + expected = np.array([ECG_LEADS.index(lead) + 1 for lead in ECG_JEPA_LEADS], float) + np.testing.assert_allclose(x[:, 100], expected / (expected.max() - expected.min()), rtol=1e-5) + + def test_all_leads_at_500_hz_without_scaling(self): + task = CLIMBECGClassification({}, num_samples=5000, leads=ECG_LEADS, normalize=False) + x = self._signal(task) + self.assertEqual(x.shape, (12, 5000)) + np.testing.assert_allclose(x[:, 0], np.arange(1, 13)) + + def test_other_rates_are_resampled_and_short_records_padded(self): + task = CLIMBECGClassification({}, num_samples=5000, normalize=False) + x = self._signal(task, fs=1000, n_samples=6000) # 6 s at 1 kHz + self.assertEqual(x.shape, (8, 5000)) + np.testing.assert_allclose(x[0, 1000:2000], 1, atol=1e-3) + np.testing.assert_allclose(x[:, 3100:], 0, atol=1e-3) # padded after 6 s + + def test_records_starting_with_zeros_are_dropped(self): + signal = np.ones((12, 5000), dtype=np.int16) + signal[:, :15] = 0 + self.assertIsNone(self._signal(CLIMBECGClassification({}), signal=signal)) + signal[3, 14] = 5 + self.assertIsNotNone(self._signal(CLIMBECGClassification({}), signal=signal)) + + def test_record_ids_with_an_extension_still_match(self): + write_record(self.tmp, "E00001") + event = type("Event", (), { + "record_id": "E00001.mat", "event_type": "georgia", + "attr_dict": {"signal_file": str(self.tmp / "E00001.mat"), "fs": 500}, + })() + patient = type("Patient", (), {"patient_id": "E00001.mat", "get_events": lambda self: [event]})() + samples = CLIMBECGClassification({"E00001": ("val", ["cd"])})(patient) + self.assertEqual([s["record_id"] for s in samples], ["E00001"]) + + def test_rejects_bad_settings(self): + for kwargs in ({"duration": 0}, {"num_samples": 0}, {"leads": ["V7"]}): + with self.subTest(**kwargs), self.assertRaises(ValueError): + CLIMBECGClassification({}, **kwargs) + + +class TestWithDatasets(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.tmp = Path(tempfile.mkdtemp()) + root = cls.tmp / "training" + write_record(root / "ptb-xl" / "g1", "HR00001") + write_record(root / "georgia" / "g1", "E00001") + write_record(root / "georgia" / "g1", "E00002") # not in the splits + write_record(root / "chapman_shaoxing" / "g1", "JS00001", chapman=True) + cls.labels = { + "HR00001": ("train", ["normal", "other"]), + "E00001": ("val", []), + "JS00001": ("val", ["afib"]), + } + cls.root = root + + @classmethod + def tearDownClass(cls): + shutil.rmtree(cls.tmp, ignore_errors=True) + + def test_cardiology_dataset(self): + dataset = CardiologyDataset( + root=str(self.root), sources=["ptb-xl", "georgia"], cache_dir=str(self.tmp / "c1") + ) + samples = dataset.set_task(CLIMBECGClassification(self.labels)) + by_id = {samples[i]["record_id"]: samples[i] for i in range(len(samples))} + self.assertEqual(sorted(by_id), ["E00001", "HR00001"]) + self.assertEqual(by_id["HR00001"]["split"], "train") + self.assertEqual(by_id["HR00001"]["signal"].shape, (8, 2500)) + # Label columns follow CLIMB_ECG_CLASSES: normal and other. + torch.testing.assert_close(by_id["HR00001"]["label"], torch.tensor([1.0, 0, 0, 0, 1, 0, 0])) + torch.testing.assert_close(by_id["E00001"]["label"], torch.zeros(7)) + + def test_chapman_shaoxing_dataset(self): + dataset = ChapmanShaoxingDataset( + root=str(self.root / "chapman_shaoxing"), + metadata_cache_dir=str(self.tmp / "meta"), + cache_dir=str(self.tmp / "c2"), + ) + samples = dataset.set_task(CLIMBECGClassification(self.labels)) + self.assertEqual(len(samples), 1) + self.assertEqual(samples[0]["record_id"], "JS00001") + self.assertEqual(samples[0]["signal"].shape, (8, 2500)) + self.assertEqual(samples[0]["label"][CLIMB_ECG_CLASSES.index("afib")].item(), 1.0) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/core/test_ecg_jepa.py b/tests/core/test_ecg_jepa.py new file mode 100644 index 0000000000..f1516ff1a6 --- /dev/null +++ b/tests/core/test_ecg_jepa.py @@ -0,0 +1,144 @@ +"""ECGJEPA and ECGJEPAEncoder on random signals.""" + +import tempfile +import unittest +from pathlib import Path + +import torch + +from pyhealth.datasets import create_sample_dataset, get_dataloader +from pyhealth.models import ECGJEPA, ECGJEPAEncoder +from pyhealth.models.ecg_jepa import cross_pattern_mask, sincos_pos_embed +from pyhealth.trainer import Trainer + +SMALL = {"dim": 16, "depth": 2, "num_heads": 2, "num_patches": 4, "patch_size": 5} + + +def _dataset(n_leads=3, n=8, mode="multilabel"): + samples = [] + for i in range(n): + label = ["a", "b"][: i % 3] if mode == "multilabel" else i % 2 + samples.append({"patient_id": str(i), "signal": torch.randn(n_leads, 20), "label": label}) + return create_sample_dataset(samples, {"signal": "tensor"}, {"label": mode}) + + +class TestParts(unittest.TestCase): + def test_pos_embed_halves_encode_patch_then_lead(self): + pos = sincos_pos_embed(8, 3, 4) + self.assertEqual(pos.shape, (12, 8)) + # Same patch, other lead: the first half (patch) is equal, the second is not. + torch.testing.assert_close(pos[1, :4], pos[5, :4]) + self.assertFalse(torch.allclose(pos[1, 4:], pos[5, 4:])) + # Same lead, other patch: the second half (lead) is equal. + torch.testing.assert_close(pos[4, 4:], pos[7, 4:]) + with self.assertRaises(ValueError): + sincos_pos_embed(6, 2, 2) + + def test_cross_pattern_mask(self): + mask = cross_pattern_mask(3, 4) + self.assertTrue(mask[0, 3]) # same lead + self.assertTrue(mask[0, 8]) # same patch, lead 2 + self.assertFalse(mask[0, 9]) # other lead and patch + self.assertTrue(torch.equal(mask, mask.T)) + + def test_encoder_attends_only_through_the_mask(self): + torch.manual_seed(0) + encoder = ECGJEPAEncoder(num_leads=2, num_patches=4, patch_size=5, dim=16, depth=1, num_heads=2) + encoder.eval() + x = torch.randn(1, 2, 20) + with torch.no_grad(): + tokens = encoder.W_P(x.reshape(1, 8, 5)) + pos = encoder.pos_embed + block = encoder.encoder_blocks.blocks[0] + mask = cross_pattern_mask(2, 4) + out = encoder.norm(block(tokens + pos, mask)).mean(1) + torch.testing.assert_close(encoder(x), out) + # Changing lead 1, patch 3 does not reach token (lead 0, patch 0) in one block. + y = x.clone() + y[0, 1, 15:] += 5 + a = block(encoder.W_P(x.reshape(1, 8, 5)) + pos, mask)[0, 0] + b = block(encoder.W_P(y.reshape(1, 8, 5)) + pos, mask)[0, 0] + torch.testing.assert_close(a, b) + + def test_encoder_lead_subset_and_bad_inputs(self): + encoder = ECGJEPAEncoder(num_leads=3, num_patches=4, patch_size=5, dim=16, depth=1, num_heads=2) + self.assertEqual(encoder(torch.randn(2, 2, 20), leads=[0, 2]).shape, (2, 16)) + with self.assertRaises(ValueError): + encoder(torch.randn(2, 3, 21)) + with self.assertRaises(ValueError): + encoder(torch.randn(2, 2, 20), leads=[0]) + for leads in ([-1, 0], [0, 3]): + with self.subTest(leads=leads), self.assertRaises(ValueError): + encoder(torch.randn(2, 2, 20), leads=leads) + + +class TestECGJEPA(unittest.TestCase): + def setUp(self): + torch.manual_seed(0) + self.dataset = _dataset() + self.batch = next(iter(get_dataloader(self.dataset, batch_size=8))) + + def test_forward_multilabel_and_binary(self): + model = ECGJEPA(self.dataset, num_leads=3, **SMALL) + out = model(**self.batch) + self.assertEqual(out["y_prob"].shape, (8, 2)) + self.assertEqual(out["embed"].shape, (8, 16)) + out["loss"].backward() + binary = _dataset(mode="binary") + out = ECGJEPA(binary, num_leads=3, **SMALL)(**next(iter(get_dataloader(binary, batch_size=8)))) + self.assertEqual(out["y_prob"].shape, (8, 1)) + no_label = {"signal": self.batch["signal"]} + self.assertNotIn("loss", ECGJEPA(self.dataset, num_leads=3, **SMALL)(**no_label)) + + def test_checkpoint_round_trip_and_lead_indices(self): + source = ECGJEPAEncoder(num_leads=8, **SMALL) + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp) / "ckpt.pth" + torch.save({"encoder": source.state_dict(), "epoch": 100}, path) + model = ECGJEPA(self.dataset, checkpoint=path, lead_indices=[0, 1, 6], **SMALL) + for name, value in source.state_dict().items(): + torch.testing.assert_close(model.encoder.state_dict()[name], value) + model.eval() + source.eval() + with torch.no_grad(): + x = self.batch["signal"] + torch.testing.assert_close(model.embed(x), source(x, [0, 1, 6])) + + def test_frozen_encoder_trains_only_the_head(self): + model = ECGJEPA(self.dataset, num_leads=3, freeze_encoder=True, **SMALL) + before = {n: p.clone() for n, p in model.encoder.named_parameters()} + optimizer = torch.optim.SGD([p for p in model.parameters() if p.requires_grad], lr=0.1) + model.train() + model(**self.batch)["loss"].backward() + optimizer.step() + for name, param in model.encoder.named_parameters(): + torch.testing.assert_close(param, before[name]) + self.assertFalse(model.encoder.training) + self.assertIsNotNone(model.fc.weight.grad) + + def test_trainer(self): + model = ECGJEPA(self.dataset, num_leads=3, **SMALL) + trainer = Trainer(model=model, metrics=["roc_auc_macro"], enable_logging=False) + loader = get_dataloader(self.dataset, batch_size=4, shuffle=True, seed=0) + trainer.train(train_dataloader=loader, epochs=1) + self.assertIn("roc_auc_macro", trainer.evaluate(loader)) + + def test_rejects_bad_settings(self): + with self.assertRaises(ValueError): + ECGJEPA(self.dataset, num_leads=2, **SMALL) # 3 leads, 2-lead grid + with self.assertRaises(ValueError): + ECGJEPA(self.dataset, num_leads=8, lead_indices=[0, 1], **SMALL) + with self.assertRaises(ValueError): + ECGJEPA(self.dataset, num_leads=8, lead_indices=[-1, 0, 1], **SMALL) + two_fields = create_sample_dataset( + [{"patient_id": str(i), "signal": torch.randn(3, 20), "other": torch.randn(3, 20), + "label": ["a"]} for i in range(2)], + {"signal": "tensor", "other": "tensor"}, {"label": "multilabel"}, + ) + with self.assertRaises(ValueError): + ECGJEPA(two_fields, num_leads=3, **SMALL) + self.assertEqual(ECGJEPA(two_fields, num_leads=3, feature_key="other", **SMALL).feature_key, "other") + + +if __name__ == "__main__": + unittest.main()