Skip to content

Add WatchSleepNet and DREAMT sleep staging pipeline - #1648

Open
AishRoopghar wants to merge 2 commits into
sunlabuiuc:masterfrom
AishRoopghar:feature/watchsleepnet-dreamt-final
Open

AishRoopghar wants to merge 2 commits into
sunlabuiuc:masterfrom
AishRoopghar:feature/watchsleepnet-dreamt-final

Conversation

@AishRoopghar

@AishRoopghar AishRoopghar commented Nov 28, 2026 •

Copy link
Copy Markdown

Contributor Information

  • Contributor: Aishwarya Roopghar
  • NetID: ar119
  • University: University of Illinois Urbana-Champaign (UIUC)
  • Course: CS 598 — Deep Learning for Healthcare
  • Project: Final Project — PyHealth Contribution
  • Scope: DREAMT-only partial reproduction of WatchSleepNet with architectural ablations and novel preprocessing extensions.

Summary

This PR extends the WatchSleepNet and DREAMT sleep staging
implementation merged in #1650, rather than introducing
a duplicate model or sequence-level task.

The contribution supports a DREAMT-only partial reproduction
of wearable sleep staging with additional architectural and
preprocessing experiments.

Changes following maintainer review

  • Rebased onto upstream master following the merge of WatchSleepNet model + DREAMTDataset sleep staging task #1650.
  • Removed the duplicate standalone WatchSleepNet implementation
    and sequence-level task.
  • Added an optional residual attention connection to the
    merged WatchSleepNet model.
  • Integrated optional NeuroKit2 preprocessing, context-aware
    IBI extraction, and 100 Hz recording support into the
    existing SleepStagingDREAMT task.
  • Retained the distinct SleepStagingDREAMTEpoch task for
    individual epoch classification.
  • Preserved backward-compatible defaults.
  • Limited dataset changes to cache directory support and
    associated typing and lint corrections.
  • Removed dependency changes from this PR.
  • Added focused tests, documentation, and runnable examples.
  • Documented the model's equal-length batching requirement.

Extensions

Residual attention

An optional residual connection around the existing attention
component. Disabled by default, with no additional trainable
parameters. Tests cover backward compatibility, gradients,
checkpoint compatibility, and causal behavior.

Context-aware IBI extraction

Optional surrounding BVP samples are used during IBI extraction,
followed by cropping to the target epoch. Timestamp continuity
and signal validity checks protect against invalid context.

The extension is disabled by default. Positive context uses
future samples and is intended for retrospective sleep staging.

NeuroKit2 remains optional. Missing dependency errors are
propagated with installation guidance.

Current PR experiments

The WatchSleepNet example includes controlled synthetic
comparisons for residual attention and context-aware IBI
extraction.

Configuration Accuracy Macro F1 REM F1 Kappa
Baseline 0.583 0.246 0.000 0.000
Residual attention 0.583 0.246 0.000 0.000
NeuroKit2, zero context 0.583 0.246 0.000 0.000
NeuroKit2, five-second context 0.583 0.246 0.000 0.000

These short, single-seed synthetic experiments verify
functionality and reproducibility of the configuration switches.
They do not establish a classification performance improvement.

The epoch-level MLP example provides an additional synthetic
dataset-to-training-to-evaluation demonstration.

Historical real-data research evaluation

The following results were obtained using the earlier standalone
research implementation, before consolidation with #1650.
They are retained as course-project research context and are
not claimed as independently reproduced results of the current
consolidated PR.

The DREAMT-only experimental evaluation used 20 participants, including 16 development participants and four reserved independent holdout participants.

Seven experimental configurations were evaluated using five-fold participant-level cross-validation, resulting in 35 fold runs.

Selected cross-validation results:

Configuration Macro F1 (mean ± SD)
Original architecture configuration 0.3022 ± 0.0433
Residual attention 0.3451 ± 0.0453
Without attention 0.3178 ± 0.0390
Without TCN 0.3412 ± 0.0808
Reduced LSTM depth 0.3174 ± 0.0177
Without TCN and attention 0.3331 ± 0.0293
Epoch-level MLP 0.3702 ± 0.0366

The selected experimental model was evaluated on the reserved holdout cohort using 3,046 epochs.

Metric Selected model Majority baseline
Accuracy 0.5489 0.6060
Macro F1 0.3928 0.2516
Weighted F1 0.5317 0.4574
Balanced accuracy 0.3904 0.3333
REM F1 0.1453 0.0000
Cohen's kappa 0.1221 0.0000
AUROC 0.5895 0.5000

