Skip to content

Add TaskAug (Raghu et al., CHIL 2022) and PTBXLBinaryClassification, with a PTB-XL MI reproduction - #1598

Open
uiuc-bet wants to merge 5 commits into
sunlabuiuc:masterfrom
uiuc-bet:taskaug
Open

uiuc-bet wants to merge 5 commits into
sunlabuiuc:masterfrom
uiuc-bet:taskaug

Conversation

@uiuc-bet

Copy link
Copy Markdown

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 learnable TaskAugPolicy. It augments only in train mode when labels are present, and it supports binary tasks only. The default backbone is ResNet1D, the paper's 1-D ResNet (kernel 15, channels 32/64/128/256). Any PyHealth model that reads signal also works, e.g. TaskAug(ds, backbone=SparcNet(ds)).
  • TaskAugPolicy has 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_step writes the IFT hypergradient into the policy's .grad. train_taskaug is 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 to target (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 reuses load_ptbxl_record and aggregate_diagnostic_superclasses from pyhealth.tasks.ptbxl. The existing PTB-XL tasks are multilabel at 100/500 Hz, and PTBXLHeartbeatMI works 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_taskaug
  • pyhealth/tasks/ptbxl_binary_classification.py: the task
  • tests/core/test_taskaug.py: 42 tests on synthetic tensors (shapes, gradients, train/eval behaviour, hypergradient against finite differences); the slowest takes 0.12 s
  • tests/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 findings
  • docs/api/models/pyhealth.models.TaskAug.rst, docs/api/tasks/pyhealth.tasks.PTBXLBinaryClassification.rst, and their toctree entries in docs/api/models.rst and docs/api/tasks.rst
  • pyhealth/models/__init__.py, pyhealth/tasks/__init__.py: exports only

How to run:

pytest tests/core/test_taskaug.py tests/core/test_ptbxl_binary_classification.py
# end to end on synthetic data, no download, a few minutes on CPU
python examples/ecg/ptbxl/ptbxl_binary_classification_taskaug.py --synthetic
# real data (PTB-XL v1.0.3)
python examples/ecg/ptbxl/ptbxl_binary_classification_taskaug.py --root <ptb-xl/1.0.3> \
    --experiment main --target MI --seeds 0 1 2 3 4

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):

Arm AUROC AUPRC Paired AUROC gain over no aug (95% CI) Paper AUROC
No augmentation 80.6 ± 0.6 60.4 ± 0.8 80.0 ± 0.8
Time mask 81.0 ± 0.4 60.8 ± 0.8 +0.4 [−0.7, +1.5] 81.1 ± 1.3
Initial policy (not learned) 80.0 ± 0.5 60.3 ± 0.7 −0.5 [−1.3, +0.3] not reported
TaskAug 80.5 ± 0.4 60.5 ± 0.8 −0.0 [−1.4, +1.3] 82.3 ± 0.5

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.

  • Ablation (new; the paper fixes K = 2 and a policy lr of 1e-2): K ∈ {1, 2, 3} × policy lr ∈ {1e-3, 1e-2, 1e-1}, 3 seeds. The best cell (K = 1, lr = 1e-3) scores 82.6 ± 0.8 AUROC against 81.3 ± 0.9 for no augmentation, within noise. Fewer stages tend to do better.
  • Extension (new): a policy learned with the ResNet, transferred frozen to 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.

@github-actions

Copy link
Copy Markdown

Test Coverage

Total: 86.30% (45655 / 52900 lines)

Modified file Coverage Lines
pyhealth/models/__init__.py 100.00% 90 / 90
pyhealth/models/taskaug.py 99.58% 237 / 238
pyhealth/tasks/__init__.py 98.04% 100 / 102
pyhealth/tasks/ptbxl_binary_classification.py 100.00% 43 / 43

Workflow run · 6f3f74b

@solarsys solarsys added the status: manual Pending maintainer's review label Nov 26, 2026
@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 6f3f74b

weights = [w for w, _ in used]
train_grads = [g for _, g in used]

val_loss = model.backbone(**val_batch)["loss"]

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] 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

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] 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,

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

@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 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.ptbxl module that the description doesn't name. PTBXLBinaryClassification imports PTBXL_DIAGNOSTIC_SUPERCLASSES (in __init__) and load_diagnostic_class_map (in __call__). The description lists only load_ptbxl_record and aggregate_diagnostic_superclasses. It also says load_ptbxl_record comes from pyhealth.tasks.ptbxl, but the code imports it from pyhealth.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_step runs 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 transfer alone 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_step raises if every policy parameter is frozen. train_taskaug guards against this, but a clear error or an early return in hyper_step would 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

@solarsys

Copy link
Copy Markdown
Collaborator

Why this PR has status: manual: overlap. Three open PRs add a PTB-XL binary classification task (#1598, #1614, #1664), and two add a TaskAug model (#1598, #1490). A maintainer has to pick one of each.

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

@solarsys

Copy link
Copy Markdown
Collaborator

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:

  • a learned per-class augmentation policy, with K Gumbel-softmax stages over seven operations;
  • trained with the implicit-function hypergradient in a bilevel loop, checked against finite differences in the tests.

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:

  1. Rebase on master. The conflicts are registration lines only.
  2. Fix the AI review's one blocking point: name the shared helpers you reuse (load_diagnostic_class_map, PTBXL_DIAGNOSTIC_SUPERCLASSES) in the description.
  3. Recommended:
    • In hyper_step, save and restore the BatchNorm buffers, since it runs the validation batch in train mode, or document the effect.
    • Raise a clear error when no policy parameter is trainable.
    • Pass weights_only=True to torch.load.
    • Add an Apache-2.0 attribution for the operations adapted from the authors' code.
    • Consider not exporting a generic top-level ResNet1D, since master has ResNet1dBackbone.

Once these fixes are pushed, we'll move this PR to status: automatic and request an AI review. If the review approves, it merges.

uiuc-bet and others added 5 commits November 30, 2026 23:38
- 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.

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.

3 participants