Repository navigation
Add WatchSleepNet and DREAMT sleep staging pipeline - #1648
AishRoopghar wants to merge 2 commits into
Conversation
Test CoverageTotal: 88.20% (57563 / 65263 lines)
|
|
/review |
| continue | ||
| try: | ||
| signal = self._extract_ibi(epoch_signal) | ||
| except Exception as exc: # noqa: BLE001 |
There was a problem hiding this comment.
[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.
| 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) |
There was a problem hiding this comment.
[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__": |
There was a problem hiding this comment.
[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.
| ) | ||
|
|
||
|
|
||
| if __name__ == "__main__": |
There was a problem hiding this comment.
[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:") |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
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:
- Missing NeuroKit2 is swallowed in the epoch task. In
pyhealth/tasks/sleep_staging_dreamt.py, theexcept Exceptionaroundself._extract_ibi(...)in__call__catches theImportErrorraised when NeuroKit2 isn't installed. Every epoch is then skipped with a warning, and the task silently returns no samples.SleepStagingDREAMTSequencealready re-raisesImportError. Please addexcept ImportError: raisebefore 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'sBatchNorm1d. 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(). Intests/core/test_sleep_staging_dreamt.pyandtests/core/test_watchsleepnet.py, theif __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
left a comment
There was a problem hiding this comment.
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)
- Drop the duplicate model. Remove
pyhealth/models/watchsleepnet.py, its doc page andtests/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 mergedWatchSleepNet, with tests. The padding point below applies to that change. - 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 asSleepStagingDREAMTEpoch, becauseSleepStagingDREAMTwill already exist. SleepStagingDREAMTSequenceoverlaps #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.
- Your epoch-level task (one sample per 30-second epoch,
- Fix the AI review's blocking item. In
__call__of the epoch task, the broadexcept Exceptionaroundself._extract_ibi(...)swallows theImportErrorraised when NeuroKit2 isn't installed. The task then silently returns no samples. Addexcept ImportError: raisebefore it, asSleepStagingDREAMTSequencealready does, plus a test for the missing-dependency path. - Move
pyproject.tomlout of this PR. Any file outsidedocs/ examples/ pyhealth/ test-resources/ tests/sends a PR to manual review, and adding a dependency group is a maintainer decision. Please open thedreamt = ["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. - Keep the DREAMT dataset diff to
cache_dir. The new optionalcache_dirargument is fine. The rest of thepyhealth/datasets/dreamt.pydiff (+52/−46) and thetests/core/test_dreamt.pydiff (+65/−38) is mostly whitespace, quoting and RNG changes to existing code. Please revert those so the diff shows onlycache_dirand a test for it. Mention thecache_dirchange in the PR description, since it changes an existing component.
Smaller items (from the AI review)
WatchSleepNet.forwardruns padded epochs throughBatchNorm1d, 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 oftests/core/test_sleep_staging_dreamt.pyandtests/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.pyprints 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.
|
#1650 (WatchSleepNet and the DREAMT |
2bfe192 to
1526167
Compare
|
Thank you, @solarsys, for the detailed review and guidance. I have updated this PR following the merge of #1650:
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. |
|
/review |
Contributor Information
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
and sequence-level task.
merged WatchSleepNet model.
IBI extraction, and 100 Hz recording support into the
existing SleepStagingDREAMT task.
individual epoch classification.
associated typing and lint corrections.
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.
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:
The selected experimental model was evaluated on the reserved holdout cohort using 3,046 epochs.
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
lint-only corrections: 98.14%.
three expected skips.
preparation time.
Scope and limitations
is outside the project scope.
rerun the historical real-data experiments.
validity or statistical superiority.
Ignoring labels in the loss does not mask padded input epochs.
included.
this revision.
File review guide
Dataset and tasks
pyhealth/datasets/dreamt.py— cache directory support.pyhealth/tasks/sleep_staging_dreamt.py— optional preprocessingextensions to the merged sequence-level task.
pyhealth/tasks/_dreamt_ibi.py— optional NeuroKit2 andcontext-aware extraction helpers.
pyhealth/tasks/sleep_staging_dreamt_epoch.py— distinctindividual epoch classification task.
pyhealth/tasks/__init__.py— epoch task registration.Model
pyhealth/models/watchsleepnet.py— optional residualattention and batching limitation documentation.
Examples
examples/dreamt_sleep_staging_watchsleepnet.py— controlledarchitectural and preprocessing experiments.
examples/eeg/sleep_staging/dreamt_sleep_staging_mlp.py—epoch-level MLP demonstration.
Tests
tests/core/test_dreamt.pytests/core/test_dreamt_ibi.pytests/core/test_dreamt_preprocessing_extensions.pytests/core/test_sleep_staging_dreamt_epoch.pytests/core/test_watchsleepnet_extensions.pyDocumentation
docs/api/models/pyhealth.models.WatchSleepNet.rstdocs/api/tasks/pyhealth.tasks.SleepStagingDREAMT.rstdocs/api/tasks/pyhealth.tasks.SleepStagingDREAMTEpoch.rstdocs/api/tasks.rstChecklist