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 sd.cpp: use BF16 cuBLAS for Q8_0 only when every GGUF the process loads is Q8_0 (#15054)

Daniel Han74b699513c4a
diff --git a/studio/backend/core/inference/sd_cpp_args.py b/studio/backend/core/inference/sd_cpp_args.py
index aa771145548..b1e86a1e2a5 100644
--- a/studio/backend/core/inference/sd_cpp_args.py
+++ b/studio/backend/core/inference/sd_cpp_args.py
@@ -170,6 +170,30 @@ def gguf_quantized_weight_types(path: Optional[str]) -> Optional[frozenset[str]]
return None
+def model_files_quantized_weight_types(files: "SdCppModelFiles") -> Optional[frozenset[str]]:
+ """Quantized types across every loaded file (the env override is process-wide), or None if any GGUF is unreadable."""
+ types = gguf_quantized_weight_types(files.diffusion_model)
+ if types is None:
+ return None
+ for path in (
+ files.vae,
+ files.audio_vae,
+ files.clip_l,
+ files.clip_g,
+ files.t5xxl,
+ files.llm,
+ files.llm_vision,
+ files.qwen2vl,
+ ):
+ if not path or not str(path).lower().endswith(".gguf"):
+ continue
+ extra = gguf_quantized_weight_types(path)
+ if extra is None:
+ return None
+ types |= extra
+ return types
+
+
def quant_cublas_env(
cuda_ccs: Sequence[tuple[int, int]],
environ: Optional[dict] = None,
diff --git a/studio/backend/core/inference/sd_cpp_backend.py b/studio/backend/core/inference/sd_cpp_backend.py
index b5143546d41..494048bff36 100644
--- a/studio/backend/core/inference/sd_cpp_backend.py
+++ b/studio/backend/core/inference/sd_cpp_backend.py
@@ -3679,7 +3679,7 @@ class SdCppDiffusionBackend:
@functools.lru_cache(maxsize = 1)
def _diffusion_weight_types() -> Optional[frozenset[str]]:
- return sd_cpp_args_mod.gguf_quantized_weight_types(paths.get("diffusion_model"))
+ return sd_cpp_args_mod.model_files_quantized_weight_types(files)
# The device pin is NOT folded in here: the binary can still change below, through the deferred
# accelerator install, the post-download re-resolve, or a server start that falls back to one-shot, and
diff --git a/studio/backend/tests/test_sd_cpp_args.py b/studio/backend/tests/test_sd_cpp_args.py
index 9bb3aea1c68..5bff66dd158 100644
--- a/studio/backend/tests/test_sd_cpp_args.py
+++ b/studio/backend/tests/test_sd_cpp_args.py
@@ -1165,6 +1165,9 @@ def test_gguf_quantized_weight_types_reads_the_tensor_table(tmp_path):
for tname, arr, qtype in tensors:
if qtype is None:
w.add_tensor(tname, arr)
+ elif arr is None: # gguf-py cannot quantize k-quants: write zeroed blocks of that type
+ blocks = np.zeros((4, gguf.GGML_QUANT_SIZES[qtype][1]), dtype = np.uint8)
+ w.add_tensor(tname, blocks, raw_dtype = qtype)
else:
w.add_tensor(tname, gguf.quants.quantize(arr, qtype), raw_dtype = qtype)
w.write_header_to_file()
@@ -1188,3 +1191,24 @@ def test_gguf_quantized_weight_types_reads_the_tensor_table(tmp_path):
assert types_of(str(tmp_path / "missing.gguf")) is None
assert types_of(str(tmp_path / "model.safetensors")) is None
assert types_of(None) is None
+
+ k_quant = write("te_q4k.gguf", [("w", None, gguf.GGMLQuantizationType.Q4_K)])
+ dense = write("vae_f16.gguf", [("w", x.astype(np.float16), None)])
+ all_types = _sd_cpp_args_module.model_files_quantized_weight_types
+
+ def route(files):
+ return _sd_cpp_args_module.quant_cublas_env(
+ [(10, 0)], environ = {}, weight_types = all_types(files)
+ )
+
+ with_k_te = SdCppModelFiles(diffusion_model = q8, llm = k_quant)
+ assert all_types(with_k_te) == frozenset({"Q8_0", "Q4_K"})
+ assert route(with_k_te) == {}
+ assert route(SdCppModelFiles(diffusion_model = q8, t5xxl = k_quant, vae = dense)) == {}
+ q8_only = SdCppModelFiles(
+ diffusion_model = q8, llm = q8, vae = dense, clip_l = str(tmp_path / "c.safetensors")
+ )
+ assert all_types(q8_only) == frozenset({"Q8_0"})
+ assert route(q8_only) == {"GGML_CUDA_QUANT_CUBLAS_MIN_BATCH": "1024"}
+ assert all_types(SdCppModelFiles(diffusion_model = q8, llm = str(tmp_path / "x.gguf"))) is None
+ assert all_types(SdCppModelFiles(diffusion_model = str(tmp_path / "m.safetensors"))) is None
diff --git a/studio/backend/tests/test_sd_cpp_backend.py b/studio/backend/tests/test_sd_cpp_backend.py
index eba69d59842..d938c4ce07b 100644
--- a/studio/backend/tests/test_sd_cpp_backend.py
+++ b/studio/backend/tests/test_sd_cpp_backend.py
@@ -1460,6 +1460,7 @@ def _run_server_load(
gguf_filename = "z.gguf",
family_override = None,
gpu_ordinal = None,
+ asset_paths = None,
):
fam = detect_family(fam_name)
monkeypatch.setattr(bk, "find_sd_server_binary", lambda: "/x/sd-server")
@@ -1476,7 +1477,10 @@ def _run_server_load(
monkeypatch.setattr(
b,
"_fetch_assets",
- lambda *a, **k: {"diffusion_model": "/m/z.gguf", "vae": "/m/vae.sft", "llm": "/m/llm.sft"},
+ lambda *a, **k: dict(
+ asset_paths
+ or {"diffusion_model": "/m/z.gguf", "vae": "/m/vae.sft", "llm": "/m/llm.sft"}
+ ),
)
monkeypatch.setattr(
bk, "resolve_diffusion_device_target", lambda: types.SimpleNamespace(device = device)
@@ -3008,11 +3012,53 @@ def test_a_k_quant_diffusion_gguf_keeps_mmq(monkeypatch, weight_types):
b = SdCppDiffusionBackend()
servers: list = []
_run_server_load(monkeypatch, b, servers, device = "cuda")
- assert seen == ["/m/z.gguf"] # the diffusion model, not the encoder or VAE
+ assert seen == ["/m/z.gguf"]
assert servers[-1].env is None
assert dict(b._state.child_env) == {}
+ "companions,expected",
+ [
+ ({"llm": ("/m/llm.gguf", frozenset({"Q4_K", "Q6_K"}))}, None),
+ (
+ {
+ "llm": ("/m/llm.gguf", frozenset({"Q8_0"})),
+ "vae": ("/m/vae.gguf", frozenset({"Q5_K"})),
+ },
+ None,
+ ),
+ ({"llm": ("/m/llm.gguf", None)}, None),
+ (
+ {"llm": ("/m/llm.gguf", frozenset({"Q8_0"})), "vae": ("/m/vae.gguf", frozenset())},
+ "1024",
+ ),
+ ],
+)
+def test_a_q8_0_diffusion_gguf_with_a_k_quant_companion_keeps_mmq(
+ monkeypatch, companions, expected
+):
+ monkeypatch.delenv("GGML_CUDA_QUANT_CUBLAS_MIN_BATCH", raising = False)
+ monkeypatch.setattr(bk, "_torch_cuda_capabilities", lambda ordinal: [(10, 0)])
+ types_by_path = {"/m/z.gguf": frozenset({"Q8_0"})}
+ types_by_path.update(dict(companions.values()))
+ seen: list = []
+ monkeypatch.setattr(
+ bk.sd_cpp_args_mod,
+ "gguf_quantized_weight_types",
+ lambda path: seen.append(path) or types_by_path[path],
+ )
+ paths = {"diffusion_model": "/m/z.gguf", "vae": "/m/vae.sft", "llm": "/m/llm.sft"}
+ paths.update({kind: path for kind, (path, _types) in companions.items()})
+ b = SdCppDiffusionBackend()
+ servers: list = []
+ _run_server_load(monkeypatch, b, servers, device = "cuda", asset_paths = paths)
+ want = None if expected is None else {"GGML_CUDA_QUANT_CUBLAS_MIN_BATCH": expected}
+ assert servers[-1].env == want
+ assert dict(b._state.child_env) == (want or {})
+ assert "/m/llm.gguf" in seen
+
+
def test_a_user_quant_cublas_value_reaches_sd_server_unchanged(monkeypatch):
monkeypatch.setenv("GGML_CUDA_QUANT_CUBLAS_MIN_BATCH", "0")
monkeypatch.setattr(bk, "_torch_cuda_capabilities", lambda ordinal: [(10, 0)])