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: read the local int8 / fp8 prequant cache back on pipeline loads (#15146)
Daniel Han25a162d09946
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.pyindex 7a76663a8c4..7b408e61b5a 100644--- a/studio/backend/core/inference/diffusion.py+++ b/studio/backend/core/inference/diffusion.py@@ -426,6 +426,8 @@ from .diffusion_comfy_quant import ()from .diffusion_single_file_trust import assert_safetensors_file, single_file_load_allowedfrom .diffusion_prequant import (+ PrequantIntoError,+ PrequantSource,hosted_fast_accum_conflict,load_prequantized_transformer,local_prequant_path_ready,@@ -9835,7 +9837,26 @@ class DiffusionBackend:else {})engaged: list[str] = []- for attr, _module in denoisers:+ cached_scheme = (+ self._pipeline_quant_from_cache(+ pipe,+ fam,+ denoisers,+ target = target,+ transformer_quant = transformer_quant,+ fast_accum = transformer_quant_fast_accum,+ loras = loras,+ base = base,+ fetch_base = fetch_base,+ source_base = _base_local_dir or fetch_base,+ hf_token = hf_token,+ )+ if native_scheme is None+ else None+ )+ if cached_scheme is not None:+ engaged.append(cached_scheme)+ for attr, _module in denoisers if cached_scheme is None else ():scheme = quantize_transformer(pipeif attr == "transformer"@@ -9851,7 +9872,13 @@ class DiffusionBackend:if scheme is None:breakengaged.append(scheme)- if engaged and len(engaged) == len(denoisers):+ if (+ engaged+ and len(engaged) == len(denoisers)+ and cached_scheme is not None+ ):+ transformer_quant_engaged = cached_scheme+ elif engaged and len(engaged) == len(denoisers):transformer_quant_engaged = engaged[0]self._save_pipeline_quant_to_cache(pipe,@@ -11212,6 +11239,85 @@ class DiffusionBackend:check_cancelled()return pipe, scheme+ @staticmethod+ def _pipeline_quant_from_cache(+ pipe: Any,+ fam: Any,+ denoisers: Any,+ *,+ target: Any,+ transformer_quant: Optional[str],+ fast_accum: Optional[bool],+ loras: Any,+ base: Optional[str],+ fetch_base: Optional[str],+ source_base: Optional[str],+ hf_token: Optional[str],+ ) -> Optional[str]:+ """Hosted checkpoints are not read: the published FLUX.2-klein-4B INT8 renders different pixels."""+ try:+ names = [attr for attr, _module in (denoisers or ())]+ transformer = getattr(pipe, "transformer", None)+ if (+ fam is None+ or transformer is None+ or names != ["transformer"]+ or _has_active_lora(loras)+ ):+ return None+ family = getattr(fam, "name", None)+ if native_quant_scheme(target, transformer_quant, family = family) is not None:+ return None+ scheme = select_transformer_quant_scheme(+ target, transformer_quant, family = family, base_repo = base+ )+ from .diffusion_prequant_cache import CACHEABLE_SCHEMES, lookup, note_hit++ if scheme not in CACHEABLE_SCHEMES or transformer_is_quantised(transformer):+ return None+ cached = lookup(fam, scheme, base_repo = base, source_base = source_base, logger = logger)+ if not cached:+ return None+ first = next(iter(transformer.parameters()), None)+ here = str(first.device) if first is not None else "cpu"+ t0 = time.perf_counter()+ loaded = load_prequantized_transformer(+ type(transformer),+ fetch_base or base,+ PrequantSource(kind = "path", location = cached, filename = None),+ device = str(getattr(target, "device", None) or here),+ dtype = getattr(first, "dtype", None),+ hf_token = hf_token,+ scheme = scheme,+ min_features = DEFAULT_MIN_LINEAR_FEATURES,+ fast_accum = fast_accum,+ cache_dir = hub_cache_dir(),+ local_files_only = True,+ logger = logger,+ placement_device = here,+ family = family,+ into = transformer,+ )+ if loaded is None:+ if transformer_is_quantised(transformer):+ raise PrequantIntoError("the cached build was partly applied and then failed")+ return None+ note_hit(cached, logger)+ logger.info(+ "diffusion.transformer_quant: %s read from the local prequant cache in %.1f s (no re-quantize)",+ scheme,+ time.perf_counter() - t0,+ )+ return scheme+ except Exception as exc: # noqa: BLE001+ if isinstance(exc, PrequantIntoError):+ raise RuntimeError(+ f"transformer_quant='{transformer_quant}' could not finish loading its cached build ({exc}); "+ "reload to quantize it fresh"+ ) from exc+ logger.warning("diffusion.prequant_cache: read skipped (%s)", exc)+ return None+@staticmethoddef _save_pipeline_quant_to_cache(pipe: Any,diff --git a/studio/backend/core/inference/diffusion_prequant.py b/studio/backend/core/inference/diffusion_prequant.pyindex 441e9715d8d..9e1326c4a99 100644--- a/studio/backend/core/inference/diffusion_prequant.py+++ b/studio/backend/core/inference/diffusion_prequant.py@@ -2328,9 +2328,14 @@ def load_prequantized_transformer(logger: Any = None,placement_device: Optional[str] = None,family: Optional[str] = None,+ into: Optional[Any] = None,) -> Optional[Any]:"""Load the pre-quantized transformer described by ``source`` onto ``device``.+ ``into``: an already-built DENSE transformer to load the checkpoint into instead of a fresh ``from_config``+ skeleton (the pipeline-quant path, whose denoiser came with the pipeline). Its key set must equal the+ checkpoint's; it stays where its weights already are, and on a refusal before assignment it is left dense.+``family`` (the Studio family name) is what a ComfyUI-format artifact needs to pick the layers Studio'sown ``scheme`` quantizes; Studio's own checkpoints record it themselves.@@ -2406,6 +2411,10 @@ def load_prequantized_transformer(comfy_scan = scan_comfy_quant(path)comfy_rotated = Falseif comfy_scan is not None:+ if into is not None:+ raise ValueError(+ "a ComfyUI-format checkpoint cannot be loaded into an existing transformer"+ )if prepare_model is not None or (component and component != DEFAULT_PREQUANT_COMPONENT):raise ValueError("a ComfyUI-format checkpoint is only read as a whole denoiser, not as the "@@ -2465,24 +2474,32 @@ def load_prequantized_transformer(# Read from the root that actually supplied the checkpoint: after a mid-session cache change the pinned root# may be gone or read-only, and load_config's raise is swallowed below into a None return, silently dropping a# prequant whose checkpoint is cached and already loaded.- config = _load_transformer_config(- transformer_cls,- base,- hf_token,- cache_dir,- path,- config_subfolder,- local_files_only = local_files_only,+ config = (+ None+ if into is not None+ else _load_transformer_config(+ transformer_cls,+ base,+ hf_token,+ cache_dir,+ path,+ config_subfolder,+ local_files_only = local_files_only,+ ))from accelerate import init_empty_weightsmetadata = ckpt.get("metadata") or {}- with init_empty_weights():- transformer = transformer_cls.from_config(config)- if prepare_model is not None:- prepare_model(transformer, metadata)- transformer.load_state_dict(state_dict, strict = True, assign = True)- if _has_meta_tensors(transformer):+ if into is not None:+ transformer = into+ _load_into_dense(transformer, state_dict, prepare_model)+ else:+ with init_empty_weights():+ transformer = transformer_cls.from_config(config)+ if prepare_model is not None:+ prepare_model(transformer, metadata)+ transformer.load_state_dict(state_dict, strict = True, assign = True)+ if into is None and _has_meta_tensors(transformer):# Non-persistent buffers (built in __init__, absent from the state dict) stay on meta. Rebuild on CPU so# they hold real values, then re-assign the quantized weights; dense bf16 never reaches the GPU.transformer = transformer_cls.from_config(config)@@ -2584,6 +2601,9 @@ def load_prequantized_transformer(placement_device or device,)return transformer+ except PrequantIntoError:+ # Partly assigned: falling back would mix two builds.+ raiseexcept Exception as exc: # noqa: BLE001 - fall back to the dense-quantise path_warn(logger, f"{scheme}:{source.kind}", exc)return None@@ -3519,6 +3539,36 @@ def stream_prequantized_module(return mode+class PrequantIntoError(RuntimeError):+ """The module is neither dense nor fully loaded."""+++def _load_into_dense(transformer: Any, state_dict: dict, prepare_model: Optional[Any]) -> None:+ """ValueError leaves the module untouched; PrequantIntoError means it was partly assigned."""+ if prepare_model is not None:+ raise ValueError(+ "prepare_model reshapes a fresh skeleton; it cannot run on an existing transformer"+ )+ own = transformer.state_dict()+ if set(own) != set(state_dict):+ missing = sorted(set(own) - set(state_dict))[:3]+ extra = sorted(set(state_dict) - set(own))[:3]+ raise ValueError(+ f"checkpoint keys differ from the transformer (missing {missing}, unexpected {extra})"+ )+ for name, tensor in state_dict.items():+ have = own[name]+ if tuple(getattr(have, "shape", ())) != tuple(getattr(tensor, "shape", ())):+ raise ValueError(+ f"checkpoint shape of {name} {tuple(tensor.shape)} != transformer {tuple(have.shape)}"+ )+ del own+ try:+ transformer.load_state_dict(state_dict, strict = True, assign = True)+ except Exception as exc: # noqa: BLE001+ raise PrequantIntoError(f"{type(exc).__name__}: {exc}") from exc++def _has_meta_tensors(module: Any) -> bool:"""True if any parameter or buffer is still on the meta device after loading."""from itertools import chaindiff --git a/studio/backend/core/inference/diffusion_prequant_cache.py b/studio/backend/core/inference/diffusion_prequant_cache.pyindex f173c95f89c..3327233e5db 100644--- a/studio/backend/core/inference/diffusion_prequant_cache.py+++ b/studio/backend/core/inference/diffusion_prequant_cache.py@@ -454,6 +454,7 @@ def lookup(base_repo: Optional[str],component: str = "transformer",logger: Any = None,+ source_base: Optional[str] = None,) -> Optional[str]:"""Path of a cached artifact for this exact source + scheme, or None. Local reads only, never raises."""if not enabled() or scheme not in CACHEABLE_SCHEMES:@@ -463,7 +464,13 @@ def lookup(key = shards = None# Every shard set: a repo without refs/main may hold several commit-pinned snapshots.seen: set = set()- for candidate in (source_shards(source, component), *_shard_sets(source, component)):+ # Serve only a build of the exact shards already loaded; other snapshots may differ under the same keys.+ candidates = (+ (source_shards(source_base, component),)+ if source_base+ else (source_shards(source, component), *_shard_sets(source, component))+ )+ for candidate in candidates:if not candidate or tuple(candidate) in seen:continueseen.add(tuple(candidate))diff --git a/studio/backend/tests/test_diffusion_prequant_cache.py b/studio/backend/tests/test_diffusion_prequant_cache.pyindex 9bd52aab9c4..7e045844cf7 100644--- a/studio/backend/tests/test_diffusion_prequant_cache.py+++ b/studio/backend/tests/test_diffusion_prequant_cache.py@@ -1431,3 +1431,191 @@ def test_the_video_save_fingerprints_the_repo_that_supplied_the_dense_weights():video = inspect.getsource(V.VideoBackend.load_pipeline)call = video.split("_save_runtime_quant_to_cache(", 1)[1][:400]assert "source = _base_local_dir or fetch_base," in call+++def _pipeline_read(D, pipe, fam, base, scheme, **kw):+ target = types.SimpleNamespace(dtype = torch.bfloat16, device = "cpu")+ return D.DiffusionBackend._pipeline_quant_from_cache(+ pipe,+ fam,+ [("transformer", pipe.transformer)],+ target = target,+ transformer_quant = scheme,+ fast_accum = None,+ loras = kw.pop("loras", []),+ base = str(base),+ fetch_base = str(base),+ source_base = kw.pop("source_base", str(base)),+ hf_token = None,+ **kw,+ )+++def _patch_scheme(monkeypatch, D, scheme):+ monkeypatch.setattr(D, "select_transformer_quant_scheme", lambda *a, **k: scheme)+ monkeypatch.setattr(D, "native_quant_scheme", lambda *a, **k: None)+++def test_a_returning_pipeline_load_reads_the_cache_bit_identically(+ env, tmp_path, scheme, monkeypatch+):+ """The pipeline-kind quantize loop wrote the cache but never read it: a second load re-quantized from bf16."""+ from core.inference import diffusion as D++ if not _SCHEME[1]:+ pytest.skip("torchao cannot quantize on this host's CPU")+ base, model = _write_base(tmp_path)+ fresh_dense = Tiny().to(torch.bfloat16)+ fresh_dense.load_state_dict(model.state_dict())+ fam = _fam(base)+ _patch_scheme(monkeypatch, D, scheme)+ miss = types.SimpleNamespace(transformer = fresh_dense)+ assert _pipeline_read(D, miss, fam, base, scheme) is None+ assert not D.transformer_is_quantised(fresh_dense)++ _quantize(model, scheme)+ assert C.save_runtime_quant(model, fam, base_repo = str(base)) is not None+ pipe = types.SimpleNamespace(transformer = fresh_dense)+ assert _pipeline_read(D, pipe, fam, base, scheme) == scheme+ assert pipe.transformer is fresh_dense and D.transformer_is_quantised(fresh_dense)+ assert fresh_dense._unsloth_runtime_quant == scheme+ assert _flat_equal(model.state_dict(), fresh_dense.state_dict()) == []+++def test_the_pipeline_read_finds_shards_under_the_source_base(env, tmp_path, scheme):+ """Saved with the dense shards read from a mirror / local snapshot: the lookup must search the same place."""+ mirror, model = _write_base(tmp_path, name = "mirror")+ upstream = tmp_path / "upstream" # no shards here: only the mirror holds them+ fam = types.SimpleNamespace(name = FAMILY, transformer_class = "Tiny", base_repo = str(upstream))+ _quantize(model, scheme)+ assert C.save_runtime_quant(model, fam, base_repo = str(upstream), source_base = str(mirror))+ assert C.lookup(fam, scheme, base_repo = str(upstream)) is None+ assert C.lookup(fam, scheme, base_repo = str(upstream), source_base = str(mirror))+++def test_a_pipeline_read_is_never_served_a_build_of_other_source_shards(env, tmp_path, scheme):+ """A build of the upstream shards must not be served to a load that read a different snapshot / mirror."""+ upstream, model = _write_base(tmp_path, name = "upstream")+ other, _ = _write_base(tmp_path, name = "other", seed = 1)+ fam = types.SimpleNamespace(name = FAMILY, transformer_class = "Tiny", base_repo = str(upstream))+ _quantize(model, scheme)+ assert C.save_runtime_quant(model, fam, base_repo = str(upstream))+ assert C.lookup(fam, scheme, base_repo = str(upstream))+ assert C.lookup(fam, scheme, base_repo = str(upstream), source_base = str(other)) is None+++def test_a_pipeline_read_that_does_not_fit_leaves_the_module_dense(+ env, tmp_path, scheme, monkeypatch+):+ from core.inference import diffusion as D++ if not _SCHEME[1]:+ pytest.skip("torchao cannot quantize on this host's CPU")+ base, model = _write_base(tmp_path)+ fam = _fam(base)+ _quantize(model, scheme)+ assert C.save_runtime_quant(model, fam, base_repo = str(base))+ _patch_scheme(monkeypatch, D, scheme)++ class Other(Tiny):+ def __init__(self) -> None:+ super().__init__()+ self.extra = torch.nn.Linear(512, 512)++ other = Other().to(torch.bfloat16)+ pipe = types.SimpleNamespace(transformer = other)+ assert _pipeline_read(D, pipe, fam, base, scheme) is None+ assert not D.transformer_is_quantised(other)+ dense = Tiny().to(torch.bfloat16)+ pipe = types.SimpleNamespace(transformer = dense)+ assert _pipeline_read(D, pipe, fam, base, scheme, loras = [("a", 1.0)]) is None+ assert not D.transformer_is_quantised(dense)+++def test_the_pipeline_quant_loop_reads_the_cache_before_quantizing():+ import inspect++ from core.inference import diffusion as D++ src = inspect.getsource(D.DiffusionBackend.load_pipeline)+ read = src.index("self._pipeline_quant_from_cache(")+ assert read < src.index("scheme = quantize_transformer(", read)+++def test_a_rotated_int8_pipeline_read_matches_the_fresh_rotated_build(env, tmp_path, monkeypatch):+ """ConvRot: cached build has the offline rotation, the read installs the online half."""+ import core.inference.diffusion_transformer_quant as Q+ from core.inference import diffusion as D+ from core.inference.diffusion_convrot import is_rotated_linear+ from safetensors.torch import save_file++ family = "qwen-image-2.1"+ monkeypatch.setenv(Q.INT8_CONVROT_ENV, "1")++ class Attn(torch.nn.Module):+ def __init__(self) -> None:+ super().__init__()+ self.to_q = torch.nn.Linear(512, 512, bias = False)+ self.to_out = torch.nn.ModuleList([torch.nn.Linear(512, 512, bias = False)])++ def forward(self, x):+ return self.to_out[0](self.to_q(x))++ class Block(torch.nn.Module):+ def __init__(self) -> None:+ super().__init__()+ self.attn = Attn()++ def forward(self, x):+ return x + self.attn(x)++ class Rot(torch.nn.Module):+ def __init__(self) -> None:+ super().__init__()+ self.transformer_blocks = torch.nn.ModuleList([Block() for _ in range(2)])++ def forward(self, x):+ for b in self.transformer_blocks:+ x = b(x)+ return x++ torch.manual_seed(0)+ built = Rot().to(torch.bfloat16)+ base = tmp_path / "base"+ (base / "transformer").mkdir(parents = True)+ save_file(+ {k: v.contiguous() for k, v in built.state_dict().items()},+ str(base / "transformer" / "diffusion_pytorch_model.safetensors"),+ )+ dense = Rot().to(torch.bfloat16)+ dense.load_state_dict(built.state_dict())+ target = types.SimpleNamespace(dtype = torch.bfloat16, device = "cpu")+ monkeypatch.setattr(Q, "native_quant_scheme", lambda *a, **k: None)+ monkeypatch.setattr(Q, "select_transformer_quant_scheme", lambda *a, **k: "int8")+ try:+ engaged = Q.quantize_transformer(+ types.SimpleNamespace(transformer = built), target, mode = "int8", family = family+ )+ except Exception: # noqa: BLE001+ engaged = None+ if engaged != "int8" or not D.transformer_is_quantised(built):+ pytest.skip("torchao cannot int8-quantize on this host's CPU")+ assert is_rotated_linear(built.transformer_blocks[0].attn.to_q)+ fam = types.SimpleNamespace(name = family, transformer_class = "Rot", base_repo = str(base))+ path = C.save_runtime_quant(built, fam, base_repo = str(base))+ if path is None:+ pytest.skip("this torchao cannot flatten int8 for the cache")++ _patch_scheme(monkeypatch, D, "int8")+ pipe = types.SimpleNamespace(transformer = dense)+ assert _pipeline_read(D, pipe, fam, base, "int8") == "int8"+ assert is_rotated_linear(dense.transformer_blocks[0].attn.to_q)+ assert _flat_equal(built.state_dict(), dense.state_dict()) == []+ x = torch.randn(4, 512, dtype = torch.bfloat16)+ with torch.no_grad():+ try:+ want = built(x)+ except Exception: # noqa: BLE001 - no CPU int8 GEMM: the bytes check above still stands+ return+ got = dense(x)+ assert torch.equal(want, got)