File size: 22,217 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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
"""Split ONNX Runtime CPU export (opset 17) for LuaNovaCFM v5 and BigVGAN."""
from __future__ import annotations

import argparse
import copy
import json
import math
from pathlib import Path

import numpy as np
import torch
from torch import nn
from torch.nn import functional as F

from ..models.bigvgan import BigVGANVocoderWrapper
from ..models.cfm import LuaNovaCFM, energy_noise_gate, f0_features, smooth_prosody_noise
from ..text.phonemizer import frontend_fingerprint, frontend_identity, phonemize
from ..training.common import load_cfm_model

CFM_INPUTS = ("tokens", "stress", "voice", "speed", "pitch_shift", "pitch_range")
CFM_OUTPUTS = ("phys_mel", "frame_lengths")
BIGVGAN_INPUTS = ("mel",)
BIGVGAN_OUTPUTS = ("audio",)


def example_cfm_inputs(text: str = "Olá, tudo bem?", device: str = "cpu") -> tuple[torch.Tensor, ...]:
    """Build valid dummy inputs matching the exported ``CFM_INPUTS`` signature."""
    phones = phonemize(text)
    return (
        torch.tensor([phones.ids], dtype=torch.long, device=device),
        torch.tensor([phones.stress], dtype=torch.long, device=device),
        torch.tensor([0], dtype=torch.long, device=device),
        torch.tensor([1.0], dtype=torch.float32, device=device),
        torch.tensor([0.0], dtype=torch.float32, device=device),
        torch.tensor([1.05], dtype=torch.float32, device=device),
    )


