Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: size audio.cpp TTS models from measured peaks and run TQ2_1 on the CPU (#16514)
oobabooga28f3e5da9128
diff --git a/studio/backend/core/inference/audio_cpp_failures.py b/studio/backend/core/inference/audio_cpp_failures.pyindex 45d2c1c8658..9c4a7f39b05 100644--- a/studio/backend/core/inference/audio_cpp_failures.py+++ b/studio/backend/core/inference/audio_cpp_failures.py@@ -134,10 +134,31 @@ def attach_failure(exc: BaseException, failure: Optional[AudioCppFailure]) -> Bareturn exc-def estimate_resident_gb(size_bytes: int) -> float:+# GiB; resident = weights * per_weight + fixed. Generic matches Qwen3-TTS at its 8192-token cap.+_GENERIC_PROFILE = (2.5, 1.5)+# family -> (per_weight, fixed, largest package measured): audio.cpp v0.9.3 CUDA peak plus at least+# 0.9 GiB. Families whose peak grows with the input (VibeVoice) must stay on the generic formula.+_MEASURED_PROFILES = {+ "chatterbox": (1.0, 3.5, 3.5),+ "higgs_audio_tts": (1.0, 2.0, 4.8),+ "kokoro_tts": (1.0, 3.5, 0.2),+ "voxcpm2": (2.2, 4.7, 4.5),+ "voxtral_tts": (1.0, 2.0, 4.4),+}+++def estimate_resident_gb(size_bytes: int, family: Optional[str] = None) -> float:"""Resident GPU memory for an audio.cpp package: weights plus graph and cache buffers.- Measured TTS peaks run about 3x the q8 weights (Qwen3-TTS 0.6B: 1.9 GB file, 5.9 GB peak)."""- return round(size_bytes / (1024**3) * 2.5 + 1.5, 2)+ A measured family uses its own profile; a package past the sizes measured for it gets the+ larger of that profile and the generic one."""+ weights_gb = size_bytes / (1024**3)+ generic = weights_gb * _GENERIC_PROFILE[0] + _GENERIC_PROFILE[1]+ profile = _MEASURED_PROFILES.get(family or "")+ if profile is None:+ return round(generic, 2)+ per_weight, fixed, measured_up_to_gb = profile+ measured = weights_gb * per_weight + fixed+ return round(measured if weights_gb <= measured_up_to_gb else max(measured, generic), 2)def smaller_variants(@@ -160,7 +181,7 @@ def smaller_variants(extra += found.size_bytes if found is not None else 0rows = []for variant in sorted(model.variants, key = lambda v: v.size_bytes, reverse = True):- estimate = estimate_resident_gb(variant.size_bytes + extra)+ estimate = estimate_resident_gb(variant.size_bytes + extra, getattr(model, "family", None))if not 0 < variant.size_bytes < model.size_bytes or (free_gb is not None and estimate > free_gb):diff --git a/studio/backend/core/inference/audio_cpp_models.py b/studio/backend/core/inference/audio_cpp_models.pyindex 342cc93d246..7e91cd498cf 100644--- a/studio/backend/core/inference/audio_cpp_models.py+++ b/studio/backend/core/inference/audio_cpp_models.py@@ -1576,8 +1576,11 @@ def list_files(_QUANT_RE = re.compile(- r"(?:^|[-_.])((?:i?q\d(?:_[a-z0-9]+)*)|bf16|f16|f32|fp16|fp32|orig)(?=$|[-_.])", re.IGNORECASE+ r"(?:^|[-_.])((?:[it]?q\d(?:_[a-z0-9]+)*)|bf16|f16|f32|fp16|fp32|orig)(?=$|[-_.])",+ re.IGNORECASE,)+# Ternary TQ2_1 (GGUF type 44) has only a CPU kernel; CUDA aborts on it (kitten_tts2 docs).+CPU_ONLY_QUANTS = frozenset(("TQ2_1",))# K and IQ quants come after F32 so the established order stays as it was._QUANT_PREFERENCE = (*("Q8_0", "F16", "BF16", "ORIG", "Q6_K", "Q5_K_M", "Q4_K_M", "Q4_0", "F32"),@@ -2154,6 +2157,11 @@ class AudioCppModel:def size_bytes(self) -> int:return self.variant.size_bytes+ @property+ def cpu_only(self) -> bool:+ """The variant's weights have no GPU kernel in audio.cpp, so it runs on the CPU backend."""+ return quant_label(self.gguf_file) in CPU_ONLY_QUANTS+@propertydef audio_type(self) -> Optional[str]:if self.task == "tts":diff --git a/studio/backend/core/inference/audio_cpp_server.py b/studio/backend/core/inference/audio_cpp_server.pyindex 2473f3bc2a3..7f7d578da2c 100644--- a/studio/backend/core/inference/audio_cpp_server.py+++ b/studio/backend/core/inference/audio_cpp_server.py@@ -496,7 +496,8 @@ class AudioCppServer:problem = model_runtime_problem(model, binary)if problem:raise AudioCppUnavailableError(problem)- backend = select_backend(binary, force_cpu)+ # A CPU-only package aborts the server on a GPU backend, whoever starts it.+ backend = select_backend(binary, force_cpu or getattr(model, "cpu_only", False))model_id = f"studio-{uuid.uuid4().hex[:12]}"entry: dict[str, Any] = {"id": model_id,diff --git a/studio/backend/core/inference/audio_device.py b/studio/backend/core/inference/audio_device.pyindex f2064989c5b..a636a426080 100644--- a/studio/backend/core/inference/audio_device.py+++ b/studio/backend/core/inference/audio_device.py@@ -8,7 +8,7 @@ accelerator (a failed load still retries on CPU). Values match RAG_EMBED_DEVICEfrom __future__ import annotationsimport os-from typing import Optional+from typing import Any, Optional__all__ = ["AUDIO_DEVICE_CHOICES",@@ -79,10 +79,15 @@ def audio_device_forces_cpu(value: Optional[str]) -> bool:return normalize_audio_device(value) == "cpu"-def audio_load_runs_on_cpu(audio_type: Optional[str], value: Optional[str]) -> bool:+def audio_load_runs_on_cpu(+ audio_type: Optional[str],+ value: Optional[str],+ model: Any = None,+) -> bool:"""True when a native audio load of this type ends up in CPU RAM: asked for, or a GGUF- audio model on an audio.cpp runtime that only runs on the CPU (Auto cannot place it on a GPU)."""- if audio_device_forces_cpu(value):+ audio model on an audio.cpp runtime that only runs on the CPU (Auto cannot place it on a GPU).+ A CPU-only audio.cpp package (``model``, TQ2_1) runs on the CPU too."""+ if audio_device_forces_cpu(value) or getattr(model, "cpu_only", False):return Truefrom core.inference.audio_cpp_models import AUDIO_CPP_AUDIO_TYPESdiff --git a/studio/backend/core/inference/orchestrator.py b/studio/backend/core/inference/orchestrator.pyindex 3e715786b6f..d31b2d582d1 100644--- a/studio/backend/core/inference/orchestrator.py+++ b/studio/backend/core/inference/orchestrator.py@@ -2337,8 +2337,11 @@ class InferenceOrchestrator:if audio_cpp_model:# The worker picks its backend from this: a Hub id alone does not say audio.cpp.sub_config["audio_cpp"] = True- if audio_load_runs_on_cpu(getattr(config, "audio_type", None), audio_device):- # A CPU-only runtime runs Auto on the CPU too: say so, so no card is chosen and the worker hides them.+ if audio_load_runs_on_cpu(+ getattr(config, "audio_type", None), audio_device, config.audio_cpp+ ):+ # A CPU-only runtime or package runs Auto on the CPU too: say so, so no card+ # is chosen and the worker hides them.audio_device = "cpu"sub_config["audio_device"] = audio_deviceif audio_device_forces_cpu(audio_device) and (@@ -2562,6 +2565,9 @@ class InferenceOrchestrator:_audio_type in NATIVE_AUDIO_TYPESand audio_load_runs_on_cpu(_audio_type, audio_device)) or model_info.get("audio_cpp_backend") == "cpu"+ self.models[self.active_model_name]["audio_cpu_only"] = bool(+ getattr(getattr(config, "audio_cpp", None), "cpu_only", False)+ )self.models[self.active_model_name].update(_mlx_runtime_mirror_fields(model_info))diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 008e4deb33d..81aac3ad9a6 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -16039,7 +16039,7 @@ def _native_audio_cpu_load(config, request) -> bool:audio_type = getattr(config, "audio_type", None)return audio_type in NATIVE_AUDIO_TYPES and audio_load_runs_on_cpu(- audio_type, getattr(request, "audio_device", None)+ audio_type, getattr(request, "audio_device", None), getattr(config, "audio_cpp", None))@@ -16052,6 +16052,9 @@ def _resident_audio_placement_matches(backend, request) -> bool:audio_type = resident.get("audio_type")if audio_type not in NATIVE_AUDIO_TYPES:return True+ if resident.get("audio_cpu_only"):+ # A CPU-only package lands on the CPU whatever the device, so no request moves it.+ return Truedevice = getattr(request, "audio_device", None)if resident.get("audio_device_fallback") == "cpu":# Its GPU start failed: Auto would land on the CPU again, so only a pinned GPU reloads.@@ -16169,7 +16172,9 @@ async def _preflight_native_audio_placement(# Umbrella id: size from the one variant it loads, not repository bytes.audio_cpp_model = getattr(config, "audio_cpp", None)if audio_cpp_model is not None:- required_gb = audio_cpp_resident_gb(audio_cpp_model.size_bytes)+ required_gb = audio_cpp_resident_gb(+ audio_cpp_model.size_bytes, audio_cpp_model.family+ )elif len(targets) > 1:required_gb = 0.0for target in targets:diff --git a/studio/backend/tests/test_audio_cpp_cpu_only_packages.py b/studio/backend/tests/test_audio_cpp_cpu_only_packages.pynew file mode 100644index 00000000000..1d59fe0c39e--- /dev/null+++ b/studio/backend/tests/test_audio_cpp_cpu_only_packages.py@@ -0,0 +1,154 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""A CPU-only audio.cpp package (KittenTTS2 TQ2_1, which aborts on CUDA) runs on the CPU on Auto."""++from __future__ import annotations++import asyncio+from dataclasses import replace+from types import SimpleNamespace++import pytest++import routes.inference as ri+from core.inference import audio_cpp_models as models+from core.inference import audio_cpp_server as srv+from core.inference import audio_device+from core.inference.audio_cpp_models import AudioCppModel, RepoFile, quant_label++FOLDER = "KittenTTS2-GGUF"+FILES = [+ RepoFile(f"{FOLDER}/kitten-tts2-20261021-q8_0.gguf", 3),+ RepoFile(f"{FOLDER}/kitten-tts2-20261021-q4_0.gguf", 2),+ RepoFile(f"{FOLDER}/kitten-tts2-20261021-tq2_1.gguf", 1),+]+++def _kitten(key: str) -> AudioCppModel:+ variants = tuple(models._single_file_variants(FILES, FOLDER))+ chosen = next(v for v in variants if v.key == key)+ return AudioCppModel(+ id = f"audio-cpp/audio.cpp-gguf/{FOLDER}",+ repo_id = "audio-cpp/audio.cpp-gguf",+ folder = FOLDER,+ display_name = FOLDER,+ family = "kitten_tts2",+ task = "tts",+ server_task = "tts",+ variant = chosen,+ variants = variants,+ default_variant = "Q8_0",+ )+++def test_the_ternary_file_is_labelled_tq2_1_and_only_it_is_cpu_only():+ assert quant_label("kitten-tts2-20261021-tq2_1.gguf") == "TQ2_1"+ assert sorted(v.key for v in models._single_file_variants(FILES, FOLDER)) == [+ "Q4_0",+ "Q8_0",+ "TQ2_1",+ ]+ assert _kitten("TQ2_1").cpu_only+ assert not _kitten("Q8_0").cpu_only and not _kitten("Q4_0").cpu_only++[email protected]("device", [None, "auto", "gpu"])+def test_auto_runs_a_cpu_only_package_on_the_cpu(monkeypatch, device):+ monkeypatch.setattr(srv, "runtime_runs_on_cpu", lambda: False)+ monkeypatch.setattr(audio_device, "audio_device_default", lambda: "auto")+ tts = _kitten("TQ2_1").audio_type+ assert audio_device.audio_load_runs_on_cpu(tts, device, _kitten("TQ2_1"))+ assert not audio_device.audio_load_runs_on_cpu(tts, device, _kitten("Q8_0"))+ assert not audio_device.audio_load_runs_on_cpu(tts, device)+++def test_the_server_never_starts_a_cpu_only_package_on_a_gpu_backend(monkeypatch):+ seen = []+ monkeypatch.setattr(srv, "ensure_binary", lambda: "/bin/audiocpp_server")+ monkeypatch.setattr(srv, "model_runtime_problem", lambda model, binary = None: None)+ monkeypatch.setattr(+ srv, "select_backend", lambda binary, force_cpu: "cpu" if force_cpu else "cuda"+ )+ monkeypatch.setattr(+ srv.AudioCppServer,+ "_start_once",+ classmethod(lambda cls, model, model_id, backend, *rest: seen.append(backend) or backend),+ )+ assert srv.AudioCppServer.start(_kitten("TQ2_1"), "/m.gguf") == "cpu"+ assert srv.AudioCppServer.start(_kitten("Q8_0"), "/m.gguf") == "cuda"+ assert srv.AudioCppServer.start(_kitten("Q8_0"), "/m.gguf", force_cpu = True) == "cpu"+++def test_the_preflight_sizes_no_gpu_for_a_cpu_only_package(monkeypatch):+ monkeypatch.setattr(srv, "runtime_runs_on_cpu", lambda: False)+ monkeypatch.setattr(srv, "model_runtime_problem", lambda model, binary = None: None)+ model = _kitten("TQ2_1")+ config = SimpleNamespace(identifier = model.id, audio_type = model.audio_type, audio_cpp = model)+ request = SimpleNamespace(gpu_ids = None, hf_token = None, max_seq_length = 2048, audio_device = "auto")+ placement = ri._LoadPlacement(None, None, False, False)+ assert ri._native_audio_cpu_load(config, request)+ # Returned untouched: no GPU chosen and no VRAM estimate, so a full card cannot refuse it.+ assert (+ asyncio.run(ri._preflight_native_audio_placement(config, request, placement)) is placement+ )+ gpu = replace(config.__dict__["audio_cpp"], variant = _kitten("Q8_0").variant)+ assert not ri._native_audio_cpu_load(+ SimpleNamespace(**{**config.__dict__, "audio_cpp": gpu}), request+ )++[email protected]("key, cpu_only", [("TQ2_1", True), ("Q8_0", False)])+def test_an_orchestrator_load_sends_cpu_to_the_worker_and_records_the_package(+ monkeypatch, key, cpu_only+):+ from unittest.mock import MagicMock, patch++ from core.inference import orchestrator as orch_mod++ class _NoThread:+ def __init__(self, *args, **kwargs):+ pass++ def start(self):+ return None++ with patch.object(orch_mod.threading, "Thread", _NoThread):+ orch = orch_mod.InferenceOrchestrator()+ monkeypatch.setattr(srv, "runtime_runs_on_cpu", lambda: False)+ model = _kitten(key)+ config = SimpleNamespace(+ identifier = model.id, gguf_variant = None, audio_type = model.audio_type, audio_cpp = model+ )+ model_info = {"identifier": model.id, "audio_type": model.audio_type}+ if cpu_only:+ model_info["audio_cpp_backend"] = "cpu"+ gpu_selection = MagicMock(return_value = ([0], {"selection_mode": "auto"}))+ spawn = MagicMock()+ with (+ patch.object(orch_mod, "prepare_gpu_selection", gpu_selection),+ patch.object(orch, "_ensure_subprocess_alive", return_value = False),+ patch.object(orch, "_spawn_subprocess", spawn),+ patch.object(+ orch, "_wait_response", return_value = {"success": True, "model_info": model_info}+ ),+ patch("utils.transformers_version.needs_transformers_5", return_value = False),+ ):+ assert orch.load_model(config = config, audio_device = "auto")++ sub_config = spawn.call_args.args[0]+ resident = orch.models[model.id]+ assert sub_config["audio_device"] == ("cpu" if cpu_only else "auto")+ # No card is sized or chosen for a load the worker runs on the CPU.+ assert gpu_selection.called is not cpu_only+ assert sub_config["gpu_selection"]["selection_mode"] == ("cpu_audio" if cpu_only else "auto")+ assert resident["audio_cpu_only"] is cpu_only and resident["audio_cpu"] is cpu_only+ # Auto again: the resident package already sits where Auto would put it.+ assert ri._resident_audio_placement_matches(orch, SimpleNamespace(audio_device = "auto"))++[email protected]("device", ["auto", "cpu", "gpu"])+def test_a_resident_cpu_only_package_is_not_reloaded_for_its_device(device):+ resident = {"audio_type": "audiocpp_tts", "audio_cpu": True, "audio_cpu_only": True}+ backend = SimpleNamespace(active_model_name = "m", models = {"m": resident})+ assert ri._resident_audio_placement_matches(backend, SimpleNamespace(audio_device = device))diff --git a/studio/backend/tests/test_audio_cpp_failure_routes.py b/studio/backend/tests/test_audio_cpp_failure_routes.pyindex 817b9a0761d..1c2ed9abaa1 100644--- a/studio/backend/tests/test_audio_cpp_failure_routes.py+++ b/studio/backend/tests/test_audio_cpp_failure_routes.py@@ -7,6 +7,7 @@ unclassified keeps today's status and text."""from __future__ import annotationsimport asyncio+import dataclassesimport jsonfrom types import SimpleNamespacefrom unittest.mock import AsyncMock, MagicMock, patch@@ -92,10 +93,11 @@ def _preflight(*,availability = None,prepared = None,+ model = None,):import utils.hardware as hardware- model = _model()+ model = model or _model()config = SimpleNamespace(identifier = model.id, audio_type = "audiocpp_tts", audio_cpp = model)request = SimpleNamespace(gpu_ids = None, hf_token = None, max_seq_length = 2048, audio_device = None)placement = ri._LoadPlacement(None, None, False, False)@@ -141,6 +143,40 @@ def test_placement_refusal_lists_variants_that_fit(monkeypatch):assert detail["message"].startswith("No single GPU has enough free memory for Model M.")+ "family, size_gb, free_gb, fits",+ [+ # 7.3 GB free is an 8 GB card under a desktop session.+ ("voxtral_tts", 3, 7.3, True),+ ("chatterbox", 3, 7.3, True),+ ("qwen3_tts", 3, 7.3, False),+ ("vibevoice", 3, 7.3, False),+ # Families whose measured peak is above the generic formula are refused where it fit.+ ("voxcpm2", 2.75, 9.5, False),+ ("qwen3_tts", 2.75, 9.5, True),+ ("kokoro_tts", 0.18, 3.0, False),+ ],+)+def test_placement_uses_the_family_estimate(monkeypatch, family, size_gb, free_gb, fits):+ monkeypatch.setattr(af, "offload_options", lambda model: [])+ size = int(size_gb * 1024**3)+ base = _model(sizes = (3,))+ variant = dataclasses.replace(+ base.variant, files = (dataclasses.replace(base.variant.files[0], size = size),)+ )+ model = dataclasses.replace(base, family = family, variant = variant, variants = (variant,))+ availability = ri._NativeAudioAvailability({0: free_gb}, {0: 0.0})+ prepared = ([0], {"selection_mode": "fallback_all"})+ if not fits:+ with pytest.raises(HTTPException) as raised:+ _preflight(None, availability = availability, prepared = prepared, model = model)+ assert raised.value.detail["code"] == "out_of_memory"+ return+ placement = _preflight(None, availability = availability, prepared = prepared, model = model)+ assert placement.resolved_gpu_ids == [0]+ assert placement.native_required_gb == af.estimate_resident_gb(size, family) < free_gb++def test_generation_crash_oom_maps_to_out_of_memory(monkeypatch):tail = "ggml_gallocr_reserve_n: failed to allocate CUDA0 buffer of size 9663676416"crash = af.attach_failure(diff --git a/studio/backend/tests/test_audio_cpp_failures.py b/studio/backend/tests/test_audio_cpp_failures.pyindex c37efd9d71e..fffaf52fc6f 100644--- a/studio/backend/tests/test_audio_cpp_failures.py+++ b/studio/backend/tests/test_audio_cpp_failures.py@@ -123,6 +123,39 @@ def test_studio_runtime_messages_classify(tmp_path, monkeypatch):assert newer.code == "family_unknown_to_runtime" and "Model M" in newer.message+def test_estimate_uses_the_measured_family_profile():+ gb = 1024**3+ generic = af.estimate_resident_gb(3 * gb)+ assert generic == af.estimate_resident_gb(3 * gb, "qwen3_tts") == 9.0+ assert af.estimate_resident_gb(3 * gb, None) == generic+ assert af.estimate_resident_gb(3 * gb, "new") == generic+ # Peak grows with the input, so it keeps the generic formula.+ assert af.estimate_resident_gb(3 * gb, "vibevoice") == generic+ # Measured below the generic formula.+ assert af.estimate_resident_gb(3 * gb, "chatterbox") == 6.5+ assert af.estimate_resident_gb(int(4.4 * gb), "voxtral_tts") == 6.4+ # Measured above it: Kokoro q8 peaks at 2.7 GB, VoxCPM2 q8 at 9.7 GB and bf16 at 13.3 GB.+ assert af.estimate_resident_gb(int(0.1765 * gb), "kokoro_tts") == 3.68 > 2.7+ assert af.estimate_resident_gb(int(2.7521 * gb), "voxcpm2") == 10.75 > 9.7+ assert af.estimate_resident_gb(int(4.4445 * gb), "voxcpm2") == 14.48 > 13.3+++def test_past_the_measured_sizes_the_estimate_never_drops_below_either_profile():+ gb = 1024**3+ # A bigger model of a family measured low: the generic formula.+ assert af.estimate_resident_gb(8 * gb, "voxtral_tts") == af.estimate_resident_gb(8 * gb) == 21.5+ # A bigger model of a family measured high: its own profile.+ assert af.estimate_resident_gb(int(8.8887 * gb), "voxcpm2") == 24.26+ assert af.estimate_resident_gb(int(8.8887 * gb)) == 23.72+++def test_smaller_variants_estimate_with_the_family(monkeypatch):+ model = replace(_model(sizes = (6, 3, 1), current = 0), family = "chatterbox")+ rows = af.smaller_variants(model)+ assert [(row["label"], row["estimate_gb"]) for row in rows] == [("Q3", 6.5), ("Q1", 4.5)]+ assert [row["label"] for row in af.smaller_variants(model, free_gb = 7.3)] == ["Q3", "Q1"]++def test_oom_lists_smaller_variants_and_offload_options(monkeypatch):from core.inference import audio_cpp_models as models