File size: 15,810 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
"""OT-CFM trajectory distillation (e.g. 8-step Sway Midpoint teacher -> 2-step Euler student)."""
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 ..data.dataset import AnnotatedDataset, BucketSampler, collate
from ..models.cfm import LuaNovaCFM, energy_noise_gate, f0_features, smooth_f0_channel
from ..models.losses import masked_mean
from .common import (
    balanced_indices,
    check_leakage,
    cosine_lr,
    export_cfm_checkpoint,
    load_cfm_model,
    update_ema,
)


def make_channel_weights(n_mels: int, hf_boost: float, device: torch.device | str) -> torch.Tensor | float:
    """Upweight upper mel bands (bins 60..n_mels) when ``hf_boost != 1.0``."""
    if hf_boost == 1.0:
        return 1.0
    ch_w = torch.ones((1, 1, n_mels), device=device, dtype=torch.float32)
    ch_w[..., 60:] = float(hf_boost)
    return ch_w / ch_w.mean()


def _teacher_velocity(

    teacher: LuaNovaCFM,

    x_cur: torch.Tensor,

    t_val: float,

    cond: torch.Tensor,

    prior_mel: torch.Tensor,

    frame_mask: torch.Tensor,

    f0_feats: torch.Tensor | None,

    cfg_scale: float,

) -> torch.Tensor:
    t_vec = torch.full((x_cur.shape[0],), float(t_val), device=x_cur.device, dtype=torch.float32)
    v_c = teacher.flow(x_cur, t_vec, cond, prior_mel, frame_mask, f0_feats=f0_feats)
    if cfg_scale == 1.0:
        return v_c
    v_u = teacher.flow(
        x_cur,
        t_vec,
        torch.zeros_like(cond),
        torch.zeros_like(prior_mel),
        frame_mask,
        f0_feats=torch.zeros_like(f0_feats) if f0_feats is not None else None,
    )
    return v_u + cfg_scale * (v_c - v_u)


