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 Images: Hires fix latent upscale interpolates the base latents directly, as ComfyUI's LatentUpscale (#14863)

Daniel Han4afc4f05ebe9
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.py
index 096e3374954..5b02f1c2c19 100644
--- a/studio/backend/core/inference/diffusion.py
+++ b/studio/backend/core/inference/diffusion.py
@@ -13038,7 +13038,7 @@ class DiffusionBackend:
kwargs["strength"] = strength
if _hires_pass is not None and _hires_pass.latent_from is not None:
# Latent upscaler: the SDXL img2img pipe takes 4-channel latents as the image.
- kwargs["image"] = diffusion_hires.encode_upscaled_latents(
+ kwargs["image"] = diffusion_hires.upscale_latents(
pipe, _hires_pass.latent_from, init_pil.size
)
# width/height: txt2img uses the slider; image-conditioned pipes must use the INPUT IMAGE's size or
@@ -13340,6 +13340,17 @@ class DiffusionBackend:
if "callback_on_step_end" in call_params:
kwargs["callback_on_step_end"] = _on_step
+ # Hires fix latent upscaler (ComfyUI LatentUpscale): the base pass hands the refine pass its latents,
+ # so it skips the VAE decode and the image post-processing that only the discarded pixels needed.
+ latent_output = bool(
+ _hires_pass is not None and _hires_pass.latent_output and not _hires_pass.refine
+ )
+ if latent_output:
+ if "output_type" not in call_params or layer_count or soft_overlay is not None:
+ raise ValueError(
+ "The latent upscaler needs a pipeline that returns latents."
+ )
+ kwargs["output_type"] = "latent"
kwargs.update(sd_controls_mod.guidance_rescale_kwargs(sd_controls, call_params))
weighting_used = [False]
@@ -13559,6 +13570,10 @@ class DiffusionBackend:
for (_, s), layers_out in zip(chunk, out):
images.extend(layers_out)
per_image_seeds.extend(s for _ in layers_out)
+ elif latent_output:
+ # One (1, C, h, w) per image; a copy, so no later forward can reuse its storage.
+ images.extend(out[i : i + 1].clone() for i in range(out.shape[0]))
+ per_image_seeds.extend(s for _, s in chunk)
else:
if soft_overlay is not None:
out = [overlay_with_mask(o, *soft_overlay) for o in out]
@@ -13586,7 +13601,8 @@ class DiffusionBackend:
cuda_graph.seal_lengths(state.cuda_graphs)
_record_peak_probe(
state,
- peak_probe,
+ # A pass that skipped its VAE decode misses that phase's peak: it must not size a plain render.
+ None if latent_output else peak_probe,
width = guard_width,
height = guard_height,
batch_size = max(chunk_shapes or [1]),
diff --git a/studio/backend/core/inference/diffusion_auto_policy.py b/studio/backend/core/inference/diffusion_auto_policy.py
index 078024c96d0..e2f9abcbb82 100644
--- a/studio/backend/core/inference/diffusion_auto_policy.py
+++ b/studio/backend/core/inference/diffusion_auto_policy.py
@@ -586,6 +586,8 @@ def format_generation_for_log(
"""One-line log summary of a generate() result."""
images = result.get("images") or ()
size = getattr(images[0], "size", None) if images else None
+ if not isinstance(size, tuple):
+ size = None # a latent tensor (Hires fix base pass) has no pixel size
fields = {
"engine": engine,
"workflow": result.get("workflow"),
diff --git a/studio/backend/core/inference/diffusion_hires.py b/studio/backend/core/inference/diffusion_hires.py
index 9ad0fe196c5..ec10590b1bd 100644
--- a/studio/backend/core/inference/diffusion_hires.py
+++ b/studio/backend/core/inference/diffusion_hires.py
@@ -57,6 +57,9 @@ class HiresPass:
cancel: threading.Event
preflight: Optional[Callable[[dict], None]] = None
source: Any = None
+ # Base pass: return the sampler's latents (``output_type="latent"``), not decoded images (latent upscaler).
+ latent_output: bool = False
+ # Refine pass: this image's base latents, ``(1, C, h, w)``, upscaled in latent space as the img2img input.
latent_from: Any = None
# The base pass leaves a pending background compile for after the refine pass (else the refine pass waits on it).
defer_bg_kick: bool = False
@@ -480,61 +483,18 @@ def sd_cpp_payload(
}
-def _vae_execution_device(pipe: Any, vae: Any, param: Any) -> Any:
- """Where the VAE computes. Under CPU offload its weights sit on the host (model offload) or on ``meta``
- (sequential offload) and the hook moves them to the card for the call, so the input must go to the card."""
- import torch
-
- hook_device = getattr(getattr(vae, "_hf_hook", None), "execution_device", None)
- if hook_device is not None:
- if isinstance(hook_device, int):
- return torch.device("cuda", hook_device)
- return torch.device(hook_device)
- if param.device.type not in ("cpu", "meta"):
- # Resident (or placed on its own card by a split): the weights are where it runs.
- return param.device
- try:
- exec_device = getattr(pipe, "_execution_device", None)
- except Exception: # noqa: BLE001 - a duck-typed pipe; fall back to the weights
- exec_device = None
- if exec_device is not None and torch.device(exec_device).type != "meta":
- return torch.device(exec_device)
- return param.device
-
-
-def encode_upscaled_latents(pipe: Any, base_image: Any, target: tuple[int, int]) -> Any:
- """VAE-encode as StableDiffusionXLImg2ImgPipeline.prepare_latents does, then interpolate nearest-exact."""
+def upscale_latents(pipe: Any, latents: Any, target: tuple[int, int]) -> Any:
+ """ComfyUI ``LatentUpscale``: ``common_upscale(samples, w // 8, h // 8, "nearest-exact", crop="disabled")`` on the
+ sampler's own latents. No VAE round trip: nearest-exact commutes with the per-channel latent scaling."""
import torch
import torch.nn.functional as F
- vae = pipe.vae
- param = next(vae.parameters())
- device, dtype = _vae_execution_device(pipe, vae, param), param.dtype
- x = pipe.image_processor.preprocess(base_image).to(device = device, dtype = dtype)
- upcast = bool(getattr(vae.config, "force_upcast", False)) and dtype == torch.float16
+ if not isinstance(latents, torch.Tensor) or latents.ndim != 4:
+ raise TypeError("The latent upscaler needs the base pass's latents, (1, C, h, w).")
+ tw, th = target
+ factor = int(getattr(pipe, "vae_scale_factor", SDXL_LATENT_FACTOR) or SDXL_LATENT_FACTOR)
with torch.inference_mode():
- if upcast:
- vae.to(dtype = torch.float32)
- x = x.float()
- try:
- lat = vae.encode(x).latent_dist.mode()
- finally:
- if upcast:
- vae.to(dtype = dtype)
- lat = lat.to(dtype)
- mean = getattr(vae.config, "latents_mean", None)
- std = getattr(vae.config, "latents_std", None)
- sf = float(vae.config.scaling_factor)
- if mean is not None and std is not None:
- m = torch.tensor(mean, device = device, dtype = dtype).view(1, -1, 1, 1)
- s = torch.tensor(std, device = device, dtype = dtype).view(1, -1, 1, 1)
- lat = (lat - m) * sf / s
- else:
- lat = lat * sf
- tw, th = target
- factor = int(getattr(pipe, "vae_scale_factor", SDXL_LATENT_FACTOR) or SDXL_LATENT_FACTOR)
- lat = F.interpolate(lat, size = (th // factor, tw // factor), mode = "nearest-exact")
- return lat
+ return F.interpolate(latents, size = (th // factor, tw // factor), mode = "nearest-exact")
def _rearm_cancel(backend: Any, cancel: threading.Event) -> None:
@@ -680,7 +640,13 @@ def run_hires(
_plan()
# A model upscaler also runs on the GPU after the base pass, so a background compile waits for it too.
defer_kick = refine or upscalers.is_model_upscaler(params.upscaler)
- ctx = HiresPass(cancel = cancel, preflight = _preflight, defer_bg_kick = defer_kick)
+ ctx = HiresPass(
+ cancel = cancel,
+ preflight = _preflight,
+ defer_bg_kick = defer_kick,
+ # The latent upscaler needs no pixels: the base pass skips its VAE decode and the refine its encode.
+ latent_output = refine and params.upscaler == upscalers.LATENT,
+ )
base = generate(backend, **kwargs, _hires_pass = ctx)
if defer_kick:
# The base pass left a compile pending: start it once the passes after it end, also when one fails or is
@@ -709,9 +675,9 @@ def run_hires(
t_up = time.perf_counter()
latent_from = None
if params.upscaler == upscalers.LATENT:
- # Placeholder at the hires size: the refine call reads only its size; the latents replace it.
+ # Placeholder at the hires size: the refine call reads only its size; the base latents replace it.
source = Image.new("RGB", target)
- latent_from = image
+ latent_from = image # this image's (1, C, h, w) base latents
elif params.upscaler == upscalers.LANCZOS:
source = image.convert("RGB").resize(target, Image.LANCZOS)
else:
diff --git a/studio/backend/tests/test_diffusion_hires.py b/studio/backend/tests/test_diffusion_hires.py
index 8a4f163c86f..990ea96740d 100644
--- a/studio/backend/tests/test_diffusion_hires.py
+++ b/studio/backend/tests/test_diffusion_hires.py
@@ -865,6 +865,8 @@ def test_run_hires_plans_against_the_model_loaded_when_the_slot_is_held():
{"prompt": "p", "width": 256, "height": 256, "steps": 8, "seed": 1, "batch_size": 1},
)
assert out["hires"]["upscaler"] == "latent"
+ # The latent upscaler asks the base pass for latents; a refine never decodes for it.
+ assert seen[0].latent_output is True and seen[1].latent_output is False
assert seen[1].latent_from is not None
@@ -1363,46 +1365,6 @@ def _fresh_tiny_sdxl(path):
return diffusers.StableDiffusionXLPipeline.from_pretrained(path, torch_dtype = torch.float32)
-def _base_image():
- from PIL import Image
- return Image.new("RGB", (64, 64), (120, 30, 200))
-
-
-def test_latent_encode_runs_where_the_offload_hook_computes(tiny_sdxl_path):
- """Sequential-style offload leaves the VAE weights on ``meta`` and computes on the hook's device: the input must
- go to that device, not to the weights' (fail-before: the input lands on ``meta``)."""
- import torch
- from accelerate import cpu_offload
-
- pipe = _fresh_tiny_sdxl(tiny_sdxl_path)
- f = pipe.vae_scale_factor
- resident = hires.encode_upscaled_latents(pipe, _base_image(), (96, 96))
- cpu_offload(pipe.vae, execution_device = torch.device("cpu"))
- assert next(pipe.vae.parameters()).device.type == "meta"
- lat = hires.encode_upscaled_latents(pipe, _base_image(), (96, 96))
- assert lat.device.type == "cpu" and lat.shape == (1, 4, 96 // f, 96 // f)
- assert torch.allclose(lat, resident, atol = 1e-5)
-
-
-def test_vae_execution_device_order():
- import torch
-
- cpu_param = torch.nn.Parameter(torch.zeros(1))
- meta_param = torch.nn.Parameter(torch.zeros(1, device = "meta"))
- hooked = types.SimpleNamespace(_hf_hook = types.SimpleNamespace(execution_device = 0))
- bare = types.SimpleNamespace()
- pipe = types.SimpleNamespace(_execution_device = torch.device("cuda", 1))
- # A whole-module offload hook names the card the weights move to.
- assert hires._vae_execution_device(pipe, hooked, cpu_param) == torch.device("cuda", 0)
- # Weights on the host or on meta with no hook of their own: the pipeline's execution device.
- assert hires._vae_execution_device(pipe, bare, cpu_param) == torch.device("cuda", 1)
- assert hires._vae_execution_device(pipe, bare, meta_param) == torch.device("cuda", 1)
- # A duck-typed pipe with no execution device keeps the weights' device.
- assert hires._vae_execution_device(types.SimpleNamespace(), bare, cpu_param) == torch.device(
- "cpu"
- )
-
-
def _cuda_or_skip():
torch = pytest.importorskip("torch")
if not torch.cuda.is_available():
@@ -1410,52 +1372,134 @@ def _cuda_or_skip():
return torch
[email protected]("offload", ["model", "sequential"])
-def test_latent_encode_under_cpu_offload_on_cuda(tiny_sdxl_path, offload):
- """Studio loads SDXL with enable_model_cpu_offload when it does not fit (fail-before: RuntimeError, input on
- the CPU while the hook moved the VAE to the card)."""
- torch = _cuda_or_skip()
- pipe = _fresh_tiny_sdxl(tiny_sdxl_path)
- pipe.to("cuda")
- resident = hires.encode_upscaled_latents(pipe, _base_image(), (96, 96))
- pipe.to("cpu")
- if offload == "model":
- pipe.enable_model_cpu_offload(device = "cuda")
- else:
- pipe.enable_sequential_cpu_offload(device = "cuda")
- assert next(pipe.vae.parameters()).device.type in ("cpu", "meta")
- lat = hires.encode_upscaled_latents(pipe, _base_image(), (96, 96))
- assert lat.device.type == "cuda"
- assert torch.allclose(lat, resident, atol = 1e-4)
-
-
-def test_tiny_sdxl_hires_latent_under_model_offload_on_cuda(tiny_sdxl_path):
- """The default SDXL Hires fix (latent upscaler) end to end on a whole-module offloaded load."""
- _cuda_or_skip()
+def _latent_hires_backend(path, device, offload):
from core.inference.diffusion import DiffusionBackend, _LoadState
- pipe = _fresh_tiny_sdxl(tiny_sdxl_path)
- pipe.enable_model_cpu_offload(device = "cuda")
+ pipe = _fresh_tiny_sdxl(path)
+ if offload == "model":
+ pipe.enable_model_cpu_offload(device = device)
+ elif offload == "sequential":
+ pipe.enable_sequential_cpu_offload(device = device)
+ else:
+ pipe.to(device)
b = DiffusionBackend()
b._state = _LoadState(
pipe = pipe,
family = _fam("sdxl"),
repo_id = "tiny",
base_repo = "tiny",
- device = "cuda",
+ device = device,
dtype = "float32",
- cpu_offload = True,
- offload_policy = "model",
+ cpu_offload = offload != "none",
+ offload_policy = offload,
+ )
+ return b, pipe
+
+
+ "device, offload",
+ [("cpu", "none"), ("cuda", "none"), ("cuda", "model"), ("cuda", "sequential")],
+)
+def test_latent_upscaler_refines_the_sampler_latents_like_comfyui(
+ tiny_sdxl_path, monkeypatch, device, offload
+):
+ """ComfyUI LatentUpscale: the refine pass gets exactly ``F.interpolate(base_latents, nearest-exact)``, with no base
+ decode and no re-encode (fail-before: the base pass decodes to 8-bit pixels and the refine VAE-encodes them)."""
+ import functools
+
+ import diffusers
+ import numpy as np
+ import torch
+ import torch.nn.functional as F
+
+ if device == "cuda":
+ _cuda_or_skip()
+ b, pipe = _latent_hires_backend(tiny_sdxl_path, device, offload)
+ vae_calls = {"encode": 0, "decode": 0}
+ for name in vae_calls:
+ bound = getattr(pipe.vae, name)
+
+ def counted(
+ *a,
+ _name = name,
+ _bound = bound,
+ **k,
+ ):
+ vae_calls[_name] += 1
+ return _bound(*a, **k)
+
+ monkeypatch.setattr(pipe.vae, name, counted)
+ base_out, refine_in = [], []
+ orig_base = diffusers.StableDiffusionXLPipeline.__call__
+ orig_refine = diffusers.StableDiffusionXLImg2ImgPipeline.__call__
+
+ @functools.wraps(orig_base)
+ def base_spy(self, *a, **k):
+ out = orig_base(self, *a, **k)
+ base_out.append((k.get("output_type"), out.images))
+ return out
+
+ @functools.wraps(orig_refine)
+ def refine_spy(self, *a, **k):
+ refine_in.append(k["image"].detach().clone())
+ return orig_refine(self, *a, **k)
+
+ monkeypatch.setattr(diffusers.StableDiffusionXLPipeline, "__call__", base_spy)
+ monkeypatch.setattr(diffusers.StableDiffusionXLImg2ImgPipeline, "__call__", refine_spy)
+ kw = dict(
+ prompt = "a cat", width = 256, height = 256, steps = 2, guidance = 5.0, seed = 7, live_preview = False
)
+ plain = b.generate(**kw, batch_size = 2)
+ assert vae_calls == {"encode": 0, "decode": 1}
+ base_out.clear()
+ vae_calls.update(encode = 0, decode = 0)
+
out = b.generate(
- prompt = "a cat",
- width = 256,
- height = 256,
- steps = 2,
- guidance = 5.0,
- seed = 7,
- live_preview = False,
+ **kw,
+ batch_size = 2,
hires = hires.HiresParams(scale = 1.5, denoise = 0.5, steps = 2, upscaler = "latent"),
)
- assert out["images"][0].size == (384, 384)
- assert out["hires"]["upscaler"] == "latent" and out["hires"]["refine_steps"] == 2
+ assert [im.size for im in out["images"]] == [(384, 384)] * 2
+ assert out["seeds"] == plain["seeds"]
+ # One decode per refined image, none for the base pass, no encode at all.
+ assert vae_calls == {"encode": 0, "decode": 2}
+ ((output_type, latents),) = base_out
+ f = pipe.vae_scale_factor
+ assert output_type == "latent" and tuple(latents.shape) == (2, 4, 256 // f, 256 // f)
+ assert len(refine_in) == 2
+ for i, got in enumerate(refine_in):
+ want = F.interpolate(latents[i : i + 1], size = (384 // f, 384 // f), mode = "nearest-exact")
+ assert got.device == want.device and torch.equal(got, want)
+ # The base pass is unchanged: its latents decode to the pixels a plain render returns.
+ with torch.inference_mode():
+ decoded = pipe.vae.decode(latents / pipe.vae.config.scaling_factor, return_dict = False)[0]
+ pixels = pipe.image_processor.postprocess(decoded, output_type = "pil")
+ for got, want in zip(pixels, plain["images"]):
+ diff = np.abs(np.asarray(got, dtype = np.int16) - np.asarray(want, dtype = np.int16))
+ assert diff.max() <= 1
+ assert b._gen is None and b._active_generate_cancel is None
+
+
+def test_latent_upscale_is_comfyui_nearest_exact_and_needs_latents():
+ torch = pytest.importorskip("torch")
+ import torch.nn.functional as F
+
+ lat = torch.randn(1, 4, 8, 12)
+ pipe = types.SimpleNamespace(vae_scale_factor = 8)
+ got = hires.upscale_latents(pipe, lat, (144, 96))
+ assert torch.equal(got, F.interpolate(lat, size = (12, 18), mode = "nearest-exact"))
+ from PIL import Image
+
+ with pytest.raises(TypeError, match = "latents"):
+ hires.upscale_latents(pipe, Image.new("RGB", (64, 64)), (96, 96))
+
+
+def test_generation_log_line_takes_a_latent_base_pass():
+ """The latent base pass returns tensors, whose ``size`` is a method, not a pixel size."""
+ torch = pytest.importorskip("torch")
+ from core.inference.diffusion_auto_policy import format_generation_for_log
+
+ line = format_generation_for_log(
+ {"images": [torch.zeros(1, 4, 8, 8)], "workflow": "txt2img"}, engine = "diffusers"
+ )
+ assert "images=1" in line and "size=" not in line