Repository navigation
Add TaskAug (Raghu et al., CHIL 2022) and PTBXLBinaryClassification, with a PTB-XL MI reproduction - #1598
Add TaskAug (Raghu et al., CHIL 2022) and PTBXLBinaryClassification, with a PTB-XL MI reproduction#1598uiuc-bet wants to merge 8 commits into
Conversation
Test CoverageTotal: 89.37% (65556 / 73356 lines)
|
|
/review |
There was a problem hiding this comment.
Previous review
AI Review
suggestion: need change
decision: human review
Thank you for this contribution. It adds TaskAug (a learned, class-conditioned ECG augmentation policy trained with an implicit-function hypergradient), a ResNet1D backbone, the PTBXLBinaryClassification task, and a PTB-XL reproduction with an ablation and a transfer experiment. The code is well tested, with hypergradient checks against finite differences and resume tests. Coverage is 99.6% for taskaug.py and 100% for the task file, and the whole repository is at 86.3%. Both are above the bar. The docs match the code, and I found no problem with the new TaskAug model or the new task.
To get this merged:
- The task reuses code from the existing
pyhealth.tasks.ptbxlmodule that the description doesn't name.PTBXLBinaryClassificationimportsPTBXL_DIAGNOSTIC_SUPERCLASSES(in__init__) andload_diagnostic_class_map(in__call__). The description lists onlyload_ptbxl_recordandaggregate_diagnostic_superclasses. It also saysload_ptbxl_recordcomes frompyhealth.tasks.ptbxl, but the code imports it frompyhealth.datasets.ptbxl. Please either confirm in the description that sharing these helpers is intended, with a short reason (for example, keeping the superclass labels consistent with the existing PTB-XL tasks), or make the task self-contained by copying them.
Optional suggestions:
hyper_stepruns the validation batch through the backbone in train mode, so BatchNorm running statistics see validation data on each policy step. The docstring says this follows the reference code, so I don't see it as blocking. A sentence in the docs noting the effect on the selected checkpoint would help readers. Alternatively, you could save and restore the BN buffers around that call.- The example's
--experiment transferalone still trains the ResNet TaskAug arm. This is by design, since it supplies the policy being transferred. A line in the example docstring saying so would help. hyper_stepraises if every policy parameter is frozen.train_taskaugguards against this, but a clear error or an early return inhyper_stepwould help direct callers.- The N = 1000 development set is an upper bound, because the patient-level cumulative split can select slightly fewer ECGs. A short note in the docstring would cover this.
Reviewed commit 6f3f74b
|
Why this PR has To help the maintainers decide, please comment here with what your PR does that the others don't, such as fidelity to the paper, results or test coverage. Whichever PR isn't picked can still contribute its unique parts on top of the chosen one. The decision is tracked in #1668. This branch also conflicts with master (registration lines only). |
|
Picked for both the PTB-XL binary task and TaskAug. We compared #1598, #1614, #1490 and #1664. This is the only PR that implements TaskAug as in the paper:
Its binary task matches the authors' labels and produces the paper's 250 Hz, 2,496-sample input. Coverage is 99–100%. Thank you also for reporting honestly that the paper's gain didn't reproduce. Before it can merge:
Once these fixes are pushed, we'll move this PR to |
- hyper_step restores the backbone's buffers, so validation batches no longer update batch norm running statistics; test added. - hyper_step raises ValueError when no policy parameter is trainable. - torch.load(..., weights_only=True) for checkpoints and policies. - Apache-2.0 attribution and list of changes in the taskaug.py header. - ResNet1D is no longer exported from pyhealth.models (master has ResNet1dBackbone); import it from pyhealth.models.taskaug. - Example docstring: N_dev is an upper bound, transfer trains the ResNet TaskAug arm, and the reported runs predate the batch norm change.
|
/review |
There was a problem hiding this comment.
Previous review
AI Review
suggestion: need change
decision: human review
Thank you for this contribution. It adds TaskAug (a learned, class-conditional ECG augmentation policy with an IFT hypergradient), a PTBXLBinaryClassification task, thorough tests, docs, and an honest PTB-XL MI reproduction. The code is well structured. Coverage is 99.6% for taskaug.py and 100% for the task file, and the whole repository is at 89%, so both clear the bar. The finite-difference check of the hypergradient is a nice touch.
To get this merged:
- Reported numbers versus the shipped code. The example docstring says the TaskAug, ablation and transfer results were produced before
hyper_stepstarted restoring batch-norm statistics. The PR description presents those results without that caveat. Please either re-run the affected arms (TaskAug, the hparam grid, the transfer arms) with the current code, or add the same note to the PR description next to the results table, so the numbers are not read as coming from this exact code. - Links to the existing PTB-XL module. The description names the reuse of
load_ptbxl_recordandaggregate_diagnostic_superclasses. The task also importsPTBXL_DIAGNOSTIC_SUPERCLASSESandload_diagnostic_class_mapfrompyhealth.tasks.ptbxl. Please add these to the description with a short reason, or confirm the whole PTB-XL helper reuse is intended and say why. Alternatively, keep the task self-contained by copying them.
Optional suggestions:
- Add a
set_taskintegration test for PTBXLBinaryClassification, as the heartbeat task has. - The real-data split logic in
PTBXLSplitsis untested. A small test on stand-in metadata would help. - The hparam summary leaves out the K=2, lr=1e-2 cell, which is the main TaskAug run. Mentioning it in the table would make the grid complete.
- Skipping finished runs from results.jsonl only checks target and epochs. Including
--n-devand batch size in the match would avoid mixing runs made with different settings.
Reviewed commit b150f5d
|
/review |
There was a problem hiding this comment.
Previous review
AI Review
suggestion: need change
decision: human review
Thank you for this contribution. TaskAug (with its learned policy, IFT hypergradient and training loop), a binary PTB-XL task, and a careful paper reproduction with an ablation and an extension are a valuable addition. The tests are thorough, including a finite-difference check of the hypergradient. Coverage is well above the bar: taskaug.py is at 99.6%, ptbxl_binary_classification.py at 100%, and the whole repository at 89%.
The change is close. One blocking problem remains.
To get this merged:
- Results versus merged code. The example's docstring says the reported runs predate a change to
hyper_step, which now restores batch-norm statistics after the policy step. That change affects the TaskAug and transferred-policy numbers, including the headline finding that the +2.3-point gain does not reproduce. The PR description doesn't mention this, so its results table doesn't describe the code being merged. Please either rerun the TaskAug and transfer arms with the current code and update the tables, or state clearly in the description (and next to the results table) which numbers came from the earlier behavior and how the change may affect them.
Optional suggestions:
- In the PTBXLBinaryClassification docs page, say that the default 250 Hz output needs a dataset built with sampling_rate=500. The docstring already says this.
- You say the operations and the ResNet match the authors' code numerically. Consider adding the check script, or a short note on how to reproduce it.
- ResNet1D resembles the 1-D ResNet already in protoecgnet.py. Copying is fine, and your description explains the paper-specific differences.
Reviewed commit b1d6642
|
/review |
| best_state = None | ||
| step = 0 | ||
| if checkpoint_path is not None and os.path.exists(checkpoint_path): | ||
| state = torch.load( |
There was a problem hiding this comment.
Fixed: torch.set_rng_state(state["rng"].cpu()). I reproduced the error on MPS (TypeError: RNG state must be a torch.ByteTensor). New test: test_resumes_on_an_accelerator trains one epoch with a checkpoint on CUDA or MPS, then resumes. It fails without the fix and is skipped when there is no accelerator.
| sampling_rate: int = 250, | ||
| length: int | None = 2496, | ||
| ) -> None: | ||
| from pyhealth.tasks.ptbxl import PTBXL_DIAGNOSTIC_SUPERCLASSES |
There was a problem hiding this comment.
The sharing is intended: the binary label has to use the same superclass list as the existing PTB-XL tasks. The PR description now names all four shared helpers and gives this reason.
| """ | ||
| from pyhealth.tasks.ptbxl import ( | ||
| aggregate_diagnostic_superclasses, | ||
| load_diagnostic_class_map, |
There was a problem hiding this comment.
Also intended, so the labels come from the same scp_statements.csv mapping as the other PTB-XL tasks. It is now listed in the description, which also corrects where load_ptbxl_record lives (pyhealth.datasets.ptbxl).
| num_stages: Operations applied in sequence (K in the paper). | ||
| temperature: Temperature of the Gumbel-softmax sample. | ||
| mask_width: Fraction of the signal the time mask zeroes; not learned. | ||
| The default is the paper's (the reference code uses 0.05). |
There was a problem hiding this comment.
Fixed. The paper never states TaskAug's mask width. 0.1 is the smallest width it searches for its time-mask baseline. The docstring now calls 0.1 a PyHealth choice and notes that the reference policy uses 0.05, which matches the rst page.
There was a problem hiding this comment.
Previous review
AI Review
suggestion: need change
decision: human review
Thank you for this contribution. It adds TaskAug, a learned class-conditional ECG augmentation policy trained with an IFT hypergradient, plus a record-level PTBXLBinaryClassification task and a PTB-XL reproduction. The tests are thorough, including the finite-difference check of the hypergradient. Coverage is well above the bar: taskaug.py is at 99.6%, ptbxl_binary_classification.py at 100%, and the whole repository at 89.4%. Your results section is also candid about the gain not reproducing. It is close, but two things need attention first.
To get this merged:
- Checkpoint resume on GPU. In
train_taskaug,torch.load(..., map_location=model.device)moves every tensor in the checkpoint to the GPU or MPS device, includingstate["rng"].torch.set_rng_staterequires a CPU ByteTensor, so resuming a run on CUDA or MPS will probably raise an error. Resume is a documented feature, and the example script uses it on GPUs. Please change the call totorch.set_rng_state(state["rng"].cpu()). A test that resumes on a GPU, when one is available, would also help, since the current resume test only runs on CPU. - Undeclared sharing with
pyhealth.tasks.ptbxl.PTBXLBinaryClassificationimportsPTBXL_DIAGNOSTIC_SUPERCLASSESandload_diagnostic_class_mapfrompyhealth/tasks/ptbxl.py. The description names onlyload_ptbxl_recordandaggregate_diagnostic_superclasses. Please either confirm in the description that this sharing is intended and say why, or keep the task self-contained by copying those pieces. Either is fine.
Optional suggestions:
- The
TaskAugPolicydocstring callsmask_width=0.1"the paper's" default. The rst docs and the example present 0.1 as a PyHealth choice and note that the reference code uses 0.05. Making the docstring match would avoid confusion. - The example's docstring implies
--experiment hparamruns only the hparam grid. The script always trains themain/taskaugarm first, because hparam and transfer reuse it. A one-line note would clarify this. - The description says
load_ptbxl_recordlives inpyhealth.tasks.ptbxl, but it is inpyhealth.datasets.ptbxl. - The example docstring says the
taskaugrow and the ablation come from code before the batch-norm restore fix. Rerunning them with the current code, if you can, would make the reported numbers match what ships.
Reviewed commit a1c99d8
| best_state = None | ||
| step = 0 | ||
| if checkpoint_path is not None and os.path.exists(checkpoint_path): | ||
| state = torch.load( |
There was a problem hiding this comment.
Fixed: torch.set_rng_state(state["rng"].cpu()). I reproduced the error on MPS (TypeError: RNG state must be a torch.ByteTensor). New test: test_resumes_on_an_accelerator trains one epoch with a checkpoint on CUDA or MPS, then resumes. It fails without the fix and is skipped when there is no accelerator.
| sampling_rate: int = 250, | ||
| length: int | None = 2496, | ||
| ) -> None: | ||
| from pyhealth.tasks.ptbxl import PTBXL_DIAGNOSTIC_SUPERCLASSES |
There was a problem hiding this comment.
The sharing is intended: the binary label has to use the same superclass list as the existing PTB-XL tasks. The PR description now names all four shared helpers and gives this reason.
| """ | ||
| from pyhealth.tasks.ptbxl import ( | ||
| aggregate_diagnostic_superclasses, | ||
| load_diagnostic_class_map, |
There was a problem hiding this comment.
Also intended, so the labels come from the same scp_statements.csv mapping as the other PTB-XL tasks. It is now listed in the description, which also corrects where load_ptbxl_record lives (pyhealth.datasets.ptbxl).
| num_stages: Operations applied in sequence (K in the paper). | ||
| temperature: Temperature of the Gumbel-softmax sample. | ||
| mask_width: Fraction of the signal the time mask zeroes; not learned. | ||
| The default is the paper's (the reference code uses 0.05). |
There was a problem hiding this comment.
Fixed. The paper never states TaskAug's mask width. 0.1 is the smallest width it searches for its time-mask baseline. The docstring now calls 0.1 a PyHealth choice and notes that the reference policy uses 0.05, which matches the rst page.
|
@solarsys, all the points from your list and from the AI reviews are addressed:
Not done, on purpose:
|
|
/review Generated by Claude Code |
|
|
||
| Findings: | ||
|
|
||
| - The baseline reproduces, but TaskAug's gain does not. Paired by seed, |
There was a problem hiding this comment.
[low] Headline finding rests on pre-change code
The Findings bullet says TaskAug's gain does not reproduce, but line 92 states the taskaug row was measured before the hyper_step change that restores batch-norm statistics, and the size of the shift is unmeasured. The disclosure is clear, so this does not block the merge. Before merging, rerun the taskaug arm (20 seeds) on the merged code, or state in the docstring and PR that this finding is provisional.
| signal = np.pad(signal, ((0, 0), (0, missing))) | ||
| return np.ascontiguousarray(signal, dtype=np.float32) | ||
|
|
||
| def __call__(self, patient: Any) -> list[dict[str, Any]]: |
There was a problem hiding this comment.
[low] No dataset-level test for the task
The tests call the task on stand-in patients and write WFDB files directly, so the event fields and the sampling-rate check are never exercised through PTBXLDataset.set_task. tests/core/test_ptbxl_heartbeat.py builds a PTBXLDataset on synthetic WFDB records and calls set_task, which is the repository's usual pattern. Adding one such test on the existing fixture would cover the integration path.
| return self.relu(out + self.shortcut(x)) | ||
|
|
||
|
|
||
| class ResNet1D(BaseModel): |
There was a problem hiding this comment.
[low] New ResNet1D not explained against existing ResNet1dBackbone
pyhealth/models/protoecgnet.py:136 already has a 1D residual backbone (ResNet1dBackbone). The new ResNet1D differs in its stem (strided conv, no max pool, kernel 15 by default), its channel and block configuration, and its classifier head, so it is not redundant. The description does not mention ResNet1dBackbone, though. Add one sentence saying why the paper's architecture is not built on it.
There was a problem hiding this comment.
AI Review
suggestion: approve
decision: human review
Thank you for this contribution. It adds TaskAug, a learned class-conditional ECG augmentation model with a bilevel training loop, and PTBXLBinaryClassification, a record-level binary PTB-XL task at 250 Hz. It also adds a PTB-XL reproduction example, docs and tests. It looks ready to merge.
What I checked:
- Scope: The change is self-contained. The only edits to existing files are the export lines in the two
__init__.pyfiles and the docs toctrees. These are registration, not changes to shared code. - Shared code: The task's reuse of the PTB-XL label helpers is named in the description with a clear reason. The same goes for using any PyHealth backbone, such as SparcNet, inside TaskAug.
- Tests and coverage: Coverage meets the bar.
taskaug.pyis at 99.6%,ptbxl_binary_classification.pyis at 100%, and the whole repository is at 89.4%. The finite-difference check of the hypergradient and the checkpoint-resume test are good additions. - Docs and results: The docs match the code. Your disclosure that the † rows predate the final
hyper_stepchange is clear and honest.
Optional suggestions:
- The new
ResNet1Dis close to the existingResNet1dBackbone. One sentence in the description on why the paper's variant is needed (kernel 15, stem padding 3) would make that choice clear to readers. - It would help to re-run the † arms with the final
hyper_step. That would confirm the non-reproduction finding on the merged code. - A small test that runs the task through
PTBXLDataset.set_taskon the fixture data would cover the dataset integration. The current tests call the task on stand-in patients.
Reviewed commit 7bcf107
Title: Add TaskAug (Raghu et al., CHIL 2022) and PTBXLBinaryClassification, with a PTB-XL MI reproduction
Contributors:
Contribution Type: Model + Task (paper reproduction)
Paper: Raghu, Shanmugam, Pomerantsev, Guttag, Stultz. Data Augmentation for Electrocardiograms. CHIL 2022, PMLR 174:282–310. https://proceedings.mlr.press/v174/raghu22a.html
Authors' code (Apache-2.0, credited in the module header): https://github.com/aniruddhraghu/ecg_aug
Description:
TaskAug learns a class-conditional ECG augmentation policy by bilevel optimization. The classifier trains on augmented batches. The policy is updated from the unaugmented validation loss through an implicit-function-theorem hypergradient with a Neumann-series inverse-Hessian approximation (Lorraine et al., 2020).
TaskAug(BaseModel)wraps a backbone with a learnableTaskAugPolicy. It augments only in train mode when labels are present, and it supports binary tasks only. The default backbone isResNet1D, the paper's 1-D ResNet (kernel 15, channels 32/64/128/256). Any PyHealth model that readssignalalso works, e.g.TaskAug(ds, backbone=SparcNet(ds)).TaskAugPolicyhas K stages. Each stage picks one of seven ops (time warp, baseline wander, Gaussian noise, time mask, displacement, scaling, no-op) with a Gumbel-softmax sample and applies it with a strength learned separately for each class. The op formulas follow the authors' code. We checked them numerically against that code with a short script that imports the authors'functional.py,warp_ops.pyandmodels.pyand runs both implementations under the same seeds on N(0, 1) signals. The smoothing kernel, wander, noise and mask match exactly; warp, displacement and resampling agree to 4e-3 (float rounding in the grid normalization); the ResNet has the same 4,633,025 parameters and an identical output with copied weights. The script needs the authors' repo, so it is not part of this PR; we can post it here.hyper_stepwrites the IFT hypergradient into the policy's.grad, and restores the backbone's batch norm statistics afterwards, so validation batches never update them.train_taskaugis the training loop: Adam for the classifier, RMSprop for the policy, policy warm-up, keeping the checkpoint with the best validation loss, and optional per-epoch checkpoints with resume. Every arm of the example uses this loop, so the comparison is fair.PTBXLBinaryClassification(BaseTask)turns each PTB-XL record into one binary sample: 1 if any of its diagnostic statements maps totarget(NORM, MI, STTC, CD or HYP). It decimates 500 Hz to 250 Hz and crops or zero-pads to 2496 samples, the paper's input. It deliberately reuses the existing PTB-XL helpers, so its labels come from the same superclass mapping as the other PTB-XL tasks:load_ptbxl_recordfrompyhealth.datasets.ptbxl, andPTBXL_DIAGNOSTIC_SUPERCLASSES,load_diagnostic_class_mapandaggregate_diagnostic_superclassesfrompyhealth.tasks.ptbxl. A change to that mapping changes this task's labels too, which is intended. The existing PTB-XL tasks are multilabel at 100/500 Hz, andPTBXLHeartbeatMIworks on single heartbeats, so none of them gives the paper's record-level binary input.Files to Review:
pyhealth/models/taskaug.py: the ops,TaskAugPolicy,ResNet1D(imported frompyhealth.models.taskaug; not exported frompyhealth.models, which hasResNet1dBackbone),TaskAug,hyper_step,train_taskaugpyhealth/tasks/ptbxl_binary_classification.py: the tasktests/core/test_taskaug.py: 45 tests on synthetic tensors (shapes, gradients, train/eval behaviour, hypergradient against finite differences, batch norm statistics kept byhyper_step, checkpoint resume); the slowest takes 0.13 s on a CPU. One of them resumes a run on a CUDA or MPS device and is skipped without onetests/core/test_ptbxl_binary_classification.py: 9 tests on stand-in patients (labels, resampling, crop/pad, invalid targets)examples/ecg/ptbxl/ptbxl_binary_classification_taskaug.py: the reproduction, the ablation and the extension; the module docstring documents the setup and the findingsdocs/api/models/pyhealth.models.TaskAug.rst,docs/api/tasks/pyhealth.tasks.PTBXLBinaryClassification.rst, and their toctree entries indocs/api/models.rstanddocs/api/tasks.rstpyhealth/models/__init__.py,pyhealth/tasks/__init__.py: exports onlyHow to run:
Results (PTB-XL v1.0.3, MI, a development set of N = 1000 split 80/20 by patient, fold 10 as the test set, 20 seeds, AUROC/AUPRC in %, mean ± SE):
Our baseline matches the paper's, but the paper's +2.3-point TaskAug gain does not reproduce: it lies outside our 95% CI. The paper itself reports that its PTB-XL gains are its smallest and not always significant, over 5 splits. Seed-to-seed SD here is 2.5 points. The example's docstring lists our protocol differences: patient-level splits, normalization fitted on the training set only, and a 10% time mask.
SparcNet, scores 76.4 ± 2.9 AUROC, against 73.0 ± 2.7 for no augmentation and 74.5 ± 2.0 for the initial policy (3 seeds). The direction is right, but the difference is not significant.Related: #1123, an earlier TaskAug PR, was closed without merging. We have not used its code. Going by its description, this PR differs in using the paper's IFT hypergradient (not a first-order approximation), the paper's kernel size and 250 Hz input, and patient-level splits.