Skip to content

feat(tts/supertonic-3): add Supertonic-3 ONNX→PyTorch→CoreML port - #64

Merged
Alex-Wengg merged 5 commits into
mainfrom
feat/tts-supertonic-3
May 19, 2026
Merged

Alex-Wengg merged 5 commits into
mainfrom
feat/tts-supertonic-3

Conversation

@Alex-Wengg

Copy link
Copy Markdown
Member

Summary

  • Hand-port of Supertone Supertonic-3 v1.7.3 (31 languages, 44.1 kHz, flow-matching diffusion, 8 denoising steps) from ONNX → PyTorch → CoreML, targeting iOS 18+ / macOS 14+ via mlprogram FP32 on CPU+ANE.
  • Four sub-networks (text_encoder, duration_predictor, vector_estimator, vocoder) reimplemented in PyTorch against the published tts.json hyperparameters with weights loaded directly from ONNX initializers by name, then traced + converted via coremltools.convert.
  • End-to-end PyTorch (infer.py) and CoreML (infer_coreml.py) drivers included. On M-series CPU+ANE the CoreML driver synthesises 6.32 s of English audio in ~0.74 s (RTFx ≈ 8.5x), ASR-validated against FluidAudio Parakeet TDT.
  • New layout: models/tts/supertonic-3/ with pyproject.toml + README.md + coreml/ containing the 4 PyTorch ports, conversion + parity scripts, and trials.md.

Parity vs ONNX-Runtime CPU

Module PyTorch vs ONNX max_abs CoreML vs PyTorch max_abs mlpackage size
vocoder 2.5e-4 1.4e-6 97 MB
text_encoder 9.8e-2 (relaxed tol) 2.3e-4 35 MB
duration_predictor 3.0e-6 3.8e-6 3.5 MB
vector_estimator 1.2e-3 3.0e-5 244 MB

Notable findings (full log in trials.md)

  • CFG via batch-2 duplication — vector_estimator tiles inputs to batch=2, runs cond + uncond in parallel, combines with (noisy + (1/total)*(4*cond − 3*uncond)) * mask. The cond style key is not the user style_ttl; it is a learned initializer (/vector_estimator/Expand_output_0).
  • Rotary is length-normalized — angles = (pos / sum(mask)) * theta, divisor differs for Q (latent_mask) and K (text_mask).
  • Attention divisor is 16.0, not sqrt(dk)=8. Off-by-2× scaling buried inside score magnitudes.
  • Style attention applies tanh(K) before the score matmul; text attention does not.
  • CoreML constraints: text.T is pinned to 128 for text_encoder + duration_predictor (relative-position pad blocks dynamic), vector_estimator/vocoder use RangeDim floored by (K−1)*D/2 (replicate-pad lower bound).
  • Python 3.14 has no BlobWriter — pin requires-python = ">=3.11,<3.13".

Test plan

  • Per-module PyTorch vs ONNX parity (coreml/validate.py) — within tolerance
  • Per-module CoreML vs PyTorch parity (coreml/verify_coreml.py) — within tolerance
  • End-to-end PyTorch wav generation (coreml/infer.py) — ASR-verified
  • End-to-end CoreML wav generation (coreml/infer_coreml.py) — ASR-verified
  • (reviewer) cd models/tts/supertonic-3 && uv sync succeeds

Hand-port of Supertone Supertonic-3 v1.7.3 (31 languages, 44.1 kHz,
flow-matching diffusion, 8 denoising steps) from ONNX to PyTorch to
CoreML. Each of the four sub-networks (text_encoder,
duration_predictor, vector_estimator, vocoder) is reimplemented in
PyTorch against the published tts.json hyperparameters with weights
loaded directly from the ONNX initializers by name, then traced with
torch.jit.trace and converted to CoreML mlprogram targeting iOS 18+.

Layout:
- coreml/{text_encoder,duration_predictor,vector_estimator,vocoder}.py
  PyTorch ports + build_*_from_onnx loaders.
- coreml/common.py  ONNX-graph helpers shared by all ports.
- coreml/convert_coreml.py  PyTorch trace → 4 .mlpackage outputs.
- coreml/validate.py / verify_coreml.py  ONNX vs PyTorch and CoreML
  vs PyTorch parity harnesses.
- coreml/infer.py  end-to-end PyTorch TTS driver (text → wav).
- coreml/infer_coreml.py  end-to-end CoreML TTS driver (text → wav).
- coreml/trials.md  numerical-parity bug log; documents the four
  non-obvious vector_estimator bugs (CFG via batch-2 duplication,
  length-normalized rotary, attention divisor = 16, tanh(K) in
  style_attn) and the per-module CoreML conversion gotchas
  (Python 3.14 BlobWriter absence, aten::Int on shape reads,
  replicate-pad lower bound, EnumeratedShapes needing iOS 18,
  int32 token wrapper).