The selected model improved six of seven reported metrics over the majority baseline, although overall accuracy was lower. These results are exploratory and do not establish statistical significance or clinical validity.

Testing and validation

  • Targeted local regression suite: 119 tests passed.
  • Targeted implementation statement coverage before the final
    lint-only corrections: 98.14%.
  • Optional dependency absence simulation: 116 passed,
    three expected skips.
  • Public API imports and example CLI checks: passed.
  • Official local contribution checker: passed.
  • Ruff 0.17.6 targeted CI lint verification: passed.
  • GitHub PR contribution-rules check: passed.
  • Full GitHub Python Test workflow: pending at description
    preparation time.

Scope and limitations

  • DREAMT-only partial reproduction; SHHS/MESA pretraining
    is outside the project scope.
  • The current consolidated implementation has not independently
    rerun the historical real-data experiments.
  • Synthetic experiments establish functionality, not clinical
    validity or statistical superiority.
  • WatchSleepNet requires equal-length sequences within a batch.
    Ignoring labels in the loss does not mask padded input epochs.
  • Context-aware preprocessing is retrospective.
  • Restricted participant data and trained checkpoints are not
    included.
  • The complete upstream Sphinx build has not been rerun for
    this revision.

File review guide

Dataset and tasks

  • pyhealth/datasets/dreamt.py — cache directory support.
  • pyhealth/tasks/sleep_staging_dreamt.py — optional preprocessing
    extensions to the merged sequence-level task.
  • pyhealth/tasks/_dreamt_ibi.py — optional NeuroKit2 and
    context-aware extraction helpers.
  • pyhealth/tasks/sleep_staging_dreamt_epoch.py — distinct
    individual epoch classification task.
  • pyhealth/tasks/__init__.py — epoch task registration.

Model

  • pyhealth/models/watchsleepnet.py — optional residual
    attention and batching limitation documentation.

Examples

  • examples/dreamt_sleep_staging_watchsleepnet.py — controlled
    architectural and preprocessing experiments.
  • examples/eeg/sleep_staging/dreamt_sleep_staging_mlp.py —
    epoch-level MLP demonstration.

Tests

  • tests/core/test_dreamt.py
  • tests/core/test_dreamt_ibi.py
  • tests/core/test_dreamt_preprocessing_extensions.py
  • tests/core/test_sleep_staging_dreamt_epoch.py
  • tests/core/test_watchsleepnet_extensions.py

Documentation

  • docs/api/models/pyhealth.models.WatchSleepNet.rst
  • docs/api/tasks/pyhealth.tasks.SleepStagingDREAMT.rst
  • docs/api/tasks/pyhealth.tasks.SleepStagingDREAMTEpoch.rst
  • docs/api/tasks.rst

Checklist

  • Consolidated with the implementation merged in WatchSleepNet model + DREAMTDataset sleep staging task #1650
  • Removed duplicate model and sequence task
  • Retained distinct epoch-level task
  • Preserved backward-compatible defaults
  • Optional dependency handling
  • Focused regression tests
  • Runnable synthetic experiments
  • API documentation
  • Original paper and dataset references
  • GitHub contribution-rules check
  • Full GitHub Python Test workflow
  • Maintainer re-review

@solarsys solarsys added the status: manual Pending maintainer's review label Nov 28, 2026
@github-actions

github-actions Bot commented Nov 28, 2026 •

Copy link
Copy Markdown

Test Coverage

Total: 88.20% (57563 / 65263 lines)

Modified file Coverage Lines
pyhealth/datasets/dreamt.py 94.87% 37 / 39
pyhealth/models/watchsleepnet.py 100.00% 113 / 113
pyhealth/tasks/__init__.py 98.57% 138 / 140
pyhealth/tasks/_dreamt_ibi.py 97.92% 47 / 48
pyhealth/tasks/sleep_staging_dreamt.py 100.00% 174 / 174
pyhealth/tasks/sleep_staging_dreamt_epoch.py 85.71% 96 / 112

Workflow run · 73ae6e1

@solarsys

Copy link
Copy Markdown
Collaborator

/review

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Reviewed commit 2bfe192

Comment thread pyhealth/tasks/sleep_staging_dreamt.py Outdated
continue
try:
signal = self._extract_ibi(epoch_signal)
except Exception as exc: # noqa: BLE001

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[medium] Broad except hides missing NeuroKit2 and silently returns no samples

_extract_ibi raises ImportError when NeuroKit2 is not installed. This except Exception catches it, logs one warning per epoch, and skips every epoch, so SleepStagingDREAMT() returns an empty list instead of failing. The sequence task (sleep_staging_dreamt_sequence.py) re-raises ImportError, and the docs say NeuroKit2 is required. Fix: add except ImportError: raise before this broad handler and add a test that patches the import to fail and expects ImportError.

Comment thread pyhealth/models/watchsleepnet.py Outdated
raise ValueError("A label sequence is longer than its signal sequence.")

# Extract one feature vector for every epoch in the padded batch.
x = signal.reshape(-1, 1, self.segment_length)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[medium] Padded epochs enter BatchNorm, so predictions depend on batch padding

The feature extractor runs on every epoch in the padded batch, including zero-filled padding. Its ResBlock BatchNorm1d layers (lines 45, 57, 70) compute batch statistics and running statistics over padding too. A patient's logits therefore change with the length of the other sequences batched with it, and the description's claim of padding-aware handling does not hold. The example uses batch_size=1 so it is unaffected, but batched training and evaluation are. Fix: run the feature extractor only on the valid epochs (select with the valid-epoch mask, then scatter results back into the padded tensor). Add a test that a sample's logits are identical whether it is batched alone or with a longer sample; the current batch tests do not check this.




if __name__ == "__main__":

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[low] unittest.main() guard sits before later test classes

The if __name__ == "__main__" block is followed by TestDREAMTSequenceDefensiveValidation (line 833). Running the file as a script exits before that class is defined, so its tests are skipped. Move the guard to the end of the file.

Comment thread tests/core/test_watchsleepnet.py Outdated
)


if __name__ == "__main__":

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[low] unittest.main() guard sits before the module-level tests

The if __name__ == "__main__" block is followed by pytest-style test functions and another class. Running the file as a script skips all of them. Move the guard to the end of the file.

signal = debug_batch["signal"][0]
labels = debug_batch["label"]

print("\\nTraining batch diagnostics:")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[low] Literal \n in print output and leftover diagnostics

The strings use \\n, so the output shows a literal backslash-n (also at line 201 and in the results prints). The batch and per-label signal diagnostics (lines 175–210) are debugging output and can be removed or reduced to the results table. The example also uses only synthetic data, so its numbers cannot reproduce the DREAMT MLP results in the description; saying so in the docstring would help.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

AI Review

suggestion: need change
decision: human review

Thank you for this contribution. It adds a DREAMT sleep-staging pipeline: epoch-level and sequence-level tasks, a WatchSleepNet model with ablation options, an end-to-end example, docs and tests. The documentation is thorough, and coverage meets the bar: 87.19% for the whole repository, and every changed file is at or above 80%. The change looks self-contained. The only edit to existing code is an optional cache_dir argument on DREAMTDataset, which is passed to the existing base-class parameter.

To get this merged:

  1. Missing NeuroKit2 is swallowed in the epoch task. In pyhealth/tasks/sleep_staging_dreamt.py, the except Exception around self._extract_ibi(...) in __call__ catches the ImportError raised when NeuroKit2 isn't installed. Every epoch is then skipped with a warning, and the task silently returns no samples. SleepStagingDREAMTSequence already re-raises ImportError. Please add except ImportError: raise before the broad handler here too, and add a test for the missing-dependency path.

Optional suggestions:

  • BatchNorm and padding. In WatchSleepNet.forward, padded epochs go through the feature extractor's BatchNorm1d. In training mode, batch statistics therefore depend on how much padding a batch has. Consider running only the valid epochs through the extractor, or documenting this. A test that checks padding independence in eval mode would also help.
  • Misplaced unittest.main(). In tests/core/test_sleep_staging_dreamt.py and tests/core/test_watchsleepnet.py, the if __name__ == "__main__": unittest.main() guards sit mid-file. Tests defined after them are skipped when the file is run as a script. Please move them to the end of each file.
  • MLP example cleanup. In dreamt_sleep_staging_mlp.py, the prints use a literal "\\n" and there are leftover debug diagnostics. The example also runs on synthetic data only, so it can't reproduce the reported results. Consider saying this in its docstring.
  • Shorter docs. The WatchSleepNet doc page is long. The research-protocol material could move to a separate page or be trimmed.

Reviewed commit 2bfe192

@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 for this pipeline and for the thorough docs and tests. We need to ask for changes, mainly because of overlap.

Why

Three open PRs implement WatchSleepNet on DREAMT: #1645, this one and #1650. PyHealth keeps one implementation per component, so we're taking #1650 as the base for the WatchSleepNet model and the night-level SleepStagingDREAMT task. It's the smallest and only adds new files. Once it merges, this PR can't add a second WatchSleepNet or a second task named SleepStagingDREAMT, but the parts that are new here are welcome.

