Skip to content

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.

Studio: fix audio.cpp partial downloads, aligner progress, CPU fallback (#13515)

Etherl00b323c1fcf3
diff --git a/studio/backend/core/inference/audio_cpp_models.py b/studio/backend/core/inference/audio_cpp_models.py
index b985e2dcb9b..e7167fe8283 100644
--- a/studio/backend/core/inference/audio_cpp_models.py
+++ b/studio/backend/core/inference/audio_cpp_models.py
@@ -2043,6 +2043,7 @@ class AudioCppModel:
music: Optional[MusicSpec] = field(default = None, hash = False, compare = False)
# A strict spec (``schema_version``) makes the runtime refuse any undeclared option.
request_keys: Optional[frozenset[str]] = field(default = None, hash = False, compare = False)
+ from_hub: bool = field(default = False, hash = False, compare = False)
@property
def is_package(self) -> bool:
@@ -2350,6 +2351,7 @@ def _resolve_uncached(
default_variant = variant.key,
unsupported = reason,
local_path = ref.local_path,
+ from_hub = from_hub,
)
spec = runtime_spec(family)
embedded = header.spec if header is not None else None
@@ -2431,6 +2433,7 @@ def _resolve_uncached(
separation = policy.separation,
music = music_with_spec_bounds(policy.music, _raw_request_options(spec, embedded)),
request_keys = _request_keys(spec, embedded),
+ from_hub = from_hub,
)
return model.with_variant(chosen)
@@ -2529,6 +2532,7 @@ def download_target(
identifier: Optional[str],
variant: Optional[str],
hf_token: Optional[str] = None,
+ persist: bool = True,
) -> Optional[tuple[str, str]]:
"""``(repo, variant key)`` the Hub GGUF downloader fetches for an umbrella folder row, else None.
@@ -2543,15 +2547,102 @@ def download_target(
return None
from hub.utils.gguf import gguf_variant_key
- return model.repo_id, gguf_variant_key(model.variant.primary)
+ key = gguf_variant_key(model.variant.primary)
+ # A cache-only listing can name a crowded folder's file by its bare quant: record Hub listings only.
+ if model.from_hub:
+ row = (model.id, model.variant.key)
+ with _job_rows_lock:
+ _job_rows[(model.repo_id.lower(), key.lower())] = row
+ # Saved only at a job's start: a status poll after completion would recreate the dropped file.
+ if persist and _saved_job_row(key) != row:
+ _save_job_row(key, row)
+ return model.repo_id, key
+
+
+# (umbrella repo, planner key) -> (row id, quant) at job start: a file in flight has no cache entry yet.
+_job_rows: dict[tuple[str, str], tuple[str, str]] = {}
+_job_rows_lock = threading.Lock()
+# Persisted for restarted / sibling backends; one file per key so concurrent writers never merge a map.
+_JOB_ROWS_DIR = "audio_cpp_job_rows"
+
+
+def _job_row_path(key: str, create: bool = False) -> Optional[Path]:
+ from hub.utils.state_dir import state_root
+
+ root = state_root(create = create)
+ if root is None:
+ return None
+ folder = root / _JOB_ROWS_DIR
+ if create:
+ try:
+ folder.mkdir(exist_ok = True)
+ except OSError:
+ return None
+ return folder / f"{hashlib.sha256(key.lower().encode()).hexdigest()[:32]}.json"
+
+
+def _saved_job_row(key: str) -> Optional[tuple[str, str]]:
+ """The persisted row of ``key``; anything unreadable or malformed reads as absent."""
+ try:
+ path = _job_row_path(key)
+ data = json.loads(path.read_text(encoding = "utf-8")) if path is not None else None
+ except Exception: # noqa: BLE001 - unreadable, malformed or absurdly nested: no saved row
+ return None
+ if not (isinstance(data, list) and len(data) == 3 and all(isinstance(v, str) for v in data)):
+ return None
+ saved_key, row_id, quant = data
+ # A damaged file must not rename another model.
+ folder = key.split("/", 1)[0]
+ if saved_key.lower() != key.lower() or not quant:
+ return None
+ if row_id.lower() != f"{AUDIO_CPP_REPO}/{folder}".lower():
+ return None
+ return row_id, quant
+
+
+def _save_job_row(key: str, row: Optional[tuple[str, str]]) -> None:
+ """Record (or with None drop) ``key``'s row on disk. Best effort: a failed write keeps the old file."""
+ path = _job_row_path(key, create = row is not None)
+ if path is None:
+ return
+ if row is None:
+ try:
+ path.unlink(missing_ok = True)
+ except OSError as exc:
+ logger.debug("audio.cpp: could not drop the row of %s: %s", key, exc)
+ return
+ tmp = path.with_name(f".{path.name}.{os.getpid()}.{threading.get_ident()}.tmp")
+ try:
+ tmp.write_text(json.dumps([key, *row]), encoding = "utf-8")
+ os.replace(tmp, path)
+ except OSError as exc:
+ logger.debug("audio.cpp: could not save the row of %s: %s", key, exc)
+ try:
+ tmp.unlink(missing_ok = True)
+ except OSError:
+ pass
+
+
+def forget_job_row(repo_id: Optional[str], variant: Optional[str]) -> None:
+ """Drop an umbrella job's saved row once the job has ended; this process keeps its own copy."""
+ if str(repo_id or "").lower() != AUDIO_CPP_REPO.lower() or not variant:
+ return
+ _save_job_row(variant.replace("\\", "/"), None)
def folder_row_for_download(repo_id: str, variant: Optional[str]) -> Optional[tuple[str, str]]:
"""``(folder row id, variant key)`` for an umbrella download job, the inverse of
- ``download_target``: jobs run on the umbrella repo, but Studio names them by row. None for
- any other job. Answered from the cache, falling back to reading the planner key's path."""
+ ``download_target``: jobs run on the umbrella repo, but Unsloth Studio names them by row. None
+ for any other job. Answered from what ``download_target`` recorded when the job started, then
+ from the cache, falling back to reading the planner key's path."""
if str(repo_id or "").lower() != AUDIO_CPP_REPO.lower() or not variant or "/" not in variant:
return None
+ with _job_rows_lock:
+ started = _job_rows.get((repo_id.lower(), variant.replace("\\", "/").lower()))
+ if started is None:
+ started = _saved_job_row(variant.replace("\\", "/"))
+ if started is not None:
+ return started
parts = variant.replace("\\", "/").split("/")
row_id = f"{AUDIO_CPP_REPO}/{parts[0]}"
try:
diff --git a/studio/backend/core/inference/audio_cpp_server.py b/studio/backend/core/inference/audio_cpp_server.py
index a14b68c8580..001e4e06981 100644
--- a/studio/backend/core/inference/audio_cpp_server.py
+++ b/studio/backend/core/inference/audio_cpp_server.py
@@ -56,6 +56,8 @@ _ERROR_BODY_BYTES = 64 * 1024
# CUDA graph replay wedges these transducers mid-request (server spins, never answers); graphs off fixes it.
_NO_CUDA_GRAPH_FAMILIES = frozenset({"nemotron_asr", "parakeet_tdt"})
_GPU_HOST_THREADS = 8
+# Startup output of a GPU backend that found no device, as opposed to a model that failed to load.
+_GPU_INIT_FAILURES = ("has no device", "failed to initialize cuda", "backend requested but")
class AudioCppUnavailableError(RuntimeError):
@@ -214,6 +216,36 @@ def model_runtime_problem(model: AudioCppModel, binary: Optional[str] = None) ->
return None
+def _gpu_vendors() -> Optional[set[str]]:
+ """GPU vendors this process can reach, or None when that cannot be told."""
+ try:
+ from utils.llama_cpp_path_settings import (
+ _amd_mask_hides_all,
+ _mask_hides_all,
+ host_gpu_vendors,
+ )
+
+ vendors = host_gpu_vendors()
+ # Windows detection only sees driver DLLs, so apply the visibility masks here too.
+ if vendors is not None:
+ if _mask_hides_all("CUDA_VISIBLE_DEVICES"):
+ vendors = vendors - {"nvidia"}
+ if _amd_mask_hides_all():
+ vendors = vendors - {"amd"}
+ return vendors
+ except Exception: # noqa: BLE001 - an unknown host keeps the build's backend
+ return None
+
+
+def _reachable(backend: str) -> str:
+ """CPU when ``backend`` needs a GPU vendor this process cannot see (e.g. CUDA_VISIBLE_DEVICES="")."""
+ vendor = {"cuda": "nvidia", "hip": "amd"}.get(backend)
+ if vendor is None:
+ return backend
+ vendors = _gpu_vendors()
+ return "cpu" if vendors is not None and vendor not in vendors else backend
+
+
def select_backend(binary: str, force_cpu: bool) -> str:
"""The ``--backend`` for this launch: CPU when asked, else what the install was built for."""
if force_cpu:
@@ -223,13 +255,13 @@ def select_backend(binary: str, force_cpu: bool) -> str:
return override
recorded = str(read_install_record(binary).get("backend") or "").strip().lower()
if recorded in ("cpu", "cuda", "vulkan", "metal", "hip"):
- return recorded
+ return _reachable(recorded)
# A custom build with no record: what it was compiled with, preferring the host's GPU.
built = compiled_backends(binary)
if sys.platform == "darwin":
return "metal" if built is None or "metal" in built else "cpu"
if shutil.which("nvidia-smi") and (built is None or "cuda" in built):
- return "cuda"
+ return _reachable("cuda")
if built and "vulkan" in built:
return "vulkan"
return "cpu"
@@ -502,10 +534,18 @@ class AudioCppServer:
if not self.alive():
tail = self.log_tail()
logger.warning("audiocpp_server exited during startup: %s", tail)
+ last = f" Last output: {sanitize_runtime_tail(tail)}" if tail else ""
+ # A CUDA build prints its CUDA init failure on CPU launches too.
+ lowered = tail.lower()
+ if self.backend != "cpu" and any(s in lowered for s in _GPU_INIT_FAILURES):
+ raise AudioCppUnavailableError(
+ f"The audio runtime could not start on the {self.backend.upper()} backend "
+ "because no usable GPU is visible. Choose CPU for the audio device in "
+ "Unsloth Studio, or set UNSLOTH_AUDIO_CPP_BACKEND=cpu." + last
+ )
raise AudioCppUnavailableError(
"The audio runtime exited before becoming ready; the model file may be "
- "incomplete or unsupported by this build."
- + (f" Last output: {sanitize_runtime_tail(tail)}" if tail else "")
+ "incomplete or unsupported by this build." + last
)
if self._probe():
return
diff --git a/studio/backend/core/inference/stt_audiocpp_sidecar.py b/studio/backend/core/inference/stt_audiocpp_sidecar.py
index 28f2627b1d0..d6d6a65de7a 100644
--- a/studio/backend/core/inference/stt_audiocpp_sidecar.py
+++ b/studio/backend/core/inference/stt_audiocpp_sidecar.py
@@ -50,6 +50,7 @@ from core.inference.audio_cpp_server import (
AudioCppServer,
AudioCppStartCancelledError,
AudioCppUnavailableError,
+ runtime_runs_on_cpu,
)
from core.inference.stt_ggml_sidecar import _pcm_to_wav_bytes
from core.inference.stt_sidecar import (
@@ -554,6 +555,18 @@ def _launches_on_cpu(entry: AudioCppModel, force_cpu: bool) -> bool:
return force_cpu or _training_active() or entry.family in CPU_ONLY_FAMILIES
+def _same_placement(on_cpu: bool, entry: AudioCppModel, force_cpu: bool) -> bool:
+ """Whether a server on the CPU (or not) is where a launch now would put ``entry``."""
+ wants_cpu = _launches_on_cpu(entry, force_cpu)
+ if on_cpu == wants_cpu:
+ return True
+ # A GPU build with no visible GPU runs on the CPU either way, so training starting or ending moves nothing.
+ try:
+ return on_cpu and runtime_runs_on_cpu()
+ except Exception: # noqa: BLE001 - an unreadable runtime keeps the old reload
+ return False
+
+
class AudioCppSttSidecar:
"""Owns one audiocpp_server serving an ASR model and proxies dictation to it."""
@@ -846,7 +859,7 @@ class AudioCppSttSidecar:
and self._model == entry
and self._forced_cpu == force_cpu
# A server training moved to the CPU goes back to the GPU once training ends.
- and self._launched_cpu == _launches_on_cpu(entry, force_cpu)
+ and _same_placement(self._launched_cpu, entry, force_cpu)
and (self._aligned or not aligned)
):
self._loaded_as = _reported_name(model, entry)
@@ -895,7 +908,7 @@ class AudioCppSttSidecar:
self._model = entry
self._loaded_as = _reported_name(model, entry)
self._forced_cpu = force_cpu
- self._launched_cpu = run_on_cpu
+ self._launched_cpu = server.backend == "cpu"
self._aligned = aligned
self._schedule_idle_unload_locked()
finally:
diff --git a/studio/backend/core/inference/stt_capabilities.py b/studio/backend/core/inference/stt_capabilities.py
index 240d56ad9a2..c149d07ba45 100644
--- a/studio/backend/core/inference/stt_capabilities.py
+++ b/studio/backend/core/inference/stt_capabilities.py
@@ -124,6 +124,8 @@ def capabilities_for(model: Optional[str], engine: Optional[str]) -> dict:
except Exception: # noqa: BLE001 - not in the cache
aligner = None
result["aligner"] = {
+ "id": QWEN3_ALIGNER.id,
+ "variant": QWEN3_ALIGNER.variant,
"downloaded": aligner is not None and audio_cpp_files.is_downloaded(aligner),
"size_bytes": (aligner and aligner.size_bytes) or _ALIGNER_SIZE_BYTES,
}
diff --git a/studio/backend/hub/services/download_lifecycle.py b/studio/backend/hub/services/download_lifecycle.py
index 3577b95ec5e..b4f71a23d8f 100644
--- a/studio/backend/hub/services/download_lifecycle.py
+++ b/studio/backend/hub/services/download_lifecycle.py
@@ -596,10 +596,24 @@ def finalize_worker_exit(
)
metadata = registry.get_job_metadata(key)
state = classify_exit(rc, cancel_requested = cancel_requested)
+ if repo_type == "model" and state == "complete":
+ # Only on completion: another backend may still be downloading a cancelled key.
+ try:
+ from core.inference.audio_cpp_models import forget_job_row
+ forget_job_row(repo_id, download_registry.variant_from_key(key))
+ except Exception:
+ logger.debug("audio.cpp download row was not pruned", exc_info = True)
if state == "complete":
if repo_id and repo_type:
account_access.record_model_grant(repo_id, repo_type)
hf_cache_scan.invalidate_hf_cache_scans()
+ if repo_type == "model":
+ # audio.cpp remembers a cache miss (the timing aligner) for 20 s; the UI re-reads it on complete.
+ try:
+ from core.inference.audio_cpp_models import forget
+ forget()
+ except Exception:
+ logger.debug("audio.cpp resolve cache was not cleared", exc_info = True)
registry.set_job(key, "complete")
# Where /v1 learns a new model exists: its resolver answers from a cached scan with no watcher, so it would report the model absent and serve whatever is resident. Models only, since noting a dataset id as a local model would refuse a bare request naming it instead of letting a foreign id fall through.
if repo_type == "model":
diff --git a/studio/backend/hub/services/models/downloads.py b/studio/backend/hub/services/models/downloads.py
index 1e756f1df7b..f6bfcc7c276 100644
--- a/studio/backend/hub/services/models/downloads.py
+++ b/studio/backend/hub/services/models/downloads.py
@@ -219,6 +219,7 @@ async def _audio_cpp_target(
repo_id: str,
variant: Optional[str],
hf_token: Optional[str] = None,
+ persist: bool = False,
) -> tuple[str, Optional[str]]:
"""``(repo, variant)`` a download of an audio.cpp umbrella folder row really works on.
@@ -232,7 +233,7 @@ async def _audio_cpp_target(
try:
from core.inference.audio_cpp_models import download_target
target = await asyncio.to_thread(
- download_target, text, (variant or "").strip() or None, hf_token
+ download_target, text, (variant or "").strip() or None, hf_token, persist
)
except Exception as exc: # noqa: BLE001 - an unresolvable row downloads nothing
logger.warning("Could not resolve the audio model %s for download: %s", text, exc)
@@ -261,7 +262,7 @@ async def download_model_response(
allow_ambient_token = allow_ambient_token and not account_access.managed_account()
if body.gguf_variant or not body.scope_id:
target_repo, target_variant = await _audio_cpp_target(
- body.repo_id, body.gguf_variant, hf_token
+ body.repo_id, body.gguf_variant, hf_token, persist = True
)
if target_repo != body.repo_id.strip():
body = body.model_copy(update = {"repo_id": target_repo, "gguf_variant": target_variant})
diff --git a/studio/backend/hub/services/models/gguf_variants.py b/studio/backend/hub/services/models/gguf_variants.py
index 3ab9850cfeb..328fbbcfb63 100644
--- a/studio/backend/hub/services/models/gguf_variants.py
+++ b/studio/backend/hub/services/models/gguf_variants.py
@@ -487,6 +487,26 @@ def variant_remaining_bytes_from_state(
)
+def _audio_cpp_remaining_bytes(
+ repo_id: str, key: str, missing_files: list, missing_companion_bytes: Optional[int]
+) -> Optional[int]:
+ """What resuming an audio.cpp row still fetches. Its whole manifest, not the generic plan, which keeps
+ one GGUF per quant and so drops a package's other components; without a manifest, the missing files."""
+ try:
+ manifest = download_manifest.read_manifest("model", repo_id, key)
+ files = manifest.expected_files if manifest is not None else ()
+ if files:
+ have = download_registry.existing_blob_bytes(
+ "model", repo_id, frozenset(f.sha256 for f in files if f.sha256)
+ )
+ return max(0, sum(max(0, int(f.size or 0)) for f in files) - have)
+ except Exception as e:
+ logger.warning(f"Manifest pricing failed for {repo_id} [{key}]: {e}")
+ if missing_companion_bytes is None:
+ return None
+ return sum(size for _path, size in missing_files) + missing_companion_bytes
+
+
def _partial_transport_for_variant(
repo_id: str,
variant: str,
@@ -1103,12 +1123,65 @@ async def _audio_cpp_variants_answer(
c is not None and audio_cpp_files.cached_files(c) is not None for c in companions
)
companion_bytes = sum(c.variant.size_bytes for c in companions if c is not None)
+ # An unresolved companion (offline, nothing cached) has an unknown size: no remainder then.
+ missing_companion_bytes = (
+ None
+ if any(c is None for c in companions)
+ else sum(
+ c.variant.size_bytes for c in companions if audio_cpp_files.cached_files(c) is None
+ )
+ )
+ try:
+ incomplete = download_registry.incomplete_blob_hashes(
+ "model", model.repo_id, active_only = True
+ )
+ except Exception as e:
+ logger.warning(f"Partial check failed for {model.id}: {e}")
+ incomplete = set()
+ # A file every row lists (a package's configs, a voice folder) says nothing about one row.
+ counts: dict[str, int] = {}
+ for variant in model.variants:
+ for path in {f.path for f in variant.files}:
+ counts[path] = counts.get(path, 0) + 1
rows = []
for variant in model.variants:
- downloaded = (
- companions_cached
- and audio_cpp_files.cached_files(model.with_variant(variant)) is not None
- )
+ row_model = model.with_variant(variant)
+ downloaded = companions_cached and audio_cpp_files.cached_files(row_model) is not None
+ partial = False
+ remaining = None
+ key = variant.key if model.is_package else gguf_variant_key(variant.primary)
+ if not downloaded:
+ missing_files = audio_cpp_files.missing_files(row_model)
+ missing = {path for path, _size in missing_files}
+ own_cached = any(
+ f.path not in missing and counts.get(f.path, 0) == 1 for f in variant.files
+ )
+ try:
+ partial = own_cached or hf_cache_scan.is_variant_partial(
+ model.repo_id,
+ key,
+ incomplete_blob_hashes = incomplete,
+ variant_blob_hashes = gguf_variant_blob_hashes(
+ model.repo_id,
+ key,
+ hf_token,
+ include_companions = False,
+ allow_remote = False,
+ ),
+ )
+ except Exception as e:
+ logger.warning(f"Partial check failed for {model.id} [{variant.key}]: {e}")
+ partial = own_cached
+ if partial:
+ remaining = (
+ None
+ if model.is_package
+ else variant_remaining_bytes_from_state(model.repo_id, key, None)
+ )
+ if remaining is None:
+ remaining = _audio_cpp_remaining_bytes(
+ model.repo_id, key, missing_files, missing_companion_bytes
+ )
rows.append(
GgufVariantDetail(
filename = variant.main_file,
@@ -1116,7 +1189,14 @@ async def _audio_cpp_variants_answer(
display_label = variant.label,
size_bytes = variant.size_bytes,
download_size_bytes = variant.size_bytes + companion_bytes,
+ download_remaining_bytes = remaining,
downloaded = downloaded,
+ partial = partial,
+ partial_transport = (
+ _partial_transport_for_variant(model.repo_id, key) if partial else None
+ ),
+ partial_resumable = partial
+ and _partial_resumable_for_variant(model.repo_id, key),
)
)
return rows
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 5f9ee46e16c..94502953dd4 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -25164,10 +25164,16 @@ def _audio_cpp_runtime_status() -> dict:
record = audio_cpp_server.read_install_record(binary)
backend = record.get("backend")
release_tag = record.get("release_tag")
+ try:
+ launch_backend = audio_cpp_server.select_backend(binary, False)
+ except Exception as exc: # noqa: BLE001 - the build is there even if its launch cannot be told
+ logger.debug("audio.cpp backend selection failed: %s", exc)
+ launch_backend = None
status = {
"available": True,
"espeak": audio_cpp_server.binary_has_espeak(binary),
"backend": backend if isinstance(backend, str) else None,
+ "launch_backend": launch_backend,
"release_tag": release_tag if isinstance(release_tag, str) else None,
"expected_tag": None,
"outdated": False,
@@ -25219,6 +25225,8 @@ async def stt_status(
mtmd = stt_mtmd_sidecar.get_mtmd_stt_sidecar()
audiocpp = stt_audiocpp_sidecar.get_audio_cpp_stt_sidecar()
audiocpp_downloaded = await asyncio.to_thread(stt_audiocpp_sidecar.downloaded_model_ids)
+ # Choosing the launch backend can run the binary's --version.
+ audio_cpp_runtime = await asyncio.to_thread(_audio_cpp_runtime_status)
transformers_downloaded = [
model_id for model_id in STT_MODELS if stt_sidecar.is_model_downloaded(model_id)
]
@@ -25297,7 +25305,7 @@ async def stt_status(
"download": stt_audiocpp_sidecar.download_status(),
},
# The audio.cpp runtime itself, for the Audio page's TTS and music rows.
- "audio_cpp_runtime": _audio_cpp_runtime_status(),
+ "audio_cpp_runtime": audio_cpp_runtime,
}
)
if account_access.managed_account():
diff --git a/studio/backend/tests/test_audio_cpp_models.py b/studio/backend/tests/test_audio_cpp_models.py
index 71355f62ed7..f27d5b0ffe3 100644
--- a/studio/backend/tests/test_audio_cpp_models.py
+++ b/studio/backend/tests/test_audio_cpp_models.py
@@ -956,6 +956,46 @@ def test_miotts_downloads_its_codec_with_every_variant():
assert kokoro.target_filenames == (names[4],)
+def test_every_umbrella_row_downloads_what_it_lists_and_what_it_prices(hub, monkeypatch):
+ from hub.utils.gguf import gguf_variant_key
+ from hub.utils.gguf_plan import build_gguf_variant_plans, plan_for_variant
+
+ names = [
+ "Kokoro-82M-GGUF/kokoro-82m-q8_0.gguf",
+ "Kokoro-82M-GGUF/README.md",
+ "PocketTTS-GGUF/english/pocket-tts-english-q8_0.gguf",
+ "PocketTTS-GGUF/english/pocket-tts-english-bf16.gguf",
+ "PocketTTS-GGUF/english/embeddings/alba.safetensors",
+ "PocketTTS-GGUF/english/embeddings/anna.safetensors",
+ "PocketTTS-GGUF/german/pocket-tts-german-q8_0.gguf",
+ "PocketTTS-GGUF/german/embeddings/karl.safetensors",
+ "MioTTS-1.7B-GGUF/miotts-1.7b-q8_0.gguf",
+ "MioTTS-1.7B-GGUF/miotts-1.7b-bf16.gguf",
+ MIOCODEC_Q8,
+ "MioCodec-25Hz-44.1kHz-v2-GGUF/miocodec-25hz-44khz-v2-f16.gguf",
+ *(f"Moonshine-Streaming-GGUF/{n}" for n in CROWDED_FOLDERS["Moonshine-Streaming-GGUF"]),
+ ]
+ _online(monkeypatch, *names, size = 5)
+ plans = build_gguf_variant_plans(
+ [SimpleNamespace(rfilename = n, size = 5, lfs = {"sha256": n}) for n in names]
+ )
+ for folder in (
+ "Kokoro-82M-GGUF",
+ "PocketTTS-GGUF",
+ "MioTTS-1.7B-GGUF",
+ "Moonshine-Streaming-GGUF",
+ ):
+ rows = _rows(f"{AUDIO_CPP_REPO}/{folder}")
+ model = acm.resolve(f"{AUDIO_CPP_REPO}/{folder}", network = True)
+ companions = [acm.resolve(c.id, c.variant, network = True) for c in model.companions]
+ companion_files = {f.path for c in companions for f in c.variant.files}
+ for variant in model.variants:
+ plan = plan_for_variant(plans, gguf_variant_key(variant.primary))
+ need = {f.path for f in variant.files} | companion_files
+ assert need <= set(plan.target_filenames), variant.key
+ assert plan.download_size_bytes == rows[variant.key].download_size_bytes, variant.key
+
+
def test_miotts_lists_as_downloaded_only_with_its_codec(hub):
from hub.services.models import gguf_variants as gv
@@ -971,12 +1011,162 @@ def test_miotts_lists_as_downloaded_only_with_its_codec(hub):
row = answer()
assert row.quant == "Q8_0" and not row.downloaded
+ # The model file without its codec is a download to finish or remove, not a fresh row.
+ assert row.partial
codec = _put(snap, MIOCODEC_Q8, _gguf_bytes(family = "miocodec"))
row = answer()
- assert row.downloaded
+ assert row.downloaded and not row.partial
assert row.download_size_bytes == row.size_bytes + codec.stat().st_size
+def _online(
+ monkeypatch,
+ *published,
+ size = 7,
+):
+ """The Hub listing: what the cache holds plus ``published`` names not downloaded yet."""
+ monkeypatch.setenv("HF_HUB_OFFLINE", "0")
+ monkeypatch.setattr(acm, "_listing_cache", {})
+ monkeypatch.setattr(acm, "_probe_header", lambda *a, **k: None)
+ calls = []
+
+ def listing(repo_id, folder, token):
+ calls.append((repo_id, folder))
+ files = {f.path: f for f in acm._cached_listing(repo_id, folder)}
+ for name in published:
+ if name.startswith(f"{folder}/" if folder else "") and name not in files:
+ files[name] = RepoFile(name, size)
+ return sorted(files.values(), key = lambda f: f.path)
+
+ monkeypatch.setattr(acm, "_hub_listing", listing)
+ return calls
+
+
+def _cancelled(
+ hub,
+ repo,
+ key,
+ paths,
+ size = 7,
+):
+ """A cancelled download of ``key``: its manifest, marker and ``.incomplete`` blobs, nothing linked."""
+ import hashlib
+
+ from hub.utils import download_manifest
+ from hub.utils.download_manifest import ExpectedFile
+
+ blobs = hub / ("models--" + repo.replace("/", "--")) / "blobs"
+ blobs.mkdir(parents = True, exist_ok = True)
+ expected = []
+ for path in paths:
+ sha = hashlib.sha256(path.encode()).hexdigest()
+ (blobs / f"{sha}.incomplete").write_bytes(b"x" * 3)
+ expected.append(ExpectedFile(path = path, size = size, sha256 = sha))
+ assert download_manifest.write_manifest("model", repo, key, expected, "http")
+ download_manifest.write_cancel_marker("model", repo, key, "http")
+
+
+def _rows(repo_id, offline = False):
+ from hub.services.models import gguf_variants as gv
+
+ acm.forget()
+ result = asyncio.run(gv._audio_cpp_variants_answer(repo_id, None, offline))
+ return {row.quant: row for row in result.response.variants}
+
+
+def test_a_cancelled_umbrella_quant_lists_as_partial_and_its_siblings_do_not(hub, monkeypatch):
+ monkeypatch.setenv("HF_HUB_CACHE", str(hub))
+ folder = "Samsone-GGUF"
+ names = [
+ f"{folder}/samsone-{s}-{q}.gguf" for s in ("99m", "134m", "356m") for q in ("q8_0", "bf16")
+ ]
+ _online(monkeypatch, *names)
+ _put(_snapshot(hub), names[0], _gguf_bytes(family = "samsone"))
+ key = f"{folder}/samsone-356m-bf16"
+ _cancelled(hub, AUDIO_CPP_REPO, key, [f"{key}.gguf"])
+ rows = _rows(f"{AUDIO_CPP_REPO}/{folder}")
+ assert sorted(rows) == sorted(
+ ["99m/Q8_0", "99m/BF16", "134m/Q8_0", "134m/BF16", "356m/Q8_0", "356m/BF16"]
+ )
+ cancelled = rows["356m/BF16"]
+ assert cancelled.partial and not cancelled.downloaded
+ assert cancelled.partial_transport == "http"
+ assert cancelled.download_remaining_bytes is not None
+ assert rows["99m/Q8_0"].downloaded and not rows["99m/Q8_0"].partial
+ assert not any(rows[k].partial for k in ("99m/BF16", "134m/Q8_0", "134m/BF16", "356m/Q8_0"))
+ assert not any(rows[k].partial_transport for k in rows if k != "356m/BF16")
+
+
+def test_miotts_rows_are_partial_only_for_the_variant_whose_codec_is_missing(hub, monkeypatch):
+ monkeypatch.setenv("HF_HUB_CACHE", str(hub))
+ _online(
+ monkeypatch,
+ "MioTTS-1.7B-GGUF/miotts-1.7b-q8_0.gguf",
+ "MioTTS-1.7B-GGUF/miotts-1.7b-bf16.gguf",
+ MIOCODEC_Q8,
+ )
+ snap = _snapshot(hub)
+ _put(snap, "MioTTS-1.7B-GGUF/miotts-1.7b-q8_0.gguf", _gguf_bytes(family = "miotts"))
+ rows = _rows(f"{AUDIO_CPP_REPO}/MioTTS-1.7B-GGUF")
+ assert rows["Q8_0"].partial and not rows["Q8_0"].downloaded
+ assert not rows["BF16"].partial
+ # No download state: priced from the missing codec, not the whole checkpoint.
+ assert rows["Q8_0"].download_remaining_bytes == 7
+ # Offline the codec cannot be resolved: its size is unknown, so no remainder rather than 0.
+ offline = _rows(f"{AUDIO_CPP_REPO}/MioTTS-1.7B-GGUF", offline = True)
+ assert offline["Q8_0"].partial
+ assert offline["Q8_0"].download_remaining_bytes != 0
+ _put(snap, MIOCODEC_Q8, b"x" * 7)
+ rows = _rows(f"{AUDIO_CPP_REPO}/MioTTS-1.7B-GGUF")
+ assert rows["Q8_0"].downloaded and not rows["Q8_0"].partial
+ # The shared codec on disk does not make a variant nobody started partial.
+ assert not rows["BF16"].partial and not rows["BF16"].downloaded
+
+
+def test_a_package_mix_with_some_of_its_files_lists_as_partial(hub, monkeypatch):
+ monkeypatch.setenv("HF_HUB_CACHE", str(hub))
+ repo = "audio-cpp/MiniMax-Music3-GGUF"
+ q8 = ("language_model_q8_0.gguf", "transformer_q8_0.gguf")
+ bf16 = ("language_model_bf16.gguf", "rvq_depth_decoder_bf16.gguf", "transformer_bf16.gguf")
+ _online(monkeypatch, *q8, *bf16)
+ snap = _minimax(hub)
+ rows = _rows(repo)
+ assert rows["Q4_0"].downloaded and not rows["Q4_0"].partial
+ # Configs and shared components on disk name no one mix.
+ assert not rows["Q8_0"].partial and not rows["BF16"].partial
+ _put(snap, q8[0], b"x" * 7)
+ _cancelled(hub, repo, "BF16", list(bf16))
+ rows = _rows(repo)
+ assert rows["Q8_0"].partial and not rows["Q8_0"].downloaded
+ assert rows["BF16"].partial and rows["BF16"].partial_transport == "http"
+ assert rows["Q4_0"].downloaded and not rows["Q4_0"].partial
+
+
+def test_a_partial_package_mix_prices_every_missing_component(hub, monkeypatch):
+ import hashlib
+
+ from utils import hf_cache_settings
+
+ monkeypatch.setenv("HF_HUB_CACHE", str(hub))
+ paths = hf_cache_settings.HuggingFaceCachePaths(hub.parent, hub, hub.parent / "xet", "studio")
+ monkeypatch.setattr(hf_cache_settings, "get_hf_cache_paths", lambda: paths)
+ repo = "audio-cpp/MiniMax-Music3-GGUF"
+ bf16 = ("language_model_bf16.gguf", "rvq_depth_decoder_bf16.gguf", "transformer_bf16.gguf")
+ _online(monkeypatch, *bf16)
+ snap = _minimax(hub)
+ _cancelled(hub, repo, "BF16", list(bf16))
+ # The language model finished; the other two components hold 3-byte resumable partials.
+ blobs = hub / ("models--" + repo.replace("/", "--")) / "blobs"
+ sha = hashlib.sha256(bf16[0].encode()).hexdigest()
+ (blobs / f"{sha}.incomplete").unlink()
+ (blobs / sha).write_bytes(b"x" * 7)
+ _put(snap, bf16[0], b"x" * 7)
+ row = _rows(repo)["BF16"]
+ assert row.partial and not row.downloaded
+ # Every component counts, and bytes a resume reuses are credited: 21 - 7 - 3 - 3.
+ assert row.download_remaining_bytes == 8
+
+
def test_download_target_maps_a_folder_row_onto_the_planner_key(hub):
_kokoro(hub)
assert acm.download_target(f"{AUDIO_CPP_REPO}/Kokoro-82M-GGUF", "Q8_0") == (
@@ -1882,6 +2072,325 @@ def test_umbrella_download_jobs_report_under_their_folder_row(hub):
assert acm.folder_row_for_download("audio-cpp/Yue2-3B-GGUF", "q8_0") is None
+CROWDED_FOLDERS = {
+ "Moonshine-Streaming-GGUF": tuple(
+ f"moonshine-streaming-{size}-q8_0.gguf" for size in ("tiny", "small", "medium")
+ ),
+ "Samsone-GGUF": tuple(
+ f"samsone-{size}-{quant}.gguf"
+ for size in ("99m", "134m", "356m")
+ for quant in ("q8_0", "bf16")
+ ),
+ "Niagara-ASR-GGUF": ("niagara-19m-batch.en-f32.gguf", "niagara-38m-batch.en-f32.gguf"),
+ "PulseVAD-GGUF": ("pulsevad-2.1k-f32.gguf", "pulsevad-81k-f32.gguf"),
+ "UniverSR-GGUF": ("universr-audio-orig.gguf", "universr-speech-orig.gguf"),
+ "Irodori-TTS-v4-Small-GGUF": (
+ "irodori-tts-v4-small-f16.gguf",
+ "irodori-tts-v4-small-q8_0.gguf",
+ "irodori-tts-v4.1-anime-q8_0.gguf",
+ ),
+}
+
+
[email protected](autouse = True)
+def _no_started_jobs(monkeypatch):
+ monkeypatch.setattr(acm, "_job_rows", {})
+
+
[email protected]("folder", sorted(CROWDED_FOLDERS))
+def test_an_umbrella_job_in_flight_reports_its_own_row_in_a_crowded_folder(
+ hub, monkeypatch, folder
+):
+ from hub.utils.gguf import gguf_variant_key
+
+ # Nothing of the folder is cached yet: the file in flight is only an .incomplete blob.
+ _online(monkeypatch, *(f"{folder}/{name}" for name in CROWDED_FOLDERS[folder]))
+ row = f"{AUDIO_CPP_REPO}/{folder}"
+ rows = _rows(row)
+ assert len(rows) == len(CROWDED_FOLDERS[folder])
+ for quant, listed in rows.items():
+ target = acm.download_target(row, quant)
+ assert target == (AUDIO_CPP_REPO, gguf_variant_key(listed.filename))
+ assert acm.folder_row_for_download(*target) == (row, quant)
+
+
+def test_a_bare_quant_start_records_the_row_key_it_resolved_to(hub, monkeypatch):
+ folder = "Moonshine-Streaming-GGUF"
+ _online(monkeypatch, *(f"{folder}/{name}" for name in CROWDED_FOLDERS[folder]))
+ row = f"{AUDIO_CPP_REPO}/{folder}"
+ target = acm.download_target(row, "Q8_0")
+ assert target == (AUDIO_CPP_REPO, f"{folder}/moonshine-streaming-tiny-q8_0")
+ assert acm.folder_row_for_download(*target) == (row, "tiny/Q8_0")
+
+
+def test_a_started_job_reports_its_row_without_touching_the_hub(hub, monkeypatch):
+ folder = "Moonshine-Streaming-GGUF"
+ _online(monkeypatch, *(f"{folder}/{name}" for name in CROWDED_FOLDERS[folder]))
+ row = f"{AUDIO_CPP_REPO}/{folder}"
+ target = acm.download_target(row, "small/Q8_0")
+ calls = []
+
+ def refused(*args, **_kw):
+ calls.append(args)
+ raise OSError("Hub unreachable")
+
+ monkeypatch.setattr(acm, "_hub_listing", refused)
+ monkeypatch.setattr(acm, "_probe_header", refused)
+ monkeypatch.setattr(acm, "_listing_cache", {})
+ acm.forget()
+ assert acm.folder_row_for_download(*target) == (row, "small/Q8_0")
+ assert acm.folder_row_for_download(AUDIO_CPP_REPO, target[1].upper()) == (row, "small/Q8_0")
+ assert calls == []
+
+
+def _restarted_offline(monkeypatch):
+ """A new backend process: no in-memory records, no Hub, nothing of the folder cached."""
+
+ def refused(*_args, **_kw):
+ raise OSError("Hub unreachable")
+
+ monkeypatch.setattr(acm, "_job_rows", {})
+ monkeypatch.setattr(acm, "_hub_listing", refused)
+ monkeypatch.setattr(acm, "_listing_cache", {})
+ acm.forget()
+
+
[email protected]("folder", sorted(CROWDED_FOLDERS))
+def test_a_restarted_backend_still_names_a_crowded_folder_job_by_row(hub, monkeypatch, folder):
+ _online(monkeypatch, *(f"{folder}/{name}" for name in CROWDED_FOLDERS[folder]))
+ row = f"{AUDIO_CPP_REPO}/{folder}"
+ targets = {quant: acm.download_target(row, quant) for quant in _rows(row)}
+ _restarted_offline(monkeypatch)
+ for quant, target in targets.items():
+ assert acm.folder_row_for_download(*target) == (row, quant)
+
+
+def test_a_damaged_saved_record_falls_back_to_the_path(hub, monkeypatch):
+ folder = "Moonshine-Streaming-GGUF"
+ key = f"{folder}/moonshine-streaming-small-q8_0"
+ row = f"{AUDIO_CPP_REPO}/{folder}"
+ path = acm._job_row_path(key, create = True)
+ for text in (
+ "{not json",
+ "[]",
+ json.dumps({key: [row, "small/Q8_0"]}),
+ json.dumps([f"{folder}/moonshine-streaming-tiny-q8_0", row, "small/Q8_0"]),
+ json.dumps([key, f"{AUDIO_CPP_REPO}/Kokoro-82M-GGUF", "small/Q8_0"]),
+ json.dumps([key, row, ""]),
+ "[" * 100_000,
+ ):
+ path.write_text(text, encoding = "utf-8")
+ _restarted_offline(monkeypatch)
+ assert acm.folder_row_for_download(AUDIO_CPP_REPO, key) == (row, "Q8_0")
+
+
+def test_backends_saving_rows_at_once_keep_each_others(hub, monkeypatch):
+ # Each record is its own file: a writer never rewrites a map another backend just changed.
+ folder = "Samsone-GGUF"
+ _online(monkeypatch, *(f"{folder}/{name}" for name in CROWDED_FOLDERS[folder]))
+ row = f"{AUDIO_CPP_REPO}/{folder}"
+ quants = sorted(_rows(row))
+ real = acm._saved_job_row
+ stale = {}
+
+ def read_before_any_write(key):
+ # Every writer looks before any other has saved, as two processes racing would.
+ return stale.setdefault(key.lower(), real(key))
+
+ monkeypatch.setattr(acm, "_saved_job_row", read_before_any_write)
+ targets = {quant: acm.download_target(row, quant) for quant in quants}
+ monkeypatch.setattr(acm, "_saved_job_row", real)
+ _restarted_offline(monkeypatch)
+ for quant, target in targets.items():
+ assert acm._saved_job_row(target[1]) == (row, quant)
+ assert acm.folder_row_for_download(*target) == (row, quant)
+
+
+def test_only_a_finished_job_drops_its_saved_record(hub, monkeypatch):
+ import logging
+
+ from core.inference import local_model_resolver
+ from hub.services import download_lifecycle
+
+ folder = "Moonshine-Streaming-GGUF"
+ _online(monkeypatch, *(f"{folder}/{name}" for name in CROWDED_FOLDERS[folder]))
+ row = f"{AUDIO_CPP_REPO}/{folder}"
+ small = acm.download_target(row, "small/Q8_0")
+ tiny = acm.download_target(row, "tiny/Q8_0")
+ assert acm._saved_job_row(small[1]) == (row, "small/Q8_0")
+ assert acm._saved_job_row(tiny[1]) == (row, "tiny/Q8_0")
+ monkeypatch.setattr(local_model_resolver, "note_downloaded", lambda *a: None)
+ monkeypatch.setattr(local_model_resolver, "invalidate_index", lambda **k: None)
+ monkeypatch.setattr(local_model_resolver, "warm_index_soon", lambda: None)
+ monkeypatch.setattr(download_lifecycle.account_access, "record_model_grant", lambda *a: None)
+ monkeypatch.setattr(
+ download_lifecycle.download_manifest, "clear_cancel_marker", lambda *a, **k: None
+ )
+
+ def end(key, rc, cancelled):
+ registry = SimpleNamespace(
+ cancel_requested = lambda _key: cancelled,
+ drop_process = lambda *a: True,
+ get_job_metadata = lambda _key: None,
+ set_job = lambda *a: None,
+ update_job_transport = lambda *a: None,
+ )
+ return download_lifecycle.finalize_worker_exit(
+ registry,
+ f"{AUDIO_CPP_REPO}::{key}",
+ SimpleNamespace(stderr = io.BytesIO(), wait = lambda: rc),
+ hf_token = None,
+ label = AUDIO_CPP_REPO,
+ log_prefix = "Download",
+ logger = logging.getLogger(__name__),
+ repo_type = "model",
+ repo_id = AUDIO_CPP_REPO,
+ )
+
+ # Still right, and another backend may be downloading the same key.
+ assert end(small[1], 1, True) != "complete"
+ assert end(small[1], 1, False) != "complete"
+ assert acm._saved_job_row(small[1]) == (row, "small/Q8_0")
+ assert end(tiny[1], 0, False) == "complete"
+ assert acm._saved_job_row(tiny[1]) is None
+ assert acm._saved_job_row(small[1]) == (row, "small/Q8_0")
+ # The status poll that learns of the completion resolves the target again: it must not save it back.
+ from hub.services.models import downloads
+
+ assert asyncio.run(downloads._audio_cpp_target(row, "tiny/Q8_0")) == tiny
+ assert acm._saved_job_row(tiny[1]) is None
+ # This process keeps its own copy, and a new download of the key records it again.
+ assert acm.folder_row_for_download(*tiny) == (row, "tiny/Q8_0")
+ acm.download_target(row, "tiny/Q8_0")
+ assert acm._saved_job_row(tiny[1]) == (row, "tiny/Q8_0")
+
+
+def test_folder_rows_without_crowding_keep_their_keys(hub, monkeypatch):
+ _online(
+ monkeypatch,
+ "Kokoro-82M-GGUF/kokoro-82m-q8_0.gguf",
+ "PocketTTS-GGUF/english/pocket-tts-english-q8_0.gguf",
+ "PocketTTS-GGUF/english/pocket-tts-english-bf16.gguf",
+ "PocketTTS-GGUF/english/embeddings/alba.safetensors",
+ )
+ for row, quant in (("Kokoro-82M-GGUF", "Q8_0"), ("PocketTTS-GGUF", "english/Q8_0")):
+ row = f"{AUDIO_CPP_REPO}/{row}"
+ target = acm.download_target(row, quant)
+ assert acm.folder_row_for_download(*target) == (row, quant)
+
+
+def test_an_unrecorded_job_falls_back_to_the_cache_then_the_planner_path(hub, monkeypatch):
+ # A job this process did not start (a restart mid-download) is named the way it was before.
+ calls = _online(monkeypatch)
+ small = "Moonshine-Streaming-GGUF/moonshine-streaming-small-q8_0"
+ pocket = "PocketTTS-GGUF/english/pocket-tts-english-q8_0"
+ moonshine = f"{AUDIO_CPP_REPO}/Moonshine-Streaming-GGUF"
+ for offline in ("1", "0"):
+ monkeypatch.setenv("HF_HUB_OFFLINE", offline)
+ acm.forget()
+ assert acm.folder_row_for_download(AUDIO_CPP_REPO, pocket) == (
+ f"{AUDIO_CPP_REPO}/PocketTTS-GGUF",
+ "english/Q8_0",
+ )
+ # Without the folder's listing the size word is unknown: the path names only the quant.
+ assert acm.folder_row_for_download(AUDIO_CPP_REPO, small) == (moonshine, "Q8_0")
+ assert calls == []
+ snap = _snapshot(hub)
+ moon = _gguf_bytes(family = "moonshine_asr")
+ _put(snap, "Moonshine-Streaming-GGUF/moonshine-streaming-tiny-q8_0.gguf", moon)
+ _put(snap, f"{small}.gguf", moon)
+ acm.forget()
+ assert acm.folder_row_for_download(AUDIO_CPP_REPO, small) == (moonshine, "small/Q8_0")
+ assert calls == []
+
+
+def test_an_offline_status_read_does_not_rename_a_started_job(hub, monkeypatch):
+ # Status polls also go through download_target; offline, a lone cached tiny lists as bare Q8_0.
+ snap = _snapshot(hub)
+ moon = _gguf_bytes(family = "moonshine_asr")
+ _put(snap, "Moonshine-Streaming-GGUF/moonshine-streaming-tiny-q8_0.gguf", moon)
+ monkeypatch.setenv("HF_HUB_OFFLINE", "1")
+ acm.forget()
+ target = acm.download_target(f"{AUDIO_CPP_REPO}/Moonshine-Streaming-GGUF", "Q8_0")
+ assert target is not None
+ assert acm._job_rows == {}
+
+
+def test_a_failed_hub_listing_does_not_record_a_cached_guess(hub, monkeypatch):
+ # Online, but the listing call fails: resolve falls back to the cache, where only tiny is.
+ snap = _snapshot(hub)
+ moon = _gguf_bytes(family = "moonshine_asr")
+ _put(snap, "Moonshine-Streaming-GGUF/moonshine-streaming-tiny-q8_0.gguf", moon)
+ monkeypatch.setenv("HF_HUB_OFFLINE", "0")
+ monkeypatch.setattr(acm, "_listing_cache", {})
+
+ def refused(*_args, **_kw):
+ raise OSError("Hub unreachable")
+
+ monkeypatch.setattr(acm, "_hub_listing", refused)
+ acm.forget()
+ row = f"{AUDIO_CPP_REPO}/Moonshine-Streaming-GGUF"
+ assert acm.resolve(row, "small/Q8_0").from_hub is False
+ acm.download_target(row, "small/Q8_0")
+ assert acm._job_rows == {}
+
+
+def test_a_folder_of_an_unknown_family_still_records_its_row(hub, monkeypatch):
+ _online(monkeypatch, "Mystery-GGUF/mystery-q8_0.gguf")
+ row = f"{AUDIO_CPP_REPO}/Mystery-GGUF"
+ assert acm.resolve(row, "Q8_0").unsupported
+ target = acm.download_target(row, "Q8_0")
+ assert target == (AUDIO_CPP_REPO, "Mystery-GGUF/mystery-q8_0")
+ assert acm._job_rows == {(AUDIO_CPP_REPO.lower(), "mystery-gguf/mystery-q8_0"): (row, "Q8_0")}
+
+
+def test_a_finished_download_clears_a_remembered_cache_miss(hub, monkeypatch):
+ import logging
+
+ from hub.services import download_lifecycle
+
+ # The aligner's capabilities read is cache-only and remembers a miss; its download ends in between.
+ monkeypatch.setenv("HF_HUB_OFFLINE", "1")
+ row = f"{AUDIO_CPP_REPO}/Qwen3-ForcedAligner-0.6B-GGUF"
+ acm.forget()
+ assert acm.resolve(row, "Q8_0", network = False) is None
+ _put(
+ _snapshot(hub),
+ "Qwen3-ForcedAligner-0.6B-GGUF/qwen3-forcedaligner-0.6b-q8_0.gguf",
+ _gguf_bytes(family = "qwen3_asr"),
+ )
+ assert acm.resolve(row, "Q8_0", network = False) is None
+ from core.inference import local_model_resolver
+
+ monkeypatch.setattr(local_model_resolver, "note_downloaded", lambda *a: None)
+ monkeypatch.setattr(local_model_resolver, "invalidate_index", lambda **k: None)
+ monkeypatch.setattr(local_model_resolver, "warm_index_soon", lambda: None)
+ monkeypatch.setattr(download_lifecycle.account_access, "record_model_grant", lambda *a: None)
+ monkeypatch.setattr(
+ download_lifecycle.download_manifest, "clear_cancel_marker", lambda *a, **k: None
+ )
+ registry = SimpleNamespace(
+ cancel_requested = lambda key: False,
+ drop_process = lambda *a: True,
+ get_job_metadata = lambda key: None,
+ set_job = lambda *a: None,
+ update_job_transport = lambda *a: None,
+ )
+ state = download_lifecycle.finalize_worker_exit(
+ registry,
+ f"{AUDIO_CPP_REPO}::",
+ SimpleNamespace(stderr = io.BytesIO(), wait = lambda: 0),
+ hf_token = None,
+ label = AUDIO_CPP_REPO,
+ log_prefix = "Download",
+ logger = logging.getLogger(__name__),
+ repo_type = "model",
+ repo_id = AUDIO_CPP_REPO,
+ )
+ assert state == "complete"
+ assert acm.resolve(row, "Q8_0", network = False) is not None
+
+
def test_active_downloads_name_umbrella_jobs_by_row(hub, monkeypatch):
import asyncio
@@ -1907,6 +2416,24 @@ def test_active_downloads_name_umbrella_jobs_by_row(hub, monkeypatch):
assert [r.repo_id for r in only.downloads] == [f"{AUDIO_CPP_REPO}/Kokoro-82M-GGUF"]
+def test_active_downloads_name_a_first_moonshine_download_by_its_row(hub, monkeypatch):
+ from hub.schemas.downloads import ActiveDownload
+ from hub.services.models import downloads
+
+ folder = "Moonshine-Streaming-GGUF"
+ _online(monkeypatch, *(f"{folder}/{name}" for name in CROWDED_FOLDERS[folder]))
+ repo, key = acm.download_target(f"{AUDIO_CPP_REPO}/{folder}", "small/Q8_0")
+ job = ActiveDownload.model_construct(repo_id = repo, variant = key, state = "downloading")
+ monkeypatch.setattr(downloads.download_lifecycle, "active_download_refs", lambda *a, **k: [job])
+ monkeypatch.setattr(
+ downloads, "resolve_cached_repo_id_case", lambda repo_id, repo_type: repo_id
+ )
+ rows = asyncio.run(downloads.get_active_downloads_response(f"{AUDIO_CPP_REPO}/{folder}"))
+ assert [(r.repo_id, r.variant) for r in rows.downloads] == [
+ (f"{AUDIO_CPP_REPO}/{folder}", "small/Q8_0")
+ ]
+
+
def test_stt_requests_carry_their_variant_in_the_model_id():
from models.inference import SttLoadRequest
@@ -2145,8 +2672,8 @@ def test_a_variantless_stt_id_keeps_the_loaded_variant_and_an_explicit_one_switc
started = []
class _Server:
- def __init__(self, model):
- self.model, self.backend = model, "cpu"
+ def __init__(self, model, backend):
+ self.model, self.backend = model, backend
def alive(self):
return True
@@ -2156,7 +2683,7 @@ def test_a_variantless_stt_id_keeps_the_loaded_variant_and_an_explicit_one_switc
def start(model, path, **kwargs):
started.append(model.variant.key)
- return _Server(model)
+ return _Server(model, "cpu" if kwargs.get("force_cpu") else "cuda")
monkeypatch.setattr(s, "ensure_engine_available", lambda: "audiocpp_server")
monkeypatch.setattr(s.AudioCppServer, "start", start)
diff --git a/studio/backend/tests/test_audio_cpp_runtime_status.py b/studio/backend/tests/test_audio_cpp_runtime_status.py
index 89e4ea01cc8..8fec928e4ec 100644
--- a/studio/backend/tests/test_audio_cpp_runtime_status.py
+++ b/studio/backend/tests/test_audio_cpp_runtime_status.py
@@ -19,10 +19,15 @@ def _patch(
binary,
record = None,
espeak = False,
+ vendors = None,
):
monkeypatch.setattr(audio_cpp_server, "find_audio_cpp_server_binary", lambda: binary)
monkeypatch.setattr(audio_cpp_server, "read_install_record", lambda _binary: record or {})
monkeypatch.setattr(audio_cpp_server, "binary_has_espeak", lambda _binary: espeak)
+ # The launch backend must not depend on this host's GPUs or a CPU-only build's --version probe.
+ monkeypatch.delenv("UNSLOTH_AUDIO_CPP_BACKEND", raising = False)
+ monkeypatch.setattr(audio_cpp_server, "_gpu_vendors", lambda: vendors)
+ monkeypatch.setattr(audio_cpp_server, "compiled_backends", lambda _binary: frozenset({"cpu"}))
def test_runtime_available_with_espeak(monkeypatch):
@@ -36,6 +41,7 @@ def test_runtime_available_with_espeak(monkeypatch):
"available": True,
"espeak": True,
"backend": "cuda",
+ "launch_backend": "cuda",
"release_tag": "v0.4.0",
"expected_tag": None,
"outdated": False,
@@ -49,6 +55,7 @@ def test_runtime_available_without_espeak(monkeypatch):
"available": True,
"espeak": False,
"backend": None,
+ "launch_backend": "cpu",
"release_tag": None,
"expected_tag": None,
"outdated": False,
@@ -67,6 +74,30 @@ def test_runtime_missing(monkeypatch):
}
+def test_cuda_build_with_no_visible_gpu_launches_on_cpu(monkeypatch):
+ # CUDA_VISIBLE_DEVICES="" hides every GPU: the build still says cuda, the launch goes to the CPU.
+ _patch(
+ monkeypatch,
+ binary = "/opt/audio.cpp/audiocpp_server",
+ record = {"backend": "cuda", "release_tag": "v0.4.0"},
+ vendors = set(),
+ )
+ status = inference._audio_cpp_runtime_status()
+ assert status["backend"] == "cuda"
+ assert status["launch_backend"] == "cpu"
+
+
+def test_launch_backend_error_keeps_the_runtime_available(monkeypatch):
+ _patch(monkeypatch, binary = "/opt/audio.cpp/audiocpp_server", record = {"backend": "cuda"})
+
+ def boom(_binary, _force_cpu):
+ raise RuntimeError("symlink loop")
+
+ monkeypatch.setattr(audio_cpp_server, "select_backend", boom)
+ status = inference._audio_cpp_runtime_status()
+ assert status["available"] is True and status["launch_backend"] is None
+
+
def test_runtime_probe_error_reports_unavailable(monkeypatch):
def boom():
raise OSError("permission denied")
@@ -251,7 +282,25 @@ def test_stt_status_payload_includes_runtime_block(monkeypatch):
"available": True,
"espeak": False,
"backend": "vulkan",
+ "launch_backend": "vulkan",
"release_tag": "v0.4.0",
"expected_tag": None,
"outdated": False,
}
+
+
+def test_stt_status_reads_the_runtime_off_the_event_loop(monkeypatch):
+ import threading
+
+ # A custom build's backend probe runs its --version, which must not stall other requests.
+ seen = []
+
+ def runtime_status():
+ seen.append(threading.current_thread() is threading.main_thread())
+ return {"available": False}
+
+ monkeypatch.setattr(inference, "_audio_cpp_runtime_status", runtime_status)
+ monkeypatch.setattr(inference.account_access, "managed_account", lambda: False)
+ response = asyncio.run(inference.stt_status(model = None, current_subject = "owner"))
+ assert json.loads(response.body)["audio_cpp_runtime"] == {"available": False}
+ assert seen == [False]
diff --git a/studio/backend/tests/test_audio_cpp_server_http.py b/studio/backend/tests/test_audio_cpp_server_http.py
index d8040cd49d3..95c7f77d4f4 100644
--- a/studio/backend/tests/test_audio_cpp_server_http.py
+++ b/studio/backend/tests/test_audio_cpp_server_http.py
@@ -268,6 +268,7 @@ def test_a_custom_build_launches_on_a_backend_it_was_compiled_with(tmp_path, mon
monkeypatch.setattr(
srv.shutil, "which", lambda name: "/usr/bin/nvidia-smi" if name == "nvidia-smi" else None
)
+ monkeypatch.setattr(srv, "_gpu_vendors", lambda: {"nvidia"})
def build(name, backends):
binary = tmp_path / name / "audiocpp_server"
@@ -283,6 +284,154 @@ def test_a_custom_build_launches_on_a_backend_it_was_compiled_with(tmp_path, mon
assert srv.select_backend(build("silent", ""), False) == "cuda"
+def _recorded_build(tmp_path, backend):
+ binary = tmp_path / backend / srv.BINARY_NAME
+ binary.parent.mkdir()
+ binary.write_bytes(b"")
+ (binary.parent / srv.INSTALL_RECORD).write_text(json.dumps({"backend": backend}))
+ return str(binary)
+
+
+ "backend, vendors, expected",
+ [
+ # CUDA_VISIBLE_DEVICES="" or a container without the NVIDIA device nodes.
+ ("cuda", set(), "cpu"),
+ ("cuda", {"nvidia"}, "cuda"),
+ # Nothing detected at all: an unknown host keeps the build's backend.
+ ("cuda", None, "cuda"),
+ ("hip", {"nvidia"}, "cpu"),
+ ("hip", {"amd"}, "hip"),
+ ("vulkan", set(), "vulkan"),
+ ("metal", {"apple"}, "metal"),
+ ],
+)
+def test_a_gpu_build_launches_on_cpu_when_its_gpu_is_not_visible(
+ tmp_path, monkeypatch, backend, vendors, expected
+):
+ monkeypatch.delenv("UNSLOTH_AUDIO_CPP_BACKEND", raising = False)
+ monkeypatch.setattr(srv, "_gpu_vendors", lambda: vendors)
+ assert srv.select_backend(_recorded_build(tmp_path, backend), False) == expected
+
+
+def test_an_explicit_backend_or_cpu_request_is_not_second_guessed(tmp_path, monkeypatch):
+ monkeypatch.setattr(srv, "_gpu_vendors", lambda: set())
+ binary = _recorded_build(tmp_path, "cuda")
+ monkeypatch.setenv("UNSLOTH_AUDIO_CPP_BACKEND", "CUDA")
+ assert srv.select_backend(binary, False) == "cuda"
+ assert srv.select_backend(binary, True) == "cpu"
+ monkeypatch.setattr(srv, "_gpu_vendors", lambda: {"nvidia"})
+ monkeypatch.delenv("UNSLOTH_AUDIO_CPP_BACKEND")
+ assert srv.select_backend(binary, True) == "cpu"
+
+
+def test_nvidia_smi_on_path_is_not_a_visible_gpu(tmp_path, monkeypatch):
+ """No install record: nvidia-smi stays on PATH when CUDA_VISIBLE_DEVICES hides every GPU."""
+ monkeypatch.delenv("UNSLOTH_AUDIO_CPP_BACKEND", raising = False)
+ monkeypatch.setattr(srv.sys, "platform", "linux")
+ monkeypatch.setattr(
+ srv.shutil, "which", lambda name: "/usr/bin/nvidia-smi" if name == "nvidia-smi" else None
+ )
+ monkeypatch.setattr(srv, "compiled_backends", lambda binary: frozenset({"cpu", "cuda"}))
+ binary = str(tmp_path / srv.BINARY_NAME)
+ monkeypatch.setattr(srv, "_gpu_vendors", lambda: set())
+ assert srv.select_backend(binary, False) == "cpu"
+ monkeypatch.setattr(srv, "_gpu_vendors", lambda: None)
+ assert srv.select_backend(binary, False) == "cuda"
+
+
+def test_gpu_vendor_probe_failure_reads_as_unknown(monkeypatch):
+ from utils import llama_cpp_path_settings
+
+ def boom():
+ raise OSError("sysfs unreadable")
+
+ monkeypatch.setattr(llama_cpp_path_settings, "host_gpu_vendors", boom)
+ assert srv._gpu_vendors() is None
+
+
+ "env, expected",
+ [
+ # With no HIP or ROCR mask set, CUDA_VISIBLE_DEVICES stands in for AMD too.
+ ({"CUDA_VISIBLE_DEVICES": ""}, set()),
+ ({"CUDA_VISIBLE_DEVICES": "-1", "HIP_VISIBLE_DEVICES": "0"}, {"amd"}),
+ ({"HIP_VISIBLE_DEVICES": ""}, {"nvidia"}),
+ ({"CUDA_VISIBLE_DEVICES": "0"}, {"nvidia", "amd"}),
+ ({}, {"nvidia", "amd"}),
+ ],
+)
+def test_visibility_masks_hide_vendors_found_by_driver_dlls(monkeypatch, env, expected):
+ """Windows detection only globs driver DLLs, so the masks are applied on top of it."""
+ from utils import llama_cpp_path_settings
+
+ for name in ("CUDA_VISIBLE_DEVICES", "HIP_VISIBLE_DEVICES", "ROCR_VISIBLE_DEVICES"):
+ monkeypatch.delenv(name, raising = False)
+ for name, value in env.items():
+ monkeypatch.setenv(name, value)
+ monkeypatch.setattr(llama_cpp_path_settings, "host_gpu_vendors", lambda: {"nvidia", "amd"})
+ assert srv._gpu_vendors() == expected
+
+
+def test_a_masked_windows_gpu_build_launches_on_cpu(tmp_path, monkeypatch):
+ from utils import llama_cpp_path_settings
+
+ monkeypatch.delenv("UNSLOTH_AUDIO_CPP_BACKEND", raising = False)
+ monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "")
+ monkeypatch.setattr(llama_cpp_path_settings, "host_gpu_vendors", lambda: {"nvidia"})
+ binary = _recorded_build(tmp_path, "cuda")
+ assert srv.select_backend(binary, False) == "cpu"
+ monkeypatch.setattr(llama_cpp_path_settings, "host_gpu_vendors", lambda: None)
+ assert srv.select_backend(binary, False) == "cuda"
+
+
+_EXITS_WITH = textwrap.dedent(
+ """
+ import sys
+ print({output!r}, flush=True)
+ sys.exit(1)
+ """
+)
+
+
+def test_a_gpu_init_failure_says_so_instead_of_blaming_the_model(
+ fake_binary, tmp_path, monkeypatch
+):
+ (tmp_path / "fake_server.py").write_text(
+ _EXITS_WITH.format(
+ output = "ggml_cuda_init: failed to initialize CUDA: no CUDA-capable device is detected\n"
+ "audiocpp_server failed: CUDA backend requested but registry 'CUDA' has no device 0"
+ ),
+ encoding = "utf-8",
+ )
+ monkeypatch.setattr(srv, "select_backend", lambda binary, force_cpu: "cuda")
+ with pytest.raises(srv.AudioCppUnavailableError) as raised:
+ srv.AudioCppServer.start(CANARY, str(tmp_path / "m.gguf"))
+ message = str(raised.value)
+ assert "incomplete" not in message
+ assert "CUDA backend" in message and "Unsloth Studio" in message
+ assert "UNSLOTH_AUDIO_CPP_BACKEND=cpu" in message
+ assert "has no device 0" in message
+
+
+ "output",
+ [
+ "gguf: unknown tensor type 42",
+ # A CUDA build on the CPU backend logs its CUDA init failure before the real one.
+ "ggml_cuda_init: failed to initialize CUDA: no CUDA-capable device is detected\n"
+ "audiocpp_server failed: unknown tensor type 42",
+ ],
+)
+def test_other_early_exits_keep_pointing_at_the_model(fake_binary, tmp_path, output):
+ (tmp_path / "fake_server.py").write_text(_EXITS_WITH.format(output = output), encoding = "utf-8")
+ with pytest.raises(srv.AudioCppUnavailableError) as raised:
+ srv.AudioCppServer.start(CANARY, str(tmp_path / "m.gguf"))
+ message = str(raised.value)
+ assert "the model file may be incomplete or unsupported by this build" in message
+ assert "unknown tensor type 42" in message
+
+
def test_stop_survives_a_server_slow_to_exit_after_sigkill(tmp_path):
# A server switching task mid-request (Vevo2 Clone <-> Edit) failed the request when the old
# process outlived the SIGKILL wait in GPU teardown.
diff --git a/studio/backend/tests/test_stt_audiocpp_details.py b/studio/backend/tests/test_stt_audiocpp_details.py
index 1ef33ee75a3..e024580a05d 100644
--- a/studio/backend/tests/test_stt_audiocpp_details.py
+++ b/studio/backend/tests/test_stt_audiocpp_details.py
@@ -457,3 +457,22 @@ def test_an_unreadable_source_is_a_decode_error(fake, side, tmp_path):
with pytest.raises(SttAudioDecodeError):
side.transcribe_path(bad, QWEN3, None)
assert fake.starts == []
+
+
[email protected]("gpu_visible", [False, True])
+def test_training_moves_the_server_only_when_its_placement_changes(
+ fake, side, monkeypatch, gpu_visible
+):
+ """A GPU build with no visible GPU already runs on the CPU, so training starting or ending keeps it."""
+ monkeypatch.setattr(
+ srv,
+ "select_backend",
+ lambda binary, force_cpu: "cpu" if force_cpu or not gpu_visible else "cuda",
+ )
+ monkeypatch.setattr(stt, "runtime_runs_on_cpu", lambda: not gpu_visible)
+ training = [False]
+ monkeypatch.setattr(stt, "_training_active", lambda: training[0])
+ for active in (False, True, False):
+ training[0] = active
+ side.transcribe(wav_bytes(), QWEN3, "en")
+ assert len(fake.starts) == (3 if gpu_visible else 1)
diff --git a/studio/backend/tests/test_stt_capabilities.py b/studio/backend/tests/test_stt_capabilities.py
index 1dafd4467f5..512ff9af531 100644
--- a/studio/backend/tests/test_stt_capabilities.py
+++ b/studio/backend/tests/test_stt_capabilities.py
@@ -52,7 +52,13 @@ def test_qwen3_reports_whether_its_aligner_is_downloaded(hub):
def aligner():
return caps.capabilities_for(f"{REPO}/Qwen3-ASR-1.7B-GGUF", "audiocpp")["aligner"]
- assert aligner() == {"downloaded": False, "size_bytes": 1_129_966_496}
+ # The page stages the named quant through the Downloads panel before a timestamped run.
+ assert aligner() == {
+ "id": f"{REPO}/Qwen3-ForcedAligner-0.6B-GGUF",
+ "variant": "Q8_0",
+ "downloaded": False,
+ "size_bytes": 1_129_966_496,
+ }
_add(hub, "Qwen3-ForcedAligner-0.6B-GGUF", "qwen3_forced_aligner")
assert aligner()["downloaded"] is True and aligner()["size_bytes"] > 0
diff --git a/studio/frontend/src/features/audio/audio-page.tsx b/studio/frontend/src/features/audio/audio-page.tsx
index 2647be1c83a..c3cb8ca7193 100644
--- a/studio/frontend/src/features/audio/audio-page.tsx
+++ b/studio/frontend/src/features/audio/audio-page.tsx
@@ -43,7 +43,7 @@ import {
audioEjectAvailable,
audioGenerationPresentation,
} from "./audio-page-policy";
-import { clipReference } from "./audio-run-request";
+import { type AudioSourceSelection, clipReference } from "./audio-run-request";
import { AudioRuntimeUpdateNotice } from "./components/audio-runtime-update-notice";
import { AudioActiveProvider } from "./components/audio-source-input";
import {
@@ -105,6 +105,7 @@ import { AUDIO_CPP_REPO, audioCppModelFor } from "./audio-cpp-catalog";
import { selectionExpired } from "./audio-run-request";
import type { AudioSourceInputHandle } from "./components/audio-source-input";
import type { AudioSourceStatus } from "./hooks/audio-source-state";
+import { useAlignerDownload } from "./hooks/use-aligner-download";
import { useTranscribeCapabilities } from "./hooks/use-transcribe-capabilities";
import { useAudioTranscribeStore } from "./stores/audio-transcribe-store";
import { SPEAKERS_MODEL_NAME, transcribeSwitches } from "./transcribe-capabilities";
@@ -1313,8 +1314,16 @@ export function AudioPage({
label: `use ${model.name}`,
onClick: () => void pickRecommendedModel(model.id),
}));
- const transcribeBlocker: GenerateBlocker | null =
- busy === "loading"
+ const alignerDownload = useAlignerDownload(
+ transcribeCaps.caps,
+ transcribeCaps.refresh,
+ transcribeOptions.request.timestamps,
+ );
+ const alignerBlocks =
+ alignerDownload.staging && transcribeOptions.request.timestamps;
+ const transcribeBlocker: GenerateBlocker | null = alignerBlocks
+ ? { reason: "Downloading the timing aligner…" }
+ : busy === "loading"
? { reason: "Waiting for the model to finish loading." }
: busy !== null
? null
@@ -1356,9 +1365,7 @@ export function AudioPage({
: null;
const canTranscribe =
mode === "transcribe" && busy === null && transcribeBlocker === null;
- const handleTranscribe = () => {
- const source = useAudioTranscribeStore.getState().source;
- if (!source) return;
+ const startTranscription = (source: AudioSourceSelection) => {
const { request } = transcribeOptions;
void runTranscription(
source,
@@ -1372,6 +1379,31 @@ export function AudioPage({
if (request.timestamps) transcribeCaps.refresh();
});
};
+ const startTranscriptionRef = useRef(startTranscription);
+ useEffect(() => {
+ startTranscriptionRef.current = startTranscription;
+ });
+ const handleTranscribe = () => {
+ const source = useAudioTranscribeStore.getState().source;
+ if (!source) return;
+ alignerDownload.runWithAligner(transcribeOptions.request.timestamps, () => {
+ // The download can outlast the click: run only while Transcribe still shows the same audio.
+ if (
+ !activeRef.current ||
+ modeRef.current !== "transcribe" ||
+ useAudioTranscribeStore.getState().source?.id !== source.id
+ )
+ return;
+ // A run would be refused while a model loads or another task runs: say so instead of dropping it.
+ if (busyRef.current !== null) {
+ toast.info("The timing aligner is ready", {
+ description: "Press Transcribe again once the current task finishes.",
+ });
+ return;
+ }
+ startTranscriptionRef.current(source);
+ });
+ };
const [transcribeAnnouncement, setTranscribeAnnouncement] = useState("");
const lastTranscribeFinish = useRef<number | null>(transcriptionFinishedAt);
useEffect(() => {
diff --git a/studio/frontend/src/features/audio/hooks/use-aligner-download.ts b/studio/frontend/src/features/audio/hooks/use-aligner-download.ts
new file mode 100644
index 00000000000..eb1b9f81e74
--- /dev/null
+++ b/studio/frontend/src/features/audio/hooks/use-aligner-download.ts
@@ -0,0 +1,60 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import { useCallback, useEffect, useRef } from "react";
+
+import { useStagedDownload } from "@/features/hub/download-manager";
+import { toast } from "@/lib/toast";
+
+import {
+ alignerDownloadEntry,
+ type SttCapabilities,
+} from "../transcribe-capabilities";
+
+/** Fetches the timing aligner through the Downloads panel before a timestamped run, instead of
+ * letting the run download it with no progress or cancel. */
+export function useAlignerDownload(
+ caps: SttCapabilities | null,
+ refreshCaps: () => void,
+ timestamps: boolean,
+) {
+ const pendingRun = useRef<(() => void) | null>(null);
+ useEffect(() => {
+ // Turning Timestamps off drops the waiting run; the download itself carries on.
+ if (!timestamps) pendingRun.current = null;
+ }, [timestamps]);
+ const { stage, staging } = useStagedDownload({
+ scopeId: "audio-aligner",
+ onReady: () => {
+ const run = pendingRun.current;
+ pendingRun.current = null;
+ refreshCaps();
+ run?.();
+ },
+ onReset: () => {
+ pendingRun.current = null;
+ },
+ onCancelled: () => {
+ if (!pendingRun.current) return;
+ pendingRun.current = null;
+ toast.info("Transcription not started", {
+ description:
+ "Timestamps need the timing aligner. Download it again, or turn Timestamps off.",
+ });
+ },
+ });
+ const runWithAligner = useCallback(
+ (timestamps: boolean, run: () => void) => {
+ const entry = alignerDownloadEntry(caps, timestamps);
+ if (!entry) {
+ pendingRun.current = null;
+ run();
+ return;
+ }
+ pendingRun.current = run;
+ stage([entry]);
+ },
+ [caps, stage],
+ );
+ return { runWithAligner, staging };
+}
diff --git a/studio/frontend/src/features/audio/hooks/use-audio-model-slot.ts b/studio/frontend/src/features/audio/hooks/use-audio-model-slot.ts
index 0976cca9e7f..1ed5a97e4e1 100644
--- a/studio/frontend/src/features/audio/hooks/use-audio-model-slot.ts
+++ b/studio/frontend/src/features/audio/hooks/use-audio-model-slot.ts
@@ -510,6 +510,8 @@ export function useAudioModelSlot({
pending.isGguf,
);
},
+ onCancelled: invalidatePendingStagedTts,
+ onReset: invalidatePendingStagedTts,
});
useEffect(() => {
diff --git a/studio/frontend/src/features/audio/transcribe-capabilities.ts b/studio/frontend/src/features/audio/transcribe-capabilities.ts
index e7c24a19b5b..0cdb6f69e7e 100644
--- a/studio/frontend/src/features/audio/transcribe-capabilities.ts
+++ b/studio/frontend/src/features/audio/transcribe-capabilities.ts
@@ -9,7 +9,12 @@ export interface SttCapabilities {
/** on_request: only when asked (Qwen3-ASR with its aligner); always: every run has them. */
timestamps: "on_request" | "always" | "unsupported";
speakers: boolean;
- aligner: { downloaded: boolean; size_bytes: number } | null;
+ aligner: {
+ downloaded: boolean;
+ size_bytes: number;
+ id?: string;
+ variant?: string;
+ } | null;
cpu_only: boolean;
}
@@ -30,6 +35,28 @@ export interface TranscribeSwitches {
export const SPEAKERS_MODEL_NAME = "MOSS-Transcribe-Diarize";
+/** The aligner download a timestamped run needs first, staged like any other quant so it shows in
+ * the Downloads panel; null when the run can start now. */
+export function alignerDownloadEntry(
+ caps: SttCapabilities | null,
+ timestamps: boolean,
+): {
+ repoId: string;
+ files: string[];
+ bytes: number;
+ ggufVariant: string;
+} | null {
+ const aligner = caps?.aligner;
+ if (!timestamps || !aligner || aligner.downloaded) return null;
+ if (!aligner.id || !aligner.variant) return null;
+ return {
+ repoId: aligner.id,
+ files: [],
+ bytes: aligner.size_bytes,
+ ggufVariant: aligner.variant,
+ };
+}
+
function formatSize(bytes: number): string {
if (bytes >= 1e9) return `${(bytes / 1e9).toFixed(1)} GB`;
return `${Math.max(1, Math.round(bytes / 1e6))} MB`;
diff --git a/studio/frontend/src/features/hub/download-manager/download-manager-controller.ts b/studio/frontend/src/features/hub/download-manager/download-manager-controller.ts
index d738a94b72c..e0e1511cbab 100644
--- a/studio/frontend/src/features/hub/download-manager/download-manager-controller.ts
+++ b/studio/frontend/src/features/hub/download-manager/download-manager-controller.ts
@@ -18,7 +18,7 @@ import {
import { hydrateDownloadManager, resetHydrationState } from "./hydration";
import { cancelJob, probeAndAdopt, setExpected } from "./poll-loop";
import { runtimeRegistry } from "./runtime-registry";
-import { useStagedDownloadQueues } from "./staged-download-queue";
+import { resetStagedQueues } from "./staged-download-queue";
import {
cancelConflict,
requestStart,
@@ -50,7 +50,7 @@ function resetDownloadManagerState(): void {
resetHydrationState();
setState(createDownloadManagerInitialState());
// A media page stays mounted across a cross-tab session change, so its queue would outlive the jobs.
- useStagedDownloadQueues.setState({ queues: {} });
+ resetStagedQueues();
}
export function __resetDownloadManagerForTests(): void {
diff --git a/studio/frontend/src/features/hub/download-manager/staged-download-queue.ts b/studio/frontend/src/features/hub/download-manager/staged-download-queue.ts
index a33f33ee3ea..2d3a1e280ec 100644
--- a/studio/frontend/src/features/hub/download-manager/staged-download-queue.ts
+++ b/studio/frontend/src/features/hub/download-manager/staged-download-queue.ts
@@ -13,7 +13,16 @@ export interface StagedQueue {
// Display state only. The owning hook still controls advancement and loading.
export const useStagedDownloadQueues = create<{
queues: Record<string, StagedQueue>;
-}>(() => ({ queues: {} }));
+ // Bumped when a session change drops every job, so mounted staging hooks drop their plans too.
+ resets: number;
+}>(() => ({ queues: {}, resets: 0 }));
+
+export function resetStagedQueues() {
+ useStagedDownloadQueues.setState(({ resets }) => ({
+ queues: {},
+ resets: resets + 1,
+ }));
+}
export function publishStagedQueue(owner: string, queue: StagedQueue | null) {
useStagedDownloadQueues.setState(({ queues }) => {
diff --git a/studio/frontend/src/features/hub/download-manager/use-staged-download.ts b/studio/frontend/src/features/hub/download-manager/use-staged-download.ts
index 176474c61c3..afa51d67f17 100644
--- a/studio/frontend/src/features/hub/download-manager/use-staged-download.ts
+++ b/studio/frontend/src/features/hub/download-manager/use-staged-download.ts
@@ -12,7 +12,10 @@ import {
scopedDownloadInventoryKind,
scopedVariant,
} from "./download-manager-types";
-import { publishStagedQueue } from "./staged-download-queue";
+import {
+ publishStagedQueue,
+ useStagedDownloadQueues,
+} from "./staged-download-queue";
import { useRepoDownload } from "./use-repo-download";
/** Total progress for the plan ID returned by `stage()`. */
@@ -46,6 +49,7 @@ export function useStagedDownload({
scopeId,
onReady,
onCancelled,
+ onReset,
publishQueue = true,
}: {
scopeId: string;
@@ -54,6 +58,8 @@ export function useStagedDownload({
onReady: () => void;
/** Clears the consumer's pending auto-load when the plan ends without every entry on disk: leaving it behind lets a later completion load a model nobody asked for. */
onCancelled?: () => void;
+ /** A cross-tab session change dropped the plan's jobs. Not `onCancelled`: a consumer starting its next plan there would carry the old session's queue over. */
+ onReset?: () => void;
}) {
const [queue, setQueue] = useState<StagedDownloadEntry[] | null>(null);
// Keep the original total as completed entries leave the queue.
@@ -119,6 +125,33 @@ export function useStagedDownload({
const onCancelledRef = useRef(onCancelled);
onCancelledRef.current = onCancelled;
+ const onResetRef = useRef(onReset);
+ useEffect(() => {
+ onResetRef.current = onReset;
+ });
+ const queueRef = useRef(queue);
+ useEffect(() => {
+ queueRef.current = queue;
+ });
+ useEffect(
+ () =>
+ useStagedDownloadQueues.subscribe((state, previous) => {
+ // Opt-in: consumers without onReset keep their plan.
+ if (
+ state.resets === previous.resets ||
+ queueRef.current === null ||
+ !onResetRef.current
+ ) {
+ return;
+ }
+ queueRef.current = null;
+ generation.current += 1;
+ inFlight.current = null;
+ setQueue(null);
+ onResetRef.current?.();
+ }),
+ [],
+ );
useEffect(() => {
if (!current) return;
let active = true;
diff --git a/studio/frontend/src/features/settings/lib/stt-download-mirror.ts b/studio/frontend/src/features/settings/lib/stt-download-mirror.ts
index 3f8f8082773..24156f51981 100644
--- a/studio/frontend/src/features/settings/lib/stt-download-mirror.ts
+++ b/studio/frontend/src/features/settings/lib/stt-download-mirror.ts
@@ -255,7 +255,10 @@ function trackSttDownloadNow(
startExternalJob({
key: jobKey(model, resolvedEngine),
repoId: options.repoId ?? getSttModelRepo(model),
- variant: sttModelName(model),
+ // A folder row's name already heads the entry; its quant is what tells downloads apart.
+ variant: isAudioCppFolderId(model)
+ ? (trackedVariants.get(key) ?? null)
+ : sttModelName(model),
expectedBytes: 0,
cancel: async () => {
try {
diff --git a/studio/frontend/tests/audio-cpp-catalog.test.ts b/studio/frontend/tests/audio-cpp-catalog.test.ts
index 9b1aee93861..4f2a74fece5 100644
--- a/studio/frontend/tests/audio-cpp-catalog.test.ts
+++ b/studio/frontend/tests/audio-cpp-catalog.test.ts
@@ -829,7 +829,12 @@ test("recommended speech and music picks are refused when the runtime cannot run
assert.equal(audioCppRuntimeProblem("OpenMOSS-Team/MOSS-TTS-Nano-100M", missing), null);
assert.equal(audioCppRuntimeProblem(null, missing), null);
const route = readText("../../backend/routes/inference.py");
- assert.match(route, /"audio_cpp_runtime": _audio_cpp_runtime_status\(\)/);
+ // Read off the event loop: choosing the launch backend can run the binary.
+ assert.match(
+ route,
+ /audio_cpp_runtime = await asyncio\.to_thread\(_audio_cpp_runtime_status\)/,
+ );
+ assert.match(route, /"audio_cpp_runtime": audio_cpp_runtime,/);
const page = readAudioWorkspaceSource();
assert.match(page, /audioCppRuntime\.current = stt\.audio_cpp_runtime \?\? null;/);
assert.match(
diff --git a/studio/frontend/tests/audio-transcribe-aligner-download.test.ts b/studio/frontend/tests/audio-transcribe-aligner-download.test.ts
new file mode 100644
index 00000000000..0bea74f2aa7
--- /dev/null
+++ b/studio/frontend/tests/audio-transcribe-aligner-download.test.ts
@@ -0,0 +1,121 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import {
+ alignerDownloadEntry,
+ type SttCapabilities,
+} from "../src/features/audio/transcribe-capabilities.ts";
+import { readSrc } from "./helpers/kit.ts";
+
+const ALIGNER_ID = "audio-cpp/audio.cpp-gguf/Qwen3-ForcedAligner-0.6B-GGUF";
+const QWEN3: SttCapabilities = {
+ engine: "audiocpp",
+ family: "qwen3_asr",
+ timestamps: "on_request",
+ speakers: false,
+ aligner: {
+ downloaded: false,
+ size_bytes: 1_129_966_496,
+ id: ALIGNER_ID,
+ variant: "Q8_0",
+ },
+ cpu_only: false,
+};
+
+test("a timestamped run stages a missing aligner as a normal quant download", () => {
+ assert.deepEqual(alignerDownloadEntry(QWEN3, true), {
+ repoId: ALIGNER_ID,
+ files: [],
+ bytes: 1_129_966_496,
+ ggufVariant: "Q8_0",
+ });
+});
+
+test("nothing is staged when the run can start now", () => {
+ assert.equal(alignerDownloadEntry(QWEN3, false), null);
+ assert.equal(
+ alignerDownloadEntry(
+ { ...QWEN3, aligner: { ...QWEN3.aligner!, downloaded: true } },
+ true,
+ ),
+ null,
+ );
+ assert.equal(alignerDownloadEntry({ ...QWEN3, aligner: null }, true), null);
+ assert.equal(alignerDownloadEntry(null, true), null);
+ // An older backend that does not name the aligner keeps its own download.
+ assert.equal(
+ alignerDownloadEntry(
+ { ...QWEN3, aligner: { downloaded: false, size_bytes: 1 } },
+ true,
+ ),
+ null,
+ );
+});
+
+test("the aligner download runs through the shared manager; cancel, Timestamps off or an untimestamped run drops the pending run", () => {
+ const hook = readSrc("features/audio/hooks/use-aligner-download.ts");
+ assert.match(hook, /useStagedDownload\(\{\s*scopeId: "audio-aligner"/);
+ assert.match(
+ hook,
+ /onReady: \(\) => \{[\s\S]*pendingRun\.current = null;[\s\S]*refreshCaps\(\);[\s\S]*run\?\.\(\);/,
+ );
+ assert.match(
+ hook,
+ /useEffect\(\(\) => \{[^}]*if \(!timestamps\) pendingRun\.current = null;\s*\}, \[timestamps\]\);/,
+ );
+ // Only a dropped run explains itself; a plan with nothing waiting stays quiet.
+ assert.match(
+ hook,
+ /onCancelled: \(\) => \{\s*if \(!pendingRun\.current\) return;\s*pendingRun\.current = null;\s*toast\.info\("Transcription not started"/,
+ );
+ assert.match(
+ hook,
+ /if \(!entry\) \{[^}]*pendingRun\.current = null;\s*run\(\);\s*return;\s*\}\s*pendingRun\.current = run;\s*stage\(\[entry\]\);/,
+ );
+});
+
+test("only a timestamped Transcribe waits for the aligner download", () => {
+ const page = readSrc("features/audio/audio-page.tsx");
+ assert.match(
+ page,
+ /useAlignerDownload\(\s*transcribeCaps\.caps,\s*transcribeCaps\.refresh,\s*transcribeOptions\.request\.timestamps,\s*\)/,
+ );
+ assert.match(
+ page,
+ /const alignerBlocks =\s*alignerDownload\.staging && transcribeOptions\.request\.timestamps;\s*const transcribeBlocker: GenerateBlocker \| null = alignerBlocks\s*\?\s*\{ reason: "Downloading the timing aligner…" \}/,
+ );
+ // The run reads the page as it is when the download ends, and only while it is still showing.
+ assert.match(
+ page,
+ /const startTranscriptionRef = useRef\(startTranscription\);\s*useEffect\(\(\) => \{\s*startTranscriptionRef\.current = startTranscription;\s*\}\);/,
+ );
+ assert.match(
+ page,
+ /alignerDownload\.runWithAligner\(transcribeOptions\.request\.timestamps, \(\) => \{[\s\S]*?!activeRef\.current \|\|\s*modeRef\.current !== "transcribe" \|\|\s*useAudioTranscribeStore\.getState\(\)\.source\?\.id !== source\.id\s*\)\s*return;[\s\S]*?startTranscriptionRef\.current\(source\);/,
+ );
+ // A download ending while a model loads cannot start the run; the user is told, not left waiting.
+ assert.match(
+ page,
+ /if \(busyRef\.current !== null\) \{\s*toast\.info\("The timing aligner is ready"[\s\S]*?return;\s*\}\s*startTranscriptionRef\.current\(source\);/,
+ );
+});
+
+test("a session reset drops a staged plan so Transcribe is not left blocked", () => {
+ const staged = readSrc(
+ "features/hub/download-manager/use-staged-download.ts",
+ );
+ const start = staged.indexOf("useStagedDownloadQueues.subscribe(");
+ const subscriber = staged.slice(start, staged.indexOf(" [],", start));
+ assert.ok(start > 0 && subscriber.length > 0);
+ // Opt-in, and never onCancelled: Images and the Hub queue start their next plan there.
+ assert.match(subscriber, /!onResetRef\.current\s*\)\s*\{\s*return;/);
+ assert.match(subscriber, /setQueue\(null\);\s*onResetRef\.current\?\.\(\);/);
+ assert.doesNotMatch(subscriber, /onCancelled/);
+ const hook = readSrc("features/audio/hooks/use-aligner-download.ts");
+ assert.match(hook, /onReset: \(\) => \{\s*pendingRun\.current = null;\s*\}/);
+ const slot = readSrc("features/audio/hooks/use-audio-model-slot.ts");
+ assert.match(slot, /onReset: invalidatePendingStagedTts,/);
+});
diff --git a/studio/frontend/tests/audio-tts-download-manager.test.ts b/studio/frontend/tests/audio-tts-download-manager.test.ts
index d7930539502..dc257132aed 100644
--- a/studio/frontend/tests/audio-tts-download-manager.test.ts
+++ b/studio/frontend/tests/audio-tts-download-manager.test.ts
@@ -144,3 +144,10 @@ test("Mac sibling inspection reserves the lifecycle slot before awaiting invento
/ttsInspectionGeneration\.current = selectionGeneration;[\s\S]*busyRef\.current = "loading";[\s\S]*setBusy\("loading"\);[\s\S]*await listGgufVariants/,
);
});
+
+test("a cancelled, failed or session-reset staged TTS download clears the pending load", () => {
+ assert.match(
+ source,
+ /useStagedDownload\(\{\s*scopeId: "audio",[\s\S]*?onCancelled: invalidatePendingStagedTts,\s*onReset: invalidatePendingStagedTts,\s*\}\);/,
+ );
+});
diff --git a/studio/frontend/tests/download-session-boundary.test.ts b/studio/frontend/tests/download-session-boundary.test.ts
index bb53ca92f76..7ca23ba6d80 100644
--- a/studio/frontend/tests/download-session-boundary.test.ts
+++ b/studio/frontend/tests/download-session-boundary.test.ts
@@ -83,6 +83,7 @@ for (const [name, eventType, event] of boundaries) {
],
});
store.set(PERSIST_KEY, "prior-session-downloads");
+ const resets = useStagedDownloadQueues.getState().resets;
try {
fireWindowEvent(eventType, event);
@@ -90,6 +91,8 @@ for (const [name, eventType, event] of boundaries) {
assert.equal(runtimeRegistry.pendingStartRepoKeys.size, 0);
assert.equal(store.has(PERSIST_KEY), false);
assert.deepEqual(useStagedDownloadQueues.getState().queues, {});
+ // Mounted staging hooks watch this to drop the plans whose jobs just went away.
+ assert.equal(useStagedDownloadQueues.getState().resets, resets + 1);
} finally {
controller.__resetDownloadManagerForTests();
await useDownloadManagerStore.persist.clearStorage();
diff --git a/studio/frontend/tests/stt-download-mirror-policy.test.ts b/studio/frontend/tests/stt-download-mirror-policy.test.ts
index a7199fd163a..6d062cd3858 100644
--- a/studio/frontend/tests/stt-download-mirror-policy.test.ts
+++ b/studio/frontend/tests/stt-download-mirror-policy.test.ts
@@ -80,3 +80,10 @@ test("an explicit Transformers transfer keeps its serving engine", () => {
/options\.engine === "transformers" \? undefined/,
);
});
+
+test("an audio.cpp folder download names its quant, not the folder twice", () => {
+ assert.match(
+ source,
+ /variant: isAudioCppFolderId\(model\)\s*\?\s*\(trackedVariants\.get\(key\) \?\? null\)\s*:\s*sttModelName\(model\),/,
+ );
+});