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 5 commits into
Conversation
Test CoverageTotal: 86.30% (45655 / 52900 lines)
|
|
/review |
| weights = [w for w, _ in used] | ||
| train_grads = [g for _, g in used] | ||
|
|
||
| val_loss = model.backbone(**val_batch)["loss"] |
There was a problem hiding this comment.
[medium] hyper_step lets validation batches update BatchNorm running statistics
hyper_step calls model.train() and then runs the validation batch through model.backbone in train mode (line 603). BatchNorm updates running_mean and running_var on every forward pass in train mode, so every policy step mixes validation-batch statistics into the backbone. train_taskaug then saves the backbone state at the end of each epoch, selects the best epoch by validation loss (computed in eval mode with those statistics), and evaluates on test with them. This biases checkpoint selection and makes the reported numbers depend on validation data. Fix: keep the hypergradient forward passes from changing buffers (for example, save and restore BatchNorm buffers around hyper_step, or run the passes with BatchNorm momentum set to 0), and add a test that hyper_step leaves running statistics unchanged. The docstring should state the chosen behaviour.
| sampling_rate: int = 250, | ||
| length: int | None = 2496, | ||
| ) -> None: | ||
| from pyhealth.tasks.ptbxl import PTBXL_DIAGNOSTIC_SUPERCLASSES |
There was a problem hiding this comment.
[medium] Undescribed sharing: PTBXL_DIAGNOSTIC_SUPERCLASSES imported from pyhealth.tasks.ptbxl
The task imports the constant PTBXL_DIAGNOSTIC_SUPERCLASSES from the concrete PTB-XL task module pyhealth.tasks.ptbxl. The description says the task reuses load_ptbxl_record and aggregate_diagnostic_superclasses from that module, but does not mention this constant. PyHealth keeps components self-contained so that changing one does not silently change another. Either add a line to the description that confirms this link and says why (for example, the binary label must use the same superclass list as the existing PTB-XL tasks), or keep the component self-contained by not importing from pyhealth.tasks.ptbxl.
| """ | ||
| from pyhealth.tasks.ptbxl import ( | ||
| aggregate_diagnostic_superclasses, | ||
| load_diagnostic_class_map, |
There was a problem hiding this comment.
[medium] Undescribed sharing: load_diagnostic_class_map imported from pyhealth.tasks.ptbxl
The task imports load_diagnostic_class_map from the concrete PTB-XL task module pyhealth.tasks.ptbxl. The description names only load_ptbxl_record and aggregate_diagnostic_superclasses as reused. PyHealth keeps components self-contained so that changing one does not silently change another. Either add this link to the description with its reason (the same scp_statements.csv mapping as the existing PTB-XL tasks), or keep the component self-contained by not importing it from pyhealth.tasks.ptbxl.
There was a problem hiding this comment.
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.
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 under the same seeds; the ResNet also matches it exactly, with copied weights.hyper_stepwrites the IFT hypergradient into the policy's.grad.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 reusesload_ptbxl_recordandaggregate_diagnostic_superclassesfrompyhealth.tasks.ptbxl. 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,TaskAug,hyper_step,train_taskaugpyhealth/tasks/ptbxl_binary_classification.py: the tasktests/core/test_taskaug.py: 42 tests on synthetic tensors (shapes, gradients, train/eval behaviour, hypergradient against finite differences); the slowest takes 0.12 stests/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.