Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio sd.cpp: load a cached earlier text encoder quant when the BF16 default cannot be fetched (#14862)
Daniel Hanfe27b8e72ce3
diff --git a/studio/backend/core/inference/diffusion_families.py b/studio/backend/core/inference/diffusion_families.pyindex 6485a23e8a5..04172a78399 100644--- a/studio/backend/core/inference/diffusion_families.py+++ b/studio/backend/core/inference/diffusion_families.py@@ -3070,6 +3070,27 @@ def _with_text_encoder_quant(return tuple(out)+# Highest precision first: the order a load that cannot download walks when its encoder file is not cached.+_SD_CPP_TEXT_ENCODER_CACHED_ORDER = ("BF16", "Q8_0", "Q4_K_M")+++def sd_cpp_text_encoder_cached_alternatives(repo: str, filename: str, kind: str) -> tuple[str, ...]:+ """Other precisions a cache-only load may use: defaults moved to BF16 after builds cached+ Q8_0 / Q4_K_M. Empty under UNSLOTH_SD_CPP_TEXT_ENCODER_QUANT (explicit pick honoured)."""+ if sd_cpp_text_encoder_quant() is not None:+ return ()+ if kind != "llm" or str(repo).lower() not in _SD_CPP_REQUANTABLE_TE_REPOS:+ return ()+ match = _SD_CPP_LLM_GGUF_QUANT_RE.search(filename)+ if match is None:+ return ()+ return tuple(+ _SD_CPP_LLM_GGUF_QUANT_RE.sub(f"-{tag}.gguf", filename)+ for tag in _SD_CPP_TEXT_ENCODER_CACHED_ORDER+ if tag != match.group(1)+ )++# sd-cli companion repos released Studio builds fetched and this one no longer reads: the unsloth copies of the# ComfyUI-built repacks, each holding only VAE / text-encoder files (no denoiser). Nothing loads from them now, but an# upgraded install still holds their bytes (up to ~70 GB), so they stay companion-only: hidden from the model pickersdiff --git a/studio/backend/core/inference/sd_cpp_backend.py b/studio/backend/core/inference/sd_cpp_backend.pyindex b1caf97e60b..5e9ba213ebd 100644--- a/studio/backend/core/inference/sd_cpp_backend.py+++ b/studio/backend/core/inference/sd_cpp_backend.py@@ -61,6 +61,7 @@ from core.inference.diffusion_families import (named_variant_base,resolve_base_repo,resolve_local_gguf_child,+ sd_cpp_text_encoder_cached_alternatives,sd_cpp_text_encoders_for,supported_family_names,_family_override_resolved,@@ -2889,6 +2890,22 @@ class _NeverRaised(Exception):"""Placeholder ``except`` target for a hub layout with no LocalEntryNotFoundError."""+def _cached_text_encoder_alternative(repo: str, filename: str, kind: str) -> Optional[str]:+ """A cached other precision of this encoder when *filename* itself is not loadable from the+ cache, else None. Network-free (``try_to_load_from_cache``)."""+ alternatives = sd_cpp_text_encoder_cached_alternatives(repo, filename, kind)+ if not alternatives:+ return None+ from core.inference.diffusion import DiffusionBackend++ if DiffusionBackend._hub_file_is_loadable(repo, filename):+ return None+ for alternative in alternatives:+ if DiffusionBackend._hub_file_is_loadable(repo, alternative):+ return alternative+ return None++def _local_entry_not_found_error() -> type[BaseException]:"""huggingface_hub's "not cached and downloads are disabled" error, or an unraisable stand-in.Resolved lazily and defensively for the same reason the rest of this module imports@@ -3455,7 +3472,9 @@ class SdCppDiffusionBackend:inner_dim = self._flux2_inner_dim(repo_id, gguf_filename, fam, hf_token, allow_network = not local_files_only)- specs = self._asset_specs(repo_id, gguf_filename, fam, inner_dim)+ specs = self._asset_specs(+ repo_id, gguf_filename, fam, inner_dim, local_only = local_files_only+ )fetch_repo = _fetch_repo_map(specs, hf_token)assets = [(fetch_repo[repo], fn, kind) for repo, fn, kind in specs]with self._lock:@@ -4132,17 +4151,25 @@ class SdCppDiffusionBackend:gguf_filename: str,fam: DiffusionFamily,inner_dim: Optional[int] = None,+ local_only: bool = False,) -> list[tuple[str, str, str]]:"""(repo, filename, kind) for every file sd-cli needs. ``kind`` is the SdCppModelFiles- field; the transformer reuses the diffusers GGUF."""+ field; the transformer reuses the diffusers GGUF. Offline / ``local_only`` swaps an uncached+ encoder for a cached other precision so the UI plan and the load agree."""specs: list[tuple[str, str, str]] = [(repo_id, gguf_filename, "diffusion_model")]if fam.sd_cpp_vae:specs.append((fam.sd_cpp_vae[0], fam.sd_cpp_vae[1], "vae"))+ offline = local_only+ if not offline:+ from utils.utils import hf_env_offline+ offline = hf_env_offline()# Pick the encoder per variant so a 9B GGUF fetches the right one: from the header when the caller read it,# else from the load identity, which a renamed file makes silent.for terepo, tefile, kind in sd_cpp_text_encoders_for(fam, repo_id, gguf_filename, inner_dim = inner_dim):+ if offline:+ tefile = _cached_text_encoder_alternative(terepo, tefile, kind) or tefilespecs.append((terepo, tefile, kind))return specs@@ -4221,25 +4248,40 @@ class SdCppDiffusionBackend:gguf_header_delta = True,)except _local_entry_not_found_error() as exc:- # Raised by huggingface_hub for exactly "not cached and outgoing traffic is disabled", so it can- # only fire under local_files_only. Its own text names neither the repo nor the file, and this- # string is what /images/load-progress toasts, so restate it with both. Re-raised untouched in the- # (unreachable) online case rather than relabelled, so nothing changes when the flag is off.- if not local_files_only:- raise- if kind == "llm_vision" and vision_optional:- # Only editing reads the projector, and edit is offered only when it is loaded. A- # Qwen-Image-2.1 GGUF cached before the projector was listed still loads for- # text-to-image; opening it from the Images page fetches the projector.- logger.info(- "sd_cpp.llm_vision_not_cached: %s/%s, editing unavailable", repo, fn+ # Not fetchable: an encoder whose default precision changed may be cached as an older quant.+ alternative = _cached_text_encoder_alternative(repo, fn, kind)+ if alternative is not None:+ logger.warning(+ "sd_cpp.text_encoder_cached_quant: %s/%s is not cached and cannot be "+ "downloaded; using the cached %s",+ repo,+ fn,+ alternative,)- continue- raise RuntimeError(- f"'{fn}' is not in the local cache for '{repo}', and this load may not "- f"download (it was not user-initiated). Open the model from the Images "- f"page to fetch it."- ) from exc+ path = hf_hub_download_with_xet_fallback(+ repo,+ alternative,+ hf_token,+ cancel_event = cancel,+ reuse_other_cache_root = True,+ local_files_only = True,+ gguf_header_delta = True,+ )+ else:+ # Only fires under local_files_only; hub text omits repo/file and this string is the UI toast.+ if not local_files_only:+ raise+ if kind == "llm_vision" and vision_optional:+ # Only edit reads the projector; text-to-image still loads without it.+ logger.info(+ "sd_cpp.llm_vision_not_cached: %s/%s, editing unavailable", repo, fn+ )+ continue+ raise RuntimeError(+ f"'{fn}' is not in the local cache for '{repo}', and this load may not "+ f"download (it was not user-initiated). Open the model from the Images "+ f"page to fetch it."+ ) from excpaths[kind] = pathif kind.endswith("_shard"):shard_paths[fn.rsplit("/", 1)[-1]] = pathdiff --git a/studio/backend/tests/test_sd_cpp_text_encoder_offline_cached_quant.py b/studio/backend/tests/test_sd_cpp_text_encoder_offline_cached_quant.pynew file mode 100644index 00000000000..9b983b772a6--- /dev/null+++ b/studio/backend/tests/test_sd_cpp_text_encoder_offline_cached_quant.py@@ -0,0 +1,178 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""A load that cannot download (cache-only, HF offline, no network) reads a cached earlier quant of the sd.cpp text+encoder when the BF16 default is not cached, instead of failing on the missing BF16 file. Fake HF cache under+tmp_path; no network, no weights."""++import pytest++from core.inference import diffusion_families as df+from core.inference.sd_cpp_backend import SdCppDiffusionBackend++_SHA = "a" * 40+++def _fam(name):+ return next(f for f in df._FAMILIES if f.name == name)+++def _cache_file(+ root,+ repo,+ filename,+ data = b"gguf",+):+ repo_dir = root / f"models--{repo.replace('/', '--')}"+ snapshot = repo_dir / "snapshots" / _SHA+ snapshot.mkdir(parents = True, exist_ok = True)+ (snapshot / filename).parent.mkdir(parents = True, exist_ok = True)+ (snapshot / filename).write_bytes(data)+ (repo_dir / "refs").mkdir(parents = True, exist_ok = True)+ (repo_dir / "refs" / "main").write_text(_SHA, encoding = "utf-8")+ return snapshot / filename+++def cache(monkeypatch, tmp_path):+ """An isolated live cache root, with huggingface_hub's own root pointed at an empty dir so the shared HF cache on+ this host cannot answer a lookup. The fetch resolves from the fake cache or raises the hub's local-miss error."""+ import huggingface_hub.constants as hub_constants+ from huggingface_hub import try_to_load_from_cache+ from huggingface_hub.errors import LocalEntryNotFoundError++ live = tmp_path / "live"+ live.mkdir()+ monkeypatch.setattr(+ "utils.hf_cache_settings.active_hf_hub_cache", lambda: str(live), raising = False+ )+ monkeypatch.setattr(hub_constants, "HF_HUB_CACHE", str(tmp_path / "empty"))+ monkeypatch.delenv(df.SD_CPP_TEXT_ENCODER_QUANT_ENV, raising = False)+ monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)+ monkeypatch.delenv("TRANSFORMERS_OFFLINE", raising = False)+ fetched = []++ def fake_download(repo, fn, tok, **kwargs):+ fetched.append((repo, fn, kwargs.get("local_files_only")))+ hit = try_to_load_from_cache(repo, fn, cache_dir = str(live))+ if isinstance(hit, str):+ return hit+ # What huggingface_hub raises both under local_files_only and when the Hub is unreachable.+ raise LocalEntryNotFoundError(f"{repo}/{fn} not cached")++ monkeypatch.setattr("utils.hf_xet_fallback.hf_hub_download_with_xet_fallback", fake_download)+ return live, fetched+++def _klein_assets(+ b,+ gguf,+ inner_dim = None,+ **kw,+):+ fam = _fam("flux.2-klein")+ return b._asset_specs("unsloth/FLUX.2-klein-9B-GGUF", gguf, fam, inner_dim, **kw)+++def _seed_klein_9b(live):+ _cache_file(live, "unsloth/FLUX.2-klein-9B-GGUF", "flux-2-klein-9b-Q4_K_M.gguf")+ _cache_file(live, "black-forest-labs/FLUX.2-dev", "vae/diffusion_pytorch_model.safetensors")+ return _cache_file(live, "unsloth/Qwen3-8B-GGUF", "Qwen3-8B-Q4_K_M.gguf")+++def test_cache_only_load_reads_the_cached_earlier_quant(cache):+ """Klein 9B loaded before the BF16 default fetched Qwen3-8B Q4_K_M. A background (cache-only) load must still+ resolve it rather than fail on the uncached BF16 file."""+ live, _fetched = cache+ old = _seed_klein_9b(live)+ b = SdCppDiffusionBackend()+ # The specs as every caller builds them today: the fetch alone must recover.+ paths = b._fetch_assets(+ _klein_assets(b, "flux-2-klein-9b-Q4_K_M.gguf"), None, local_files_only = True+ )+ assert paths["llm"] == str(old)+ # And the cache-only load's own specs already name the cached file.+ specs = _klein_assets(b, "flux-2-klein-9b-Q4_K_M.gguf", local_only = True)+ assert ("unsloth/Qwen3-8B-GGUF", "Qwen3-8B-Q4_K_M.gguf", "llm") in specs+ assert b._fetch_assets(specs, None, local_files_only = True)["llm"] == str(old)+++def test_fetch_falls_back_when_the_default_cannot_be_downloaded(cache):+ """The specs still name BF16 (an online load wants it), but the Hub is unreachable: the fetch reads the cached+ quant, cache-only, instead of raising the hub's local-miss error."""+ live, fetched = cache+ old = _seed_klein_9b(live)+ b = SdCppDiffusionBackend()+ specs = _klein_assets(b, "flux-2-klein-9b-Q4_K_M.gguf")+ assert ("unsloth/Qwen3-8B-GGUF", "Qwen3-8B-BF16.gguf", "llm") in specs+ paths = b._fetch_assets(specs, None, local_files_only = False)+ assert paths["llm"] == str(old)+ assert ("unsloth/Qwen3-8B-GGUF", "Qwen3-8B-Q4_K_M.gguf", True) in fetched+++def test_hf_offline_plan_shows_the_cached_quant(cache, monkeypatch):+ """Under HF_HUB_OFFLINE the download plan (what the UI prices and stages) names the cached file the load will+ read, not a BF16 download that cannot happen."""+ live, _fetched = cache+ _cache_file(live, "unsloth/Qwen3-4B-GGUF", "Qwen3-4B-Q8_0.gguf")+ monkeypatch.setenv("HF_HUB_OFFLINE", "1")+ b = SdCppDiffusionBackend()+ fam = _fam("z-image")+ specs = b._asset_specs("unsloth/Z-Image-Turbo-GGUF", "z-image-turbo-Q4_K_M.gguf", fam)+ assert ("unsloth/Qwen3-4B-GGUF", "Qwen3-4B-Q8_0.gguf", "llm") in specs+ assert ("unsloth/Qwen3-4B-GGUF", "Qwen3-4B-BF16.gguf", "llm") not in specs+++def test_highest_cached_precision_wins_and_bf16_is_kept_when_cached(cache):+ live, _fetched = cache+ _cache_file(live, "unsloth/Qwen3-8B-GGUF", "Qwen3-8B-Q4_K_M.gguf")+ _cache_file(live, "unsloth/Qwen3-8B-GGUF", "Qwen3-8B-Q8_0.gguf")+ b = SdCppDiffusionBackend()+ specs = _klein_assets(b, "flux-2-klein-9b-Q4_K_M.gguf", local_only = True)+ assert ("unsloth/Qwen3-8B-GGUF", "Qwen3-8B-Q8_0.gguf", "llm") in specs+ _cache_file(live, "unsloth/Qwen3-8B-GGUF", "Qwen3-8B-BF16.gguf")+ specs = _klein_assets(b, "flux-2-klein-9b-Q4_K_M.gguf", local_only = True)+ assert ("unsloth/Qwen3-8B-GGUF", "Qwen3-8B-BF16.gguf", "llm") in specs+++def test_online_specs_and_explicit_override_are_unchanged(cache, monkeypatch):+ """An online load still wants BF16 (fresh loads get the accuracy default), and an explicit+ UNSLOTH_SD_CPP_TEXT_ENCODER_QUANT is honoured, not swapped, even offline."""+ live, _fetched = cache+ _seed_klein_9b(live)+ b = SdCppDiffusionBackend()+ specs = _klein_assets(b, "flux-2-klein-9b-Q4_K_M.gguf")+ assert ("unsloth/Qwen3-8B-GGUF", "Qwen3-8B-BF16.gguf", "llm") in specs+ monkeypatch.setenv(df.SD_CPP_TEXT_ENCODER_QUANT_ENV, "q8_0")+ specs = _klein_assets(b, "flux-2-klein-9b-Q4_K_M.gguf", local_only = True)+ assert ("unsloth/Qwen3-8B-GGUF", "Qwen3-8B-Q8_0.gguf", "llm") in specs+ with pytest.raises(RuntimeError, match = "Qwen3-8B-Q8_0.gguf"):+ b._fetch_assets(specs, None, local_files_only = True)+++def test_nothing_cached_still_fails_with_the_named_default(cache):+ live, _fetched = cache+ _cache_file(live, "unsloth/FLUX.2-klein-9B-GGUF", "flux-2-klein-9b-Q4_K_M.gguf")+ _cache_file(live, "black-forest-labs/FLUX.2-dev", "vae/diffusion_pytorch_model.safetensors")+ b = SdCppDiffusionBackend()+ specs = _klein_assets(b, "flux-2-klein-9b-Q4_K_M.gguf", local_only = True)+ with pytest.raises(RuntimeError, match = "Qwen3-8B-BF16.gguf"):+ b._fetch_assets(specs, None, local_files_only = True)+++def test_only_the_requantable_llm_encoders_have_alternatives(cache):+ assert df.sd_cpp_text_encoder_cached_alternatives(+ "unsloth/Qwen3-4B-GGUF", "Qwen3-4B-BF16.gguf", "llm"+ ) == ("Qwen3-4B-Q8_0.gguf", "Qwen3-4B-Q4_K_M.gguf")+ assert (+ df.sd_cpp_text_encoder_cached_alternatives(+ "unsloth/Qwen3-VL-4B-Instruct-GGUF", "Qwen3-VL-4B-Instruct-Q8_0.gguf", "llm"+ )+ == ()+ )+ assert (+ df.sd_cpp_text_encoder_cached_alternatives(+ "unsloth/Qwen3-4B-GGUF", "Qwen3-4B-BF16.gguf", "llm_vision"+ )+ == ()+ )