Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: fine-tune Qwen3 voices with the official single-speaker recipe (#8857)

[._.]/ Adam Eivy1545a9544a03
diff --git a/docs/features/voice.md b/docs/features/voice.md
index 780cc5da07..c57a35ba99 100644
--- a/docs/features/voice.md
+++ b/docs/features/voice.md
@@ -26,8 +26,9 @@ environment, install `mlx-audio` at commit
`soundfile` and `huggingface_hub`. The runtime probe checks MLX/Metal availability
without loading weights. MLX cloning requires a reference transcript and a
loaded speech-tokenizer encoder; otherwise it fails rather than generating an
-unconditioned voice. Training and custom checkpoints remain unavailable. Speech-rate changes and instruction-controlled Base cloning are
-refused rather than reported as applied controls. Explicit model
+unconditioned voice. Speech-rate changes and instruction-controlled Base cloning are
+refused rather than reported as applied controls. Fine-tuning is described
+under Voice Studio below. Explicit model
downloads in Settings fetch the official Qwen snapshot at an immutable Hub
revision and verify the size and digest of every required file, including the
speech tokenizer weights, before publishing readiness. Downloads require
@@ -368,9 +369,25 @@ streaming qualification. Without that opt-in, AuK remains studio-only and the
existing interactive fallback is retained. The production planner checks the
interactive route rather than treating every approved studio voice as live-ready.
-The separate Qwen runtime supports verified local inference but has no training adapter. Its probe reports
-`training_adapter: null`, so starting fine-tuning returns `503 QWEN3_TRAINING_UNAVAILABLE` before any job
-record or process exists, and checkpoints recorded by earlier placeholder runners (no producing adapter) are
-refused with `409 CHECKPOINT_UNVERIFIED` rather than promoted. The runtime is excluded from
+The separate Qwen runtime can fine-tune one speaker with the official
+[Qwen3-TTS single-speaker recipe](https://github.com/QwenLM/Qwen3-TTS/tree/022e286b98fbec7e1e916cb940cdf532cd9f488e/finetuning)
+(adapter `qwen-tts-sft-12hz`). The runner ports that recipe rather than
+calling the upstream scripts. The probe names the adapter only on CUDA with
+bf16 support and `qwen-tts`, `librosa` and `safetensors` installed. CPU and Apple Silicon hosts report
+`training_adapter: null`, and starts return `503 QWEN3_TRAINING_UNAVAILABLE` before any job record or process
+exists. Training uses a verified, downloaded Base snapshot offline (`409 QWEN3_MODEL_NOT_INSTALLED`
+otherwise). It uses the profile's transcribed source recordings, with the first recording as the speaker
+reference. Full-parameter training needs substantial GPU memory. Each checkpoint is a full model copy
+(about the base snapshot's size), so the checkpoint interval (optimizer steps) bounds disk use.
+
+A checkpoint is published only after the runner records the SHA-256 of every file it loads. It must pass
+the same verification and loader used for synthesis and render a non-silent audition (`audition.wav`).
+Checkpoints that fail are deleted. The published revision is
+`<base-model>@<base-revision>+sha256.<weights-digest>`; promotion records it, and fine-tuned synthesis
+refuses a checkpoint whose files changed or whose revision differs. Checkpoints load only through
+qwen-tts on CPU/CUDA; MLX refuses them. Checkpoints recorded by earlier placeholder runners have no
+producing adapter or sealed revision and are refused with `409 CHECKPOINT_UNVERIFIED` rather than promoted.
+Fixture tests prove this publication contract, not training quality. A real training run on supported
+hardware is still pending in #8857. Operators should listen to each audition before promoting. The runtime is excluded from
Voice Studio assignment until repaired (issue #8857). Voice Studio does not
claim a Qwen runtime is working merely because its metadata exists.
diff --git a/scripts/qwen3_tts_runner.py b/scripts/qwen3_tts_runner.py
index 44a429f512..f3781388d3 100755
--- a/scripts/qwen3_tts_runner.py
+++ b/scripts/qwen3_tts_runner.py
@@ -5,8 +5,8 @@ Provides CLI entry points for:
- Environment & hardware probe (--probe)
- Voice design inference (--mode design)
- Consented instant cloning (--mode clone)
-- Standard / fine-tuned synthesis (--mode synthesize)
-- Fine-tuning runner (--mode fine-tune)
+- Verified fine-tuned checkpoint synthesis (--mode fine-tuned)
+- Official single-speaker fine-tuning on CUDA (--mode fine-tune)
"""
from __future__ import annotations
@@ -14,10 +14,13 @@ from __future__ import annotations
import argparse
import contextlib
import hashlib
+import importlib.util
+import math
import os
import re
import json
import platform
+import shutil
import sys
import tempfile
from pathlib import Path
@@ -39,6 +42,24 @@ REQUIRED_FILES = (
"speech_tokenizer/model.safetensors", "speech_tokenizer/preprocessor_config.json",
)
+# Official single-speaker SFT recipe for the 12 Hz Base models, ported from
+# QwenLM/Qwen3-TTS finetuning/ (sft_12hz.py + dataset.py, Apache-2.0) at commit
+# 022e286b98fbec7e1e916cb940cdf532cd9f488e. The recipe trains in bf16 on CUDA.
+TRAINING_ADAPTER = "qwen-tts-sft-12hz"
+TRAINABLE_MODELS = tuple(model for model in SUPPORTED_MODELS if model.endswith("-Base"))
+CHECKPOINT_MANIFEST = "portos-checkpoint.json"
+CHECKPOINT_WEIGHTS = "model.safetensors"
+# The recipe writes the target speaker embedding into this codec-embedding row
+# and registers the speaker name against it in the checkpoint config.
+SPEAKER_TOKEN_ID = 3000
+SPEAKER_NAME_RE = re.compile(r"[a-z][a-z0-9_]{0,39}")
+AUDITION_TEXT = "This is a short audition of the fine-tuned voice."
+TRAINING_BATCH_SIZE = 2
+TRAINING_GRADIENT_ACCUMULATION = 4
+TRAINING_LEARNING_RATE = 2e-5
+MAX_TRAINING_SAMPLES = 500
+MAX_TRAINING_TEXT = 2000
+
def publish_json(path: Path, data: dict) -> None:
descriptor, temporary = tempfile.mkstemp(prefix=".verified-", dir=path.parent)
@@ -162,6 +183,26 @@ def download_model(model_id: str, models_dir: Path) -> dict:
return {"ok": True, "modelId": model_id, "revision": revision, "path": str(snapshot)}
+def is_apple_silicon() -> bool:
+ return platform.system() == "Darwin" and platform.machine() == "arm64"
+
+
+def training_runtime_available() -> bool:
+ """True only where the official recipe can run: bf16 CUDA plus its imports."""
+ if is_apple_silicon():
+ return False
+ try:
+ import librosa # noqa: F401
+ import soundfile # noqa: F401
+ import torch
+ from qwen_tts import Qwen3TTSModel # noqa: F401
+ from qwen_tts.core.models.modeling_qwen3_tts import mel_spectrogram # noqa: F401
+ from safetensors.torch import save_file # noqa: F401
+ except ImportError:
+ return False
+ return bool(torch.cuda.is_available() and torch.cuda.is_bf16_supported())
+
+
def probe_runtime(models_dir: Path | None = None) -> dict:
"""Probe hardware, PyTorch, Transformers, and cached model weights."""
result = {
@@ -174,8 +215,8 @@ def probe_runtime(models_dir: Path | None = None) -> dict:
"mps_available": False,
"vram_gb": None,
"models": {},
- # Name of a real training adapter once one exists. Inference readiness
- # never implies training support; PortOS refuses fine-tuning while null.
+ # Inference readiness never implies training support; PortOS refuses
+ # fine-tuning unless the probe names the adapter that will train.
"training_adapter": None,
}
@@ -204,7 +245,7 @@ def probe_runtime(models_dir: Path | None = None) -> dict:
pass
# Probe the actual backend without loading a model or acquiring weights.
- if platform.system() == "Darwin" and platform.machine() == "arm64":
+ if is_apple_silicon():
result["error"] = "Qwen3-TTS inference requires mlx-audio and soundfile on Apple Silicon"
try:
import mlx.core as mx
@@ -225,6 +266,8 @@ def probe_runtime(models_dir: Path | None = None) -> dict:
result["error"] = None
except ImportError:
pass
+ if result["ok"] and training_runtime_available():
+ result["training_adapter"] = TRAINING_ADAPTER
for model_id in SUPPORTED_MODELS:
model_path = models_dir / model_id.replace("/", "--") if models_dir else None
@@ -242,19 +285,66 @@ def unavailable(operation: str) -> int:
print(json.dumps({
"ok": False,
"code": "QWEN3_RUNTIME_UNAVAILABLE",
- "error": f"Qwen3-TTS {operation} is unavailable: no real model adapter is implemented",
+ "error": f"Qwen3-TTS {operation} is unavailable",
}), file=sys.stderr)
return 1
+def use_offline_hub() -> None:
+ # qwen-tts loads its processor/codec independently. Offline flags cover those
+ # nested loads too; status, inference and training cannot acquire weights.
+ os.environ["HF_HUB_OFFLINE"] = "1"
+ os.environ["TRANSFORMERS_OFFLINE"] = "1"
+
+
+def load_torch_model(path: Path, seed: int):
+ """Load a verified local snapshot or checkpoint with the official package."""
+ import torch
+ from qwen_tts import Qwen3TTSModel
+
+ device = "cuda:0" if torch.cuda.is_available() else "cpu"
+ dtype = (torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16) if device != "cpu" else torch.float32
+ torch.manual_seed(seed)
+ model = Qwen3TTSModel.from_pretrained(
+ str(path), device_map=device, dtype=dtype,
+ attn_implementation="eager", local_files_only=True,
+ )
+ return torch, model
+
+
+def write_model_audio(wavs, sample_rate, output_path) -> None:
+ """Publish one finite, non-silent PCM WAV; never write rejected audio."""
+ import numpy as np
+ import soundfile as sf
+
+ if len(wavs) != 1 or not isinstance(sample_rate, int) or sample_rate <= 0:
+ raise ValueError("Invalid model audio result")
+ audio = np.asarray(wavs[0])
+ if audio.ndim != 1 or not audio.size or not np.isfinite(audio).all() or not np.any(audio):
+ raise ValueError("Model returned empty, silent or invalid audio")
+ # Publish only the completed PCM WAV; the JS transport buffers it.
+ sf.write(output_path, audio, sample_rate, format="WAV", subtype="PCM_16")
+
+
+def synthesis_failed(output_wav) -> int:
+ # Provider exceptions may contain private reference paths/transcripts.
+ # Return a bounded error instead of publishing their raw exception text.
+ Path(output_wav).unlink(missing_ok=True)
+ print(json.dumps({"ok": False, "code": "QWEN3_SYNTHESIS_FAILED",
+ "error": "Qwen3-TTS model inference failed; no audio was published"}), file=sys.stderr)
+ return 1
+
+
def run_synthesis(args: argparse.Namespace) -> int:
+ if args.mode == "fine-tuned":
+ return run_checkpoint_synthesis(args)
# Resolve the verified immutable snapshot ourselves. Never let a model ID,
# arbitrary checkpoint, or missing local file trigger an implicit download.
if args.checkpoint_path or args.model_path:
return unavailable("custom checkpoints/model paths")
if args.rate != 1.0:
return unavailable("speech-rate control")
- use_mlx = platform.system() == "Darwin" and platform.machine() == "arm64"
+ use_mlx = is_apple_silicon()
if args.model_id not in SUPPORTED_MODELS or not args.models_dir:
return unavailable("inference without a supported verified local model")
model_dir = Path(args.models_dir) / args.model_id.replace("/", "--")
@@ -275,14 +365,11 @@ def run_synthesis(args: argparse.Namespace) -> int:
if use_mlx and not design and not (args.reference_transcript or "").strip():
return unavailable("MLX reference cloning without a transcript")
- # qwen-tts loads its processor/codec independently. Offline flags cover those
- # nested loads too; status and inference cannot acquire unrequested weights.
- os.environ["HF_HUB_OFFLINE"] = "1"
- os.environ["TRANSFORMERS_OFFLINE"] = "1"
+ use_offline_hub()
try:
with contextlib.redirect_stdout(sys.stderr):
- import numpy as np
- import soundfile as sf
+ import numpy # noqa: F401 - both backends need the audio writer deps
+ import soundfile # noqa: F401
if use_mlx:
import mlx.core as mx
from mlx_audio.tts.utils import load_model
@@ -312,16 +399,7 @@ def run_synthesis(args: argparse.Namespace) -> int:
mx.eval(results[0].audio)
wavs, sample_rate = [results[0].audio], results[0].sample_rate
else:
- import torch
- from qwen_tts import Qwen3TTSModel
-
- device = "cuda:0" if torch.cuda.is_available() else "cpu"
- dtype = (torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16) if device != "cpu" else torch.float32
- torch.manual_seed(args.seed)
- model = Qwen3TTSModel.from_pretrained(
- str(snapshot), device_map=device, dtype=dtype,
- attn_implementation="eager", local_files_only=True,
- )
+ torch, model = load_torch_model(snapshot, args.seed)
with torch.inference_mode():
if design:
wavs, sample_rate = model.generate_voice_design(
@@ -335,13 +413,7 @@ def run_synthesis(args: argparse.Namespace) -> int:
ref_text=args.reference_transcript or None,
x_vector_only_mode=not bool(args.reference_transcript),
)
- if len(wavs) != 1 or not isinstance(sample_rate, int) or sample_rate <= 0:
- raise ValueError("Invalid model audio result")
- audio = np.asarray(wavs[0])
- if audio.ndim != 1 or not audio.size or not np.isfinite(audio).all() or not np.any(audio):
- raise ValueError("Model returned empty, silent or invalid audio")
- # Publish only the completed PCM WAV; the JS transport buffers it.
- sf.write(args.output_wav, audio, sample_rate, format="WAV", subtype="PCM_16")
+ write_model_audio(wavs, sample_rate, args.output_wav)
print(json.dumps({
"ok": True, "modelRevision": f"{args.model_id}@{snapshot.name}",
"effectiveControls": {"rate": 1.0, "seed": args.seed,
@@ -352,16 +424,360 @@ def run_synthesis(args: argparse.Namespace) -> int:
except ImportError:
return unavailable("inference dependencies (install mlx-audio on Apple Silicon or qwen-tts on CPU/CUDA)")
except Exception:
- # Provider exceptions may contain private reference paths/transcripts.
- # Return a bounded error instead of publishing their raw exception text.
- Path(args.output_wav).unlink(missing_ok=True)
- print(json.dumps({"ok": False, "code": "QWEN3_SYNTHESIS_FAILED",
- "error": "Qwen3-TTS model inference failed; no audio was published"}), file=sys.stderr)
- return 1
+ return synthesis_failed(args.output_wav)
+
+
+def run_checkpoint_synthesis(args: argparse.Namespace) -> int:
+ """Speak with a checkpoint this adapter produced, verified before loading."""
+ if is_apple_silicon():
+ return unavailable("fine-tuned checkpoints on Apple Silicon")
+ if args.rate != 1.0:
+ return unavailable("speech-rate control")
+ if args.instructions:
+ return unavailable("instruction control for fine-tuned checkpoints")
+ if not args.text or not args.text.strip():
+ return unavailable("inference without text")
+ checkpoint = Path(args.checkpoint_path) if args.checkpoint_path else None
+ manifest = verified_checkpoint(checkpoint) if checkpoint else None
+ if manifest is None:
+ return unavailable("an unverified fine-tuned checkpoint")
+
+ use_offline_hub()
+ try:
+ with contextlib.redirect_stdout(sys.stderr):
+ torch, model = load_torch_model(checkpoint, args.seed)
+ with torch.inference_mode():
+ wavs, sample_rate = model.generate_custom_voice(
+ text=args.text, speaker=manifest["speaker"], language="Auto",
+ )
+ write_model_audio(wavs, sample_rate, args.output_wav)
+ print(json.dumps({
+ "ok": True, "modelRevision": checkpoint_revision(manifest),
+ "effectiveControls": {"rate": 1.0, "seed": args.seed, "instructions": None, "mode": "fine-tuned"},
+ }))
+ return 0
+ except ImportError:
+ return unavailable("fine-tuned inference dependencies (install qwen-tts on CPU/CUDA)")
+ except Exception:
+ return synthesis_failed(args.output_wav)
+
+
+# --- Fine-tuning -----------------------------------------------------------
+
+def emit_event(stream, event: dict) -> None:
+ print(json.dumps(event), file=stream, flush=True)
+
+
+def training_failed(code: str, error: str) -> int:
+ # Fixed messages only: dataset paths and transcripts are private.
+ print(json.dumps({"ok": False, "code": code, "error": error}), file=sys.stderr)
+ return 1
+
+
+def load_training_dataset(path: Path) -> dict:
+ """Validate the dataset manifest PortOS writes for one training job."""
+ dataset = json.loads(path.read_text())
+ speaker = dataset["speaker"]
+ if not isinstance(speaker, str) or not SPEAKER_NAME_RE.fullmatch(speaker):
+ raise ValueError("Invalid speaker name")
+ reference = Path(dataset["reference_audio"])
+ samples = dataset["samples"]
+ if not reference.is_file() or not isinstance(samples, list) or not 0 < len(samples) <= MAX_TRAINING_SAMPLES:
+ raise ValueError("Invalid training dataset")
+ cleaned = []
+ for sample in samples:
+ audio, text = Path(sample["audio"]), sample["text"]
+ if not audio.is_file() or not isinstance(text, str) or not text.strip() or len(text) > MAX_TRAINING_TEXT:
+ raise ValueError("Invalid training sample")
+ cleaned.append({"audio": str(audio), "text": text.strip()})
+ return {"speaker": speaker, "reference_audio": str(reference), "samples": cleaned}
+
+
+def checkpoint_revision(manifest: dict) -> str:
+ """Bind a fine-tuned voice to its base revision and exact trained weights."""
+ digest = manifest["files"][CHECKPOINT_WEIGHTS]["digest"]
+ return f"{manifest['base_model_id']}@{manifest['base_revision']}+sha256.{digest}"
+
+
+def write_checkpoint_files(snapshot: Path, target: Path, speaker: str) -> None:
+ """Copy the verified base files a checkpoint loads, as the recipe does, and
+ register the trained speaker. The recipe's trainer writes the weights."""
+ for filename in REQUIRED_FILES:
+ if filename == CHECKPOINT_WEIGHTS:
+ continue
+ destination = target / filename
+ destination.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copyfile(snapshot / filename, destination)
+ config = json.loads((snapshot / "config.json").read_text(encoding="utf-8"))
+ config["tts_model_type"] = "custom_voice"
+ talker = config.get("talker_config", {})
+ talker["spk_id"] = {speaker: SPEAKER_TOKEN_ID}
+ talker["spk_is_dialect"] = {speaker: False}
+ config["talker_config"] = talker
+ (target / "config.json").write_text(json.dumps(config, indent=2, ensure_ascii=False), encoding="utf-8")
+
+
+def seal_checkpoint(target: Path, *, base_model_id: str, base_revision: str, speaker: str, step: int, loss) -> dict:
+ """Record digests of every file the checkpoint loads. Synthesis refuses a
+ checkpoint whose bytes no longer match."""
+ files = {}
+ for filename in REQUIRED_FILES:
+ path = target / filename
+ fingerprint = file_fingerprint(path)
+ checksum = hashlib.sha256()
+ with path.open("rb") as source:
+ for chunk in iter(lambda: source.read(1024 * 1024), b""):
+ checksum.update(chunk)
+ if file_fingerprint(path) != fingerprint:
+ raise ValueError(f"Checkpoint file changed while sealing: {filename}")
+ files[filename] = {"size": fingerprint[0], "algorithm": "sha256",
+ "digest": checksum.hexdigest(), "fingerprint": fingerprint}
+ manifest = {
+ "adapter": TRAINING_ADAPTER, "base_model_id": base_model_id, "base_revision": base_revision,
+ "speaker": speaker, "step": step, "loss": loss, "files": files,
+ }
+ publish_json(target / CHECKPOINT_MANIFEST, manifest)
+ return manifest
+
+
+def verified_checkpoint(checkpoint: Path) -> dict | None:
+ """Read a sealed checkpoint produced by this adapter; never fetch or trust
+ unsealed, foreign or modified files."""
+ try:
+ manifest = json.loads((checkpoint / CHECKPOINT_MANIFEST).read_text())
+ if (manifest["adapter"] != TRAINING_ADAPTER or manifest["base_model_id"] not in TRAINABLE_MODELS
+ or not re.fullmatch(r"[0-9a-f]{40}", manifest["base_revision"])
+ or not SPEAKER_NAME_RE.fullmatch(manifest["speaker"])):
+ return None
+ for filename in REQUIRED_FILES:
+ metadata = manifest["files"][filename]
+ if metadata["algorithm"] != "sha256":
+ return None
+ path = checkpoint / filename
+ if sys.platform == "win32" or file_fingerprint(path) != metadata.get("fingerprint"):
+ verify_file(path, metadata)
+ return manifest
+ except (OSError, ValueError, KeyError, TypeError):
+ return None
+
+
+def train_checkpoints(snapshot: Path, dataset: dict, args: argparse.Namespace, staging: Path, emit) -> list[dict]:
+ """Run the official single-speaker SFT recipe and stage weight snapshots.
+
+ This mirrors sft_12hz.py/dataset.py: codec-0 language-model loss plus 0.3x
+ sub-talker loss, AdamW (lr 2e-5, weight decay 0.01), batch 2 with 4-step
+ gradient accumulation and norm-1.0 clipping, bf16 weights, and the reference
+ speaker embedding written into codec row 3000. Staged directories are not
+ promotable until `run_fine_tuning` reloads and auditions them.
+ """
+ import librosa
+ import torch
+ from qwen_tts import Qwen3TTSModel
+ from qwen_tts.core.models.modeling_qwen3_tts import mel_spectrogram
+ from safetensors.torch import save_file
+
+ torch.manual_seed(args.seed)
+ attention = "flash_attention_2" if importlib.util.find_spec("flash_attn") else "eager"
+ qwen = Qwen3TTSModel.from_pretrained(
+ str(snapshot), device_map="cuda:0", dtype=torch.bfloat16,
+ attn_implementation=attention, local_files_only=True,
+ )
+ model, processor, config = qwen.model, qwen.processor, qwen.model.config
+ talker_config = config.talker_config
+
+ def load_24k(path):
+ audio, _ = librosa.load(path, sr=24000, mono=True)
+ return audio.astype("float32")
+
+ with torch.no_grad():
+ reference = torch.from_numpy(load_24k(dataset["reference_audio"])).unsqueeze(0)
+ reference_mel = mel_spectrogram(
+ reference, n_fft=1024, num_mels=128, sampling_rate=24000,
+ hop_size=256, win_size=1024, fmin=0, fmax=12000,
+ ).transpose(1, 2)
+ speaker_embedding = model.speaker_encoder(reference_mel.to(model.device).to(model.dtype)).detach()
+ items = []
+ for sample in dataset["samples"]:
+ codes = model.speech_tokenizer.encode(load_24k(sample["audio"]), sr=24000).audio_codes[0]
+ prompt = f"<|im_start|>assistant\n{sample['text']}<|im_end|>\n<|im_start|>assistant\n"
+ text_ids = processor(text=prompt, return_tensors="pt", padding=True)["input_ids"]
+ text_ids = text_ids.unsqueeze(0) if text_ids.dim() == 1 else text_ids
+ # Codec encode runs in inference mode; rebuild plain tensors so the
+ # embedding lookups can be saved for backward.
+ items.append({"text_ids": text_ids[:, :-5], "codes": torch.tensor(codes.cpu().tolist(), dtype=torch.long)})
+
+ def collate(batch):
+ length = max(item["text_ids"].shape[1] + item["codes"].shape[0] for item in batch) + 8
+ size = len(batch)
+ input_ids = torch.zeros((size, length, 2), dtype=torch.long)
+ codec_ids = torch.zeros((size, length, 16), dtype=torch.long)
+ text_mask = torch.zeros((size, length), dtype=torch.bool)
+ codec_embedding_mask = torch.zeros((size, length), dtype=torch.bool)
+ codec_mask = torch.zeros((size, length), dtype=torch.bool)
+ attention_mask = torch.zeros((size, length), dtype=torch.long)
+ labels = torch.full((size, length), -100, dtype=torch.long)
+ for i, item in enumerate(batch):
+ text_ids, codes = item["text_ids"], item["codes"]
+ text_len, codec_len = text_ids.shape[1], codes.shape[0]
+ end = 8 + text_len + codec_len
+ input_ids[i, :3, 0] = text_ids[0, :3]
+ input_ids[i, 3:7, 0] = config.tts_pad_token_id
+ input_ids[i, 7, 0] = config.tts_bos_token_id
+ input_ids[i, 8:8 + text_len - 3, 0] = text_ids[0, 3:]
+ input_ids[i, 8 + text_len - 3, 0] = config.tts_eos_token_id
+ input_ids[i, 8 + text_len - 2:end, 0] = config.tts_pad_token_id
+ text_mask[i, :end] = True
+ input_ids[i, 3:8, 1] = torch.tensor([
+ talker_config.codec_nothink_id, talker_config.codec_think_bos_id,
+ talker_config.codec_think_eos_id, 0, talker_config.codec_pad_id,
+ ])
+ input_ids[i, 8:8 + text_len - 2, 1] = talker_config.codec_pad_id
+ input_ids[i, 8 + text_len - 2, 1] = talker_config.codec_bos_id
+ audio_start, audio_end = 8 + text_len - 1, 8 + text_len - 1 + codec_len
+ input_ids[i, audio_start:audio_end, 1] = codes[:, 0]
+ input_ids[i, audio_end, 1] = talker_config.codec_eos_token_id
+ labels[i, audio_start:audio_end] = codes[:, 0]
+ labels[i, audio_end] = talker_config.codec_eos_token_id
+ codec_ids[i, audio_start:audio_end, :] = codes
+ codec_embedding_mask[i, 3:end] = True
+ codec_embedding_mask[i, 6] = False # speaker embedding slot
+ codec_mask[i, audio_start:audio_end] = True
+ attention_mask[i, :end] = 1
+ device = model.device
+ return {
+ "input_ids": input_ids.to(device), "codec_ids": codec_ids.to(device),
+ "text_mask": text_mask.unsqueeze(-1).to(device),
+ "codec_embedding_mask": codec_embedding_mask.unsqueeze(-1).to(device),
+ "codec_mask": codec_mask.to(device), "attention_mask": attention_mask.to(device),
+ "labels": labels.to(device),
+ }
+
+ def batch_loss(batch):
+ input_ids, codec_ids, codec_mask = batch["input_ids"], batch["codec_ids"], batch["codec_mask"]
+ text_embedding = model.talker.model.text_embedding(input_ids[:, :, 0]) * batch["text_mask"]
+ codec_embedding = model.talker.model.codec_embedding(input_ids[:, :, 1]) * batch["codec_embedding_mask"]
+ codec_embedding[:, 6, :] = speaker_embedding
+ embeddings = text_embedding + codec_embedding
+ for i in range(1, 16):
+ layer = model.talker.code_predictor.get_input_embeddings()[i - 1]
+ embeddings = embeddings + layer(codec_ids[:, :, i]) * codec_mask.unsqueeze(-1)
+ outputs = model.talker(
+ inputs_embeds=embeddings[:, :-1, :], attention_mask=batch["attention_mask"][:, :-1],
+ labels=batch["labels"][:, 1:], output_hidden_states=True,
+ )
+ hidden = outputs.hidden_states[0][-1][codec_mask[:, :-1]]
+ _, sub_talker_loss = model.talker.forward_sub_talker_finetune(codec_ids[codec_mask], hidden)
+ return outputs.loss + 0.3 * sub_talker_loss
+
+ def stage(step, loss):
+ target = staging / f"step-{step}"
+ shutil.rmtree(target, ignore_errors=True)
+ write_checkpoint_files(snapshot, target, dataset["speaker"])
+ state = {key: value.detach().to("cpu") for key, value in model.state_dict().items()
+ if not key.startswith("speaker_encoder")}
+ row = "talker.model.codec_embedding.weight"
+ state[row] = state[row].clone()
+ state[row][SPEAKER_TOKEN_ID] = speaker_embedding[0].detach().to("cpu", state[row].dtype)
+ save_file(state, str(target / CHECKPOINT_WEIGHTS))
+ return {"path": target, "step": step, "loss": loss}
+
+ optimizer = torch.optim.AdamW(model.parameters(), lr=TRAINING_LEARNING_RATE, weight_decay=0.01)
+ batches_per_epoch = math.ceil(len(items) / TRAINING_BATCH_SIZE)
+ steps_per_epoch = math.ceil(batches_per_epoch / TRAINING_GRADIENT_ACCUMULATION)
+ total_steps = steps_per_epoch * args.epochs
+ generator = torch.Generator().manual_seed(args.seed)
+ staged, step = [], 0
+ model.train()
+ for _epoch in range(args.epochs):
+ order = torch.randperm(len(items), generator=generator).tolist()
+ batches = [order[i:i + TRAINING_BATCH_SIZE] for i in range(0, len(order), TRAINING_BATCH_SIZE)]
+ for start in range(0, len(batches), TRAINING_GRADIENT_ACCUMULATION):
+ group = batches[start:start + TRAINING_GRADIENT_ACCUMULATION]
+ total = 0.0
+ for indices in group:
+ loss = batch_loss(collate([items[i] for i in indices]))
+ (loss / len(group)).backward()
+ total += loss.item() / len(group)
+ torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
+ optimizer.step()
+ optimizer.zero_grad(set_to_none=True)
+ step += 1
+ if not math.isfinite(total):
+ raise ValueError("Training loss diverged")
+ loss_value = round(total, 6)
+ emit({"stage": "training", "step": step, "total_steps": total_steps, "loss": loss_value,
+ "progress": round(100 * step / total_steps, 2)})
+ if step % args.checkpoint_interval == 0 or step == total_steps:
+ staged.append(stage(step, loss_value))
+ # Release the trainer before auditions load each checkpoint on the device.
+ del optimizer, model, qwen
+ torch.cuda.empty_cache()
+ return staged
def run_fine_tuning(args: argparse.Namespace) -> int:
- return unavailable("fine-tuning")
+ """Train, then publish only checkpoints that reload and speak."""
+ if args.model_id not in TRAINABLE_MODELS or not args.models_dir:
+ return unavailable("fine-tuning without a supported verified Base model")
+ if args.epochs < 1 or args.checkpoint_interval < 1:
+ return training_failed("QWEN3_TRAINING_INVALID_REQUEST", "Invalid fine-tuning schedule")
+ if not training_runtime_available():
+ return unavailable("fine-tuning on this hardware/runtime (requires CUDA with bf16, qwen-tts and librosa)")
+ snapshot = installed_snapshot(Path(args.models_dir) / args.model_id.replace("/", "--"), args.model_id)
+ if snapshot is None:
+ return unavailable("fine-tuning without downloaded and verified weights")
+ try:
+ dataset = load_training_dataset(Path(args.dataset_manifest))
+ except (OSError, ValueError, KeyError, TypeError):
+ return training_failed("QWEN3_TRAINING_INVALID_DATASET", "Fine-tuning dataset is missing or invalid")
+
+ output_dir = Path(args.output_dir)
+ staging = output_dir / ".staging"
+ events = sys.stdout
+ emit = lambda event: emit_event(events, event) # noqa: E731
+ use_offline_hub()
+ try:
+ with contextlib.redirect_stdout(sys.stderr):
+ staged = train_checkpoints(snapshot, dataset, args, staging, emit)
+ published = 0
+ for item in staged:
+ sample = item["path"] / "audition.wav"
+ try:
+ # Seal first, then pass the same gate and loader synthesis
+ # uses: only sealed bytes that reload and speak are promotable.
+ manifest = seal_checkpoint(
+ item["path"], base_model_id=args.model_id, base_revision=snapshot.name,
+ speaker=dataset["speaker"], step=item["step"], loss=item["loss"],
+ )
+ if verified_checkpoint(item["path"]) != manifest:
+ raise ValueError("Checkpoint seal did not verify")
+ torch, model = load_torch_model(item["path"], args.seed)
+ with torch.inference_mode():
+ wavs, sample_rate = model.generate_custom_voice(
+ text=AUDITION_TEXT, speaker=manifest["speaker"], language="Auto",
+ )
+ write_model_audio(wavs, sample_rate, sample)
+ del model
+ torch.cuda.empty_cache()
+ except Exception:
+ print(f"❌ Checkpoint at step {item['step']} failed its reload audition", file=sys.stderr)
+ shutil.rmtree(item["path"], ignore_errors=True)
+ continue
+ target = output_dir / f"checkpoint-step-{item['step']}"
+ os.replace(item["path"], target)
+ published += 1
+ emit({"stage": "checkpoint", "checkpoint": target.name, "step": item["step"],
+ "checkpoint_path": str(target), "sample_wav": str(target / "audition.wav"),
+ "loss": item["loss"], "model_revision": checkpoint_revision(manifest)})
+ shutil.rmtree(staging, ignore_errors=True)
+ if not published:
+ return training_failed("QWEN3_TRAINING_FAILED", "No fine-tuned checkpoint passed its reload audition")
+ emit({"stage": "completed", "checkpoints": published})
+ return 0
+ except ImportError:
+ return unavailable("fine-tuning dependencies")
+ except Exception:
+ return training_failed("QWEN3_TRAINING_FAILED", "Qwen3-TTS fine-tuning failed; unverified checkpoints were not published")
def main() -> int:
@@ -369,7 +785,7 @@ def main() -> int:
parser.add_argument("--download", action="store_true", help="Explicitly download and verify a model snapshot")
parser.add_argument("--probe", action="store_true", help="Probe runtime and available models")
parser.add_argument("--models-dir", type=str, help="Directory containing downloaded model weights")
- parser.add_argument("--mode", choices=["design", "clone", "synthesize", "fine-tune"], default="synthesize")
+ parser.add_argument("--mode", choices=["design", "clone", "synthesize", "fine-tuned", "fine-tune"], default="synthesize")
parser.add_argument("--text", type=str, help="Input text for synthesis")
parser.add_argument("--instructions", type=str, help="Delivery / voice design instructions")
parser.add_argument("--seed", type=int, default=42, help="RNG seed")
@@ -380,10 +796,10 @@ def main() -> int:
parser.add_argument("--model-id", type=str, help="HuggingFace model ID")
parser.add_argument("--model-path", type=str, help="Local directory containing model snapshot")
parser.add_argument("--output-wav", type=str, help="Target path for synthesized WAV")
- parser.add_argument("--dataset-dir", type=str, help="Directory containing audio and transcripts for fine-tuning")
+ parser.add_argument("--dataset-manifest", type=str, help="JSON manifest of training audio, transcripts and reference")
parser.add_argument("--output-dir", type=str, help="Output directory for training checkpoints")
parser.add_argument("--epochs", type=int, default=5, help="Number of training epochs")
- parser.add_argument("--checkpoint-interval", type=int, default=50, help="Steps between checkpoints")
+ parser.add_argument("--checkpoint-interval", type=int, default=50, help="Optimizer steps between checkpoints")
args = parser.parse_args()
@@ -406,8 +822,8 @@ def main() -> int:
return 0
if args.mode == "fine-tune":
- if not args.dataset_dir or not args.output_dir:
- sys.stderr.write("Error: --dataset-dir and --output-dir are required for fine-tune mode\n")
+ if not args.dataset_manifest or not args.output_dir:
+ sys.stderr.write("Error: --dataset-manifest and --output-dir are required for fine-tune mode\n")
return 1
return run_fine_tuning(args)
diff --git a/scripts/qwen3_tts_runner.test.js b/scripts/qwen3_tts_runner.test.js
index b9c8683f08..b0652c58fb 100644
--- a/scripts/qwen3_tts_runner.test.js
+++ b/scripts/qwen3_tts_runner.test.js
@@ -371,3 +371,157 @@ print(json.dumps({"status": status, "unavailable": unavailable}))
expect(result.unavailable).toMatchObject({ ok: false });
});
});
+
+// The official training recipe needs bf16 CUDA and its Torch/qwen-tts/librosa
+// stack. These doubles stand in for that stack so the adapter's publication
+// contract runs anywhere; the recipe's tensor math is not exercised here.
+const trainingFixture = String.raw`
+torch.cuda = types.SimpleNamespace(is_available=lambda: True, is_bf16_supported=lambda: True,
+ empty_cache=lambda: None)
+torch.__version__ = "fixture"
+# Checkpoints rewrite the base config, so the fake Hub serves a JSON one.
+payloads["config.json"] = json.dumps({"tts_model_type": "base", "talker_config": {"hidden_size": 8}}).encode()
+for entry in entries:
+ if entry.rfilename == "config.json":
+ entry.size = len(payloads["config.json"])
+ entry.blob_id = hashlib.sha1(f"blob {entry.size}\0".encode() + payloads["config.json"]).hexdigest()
+for name in ("librosa", "safetensors", "safetensors.torch", "transformers", "qwen_tts.core",
+ "qwen_tts.core.models", "qwen_tts.core.models.modeling_qwen3_tts"):
+ sys.modules[name] = types.ModuleType(name)
+sys.modules["transformers"].__version__ = "fixture"
+sys.modules["safetensors.torch"].save_file = lambda *args: None
+sys.modules["qwen_tts.core.models.modeling_qwen3_tts"].mel_spectrogram = lambda *args, **kwargs: None
+def custom_voice(self, **kwargs):
+ events.append({"custom": kwargs})
+ if "step-1" in events[-2]["path"]:
+ raise RuntimeError("private checkpoint failure")
+ return [[1]], 24000
+Model.generate_custom_voice = custom_voice
+base_model = runner.SUPPORTED_MODELS[1]
+def training_args(root, dataset, **kwargs):
+ return types.SimpleNamespace(model_id=kwargs.get("model_id", base_model), models_dir=str(root),
+ dataset_manifest=str(dataset), output_dir=str(root / "job"), epochs=1, checkpoint_interval=1, seed=7)
+def write_dataset(root):
+ clip = root / "clip.wav"
+ clip.write_bytes(b"explicit test fixture")
+ dataset = root / "dataset.json"
+ dataset.write_text(json.dumps({"speaker": "portos_voice", "reference_audio": str(clip),
+ "samples": [{"audio": str(clip), "text": "Invented training words."}]}))
+ return dataset
+trained = []
+def fake_train(snapshot, dataset, args, staging, emit):
+ trained.append(dataset)
+ staged = []
+ for step in (1, 2):
+ emit({"stage": "training", "step": step, "total_steps": 2, "loss": 0.5, "progress": step * 50})
+ target = staging / f"step-{step}"
+ runner.write_checkpoint_files(snapshot, target, dataset["speaker"])
+ (target / runner.CHECKPOINT_WEIGHTS).write_bytes(f"fixture weights {step}".encode())
+ staged.append({"path": target, "step": step, "loss": 0.5})
+ return staged
+runner.train_checkpoints = fake_train
+`;
+
+describe.skipIf(!python)('Qwen3 fine-tuning adapter', () => {
+ it('names the adapter only where the official recipe can run', () => {
+ const result = run(inferenceFixture + trainingFixture + String.raw`
+cuda = runner.probe_runtime()["training_adapter"]
+torch.cuda.is_bf16_supported = lambda: False
+no_bf16 = runner.probe_runtime()["training_adapter"]
+torch.cuda.is_bf16_supported = lambda: True
+sys.modules["librosa"] = None
+missing = runner.probe_runtime()["training_adapter"]
+print(json.dumps([cuda, no_bf16, missing]))
+`);
+ expect(result).toEqual(['qwen-tts-sft-12hz', null, null]);
+ });
+
+ it('publishes only sealed checkpoints that reload and speak, then synthesizes from exactly those bytes', () => {
+ const result = run(inferenceFixture + trainingFixture + String.raw`
+with tempfile.TemporaryDirectory() as temp:
+ root = Path(temp)
+ runner.download_model(base_model, root)
+ output, error = io.StringIO(), io.StringIO()
+ with contextlib.redirect_stdout(output), contextlib.redirect_stderr(error):
+ status = runner.run_fine_tuning(training_args(root, write_dataset(root)))
+ assert status == 0, error.getvalue()
+ assert "private checkpoint failure" not in error.getvalue()
+ frames = [json.loads(line) for line in output.getvalue().splitlines()]
+ checkpoints = [frame for frame in frames if frame["stage"] == "checkpoint"]
+ job = root / "job"
+ # The checkpoint whose reload audition failed is discarded, not published.
+ assert [frame["step"] for frame in checkpoints] == [2]
+ assert not (job / "checkpoint-step-1").exists() and not (job / ".staging").exists()
+ checkpoint = Path(checkpoints[0]["checkpoint_path"])
+ assert checkpoint == job / "checkpoint-step-2" and Path(checkpoints[0]["sample_wav"]).is_file()
+ config = json.loads((checkpoint / "config.json").read_text())
+ assert config["tts_model_type"] == "custom_voice"
+ assert config["talker_config"]["spk_id"] == {"portos_voice": 3000}
+ # Auditions load the checkpoint offline through the synthesis loader.
+ loads = [event for event in events if "path" in event]
+ assert all(event["local_files_only"] is True for event in loads)
+ assert events[-1] == {"custom": {"text": runner.AUDITION_TEXT, "speaker": "portos_voice", "language": "Auto"}}
+
+ events.clear()
+ args = args_for(root, mode="fine-tuned")
+ args.checkpoint_path = str(checkpoint)
+ output = io.StringIO()
+ with contextlib.redirect_stdout(output):
+ assert runner.run_synthesis(args) == 0
+ synthesis = json.loads(output.getvalue())
+ assert events[1]["path"] == str(checkpoint)
+ assert events[2] == {"custom": {"text": "An invented sentence.", "speaker": "portos_voice", "language": "Auto"}}
+
+ # Modified weights, even at the same size and mtime, and unsealed foreign
+ # directories never load.
+ weights = checkpoint / runner.CHECKPOINT_WEIGHTS
+ stat = weights.stat()
+ weights.write_bytes(b"x" * stat.st_size)
+ os.utime(weights, ns=(stat.st_atime_ns, stat.st_mtime_ns))
+ events.clear()
+ with contextlib.redirect_stderr(io.StringIO()):
+ assert runner.run_synthesis(args) == 1
+ args.checkpoint_path = str(root)
+ assert runner.run_synthesis(args) == 1
+ assert events == []
+ print(json.dumps({"checkpoint": checkpoints[0], "synthesis": synthesis}))
+`);
+ const digest = /^Qwen\/Qwen3-TTS-12Hz-1\.7B-Base@a{40}\+sha256\.[0-9a-f]{64}$/;
+ expect(result.checkpoint).toMatchObject({ checkpoint: 'checkpoint-step-2', model_revision: expect.stringMatching(digest) });
+ expect(result.synthesis).toMatchObject({ ok: true, modelRevision: result.checkpoint.model_revision, effectiveControls: { mode: 'fine-tuned', seed: 42 } });
+ });
+
+ it('refuses unsupported hardware, models and datasets before training starts', () => {
+ const result = run(inferenceFixture + trainingFixture + String.raw`
+with tempfile.TemporaryDirectory() as temp:
+ root = Path(temp)
+ dataset = write_dataset(root)
+ failures = []
+ def attempt(args):
+ error = io.StringIO()
+ with contextlib.redirect_stderr(error), contextlib.redirect_stdout(io.StringIO()):
+ assert runner.run_fine_tuning(args) == 1
+ failures.append(json.loads(error.getvalue().splitlines()[-1])["code"])
+ attempt(training_args(root, dataset)) # base weights not downloaded
+ runner.download_model(base_model, root)
+ attempt(training_args(root, dataset, model_id=runner.SUPPORTED_MODELS[0]))
+ (root / "clip.wav").unlink()
+ attempt(training_args(root, dataset))
+ torch.cuda.is_available = lambda: False
+ attempt(training_args(root, write_dataset(root)))
+ runner.platform.system = lambda: "Darwin"
+ runner.platform.machine = lambda: "arm64"
+ torch.cuda.is_available = lambda: True
+ attempt(training_args(root, dataset))
+ assert trained == [] and not (root / "job").exists()
+ print(json.dumps(failures))
+`);
+ expect(result).toEqual([
+ 'QWEN3_RUNTIME_UNAVAILABLE',
+ 'QWEN3_RUNTIME_UNAVAILABLE',
+ 'QWEN3_TRAINING_INVALID_DATASET',
+ 'QWEN3_RUNTIME_UNAVAILABLE',
+ 'QWEN3_RUNTIME_UNAVAILABLE',
+ ]);
+ });
+});
diff --git a/server/services/voice/fineTuning.js b/server/services/voice/fineTuning.js
index 47fbbd6888..0d2a4a1f11 100644
--- a/server/services/voice/fineTuning.js
+++ b/server/services/voice/fineTuning.js
@@ -6,14 +6,17 @@
* checkpoint promotion.
*
* Training is machine-local, optional, and never assumes the last checkpoint is best.
- * It starts only when the runner's probe names a real training adapter; today
- * none exists, so starts refuse and adapter-less legacy checkpoints never promote.
+ * It starts only when the runner's probe names a real training adapter (the
+ * official Qwen single-speaker recipe on bf16 CUDA). The runner publishes a
+ * checkpoint only after it is sealed and reloads to render an audition, and
+ * reports the digest-bound revision promotion records. Adapter-less legacy
+ * checkpoints and checkpoints without that revision never promote.
*/
import { randomUUID } from 'node:crypto';
import { existsSync } from 'node:fs';
import { mkdir, readdir } from 'node:fs/promises';
-import { join } from 'node:path';
+import { dirname, join } from 'node:path';
import { spawn } from '../../lib/childProcess.js';
import { ServerError } from '../../lib/errorHandler.js';
import { atomicWrite, readJSONFileStrict } from '../../lib/fileUtils.js';
@@ -21,7 +24,9 @@ import { safeChildProcessOptions } from '../../lib/processEnv.js';
import { closeJobAfterDelay } from '../../lib/sseUtils.js';
import {
DEFAULT_CLONE_MODEL,
+ QWEN3_TTS_MODELS_DIR,
QWEN3_TTS_RUNNER_SCRIPT,
+ SUPPORTED_QWEN3_MODELS,
getQwen3RuntimeStatus,
} from './qwen3TtsRuntime.js';
import {
@@ -51,6 +56,14 @@ const JOB_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}
// shape so whichever writes first leaves the same record.
const CANCELLED_OUTCOME = Object.freeze({ status: 'cancelled', error: 'Cancelled by user' });
+// The official recipe fine-tunes the Base variants only.
+const TRAINABLE_MODELS = new Set(SUPPORTED_QWEN3_MODELS.map((model) => model.id).filter((id) => id.endsWith('-Base')));
+// Single-speaker recipe: one registered speaker name per checkpoint.
+const TRAINING_SPEAKER = 'portos_voice';
+const DATASET_MANIFEST_FILE = 'dataset.json';
+const AUDIO_FILE_RE = /\.(wav|mp3|flac|m4a)$/i;
+const STDERR_TAIL_BYTES = 8192;
+
const jobRecordPath = (profileId, jobId) =>
join(profileArtifactDirectory(profileId), 'fine-tune', jobId, JOB_RECORD_FILE);
@@ -141,7 +154,7 @@ export async function validateFineTuningDataset(profileId) {
}
const files = await readdir(sourceDir);
- const audioFiles = files.filter((f) => /\.(wav|mp3|flac|m4a)$/i.test(f));
+ const audioFiles = files.filter((f) => AUDIO_FILE_RE.test(f));
fileCount = audioFiles.length;
if (fileCount === 0) {
@@ -168,6 +181,35 @@ export async function validateFineTuningDataset(profileId) {
};
}
+/**
+ * Pair each transcribed source asset with its recording. The first pair is the
+ * speaker reference; the recipe recommends one reference for every sample.
+ */
+function buildTrainingDataset(profile, sourceDir) {
+ const samples = (profile.sourceAssets || [])
+ .filter((asset) => typeof asset.filename === 'string' && AUDIO_FILE_RE.test(asset.filename)
+ && asset.filename === asset.filename.split(/[\\/]/).pop()
+ && asset.transcript?.trim() && existsSync(join(sourceDir, asset.filename)))
+ .map((asset) => ({ audio: join(sourceDir, asset.filename), text: asset.transcript.trim() }));
+ if (samples.length === 0) {
+ throw new ServerError('Dataset not ready: no transcribed source recording is available', {
+ status: 400,
+ code: 'DATASET_NOT_READY',
+ });
+ }
+ return { speaker: TRAINING_SPEAKER, reference_audio: samples[0].audio, samples };
+}
+
+// A checkpoint frame is recorded only when the runner sealed and auditioned
+// it inside this job's own directory.
+const isPublishedCheckpoint = (event, outputDir) => (
+ typeof event.checkpoint === 'string'
+ && typeof event.checkpoint_path === 'string'
+ && dirname(event.checkpoint_path) === outputDir
+ && typeof event.model_revision === 'string'
+ && /@[0-9a-f]{40}\+sha256\.[0-9a-f]{64}$/.test(event.model_revision)
+);
+
/**
* Start an explicit fine-tuning job for a voice profile.
*/
@@ -194,12 +236,27 @@ export async function startFineTuningJob({
code: 'QWEN3_TRAINING_UNAVAILABLE',
});
}
+ if (!TRAINABLE_MODELS.has(baseModel)) {
+ throw new ServerError('Qwen3-TTS fine-tuning supports only the Base models', {
+ status: 400,
+ code: 'QWEN3_TRAINING_UNSUPPORTED_MODEL',
+ });
+ }
+ if (!runtime.models?.[baseModel]?.downloaded) {
+ throw new ServerError('Download and verify the Qwen3-TTS base model before fine-tuning', {
+ status: 409,
+ code: 'QWEN3_MODEL_NOT_INSTALLED',
+ });
+ }
const profile = await getVoiceProfileRequired(profileId);
+ const dataset = buildTrainingDataset(profile, validation.sourceDir);
const jobId = randomUUID();
const profileDir = profileArtifactDirectory(profile.id);
const outputDir = join(profileDir, 'fine-tune', jobId);
await mkdir(outputDir, { recursive: true });
+ const datasetManifest = join(outputDir, DATASET_MANIFEST_FILE);
+ await atomicWrite(datasetManifest, dataset);
const abortController = new AbortController();
const jobState = {
@@ -210,7 +267,8 @@ export async function startFineTuningJob({
status: 'running',
progress: 0,
step: 0,
- totalSteps: epochs * 50,
+ // Optimizer steps depend on the dataset; the runner reports the total.
+ totalSteps: null,
loss: null,
checkpoints: [],
outputDir,
@@ -229,7 +287,8 @@ export async function startFineTuningJob({
const args = [
QWEN3_TTS_RUNNER_SCRIPT,
'--mode', 'fine-tune',
- '--dataset-dir', validation.sourceDir,
+ '--models-dir', QWEN3_TTS_MODELS_DIR,
+ '--dataset-manifest', datasetManifest,
'--output-dir', outputDir,
'--epochs', String(epochs),
'--checkpoint-interval', String(checkpointInterval),
@@ -240,6 +299,19 @@ export async function startFineTuningJob({
// Keep a handle on the child so a future shutdown hook can reach in-flight training.
jobState.child = child;
+ // Drain stderr so a long run cannot block on a full pipe; keep the tail for
+ // the runner's structured (path-free) failure message.
+ let stderrTail = '';
+ child.stderr?.on('data', (chunk) => { stderrTail = (stderrTail + chunk.toString()).slice(-STDERR_TAIL_BYTES); });
+ const runnerError = () => {
+ try {
+ const failure = JSON.parse(stderrTail.trim().split(/\r?\n/).at(-1));
+ return typeof failure?.error === 'string' ? failure.error : null;
+ } catch {
+ return null;
+ }
+ };
+
let lineBuffer = '';
child.stdout.on('data', (chunk) => {
lineBuffer += chunk.toString();
@@ -256,13 +328,14 @@ export async function startFineTuningJob({
jobState.totalSteps = event.total_steps || jobState.totalSteps;
jobState.loss = event.loss;
jobState.progress = event.progress;
- } else if (event.stage === 'checkpoint') {
+ } else if (event.stage === 'checkpoint' && isPublishedCheckpoint(event, outputDir)) {
jobState.checkpoints.push({
id: event.checkpoint,
step: event.step,
checkpointPath: event.checkpoint_path,
sampleWav: event.sample_wav,
loss: event.loss,
+ modelRevision: event.model_revision,
createdAt: new Date().toISOString(),
});
// Checkpoints are the promotable artifact, so index each one as it
@@ -300,7 +373,9 @@ export async function startFineTuningJob({
// run is the likely cause, so name the signal rather than "code null".
settle({
status: 'failed',
- error: code === null ? `Process terminated by signal ${signal}` : `Process exited with code ${code}`,
+ error: code === null
+ ? `Process terminated by signal ${signal}`
+ : (runnerError() || `Process exited with code ${code}`),
});
});
@@ -313,6 +388,7 @@ export async function startFineTuningJob({
profileId: profile.id,
status: jobState.status,
totalSteps: jobState.totalSteps,
+ trainingAdapter: jobState.trainingAdapter,
startedAt: jobState.startedAt,
};
}
@@ -356,9 +432,9 @@ export async function promoteCheckpoint({ profileId, jobId, checkpointId }) {
if (!ckpt) {
throw new ServerError(`Checkpoint not found: ${checkpointId}`, { status: 404, code: 'CHECKPOINT_NOT_FOUND' });
}
- // Earlier runners wrote text placeholders named .safetensors. A job without
- // the adapter that produced it can never become an approved voice.
- if (!job.trainingAdapter) {
+ // Earlier runners wrote text placeholders named .safetensors. A checkpoint
+ // without its producing adapter and sealed revision never becomes a voice.
+ if (!job.trainingAdapter || typeof ckpt.modelRevision !== 'string') {
throw new ServerError('Checkpoint was not produced by a supported training adapter', {
status: 409,
code: 'CHECKPOINT_UNVERIFIED',
@@ -371,7 +447,7 @@ export async function promoteCheckpoint({ profileId, jobId, checkpointId }) {
characterId: job.characterId,
checkpointPath: ckpt.checkpointPath,
checkpointId: ckpt.id,
- modelRevision: `qwen3-tts:checkpoint-${ckpt.step}`,
+ modelRevision: ckpt.modelRevision,
step: ckpt.step,
});
}
diff --git a/server/services/voice/fineTuning.test.js b/server/services/voice/fineTuning.test.js
index d5e813de27..25fa36faf4 100644
--- a/server/services/voice/fineTuning.test.js
+++ b/server/services/voice/fineTuning.test.js
@@ -8,9 +8,9 @@ import { SSE_CLEANUP_DELAY_MS } from '../../lib/sseUtils.js';
let voiceProfilesRoot = '';
const queryMock = vi.fn();
-// Both overrides default to null = "use the real thing". The runner itself
-// reports no training adapter today (scripts/qwen3_tts_runner.test.js), so the
-// lifecycle cases stand in a scripted adapter and child for a future one.
+// Both overrides default to null = "use the real thing". The runner's own
+// publication contract is covered in scripts/qwen3_tts_runner.test.js; these
+// lifecycle cases script its stdout frames instead of training a model.
let spawnOverride = null;
let runtimeOverride = null;
@@ -90,6 +90,7 @@ const jobRecordPath = (jobId) => join(voiceProfilesRoot, PROFILE.id, 'fine-tune'
const createScriptedChild = ({ signal } = {}) => {
const child = new EventEmitter();
child.stdout = new EventEmitter();
+ child.stderr = new EventEmitter();
child.kill = vi.fn();
// Frames mirror the runner's stdout contract (scripts/qwen3_tts_runner.py);
// they describe the contract a real training adapter must emit.
@@ -111,21 +112,36 @@ const createScriptedChild = ({ signal } = {}) => {
return child;
};
-const checkpointFrame = (step) => ({
+const BASE_MODEL = 'Qwen/Qwen3-TTS-12Hz-1.7B-Base';
+const jobDir = (jobId) => join(voiceProfilesRoot, PROFILE.id, 'fine-tune', jobId);
+const revisionFor = (step) => `${BASE_MODEL}@${'a'.repeat(40)}+sha256.${String(step).padStart(64, '0')}`;
+
+// A sealed, auditioned checkpoint as the runner publishes it: inside the job's
+// directory, with the digest-bound revision promotion records.
+const checkpointFrame = (jobId, step) => ({
stage: 'checkpoint',
step,
- checkpoint: `checkpoint-${step}.safetensors`,
- checkpoint_path: `/scripted/checkpoint-${step}.safetensors`,
- sample_wav: `/scripted/sample-step-${step}.wav`,
+ checkpoint: `checkpoint-step-${step}`,
+ checkpoint_path: join(jobDir(jobId), `checkpoint-step-${step}`),
+ sample_wav: join(jobDir(jobId), `checkpoint-step-${step}`, 'audition.wav'),
loss: 0.42,
+ model_revision: revisionFor(step),
+});
+
+const READY_RUNTIME = Object.freeze({
+ ok: true,
+ pythonPath: '/scripted/python',
+ trainingAdapter: 'qwen-tts-sft-12hz',
+ models: { [BASE_MODEL]: { downloaded: true } },
});
/** Install a scripted child and hand the test the handle spawn will return. */
const useScriptedRunner = () => {
- runtimeOverride = { ok: true, pythonPath: '/scripted/python', trainingAdapter: 'scripted-adapter' };
+ runtimeOverride = READY_RUNTIME;
let child = null;
- spawnOverride = (_command, _args, options) => {
+ spawnOverride = (_command, args, options) => {
child = createScriptedChild(options);
+ child.args = args;
return child;
};
// The job's spawn happens inside startFineTuningJob, so resolve lazily.
@@ -183,12 +199,24 @@ describe('fineTuning', () => {
expect(startRes).toMatchObject({ jobId: expect.any(String), status: 'running' });
const child = scripted();
+ // The runner receives the verified model root and a dataset manifest that
+ // pairs each transcribed recording with its text.
+ const argValue = (flag) => child.args[child.args.indexOf(flag) + 1];
+ expect(argValue('--model-id')).toBe(BASE_MODEL);
+ expect(argValue('--models-dir')).toEqual(expect.any(String));
+ expect(JSON.parse(await readFile(argValue('--dataset-manifest'), 'utf8'))).toEqual({
+ speaker: 'portos_voice',
+ reference_audio: join(voiceProfilesRoot, PROFILE.id, 'source', 'sample.wav'),
+ samples: [{ audio: join(voiceProfilesRoot, PROFILE.id, 'source', 'sample.wav'), text: 'Training transcription sample.' }],
+ });
child.emitFrames(
- { stage: 'init', total_steps: 100 },
{ stage: 'training', step: 20, total_steps: 100, loss: 1.2, progress: 20 },
- checkpointFrame(20),
- checkpointFrame(100),
- { stage: 'completed', total_steps: 100 },
+ checkpointFrame(startRes.jobId, 20),
+ // Frames that were not sealed inside this job are never indexed.
+ { ...checkpointFrame(startRes.jobId, 40), checkpoint_path: '/elsewhere/checkpoint-step-40' },
+ { ...checkpointFrame(startRes.jobId, 60), model_revision: 'qwen3-tts:checkpoint-60' },
+ checkpointFrame(startRes.jobId, 100),
+ { stage: 'completed', checkpoints: 2 },
);
child.exit(0);
@@ -199,12 +227,14 @@ describe('fineTuning', () => {
expect(status.status).toBe('completed');
expect(status.progress).toBe(100);
expect(status.step).toBe(20);
- expect(status.checkpoints).toHaveLength(2);
+ expect(status.totalSteps).toBe(100);
+ expect(status.checkpoints.map((checkpoint) => checkpoint.step)).toEqual([20, 100]);
expect(status.checkpoints[0]).toMatchObject({
- id: 'checkpoint-20.safetensors',
+ id: 'checkpoint-step-20',
step: 20,
- checkpointPath: '/scripted/checkpoint-20.safetensors',
- sampleWav: '/scripted/sample-step-20.wav',
+ checkpointPath: join(jobDir(startRes.jobId), 'checkpoint-step-20'),
+ sampleWav: join(jobDir(startRes.jobId), 'checkpoint-step-20', 'audition.wav'),
+ modelRevision: revisionFor(20),
});
const promoteRes = await promoteCheckpoint({
@@ -215,7 +245,8 @@ describe('fineTuning', () => {
expect(promoteRes).toMatchObject({
kind: 'fine-tuned',
approval: { status: 'approved' },
- inference: { checkpointPath: '/scripted/checkpoint-20.safetensors' },
+ modelRevision: revisionFor(20),
+ inference: { checkpointPath: join(jobDir(startRes.jobId), 'checkpoint-step-20') },
});
});
@@ -225,7 +256,7 @@ describe('fineTuning', () => {
const scripted = useScriptedRunner();
const startRes = await startFineTuningJob({ profileId: PROFILE.id, epochs: 50 });
- scripted().emitFrames(checkpointFrame(50));
+ scripted().emitFrames(checkpointFrame(startRes.jobId, 50));
const cancelRes = cancelFineTuningJob(startRes.jobId);
expect(cancelRes).toMatchObject({ ok: true, jobId: startRes.jobId, status: 'cancelled' });
@@ -255,6 +286,17 @@ describe('fineTuning', () => {
error: 'Process exited with code 3',
});
+ // The runner's structured, path-free failure is what the operator sees.
+ const refused = await startFineTuningJob({ profileId: PROFILE.id, epochs: 2 });
+ scripted().stderr.emit('data', Buffer.from(`${JSON.stringify({
+ ok: false, code: 'QWEN3_TRAINING_FAILED', error: 'No fine-tuned checkpoint passed its reload audition',
+ })}\n`));
+ scripted().exit(1);
+ expect(await drainJobRecord(refused.jobId)).toMatchObject({
+ status: 'failed',
+ error: 'No fine-tuned checkpoint passed its reload audition',
+ });
+
// A killed child reports a null code; "exited with code null" tells the
// operator nothing about an OOM reap partway through a long run.
const killed = await startFineTuningJob({ profileId: PROFILE.id, epochs: 2 });
@@ -275,7 +317,7 @@ describe('fineTuning', () => {
epochs: 2,
checkpointInterval: 20,
});
- scripted().emitFrames(checkpointFrame(100), { stage: 'completed', total_steps: 100 });
+ scripted().emitFrames(checkpointFrame(jobId, 100), { stage: 'completed', total_steps: 100 });
scripted().exit(0);
const record = await drainJobRecord(jobId);
@@ -300,7 +342,7 @@ describe('fineTuning', () => {
epochs: 2,
checkpointInterval: 20,
});
- scripted().emitFrames(checkpointFrame(100), { stage: 'completed', total_steps: 100 });
+ scripted().emitFrames(checkpointFrame(jobId, 100), { stage: 'completed', total_steps: 100 });
scripted().exit(0);
const record = await drainJobRecord(jobId);
expect(record.checkpoints.length).toBeGreaterThan(0);
@@ -359,7 +401,7 @@ describe('fineTuning', () => {
epochs: 2,
checkpointInterval: 20,
});
- scripted().emitFrames(checkpointFrame(100), { stage: 'completed', total_steps: 100 });
+ scripted().emitFrames(checkpointFrame(jobId, 100), { stage: 'completed', total_steps: 100 });
scripted().exit(0);
await drainJobRecord(jobId);
@@ -376,6 +418,23 @@ describe('fineTuning', () => {
});
});
+describe('fineTuning without a trainable model', () => {
+ it('refuses non-Base or unverified base weights before creating a job or spawning', async () => {
+ queryMock.mockResolvedValue({ rows: [{ data: PROFILE }] });
+ await seedSourceAudio();
+ spawnOverride = vi.fn();
+ runtimeOverride = READY_RUNTIME;
+
+ await expect(startFineTuningJob({ profileId: PROFILE.id, baseModel: 'Qwen/Qwen3-TTS-12Hz-1.7B-VoiceDesign' }))
+ .rejects.toMatchObject({ status: 400, code: 'QWEN3_TRAINING_UNSUPPORTED_MODEL' });
+ runtimeOverride = { ...READY_RUNTIME, models: { [BASE_MODEL]: { downloaded: false } } };
+ await expect(startFineTuningJob({ profileId: PROFILE.id }))
+ .rejects.toMatchObject({ status: 409, code: 'QWEN3_MODEL_NOT_INSTALLED' });
+ expect(spawnOverride).not.toHaveBeenCalled();
+ await expect(readFile(join(voiceProfilesRoot, PROFILE.id, 'fine-tune'))).rejects.toMatchObject({ code: 'ENOENT' });
+ });
+});
+
describe('fineTuning without a training adapter', () => {
it('refuses to start before creating a job or spawning when inference is ready but training is not', async () => {
queryMock.mockResolvedValue({ rows: [{ data: PROFILE }] });
@@ -402,6 +461,15 @@ describe('fineTuning without a training adapter', () => {
checkpoints: [{ id: 'checkpoint-20.safetensors', step: 20, checkpointPath: '/legacy/checkpoint-20.safetensors' }],
}));
+ await expect(promoteCheckpoint({ profileId: PROFILE.id, jobId, checkpointId: 'checkpoint-20.safetensors' }))
+ .rejects.toMatchObject({ status: 409, code: 'CHECKPOINT_UNVERIFIED' });
+
+ // An adapter name alone is not enough: an unsealed checkpoint has no
+ // digest-bound revision for synthesis to verify against.
+ await writeFile(jobRecordPath(jobId), JSON.stringify({
+ ...JSON.parse(await readFile(jobRecordPath(jobId), 'utf8')),
+ trainingAdapter: 'qwen-tts-sft-12hz',
+ }));
await expect(promoteCheckpoint({ profileId: PROFILE.id, jobId, checkpointId: 'checkpoint-20.safetensors' }))
.rejects.toMatchObject({ status: 409, code: 'CHECKPOINT_UNVERIFIED' });
expect(queryMock.mock.calls.some(([sql]) => /insert|update/i.test(sql))).toBe(false);
diff --git a/server/services/voice/tts-qwen3.js b/server/services/voice/tts-qwen3.js
index 0e14dce4f7..87522a0d0b 100644
--- a/server/services/voice/tts-qwen3.js
+++ b/server/services/voice/tts-qwen3.js
@@ -52,6 +52,14 @@ export async function synthesizeQwen3(text, opts = {}, signal) {
}
const mode = opts.mode || (opts.referenceAudio ? 'clone' : (opts.instructions ? 'design' : 'synthesize'));
+ const fineTuned = mode === 'fine-tuned';
+ if (fineTuned && (!opts.checkpointPath || !opts.modelId)) {
+ throw new ServerError('Fine-tuned Qwen3-TTS voice has no promoted checkpoint', {
+ status: 503,
+ code: 'QWEN3_RUNTIME_UNAVAILABLE',
+ });
+ }
+ // A fine-tuned profile's modelId is the sealed checkpoint revision it promoted.
const modelId = opts.modelId || (mode === 'clone' ? DEFAULT_CLONE_MODEL : DEFAULT_DESIGN_MODEL);
const rate = typeof opts.rate === 'number' && Number.isFinite(opts.rate)
? Math.max(0.25, Math.min(4.0, opts.rate))
@@ -112,9 +120,13 @@ export async function synthesizeQwen3(text, opts = {}, signal) {
let result;
try { result = JSON.parse(stdout.trim()); } catch { /* Invalid adapter output is never successful speech. */ }
- if (result?.ok !== true || typeof result.modelRevision !== 'string' || !result.modelRevision.startsWith(`${modelId}@`)
- || !/^[a-f0-9]{40}$/.test(result.modelRevision.slice(modelId.length + 1))
- || !['design', 'clone'].includes(result.effectiveControls?.mode)
+ // Fine-tuned speech must come from exactly the promoted checkpoint bytes.
+ const revisionMatches = fineTuned
+ ? result?.modelRevision === modelId && result?.effectiveControls?.mode === 'fine-tuned'
+ : typeof result?.modelRevision === 'string' && result.modelRevision.startsWith(`${modelId}@`)
+ && /^[a-f0-9]{40}$/.test(result.modelRevision.slice(modelId.length + 1))
+ && ['design', 'clone'].includes(result.effectiveControls?.mode);
+ if (result?.ok !== true || !revisionMatches
|| result.effectiveControls?.rate !== rate || result.effectiveControls?.seed !== seed) {
throw new ServerError('Qwen3-TTS returned invalid inference evidence', { status: 502, code: 'QWEN3_SYNTHESIS_INVALID_RESULT' });
}
diff --git a/server/services/voice/tts-qwen3.test.js b/server/services/voice/tts-qwen3.test.js
index e0c81dd6e8..d7f0370d91 100644
--- a/server/services/voice/tts-qwen3.test.js
+++ b/server/services/voice/tts-qwen3.test.js
@@ -74,4 +74,24 @@ describe('tts-qwen3', () => {
readFile.mockResolvedValue(Buffer.from('not a wav'));
await expect(synthesizeQwen3('Example')).rejects.toMatchObject({ code: 'QWEN3_SYNTHESIS_INVALID_RESULT' });
});
+
+ it('speaks a fine-tuned voice only from the exact promoted checkpoint revision', async () => {
+ const revision = `Qwen/Qwen3-TTS-12Hz-1.7B-Base@${'a'.repeat(40)}+sha256.${'b'.repeat(64)}`;
+ const opts = { mode: 'fine-tuned', checkpointPath: '/example/checkpoint-step-20', modelId: revision };
+ const fineTuned = { ok: true, modelRevision: revision, effectiveControls: { mode: 'fine-tuned', seed: 42, rate: 1, instructions: null } };
+ runnerResponse(fineTuned);
+ await expect(synthesizeQwen3('Example', opts)).resolves.toMatchObject({ modelRevision: revision });
+ const args = spawn.mock.calls[0][1];
+ expect(args[args.indexOf('--checkpoint-path') + 1]).toBe('/example/checkpoint-step-20');
+ expect(args[args.indexOf('--mode') + 1]).toBe('fine-tuned');
+
+ // Different trained weights under the same base revision are not this voice.
+ runnerResponse({ ...fineTuned, modelRevision: revision.replace(/b{64}$/, 'c'.repeat(64)) });
+ await expect(synthesizeQwen3('Example', opts)).rejects.toMatchObject({ code: 'QWEN3_SYNTHESIS_INVALID_RESULT' });
+
+ spawn.mockClear();
+ await expect(synthesizeQwen3('Example', { mode: 'fine-tuned', modelId: revision }))
+ .rejects.toMatchObject({ status: 503, code: 'QWEN3_RUNTIME_UNAVAILABLE' });
+ expect(spawn).not.toHaveBeenCalled();
+ });
});