Repository navigation
[BTY-38] TarDiff: official noise schedule, v-prediction and guidance - #1578
Conversation
Opt-in TarDiff options (defaults keep the merged behaviour): - beta_schedule="scaled_linear": Latent Diffusion's betas, as in TarDiff's official code (T=200, 5e-4 to 0.1). - prediction="v": v-prediction, accurate at the noisiest steps, where eps errors are amplified by 1/sqrt(abar). - generate(guide_on_x0=True, cosine=True): guidance as the official code does it (cosine between the guide's gradient on the clean-series estimate and G). - load_model accepts checkpoints saved before these options. PTBXLHeartbeatMI drops beats cut by the record's edges, which max_beats_per_record would otherwise mostly keep. The PTB-XL example uses the official schedule, v-prediction and official guidance by default, names checkpoints after the data and settings, and reports tardiff_selected with the guidance scale picked on validation.
Test CoverageTotal: 86.32% (45896 / 53170 lines)
|
|
/review |
There was a problem hiding this comment.
Previous review
AI Review
suggestion: need change
decision: need change
Thank you for this work. It traces the off-scale PTB-XL samples to three causes. It adds opt-in scaled-linear betas, v-prediction and official-style cosine guidance, plus a validation-based scale selection in the example. The model changes look correct, and the tests cover them well. Coverage is above the bar: 99.6% for tardiff.py and 97.3% for ptbxl_heartbeat.py, with 86.2% for the whole repository.
To get this merged:
- The description says every fix is opt-in and the defaults keep the merged behaviour.
PTBXLHeartbeatMI.heartbeatsnow always callssegment_heartbeats(..., skip_partial=True). That changes the public task's default output: it produces fewer samples, andbeatindices now count only whole beats. Please make this opt-in, for example with a task argument such asskip_partial_beats=Falsethat the example turns on. If you want the new behaviour to be the default, say so clearly in the description and docs. Either way, add a task-level test that covers the edge-beat behaviour.
Optional suggestions:
- The module docstring (around line 12) and the
UNet1Ddocstring (around line 113) intardiff.pystill say the network predicts noise. That is not true withprediction="v". - The backward-compatibility checkpoint test only removes
beta_schedule. Removingpredictionas well would exercise that default. - An explicit
--diffusion-checkpointskips the settings-based name. The model's config check still catches mismatches, but the "never reused without warning" claim then holds only for the default path. - One line in the
PTBXLHeartbeatMIdocstring is now long. You could rewrap it.
Reviewed commit 874b84b
- PTBXLHeartbeatMI: skip_partial_beats=False keeps the merged output; the TarDiff example turns it on. Task-level test for the edge beat. - tardiff.py docstrings: the U-Net predicts the noise or v. - Checkpoint compatibility test drops both prediction and beta_schedule. - Example warns that an explicit --diffusion-checkpoint is not checked against the training data. Signed-off-by: Irvi Aini <irvi.fa@gmail.com>
b3b559d to
2fb8be0
Compare
|
/review |
| if cosine: | ||
| norm = sum((g**2).sum() for g, _ in pairs).sqrt() | ||
| norm_G = sum((Gi**2).sum() for _, Gi in pairs).sqrt() | ||
| dot = dot / (norm * norm_G + 1e-12) |
There was a problem hiding this comment.
[low] Cosine guidance gives NaN when the batch gradient is exactly zero
With cosine=True, norm = sqrt(sum(g2)) has an infinite derivative at zero. If every sample's loss gradient is exactly zero in float32 (a saturated guide on a whole batch), the backward pass produces NaN, which then ends up in the sampled series. This is unlikely but silent. Fix by taking the square root of the sum plus a small constant, e.g. norm = (sum((g2).sum() for g, _ in pairs) + 1e-24).sqrt(), and the same for norm_G.
| "guidance": G, | ||
| "guidance_scale": w, | ||
| "guide_on_x0": args.guidance == "official", | ||
| "cosine": args.guidance == "official", |
There was a problem hiding this comment.
[low] Cosine guidance strength depends on the chunk size, and the final chunk differs
With guide_on_x0 and cosine, the guidance is one cosine over the whole batch, so the push on each series shrinks with batch size. The example calls diffusion.generate in chunks of 256, so the final, smaller chunk (about 100 beats here) is guided more strongly than the others. The docstring warns about batch size but the example doesn't account for it. Fix by generating every chunk at a fixed size (padding the last one and dropping the extra samples), or by noting the effect in the example.
|
|
||
| def checkpoint_name(args): | ||
| """Names the diffusion checkpoint after everything that changes it.""" | ||
| data = "toy" if args.synthetic else f"ptbxl-b{args.max_beats_per_record}" |
There was a problem hiding this comment.
[low] Checkpoint name does not identify the PTB-XL data it was trained on
checkpoint_name uses only ptbxl-b{max_beats}, not the --root path or PTB-XL version. A different PTB-XL copy with the same settings would silently reuse a checkpoint trained on other data, which is the reuse the PR says it avoids. Fix by adding the root (or a hash of it) to the name, or by printing a warning when a checkpoint is loaded for a different root.
There was a problem hiding this comment.
AI Review
suggestion: approve
decision: approve
Thank you for this follow-up. It adds opt-in scaled-linear betas, v-prediction and the official-style cosine guidance on the clean-series estimate to TarDiff. It also adds a skip_partial option for PTB-XL heartbeats. The diagnosis table and the multi-seed results make a convincing case. The change looks ready to merge.
Why I think so:
- The defaults keep the old behaviour, and old checkpoints still load. The tests cover that.
- The new options are tested: both beta schedules, v-prediction recovering the noise and the series, the cosine gradient against a closed form, and the edge-beat handling.
- Coverage meets the bar. tardiff.py is at 99.6% and ptbxl_heartbeat.py at 97.3%. The whole repository is at 86.3%.
- The links between components (the task using load_ptbxl_record and the superclass helpers, and the example using PTBXLDataset, split_by_strat_fold, SparcNet and TarDiff) are unchanged from #1562 and are named in the description.
- The docs match the code.
Optional suggestions:
- The cosine divides by
norm * norm_G + 1e-12. If the whole batch gradient is exactly zero, the sqrt backward pass can give NaN. You could clamp the norms instead. - The cosine is taken over the whole batch, so the final smaller chunk in the example is guided slightly differently. The docstring already notes the batch-size dependence. You could mention the last chunk in the example too.
- The checkpoint name doesn't identify the PTB-XL root, so two different data roots with the same settings would share a checkpoint.
- In the TarDiff module docstring, the edited line about v-prediction runs past the usual line width and could be re-wrapped.
Reviewed commit 2fb8be0
…r BTY-38 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01BdtuVKBLhWpYbhTQbaZaTt
[BTY-38] TarDiff: official noise schedule, v-prediction and guidance
Follow-up to #1562, which found that
TarDiff(#1552) generated off-scale PTB-XL heartbeats, so its guided results were at chance. This PR traces that to three causes, adds a fix for each as an opt-in option (the defaults keep the merged behaviour; the example script turns them on), and re-runs the reproduction. With the fixes, TarDiff-guided synthetic beats train a better classifier than unguided ones on all three seeds, which is the paper's main claim.Paper: Deng et al., "TarDiff: Target-Oriented Diffusion Guidance for Synthetic Electronic Health Record Time Series Generation", arXiv:2504.17613, 2025. Official code: https://github.com/devin-21/TarDiff (no licence, so it was read to check settings and nothing was copied).
Changes
pyhealth/models/generators/tardiff.py(all opt-in; old checkpoints still load):beta_schedule="scaled_linear": Latent Diffusion's betas (square roots evenly spaced), as TarDiff's official code uses. The official config pairs it withn_steps=200,beta_start=5e-4,beta_end=0.1.prediction="v": v-prediction (Salimans and Ho, 2022). With noise (eps) prediction, the clean-series estimate at the noisiest steps is the eps error times1/sqrt(abar)(about 40 at the last step), so a small error swamps it.generate(guide_on_x0=True, cosine=True): guidance as the official code does it. The guide scores the step's clean-series estimate (the kind of input it was trained on) instead of the noisyx_t, and the score is the cosine between the batch's loss gradient andG, instead of the raw dot product. The official code also shrinks each step by1 - scale, which this leaves out (the released scale is 1e-5, which makes the guidance almost zero).pyhealth/tasks/ptbxl_heartbeat.py:segment_heartbeats(skip_partial=True)drops beats cut by the record's edges.PTBXLHeartbeatMI(skip_partial_beats=False)exposes it; the default keeps [BTY-38] Reproduce TarDiff on PTB-XL heartbeats (TSTR and TSRTR) #1562's output (edge beats zero-padded), and the example turns it on. Medformer pads these beats instead; on PTB's two-minute records that matters little, but on PTB-XL's 10 s records withmax_beats_per_record=1, the one kept beat (the first) is often partial. Listed with the other differences in the docstring.examples/ecg/ptbxl/tardiff_ptbxl_tstr.py: the official schedule, v-prediction and official guidance are the defaults (--beta-schedule,--n-steps,--beta-start,--beta-end,--prediction,--guidance official|paper). Default guidance scales are 300, 1000 and 3000 for--guidance official, and the paper's 100 for--guidance paper.tardiff_selectedreports each setting at the scale with the best validation AUROC, so the scale isn't picked on the test fold. The diffusion checkpoint is named after the data and the training settings, so a model trained on toy data or with other settings is not silently reused. An explicit--diffusion-checkpointis checked only against the model settings (the saved config), and the script prints a warning saying the training data wasn't checked. The--synthetic --tinyusage line is fixed.v; the cosine guidance gradient against a closed form for a logistic-regression guide; the official options changing the samples; loading a checkpoint saved before the options (withoutbeta_scheduleandprediction);skip_partial; and the task withskip_partial_beatson and off, on a record whose last beat is cut by its end.Links between components are unchanged from #1562: the task uses
load_ptbxl_record(pyhealth.datasets.ptbxl) and the superclass helpers inpyhealth.tasks.ptbxl; the example usesPTBXLDataset,split_by_strat_fold,SparcNetandTarDiff.Diagnosis (small U-Net, 5,000 iterations; real beats have std 0.89; "guide accuracy" is how often the real-data classifier labels generated beats with their class)
With eps prediction, the error in the noise prediction at t = 199 was 0.0095, and the clean-series estimate there had std 3.9 and a cosine of 0.07 with the true beat. More sampling steps didn't help (DDIM with 25 or 200 steps, and full DDPM, all gave std about 3). On toy data, the paper's guidance equation (raw dot product, on
x_t) made guided samples look like the opposite class (TSTR AUROC about 0.1): the dot product can grow just by making samples misclassified. The cosine on the clean-series estimate doesn't do that.Results (laptop setting:
--unet small --max-beats-per-record 1 --iterations 5000 --diffusion-batch-size 128 --steps 25 --ratios 1.0 --epochs 5, all other options at their new defaults; 11,622 / 1,454 / 1,462 train / val / test beats; PTB-XL test fold 10; mean (std) over seeds 0, 1, 2)Validation picked w=1000, 300 and 1000 for the three seeds. TarDiff beats unguided TSTR on every seed: by +0.016, +0.036 and +0.019 AUROC, and by +0.030, +0.098 and +0.043 AUPRC. The real baseline rises from 0.928 to 0.945 AUROC with the edge-beat fix. Adding synthetic beats to the real ones doesn't help beyond real alone in this setting (both TSRTR rows are within a seed's noise of the real row), unlike the paper, which reports TSRTR gains; this is a small diffusion model (1.2M parameters, 5k iterations) on one beat per record, against the paper's 16.3M-parameter model trained for 20k iterations on all beats.
The paper's full setting (
--unet paper, 4 beats per record, 20k iterations) wasn't run; it needs a GPU.