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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: add verified MLX Qwen voice inference (#8857)
[._.]/ Adam Eivyd4d18f1e46f5
diff --git a/docs/features/voice.md b/docs/features/voice.mdindex e5a2d621a5..0fd1eb06b1 100644--- a/docs/features/voice.md+++ b/docs/features/voice.md@@ -10,7 +10,7 @@ PortOS includes an optional voice assistant with support for fully local operati|-------|----------------|--------------|--------|| Speech-to-text | Browser [Web Speech API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Speech_API) (default — **note**: Chromium browsers forward audio to a vendor cloud speech service) or [whisper.cpp](https://github.com/ggerganov/whisper.cpp) via `whisper-server` (HTTP :5562, fully local) | — | ✅ (whisper) / ⚠️ (web-speech) || LLM | LM Studio (`/v1/chat/completions`) | OpenAI-compatible local server | ✅ |-| Text-to-speech | [Piper](https://github.com/rhasspy/piper) (CLI) | Qwen3-TTS (CPU/CUDA; MLX pending) | ✅ |+| Text-to-speech | [Piper](https://github.com/rhasspy/piper) (CLI) | Qwen3-TTS (CPU/CUDA/Apple Silicon MLX) | ✅ || Voice activity | AudioWorklet + RMS VAD (hands-free) or `MediaRecorder` (push-to-talk) — Web Speech mode bypasses server audio and posts final text via `voice:text` | — | ✅ |The TTS engine is selectable in **Settings → Voice → TTS engine**.@@ -19,8 +19,14 @@ The TTS engine is selectable in **Settings → Voice → TTS engine**.[qwen-tts inference API](https://github.com/QwenLM/Qwen3-TTS#python-package-usage)for voice design and reference cloning on CPU/CUDA. Install `qwen-tts` in theisolated Qwen Python environment; the package supplies Torch, NumPy and-SoundFile. Apple Silicon MLX, training and custom checkpoints are still-unavailable. Speech-rate changes and instruction-controlled Base cloning are+SoundFile. Apple Silicon uses [MLX Audio](https://github.com/Blaizzy/mlx-audio)+against the same verified official snapshots. In the isolated Qwen Python+environment, install `mlx-audio` at commit+`784b29e2691a93ca7483147d86f61859dfaa6296` (the adapter's reference API) plus+`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 arerefused rather than reported as applied controls. Explicit modeldownloads in Settings fetch the official Qwen snapshot at an immutable Hubrevision and verify the size and digest of every required file, including the@@ -40,7 +46,7 @@ The returned model revision includes the immutable commit hash. No modeldownload runs automatically. Audio is buffered, not streamed.A real-model intelligibility smoke run is still pending in #8857; fixture tests-prove the adapter contract, not speech quality. On a CPU/CUDA host with the+prove the adapter contract, not speech quality. On a supported host with theisolated environment and verified weights, run the following manually fromthe repository root (substitute the isolated Python executable and model root):@@ -362,6 +368,6 @@ streaming qualification. Without that opt-in, AuK remains studio-only and theexisting interactive fallback is retained. The production planner checks theinteractive route rather than treating every approved studio voice as live-ready.-The legacy Qwen runtime has placeholder inference/training and is excluded from+The separate Qwen runtime supports verified local inference but has no training adapter and is excluded fromVoice Studio assignment until repaired (issue #8857). Voice Studio does notclaim a Qwen runtime is working merely because its metadata exists.diff --git a/scripts/qwen3_tts_runner.py b/scripts/qwen3_tts_runner.pyindex fd9c4a5816..49cfbef496 100755--- a/scripts/qwen3_tts_runner.py+++ b/scripts/qwen3_tts_runner.py@@ -200,10 +200,20 @@ def probe_runtime(models_dir: Path | None = None) -> dict:except ImportError:pass- # Apple Silicon is deliberately unavailable until the MLX adapter exists;- # the presence of a Torch MPS device must not advertise supported inference.+ # Probe the actual backend without loading a model or acquiring weights.if platform.system() == "Darwin" and platform.machine() == "arm64":- result["error"] = "Qwen3-TTS MLX inference is unavailable on Apple Silicon"+ result["error"] = "Qwen3-TTS inference requires mlx-audio and soundfile on Apple Silicon"+ try:+ import mlx.core as mx+ from mlx_audio.tts.models.qwen3_tts import Model+ from mlx_audio.tts.utils import load_model+ import soundfile+ if mx.metal.is_available():+ result["ok"] = True+ result["error"] = None+ result["device"] = "mlx"+ except ImportError:+ passelif result["torch_installed"] and result["transformers_installed"]:try:from qwen_tts import Qwen3TTSModel@@ -241,8 +251,7 @@ def run_synthesis(args: argparse.Namespace) -> int:return unavailable("custom checkpoints/model paths")if args.rate != 1.0:return unavailable("speech-rate control")- if platform.system() == "Darwin" and platform.machine() == "arm64":- return unavailable("MLX inference on Apple Silicon")+ use_mlx = platform.system() == "Darwin" and platform.machine() == "arm64"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("/", "--")@@ -258,6 +267,10 @@ def run_synthesis(args: argparse.Namespace) -> int:return unavailable("cloning without a local reference recording")if not design and args.instructions:return unavailable("instruction-controlled reference cloning")+ # MLX Base uses in-context cloning. Without both a transcript and an+ # encoder it falls back to unconditioned speech, which is not cloning.+ 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.@@ -267,29 +280,58 @@ def run_synthesis(args: argparse.Namespace) -> int:with contextlib.redirect_stdout(sys.stderr):import numpy as npimport soundfile as sf- 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,- )- with torch.inference_mode():+ if use_mlx:+ import mlx.core as mx+ from mlx_audio.tts.utils import load_model++ mx.random.seed(args.seed)+ model = load_model(snapshot, strict=True)+ if model.tokenizer is None or model.speech_tokenizer is None:+ raise ValueError("MLX model tokenizer is unavailable")if design:- wavs, sample_rate = model.generate_voice_design(- text=args.text, language="Auto",+ results = list(model.generate_voice_design(+ text=args.text, language="auto",instruct=args.instructions or "A clear natural speaking voice.",- )+ stream=False, verbose=False,+ ))else:- wavs, sample_rate = model.generate_voice_clone(- text=args.text, language="Auto",+ if not model.speech_tokenizer.has_encoder:+ raise ValueError("MLX reference encoder is unavailable")+ results = list(model.generate(+ text=args.text, lang_code="auto",ref_audio=str(Path(args.reference_audio).resolve()),- ref_text=args.reference_transcript or None,- x_vector_only_mode=not bool(args.reference_transcript),- )+ ref_text=args.reference_transcript,+ split_pattern=None, stream=False, verbose=False,+ ))+ if len(results) != 1:+ raise ValueError("Invalid MLX model audio result")+ # Materialize lazy MLX output before publishing any audio.+ 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,+ )+ with torch.inference_mode():+ if design:+ wavs, sample_rate = model.generate_voice_design(+ text=args.text, language="Auto",+ instruct=args.instructions or "A clear natural speaking voice.",+ )+ else:+ wavs, sample_rate = model.generate_voice_clone(+ text=args.text, language="Auto",+ ref_audio=str(Path(args.reference_audio).resolve()),+ 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])@@ -305,7 +347,7 @@ def run_synthesis(args: argparse.Namespace) -> int:}))return 0except ImportError:- return unavailable("inference dependencies (install qwen-tts in the isolated environment)")+ 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.@@ -339,7 +381,7 @@ def main() -> int: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")-+args = parser.parse_args()if args.download:diff --git a/scripts/qwen3_tts_runner.test.js b/scripts/qwen3_tts_runner.test.jsindex e34ce0147c..9715ba17fb 100644--- a/scripts/qwen3_tts_runner.test.js+++ b/scripts/qwen3_tts_runner.test.js@@ -98,6 +98,43 @@ def args_for(root, **kwargs):seed=42, output_wav=str(root / "output.wav"))`;+// MLX uses a generator and a separate codec encoder; exercise its actual+// adapter shape without importing Metal or synthesizing real model audio.+const mlxFixture = String.raw`+runner.platform.system = lambda: "Darwin"+runner.platform.machine = lambda: "arm64"+mlx = types.ModuleType("mlx")+core = types.ModuleType("mlx.core")+core.random = types.SimpleNamespace(seed=lambda seed: events.append({"mlxSeed": seed}))+core.eval = lambda audio: events.append({"evaluated": True})+core.metal = types.SimpleNamespace(is_available=lambda: True)+mlx.core = core+sys.modules["mlx"] = mlx+sys.modules["mlx.core"] = core+class MlxModel:+ tokenizer = object()+ speech_tokenizer = types.SimpleNamespace(has_encoder=True)+ def generate_voice_design(self, **kwargs):+ events.append({"mlxDesign": kwargs})+ yield types.SimpleNamespace(audio=[1], sample_rate=24000)+ def generate(self, **kwargs):+ events.append({"mlxClone": kwargs})+ yield types.SimpleNamespace(audio=[1], sample_rate=24000)+def load_mlx(path, **kwargs):+ assert isinstance(path, Path) and path.name == revision+ assert os.environ["HF_HUB_OFFLINE"] == "1"+ assert os.environ["TRANSFORMERS_OFFLINE"] == "1"+ assert kwargs == {"strict": True}+ events.append({"mlxLoad": True})+ return MlxModel()+utils = types.ModuleType("mlx_audio.tts.utils")+utils.load_model = load_mlx+sys.modules["mlx_audio.tts.utils"] = utils+qwen_mlx = types.ModuleType("mlx_audio.tts.models.qwen3_tts")+qwen_mlx.Model = MlxModel+sys.modules["mlx_audio.tts.models.qwen3_tts"] = qwen_mlx+`;+describe.skipIf(!python)('Qwen3 explicit model acquisition', () => {it('publishes only complete immutable snapshots and detects missing/truncated required weights', () => {const result = run(String.raw`@@ -207,7 +244,7 @@ with tempfile.TemporaryDirectory() as temp:expect(result.clone).toMatchObject({ ok: true, modelRevision: `Qwen/Qwen3-TTS-12Hz-1.7B-Base@${'a'.repeat(40)}`, effectiveControls: { mode: 'clone' } });});- it('refuses missing weights, unsupported controls/variants and Apple Silicon without calling the model', () => {+ it('refuses missing weights, unsupported controls/variants and missing MLX dependencies without calling the model', () => {const result = run(inferenceFixture + String.raw`with tempfile.TemporaryDirectory() as temp:root = Path(temp)@@ -226,6 +263,7 @@ with tempfile.TemporaryDirectory() as temp:args.checkpoint_path = Nonerunner.platform.system = lambda: "Darwin"runner.platform.machine = lambda: "arm64"+ sys.modules["mlx"] = Noneassert runner.run_synthesis(args) == 1assert runner.run_fine_tuning(args) == 1assert events == []@@ -262,3 +300,74 @@ with tempfile.TemporaryDirectory() as temp:expect(result.every((failure) => failure.code === 'QWEN3_SYNTHESIS_FAILED')).toBe(true);});});+++describe.skipIf(!python)('Qwen3 Apple Silicon inference', () => {+ it('runs design and transcript-conditioned cloning through the verified MLX snapshot', () => {+ const result = run(inferenceFixture + mlxFixture + String.raw`+with tempfile.TemporaryDirectory() as temp:+ root = Path(temp)+ runner.download_model(model_id, root)+ output = io.StringIO()+ with contextlib.redirect_stdout(output):+ assert runner.run_synthesis(args_for(root, instructions="Warm natural alto")) == 0+ design = json.loads(output.getvalue())+ assert events == [{"mlxSeed": 42}, {"mlxLoad": True}, {"mlxDesign": {+ "text": "An invented sentence.", "language": "auto", "instruct": "Warm natural alto",+ "stream": False, "verbose": False}}, {"evaluated": True}]+ model_id = runner.SUPPORTED_MODELS[1]+ runner.download_model(model_id, root)+ reference = root / "reference.wav"+ reference.write_bytes(b"explicit test fixture")+ events.clear()+ output = io.StringIO()+ with contextlib.redirect_stdout(output):+ assert runner.run_synthesis(args_for(root, mode="clone", reference=str(reference), transcript="Reference words.")) == 0+ clone = json.loads(output.getvalue())+ assert events[2]["mlxClone"] == {+ "text": "An invented sentence.", "lang_code": "auto", "ref_audio": str(reference.resolve()),+ "ref_text": "Reference words.", "split_pattern": None, "stream": False, "verbose": False}+ with wave.open(str(root / "output.wav")) as audio:+ assert audio.getnframes() == 240 and audio.getframerate() == 24000+ print(json.dumps({"design": design, "clone": clone}))+`);+ expect(result.design).toMatchObject({ ok: true, effectiveControls: { mode: 'design', seed: 42 } });+ expect(result.clone).toMatchObject({ ok: true, modelRevision: `Qwen/Qwen3-TTS-12Hz-1.7B-Base@${'a'.repeat(40)}`, effectiveControls: { mode: 'clone' } });+ });++ it('refuses cloning without transcript or encoder instead of publishing unconditioned speech', () => {+ const result = run(inferenceFixture + mlxFixture + String.raw`+with tempfile.TemporaryDirectory() as temp:+ root = Path(temp)+ model_id = runner.SUPPORTED_MODELS[1]+ runner.download_model(model_id, root)+ reference = root / "reference.wav"+ reference.write_bytes(b"explicit test fixture")+ args = args_for(root, mode="clone", reference=str(reference))+ with contextlib.redirect_stderr(io.StringIO()):+ assert runner.run_synthesis(args) == 1+ assert events == []+ args.reference_transcript = "Reference words."+ MlxModel.speech_tokenizer.has_encoder = False+ assert runner.run_synthesis(args) == 1+ assert not any("mlxClone" in event for event in events)+ assert not (root / "output.wav").exists()+ print(json.dumps({"noUnconditionedAudio": True}))+`);+ expect(result).toEqual({ noUnconditionedAudio: true });+ });++ it('probes MLX readiness without Torch or loading weights and refuses missing Metal', () => {+ const result = run(inferenceFixture + mlxFixture + String.raw`+sys.modules["torch"] = None+sys.modules["transformers"] = None+status = runner.probe_runtime()+assert events == []+core.metal.is_available = lambda: False+unavailable = runner.probe_runtime()+print(json.dumps({"status": status, "unavailable": unavailable}))+`);+ expect(result.status).toMatchObject({ ok: true, device: 'mlx', error: null, torch_installed: false });+ expect(result.unavailable).toMatchObject({ ok: false });+ });+});