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
Images: fix the img2img VAE dtype crash and make the Resolution control bound Transform (#8583)
Daniel Han6d37709b4516
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.pyindex 887abeb3547..db5486347e2 100644--- a/studio/backend/core/inference/diffusion.py+++ b/studio/backend/core/inference/diffusion.py@@ -18,6 +18,7 @@ bar. GPU-handoff policy lives in the arbiter the routes call, not here.from __future__ import annotations+import functoolsimport inspectimport jsonimport os@@ -421,6 +422,27 @@ def _clamp_max_side(img: Any, max_side: int) -> Any:return img.resize((nw, nh), Image.LANCZOS)+def _fit_within(img: Any, max_w: int, max_h: int) -> Any:+ """Downscale a PIL image to fit inside a ``max_w`` x ``max_h`` box, preserving aspect ratio;+ a no-op when it already fits. NEVER enlarges -- growing a source is the Upscale workflow.++ img2img takes its output size from the upload, which left the Resolution control inert for+ Transform: a 4000px photo generated at the 2048 clamp and the refusal it raised named a size+ the sliders could not change. Bounding the upload by the requested box makes that control+ mean what it says."""+ from PIL import Image++ w, h = img.size+ bw = max(1, int(max_w))+ bh = max(1, int(max_h))+ if w <= bw and h <= bh:+ return img+ scale = min(bw / float(w), bh / float(h))+ nw = max(1, int(round(w * scale)))+ nh = max(1, int(round(h * scale)))+ return img.resize((nw, nh), Image.LANCZOS)++def _image_variant_hint(family_name: Optional[str],single_file_name: Optional[str],@@ -4731,6 +4753,55 @@ class DiffusionBackend:except (StopIteration, AttributeError, RuntimeError, TypeError):pass+ @staticmethod+ def _make_vae_encode_dtype_safe(pipe: Any) -> None:+ """Cast whatever tensor reaches ``vae.encode`` to the VAE's OWN dtype, so an+ image-conditioned call cannot die on ``Input type (float) and bias type+ (c10::BFloat16) should be the same``.++ ``_align_vae_dtype`` pins the VAE to the DENOISER's dtype, but the img2img /+ inpaint pipelines consult neither: they cast the upload to whatever the TEXT+ ENCODER produced (``prompt_embeds[0].dtype`` in ``ZImageImg2ImgPipeline``), a+ third dtype nobody reconciles. When that lands on fp32 against bf16 VAE weights+ the first conv raises, and the user sees only an opaque failure toast.++ Wrapping ``encode`` rather than widening ``_align_vae_dtype`` is deliberate: the+ mismatch is between the pipeline's chosen input dtype and the VAE, so the fix has+ to live at that boundary to hold for every family and diffusers version, instead+ of tracking which attribute each pipeline reads this release. Latents come back+ untouched -- ``scale_noise`` and the schedulers upcast to fp32 anyway.++ Idempotent (a re-wrap on a warm pipe is a no-op) and best-effort: any failure+ leaves the original ``encode`` in place."""+ vae = getattr(pipe, "vae", None)+ if vae is None or getattr(vae, "_unsloth_dtype_safe_encode", False):+ return+ try:+ import torch++ original = vae.encode++ @functools.wraps(original)+ def _encode(x: Any, *args: Any, **kwargs: Any) -> Any:+ # Probed per call, not at wrap time: _align_vae_dtype and a txt2img decode+ # both re-cast the VAE. A failed probe forwards the tensor as it arrived.+ try:+ if isinstance(x, torch.Tensor):+ target = next(+ (p.dtype for p in vae.parameters() if p.dtype.is_floating_point),+ None,+ )+ if target is not None and x.dtype != target:+ x = x.to(dtype = target)+ except (AttributeError, RuntimeError, StopIteration, TypeError):+ pass+ return original(x, *args, **kwargs)++ vae.encode = _encode+ vae._unsloth_dtype_safe_encode = True+ except (AttributeError, RuntimeError, TypeError):+ pass+@staticmethoddef _resolve_lora_set(specs: list[tuple[str, float]],@@ -5226,7 +5297,13 @@ class DiffusionBackend:# Snap odd-sized inputs (and the mask) to a multiple of 16 where the OUTPUT size comes from the input image.if init_pil is not None and workflow in ("img2img", "inpaint", "edit"):# img2img/inpaint take output size from the upload, so bound the longest side to 2048 (a phone photo would OOM).- if workflow in ("img2img", "inpaint"):+ if workflow == "img2img":+ # ...and bound Transform by the REQUESTED size too, so the Resolution+ # control caps the output instead of being inert. img2img only: an+ # inpaint payload is the canvas the mask was painted against (Extend+ # sends a deliberately ENLARGED one), so shrinking it would break them.+ init_pil = _fit_within(init_pil, min(2048, width), min(2048, height))+ elif workflow == "inpaint":init_pil = _clamp_max_side(init_pil, 2048)init_pil = _snap_to_multiple(init_pil, 16)if mask_pil is not None and mask_pil.size != init_pil.size:@@ -5235,6 +5312,9 @@ class DiffusionBackend:if init_pil is not None:# Keep the VAE encode dtype consistent with the input image.self._align_vae_dtype(pipe, state.family.denoiser_attr)+ # ...and with the dtype the PIPELINE hands the encoder, which is neither+ # of the two the line above reconciles.+ self._make_vae_encode_dtype_safe(pipe)# Pipelines vary in accepted kwargs, so gate every optional one on the signature.call_params = inspect.signature(pipe.__call__).parameters@@ -5325,6 +5405,10 @@ class DiffusionBackend:batch_size = guard_batch,# The hint the load planned with, so the distilled / edit multipliers match.family = state.variant_hint,+ # img2img is bounded by the Resolution control (see _fit_within), so+ # "generate at a smaller resolution" is actionable there; the rest size+ # from the upload alone and get the upload-side remedy.+ source_driven = workflow in ("inpaint", "upscale", "edit"),logger = logger,)except ValueError:diff --git a/studio/backend/core/inference/diffusion_memory.py b/studio/backend/core/inference/diffusion_memory.pyindex 85cae4cbb52..a2492246afc 100644--- a/studio/backend/core/inference/diffusion_memory.py+++ b/studio/backend/core/inference/diffusion_memory.py@@ -1013,10 +1013,16 @@ def image_activation_shortfall_message(batch_size: int = 1,family: Optional[str] = None,base_overhead_mib: int = DEFAULT_BASE_OVERHEAD_MIB,+ source_driven: bool = False,) -> Optional[str]:"""A user-facing refusal when this generation's ACTIVATIONS plus the flat base overheadcannot fit the free device budget, else None.+ ``source_driven`` says the refused size comes from an UPLOADED image rather than the+ Resolution control (inpaint / extend / upscale / edit). Telling those callers to "generate at+ a smaller resolution" points them at a control that cannot change the number in the refusal.+ Same verdict either way; only the remedy sentence differs.+Why this is a refusal and not another tuning knob: weights can be offloaded, activationscannot. Every offload tier moves WEIGHTS between host and device; the latents, attentionbuffers and VAE intermediates a forward pass allocates have to be on the device while it@@ -1108,7 +1114,8 @@ def image_activation_shortfall_message(# Only when the batch is what was budgeted. A refusal measured on ONE image cannot be# answered by asking for fewer, and pointing there sends the caller at the one change# that provably will not help.- f"Generate at a smaller resolution{' or a smaller batch size' if batch > 1 else ''}, "+ f"{'Upload a smaller source image (this workflow takes its output size from the image, not the Resolution setting)' if source_driven else 'Generate at a smaller resolution'}"+ f"{' or a smaller batch size' if batch > 1 else ''}, ""free device memory by closing other applications, or set "f"{OVERSIZED_GENERATE_ENV}=1 to attempt it anyway.")@@ -1122,6 +1129,7 @@ def raise_on_image_activation_shortfall(batch_size: int = 1,family: Optional[str] = None,base_overhead_mib: int = DEFAULT_BASE_OVERHEAD_MIB,+ source_driven: bool = False,logger: Any = None,) -> None:"""Refuse a generation whose activations cannot fit the free device budget. No-op whenever@@ -1138,6 +1146,7 @@ def raise_on_image_activation_shortfall(batch_size = batch_size,family = family,base_overhead_mib = base_overhead_mib,+ source_driven = source_driven,)if message is None:returndiff --git a/studio/backend/tests/test_diffusion_backend.py b/studio/backend/tests/test_diffusion_backend.pyindex 5d3ac6e3182..557537547f6 100644--- a/studio/backend/tests/test_diffusion_backend.py+++ b/studio/backend/tests/test_diffusion_backend.py@@ -8577,19 +8577,45 @@ def test_generate_refuses_a_resolution_whose_activations_cannot_fit(def test_generate_guard_measures_the_input_image_not_the_sliders(fake_runtime, tmp_path, monkeypatch):- # img2img / inpaint / upscale / edit take their OUTPUT size from the uploaded image, so reading- # the width/height kwargs would check a frame this call never renders. A 2048x2048 upload with+ # inpaint / upscale / edit take their OUTPUT size from the uploaded image, so reading the+ # width/height kwargs would check a frame this call never renders. A 2048x2048 upload with# the sliders left at 1024 is four times the planned area.backend = _loaded_backend_on_a_16g_card(tmp_path, monkeypatch)- with pytest.raises(ValueError, match = "2048x2048"):+ with pytest.raises(ValueError) as excinfo:backend.generate(prompt = "a sloth",width = 1024,height = 1024,steps = 4,init_image = _png_b64(2048),+ mask_image = _mask_b64(2048),)+ message = str(excinfo.value)+ assert "2048x2048" in message+ # ...and must not advise changing the Resolution control, which cannot move that number+ # for a workflow whose canvas comes from the upload.+ assert "Upload a smaller source image" in message+ assert "smaller resolution" not in message+++def test_transform_fits_the_upload_to_the_sliders_instead_of_refusing(+ fake_runtime, tmp_path, monkeypatch+):+ # Reported: Transform refused at 2048x2048 however small the sliders were set, because+ # img2img sized from the upload alone. Fitting the upload to the requested box renders+ # instead of refusing, at the size that was asked for.+ backend = _loaded_backend_on_a_16g_card(tmp_path, monkeypatch)++ out = backend.generate(+ prompt = "a sloth",+ width = 1024,+ height = 1024,+ steps = 4,+ init_image = _png_b64(2048),+ )+ assert len(out["images"]) == 1+ assert _FakeImg2ImgPipe.last_kwargs["image"].size == (1024, 1024)def test_generate_guard_uses_the_hint_the_load_planned_with(fake_runtime, tmp_path, monkeypatch):diff --git a/studio/backend/tests/test_diffusion_img2img_dtype.py b/studio/backend/tests/test_diffusion_img2img_dtype.pynew file mode 100644index 00000000000..9a4c29ef26f--- /dev/null+++ b/studio/backend/tests/test_diffusion_img2img_dtype.py@@ -0,0 +1,119 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""CPU-only unit tests for the image-conditioned VAE encode dtype guard.++Image Transform on a bf16 denoiser whose text encoder settled on fp32 died with ``Input type+(float) and bias type (c10::BFloat16) should be the same``: ``prepare_latents`` casts the upload+to ``prompt_embeds[0].dtype`` and feeds it straight to ``vae.encode``, so neither the denoiser+dtype nor the VAE's own gets a say. ``_make_vae_encode_dtype_safe`` closes that gap at the+encoder boundary. No GPU, no diffusers.+"""++from __future__ import annotations++import types++from core.inference.diffusion import DiffusionBackend+++class _RecordingVae:+ """A VAE stand-in that records the dtype its ``encode`` was actually handed."""++ def __init__(self, dtype):+ self._dtype = dtype+ self.seen_dtype = None+ self.seen_args = None+ self.encode = self._encode++ def parameters(self):+ yield types.SimpleNamespace(dtype = self._dtype)++ def _encode(self, x, *args, **kwargs):+ self.seen_dtype = getattr(x, "dtype", None)+ self.seen_args = (args, kwargs)+ return "latents"+++def test_encode_input_is_cast_to_the_vae_dtype():+ import torch++ # The reported crash: fp32 image tensor (text-encoder dtype) into a bf16 VAE.+ vae = _RecordingVae(dtype = torch.bfloat16)+ pipe = types.SimpleNamespace(vae = vae)+ DiffusionBackend._make_vae_encode_dtype_safe(pipe)+ out = vae.encode(torch.zeros(1, 3, 64, 64, dtype = torch.float32))+ assert vae.seen_dtype == torch.bfloat16+ assert out == "latents" # the wrapper is transparent+++def test_encode_input_is_cast_the_other_direction_too():+ import torch++ # The mirror mismatch (bf16 image into an fp32 / force_upcast VAE) is the same bug.+ vae = _RecordingVae(dtype = torch.float32)+ DiffusionBackend._make_vae_encode_dtype_safe(types.SimpleNamespace(vae = vae))+ vae.encode(torch.zeros(1, 3, 64, 64, dtype = torch.bfloat16))+ assert vae.seen_dtype == torch.float32+++def test_matching_dtype_is_left_alone_and_extra_args_pass_through():+ import torch++ vae = _RecordingVae(dtype = torch.bfloat16)+ DiffusionBackend._make_vae_encode_dtype_safe(types.SimpleNamespace(vae = vae))+ x = torch.zeros(1, 3, 64, 64, dtype = torch.bfloat16)+ vae.encode(x, return_dict = False)+ assert vae.seen_dtype == torch.bfloat16+ assert vae.seen_args == ((), {"return_dict": False})+++def test_non_tensor_input_passes_through_untouched():+ import torch++ # Some callers hand encode a list of tensors or a distribution; never guess, just forward.+ vae = _RecordingVae(dtype = torch.bfloat16)+ DiffusionBackend._make_vae_encode_dtype_safe(types.SimpleNamespace(vae = vae))+ vae.encode(["not", "a", "tensor"])+ assert vae.seen_dtype is None+++def test_wrapping_is_idempotent():+ import torch++ # generate() runs this on every image-conditioned call, so stacking wrappers would leak depth.+ vae = _RecordingVae(dtype = torch.bfloat16)+ pipe = types.SimpleNamespace(vae = vae)+ DiffusionBackend._make_vae_encode_dtype_safe(pipe)+ first = vae.encode+ DiffusionBackend._make_vae_encode_dtype_safe(pipe)+ assert vae.encode is first+++def test_dtype_is_read_at_call_time_not_wrap_time():+ import torch++ # _align_vae_dtype (and a txt2img decode) re-cast the VAE, so a wrap-time snapshot goes stale.+ vae = _RecordingVae(dtype = torch.bfloat16)+ DiffusionBackend._make_vae_encode_dtype_safe(types.SimpleNamespace(vae = vae))+ vae._dtype = torch.float32+ vae.encode(torch.zeros(1, 3, 64, 64, dtype = torch.bfloat16))+ assert vae.seen_dtype == torch.float32+++def test_missing_vae_and_broken_probe_are_no_ops():+ import torch++ # Best-effort: a missing VAE, or one whose parameters() raises, must never become a 500.+ DiffusionBackend._make_vae_encode_dtype_safe(types.SimpleNamespace())+ DiffusionBackend._make_vae_encode_dtype_safe(types.SimpleNamespace(vae = None))++ class _BrokenVae(_RecordingVae):+ def parameters(self):+ raise RuntimeError("meta device")++ vae = _BrokenVae(dtype = torch.bfloat16)+ DiffusionBackend._make_vae_encode_dtype_safe(types.SimpleNamespace(vae = vae))+ # The probe fails inside the call, so the tensor is forwarded as it arrived.+ vae.encode(torch.zeros(1, 3, 8, 8, dtype = torch.float32))+ assert vae.seen_dtype == torch.float32diff --git a/studio/backend/tests/test_diffusion_img2img_size.py b/studio/backend/tests/test_diffusion_img2img_size.pynew file mode 100644index 00000000000..39cd6869652--- /dev/null+++ b/studio/backend/tests/test_diffusion_img2img_size.py@@ -0,0 +1,100 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""CPU-only unit tests for the Transform output-size bound and the refusal it produces.++Reported: Image Transform refused at 2048x2048 no matter how small the Resolution controls were+set, because img2img sized from the upload (clamped to a fixed 2048) and the refusal then advised+changing a control that could not move that number. ``_fit_within`` makes the control bound the+source; ``source_driven`` fixes the remedy sentence where it still cannot.+"""++from __future__ import annotations++import types++import pytest++from core.inference.diffusion import _clamp_max_side, _fit_within+from core.inference.diffusion_memory import DeviceMemory, image_activation_shortfall_message++PIL = pytest.importorskip("PIL.Image")+++def _img(w: int, h: int):+ return PIL.new("RGB", (w, h))+++def test_oversized_source_is_bounded_by_the_requested_box():+ # The reported case: a big upload with the sliders set small.+ out = _fit_within(_img(4000, 3000), 512, 512)+ assert out.size == (512, 384) # fits the box, aspect ratio preserved+++def test_bound_is_the_box_not_just_the_longest_side():+ # A wide box and a square source: the HEIGHT binds, which a longest-side clamp misses.+ assert _fit_within(_img(1024, 1024), 1024, 256).size == (256, 256)+ # The longest-side clamp leaves it untouched -- the two are not interchangeable.+ assert _clamp_max_side(_img(1024, 1024), 1024).size == (1024, 1024)+++def test_small_source_is_never_enlarged():+ # Growing a source is the Upscale workflow; Transform must not silently do it.+ src = _img(384, 256)+ assert _fit_within(src, 2048, 2048) is src+ # Exactly on the box is also a no-op (identity, no resample pass).+ on_box = _img(512, 512)+ assert _fit_within(on_box, 512, 512) is on_box+++def test_one_axis_over_still_downscales_both():+ assert _fit_within(_img(2048, 512), 1024, 1024).size == (1024, 256)+++def test_degenerate_box_does_not_produce_a_zero_dimension():+ # Only a malformed request gets here, but a 0-px side would raise deep inside the VAE.+ out = _fit_within(_img(1000, 10), 1, 1)+ assert out.size[0] >= 1 and out.size[1] >= 1+++def _cuda(free_mib: int, total_mib: int) -> DeviceMemory:+ return DeviceMemory(+ backend = "cuda",+ device = "cuda",+ memory_kind = "discrete_vram",+ free_mib = free_mib,+ total_mib = total_mib,+ )+++def _shortfall(**kwargs) -> str:+ # 4096x4096 on a card with ~14 GB free is well past both arms of the guard.+ message = image_activation_shortfall_message(+ device_memory = _cuda(free_mib = 14000, total_mib = 16000),+ width = 4096,+ height = 4096,+ **kwargs,+ )+ assert message is not None+ return message+++def test_slider_driven_refusal_keeps_the_resolution_remedy():+ message = _shortfall()+ assert "Generate at a smaller resolution" in message+ assert "Upload a smaller source image" not in message+++def test_source_driven_refusal_points_at_the_upload_instead():+ message = _shortfall(source_driven = True)+ assert "Upload a smaller source image" in message+ # The wrong advice must be gone, not merely accompanied.+ assert "Generate at a smaller resolution" not in message+ assert "Resolution setting" in message+++def test_batch_note_still_composes_with_either_remedy():+ for source_driven in (False, True):+ message = _shortfall(batch_size = 4, source_driven = source_driven)+ assert "or a smaller batch size" in message+ assert "at a batch of 4" in messagediff --git a/studio/frontend/src/features/images/images-page.tsx b/studio/frontend/src/features/images/images-page.tsxindex 88f01c6b657..1dd6ab67954 100644--- a/studio/frontend/src/features/images/images-page.tsx+++ b/studio/frontend/src/features/images/images-page.tsx@@ -3989,7 +3989,18 @@ export function ImagesPage({ active = true }: { active?: boolean }) {</Field><Fieldlabel="Resolution"- hint="Width and height in pixels. Sizes run from 256 to 2048 in steps of 16. Z-Image is trained around 1 megapixel, so much larger sizes can look worse."+ hint={+ // Image-conditioned workflows size from the source, so "this is the output size"+ // is wrong there: Transform caps the source by this box, the rest ignore it.+ workflow === "transform"+ ? "Caps the output size. The source image is scaled down to fit inside this box, keeping its aspect ratio, so the result may be smaller than the values shown."+ : workflow === "inpaint" ||+ workflow === "extend" ||+ workflow === "upscale" ||+ workflow === "edit"+ ? "Not used by this workflow: the output size comes from the source image. Upload a smaller image to generate at a smaller size."+ : "Width and height in pixels. Sizes run from 256 to 2048 in steps of 16. Z-Image is trained around 1 megapixel, so much larger sizes can look worse."+ }><div className="flex items-center gap-2"><DimensionSelect