voc: stop at the ISTFT head projection, ship spec
Browse files- kaggle/export_browser.py +35 -16
kaggle/export_browser.py
CHANGED
|
@@ -167,41 +167,60 @@ def stage_agg(mm, torch) -> dict:
|
|
| 167 |
|
| 168 |
|
| 169 |
def stage_voc(mm, torch) -> dict:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 170 |
import onnxruntime as ort
|
| 171 |
|
| 172 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 173 |
|
| 174 |
-
class
|
| 175 |
def __init__(self):
|
| 176 |
super().__init__()
|
| 177 |
-
self.
|
| 178 |
|
| 179 |
def forward(self, latent):
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
|
|
|
|
|
|
| 183 |
|
| 184 |
-
voc =
|
| 185 |
T = 8
|
| 186 |
-
dev = next(
|
| 187 |
dummy = torch.randn(1, T, mm.latent_dim, device=dev)
|
| 188 |
with torch.no_grad():
|
| 189 |
ref = voc(dummy)
|
| 190 |
-
log(f"
|
| 191 |
-
if ref.dim() == 2:
|
| 192 |
-
ref = ref.unsqueeze(1)
|
| 193 |
|
| 194 |
path = OUT / "voc.onnx"
|
| 195 |
torch.onnx.export(voc, (dummy,), str(path), input_names=["latent"],
|
| 196 |
-
output_names=["
|
| 197 |
opset_version=20, do_constant_folding=True, dynamo=False)
|
| 198 |
sess = ort.InferenceSession(str(path), providers=["CPUExecutionProvider"])
|
| 199 |
got = sess.run(None, {"latent": np_(dummy)})[0]
|
| 200 |
-
if got.ndim == 2:
|
| 201 |
-
got = got[:, None]
|
| 202 |
c = cosine(np_(ref), got)
|
| 203 |
-
log(f"voc.onnx {path.stat().st_size / 1e6:.0f} MB cos={c:.6f}
|
| 204 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 205 |
|
| 206 |
|
| 207 |
def quantize(paths: list[Path], bits: int = 4) -> list[dict]:
|
|
|
|
| 167 |
|
| 168 |
|
| 169 |
def stage_voc(mm, torch) -> dict:
|
| 170 |
+
"""Export the vocoder up to the ISTFT head's linear projection.
|
| 171 |
+
|
| 172 |
+
`decode` ends in a complex STFT, which ONNX cannot represent. The head does
|
| 173 |
+
`linear -> (mag, phase) -> complex -> istft`, so the last real-valued tensor
|
| 174 |
+
is the projection output. The host does the rest, matching the documented
|
| 175 |
+
`voc -> spec` contract.
|
| 176 |
+
"""
|
| 177 |
import onnxruntime as ort
|
| 178 |
|
| 179 |
+
dec = mm.audio.decoder
|
| 180 |
+
head = dec.head
|
| 181 |
+
lin = getattr(head, "linear", None)
|
| 182 |
+
if lin is None:
|
| 183 |
+
lin = next((m for m in head.modules() if isinstance(m, torch.nn.Linear)), None)
|
| 184 |
+
if lin is None:
|
| 185 |
+
raise RuntimeError("could not find the ISTFT head projection layer")
|
| 186 |
+
log(f"head projection: out_features={getattr(lin, 'out_features', '?')}")
|
| 187 |
|
| 188 |
+
class VocSpec(torch.nn.Module):
|
| 189 |
def __init__(self):
|
| 190 |
super().__init__()
|
| 191 |
+
self.dec = dec
|
| 192 |
|
| 193 |
def forward(self, latent):
|
| 194 |
+
x = self.dec.fc1(latent)
|
| 195 |
+
if getattr(self.dec, "patch_size", -1) != -1:
|
| 196 |
+
x = self.dec.upsampling.upsampler(x.transpose(1, 2)).transpose(1, 2)
|
| 197 |
+
x = self.dec.decoder(inputs_embeds=x).last_hidden_state
|
| 198 |
+
return lin(x)
|
| 199 |
|
| 200 |
+
voc = VocSpec().float().eval()
|
| 201 |
T = 8
|
| 202 |
+
dev = next(dec.parameters()).device
|
| 203 |
dummy = torch.randn(1, T, mm.latent_dim, device=dev)
|
| 204 |
with torch.no_grad():
|
| 205 |
ref = voc(dummy)
|
| 206 |
+
log(f"spec shape {tuple(ref.shape)}")
|
|
|
|
|
|
|
| 207 |
|
| 208 |
path = OUT / "voc.onnx"
|
| 209 |
torch.onnx.export(voc, (dummy,), str(path), input_names=["latent"],
|
| 210 |
+
output_names=["spec"], dynamic_axes={"latent": {1: "t"}},
|
| 211 |
opset_version=20, do_constant_folding=True, dynamo=False)
|
| 212 |
sess = ort.InferenceSession(str(path), providers=["CPUExecutionProvider"])
|
| 213 |
got = sess.run(None, {"latent": np_(dummy)})[0]
|
|
|
|
|
|
|
| 214 |
c = cosine(np_(ref), got)
|
| 215 |
+
log(f"voc.onnx {path.stat().st_size / 1e6:.0f} MB cos={c:.6f} spec={got.shape}")
|
| 216 |
+
|
| 217 |
+
meta = {"n_fft": int(head.n_fft), "hop_length": int(head.hop_length),
|
| 218 |
+
"padding": str(getattr(head, "padding", "same")),
|
| 219 |
+
"spec_bins": int(got.shape[-1]), "frames_per_latent": T}
|
| 220 |
+
(OUT / "voc_meta.json").write_text(json.dumps(meta, indent=1))
|
| 221 |
+
log(f"voc meta {meta}")
|
| 222 |
+
return {"graph": "voc", "mb": round(path.stat().st_size / 1e6, 1), "cos": c,
|
| 223 |
+
"spec_shape": list(got.shape)}
|
| 224 |
|
| 225 |
|
| 226 |
def quantize(paths: list[Path], bits: int = 4) -> list[dict]:
|