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
fix(studio): img2img/inpaint on GGUF image models — from_pipe fallback with no recast (#9186) (#9193)
yzxcj797a341b96905f7
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.pyindex e038ad31e64..b8ca7509da6 100644--- a/studio/backend/core/inference/diffusion.py+++ b/studio/backend/core/inference/diffusion.py@@ -902,6 +902,28 @@ def _install_gguf_prefix_strip(transformer_cls: Any, logger: Any) -> None:logger.warning("diffusion.gguf: prefix-strip shim not installed: %s", exc)[email protected]_cache(maxsize = None)+def _no_recast_pipeline_class(pipe_cls: Any) -> Any:+ """``pipe_cls`` with the dtype half of ``.to()`` dropped; device moves still work.++ Pipelines built by ``from_pipe`` share the resident pipeline's module objects, so a+ dtype cast through one rewrites the loaded model (#9186). Cached because a ControlNet+ swap rebuilds its pipeline: one subclass per class, not a new type per build.+ """++ def to(self, *args: Any, **kwargs: Any) -> Any:+ import torch++ args = tuple(arg for arg in args if not isinstance(arg, torch.dtype))+ kwargs.pop("dtype", None)+ if not args and not kwargs:+ return self+ return super(no_recast, self).to(*args, **kwargs)++ no_recast = type(pipe_cls.__name__, (pipe_cls,), {"to": to})+ return no_recast++_NO_WEIGHT = object()@@ -4923,6 +4945,19 @@ class DiffusionBackend:explicit_offload = cpu_offload,)+ @staticmethod+ def _from_pipe_no_recast(pipe: Any, pipe_cls: Any, **extra: Any) -> Any:+ """``Pipeline.from_pipe``, minus the cast it ends on.++ from_pipe casts every component it reuses, to float32 unless the caller named a+ dtype, and on the pinned revision an explicit ``torch_dtype = None`` no longer+ suppresses it. Those components are the resident pipeline's own, so the cast raises+ on a quantized denoiser (#9186) and silently doubles an unquantized one. Catching+ that error is not enough -- components are cast in name order, so earlier ones are+ float32 already when a later one refuses.+ """+ return _no_recast_pipeline_class(pipe_cls).from_pipe(pipe, **extra)+def _workflow_pipe(self, state: _LoadState, class_name: Optional[str], workflow: str) -> Any:"""The diffusers pipeline for an image-conditioned ``workflow``, built once andcached. ``Pipeline.from_pipe`` re-wires the loaded text-to-image pipe's resident@@ -4938,9 +4973,7 @@ class DiffusionBackend:return cachedimport diffusers- # torch_dtype=None is load-bearing: from_pipe otherwise recasts EVERY component to fp32, which hard-crashes the- # dense-quant path (torchao subclasses cannot swap_tensors). None reuses resident modules at their loaded dtype.- pipe = getattr(diffusers, class_name).from_pipe(state.pipe, torch_dtype = None)+ pipe = self._from_pipe_no_recast(state.pipe, getattr(diffusers, class_name))# Publish to the shared aux cache only if THIS load is still current: from_pipe runs without _lock, so an unload can null _state and caching would hand out stale modules.with self._lock:if self._state is state:@@ -4950,9 +4983,8 @@ class DiffusionBackend:def _controlnet_pipe(self, state: _LoadState, resolved_cn: Any, cancel: threading.Event) -> Any:"""Build (once, cached) the family's diffusers ControlNet pipeline around the requestedControlNet model. The ControlNet model is a small extra module loaded via from_pretrained- and cached by id; the pipeline is assembled with ``Pipeline.from_pipe(base,- controlnet=model)`` -- reusing the resident base modules at their loaded dtype (no reload,- no recast; torch_dtype=None for the same reason as _workflow_pipe). Raises a clear+ and cached by id; the pipeline is assembled from the resident base pipe through+ ``_from_pipe_no_recast``, reusing its modules at their loaded dtype. Raises a clearValueError when the family declares no ControlNet classes."""fam = state.familypipe_cls_name = getattr(fam, "controlnet_pipeline_class", None)@@ -5011,8 +5043,8 @@ class DiffusionBackend:key = (pipe_cls_name, resolved_cn.id)pipe = self._cn_pipes.get(key)if pipe is None:- pipe = getattr(diffusers, pipe_cls_name).from_pipe(- state.pipe, controlnet = cn_model, torch_dtype = None+ pipe = self._from_pipe_no_recast(+ state.pipe, getattr(diffusers, pipe_cls_name), controlnet = cn_model)with self._lock:# Same race as the model cache: an unload may have cleared _cn_pipes while from_pipe ran.diff --git a/studio/backend/tests/test_diffusion_backend.py b/studio/backend/tests/test_diffusion_backend.pyindex 5a889d80b4c..cb38cd18f9e 100644--- a/studio/backend/tests/test_diffusion_backend.py+++ b/studio/backend/tests/test_diffusion_backend.py@@ -632,11 +632,19 @@ class _FakeImg2ImgPipe:class _FakeImg2ImgPipeline:built_from: object = Nonefrom_pipe_kwargs: dict = {}+ recast_dtype: object = None++ def to(self, *args, **kwargs):+ _FakeImg2ImgPipeline.recast_dtype = kwargs.get("dtype")+ return self@classmethoddef from_pipe(cls, base_pipe, **kwargs):_FakeImg2ImgPipeline.built_from = base_pipe_FakeImg2ImgPipeline.from_pipe_kwargs = kwargs+ _FakeImg2ImgPipeline.recast_dtype = None+ # from_pipe's terminal cast, which is what makes the call site's class choice observable.+ cls().to(dtype = kwargs.get("dtype") or kwargs.get("torch_dtype") or "float32")return _FakeImg2ImgPipe()@@ -673,10 +681,17 @@ class _FakeInpaintPipe:class _FakeInpaintPipeline:built_from: object = None+ recast_dtype: object = None++ def to(self, *args, **kwargs):+ _FakeInpaintPipeline.recast_dtype = kwargs.get("dtype")+ return self@classmethoddef from_pipe(cls, base_pipe, **kwargs):_FakeInpaintPipeline.built_from = base_pipe+ _FakeInpaintPipeline.recast_dtype = None+ cls().to(dtype = kwargs.get("dtype") or kwargs.get("torch_dtype") or "float32")return _FakeInpaintPipe()@@ -1116,8 +1131,11 @@ def test_generate_img2img_uses_from_pipe(fake_runtime, tmp_path):assert len(out["images"]) == 1# from_pipe was handed the loaded text-to-image pipe (component reuse, no reload).assert _FakeImg2ImgPipeline.built_from is loaded_pipe- # ...with torch_dtype=None so from_pipe skips the float32 recast that crashes on torchao weights.- assert _FakeImg2ImgPipeline.from_pipe_kwargs.get("torch_dtype", "MISSING") is None+ # ...naming no dtype, and built through a class that drops from_pipe's terminal cast --+ # which is what actually protects the resident modules (#9186).+ assert "torch_dtype" not in _FakeImg2ImgPipeline.from_pipe_kwargs+ assert "dtype" not in _FakeImg2ImgPipeline.from_pipe_kwargs+ assert _FakeImg2ImgPipeline.recast_dtype is Nonecall = _FakeImg2ImgPipe.last_kwargsassert call["image"] is not None # decoded source image passed throughassert call["strength"] == 0.5@@ -1128,6 +1146,186 @@ def test_generate_img2img_uses_from_pipe(fake_runtime, tmp_path):assert backend._state.pipe.last_kwargs.get("image") is None+# ── from_pipe never recasts a reused component (#9186) ──────────────────────+++class _Component:+ """Records the dtype it is left at; a quantized one refuses a cast, as ModelMixin does."""++ def __init__(+ self,+ dtype,+ quantized = False,+ ):+ self.dtype = dtype+ self.is_quantized = quantized++ def to(+ self,+ device = None,+ dtype = None,+ ):+ if dtype is not None:+ if self.is_quantized:+ raise ValueError("Casting a quantized model to a new `dtype` is unsupported.")+ self.dtype = dtype+ return self+++class _Resident:+ """The loaded text-to-image pipeline the workflow pipes are built from."""++ def __init__(self, *, quantized_transformer):+ self.components = {+ "text_encoder": _Component("bfloat16"),+ "transformer": _Component("bfloat16", quantized = quantized_transformer),+ "vae": _Component("bfloat16"),+ }++ def dtypes(self):+ return {name: c.dtype for name, c in self.components.items()}+++class _RecastingPipeline:+ """``from_pipe`` as every diffusers Studio can install implements it: reuse the resident+ components, then cast them in name order to float32 unless the caller named a dtype."""++ seen: dict = {}+ recasts = True++ def __init__(self, **components):+ self.components = components+ for name, component in components.items():+ setattr(self, name, component)++ def to(self, *args, **kwargs):+ dtype = kwargs.get("dtype")+ for name in sorted(self.components):+ component = self.components[name]+ if hasattr(component, "to"):+ component.to(dtype = dtype)+ return self++ @classmethod+ def from_pipe(cls, base_pipe, **kwargs):+ _RecastingPipeline.seen = dict(kwargs)+ new = cls(**dict(base_pipe.components, **kwargs))+ if cls.recasts:+ new.to(dtype = kwargs.get("dtype") or kwargs.get("torch_dtype") or "float32")+ return new+++class _PreservingPipeline(_RecastingPipeline):+ """``from_pipe`` once upstream keeps the loaded dtype instead of defaulting to float32."""++ recasts = False+++def _torch_with_dtype(monkeypatch):+ """A torch stub whose ``dtype`` is a real class, so ``isinstance`` means something."""+ torch = types.ModuleType("torch")++ class dtype: # noqa: N801 -- mirrors torch.dtype+ pass++ torch.dtype = dtype+ monkeypatch.setitem(sys.modules, "torch", torch)+ return torch+++def test_no_recast_class_drops_every_shape_of_dtype_cast(monkeypatch):+ """Every form of dtype ``.to()`` accepts is ignored; every form of device is forwarded."""+ from core.inference.diffusion import _no_recast_pipeline_class++ torch = _torch_with_dtype(monkeypatch)+ fp32 = torch.dtype()++ class _Recorder:+ def __init__(self):+ self.calls = []++ def to(self, *args, **kwargs):+ self.calls.append((args, kwargs))+ return self++ pipe = _no_recast_pipeline_class(_Recorder)()++ assert pipe.to(fp32) is pipe # positional dtype+ assert pipe.to(dtype = fp32) is pipe # keyword dtype+ assert pipe.calls == [] # neither of them reached the parent++ pipe.to("cuda")+ pipe.to("cuda", fp32)+ pipe.to(device = "cuda", dtype = fp32)+ assert pipe.calls == [(("cuda",), {}), (("cuda",), {}), ((), {"device": "cuda"})]+++def test_no_recast_class_is_cached_and_keeps_identity():+ """One subclass per pipeline class, and it still passes as the family's own class --+ which the rest of the backend and the diffusers internals go on assuming."""+ from core.inference.diffusion import _no_recast_pipeline_class++ cls = _no_recast_pipeline_class(_RecastingPipeline)+ assert _no_recast_pipeline_class(_RecastingPipeline) is cls+ assert issubclass(cls, _RecastingPipeline)+ assert cls.__name__ == _RecastingPipeline.__name__++[email protected]("pipeline_cls", [_RecastingPipeline, _PreservingPipeline])[email protected]("quantized_transformer", [True, False])+def test_from_pipe_no_recast_leaves_every_component_at_its_loaded_dtype(+ pipeline_cls, quantized_transformer+):+ """The build succeeds and no component moves off bfloat16.++ The two quantization cases fail differently against a recasting from_pipe: a quantized+ denoiser makes the cast raise, and since components are cast in name order the text+ encoder is float32 already by then, so catching the error is not a fix; unquantized+ raises nothing at all and the whole pipeline is silently doubled in place. The two+ pipeline classes cover a from_pipe that recasts and one that has stopped, so an upstream+ fix landing under Studio cannot change the outcome."""+ from core.inference.diffusion import DiffusionBackend++ resident = _Resident(quantized_transformer = quantized_transformer)+ before = resident.dtypes()++ pipe = DiffusionBackend._from_pipe_no_recast(resident, pipeline_cls)++ assert resident.dtypes() == before == {n: "bfloat16" for n in before}+ assert pipe.transformer is resident.components["transformer"]+ assert pipe.vae is resident.components["vae"]+++def test_from_pipe_no_recast_names_no_dtype_and_forwards_extras():+ """The helper names no dtype, and passes a ControlNet along."""+ from core.inference.diffusion import DiffusionBackend++ resident = _Resident(quantized_transformer = True)+ DiffusionBackend._from_pipe_no_recast(resident, _RecastingPipeline)+ assert _RecastingPipeline.seen == {} # neither torch_dtype nor dtype++ controlnet = _Component("bfloat16")+ pipe = DiffusionBackend._from_pipe_no_recast(+ resident, _RecastingPipeline, controlnet = controlnet+ )+ assert _RecastingPipeline.seen == {"controlnet": controlnet}+ assert pipe.controlnet is controlnet+++def test_from_pipe_no_recast_does_not_swallow_errors():+ """A real assembly failure must surface: catching the quantized-cast error would hide+ that from_pipe had already cast every component ahead of the one that refused."""+ from core.inference.diffusion import DiffusionBackend++ class _Broken:+ @classmethod+ def from_pipe(cls, base_pipe, **kwargs):+ raise ValueError("Casting a quantized model to a new `dtype` is unsupported")++ with pytest.raises(ValueError, match = "Casting a quantized model"):+ DiffusionBackend._from_pipe_no_recast(_Resident(quantized_transformer = True), _Broken)++def test_generate_img2img_unsupported_family_raises(fake_runtime, tmp_path, monkeypatch):"""A family with no image-conditioning at all (no img2img/inpaint/edit/reference) rejectsan init_image with a clear error rather than failing deep in the pipeline."""@@ -1431,6 +1629,7 @@ def test_generate_inpaint_uses_from_pipe(fake_runtime, tmp_path):assert len(out["images"]) == 1# The inpaint pipe (not img2img) was selected and built from the loaded pipe.assert _FakeInpaintPipeline.built_from is loaded_pipe+ assert _FakeInpaintPipeline.recast_dtype is None # reused modules, never recast (#9186)assert _FakeImg2ImgPipeline.built_from is Nonecall = _FakeInpaintPipe.last_kwargsassert call["image"] is not None and call["mask_image"] is not Nonediff --git a/studio/backend/tests/test_diffusion_controlnet.py b/studio/backend/tests/test_diffusion_controlnet.pyindex bb847341107..663315b648e 100644--- a/studio/backend/tests/test_diffusion_controlnet.py+++ b/studio/backend/tests/test_diffusion_controlnet.py@@ -240,6 +240,12 @@ class _FakeCNModel:class _FakeCNPipe:+ recast_dtype: object = None++ def to(self, *args, **kwargs):+ _FakeCNPipe.recast_dtype = kwargs.get("dtype")+ return self+@classmethoddef from_pipe(cls,@@ -250,6 +256,8 @@ class _FakeCNPipe:p = cls()p.base = basep.controlnet = controlnet+ _FakeCNPipe.recast_dtype = None+ p.to(dtype = torch_dtype or "float32") # from_pipe's terminal castreturn p@@ -298,6 +306,8 @@ def test_controlnet_pipe_loads_once_and_caches(monkeypatch):assert p1.controlnet.path == "repo/id" and p1.controlnet.device == "cpu"# A remote (non-local) ControlNet must force safetensors so a pickle cannot deserialize even if the Hub scan failed open.assert p1.controlnet.use_safetensors is True+ # The cast never reaches the resident base modules the ControlNet pipe shares (#9186).+ assert _FakeCNPipe.recast_dtype is None# cached: same id -> same model + same pipe, no reload.p2 = b._controlnet_pipe(st, resolved, threading.Event())assert p2 is p1