Final parity vs ONNX-Runtime CPU: vocoder 2.5e-4, text_encoder
9.8e-2 (relaxed tol), duration_predictor 3.0e-6, vector_estimator
1.2e-3. CoreML vs PyTorch: all four modules within 3e-4.

End-to-end CoreML on M-series CPU+ANE: ~0.74 s to synthesize 6.32 s
of English audio (RTFx ≈ 8.5x), ASR-validated. Used by FluidAudio's
Supertonic3Manager in `Sources/FluidAudio/TTS/Supertonic3/`.
3/4 modules land on ANE with FP16 (FP32 forces 0% ANE everywhere). The
vector_estimator has 89.6% ops ANE-eligible but ANE plan build still
fails on one bool tile op in style-attention; falls back to CPU+GPU.

- convert_coreml.py: --fp16 flag, default kept FP32 for parity verify
- convert_ve_fixed.py: fixed-L variant to bypass RangeDim ANE limits
- trials.md: ANE profile section (M2), bool-tile blocker, EnumShapes
  stride gotcha, per-module compute-unit recommendations
- README.md: FP16 sizes, conversion commands, profile table
Replaces four bool-mask sites (masked_fill / where) with float additive
or multiplicative masking so the FP16 vector_estimator no longer trips
the ANE `bool tile` rejection.

Sites:
- vector_estimator.py text-attn: `scores - (1.0 - mask) * 1e4`
- vector_estimator.py style-attn: `attn * mask` (post-softmax)
- common.py RelPosSelfAttention: additive (same as above)
- text_encoder.py post-softmax: multiplicative (same as above)

PyTorch ↔ ONNX parity preserved within tolerance (max_abs unchanged).
End-to-end CoreML FP16 quality confirmed via FluidAudio Parakeet ASR
(0.939 confidence).

ANE eligibility for vector_estimator (fixed L=128 T=128) improves
89.6% → 93.0%; the rejected ops now match the expected fp32/fp16
boundary set (no bool, no tile, no select). However, the ANE plan
build still fails with opaque `ANECCompile() FAILED (11)` at both
L=128 and L=64 — documented as the residual blocker in trials.md.

Also adds a `_patch_int_cast` workaround to convert_coreml.py for a
coremltools `_cast` bug that crashes on (1,)-shape int tensors fed
into `aten::Int`.
Records four more failed attempts to land vector_estimator on ANE after
the float-mask refactor:
- L=64, L=256: identical 93.0% eligibility / ANECCompile() FAILED (11) —
  size is not the issue
- iOS17 target: same failure — not iOS18-specific
- FP16 inputs/outputs: lifts eligibility to 94.1% (drops 8 boundary
  casts) but same failure — boundary casts aren't the issue either

GPU is no faster than CPU at L=128 (32.5ms vs 31.2ms), so there is no
easy "fall back to GPU" win either.

Diagnoses the residual as a partition-island problem: the 40-48 CPU
fallback ops cluster into two non-ANE subgraphs (timestep embedding head
and rotary positional encoding) that force the ANE compiler to plan
multiple ANE↔CPU regions, which it rejects with opaque error 11.

Next-step candidate (not tried): precompute timestep embedding and
rotary sin/cos tables on CPU, pass as extra model inputs. Estimated
~50ms / generation gain (RTFx 17 → 22) for ~1-2h refactor + parity
reverify, with no guarantee error 11 isn't masking a deeper blocker.
…proves partition-island hypothesis

Round 3 attempt: authored vector_estimator_ane.py (parallel module, shared
weights) that precomputes time_emb, rotary cos/sin tables, and inv_total_step
on host and feeds them in as extra inputs. Eliminates the TimeEncoder MLP,
rotary angle computation, and CFG inverse subgraphs from the model body.

Parity vs original is bit-exact (max_abs = 0.000e+00).

Result at L=128, T=128, FP16 I/O, iOS18:
  644/644 ops on ANE (100.0%), 0 on CPU
  E5RT: ANECCompile() FAILED (11)

So the partition-island hypothesis was wrong — even a fully ANE-pure
subgraph (zero CPU fallback ops) trips the same opaque error 11. Remaining
hypotheses are all Apple-side: weight footprint exceeds plan budget,
batch-2 CFG intermediate-buffer overflow, or an op-pattern codegen bug.
No model-side change short of restructuring the architecture itself is
likely to land it. Stop chasing ANE for VectorEstimator; keep cpu_and_gpu
or all for E2E RTFx ≈ 17.
@Alex-Wengg
Alex-Wengg merged commit dde9d62 into main May 19, 2026
@Alex-Wengg
Alex-Wengg deleted the feat/tts-supertonic-3 branch May 19, 2026 03:30
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant