File size: 21,953 Bytes
d4101a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
"""Option A: E2E fine-tuning of LuaNovaCFM v5 through frozen MIT BigVGAN and frozen NVIDIA pretrained MPD/MRD."""
from __future__ import annotations

import argparse
from collections import defaultdict
import copy
import json
import math
from pathlib import Path
import time

import torch
from torch import nn
from torch.nn import functional as F
from torch.utils.checkpoint import checkpoint

from ..data.dataset import AnnotatedDataset, BucketSampler, collate
from ..models.bigvgan import BigVGANMelExtractor, _ensure_bigvgan_importable
from ..models.cfm import LuaNovaCFM, energy_noise_gate, f0_features, smooth_f0_channel
from ..models.losses import SpectralLoss, masked_mean
from .common import (
    MelDatasetView,
    balanced_indices,
    check_leakage,
    cosine_lr,
    export_cfm_checkpoint,
    load_cfm_model,
    precompute_bigvgan_mels,
    update_ema,
)


def _unrolled_ode_sample(

    model: LuaNovaCFM,

    cond: torch.Tensor,

    prior_mel: torch.Tensor,

    frame_mask: torch.Tensor,

    f0_feats: torch.Tensor | None,

    n_steps: int,

    cfg_scale: float,

    temperature: float,

    solver: str,

    sway_coef: float,

    use_checkpoint: bool = True,

    noise_gate: torch.Tensor | None = None,

) -> torch.Tensor:
    sigma = model.cfm_config.prior_sigma * temperature
    eps = torch.randn_like(prior_mel)
    noise = sigma * eps if noise_gate is None else sigma * noise_gate * eps
    x = (prior_mel + noise) * frame_mask[..., None]
    zero_cond = torch.zeros_like(cond)
    zero_prior = torch.zeros_like(prior_mel)
    zero_f0 = torch.zeros_like(f0_feats) if f0_feats is not None else None

    def velocity(x_cur: torch.Tensor, t_val: float) -> torch.Tensor:
        t_vec = torch.full((x_cur.shape[0],), t_val, device=x_cur.device, dtype=torch.float32)
        v_c = model.flow(x_cur, t_vec, cond, prior_mel, frame_mask, f0_feats=f0_feats)
        if cfg_scale == 1.0:
            return v_c
        v_u = model.flow(x_cur, t_vec, zero_cond, zero_prior, frame_mask, f0_feats=zero_f0)
        return v_u + cfg_scale * (v_c - v_u)

    def one_step(x_in: torch.Tensor, t0_val: float, dt_val: float) -> torch.Tensor:
        if solver == "midpoint":
            v0 = velocity(x_in, t0_val)
            x_mid = (x_in + 0.5 * dt_val * v0) * frame_mask[..., None]
            v_mid = velocity(x_mid, t0_val + 0.5 * dt_val)
            return (x_in + dt_val * v_mid) * frame_mask[..., None]
        v0 = velocity(x_in, t0_val)
        return (x_in + dt_val * v0) * frame_mask[..., None]

    t_grid = model.sway_time_grid(n_steps, sway_coef)
    for i in range(n_steps):
        t0, t1 = t_grid[i], t_grid[i + 1]
        dt_i = t1 - t0
        if use_checkpoint and model.training and x.requires_grad:
            x = checkpoint(lambda x_s, a=t0, d=dt_i: one_step(x_s, a, d), x, use_reentrant=False)
        else:
            x = one_step(x, t0, dt_i)
    return x


def _lr_at(step: int, warmup: int, total_steps: int, base_lr: float, min_lr: float = 4e-6) -> float:
    if step < warmup:
        return base_lr * (step + 1) / max(warmup, 1)
    prog = min(max((step - warmup) / max(total_steps - warmup, 1), 0.0), 1.0)
    return min_lr + 0.5 * (base_lr - min_lr) * (1.0 + math.cos(math.pi * prog))


def option_a_micro_step(

    model: LuaNovaCFM,

    voc_net: nn.Module,

    mpd: nn.Module,

    mrd: nn.Module,

    ext: BigVGANMelExtractor,

    spectral: SpectralLoss,

    feature_loss_fn,

    generator_loss_fn,

    batch: dict,

    args,

    use_bf16: bool,

) -> tuple[torch.Tensor, dict[str, float]]:
    c = model.config
    hop = int(c.hop)
    with torch.no_grad():
        hidden, tok_mask = model.encode(batch["tokens"], batch["stress"], batch["token_lengths"], batch["speakers"])
        p_tok_ctx, c_ctx_tok = model.encode_prosody_context(hidden, batch["tokens"], batch["stress"], tok_mask)
        ac_f, pr_f, fmask, flen = model.expand_with_context(hidden, p_tok_ctx, c_ctx_tok, batch["durations"], tok_mask, batch["speakers"])
        _, pred_pros, _ = model.sample_prosody(pr_f, fmask, seed=0)

    if args.teacher_prob > 0.0:
        teach = torch.rand(len(flen), device=flen.device) < args.teacher_prob
        condition = torch.where(teach[:, None, None], batch["prosody"], model.hard_prosody(pred_pros))
    else:
        condition = model.hard_prosody(pred_pros)
    if args.f0_smooth_prob > 0.0:
        condition = smooth_f0_channel(condition, args.f0_smooth_prob)

    base_h = ac_f if model.cfm_config.acoustic_from_frames else pr_f
    f0_feats = f0_features(condition, fmask) if model.cfm_config.use_f0_harmonics else None
    noise_gate = energy_noise_gate(condition, fmask) if model.cfm_config.use_energy_gate else None
    x1 = ((batch["vocos_mel"] - model.vocoder.mel_mean) / model.vocoder.mel_scale) * fmask[..., None]

    ch_w = torch.ones((1, 1, c.vocos_n_mels), device=x1.device, dtype=torch.float32)
    ch_w[..., 60:] = args.hf_boost
    ch_w = ch_w / ch_w.mean()

    with torch.amp.autocast("cuda", dtype=torch.bfloat16, enabled=use_bf16):
        cond, prior_mel = model.condition_and_prior(base_h, condition, fmask)
        mel_norm = _unrolled_ode_sample(
            model, cond, prior_mel, fmask, f0_feats,
            n_steps=args.ode_steps, cfg_scale=1.0, temperature=args.ode_temp,
            solver="midpoint", sway_coef=args.sway_coef, use_checkpoint=True, noise_gate=noise_gate,
        )
        # Anchor CFM velocity on full sequence to preserve manifold alignment
        t_anc = torch.sigmoid(torch.randn(x1.shape[0], device=x1.device, dtype=torch.float32) * 0.8).clamp(1e-3, 1.0 - 1e-3)
        eps_anc = torch.randn_like(x1)
        if noise_gate is not None:
            eps_anc = eps_anc * noise_gate
        x0_anc = (prior_mel.detach().float() + model.cfm_config.prior_sigma * eps_anc) * fmask[..., None]
        xt_anc = ((1.0 - t_anc[:, None, None]) * x0_anc + t_anc[:, None, None] * x1) * fmask[..., None]
        v_pred_anc = model.flow(xt_anc, t_anc, cond, prior_mel.detach(), fmask, f0_feats=f0_feats)

    cfm_anchor = masked_mean(((v_pred_anc.float() - (x1 - x0_anc)).abs() * ch_w).mean(-1), fmask)
    mel_f = mel_norm.float()
    mel_l1 = masked_mean(((mel_f - x1).abs() * ch_w).mean(-1), fmask)
    pair_mask = fmask[:, 1:] & fmask[:, :-1]
    delta_l = masked_mean(((mel_f[:, 1:] - mel_f[:, :-1]) - (x1[:, 1:] - x1[:, :-1])).abs().mean(-1), pair_mask)
    fdelta_l = masked_mean(((mel_f[..., 1:] - mel_f[..., :-1]) - (x1[..., 1:] - x1[..., :-1])).abs().mean(-1), fmask)

    # Interior window crop -> frozen BigVGAN -> edge trim -> frozen STFT / Mel / MPD / MRD losses
    b_sz = mel_f.shape[0]
    crop_f = min(int(args.crop_frames), int(flen.min().item()))
    starts = [
        int(torch.randint(0, int(flen[i].item()) - crop_f + 1, (1,)).item()) if int(flen[i].item()) > crop_f else 0
        for i in range(b_sz)
    ]
    mel_crop = torch.stack([mel_f[i, s0 : s0 + crop_f] for i, s0 in enumerate(starts)], dim=0)
    gt_crop = torch.stack([batch["wave"][i, s0 * hop : (s0 + crop_f) * hop] for i, s0 in enumerate(starts)], dim=0)[:, None, :]

    phys_crop = (mel_crop * model.vocoder.mel_scale + model.vocoder.mel_mean).clamp(min=-11.512925)
    with torch.amp.autocast("cuda", dtype=torch.bfloat16, enabled=use_bf16):
        pred_wav = voc_net(phys_crop.transpose(1, 2).contiguous())

    trim = min(int(args.edge_trim), pred_wav.shape[-1] // 8)
    pred_trim = pred_wav[:, :, trim:-trim] if trim > 0 else pred_wav
    gt_trim = gt_crop[:, :, trim:-trim] if trim > 0 else gt_crop

    with torch.amp.autocast("cuda", dtype=torch.bfloat16, enabled=use_bf16):
        _, y_df_g, fmap_f_r, fmap_f_g = mpd(gt_trim, pred_trim)

    pred_32 = pred_trim.float()
    gt_32 = gt_trim.float()
    with torch.amp.autocast("cuda", enabled=False):
        _, y_ds_g, fmap_s_r, fmap_s_g = mrd(gt_32, pred_32)
        trim_len = torch.full((b_sz,), pred_32.shape[-1], device=x1.device, dtype=torch.long)
        stft_l, _ = spectral(pred_32.squeeze(1), gt_32.squeeze(1), trim_len)
        wmel_l = F.l1_loss(ext(pred_32.squeeze(1)), ext(gt_32.squeeze(1)))
        fm_l = (
            feature_loss_fn([[a.float() for a in l] for l in fmap_f_r], [[a.float() for a in l] for l in fmap_f_g])
            + feature_loss_fn(fmap_s_r, fmap_s_g)
        )
        adv_l = generator_loss_fn([t.float() for t in y_df_g])[0] + generator_loss_fn(y_ds_g)[0]

    loss = (
        args.w_cfm_anchor * cfm_anchor
        + args.w_mel * mel_l1
        + args.w_delta * delta_l
        + args.w_fdelta * fdelta_l
        + args.w_stft * stft_l
        + args.w_wmel * wmel_l
        + args.w_fm * fm_l
        + args.w_adv * adv_l
    )
    stats = {
        "loss": float(loss.detach()),
        "stft": float(stft_l.detach()),
        "wmel": float(wmel_l.detach()),
        "fm": float(fm_l.detach()),
        "adv": float(adv_l.detach()),
        "anc": float(cfm_anchor.detach()),
        "mel": float(mel_l1.detach()),
        "delta": float(delta_l.detach()),
    }
    return loss, stats


@torch.no_grad()
def validate_option_a(

    ema_model: LuaNovaCFM,

    voc_net: nn.Module,

    ext: BigVGANMelExtractor,

    spectral: SpectralLoss,

    val_ds: AnnotatedDataset,

    val_gt: dict[int, torch.Tensor],

    val_indices: list[int],

    args,

) -> dict[str, float]:
    ema_model.eval()
    stft_tot, wmel_tot, dt_tot, n = 0.0, 0.0, 0.0, 0
    hop = int(ema_model.config.hop)
    for idx in val_indices:
        it = val_ds[idx]
        gt_wav = it["wave"][None].to(device=args.device, dtype=torch.float32)
        gt_m = val_gt[idx][None].to(device=args.device, dtype=torch.float32)
        tok = it["tokens"][None].to(args.device)
        st = it["stress"][None].to(args.device)
        tl = torch.tensor([tok.shape[1]], device=args.device)
        sp = torch.tensor([int(it["speaker"])], device=args.device)
        dur = it["durations"][None].to(args.device)

        h, m = ema_model.encode(tok, st, tl, sp)
        pt, ct = ema_model.encode_prosody_context(h, tok, st, m)
        af, pr_f, fm, fl = ema_model.expand_with_context(h, pt, ct, dur, m, sp)
        _, pred_pros, _ = ema_model.sample_prosody(pr_f, fm, seed=0)
        cond_p = ema_model.hard_prosody(pred_pros)
        base_h = af if ema_model.cfm_config.acoustic_from_frames else pr_f
        cond, prior_mel = ema_model.condition_and_prior(base_h, cond_p, fm)
        f0f = f0_features(cond_p, fm) if ema_model.cfm_config.use_f0_harmonics else None
        ng = energy_noise_gate(cond_p, fm) if ema_model.cfm_config.use_energy_gate else None
        mel_norm = ema_model.sample_mel(
            cond, prior_mel, fm, n_steps=args.ode_steps, cfg_scale=1.0,
            temperature=args.ode_temp, solver="midpoint", seed=0,
            f0_feats=f0f, noise_gate=ng, sway_coef=args.sway_coef,
        )
        phys = (mel_norm.float() * ema_model.vocoder.mel_scale + ema_model.vocoder.mel_mean).clamp(min=-11.512925)
        pred_wav = voc_net(phys.transpose(1, 2).contiguous()).squeeze(1)[:, : int(fl[0]) * hop]
        s_len = torch.tensor([pred_wav.shape[-1]], device=args.device, dtype=torch.long)
        stft_l, _ = spectral(pred_wav, gt_wav, s_len)
        rec_m = ext(pred_wav)
        n_f = min(rec_m.shape[1], gt_m.shape[1])
        wmel_l = F.l1_loss(rec_m[:, :n_f], gt_m[:, :n_f])
        dt_mel = (rec_m[:, 1:n_f] - rec_m[:, : n_f - 1]).abs().mean()
        stft_tot += float(stft_l)
        wmel_tot += float(wmel_l)
        dt_tot += float(dt_mel)
        n += 1
    return {
        "val_stft": stft_tot / max(n, 1),
        "val_wmel": wmel_tot / max(n, 1),
        "val_dt_mel": dt_tot / max(n, 1),
    }


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--train", type=Path, required=True)
    parser.add_argument("--validation", type=Path, required=True)
    parser.add_argument("--init-v5", type=Path, required=True)
    parser.add_argument("--vocoder-id", default="nvidia/bigvgan_base_24khz_100band")
    parser.add_argument("--output", type=Path, required=True)
    parser.add_argument("--device", default="cuda")
    parser.add_argument("--steps", type=int, default=4000)
    parser.add_argument("--batch-size", type=int, default=4)
    parser.add_argument("--grad-accum", type=int, default=3)
    parser.add_argument("--crop-frames", type=int, default=40)
    parser.add_argument("--edge-trim", type=int, default=512)
    parser.add_argument("--ode-steps", type=int, default=4)
    parser.add_argument("--ode-temp", type=float, default=0.40)
    parser.add_argument("--sway-coef", type=float, default=-0.5)
    parser.add_argument("--lr", type=float, default=4e-5)
    parser.add_argument("--min-lr", type=float, default=4e-6)
    parser.add_argument("--warmup", type=int, default=200)
    parser.add_argument("--ema-decay", type=float, default=0.995)
    parser.add_argument("--teacher-prob", type=float, default=0.35)
    parser.add_argument("--f0-smooth-prob", type=float, default=0.15)
    parser.add_argument("--hf-boost", type=float, default=1.40)
    parser.add_argument("--w-cfm-anchor", type=float, default=1.0)
    parser.add_argument("--w-mel", type=float, default=0.5)
    parser.add_argument("--w-delta", type=float, default=0.8)
    parser.add_argument("--w-fdelta", type=float, default=0.4)
    parser.add_argument("--w-stft", type=float, default=1.5)
    parser.add_argument("--w-wmel", type=float, default=2.0)
    parser.add_argument("--w-fm", type=float, default=0.08)
    parser.add_argument("--w-adv", type=float, default=0.05)
    parser.add_argument("--val-every", type=int, default=500)
    parser.add_argument("--log-every", type=int, default=10)
    parser.add_argument("--save-steps", nargs="+", type=int, default=[1500, 3000, 4000])
    parser.add_argument("--seed", type=int, default=20261123)
    args = parser.parse_args()

    torch.manual_seed(args.seed)
    torch.backends.cuda.matmul.allow_tf32 = True
    torch.backends.cudnn.allow_tf32 = True

    _ensure_bigvgan_importable()
    import bigvgan
    from discriminators import MultiPeriodDiscriminator, MultiResolutionDiscriminator
    from huggingface_hub import hf_hub_download
    from loss import feature_loss, generator_loss

    model = load_cfm_model(args.init_v5, args.device)
    model.freeze_frontend(True)
    for p in model.vocoder.parameters():
        p.requires_grad_(False)
    ema_model = copy.deepcopy(model).eval()
    for p in ema_model.parameters():
        p.requires_grad_(False)

    trainable = [p for p in model.parameters() if p.requires_grad]
    trainable_prefixes = sorted({n.split(".")[0] for n, p in model.named_parameters() if p.requires_grad})

    voc_net = bigvgan.BigVGAN.from_pretrained(args.vocoder_id, use_cuda_kernel=False)
    voc_net.remove_weight_norm()
    voc_net = voc_net.eval().to(args.device)
    for p in voc_net.parameters():
        p.requires_grad_(False)

    do_path = hf_hub_download(args.vocoder_id, "bigvgan_discriminator_optimizer.pt")
    do_ckpt = torch.load(do_path, map_location="cpu", weights_only=True)
    mpd = MultiPeriodDiscriminator(voc_net.h).to(args.device)
    mrd = MultiResolutionDiscriminator(voc_net.h).to(args.device)
    mpd.load_state_dict(do_ckpt["mpd"], strict=True)
    mrd.load_state_dict(do_ckpt["mrd"], strict=True)
    del do_ckpt
    for mod in (mpd, mrd):
        mod.eval()
        for p in mod.parameters():
            p.requires_grad_(False)

    train_ds = AnnotatedDataset(args.train, model.config, voiced_vowels=True, cache=True)
    val_ds = AnnotatedDataset(args.validation, model.config, voiced_vowels=True, cache=True)
    check_leakage(train_ds, val_ds)
    pool = [i for i in range(len(train_ds)) if train_ds.lengths[i] >= args.crop_frames]
    val_indices = balanced_indices(val_ds, len(val_ds))
    print(f"Preloading train ({len(pool)}) and validation ({len(val_indices)}) ...", flush=True)
    train_ds.preload(pool, workers=8)
    val_ds.preload(val_indices, workers=4)

    ext = BigVGANMelExtractor().to(args.device).eval()
    t_mel = time.perf_counter()
    train_bg, _, _ = precompute_bigvgan_mels(train_ds, pool, ext, args.device, compute_stats=False)
    val_bg, _, _ = precompute_bigvgan_mels(val_ds, val_indices, ext, args.device, compute_stats=False)
    print(
        f"Precomputed BigVGAN mels in {time.perf_counter() - t_mel:.2f}s | trainable={trainable_prefixes} "
        f"({sum(p.numel() for p in trainable):,} params)",
        flush=True,
    )

    spectral = SpectralLoss(
        model.config.sample_rate,
        resolutions=((256, 64), (512, 128), (1024, 256), (2048, 512)),
        mel=(1024, 256, 80),
    ).to(args.device)
    train_view = MelDatasetView(train_ds, train_bg)
    sampler = BucketSampler([train_ds.lengths[i] for i in pool], args.batch_size * 500, args.batch_size, args.seed)
    optimizer = torch.optim.AdamW(trainable, lr=args.lr, betas=(0.9, 0.98), weight_decay=0.01)

    is_cuda = torch.cuda.is_available() and str(args.device).startswith("cuda")
    use_bf16 = is_cuda
    grad_accum = max(int(args.grad_accum), 1)
    args.output.mkdir(parents=True, exist_ok=True)
    log_f = (args.output / "train.log").open("a", encoding="utf-8", buffering=1)

    def emit(msg: str) -> None:
        print(msg, flush=True)
        log_f.write(msg + "\n")
        log_f.flush()

    if is_cuda:
        torch.cuda.reset_peak_memory_stats(args.device)

    v0 = validate_option_a(ema_model, voc_net, ext, spectral, val_ds, val_bg, val_indices, args)
    emit(f"[step 0] {json.dumps(v0)}")

    win = defaultdict(float)
    win_n = 0
    win_t = time.monotonic()
    save_set = set(int(s) for s in args.save_steps) | {int(args.steps)}

    try:
        for step in range(args.steps):
            lr = cosine_lr(step, args.warmup, args.steps, args.lr, min_lr=args.min_lr)
            for pg in optimizer.param_groups:
                pg["lr"] = lr

            model.train()
            optimizer.zero_grad(set_to_none=True)
            acc = defaultdict(float)

            for _micro in range(grad_accum):
                batch_ids = [pool[i] for i in sampler.next()]
                batch = collate([train_view[i] for i in batch_ids], args.device)
                loss_mb, st_mb = option_a_micro_step(
                    model, voc_net, mpd, mrd, ext, spectral, feature_loss, generator_loss,
                    batch, args, use_bf16=use_bf16,
                )
                if not torch.isfinite(loss_mb):
                    raise RuntimeError(f"Non-finite loss at step {step}: {loss_mb}")
                (loss_mb / grad_accum).backward()
                for k, v in st_mb.items():
                    acc[k] += v / grad_accum
                del batch, loss_mb

            grad_norm = float(nn.utils.clip_grad_norm_(trainable, 1.0))
            optimizer.step()
            update_ema(ema_model, model, args.ema_decay)

            cur = step + 1
            for k, v in acc.items():
                win[k] += v
            win["grad_norm"] += grad_norm
            win_n += 1

            do_val = (cur % args.val_every == 0) or (cur == args.steps)
            do_save = cur in save_set
            do_log = (cur % args.log_every == 0) or (cur == 1) or do_val or do_save

            if do_log:
                if is_cuda:
                    torch.cuda.synchronize()
                dt = max(time.monotonic() - win_t, 1e-6)
                it_s = win_n / dt
                eta_min = (args.steps - cur) / max(it_s, 1e-6) / 60.0
                vram_gb = (torch.cuda.memory_allocated(args.device) / 1e9) if is_cuda else 0.0
                vram_peak_gb = (torch.cuda.max_memory_allocated(args.device) / 1e9) if is_cuda else 0.0
                rec = {k: round(v / win_n, 4) for k, v in win.items()}
                rec.update(
                    step=cur,
                    lr=round(lr, 7),
                    it_s=round(it_s, 2),
                    eta_min=round(eta_min, 2),
                    vram_gb=round(vram_gb, 2),
                    vram_peak_gb=round(vram_peak_gb, 2),
                )
                if do_val:
                    val_m = validate_option_a(ema_model, voc_net, ext, spectral, val_ds, val_bg, val_indices, args)
                    rec.update({k: round(v, 5) for k, v in val_m.items()})
                with (args.output / "metrics.jsonl").open("a", encoding="utf-8") as mf:
                    mf.write(json.dumps(rec) + "\n")
                    mf.flush()
                pct = 100.0 * cur / max(args.steps, 1)
                msg = (
                    f"[step {cur:05d}/{args.steps:05d} | {pct:5.1f}%] "
                    f"loss={rec['loss']:.3f} stft={rec['stft']:.3f} wmel={rec['wmel']:.3f} "
                    f"fm={rec['fm']:.2f} adv={rec['adv']:.2f} anc={rec['anc']:.3f} | "
                    f"{rec['it_s']:.2f} it/s | ETA {rec['eta_min']:.1f}m | VRAM {rec['vram_gb']:.2f}/{rec['vram_peak_gb']:.2f} GB"
                )
                if do_val:
                    msg += f" | val_stft={rec['val_stft']:.5f} val_wmel={rec['val_wmel']:.5f} val_dt={rec['val_dt_mel']:.4f}"
                emit(msg)
                win = defaultdict(float)
                win_n = 0
                win_t = time.monotonic()

            if do_save:
                export_cfm_checkpoint(ema_model, args.output / f"inference_v5_e2e_step-{cur:06d}.pt", cur, train_ds.annotation)
                export_cfm_checkpoint(ema_model, args.output / "inference_v5_e2e_ema.pt", cur, train_ds.annotation)
    finally:
        log_f.close()


if __name__ == "__main__":
    main()