Repository navigation
feat: xTTS v2 support - #876
Conversation
Full xTTSv2 text-to-speech port including: - GPT-2 based mel code generator with causal flash attention - ConditioningEncoder (latent_encoder) with GroupNorm32 + 16-head QKV attention - PerceiverResampler with GEGLU FFN and parameter-free RMSNorm - HiFi-GAN HiFiDecoder with 5x speaker conditioning injection points - ResNet SpeakerEncoder with Attentive Statistics Pooling (ASP) - BPE tokenizer with full text normalization (abbreviations, symbols, numbers) Key implementation details: - GGML graph-based latent extraction with proper causal masking and flash-attn output merge (no permute - result layout is already merged) - Host-side incremental generation (gpt_gen) with KV cache for AR decoding - Correct conditioning mel: HTK scale, reflect padding, n_fft=2048 hop=256, 4-second chunk averaging with mel_norms division - Double LayerNorm in GPT head (ln_f + final_norm per HF GPT2Model) - Speaker encoder: Hamming window, log-power mels, InstanceNorm, ASP pooling - Vocoder: 4.35x total upsampling (4x frame + 24k/22k rate conversion) Verified: extract latents match PyTorch reference cos=1.0000 at all positions. Whisper transcriptions are exact across multiple test sentences and voices. Also: add language field to transcription JSON response (runtime.cpp)
|
Test WAV: final2.wav |
|
@whoreson Thanks for working on XTTS v2. I’m open to supporting it, but the current implementation needs substantial cleanup before review:
Please keep the changes scoped to the model and necessary integration. These are structural requirements, independent of whether the current implementation produces recognizable speech. |
|
Sweet. Then I'll develop with a merge in mind, instead of just yoloing locally. |
…ndow centering + reflect pad, stem relu/bn order + missing bias, SE-block final relu), 6s conditioning chunks; pipeline verified vs reference
…cond mel (17.4s->0.01s/chunk), OpenMP-parallel cond_enc/perceiver/h_c1d, batched GEMM prefix prefill, speaker encoder input truncated to 30s (matches reference), --threads now propagates via n_threads request option; XTTS_TIMING env-gated phase timing
…er change, move model under community_models
… shared execution threads, session reports load failures instead of silent defaults
…longform, torchaudio-compatible framework resampling, session-owned conditioning cache, proper error reporting
…, positions inner; reduces prefix batch traffic from 76GB to 1.5GB
- Add convert_xtts_v2_to_gguf.py: PyTorch -> GGUF converter producing GPT and vocoder GGUF files for audio.cpp. Includes llama-quantize commands in docstring for Q8_0/Q4_0 (1.7GB -> 492MB Q8_0 / 290MB Q4_0). - Fix tconv1d() to handle quantized tensor types (Q8_0, Q4_0) via ggml_get_type_traits()->to_float dequantization. Verified: F16, Q8_0, Q4_0 all produce correct speech (Whisper verified).
|
Getting real fast. Preconverted and also quantized ggoofs: https://huggingface.co/onicubag/xTTSv2-GGUF |
Replace the host-side forward_token/forward_batch loops with a GGML compute graph per decode step (llama.cpp pattern): - Weights stay in their on-disk GGUF type; no F32 host copies of the GPT block/head weights (~1.5 GB RAM saved). - KV cache: persistent F16 [head_dim, n_ctx, n_heads] per layer, allocated once and reused across chunks; rows appended per step via ggml_set_rows; attention via ggml_flash_attn_ext with an additive F16 causal mask over a 256-bucket-padded window. - Prefill (cond latents + text + start token) runs as one batched graph pass; decode rebuilds the graph only when the KV window crosses a bucket boundary. - ln_f + final_norm + mel_head fused into the graph; logits read back only for the last position. - Threads propagated via ggml_backend_cpu_set_n_threads. Correctness: greedy decode produces a code sequence identical to the previous host implementation (verified against the reference logits, cos=1.0000 at step 0). The initial version produced NaNs from step 2 because the incremental single-element causal-mask update did not stick: the gallocr may reassign the mask tensor's buffer region between computes, so the mask must be refilled before every compute (done now; cost is O(n_kv) F16 bytes per step). Performance (32 threads, 24s of audio, RTF includes one-time conditioning): prefix batch 1.07s -> 0.18s; full longform RTF 2.9 -> 2.4. Also adds tools/community_models/quantize_xtts_v2.py for producing Q8_0/Q4_0 GGUF variants (weights are currently F32 on disk, so the expected next step is a quantized model package).
Q8_0 GPT weights: 542 MB vs 1.68 GB F32, whisper-verified identical transcription, longform RTF 2.4 -> 1.66 (32 threads). The decode graph reads GGUF tensor types natively via ggml_mul_mat, so no code change is needed to consume quantized weights.
…labels Q4_K_M verified end-to-end: exact Whisper transcription on short and longform text, longform RTF 1.59 (Q8_0 1.66, F32 2.4). Packages now: q8_0 (default, 518MB), f16 (1.75GB), q4_k_m (366MB).
…ler guard The teacher-forced extract_latents pass recomputed the entire sequence forward (2.7-3.1 s per chunk) to obtain hidden states that the decode loop had already produced: each decode step's post ln_f+final_norm hidden is exactly the latent frame the reference slices. The decode graph now marks the pre-logits hidden as a second output and the session consumes the captured frames (mel_head -> vocoder mapping starts at the start_mel position; verified by deterministic-greedy A/B against the extract path: lag-0 aligned, corr 0.95, identical transcription; the residual is the F16 KV cache vs the extract pass's in-graph F32 K/V). Also adds a std::isfinite(max_logit) check in the sampler so a future NaN costs one step instead of a max_tokens runaway. Longform RTF (25 s audio, Q4_K_M, 32 threads): 1.59 -> 1.41.
…ed path The conditioning mel statistics now load from mel_norms.bin next to the GPT GGUF at engine load time. Also drops the remaining XTTS_DUMP_PERC/ per-chunk timing debug hooks from compute_conditioning (chunk loop kept sequential: intra-chunk 32-thread OpenMP parallelism dominates the 5x chunk-level parallelism, which nested regions would serialize).
|
Wasn't satisfied with 1.5-1.6 RTF (CPU-only), so I tossed the decrepit mainline GGML, and ported audio.cpp to use ik_llama.cpp's GGML. (Q4_K_M, Intel(R) Xeon(R) Silver 4214 CPU @ 2.20GHz, 32 threads) stock: ik: I guess all other audio.cpp models would be similarly sped-up by dumping the legacy GGML. Should I do it in another PR, or not interested? EDIT: Commited as a branch on my clone. |
|
@whoreson Thanks for improving the code! The RTF target is for CUDA, so I think your current code should meet the bar given its CPU performance. I'd like to see backend-specific optimizations, but definitely not another GGML dependency. I'd prefer to identify the most useful optimizations and see whether they can be integrated cleanly into the existing framework, with minimal risk of causing regressions in other models. You can suggest the optimizations that offer the largest performance gains, and I'll see whether and how to integrate them. |
|
Yeah, I'm still exploring stuff with the vocoder while I'm completely optionally and code-wise independently tossing mainline GGML on my end at the same time. The thing people usually don't know about though, and thus I'd like to make sure to enunciate correctly, is that ggml-org's matmul capabilities are basically toy-level compared to the engine in ik_llama (not really affiliated with either btw, though I did send a few bugreports and patches to the latter), especially when CPU or mixed offload is concerned (which is not an issue with TTS, just mentioning). Actual example: an RTX4090 with Qwen 3.6-27b-Q5K at a fully-populated 200k ctx (thus, offloading) does 1 tok/s, while on IK, with an even larger (IQ6) quant, it decodes at 7-9 (!) tok/s... it's not even the same ballpark. So this is not "another GGML dependency" but a forked and significantly enhanced GGML in and of itself that you can already compile to with a CMake option existing right now, but does need some patches and compatibility shims as shown in https://github.com/whoreson/audio.cpp/commits/ik_llama/ I momentarily beg to differ on your viewpoint on this issue, I don think this is a dependency/maintaining/coding-thing at all, the real cons are:
Pros:
As I said this is completely separate from the xTTS work, just wanted to make sure I telegraphed the issue correctly in this damned wall of text. So about the PR, once I'm done on optimizing the vocoder and met your requirements on the list, I guess I'm merging onto HEAD. Anything else I should do? Hmm. Come to think of it, now that the bulk of the work is done, I'm gonna do the same surgery on ACEstep and stable-diffusion.cpp. BRB |
|
I think you underestimate the effort required to maintain a separate GGML backend. Audio.cpp’s vendored GGML has over 13,000 changed lines relative to its upstream base, covering extensions, optimizations, and correctness fixes for audio workloads. Losing any of them could introduce correctness or performance regressions across multiple models. These workloads involve much more than AR decoding, while IK primarily targets LLM-style computation. The CPU gains are real, but they are not universal: the benefit depends on the model architecture, tensor shapes, and operations that dominate inference. Replacing audio.cpp's vendored GGML with IK and adding a compatibility layer is not the right direction. audio.cpp is CUDA-first. And API compatibility alone does not guarantee equivalent behavior, backend coverage, or performance. The lower-risk approach is to selectively port useful IK optimizations into audio.cpp's existing GGML (starting with additive and opt-in new ops) and ensure they don't introduce regressions across models and backends. Evidence: I tested PockeTTS and Supertonic.
Your branch aborts on unsupported ops, even after fixing registry selection. Supertonic exposes correctness issues: For 94-char inputs
ASR Transcript:
I also profile a few compoents
|
|
Nice, thanks for testing it! Yes, I agree on all fronts, when running on CPU is not truly a concern, then it's probably better to stick with ggml-org, just for support and stablity. The aborts are not surprising, considering I haven't tested CUDA at all, and this was just a lousy/trial first pass with Qwen 27b. Ideally I am going to review/rework it with GLM-5.3-Flash which is way more competent on architecture, but since I do everything on slow local hardware (yeah, running GLM on CPU), it's better to release something that works in a scenario and get eyes+opinion, and work with feedback already in mind. And having developed my own C99 inference engine PicoLM, I'm acutely aware of architectural changes causing regressions. It was a mere question and a gauge of interest with a proof-of-concept, very far from being mergeable of course. I'm not that deep into TTS (for dual english/hungarian, only xTTS works well) but I did assume that the use case differs to a significant degree. In any case, I'm already very content that it works well for the xTTS+CPU usecase, I'll just leave the forked clone up so that the work doesn't have to get duplicated, should anyone else ever want to do this. |
llama-quantize crashes on the xtts-v2 vocoder GGUF (custom tensor naming/layout trips its size validation), so quantizing the vocoder requires a standalone converter. This tool converts F32 '.weight' tensors (ndims >= 3, i.e. conv kernels) to F16 while copying every other tensor verbatim, preserving all KV metadata. Write flow: gguf_write_to_file(only_meta=true), reopen to learn the computed data offset, then random-access fwrite per tensor at data_offset + tensor_offset. Verified bit-exact for all 421 tensors (44 converted, 377 kept) against the source file. Finding: the vocoder is FLOP-bound, not bandwidth-bound - F16 weights give zero wall-clock speedup (1.69s vs 1.70s for a 3.3s clip), so quantization is not a useful optimization here. The tool is kept for future experiments (e.g. Q8_0 via im2col-compatible 2D weight layout).
gpt.cpp / vocoder.cpp: - M_PI: define _USE_MATH_DEFINES at the top of both files before any include (MSVC guards M_PI behind it, and framework headers may pull <cmath> in transitively). Covers the FFT twiddles, Hamming window and mel filterbank math (5 error sites). - __builtin_ctz: GCC/Clang builtin, not available under MSVC. Added a portable xtts_ctz32() helper using _BitScanForward on MSVC and __builtin_ctz elsewhere (used by the radix-2 FFT bit-reversal table). - std::filesystem::path::c_str() returns const wchar_t* on Windows, so passing it to load_gguf(const char*) / gguf_init_from_file() fails to compile. Bind path.string() to a local and pass that instead (matching the existing pattern in vocoder.cpp / tokenizer_text.cpp). Fixed both call sites: the weights load and the metadata KV read. - std::fill(o, o + d, 0) with an int literal on a float* range triggered C4244 under MSVC; use 0.0f. loader.h: - make_xtts_v2_loader() was declared extern "C" while returning std::shared_ptr<IVoiceModelLoader> - C linkage cannot return C++ classes (C2526). All sibling community models declare this factory as a plain C++ function, and CMakeLists.txt registers it by its namespace-qualified C++ name, so the extern "C" was simply dropped.
Remove XTTS_DEBUG, XTTS_DUMP_PERC, XTTS_DUMP_FB, XTTS_DUMP_PWR, XTTS_DUMP_LOGITS, XTTS_DUMP_INPUT_EMBS, XTTS_DUMP_LNF, XTTS_DUMP_SPK_*, XTTS_INJECT_SPK_MEL, XTTS_TIMING, XTTS_GRAPH_PRINT, XTTS_FORCE_CODES, XTTS_NOCOND environment variable controls. All 49 getenv() calls across gpt.cpp, vocoder.cpp, session.cpp, and tokenizer_text.cpp are now gone. Also removes dead timing variables (tp0, ts0, td0, tb0, n_steps, n_rebuilds, t_dec, t_sample, t_build) and the session.cpp XTTS_TIMING prints. The XTTS_DEBUG tokenizer dump and perceiver FFN/QKV/attn intermediates, speaker encoder network dumps, and conditioning latent stats prints are all removed. Build clean, transcription verified exact.
|
@whoreson Thanks for the updates! The PR is much better scoped now. However, a few issues remain:
Would you like to host and maintain the GGUF packages yourself? If so, please point the spec to your repository. Otherwise, we can host them in audio-cpp/audio.cpp-gguf and point the packages there. |
… and model spec repo - Vocoder: split single-pass 4.354x interpolation into two chained stages (4x then 1.088x) matching PyTorch F.interpolate align_corners=False semantics - Vocoder: fix vin/spk backend buffer leaks in generate() - GPT: read mel normalization stats from GGUF metadata (xtts.mel_stats) instead of requiring separate mel_norms.bin file - Converter: embed mel_stats as GGUF float32 array, drop mel_norms.bin output - Model spec: update download repo to onicubag/xTTSv2-GGUF - Converter: add warning about ik_llama.cpp producing incorrect quantized GGUFs
…ides - GPT/Vocoder: replace hardcoded ggml_backend_cpu_init() with core::init_backend(BackendConfig) so GPU backends (CUDA/ROCm/Vulkan) are actually used when --device is specified - Session: store BackendConfig and pass it to both engines at load time - Session: resolve inference options (temperature, top_k, top_p, repetition_penalty, max_mel_tokens, language) from TaskRequest.options at run() time, falling back to prepare-time defaults - Clean up unused timing variables (xtts_cache_t0, xtts_chunk_t0)
|
Commited. Although I don't agree with needlessly cramming every kind of textual/binary attachment into a single GGUF (especially textual ones). I found it a terrible idea even back in 2023, especially considering the fact that ggerganov came up with it right at the same time everyone was busy requantizing their llama 2 files due to the wrong rms_norm_eps being hardcoded (ggml-org/llama.cpp#2373), so it was a curious thing to see him double-down on a big mistake. To this day people are sharding their GGUFs (https://huggingface.co/unsloth/GLM-5.3-Flash-GGUF/tree/main/UD-Q4_K_XL) so that the KV part can be updated easier later... bleh About GGUFs: well it's sloppingface's responsibility keeping them online so it wouldn't be "mine" per se, so either is fine by me. (they love returning HTTP 400 for days sometimes, but such is life) Updated the spec file. Unrelated: I think you should consider something like this diff attached, the default batch concat sounds terrible with 0 silence between the lines. |
|
Take it over. I'll refactor it from the ground up and push the changes directly to this PR. |
Changes compared to 406f52f:
Not included in this PR:
|
|
whoreson@8a4fcb5 should be merged methinks |
|
Please open a PR based on the current main head. |
|
shithub makes that a humiliation ritual, so I'll pass (create a branch just for this, really?..) EDIT: amended with fixes for more languages. |
|
Hmm. Have you perhaps tested this a bit, or is it only me? Because I'm seeing brutal hallucinations (speaker's voice degenerating, weird pauses/silence, etc) on the refactored+server+CUDA combination, which I'm not seeing even after listening hours of material with the IK+CPU branch. Not yet sure what causes it, I'll try without CUDA first. |
|
@whoreson My rewrite was based on 406f52f, but the outputs were not byte-identical because the rewrite included several bug fixes. I validated transcription accuracy using WER, rather than waveform parity. I checked the old logs. With greedy decoding and 30 random short to long test cases (80 to 600 chars):
Of course they don’t rule out the voice degeneration or unusual pauses you reported. |
|
Ah yes, now I remember: another difference is I had to use Q8_0 instead of Q4_K_M on the refactored because of this: audio.cpp\external\ggml\src\ggml-cuda\getrows.cu:218: ggml_cuda_get_rows_switch_src0_type: unsupported src0 type: q4_K So this should probably be fixed on your end, and also, the Q8_0 quant may also be the cause of issues, I'll test more. |
Any interest in having xTTSv2 supported? After long months of work (started by Qwen 3.6-27b, finished by GLM-5.3-Flash-IQ6_K) I've succeeded.
Why? Because this is the only multi-lingual TTS model which doesn't sound like ass (such as OmniVoice, which is terrible in Hungarian due to bad training, and totally monotonous in English).
Development: 100% LLM-powered
Status: very WIP. Reference speaker works, and output is clearly recognizable. Needs work to match Python completely.
License: dunno, never checked, dontcare