"""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()