def distill_loss_step(

    teacher: LuaNovaCFM,

    student: LuaNovaCFM,

    batch: dict,

    ch_w: torch.Tensor | float,

    teacher_steps: int = 8,

    teacher_sway: float = -0.5,

    teacher_temp: float = 0.35,

    teacher_cfg: float = 1.0,

    teacher_solver: str = "midpoint",

    student_steps: int = 2,

    student_sway: float = 0.0,

    teacher_prob: float = 0.35,

    f0_smooth_prob: float = 0.15,

    training: bool = True,

) -> tuple[torch.Tensor, dict[str, float]]:
    """Compute trajectory distillation loss matching student Euler ODE against the teacher ODE."""
    dev_type = "cuda" if batch["tokens"].device.type == "cuda" else "cpu"
    use_bf16 = dev_type == "cuda"

    s_grid = student.sway_time_grid(student_steps, student_sway)
    s_mid_idx = max(1, student_steps // 2)
    s_mid_t = s_grid[s_mid_idx]
    t_grid = teacher.sway_time_grid(teacher_steps, teacher_sway)
    t_mid_idx = min(range(1, len(t_grid)), key=lambda idx: abs(t_grid[idx] - s_mid_t))

    with torch.no_grad():
        hidden, token_mask = teacher.encode(batch["tokens"], batch["stress"], batch["token_lengths"], batch["speakers"])
        prosody_token_ctx, clause_ctx_tok = teacher.encode_prosody_context(
            hidden, batch["tokens"], batch["stress"], token_mask
        )
        acoustic_frames, prosody_frames, frame_mask, flen = teacher.expand_with_context(
            hidden, prosody_token_ctx, clause_ctx_tok, batch["durations"], token_mask, batch["speakers"]
        )
        if teacher.cfm_config.acoustic_from_frames and teacher_prob >= 1.0:
            prosody_hidden = None
            pred_pros = None
        else:
            prosody_hidden, pred_pros, _ = teacher.sample_prosody(prosody_frames, frame_mask, seed=0)

        if pred_pros is None or teacher_prob >= 1.0:
            condition = batch["prosody"]
        elif training and teacher_prob > 0.0:
            teach = torch.rand(len(flen), device=flen.device) < teacher_prob
            condition = torch.where(teach[:, None, None], batch["prosody"], teacher.hard_prosody(pred_pros))
        else:
            condition = teacher.hard_prosody(pred_pros)
        if training and f0_smooth_prob > 0.0:
            condition = smooth_f0_channel(condition, f0_smooth_prob)

        base_h = acoustic_frames if teacher.cfm_config.acoustic_from_frames else prosody_hidden
        f0_feats = f0_features(condition, frame_mask) if teacher.cfm_config.use_f0_harmonics else None
        gate = energy_noise_gate(condition, frame_mask) if teacher.cfm_config.use_energy_gate else 1.0

        with torch.amp.autocast(device_type=dev_type, dtype=torch.bfloat16, enabled=use_bf16):
            cond, prior_mel = teacher.condition_and_prior(base_h, condition, frame_mask)
            sigma = float(teacher.cfm_config.prior_sigma) * float(teacher_temp)
            eps = torch.randn_like(prior_mel) if training else torch.zeros_like(prior_mel)
            x0 = (prior_mel.float() + sigma * gate * eps) * frame_mask[..., None]

            x_t = x0
            x_t_mid = x0
            for i in range(teacher_steps):
                t0, t1 = t_grid[i], t_grid[i + 1]
                dt_i = t1 - t0
                if teacher_solver == "midpoint":
                    v0 = _teacher_velocity(teacher, x_t, t0, cond, prior_mel, frame_mask, f0_feats, teacher_cfg)
                    x_mid = (x_t + 0.5 * dt_i * v0) * frame_mask[..., None]
                    vm = _teacher_velocity(
                        teacher, x_mid, t0 + 0.5 * dt_i, cond, prior_mel, frame_mask, f0_feats, teacher_cfg
                    )
                    x_t = (x_t + dt_i * vm) * frame_mask[..., None]
                else:
                    v0 = _teacher_velocity(teacher, x_t, t0, cond, prior_mel, frame_mask, f0_feats, teacher_cfg)
                    x_t = (x_t + dt_i * v0) * frame_mask[..., None]
                if i + 1 == t_mid_idx:
                    x_t_mid = x_t
            x_t_end = x_t

    with torch.amp.autocast(device_type=dev_type, dtype=torch.bfloat16, enabled=use_bf16):
        b = x0.shape[0]
        x_s = x0
        x_s_mid = x0
        for i in range(student_steps):
            t0, t1 = s_grid[i], s_grid[i + 1]
            dt_i = t1 - t0
            t_vec = torch.full((b,), t0, device=x0.device, dtype=torch.float32)
            v_s = student.flow(x_s, t_vec, cond, prior_mel, frame_mask, f0_feats=f0_feats)
            x_s = (x_s + dt_i * v_s) * frame_mask[..., None]
            if i + 1 == s_mid_idx:
                x_s_mid = x_s
        x_s_end = x_s

    xs_end_f = x_s_end.float()
    xt_end_f = x_t_end.float()
    end_l1 = masked_mean(((xs_end_f - xt_end_f).abs() * ch_w).mean(-1), frame_mask)
    mid_l1 = masked_mean(((x_s_mid.float() - x_t_mid.float()).abs() * ch_w).mean(-1), frame_mask)
    pair_mask = frame_mask[:, 1:] & frame_mask[:, :-1]
    dt_l1 = masked_mean(
        (((xs_end_f[:, 1:] - xs_end_f[:, :-1]) - (xt_end_f[:, 1:] - xt_end_f[:, :-1])).abs()).mean(-1),
        pair_mask,
    )
    df_l1 = masked_mean(
        (((xs_end_f[..., 1:] - xs_end_f[..., :-1]) - (xt_end_f[..., 1:] - xt_end_f[..., :-1])).abs()).mean(-1),
        frame_mask,
    )
    loss = end_l1 + 0.5 * mid_l1 + 0.7 * dt_l1 + 0.4 * df_l1
    metrics = {
        "loss": float(loss.detach()),
        "end_l1": float(end_l1.detach()),
        "mid_l1": float(mid_l1.detach()),
        "dt_l1": float(dt_l1.detach()),
        "df_l1": float(df_l1.detach()),
    }
    return loss, metrics


@torch.no_grad()
def validate_distill(

    teacher: LuaNovaCFM,

    student: LuaNovaCFM,

    dataset: AnnotatedDataset,

    indices: list[int],

    device: str,

    ch_w: torch.Tensor | float,

    args: argparse.Namespace,

) -> dict[str, float]:
    was_flow_training = student.flow.training
    student.eval()
    totals: dict[str, float] = defaultdict(float)
    weight = 0
    for start in range(0, len(indices), 8):
        batch = collate([dataset[i] for i in indices[start : start + 8]], device)
        sz = len(batch["frame_lengths"])
        _, m = distill_loss_step(
            teacher,
            student,
            batch,
            ch_w,
            teacher_steps=args.teacher_steps,
            teacher_sway=args.teacher_sway,
            teacher_temp=args.teacher_temp,
            teacher_cfg=args.teacher_cfg,
            teacher_solver=args.teacher_solver,
            student_steps=args.student_steps,
            student_sway=args.student_sway,
            teacher_prob=args.teacher_prob,
            f0_smooth_prob=0.0,
            training=False,
        )
        for k, v in m.items():
            totals[f"val_{k}"] += v * sz
        weight += sz
    if was_flow_training:
        student.flow.train()
    return {k: v / max(weight, 1) for k, v in totals.items()}


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("--teacher", type=Path, required=True, help="Teacher CFM v5 checkpoint (.pt)")
    parser.add_argument("--output", type=Path, required=True)
    parser.add_argument("--device", default="cuda")
    parser.add_argument("--steps", type=int, default=12000)
    parser.add_argument("--batch-frames", type=int, default=6000)
    parser.add_argument("--max-batch", type=int, default=16)
    parser.add_argument("--lr", type=float, default=1e-4)
    parser.add_argument("--min-lr", type=float, default=5e-6)
    parser.add_argument("--warmup", type=int, default=400)
    parser.add_argument("--ema-decay", type=float, default=0.999)
    parser.add_argument("--teacher-steps", type=int, default=8)
    parser.add_argument("--teacher-sway", type=float, default=-0.5)
    parser.add_argument("--teacher-temp", type=float, default=0.35)
    parser.add_argument("--teacher-cfg", type=float, default=1.0)
    parser.add_argument("--teacher-solver", default="midpoint", choices=["euler", "midpoint"])
    parser.add_argument("--student-steps", type=int, default=2)
    parser.add_argument("--student-sway", type=float, default=0.0)
    parser.add_argument("--teacher-prob", type=float, default=0.35)
    parser.add_argument("--hf-boost", type=float, default=1.40)
    parser.add_argument("--f0-smooth-prob", type=float, default=0.15)
    parser.add_argument("--save-every", type=int, default=3000)
    parser.add_argument("--log-every", type=int, default=100)
    parser.add_argument("--seed", type=int, default=20261121)
    parser.add_argument("--max-seconds", type=float, default=3600.0)
    args = parser.parse_args()

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

    teacher = load_cfm_model(args.teacher, device=args.device, load_vocos=False).eval()
    for p in teacher.parameters():
        p.requires_grad_(False)

    student = copy.deepcopy(teacher)
    for p in student.parameters():
        p.requires_grad_(False)
    for p in student.flow.parameters():
        p.requires_grad_(True)
    student.eval()
    student.flow.train()

    ema_model = copy.deepcopy(student).eval()
    for p in ema_model.parameters():
        p.requires_grad_(False)

    trainable = list(student.flow.parameters())
    optimizer = torch.optim.AdamW(trainable, lr=args.lr, betas=(0.9, 0.98), weight_decay=0.01)

    train_ds = AnnotatedDataset(args.train, student.config, voiced_vowels=True, cache=True)
    val_ds = AnnotatedDataset(args.validation, student.config, voiced_vowels=True, cache=True)
    check_leakage(train_ds, val_ds)
    pool = list(range(len(train_ds)))
    val_indices = balanced_indices(val_ds, min(32, len(val_ds)))
    train_ds.preload(pool, workers=8)
    val_ds.preload(val_indices, workers=4)
    sampler = BucketSampler([train_ds.lengths[i] for i in pool], args.batch_frames, args.max_batch, args.seed)
    ch_w = make_channel_weights(student.config.vocos_n_mels, args.hf_boost, args.device)

    args.output.mkdir(parents=True, exist_ok=True)
    log_file = (args.output / "train.log").open("a", encoding="utf-8", buffering=1)
    metrics_path = args.output / "metrics.jsonl"

    def log_record(rec: dict) -> None:
        line = json.dumps(rec, ensure_ascii=False)
        print(line, flush=True)
        log_file.write(line + "\n")
        log_file.flush()
        with metrics_path.open("a", encoding="utf-8") as mf:
            mf.write(line + "\n")

    init_val = validate_distill(teacher, ema_model, val_ds, val_indices, args.device, ch_w, args)
    log_record(
        {
            "step": 0,
            "trainable_flow_params": sum(p.numel() for p in trainable),
            "teacher_steps": args.teacher_steps,
            "teacher_sway": args.teacher_sway,
            "teacher_temp": args.teacher_temp,
            "student_steps": args.student_steps,
            "student_sway": args.student_sway,
            **init_val,
        }
    )

    t_start = time.monotonic()
    t_win = time.monotonic()
    win: dict[str, float] = defaultdict(float)
    win_steps = 0

    try:
        for step in range(1, args.steps + 1):
            lr = cosine_lr(step - 1, args.warmup, args.steps, args.lr, args.min_lr)
            for g in optimizer.param_groups:
                g["lr"] = lr
            batch = collate([train_ds[pool[i]] for i in sampler.next()], args.device)
            optimizer.zero_grad(set_to_none=True)
            loss, m = distill_loss_step(
                teacher,
                student,
                batch,
                ch_w,
                teacher_steps=args.teacher_steps,
                teacher_sway=args.teacher_sway,
                teacher_temp=args.teacher_temp,
                teacher_cfg=args.teacher_cfg,
                teacher_solver=args.teacher_solver,
                student_steps=args.student_steps,
                student_sway=args.student_sway,
                teacher_prob=args.teacher_prob,
                f0_smooth_prob=args.f0_smooth_prob,
                training=True,
            )
            loss.backward()
            grad_norm = float(nn.utils.clip_grad_norm_(trainable, 5.0))
            optimizer.step()
            update_ema(ema_model, student, args.ema_decay)

            for k, v in m.items():
                win[k] += v
            win["grad_norm"] += grad_norm
            win_steps += 1
            elapsed = time.monotonic() - t_start
            should_stop = step == args.steps or elapsed >= args.max_seconds
            save = step % args.save_every == 0 or should_stop

            if step % args.log_every == 0 or save:
                if str(args.device).startswith("cuda"):
                    torch.cuda.synchronize()
                dt = max(time.monotonic() - t_win, 1e-6)
                rec: dict[str, object] = {k: v / win_steps for k, v in win.items()}
                rec.update(step=step, lr=lr, steps_per_s=win_steps / dt, elapsed_s=elapsed)
                if save:
                    rec.update(validate_distill(teacher, ema_model, val_ds, val_indices, args.device, ch_w, args))
                    export_cfm_checkpoint(
                        ema_model, args.output / "inference_v5_fast2_ema.pt", step, train_ds.annotation
                    )
                    export_cfm_checkpoint(
                        ema_model, args.output / f"inference_v5_fast2_step-{step:06d}.pt", step, train_ds.annotation
                    )
                log_record(rec)
                win = defaultdict(float)
                win_steps = 0
                t_win = time.monotonic()

            if should_stop:
                break
    finally:
        log_file.close()


if __name__ == "__main__":
    main()