Skip to content

[Dataset + Task + Model] WatchSleepNet sleep stage prediction (Wang et al., 2025) with additional data sources (Sleep-Accel, ISRUC) - #1645

Open
NathanCYee wants to merge 32 commits into
sunlabuiuc:masterfrom
NathanCYee:nyee31_aluoma_watchsleepnet
Open

NathanCYee wants to merge 32 commits into
sunlabuiuc:masterfrom
NathanCYee:nyee31_aluoma_watchsleepnet

Conversation

@NathanCYee

@NathanCYee NathanCYee commented Nov 28, 2026 •

Copy link
Copy Markdown

Contributors

CSE 6250 Team A2

Contribution type

Full Pipeline: Dataset + Task + Model (CSE6250 BD4H Reproducibility Challenge, Fall 2026)

Original 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, in Proceedings of Machine Learning Research 287:145-165 Available from https://proceedings.mlr.press/v287/wang25a.html.

Description

Replicate findings from the WatchSleepNet paper, with processing to downsample and transform ECG and PPG data to inter-beat interval (IBI), train, and evaluate model using IBI to predict 3-class (Wake, NREM, REM) sleep stage.

Extend on paper finds with IBI processing of new datasets (ISRUC, Sleep-Accel) and additional evaluation of model. Perform additional ablation through model quantization (bf16, fp16) both during training and evaluating performance of an already trained quantized model.

Code Changes

Dataset: DREAMT and Sleep-Accel

  • Extend DREAMTDataset with canonical stage mapping, PSG/wearable CSV loading, and an IBI staging default task.
  • Add SleepAccelDataset for PhysioNet Sleep-Accel with cached metadata for labels, heart rate, motion, and steps, plus a heart-rate-based default task.
  • Reuse the NSRR and ISRUC datasets unchanged, with source-reference comments added to the NSRR readers.

Task: SleepStagingIBI*

  • Add five tasks (DREAMT, SHHS, MESA, ISRUC, Sleep-Accel) that produce fixed-length IBI epochs and three-class Wake/NREM/REM labels, masking unknown epochs.
  • Convert ECG, PPG, or heart rate into IBI with configurable epoch size, signal source, and peak backend.

Model: WatchSleepNet

  • Port the paper's CNN + TCN + BiLSTM + attention architecture as a PyHealth model with configurable architecture, precision (fp32/fp16/bf16), and loss function.
  • Support full-recording batches with padding masks and checkpoints compatible with the original implementation.

Examples:

  • Add pretraining, finetuning, quantization, evaluation, and synthetic data generation scripts, with shared training and checkpoint helpers.

Exclusions

Code for an additional dataset (MIT-BIH Polysomnographic Database) was written, however, dataset processing would require a new repository dependency on wfdb version 4.1.0 and above. We have excluded the additional dataset due to the repository-wide impacts of the new dpeendency.

File guide

Dataset

  • pyhealth/datasets/dreamt.py - stage mapping, CSV loading, IBI default task
  • pyhealth/datasets/sleep_accel.py - SleepAccelDataset and file loaders
  • pyhealth/datasets/configs/sleep_accel.yaml - metadata table schema
  • pyhealth/datasets/__init__.py - export SleepAccelDataset
  • pyhealth/datasets/nsrr_sleep.py - source-reference comments

Task

  • pyhealth/tasks/sleep_staging_ibi.py - five IBI staging tasks and helpers
  • pyhealth/tasks/sleep_staging_nsrr.py - source-reference comments
  • pyhealth/tasks/__init__.py - export the five tasks

Model

  • pyhealth/models/watchsleepnet.py - WatchSleepNet and its building blocks
  • pyhealth/models/__init__.py - export WatchSleepNet

Example

  • examples/watchsleepnet/watchsleepnet_common.py - shared CLI, builders, training and checkpoint helpers
  • examples/watchsleepnet/watchsleepnet_pretrain_shhs_mesa.py - pretraining script
  • examples/watchsleepnet/watchsleepnet_finetune.py - finetuning script
  • examples/watchsleepnet/watchsleepnet_quantize.py - checkpoint quantization script
  • examples/watchsleepnet/watchsleepnet_evaluate.py - evaluation script
  • ‎examples/watchsleepnet/watchsleepnet_synthetic_data.py - synthetic data generator for testing examples

