Qwen3-TTS GGUF + ONNX
Pre-converted weights for running Qwen3-TTS 12Hz 1.7B Base entirely via llama.cpp + ONNX Runtime. No PyTorch required.
Which model is this: the 1.7B Base variant (voice cloning from a reference sample), not the 0.6B, and not CustomVoice or VoiceDesign. About 1.5 GB total.
Why this repo
The upstream conversion toolchain expects the original PyTorch weights and a three-stage export (codec/speaker/decoder ONNX, talker GGUF, predictor GGUF) spread across a dozen scripts. These files are the finished output of that pipeline: download and run.
Files
| File | Size | Format |
|---|---|---|
| qwen3_tts_talker.q5_k.gguf | 960 MB | GGUF Q5_K |
| qwen3_tts_predictor.q8_0.gguf | 145 MB | GGUF Q8_0 |
| qwen3_tts_decoder.fp16.onnx | 220 MB | ONNX FP16 |
| qwen3_tts_speaker_encoder.fp16.onnx | 24 MB | ONNX FP16 |
| qwen3_tts_codec_encoder.fp16.onnx | 109 MB | ONNX FP16 |
| tokenizer.json | 11 MB | JSON |
INT8 and FP32 variants are also included for the ONNX components.
Usage
Requires the HaujetZhao/Qwen3-TTS-GGUF runtime package and llama.cpp compiled libraries.
pip install huggingface_hub
hf download Solidaxel/Qwen3-TTS-GGUF --local-dir model-base
Then point the runtime at that directory:
from qwen3_tts_gguf import TTSEngine, TTSConfig
engine = TTSEngine(model_dir="model-base")
stream = engine.create_stream()
stream.set_voice("output/elaborate/sample.json") # reference voice
result = stream.clone("Hello, world!", config=TTSConfig(temperature=0.8, seed=42))
stream.join()
result.save("output.wav")
The runtime also ships 51-Interactive-Clone.py for an interactive session and 43-Inference-Base.py for the Base variant, which is the one in this repo.
Preparing a reference voice
The Base model clones from a pair: a short reference clip + its exact transcript. A clip with music, noise or other voices under it gets cloned too, so clean it first. This is the pipeline we use. No voice samples are shipped in this repo: use a recording you have the right to clone.
1. Cut and convert. Pick a passage with one speaker and convert it to 44.1 kHz stereo, the format Demucs expects:
ffmpeg -ss 00:00:20 -t 60 -i source.mp4 -ac 2 -ar 44100 segment.wav
2. Isolate the voice with Demucs. The htdemucs model splits the track into stems and we keep only vocals. Recent torchaudio versions make the demucs CLI fail on save (it wants torchcodec, which often fails to load against the system FFmpeg), so call the API and write the file with soundfile. It takes about 25 s per minute of audio on CPU.
import sys
import soundfile as sf
import torch
from demucs.apply import apply_model
from demucs.pretrained import get_model
model = get_model("htdemucs")
model.eval()
wav, sr = sf.read(sys.argv[1], always_2d=True, dtype="float32")
assert sr == model.samplerate and wav.shape[1] == 2, "convert to 44.1 kHz stereo first"
x = torch.from_numpy(wav.T)
mono = x.mean(0)
mean, std = mono.mean(), mono.std() + 1e-8
with torch.no_grad():
stems = apply_model(model, ((x - mean) / std)[None], device="cpu")[0]
vocals = stems[model.sources.index("vocals")] * std + mean
sf.write(sys.argv[2], vocals.T.numpy(), model.samplerate)
python separate.py segment.wav vocals.wav
3. Choose the reference clip. Listen to vocals.wav and cut 8 to 10 seconds with no separation artifacts, ending cleanly on a full word. In our tests a short clean clip clones better than a long one, and a clip that ends mid-phrase leaks its last words as a lead-in at the start of every generation.
ffmpeg -ss 3.2 -t 8.6 -i vocals.wav -ac 1 ref.wav
4. Transcribe the clean clip. Run speech recognition on the cleaned reference, not on the original: background sound degrades the transcript. We use Whisper small on CPU:
whisper ref.wav --model small --language it --output_format txt
Then read the transcript while listening and fix it by hand. It must match the audio word for word, because a single misheard word degrades the clone. Save it as ref.txt.
5. Encode the voice:
voice = stream.set_voice("ref.wav", open("ref.txt", encoding="utf-8").read().strip())
The encoded result can be reused for every generation (see below).
Normalizing numbers and symbols
The model reads digits and symbols badly: it skips them, reads them in the wrong language or invents a pronunciation. Before synthesis, rewrite them as words in the target language. Below are two ready versions, Italian (the one we run in production, condensed) and English, both built on num2words (pip install num2words). What they handle:
| Input | Italian | English |
|---|---|---|
| decimals | 81,6 -> ottantuno virgola sei | 81.6 -> eighty-one point six |
| thousands | 1.234 -> milleduecentotrentaquattro | 1,234 -> one thousand, two hundred and thirty-four |
| percentages, signs | +5% -> più cinque per cento | +5% -> plus five percent |
| currencies | $81,6B -> ottantuno virgola sei miliardi di dollari | $81.6B -> eighty-one point six billion dollars |
| units | 2TB -> due terabyte | 2TB -> two terabytes |
| file names | config.json -> config punto i lunga esse o enne | config.json -> config dot jay ess o en |
Decimals are read digit by digit. Table rows (two or more |) are dropped, since they cannot be read aloud. Single-letter units are left out on purpose: m could mean metres or millions.
The separators are swapped between the two languages. Italian uses the comma for decimals and the dot for thousands; the Italian version still accepts an English-style decimal dot (11.3) when it cannot be a thousands group. English uses the dot for decimals and the comma for thousands.
The order of the rules is critical. Each specific rule must run before the generic one that turns every remaining number into words. Otherwise 11.3% becomes "centotredici per cento" (a real bug we had) and 2TB becomes "due mila miliardi". The number pattern also requires a digit after each separator, so the full stop in in 2026. and the commas in 1, 2 and 3 survive: the block splitter needs them.
Italian
import re
from num2words import num2words
SCALE = {"k": "mila", "m": "milioni", "mln": "milioni", "b": "miliardi", "mld": "miliardi"}
UNITS = {"km": "chilometri", "kg": "chilogrammi", "GB": "gigabyte", "TB": "terabyte",
"MB": "megabyte", "GHz": "gigahertz", "kWh": "chilowattora", "W": "watt"}
LETTERS = dict(zip("abcdefghijklmnopqrstuvwxyz",
"a bi ci di e effe gi acca i i_lunga cappa elle emme enne o pi cu erre esse ti u vu "
"doppia_vu ics ipsilon zeta".split()))
NUM = r"\d+(?:[.,]\d+)*" # a separator must be followed by a digit
def words(n):
"""'81,6' -> 'ottantuno virgola sei'. Comma = decimal; a dot is decimal only
when it does not group thousands ('11.3' decimal, '1.234' = 1234)."""
if "," in n:
i, _, d = n.partition(",")
elif "." in n and not re.fullmatch(r"\d{1,3}(\.\d{3})+", n):
i, _, d = n.rpartition(".")
else:
i, d = n, ""
i = i.replace(".", "")
if not i.isdigit():
return n
w = num2words(int(i), lang="it")
if d.isdigit(): # decimals digit by digit
w += " virgola " + " ".join(num2words(int(c), lang="it") for c in d)
return w
def normalize(text):
# order matters: each rule must run before the generic number rule eats its digits
text = "\n".join(l for l in text.splitlines() if l.count("|") < 2) # drop table rows
text = re.sub(r"\b([\w-]+)\.(md|py|json|txt|wav|gguf)\b", # file.md -> file punto emme di
lambda m: m[1] + " punto " + " ".join(LETTERS[c] for c in m[2]).replace("_", " "), text)
text = re.sub(r"\+(?=\d)", "più ", text)
text = re.sub(rf"({NUM})\s*%", lambda m: words(m[1]) + " per cento", text)
text = re.sub(rf"([$€])\s?({NUM})\s?(K|M|B|mln|mld)?\b", lambda m: words(m[2])
+ (" " + SCALE[m[3].lower()] + " di" if m[3] else "")
+ (" dollari" if m[1] == "$" else " euro"), text)
text = re.sub(rf"({NUM})\s?€", lambda m: words(m[1]) + " euro", text)
text = re.sub(rf"({NUM})\s?({'|'.join(sorted(UNITS, key=len, reverse=True))})\b",
lambda m: words(m[1]) + " " + UNITS[m[2]], text) # units before scale: 2TB
text = re.sub(rf"({NUM})\s?(K|M|B|mln|mld)\b", lambda m: words(m[1]) + " " + SCALE[m[2].lower()], text)
return re.sub(NUM, lambda m: words(m[0]), text).strip()
English
import re
from num2words import num2words
SCALE = {"k": "thousand", "m": "million", "b": "billion", "bn": "billion", "t": "trillion"}
UNITS = {"km": "kilometers", "kg": "kilograms", "GB": "gigabytes", "TB": "terabytes",
"MB": "megabytes", "GHz": "gigahertz", "kWh": "kilowatt hours", "W": "watts"}
LETTERS = dict(zip("abcdefghijklmnopqrstuvwxyz",
"a bee cee dee e ef gee aitch i jay kay el em en o pee cue ar ess tee u vee "
"double_u ex why zee".split()))
NUM = r"\d+(?:[.,]\d+)*" # a separator must be followed by a digit
def words(n):
"""'81.6' -> 'eighty-one point six'. Dot = decimal; a comma groups thousands
('1,234' = 1234). Decimals are read digit by digit."""
i, _, d = n.replace(",", "").partition(".")
w = num2words(int(i), lang="en")
if d:
w += " point " + " ".join(num2words(int(c), lang="en") for c in d)
return w
def normalize(text):
# order matters: each rule must run before the generic number rule eats its digits
text = "\n".join(l for l in text.splitlines() if l.count("|") < 2) # drop table rows
text = re.sub(r"\b([\w-]+)\.(md|py|json|txt|wav|gguf)\b", # file.md -> file dot em dee
lambda m: m[1] + " dot " + " ".join(LETTERS[c] for c in m[2]).replace("_", " "), text)
text = re.sub(r"\+(?=\d)", "plus ", text)
text = re.sub(rf"({NUM})\s*%", lambda m: words(m[1]) + " percent", text)
text = re.sub(rf"([$€£])\s?({NUM})\s?(K|M|B|bn|T)?\b", lambda m: words(m[2])
+ (" " + SCALE[m[3].lower()] if m[3] else "")
+ {"$": " dollars", "€": " euros", "£": " pounds"}[m[1]], text)
text = re.sub(rf"({NUM})\s?({'|'.join(sorted(UNITS, key=len, reverse=True))})\b",
lambda m: words(m[1]) + " " + UNITS[m[2]], text) # units before scale: 2TB
text = re.sub(rf"({NUM})\s?(K|M|B|bn|T)\b", lambda m: words(m[1]) + " " + SCALE[m[2].lower()], text)
return re.sub(NUM, lambda m: words(m[0]), text).strip()
num2words in English writes years as cardinals (2026 -> "two thousand and twenty-six"); if your texts are full of years, num2words(n, lang="en", to="year") gives "twenty twenty-six". For another language, change lang=, the words for the decimal point, per cent and currencies, and the letter names.
Long texts (minutes of speech)
A single clone() call breaks down past roughly 110 seconds of audio: the model stops emitting the end-of-speech token and fills up to max_steps with noise or loops. For anything longer than a paragraph, split the text and synthesize it block by block. This is the recipe we run in production for spoken replies of several minutes.
1. Clean and normalize the text first. Strip markdown, code and URLs, then spell out numbers, percentages, currencies and acronyms in the target language (we use num2words). See Normalizing numbers and symbols.
2. Split by duration, not by characters. Measure the speaking rate of your reference voice (words per second) and size the blocks so each one stays well under ~110 s. Two numbers per voice: target (close the block once it reaches this many words) and maxw (never exceed this). As a reference, a slow voice at ~1.4 words/s works with target=55, maxw=75; a faster one at ~2.6 words/s with target=95, maxw=125. Cut at sentence ends first, then at commas, and only as a last resort every maxw words.
3. Encode the voice once, re-apply it before every block. Without the second set_voice(voice) the blocks after the first come out truncated.
4. Scale max_steps with the block length and retry empty results: synthesis occasionally returns no audio. Recreating the stream, re-encoding the voice and shifting the seed fixes it.
import re
import numpy as np
from qwen3_tts_gguf import TTSEngine, TTSConfig
def split_blocks(text, target=55, maxw=75):
pieces = []
for s in re.split(r"(?<=[.!?])\s+", text.strip()):
if len(s.split()) <= maxw:
pieces.append(s)
continue
cur = []
for part in re.split(r"(?<=,)\s+", s): # long sentence: cut at commas
words = part.split()
if len(words) > maxw: # no commas at all: hard cut
if cur:
pieces.append(" ".join(cur)); cur = []
pieces += [" ".join(words[i:i + maxw]) for i in range(0, len(words), maxw)]
continue
if cur and len(" ".join(cur).split()) + len(words) > maxw:
pieces.append(" ".join(cur)); cur = []
cur.append(part)
if cur:
pieces.append(" ".join(cur))
blocks, cur, n = [], [], 0
for p in pieces:
w = len(p.split())
if cur and n + w > maxw:
blocks.append(" ".join(cur)); cur, n = [], 0
cur.append(p); n += w
if n >= target:
blocks.append(" ".join(cur)); cur, n = [], 0
if cur:
blocks.append(" ".join(cur))
return blocks
engine = TTSEngine(model_dir="model-base")
stream = engine.create_stream()
voice = stream.set_voice("ref.wav", "Exact transcript of ref.wav.") # encode once
audio = []
for block in split_blocks(long_text):
for attempt in range(3):
cfg = TTSConfig(temperature=0.5, sub_temperature=0.5,
seed=44 + attempt, sub_seed=44 + attempt,
streaming=False, max_steps=max(600, len(block.split()) * 20))
stream.set_voice(voice) # re-apply the anchor every block
res = stream.clone(text=block, language="Italian", config=cfg)
if res is not None and res.audio is not None and len(res.audio) > 0:
audio.append(np.asarray(res.audio, dtype=np.float32))
break
stream = engine.create_stream() # empty result: fresh stream + voice
voice = stream.set_voice("ref.wav", "Exact transcript of ref.wav.")
5. Pick a playback strategy.
- Incremental: play block 1 as soon as it is ready and synthesize block 2 while it plays. First sound after a couple of seconds on GPU. Good when the GPU keeps up with real time.
- Generate all, then play: concatenate the blocks (
np.concatenate(audio)) into one file and play or send it at the end. On CPU this avoids long silences between blocks; show elapsed time and an estimate of what is left while it works.
Keeping the engine resident (a small local HTTP server that holds the models in memory and caches each encoded voice) saves the model load on every request.
Pitfalls we hit:
temperaturebelow 0.5, and a few specific seeds, make the model miss the end-of-speech token: the block degenerates and runs tomax_steps. Test your seed on a handful of sentences.- The last syllable of a block is sometimes clipped. A short throwaway closing word at the end of the text works around it.
- A short reference clip (~8 to 10 s) that ends cleanly on a full word clones better than a long one, and avoids a stray lead-in from its last words.
- The GGUF backend can occasionally abort (
GGML_ASSERT); if you batch many generations, run them in a supervised process. Amunmap_chunk(): invalid pointerat process exit is harmless, the WAV is already written.
Credits
- Original model: Qwen/Qwen3-TTS-12Hz-1.7B-Base (Apache 2.0)
- GGUF/ONNX conversion: HaujetZhao/Qwen3-TTS-GGUF (MIT)
- Redistribution: SolidAxel Project
License
Apache 2.0, same as the original model.