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 8 commits into
sunlabuiuc:masterfrom
uiuc-bet:taskaug
Open

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

Conversation

@uiuc-bet

@uiuc-bet uiuc-bet commented Nov 24, 2026 •

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 with a short script that imports the authors' functional.py, warp_ops.py and models.py and 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_step writes the IFT hypergradient into the policy's .grad, and restores the backbone's batch norm statistics afterwards, so validation batches never update them. 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 deliberately reuses the existing PTB-XL helpers, so its labels come from the same superclass mapping as the other PTB-XL tasks: load_ptbxl_record from pyhealth.datasets.ptbxl, and PTBXL_DIAGNOSTIC_SUPERCLASSES, load_diagnostic_class_map and aggregate_diagnostic_superclasses from pyhealth.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, 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 (imported from pyhealth.models.taskaug; not exported from pyhealth.models, which has ResNet1dBackbone), TaskAug, hyper_step, train_taskaug
  • pyhealth/tasks/ptbxl_binary_classification.py: the task
  • tests/core/test_taskaug.py: 45 tests on synthetic tensors (shapes, gradients, train/eval behaviour, hypergradient against finite differences, batch norm statistics kept by hyper_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 one
  • 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):

Which code produced these numbers. Rows marked † (TaskAug, the whole ablation, and the policy transferred to SparcNet) come from the code before this PR's last hyper_step change. In those runs, as in the authors' code, each policy step ran the training batch a second time and one validation batch through the backbone in train mode. That added both to the batch norm running statistics, so about a third of those updates came from validation ECGs. The merged code restores the statistics after each policy step. The running statistics are used to pick the best epoch (by validation loss) and to score the test set. So the † numbers, including the finding that the paper's +2.3-point gain does not reproduce, may shift under the merged code. We expect a small shift, because validation and training ECGs come from the same folds, but we have not measured it. The unmarked rows (no augmentation, time mask, initial policy, and SparcNet with no augmentation or the initial policy) never call hyper_step, so this change does not affect them.

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

github-actions Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

Test Coverage

Total: 89.37% (65556 / 73356 lines)

Modified file Coverage Lines
pyhealth/datasets/ham10000.py 94.48% 137 / 145
pyhealth/graph/cooccurrence.py 100.00% 37 / 37
pyhealth/metrics/__init__.py 100.00% 21 / 21
pyhealth/metrics/fairness_selection.py 100.00% 27 / 27
pyhealth/metrics/group_fairness.py 100.00% 97 / 97
pyhealth/models/__init__.py 100.00% 140 / 140
pyhealth/models/apex_gp.py 95.96% 499 / 520
pyhealth/models/cehrgpt.py 98.31% 116 / 118
pyhealth/models/fedweight.py 98.48% 260 / 264
pyhealth/models/protoecgnet.py 98.18% 377 / 384
pyhealth/models/protoecgnet_h1.py 94.53% 259 / 274
pyhealth/models/protoecgnet_h1_checkpoint.py 87.71% 157 / 179
pyhealth/models/protoecgnet_h1_data.py 88.80% 111 / 125
pyhealth/models/protoecgnet_h1_reference.py 100.00% 153 / 153
pyhealth/models/taskaug.py 99.59% 243 / 244
pyhealth/processors/__init__.py 95.92% 47 / 49
pyhealth/processors/band_power_processor.py 98.80% 82 / 83
pyhealth/processors/vit_embedding_processor.py 89.60% 155 / 173
pyhealth/sampler/__init__.py 100.00% 5 / 5
pyhealth/sampler/group_sampler.py 100.00% 83 / 83
pyhealth/tasks/__init__.py 98.70% 152 / 154
pyhealth/tasks/cehrgpt_omop.py 97.16% 205 / 211
pyhealth/tasks/fedweight_eicu.py 100.00% 91 / 91
pyhealth/tasks/ham10000_malignancy.py 100.00% 42 / 42
pyhealth/tasks/ptbxl_binary_classification.py 100.00% 43 / 43

Workflow run · 7bcf107

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

Previous review

Reviewed commit 6f3f74b

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

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.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.
@solarsys

solarsys commented Dec 1, 2026

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.

Previous review

Reviewed commit b150f5d

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

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:

  1. Reported numbers versus the shipped code. The example docstring says the TaskAug, ablation and transfer results were produced before hyper_step started 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.
  2. Links to the existing PTB-XL module. The description names the reuse of load_ptbxl_record and aggregate_diagnostic_superclasses. The task also imports PTBXL_DIAGNOSTIC_SUPERCLASSES and load_diagnostic_class_map from pyhealth.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_task integration test for PTBXLBinaryClassification, as the heartbeat task has.
  • The real-data split logic in PTBXLSplits is 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-dev and batch size in the match would avoid mixing runs made with different settings.

Reviewed commit b150f5d

@solarsys

solarsys commented Dec 1, 2026

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.

Previous review

Reviewed commit b1d6642

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

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

@jhnwu3

jhnwu3 commented Dec 1, 2026

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.

Previous review

Reviewed commit a1c99d8

best_state = None
step = 0
if checkpoint_path is not None and os.path.exists(checkpoint_path):
state = torch.load(

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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,

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment thread pyhealth/models/taskaug.py Outdated
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).

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

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

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:

  1. 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, including state["rng"]. torch.set_rng_state requires 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 to torch.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.
  2. Undeclared sharing with pyhealth.tasks.ptbxl. PTBXLBinaryClassification imports PTBXL_DIAGNOSTIC_SUPERCLASSES and load_diagnostic_class_map from pyhealth/tasks/ptbxl.py. The description names only load_ptbxl_record and aggregate_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 TaskAugPolicy docstring calls mask_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 hparam runs only the hparam grid. The script always trains the main/taskaug arm first, because hparam and transfer reuse it. A one-line note would clarify this.
  • The description says load_ptbxl_record lives in pyhealth.tasks.ptbxl, but it is in pyhealth.datasets.ptbxl.
  • The example docstring says the taskaug row 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(

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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,

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment thread pyhealth/models/taskaug.py Outdated
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).

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@uiuc-bet

uiuc-bet commented Dec 1, 2026

Copy link
Copy Markdown
Author

@solarsys, all the points from your list and from the AI reviews are addressed:

  • Rebased on master. The conflicts were registration lines only.
  • Shared PTB-XL helpers: the description now names all four (load_ptbxl_record from pyhealth.datasets.ptbxl; PTBXL_DIAGNOSTIC_SUPERCLASSES, load_diagnostic_class_map, aggregate_diagnostic_superclasses from pyhealth.tasks.ptbxl). The reuse is intended, so the labels match the other PTB-XL tasks. Until today the description itself had not been updated; sorry for the repeated flags.
  • BatchNorm in hyper_step: the backbone's buffers are saved and restored, with a test.
  • Frozen policy: hyper_step raises ValueError when no policy parameter is trainable, with a test.
  • Checkpoints: loaded with weights_only=True. Resume on CUDA/MPS is fixed (the RNG state goes back to the CPU), with an accelerator test.
  • Attribution: an Apache-2.0 attribution and a list of our changes are in the taskaug.py header.
  • ResNet1D: no longer exported from pyhealth.models; it is in pyhealth.models.taskaug. We keep our own version, not a reuse of protoecgnet.py's or ResNet1dBackbone, because of the paper's stem (a kernel-15 convolution, padding 3, no max pool).
  • Results: a note right above the results table marks the rows that predate the BatchNorm change (†: TaskAug, the ablation, the transferred policy). It says how they may move, and that the baselines are unaffected. We may rerun those arms and update the tables.
  • Docs and example: a 500 Hz note on the task's docs page; mask_width is described consistently; the example says that every experiment trains main's TaskAug arm and that N = 1000 is an upper bound; skipped runs must now match --n-dev and the batch size.

Not done, on purpose:

  • A set_task integration test: building a PTBXLDataset from WFDB files takes over a second (the heartbeat task's takes 1.46 s), and we keep tests under 1 s. The task's tests call it on stand-in patients.
  • A test for PTBXLSplits: it is example code, not library code.
  • The reference-check script: it imports the authors' repo, so it is not in the PR. The description gives the method and the numbers, and we can post the script here.

solarsys commented Dec 4, 2026

Copy link
Copy Markdown
Collaborator

/review


Generated by Claude Code

@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 7bcf107


Findings:

- The baseline reproduces, but TaskAug's gain does not. Paired by seed,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

@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: 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__.py files 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.py is at 99.6%, ptbxl_binary_classification.py is 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_step change is clear and honest.

Optional suggestions:

  • The new ResNet1D is close to the existing ResNet1dBackbone. 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_task on the fixture data would cover the dataset integration. The current tests call the task on stand-in patients.

Reviewed commit 7bcf107

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.

4 participants