Documentation

  • docs/api/datasets/pyhealth.datasets.SleepAccelDataset.rst, docs/api/datasets.rst
  • docs/api/tasks/pyhealth.tasks.SleepStagingIBI*.rst, docs/api/tasks.rst
  • docs/api/models/pyhealth.models.WatchSleepNet.rst, docs/api/models.rst

Tests

  • tests/core/test_dreamt.py - dataset and IBI task tests
  • tests/core/test_isruc.py - IBI task tests
  • tests/core/test_nsrr_sleep.py - SHHS/MESA IBI task tests
  • tests/core/test_sleep_accel.py - Sleep-Accel dataset and task tests
  • tests/core/test_sleep_staging_ibi.py - IBI helper tests
  • tests/core/test_watchsleepnet.py - model tests

Testing

42 new unit tests across six files, all on small synthetic data in temporary directories.

python -m pytest tests/core/test_dreamt.py tests/core/test_isruc.py tests/core/test_nsrr_sleep.py tests/core/test_sleep_accel.py tests/core/test_sleep_staging_ibi.py tests/core/test_watchsleepnet.py -q

Use of original code

The authors' repository github.com/willKeWang/WatchSleepNet_public was used as a reference for the data preprocessing and model structure. We have extended upon it by aligning with PyHealth structure, replicating the data preprocessing on additional datasets, and adding additional configurations for extension and ablation.

@github-actions

github-actions Bot commented Nov 28, 2026 •

Copy link
Copy Markdown

Test Coverage

Total: 87.39% (53005 / 60652 lines)

Modified file Coverage Lines
pyhealth/datasets/__init__.py 100.00% 87 / 87
pyhealth/datasets/dreamt.py 95.52% 64 / 67
pyhealth/datasets/nsrr_sleep.py 100.00% 46 / 46
pyhealth/datasets/sleep_accel.py 78.05% 64 / 82
pyhealth/models/__init__.py 100.00% 107 / 107
pyhealth/models/deephit.py 95.27% 141 / 148
pyhealth/models/watchsleepnet.py 94.25% 213 / 226
pyhealth/tasks/__init__.py 98.35% 119 / 121
pyhealth/tasks/sleep_staging_ibi.py 80.99% 392 / 484
pyhealth/tasks/sleep_staging_nsrr.py 96.15% 125 / 130

Workflow run · 63ee7bb

@NathanCYee NathanCYee changed the title [Dataset + Task + Model] WatchSleepNet sleep stage prediction (Wang et al., 2025) with additional data sources [Dataset + Task + Model] WatchSleepNet sleep stage prediction (Wang et al., 2025) with additional data sources (Sleep-Accel, ISRUC) Nov 28, 2026
@NathanCYee
NathanCYee marked this pull request as ready for review November 28, 2026 17:56
@NathanCYee

NathanCYee commented Nov 28, 2026 •

Copy link
Copy Markdown
Author

@solarsys I see other PRs #1650 and #1648 were opened shortly after this one was created that covers several of the same parts of WatchSleepNet. This one has some more additions with additional datasets and examples. Lets find a way to resolve the conflicts and order the PRs

@NathanCYee

Copy link
Copy Markdown
Author

/review

@solarsys solarsys left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you, Aleksi and Nathan, and thanks for raising the overlap. Your PR was opened first (as a draft), and it covers the most ground: SHHS, MESA, ISRUC and Sleep-Accel, plus pretraining, fine-tuning and quantization. We'd like those additions in PyHealth. Here's the plan and what needs to change.

The plan

Three open PRs implement WatchSleepNet on DREAMT: this one, #1648 and #1650. PyHealth keeps one implementation per component. We're taking #1650 as the base for the WatchSleepNet model and the DREAMT task, because it was ready for review first, it's small enough for the AI review, and it only adds new files. This PR then becomes the home for the parts nobody else has: the IBI tasks for the other cohorts, the Sleep-Accel dataset and the training workflow.

Blocking issues

  1. Too large to review. The diff is about 264,000 characters. The AI review refuses anything over 200,000, so it can't run on this PR. Please split it (suggested split below).
  2. Duplicate model. After #1650 merges, please drop pyhealth/models/watchsleepnet.py and build on the merged WatchSleepNet.
    • It takes a per-night tensor of shape (T, 750) and a (T,) label tensor; feature_key and label_key let you use other field names.
    • Make your IBI tasks produce inputs it accepts, or explain in the description why they can't.
    • If your model has something #1650's lacks (hooks for pretraining and fine-tuning, quantization support), propose it as a focused change to the merged model, with tests.
  3. Duplicate DREAMT task. SleepStagingIBIDREAMT overlaps #1650's SleepStagingDREAMT. Please drop it. If your IBI extraction differs in a way that matters, propose it as an option on the existing task, and say what it changes.
  4. Edits to existing files that aren't needed:
    • pyhealth/datasets/nsrr_sleep.py and pyhealth/tasks/sleep_staging_nsrr.py: the changes are only comments linking to the original repo. Please revert them; the links can go in your new files or the example README.
    • pyhealth/datasets/dreamt.py:
      • Move DREAMT_STAGE_MAPPING, map_dreamt_stages and load_dreamt_frame into your task module. They're task-side helpers, and sleep_staging_ibi.py already imports them lazily.
      • Drop the new default_task property. Changing an existing dataset's default task is a separate decision.
      • Drop the Optional[...] to X | None rewrite.
    • The get_patient_file rewrite fixes a real bug: an undefined variable when the folder name is unexpected. It also changes the return value from Path to str. Please send it as its own small PR with a test. It's useful on its own, but it isn't part of WatchSleepNet.
    • tests/core/test_dreamt.py, test_isruc.py and test_nsrr_sleep.py: please leave the existing tests and their helpers untouched, and put the new tests in new files, as you already do in test_sleep_staging_ibi.py.
  5. Shared private helpers. The IBI tasks import private helpers from other task modules: _read_edf_channels, _read_stage_codes, CHANNEL_ALIASES and LABEL_SCHEMES from sleep_staging_nsrr, and helpers from sleep_staging_isruc. The AI review blocks sharing between components unless the PR description names it and gives a reason. Please add that sentence, or copy the pieces you need.

Also, please fix

  • peak_backend="auto" uses biosppy or neurokit2 when they're installed, neither of which PyHealth depends on, and falls back to scipy otherwise. The same code can then give different IBIs on different machines. Please default to "scipy" and let users opt in to the others.

Suggested split, after #1650 merges

  1. The IBI tasks for SHHS, MESA and ISRUC, producing inputs the merged WatchSleepNet accepts, with their tests in new files and one short example.
  2. The Sleep-Accel dataset (sleep_accel.py, its config, docs and test) and SleepStagingIBISleepAccel.
  3. The pretraining, fine-tuning, evaluation and quantization examples, plus any model additions from item 2 above.

Each part then fits under the review limit and touches only new files plus the __init__.py and docs registrations, so it can go through the automatic AI review. Once you've split it, you can close this PR or repurpose it as the first part. Thank you, and sorry for the extra work. The additional cohorts are the most valuable part of this PR.

@NathanCYee

Copy link
Copy Markdown
Author

Thank you for the review @solarsys. PR #1650 creates DREAMT sleep staging as its own isolated task while this PR creates a generalized sleep staging task that can also be applied to NSRR data (SHHS, MESA), ISRUC, and Sleep-Accel.

The shared core task structure would be more extensible than a dedicated task per dataset. Can we re-evaluate which sleep staging task we should pick for a final merge, or have both present instead of depending on the other task implementation?

@solarsys

Copy link
Copy Markdown
Collaborator

#1650 (WatchSleepNet and the DREAMT SleepStagingDREAMT task) has merged. You can now rebase on master and reduce this PR to the parts listed in the review above, building on the merged WatchSleepNet.

@NathanCYee

Copy link
Copy Markdown
Author

Thanks for the update @solarsys.

I have made a few changes to resolve the points raised in no 4.

Regarding no 1 on the commit size. We are completing this PR for a final class project in CSE 6250, which requires us to raise a PR with our contributions. We wanted to implement a full pipeline with dataset + task + model + examples, but since the model was added after our PR was implemented this has complicated things that I need to verify with my grader. I am not sure if multiple PRs can be graded as a part of this class.

