Repository navigation
Add wav2sleep model and multi-signal sleep staging task - #1727
Conversation
Test CoverageTotal: 89.44% (69268 / 77448 lines)
|
|
Why this PR has To make it eligible: drop |
Thanks, done. mesa.py is gone, along with its config, docs page and index entries, so the PR no longer touches pyhealth/datasets. MultiSignalSleepStaging now runs on NSRRSleepDataset(cohort="mesa"). The only gap was the label format: NSRRSleepDataset points to the profusion XML, and our reader only handled the NSRR-harmonized XML. I updated read_nsrr_stages to read both, so NSRRSleepDataset didn't need any changes and there's no separate PR. I also added a test that runs the task through NSRRSleepDataset on synthetic files. |
|
Good news: the reasons this PR had |
|
/review |
There was a problem hiding this comment.
Previous review
AI Review
suggestion: need change
decision: need change
Thank you for this contribution. It adds a Wav2Sleep model, a whole-night multi-signal sleep staging task, and an example with three ablations. The model code looks careful and well tested. Coverage meets the bar: the repository total is 88.39%, wav2sleep.py is 99.42% and multi_signal_sleep_staging.py is 97.96%. The change is close, but the diff and the description don't match yet.
To get this merged:
- Missing dataset files. The description lists
MESADataset,pyhealth/datasets/mesa.py,configs/mesa.yaml,tests/core/test_mesa.pyanddocs/api/datasets/pyhealth.datasets.MESADataset.rst. None of them are in the diff. The example and tests use the existingNSRRSleepDatasetinstead, andtests/core/test_multi_signal_sleep_staging.pyis in the diff but isn't listed in the description. Please either add the MESA dataset files with tests, docs and a source link (https://sleepdata.org/datasets/mesa), or update the description, testing commands and file list to match what the diff contains. - Use of
NSRRSleepDataset. The example, the task docs and the tests depend onNSRRSleepDataset, including itsprepare_metadatamethod. The description doesn't mention this. Please say in the description that the dependency is intended and why, or make the component self-contained. Both are fine. - Overlap with the existing NSRR task.
MultiSignalSleepStagingrepeats much of the existingSleepStagingCardioRespiratory(NSRR channel reading, resampling, z-scoring, class mapping). The description mentions #1425 but doesn't explain why this separate task is needed. Please state the difference clearly, for example whole-night samples with native-rate EDF reading, and why it can't be an option of the existing task. - Truncated EDF handling.
read_edf_channelsraisesValueErroron a truncated file, and__call__doesn't catch it. One bad night would abortset_task. This also contradicts the description's claim that partial downloads work. Please catch the error, log a warning and skip that night, and add a test.
Optional suggestions:
- The example silently reuses an existing
wav2sleep_fixed.ptfrom--outin the corruption experiment. A log message or a flag would avoid stale results. - The example's docstring says "a few minutes" on CPU, while the description says about a minute. Please make them agree.
- The example helpers (
corrupt,evaluate) have no tests. A small test would help.
Reviewed commit b9f54d5
|
The description now matches the diff. It lists no dataset files and does list the new tests. It also says the NSRRSleepDataset dependency is intended, and explains why this is a separate task from SleepStagingCardioRespiratory: it makes one sample per whole night with a label per epoch, and it keeps nights with a missing signal instead of skipping them. Adding that as an option would give the existing task two schemas. A night with a missing, truncated or malformed file is now skipped with a warning, and there's a test for it through call. I also did the optional ones. The corruption run only reuses a checkpoint trained with the same settings, the runtime says about 2 minutes in both places, and corrupt and evaluate have tests. |
|
/review |
There was a problem hiding this comment.
Previous review
AI Review
suggestion: need change
decision: need change
Thank you for this contribution. It adds a Wav2Sleep model and a whole-night MultiSignalSleepStaging task on top of NSRRSleepDataset. It also adds an example with three ablations, docs and tests. The PR is well organised. It explains why the task is separate from SleepStagingCardioRespiratory, and it says clearly how the example uses NSRRSleepDataset. Coverage is above the bar: wav2sleep.py is at 99.4%, multi_signal_sleep_staging.py at 98.0%, and the whole repository at 88.4%.
To get this merged:
- In
examples/mesa_sleep_staging_wav2sleep.py,corrupt(..., "dropout_second_half")zeroesx[:, n_epochs // 2:]. Heren_epochs = x.shape[1]is the padded length of 1200 epochs, not the length of the recorded night. For a night shorter than 10 h, this drops the ECG from epoch 600 onward. That is not the second half of the night (for a night of about 800 epochs it is only the last quarter). So the docstring text "ECG lost, second half", the 0.280 → 0.144 result and the PR description don't match what the code does. Please either compute the midpoint from the scored or recorded epochs of each night (for example from the labels, or from where the padding starts), or reword the experiment and its docs to say "ECG lost from epoch 600 of the padded night". If you change the code, please re-run or re-check the reported numbers. The flat-line corruption is also applied over the padded array. The docs should say whether that is intended.
Optional suggestions:
SingleSignalWav2Sleepwithuse_signals=["ecg"]raises a ValueError on any batch that contains a night with no ECG. This is fine for your 500 MESA nights, but a note or a filter would make the baseline more robust.- The checkpoint-reuse logic in
corruption_experimentis untested. A small test could cover it. - The task docstring describes
output_schemaslightly differently from the actual("tensor", {"dtype": torch.long})tuple. - #1688 adds an SHHS multimodal sleep staging task. A one-line statement in the description of how this task differs from it, such as the MESA/NSRR scope and the whole-night samples, would help maintainers.
Reviewed commit 1c628c3
…rlap, harden readers and inputs
|
/review |
| def setUp(self): | ||
| self._tmp = tempfile.TemporaryDirectory(ignore_cleanup_errors=True) | ||
| out = Path(self._tmp.name) | ||
| self.dataset = TestEvaluate.dataset |
There was a problem hiding this comment.
[low] TestCheckpointReuse depends on another test class's setUpClass
self.dataset = TestEvaluate.dataset only works if TestEvaluate.setUpClass has already run. Selecting this class alone (for example pytest ...::TestCheckpointReuse) or running it under a different order or parallel runner raises AttributeError. Build the small dataset inside this class's setUp, or move the shared dataset construction to a module-level helper that both classes call.
| def __init__( | ||
| self, | ||
| signals: tuple[str, ...] = ("ecg", "ppg", "abd", "thx"), | ||
| channels: Mapping[str, str] | None = None, |
There was a problem hiding this comment.
[low] channels argument has no test
The description advertises channel names as arguments so the task fits other NSRR cohorts, but no test passes a channels mapping. Every test uses the MESA defaults. Add a test that writes an EDF with renamed channel labels, passes the matching channels mapping, and checks that the signal is read from the renamed channel.
There was a problem hiding this comment.
AI Review
suggestion: approve
decision: approve
Thank you for this contribution, and for the detailed description. It adds a Wav2Sleep model, a whole-night MultiSignalSleepStaging task, docs, tests and an example with three ablations. The model follows the paper's design. The task reads the EDF channels at their native rates, handles missing channels as all-NaN, and skips bad nights with a warning. The description also explains why this is a separate task from SleepStagingCardioRespiratory and SHHSMultimodalSleepStaging.
It looks ready to merge. The diff is complete and matches the description. The links to NSRRSleepDataset, BaseModel, BaseTask and the label processors are either named in the description or are shared base code. Coverage meets the bar:
- wav2sleep.py: 99.4%
- multi_signal_sleep_staging.py: 97.5%
- whole repository: 89.4% (bar is 60%)
Optional suggestions:
- TestCheckpointReuse in tests/core/test_mesa_sleep_staging_example.py uses TestEvaluate.dataset, which only exists after that class's setUpClass has run. Running it alone would fail. Building its own small dataset in setUp would fix this.
- The channels override for other NSRR cohorts has no test. A short test with renamed channels would cover it.
- The module docstring of the example is long. The results tables could move to the docs page, which would keep the script's header short.
Reviewed commit 375f18f
Contributors:
University of Illinois Urbana-Champaign, CS 598 DL4H, Fall 2026, Team T20.
Contribution Type: New Task + new Model, built on the existing
NSRRSleepDataset.Paper: Jonathan F. Carter and Lionel Tarassenko. wav2sleep: A Unified Multi-Modal Approach to Sleep Stage Classification from Physiological Signals. Proceedings of the 4th Machine Learning for Health Symposium, PMLR 259:186–202 (2025). https://proceedings.mlr.press/v259/carter25a.html (authors' code: https://github.com/joncarter1/wav2sleep, MIT)
Description:
wav2sleep stages every 30 s epoch of a night from any subset of the cardio-respiratory signals ECG, PPG and abdominal and thoracic respiratory effort (ABD, THX). That lets one model be trained across sleep cohorts that recorded different signals. This PR adds the two pieces needed to reproduce it in PyHealth, on top of the existing
NSRRSleepDataset(cohort="mesa"):MultiSignalSleepStagingtask: prepares each night as in the paper.NSRRSleepDatasetindexes (the NSRR-harmonized*-nsrr.xmlformat also works), and maps them to 4 classes (W, light, deep, REM) or 5 classes. Unscored and padded epochs are-1.set_task.read_edf_channels) rather than the private_read_edf_channelsinsleep_staging_nsrr.py. Ours keeps the exact channel labels so channel names can be passed per cohort, returns float64, and raises on a truncated file so the task can skip that night instead of training on part of it.Wav2Sleepmodel (BaseModel), with the paper's defaults:EpochMixertransformer with a CLS token that attends only to the signals present in each night (key-padding mask);SequenceMixerof dilated convolutions (dilations 1–32, two blocks).masking="fixed"with the paper's probabilities, or"subset"/"none"), plus random polarity inversion.use_signals=[...]evaluates a trained model on any subset of its signals. An unknown signal name or a label>= n_classesraises a clearValueError.tensor(-1ignored). The model supplies a multiclass label processor, asDeepSleepNetdoes, soTrainerscores every scored epoch (metrics=["accuracy", "cohen_kappa"]).Uses the existing
NSRRSleepDataset(intended): MESA is already covered byNSRRSleepDataset(cohort="mesa")from #1425, so this PR adds no dataset and doesn't changeNSRRSleepDataset. The task only needs each event'ssignal_file(EDF) andlabel_file(XML), whichNSRRSleepDatasetprovides. The example uses itsprepare_metadatato build the MESA index, then writes a smaller copy of that index to train on a subset of nights.Why a separate task from
SleepStagingCardioRespiratory(#1425): both read NSRR EDF channels, resample them to 1024/256 points per 30 s and use the same 4 classes. The outputs differ in ways that would change the existing task's schema and behaviour, not just add an option:SleepStagingCardioRespiratoryMultiSignalSleepStaging(1200, points)per signalmulticlass)-1for unscored or padding (tensor)wav2sleep needs the second column. Its sequence mixer looks across the whole night, so it needs whole-night samples. And it's trained on nights that recorded different signals (e.g. SHHS has no PPG), so a missing signal must be marked unavailable rather than dropping the night. Adding this as an option would give
SleepStagingCardioRespiratorytwo different input and output schemas, so we kept it as a separate task. And fromSHHSMultimodalSleepStaging(#1688): that task also marks missing signals, but it makes one sample per epoch with one label, supports only ECG, ABD and THX (SHHS has no PPG), and uses fixed SHHS channel names. Ours makes one sample per whole night, adds PPG, and takes the channel names as arguments, so it fits MESA and other NSRR cohorts. A per-night mode there would change its schema in the same way. Neither #1425 nor #1688 adds the wav2sleep model. Our task lives inmulti_signal_sleep_staging.pyso it doesn't collide withsleep_staging_nsrr.py; no existing files are changed apart from index entries.Example and ablations (
examples/mesa_sleep_staging_wav2sleep.py): the full pipeline, from dataset to task toTrainerto evaluation on each input set. It adds three ablations that are not in the paper:Without
--root, it writes synthetic nights and runs all three ablations in a few minutes (about 2 with a GPU, about 5 on a CPU). Results on 500 MESA nights are in its module docstring and summarized below. They were produced with an earlier version of the script that read the NSRR-harmonized (*-nsrr.xml) stage annotations instead of the profusion filesNSRRSleepDatasetindexes; the task's preprocessing and the model are unchanged. The data has since been deleted under the NSRR data use agreement, so they can't be re-run with the current version.Results (500 MESA nights, 350/49/101 train/val/test split by participant, one RTX 5070 Ti):
Cohen's κ on the test set, by the signals given to the model:
Each number is one training run. Two runs of the same setting differed by 0.013 κ.
The paper trains on about 10,000 nights from seven cohorts with batch size 16. We use 350 MESA nights with batch size 2, which is the most that fits a 16 GB GPU at 10 h per night, so absolute κ is lower than the paper's.
Files to Review:
pyhealth/models/wav2sleep.py: the model (SignalEncoder,EpochMixer,SequenceMixer,Wav2Sleep)pyhealth/tasks/multi_signal_sleep_staging.py: the task, plus theread_edf_channelsandread_nsrr_stageshelperstests/core/test_wav2sleep.py: model tests (shapes, gradients, masking, missing signals, input errors, state-dict round trip, Trainer)tests/core/test_multi_signal_sleep_staging.py: task tests, including one throughNSRRSleepDataset(cohort="mesa")and the skip paths for bad files, on tiny synthetic EDF and XML files written to a temporary directorytests/core/test_mesa_sleep_staging_example.py: tests for the example'scorrupt,evaluateandwith_signalhelpers, and for reusing or retraining the saved checkpointexamples/mesa_sleep_staging_wav2sleep.py: the full pipeline and ablations. The corruption experiment reuses the saved model only if it was trained with the same settings, and logs which it diddocs/api/models/pyhealth.models.Wav2Sleep.rst,docs/api/tasks/pyhealth.tasks.MultiSignalSleepStaging.rst: new docs pagesdocs/api/{models,tasks}.rstandpyhealth/{models,tasks}/__init__.py: index and import entries (one entry each)Testing:
python -m pytest tests/core/test_wav2sleep.py tests/core/test_multi_signal_sleep_staging.py tests/core/test_mesa_sleep_staging_example.py python examples/mesa_sleep_staging_wav2sleep.py # synthetic, a few minutes python examples/mesa_sleep_staging_wav2sleep.py --root /path/to/nsrr/mesa --max-nights 500All tests use synthetic data. The three test files (50 tests) run in about 20 s on a CPU; the slowest test (the task through
NSRRSleepDataset) takes about 2.5 s. No NSRR data is included in this PR. MESA requires an approved NSRR data use agreement.