class ExportableCFMAcoustic(nn.Module):
    """ONNX-traceable unrolled acoustic front-end + OT-CFM ODE predicting physical 100-band log-mel."""

    def __init__(

        self,

        model: LuaNovaCFM,

        n_steps: int = 2,

        cfg_scale: float = 1.0,

        temperature: float = 0.35,

        solver: str = "euler",

        sway_coef: float = 0.0,

        seed: int = 0,

        dur_steps: int | None = None,

        dur_temp: float | None = None,

        prosody_steps: int | None = None,

        prosody_temp: float | None = None,

    ) -> None:
        super().__init__()
        self.model = model.eval()
        self.n_steps = int(n_steps)
        self.cfg_scale = float(cfg_scale)
        self.temperature = float(temperature)
        self.solver = str(solver)
        self.sway_coef = float(sway_coef)
        cc = model.cfm_config
        c = model.config
        self.dur_steps = int(cc.dur_flow_steps if dur_steps is None else dur_steps)
        self.dur_temp = float(cc.dur_flow_temp if dur_temp is None else dur_temp)
        self.prosody_steps = int(cc.prosody_flow_steps if prosody_steps is None else prosody_steps)
        self.prosody_temp = float(cc.prosody_flow_temp if prosody_temp is None else prosody_temp)

        gen = torch.Generator().manual_seed(int(seed))
        self.register_buffer(
            "base_noise",
            torch.randn((1, c.max_frames, c.vocos_n_mels), generator=gen, dtype=torch.float32),
            persistent=False,
        )
        if model.dur_flow is not None:
            dur_gen = torch.Generator().manual_seed(int(seed) + 101)
            self.register_buffer(
                "base_dur_noise",
                torch.randn((1, c.max_tokens, 1), generator=dur_gen, dtype=torch.float32),
                persistent=False,
            )
        if model.prosody_flow is not None:
            pros_gen = torch.Generator().manual_seed(int(seed) + 202)
            self.register_buffer(
                "base_prosody_noise",
                torch.randn((1, c.max_frames, 2), generator=pros_gen, dtype=torch.float32),
                persistent=False,
            )

    def _velocity(

        self,

        x: torch.Tensor,

        t_val: float,

        cond: torch.Tensor,

        prior_mel: torch.Tensor,

        frame_mask: torch.Tensor,

        f0_feats: torch.Tensor | None,

    ) -> torch.Tensor:
        t_vec = torch.full((1,), float(t_val), device=x.device, dtype=torch.float32)
        v_c = self.model.flow(x, t_vec, cond, prior_mel, frame_mask, f0_feats=f0_feats)
        if self.cfg_scale == 1.0:
            return v_c
        v_u = self.model.flow(
            x,
            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 + self.cfg_scale * (v_c - v_u)

    def forward(

        self,

        tokens: torch.Tensor,

        stress: torch.Tensor,

        voice: torch.Tensor,

        speed: torch.Tensor,

        pitch_shift: torch.Tensor,

        pitch_range: torch.Tensor,

    ) -> tuple[torch.Tensor, torch.Tensor]:
        m, c = self.model, self.model.config
        mask = torch.ones_like(tokens, dtype=torch.bool)
        hidden = m.encoder(m.tokens(tokens) + m.stress(stress) + m.voices(voice)[:, None], mask)
        prosody_token_ctx, clause_ctx_tok = m.encode_prosody_context(hidden, tokens, stress, mask)

        raw = m.duration(prosody_token_ctx, mask).float()
        prior_z = raw[..., 0].clamp(0.0, math.log1p(400.0))
        if m.dur_flow is not None:
            sigma_d = m.cfm_config.dur_flow_sigma * self.dur_temp
            z = prior_z[..., None] + sigma_d * self.base_dur_noise[:, : tokens.shape[1], :]
            dt_d = 1.0 / max(self.dur_steps, 1)
            for i in range(self.dur_steps):
                t_d = torch.full((1,), i * dt_d, device=tokens.device, dtype=torch.float32)
                v_d = m.dur_flow(z, t_d, prior_z[..., None], prosody_token_ctx, mask)
                z = z + dt_d * v_d
            z1 = z.squeeze(-1)
        else:
            z1 = prior_z
        frames = torch.round((torch.exp(z1.clamp(0.0, math.log1p(400.0))) - 1.0) / speed).long().clamp_min(1)
        durations = torch.where(m.phone_tokens[tokens] | (raw[..., 1] > 0), frames, torch.zeros_like(frames))

        ends = durations.cumsum(1)
        total = ends[0, -1]
        frame = torch.arange(total, device=tokens.device)[None]
        # Cumulative comparison avoids torch.searchsorted which is absent from ONNX opset 17.
        index = (ends[:, :, None] <= frame[:, None, :]).sum(1).clamp(max=tokens.shape[1] - 1)
        owned = durations.gather(1, index).clamp_min(1)
        offset = frame - (ends.gather(1, index) - durations.gather(1, index))
        relative = (offset.float() + 0.5) / owned.float()
        features = torch.stack((relative, 1.0 - relative, torch.log1p(owned.float()) / 4.0), dim=-1)
        pos_voice = m.frame_position(features) + m.frame_voices(voice)[:, None]
        expanded = hidden.gather(1, index[..., None].expand(-1, -1, c.channels)) + pos_voice
        frame_mask = torch.ones((1, total), device=tokens.device, dtype=torch.bool)
        if m.context_adapter is not None or m.frame_ctx_proj is not None:
            prosody_frames = prosody_token_ctx.gather(1, index[..., None].expand(-1, -1, c.channels)) + pos_voice
            if m.frame_ctx_proj is not None:
                f_pos = (frame.float() + 0.5) / total.float()
                f_rem = 1.0 - f_pos
                c_f = clause_ctx_tok.gather(1, index[..., None].expand(-1, -1, 4))
                ctx_6 = torch.cat((f_pos[..., None], f_rem[..., None], c_f.float()), dim=-1)
                prosody_frames = prosody_frames + m.frame_ctx_proj(ctx_6)
        else:
            prosody_frames = expanded

        prosody_hidden, prosody = m.predict_prosody(prosody_frames, frame_mask)
        if m.prosody_flow is not None:
            eps_sm = smooth_prosody_noise(self.base_prosody_noise[:, :total, :], frame_mask, m.prosody_noise_kernel)
            prior_fe = torch.stack((prosody[..., 0].float(), prosody[..., 2].float()), dim=-1)
            voicing_prob = torch.sigmoid(prosody[..., 1:2].float())
            sigma_p = m.cfm_config.prosody_flow_sigma * self.prosody_temp
            y = prior_fe + sigma_p * eps_sm
            dt_p = 1.0 / max(self.prosody_steps, 1)
            for i in range(self.prosody_steps):
                t_p = torch.full((1,), i * dt_p, device=tokens.device, dtype=torch.float32)
                v_p = m.prosody_flow(y, t_p, prior_fe, voicing_prob, prosody_hidden, frame_mask)
                y = y + dt_p * v_p
            prosody = torch.cat((y[..., :1], prosody[..., 1:2].float(), y[..., 1:2]), dim=-1)

        is_vowel = m.vowel_tokens[tokens.gather(1, index)]
        prosody = torch.cat(
            (
                prosody[..., :1],
                torch.where(is_vowel, prosody[..., 1].clamp_min(1.0), prosody[..., 1])[..., None],
                prosody[..., 2:],
            ),
            dim=-1,
        )
        voiced = (prosody[..., 1] > 0).float()
        mean = (prosody[..., 0] * voiced).sum(1, keepdim=True) / voiced.sum(1, keepdim=True).clamp_min(1.0)
        pitch = mean + (prosody[..., 0] - mean) * pitch_range + pitch_shift
        prosody = torch.cat((pitch[..., None], prosody[..., 1:]), dim=-1)
        hard_p = m.hard_prosody(prosody)
        base_h = expanded if m.cfm_config.acoustic_from_frames else prosody_hidden
        cond, prior_mel = m.condition_and_prior(base_h, hard_p, frame_mask)
        f0_feats = f0_features(hard_p, frame_mask) if m.cfm_config.use_f0_harmonics else None

        sigma = m.cfm_config.prior_sigma * self.temperature
        noise_gate = energy_noise_gate(hard_p, frame_mask) if m.cfm_config.use_energy_gate else 1.0
        x = prior_mel + sigma * noise_gate * self.base_noise[:, :total, :]

        t_grid = m.sway_time_grid(self.n_steps, self.sway_coef)
        for i in range(self.n_steps):
            t0, t1 = t_grid[i], t_grid[i + 1]
            dt_i = t1 - t0
            v0 = self._velocity(x, t0, cond, prior_mel, frame_mask, f0_feats)
            if self.solver == "midpoint":
                v_mid = self._velocity(x + 0.5 * dt_i * v0, t0 + 0.5 * dt_i, cond, prior_mel, frame_mask, f0_feats)
                x = x + dt_i * v_mid
            else:
                x = x + dt_i * v0

        phys_mel = (x * m.vocoder.mel_scale + m.vocoder.mel_mean).clamp(min=-11.512925)
        frame_lengths = ends[:, -1].long()
        return phys_mel, frame_lengths


class _OnnxUpSample1d(nn.Module):
    """Static-channel ONNX-safe replacement for ``alias_free_activation.UpSample1d``."""

    def __init__(self, orig: nn.Module, channels: int) -> None:
        super().__init__()
        self.stride = int(orig.stride)
        self.pad = int(orig.pad)
        self.pad_left = int(orig.pad_left)
        self.pad_right = int(orig.pad_right)
        self.channels = int(channels)
        scaled = orig.filter.detach() * float(orig.ratio)
        self.register_buffer("weight", scaled.expand(self.channels, 1, -1).contiguous())

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        if self.pad > 0:
            left = x[:, :, :1].expand(-1, -1, self.pad)
            right = x[:, :, -1:].expand(-1, -1, self.pad)
            x = torch.cat((left, x, right), dim=-1)
        x = F.conv_transpose1d(x, self.weight, stride=self.stride, groups=self.channels)
        return x[:, :, self.pad_left : -self.pad_right]


class _OnnxLowPassFilter1d(nn.Module):
    """Static-channel ONNX-safe replacement for ``alias_free_activation.LowPassFilter1d``."""

    def __init__(self, orig: nn.Module, channels: int) -> None:
        super().__init__()
        self.stride = int(orig.stride)
        self.padding = bool(orig.padding)
        self.pad_left = int(orig.pad_left)
        self.pad_right = int(orig.pad_right)
        self.channels = int(channels)
        self.register_buffer("weight", orig.filter.detach().expand(self.channels, 1, -1).contiguous())

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        if self.padding:
            left = x[:, :, :1].expand(-1, -1, self.pad_left)
            right = x[:, :, -1:].expand(-1, -1, self.pad_right)
            x = torch.cat((left, x, right), dim=-1)
        return F.conv1d(x, self.weight, stride=self.stride, groups=self.channels)


def _make_bigvgan_onnx_safe(net: nn.Module) -> nn.Module:
    net_copy = copy.deepcopy(net).eval()
    for mod in net_copy.modules():
        if hasattr(mod, "act") and hasattr(mod, "upsample") and hasattr(mod, "downsample"):
            channels = int(getattr(mod.act, "in_features"))
            mod.upsample = _OnnxUpSample1d(mod.upsample, channels)
            mod.downsample.lowpass = _OnnxLowPassFilter1d(mod.downsample.lowpass, channels)
    return net_copy


class ExportableBigVGAN(nn.Module):
    """ONNX-traceable BigVGAN wrapper mapping physical log-mel ``[B, T, 100]`` -> audio ``[B, T*256]``."""

    def __init__(self, vocoder: BigVGANVocoderWrapper) -> None:
        super().__init__()
        self.net = _make_bigvgan_onnx_safe(vocoder.net)

    def forward(self, mel: torch.Tensor) -> torch.Tensor:
        return self.net(mel.transpose(1, 2).contiguous()).squeeze(1)


def _export_torch_onnx(

    module: nn.Module,

    args: tuple[torch.Tensor, ...],

    out_path: Path,

    input_names: list[str],

    output_names: list[str],

    dynamic_axes: dict[str, dict[int, str]],

    opset: int,

) -> Path:
    import onnx

    out_path.parent.mkdir(parents=True, exist_ok=True)
    kwargs = dict(
        input_names=input_names,
        output_names=output_names,
        dynamic_axes=dynamic_axes,
        opset_version=opset,
        do_constant_folding=True,
    )
    try:
        torch.onnx.export(module, args, str(out_path), dynamo=False, **kwargs)
    except TypeError:
        torch.onnx.export(module, args, str(out_path), **kwargs)
    onnx_model = onnx.load(str(out_path))
    onnx.checker.check_model(onnx_model)
    return out_path


def export_cfm_onnx(

    cfm_path_or_model: Path | str | LuaNovaCFM,

    out_path: Path | str,

    n_steps: int = 2,

    cfg_scale: float = 1.0,

    temperature: float = 0.35,

    solver: str = "euler",

    sway_coef: float = 0.0,

    seed: int = 0,

    opset: int = 17,

) -> Path:
    """Export LuaNovaCFM acoustic predictor to ONNX + companion ``.meta.json``."""
    model = (
        cfm_path_or_model
        if isinstance(cfm_path_or_model, LuaNovaCFM)
        else load_cfm_model(cfm_path_or_model, device="cpu", load_vocos=False)
    ).cpu().eval()
    wrapper = ExportableCFMAcoustic(
        model,
        n_steps=n_steps,
        cfg_scale=cfg_scale,
        temperature=temperature,
        solver=solver,
        sway_coef=sway_coef,
        seed=seed,
    ).eval()
    dummy = example_cfm_inputs()
    target = Path(out_path)
    with torch.no_grad():
        _export_torch_onnx(
            wrapper,
            dummy,
            target,
            input_names=list(CFM_INPUTS),
            output_names=list(CFM_OUTPUTS),
            dynamic_axes={"tokens": {1: "tokens"}, "stress": {1: "tokens"}, "phys_mel": {1: "frames"}},
            opset=opset,
        )
    meta = {
        "sample_rate": int(model.config.sample_rate),
        "hop": int(model.config.hop),
        "n_mels": int(model.config.vocos_n_mels),
        "max_tokens": int(model.config.max_tokens),
        "speakers": list(model.config.speakers),
        "n_steps": int(n_steps),
        "solver": str(solver),
        "sway_coef": float(sway_coef),
        "temperature": float(temperature),
        "cfg_scale": float(cfg_scale),
        "seed": int(seed),
        "frontend": {**frontend_identity(), "fingerprint": frontend_fingerprint()},
    }
    meta_path = target.with_suffix(".meta.json")
    meta_path.write_text(json.dumps(meta, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
    return target


def export_bigvgan_onnx(

    vocoder_path_or_id: Path | str | BigVGANVocoderWrapper,

    out_path: Path | str,

    opset: int = 17,

    dummy_frames: int = 40,

) -> Path:
    """Export MIT BigVGAN 24 kHz 100-band vocoder to dynamic-length ONNX."""
    if isinstance(vocoder_path_or_id, BigVGANVocoderWrapper):
        vocoder = vocoder_path_or_id.cpu().eval()
    else:
        voc_target = Path(vocoder_path_or_id)
        if voc_target.is_file():
            vocoder = BigVGANVocoderWrapper(ckpt_path=voc_target, device="cpu")
        else:
            vocoder = BigVGANVocoderWrapper(model_id=str(vocoder_path_or_id), device="cpu")
    wrapper = ExportableBigVGAN(vocoder).eval()
    dummy_mel = torch.full((1, int(dummy_frames), 100), -5.0, dtype=torch.float32)
    target = Path(out_path)
    with torch.no_grad():
        return _export_torch_onnx(
            wrapper,
            (dummy_mel,),
            target,
            input_names=list(BIGVGAN_INPUTS),
            output_names=list(BIGVGAN_OUTPUTS),
            dynamic_axes={"mel": {1: "frames"}, "audio": {1: "samples"}},
            opset=opset,
        )


def verify_cfm_onnx(

    cfm_path_or_model: Path | str | LuaNovaCFM,

    onnx_path: Path | str,

    n_steps: int = 2,

    cfg_scale: float = 1.0,

    temperature: float = 0.35,

    solver: str = "euler",

    sway_coef: float = 0.0,

    seed: int = 0,

    text: str = "Olá, tudo bem com você hoje?",

) -> dict[str, float]:
    """Compare exported ONNX acoustic predictions against PyTorch ``ExportableCFMAcoustic``."""
    import onnxruntime as ort

    model = (
        cfm_path_or_model
        if isinstance(cfm_path_or_model, LuaNovaCFM)
        else load_cfm_model(cfm_path_or_model, device="cpu", load_vocos=False)
    ).cpu().eval()
    wrapper = ExportableCFMAcoustic(
        model,
        n_steps=n_steps,
        cfg_scale=cfg_scale,
        temperature=temperature,
        solver=solver,
        sway_coef=sway_coef,
        seed=seed,
    ).eval()
    inputs = example_cfm_inputs(text=text, device="cpu")
    with torch.no_grad():
        mel_pt, flen_pt = wrapper(*inputs)
    sess = ort.InferenceSession(str(onnx_path), providers=["CPUExecutionProvider"])
    feed = {name: arr.numpy() for name, arr in zip(CFM_INPUTS, inputs)}
    mel_ort, flen_ort = sess.run(list(CFM_OUTPUTS), feed)
    diff = np.abs(mel_pt.numpy() - mel_ort)
    return {
        "max_abs_diff": float(diff.max()),
        "mean_abs_diff": float(diff.mean()),
        "frames_match": float(int(flen_pt.item()) == int(flen_ort.item())),
        "frames": float(int(flen_ort.item())),
    }


def verify_bigvgan_onnx(

    vocoder_path_or_id: Path | str | BigVGANVocoderWrapper,

    onnx_path: Path | str,

    test_frames: int = 67,

) -> dict[str, float]:
    """Compare exported BigVGAN ONNX output against PyTorch at an arbitrary frame length."""
    import onnxruntime as ort

    if isinstance(vocoder_path_or_id, BigVGANVocoderWrapper):
        vocoder = vocoder_path_or_id.cpu().eval()
    else:
        voc_target = Path(vocoder_path_or_id)
        if voc_target.is_file():
            vocoder = BigVGANVocoderWrapper(ckpt_path=voc_target, device="cpu")
        else:
            vocoder = BigVGANVocoderWrapper(model_id=str(vocoder_path_or_id), device="cpu")
    mel = torch.randn((1, int(test_frames), 100), dtype=torch.float32) * 0.5 - 5.0
    flen = torch.tensor([test_frames], dtype=torch.long)
    with torch.no_grad():
        wav_pt = vocoder.decode_raw_mel(mel, flen).numpy()
    sess = ort.InferenceSession(str(onnx_path), providers=["CPUExecutionProvider"])
    (wav_ort,) = sess.run(list(BIGVGAN_OUTPUTS), {"mel": mel.numpy()})
    diff = np.abs(wav_pt - wav_ort)
    return {
        "max_abs_diff": float(diff.max()),
        "mean_abs_diff": float(diff.mean()),
        "samples": float(wav_ort.shape[-1]),
    }


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--cfm", type=Path, default=None, help="Path to CFM v5 checkpoint (.pt)")
    parser.add_argument("--vocoder", default=None, help="Path to BigVGAN .pt checkpoint or HF model ID")
    parser.add_argument("--out-dir", type=Path, required=True)
    parser.add_argument("--cfm-name", default="cfm_v5.onnx")
    parser.add_argument("--vocoder-name", default="bigvgan_base_ft.onnx")
    parser.add_argument("--steps", type=int, default=2)
    parser.add_argument("--solver", default="euler", choices=["euler", "midpoint"])
    parser.add_argument("--sway-coef", type=float, default=0.0)
    parser.add_argument("--temperature", type=float, default=0.35)
    parser.add_argument("--cfg-scale", type=float, default=1.0)
    parser.add_argument("--seed", type=int, default=0)
    parser.add_argument("--opset", type=int, default=17)
    parser.add_argument("--verify", action="store_true")
    args = parser.parse_args()

    if args.cfm is None and args.vocoder is None:
        parser.error("provide at least --cfm or --vocoder")

    args.out_dir.mkdir(parents=True, exist_ok=True)
    if args.cfm is not None:
        cfm_out = export_cfm_onnx(
            args.cfm,
            args.out_dir / args.cfm_name,
            n_steps=args.steps,
            cfg_scale=args.cfg_scale,
            temperature=args.temperature,
            solver=args.solver,
            sway_coef=args.sway_coef,
            seed=args.seed,
            opset=args.opset,
        )
        print(f"Exported CFM ONNX -> {cfm_out}", flush=True)
        if args.verify:
            stats = verify_cfm_onnx(
                args.cfm,
                cfm_out,
                n_steps=args.steps,
                cfg_scale=args.cfg_scale,
                temperature=args.temperature,
                solver=args.solver,
                sway_coef=args.sway_coef,
                seed=args.seed,
            )
            print("CFM parity:", json.dumps(stats), flush=True)

    if args.vocoder is not None:
        voc_out = export_bigvgan_onnx(args.vocoder, args.out_dir / args.vocoder_name, opset=args.opset)
        print(f"Exported BigVGAN ONNX -> {voc_out}", flush=True)
        if args.verify:
            stats = verify_bigvgan_onnx(args.vocoder, voc_out)
            print("BigVGAN parity:", json.dumps(stats), flush=True)


if __name__ == "__main__":
    main()