Regarding the merge, My partner and I will evaluate what has to change as I will be unavailable. We will stage it as a PR on my fork and merge it into this branch.

@NathanCYee

Copy link
Copy Markdown
Author

Hi @solarsys,

I compared the model that is on master with my PR and the published code for the WatchSleepNet paper. Both models deviate from the original paper, but the model on the master branch made several changes to the paper's implementation that aren't on this PR. Since you already approve of the deviated model, I would like to ask how to proceed with reusing the model or updating it. Should the structure of the model be updated to align closer with the paper (which may be a breaking change)?

Component Paper Upstream master PR #1645
Module layout feature_extractor / tcn / lstm_layer / classifier L242 resnet / collapse / tcn / lstm / attention / fc L208 same names as paper L482
Input channels 1 channel via num_features L242 num_input_channels (default 1), 3-D or 4-D input L173 hardcoded 1 channel L654
Per-epoch stem Conv1d(1→16, k=7, s=1, p=3) + ReLU L64 none; first residual block sees raw input L202 same as paper L136
Residual conv k=3, bias=False L8 k=5, bias=True L52 k=3, bias=False L48
Residual normalization BN→ReLU→Dropout(0.2) after each conv L18 BN→ReLU only, no dropout L68 BN→ReLU→Dropout(0.2) L64
Residual add x += residual after dropout, no post-add activation L51 relu(out + shortcut(x)) L70 x + residual, no post-add activation L123
Stride schedule four stride-4 blocks, 32/64/128/256 L73 (5, 5, 5, 2), 32/64/128/256 L174 four stride-4 blocks L146
Per-epoch collapse final_conv(256→256, k=3, s=4) + flatten L80 Linear(final_len→1) over time L214 same as paper L164
TCN width num_channels L246 res_channels[-1]; no num_channels arg L209 num_channels L491
TCN padding symmetric (k-1)*d//2, non-causal L106 causal left pad L100 symmetric, non-causal L217
TCN block conv→BN→ReLU→Dropout, no residual, dilation 1/2/4 L99 two convs→ReLU→Dropout, residual add, no BN L106 conv→BN→ReLU→Dropout, no residual L206
LSTM packed pack_padded_sequence L158 unpacked L271 packed L304
LSTM dropout none L134 dropout=0.2 L231 none L272
Attention mask key_padding_mask from lengths L173 no padding mask; optional causal attn_mask L272 key_padding_mask L327
Classifier Linear(hidden*2 → C) L271 Linear(out_dim → C), out_dim depends on bidirectional L233 Linear(hidden*2 → C) L516
Forward signature forward(x, lengths) L273 forward(**kwargs) L305 forward(**kwargs) L611
Lengths required L273 not used L305 explicit lengths or trailing-zero inference L586
Loss external CrossEntropyLoss in engine.py compute_loss with class_weights, focal_gamma, ignore_index=-100 L281 ce / weighted_ce / focal / inverse_focal L569
Outputs logits (B, T, C) L291 logits + full y_prob / y_true (B, T, ·) L305 logits + flattened valid y_prob / y_true L696
Label processor / metrics N/A (external engine) inherits BaseModel; empty for tensor targets L113 MultiClassLabelProcessor override L526
Quantization none none fp32 / fp16 / bf16 L518
State dict feature_extractor.*, tcn.layers.*, lstm_layer.*, classifier.* _dummy_param, resnet.*, collapse.*, tcn.*, lstm.*, attention.*, fc.* L208 same as paper; _dummy_param deleted L427
Parameters (3-class default) 8,456,131 9,501,095 8,456,131

@NathanCYee

Copy link
Copy Markdown
Author

The DREAMT tasks also process different subsets of the dataset. The master's merged SleepStagingDREAMT pulls from the 64hz DREAMT data while this branches SleepStagingIBIDREAMT pulls from the 100Hz DREAMT data.

The 100Hz subset processing on this PR aligns with how the authors of the WatchSleepNet paper processed the DREAMT data. Since the files don't conflict, maybe we can keep both of the processing tasks and rename them to be clear that one processes 100Hz data while the other processes 64Hz data.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

status: manual Pending maintainer's review

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants