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 diffusion: key the CFG-batch verdict on the weight quant, not just the module layout (#15047)
Daniel Hana1d9411fe814
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.pyindex 8dd82dd4a8d..6dbda38c4df 100644--- a/studio/backend/core/inference/diffusion.py+++ b/studio/backend/core/inference/diffusion.py@@ -10616,7 +10616,11 @@ class DiffusionBackend:# After every forward wrapper of the speed / graph layers, so the replica sees the final module.install_cfg_parallel(pipe, offload_policy = effective_policy, logger = logger)install_cfg_batch(- pipe, offload_policy = effective_policy, speed_mode = speed_mode, logger = logger+ pipe,+ offload_policy = effective_policy,+ speed_mode = speed_mode,+ transformer_quant = transformer_quant_engaged,+ logger = logger,)# Z-Image guided steps at the guidance-off batch: turning CFG on compiles and records nothing new.# compiled_only: an eager denoiser keeps the batched guided call (no graph to protect).diff --git a/studio/backend/core/inference/diffusion_cfg_batch.py b/studio/backend/core/inference/diffusion_cfg_batch.pyindex 3f143e4de2a..825a6cc40e9 100644--- a/studio/backend/core/inference/diffusion_cfg_batch.py+++ b/studio/backend/core/inference/diffusion_cfg_batch.py@@ -19,8 +19,9 @@ Priced once per request shape, before any batched result is used: steps 1-2 runpair >= ``_RESIDENT_MAX_PAIR_S`` stays plain untried. Otherwise a discarded trial (plain pairs interleaved with doubledcalls) batches steps 3+ only if the fastest batched step (predict, merge, snapshot, doubled call, split, verify) beats thefastest plain pair by ``_MEASURED_FRACTION``, so every render of a shape takes one path (same seed, same image). The-verdict is latched for the load (memory pressure never re-times it) and stored per (model, speed tier, offload policy,-card, compiled or eager, request shape, runtimes) next to the learned peaks, first writer wins: a borderline shape+verdict is latched for the load (memory pressure never re-times it) and stored per (model, weight tensor classes and+quant scheme, speed tier, offload policy, card, compiled or eager, request shape, runtimes) next to the learned peaks,+first writer wins: a borderline shapecannot land on a different path in another process (``UNSLOTH_DIFFUSION_CFG_BATCH_VERDICTS=0`` keeps it per load;``UNSLOTH_DIFFUSION_CFG_BATCH_VERDICTS_FILE`` names the file). The doubled call needs room for twice a plain call'sactivations; no room, or an OOM, turns the shape plain for the rest of that render.@@ -264,6 +265,8 @@ VERDICTS_ENV = "UNSLOTH_DIFFUSION_CFG_BATCH_VERDICTS"VERDICTS_FILE_ENV = "UNSLOTH_DIFFUSION_CFG_BATCH_VERDICTS_FILE"_VERDICTS_FILE = "diffusion_cfg_batch_verdicts.json"_VERDICTS_MAX = 512+# v1 keyed a bf16 load and its torchao INT8 / FP8 load alike+_VERDICTS_VERSION = 2_BATCH = "batch"_PLAIN = "plain"@@ -292,8 +295,12 @@ def _read_verdicts(path: Any) -> dict:data = json.loads(path.read_text(encoding = "utf-8"))except Exception: # noqa: BLE001 - absent or corrupt: an empty storereturn {}- if not isinstance(data, dict) or data.get("runtime") != peaks.runtime_stamp():- return {} # written under other kernels: their timings do not apply+ if (+ not isinstance(data, dict)+ or data.get("version") != _VERDICTS_VERSION+ or data.get("runtime") != peaks.runtime_stamp()+ ):+ return {}entries = data.get("entries")return entries if isinstance(entries, dict) else {}@@ -340,7 +347,11 @@ def _settle_verdict(key: str, verdict: dict) -> dict:try:with os.fdopen(fd, "w", encoding = "utf-8") as handle:json.dump(- {"version": 1, "runtime": peaks.runtime_stamp(), "entries": entries},+ {+ "version": _VERDICTS_VERSION,+ "runtime": peaks.runtime_stamp(),+ "entries": entries,+ },handle,indent = 1,)@@ -365,22 +376,41 @@ def _card_name(latent: Any) -> Optional[str]:return device_name(latent.device)-def _load_identity(denoiser: Any, offload_policy: str, speed_mode: Optional[str]) -> Optional[str]:- """What a doubled call's timing depends on in the load: class, config, weight dtypes / layer classes (quant),- offload policy and speed tier. Hashed: it is a store key, never read back."""+def _weight_kind(p: Any) -> str:+ """torchao ``quantize_`` keeps ``nn.Linear`` and a bf16 ``.dtype``: only the tensor class tells the loads apart."""+ data = getattr(p, "data", p)+ kind = type(data) if type(p).__name__ == "Parameter" else type(p)+ names = list(getattr(kind, "tensor_attribute_names", None) or ()) + list(+ getattr(kind, "optional_tensor_attribute_names", None) or ()+ )+ attrs = [f"{n}={getattr(data, n, None)!r}" for n in names if n != "block_size"]+ return f"{kind.__module__}.{kind.__qualname__}" + (f"({','.join(attrs)})" if attrs else "")+++def _load_identity(+ denoiser: Any,+ offload_policy: str,+ speed_mode: Optional[str],+ transformer_quant: Optional[str] = None,+) -> Optional[str]:+ """What a doubled call's timing depends on in the load. Hashed: it is a store key, never read back."""import hashlibimport jsontry:config = getattr(denoiser, "config", None)layers = sorted({f"{type(m).__module__}.{type(m).__name__}" for m in denoiser.modules()})- dtypes = sorted({str(p.dtype) for p in denoiser.parameters()})+ params = list(denoiser.parameters())+ dtypes = sorted({str(p.dtype) for p in params})+ weights = sorted({_weight_kind(p) for p in params})blob = json.dumps([f"{type(denoiser).__module__}.{type(denoiser).__name__}",dict(config) if config is not None else None,layers,dtypes,+ weights,+ None if transformer_quant is None else str(transformer_quant),offload_policy,speed_mode,],@@ -739,7 +769,12 @@ class CfgBatchRouter:if not card:return Nonecompiled = "compiled" if self.render_compiled is not None else "eager"- return f"{self.identity}|{card}|{compiled}|{shape.key}"+ module = self.module_ref()+ # Read live: set_attention_backend() changes neither the module classes nor the config.+ attention = (+ getattr(module, "_unsloth_attention_backend", None) if module is not None else None+ )+ return f"{self.identity}|{card}|{compiled}|{attention}|{shape.key}"def _stored_verdict(self, shape: _Shape, latent: Any) -> Optional[dict]:key = self._verdict_key(shape, latent)@@ -1053,12 +1088,19 @@ def install_cfg_batch(*,offload_policy: str,speed_mode: Optional[str] = None,+ transformer_quant: Optional[str] = None,logger: Any = None,) -> Optional[str]:"""Arm :class:`CfgBatchRouter` on ``pipe.transformer``; the decline reason, or None when armed. An optional lever:it never fails a load. ``speed_mode`` is the request's value (None = unset)."""try:- return _install(pipe, offload_policy = offload_policy, speed_mode = speed_mode, logger = logger)+ return _install(+ pipe,+ offload_policy = offload_policy,+ speed_mode = speed_mode,+ transformer_quant = transformer_quant,+ logger = logger,+ )except Exception as exc: # noqa: BLE001if logger is not None:logger.info("diffusion.cfg_batch: not armed (%s: %s)", type(exc).__name__, exc)@@ -1070,6 +1112,7 @@ def _install(*,offload_policy: str,speed_mode: Optional[str] = None,+ transformer_quant: Optional[str] = None,logger: Any = None,) -> Optional[str]:reason = cfg_batch_decline(pipe, offload_policy = offload_policy, speed_mode = speed_mode)@@ -1090,7 +1133,7 @@ def _install(logger = logger,)router.offloaded = _offloaded(denoiser, offload_policy)- router.identity = _load_identity(denoiser, offload_policy, speed_mode)+ router.identity = _load_identity(denoiser, offload_policy, speed_mode, transformer_quant)try:_ROUTERS[pipe] = routerexcept TypeError:diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.pyindex 7f958775a1f..0b575840e08 100644--- a/studio/backend/core/inference/video.py+++ b/studio/backend/core/inference/video.py@@ -10003,7 +10003,11 @@ class VideoBackend:)install_cfg_parallel(pipe, offload_policy = offload_policy, logger = logger)install_cfg_batch(- pipe, offload_policy = offload_policy, speed_mode = speed_mode, logger = logger+ pipe,+ offload_policy = offload_policy,+ speed_mode = speed_mode,+ transformer_quant = transformer_quant_engaged,+ logger = logger,)# Opt-in (UNSLOTH_DIFFUSION_BG_COMPILE=1): off by default so the same seed twice repeats.from . import diffusion_bg_compile as bg_compilediff --git a/studio/backend/tests/test_diffusion_cfg_batch.py b/studio/backend/tests/test_diffusion_cfg_batch.pyindex 3976b232689..2cf63836b8d 100644--- a/studio/backend/tests/test_diffusion_cfg_batch.py+++ b/studio/backend/tests/test_diffusion_cfg_batch.py@@ -892,3 +892,107 @@ def test_the_verdict_store_is_keyed_on_the_card_and_skipped_off_cuda(monkeypatchpipe3, model3 = _fresh_load(type(model))assert _render(pipe3, model3)[4:10] == _TRIALassert (tmp_path / "verdicts.json").read_text() == before+++class _QuantDen(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.config = {"num_layers": 2, "hidden": 64}+ torch.manual_seed(0)+ self.a = torch.nn.Linear(64, 64, dtype = torch.bfloat16)+ self.b = torch.nn.Linear(64, 64, dtype = torch.bfloat16)+++def _torchao_loads():+ import copy++ tq = pytest.importorskip("torchao.quantization")+ base = _QuantDen()+ loads = {"bf16": base}+ int8 = copy.deepcopy(base)+ tq.quantize_(int8, tq.Int8DynamicActivationInt8WeightConfig())+ loads["int8"] = int8+ try:+ from torchao.float8.inference import Float8MMConfig+ for fast in (True, False):+ fp8 = copy.deepcopy(base)+ tq.quantize_(+ fp8,+ tq.Float8DynamicActivationFloat8WeightConfig(+ granularity = tq.PerRow(), mm_config = Float8MMConfig(use_fast_accum = fast)+ ),+ )+ loads[f"fp8_fast{int(fast)}"] = fp8+ except Exception: # noqa: BLE001+ pass+ assert {str(m.a.weight.dtype) for m in loads.values()} == {"torch.bfloat16"}+ return loads+++def test_the_verdict_key_tells_bf16_from_torchao_int8_and_fp8_loads():+ loads = _torchao_loads()+ keys = {name: cb._load_identity(m, "none", None) for name, m in loads.items()}+ assert None not in keys.values()+ assert len(set(keys.values())) == len(keys), keys+++def test_the_verdict_key_includes_the_engaged_transformer_quant():+ model = _QuantDen()+ keys = {q: cb._load_identity(model, "none", None, q) for q in (None, "int8", "fp8", "nvfp4")}+ assert len(set(keys.values())) == len(keys)+++def test_the_same_load_gives_a_stable_verdict_key():+ loads = _torchao_loads()+ import copy++ for name, model in loads.items():+ again = copy.deepcopy(model)+ assert cb._load_identity(model, "none", "default", "int8") == cb._load_identity(+ again, "none", "default", "int8"+ ), name+ assert cb._load_identity(_QuantDen(), "none", None) == cb._load_identity(+ _QuantDen(), "none", None+ )+++def test_install_keys_the_router_on_the_engaged_quant(monkeypatch):+ monkeypatch.setenv(cb.CFG_BATCH_ENV, "auto")+ ids = set()+ for quant in (None, "int8"):+ pipe = _Pipe(_quiet_flux())+ assert cb.install_cfg_batch(pipe, offload_policy = "none", transformer_quant = quant) is None+ ids.add(cb.router_for(pipe).identity)+ assert len(ids) == 2 and None not in ids+++def test_the_verdict_key_follows_the_live_attention_backend(monkeypatch):+ monkeypatch.setenv(cb.CFG_BATCH_ENV, "auto")+ monkeypatch.setattr(cb, "_card_name", lambda latent: "card")+ pipe = _Pipe(_quiet_flux())+ assert cb.install_cfg_batch(pipe, offload_policy = "none") is None+ router = cb.router_for(pipe)+ shape = cb._Shape("s")+ keys = set()+ for backend in (None, "native", "flash"):+ pipe.transformer._unsloth_attention_backend = backend+ keys.add(router._verdict_key(shape, None))+ assert len(keys) == 3 and None not in keys+++def test_a_version_1_verdict_store_is_not_read(monkeypatch, tmp_path):+ import json++ from core.inference import diffusion_measured_peaks as peaks++ path = tmp_path / "verdicts.json"+ monkeypatch.setenv("UNSLOTH_DIFFUSION_CFG_BATCH_VERDICTS_FILE", str(path))+ entry = {"k": {"verdict": "plain", "reason": "old key"}}+ path.write_text(json.dumps({"version": 1, "runtime": peaks.runtime_stamp(), "entries": entry}))+ assert cb.stored_verdict("k") is None+ path.write_text(+ json.dumps(+ {"version": cb._VERDICTS_VERSION, "runtime": peaks.runtime_stamp(), "entries": entry}+ )+ )+ assert cb.stored_verdict("k") == entry["k"]