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: load community SDXL single-file GGUFs on the Images page (#13035)
Daniel Hanf9718db12821
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.pyindex ff1bd115c5b..e9217f65c28 100644--- a/studio/backend/core/inference/diffusion.py+++ b/studio/backend/core/inference/diffusion.py@@ -45,7 +45,13 @@ from utils.gpu_memory_events import invalidates_gpu_memory as _invalidates_gpu_mfrom utils.account_context import account_thread, current_account_idfrom utils.hardware import clear_gpu_cache-from .diffusion_content import assert_local_pick_is_dit, content_variant_hint+from .diffusion_content import (+ assert_local_pick_is_dit,+ content_variant_hint,+ local_pick_file,+ whole_pipeline_gguf_family,+)+from .diffusion_gguf_pipeline import load_whole_pipeline_gguf, whole_pipeline_gguf_resident_mibfrom .diffusion_families import (DIFFUSION_CANCELLED_MSG,DIFFUSION_NOT_LOADED_MSG,@@ -1558,6 +1564,31 @@ def _restore_gguf_trimmed_dims(model: Any, state_dict: Any) -> Any:return state_dict+def _generation_defaults_for(+ repo_id: Optional[str], gguf_filename: Optional[str], base_repo: Optional[str]+) -> Optional[dict[str, float]]:+ """The (steps, guidance) the OpenAI route renders this load with, header variant before base (FLUX.1's base is+ schnell), so the Images form can match it."""+ try:+ steps, guidance = default_generation_params(+ gguf_filename, content_variant_hint(repo_id, gguf_filename), repo_id, base_repo+ )+ except Exception: # noqa: BLE001 - status must not fail on a recipe lookup+ return None+ return {"steps": int(steps), "guidance": float(guidance)}+++_WHOLE_PIPELINE_GGUF_LORA_MSG = (+ "LoRA is not available on a whole-pipeline GGUF: its UNet runs as the stored GGUF weights, which cannot carry "+ "adapters. Load the .safetensors checkpoint to use a LoRA, or clear the LoRA selection."+)+++def _whole_pipeline_gguf_pick(repo_id: Optional[str], gguf_filename: Optional[str]) -> bool:+ """True when the pick is an on-disk GGUF carrying a whole single-file pipeline (UNet + text encoders + VAE)."""+ return whole_pipeline_gguf_family(local_pick_file(repo_id, gguf_filename)) is not None++def _dequantize_gguf_outside_linears(model: Any,dtype: Any,@@ -3203,11 +3234,17 @@ class DiffusionBackend:if not family_buildable_here(fam, model_kind = kind):assert_pipeline_class_available(fam.pipeline_class, fam.name)- # Families whose single file IS the whole pipeline have no GGUF path; reject before eviction- if kind == "gguf" and fam.single_file_is_pipeline:+ # Whole-pipeline families take a GGUF only when it is whole too (stable-diffusion.cpp ``convert``).+ if (+ kind == "gguf"+ and fam.single_file_is_pipeline+ and not _whole_pipeline_gguf_pick(repo_id, gguf_filename)+ ):raise ValueError(- f"'{fam.name}' checkpoints are whole-pipeline single files and have no GGUF "- f"transformer variant; load the .safetensors pipeline instead of a GGUF."+ f"'{fam.name}' checkpoints are whole-pipeline single files, so a GGUF loads only when it "+ f"also carries the text encoders and VAE under the checkpoint's own tensor names (a current "+ f"stable-diffusion.cpp convert of the checkpoint, on disk). Load the .safetensors checkpoint, or "+ f"such a GGUF, instead.")# A multi-denoiser family (Ideogram 4) has no transformer-only path; reject before evictionif kind in ("gguf", "single_file") and fam.pipeline_only:@@ -3232,7 +3269,7 @@ class DiffusionBackend:f"base_repo is restricted to unsloth/* repos (or a local path); got '{base_repo}'.")# A local base_repo loads as a full pipeline; reject a non-pipeline one before eviction- whole_file = kind == "single_file" and fam.single_file_is_pipeline+ whole_file = kind in ("single_file", "gguf") and fam.single_file_is_pipelineexcluded = ((fam.denoiser_attr,) if kind in ("gguf", "single_file") and not whole_file else ())@@ -3379,6 +3416,12 @@ class DiffusionBackend:text_encoder_files = text_encoder_files,vae_file = vae_file,)+ if (+ _has_active_lora(loras)+ and getattr(fam, "single_file_is_pipeline", False)+ and resolve_model_kind(gguf_filename, model_kind) == "gguf"+ ):+ raise ValueError(_WHOLE_PIPELINE_GGUF_LORA_MSG)# Refuse an EXPLICIT precision this host can never honor BEFORE the load starts, so the route answers 409 with# the reason instead of evicting the resident model, downloading several GB and only then failing. The# declines that need the real footprint can only be found mid-load and surface through load-progress.@@ -4519,8 +4562,8 @@ class DiffusionBackend:if s.rfilename == gguf_filename}_record_revision(revisions_out, repo_id, info)- # A whole-pipeline single file (SDXL) needs only the base's config/tokenizer, not its weights.- if kind == "single_file" and single_file_is_pipeline:+ # A whole-pipeline single file (SDXL, or its GGUF) needs only the base's config/tokenizer, not its weights.+ if kind in ("single_file", "gguf") and single_file_is_pipeline:base_filter = _base_config_file_downloadedelse:@@ -6017,6 +6060,11 @@ class DiffusionBackend:speed_mode is not None and str(speed_mode).strip().lower() == SPEED_OFF)transformer_quant = "off" if speed_off else TQ_AUTO+ if kind == "gguf" and fam.single_file_is_pipeline:+ # A whole-pipeline GGUF (SDXL) has no dense twin in the base repo: its UNet runs as stored.+ if _has_active_lora(loras):+ raise ValueError(_WHOLE_PIPELINE_GGUF_LORA_MSG)+ transformer_quant = "off"# The one case that must fail closed: a named scheme (not auto, not off). Normalized here so "FP8" and# "fp8" refuse identically; a bogus value already raised above.transformer_quant_pinned = (@@ -7089,9 +7137,9 @@ class DiffusionBackend:logger,_load_token,)- elif kind == "single_file" and fam.single_file_is_pipeline:+ elif kind in ("single_file", "gguf") and fam.single_file_is_pipeline:# A single-file SDXL-style checkpoint is the WHOLE pipeline: load it through the pipeline- # class with ``config`` on the base repo.+ # class with ``config`` on the base repo. Its GGUF (validated whole) loads the same way.sf_pipe_kwargs: dict[str, Any] = {"local_files_only": local_files_only,"torch_dtype": dtype,@@ -7107,7 +7155,23 @@ class DiffusionBackend:"A ComfyUI-quantized checkpoint holds only a denoiser; this family's single ""file is a whole pipeline, so it cannot be loaded here.")- pipe = pipeline_cls.from_single_file(single_file_path, **sf_pipe_kwargs)+ if kind == "gguf":+ pipe = load_whole_pipeline_gguf(+ pipeline_cls,+ getattr(diffusers, fam.transformer_class),+ single_file_path,+ sf_pipe_kwargs,+ dtype = dtype,+ denoiser_attr = fam.denoiser_attr,+ logger = logger,+ )+ _dequantize_gguf_outside_linears(+ getattr(pipe, fam.denoiser_attr), dtype, logger+ )+ else:+ pipe = pipeline_cls.from_single_file(+ single_file_path, **sf_pipe_kwargs+ )else:# Transformer-only single file; VAE/text-encoder/scheduler come from the base repo.sf_kwargs: dict[str, Any] = {@@ -8936,7 +9000,7 @@ class DiffusionBackend:# is read for config only, but the plan still adds the base's cached companion weights, so a user who once# loaded the full pipeline has those bytes counted twice. Harmless as an offload hint, a rejected load as# a hard refusal.- if kind == "single_file" and getattr(fam, "single_file_is_pipeline", False):+ if kind in ("single_file", "gguf") and getattr(fam, "single_file_is_pipeline", False):companion = plan.estimates.get("companion_dense_mib")current = plan.estimates.get("model_dense_mib")if companion and current is not None and int(companion) < int(current):@@ -9394,6 +9458,11 @@ class DiffusionBackend:)if _comfy_mib is not None:transformer_resident = _comfy_mib+ elif getattr(fam, "single_file_is_pipeline", False):+ # Only the denoiser's linears stay packed; the text encoders, VAE and the rest load dense.+ transformer_resident = whole_pipeline_gguf_resident_mib(+ single_file_path, dense_bytes = _float_load_itemsize(load_dtype) or 2+ ) or estimate_gguf_resident_mib(file_size_mib(single_file_path))else:transformer_resident = estimate_gguf_resident_mib(file_size_mib(single_file_path))# Companions (VAE + text encoders) load near on-disk size; sum the base-repo cache, or a LOCAL base's@@ -11258,6 +11327,7 @@ class DiffusionBackend:"supports_lora": False,"supports_controlnet": False,"resolved": None,+ "generation_defaults": None,}from core.inference import diffusion_controlnet, diffusion_lorafrom hub.utils.gguf import extract_quant_token@@ -11296,6 +11366,9 @@ class DiffusionBackend:"transformer_cache": state.transformer_cache,"transformer_cache_stats": static_skip_stats(state.pipe),"resolved": resolved,+ "generation_defaults": _generation_defaults_for(+ state.repo_id, state.gguf_filename, state.base_repo+ ),# Workflows the loaded family supports, so the UI can gate its tabs."workflows": _family_workflows(state.family),"supports_negative_prompt": state.family.uses_negative_prompt,diff --git a/studio/backend/core/inference/diffusion_content.py b/studio/backend/core/inference/diffusion_content.pyindex faeb62eaa6c..4eb55324f53 100644--- a/studio/backend/core/inference/diffusion_content.py+++ b/studio/backend/core/inference/diffusion_content.py@@ -64,6 +64,8 @@ class CheckpointInfo:what: str = "" # e.g. "a VAE", used in refusalslayout: str = ""variant: Optional[str] = None # flux.1-schnell vs flux.1-dev+ # denoiser + text encoder(s) + VAE in one file (an SDXL checkpoint, or its stable-diffusion.cpp GGUF)+ whole_pipeline: bool = Falsedef family_page(family: Optional[str]) -> Optional[str]:@@ -200,6 +202,11 @@ _DIT_PREFIXES = ("",)+# Not cond_stage_model: older stable-diffusion.cpp converts keep SDXL's second encoder there in HF CLIP+# names, which diffusers reads as the first encoder, so the load would fail after eviction.+_BUNDLED_TEXT_ENCODER_TOPS = frozenset({"conditioner", "text_encoders"})+_BUNDLED_VAE_TOPS = frozenset({"first_stage_model", "vae"})+_LORA_RE = re.compile(r"(?:^|\.)(?:lora_[AB]|lora_down|lora_up|lora\.(?:up|down)|lokr_w\d|hada_w\d_[ab])(?:\.|$)|^lora_unet_|^lora_te\d?_")@@ -499,6 +506,7 @@ def classify_tensors(shapes: dict[str, list[int]], meta: Optional[dict] = None)"audio_vae",})+ whole_pipeline = bool(tops & _BUNDLED_TEXT_ENCODER_TOPS) and bool(tops & _BUNDLED_VAE_TOPS)for prefix in _DIT_PREFIXES:sub = _strip(shapes, prefix)if not sub:@@ -507,7 +515,7 @@ def classify_tensors(shapes: dict[str, list[int]], meta: Optional[dict] = None)if info is not None:layout = "gguf" if arch else ("checkpoint" if bundled else info.layout)return CheckpointInfo(- info.role, info.family, info.page, info.what, layout, info.variant+ info.role, info.family, info.page, info.what, layout, info.variant, whole_pipeline)te = _match_text_encoder(keys)@@ -564,6 +572,22 @@ def offer_as_dit(path: str) -> bool:return inspect_checkpoint(path).role not in NON_DIT_ROLES+def whole_pipeline_gguf_family(path: Optional[str]) -> Optional[str]:+ """Family of a GGUF carrying the whole pipeline (denoiser, text encoders, VAE) of a single-file-pipeline family+ (SDXL), as stable-diffusion.cpp ``convert`` writes it. None otherwise."""+ if not path or not str(path).lower().endswith(".gguf"):+ return None+ info = inspect_checkpoint(str(path))+ if info.role != ROLE_DIT or not info.family or not info.whole_pipeline:+ return None+ try:+ from .diffusion_families import detect_family+ fam = detect_family("", override = info.family)+ except Exception: # noqa: BLE001 - no registry: not a pick this module can vouch for+ return None+ return info.family if fam is not None and fam.single_file_is_pipeline else None++def local_pick_file(repo_id: Optional[str], filename: Optional[str]) -> Optional[str]:try:if not repo_id:diff --git a/studio/backend/core/inference/diffusion_gguf_pipeline.py b/studio/backend/core/inference/diffusion_gguf_pipeline.pynew file mode 100644index 00000000000..1db08b17bf8--- /dev/null+++ b/studio/backend/core/inference/diffusion_gguf_pipeline.py@@ -0,0 +1,120 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Load a whole-pipeline GGUF (stable-diffusion.cpp ``convert`` of an SDXL checkpoint) through diffusers.++Pipeline-level ``from_single_file`` treats every component as packed GGUF bytes (text encoders fail 816 vs 768), so+only the denoiser loads quantized; the rest is dequantized once and fed to the pipeline loader in place of the read.+"""++import threading+from typing import Any, Optional++_DENOISER_PREFIX = "model.diffusion_model."+_PATCH_LOCK = threading.Lock()+++def whole_pipeline_gguf_resident_mib(path: Optional[str], *, dense_bytes: int = 2) -> Optional[int]:+ """Resident MiB as ``load_whole_pipeline_gguf`` lays it out: quantized denoiser linears packed, every other tensor+ dense at ``dense_bytes`` per element. None when the header cannot be read."""+ try:+ from gguf import GGMLQuantizationType, GGUFReader+ tensors = GGUFReader(str(path)).tensors+ except Exception: # noqa: BLE001 - caller falls back to the packed-file estimate+ return None+ unquantized = {+ GGMLQuantizationType.F32,+ GGMLQuantizationType.F16,+ GGMLQuantizationType.BF16,+ }+ total = 0+ for t in tensors:+ packed = (+ t.name.startswith(_DENOISER_PREFIX)+ and len(t.shape) == 2+ and t.tensor_type not in unquantized+ )+ total += int(t.n_bytes) if packed else int(t.n_elements) * dense_bytes+ return int(total * 1.05 / (1024 * 1024)) if total else None+++def split_whole_pipeline_checkpoint(checkpoint: dict, dtype: Any) -> tuple[dict, dict]:+ """(denoiser state dict still GGUF-packed, every other tensor dequantized at ``dtype``)."""+ from diffusers.quantizers.gguf.utils import GGUFParameter, dequantize_gguf_tensor++ denoiser: dict = {}+ rest: dict = {}+ for key, value in checkpoint.items():+ if key.startswith(_DENOISER_PREFIX):+ denoiser[key] = value+ elif isinstance(value, GGUFParameter):+ rest[key] = dequantize_gguf_tensor(value).to(dtype)+ else:+ rest[key] = value+ return denoiser, rest+++def load_whole_pipeline_gguf(+ pipeline_cls: Any,+ denoiser_cls: Any,+ path: str,+ pipe_kwargs: dict,+ *,+ dtype: Any,+ denoiser_attr: str = "unet",+ logger: Optional[Any] = None,+) -> Any:+ """Denoiser stays GGUF-quantized, text encoders and VAE load dense at ``dtype``; ``pipe_kwargs`` as for the+ safetensors ``from_single_file``."""+ import diffusers+ import diffusers.loaders.single_file as single_file_mod+ from diffusers.loaders.single_file_utils import load_single_file_checkpoint++ checkpoint = load_single_file_checkpoint(+ path,+ local_files_only = pipe_kwargs.get("local_files_only"),+ cache_dir = pipe_kwargs.get("cache_dir"),+ token = pipe_kwargs.get("token"),+ )+ denoiser_sd, rest = split_whole_pipeline_checkpoint(checkpoint, dtype)+ del checkpoint+ if not denoiser_sd:+ raise ValueError(f"'{path}' carries no {denoiser_attr} tensors ({_DENOISER_PREFIX}*).")+ model_kwargs = {+ key: pipe_kwargs[key]+ for key in ("local_files_only", "cache_dir", "token")+ if pipe_kwargs.get(key) is not None+ }+ denoiser = denoiser_cls.from_single_file(+ denoiser_sd,+ config = pipe_kwargs.get("config"),+ subfolder = denoiser_attr,+ quantization_config = diffusers.GGUFQuantizationConfig(compute_dtype = dtype),+ torch_dtype = dtype,+ **model_kwargs,+ )+ del denoiser_sd+ original = single_file_mod.load_single_file_checkpoint++ def _read(link, *args, **kwargs):+ if str(link) == str(path):+ return rest+ return original(link, *args, **kwargs)++ # Module-global swap: serialized so concurrent single-file loads never see another load's tensors+ with _PATCH_LOCK:+ single_file_mod.load_single_file_checkpoint = _read+ try:+ pipe = pipeline_cls.from_single_file(path, **{denoiser_attr: denoiser}, **pipe_kwargs)+ finally:+ single_file_mod.load_single_file_checkpoint = original+ if logger is not None:+ logger.info(+ "diffusion.gguf_pipeline: %s loaded from a whole-pipeline GGUF (%s GGUF-quantized, %d other tensors "+ "dequantized at %s)",+ pipeline_cls.__name__,+ denoiser_attr,+ len(rest),+ dtype,+ )+ return pipediff --git a/studio/backend/hub/services/models/catalog_classification.py b/studio/backend/hub/services/models/catalog_classification.pyindex 2014e5c5d94..57d33f5357d 100644--- a/studio/backend/hub/services/models/catalog_classification.py+++ b/studio/backend/hub/services/models/catalog_classification.py@@ -252,9 +252,31 @@ def _gguf_file_task(path: str | Path, name_hints: tuple[Optional[str], ...]) ->arch = _gguf_architecture(str(path))if is_audio_cpp_gguf_architecture(arch):return _audio_cpp_classification(path, name_hints)[0]+ if arch is None or arch.lower() == "sdxl":+ whole = _whole_pipeline_gguf_task(path)+ if whole is not None:+ return wholereturn _arch_to_task(arch, name_hints = name_hints)+def _whole_pipeline_gguf_task(path: str | Path) -> Optional[str]:+ """Images task for a whole-pipeline SDXL GGUF: sd.cpp ``convert`` writes no architecture, so the name fallback+ would call it a chat model."""+ try:+ from core.inference.diffusion_content import whole_pipeline_gguf_family++ family = whole_pipeline_gguf_family(str(path))+ if family is None:+ return None+ from core.inference.diffusion_engine_router import family_buildable_here+ from core.inference.diffusion_families import detect_family++ buildable = family_buildable_here(detect_family("", override = family), model_kind = "gguf")+ except Exception:+ return None+ return "text-to-image" if buildable else _UNSUPPORTED_DIFFUSION_TASK++def _arch_to_task(arch: Optional[str], name_hints: tuple[Optional[str], ...] = ()) -> Optional[str]:if any(_is_h3_bundle_gguf_hint(hint) for hint in name_hints):return _VIDEO_GEN_TASKdiff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.pyindex 258e5ce145d..b7c8c32b076 100644--- a/studio/backend/models/inference.py+++ b/studio/backend/models/inference.py@@ -5192,6 +5192,11 @@ class DiffusionStatusResponse(BaseModel):description = "Per-control resolved value + provenance (source auto|explicit + reason), ""keyed by Advanced control name; null when unloaded or unavailable.",)+ generation_defaults: Optional[Dict[str, float]] = Field(+ None,+ description = "Default steps and guidance for the loaded model (file header before base repo); "+ "null when unloaded or on an engine that does not report it.",+ )class DiffusionInferenceInfo(BaseModel):diff --git a/studio/backend/tests/fixtures/sdxl_whole_pipeline_gguf_header.json b/studio/backend/tests/fixtures/sdxl_whole_pipeline_gguf_header.jsonnew file mode 100644index 00000000000..bf858870977--- /dev/null+++ b/studio/backend/tests/fixtures/sdxl_whole_pipeline_gguf_header.json@@ -0,0 +1,573 @@+{+"source": "SG161222/RealVisXL_V4.0@26dfe44930964cd70d0a817b6d1cc945c130e38d RealVisXL_V4.0.safetensors (sha256 912c9dc74f5855175c31a7993f863a043ac8dcc31732b324cd05d75cd7e16844) converted with stable-diffusion.cpp `sd-cli -M convert --type q8_0`; real tensor names and shapes, trimmed to index 0 of every stack; the file carries no metadata keys (no general.architecture)",+"shapes": {+"conditioner.embedders.0.transformer.text_model.embeddings.position_embedding.weight": [+77,+768+],+"conditioner.embedders.0.transformer.text_model.embeddings.token_embedding.weight": [+49408,+768+],+"conditioner.embedders.0.transformer.text_model.encoder.layers.0.layer_norm1.bias": [+768+],+"conditioner.embedders.0.transformer.text_model.encoder.layers.0.layer_norm1.weight": [+768+],+"conditioner.embedders.0.transformer.text_model.encoder.layers.0.layer_norm2.bias": [+768+],+"conditioner.embedders.0.transformer.text_model.encoder.layers.0.layer_norm2.weight": [+768+],+"conditioner.embedders.0.transformer.text_model.encoder.layers.0.mlp.fc1.bias": [+3072+],+"conditioner.embedders.0.transformer.text_model.encoder.layers.0.mlp.fc1.weight": [+3072,+768+],+"conditioner.embedders.0.transformer.text_model.encoder.layers.0.mlp.fc2.bias": [+768+],+"conditioner.embedders.0.transformer.text_model.encoder.layers.0.mlp.fc2.weight": [+768,+3072+],+"conditioner.embedders.0.transformer.text_model.encoder.layers.0.self_attn.k_proj.bias": [+768+],+"conditioner.embedders.0.transformer.text_model.encoder.layers.0.self_attn.k_proj.weight": [+768,+768+],+"conditioner.embedders.0.transformer.text_model.encoder.layers.0.self_attn.out_proj.bias": [+768+],+"conditioner.embedders.0.transformer.text_model.encoder.layers.0.self_attn.out_proj.weight": [+768,+768+],+"conditioner.embedders.0.transformer.text_model.encoder.layers.0.self_attn.q_proj.bias": [+768+],+"conditioner.embedders.0.transformer.text_model.encoder.layers.0.self_attn.q_proj.weight": [+768,+768+],+"conditioner.embedders.0.transformer.text_model.encoder.layers.0.self_attn.v_proj.bias": [+768+],+"conditioner.embedders.0.transformer.text_model.encoder.layers.0.self_attn.v_proj.weight": [+768,+768+],+"conditioner.embedders.0.transformer.text_model.final_layer_norm.bias": [+768+],+"conditioner.embedders.0.transformer.text_model.final_layer_norm.weight": [+768+],+"first_stage_model.decoder.conv_in.bias": [+512+],+"first_stage_model.decoder.conv_in.weight": [+512,+4,+3,+3+],+"first_stage_model.decoder.conv_out.bias": [+3+],+"first_stage_model.decoder.conv_out.weight": [+3,+128,+3,+3+],+"first_stage_model.decoder.mid.attn_1.k.bias": [+512+],+"first_stage_model.decoder.mid.attn_1.k.weight": [+512,+512,+1,+1+],+"first_stage_model.decoder.mid.attn_1.norm.bias": [+512+],+"first_stage_model.decoder.mid.attn_1.norm.weight": [+512+],+"first_stage_model.decoder.mid.attn_1.proj_out.bias": [+512+],+"first_stage_model.decoder.mid.attn_1.proj_out.weight": [+512,+512,+1,+1+],+"first_stage_model.decoder.mid.attn_1.q.bias": [+512+],+"first_stage_model.decoder.mid.attn_1.q.weight": [+512,+512,+1,+1+],+"first_stage_model.decoder.mid.attn_1.v.bias": [+512+],+"first_stage_model.decoder.mid.attn_1.v.weight": [+512,+512,+1,+1+],+"first_stage_model.decoder.mid.block_1.conv1.bias": [+512+],+"first_stage_model.decoder.mid.block_1.conv1.weight": [+512,+512,+3,+3+],+"first_stage_model.decoder.mid.block_1.conv2.bias": [+512+],+"first_stage_model.decoder.mid.block_1.norm1.bias": [+512+],+"first_stage_model.decoder.mid.block_1.norm1.weight": [+512+],+"first_stage_model.decoder.mid.block_1.norm2.bias": [+512+],+"first_stage_model.decoder.mid.block_1.conv2.weight": [+512,+512,+3,+3+],+"first_stage_model.decoder.mid.block_2.conv1.bias": [+512+],+"first_stage_model.decoder.mid.block_2.conv1.weight": [+512,+512,+3,+3+],+"first_stage_model.decoder.mid.block_1.norm2.weight": [+512+],+"first_stage_model.decoder.mid.block_2.conv2.bias": [+512+],+"first_stage_model.decoder.mid.block_2.conv2.weight": [+512,+512,+3,+3+],+"first_stage_model.decoder.mid.block_2.norm1.bias": [+512+],+"first_stage_model.decoder.mid.block_2.norm1.weight": [+512+],+"first_stage_model.decoder.mid.block_2.norm2.bias": [+512+],+"first_stage_model.decoder.mid.block_2.norm2.weight": [+512+],+"first_stage_model.decoder.norm_out.bias": [+128+],+"first_stage_model.decoder.norm_out.weight": [+128+],+"first_stage_model.decoder.up.0.block.0.conv1.bias": [+128+],+"first_stage_model.decoder.up.0.block.0.conv1.weight": [+128,+256,+3,+3+],+"first_stage_model.decoder.up.0.block.0.conv2.bias": [+128+],+"first_stage_model.decoder.up.0.block.0.conv2.weight": [+128,+128,+3,+3+],+"first_stage_model.decoder.up.0.block.0.nin_shortcut.bias": [+128+],+"first_stage_model.decoder.up.0.block.0.nin_shortcut.weight": [+128,+256,+1,+1+],+"first_stage_model.decoder.up.0.block.0.norm1.bias": [+256+],+"first_stage_model.decoder.up.0.block.0.norm1.weight": [+256+],+"first_stage_model.decoder.up.0.block.0.norm2.bias": [+128+],+"first_stage_model.decoder.up.0.block.0.norm2.weight": [+128+],+"first_stage_model.encoder.conv_in.bias": [+128+],+"first_stage_model.encoder.conv_in.weight": [+128,+3,+3,+3+],+"first_stage_model.encoder.conv_out.bias": [+8+],+"first_stage_model.encoder.conv_out.weight": [+8,+512,+3,+3+],+"first_stage_model.encoder.down.0.block.0.conv1.bias": [+128+],+"first_stage_model.encoder.down.0.block.0.conv1.weight": [+128,+128,+3,+3+],+"first_stage_model.encoder.down.0.block.0.conv2.bias": [+128+],+"first_stage_model.encoder.down.0.block.0.conv2.weight": [+128,+128,+3,+3+],+"first_stage_model.encoder.down.0.block.0.norm1.bias": [+128+],+"first_stage_model.encoder.down.0.block.0.norm1.weight": [+128+],+"first_stage_model.encoder.down.0.block.0.norm2.bias": [+128+],+"first_stage_model.encoder.down.0.block.0.norm2.weight": [+128+],+"first_stage_model.encoder.down.0.downsample.conv.bias": [+128+],+"first_stage_model.encoder.down.0.downsample.conv.weight": [+128,+128,+3,+3+],+"first_stage_model.encoder.mid.attn_1.k.weight": [+512,+512,+1,+1+],+"first_stage_model.encoder.mid.attn_1.norm.bias": [+512+],+"first_stage_model.encoder.mid.attn_1.k.bias": [+512+],+"first_stage_model.encoder.mid.attn_1.norm.weight": [+512+],+"first_stage_model.encoder.mid.attn_1.proj_out.bias": [+512+],+"first_stage_model.encoder.mid.attn_1.proj_out.weight": [+512,+512,+1,+1+],+"first_stage_model.encoder.mid.attn_1.q.bias": [+512+],+"first_stage_model.encoder.mid.attn_1.q.weight": [+512,+512,+1,+1+],+"first_stage_model.encoder.mid.attn_1.v.bias": [+512+],+"first_stage_model.encoder.mid.block_1.conv1.bias": [+512+],+"first_stage_model.encoder.mid.attn_1.v.weight": [+512,+512,+1,+1+],+"first_stage_model.encoder.mid.block_1.conv1.weight": [+512,+512,+3,+3+],+"first_stage_model.encoder.mid.block_1.conv2.bias": [+512+],+"first_stage_model.encoder.mid.block_1.conv2.weight": [+512,+512,+3,+3+],+"first_stage_model.encoder.mid.block_1.norm1.bias": [+512+],+"first_stage_model.encoder.mid.block_1.norm1.weight": [+512+],+"first_stage_model.encoder.mid.block_1.norm2.bias": [+512+],+"first_stage_model.encoder.mid.block_1.norm2.weight": [+512+],+"first_stage_model.encoder.mid.block_2.conv1.bias": [+512+],+"first_stage_model.encoder.mid.block_2.conv1.weight": [+512,+512,+3,+3+],+"first_stage_model.encoder.mid.block_2.conv2.bias": [+512+],+"first_stage_model.encoder.mid.block_2.norm1.bias": [+512+],+"first_stage_model.encoder.mid.block_2.conv2.weight": [+512,+512,+3,+3+],+"first_stage_model.encoder.mid.block_2.norm1.weight": [+512+],+"first_stage_model.encoder.mid.block_2.norm2.bias": [+512+],+"first_stage_model.encoder.mid.block_2.norm2.weight": [+512+],+"first_stage_model.encoder.norm_out.bias": [+512+],+"first_stage_model.encoder.norm_out.weight": [+512+],+"first_stage_model.post_quant_conv.bias": [+4+],+"first_stage_model.post_quant_conv.weight": [+4,+4,+1,+1+],+"first_stage_model.quant_conv.bias": [+8+],+"first_stage_model.quant_conv.weight": [+8,+8,+1,+1+],+"model.diffusion_model.input_blocks.0.0.bias": [+320+],+"model.diffusion_model.input_blocks.0.0.weight": [+320,+4,+3,+3+],+"model.diffusion_model.label_emb.0.0.bias": [+1280+],+"model.diffusion_model.label_emb.0.0.weight": [+1280,+2816+],+"model.diffusion_model.label_emb.0.2.bias": [+1280+],+"model.diffusion_model.label_emb.0.2.weight": [+1280,+1280+],+"model.diffusion_model.middle_block.0.in_layers.0.bias": [+1280+],+"model.diffusion_model.middle_block.0.in_layers.0.weight": [+1280+],+"model.diffusion_model.middle_block.0.out_layers.0.bias": [+1280+],+"model.diffusion_model.middle_block.0.out_layers.0.weight": [+1280+],+"model.diffusion_model.out.0.bias": [+320+],+"model.diffusion_model.out.0.weight": [+320+],+"model.diffusion_model.output_blocks.0.0.in_layers.0.bias": [+2560+],+"model.diffusion_model.output_blocks.0.0.in_layers.0.weight": [+2560+],+"model.diffusion_model.output_blocks.0.0.out_layers.0.bias": [+1280+],+"model.diffusion_model.output_blocks.0.0.out_layers.0.weight": [+1280+],+"model.diffusion_model.output_blocks.0.0.skip_connection.bias": [+1280+],+"model.diffusion_model.output_blocks.0.0.skip_connection.weight": [+1280,+2560,+1,+1+],+"model.diffusion_model.output_blocks.0.1.norm.bias": [+1280+],+"model.diffusion_model.output_blocks.0.1.norm.weight": [+1280+],+"model.diffusion_model.output_blocks.0.1.proj_in.bias": [+1280+],+"model.diffusion_model.output_blocks.0.1.proj_in.weight": [+1280,+1280+],+"model.diffusion_model.output_blocks.0.1.proj_out.bias": [+1280+],+"model.diffusion_model.output_blocks.0.1.proj_out.weight": [+1280,+1280+],+"model.diffusion_model.output_blocks.0.1.transformer_blocks.0.attn1.to_k.weight": [+1280,+1280+],+"model.diffusion_model.output_blocks.0.1.transformer_blocks.0.attn1.to_out.0.bias": [+1280+],+"model.diffusion_model.output_blocks.0.1.transformer_blocks.0.attn1.to_out.0.weight": [+1280,+1280+],+"model.diffusion_model.output_blocks.0.1.transformer_blocks.0.attn1.to_q.weight": [+1280,+1280+],+"model.diffusion_model.output_blocks.0.1.transformer_blocks.0.attn1.to_v.weight": [+1280,+1280+],+"model.diffusion_model.output_blocks.0.1.transformer_blocks.0.attn2.to_k.weight": [+1280,+2048+],+"model.diffusion_model.output_blocks.0.1.transformer_blocks.0.attn2.to_out.0.bias": [+1280+],+"model.diffusion_model.output_blocks.0.1.transformer_blocks.0.attn2.to_out.0.weight": [+1280,+1280+],+"model.diffusion_model.output_blocks.0.1.transformer_blocks.0.attn2.to_q.weight": [+1280,+1280+],+"model.diffusion_model.output_blocks.0.1.transformer_blocks.0.attn2.to_v.weight": [+1280,+2048+],+"model.diffusion_model.output_blocks.0.1.transformer_blocks.0.ff.net.0.proj.bias": [+10240+],+"model.diffusion_model.output_blocks.0.1.transformer_blocks.0.ff.net.0.proj.weight": [+10240,+1280+],+"model.diffusion_model.output_blocks.0.1.transformer_blocks.0.norm1.bias": [+1280+],+"model.diffusion_model.output_blocks.0.1.transformer_blocks.0.norm1.weight": [+1280+],+"model.diffusion_model.output_blocks.0.1.transformer_blocks.0.norm2.bias": [+1280+],+"model.diffusion_model.output_blocks.0.1.transformer_blocks.0.norm2.weight": [+1280+],+"model.diffusion_model.output_blocks.0.1.transformer_blocks.0.norm3.bias": [+1280+],+"model.diffusion_model.output_blocks.0.1.transformer_blocks.0.norm3.weight": [+1280+],+"model.diffusion_model.time_embed.0.bias": [+1280+],+"model.diffusion_model.time_embed.0.weight": [+1280,+320+]+}+}diff --git a/studio/backend/tests/test_diffusion_sdxl.py b/studio/backend/tests/test_diffusion_sdxl.pyindex 6d7b14231c1..c87d4047862 100644--- a/studio/backend/tests/test_diffusion_sdxl.py+++ b/studio/backend/tests/test_diffusion_sdxl.py@@ -183,9 +183,10 @@ def test_sdxl_refiner_not_trusted():def test_sdxl_gguf_load_rejected_up_front():- # SDXL has no transformer-only GGUF variant (its single file is the whole pipeline), so a GGUF request fails cheap validation before the GPU handoff.+ # SDXL's single file is the whole pipeline, so only an on-disk GGUF carrying all of it loads (#11391); a Hub+ # GGUF request still fails cheap validation before the GPU handoff.backend = DiffusionBackend()- with pytest.raises(ValueError, match = "no GGUF"):+ with pytest.raises(ValueError, match = "also carries the text encoders and VAE"):backend.validate_load_request("some-org/my-sdxl.gguf", gguf_filename = "my-sdxl.gguf", family_override = "sdxl")diff --git a/studio/backend/tests/test_sdxl_whole_pipeline_gguf.py b/studio/backend/tests/test_sdxl_whole_pipeline_gguf.pynew file mode 100644index 00000000000..bbd834491c2--- /dev/null+++ b/studio/backend/tests/test_sdxl_whole_pipeline_gguf.py@@ -0,0 +1,391 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""SDXL single-file GGUFs (#11391): a stable-diffusion.cpp ``convert`` of a community SDXL checkpoint holds the UNet,+both text encoders and the VAE, with no ``general.architecture``. It lists on the Images page, validates for the+diffusers load, and a denoiser-only SDXL GGUF still gets a precise refusal. The fixture is the real header of+RealVisXL_V4.0 converted to q8_0 (names and shapes, trimmed to index 0 of every stack)."""++from __future__ import annotations++import json+import struct+import sys+import types+from pathlib import Path++import pytest++from core.inference import diffusion_content as dc+from core.inference import diffusion_families as df+from hub.services.models import catalog_classification as cc++_FIXTURE = json.loads(+ (Path(__file__).parent / "fixtures" / "sdxl_whole_pipeline_gguf_header.json").read_text(+ encoding = "utf-8"+ )+)+_SHAPES: dict = _FIXTURE["shapes"]+_UNET = {k: v for k, v in _SHAPES.items() if k.startswith("model.diffusion_model.")}+_NO_VAE = {k: v for k, v in _SHAPES.items() if not k.startswith("first_stage_model.")}+++def _write_gguf(+ path: Path,+ shapes: dict,+ arch: str | None = None,+) -> Path:+ """A GGUF header with ``shapes`` and, like sd.cpp's convert, no metadata unless ``arch`` is given."""++ def s(text):+ b = text.encode()+ return struct.pack("<Q", len(b)) + b++ out = struct.pack("<IIQQ", 0x46554747, 3, len(shapes), 1 if arch else 0)+ if arch:+ out += s("general.architecture") + struct.pack("<I", 8) + s(arch)+ for name, shape in shapes.items():+ dims = list(reversed(shape))+ out += s(name) + struct.pack("<I", len(dims)) + struct.pack(f"<{len(dims)}Q", *dims)+ out += struct.pack("<IQ", 0, 0)+ path.parent.mkdir(parents = True, exist_ok = True)+ path.write_bytes(out)+ return path+++def test_fixture_is_the_three_part_sd_cpp_layout():+ tops = {k.split(".", 1)[0] for k in _SHAPES}+ assert tops == {"model", "conditioner", "first_stage_model"}+ assert "model.diffusion_model.label_emb.0.0.weight" in _SHAPES+++def test_whole_pipeline_gguf_is_an_sdxl_checkpoint(tmp_path):+ path = _write_gguf(tmp_path / "RealVisXL_V4.0-q8_0.gguf", _SHAPES)+ info = dc.inspect_checkpoint(str(path))+ assert (info.role, info.family, info.page, info.whole_pipeline) == (+ "dit",+ "sdxl",+ "image",+ True,+ )+ assert dc.whole_pipeline_gguf_family(str(path)) == "sdxl"++[email protected]("shapes", [_UNET, _NO_VAE], ids = ["unet_only", "no_vae"])+def test_partial_sdxl_gguf_is_not_a_whole_pipeline(tmp_path, shapes):+ path = _write_gguf(tmp_path / "sdxl_unet-q8_0.gguf", shapes)+ info = dc.inspect_checkpoint(str(path))+ assert info.family == "sdxl" and not info.whole_pipeline+ assert dc.whole_pipeline_gguf_family(str(path)) is None+++def test_legacy_sd_cpp_text_encoder_layout_is_refused_up_front(tmp_path):+ from core.inference.diffusion import get_diffusion_backend++ legacy = {+ k.replace("conditioner.embedders.0.transformer.", "cond_stage_model.transformer.").replace(+ "conditioner.embedders.1.model.", "cond_stage_model.1.transformer.text_model."+ ): v+ for k, v in _SHAPES.items()+ }+ path = _write_gguf(tmp_path / "stable-diffusion-xl-base-1.0-Q4_0.gguf", legacy)+ assert dc.whole_pipeline_gguf_family(str(path)) is None+ with pytest.raises(ValueError, match = "also carries the text encoders and VAE"):+ get_diffusion_backend().validate_load_request(+ str(tmp_path), gguf_filename = "stable-diffusion-xl-base-1.0-Q4_0.gguf", model_kind = "gguf"+ )+++def test_whole_pipeline_safetensors_still_reports_its_layout(tmp_path):+ # The flag rides on CheckpointInfo for every format; a .safetensors path never takes the GGUF route.+ header = {k: {"dtype": "F16", "shape": v, "data_offsets": [0, 0]} for k, v in _SHAPES.items()}+ raw = json.dumps(header).encode()+ path = tmp_path / "RealVisXL_V4.0.safetensors"+ path.write_bytes(struct.pack("<Q", len(raw)) + raw)+ assert dc.inspect_checkpoint(str(path)).whole_pipeline+ assert dc.whole_pipeline_gguf_family(str(path)) is None+++def test_whole_pipeline_gguf_lists_on_the_images_page(tmp_path):+ path = _write_gguf(tmp_path / "RealVisXL_V4.0-q8_0.gguf", _SHAPES)+ # Before: no architecture key fell through to the name, which reads as a chat model (task None).+ assert cc._gguf_file_task(path, ()) == "text-to-image"+++def test_denoiser_only_sdxl_gguf_keeps_its_old_classification(tmp_path):+ path = _write_gguf(tmp_path / "sdxl_unet-q8_0.gguf", _UNET)+ assert cc._gguf_file_task(path, ()) == cc._arch_to_task(None, name_hints = ())+++def test_llm_gguf_classification_is_unchanged(tmp_path):+ path = _write_gguf(+ tmp_path / "Qwen3-0.6B-Q8_0.gguf", {"token_embd.weight": [151936, 1024]}, "qwen3"+ )+ assert cc._gguf_file_task(path, ()) == "text-generation"+ # An arch-less GGUF that is not a diffusion checkpoint falls back exactly as before.+ other = _write_gguf(tmp_path / "mystery.gguf", {"blk.0.attn_q.weight": [8, 8]})+ assert cc._gguf_file_task(other, ()) == cc._arch_to_task(None, name_hints = ())+++def test_validation_accepts_a_whole_pipeline_gguf(tmp_path):+ from core.inference.diffusion import get_diffusion_backend++ _write_gguf(tmp_path / "RealVisXL_V4.0-q8_0.gguf", _SHAPES)+ fam = get_diffusion_backend().validate_load_request(+ str(tmp_path), gguf_filename = "RealVisXL_V4.0-q8_0.gguf", model_kind = "gguf"+ )+ assert fam.name == "sdxl" and fam.single_file_is_pipeline+++def test_comfy_checkpoints_layout_validates_too(tmp_path):+ from core.inference.diffusion import get_diffusion_backend++ folder = tmp_path / "ComfyUI" / "models" / "checkpoints"+ _write_gguf(folder / "RealVisXL_V4.0-q8_0.gguf", _SHAPES)+ fam = get_diffusion_backend().validate_load_request(+ str(folder), gguf_filename = "RealVisXL_V4.0-q8_0.gguf", model_kind = "gguf"+ )+ assert fam.name == "sdxl"++[email protected]("shapes", [_UNET, _NO_VAE], ids = ["unet_only", "no_vae"])+def test_validation_refuses_a_partial_sdxl_gguf_precisely(tmp_path, shapes):+ from core.inference.diffusion import get_diffusion_backend+ _write_gguf(tmp_path / "sdxl_unet-q8_0.gguf", shapes)+ with pytest.raises(ValueError, match = "also carries the text encoders and VAE"):+ get_diffusion_backend().validate_load_request(+ str(tmp_path), gguf_filename = "sdxl_unet-q8_0.gguf", model_kind = "gguf"+ )+++def test_validation_refuses_a_hub_sdxl_gguf(tmp_path):+ from core.inference.diffusion import get_diffusion_backend+ with pytest.raises(ValueError, match = "on disk"):+ get_diffusion_backend().validate_load_request(+ "someone/sdxl-gguf",+ gguf_filename = "sdxl-q8_0.gguf",+ model_kind = "gguf",+ family_override = "sdxl",+ )+++def test_the_load_branch_routes_whole_pipeline_ggufs_to_the_bundle_loader():+ src = (Path(__file__).parents[1] / "core" / "inference" / "diffusion.py").read_text(+ encoding = "utf-8"+ )+ branch = src[+ src.index('elif kind in ("single_file", "gguf") and fam.single_file_is_pipeline:') :+ ]+ branch = branch[: branch.index("\n else:\n")]+ assert "load_whole_pipeline_gguf(" in branch+ assert "_dequantize_gguf_outside_linears(" in branch+ # Auto precision must not take the dense fast path, which would load the base repo's UNet instead.+ assert 'if kind == "gguf" and fam.single_file_is_pipeline:\n' in src+++def test_bundle_loader_redirects_only_its_own_file(monkeypatch):+ from core.inference import diffusion_gguf_pipeline as gp++ reads = []++ def real_read(link, *args, **kwargs):+ reads.append(link)+ return {+ "model.diffusion_model.input_blocks.0.0.weight": "unet",+ "conditioner.embedders.0.transformer.x": "te",+ "first_stage_model.decoder.conv_in.weight": "vae",+ }++ single_file = types.ModuleType("diffusers.loaders.single_file")+ single_file.load_single_file_checkpoint = real_read+ utils = types.ModuleType("diffusers.loaders.single_file_utils")+ utils.load_single_file_checkpoint = real_read+ gguf_utils = types.ModuleType("diffusers.quantizers.gguf.utils")+ gguf_utils.GGUFParameter = type("GGUFParameter", (), {})+ gguf_utils.dequantize_gguf_tensor = lambda t: t+ diffusers = types.ModuleType("diffusers")+ diffusers.GGUFQuantizationConfig = lambda compute_dtype: ("gguf", compute_dtype)+ for name, mod in {+ "diffusers": diffusers,+ "diffusers.loaders": types.ModuleType("diffusers.loaders"),+ "diffusers.loaders.single_file": single_file,+ "diffusers.loaders.single_file_utils": utils,+ "diffusers.quantizers": types.ModuleType("diffusers.quantizers"),+ "diffusers.quantizers.gguf": types.ModuleType("diffusers.quantizers.gguf"),+ "diffusers.quantizers.gguf.utils": gguf_utils,+ }.items():+ monkeypatch.setitem(sys.modules, name, mod)+ diffusers.loaders = sys.modules["diffusers.loaders"]+ sys.modules["diffusers.loaders"].single_file = single_file++ seen = {}++ class Unet:+ @classmethod+ def from_single_file(cls, sd, **kwargs):+ seen["unet_sd"], seen["unet_kwargs"] = sd, kwargs+ return "UNET"++ class Pipe:+ @classmethod+ def from_single_file(cls, path, **kwargs):+ seen["pipe_kwargs"] = kwargs+ seen["pipe_read"] = single_file.load_single_file_checkpoint(path)+ seen["other_read"] = single_file.load_single_file_checkpoint("/elsewhere.safetensors")+ return "PIPE"++ out = gp.load_whole_pipeline_gguf(+ Pipe,+ Unet,+ "/m/RealVisXL_V4.0-q8_0.gguf",+ {+ "config": "stabilityai/stable-diffusion-xl-base-1.0",+ "local_files_only": True,+ "torch_dtype": "bf16",+ },+ dtype = "bf16",+ )+ assert out == "PIPE"+ assert list(seen["unet_sd"]) == ["model.diffusion_model.input_blocks.0.0.weight"]+ assert seen["unet_kwargs"]["subfolder"] == "unet"+ assert seen["unet_kwargs"]["quantization_config"] == ("gguf", "bf16")+ assert seen["unet_kwargs"]["local_files_only"] is True+ assert seen["pipe_kwargs"]["unet"] == "UNET"+ assert set(seen["pipe_read"]) == {+ "conditioner.embedders.0.transformer.x",+ "first_stage_model.decoder.conv_in.weight",+ }+ # Another file read during the load reaches the real reader, and the swap is undone afterwards.+ assert reads == ["/m/RealVisXL_V4.0-q8_0.gguf", "/elsewhere.safetensors"]+ assert single_file.load_single_file_checkpoint is real_read+++def test_family_detection_for_the_pick_is_sdxl(tmp_path):+ _write_gguf(tmp_path / "RealVisXL_V4.0-q8_0.gguf", _SHAPES)+ fam = df.detect_family_for_pick(str(tmp_path), "RealVisXL_V4.0-q8_0.gguf")+ assert fam is not None and fam.name == "sdxl"+++def test_whole_pipeline_gguf_stages_only_the_base_config(tmp_path, monkeypatch):+ import huggingface_hub++ from core.inference.diffusion import DiffusionBackend++ _write_gguf(tmp_path / "RealVisXL_V4.0-q8_0.gguf", _SHAPES)+ names = [+ "model_index.json",+ "unet/config.json",+ "unet/diffusion_pytorch_model.safetensors",+ "text_encoder/model.safetensors",+ "tokenizer/vocab.json",+ "vae/diffusion_pytorch_model.safetensors",+ ]+ listing = types.SimpleNamespace(+ siblings = [types.SimpleNamespace(rfilename = n, size = 10**9) for n in names], sha = "abc"+ )+ monkeypatch.setattr(+ huggingface_hub,+ "HfApi",+ lambda: types.SimpleNamespace(model_info = lambda *a, **k: listing),+ )+ _total, files = DiffusionBackend._estimate_download_bytes(+ str(tmp_path),+ "RealVisXL_V4.0-q8_0.gguf",+ "stabilityai/stable-diffusion-xl-base-1.0",+ None,+ kind = "gguf",+ single_file_is_pipeline = True,+ )+ # The GGUF carries the UNet, text encoders and VAE: no base weight is staged.+ assert sorted(files) == ["model_index.json", "tokenizer/vocab.json", "unet/config.json"]+++def test_whole_pipeline_gguf_resident_prices_dequantized_components(tmp_path, monkeypatch):+ from core.inference import diffusion_gguf_pipeline as gp++ q8, f16 = object(), object()+ tensors = [+ # quantized UNet linear: stays packed (100 bytes)+ types.SimpleNamespace(+ name = "model.diffusion_model.a.weight",+ shape = [8, 8],+ tensor_type = q8,+ n_bytes = 100,+ n_elements = 64,+ ),+ # quantized UNet conv and a quantized text encoder linear: both dequantized+ types.SimpleNamespace(+ name = "model.diffusion_model.c.weight",+ shape = [2, 2, 2, 2],+ tensor_type = q8,+ n_bytes = 30,+ n_elements = 16,+ ),+ types.SimpleNamespace(+ name = "conditioner.embedders.0.w",+ shape = [8, 8],+ tensor_type = q8,+ n_bytes = 70,+ n_elements = 64,+ ),+ ]+ fake = types.ModuleType("gguf")+ fake.GGMLQuantizationType = types.SimpleNamespace(F32 = f16, F16 = f16, BF16 = f16)+ fake.GGUFReader = lambda path: types.SimpleNamespace(tensors = tensors)+ monkeypatch.setitem(sys.modules, "gguf", fake)+ mib = 1024 * 1024+ for t in tensors:+ t.n_bytes *= mib+ t.n_elements *= mib+ # 100 packed + (16 + 64) * 2 dense = 260 MiB, plus the 5% margin+ assert gp.whole_pipeline_gguf_resident_mib("x.gguf") == int(260 * 1.05)+ assert gp.whole_pipeline_gguf_resident_mib("x.gguf", dense_bytes = 4) == int(420 * 1.05)+ monkeypatch.setattr(fake, "GGUFReader", lambda path: (_ for _ in ()).throw(OSError("bad")))+ assert gp.whole_pipeline_gguf_resident_mib("x.gguf") is None+++def test_status_reports_the_header_variant_recipe(tmp_path):+ from core.inference.diffusion import _generation_defaults_for++ # A renamed FLUX.1-dev whose base resolves to schnell: the header variant decides, as the OpenAI route does.+ shapes = {+ "double_blocks.0.img_attn.qkv.weight": [9216, 3072],+ "single_blocks.0.linear1.weight": [21504, 3072],+ "vector_in.in_layer.weight": [3072, 768],+ "img_in.weight": [3072, 64],+ "guidance_in.in_layer.weight": [3072, 256],+ }+ header = {k: {"dtype": "BF16", "shape": v, "data_offsets": [0, 0]} for k, v in shapes.items()}+ raw = json.dumps(header).encode()+ (tmp_path / "my_flux.safetensors").write_bytes(struct.pack("<Q", len(raw)) + raw)+ assert dc.content_variant_hint(str(tmp_path), "my_flux.safetensors") == "flux.1-dev"+ got = _generation_defaults_for(+ str(tmp_path), "my_flux.safetensors", "black-forest-labs/FLUX.1-schnell"+ )+ assert (got["steps"], got["guidance"]) == df.default_generation_params("flux.1-dev")+ assert (got["steps"], got["guidance"]) != df.default_generation_params(+ "black-forest-labs/FLUX.1-schnell"+ )+ # SDXL fine-tune with an opaque name: its base names the family.+ _write_gguf(tmp_path / "RealVisXL_V4.0-q8_0.gguf", _SHAPES)+ got = _generation_defaults_for(+ str(tmp_path), "RealVisXL_V4.0-q8_0.gguf", "stabilityai/stable-diffusion-xl-base-1.0"+ )+ assert got == {"steps": 25, "guidance": 7.0}+++def test_lora_on_a_whole_pipeline_gguf_is_refused_before_the_load(tmp_path):+ from core.inference.diffusion import get_diffusion_backend++ _write_gguf(tmp_path / "RealVisXL_V4.0-q8_0.gguf", _SHAPES)+ backend = get_diffusion_backend()+ with pytest.raises(ValueError, match = "LoRA is not available on a whole-pipeline GGUF"):+ backend.begin_load(+ str(tmp_path),+ gguf_filename = "RealVisXL_V4.0-q8_0.gguf",+ model_kind = "gguf",+ local_files_only = True,+ loras = [("some/sdxl-lora", 1.0)],+ )+ # Nothing started: the resident model was never evicted.+ assert backend._loading is Nonediff --git a/studio/frontend/src/features/images/api.ts b/studio/frontend/src/features/images/api.tsindex 953bc16bfac..59e5de6e90d 100644--- a/studio/frontend/src/features/images/api.ts+++ b/studio/frontend/src/features/images/api.ts@@ -77,6 +77,8 @@ export interface DiffusionStatus {// Per-Advanced-control provenance, keyed by control name. Present only when a model is loaded on a// backend that records it; absent on older backends.resolved?: Record<string, DiffusionResolvedControl> | null;+ // Default steps / guidance the backend renders the loaded model with (file header before base repo).+ generation_defaults?: { steps?: number; guidance?: number } | null;}export interface DiffusionConditioning {diff --git a/studio/frontend/src/features/images/image-generation-defaults.ts b/studio/frontend/src/features/images/image-generation-defaults.tsindex 75d8819311f..810c9061670 100644--- a/studio/frontend/src/features/images/image-generation-defaults.ts+++ b/studio/frontend/src/features/images/image-generation-defaults.ts@@ -65,6 +65,28 @@ export function defaultsKeyFor(repoId: string, familyOverride: unknown): stringreturn defaultsFor(repoId) !== DEFAULT_GEN ? repoId : (explicitFamily(familyOverride) ?? repoId);}+/** The loaded model's recipe for a pick that got the fallback (its name named no family), else null. */+export function loadedRecipeFor(+ pickDefaults: { steps: number; guidance: number } | null | undefined,+ residentKey: string,+ reported?: { steps?: number; guidance?: number } | null,+): { steps: number; guidance: number } | null {+ if (pickDefaults !== DEFAULT_GEN) return null;+ const resident = residentRecipeFor(residentKey, reported);+ return resident.steps === DEFAULT_GEN.steps && resident.guidance === DEFAULT_GEN.guidance ? null : resident;+}++/** The resident model's recipe: the backend's own when it reports one, else the base-repo key's. */+export function residentRecipeFor(+ residentKey: string,+ reported?: { steps?: number; guidance?: number } | null,+): { steps: number; guidance: number } {+ if (reported && typeof reported.steps === "number" && typeof reported.guidance === "number") {+ return { steps: reported.steps, guidance: reported.guidance };+ }+ return defaultsFor(residentKey);+}+export function residentDefaultsKey(repoId: string,baseRepo: string | null | undefined,diff --git a/studio/frontend/src/features/images/images-page.tsx b/studio/frontend/src/features/images/images-page.tsxindex 87e2ad02d8d..7cd6a9537a8 100644--- a/studio/frontend/src/features/images/images-page.tsx+++ b/studio/frontend/src/features/images/images-page.tsx@@ -187,7 +187,15 @@ import {import { toast } from "@/lib/toast";import { loadGalleryUntil } from "@/lib/gallery-deep-link";import { subscribeModelEjected } from "@/lib/model-lifecycle-events";-import { DEFAULT_GEN, defaultsFor, defaultsKeyFor, residentDefaultsKey, resolutionFor } from "./image-generation-defaults";+import {+ DEFAULT_GEN,+ defaultsFor,+ defaultsKeyFor,+ loadedRecipeFor,+ residentDefaultsKey,+ residentRecipeFor,+ resolutionFor,+} from "./image-generation-defaults";import {MIN_DIM,type SizeLimits,@@ -1474,10 +1482,13 @@ export function ImagesPage({// Whether the user has taken the recipe since the pick still waiting for its status: a preset// selected while the model downloaded is newer than that pick.const pickRecipeSuperseded = useRef<(() => boolean) | null>(null);+ // The recipe the last pick applied, so a load that reveals the family can replace a fallback.+ const pickDefaults = useRef<{ steps: number; guidance: number } | null>(null);// Put back everything a pick optimistically applied. Setters are stable, so this never re-renders on its own.const revertPick = useCallback((r: PickRevert) => {setQuant(r.prev);setPendingModelDefaults(null);+ pickDefaults.current = null;// Equality alone cannot tell "nobody touched this" from "the user chose the same number": a// preset selected after the pick owns these fields.if (!pickRecipeSuperseded.current?.()) {@@ -1703,10 +1714,12 @@ export function ImagesPage({[batchSize, count, guidance, height, negativePrompt, steps, width],);const residentDefaults = residentDefaultsKey(status?.repo_id ?? "", status?.base_repo, status?.resolved?.family_override);+ const { steps: residentSteps, guidance: residentGuidance } = residentRecipeFor(+ residentDefaults,+ status?.generation_defaults,+ );const imageDefaultRecipe = useMemo<ImageGenerationPresetParams>(() => {- const recommended =- pendingModelDefaults ??- defaultsFor(residentDefaults);+ const recommended = pendingModelDefaults ?? { steps: residentSteps, guidance: residentGuidance };// Reset restores the resident build's canvas, the same one the seed above applied. A constant// here would quietly undo it and put a 24 GB card back over its budget.const size = resolutionFor(status?.base_repo ?? status?.repo_id ?? "", {@@ -1725,7 +1738,8 @@ export function ImagesPage({};}, [pendingModelDefaults,- residentDefaults,+ residentSteps,+ residentGuidance,status?.base_repo,status?.repo_id,status?.model_kind,@@ -1770,6 +1784,7 @@ export function ImagesPage({const claimedAt = imageFormClaimId();pickRecipeSuperseded.current = () => imageFormClaimId() !== claimedAt;const recommended = defaultsFor(defaultsKeyFor(repoId, effectiveFamilyOverride));+ pickDefaults.current = recommended;setPendingModelDefaults(recommended);setSteps(recommended.steps);setGuidance(recommended.guidance);@@ -2636,6 +2651,17 @@ export function ImagesPage({setRememberedModel(remembered);}setBusy(null);+ // A fallback-recipe pick takes the loaded family recipe on an untouched form (else SDXL runs 9 steps, CFG 0).+ const loadedRecipe = loadedRecipeFor(+ pickDefaults.current,+ residentDefaultsKey(loaded.repo_id ?? "", loaded.base_repo, loaded.resolved?.family_override),+ loaded.generation_defaults,+ );+ pickDefaults.current = null;+ if (loadedRecipe && !pickRecipeSuperseded.current?.()) {+ setSteps((cur) => (cur === DEFAULT_GEN.steps ? loadedRecipe.steps : cur));+ setGuidance((cur) => (cur === DEFAULT_GEN.guidance ? loadedRecipe.guidance : cur));+ }// Load succeeded: the optimistic quant is now the real one, so drop the pending revert.quantRevert.current?.commitRecipeClaim?.();quantRevert.current = null;@@ -2801,7 +2827,7 @@ export function ImagesPage({const repoId = status?.loaded ? status.repo_id : null;if (!repoId) return;if (lastLoad.current) return;- const seedKey = `${repoId}\0${residentDefaults}`;+ const seedKey = `${repoId}\0${residentDefaults}\0${residentSteps}\0${residentGuidance}`;if (seededResident.current === seedKey) return;seededResident.current = seedKey;// Wire Reapply to the resident model too. Only a full pipeline is reloadable by repo id@@ -2815,7 +2841,7 @@ export function ImagesPage({residentSeeded.current = true;if (imagePresets.storedRecipe) return;}- const d = defaultsFor(residentDefaults);+ const d = { steps: residentSteps, guidance: residentGuidance };setPendingModelDefaults(null);setSteps(d.steps);setGuidance(d.guidance);@@ -2835,6 +2861,8 @@ export function ImagesPage({}, [imagePresets.storedRecipe,residentDefaults,+ residentSteps,+ residentGuidance,status?.display_repo_id,status?.loaded,status?.repo_id,diff --git a/studio/frontend/tests/image-generation-defaults.test.ts b/studio/frontend/tests/image-generation-defaults.test.tsindex 529f46a8371..0bb5a44cab1 100644--- a/studio/frontend/tests/image-generation-defaults.test.ts+++ b/studio/frontend/tests/image-generation-defaults.test.ts@@ -8,7 +8,9 @@ import test from "node:test";import {defaultsFor,defaultsKeyFor,+ loadedRecipeFor,residentDefaultsKey,+ residentRecipeFor,resolutionFor,} from "../src/features/images/image-generation-defaults.ts";@@ -188,3 +190,49 @@ test("every Qwen-Image-Layered spelling the backend accepts gets its 20 / 2.5 reassert.deepEqual(defaultsFor(id), { steps: 20, guidance: 2.5 }, id);}});++test("a community single file picked by path takes its family recipe once loaded (#11391)", () => {+ const pick = defaultsFor(defaultsKeyFor("/models/checkpoints/RealVisXL_V4.0.safetensors", null));+ const resident = residentDefaultsKey(+ "/models/checkpoints",+ "stabilityai/stable-diffusion-xl-base-1.0",+ { value: "sdxl", source: "auto" },+ );+ assert.deepEqual(loadedRecipeFor(pick, resident), { steps: 25, guidance: 7 });+ // A pick whose name already chose a recipe keeps it (Schnell is not re-seeded as dev).+ assert.equal(+ loadedRecipeFor(defaultsFor("black-forest-labs/FLUX.1-schnell"), "black-forest-labs/FLUX.1-dev"),+ null,+ );+ // An unrecognised resident leaves the form alone.+ assert.equal(loadedRecipeFor(pick, "/models/unknown"), null);+ assert.equal(loadedRecipeFor(null, resident), null);+ // The backend's header-read recipe wins: a renamed FLUX.1-dev keeps 20 steps, not its schnell base's 4.+ const schnellBase = residentDefaultsKey("/models/my_flux.safetensors", "black-forest-labs/FLUX.1-schnell", null);+ assert.deepEqual(loadedRecipeFor(pick, schnellBase, { steps: 20, guidance: 3.5 }), { steps: 20, guidance: 3.5 });+ assert.equal(loadedRecipeFor(pick, schnellBase, { steps: 9, guidance: 0 }), null);+});++test("the Images page applies the loaded family recipe only to an untouched fallback form", () => {+ const src = readSrc("features/images/images-page.tsx");+ const ready = src.slice(src.indexOf('if (p.phase === "ready")'), src.indexOf('if (p.phase === "error")'));+ assert.match(ready, /loadedRecipeFor\(\s*pickDefaults\.current/);+ assert.match(ready, /!pickRecipeSuperseded\.current\?\.\(\)/);+ assert.match(ready, /cur === DEFAULT_GEN\.steps \? loadedRecipe\.steps : cur/);+});++test("the resident recipe prefers the backend-reported one", () => {+ const schnellBase = residentDefaultsKey("/models/my_flux.safetensors", "black-forest-labs/FLUX.1-schnell", null);+ assert.deepEqual(residentRecipeFor(schnellBase, { steps: 20, guidance: 3.5 }), { steps: 20, guidance: 3.5 });+ // An older backend (or the native engine) reports nothing: the base-repo key decides, as before.+ assert.deepEqual(residentRecipeFor(schnellBase, null), defaultsFor("black-forest-labs/FLUX.1-schnell"));+ assert.deepEqual(residentRecipeFor(schnellBase, {}), defaultsFor("black-forest-labs/FLUX.1-schnell"));+});++test("the Images page seeds Default from the resident recipe and drops the pick token on revert", () => {+ const src = readSrc("features/images/images-page.tsx");+ assert.match(src, /residentRecipeFor\(\s*residentDefaults,\s*status\?\.generation_defaults/);+ assert.doesNotMatch(src, /defaultsFor\(residentDefaults\)/);+ const revert = src.slice(src.indexOf("const revertPick = useCallback"), src.indexOf("}, []);", src.indexOf("const revertPick = useCallback")));+ assert.match(revert, /pickDefaults\.current = null/);+});