Luigi commited on
Commit
32b0a98
·
verified ·
1 Parent(s): a0e4648

Upload scripts/export_onnx_primetts_v21.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. scripts/export_onnx_primetts_v21.py +172 -0
scripts/export_onnx_primetts_v21.py ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Export PrimeTTS v2 (MB-iSTFT-VITS, Xinran G_400000) to ONNX for the demo Space
3
+ (ORT-CPU). opset17, dynamo=False per the project's validated export contract.
4
+
5
+ torch.istft has no ONNX op, so the tiny gen-head iSTFT (n_fft=16, hop=4) is replaced
6
+ by an exact equivalent: irFFT as a fixed matrix product + windowed overlap-add via
7
+ ConvTranspose1d + window-envelope normalization (verified vs torch.istft before export).
8
+
9
+ Inputs : x[1,T] int64, tone[1,T] int64, lang[1,T] int64, x_lengths[1] int64,
10
+ noise_scale[1] f32, length_scale[1] f32
11
+ Output : wav[1,1,L] f32 @16kHz
12
+ """
13
+ import argparse, json, math, os, sys
14
+
15
+ import numpy as np
16
+ import torch
17
+
18
+ _ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
19
+ sys.path.insert(0, _ROOT)
20
+
21
+ from models import SynthesizerTrn
22
+ import models as models_mod
23
+
24
+
25
+ class OnnxISTFT(torch.nn.Module):
26
+ """Drop-in for TorchSTFT.inverse (center=True), ONNX-exportable, exact."""
27
+
28
+ def __init__(self, n_fft, hop, window):
29
+ super().__init__()
30
+ self.n_fft, self.hop = n_fft, hop
31
+ n_bins = n_fft // 2 + 1
32
+ k = torch.arange(n_bins).unsqueeze(1).float()
33
+ n = torch.arange(n_fft).unsqueeze(0).float()
34
+ coef = torch.full((n_bins, 1), 2.0)
35
+ coef[0, 0] = 1.0
36
+ if n_fft % 2 == 0:
37
+ coef[-1, 0] = 1.0
38
+ ang = 2 * math.pi * k * n / n_fft
39
+ self.register_buffer("C", (coef * torch.cos(ang)) / n_fft) # [bins, n_fft]
40
+ self.register_buffer("S", (-coef * torch.sin(ang)) / n_fft) # [bins, n_fft]
41
+ self.register_buffer("win", window.reshape(1, -1, 1)) # [1, n_fft, 1]
42
+ ola_k = torch.eye(n_fft).unsqueeze(1) # [n_fft,1,n_fft]
43
+ self.register_buffer("ola_kernel", ola_k)
44
+ self.register_buffer("env_kernel", (window ** 2).reshape(1, 1, -1))
45
+
46
+ def inverse(self, magnitude, phase):
47
+ real = magnitude * torch.cos(phase) # [B, bins, T]
48
+ imag = magnitude * torch.sin(phase)
49
+ # frames[b, n, t] = sum_k real[b,k,t]*C[k,n] + imag[b,k,t]*S[k,n]
50
+ frames = torch.einsum("bkt,kn->bnt", real, self.C) + \
51
+ torch.einsum("bkt,kn->bnt", imag, self.S)
52
+ frames = frames * self.win # analysis window
53
+ y = torch.nn.functional.conv_transpose1d(frames, self.ola_kernel, stride=self.hop)
54
+ ones = torch.ones_like(frames[:, :1, :])
55
+ env = torch.nn.functional.conv_transpose1d(ones, self.env_kernel, stride=self.hop)
56
+ y = y / torch.clamp(env, min=1e-9)
57
+ half = self.n_fft // 2
58
+ y = y[:, :, half:-half] # center=True trim
59
+ return y # [B,1,L] (matches TorchSTFT.inverse's unsqueeze(-2))
60
+
61
+
62
+ class ExportWrapper(torch.nn.Module):
63
+ def __init__(self, net):
64
+ super().__init__()
65
+ self.net = net
66
+
67
+ def forward(self, x, tone, lang, x_lengths, sid, noise_scale, length_scale):
68
+ o, *_ = self.net.infer(x, tone, lang, x_lengths, sid=sid,
69
+ noise_scale=noise_scale, length_scale=length_scale)
70
+ return o
71
+
72
+
73
+ def main():
74
+ ap = argparse.ArgumentParser()
75
+ ap.add_argument("--ckpt", default="/home/luigi/mbvits_run/keep_v21b_12500_G.pth")
76
+ ap.add_argument("--config", default=os.path.join(_ROOT, "configs", "zhtw_mb_istft_16k_v21b.json"))
77
+ ap.add_argument("--out", default="/home/luigi/mbvits_run/primetts_v21_3voice.onnx")
78
+ args = ap.parse_args()
79
+
80
+ cfg = json.load(open(args.config))
81
+ m, d = cfg["model"], cfg["data"]
82
+ net = SynthesizerTrn(88, d["filter_length"] // 2 + 1,
83
+ cfg["train"]["segment_size"] // d["hop_length"], **m)
84
+ sd = torch.load(args.ckpt, map_location="cpu", weights_only=False)["model"]
85
+ sd = {(k[7:] if k.startswith("module.") else k): v for k, v in sd.items()}
86
+ net.load_state_dict(sd, strict=True)
87
+ net.eval()
88
+ net.dec.remove_weight_norm()
89
+
90
+ # numeric check of OnnxISTFT vs torch.istft BEFORE swapping it in
91
+ ts = net.dec.stft if hasattr(net.dec, "stft") else None
92
+ # Multiband generator constructs TorchSTFT inline in forward via module-level import;
93
+ # check models.py: it uses `stft.inverse(...)` where stft is built in forward? Inspect:
94
+ oi = OnnxISTFT(m["gen_istft_n_fft"], m["gen_istft_hop_size"],
95
+ torch.hann_window(m["gen_istft_n_fft"]))
96
+ from stft import TorchSTFT
97
+ ref = TorchSTFT(filter_length=m["gen_istft_n_fft"], hop_length=m["gen_istft_hop_size"],
98
+ win_length=m["gen_istft_n_fft"])
99
+ mag = torch.rand(4, m["gen_istft_n_fft"] // 2 + 1, 57) + 0.1
100
+ ph = (torch.rand(4, m["gen_istft_n_fft"] // 2 + 1, 57) - 0.5) * 2 * math.pi
101
+ a = ref.inverse(mag, ph)
102
+ b = oi.inverse(mag, ph)
103
+ err = (a - b).abs().max().item()
104
+ print(f"[istft-check] torch vs onnx-istft max abs err = {err:.3e} shapes {tuple(a.shape)} {tuple(b.shape)}")
105
+ assert err < 1e-4, "OnnxISTFT mismatch"
106
+
107
+ # swap: the MB generator calls `stft.inverse(spec, phase)` on a TorchSTFT instance
108
+ # created in its forward (models.py line ~330: stft = TorchSTFT(...).to(x.device)).
109
+ # Patch the class used by models.py so the instance built in forward IS ours.
110
+ class PatchedTorchSTFT(torch.nn.Module):
111
+ def __init__(self, filter_length=16, hop_length=4, win_length=16, window="hann"):
112
+ super().__init__()
113
+ self._oi = OnnxISTFT(filter_length, hop_length, torch.hann_window(win_length))
114
+ def inverse(self, magnitude, phase):
115
+ return self._oi.inverse(magnitude, phase)
116
+ def to(self, *a, **k):
117
+ return self
118
+ models_mod.TorchSTFT = PatchedTorchSTFT
119
+ import stft as stft_mod
120
+ stft_mod.TorchSTFT = PatchedTorchSTFT
121
+
122
+ # PQMF hardcodes .cuda(); rebuild it CPU-safe with identical filters
123
+ from pqmf import design_prototype_filter
124
+
125
+ class CpuPQMF(torch.nn.Module):
126
+ def __init__(self, device=None, subbands=4, taps=62, cutoff_ratio=0.15, beta=9.0):
127
+ super().__init__()
128
+ h_proto = design_prototype_filter(taps, cutoff_ratio, beta)
129
+ h_synthesis = np.zeros((subbands, len(h_proto)))
130
+ for k in range(subbands):
131
+ h_synthesis[k] = 2 * h_proto * np.cos(
132
+ (2 * k + 1) * (np.pi / (2 * subbands)) *
133
+ (np.arange(taps + 1) - ((taps - 1) / 2)) - (-1) ** k * np.pi / 4)
134
+ self.register_buffer("synthesis_filter",
135
+ torch.from_numpy(h_synthesis).float().unsqueeze(0))
136
+ updown = torch.zeros((subbands, subbands, subbands))
137
+ for k in range(subbands):
138
+ updown[k, k, 0] = 1.0
139
+ self.register_buffer("updown_filter", updown)
140
+ self.subbands = subbands
141
+ self.pad_fn = torch.nn.ConstantPad1d(taps // 2, 0.0)
142
+
143
+ def synthesis(self, x):
144
+ x = torch.nn.functional.conv_transpose1d(
145
+ x, self.updown_filter * self.subbands, stride=self.subbands)
146
+ return torch.nn.functional.conv1d(self.pad_fn(x), self.synthesis_filter)
147
+
148
+ def to(self, *a, **k):
149
+ return self
150
+
151
+ models_mod.PQMF = CpuPQMF
152
+
153
+ wrap = ExportWrapper(net)
154
+ T = 33
155
+ ex = (torch.randint(1, 87, (1, T)), torch.randint(0, 6, (1, T)),
156
+ torch.randint(0, 2, (1, T)), torch.tensor([T], dtype=torch.long),
157
+ torch.tensor([0], dtype=torch.long), torch.tensor([0.667], dtype=torch.float32), torch.tensor([1.0], dtype=torch.float32))
158
+ with torch.no_grad():
159
+ wav = wrap(*ex)
160
+ print(f"[trace-check] eager wav {tuple(wav.shape)}")
161
+
162
+ torch.onnx.export(
163
+ wrap, ex, args.out, opset_version=17, dynamo=False,
164
+ input_names=["x", "tone", "lang", "x_lengths", "sid", "noise_scale", "length_scale"],
165
+ output_names=["wav"],
166
+ dynamic_axes={"x": {1: "T"}, "tone": {1: "T"}, "lang": {1: "T"}, "wav": {2: "L"}},
167
+ )
168
+ print(f"[export] wrote {args.out} ({os.path.getsize(args.out)/1e6:.1f} MB)")
169
+
170
+
171
+ if __name__ == "__main__":
172
+ main()