diff --git a/docs/api/datasets.rst b/docs/api/datasets.rst
index 2a1db44afe..5976a5610a 100644
--- a/docs/api/datasets.rst
+++ b/docs/api/datasets.rst
@@ -485,6 +485,11 @@ PyHealth does not ship any data: you download each dataset from its source and p
- `ISRUC `__
- No
- —
+ * - :doc:`Sleep-Accel `
+ - Open
+ - `PhysioNet `__
+ - No
+ - —
* - :doc:`EESM23 (ear-EEG) `
- Open
- `OpenNeuro `__
@@ -670,6 +675,7 @@ Available Datasets
datasets/pyhealth.datasets.DREAMTDataset
datasets/pyhealth.datasets.SHHSDataset
datasets/pyhealth.datasets.SleepEDFDataset
+ datasets/pyhealth.datasets.SleepAccelDataset
datasets/pyhealth.datasets.NSRRSleepDataset
datasets/pyhealth.datasets.EHRShotDataset
datasets/pyhealth.datasets.Support2Dataset
diff --git a/docs/api/datasets/pyhealth.datasets.SleepAccelDataset.rst b/docs/api/datasets/pyhealth.datasets.SleepAccelDataset.rst
new file mode 100644
index 0000000000..b8155d5ed9
--- /dev/null
+++ b/docs/api/datasets/pyhealth.datasets.SleepAccelDataset.rst
@@ -0,0 +1,17 @@
+pyhealth.datasets.SleepAccelDataset
+===================================
+
+PhysioNet Sleep-Accel contains wrist heart rate, acceleration, step counts and
+30 s sleep-stage labels from a night of polysomnography. The PyHealth loader
+writes ``sleep_accel-pyhealth.csv`` with absolute paths for each complete
+subject and exposes the four modalities as one event per recording.
+
+Because the dataset has no raw PPG or ECG waveform, IBI staging derives
+``60 / bpm`` samples from the heart-rate stream. Use
+:class:`~pyhealth.tasks.SleepStagingIBISleepAccel` to build the shared
+``(T, 750)`` IBI tensors and three-class labels.
+
+.. autoclass:: pyhealth.datasets.SleepAccelDataset
+ :members:
+ :undoc-members:
+ :show-inheritance:
diff --git a/docs/api/models.rst b/docs/api/models.rst
index 64f0694c24..c2a219e66b 100644
--- a/docs/api/models.rst
+++ b/docs/api/models.rst
@@ -48,6 +48,9 @@ routes each feature type automatically.
* - :doc:`models/pyhealth.models.UNet`
- Your task is pixel/voxel-level segmentation with an image and a mask
- ``UNet2D``/``UNet3D``; pair with ``PatchDataset``, ``PatchSampler`` and Dice/IoU metrics
+ * - :doc:`models/pyhealth.models.WatchSleepNet`
+ - You have whole-night IBI sequences and want one sleep-stage label per 30 s epoch
+ - CNN + TCN + BiLSTM + attention; masks padded and unknown epochs from loss/metrics
* - :doc:`models/pyhealth.models.GNN`
- Features include graph-structured data
- Works with ``GraphProcessor``; see :doc:`graph` for setup
@@ -328,6 +331,7 @@ API Reference
models/pyhealth.models.CLIPStress
models/pyhealth.models.EEGNet
models/pyhealth.models.DeepSleepNet
+ models/pyhealth.models.WatchSleepNet
models/pyhealth.models.SleepKD
models/pyhealth.models.SparcNet
models/pyhealth.models.StageNet
diff --git a/docs/api/models/pyhealth.models.WatchSleepNet.rst b/docs/api/models/pyhealth.models.WatchSleepNet.rst
new file mode 100644
index 0000000000..ff20dbd4fc
--- /dev/null
+++ b/docs/api/models/pyhealth.models.WatchSleepNet.rst
@@ -0,0 +1,19 @@
+pyhealth.models.WatchSleepNet
+===================================
+
+WatchSleepNet, a CNN + TCN + BiLSTM + attention model that stages every 30 s epoch of an IBI sequence.
+
+This module is a PyHealth implementation of the original WatchSleepNet paper:
+
+Wang, W.K., Chen, B., Yang, J., Jeong, H., Hershkovich, L., Islam, S.M.M.,
+Liu, M., Roghanizad, A.R., Shandhi, M.M.H., Spector, A.R. & Dunn, J. (2025).
+`WatchSleepNet: A Novel Model and Pretraining Approach for Advancing Sleep
+Staging with Smartwatches
+`_. Proceedings of the sixth
+Conference on Health, Inference, and Learning (CHIL 2025), Proceedings of
+Machine Learning Research 287:145-165.
+
+.. autoclass:: pyhealth.models.WatchSleepNet
+ :members:
+ :undoc-members:
+ :show-inheritance:
diff --git a/docs/api/tasks.rst b/docs/api/tasks.rst
index b81e204464..6ba465fe3a 100644
--- a/docs/api/tasks.rst
+++ b/docs/api/tasks.rst
@@ -268,6 +268,11 @@ Available Tasks
Sleep Staging (SleepEDF)
Sleep-EDF Forecasting
Sleep Staging (Cardio-Respiratory, NSRR)
+ IBI Sleep Staging (DREAMT)
+ IBI Sleep Staging (NSRR SHHS)
+ IBI Sleep Staging (NSRR MESA)
+ IBI Sleep Staging (ISRUC)
+ IBI Sleep Staging (Sleep-Accel)
Sleep Staging Sequences (SleepEDF)
Sleep Staging (ISRUC)
Sleep Staging Sequences (ISRUC)
diff --git a/docs/api/tasks/pyhealth.tasks.SleepStagingIBIDREAMT.rst b/docs/api/tasks/pyhealth.tasks.SleepStagingIBIDREAMT.rst
new file mode 100644
index 0000000000..b705c79196
--- /dev/null
+++ b/docs/api/tasks/pyhealth.tasks.SleepStagingIBIDREAMT.rst
@@ -0,0 +1,11 @@
+pyhealth.tasks.SleepStagingIBIDREAMT
+=====================================
+
+Per-recording inter-beat-interval sleep staging for DREAMT. Reads the
+``data_100Hz`` BVP signal by default, recovers the 30 s epoch grid from stage
+changes, and emits ``(T, 750)`` IBI tensors with three-class labels.
+
+.. autoclass:: pyhealth.tasks.sleep_staging_ibi.SleepStagingIBIDREAMT
+ :members:
+ :undoc-members:
+ :show-inheritance:
diff --git a/docs/api/tasks/pyhealth.tasks.SleepStagingIBIISRUC.rst b/docs/api/tasks/pyhealth.tasks.SleepStagingIBIISRUC.rst
new file mode 100644
index 0000000000..e8f4bdbdec
--- /dev/null
+++ b/docs/api/tasks/pyhealth.tasks.SleepStagingIBIISRUC.rst
@@ -0,0 +1,13 @@
+pyhealth.tasks.SleepStagingIBIISRUC
+===================================
+
+ECG-derived inter-beat-interval sleep staging for ISRUC-Sleep. By default the
+task reads the ``X2`` ECG channel at its native 200 Hz rate, strides the IBI
+signal by eight, and emits ``(T, 750)`` tensors with three-class labels. Choose
+``scorer="expert2"`` to use the second expert's hypnogram instead of the
+first.
+
+.. autoclass:: pyhealth.tasks.sleep_staging_ibi.SleepStagingIBIISRUC
+ :members:
+ :undoc-members:
+ :show-inheritance:
diff --git a/docs/api/tasks/pyhealth.tasks.SleepStagingIBIMESA.rst b/docs/api/tasks/pyhealth.tasks.SleepStagingIBIMESA.rst
new file mode 100644
index 0000000000..1e697aeec2
--- /dev/null
+++ b/docs/api/tasks/pyhealth.tasks.SleepStagingIBIMESA.rst
@@ -0,0 +1,11 @@
+pyhealth.tasks.SleepStagingIBIMESA
+===================================
+
+Per-recording inter-beat-interval sleep staging for NSRR MESA. Resamples the
+Pleth channel from 256 Hz to 100 Hz, strides IBI by four, and emits
+``(T, 750)`` tensors with three-class labels.
+
+.. autoclass:: pyhealth.tasks.sleep_staging_ibi.SleepStagingIBIMESA
+ :members:
+ :undoc-members:
+ :show-inheritance:
diff --git a/docs/api/tasks/pyhealth.tasks.SleepStagingIBISHHS.rst b/docs/api/tasks/pyhealth.tasks.SleepStagingIBISHHS.rst
new file mode 100644
index 0000000000..d935b17131
--- /dev/null
+++ b/docs/api/tasks/pyhealth.tasks.SleepStagingIBISHHS.rst
@@ -0,0 +1,11 @@
+pyhealth.tasks.SleepStagingIBISHHS
+===================================
+
+Per-recording inter-beat-interval sleep staging for NSRR SHHS. Reads the ECG
+channel at 125 Hz, strides IBI by five, and emits ``(T, 750)`` tensors with
+three-class labels.
+
+.. autoclass:: pyhealth.tasks.sleep_staging_ibi.SleepStagingIBISHHS
+ :members:
+ :undoc-members:
+ :show-inheritance:
diff --git a/docs/api/tasks/pyhealth.tasks.SleepStagingIBISleepAccel.rst b/docs/api/tasks/pyhealth.tasks.SleepStagingIBISleepAccel.rst
new file mode 100644
index 0000000000..134a8f63ff
--- /dev/null
+++ b/docs/api/tasks/pyhealth.tasks.SleepStagingIBISleepAccel.rst
@@ -0,0 +1,12 @@
+pyhealth.tasks.SleepStagingIBISleepAccel
+========================================
+
+Heart-rate-derived inter-beat-interval sleep staging for Sleep-Accel. The task
+interpolates ``60 / bpm`` onto a 25 Hz grid and emits ``(T, 750)`` tensors with
+three-class labels. It maps R&K stages to Wake ``0``, NREM ``1``, REM ``2`` and
+unknown ``-1``, and caps each recording at 1100 epochs by default.
+
+.. autoclass:: pyhealth.tasks.sleep_staging_ibi.SleepStagingIBISleepAccel
+ :members:
+ :undoc-members:
+ :show-inheritance:
diff --git a/examples/watchsleepnet/readme.md b/examples/watchsleepnet/readme.md
new file mode 100644
index 0000000000..ade3571e9e
--- /dev/null
+++ b/examples/watchsleepnet/readme.md
@@ -0,0 +1,135 @@
+# WatchSleepNet Examples
+
+WatchSleepNet is a sleep-stage classification algorithm that uses inter-beat interval (IBI) signals derived from polysomnography (PSG) data (ECG, PPG, heart rate). The original paper utilized a two-stage pre-training process, where the model was pre-trained on a large corpus of high quality PSG data like the Sleep Heart Health Study (SHHS) and the Multi-Ethnic Study of Atherosclerosis (MESA) and then fine-tuned on a smaller set of data collected from wearable devices like the Dataset for Real-time sleep stage EstimAtion using Multisensor wearable Technology (DREAMT).
+
+These examples run an end-to-end pipeline for processing datasets to extract IBI from signals, pre-training a model, fine-tuning, and then performing evaluation of a trained model.
+
+Run the commands from the PyHealth repository root with the environment where PyHealth is installed.
+
+## Synthetic Data Generation
+
+If you do not have access to the restricted datasets (SHHS, MESA, DREAMT), the synthetic data generator script can be used to generate datasets for testing. Run the command and pass in the desired dataset to generate (`dreamt`, `mesa`, `shhs`), the number of samples, and the output folder path.
+
+```bash
+python examples/watchsleepnet/watchsleepnet_synthetic_data.py \
+ --dataset shhs --num-samples 5 --output-dir synthetic/shhs
+```
+
+The script will create a folder with the same structure and simulated PSG files as the target dataset. Since the PSG files are randomly generated, they will likely result in poor model training results compared to real data but they can be used to validate the pipeline works.
+
+Generate enough samples for a 60/20/20 train/test/validate split. Each recording defaults to 20 epochs of 30 seconds; use `--epochs` to change this, `--seed` for deterministic output, and `--overwrite` to replace a non-empty output directory. If `--output-dir` is omitted, the dataset is written to `synthetic_data/`.
+
+## Training Model
+
+To train the model, specify paths to the SHHS and MESA dataset, output path, and number of epochs.
+
+The script will perform data transformation to IBI and train the model on the extracted IBI. `--loss` accepts `ce` (default), `weighted_ce`, `focal`, or `inverse_focal`.
+
+```bash
+python examples/watchsleepnet/watchsleepnet_pretrain_shhs_mesa.py \
+ --shhs-root /path/to/shhs --mesa-root /path/to/mesa --epochs 200 \
+ --output-dir output/watchsleepnet-pretrain
+```
+
+The output directory contains `pretrained.pt`, `training_history.csv`, `results.csv`, `results.json`, and a reusable PyHealth cache under `cache/shhs` and `cache/mesa`.
+
+### Ablations
+
+Use `--quantization` to train with `fp32` (default), `bf16`, or `fp16` compute:
+
+```bash
+python examples/watchsleepnet/watchsleepnet_pretrain_shhs_mesa.py \
+ --shhs-root /path/to/shhs --mesa-root /path/to/mesa --epochs 200 \
+ --output-dir output/watchsleepnet-pretrain-bf16 --quantization bf16
+```
+
+Architecture flags override the defaults for one run. For example, to disable the TCN and self-attention and shrink the model:
+
+```bash
+python examples/watchsleepnet/watchsleepnet_pretrain_shhs_mesa.py \
+ --shhs-root /path/to/shhs --mesa-root /path/to/mesa --epochs 200 \
+ --output-dir output/watchsleepnet-no-tcn-attn \
+ --use-tcn false --use-attention false \
+ --hidden-dim 128 --num-heads 8 --num-layers 2 --tcn-layers 1
+```
+
+## Fine Tuning Model
+
+After a model is trained, a `pretrained.pt` model checkpoint will be saved in the output folder. This checkpoint is used for reloading the model for further training or evaluation.
+
+To fine tune the model, specify the checkpoint model path, the dataset, path to the fine tune dataset, number of epochs to fine tune, and the output folder for the trained model. `--loss` and the architecture flags from the pretraining section can also be overridden here.
+
+```bash
+python examples/watchsleepnet/watchsleepnet_finetune.py --dataset dreamt \
+ --root /path/to/dreamt \
+ --checkpoint output/watchsleepnet-pretrain/pretrained.pt \
+ --epochs 5 --output-dir output/watchsleepnet-finetune
+```
+
+The output directory contains `finetuned.pt`, `training_history.csv`, `results.csv`, `results.json`, and a reusable cache under `cache`.
+
+## Quantizing Model
+
+A model trained at full precision `fp32` can be quantized to a lower precision `bf16` or `fp16`.
+
+```bash
+python examples/watchsleepnet/watchsleepnet_quantize.py \
+ --checkpoint output/watchsleepnet-pretrain/pretrained.pt \
+ --output output/watchsleepnet-pretrain/pretrained_bf16.pt \
+ --quantization bf16
+```
+
+The quantized model will be saved to a separate `.pt` file that can be loaded for further fine tuning or evaluation. A `quantization.json` report (or the path passed to `--report`) records the resulting tensor dtype counts.
+
+## Evaluating Performance
+
+To evaluate a trained model checkpoint, specify the dataset, path to the dataset, the trained model checkpoint, and the output folder.
+
+To avoid reprocessing the dataset, pass `--cache-dir` pointing to the PyHealth cache generated during training or fine tuning.
+
+```bash
+python examples/watchsleepnet/watchsleepnet_evaluate.py \
+ --checkpoint output/watchsleepnet-finetune/finetuned.pt \
+ --dataset dreamt --root /path/to/dreamt \
+ --cache-dir output/watchsleepnet-finetune/cache \
+ --output-dir output/watchsleepnet-evaluate
+```
+
+Evaluation reuses the task settings stored in the checkpoint (`points_per_epoch`, `max_epochs`, `signal_source`, and `scorer`); the matching CLI flags override them. The output folder saves `results.csv`, `results.json`, and `confusion_matrix.png` with overall metrics (Accuracy, macro/weighted F1, AUROC, Cohen's Kappa) and per-class Wake/NREM/REM F1.
+
+All real-data training and evaluation scripts accept `--peak-backend`; it defaults to `scipy` so IBI extraction is reproducible. Pass `--peak-backend auto`, `neurokit`, or `biosppy` to opt into the reference detectors, which require optional packages that PyHealth does not install.
+
+## Additional Datasets
+
+Two additional datasets that were not used by the original model were implemented: Sleep-Accel and ISRUC. For ISRUC, IBI signals are extracted from the ECG channel; for Sleep-Accel, they are extracted from heart rate.
+
+For ISRUC, point `--root` at one extracted subgroup folder. Each subject folder contains `/.rec` plus the expert hypnograms `_1.txt` and `_2.txt`. The ECG channel may be named (`X2`, `ECG`, `EKG`, etc.) or, in some exports, numerically labelled; in the latter case the EDF transducer field (`EKG_Channel`) is used to locate it. Use `--scorer expert1` (default) or `expert2`.
+
+```bash
+python examples/watchsleepnet/watchsleepnet_finetune.py --dataset isruc \
+ --root /path/to/ISRUC-Sleep-I \
+ --checkpoint output/watchsleepnet-pretrain/pretrained.pt \
+ --epochs 10 --output-dir output/watchsleepnet-finetune-isruc
+```
+
+For Sleep-Accel, point `--root` at a directory containing `heart_rate/`, `labels/`, `motion/`, and `steps/` subdirectories.
+
+```bash
+python examples/watchsleepnet/watchsleepnet_finetune.py --dataset sleep_accel \
+ --root /path/to/sleep-accel \
+ --checkpoint output/watchsleepnet-pretrain/pretrained.pt \
+ --epochs 10 --output-dir output/watchsleepnet-finetune-sleep-accel
+```
+
+To evaluate a trained model on either dataset, use the same `--dataset` and `--root` pattern (plus `--cache-dir` to reuse the training cache).
+
+```bash
+python examples/watchsleepnet/watchsleepnet_evaluate.py \
+ --checkpoint output/watchsleepnet-finetune-sleep-accel/finetuned.pt \
+ --dataset sleep_accel --root /path/to/sleep-accel \
+ --cache-dir output/watchsleepnet-finetune-sleep-accel/cache \
+ --output-dir output/watchsleepnet-evaluate-sleep-accel
+```
+
+`sleep-accel` is not a valid dataset name; use `sleep_accel`.
+
diff --git a/examples/watchsleepnet/watchsleepnet_common.py b/examples/watchsleepnet/watchsleepnet_common.py
new file mode 100644
index 0000000000..12d48720c3
--- /dev/null
+++ b/examples/watchsleepnet/watchsleepnet_common.py
@@ -0,0 +1,889 @@
+"""Shared helpers for the WatchSleepNet real-data examples.
+
+Every training example requires an explicit root to a real dataset directory;
+there is no synthetic-data fallback. The same functions build datasets, tasks,
+models, checkpoints, and report tables for DREAMT, SHHS, MESA, ISRUC and
+Sleep-Accel cohorts.
+
+Examples:
+ >>> from watchsleepnet_common import CLASS_NAMES, LOSS_MODES
+ >>> from watchsleepnet_common import QUANTIZATION_MODES
+ >>> CLASS_NAMES
+ ('Wake', 'NREM', 'REM')
+ >>> QUANTIZATION_MODES
+ ('fp32', 'bf16', 'fp16')
+ >>> LOSS_MODES
+ ('ce', 'weighted_ce', 'focal', 'inverse_focal')
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+from collections.abc import Mapping, Sequence
+from pathlib import Path
+from typing import Any
+
+import numpy as np
+import pandas as pd
+import torch
+from scipy.signal import resample
+from sklearn.metrics import accuracy_score, f1_score
+
+from pyhealth.datasets import (
+ DREAMTDataset,
+ ISRUCDataset,
+ NSRRSleepDataset,
+ SleepAccelDataset,
+ create_sample_dataset,
+ get_dataloader,
+ split_by_patient,
+)
+from pyhealth.models import WatchSleepNet
+from pyhealth.tasks import (
+ SleepStagingIBIDREAMT,
+ SleepStagingIBIISRUC,
+ SleepStagingIBIMESA,
+ SleepStagingIBISHHS,
+ SleepStagingIBISleepAccel,
+)
+from pyhealth.trainer import Trainer
+
+CLASS_NAMES = ("Wake", "NREM", "REM")
+QUANTIZATION_MODES = ("fp32", "bf16", "fp16")
+LOSS_MODES = ("ce", "weighted_ce", "focal", "inverse_focal")
+PEAK_BACKENDS = ("scipy", "auto", "neurokit", "biosppy")
+DEFAULT_PEAK_BACKEND = "scipy"
+QUANTIZATION_DTYPES = {
+ "fp32": torch.float32,
+ "bf16": torch.bfloat16,
+ "fp16": torch.float16,
+}
+DEFAULT_MODEL_KWARGS = {
+ "num_channels": 256,
+ "kernel_size": 5,
+ "hidden_dim": 256,
+ "num_heads": 16,
+ "num_layers": 4,
+ "tcn_layers": 3,
+}
+TRAINER_METRICS = ["accuracy", "f1_macro", "cohen_kappa"]
+CHECKPOINT_FORMAT = "watchsleepnet-pyhealth-v1"
+
+
+def existing_dir(value: str) -> Path:
+ """Returns an existing directory supplied on the command line.
+
+ Args:
+ value: User-supplied dataset path.
+
+ Returns:
+ The expanded path.
+
+ Raises:
+ argparse.ArgumentTypeError: If the path is not an existing directory.
+
+ Examples:
+ >>> existing_dir(".").is_dir()
+ True
+ """
+ path = Path(value).expanduser()
+ if not path.is_dir():
+ raise argparse.ArgumentTypeError(
+ f"{value!r} does not point to an existing dataset directory"
+ )
+ return path
+
+
+def add_peak_backend_arg(
+ parser: argparse.ArgumentParser,
+) -> argparse.ArgumentParser:
+ """Adds the shared IBI peak-detector flag to an example CLI.
+
+ Args:
+ parser: Parser to extend.
+
+ Returns:
+ The same parser.
+
+ Examples:
+ >>> args = add_peak_backend_arg(argparse.ArgumentParser()).parse_args([])
+ >>> args.peak_backend
+ 'scipy'
+ """
+ parser.add_argument(
+ "--peak-backend",
+ choices=PEAK_BACKENDS,
+ default=DEFAULT_PEAK_BACKEND,
+ help="IBI beat detector; the others require optional packages",
+ )
+ return parser
+
+
+def build_dataset(
+ name: str,
+ root: str | os.PathLike[str],
+ cohort: str | None = None,
+ cache_dir: str | None = None,
+) -> Any:
+ """Builds a PyHealth dataset for one of the supported IBI sources.
+
+ Args:
+ name: ``"dreamt"``, ``"shhs"``, ``"mesa"``, ``"isruc"`` or
+ ``"sleep_accel"``.
+ root: Dataset directory.
+ cohort: NSRR cohort; defaults to ``name``.
+ cache_dir: Optional writable cache for PyHealth metadata.
+
+ Returns:
+ A fitted PyHealth dataset.
+
+ Raises:
+ ValueError: For an unknown name.
+
+ Examples:
+ >>> build_dataset("dreamt", "unused-root") if False else "ready"
+ 'ready'
+ """
+ if name == "dreamt":
+ return DREAMTDataset(root=str(root))
+ if name in ("shhs", "mesa"):
+ return NSRRSleepDataset(
+ root=str(root),
+ cohort=cohort or name,
+ cache_dir=cache_dir,
+ )
+ if name == "isruc":
+ return ISRUCDataset(root=str(root), cache_dir=cache_dir)
+ if name == "sleep_accel":
+ return SleepAccelDataset(root=str(root), cache_dir=cache_dir)
+ raise ValueError(f"unknown dataset {name!r}")
+
+
+def build_task(
+ name: str,
+ points_per_epoch: int = 750,
+ max_epochs: int = 1100,
+ signal_source: str = "psg_100hz",
+ signal_channel: str | None = None,
+ peak_backend: str = "scipy",
+ scorer: str = "expert1",
+) -> Any:
+ """Builds the three-class IBI task for a dataset.
+
+ Args:
+ name: ``"dreamt"``, ``"shhs"``, ``"mesa"``, ``"isruc"`` or
+ ``"sleep_accel"``.
+ points_per_epoch: IBI samples per 30 s epoch.
+ max_epochs: Maximum epochs per recording.
+ signal_source: ``"psg_100hz"`` or ``"wearable_64hz"`` for DREAMT.
+ signal_channel: Waveform column or EDF channel.
+ peak_backend: Beat detector. Defaults to ``"scipy"`` so samples
+ do not depend on optional packages. ``"auto"`` is an opt-in that
+ prefers the installed biosppy/neurokit backends with a scipy
+ fallback.
+ scorer: ``"expert1"`` or ``"expert2"`` hypnogram for ISRUC.
+
+ Returns:
+ A task whose samples use the shared signal/lengths/label contract.
+
+ Raises:
+ ValueError: For an unknown name.
+
+ Examples:
+ >>> build_task("dreamt", points_per_epoch=375).points_per_epoch
+ 375
+ >>> build_task("isruc", scorer="expert2").scorer
+ 'expert2'
+ """
+ if name == "dreamt":
+ return SleepStagingIBIDREAMT(
+ signal_source=signal_source,
+ signal_channel=signal_channel or "BVP",
+ points_per_epoch=points_per_epoch,
+ max_epochs=max_epochs,
+ peak_backend=peak_backend,
+ )
+ if name == "shhs":
+ return SleepStagingIBISHHS(
+ signal_channel=signal_channel or "ECG",
+ points_per_epoch=points_per_epoch,
+ max_epochs=max_epochs,
+ peak_backend=peak_backend,
+ )
+ if name == "mesa":
+ return SleepStagingIBIMESA(
+ signal_channel=signal_channel or "Pleth",
+ points_per_epoch=points_per_epoch,
+ max_epochs=max_epochs,
+ peak_backend=peak_backend,
+ )
+ if name == "isruc":
+ return SleepStagingIBIISRUC(
+ scorer=scorer,
+ channel=signal_channel,
+ points_per_epoch=points_per_epoch,
+ max_epochs=max_epochs,
+ peak_backend=peak_backend,
+ )
+ if name == "sleep_accel":
+ return SleepStagingIBISleepAccel(
+ points_per_epoch=points_per_epoch,
+ max_epochs=max_epochs,
+ )
+ raise ValueError(f"unknown dataset {name!r}")
+
+
+def build_samples(dataset: Any, task: Any, num_workers: int = 1) -> Any:
+ """Applies a task to a base dataset with a bounded worker count.
+
+ Args:
+ dataset: A fitted PyHealth dataset.
+ task: A task from :func:`build_task`.
+ num_workers: Number of PyHealth task workers. One avoids spawning a
+ process pool in CI and gives deterministic sample order.
+
+ Returns:
+ A PyHealth ``SampleDataset`` with the shared IBI contract.
+
+ Examples:
+ >>> build_samples(None, None) if False else "ready"
+ 'ready'
+ """
+ return dataset.set_task(task, num_workers=num_workers)
+
+
+def _rebuild(samples: list[dict[str, Any]], source: Any, name: str = "") -> Any:
+ return create_sample_dataset(
+ samples=samples,
+ input_schema=dict(source.input_schema),
+ output_schema=dict(source.output_schema),
+ dataset_name=name or getattr(source, "dataset_name", ""),
+ task_name=getattr(source, "task_name", ""),
+ )
+
+
+def pool_datasets(datasets: Sequence[Any]) -> Any:
+ """Pools sample datasets into one ``SampleDataset``.
+
+ Patient IDs are prefixed with the source index when more than one dataset
+ is pooled, so SHHS and MESA IDs cannot collide.
+
+ Args:
+ datasets: Sample datasets with identical schemas.
+
+ Returns:
+ A single in-memory sample dataset.
+
+ Examples:
+ >>> import numpy as np, torch
+ >>> from pyhealth.datasets import create_sample_dataset
+ >>> def ds(pid):
+ ... return create_sample_dataset(
+ ... [{"patient_id": pid, "signal": np.zeros((1, 750), "float32"),
+ ... "label": np.array([0]), "lengths": 1}],
+ ... {"signal": "tensor", "lengths": "raw"},
+ ... {"label": ("tensor", {"dtype": torch.long})})
+ >>> len(pool_datasets([ds("p1"), ds("p2")]))
+ 2
+ """
+ samples: list[dict[str, Any]] = []
+ for index, dataset in enumerate(datasets):
+ for sample in dataset:
+ item = dict(sample)
+ if len(datasets) > 1:
+ item["patient_id"] = f"d{index}-{item['patient_id']}"
+ samples.append(item)
+ return _rebuild(samples, datasets[0], "pooled")
+
+
+def resample_dataset(dataset: Any, points: int = 750) -> Any:
+ """Resamples each IBI row to ``points`` without changing labels or schema.
+
+ This is used for the ``points_per_epoch`` ablation: the task computes IBI
+ at a lower rate, then every epoch row is brought back to the 750 samples
+ the model requires so only the information bandwidth changes.
+
+ Args:
+ dataset: A sample dataset with ``(T, S)`` signal tensors.
+ points: Target width for each epoch row.
+
+ Returns:
+ A rebuilt sample dataset.
+
+ Examples:
+ >>> import numpy as np, torch
+ >>> from pyhealth.datasets import create_sample_dataset
+ >>> ds = create_sample_dataset(
+ ... [{"patient_id": "p1", "signal": np.zeros((2, 375), "float32"),
+ ... "label": np.array([0, 1]), "lengths": 2}],
+ ... {"signal": "tensor", "lengths": "raw"},
+ ... {"label": ("tensor", {"dtype": torch.long})})
+ >>> tuple(resample_dataset(ds, 750)[0]["signal"].shape)
+ (2, 750)
+ """
+ samples = []
+ for sample in dataset:
+ item = dict(sample)
+ signal = np.asarray(item["signal"])
+ item["signal"] = resample(signal, points, axis=-1).astype(np.float32)
+ samples.append(item)
+ return _rebuild(samples, dataset, "resampled")
+
+
+def split_dataset(dataset: Any, seed: int = 0) -> tuple[Any, Any, Any]:
+ """Splits a sample dataset by patient into 60/20/20 parts.
+
+ Args:
+ dataset: A sample dataset with at least three patients.
+ seed: Seed used by :func:`pyhealth.datasets.split_by_patient`.
+
+ Returns:
+ Train, validation, and test sample datasets.
+
+ Raises:
+ ValueError: If any split is empty.
+
+ Examples:
+ >>> import numpy as np, torch
+ >>> from pyhealth.datasets import create_sample_dataset
+ >>> samples = [
+ ... {"patient_id": f"p{i}", "signal": np.zeros((1, 750), "float32"),
+ ... "label": np.array([0]), "lengths": 1} for i in range(5)]
+ >>> parts = split_dataset(create_sample_dataset(
+ ... samples, {"signal": "tensor", "lengths": "raw"},
+ ... {"label": ("tensor", {"dtype": torch.long})}))
+ >>> [len(part) for part in parts]
+ [3, 1, 1]
+ """
+ parts = split_by_patient(dataset, [0.6, 0.2, 0.2], seed=seed)
+ if any(len(part) == 0 for part in parts):
+ raise ValueError(
+ "patient split produced an empty part; use at least three patients "
+ "with 5 or more for a stable 60/20/20 split"
+ )
+ return parts
+
+
+def build_model(
+ dataset: Any,
+ seed: int = 0,
+ model_kwargs: Mapping[str, Any] | None = None,
+ quantization: str = "fp32",
+ loss: str = "ce",
+) -> WatchSleepNet:
+ """Builds a WatchSleepNet with a fixed seed for reproducible ablations.
+
+ Args:
+ dataset: The fitted sample dataset.
+ seed: Seed applied to PyTorch before model construction.
+ model_kwargs: Overrides of :data:`DEFAULT_MODEL_KWARGS`.
+ quantization: One of :data:`QUANTIZATION_MODES`.
+ loss: One of :data:`LOSS_MODES`; ``"ce"`` is the reference default.
+
+ Returns:
+ An untrained model with a three-class classifier.
+
+ Examples:
+ >>> import numpy as np, torch
+ >>> from pyhealth.datasets import create_sample_dataset
+ >>> ds = create_sample_dataset(
+ ... [{"patient_id": "p1", "signal": np.zeros((1, 750), "float32"),
+ ... "label": np.array([0]), "lengths": 1}],
+ ... {"signal": "tensor", "lengths": "raw"},
+ ... {"label": ("tensor", {"dtype": torch.long})})
+ >>> build_model(ds).n_classes
+ 3
+ """
+ params = dict(DEFAULT_MODEL_KWARGS)
+ params.update(model_kwargs or {})
+ torch.manual_seed(seed)
+ return WatchSleepNet(
+ dataset=dataset,
+ n_classes=len(CLASS_NAMES),
+ quantization=quantization,
+ loss=loss,
+ **params,
+ )
+
+
+def get_loaders(
+ parts: Sequence[Any], batch_size: int = 16, seed: int = 0
+) -> list[Any]:
+ """Creates train/validation/test loaders with a deterministic shuffle.
+
+ Args:
+ parts: Train, validation, and test sample datasets.
+ batch_size: Batch size for all loaders.
+ seed: Shuffle seed, applied only to the training loader.
+
+ Returns:
+ A list of three data loaders.
+
+ Examples:
+ >>> import numpy as np, torch
+ >>> from pyhealth.datasets import create_sample_dataset
+ >>> samples = [
+ ... {"patient_id": f"p{i}", "signal": np.zeros((1, 750), "float32"),
+ ... "label": np.array([0]), "lengths": 1} for i in range(5)]
+ >>> ds = create_sample_dataset(
+ ... samples, {"signal": "tensor", "lengths": "raw"},
+ ... {"label": ("tensor", {"dtype": torch.long})})
+ >>> [len(loader.dataset) for loader in get_loaders(split_dataset(ds))]
+ [3, 1, 1]
+ """
+ return [
+ get_dataloader(part, batch_size=batch_size, shuffle=(i == 0), seed=seed)
+ for i, part in enumerate(parts)
+ ]
+
+
+def fit(
+ model: WatchSleepNet,
+ loaders: Sequence[Any],
+ epochs: int = 5,
+ lr: float = 5e-5,
+ weight_decay: float = 1e-4,
+ device: str | None = None,
+ quantization: str = "fp32",
+) -> tuple[Trainer, list[dict[str, float]]]:
+ """Trains with ``Trainer.train`` and records one validation row per epoch.
+
+ Args:
+ model: The model to train in place.
+ loaders: Train and validation data loaders.
+ epochs: Number of training epochs.
+ lr: Adam learning rate.
+ weight_decay: Adam weight decay.
+ device: Torch device; ``None`` lets Trainer choose it.
+ quantization: Used to raise Adam's epsilon for fp16 stability.
+
+ Returns:
+ The trainer and a list of per-epoch validation score dicts.
+
+ Examples:
+ >>> fit(model=None, loaders=[]) if False else "ready"
+ 'ready'
+ """
+ trainer = Trainer(model=model, metrics=TRAINER_METRICS, enable_logging=False,
+ device=device)
+ optimizer_params: dict[str, float] = {"lr": lr}
+ if quantization == "fp16":
+ optimizer_params["eps"] = 1e-4
+ history: list[dict[str, float]] = []
+ for epoch in range(int(epochs)):
+ trainer.train(
+ train_dataloader=loaders[0],
+ val_dataloader=loaders[1] if len(loaders) > 1 else None,
+ epochs=1,
+ optimizer_params=optimizer_params,
+ weight_decay=weight_decay,
+ monitor="accuracy" if len(loaders) > 1 else None,
+ )
+ scores = trainer.evaluate(loaders[1]) if len(loaders) > 1 else {}
+ history.append({"epoch": epoch + 1, **{k: float(v) for k, v in scores.items()}})
+ return trainer, history
+
+
+def predict(
+ model: WatchSleepNet,
+ loader: Any,
+ device: str | None = None,
+) -> tuple[np.ndarray, np.ndarray]:
+ """Collects flattened true labels and class probabilities from a loader.
+
+ Args:
+ model: A trained model.
+ loader: Data loader for the evaluation split.
+ device: Torch device; ``None`` uses the model's parameter device.
+
+ Returns:
+ ``(y_true, y_prob)`` arrays over valid, non-padded epochs.
+
+ Examples:
+ >>> predict(model=None, loader=None) if False else "ready"
+ 'ready'
+ """
+ target = device or str(model.device)
+ model.eval()
+ true_parts, prob_parts = [], []
+ with torch.no_grad():
+ for batch in loader:
+ batch = {k: v.to(target) if isinstance(v, torch.Tensor) else v
+ for k, v in batch.items()}
+ output = model(**batch)
+ true_parts.append(output["y_true"].detach().cpu().numpy())
+ prob_parts.append(output["y_prob"].detach().cpu().numpy())
+ if not true_parts:
+ return np.empty(0, dtype=np.int64), np.empty((0, len(CLASS_NAMES)))
+ return np.concatenate(true_parts), np.concatenate(prob_parts)
+
+
+def summarize_predictions(
+ y_true: np.ndarray, y_prob: np.ndarray
+) -> dict[str, float]:
+ """Computes accuracy, per-class F1, and predicted-class distribution.
+
+ Args:
+ y_true: Flattened integer labels in ``0..2``.
+ y_prob: Class probabilities with shape ``(n, 3)``.
+
+ Returns:
+ A flat dictionary of scalar metrics. Per-class F1 values expose
+ NREM-majority collapse even when accuracy looks reasonable.
+
+ Examples:
+ >>> import numpy as np
+ >>> row = summarize_predictions(np.array([0, 1]), np.eye(3)[:2])
+ >>> row["accuracy"], row["f1_rem"]
+ (1.0, 0.0)
+ """
+ y_true = np.asarray(y_true, dtype=np.int64)
+ y_prob = np.asarray(y_prob, dtype=np.float64).reshape(-1, len(CLASS_NAMES))
+ labels = list(range(len(CLASS_NAMES)))
+ y_pred = y_prob.argmax(axis=1) if y_prob.size else np.empty(0, dtype=np.int64)
+ f1 = f1_score(y_true, y_pred, labels=labels, average=None, zero_division=0)
+ counts = np.bincount(y_pred, minlength=len(CLASS_NAMES)).astype(float)
+ distribution = counts / max(len(y_pred), 1)
+ result = {
+ "accuracy": float(accuracy_score(y_true, y_pred)) if y_true.size else 0.0,
+ "f1_macro": float(np.mean(f1)),
+ "n_epochs": int(y_true.size),
+ }
+ for name, value in zip(CLASS_NAMES, f1, strict=True):
+ result[f"f1_{name.lower()}"] = float(value)
+ for name, value in zip(CLASS_NAMES, distribution, strict=True):
+ result[f"pred_{name.lower()}"] = float(value)
+ return result
+
+
+def save_checkpoint(
+ path: str | os.PathLike[str],
+ model: WatchSleepNet,
+ config: Mapping[str, Any],
+ metrics: Mapping[str, Any] | None = None,
+) -> Path:
+ """Saves a self-describing checkpoint with a bare state dict inside.
+
+ Args:
+ path: Output ``.pt`` path.
+ model: Model whose state dict is saved.
+ config: Dataset, task, model, and training configuration.
+ metrics: Optional final evaluation metrics.
+
+ Returns:
+ The output path.
+
+ Examples:
+ >>> save_checkpoint("unused.pt", None, {}) if False else "ready"
+ 'ready'
+ """
+ path = Path(path)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ torch.save(
+ {
+ "format": CHECKPOINT_FORMAT,
+ "state_dict": {k: v.detach().cpu() for k, v in model.state_dict().items()},
+ "config": dict(config),
+ "metrics": dict(metrics or {}),
+ },
+ path,
+ )
+ return path
+
+
+def load_checkpoint(
+ path: str | os.PathLike[str],
+) -> tuple[dict[str, torch.Tensor], dict[str, Any]]:
+ """Loads either a self-describing bundle or a bare ``.pt`` state dict.
+
+ Args:
+ path: Checkpoint path produced by this helper or ``Trainer.save_ckpt``.
+
+ Returns:
+ The state dict and any bundled metadata (empty for bare checkpoints).
+
+ Examples:
+ >>> load_checkpoint("unused.pt") if False else "ready"
+ 'ready'
+ """
+ payload = torch.load(path, map_location="cpu", weights_only=True)
+ if isinstance(payload, Mapping) and "state_dict" in payload:
+ state = dict(payload["state_dict"])
+ metadata = {k: v for k, v in payload.items() if k != "state_dict"}
+ else:
+ state = dict(payload)
+ metadata = {}
+ cleaned = {}
+ for key, value in state.items():
+ name = key
+ for prefix in ("module.", "model."):
+ name = name.removeprefix(prefix)
+ cleaned[name] = value
+ return cleaned, metadata
+
+
+def build_model_from_checkpoint(
+ path: str | os.PathLike[str],
+ dataset: Any,
+ seed: int = 0,
+ overrides: Mapping[str, Any] | None = None,
+) -> tuple[WatchSleepNet, dict[str, Any]]:
+ """Rebuilds a model from a self-describing bundle or a bare ``.pt`` file.
+
+ Values in ``overrides`` win over the checkpoint config. Bare checkpoints use
+ :data:`DEFAULT_MODEL_KWARGS` and ``fp32``; the original bare checkpoint
+ layout is therefore accepted without extra metadata.
+
+ Args:
+ path: Checkpoint produced by :func:`save_checkpoint`,
+ :func:`quantize_checkpoint`, or ``Trainer.save_ckpt``.
+ dataset: The fitted sample dataset used to build the classifier.
+ seed: Seed applied before model construction.
+ overrides: Optional model kwargs, quantization, loss, or dataset name.
+
+ Returns:
+ The loaded model and the checkpoint metadata.
+
+ Examples:
+ >>> build_model_from_checkpoint("unused.pt", None) if False else "ready"
+ 'ready'
+ """
+ state, metadata = load_checkpoint(path)
+ config = dict(metadata.get("config", {}))
+ options = dict(overrides or {})
+ model_kwargs = dict(DEFAULT_MODEL_KWARGS)
+ model_kwargs.update(config.get("model", config.get("model_kwargs", {})))
+ model_kwargs.update(options.get("model_kwargs", {}))
+ for key in DEFAULT_MODEL_KWARGS:
+ if key in options:
+ model_kwargs[key] = options[key]
+ for key in ("use_attention", "use_tcn"):
+ if key in config:
+ model_kwargs[key] = config[key]
+ if key in options:
+ model_kwargs[key] = options[key]
+ quantization = options.get(
+ "quantization", config.get("quantization", "fp32")
+ )
+ loss = options.get("loss", config.get("loss", "ce"))
+ model = build_model(dataset, seed=seed, model_kwargs=model_kwargs,
+ quantization=quantization, loss=loss)
+ model.load_state_dict(state, strict=True)
+ return model, metadata
+
+
+def add_model_args(parser: argparse.ArgumentParser) -> argparse.ArgumentParser:
+ """Adds optional architecture flags that override model defaults.
+
+ Args:
+ parser: Argument parser to update.
+
+ Returns:
+ The same parser, for chaining.
+
+ Examples:
+ >>> import argparse
+ >>> args = add_model_args(argparse.ArgumentParser()).parse_args([])
+ >>> args.hidden_dim, args.use_attention
+ (None, None)
+ """
+ parser.add_argument("--hidden-dim", type=int, default=None)
+ parser.add_argument("--num-channels", type=int, default=None)
+ parser.add_argument("--num-heads", type=int, default=None)
+ parser.add_argument("--num-layers", type=int, default=None)
+ parser.add_argument("--tcn-layers", type=int, default=None)
+ parser.add_argument(
+ "--use-attention", choices=("true", "false"), default=None
+ )
+ parser.add_argument("--use-tcn", choices=("true", "false"), default=None)
+ return parser
+
+
+def model_kwargs_from_args(args: argparse.Namespace) -> dict[str, Any]:
+ """Converts architecture CLI flags into ``WatchSleepNet`` kwargs.
+
+ Args:
+ args: Namespace populated by :func:`add_model_args`.
+
+ Returns:
+ Only the architecture options the caller explicitly set.
+
+ Examples:
+ >>> import argparse
+ >>> parser = add_model_args(argparse.ArgumentParser())
+ >>> model_kwargs_from_args(parser.parse_args(["--hidden-dim", "8"]))
+ {'hidden_dim': 8}
+ """
+ names = {
+ "hidden_dim": "hidden_dim",
+ "num_channels": "num_channels",
+ "num_heads": "num_heads",
+ "num_layers": "num_layers",
+ "tcn_layers": "tcn_layers",
+ }
+ kwargs: dict[str, Any] = {}
+ for flag, key in names.items():
+ value = getattr(args, flag, None)
+ if value is not None:
+ kwargs[key] = value
+ for flag, key in (("use_attention", "use_attention"), ("use_tcn", "use_tcn")):
+ value = getattr(args, flag, None)
+ if value is not None:
+ kwargs[key] = value == "true"
+ return kwargs
+
+
+def quantize_checkpoint(
+ source: str | os.PathLike[str],
+ target: str | os.PathLike[str],
+ quantization: str,
+) -> Path:
+ """Casts every floating-point checkpoint tensor to a compute dtype.
+
+ Args:
+ source: Input bundle or bare ``.pt`` checkpoint.
+ target: Output ``.pt`` path.
+ quantization: One of :data:`QUANTIZATION_MODES`.
+
+ Returns:
+ The output path.
+
+ Raises:
+ ValueError: If ``quantization`` is unsupported.
+
+ Examples:
+ >>> quantize_checkpoint("a.pt", "b.pt", "fp8") if False else "ready"
+ 'ready'
+ """
+ if quantization not in QUANTIZATION_DTYPES:
+ raise ValueError(
+ f"quantization must be one of {QUANTIZATION_MODES}, got {quantization!r}"
+ )
+ state, metadata = load_checkpoint(source)
+ source_format = metadata.get("format", "bare-state-dict")
+ dtype = QUANTIZATION_DTYPES[quantization]
+ cast = {
+ key: value.to(dtype) if torch.is_floating_point(value) else value.clone()
+ for key, value in state.items()
+ }
+ metadata["format"] = CHECKPOINT_FORMAT
+ metadata["quantization"] = quantization
+ target = Path(target)
+ target.parent.mkdir(parents=True, exist_ok=True)
+ torch.save(
+ {
+ "format": CHECKPOINT_FORMAT,
+ "state_dict": cast,
+ "config": metadata.get("config", {}),
+ "metrics": metadata.get("metrics", {}),
+ "quantization": quantization,
+ "source_format": source_format,
+ },
+ target,
+ )
+ return target
+
+
+def write_results(
+ output_dir: str | os.PathLike[str],
+ rows: Sequence[Mapping[str, Any]],
+ metadata: Mapping[str, Any] | None = None,
+) -> tuple[Path, Path]:
+ """Writes ``results.csv`` and ``results.json`` with one row per condition.
+
+ Args:
+ output_dir: Directory to create or overwrite the result files in.
+ rows: Metric dictionaries, one per experiment condition.
+ metadata: Extra JSON metadata such as seeds and dataset roots.
+
+ Returns:
+ The CSV and JSON paths.
+
+ Examples:
+ >>> import tempfile
+ >>> with tempfile.TemporaryDirectory() as tmp:
+ ... csv_path, json_path = write_results(tmp, [{"accuracy": 1.0}])
+ ... csv_path.name, json_path.name
+ ('results.csv', 'results.json')
+ """
+ output_dir = Path(output_dir)
+ output_dir.mkdir(parents=True, exist_ok=True)
+ frame = pd.DataFrame(list(rows))
+ csv_path = output_dir / "results.csv"
+ frame.to_csv(csv_path, index=False)
+
+ def plain(value: Any) -> Any:
+ return value.item() if hasattr(value, "item") else value
+
+ payload = {
+ "metadata": {k: plain(v) for k, v in (metadata or {}).items()},
+ "results": [
+ {k: plain(v) for k, v in row.items()} for row in rows
+ ],
+ }
+ json_path = output_dir / "results.json"
+ json_path.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n")
+ return csv_path, json_path
+
+
+def print_table(rows: Sequence[Mapping[str, Any]], columns: Sequence[str]) -> None:
+ """Prints an aligned table of the requested columns.
+
+ Args:
+ rows: Metric dictionaries.
+ columns: Column names to print in order.
+
+ Returns:
+ None. The table is written to standard output.
+
+ Examples:
+ >>> print_table([{"accuracy": 1.0}], ["accuracy"])
+ accuracy
+ 1.0000
+ """
+ widths = [max(len(c), 8) for c in columns]
+ print(" ".join(c.ljust(w).rstrip() for c, w in zip(columns, widths, strict=True)))
+ for row in rows:
+ cells = []
+ for column, width in zip(columns, widths, strict=True):
+ value = row.get(column, "")
+ if isinstance(value, float):
+ cells.append(f"{value:.4f}".ljust(width))
+ else:
+ cells.append(str(value).ljust(width))
+ print(" ".join(cell.rstrip() for cell in cells))
+
+
+def add_training_args(parser: argparse.ArgumentParser) -> argparse.ArgumentParser:
+ """Adds the shared training, seed, device, and quantization CLI flags.
+
+ Args:
+ parser: Argument parser to update.
+
+ Returns:
+ The same parser, for chaining.
+
+ Examples:
+ >>> import argparse
+ >>> args = add_training_args(argparse.ArgumentParser()).parse_args([])
+ >>> args.quantization, args.seed, args.loss
+ ('fp32', 0, 'ce')
+ """
+ parser.add_argument("--epochs", type=int, default=5)
+ parser.add_argument("--batch-size", type=int, default=16)
+ parser.add_argument("--num-workers", type=int, default=1)
+ parser.add_argument("--lr", type=float, default=5e-5)
+ parser.add_argument("--weight-decay", type=float, default=1e-4)
+ parser.add_argument("--seed", type=int, default=0)
+ parser.add_argument("--device", default=None, help="torch device; default auto")
+ parser.add_argument("--quantization", choices=QUANTIZATION_MODES, default="fp32")
+ parser.add_argument(
+ "--loss",
+ choices=LOSS_MODES,
+ default="ce",
+ help="training loss; ce is the reference default",
+ )
+ parser.add_argument("--output-dir", default="output/watchsleepnet")
+ return parser
diff --git a/examples/watchsleepnet/watchsleepnet_evaluate.py b/examples/watchsleepnet/watchsleepnet_evaluate.py
new file mode 100644
index 0000000000..431cf17ac5
--- /dev/null
+++ b/examples/watchsleepnet/watchsleepnet_evaluate.py
@@ -0,0 +1,411 @@
+"""Evaluates a trained WatchSleepNet checkpoint on a real staging cohort.
+
+The script rebuilds the IBI task from a real dataset root, loads a
+bare ``.pt`` state dict or a self-describing checkpoint, evaluates on the
+held-out patient split, prints the metric table, and writes ``results.csv``,
+``results.json``, and a three-class ``confusion_matrix.png`` to ``--output-dir``.
+DREAMT, SHHS, MESA, ISRUC and Sleep-Accel roots are supported; ISRUC uses the
+checkpoint's scorer unless ``--scorer`` overrides it.
+
+Command:
+ python examples/watchsleepnet/watchsleepnet_evaluate.py \
+ --checkpoint output/watchsleepnet-finetune/finetuned.pt \
+ --dataset dreamt --root /path/to/dreamt \
+ --output-dir output/watchsleepnet-evaluate
+
+Metrics include accuracy, macro one-vs-rest AUROC, Cohen's kappa, macro F1,
+weighted F1, and Wake/NREM/REM F1. Classes with no positive examples are skipped
+when averaging AUROC, so a small held-out split remains scorable.
+"""
+
+from __future__ import annotations
+
+import argparse
+import random
+import warnings
+from pathlib import Path
+from typing import Any
+
+import numpy as np
+import torch
+from sklearn.metrics import (
+ cohen_kappa_score,
+ confusion_matrix,
+ f1_score,
+ roc_auc_score,
+)
+
+try:
+ from .watchsleepnet_common import (
+ CLASS_NAMES,
+ add_peak_backend_arg,
+ build_dataset,
+ build_model_from_checkpoint,
+ build_samples,
+ build_task,
+ existing_dir,
+ get_loaders,
+ load_checkpoint,
+ predict,
+ print_table,
+ resample_dataset,
+ split_dataset,
+ summarize_predictions,
+ write_results,
+ )
+except ImportError:
+ from watchsleepnet_common import (
+ CLASS_NAMES,
+ add_peak_backend_arg,
+ build_dataset,
+ build_model_from_checkpoint,
+ build_samples,
+ build_task,
+ existing_dir,
+ get_loaders,
+ load_checkpoint,
+ predict,
+ print_table,
+ resample_dataset,
+ split_dataset,
+ summarize_predictions,
+ write_results,
+ )
+
+REPORT_COLUMNS = (
+ "dataset",
+ "n_epochs",
+ "accuracy",
+ "auroc",
+ "cohen_kappa",
+ "f1_macro",
+ "f1_weighted",
+ "f1_wake",
+ "f1_nrem",
+ "f1_rem",
+)
+
+
+def existing_file(value: str) -> Path:
+ """Returns an existing checkpoint file supplied on the command line.
+
+ Args:
+ value: User-supplied checkpoint path.
+
+ Returns:
+ The expanded path.
+
+ Raises:
+ argparse.ArgumentTypeError: If the path is not an existing file.
+
+ Examples:
+ >>> import tempfile
+ >>> with tempfile.TemporaryDirectory() as tmp:
+ ... path = Path(tmp) / "model.pt"
+ ... _ = path.write_bytes(b"")
+ ... existing_file(str(path)).name
+ 'model.pt'
+ """
+ path = Path(value).expanduser()
+ if not path.is_file():
+ raise argparse.ArgumentTypeError(
+ f"{value!r} does not point to an existing checkpoint file"
+ )
+ return path
+
+
+def macro_ovr_auroc(y_true: np.ndarray, y_prob: np.ndarray) -> float:
+ """Computes macro one-vs-rest AUROC over the three staging classes.
+
+ Args:
+ y_true: Integer labels in ``0..2``.
+ y_prob: Class probabilities with shape ``(n, 3)``.
+
+ Returns:
+ The mean AUROC over classes with both positive and negative examples,
+ or ``0.0`` when no such class exists.
+
+ Examples:
+ >>> import numpy as np
+ >>> probs = np.array([[0.9, 0.1, 0.0], [0.2, 0.8, 0.0]])
+ >>> macro_ovr_auroc(np.array([0, 1]), probs)
+ 1.0
+ """
+ truth = np.asarray(y_true, dtype=np.int64)
+ scores = np.asarray(y_prob, dtype=np.float64).reshape(-1, len(CLASS_NAMES))
+ if not truth.size:
+ return 0.0
+ values = []
+ for index in range(len(CLASS_NAMES)):
+ binary = (truth == index).astype(np.int64)
+ if np.unique(binary).size < 2:
+ continue
+ values.append(float(roc_auc_score(binary, scores[:, index])))
+ return float(np.mean(values)) if values else 0.0
+
+
+def evaluation_metrics(y_true: np.ndarray, y_prob: np.ndarray) -> dict[str, Any]:
+ """Computes the full evaluation table from flattened predictions.
+
+ Args:
+ y_true: Integer labels in ``0..2``.
+ y_prob: Class probabilities with shape ``(n, 3)``.
+
+ Returns:
+ A flat dictionary with accuracy, AUROC, kappa, macro/weighted F1, and
+ per-class F1. Empty inputs produce zeros.
+
+ Examples:
+ >>> import numpy as np
+ >>> row = evaluation_metrics(np.array([0, 1, 2]), np.eye(3))
+ >>> row["accuracy"], row["auroc"], row["cohen_kappa"]
+ (1.0, 1.0, 1.0)
+ >>> row["f1_macro"], row["f1_weighted"]
+ (1.0, 1.0)
+ >>> row["f1_wake"], row["f1_nrem"], row["f1_rem"]
+ (1.0, 1.0, 1.0)
+ """
+ metrics = dict(summarize_predictions(y_true, y_prob))
+ truth = np.asarray(y_true, dtype=np.int64)
+ scores = np.asarray(y_prob, dtype=np.float64).reshape(-1, len(CLASS_NAMES))
+ predicted = (
+ scores.argmax(axis=1) if scores.size else np.empty(0, dtype=np.int64)
+ )
+ labels = list(range(len(CLASS_NAMES)))
+ if not truth.size:
+ metrics.update(
+ auroc=0.0,
+ cohen_kappa=0.0,
+ f1_weighted=0.0,
+ )
+ return metrics
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore")
+ kappa = cohen_kappa_score(truth, predicted, labels=labels)
+ metrics["auroc"] = macro_ovr_auroc(truth, scores)
+ metrics["cohen_kappa"] = float(kappa) if np.isfinite(kappa) else 0.0
+ metrics["f1_weighted"] = float(
+ f1_score(truth, predicted, labels=labels, average="weighted",
+ zero_division=0)
+ )
+ return metrics
+
+
+def save_confusion_matrix(
+ y_true: np.ndarray, y_pred: np.ndarray, output_dir: str | Path
+) -> Path:
+ """Saves a labeled three-class confusion matrix as a PNG.
+
+ Args:
+ y_true: Integer labels in ``0..2``.
+ y_pred: Predicted labels in ``0..2``.
+ output_dir: Report directory to write ``confusion_matrix.png`` into.
+
+ Returns:
+ The saved image path.
+
+ Examples:
+ >>> import numpy as np
+ >>> import tempfile
+ >>> with tempfile.TemporaryDirectory() as tmp:
+ ... path = save_confusion_matrix(
+ ... np.array([0, 1]), np.array([0, 2]), tmp
+ ... )
+ ... path.name
+ 'confusion_matrix.png'
+ """
+ import matplotlib
+
+ matplotlib.use("Agg")
+ import matplotlib.pyplot as plt
+
+ output_dir = Path(output_dir)
+ output_dir.mkdir(parents=True, exist_ok=True)
+ matrix = confusion_matrix(
+ np.asarray(y_true, dtype=np.int64),
+ np.asarray(y_pred, dtype=np.int64),
+ labels=list(range(len(CLASS_NAMES))),
+ )
+ figure, axis = plt.subplots(figsize=(5.5, 4.5))
+ image = axis.imshow(matrix, cmap="Blues")
+ axis.set_xticks(range(len(CLASS_NAMES)), CLASS_NAMES)
+ axis.set_yticks(range(len(CLASS_NAMES)), CLASS_NAMES)
+ axis.set_xlabel("Predicted")
+ axis.set_ylabel("True")
+ axis.set_title("WatchSleepNet confusion matrix")
+ for row in range(len(CLASS_NAMES)):
+ for column in range(len(CLASS_NAMES)):
+ axis.text(
+ column,
+ row,
+ str(int(matrix[row, column])),
+ ha="center",
+ va="center",
+ color="white" if matrix[row, column] > matrix.max() / 2 else "black",
+ )
+ figure.colorbar(image, ax=axis)
+ figure.tight_layout()
+ path = output_dir / "confusion_matrix.png"
+ figure.savefig(path, dpi=150)
+ plt.close(figure)
+ return path
+
+
+def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
+ """Parses command-line arguments for checkpoint evaluation.
+
+ Args:
+ argv: Optional argument list. Defaults to ``sys.argv[1:]``.
+
+ Returns:
+ The parsed namespace. ``seed`` defaults to the checkpoint's split seed.
+
+ Examples:
+ >>> args = parse_args([
+ ... "--checkpoint", __file__, "--root", ".",
+ ... "--output-dir", "out",
+ ... ])
+ >>> args.dataset, args.batch_size
+ ('dreamt', 16)
+ >>> args.peak_backend
+ 'scipy'
+ """
+ parser = argparse.ArgumentParser(
+ description=__doc__.splitlines()[0],
+ formatter_class=argparse.ArgumentDefaultsHelpFormatter,
+ )
+ parser.add_argument(
+ "--checkpoint", required=True, type=existing_file,
+ help="trained .pt state dict or bundled checkpoint",
+ )
+ parser.add_argument(
+ "--dataset",
+ choices=("dreamt", "shhs", "mesa", "isruc", "sleep_accel"),
+ default="dreamt",
+ )
+ parser.add_argument(
+ "--root", required=True, type=existing_dir, help="real dataset root"
+ )
+ parser.add_argument(
+ "--cache-dir",
+ default=None,
+ help="reuse a PyHealth cache from training (e.g. /cache)",
+ )
+ parser.add_argument(
+ "--output-dir", required=True, type=Path, help="report directory"
+ )
+ parser.add_argument("--batch-size", type=int, default=16)
+ parser.add_argument("--num-workers", type=int, default=1)
+ parser.add_argument("--seed", type=int, default=None)
+ parser.add_argument("--device", default=None, help="torch device; default auto")
+ parser.add_argument("--signal-source", default=None)
+ parser.add_argument("--signal-channel", default=None)
+ parser.add_argument(
+ "--scorer", choices=("expert1", "expert2"), default=None
+ )
+ parser.add_argument("--points-per-epoch", type=int, default=None)
+ parser.add_argument("--task-max-epochs", type=int, default=None)
+ add_peak_backend_arg(parser)
+ return parser.parse_args(argv)
+
+
+def main(argv: list[str] | None = None) -> int:
+ """Evaluates one checkpoint and writes a complete report folder.
+
+ Args:
+ argv: Optional argument list.
+
+ Returns:
+ Process exit code, ``0`` on success.
+
+ Examples:
+ >>> main([
+ ... "--checkpoint", __file__, "--root", ".",
+ ... "--output-dir", "out",
+ ... ]) if False else "ready"
+ 'ready'
+ """
+ args = parse_args(argv)
+ _, metadata = load_checkpoint(args.checkpoint)
+ config: dict[str, Any] = dict(metadata.get("config", {}))
+ task_config: dict[str, Any] = dict(config.get("task", {}))
+ seed = args.seed if args.seed is not None else int(config.get("split_seed", 0))
+ points = (
+ args.points_per_epoch
+ if args.points_per_epoch is not None
+ else int(task_config.get("points_per_epoch", 750))
+ )
+ max_epochs = (
+ args.task_max_epochs
+ if args.task_max_epochs is not None
+ else int(task_config.get("max_epochs", 1100))
+ )
+ signal_source = args.signal_source or str(
+ task_config.get("signal_source", "psg_100hz")
+ )
+ scorer = args.scorer or str(task_config.get("scorer", "expert1"))
+
+ random.seed(seed)
+ np.random.seed(seed)
+ torch.manual_seed(seed)
+
+ dataset = build_dataset(
+ args.dataset, args.root, cache_dir=args.cache_dir
+ )
+ task = build_task(
+ args.dataset,
+ points_per_epoch=points,
+ max_epochs=max_epochs,
+ signal_source=signal_source,
+ signal_channel=args.signal_channel,
+ scorer=scorer,
+ peak_backend=args.peak_backend,
+ )
+ samples = build_samples(dataset, task, num_workers=args.num_workers)
+ if points != 750:
+ samples = resample_dataset(samples, 750)
+ parts = split_dataset(samples, seed=seed)
+ loader = get_loaders(parts, batch_size=args.batch_size, seed=seed)[2]
+
+ model, _ = build_model_from_checkpoint(
+ args.checkpoint, parts[0], seed=seed
+ )
+ target = args.device or str(model.device)
+ model.to(target)
+ y_true, y_prob = predict(model, loader, device=target)
+ y_pred = (
+ y_prob.argmax(axis=1) if y_prob.size else np.empty(0, dtype=np.int64)
+ )
+
+ row = {"dataset": args.dataset, **evaluation_metrics(y_true, y_prob)}
+ image_path = save_confusion_matrix(y_true, y_pred, args.output_dir)
+ matrix = confusion_matrix(
+ y_true,
+ y_pred,
+ labels=list(range(len(CLASS_NAMES))),
+ ).tolist()
+ write_results(
+ args.output_dir,
+ [row],
+ {
+ "checkpoint": str(args.checkpoint),
+ "root": str(args.root),
+ "split": "test",
+ "seed": seed,
+ "task": {
+ "signal_source": signal_source,
+ "points_per_epoch": points,
+ "max_epochs": max_epochs,
+ "scorer": scorer,
+ },
+ "confusion_matrix": matrix,
+ "confusion_matrix_image": image_path.name,
+ },
+ )
+ print_table([row], REPORT_COLUMNS)
+ print(f"confusion matrix: {image_path}")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/examples/watchsleepnet/watchsleepnet_finetune.py b/examples/watchsleepnet/watchsleepnet_finetune.py
new file mode 100644
index 0000000000..53677fb07d
--- /dev/null
+++ b/examples/watchsleepnet/watchsleepnet_finetune.py
@@ -0,0 +1,286 @@
+"""WatchSleepNet fine-tuning from a bare or bundled checkpoint.
+
+The script requires a real dataset root, optionally loads an existing ``.pt``
+checkpoint, fine-tunes with ``Trainer.train``, evaluates with
+``Trainer.evaluate``, and saves a self-describing fine-tuned checkpoint.
+DREAMT, SHHS, MESA, ISRUC and Sleep-Accel roots are supported. There is no
+synthetic-data fallback. ``--loss`` selects the training objective; ``ce`` is
+the reference default.
+
+Command:
+ python examples/watchsleepnet/watchsleepnet_pretrain_shhs_mesa.py \
+ --shhs-root /path/to/shhs --mesa-root /path/to/mesa --epochs 200 \
+ --output-dir output/watchsleepnet-pretrain
+ python examples/watchsleepnet/watchsleepnet_finetune.py --dataset dreamt \
+ --root /path/to/dreamt \
+ --checkpoint output/watchsleepnet-pretrain/pretrained.pt \
+ --epochs 5 --output-dir output/watchsleepnet-finetune
+
+Example output table::
+
+ dataset status checkpoint_loaded accuracy f1_wake f1_nrem f1_rem
+ dreamt ok True 0.6364 0.0000 0.7778 0.0000
+
+Per-class F1 and the predicted-class distribution are written to
+``results.csv``/``results.json``; they expose NREM-majority collapse.
+"""
+
+from __future__ import annotations
+
+import argparse
+import random
+from pathlib import Path
+
+import numpy as np
+import pandas as pd
+
+try:
+ from .watchsleepnet_common import (
+ DEFAULT_MODEL_KWARGS,
+ add_model_args,
+ add_peak_backend_arg,
+ add_training_args,
+ build_dataset,
+ build_model,
+ build_model_from_checkpoint,
+ build_samples,
+ build_task,
+ existing_dir,
+ fit,
+ get_loaders,
+ load_checkpoint,
+ model_kwargs_from_args,
+ predict,
+ print_table,
+ save_checkpoint,
+ split_dataset,
+ summarize_predictions,
+ write_results,
+ )
+except ImportError:
+ from watchsleepnet_common import (
+ DEFAULT_MODEL_KWARGS,
+ add_model_args,
+ add_peak_backend_arg,
+ add_training_args,
+ build_dataset,
+ build_model,
+ build_model_from_checkpoint,
+ build_samples,
+ build_task,
+ existing_dir,
+ fit,
+ get_loaders,
+ load_checkpoint,
+ model_kwargs_from_args,
+ predict,
+ print_table,
+ save_checkpoint,
+ split_dataset,
+ summarize_predictions,
+ write_results,
+ )
+
+TABLE_COLUMNS = (
+ "dataset",
+ "status",
+ "loss",
+ "checkpoint_loaded",
+ "pre_accuracy",
+ "accuracy",
+ "f1_wake",
+ "f1_nrem",
+ "f1_rem",
+ "pred_nrem",
+)
+
+
+def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
+ """Parses command-line arguments for the fine-tuning example.
+
+ Args:
+ argv: Optional argument list.
+
+ Returns:
+ The parsed namespace. ``quantization`` is ``None`` unless explicitly
+ set, so a loaded checkpoint's own mode is preserved.
+
+ Examples:
+ >>> args = parse_args(["--root", "."])
+ >>> args.quantization is None, args.loss
+ (True, 'ce')
+ >>> args.peak_backend
+ 'scipy'
+ >>> parse_args(["--root", ".", "--peak-backend", "auto"]).peak_backend
+ 'auto'
+ """
+ parser = argparse.ArgumentParser(
+ description=__doc__.splitlines()[0],
+ formatter_class=argparse.ArgumentDefaultsHelpFormatter,
+ )
+ parser.add_argument(
+ "--dataset",
+ choices=("dreamt", "shhs", "mesa", "isruc", "sleep_accel"),
+ default="dreamt",
+ )
+ parser.add_argument(
+ "--root", required=True, type=existing_dir, help="real dataset root"
+ )
+ parser.add_argument("--checkpoint", default=None, help=".pt to fine-tune")
+ parser.add_argument("--points-per-epoch", type=int, default=750)
+ parser.add_argument("--task-max-epochs", type=int, default=None)
+ parser.add_argument(
+ "--signal-source",
+ choices=("psg_100hz", "wearable_64hz"),
+ default="psg_100hz",
+ )
+ parser.add_argument(
+ "--scorer", choices=("expert1", "expert2"), default="expert1"
+ )
+ add_peak_backend_arg(parser)
+ add_training_args(parser)
+ add_model_args(parser)
+ parser.set_defaults(quantization=None)
+ return parser.parse_args(argv)
+
+
+def main(argv: list[str] | None = None) -> int:
+ """Fine-tunes from an optional checkpoint and writes model and result files.
+
+ Args:
+ argv: Optional argument list.
+
+ Returns:
+ Zero after a completed run.
+
+ Examples:
+ >>> main(["--root", ".", "--epochs", "0"]) if False else "ready"
+ 'ready'
+ """
+ args = parse_args(argv)
+ random.seed(args.seed)
+ np.random.seed(args.seed)
+ output_dir = Path(args.output_dir)
+ output_dir.mkdir(parents=True, exist_ok=True)
+
+ root = Path(args.root)
+ cache_dir = output_dir / "cache"
+ dataset = build_dataset(
+ args.dataset, root, cache_dir=str(cache_dir)
+ )
+ task = build_task(
+ args.dataset,
+ points_per_epoch=args.points_per_epoch,
+ max_epochs=args.task_max_epochs or 1100,
+ signal_source=args.signal_source,
+ scorer=args.scorer,
+ peak_backend=args.peak_backend,
+ )
+ samples = build_samples(dataset, task, num_workers=args.num_workers)
+ parts = split_dataset(samples, seed=args.seed)
+ loaders = get_loaders(
+ parts, batch_size=args.batch_size, seed=args.seed
+ )
+
+ cli_kwargs = model_kwargs_from_args(args)
+ checkpoint_config: dict[str, object] = {}
+ if args.checkpoint:
+ _, metadata = load_checkpoint(args.checkpoint)
+ checkpoint_config = dict(metadata.get("config", {}))
+ overrides: dict[str, object] = {}
+ if args.quantization is not None:
+ overrides["quantization"] = args.quantization
+ overrides["loss"] = args.loss
+ if cli_kwargs:
+ overrides["model_kwargs"] = cli_kwargs
+ model, _ = build_model_from_checkpoint(
+ args.checkpoint, parts[0], seed=args.seed, overrides=overrides
+ )
+ else:
+ model = build_model(
+ parts[0], seed=args.seed, model_kwargs=cli_kwargs,
+ quantization=args.quantization or "fp32", loss=args.loss,
+ )
+ quantization = str(
+ args.quantization
+ or checkpoint_config.get("quantization", "fp32")
+ )
+ model_kwargs = dict(DEFAULT_MODEL_KWARGS)
+ model_kwargs.update(checkpoint_config.get("model", {}))
+ model_kwargs.update(cli_kwargs)
+
+ pre_metrics = {}
+ if args.checkpoint:
+ pre_true, pre_prob = predict(model, loaders[2],
+ device=args.device)
+ pre_metrics = summarize_predictions(pre_true, pre_prob)
+
+ trainer, history = fit(
+ model,
+ loaders,
+ epochs=args.epochs,
+ lr=args.lr,
+ weight_decay=args.weight_decay,
+ device=args.device,
+ quantization=quantization,
+ )
+ val_scores = trainer.evaluate(loaders[1])
+ y_true, y_prob = predict(model, loaders[2], device=args.device)
+ metrics = summarize_predictions(y_true, y_prob)
+
+ checkpoint = save_checkpoint(
+ output_dir / "finetuned.pt",
+ model,
+ {
+ "stage": "finetune",
+ "dataset": args.dataset,
+ "root": str(root),
+ "source_checkpoint": args.checkpoint,
+ "task": {
+ "signal_source": args.signal_source,
+ "points_per_epoch": args.points_per_epoch,
+ "max_epochs": args.task_max_epochs or 1100,
+ "scorer": args.scorer,
+ },
+ "model": model_kwargs,
+ "quantization": quantization,
+ "loss": args.loss,
+ "split_seed": args.seed,
+ "training": {
+ "epochs": args.epochs,
+ "batch_size": args.batch_size,
+ "lr": args.lr,
+ "weight_decay": args.weight_decay,
+ },
+ },
+ metrics,
+ )
+ pd.DataFrame(history).to_csv(
+ output_dir / "training_history.csv", index=False
+ )
+ row = {
+ "dataset": args.dataset,
+ "status": "ok",
+ "loss": args.loss,
+ "checkpoint_loaded": bool(args.checkpoint),
+ "pre_accuracy": pre_metrics.get("accuracy", ""),
+ "val_accuracy": float(val_scores.get("accuracy", 0.0)),
+ "checkpoint": str(checkpoint),
+ **metrics,
+ }
+ write_results(
+ output_dir,
+ [row],
+ {
+ "root": str(root),
+ "loss": args.loss,
+ "seed": args.seed,
+ "source_checkpoint": args.checkpoint,
+ },
+ )
+ print_table([row], TABLE_COLUMNS)
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/examples/watchsleepnet/watchsleepnet_pretrain_shhs_mesa.py b/examples/watchsleepnet/watchsleepnet_pretrain_shhs_mesa.py
new file mode 100644
index 0000000000..bfdfe9f495
--- /dev/null
+++ b/examples/watchsleepnet/watchsleepnet_pretrain_shhs_mesa.py
@@ -0,0 +1,236 @@
+"""SHHS+MESA WatchSleepNet pretraining on real cohorts.
+
+The script requires real SHHS and MESA roots, builds the three-class
+IBI tasks, pools the recordings, splits by patient, trains
+:class:`~pyhealth.models.WatchSleepNet` with ``Trainer.train``, and saves a
+self-describing checkpoint plus ``training_history.csv``. There is no
+synthetic-data fallback.
+
+Command:
+ python examples/watchsleepnet/watchsleepnet_pretrain_shhs_mesa.py \
+ --shhs-root /path/to/shhs --mesa-root /path/to/mesa --epochs 200 \
+ --output-dir output/watchsleepnet-pretrain
+
+A 1100-epoch cap is used by default. ``--loss`` selects the
+training objective; ``ce`` is the reference default. Example output table::
+
+ cohort status accuracy f1_wake f1_nrem f1_rem
+ shhs+mesa ok 0.6364 0.0000 0.7778 0.0000
+
+The predicted-class distribution is also reported in ``results.csv`` so that
+NREM-majority collapse remains visible even when accuracy looks reasonable.
+"""
+
+from __future__ import annotations
+
+import argparse
+import random
+from pathlib import Path
+
+import numpy as np
+import pandas as pd
+
+try:
+ from .watchsleepnet_common import (
+ add_model_args,
+ add_peak_backend_arg,
+ add_training_args,
+ build_dataset,
+ build_model,
+ build_samples,
+ build_task,
+ existing_dir,
+ fit,
+ get_loaders,
+ model_kwargs_from_args,
+ pool_datasets,
+ predict,
+ print_table,
+ save_checkpoint,
+ split_dataset,
+ summarize_predictions,
+ write_results,
+ )
+except ImportError:
+ from watchsleepnet_common import (
+ add_model_args,
+ add_peak_backend_arg,
+ add_training_args,
+ build_dataset,
+ build_model,
+ build_samples,
+ build_task,
+ existing_dir,
+ fit,
+ get_loaders,
+ model_kwargs_from_args,
+ pool_datasets,
+ predict,
+ print_table,
+ save_checkpoint,
+ split_dataset,
+ summarize_predictions,
+ write_results,
+ )
+
+TABLE_COLUMNS = (
+ "cohort",
+ "status",
+ "loss",
+ "accuracy",
+ "f1_wake",
+ "f1_nrem",
+ "f1_rem",
+ "pred_wake",
+ "pred_nrem",
+ "pred_rem",
+)
+
+
+def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
+ """Parses command-line arguments for the pretraining example.
+
+ Args:
+ argv: Optional argument list.
+
+ Returns:
+ The parsed namespace.
+
+ Examples:
+ >>> args = parse_args(["--shhs-root", ".", "--mesa-root", ".",
+ ... "--epochs", "2"])
+ >>> args.epochs, args.peak_backend
+ (2, 'scipy')
+ """
+ parser = argparse.ArgumentParser(
+ description=__doc__.splitlines()[0],
+ formatter_class=argparse.ArgumentDefaultsHelpFormatter,
+ )
+ parser.add_argument(
+ "--shhs-root", required=True, type=existing_dir, help="real SHHS root"
+ )
+ parser.add_argument(
+ "--mesa-root", required=True, type=existing_dir, help="real MESA root"
+ )
+ parser.add_argument("--points-per-epoch", type=int, default=750)
+ parser.add_argument("--task-max-epochs", type=int, default=None)
+ add_peak_backend_arg(parser)
+ add_training_args(parser)
+ add_model_args(parser)
+ return parser.parse_args(argv)
+
+
+def main(argv: list[str] | None = None) -> int:
+ """Runs pretraining and writes the checkpoint, history, and result files.
+
+ Args:
+ argv: Optional argument list.
+
+ Returns:
+ Zero after a completed run.
+
+ Examples:
+ >>> main(["--shhs-root", ".", "--mesa-root", ".",
+ ... "--epochs", "0"]) if False else "ready"
+ 'ready'
+ """
+ args = parse_args(argv)
+ random.seed(args.seed)
+ np.random.seed(args.seed)
+ output_dir = Path(args.output_dir)
+ output_dir.mkdir(parents=True, exist_ok=True)
+
+ cache_root = output_dir / "cache"
+ cohorts = [("shhs", Path(args.shhs_root)), ("mesa", Path(args.mesa_root))]
+
+ sample_sets = []
+ for name, root in cohorts:
+ dataset = build_dataset(
+ name, root, cache_dir=str(cache_root / name)
+ )
+ task = build_task(
+ name,
+ points_per_epoch=args.points_per_epoch,
+ max_epochs=(
+ args.task_max_epochs
+ if args.task_max_epochs is not None
+ else 1100
+ ),
+ peak_backend=args.peak_backend,
+ )
+ sample_sets.append(
+ build_samples(dataset, task, num_workers=args.num_workers)
+ )
+ samples = pool_datasets(sample_sets)
+ parts = split_dataset(samples, seed=args.seed)
+ loaders = get_loaders(
+ parts, batch_size=args.batch_size, seed=args.seed
+ )
+ model_kwargs = model_kwargs_from_args(args)
+ model = build_model(
+ parts[0], seed=args.seed, model_kwargs=model_kwargs,
+ quantization=args.quantization, loss=args.loss,
+ )
+ trainer, history = fit(
+ model,
+ loaders,
+ epochs=args.epochs,
+ lr=args.lr,
+ weight_decay=args.weight_decay,
+ device=args.device,
+ quantization=args.quantization,
+ )
+ val_scores = trainer.evaluate(loaders[1])
+ y_true, y_prob = predict(model, loaders[2], device=args.device)
+ metrics = summarize_predictions(y_true, y_prob)
+
+ checkpoint = save_checkpoint(
+ output_dir / "pretrained.pt",
+ model,
+ {
+ "stage": "pretrain",
+ "cohorts": [name for name, _ in cohorts],
+ "roots": {name: str(root) for name, root in cohorts},
+ "task": {
+ "points_per_epoch": args.points_per_epoch,
+ "max_epochs": args.task_max_epochs or 1100,
+ },
+ "model": model_kwargs,
+ "quantization": args.quantization,
+ "loss": args.loss,
+ "split_seed": args.seed,
+ "training": {
+ "epochs": args.epochs,
+ "batch_size": args.batch_size,
+ "lr": args.lr,
+ "weight_decay": args.weight_decay,
+ },
+ },
+ metrics,
+ )
+ pd.DataFrame(history).to_csv(
+ output_dir / "training_history.csv", index=False
+ )
+ row = {
+ "cohort": "+".join(name for name, _ in cohorts),
+ "status": "ok",
+ "loss": args.loss,
+ "val_accuracy": float(val_scores.get("accuracy", 0.0)),
+ "checkpoint": str(checkpoint),
+ **metrics,
+ }
+ write_results(
+ output_dir,
+ [row],
+ {
+ "roots": {name: str(root) for name, root in cohorts},
+ "loss": args.loss,
+ "seed": args.seed,
+ },
+ )
+ print_table([row], TABLE_COLUMNS)
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/examples/watchsleepnet/watchsleepnet_quantize.py b/examples/watchsleepnet/watchsleepnet_quantize.py
new file mode 100644
index 0000000000..e79c138f62
--- /dev/null
+++ b/examples/watchsleepnet/watchsleepnet_quantize.py
@@ -0,0 +1,136 @@
+"""Casts a WatchSleepNet checkpoint to fp32, bf16, or fp16 without training.
+
+This example needs no dataset: it loads a bare ``.pt`` state dict or a
+self-describing bundle, casts floating-point tensors, and saves the result.
+Unsupported dtype/device behavior is left to PyTorch; the script reports the
+dtype counts it actually wrote rather than pre-labeling any mode.
+
+Casting a checkpoint does not train a model; it only checks that the PyHealth
+checkpoint path preserves the requested compute dtype.
+
+Command:
+ python examples/watchsleepnet/watchsleepnet_quantize.py \
+ --checkpoint output/watchsleepnet-pretrain/pretrained.pt \
+ --output output/watchsleepnet-pretrain/pretrained_fp16.pt \
+ --quantization fp16
+
+Example output table::
+
+ tensor_dtype count
+ torch.float16 135
+ torch.int64 0
+
+``quantization.csv`` and ``quantization.json`` are written next to ``--output``.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+from collections import Counter
+from pathlib import Path
+
+try:
+ from .watchsleepnet_common import (
+ QUANTIZATION_MODES,
+ load_checkpoint,
+ print_table,
+ quantize_checkpoint,
+ )
+except ImportError:
+ from watchsleepnet_common import (
+ QUANTIZATION_MODES,
+ load_checkpoint,
+ print_table,
+ quantize_checkpoint,
+ )
+
+
+def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
+ """Parses command-line arguments for checkpoint quantization.
+
+ Args:
+ argv: Optional argument list.
+
+ Returns:
+ The parsed namespace.
+
+ Examples:
+ >>> args = parse_args(["--checkpoint", "a.pt", "--output", "b.pt",
+ ... "--quantization", "bf16"])
+ >>> args.quantization
+ 'bf16'
+ """
+ parser = argparse.ArgumentParser(
+ description=__doc__.splitlines()[0],
+ formatter_class=argparse.ArgumentDefaultsHelpFormatter,
+ )
+ parser.add_argument("--checkpoint", required=True, help="input .pt file")
+ parser.add_argument("--output", required=True, help="output .pt file")
+ parser.add_argument("--quantization", required=True,
+ choices=QUANTIZATION_MODES)
+ parser.add_argument("--report", default=None,
+ help="report path; defaults next to --output")
+ return parser.parse_args(argv)
+
+
+def main(argv: list[str] | None = None) -> int:
+ """Loads, casts, saves, and reports a checkpoint.
+
+ Args:
+ argv: Optional argument list.
+
+ Returns:
+ Zero after the cast completes.
+
+ Examples:
+ >>> main(["--checkpoint", "unused.pt", "--output", "out.pt",
+ ... "--quantization", "fp32"]) if False else "ready"
+ 'ready'
+ """
+ args = parse_args(argv)
+ source = Path(args.checkpoint)
+ target = Path(args.output)
+ _, metadata = load_checkpoint(source)
+ quantize_checkpoint(source, target, args.quantization)
+ state, output_metadata = load_checkpoint(target)
+ counts = Counter(str(tensor.dtype) for tensor in state.values())
+ rows = [
+ {"tensor_dtype": dtype, "count": count}
+ for dtype, count in sorted(counts.items())
+ ]
+
+ report = (
+ Path(args.report) if args.report else target.parent / "quantization.json"
+ )
+ report.parent.mkdir(parents=True, exist_ok=True)
+ report.write_text(
+ json.dumps(
+ {
+ "source": str(source),
+ "target": str(target),
+ "quantization": args.quantization,
+ "source_format": output_metadata.get(
+ "source_format", metadata.get("format", "bare-state-dict")
+ ),
+ "dtype_counts": dict(counts),
+ "config": output_metadata.get("config", {}),
+ },
+ indent=2,
+ sort_keys=True,
+ default=str,
+ )
+ + "\n"
+ )
+ csv_path = report.with_suffix(".csv")
+ with open(csv_path, "w") as handle:
+ handle.write("tensor_dtype,count\n")
+ handle.writelines(
+ f"{row['tensor_dtype']},{row['count']}\n" for row in rows
+ )
+ print_table(rows, ("tensor_dtype", "count"))
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/examples/watchsleepnet/watchsleepnet_synthetic_data.py b/examples/watchsleepnet/watchsleepnet_synthetic_data.py
new file mode 100644
index 0000000000..6c22f0e526
--- /dev/null
+++ b/examples/watchsleepnet/watchsleepnet_synthetic_data.py
@@ -0,0 +1,551 @@
+"""Generate synthetic DREAMT, SHHS, or MESA recordings.
+
+The generated tree mirrors the folder and file layout expected by
+:class:`~pyhealth.datasets.DREAMTDataset` and
+:class:`~pyhealth.datasets.NSRRSleepDataset`, but contains deterministic mock
+waveforms and hypnograms. It lets reviewers run the WatchSleepNet pipeline
+without access to the protected source datasets.
+
+DREAMT output::
+
+