What to change after #1650 merges (rebase on master first)

  1. Drop the duplicate model. Remove pyhealth/models/watchsleepnet.py, its doc page and tests/core/test_watchsleepnet.py. If your model has options #1650's lacks (your ablation switches, for example), propose them as a focused change to the merged WatchSleepNet, with tests. The padding point below applies to that change.
  2. Rename and narrow the tasks.
    • Your epoch-level task (one sample per 30-second epoch, {"signal": "tensor"} mapped to a multiclass label) is new. Please keep it under its own name, such as SleepStagingDREAMTEpoch, because SleepStagingDREAMT will already exist.
    • SleepStagingDREAMTSequence overlaps #1650's task, which already returns one (T, 750) sequence per night. Keep it only if it does something that task doesn't. If so, say what in the PR description; it may fit better as an option on the existing task.
  3. Fix the AI review's blocking item. In __call__ of the epoch task, the broad except Exception around self._extract_ibi(...) swallows the ImportError raised when NeuroKit2 isn't installed. The task then silently returns no samples. Add except ImportError: raise before it, as SleepStagingDREAMTSequence already does, plus a test for the missing-dependency path.
  4. Move pyproject.toml out of this PR. Any file outside docs/ examples/ pyhealth/ test-resources/ tests/ sends a PR to manual review, and adding a dependency group is a maintainer decision. Please open the dreamt = ["neurokit2>=0.2.10"] extra as its own small PR. Keep the import optional here, with an error message that names the package to install.
  5. Keep the DREAMT dataset diff to cache_dir. The new optional cache_dir argument is fine. The rest of the pyhealth/datasets/dreamt.py diff (+52/−46) and the tests/core/test_dreamt.py diff (+65/−38) is mostly whitespace, quoting and RNG changes to existing code. Please revert those so the diff shows only cache_dir and a test for it. Mention the cache_dir change in the PR description, since it changes an existing component.

Smaller items (from the AI review)

  • WatchSleepNet.forward runs padded epochs through BatchNorm1d, so training-mode statistics depend on how much padding a batch has. Run only the valid epochs through the extractor, or document this, and add an eval-mode test that padding doesn't change the outputs.
  • The if __name__ == "__main__": unittest.main() guards sit in the middle of tests/core/test_sleep_staging_dreamt.py and tests/core/test_watchsleepnet.py. Tests defined after them are skipped when the file is run directly. Please move the guards to the end.
  • examples/eeg/sleep_staging/dreamt_sleep_staging_mlp.py prints a literal "\\n" and still has debug output. It also runs on synthetic data only, so please say in its docstring that it can't reproduce the reported numbers.
  • The WatchSleepNet doc page is long. If the model moves into #1650's implementation, any extra material can go into that page later, briefly.

After this, the PR should touch only new files plus the small cache_dir change, and it can get a normal AI review. Thanks again.

@AishRoopghar

Copy link
Copy Markdown
Author

Thank you, @solarsys for the review and clarification regarding the overlapping contributions.

I am working on the requested changes while awaiting the merge of #1650.

@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.

@AishRoopghar
AishRoopghar force-pushed the feature/watchsleepnet-dreamt-final branch from 2bfe192 to 1526167 Compare November 29, 2026 20:02
@AishRoopghar

Copy link
Copy Markdown
Author

Thank you, @solarsys, for the detailed review and guidance.

I have updated this PR following the merge of #1650:

  • Rebased onto upstream master and removed the duplicate standalone model and sequence-level task.
  • Added optional residual attention to the merged WatchSleepNet model.
  • Integrated optional NeuroKit2 preprocessing, context-aware IBI extraction, and 100 Hz recording support into the existing SleepStagingDREAMT task.
  • Retained the distinct epoch-level task as SleepStagingDREAMTEpoch.
  • Corrected missing optional dependency handling.
  • Limited dataset changes to cache directory support and associated typing and lint corrections.
  • Documented the equal-length batching requirement.
  • Updated the examples, documentation, and focused regression tests.

The optional NeuroKit2 dependency has been moved to a separate PR: #1719.

Local validation completed successfully with 119 regression tests passing. The GitHub contribution-rules check also passed. The full Python CI workflow was still running at the last verification.

The PR description now distinguishes the earlier real-data research results from the synthetic experiments performed with the consolidated implementation.

I would appreciate a re-review when convenient. Thank you again for your guidance.

@AishRoopghar

Copy link
Copy Markdown
Author

/review

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