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: keep unrunnable speech GGUFs out of the model pickers (#9433)

Nilay86a899304b9b
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.py
index db98ff9e794..f1d98e71ad7 100644
--- a/studio/backend/core/inference/diffusion.py
+++ b/studio/backend/core/inference/diffusion.py
@@ -57,7 +57,12 @@ from .diffusion_families import (
resolve_local_gguf_child,
supported_family_names,
)
-from .diffusion_compat import assert_flux2_pick_compatible, flux2_pick_mismatch
+from .diffusion_compat import (
+ assert_flux2_pick_compatible,
+ assert_pick_is_not_speech,
+ flux2_pick_mismatch,
+ speech_pick_refusal,
+)
from .diffusion_device import (
DiffusionDeviceTarget,
apply_diffusion_device_ordinal,
@@ -1916,6 +1921,7 @@ class DiffusionBackend:
model_kind: Optional[str] = None,
base_repo: Optional[str] = None,
hf_token: Optional[str] = None,
+ allow_network: bool = True,
) -> None:
"""The gated/unreadable-base and FLUX.2 size-pairing refusals, run by the route BEFORE it
takes the GPU.
@@ -1942,6 +1948,11 @@ class DiffusionBackend:
# range request for the GGUF's tensor table), and fails open on anything it cannot read.
# The UPSTREAM base, not the mirror: the size tables key on vendor ids.
assert_flux2_pick_compatible(fam, repo_id, gguf_filename, base, hf_token)
+ # No media backend decodes a speech GGUF, and detect_family_for_pick answers from the
+ # folder name, so a csm file beside a denoiser reaches this loader as one of its own.
+ # Cache-only for a load nobody asked for: this probe would otherwise spend a revision HEAD,
+ # or a range request and its bound, on the one path that promised to stay off the Hub.
+ assert_pick_is_not_speech(repo_id, gguf_filename, hf_token, allow_network)
# ── Background load + progress ─────────────────────────────────────────
@@ -2133,6 +2144,13 @@ class DiffusionBackend:
assert_flux2_pick_compatible(
fam, kwargs["repo_id"], kwargs.get("gguf_filename"), base, kwargs.get("hf_token")
)
+ # Same verdict here, so a direct begin_load is covered too.
+ assert_pick_is_not_speech(
+ kwargs["repo_id"],
+ kwargs.get("gguf_filename"),
+ kwargs.get("hf_token"),
+ allow_network = not local_files_only,
+ )
with self._lock:
# Stamp progress only if this load is still current (a superseder has its own token).
if self._load_token == token and self._loading is not None:
@@ -2585,7 +2603,11 @@ class DiffusionBackend:
# a 400 here would start the very download this is meant to prevent; carried in the
# envelope instead, the picker can refuse at SELECTION time. Metadata only (one range
# request for the GGUF's tensor table), and None whenever nothing is known to be wrong.
- incompatible = flux2_pick_mismatch(fam, repo_id, gguf_filename, base, hf_token)
+ # The speech verdict belongs here too, not only on the load preflight: the Images page
+ # stages and downloads before it calls load, so a later refusal arrives after the bytes.
+ incompatible = flux2_pick_mismatch(
+ fam, repo_id, gguf_filename, base, hf_token
+ ) or speech_pick_refusal(repo_id, gguf_filename, hf_token)
# Only a checkpoint that really resolves on the Hub earns the right to drop dense shards.
te_files = self._te_prequant_plan_files(
fam, text_encoder_quant, hf_token, load_kwargs.get("gpu_ordinal")
diff --git a/studio/backend/core/inference/diffusion_compat.py b/studio/backend/core/inference/diffusion_compat.py
index 2c55408dc27..c8f7a073c45 100644
--- a/studio/backend/core/inference/diffusion_compat.py
+++ b/studio/backend/core/inference/diffusion_compat.py
@@ -94,10 +94,20 @@ def _file_identity(path: Optional[str]) -> Optional[tuple]:
def _local_gguf_path(repo_id: str, gguf_filename: str) -> Optional[str]:
"""The on-disk checkpoint for this pick, or None when it has to come off the Hub.
- Covers a local On Device directory and a Hub file already in either cache root: reading a file
- we hold beats a range request, and it is the same file ``_resolve_gguf_path`` will open."""
+ Covers a local On Device directory, a pick that NAMES the checkpoint outright, and a Hub file
+ already in either cache root: reading a file we hold beats a range request, and it is the same
+ file ``_resolve_gguf_path`` will open.
+
+ The file case is resolved the way the loader resolves it:
+ ``VideoBackend._resolve_checkpoint_path`` answers a file-valued ``repo_id`` with that file,
+ ignoring ``gguf_filename``, and ``validate_load_request`` admits exactly that pick, so
+ ``/video/load`` really can be handed one. Appending the filename under a file instead raises
+ ``FileNotFoundError``, an ``OSError``, swallowed below as "remote id" -- and failing open on
+ the pick the loader is about to open directly is the one hole this exists to close."""
try:
local_root = Path(repo_id).expanduser()
+ if local_root.is_file():
+ return str(local_root)
if local_root.exists():
return str(resolve_local_gguf_child(local_root, gguf_filename))
# OSError/RuntimeError: invalid path characters, or an unresolvable '~' -> a remote id.
@@ -161,6 +171,42 @@ def _read_local_header(path: str) -> bytes:
return b""
+def _ranged_stream(session: Any, url: str, headers: dict) -> Any:
+ """A context manager over a ranged GET, on either HTTP client huggingface_hub ships.
+
+ ``huggingface_hub`` 1.0 replaced requests with httpx, and ``get_session`` returns whichever
+ the installed version builds. The two streaming APIs do not overlap: httpx has no
+ ``stream = True`` keyword (it streams via ``Client.stream``), so asking for one on 1.x raises
+ ``TypeError`` inside the worker's blanket except and every remote probe silently reads nothing
+ -- a preflight that refuses nothing. studio.txt floors 1.23 on python >= 3.10 and pins 0.36
+ below it, so BOTH are shipped and both have to work.
+
+ ``Client.stream`` is a method; ``requests.Session.stream`` is a plain bool attribute, so the
+ branch tests for a callable rather than for the name."""
+ if callable(getattr(session, "stream", None)):
+ # httpx does not follow redirects by default and the Hub answers a resolve URL with a
+ # 302 to the CDN, so an unfollowed hop would read as "not 206" and fail open.
+ return session.stream(
+ "GET",
+ url,
+ headers = headers,
+ timeout = _HEADER_TIMEOUT_SECONDS,
+ follow_redirects = True,
+ )
+ return session.get(
+ url,
+ headers = headers,
+ timeout = _HEADER_TIMEOUT_SECONDS,
+ stream = True,
+ )
+
+
+def _iter_body(response: Any, chunk_size: int):
+ """The response body in chunks, from httpx's reader or requests'."""
+ reader = getattr(response, "iter_bytes", None) or response.iter_content
+ return reader(chunk_size)
+
+
def _interrupt_read(response: Any) -> None:
"""Make a read parked on ``response`` return, so the whole-body deadline can be enforced.
@@ -168,7 +214,8 @@ def _interrupt_read(response: Any) -> None:
thread blocked inside ``iter_content``: ``Response.close`` drops the file object while the
socket stays readable, so the read sits there regardless. Best effort -- and on a urllib3
older than 2.3, which is where ``shutdown`` first appears, there is nothing here that can wake
- it. The caller does not depend on this working; it reads on a worker it can abandon.
+ it. An httpx response has no ``raw`` at all, so it takes the ``close`` branch. The caller does
+ not depend on this working; it reads on a worker it can abandon.
``None`` means the worker has not got a response yet -- it is still inside connect or the
header wait -- so there is nothing to half-close and abandoning it is the whole bound."""
@@ -209,11 +256,8 @@ def _read_gguf_header(repo_id: str, gguf_filename: str, hf_token: Optional[str])
try:
headers = dict(build_hf_headers(token = hf_token))
headers["Range"] = f"bytes=0-{_GGUF_HEADER_BYTES - 1}"
- with get_session().get(
- hf_hub_url(repo_id, gguf_filename),
- headers = headers,
- timeout = _HEADER_TIMEOUT_SECONDS,
- stream = True,
+ with _ranged_stream(
+ get_session(), hf_hub_url(repo_id, gguf_filename), headers
) as response:
holder[0] = response
# 206 or nothing. A server (or a proxy) that ignored the Range header answers 200
@@ -222,7 +266,7 @@ def _read_gguf_header(repo_id: str, gguf_filename: str, hf_token: Optional[str])
if response.status_code != 206:
return
deadline = time.monotonic() + _HEADER_TIMEOUT_SECONDS
- for chunk in response.iter_content(chunk_size = 65536):
+ for chunk in _iter_body(response, 65536):
# extend, not `+=`: augmented assignment to a closed-over name would rebind
# it as a local of _fetch and lose every byte.
buffer.extend(chunk)
@@ -304,7 +348,7 @@ def flux2_inner_dim_for_pick(
inner_dim = gguf_flux2_inner_dim(local)
else:
inner_dim = gguf_flux2_inner_dim_from_header(
- _read_gguf_header(repo_id, gguf_filename, token)
+ _shared_gguf_header(repo_id, gguf_filename, token, local)
)
with _CACHE_LOCK:
# Plain FIFO-ish eviction: this only bounds a session's worth of picks, and a re-probe
@@ -363,6 +407,222 @@ def flux2_pick_mismatch(
)
+# GGUF ``general.architecture`` values nothing in Studio can decode. Beside the FLUX.2 check
+# because both ask whether the pick is loadable, off the same prefix. The set itself lives in a
+# leaf module, shared with the chat gate and the listing classifier so they cannot drift.
+from utils.gguf_archs import ( # noqa: E402 -- beside the cache it keys
+ SPEECH_GGUF_ARCHS as _SPEECH_GGUF_ARCHS,
+ is_speech_gguf_architecture,
+)
+
+_SPEECH_ARCH_CACHE: dict[
+ tuple[str, str, str, Optional[tuple]], tuple[Optional[str], Optional[float]]
+] = {}
+_SPEECH_ARCH_CACHE_MAX = 256
+# Every remote-backed verdict ages out. An UNCACHED one keys on a local identity of None, so a
+# republish under the same filename changes nothing about the key. A SNAPSHOT-backed one keys on
+# the file's identity, which a republish does change -- but only once the new bytes are down, and
+# the entry memoises a revision check that ran only the first time, so holding it forever means
+# never asking the Hub again for the life of the process. Only a true On Device checkpoint is
+# permanent: it is the file the loader opens, so there is no revision to be behind. Matches the
+# variant listing's own freshness window for moved revisions.
+_SPEECH_REMOTE_TTL_SECONDS = 60.0
+
+# (repo_id, gguf_filename, token fingerprint, local file identity) -> the header prefix.
+#
+# The inner-dim probe and the speech probe read the SAME first _GGUF_HEADER_BYTES of the SAME
+# file, and a flux.2 pick that is not a size mismatch runs both: two range requests, each with its
+# own _HEADER_TIMEOUT_SECONDS, so a picker the user waits on could wear twice its documented
+# bound. They share the read now, keyed and aged exactly like the speech memo beside it, so this
+# adds no staleness the module did not already accept.
+#
+# Deliberately NOT consulted by the revalidation paths: their whole job is to re-read a file the
+# Hub has republished, and answering those from a memo would defeat them.
+_HEADER_PREFIX_CACHE: dict[tuple[str, str, str, Optional[tuple]], tuple[bytes, float]] = {}
+_HEADER_PREFIX_CACHE_MAX = 32
+
+
+def _shared_gguf_header(
+ repo_id: str, gguf_filename: str, token: Optional[str], local: Optional[str]
+) -> bytes:
+ """``_read_gguf_header``, read once for the probes that run back to back on one pick."""
+ key = (repo_id, gguf_filename, _token_fingerprint(token), _file_identity(local))
+ now = time.monotonic()
+ with _CACHE_LOCK:
+ memo = _HEADER_PREFIX_CACHE.get(key)
+ if memo is not None:
+ prefix, expires_at = memo
+ if now < expires_at:
+ return prefix
+ del _HEADER_PREFIX_CACHE[key]
+ prefix = _read_gguf_header(repo_id, gguf_filename, token)
+ # An empty prefix is a failed read, and the two probes disagreeing about that is not worth a
+ # sticky miss: each still memoises its own "no verdict" on its own terms.
+ if not prefix:
+ return prefix
+ with _CACHE_LOCK:
+ if len(_HEADER_PREFIX_CACHE) >= _HEADER_PREFIX_CACHE_MAX:
+ _HEADER_PREFIX_CACHE.clear()
+ _HEADER_PREFIX_CACHE[key] = (prefix, now + _SPEECH_REMOTE_TTL_SECONDS)
+ return prefix
+
+
+def _arch_from_prefix(prefix: bytes, gguf_filename: str) -> Optional[str]:
+ """``general.architecture`` out of a header prefix, or None when it says nothing."""
+ # Magic, version and the two counts: anything shorter is not a GGUF at all.
+ if len(prefix) < 24:
+ return None
+ try:
+ import tempfile
+
+ from utils.models.gguf_metadata import read_gguf_architecture
+ with tempfile.TemporaryDirectory(prefix = "unsloth-speech-probe-") as probe_dir:
+ # Named after the real file, like the chat-side probe: a GGUF declaring no
+ # architecture is judged by its name, which a temp name would lose.
+ probe_path = os.path.join(probe_dir, os.path.basename(gguf_filename))
+ with open(probe_path, "wb") as handle:
+ handle.write(prefix)
+ return (read_gguf_architecture(probe_path) or "").strip().lower() or None
+ except Exception: # noqa: BLE001 -- a probe that failed is not a verdict
+ return None
+
+
+def _revalidated_speech_arch(
+ repo_id: str,
+ gguf_filename: str,
+ token: Optional[str],
+ local: Optional[str],
+ arch: Optional[str],
+ allow_network: bool = True,
+) -> Optional[str]:
+ """*arch* again, re-read off the Hub when the cached copy it came from is behind.
+
+ ``try_to_load_from_cache`` resolves the LOCAL ``refs/main``, so a republished checkpoint is
+ judged off bytes ``hf_hub_download`` is about to replace. BOTH directions, unlike the size
+ pairing (refusals only): a stale allow hands csm bytes to a media loader after the download
+ and the teardown, the very outcome this preflight exists to prevent. An unknown revision or
+ an unreadable live header keeps *arch*, so an offline host never flips a verdict, and no
+ CACHED copy means no revision to be behind -- an uncached remote pick and an On Device file
+ both skip the HEAD. Memoised by the caller: one HEAD per cached copy per token per session."""
+ cached = _snapshot_revision(local)
+ if cached is None:
+ return arch
+ if not allow_network:
+ # A cache-only caller cannot wear the HEAD; the caller declines to memoise this answer,
+ # so the next one that CAN reach the Hub still revalidates it.
+ return arch
+ live = _hub_revision(repo_id, gguf_filename, token)
+ if live is None or live == cached:
+ return arch
+ refreshed = _arch_from_prefix(_read_gguf_header(repo_id, gguf_filename, token), gguf_filename)
+ # A re-read that said nothing -- failed range request, or an unparseable new header -- keeps
+ # the verdict we had rather than replacing it with silence. Failing open on an UNKNOWN pick is
+ # the contract; throwing away a known one let a csm file through on a dropped connection.
+ return refreshed if refreshed is not None else arch
+
+
+def _speech_probe_architecture(
+ repo_id: str,
+ gguf_filename: str,
+ hf_token: Optional[str],
+ allow_network: bool = True,
+) -> Optional[str]:
+ """``general.architecture`` of a pick, from a cached copy or one range request.
+
+ Keyed like the inner-dim memo beside it, for the same two reasons: the token fingerprint,
+ because a probe that failed on an expired credential caches "no verdict" and the retry with a
+ working one would read that back and let the speech file through to the download; the file
+ identity, because a checkpoint replaced under the same name is a different checkpoint."""
+ token = (hf_token or "").strip() or None
+ # Resolved BEFORE the memo is consulted, because the file's identity is part of the key.
+ local = _local_gguf_path(repo_id, gguf_filename)
+ key = (repo_id, gguf_filename, _token_fingerprint(token), _file_identity(local))
+ with _CACHE_LOCK:
+ memo = _SPEECH_ARCH_CACHE.get(key)
+ if memo is not None:
+ arch, expires_at = memo
+ if expires_at is None or time.monotonic() < expires_at:
+ return arch
+ del _SPEECH_ARCH_CACHE[key]
+ if local is None and not allow_network:
+ # Memo or local header only, as the size pairing does. Nothing is memoised, so the next
+ # caller that CAN wait still gets a real answer instead of this one's silence.
+ return None
+ prefix = (
+ _read_local_header(local)
+ if local
+ else _shared_gguf_header(repo_id, gguf_filename, token, local)
+ )
+ arch = _arch_from_prefix(prefix, gguf_filename)
+ # Inside the memo, so a republished checkpoint is caught in either direction and the HEAD is
+ # spent once per cached copy rather than on every pick.
+ arch = _revalidated_speech_arch(repo_id, gguf_filename, token, local, arch, allow_network)
+ # A cached copy whose revision check was skipped is only HALF an answer, so it must not be
+ # memoised: the network-allowed caller behind it would read this back and never revalidate.
+ if not allow_network and _snapshot_revision(local) is not None:
+ return arch
+ with _CACHE_LOCK:
+ if len(_SPEECH_ARCH_CACHE) >= _SPEECH_ARCH_CACHE_MAX:
+ _SPEECH_ARCH_CACHE.clear()
+ # Permanent only for a true On Device file, which has no revision to be behind. A cached
+ # Hub snapshot ages out like an uncached pick: its entry memoises a revision check, and
+ # holding that forever would ask the Hub exactly once per file per process.
+ permanent = local is not None and _snapshot_revision(local) is None
+ _SPEECH_ARCH_CACHE[key] = (
+ arch,
+ None if permanent else time.monotonic() + _SPEECH_REMOTE_TTL_SECONDS,
+ )
+ return arch
+
+
+def speech_pick_refusal(
+ repo_id: str,
+ gguf_filename: Optional[str],
+ hf_token: Optional[str] = None,
+ allow_network: bool = True,
+) -> Optional[str]:
+ """Why this diffusion pick cannot load, when it names a speech GGUF, else None.
+
+ A media pick names its file, and ``detect_family_for_pick`` resolves the family from the FOLDER
+ rather than that name, so a csm quant sitting beside a FLUX denoiser answers flux.1: the pick
+ pulls the checkpoint and tears the resident pipeline down before the loader finds out.
+
+ Metadata only, like the FLUX.2 pairing above: a cached copy answers with no request, else one
+ range request. Fails open on everything -- no filename, an unreadable header, an offline host,
+ a server that ignores Range -- because refusing a pick that works is worse than the download
+ this saves.
+ """
+ # A ".gguf" name only, as the size pairing does: a single_file pick names a .safetensors,
+ # which has no GGUF header, and a range request to learn that on every such load is waste.
+ if not repo_id or not gguf_filename or not gguf_filename.lower().endswith(".gguf"):
+ return None
+ arch = _speech_probe_architecture(repo_id, gguf_filename, hf_token, allow_network)
+ if is_speech_gguf_architecture(arch):
+ # Named only when the header carried an identifier: the Mimi vocoder puts a whole
+ # sentence in general.architecture, and quoting that back reads as gibberish.
+ named = f"{arch} " if arch in _SPEECH_GGUF_ARCHS else ""
+ return (
+ f"'{os.path.basename(gguf_filename)}' is a {named}speech checkpoint, which no image "
+ "or video backend can decode. Pick one of this folder's media GGUFs instead."
+ )
+ return None
+
+
+def assert_pick_is_not_speech(
+ repo_id: str,
+ gguf_filename: Optional[str],
+ hf_token: Optional[str] = None,
+ allow_network: bool = True,
+) -> None:
+ """Refuse a speech GGUF pick before anything is downloaded or unloaded.
+
+ ``ValueError`` like the FLUX.2 assert: /images/load maps it to 400 and the download-plan
+ catches it, whereas a RuntimeError escapes the plan as a bare 500."""
+ reason = speech_pick_refusal(repo_id, gguf_filename, hf_token, allow_network)
+ if reason is not None:
+ raise ValueError(reason)
+
+
def assert_flux2_pick_compatible(
fam: Any,
repo_id: str,
@@ -383,3 +643,5 @@ def _reset_inner_dim_cache() -> None:
"""Drop the memoised header probes. Tests only."""
with _CACHE_LOCK:
_INNER_DIM_CACHE.clear()
+ _SPEECH_ARCH_CACHE.clear()
+ _HEADER_PREFIX_CACHE.clear()
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index 56dbf83d765..53ddc2f490e 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -366,6 +366,14 @@ from state.tool_approvals import (
)
from utils.paths.path_utils import _is_wsl, is_appledouble_metadata
+# The leaf module, not utils.models: importing anything from that package runs its __init__,
+# which pulls in model_config and therefore PyYAML. This is the chat backend, imported wherever
+# Studio's Python is, so it must not make the whole models package a hard import dependency.
+from utils.gguf_archs import (
+ SPEECH_GGUF_ARCHS as _SPEECH_GGUF_ARCHS,
+ is_speech_gguf_architecture,
+)
+
logger = get_logger(__name__)
# Floor for a GGUF TTS read, scaled by requested tokens at the call site. This backend
@@ -12325,6 +12333,9 @@ class LlamaCppBackend:
_DIFFUSION_ARCHES = (
_IMAGE_ARCHES | _AMBIGUOUS_IMAGE_ARCHES | _VIDEO_ARCHES | _UNRUNNABLE_MEDIA_ARCHES
)
+ # TTS archs llama.cpp cannot load (CSM support is only on an unmerged upstream branch). One
+ # shared definition, so this gate and the listing classifier cannot drift.
+ _SPEECH_ARCHES = _SPEECH_GGUF_ARCHS
# Not architectures: the literal placeholders gguf-connector writes into
# general.architecture for its diffusion GGUFs (gguf-org/flux2-dev-gguf and
@@ -12426,13 +12437,25 @@ class LlamaCppBackend:
# so the remote probe's prefix can carry it even where bulkier later metadata leaves
# the walk unfinished. The walk still gates the no-architecture fallback below, the
# one case where an incomplete read is indistinguishable from declaring nothing.
- if arch not in self._DIFFUSION_ARCHES and not getattr(self, "_gguf_header_parsed", False):
+ if (
+ arch not in self._DIFFUSION_ARCHES
+ and not is_speech_gguf_architecture(arch)
+ and not getattr(self, "_gguf_header_parsed", False)
+ ):
return None
if arch in self._PLACEHOLDER_ARCHES:
# Names no architecture, so treat it like a GGUF that declares none and let the
# name-based branch below name a page.
arch = ""
if arch:
+ if is_speech_gguf_architecture(arch):
+ # Points at the Transformers build, not this file on the Audio page: that page
+ # cannot list a speech GGUF either, so it would promise a row that is not there.
+ return (
+ "This is a text-to-speech GGUF, which llama.cpp cannot load: it has no "
+ "CSM decoder. Run the model's Transformers build (for example "
+ "unsloth/csm-1b) from the Audio page instead."
+ )
if arch in self._UNRUNNABLE_MEDIA_ARCHES:
return (
f"This is an image / video generation GGUF (architecture '{arch}'), "
@@ -13209,6 +13232,14 @@ class LlamaCppBackend:
arch_match = re.search(r"unknown model architecture:\s*'([^']+)'", lowered)
if arch_match:
arch = arch_match.group(1)
+ if is_speech_gguf_architecture(arch):
+ # Same wording rule as the pre-launch refusal above: name the build that runs,
+ # not a page this file will not appear on.
+ return (
+ f"'{arch}' is a text-to-speech GGUF, which llama-server cannot run as a "
+ "chat/completion model. Run the model's Transformers build (for example "
+ "unsloth/csm-1b) from Unsloth's Audio page instead."
+ )
if arch in LlamaCppBackend._UNRUNNABLE_MEDIA_ARCHES:
return (
f"'{arch}' is an image / video generation GGUF, which llama-server "
diff --git a/studio/backend/core/inference/sd_cpp_backend.py b/studio/backend/core/inference/sd_cpp_backend.py
index 98442283cdb..88383ed2b33 100644
--- a/studio/backend/core/inference/sd_cpp_backend.py
+++ b/studio/backend/core/inference/sd_cpp_backend.py
@@ -1015,6 +1015,17 @@ def _with_mirrors(repo_ids) -> tuple[str, ...]:
return tuple(dict.fromkeys(out))
+def _assert_pick_is_not_speech(
+ repo_id: str,
+ gguf_filename: Optional[str],
+ hf_token: Optional[str] = None,
+ allow_network: bool = True,
+) -> None:
+ """The shared speech refusal, imported lazily so this module keeps its import cost."""
+ from .diffusion_compat import assert_pick_is_not_speech
+ assert_pick_is_not_speech(repo_id, gguf_filename, hf_token, allow_network)
+
+
class SdCppDiffusionBackend:
"""Native sd.cpp backend with the diffusers ``DiffusionBackend`` method surface."""
@@ -1374,6 +1385,11 @@ class SdCppDiffusionBackend:
# offline load asks it the way begin_load does: memo or local header or nothing. A
# None here only falls back to the filename heuristic for the encoder pick, and a
# cache-only load can fetch nothing the heuristic did not already have.
+ # The speech verdict lands here rather than in begin_load, which is offline-only by
+ # contract; before _asset_specs, so the refusal precedes any fetch.
+ _assert_pick_is_not_speech(
+ repo_id, gguf_filename, hf_token, allow_network = not local_files_only
+ )
inner_dim = self._flux2_inner_dim(
repo_id, gguf_filename, fam, hf_token, allow_network = not local_files_only
)
@@ -1749,6 +1765,8 @@ class SdCppDiffusionBackend:
if fam is None or not family_sd_cpp_supported(fam):
# Unreachable through the route, but a direct caller gets the same message begin_load would raise.
raise ValueError(f"'{repo_id}' has no native sd.cpp asset mapping.")
+ # Same reason as the diffusers plan: this is what stages the download.
+ _assert_pick_is_not_speech(repo_id, gguf_filename, hf_token)
specs = self._asset_specs(
repo_id,
@@ -1882,6 +1900,7 @@ class SdCppDiffusionBackend:
model_kind: Optional[str] = None,
base_repo: Optional[str] = None,
hf_token: Optional[str] = None,
+ allow_network: bool = True, # noqa: ARG002 -- signature parity; no speech probe here
) -> None:
"""The companion refusal ``_run_load`` makes, run by the route BEFORE it takes the GPU.
diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.py
index 35e64bc8db2..12a948b90db 100644
--- a/studio/backend/core/inference/video.py
+++ b/studio/backend/core/inference/video.py
@@ -461,6 +461,17 @@ def _scheduler_step_progress(pipe: Any, on_step: Any):
scheduler.step = original
+def _assert_pick_is_not_speech(
+ repo_id: str,
+ gguf_filename: Optional[str],
+ hf_token: Optional[str] = None,
+ allow_network: bool = True,
+) -> None:
+ """The shared speech refusal, imported lazily so this module keeps its import cost."""
+ from .diffusion_compat import assert_pick_is_not_speech
+ assert_pick_is_not_speech(repo_id, gguf_filename, hf_token, allow_network)
+
+
def _detect_load_family(
repo_id: str, gguf_filename: Optional[str], family_override: Optional[str]
) -> Optional[VideoFamily]:
@@ -1391,6 +1402,14 @@ class VideoBackend:
fam = _detect_load_family(
kwargs["repo_id"], kwargs.get("gguf_filename"), kwargs.get("family_override")
)
+ # Also on the worker, which a direct begin_load reaches without a plan. Here rather
+ # than in validate_load_request, which is network-free by contract.
+ _assert_pick_is_not_speech(
+ kwargs["repo_id"],
+ kwargs.get("gguf_filename"),
+ kwargs.get("hf_token"),
+ allow_network = not local_files_only,
+ )
kind = resolve_video_model_kind(kwargs.get("gguf_filename"), kwargs.get("model_kind"))
from .video_minimax_h3 import is_h3_native
@@ -2733,6 +2752,9 @@ class VideoBackend:
from huggingface_hub import HfApi
fam = _detect_load_family(repo_id, gguf_filename, family_override)
+ # _detect_load_family resolves from the REPO id first, so a mixed repo answers its media
+ # family for every file in it, a csm quant included. Refuse before the plan stages a byte.
+ _assert_pick_is_not_speech(repo_id, gguf_filename, hf_token)
kind = resolve_video_model_kind(gguf_filename, model_kind)
from .video_minimax_h3 import is_h3_native
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 63678b5c8d9..867ea5a0ae0 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -25782,6 +25782,7 @@ async def load_diffusion_model_gated(
model_kind = kind,
base_repo = request.base_repo,
hf_token = request.hf_token,
+ allow_network = user_initiated,
)
# Last refusal before anything is torn down: a gated/unreadable companion repo. The download
@@ -25822,6 +25823,19 @@ async def load_diffusion_model_gated(
transformer_quant = request.transformer_quant,
text_encoder_quant = request.text_encoder_quant,
)
+ # And the same for a speech GGUF picked out of a mixed image repo. Both engines assert it
+ # too, but the diffusers copy runs inside acquire_for and the native one on its worker,
+ # so either refusal arrives after chat was evicted and an engine switch unloaded the
+ # resident model. Off-thread for the header read; cache-only unless the user asked.
+ from core.inference.diffusion_compat import assert_pick_is_not_speech
+
+ await asyncio.to_thread(
+ assert_pick_is_not_speech,
+ request.model_path,
+ request.gguf_filename,
+ request.hf_token,
+ user_initiated,
+ )
preflighted = None
if pending_name is not None and (needs_gpu or pending_name != active_engine_name()):
preflighted = engine_for(pending_name)
diff --git a/studio/backend/routes/models.py b/studio/backend/routes/models.py
index 776082c93a1..6d6cd4036a9 100644
--- a/studio/backend/routes/models.py
+++ b/studio/backend/routes/models.py
@@ -220,6 +220,10 @@ from models.responses import (
EmbeddingCheckResponse,
)
from utils.paths.path_utils import is_appledouble_metadata
+from utils.gguf_archs import (
+ SPEECH_GGUF_ARCHS,
+ is_speech_gguf_architecture,
+)
router = APIRouter()
logger = get_logger(__name__)
@@ -4085,6 +4089,12 @@ _VIDEO_GEN_TASK = "text-to-video"
# Task tag for the archs above; mirrored by the frontend NON_CHAT_TASKS gate.
_UNSUPPORTED_DIFFUSION_TASK = "image-diffusion-unsupported"
+# TTS-only GGUF archs llama.cpp cannot load, tagged speech so the chat picker keeps them out of
+# llama-server. One shared definition rather than a copy per layer: the chat gate, this classifier
+# and the media preflight all have to agree.
+_SPEECH_GGUF_ARCHS = SPEECH_GGUF_ARCHS
+_SPEECH_TASK = "text-to-speech"
+
# The two denoiser partitions, by the filename prefix the loader itself validates against
# (``video_minimax_h3``). These GGUFs carry no architecture metadata, so the NAME is the only
@@ -4195,6 +4205,8 @@ def _arch_to_task(arch: Optional[str], name_hints: tuple[Optional[str], ...] = (
else _UNSUPPORTED_DIFFUSION_TASK
)
return _UNSUPPORTED_DIFFUSION_TASK
+ if is_speech_gguf_architecture(a):
+ return _SPEECH_TASK
if a in _DIFFUSION_GGUF_ARCHS:
# Third gate, mirroring the cached-repo picker: a family no engine here can build can only fail.
if not _gguf_family_buildable(name_hints):
@@ -4317,6 +4329,12 @@ def _gguf_folder_task(
# Trimmed back to the cap as it fills: a folder holding thousands of GGUFs should not cost
# a list of thousands of paths to read 64 of them.
scored: list[tuple[tuple[str, str], Path]] = []
+ # Recorded as the tail is dropped, never inferred from `scored` afterwards: the trimming
+ # branch cuts back to the cap, so a folder that overflows and then ends leaves exactly
+ # `_MAX_TASK_CLASSIFY_GGUFS` entries behind, indistinguishable from a folder that fit.
+ # Reading that as a complete scan is what would let 129 files answer speech off their
+ # first 64 and hide the runnable sibling in the discarded tail.
+ overflowed = False
for path in _iter_gguf_paths(root, deadline):
name = path.name
if _is_mmproj_filename(name) or _is_trailing_split_shard(name):
@@ -4325,29 +4343,61 @@ def _gguf_folder_task(
if len(scored) > _MAX_TASK_CLASSIFY_GGUFS * 2:
scored.sort(key = lambda item: item[0])
del scored[_MAX_TASK_CLASSIFY_GGUFS:]
+ overflowed = True
scored.sort(key = lambda item: item[0])
paths = [path for _, path in scored[:_MAX_TASK_CLASSIFY_GGUFS]]
+ # Whether every candidate in the folder made it into `paths`. The walk gives up at its own
+ # deadline and the cap drops the tail, so either can leave a sibling unseen.
+ complete = (
+ not overflowed
+ and len(scored) <= _MAX_TASK_CLASSIFY_GGUFS
+ and time.monotonic() < deadline
+ )
except Exception:
return None
unsupported: Optional[str] = None
+ speech: Optional[str] = None
read_deadline = time.monotonic() + _TASK_CLASSIFY_READ_SECONDS
for index, path in enumerate(paths):
# The first read always happens, so a folder still classifies from its first ordered file
# even where the budget was gone before this loop started.
if index and time.monotonic() >= read_deadline:
+ complete = False
break
try:
task = _arch_to_task(_gguf_architecture(str(path)), name_hints = id_hints + (path.name,))
except Exception:
+ # Unread, so unranked: this file might have been the runnable sibling, and speech
+ # cannot rest on a folder we only partly read.
+ complete = False
+ continue
+ if task is None:
+ # Same as the read that raised: a truncated header gives no architecture, and
+ # `_arch_to_task` answers None rather than guessing.
+ complete = False
continue
if task in _LOADABLE_MEDIA_GGUF_TASKS:
return task
- if task == _UNSUPPORTED_DIFFUSION_TASK:
+ # Speech ranks below everything else runnable, not just below the loadable media archs:
+ # nothing here runs a llama-csm GGUF, so answering speech while a sibling is loadable
+ # hides that sibling. Ranking it with the unsupported diffusion archs saved a runnable
+ # image/video checkpoint but not a chat one -- a chat GGUF lands in `fallback`, which
+ # `unsupported` outranked, so a csm + qwen3 folder answered speech and the arch-task gate
+ # hid the qwen3. Last resort only, so a speech-only folder still tags speech.
+ if task == _SPEECH_TASK:
+ if speech is None:
+ speech = task
+ elif task == _UNSUPPORTED_DIFFUSION_TASK:
if unsupported is None:
unsupported = task
elif task is not None and fallback is None:
fallback = task
- return unsupported or fallback
+ # Speech only when the ranking above saw the whole folder. It is the one answer that HIDES a
+ # row rather than filing it, so a walk that gave up at its deadline, a folder past the cap, or
+ # a read budget spent after the csm quant sorted first would otherwise hide the runnable
+ # sibling it never reached. Every other verdict is safe on a partial read: the worst case is a
+ # row filed on the wrong page, not one the user cannot find at all.
+ return unsupported or fallback or (speech if complete else None)
def _repo_gguf_task(repo_info) -> Optional[str]:
diff --git a/studio/backend/routes/video.py b/studio/backend/routes/video.py
index 2ca5940619a..8ffdfe9cf1b 100644
--- a/studio/backend/routes/video.py
+++ b/studio/backend/routes/video.py
@@ -282,6 +282,20 @@ async def load_video_model_gated(
memory_mode = request.memory_mode,
gpu_ordinal = gpu_ordinal,
)
+ # Same bar again, for a speech GGUF picked out of a mixed video repo. The backend's own
+ # assertion runs on the load worker, INSIDE acquire_for, so a refusal there arrives
+ # having already evicted the chat model this gate exists to preserve. Off-thread because
+ # the probe reads a header, and cache-only when the load is not user-initiated, matching
+ # the locality promise begin_load makes below.
+ from core.inference.diffusion_compat import assert_pick_is_not_speech
+
+ await asyncio.to_thread(
+ assert_pick_is_not_speech,
+ request.model_path,
+ request.gguf_filename,
+ request.hf_token,
+ user_initiated,
+ )
# Take the GPU from chat only for a non-CPU load. Release stale VIDEO ownership on a CPU load (owner-guarded no-op).
device = await asyncio.to_thread(lambda: resolve_diffusion_device_target().device)
diff --git a/studio/backend/tests/test_cached_gguf_routes.py b/studio/backend/tests/test_cached_gguf_routes.py
index a63a58aabf8..30ccdf7fffc 100644
--- a/studio/backend/tests/test_cached_gguf_routes.py
+++ b/studio/backend/tests/test_cached_gguf_routes.py
@@ -3,6 +3,7 @@
import asyncio
import json
+import os
import sys
import threading
import time
@@ -2807,6 +2808,14 @@ def test_arch_to_task_hides_unsupported_diffusion_from_chat():
assert not missing, f"diffusion archs would still show in chat: {missing}"
+def test_arch_to_task_tags_speech_archs_as_speech():
+ # llama.cpp cannot load these at all, so chat must not claim them.
+ for arch in models_route._SPEECH_GGUF_ARCHS:
+ assert models_route._arch_to_task(arch) == models_route._SPEECH_TASK
+ from core.inference.llama_cpp import LlamaCppBackend
+ assert models_route._SPEECH_GGUF_ARCHS == set(LlamaCppBackend._SPEECH_ARCHES)
+
+
def test_arch_to_task_tags_the_h3_gguf_bundle_as_video():
# The published MiniMax-H3 GGUFs carry kv_count 0, so general.architecture is absent and the
# arch read alone leaves the downloaded repo without a task -- dropped from the Video picker's
@@ -5195,6 +5204,159 @@ def test_the_classify_order_is_the_same_wherever_the_folder_lives(tmp_path):
)
+def test_a_runnable_media_checkpoint_outranks_a_speech_gguf(tmp_path):
+ """Nothing loads a ``llama-csm`` GGUF, so returning speech the moment it sorts first would
+ hide the runnable denoiser beside it."""
+ folder = tmp_path / "mixed-speech"
+ # "csm" sorts before "flux" and cannot load here; the FLUX denoiser beside it can.
+ _arch_gguf(folder / "csm-1b-Q4_0.gguf", "llama-csm")
+ _arch_gguf(folder / "flux1-dev-Q4_K_M.gguf", "flux")
+ assert models_route._gguf_folder_task(folder, ("someone/mixed-GGUF",)) == "text-to-image"
+
+ # Nothing runnable beside it: still speech, so the chat picker keeps leaving it out.
+ speech = tmp_path / "speech-only"
+ _arch_gguf(speech / "csm-1b-Q4_0.gguf", "llama-csm")
+ assert (
+ models_route._gguf_folder_task(speech, ("someone/csm-GGUF",)) == models_route._SPEECH_TASK
+ )
+
+
+def test_a_runnable_chat_checkpoint_outranks_a_speech_gguf(tmp_path):
+ """Ranking speech with the unsupported diffusion archs saved a runnable image/video sibling
+ but not a chat one: a chat GGUF answers ``fallback``, which ``unsupported`` outranked, so a
+ csm + qwen3 folder tagged speech and the gate hid the qwen3. Speech is the last resort now."""
+ folder = tmp_path / "mixed-chat-speech"
+ # "csm" sorts first and cannot load here; the qwen3 chat checkpoint beside it can.
+ _arch_gguf(folder / "csm-1b-Q4_0.gguf", "llama-csm")
+ _arch_gguf(folder / "qwen3-8b-Q4_K_M.gguf", "llama")
+ assert models_route._gguf_folder_task(folder, ("someone/mixed-GGUF",)) == "text-generation"
+
+ # Unsupported diffusion still outranks the text fallback; the demotion did not change that.
+ diffusion = tmp_path / "mixed-diffusion-speech"
+ _arch_gguf(diffusion / "csm-1b-Q4_0.gguf", "llama-csm")
+ _arch_gguf(diffusion / "sd3-Q4_0.gguf", "sd3")
+ assert (
+ models_route._gguf_folder_task(diffusion, ("someone/sd3-GGUF",))
+ == models_route._UNSUPPORTED_DIFFUSION_TASK
+ )
+
+
+def test_a_truncated_classification_never_answers_speech(tmp_path, monkeypatch):
+ """Speech is the one verdict that HIDES a row, so it may only be given after the whole folder
+ was seen. Each of the three ways this walk gives up early -- the walk deadline, the 64-file
+ cap, and the read budget -- could otherwise stop right after the csm quant that sorts first and
+ hide the runnable sibling it never reached, which is worse than the mis-filing it prevents."""
+ folder = tmp_path / "mixed-chat-speech"
+ _arch_gguf(folder / "csm-1b-Q4_0.gguf", "llama-csm")
+ _arch_gguf(folder / "qwen3-8b-Q4_K_M.gguf", "llama")
+ assert models_route._gguf_folder_task(folder, ("someone/mixed-GGUF",)) == "text-generation"
+
+ # The read budget gone before the second file: the first read always happens, so the csm quant
+ # is the only verdict in hand.
+ monkeypatch.setattr(models_route, "_TASK_CLASSIFY_READ_SECONDS", -1.0)
+ assert models_route._gguf_folder_task(folder, ("someone/mixed-GGUF",)) is None
+ monkeypatch.undo()
+
+ # The walk giving up at its deadline with only the csm quant yielded.
+ def truncating(root, deadline = None):
+ yield folder / "csm-1b-Q4_0.gguf"
+ while deadline is not None and time.monotonic() < deadline:
+ time.sleep(0.01)
+
+ monkeypatch.setattr(models_route, "_iter_gguf_paths", truncating)
+ assert models_route._gguf_folder_task(folder, ("someone/mixed-GGUF",)) is None
+ monkeypatch.undo()
+
+ # The cap dropping the tail the runnable sibling sorts into.
+ capped = tmp_path / "capped"
+ for index in range(models_route._MAX_TASK_CLASSIFY_GGUFS + 4):
+ _arch_gguf(capped / f"aaa-{index:03d}-csm.gguf", "llama-csm")
+ _arch_gguf(capped / "zzz-qwen3-Q4_K_M.gguf", "llama")
+ assert models_route._gguf_folder_task(capped, ("someone/capped-GGUF",)) is None
+
+ # A speech-only folder read in full still tags speech, so the picker keeps leaving it out.
+ speech = tmp_path / "speech-only"
+ _arch_gguf(speech / "csm-1b-Q4_0.gguf", "llama-csm")
+ assert (
+ models_route._gguf_folder_task(speech, ("someone/csm-GGUF",)) == models_route._SPEECH_TASK
+ )
+
+
+def test_a_folder_trimmed_exactly_back_to_the_cap_never_answers_speech(tmp_path):
+ """The overflow that leaves the candidate list looking untouched still hides a sibling.
+
+ Candidates are trimmed only once the list passes twice the cap, and the trim cuts it back to
+ the cap exactly. A folder whose walk ENDS on that trim therefore finishes holding precisely
+ ``_MAX_TASK_CLASSIFY_GGUFS`` entries -- the same length a folder that fit would leave -- so
+ completeness read off that length says the whole folder was seen when 65 files were thrown
+ away. Speech is the one verdict that hides the row, so the folder answers text-to-speech off
+ its first 64 csm quants and the runnable qwen3 sorted into the discarded tail becomes
+ unreachable in every picker.
+
+ The boundary repeats: each later trim lands on the same length, hence the second size."""
+ cap = models_route._MAX_TASK_CLASSIFY_GGUFS
+ # 2 * cap + 1 is the count that trips the trim on its final candidate; + 1 more trim's worth
+ # is the next one that does, confirming this is a recurring boundary and not one bad number.
+ for total in (2 * cap + 1, 3 * cap + 2):
+ folder = tmp_path / f"trimmed-{total}"
+ # Every speech quant sorts ahead of the chat one, so the retained 64 are all csm and the
+ # runnable sibling is exactly what the trim discards.
+ for index in range(total - 1):
+ _arch_gguf(folder / f"aaa-{index:04d}-csm.gguf", "llama-csm")
+ _arch_gguf(folder / "zzz-qwen3-Q4_K_M.gguf", "llama")
+ assert models_route._gguf_folder_task(folder, ("someone/trimmed-GGUF",)) is None, total
+
+
+def test_a_sibling_whose_header_will_not_read_keeps_speech_off_the_folder(tmp_path):
+ """A candidate that never got classified might have been the runnable one.
+
+ ``_gguf_architecture`` answers None on a truncated or unreadable header and ``_arch_to_task``
+ answers None rather than guessing, while a read that raises is skipped outright. Neither used
+ to clear ``complete``, so a folder holding a readable csm quant beside a sibling it could not
+ classify answered text-to-speech with full confidence, and the arch-task gate then hid the row
+ the unread sibling was on. The scan saw the file; it just never learned what it was, which is
+ the same standing as a file the walk never reached."""
+ for label, write_sibling in (
+ ("truncated", lambda p: p.write_bytes(b"GGUF\x03\x00\x00\x00")),
+ ("empty", lambda p: p.write_bytes(b"")),
+ ("not-a-gguf", lambda p: p.write_bytes(b"just some bytes, no magic at all")),
+ ):
+ folder = tmp_path / f"unreadable-{label}"
+ _arch_gguf(folder / "aaa-csm.gguf", "llama-csm")
+ sibling = folder / "zzz-qwen3-Q4_K_M.gguf"
+ sibling.parent.mkdir(parents = True, exist_ok = True)
+ write_sibling(sibling)
+ assert models_route._gguf_folder_task(folder, ("someone/mixed-GGUF",)) is None, label
+
+ # The control: with the sibling readable and runnable, the folder still files as chat, so the
+ # fix withholds speech on an unread sibling rather than withholding it always.
+ readable = tmp_path / "readable"
+ _arch_gguf(readable / "aaa-csm.gguf", "llama-csm")
+ _arch_gguf(readable / "zzz-qwen3-Q4_K_M.gguf", "llama")
+ assert models_route._gguf_folder_task(readable, ("someone/mixed-GGUF",)) == "text-generation"
+
+ # And a speech-ONLY folder, every file of it read, still tags speech.
+ speech_only = tmp_path / "speech-only"
+ _arch_gguf(speech_only / "aaa-csm.gguf", "llama-csm")
+ _arch_gguf(speech_only / "bbb-csm.gguf", "llama-csm")
+ assert models_route._gguf_folder_task(speech_only, ("someone/csm-GGUF",)) == "text-to-speech"
+
+
+def test_only_a_read_architecture_ever_answers_speech():
+ """The frontend gate is fail-CLOSED on a text-to-speech tag while every backend probe fails
+ open, and that is only safe because the tag can come from nothing but ``general.architecture``.
+ A name hint reaching this verdict would hide the runnable TTS GGUFs (Orpheus, OuteTTS) whose
+ files are named for a family but declare a plain ``llama`` arch."""
+ hints = ("unsloth/csm-1b-GGUF", "csm-1b-Q4_0.gguf", "sesame-csm", "text-to-speech")
+ assert models_route._arch_to_task("llama-csm") == models_route._SPEECH_TASK
+ for arch in (None, "", "llama", "qwen3", "flux"):
+ assert models_route._arch_to_task(arch, name_hints = hints) != models_route._SPEECH_TASK
+ # Orpheus ships as a llama GGUF, so it must stay a chat row for the gate to leave it alone.
+ assert models_route._arch_to_task("llama", name_hints = ("unsloth/orpheus-3b-0.1-ft-GGUF",)) == (
+ "text-generation"
+ )
+
+
def test_a_buildable_denoiser_outranks_an_arch_the_backend_cannot_assemble(tmp_path):
"""``_UNSUPPORTED_DIFFUSION_TASK`` hides a row from the chat picker AND from the Images and
Video ones, so a folder holding both a checkpoint this backend can build and one it cannot has
@@ -5651,3 +5813,59 @@ def test_the_listing_probe_hides_a_class_the_installed_diffusers_predates(monkey
installed[0] = "0.33.0"
assert family_pipeline_available(wan) is True
assert "diffusers" not in sys.modules, "the listing probe imported diffusers"
+
+
+# ── the architectures published CSM bundles actually declare ────────────────────
+
+# ggml-org/sesame-csm-1b-GGUF ships its Mimi vocoder with a SENTENCE where the architecture
+# identifier belongs. Verified against the live repo, not invented.
+_VOCODER_ARCH = "this model cannot be used as LLM, use it via --model-vocoder in TTS examples"
+
+
+def test_every_published_csm_spelling_classifies_as_speech():
+ """The gate keyed on "llama-csm" alone, which is one publisher's spelling. Every CSM GGUF
+ on the Hub uses a different one, so the chat picker offered all of them to llama-server."""
+ for arch in ("llama-csm", "csm", "csm-tts", "mimi", "LLAMA-CSM", " csm-tts "):
+ assert models_route._arch_to_task(arch) == models_route._SPEECH_TASK, arch
+ # The vocoder's sentence, and a reworded copy of it.
+ for arch in (_VOCODER_ARCH, "cannot be used as LLM"):
+ assert models_route._arch_to_task(arch) == models_route._SPEECH_TASK, arch
+ # Neighbours that must keep running: Orpheus and OuteTTS ship as plain llama GGUFs.
+ for arch in ("llama", "qwen3", "csmith", "mimic", "flux"):
+ assert models_route._arch_to_task(arch) != models_route._SPEECH_TASK, arch
+
+
+def test_the_real_sesame_bundle_is_classified_as_speech(tmp_path):
+ """The repo this feature was written for. "kyutai-mimi" sorts before both "sesame-" files,
+ and its sentence-shaped architecture used to answer text-generation, which took `fallback`
+ and outranked the two llama-csm results: the whole bundle was offered as a chat model."""
+ bundle = tmp_path / "sesame-csm-1b-GGUF"
+ _arch_gguf(bundle / "kyutai-mimi.gguf", _VOCODER_ARCH)
+ _arch_gguf(bundle / "sesame-csm-backbone.gguf", "llama-csm")
+ _arch_gguf(bundle / "sesame-csm-decoder.gguf", "llama-csm")
+ assert models_route._gguf_folder_task(bundle, ("ggml-org/sesame-csm-1b-GGUF",)) == (
+ models_route._SPEECH_TASK
+ )
+
+ # The other published layouts, each with its own spelling.
+ for repo, files in (
+ ("cartesia/sesame-csm-1b-gguf", {"q8.gguf": "csm"}),
+ ("cstr/csm-1b-GGUF", {"csm-1b-q8_0.gguf": "csm-tts"}),
+ ("johnbenac/sesame-csm-1b-GGUF-encoder", {"kyutai-mimi.gguf": "mimi"}),
+ ):
+ folder = tmp_path / repo.replace("/", "__")
+ for name, arch in files.items():
+ _arch_gguf(folder / name, arch)
+ assert models_route._gguf_folder_task(folder, (repo,)) == models_route._SPEECH_TASK, repo
+
+
+def test_a_speech_arch_is_the_same_answer_in_every_layer():
+ """The listing classifier, the chat refusal and the media preflight held three separate
+ copies of the set; they read one definition now."""
+ from core.inference.diffusion_compat import _SPEECH_GGUF_ARCHS as compat_archs
+ from core.inference.llama_cpp import LlamaCppBackend
+ from utils.gguf_archs import SPEECH_GGUF_ARCHS
+
+ assert models_route._SPEECH_GGUF_ARCHS is SPEECH_GGUF_ARCHS
+ assert compat_archs is SPEECH_GGUF_ARCHS
+ assert LlamaCppBackend._SPEECH_ARCHES is SPEECH_GGUF_ARCHS
diff --git a/studio/backend/tests/test_diffusion_compat_preflight.py b/studio/backend/tests/test_diffusion_compat_preflight.py
index 4363b247522..4793d8b5391 100644
--- a/studio/backend/tests/test_diffusion_compat_preflight.py
+++ b/studio/backend/tests/test_diffusion_compat_preflight.py
@@ -16,6 +16,7 @@ and a stubbed ``hf_hub_download`` fails the test if anything tries to fetch a wh
from __future__ import annotations
+import inspect
import threading
import time
import types
@@ -1001,3 +1002,705 @@ def test_an_on_device_checkpoint_is_never_revalidated(monkeypatch, tmp_path):
assert reason is not None and "klein-9B" in reason
assert requests == []
+
+
+# ── Speech picks ───────────────────────────────────────────────────────────────
+# The variant listing drops the speech quants whose bytes are on disk, but an UNDOWNLOADED one
+# has none to read and stays offered -- and detect_family_for_pick answers from the folder name,
+# so a csm file beside a FLUX denoiser resolves to flux.1 and reaches this loader as its own.
+
+CSM_REPO = "someone/mixed-media-GGUF"
+CSM_FILE = "csm-1b-Q4_0.gguf"
+DENOISER_FILE = "flux1-dev-Q4_K_M.gguf"
+
+
+def _arch_header(architecture: str) -> bytes:
+ """A minimal GGUF prefix carrying just ``general.architecture``.
+
+ Hand-rolled rather than via ``GGUFWriter`` like the size-pairing fixtures: this probe reads a
+ single KV pair, and writing it by hand is what ``test_cached_gguf_routes.py`` does for the
+ listing-side gate, so both ends of this feature are pinned against the same bytes."""
+ import struct
+
+ def string(value: str) -> bytes:
+ data = value.encode()
+ return struct.pack("<Q", len(data)) + data
+
+ return (
+ struct.pack("<IIQQ", 0x46554747, 3, 0, 1)
+ + string("general.architecture")
+ + struct.pack("<I", 8)
+ + string(architecture)
+ )
+
+
+def test_an_undownloaded_speech_pick_is_refused_before_any_download(monkeypatch):
+ """The whole point: the refusal lands off one range request, so the checkpoint is never
+ pulled and the resident pipeline never torn down for a file that cannot decode."""
+ requests = _stub_range_reads(monkeypatch, {CSM_FILE: _arch_header("llama-csm")})
+
+ with pytest.raises(ValueError) as excinfo:
+ diffusion_compat.assert_pick_is_not_speech(CSM_REPO, CSM_FILE)
+
+ detail = str(excinfo.value)
+ assert CSM_FILE in detail and "llama-csm" in detail
+ assert len(requests) == 1
+ url, byte_range = requests[0]
+ assert url.endswith(f"{CSM_REPO}/resolve/main/{CSM_FILE}")
+ # Bounded: the request must name an end offset, or a mis-set header streams the checkpoint.
+ assert byte_range == f"bytes=0-{diffusion_compat._GGUF_HEADER_BYTES - 1}"
+
+
+def test_a_runnable_media_pick_in_the_same_repo_still_loads(monkeypatch):
+ """The sibling this refusal exists to protect: catching it too would hide the only checkpoint
+ in the folder the media backends CAN run."""
+ _stub_range_reads(monkeypatch, {DENOISER_FILE: _arch_header("flux")})
+
+ assert diffusion_compat.speech_pick_refusal(CSM_REPO, DENOISER_FILE) is None
+ diffusion_compat.assert_pick_is_not_speech(CSM_REPO, DENOISER_FILE)
+
+
+def test_an_unreadable_speech_header_fails_open(monkeypatch):
+ """Fail-open throughout: refusing a pick that works is worse than the download this saves."""
+ _stub_range_reads(monkeypatch, {}, status = 200)
+
+ assert diffusion_compat.speech_pick_refusal(CSM_REPO, CSM_FILE) is None
+ diffusion_compat.assert_pick_is_not_speech(CSM_REPO, CSM_FILE)
+
+
+def test_a_pick_with_no_gguf_filename_is_not_probed(monkeypatch):
+ """A pipeline or single_file pick names no GGUF, so there is no header to ask."""
+ requests = _stub_range_reads(monkeypatch, {CSM_FILE: _arch_header("llama-csm")})
+
+ assert diffusion_compat.speech_pick_refusal(CSM_REPO, None) is None
+ assert requests == []
+
+
+def test_the_speech_verdict_is_memoised_per_pick(monkeypatch):
+ """Expanding and re-picking a row must not re-spend the range request."""
+ requests = _stub_range_reads(monkeypatch, {CSM_FILE: _arch_header("llama-csm")})
+
+ assert diffusion_compat.speech_pick_refusal(CSM_REPO, CSM_FILE) is not None
+ assert diffusion_compat.speech_pick_refusal(CSM_REPO, CSM_FILE) is not None
+ assert len(requests) == 1
+
+
+def test_a_failed_probe_is_not_reused_for_a_retry_with_a_working_token(monkeypatch):
+ """A probe that failed on an expired credential memoises "no verdict". Keyed without the
+ token, the retry with a working one reads that back and the speech file reaches the download
+ this preflight exists to stop."""
+ bodies = {CSM_FILE: _arch_header("llama-csm")}
+ requests: list = []
+
+ class _Session:
+ def get(
+ self,
+ url,
+ headers = None,
+ timeout = None,
+ stream = False,
+ ):
+ header_map = headers or {}
+ requests.append(header_map.get("authorization") or header_map.get("Authorization"))
+ # The expired credential is refused; the working one is served.
+ if not any("good" in str(v) for v in header_map.values()):
+ return _FakeResponse(401)
+ body = next((b for name, b in bodies.items() if url.endswith(name)), None)
+ return _FakeResponse(206, body) if body is not None else _FakeResponse(404)
+
+ monkeypatch.setattr("huggingface_hub.utils.get_session", lambda: _Session())
+ monkeypatch.setattr("huggingface_hub.try_to_load_from_cache", lambda *a, **k: None)
+ monkeypatch.setattr(diffusion_compat, "_local_gguf_path", lambda *a, **k: None)
+
+ assert diffusion_compat.speech_pick_refusal(CSM_REPO, CSM_FILE, "expired") is None
+ # Same pick, different credential: it must probe again rather than answer from that miss.
+ assert diffusion_compat.speech_pick_refusal(CSM_REPO, CSM_FILE, "good-token") is not None
+ assert len(requests) == 2
+
+
+def test_a_checkpoint_that_lands_after_a_miss_is_probed_again(monkeypatch, tmp_path):
+ """A file replaced under the same name is a different checkpoint; keyed without its identity
+ the verdict never revisits it."""
+ _stub_range_reads(monkeypatch, {})
+ landed = tmp_path / CSM_FILE
+ seen: dict = {"path": None}
+ monkeypatch.setattr(diffusion_compat, "_local_gguf_path", lambda *a, **k: seen["path"])
+
+ # Nothing on disk and nothing served: no opinion, and that miss is memoised.
+ assert diffusion_compat.speech_pick_refusal(CSM_REPO, CSM_FILE) is None
+
+ landed.write_bytes(_arch_header("llama-csm"))
+ seen["path"] = str(landed)
+
+ assert diffusion_compat.speech_pick_refusal(CSM_REPO, CSM_FILE) is not None
+
+
+def _cache_entry(tmp_path, revision, arch):
+ """A GGUF sitting in an HF cache snapshot dir, so ``_snapshot_revision`` can read its commit."""
+ snapshot = tmp_path / "models--someone--mixed-media-GGUF" / "snapshots" / revision
+ snapshot.mkdir(parents = True, exist_ok = True)
+ path = snapshot / CSM_FILE
+ path.write_bytes(_arch_header(arch))
+ return str(path)
+
+
+def test_a_republished_gguf_is_not_refused_from_the_stale_cached_copy(monkeypatch, tmp_path):
+ """``try_to_load_from_cache`` resolves the LOCAL refs/main, so a republished filename would
+ be refused off the csm bytes still on disk while ``hf_hub_download`` refreshes and loads the
+ new ones."""
+ cached = _cache_entry(tmp_path, "oldsha", "llama-csm")
+ monkeypatch.setattr(diffusion_compat, "_local_gguf_path", lambda *a, **k: cached)
+ monkeypatch.setattr(diffusion_compat, "_hub_revision", lambda *a, **k: "newsha")
+ # The Hub now serves a denoiser at the same name.
+ _stub_range_reads(monkeypatch, {CSM_FILE: _arch_header("flux")})
+
+ assert diffusion_compat.speech_pick_refusal(CSM_REPO, CSM_FILE) is None
+
+
+def test_a_cached_gguf_at_the_current_revision_is_still_refused(monkeypatch, tmp_path):
+ """The revalidation must not become an escape hatch: same commit, same verdict."""
+ cached = _cache_entry(tmp_path, "samesha", "llama-csm")
+ monkeypatch.setattr(diffusion_compat, "_local_gguf_path", lambda *a, **k: cached)
+ monkeypatch.setattr(diffusion_compat, "_hub_revision", lambda *a, **k: "samesha")
+ _stub_range_reads(monkeypatch, {})
+
+ assert diffusion_compat.speech_pick_refusal(CSM_REPO, CSM_FILE) is not None
+
+
+def test_a_revision_check_that_cannot_run_keeps_the_refusal(monkeypatch, tmp_path):
+ """An offline or erroring host leaves today's verdict alone rather than opening the gate."""
+ cached = _cache_entry(tmp_path, "oldsha", "llama-csm")
+ monkeypatch.setattr(diffusion_compat, "_local_gguf_path", lambda *a, **k: cached)
+ monkeypatch.setattr(diffusion_compat, "_hub_revision", lambda *a, **k: None)
+ _stub_range_reads(monkeypatch, {})
+
+ assert diffusion_compat.speech_pick_refusal(CSM_REPO, CSM_FILE) is not None
+
+
+def test_an_on_device_speech_checkpoint_is_never_revalidated(monkeypatch, tmp_path):
+ """An On Device file is the one the loader opens, so there is no revision to be behind."""
+ on_device = tmp_path / CSM_FILE
+ on_device.write_bytes(_arch_header("llama-csm"))
+ monkeypatch.setattr(diffusion_compat, "_local_gguf_path", lambda *a, **k: str(on_device))
+ asked: list = []
+
+ def _never(*a, **k):
+ asked.append(a)
+ return "newsha"
+
+ monkeypatch.setattr(diffusion_compat, "_hub_revision", _never)
+ _stub_range_reads(monkeypatch, {})
+
+ assert diffusion_compat.speech_pick_refusal(CSM_REPO, CSM_FILE) is not None
+ assert asked == []
+
+
+def test_a_pick_that_names_the_checkpoint_outright_is_probed_like_the_loader_opens_it(tmp_path):
+ """A file-valued ``repo_id`` is a pick the video loader accepts, so the preflight must read it.
+
+ ``VideoBackend._resolve_checkpoint_path`` answers ``if root.is_file(): return root`` and
+ ignores ``gguf_filename``, and ``VideoBackend.validate_load_request`` admits exactly that
+ pick, so ``POST /video/load`` with ``model_path`` naming a .gguf reaches the loader today.
+
+ Resolving it as a repo ROOT instead appends the filename under the file, raising
+ ``FileNotFoundError`` -- an ``OSError``, hence swallowed as "remote id". The pick then has no
+ local path: an offline preflight allows it outright, an online one range-requests a
+ filesystem path off the Hub and fails open. Either way the csm checkpoint survives the gate,
+ the resident pipeline is evicted, and the file reaches the media loader."""
+ direct = tmp_path / "wan-models" / CSM_FILE
+ direct.parent.mkdir(parents = True)
+ direct.write_bytes(_arch_header("llama-csm"))
+
+ # Offline, so a probe that found no local path has nothing left to fall back on and must let
+ # the pick through: this asserts the file was actually read, not that the network saved us.
+ reason = diffusion_compat.speech_pick_refusal(str(direct), CSM_FILE, None, False)
+ assert reason is not None and "llama-csm" in reason
+
+ # And it resolves to the very file the loader would open, rather than merely to something.
+ assert diffusion_compat._local_gguf_path(str(direct), CSM_FILE) == str(direct)
+
+ # The runnable sibling named the same way still loads: this must not refuse every direct file.
+ denoiser = direct.parent / DENOISER_FILE
+ denoiser.write_bytes(_arch_header("flux"))
+ assert diffusion_compat.speech_pick_refusal(str(denoiser), DENOISER_FILE, None, False) is None
+
+ # The folder-valued pick keeps resolving through the containment check, unchanged.
+ assert diffusion_compat._local_gguf_path(str(direct.parent), CSM_FILE) == str(direct)
+
+
+# ── Every engine and both stages ───────────────────────────────────────────────
+# The Images and Video pages stage and download BEFORE they call load, so a load-only gate
+# arrives after the bytes. And on all three engines: a mixed VIDEO repo goes through
+# VideoBackend and a CPU/MPS or sd.cpp-forced image pick through SdCppDiffusionBackend, neither
+# of which shares DiffusionBackend's preflight.
+
+
+def test_the_shared_refusal_is_wired_into_every_plan_and_load_path():
+ """Structural, deliberately: the tests above pin the verdict, but what keeps regressing is
+ where it is CALLED, and exercising each engine's plan/load needs a live backend and a Hub."""
+ import inspect
+
+ from core.inference import diffusion, sd_cpp_backend, video
+
+ # Images: folded into incompatible_reason, which the page renders instead of staging entries.
+ plan = inspect.getsource(diffusion.DiffusionBackend.download_plan)
+ assert "speech_pick_refusal" in plan
+
+ # Video: plan and worker both, since a direct begin_load reaches no plan.
+ assert "_assert_pick_is_not_speech" in inspect.getsource(video.VideoBackend.download_plan)
+ assert "_assert_pick_is_not_speech" in inspect.getsource(video.VideoBackend._run_load)
+
+ # sd.cpp: plan and worker. NOT begin_load, which is offline-only and cannot afford the bound.
+ sd_plan = inspect.getsource(sd_cpp_backend.SdCppDiffusionBackend.download_plan)
+ assert "_assert_pick_is_not_speech" in sd_plan
+ assert "_assert_pick_is_not_speech" not in inspect.getsource(
+ sd_cpp_backend.SdCppDiffusionBackend.begin_load
+ )
+
+
+def test_the_video_and_sd_cpp_helpers_delegate_to_the_one_verdict(monkeypatch):
+ """Three engines, one refusal. A second copy of the speech arch set is how they drift."""
+ from core.inference import sd_cpp_backend, video
+
+ seen: list = []
+ monkeypatch.setattr(
+ diffusion_compat,
+ "assert_pick_is_not_speech",
+ lambda *a, **k: seen.append(a),
+ )
+
+ video._assert_pick_is_not_speech(CSM_REPO, CSM_FILE, "tok", allow_network = False)
+ sd_cpp_backend._assert_pick_is_not_speech(CSM_REPO, CSM_FILE, "tok", allow_network = False)
+
+ # The cache-only flag rides through: an offline promise must not drop at the delegation edge.
+ assert seen == [(CSM_REPO, CSM_FILE, "tok", False), (CSM_REPO, CSM_FILE, "tok", False)]
+
+
+def test_a_media_gguf_republished_as_speech_is_refused(monkeypatch, tmp_path):
+ """The direction that matters more: a stale refusal only costs a pick, but a stale ALLOW
+ hands csm bytes to a media loader after the download and the teardown. So the revalidation
+ cannot be the cheap side of an asymmetry the way the size pairing's is."""
+ snapshot = tmp_path / "models--someone--mixed-media-GGUF" / "snapshots" / "oldsha"
+ snapshot.mkdir(parents = True)
+ cached = snapshot / CSM_FILE
+ # On disk this is still the runnable denoiser the row was offering.
+ cached.write_bytes(_arch_header("flux"))
+
+ monkeypatch.setattr(diffusion_compat, "_local_gguf_path", lambda *a, **k: str(cached))
+ monkeypatch.setattr(diffusion_compat, "_hub_revision", lambda *a, **k: "newsha")
+ # The Hub has since replaced it with a speech checkpoint at the same filename.
+ _stub_range_reads(monkeypatch, {CSM_FILE: _arch_header("llama-csm")})
+
+ assert diffusion_compat.speech_pick_refusal(CSM_REPO, CSM_FILE) is not None
+
+
+def test_an_uncached_pick_never_spends_a_revision_head(monkeypatch):
+ """No cached copy means no revision to be behind, so the symmetric revalidation must not cost
+ every remote pick an extra Hub round trip."""
+ monkeypatch.setattr(diffusion_compat, "_local_gguf_path", lambda *a, **k: None)
+ asked: list = []
+ monkeypatch.setattr(
+ diffusion_compat, "_hub_revision", lambda *a, **k: asked.append(a) or "newsha"
+ )
+ _stub_range_reads(monkeypatch, {CSM_FILE: _arch_header("llama-csm")})
+
+ assert diffusion_compat.speech_pick_refusal(CSM_REPO, CSM_FILE) is not None
+ assert asked == []
+
+
+def test_a_cache_only_load_never_range_reads_an_uncached_pick(monkeypatch):
+ """An automatic load sets local_files_only, and that contract covers the metadata probes too:
+ an uncached pick gives up rather than spend the range request and its 15s bound."""
+ requests = _stub_range_reads(monkeypatch, {CSM_FILE: _arch_header("llama-csm")})
+ monkeypatch.setattr(diffusion_compat, "_local_gguf_path", lambda *a, **k: None)
+
+ assert diffusion_compat.speech_pick_refusal(CSM_REPO, CSM_FILE, allow_network = False) is None
+ assert requests == []
+
+ # And nothing was memoised, so the next caller that CAN wait still gets a real answer.
+ assert diffusion_compat.speech_pick_refusal(CSM_REPO, CSM_FILE) is not None
+ assert len(requests) == 1
+
+
+def test_a_cache_only_load_still_reads_a_checkpoint_already_on_disk(monkeypatch, tmp_path):
+ """Offline does not mean blind: a copy already on disk answers with no request at all."""
+ on_device = tmp_path / CSM_FILE
+ on_device.write_bytes(_arch_header("llama-csm"))
+ requests = _stub_range_reads(monkeypatch, {})
+ monkeypatch.setattr(diffusion_compat, "_local_gguf_path", lambda *a, **k: str(on_device))
+
+ assert diffusion_compat.speech_pick_refusal(CSM_REPO, CSM_FILE, allow_network = False) is not None
+ assert requests == []
+
+
+def test_a_cache_only_probe_does_not_memoise_a_skipped_revision_check(monkeypatch, tmp_path):
+ """A cached copy read WITHOUT its revision check is half an answer; memoising it would let
+ the network-allowed caller behind it read that back and never revalidate."""
+ snapshot = tmp_path / "models--someone--mixed-media-GGUF" / "snapshots" / "oldsha"
+ snapshot.mkdir(parents = True)
+ cached = snapshot / CSM_FILE
+ cached.write_bytes(_arch_header("flux"))
+ monkeypatch.setattr(diffusion_compat, "_local_gguf_path", lambda *a, **k: str(cached))
+
+ heads: list = []
+ monkeypatch.setattr(
+ diffusion_compat, "_hub_revision", lambda *a, **k: heads.append(a) or "newsha"
+ )
+ _stub_range_reads(monkeypatch, {CSM_FILE: _arch_header("llama-csm")})
+
+ # Offline: reads the stale local bytes, asks no revision, allows the pick.
+ assert diffusion_compat.speech_pick_refusal(CSM_REPO, CSM_FILE, allow_network = False) is None
+ assert heads == []
+
+ # The next caller that can reach the Hub must still catch the republish.
+ assert diffusion_compat.speech_pick_refusal(CSM_REPO, CSM_FILE) is not None
+ assert len(heads) == 1
+
+
+def test_an_uncached_remote_verdict_is_not_memoised_forever(monkeypatch):
+ """An uncached remote pick keys on a local identity of None, so a republish under the same
+ filename changes nothing about the key. Without a TTL the first verdict would outlive the
+ process and keep refusing a checkpoint that is runnable now."""
+ monkeypatch.setattr(diffusion_compat, "_local_gguf_path", lambda *a, **k: None)
+ bodies = {CSM_FILE: _arch_header("llama-csm")}
+ _stub_range_reads(monkeypatch, bodies)
+ # Driven, not real: the entry expires relative to whatever monotonic said when it was written.
+ clock = [1000.0]
+ monkeypatch.setattr(diffusion_compat.time, "monotonic", lambda: clock[0])
+
+ assert diffusion_compat.speech_pick_refusal(CSM_REPO, CSM_FILE) is not None
+ # Inside the window: the memo answers and the Hub is not asked again.
+ assert diffusion_compat.speech_pick_refusal(CSM_REPO, CSM_FILE) is not None
+
+ # The repo republishes it as a runnable denoiser and the window lapses.
+ bodies[CSM_FILE] = _arch_header("flux")
+ clock[0] += diffusion_compat._SPEECH_REMOTE_TTL_SECONDS + 1.0
+
+ assert diffusion_compat.speech_pick_refusal(CSM_REPO, CSM_FILE) is None
+
+
+def test_a_snapshot_backed_verdict_keeps_its_entry_across_the_window(monkeypatch, tmp_path):
+ """A cached entry needs no TTL: its key carries the file identity and the revision check asks
+ the Hub. Expiring it too would spend a range read per pick for nothing."""
+ snapshot = tmp_path / "models--someone--mixed-media-GGUF" / "snapshots" / "samesha"
+ snapshot.mkdir(parents = True)
+ cached = snapshot / CSM_FILE
+ cached.write_bytes(_arch_header("llama-csm"))
+ monkeypatch.setattr(diffusion_compat, "_local_gguf_path", lambda *a, **k: str(cached))
+ monkeypatch.setattr(diffusion_compat, "_hub_revision", lambda *a, **k: "samesha")
+ requests = _stub_range_reads(monkeypatch, {})
+
+ clock = [1000.0]
+ monkeypatch.setattr(diffusion_compat.time, "monotonic", lambda: clock[0])
+
+ assert diffusion_compat.speech_pick_refusal(CSM_REPO, CSM_FILE) is not None
+ clock[0] += diffusion_compat._SPEECH_REMOTE_TTL_SECONDS * 10
+ assert diffusion_compat.speech_pick_refusal(CSM_REPO, CSM_FILE) is not None
+ assert requests == []
+
+
+def test_both_media_routes_refuse_a_speech_pick_before_taking_the_gpu():
+ """The backends assert this too, but on the load worker, INSIDE acquire_for, so a refusal
+ there arrives having already evicted the chat model the gate exists to preserve -- and on the
+ image route after an engine switch unloaded the resident pipeline. Both routes must refuse
+ before they reach the arbiter."""
+ import inspect
+
+ from routes import inference as inference_route
+ from routes import video as video_route
+
+ # The CALL, not the import line at the top of each route, which names acquire_for far earlier.
+ for source, acquire, label in (
+ (inspect.getsource(video_route.load_video_model_gated), "acquire_for(VIDEO", "video"),
+ (
+ inspect.getsource(inference_route.load_diffusion_model_gated),
+ "acquire_for(DIFFUSION",
+ "images",
+ ),
+ ):
+ assert "assert_pick_is_not_speech" in source, label
+ assert acquire in source, label
+ assert source.index("assert_pick_is_not_speech") < source.index(acquire), label
+
+
+def test_an_automatic_image_load_keeps_the_pre_eviction_preflight_offline():
+ """The route's own speech check already honours user_initiated, but it then calls
+ preflight_base_access, which reaches the same assertion again. Left network-enabled that
+ second call spends a revision HEAD (or an uncached range request and its 15s bound) on the
+ one path that promised to stay off the Hub."""
+ import inspect
+
+ from core.inference import diffusion, sd_cpp_backend
+ from routes import inference as inference_route
+
+ preflight = inspect.getsource(diffusion.DiffusionBackend.preflight_base_access)
+ assert "assert_pick_is_not_speech(repo_id, gguf_filename, hf_token, allow_network)" in preflight
+
+ # The route hands its own locality flag down rather than letting the default win.
+ route = inspect.getsource(inference_route.load_diffusion_model_gated)
+ assert "allow_network = user_initiated" in route
+
+ # Both engines keep one signature, since the route preflights whichever one it picked.
+ for backend in (diffusion.DiffusionBackend, sd_cpp_backend.SdCppDiffusionBackend):
+ assert "allow_network" in inspect.signature(backend.preflight_base_access).parameters
+
+
+# The Mimi vocoder in ggml-org/sesame-csm-1b-GGUF writes a SENTENCE where the architecture
+# identifier belongs. Read off the live repo, not invented.
+_VOCODER_ARCH = "this model cannot be used as LLM, use it via --model-vocoder in TTS examples"
+
+
+# ── the HTTP client huggingface_hub actually hands us ──────────────────────────
+
+
+class _HttpxLikeClient:
+ """An httpx.Client's surface, which is what ``get_session`` returns on huggingface_hub 1.x.
+
+ Deliberately NOT a mock of the requests API: `get` rejects `stream`, there is no
+ `iter_content`, and there is no `raw`. requirements/studio.txt floors 1.23 on python >= 3.10,
+ so this is the client every supported install has."""
+
+ def __init__(self, body):
+ self.body = body
+ self.calls: list[tuple[str, str]] = []
+
+ def get(
+ self,
+ url,
+ params = None,
+ headers = None,
+ timeout = None,
+ **kwargs,
+ ):
+ if "stream" in kwargs:
+ raise TypeError("Client.get() got an unexpected keyword argument 'stream'")
+ raise AssertionError("a ranged header read must use the streaming API")
+
+ def stream(
+ self,
+ method,
+ url,
+ headers = None,
+ timeout = None,
+ follow_redirects = False,
+ ):
+ self.calls.append((method, (headers or {}).get("Range", "")))
+ assert follow_redirects, "the Hub answers a resolve URL with a 302 to the CDN"
+ return _HttpxLikeStream(self.body)
+
+
+class _HttpxLikeStream:
+ def __init__(self, body):
+ self.body = body
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *exc):
+ return False
+
+ @property
+ def status_code(self):
+ return 206
+
+ def iter_bytes(self, chunk_size = 65536):
+ for start in range(0, len(self.body), chunk_size):
+ yield self.body[start : start + chunk_size]
+
+ def close(self):
+ pass
+
+
+def test_the_ranged_read_works_on_the_httpx_client_hub_1_x_returns(monkeypatch):
+ """huggingface_hub 1.0 swapped requests for httpx, and httpx has no ``stream = True``
+ keyword. Asking for one raised TypeError inside the worker's blanket except, so the probe
+ read nothing and EVERY uncached remote pick failed open: a preflight that refused nothing."""
+ client = _HttpxLikeClient(_arch_header("llama-csm"))
+ monkeypatch.setattr("huggingface_hub.utils.get_session", lambda: client)
+ monkeypatch.setattr("huggingface_hub.try_to_load_from_cache", lambda *a, **k: None)
+ diffusion_compat._reset_inner_dim_cache()
+
+ assert diffusion_compat.speech_pick_refusal(CSM_REPO, CSM_FILE) is not None
+ # Still one bounded ranged request, exactly as on the requests client.
+ assert client.calls == [("GET", f"bytes=0-{diffusion_compat._GGUF_HEADER_BYTES - 1}")]
+
+
+def test_the_ranged_read_still_works_on_the_requests_session_hub_0_x_returns(monkeypatch):
+ """The other half of the floor: python < 3.10 pins 0.36, whose session is requests'."""
+ requests_log = _stub_range_reads(monkeypatch, {CSM_FILE: _arch_header("llama-csm")})
+
+ assert diffusion_compat.speech_pick_refusal(CSM_REPO, CSM_FILE) is not None
+ assert len(requests_log) == 1
+
+
+def test_a_requests_session_is_not_mistaken_for_an_httpx_client(monkeypatch):
+ """``requests.Session.stream`` is a plain bool attribute and ``httpx.Client.stream`` is a
+ method, so the branch has to test for a CALLABLE. Testing for the name alone sends a requests
+ session down the httpx path and breaks the client that works today."""
+ import requests
+
+ assert hasattr(requests.Session(), "stream")
+ assert not callable(getattr(requests.Session(), "stream", None))
+
+
+# ── verdict freshness ──────────────────────────────────────────────────────────
+
+
+def test_a_cached_snapshot_verdict_does_not_outlive_its_revision_check(monkeypatch, tmp_path):
+ """A snapshot-backed entry memoises a revision check. Holding it forever meant the Hub was
+ asked once per file per process, so a checkpoint republished later in the session kept the
+ verdict read off bytes that had since been replaced."""
+ cached = _cache_entry(tmp_path, "oldsha", "llama-csm")
+ monkeypatch.setattr(diffusion_compat, "_local_gguf_path", lambda *a, **k: cached)
+ heads: list = []
+
+ def _head(*a, **k):
+ heads.append(a)
+ return "oldsha"
+
+ monkeypatch.setattr(diffusion_compat, "_hub_revision", _head)
+ _stub_range_reads(monkeypatch, {})
+
+ assert diffusion_compat.speech_pick_refusal(CSM_REPO, CSM_FILE) is not None
+ assert len(heads) == 1
+ # Inside the window the memo answers, as before.
+ assert diffusion_compat.speech_pick_refusal(CSM_REPO, CSM_FILE) is not None
+ assert len(heads) == 1
+ # Past it, the Hub is asked again.
+ monkeypatch.setattr(
+ diffusion_compat.time,
+ "monotonic",
+ lambda: 1e9 + diffusion_compat._SPEECH_REMOTE_TTL_SECONDS,
+ )
+ assert diffusion_compat.speech_pick_refusal(CSM_REPO, CSM_FILE) is not None
+ assert len(heads) == 2
+
+
+def test_an_on_device_verdict_is_still_cached_permanently(monkeypatch, tmp_path):
+ """The other half: an On Device file has no revision to be behind, so its entry is keyed on
+ the file's identity and never needs to age out."""
+ on_device = tmp_path / CSM_FILE
+ on_device.write_bytes(_arch_header("llama-csm"))
+ monkeypatch.setattr(diffusion_compat, "_local_gguf_path", lambda *a, **k: str(on_device))
+ _stub_range_reads(monkeypatch, {})
+
+ assert diffusion_compat.speech_pick_refusal(CSM_REPO, CSM_FILE) is not None
+ key = next(iter(diffusion_compat._SPEECH_ARCH_CACHE))
+ assert diffusion_compat._SPEECH_ARCH_CACHE[key][1] is None
+
+
+def test_a_failed_refresh_keeps_the_verdict_it_already_had(monkeypatch, tmp_path):
+ """A HEAD that reports a new revision and a re-read that then fails used to replace a known
+ llama-csm verdict with None, opening the gate on nothing worse than a dropped connection.
+ Failing open on an UNKNOWN pick is the contract; discarding a known one is not."""
+ cached = _cache_entry(tmp_path, "oldsha", "llama-csm")
+ monkeypatch.setattr(diffusion_compat, "_local_gguf_path", lambda *a, **k: cached)
+ monkeypatch.setattr(diffusion_compat, "_hub_revision", lambda *a, **k: "newsha")
+ # The re-read of the new revision returns nothing at all.
+ _stub_range_reads(monkeypatch, {})
+
+ assert diffusion_compat.speech_pick_refusal(CSM_REPO, CSM_FILE) is not None
+
+ # A re-read that SUCCEEDS still replaces it, in both directions.
+ diffusion_compat._reset_inner_dim_cache()
+ _stub_range_reads(monkeypatch, {CSM_FILE: _arch_header("flux")})
+ monkeypatch.setattr(diffusion_compat, "_local_gguf_path", lambda *a, **k: cached)
+ monkeypatch.setattr(diffusion_compat, "_hub_revision", lambda *a, **k: "newsha")
+ assert diffusion_compat.speech_pick_refusal(CSM_REPO, CSM_FILE) is None
+
+
+def test_every_published_csm_spelling_is_refused_by_the_media_preflight(monkeypatch):
+ """The media half of the same set the chat gate uses: a bundle's vocoder reaches a media
+ loader exactly like its backbone does."""
+ for arch in ("llama-csm", "csm", "csm-tts", "mimi"):
+ _stub_range_reads(monkeypatch, {CSM_FILE: _arch_header(arch)})
+ assert diffusion_compat.speech_pick_refusal(CSM_REPO, CSM_FILE) is not None, arch
+ # The vocoder's sentence is quoted back to nobody, but it still refuses.
+ _stub_range_reads(monkeypatch, {CSM_FILE: _arch_header(_VOCODER_ARCH)})
+ reason = diffusion_compat.speech_pick_refusal(CSM_REPO, CSM_FILE)
+ assert reason is not None and "--model-vocoder" not in reason
+
+
+def test_one_pick_range_reads_the_header_once_for_both_probes(monkeypatch, tmp_path):
+ """The size pairing and the speech verdict read the SAME prefix of the SAME file.
+
+ `/images/download-plan` runs them back to back on every hub pick, and `or` only skips the
+ second when the first refuses -- so the ordinary case, a flux.2 GGUF that pairs correctly,
+ made two range requests. Each carries its own _HEADER_TIMEOUT_SECONDS, so a picker the user
+ is sitting in front of could wear twice the bound this module documents. One read now.
+ """
+ requests = _stub_range_reads(monkeypatch, {KLEIN_4B_FILE: _gguf_header(3072, tmp_path)})
+
+ assert (
+ diffusion_compat.flux2_pick_mismatch(
+ FLUX2_FAMILY, KLEIN_4B_GGUF, KLEIN_4B_FILE, KLEIN_4B_BASE
+ )
+ is None
+ ), "the fixture pairs correctly, so the speech probe behind it really does run"
+ assert diffusion_compat.speech_pick_refusal(KLEIN_4B_GGUF, KLEIN_4B_FILE) is None
+
+ assert len(requests) == 1, f"one pick, one header read; got {len(requests)}"
+
+
+def test_a_revalidation_still_re_reads_rather_than_answering_from_the_shared_prefix(
+ monkeypatch, tmp_path
+):
+ """The shared read must not reach the paths whose whole job is to re-read.
+
+ A checkpoint republished at the same filename is caught by re-reading its header off the
+ Hub. Serving that from the prefix memo would hand the revalidation the very bytes it is
+ trying to get past, and a media GGUF republished as speech would load.
+ """
+ source = inspect.getsource(diffusion_compat)
+ for fn in ("_revalidated_inner_dim", "_revalidated_speech_arch"):
+ body = source.split(f"def {fn}(", 1)[1].split("\ndef ", 1)[0]
+ assert "_shared_gguf_header" not in body, f"{fn} must re-read, not consult the memo"
+ assert "_read_gguf_header" in body
+
+
+def test_the_chat_backend_does_not_import_pyyaml_to_learn_the_speech_verdict():
+ """`core.inference.llama_cpp` must not drag the models package in at import time.
+
+ The speech verdict is shared, and reaching it through `utils.models.gguf_metadata` runs
+ `utils.models.__init__`, which imports `model_config`, which imports `yaml`. That made
+ PyYAML a hard import dependency of the chat backend and took the repo's own Source lint
+ job red, where `tests/studio/load_freeze/test_load_orchestrator.py` imports the backend
+ without PyYAML installed. The constants live in the leaf module `utils.gguf_archs`, and
+ every caller imports them from there.
+ """
+ import importlib
+ import subprocess
+ import sys
+ from pathlib import Path
+
+ backend = Path(diffusion_compat.__file__).resolve().parents[2]
+ probe = (
+ "import sys\n"
+ "class Blocker:\n"
+ " def find_spec(self, name, path=None, target=None):\n"
+ " if name == 'yaml' or name.startswith('yaml.'):\n"
+ " raise ModuleNotFoundError(\"No module named 'yaml'\")\n"
+ " return None\n"
+ "sys.meta_path.insert(0, Blocker())\n"
+ f"sys.path.insert(0, {str(backend)!r})\n"
+ "import core.inference.llama_cpp as m\n"
+ "from utils.gguf_archs import SPEECH_GGUF_ARCHS\n"
+ # Identity, not equality: one definition, re-exported, never copied.
+ "assert m.LlamaCppBackend._SPEECH_ARCHES is SPEECH_GGUF_ARCHS\n"
+ "print('ok')\n"
+ )
+ # A subprocess because this pytest session has already imported yaml, and a meta_path
+ # blocker cannot un-import it.
+ result = subprocess.run(
+ [sys.executable, "-c", probe], capture_output = True, text = True, timeout = 300
+ )
+ assert result.returncode == 0, f"stderr: {result.stderr}"
+
+ # And nothing re-exports them from inside the heavy package: that would let an importer
+ # reach them by the very path this test exists to keep out of the chain, and
+ # scripts/verify_import_hoist.py blocks one outside a package __init__ anyway.
+ gguf_metadata = importlib.import_module("utils.models.gguf_metadata")
+ for name in ("SPEECH_GGUF_ARCHS", "is_speech_gguf_architecture"):
+ assert not hasattr(
+ gguf_metadata, name
+ ), f"{name} must be imported from utils.gguf_archs, not through utils.models"
diff --git a/studio/backend/tests/test_llama_cpp_non_chat_gguf_preflight.py b/studio/backend/tests/test_llama_cpp_non_chat_gguf_preflight.py
index 481998872b0..09725b8f413 100644
--- a/studio/backend/tests/test_llama_cpp_non_chat_gguf_preflight.py
+++ b/studio/backend/tests/test_llama_cpp_non_chat_gguf_preflight.py
@@ -395,3 +395,10 @@ def test_the_metadata_less_branch_asks_what_the_pickers_ask(tmp_path):
_arch_to_task("wan", name_hints = (identifier, name)) == "text-to-video"
) is page_named
assert ("Open it from the Video page" in message) is page_named, message
+
+
+def test_speech_arch_names_the_audio_page(tmp_path):
+ _, message = _refusal(tmp_path, arch = "llama-csm", name = "sesame-csm-backbone.gguf")
+ assert message is not None
+ assert "Audio page" in message
+ assert "Images page" not in message
diff --git a/studio/backend/tests/test_llama_cpp_start_failure_classification.py b/studio/backend/tests/test_llama_cpp_start_failure_classification.py
index 878cc6379c1..b33db7b1e0e 100644
--- a/studio/backend/tests/test_llama_cpp_start_failure_classification.py
+++ b/studio/backend/tests/test_llama_cpp_start_failure_classification.py
@@ -95,6 +95,15 @@ class TestDiffusionArchitectures:
assert "cannot run" in msg.lower()
assert "enough memory" not in msg.lower()
+ @pytest.mark.parametrize("arch", sorted(LlamaCppBackend._SPEECH_ARCHES))
+ def test_every_speech_arch_routes_to_the_audio_page(self, arch):
+ out = f"error loading model: unknown model architecture: '{arch}'"
+ msg = _classify(out, f"/models/{arch}.gguf", f"local/{arch}")
+ assert "text-to-speech" in msg.lower()
+ assert "Audio page" in msg
+ assert "Images page" not in msg
+ assert arch in msg
+
def test_media_arch_sets_are_disjoint_and_cover_the_union(self):
sets = (
LlamaCppBackend._IMAGE_ARCHES,
diff --git a/studio/backend/utils/gguf_archs.py b/studio/backend/utils/gguf_archs.py
new file mode 100644
index 00000000000..b4006ca85a1
--- /dev/null
+++ b/studio/backend/utils/gguf_archs.py
@@ -0,0 +1,45 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""The speech-architecture verdict, as a leaf module with no package baggage.
+
+It lives here rather than beside the rest of the GGUF metadata helpers because
+``utils.models.__init__`` eagerly imports ``model_config``, which imports ``yaml``.
+``core.inference.llama_cpp`` needs this verdict at import time, and reaching it through
+``utils.models`` made the whole models package -- and PyYAML with it -- a hard import
+dependency of the chat backend. That took the repo's own Source lint job red, where
+``tests/studio/load_freeze/test_load_orchestrator.py`` imports the backend without PyYAML
+installed.
+
+Every caller imports from here, so there is exactly ONE definition.
+"""
+
+from __future__ import annotations
+
+from typing import Optional
+
+# ``general.architecture`` values naming a speech or neural-codec checkpoint that no Studio
+# runtime can decode: llama.cpp has no CSM decoder (still an unmerged upstream PR) and no
+# media backend reads one either. Published CSM GGUFs do not agree on a spelling, so all four
+# on the Hub today are listed: ggml-org "llama-csm", cartesia "csm", cstr "csm-tts", and a
+# bundle's Mimi vocoder half "mimi". Named once so the chat gate, the listing classifier and
+# the media preflight cannot drift apart.
+SPEECH_GGUF_ARCHS = frozenset({"llama-csm", "csm", "csm-tts", "mimi"})
+
+# The Mimi vocoder in ggml-org/sesame-csm-1b-GGUF puts a whole SENTENCE in general.architecture
+# rather than an identifier. Matched on the flag, not the full string, so a reword still lands.
+_VOCODER_MARKERS = ("--model-vocoder", "cannot be used as llm")
+
+
+def is_speech_gguf_architecture(architecture: Optional[str]) -> bool:
+ """Whether ``general.architecture`` names something only a TTS runtime can decode.
+
+ Case- and space-insensitive, like every other architecture comparison here. ``None`` and the
+ empty string are NOT speech: a GGUF declaring no architecture is unknown, and every caller
+ fails open on unknown."""
+ if not architecture:
+ return False
+ normalized = architecture.strip().lower()
+ if normalized in SPEECH_GGUF_ARCHS:
+ return True
+ return any(marker in normalized for marker in _VOCODER_MARKERS)
diff --git a/studio/backend/utils/models/gguf_metadata.py b/studio/backend/utils/models/gguf_metadata.py
index 72c50c07b9f..df6d55e44b3 100644
--- a/studio/backend/utils/models/gguf_metadata.py
+++ b/studio/backend/utils/models/gguf_metadata.py
@@ -571,3 +571,11 @@ def pairing_score(
return 60 if w_base.lower() == p_base.lower() else -1
return 0
+
+
+# ── speech / codec architectures ────────────────────────────────────────────
+
+# Not defined here, and deliberately not re-exported either: they live in the leaf module
+# ``utils.gguf_archs``, because importing anything from THIS package runs
+# ``utils.models.__init__``, which pulls in ``model_config`` and therefore PyYAML, and
+# ``core.inference.llama_cpp`` needs the verdict at import time. Import it from there.
diff --git a/studio/frontend/src/features/audio/audio-page.tsx b/studio/frontend/src/features/audio/audio-page.tsx
index 3d9cc7d053b..9e91c292add 100644
--- a/studio/frontend/src/features/audio/audio-page.tsx
+++ b/studio/frontend/src/features/audio/audio-page.tsx
@@ -1882,7 +1882,12 @@ export function AudioPage({
// The catalog rows are already filtered to families with a GGUF sibling; these
// have none, so offering them only produces that error.
.filter((lora) => !isMac || lora.export_type === "gguf")
- .filter((lora) => isTtsAudioType(lora.audio_type))
+ // The GGUF flag matters: GGUF_TTS_AUDIO_TYPES leaves csm out because llama.cpp has
+ // no CSM decoder, so a csm LoRA exported to GGUF fails at load. Without it the
+ // wider Transformers list answered and the row was offered anyway.
+ .filter((lora) =>
+ isTtsAudioType(lora.audio_type, lora.export_type === "gguf"),
+ )
.map((lora) => ({
id: lora.adapter_path,
name: audioModelLabel(lora.adapter_path),
diff --git a/studio/frontend/src/features/model-picker/components/model-selector/audio-picker-policy.ts b/studio/frontend/src/features/model-picker/components/model-selector/audio-picker-policy.ts
index 1e269bfd791..6dda465e50d 100644
--- a/studio/frontend/src/features/model-picker/components/model-selector/audio-picker-policy.ts
+++ b/studio/frontend/src/features/model-picker/components/model-selector/audio-picker-policy.ts
@@ -65,6 +65,46 @@ export function communityAudioRowIsRunnable({
return !(isGguf && /(?:^|[-_./])csm(?:$|[-_./])/.test(family));
}
+/** A GGUF llama.cpp cannot decode, however it was found: CSM is Transformers-only, so it
+ * never loads in llama-server. Beside communityAudioRowIsRunnable's list to stay in step. */
+export function speechGgufIsUndecodable({
+ isGguf,
+ id,
+ baseModel,
+ tags,
+}: {
+ isGguf: boolean;
+ id: string;
+ baseModel?: string | null;
+ tags?: readonly string[] | null;
+}): boolean {
+ if (!isGguf) return false;
+ return [id, baseModel ?? "", ...(tags ?? [])]
+ .map((value) => value.toLowerCase())
+ .some((value) => CSM_PATH_SEGMENT.test(value));
+}
+
+/** `csm` as its own path or name segment. The separator class carries a BACKSLASH as well as a
+ * slash: this is handed local checkpoint paths, and on Windows `C:\models\csm-1b\model.gguf`
+ * reads as one long segment to a posix-only class, and clears. */
+const CSM_PATH_SEGMENT = /(?:^|[-_./\\])csm(?:$|[-_./\\])/;
+
+/** Whether a fine-tuned or exported row is a CSM checkpoint in a GGUF container, which no
+ * runtime here decodes. `audioType` is read off the checkpoint by the backend, so it holds
+ * even where nothing in the path says "csm". */
+export function localAudioRowIsUndecodableGguf({
+ audioType,
+ exportType,
+ isDirectGguf = false,
+}: {
+ audioType?: string | null;
+ exportType?: string | null;
+ isDirectGguf?: boolean;
+}): boolean {
+ const isGguf = exportType === "gguf" || isDirectGguf;
+ return isGguf && (audioType ?? "").toLowerCase() === "csm";
+}
+
/** Whether an audio pick from the chat picker may be routed to the Audio page.
*
* The page's own lists apply `communityAudioRowIsRunnable`, so routing a repo that fails
@@ -77,6 +117,7 @@ export function audioPickIsRoutable({
isGguf,
isCurated,
isLocalCheckpoint = false,
+ taskFromGgufArch = false,
baseModel,
tags,
libraryName,
@@ -87,16 +128,27 @@ export function audioPickIsRoutable({
isCurated: boolean;
/** Trained or exported here, so its codec was read off the checkpoint itself. */
isLocalCheckpoint?: boolean;
+ /** Filesystem inventory row: its task came from reading the GGUF's own architecture. */
+ taskFromGgufArch?: boolean;
baseModel?: string | null;
tags?: readonly string[] | null;
libraryName?: string | null;
}): boolean {
+ // The backend tags text-to-speech ONLY for llama-csm (_SPEECH_GGUF_ARCHS), the one arch
+ // llama.cpp has no decoder for, so that read outranks both the curated match and the
+ // PATH-based heuristic below -- which clears a CSM file at /models/orpheus/custom.gguf
+ // and routes it to Audio after the handoff already evicted the chat model.
+ if (taskFromGgufArch && isGguf && task === "text-to-speech") return false;
if (isCurated) return true;
// A checkpoint from outputs/ has no Hub identity for communityAudioRowIsRunnable to
// judge, and the family-name heuristic it applies would reject it on its directory
// name. Its task came from the backend reading the checkpoint, which is the stronger
// signal, and the Audio page lists it off that same tag.
if (isLocalCheckpoint) {
+ // Provenance says nothing about the decoder: a CSM GGUF found on disk is as
+ // unrunnable as a cached one, and routing it hands Audio a row it cannot show after
+ // the ?model= handoff already evicted the chat model.
+ if (speechGgufIsUndecodable({ isGguf, id, baseModel, tags })) return false;
return (
task === "text-to-speech" || task === "automatic-speech-recognition"
);
diff --git a/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx b/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx
index 96ff5d24c64..0b3c3253d4f 100644
--- a/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx
+++ b/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx
@@ -113,6 +113,7 @@ import {
type CommunityModelPolicy,
allowedHiddenModelIdMatches,
audioPickIsRoutable,
+ localAudioRowIsUndecodableGguf,
communityAudioRowIsRunnable,
curatedAudioInventoryMatches,
curatedAudioInventoryTask,
@@ -3425,14 +3426,26 @@ export function HubModelPicker({
const sortedCachedGguf = useMemo(
() =>
sortCachedRepos(
- cachedGguf.filter((c) =>
- passesTaskGate(
- c.task,
- c.repo_id,
- task,
- catalog,
- activeCatalogArtifactIds,
- ),
+ cachedGguf.filter(
+ (c) =>
+ passesTaskGate(
+ c.task,
+ c.repo_id,
+ task,
+ catalog,
+ activeCatalogArtifactIds,
+ ) &&
+ // A speech GGUF no backend here can decode (CSM) would otherwise be listed as
+ // a chat model and only fail in llama-server. Non-audio rows always pass.
+ audioPickIsRoutable({
+ id: c.repo_id,
+ task: c.task,
+ isGguf: true,
+ isCurated: artifactForRepoId(c.repo_id, AUDIO_CATALOG) !== null,
+ // _repo_gguf_task reads these off the arch too, so the same rule holds: a
+ // speech tag means llama-csm even when the repo id names another family.
+ taskFromGgufArch: true,
+ }),
),
downloadedSort,
loadTimes,
@@ -3525,6 +3538,18 @@ export function HubModelPicker({
lmStudioModels.filter(
(m) =>
filesystemRowsSupportedForTask(task, m.task) &&
+ // The same speech gate the cached GGUF rows get: a CSM file found in LM
+ // Studio, ./models or a scan folder is just as undecodable, and routing it to
+ // Audio evicts the chat model before the row is reported unsupported.
+ audioPickIsRoutable({
+ id: m.model_id ?? m.id,
+ task: m.task,
+ isGguf: localModelIsGguf(m),
+ isCurated: artifactForRepoId(m.model_id ?? m.id, AUDIO_CATALOG) !== null,
+ // These rows are tasked by _local_model_task reading the GGUF's own arch,
+ // so a text-to-speech tag here means llama-csm, whatever the file is named.
+ taskFromGgufArch: true,
+ }) &&
// The backend tags every local model with its task for exactly this: on the Images/Video pages a chat GGUF must not be offered.
passesTaskGate(
m.task,
@@ -3559,6 +3584,18 @@ export function HubModelPicker({
localDirModels.filter(
(m) =>
filesystemRowsSupportedForTask(task, m.task) &&
+ // The same speech gate the cached GGUF rows get: a CSM file found in LM
+ // Studio, ./models or a scan folder is just as undecodable, and routing it to
+ // Audio evicts the chat model before the row is reported unsupported.
+ audioPickIsRoutable({
+ id: m.model_id ?? m.id,
+ task: m.task,
+ isGguf: localModelIsGguf(m),
+ isCurated: artifactForRepoId(m.model_id ?? m.id, AUDIO_CATALOG) !== null,
+ // These rows are tasked by _local_model_task reading the GGUF's own arch,
+ // so a text-to-speech tag here means llama-csm, whatever the file is named.
+ taskFromGgufArch: true,
+ }) &&
passesTaskGate(
m.task,
m.model_id ?? m.id,
@@ -3596,6 +3633,18 @@ export function HubModelPicker({
customFolderModels.filter(
(m) =>
filesystemRowsSupportedForTask(task, m.task) &&
+ // The same speech gate the cached GGUF rows get: a CSM file found in LM
+ // Studio, ./models or a scan folder is just as undecodable, and routing it to
+ // Audio evicts the chat model before the row is reported unsupported.
+ audioPickIsRoutable({
+ id: m.model_id ?? m.id,
+ task: m.task,
+ isGguf: localModelIsGguf(m),
+ isCurated: artifactForRepoId(m.model_id ?? m.id, AUDIO_CATALOG) !== null,
+ // These rows are tasked by _local_model_task reading the GGUF's own arch,
+ // so a text-to-speech tag here means llama-csm, whatever the file is named.
+ taskFromGgufArch: true,
+ }) &&
passesTaskGate(
m.task,
m.model_id ?? m.id,
@@ -3721,6 +3770,18 @@ export function HubModelPicker({
const fineTunedRows = useMemo(() => {
const needle = normalizeForSearch(debouncedQuery.trim());
return loraModels
+ .filter(
+ (m) =>
+ // A CSM export in a GGUF container loads nowhere: llama.cpp has no decoder and the
+ // Audio page does not list speech GGUFs either. audioType comes off the checkpoint,
+ // so it catches an exported row regardless of path; local rows have no audioType
+ // and are refused at load instead.
+ !localAudioRowIsUndecodableGguf({
+ audioType: m.audioType,
+ exportType: m.exportType,
+ isDirectGguf: m.isDirectGguf,
+ }),
+ )
.filter((m) => {
const text = normalizeForSearch(
`${m.name} ${m.baseModel ?? ""} ${m.id}`,
diff --git a/studio/frontend/tests/audio-picker-policy.test.ts b/studio/frontend/tests/audio-picker-policy.test.ts
index f95dba88627..fcb7fe772f1 100644
--- a/studio/frontend/tests/audio-picker-policy.test.ts
+++ b/studio/frontend/tests/audio-picker-policy.test.ts
@@ -12,6 +12,8 @@ import {
curatedAudioInventoryTask,
filesystemRowsSupportedForTask,
macTtsHubRowIsRunnable,
+ localAudioRowIsUndecodableGguf,
+ speechGgufIsUndecodable,
shouldDiscoverCommunityModels,
shouldRecommendCommunityModels,
taskCatalogFormatMatches,
@@ -513,6 +515,64 @@ test("only speech repos the runtime can serve are routed to the Audio page", ()
);
});
+test("a cached speech GGUF no backend can decode is not listed at all", () => {
+ assert.match(
+ pickerSource,
+ /cachedGguf\.filter\([\s\S]*passesTaskGate\([\s\S]*audioPickIsRoutable\(\{[\s\S]*isGguf: true/,
+ );
+ assert.equal(
+ audioPickIsRoutable({
+ id: "ggml-org/sesame-csm-1b-GGUF",
+ task: "text-to-speech",
+ isGguf: true,
+ isCurated: false,
+ }),
+ false,
+ );
+});
+
+test("a speech GGUF found on the filesystem is gated like a cached one", () => {
+ // The backend tags llama-csm as text-to-speech wherever it is discovered, so every
+ // filesystem list has to ask the same policy the cached GGUF list does.
+ for (const rows of [
+ "lmStudioModels",
+ "localDirModels",
+ "customFolderModels",
+ ]) {
+ assert.match(
+ pickerSource,
+ new RegExp(
+ `${rows}\\.filter\\([\\s\\S]*?audioPickIsRoutable\\(\\{`,
+ ),
+ `${rows} must apply the speech gate`,
+ );
+ }
+});
+
+test("a local CSM GGUF is unroutable even though it was found on disk", () => {
+ assert.equal(
+ audioPickIsRoutable({
+ id: "/models/sesame-csm-1b-GGUF/csm-1b-Q4_K_M.gguf",
+ task: "text-to-speech",
+ isGguf: true,
+ isCurated: false,
+ isLocalCheckpoint: true,
+ }),
+ false,
+ );
+ // A Transformers CSM checkpoint still runs, so local provenance keeps routing it.
+ assert.equal(
+ audioPickIsRoutable({
+ id: "/outputs/csm-1b-finetune",
+ task: "text-to-speech",
+ isGguf: false,
+ isCurated: false,
+ isLocalCheckpoint: true,
+ }),
+ true,
+ );
+});
+
test("an unroutable speech pick is refused instead of loaded into chat", () => {
assert.match(
pickerSource,
@@ -536,3 +596,161 @@ test("a local Whisper checkpoint is not advertised as a routable ASR row", () =>
);
assert.match(source, /pipelineTag: audioPipelineTagFor\(adapter\.audioType, true\)/);
});
+
+test("an arch-tasked speech GGUF is rejected however its path or repo id is named", () => {
+ // text-to-speech is tagged on a GGUF only after reading a llama-csm arch. The family
+ // heuristic re-infers from the NAME, so a CSM file parked under a runnable-looking
+ // directory used to clear the gate and evict the chat model for a row Audio cannot show.
+ const parkedUnderOrpheus = {
+ id: "/models/orpheus/custom.gguf",
+ task: "text-to-speech",
+ isGguf: true,
+ isCurated: false,
+ };
+ assert.equal(audioPickIsRoutable(parkedUnderOrpheus), true);
+ assert.equal(
+ audioPickIsRoutable({ ...parkedUnderOrpheus, taskFromGgufArch: true }),
+ false,
+ );
+ // The arch read outranks a curated name match too: llama.cpp has no CSM decoder, so
+ // the file is undecodable no matter which catalog id its folder happens to echo.
+ assert.equal(
+ audioPickIsRoutable({
+ ...parkedUnderOrpheus,
+ isCurated: true,
+ taskFromGgufArch: true,
+ }),
+ false,
+ );
+ // Same rule on the cached-repo side, where the task comes off the arch as well.
+ assert.equal(
+ audioPickIsRoutable({
+ id: "someone/orpheus-3b-custom-GGUF",
+ task: "text-to-speech",
+ isGguf: true,
+ isCurated: false,
+ taskFromGgufArch: true,
+ }),
+ false,
+ );
+ // Orpheus GGUFs report a plain `llama` arch, so they arrive tagged text-generation and
+ // the gate must leave them alone; a non-GGUF CSM still runs on the Transformers path.
+ assert.equal(
+ audioPickIsRoutable({
+ id: "/models/orpheus/custom.gguf",
+ task: "text-generation",
+ isGguf: true,
+ isCurated: false,
+ taskFromGgufArch: true,
+ }),
+ true,
+ );
+ assert.equal(
+ audioPickIsRoutable({
+ id: "unsloth/csm-1b",
+ task: "text-to-speech",
+ isGguf: false,
+ isCurated: true,
+ taskFromGgufArch: true,
+ }),
+ true,
+ );
+});
+
+test("every filesystem list passes the arch-tasked flag, not just the policy call", () => {
+ // The policy is only as good as its call sites: a list that asks without the flag gets
+ // the name heuristic back and re-opens the hole this gate exists to close.
+ const callSites = pickerSource.match(/taskFromGgufArch: true/g) ?? [];
+ assert.equal(callSites.length, 4);
+});
+
+test("a Windows path is judged like its posix equivalent", () => {
+ // The separator class carries a backslash: these predicates are handed local checkpoint
+ // paths, and on Windows the same file arrives as C:\models\csm-1b\model.gguf, which a
+ // posix-only class reads as one long segment and clears.
+ for (const id of [
+ "/models/csm-1b/model.gguf",
+ "C:\\models\\csm-1b\\model.gguf",
+ "C:\\Users\\me\\models\\csm\\q8.gguf",
+ ]) {
+ assert.equal(
+ speechGgufIsUndecodable({ isGguf: true, id }),
+ true,
+ `${id} must be undecodable`,
+ );
+ assert.equal(
+ audioPickIsRoutable({
+ id,
+ task: "text-to-speech",
+ isGguf: true,
+ isCurated: false,
+ isLocalCheckpoint: true,
+ }),
+ false,
+ `${id} must not route`,
+ );
+ }
+ // Still no false positive on a name that merely contains the letters.
+ assert.equal(
+ speechGgufIsUndecodable({ isGguf: true, id: "C:\\models\\csmith-7b\\q8.gguf" }),
+ false,
+ );
+});
+
+test("a csm checkpoint exported to GGUF is not offered anywhere", () => {
+ // audioType is read off the checkpoint by the backend, so it is authoritative even where
+ // nothing in the path says csm. llama.cpp has no CSM decoder, whatever the container.
+ assert.equal(
+ localAudioRowIsUndecodableGguf({ audioType: "csm", exportType: "gguf" }),
+ true,
+ );
+ assert.equal(
+ localAudioRowIsUndecodableGguf({ audioType: "csm", isDirectGguf: true }),
+ true,
+ );
+ assert.equal(
+ localAudioRowIsUndecodableGguf({ audioType: "CSM", exportType: "gguf" }),
+ true,
+ );
+ // A csm LoRA or merged safetensors checkpoint still runs on the Transformers path.
+ assert.equal(
+ localAudioRowIsUndecodableGguf({ audioType: "csm", exportType: "merged" }),
+ false,
+ );
+ assert.equal(
+ localAudioRowIsUndecodableGguf({ audioType: "csm", exportType: "lora" }),
+ false,
+ );
+ // The codecs llama.cpp DOES decode keep their GGUF exports.
+ for (const audioType of ["snac", "bicodec", "dac"]) {
+ assert.equal(
+ localAudioRowIsUndecodableGguf({ audioType, exportType: "gguf" }),
+ false,
+ audioType,
+ );
+ }
+});
+
+test("the fine-tuned section applies the undecodable-GGUF gate", () => {
+ assert.match(
+ pickerSource,
+ /loraModels[\s\S]{0,400}?localAudioRowIsUndecodableGguf\(\{/,
+ );
+});
+
+test("the audio page asks the GGUF-aware TTS predicate for trained rows", () => {
+ // GGUF_TTS_AUDIO_TYPES leaves csm out because llama.cpp has no CSM decoder. Calling
+ // isTtsAudioType without the flag answered off the wider Transformers list and offered
+ // a csm GGUF export that fails at load.
+ const source = readFileSync(
+ new URL(
+ "../src/features/audio/audio-page.tsx",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ assert.match(
+ source,
+ /isTtsAudioType\(\s*lora\.audio_type,\s*lora\.export_type === "gguf",?\s*\)/,
+ );
+});