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 and ESRGAN model upscalers (#14651)

Daniel Han45b095e2b6c9
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.py
index 84741454a86..d694ba57b65 100644
--- a/studio/backend/core/inference/diffusion.py
+++ b/studio/backend/core/inference/diffusion.py
@@ -233,6 +233,8 @@ from .diffusion_memory import (
vae_is_sliced,
)
from .diffusion_torchao_patches import install_torchao_int_mm_patch
+from . import diffusion_hires, diffusion_upscalers
+from .diffusion_hires import HiresPass, with_hires
from .image_orientation import exif_upright
from .mcp_images import flattened_rgb
from .media_decode_phase import decode_phase, denoise_phase
@@ -12276,6 +12278,7 @@ class DiffusionBackend:
)
@_release_render_on_unload
+ @with_hires
def generate(
self,
*,
@@ -12325,16 +12328,22 @@ class DiffusionBackend:
mask_blur: Optional[int] = None,
inpaint_only_masked: Optional[bool] = None,
inpaint_padding: Optional[int] = None,
+ # Upscale workflow: a model upscaler id (diffusion_upscalers) in place of the Lanczos resize. None = Lanczos.
+ upscale_model: Optional[str] = None,
+ _hires_pass: Optional[HiresPass] = None,
) -> dict[str, Any]:
import torch
+ from contextlib import nullcontext
+
from PIL import Image
# Per-generation cancel Event that unload()/a superseding load set (under _lock) to abort just this denoise.
- cancel = threading.Event()
+ cancel = _hires_pass.cancel if _hires_pass is not None else threading.Event()
from core.inference.generation_ticket import bind_generation_cancel
- bind_generation_cancel(cancel)
- with self._generation_slot(cancel):
+ if _hires_pass is None:
+ bind_generation_cancel(cancel)
+ with nullcontext() if _hires_pass is not None else self._generation_slot(cancel):
# Never render beside a background compile; wait outside the state lock so status polls keep answering.
pending_bg = getattr(self._state, "bg_compile", None)
if pending_bg is not None and pending_bg.compiling():
@@ -12504,6 +12513,13 @@ class DiffusionBackend:
)
workflow = "reference"
conditioned = True
+ elif _hires_pass is not None and _hires_pass.refine:
+ workflow = "upscale"
+ pipe = self._workflow_pipe(state, fam.img2img_pipeline_class, workflow)
+ init_pil = _hires_pass.source
+ steps = diffusion_hires.refine_inference_steps(
+ steps, float(strength), diffusion_hires.timestep_rule(pipe)
+ )
elif mask_image is not None and init_image is not None:
workflow = "inpaint"
pipe = self._workflow_pipe(state, fam.inpaint_pipeline_class, workflow)
@@ -12530,12 +12546,28 @@ class DiffusionBackend:
f"({max(iw, ih)}px) already meets the {max_side}px output limit. "
f"Use a smaller source image."
)
- init_pil = init_pil.resize((tw, th), Image.LANCZOS)
+ if upscale_model:
+ # ESRGAN-family model, then resized to the target (ComfyUI ImageUpscaleWithModel -> ImageScale).
+ init_pil = diffusion_upscalers.upscale_with_model(
+ init_pil,
+ upscale_model,
+ (tw, th),
+ device = state.device,
+ keep_resident = getattr(state, "offload_policy", None)
+ in (None, OFFLOAD_NONE),
+ cancel = cancel,
+ ).image
+ else:
+ init_pil = init_pil.resize((tw, th), Image.LANCZOS)
upscale = round(
max(tw / iw, th / ih), 2
) # the factor after both caps, for the log
if strength is None:
strength = 0.35 # hires-fix default: preserve content, add detail
+ elif upscale_model:
+ raise ValueError(
+ "upscale_model applies only to the Upscale workflow (init_image + upscale > 1)."
+ )
elif getattr(fam, "reference", False) and init_image is not None:
workflow = "reference"
conditioned = True
@@ -12731,6 +12763,11 @@ class DiffusionBackend:
kwargs["padding_mask_crop"] = inpaint_padding_applied
if strength is not None and "strength" in call_params:
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(
+ 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
# the latents mismatch, and many drop them, so pass only when accepted.
if not source_sized:
@@ -12896,6 +12933,8 @@ class DiffusionBackend:
logger = logger,
)
verdict = raise_on_image_activation_shortfall(**guard_kwargs)
+ if _hires_pass is not None and _hires_pass.preflight is not None:
+ _hires_pass.preflight(guard_kwargs)
_guard_layer_cards(state.pipe, guard_target, guard_kwargs)
restore_vae = _tile_for_verdict(
pipe, verdict, guard_target, guard_kwargs, guard_batch, restore_vae, logger
@@ -12907,7 +12946,13 @@ class DiffusionBackend:
"diffusion.generate: activation headroom re-check skipped (%s)", exc
)
- gen = _GenState(total_steps = steps * len(chunks))
+ # The steps the pipe runs: a Hires refine converts its count to a longer schedule it enters partway.
+ progress_steps = (
+ int(_hires_pass.stats.get("refine_steps") or steps)
+ if _hires_pass is not None and _hires_pass.refine
+ else steps
+ )
+ gen = _GenState(total_steps = progress_steps * len(chunks))
# Steps completed by FINISHED chunks, so the bar spans the whole multi-chunk call (mutable cell for
# _on_step).
steps_done = [0]
@@ -12944,7 +12989,7 @@ class DiffusionBackend:
width = preview_w,
device = state.device,
publish = _publish_preview,
- total_steps = steps,
+ total_steps = progress_steps,
)
# Count steps the GPU FINISHED (per-step CUDA events, as the video path): under CUDA graphs the host
@@ -12958,12 +13003,12 @@ class DiffusionBackend:
)
# Replaced per chunk: a finished chunk's boundary must not end the next one's denoise.
- chunk_ticker = [_CompletedStepTicker(steps)]
+ chunk_ticker = [_CompletedStepTicker(progress_steps)]
def _report(done_in_chunk: int) -> None:
if gen.phase not in ("encode", "denoise"):
return
- done = steps_done[0] + max(0, min(int(done_in_chunk), steps))
+ done = steps_done[0] + max(0, min(int(done_in_chunk), progress_steps))
if done <= gen.step:
return
gen.phase = "denoise"
@@ -12978,7 +13023,7 @@ class DiffusionBackend:
def _flip_to_decode(gen = gen) -> None:
# The chunk's denoise is provably over: complete it even if a skipped event left the count short.
- _report(steps)
+ _report(progress_steps)
gen.phase = "decode"
gen.eta_seconds = None
@@ -13147,7 +13192,7 @@ class DiffusionBackend:
if state.te_releaser is not None:
state.te_releaser.release()
- chunk_ticker[0] = _CompletedStepTicker(steps)
+ chunk_ticker[0] = _CompletedStepTicker(progress_steps)
def _enter_decode_phase() -> None:
"""The decoder was entered: a HOST position, possibly far ahead of the GPU. Mark the
@@ -13235,7 +13280,7 @@ class DiffusionBackend:
images.extend(out)
per_image_seeds.extend(s for _, s in chunk)
chunk_shapes.append(len(chunk))
- steps_done[0] += steps
+ steps_done[0] += progress_steps
except BaseException:
if previewer is not None:
previewer.finish()
@@ -13272,7 +13317,8 @@ class DiffusionBackend:
if bg_eager:
# Nothing compiled ran, so nothing to register or save yet.
bg.note_eager_generation()
- bg.kick()
+ if _hires_pass is None or not _hires_pass.defer_bg_kick:
+ bg.kick()
else:
try:
# Register the dims the forward ACTUALLY compiled with, and every distinct chunk size (a static
@@ -13317,7 +13363,8 @@ class DiffusionBackend:
# Components are offloaded and transfer copies dropped; return the pages now.
reclaim_offload_host_memory(state.offload_policy, logger = logger)
# Count the finished generation (drives deferred speed); a batch is one generation.
- object.__setattr__(state, "generation_count", state.generation_count + 1)
+ if _hires_pass is None or not _hires_pass.refine:
+ object.__setattr__(state, "generation_count", state.generation_count + 1)
result = {
"images": list(images),
"seed": int(seed),
@@ -13363,6 +13410,8 @@ class DiffusionBackend:
"inpaint_only_masked": True if inpaint_padding_applied is not None else None,
"inpaint_padding": inpaint_padding_applied,
}
+ if upscale_model and workflow == "upscale":
+ result["upscale_model"] = upscale_model
if applied_shift is not None:
result["shift"] = shift
result["base_shift"] = base_shift
@@ -13599,6 +13648,7 @@ class DiffusionBackend:
self._aux_pipes.clear()
self._cn_pipes.clear()
self._cn_models.clear()
+ diffusion_upscalers.release_models()
self._state = None
del state
try:
@@ -13730,6 +13780,7 @@ class DiffusionBackend:
if pipe_sample_sigmas(state.pipe) is not None
else shift_control(_state_shift_node(state), getattr(state.pipe, "scheduler", None)),
"textual_inversion": getattr(state.family, "textual_inversion", None),
+ **_hires_status(state.family),
"conditioning": conditioning_capabilities(
state.family, _family_workflows(state.family)
),
@@ -13782,6 +13833,24 @@ def _transformer_quant_backend(state: Any) -> Optional[str]:
return None
+def _hires_status(fam: DiffusionFamily) -> dict[str, Any]:
+ """Status keys for Hires fix (hidden without an img2img path) and the Upscale workflow's model upscalers."""
+ try:
+ models = diffusion_upscalers.model_upscalers()
+ except Exception as exc: # noqa: BLE001 - a broken scan hides model upscalers, never the status
+ logger.debug("diffusion.upscalers: scan failed: %s", exc)
+ models = []
+ hires = diffusion_hires.capability(fam, model_rows = models)
+ return {
+ "hires": hires,
+ # Why the control is hidden (no img2img path yet), shown in its place.
+ "hires_unavailable_reason": diffusion_hires.unavailable_reason(fam)
+ if hires is None
+ else None,
+ "upscale_models": models if getattr(fam, "img2img_pipeline_class", None) else [],
+ }
+
+
def _family_workflows(fam: DiffusionFamily) -> list[str]:
"""The workflow ids the diffusers engine can run for ``fam`` (drives UI gating)."""
# Instruction-editing families have no txt2img mode, so expose only "edit".
diff --git a/studio/backend/core/inference/diffusion_hires.py b/studio/backend/core/inference/diffusion_hires.py
new file mode 100644
index 00000000000..8c6283cdcc8
--- /dev/null
+++ b/studio/backend/core/inference/diffusion_hires.py
@@ -0,0 +1,827 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Hires fix: txt2img, upscale, then refine (img2img at a denoise) in one request.
+
+Defaults follow ComfyUI's 2_pass_txt2img example (1.5x, denoise 0.5, 14 steps). Hires steps is the exact refine
+count, as in ComfyUI (``new_steps = int(steps / denoise)``) and A1111 (``hr_second_pass_steps or steps``).
+"""
+
+from __future__ import annotations
+
+import contextlib
+import functools
+import inspect
+import math
+import threading
+import time
+from dataclasses import dataclass, field, replace
+from typing import Any, Callable, Optional
+
+from loggers import get_logger
+
+from . import diffusion_upscalers as upscalers
+
+logger = get_logger(__name__)
+
+DEFAULT_SCALE = 1.5
+DEFAULT_DENOISE = 0.5
+# The smallest non-zero denoise: the 0.01 step of A1111's "Denoising strength" slider and ComfyUI's KSampler denoise.
+# Below it ``steps / denoise`` grows without bound.
+MIN_DENOISE = 0.01
+MIN_SCALE = 1.0
+MAX_SCALE = 4.0
+MAX_SIDE = 2048
+# StableDiffusionXLImg2ImgPipeline.prepare_latents takes a 4-channel latent as is.
+LATENT_FAMILIES = frozenset({"sdxl"})
+SDXL_LATENT_FACTOR = 8
+
+RULE_FLOOR = "floor" # SDXL: init_timestep = min(int(N * s), N)
+RULE_FLOW = "flow" # FLUX / Qwen-Image / Z-Image: t_start = int(max(N - min(N * s, N), 0)); runs N - t_start
+
+
+@dataclass(frozen = True)
+class HiresParams:
+ scale: float = DEFAULT_SCALE
+ denoise: float = DEFAULT_DENOISE
+ # None = the base pass's step count (A1111 ``hr_second_pass_steps or steps``).
+ steps: Optional[int] = None
+ # None = the family default (latent on SDXL, Lanczos elsewhere).
+ upscaler: Optional[str] = None
+ # None = the base guidance (Forge ``hr_cfg``, infotext "Hires CFG Scale").
+ guidance: Optional[float] = None
+
+
+@dataclass
+class HiresPass:
+ cancel: threading.Event
+ preflight: Optional[Callable[[dict], None]] = None
+ source: Any = None
+ 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
+ refine: bool = False
+ stats: dict = field(default_factory = dict)
+
+
+def default_upscaler(family_name: Optional[str]) -> str:
+ return upscalers.LATENT if family_name in LATENT_FAMILIES else upscalers.LANCZOS
+
+
+def resolve_params(hires: HiresParams, family_name: Optional[str]) -> HiresParams:
+ """Fill the family default upscaler and validate the request against the family (ValueError -> 400)."""
+ upscaler = hires.upscaler or default_upscaler(family_name)
+ upscalers.check_upscaler_id(upscaler)
+ if upscaler == upscalers.LATENT and family_name not in LATENT_FAMILIES:
+ raise ValueError(
+ "The latent upscaler is available on SDXL only; pick Lanczos or a model upscaler for this model."
+ )
+ if not (MIN_SCALE <= float(hires.scale) <= MAX_SCALE):
+ raise ValueError(f"Hires upscale must be between {MIN_SCALE:g} and {MAX_SCALE:g}.")
+ if not (0.0 <= float(hires.denoise) <= 1.0):
+ raise ValueError("Hires denoising strength must be between 0 and 1.")
+ if 0.0 < float(hires.denoise) < MIN_DENOISE:
+ raise ValueError(
+ f"Hires denoising strength must be 0 (upscale only) or at least {MIN_DENOISE:g}."
+ )
+ if upscaler == upscalers.LATENT and float(hires.denoise) <= 0.0:
+ raise ValueError(
+ "The latent upscaler needs a refine pass: set a denoising strength above 0."
+ )
+ return replace(hires, upscaler = upscaler)
+
+
+def hires_target_size(
+ width: int,
+ height: int,
+ scale: float,
+ *,
+ multiple: int = 16,
+ max_side: int = MAX_SIDE,
+ max_pixels: Optional[int] = None,
+) -> tuple[int, int]:
+ """``round(side * scale)`` to a multiple of 16, scaled down to fit ``max_side`` and ``max_pixels``."""
+ multiple = max(1, int(multiple))
+ tw_f, th_f = float(width) * float(scale), float(height) * float(scale)
+ fit = min(1.0, float(max_side) / max(tw_f, th_f))
+ if max_pixels:
+ fit = min(fit, math.sqrt(float(max_pixels) / (tw_f * th_f)))
+ tw = max(multiple, int(round(tw_f * fit / multiple)) * multiple)
+ th = max(multiple, int(round(th_f * fit / multiple)) * multiple)
+ if max_pixels:
+ while tw * th > max_pixels and (tw > multiple or th > multiple):
+ if tw >= th:
+ tw -= multiple
+ else:
+ th -= multiple
+ return tw, th
+
+
+def steps_run(num_inference_steps: int, strength: float, rule: str) -> int:
+ """Steps an img2img pipeline actually denoises for ``num_inference_steps`` at ``strength``."""
+ n = int(num_inference_steps)
+ s = float(strength)
+ if rule == RULE_FLOOR:
+ return min(int(n * s), n)
+ t_start = int(max(n - min(n * s, n), 0))
+ return n - t_start
+
+
+def refine_inference_steps(steps: int, denoise: float, rule: str) -> int:
+ """The ``num_inference_steps`` that makes the refine pass run EXACTLY ``steps`` steps at ``denoise``."""
+ steps = max(1, int(steps))
+ denoise = float(denoise)
+ if denoise >= 1.0:
+ return steps
+ # ComfyUI's schedule first (``new_steps = int(steps / denoise)``), then the nearest count that also works.
+ guess = int(steps / denoise)
+ for n in (guess, guess + 1, guess - 1, guess + 2, guess - 2, guess + 3):
+ if n >= steps and steps_run(n, denoise, rule) == steps:
+ return n
+ n = steps
+ # denoise >= MIN_DENOISE bounds this at about steps / MIN_DENOISE.
+ limit = int(math.ceil(steps / max(denoise, MIN_DENOISE))) + 4
+ while steps_run(n, denoise, rule) < steps:
+ if n >= limit:
+ raise ValueError(
+ f"Hires fix cannot schedule {steps} refine steps at denoise {denoise:g}."
+ )
+ n += 1
+ return n
+
+
+def timestep_rule(pipe: Any) -> str:
+ """Which rounding ``pipe.get_timesteps`` applies; FLOOR for SDXL-style ``int(N * strength)``."""
+ fn = getattr(type(pipe), "get_timesteps", None)
+ try:
+ src = inspect.getsource(fn) if fn is not None else ""
+ except (OSError, TypeError):
+ src = ""
+ return RULE_FLOOR if "int(num_inference_steps * strength)" in src else RULE_FLOW
+
+
+def _upscaler_rows(family_name: Optional[str], model_rows: list[dict]) -> list[dict]:
+ rows: list[dict] = []
+ if family_name in LATENT_FAMILIES:
+ rows.append(
+ {
+ "id": upscalers.LATENT,
+ "label": upscalers.BUILTIN_LABELS[upscalers.LATENT],
+ "kind": "latent",
+ }
+ )
+ rows.append(
+ {
+ "id": upscalers.LANCZOS,
+ "label": upscalers.BUILTIN_LABELS[upscalers.LANCZOS],
+ "kind": "pixel",
+ }
+ )
+ rows.extend({"id": r["id"], "label": r["label"], "kind": "model"} for r in model_rows)
+ return rows
+
+
+def capability(
+ family: Any,
+ *,
+ model_rows: Optional[list[dict]] = None,
+ max_side: int = MAX_SIDE,
+ native: bool = False,
+) -> Optional[dict]:
+ """Status ``hires`` block for a family with an img2img path; None hides the control."""
+ if family is None or getattr(family, "edit", False) or getattr(family, "layer_count", 0):
+ return None
+ if not getattr(family, "img2img_pipeline_class", None):
+ return None
+ name = getattr(family, "name", None)
+ side = min(int(max_side), int(getattr(family, "max_output_side", MAX_SIDE) or MAX_SIDE))
+ return {
+ "upscalers": _upscaler_rows(name, list(model_rows or [])),
+ "default_upscaler": default_upscaler(name),
+ "defaults": {"scale": DEFAULT_SCALE, "denoise": DEFAULT_DENOISE},
+ "max_side": side,
+ # sd.cpp takes no separate refine CFG and no upscale-only pass (plan_sd_cpp refuses both).
+ "supports_guidance": not native,
+ "min_denoise": MIN_DENOISE if native else 0.0,
+ }
+
+
+def unavailable_reason(family: Any) -> Optional[str]:
+ if family is None or getattr(family, "edit", False):
+ return None
+ if not getattr(family, "img2img_pipeline_class", None):
+ return f"Hires fix needs an image-to-image path, which {getattr(family, 'name', 'this model')} does not have yet."
+ return None
+
+
+def record_fields(result_hires: Optional[dict]) -> dict:
+ if not result_hires:
+ return {}
+ return {
+ "hires_scale": result_hires.get("scale"),
+ "hires_denoise": result_hires.get("denoise"),
+ "hires_steps": result_hires.get("steps"),
+ "hires_upscaler": result_hires.get("upscaler"),
+ "hires_guidance": result_hires.get("guidance"),
+ "hires_base_width": result_hires.get("base_width"),
+ "hires_base_height": result_hires.get("base_height"),
+ }
+
+
+def infotext_meta(meta: dict) -> dict:
+ """A1111 ``Size`` is the base pass, so a Hires fix image records the base ``width``/``height``."""
+ if (
+ meta.get("hires_scale") is None
+ or not meta.get("hires_base_width")
+ or not meta.get("hires_base_height")
+ ):
+ return meta
+ return {
+ **meta,
+ "width": meta["hires_base_width"],
+ "height": meta["hires_base_height"],
+ # The rendered size, for infotext_fields' Hires resize.
+ "hires_width": meta.get("width"),
+ "hires_height": meta.get("height"),
+ }
+
+
+def infotext_fields(meta: dict) -> str:
+ """A1111 infotext for a hires image in A1111 / Forge key names; empty for any other image."""
+ if meta.get("hires_scale") is None:
+ return ""
+ parts = [f"Denoising strength: {meta.get('hires_denoise')}"]
+ out_w, out_h = meta.get("hires_width"), meta.get("hires_height")
+ base_w, base_h = meta.get("hires_base_width"), meta.get("hires_base_height")
+ scale = float(meta["hires_scale"])
+ if (
+ out_w
+ and out_h
+ and base_w
+ and base_h
+ and (int(out_w), int(out_h)) != (int(int(base_w) * scale), int(int(base_h) * scale))
+ ):
+ # A1111 sizes ``Hires upscale`` as int(side * scale); a capped or 16-rounded target is written the way A1111
+ # writes an explicit size (processing.py: "Hires resize" in place of "Hires upscale"), so it reproduces.
+ parts.append(f"Hires resize: {int(out_w)}x{int(out_h)}")
+ else:
+ parts.append(f"Hires upscale: {meta.get('hires_scale')}")
+ if meta.get("hires_steps"):
+ parts.append(f"Hires steps: {meta['hires_steps']}")
+ label = upscalers.model_label(meta.get("hires_upscaler"))
+ if label:
+ parts.append(f"Hires upscaler: {label}")
+ if meta.get("hires_guidance") is not None:
+ parts.append(f"Hires CFG Scale: {meta['hires_guidance']}")
+ return ", " + ", ".join(parts)
+
+
+# sd-server img_gen ``hires`` object (examples/common/common.cpp), upstream PR #1451.
+SD_CPP_HELP_MARKER = "--hires-denoising-strength"
+
+
+_sd_cpp_help_cache: dict[tuple[str, int], bool] = {}
+
+
+def sd_cpp_supports_hires(binary: Optional[str]) -> bool:
+ """Whether ``--help`` lists hires. Fails closed: an older sd-server ignores ``hires`` and renders the base pass."""
+ import os
+
+ if not binary:
+ return False
+ try:
+ key = (str(binary), int(os.stat(binary).st_mtime_ns))
+ except OSError:
+ return False
+ cached = _sd_cpp_help_cache.get(key)
+ if cached is None:
+ from core.inference.sd_cpp_backend import _sd_cpp_probe_output
+
+ text = _sd_cpp_probe_output(str(binary), "--help")
+ cached = text is not None and SD_CPP_HELP_MARKER in text
+ _sd_cpp_help_cache[key] = cached
+ return cached
+
+
+def sd_cpp_capability(
+ family: Any, *, mode: Optional[str], binary: Optional[str]
+) -> tuple[Optional[dict], Optional[str]]:
+ base = capability(family, model_rows = upscalers.native_model_upscalers(), native = True)
+ if base is None:
+ return None, None
+ if mode != "server":
+ return None, "Hires fix runs on the resident native server; this load uses one-shot sd-cli."
+ if not sd_cpp_supports_hires(binary):
+ return (
+ None,
+ "This stable-diffusion.cpp build has no Hires fix support; update the native engine.",
+ )
+ return base, None
+
+
+@dataclass(frozen = True)
+class SdCppHiresPlan:
+ params: HiresParams
+ base_width: int
+ base_height: int
+ target: tuple[int, int]
+ # Steps the Hires pass actually samples (sd.cpp derives them from the sent ``steps`` and the strength).
+ refine_steps: int
+ # The ``steps`` sent so sd.cpp samples the requested count (A1111 runs exactly ``Hires steps``); None = requested.
+ request_steps: Optional[int] = None
+
+
+def plan_sd_cpp(
+ family: Any,
+ hires: HiresParams,
+ *,
+ mode: Optional[str],
+ binary: Optional[str],
+ width: int,
+ height: int,
+ steps: int,
+) -> SdCppHiresPlan:
+ """Validate a Hires fix request for the native engine (ValueError -> 400) and size it like the diffusers engine."""
+ cap, reason = sd_cpp_capability(family, mode = mode, binary = binary)
+ if cap is None:
+ raise ValueError(
+ reason
+ or f"Hires fix is not supported for '{getattr(family, 'name', 'this')}' on the native engine."
+ )
+ params = resolve_params(hires, getattr(family, "name", None))
+ if float(params.denoise) <= 0.0:
+ raise ValueError(
+ "Upscale only (denoise 0) is not available on the native engine; set a denoise above 0."
+ )
+ if params.guidance is not None:
+ raise ValueError(
+ "A separate Hires CFG is not available on the native engine; leave it unset."
+ )
+ target = hires_target_size(
+ int(width),
+ int(height),
+ params.scale,
+ multiple = int(getattr(family, "dimension_multiple", 16) or 16),
+ max_side = min(MAX_SIDE, int(getattr(family, "max_output_side", MAX_SIDE) or MAX_SIDE)),
+ max_pixels = int(getattr(family, "max_output_pixels", 0) or 0) or None,
+ )
+ from core.inference.diffusion_conditioning import check_output_size
+
+ check_output_size(family, *target)
+ request_steps = sd_cpp_hires_request_steps(int(params.steps or steps), float(params.denoise))
+ return SdCppHiresPlan(
+ params = params,
+ base_width = int(width),
+ base_height = int(height),
+ target = target,
+ refine_steps = sd_cpp_hires_sampled_steps(request_steps, float(params.denoise)),
+ request_steps = request_steps,
+ )
+
+
+def stage_sd_cpp_upscaler(
+ upscaler_id: str,
+ scratch_dir: str,
+ *,
+ cancel: Any = None,
+) -> tuple[str, Any]:
+ """Link a model upscaler into sd-server's --hires-upscalers-dir; returns (name without extension, staged path)."""
+ import os
+ import shutil
+ from pathlib import Path
+
+ source = upscalers.resolve_model_path(upscaler_id, cancel = cancel)
+ name = (
+ "hires_"
+ + "".join(ch if ch.isalnum() else "_" for ch in upscaler_id)[:80]
+ + "_"
+ + os.urandom(3).hex()
+ )
+ dest = Path(scratch_dir) / (name + source.suffix.lower())
+ try:
+ os.symlink(source, dest)
+ except OSError:
+ try:
+ os.link(source, dest)
+ except OSError:
+ shutil.copyfile(source, dest)
+ return name, dest
+
+
+def result_block(plan: "SdCppHiresPlan") -> dict:
+ p = plan.params
+ return {
+ "scale": float(p.scale),
+ "denoise": float(p.denoise),
+ "steps": p.steps,
+ "upscaler": p.upscaler,
+ "guidance": p.guidance,
+ "base_width": plan.base_width,
+ "base_height": plan.base_height,
+ "width": plan.target[0],
+ "height": plan.target[1],
+ "refine_steps": plan.refine_steps,
+ }
+
+
+def sd_cpp_upscaler_name(upscaler_id: str, staged_name: Optional[str] = None) -> str:
+ if upscaler_id == upscalers.LATENT:
+ return "Latent (nearest-exact)"
+ if upscaler_id == upscalers.LANCZOS:
+ return "Lanczos"
+ if not staged_name:
+ raise ValueError(f"Upscaler '{upscaler_id}' was not staged for the native engine.")
+ return staged_name
+
+
+def sd_cpp_hires_sampled_steps(steps: int, denoise: float) -> int:
+ """Steps sd.cpp's Hires pass samples (and reports progress over), from make_hires_sigma_schedule in
+ src/pipeline/request.cpp: ``scheduler_steps = int(steps / strength)``, ``t_enc = int(scheduler_steps * strength)``
+ capped at ``scheduler_steps - 1``, in C ``float`` arithmetic."""
+ import numpy as np
+
+ strength = np.float32(denoise)
+ effective = max(1, int(steps))
+ scheduler_steps = max(1, int(np.float32(effective) / strength))
+ t_enc = int(np.float32(scheduler_steps) * strength)
+ if t_enc >= scheduler_steps:
+ t_enc = scheduler_steps - 1
+ return max(1, t_enc)
+
+
+def sd_cpp_hires_request_steps(steps: int, denoise: float) -> int:
+ """The ``steps`` to send so sd.cpp samples exactly ``steps`` (A1111 setup_img2img_steps: ``t_enc = requested - 1``,
+ i.e. the requested count). sd.cpp truncates twice, so 20 at 0.35 samples 19; the nearest sent count that samples
+ the request is used, else the request itself (some counts are unreachable, e.g. 20 at 0.35)."""
+ steps = max(1, int(steps))
+ for sent in range(steps, steps + 4):
+ if sd_cpp_hires_sampled_steps(sent, denoise) == steps:
+ return sent
+ return steps
+
+
+def sd_cpp_payload(
+ hires: HiresParams,
+ base_steps: int,
+ target: tuple[int, int],
+ upscaler_name: str,
+ request_steps: Optional[int] = None,
+) -> dict:
+ """``request_steps`` (plan_sd_cpp) makes sd.cpp sample the requested refine count; the size is explicit so both
+ engines match."""
+ return {
+ "enabled": True,
+ "upscaler": upscaler_name,
+ "scale": float(hires.scale),
+ "target_width": int(target[0]),
+ "target_height": int(target[1]),
+ "steps": int(request_steps or hires.steps or base_steps),
+ "denoising_strength": float(hires.denoise),
+ }
+
+
+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."""
+ import torch
+ import torch.nn.functional as F
+
+ vae = pipe.vae
+ param = next(vae.parameters())
+ device, dtype = param.device, 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
+ 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
+
+
+def _rearm_cancel(backend: Any, cancel: threading.Event) -> None:
+ """The base pass deregisters the cancel event; re-register it so Stop still lands in the refine pass."""
+ from core.inference.diffusion_families import DIFFUSION_CANCELLED_MSG
+ from utils.account_context import current_account_id
+
+ with backend._generation_cancel_lock:
+ if cancel.is_set():
+ raise RuntimeError(DIFFUSION_CANCELLED_MSG)
+ backend._active_generate_cancel = cancel
+ backend._active_generate_account = current_account_id()
+
+
+def _publish_upscale_phase(backend: Any, total_steps: int) -> None:
+ """Keep progress ACTIVE between the passes (the base pass clears it as it returns)."""
+ from core.inference.diffusion import _GenState
+ with backend._lock:
+ backend._gen = _GenState(total_steps = max(1, int(total_steps)), phase = "encode")
+
+
+def _progress_cleared_on_exit(backend: Any):
+ """Clear the between-passes phase even when no refine pass runs (upscale-only or failed upscale)."""
+ try:
+ yield
+ finally:
+ with backend._lock:
+ backend._gen = None
+
+
+def _kick_deferred_bg_compile(backend: Any) -> None:
+ state = getattr(backend, "_state", None)
+ bg = getattr(state, "bg_compile", None) if state is not None else None
+ if bg is not None:
+ try:
+ bg.kick() # idempotent; a no-op unless a compile is pending
+ except Exception as exc: # noqa: BLE001 - never mask the pass's own error
+ logger.debug("diffusion.hires: deferred compile kick failed: %s", exc)
+
+
+def _check_request(kwargs: dict) -> None:
+ for name, label in (
+ ("init_image", "a source image"),
+ ("mask_image", "a mask"),
+ ("reference_images", "reference images"),
+ ("workflow", "an explicit workflow"),
+ ("localized_edit", "a localized edit"),
+ ):
+ if kwargs.get(name):
+ raise ValueError(
+ f"Hires fix runs on text to image only; it cannot be combined with {label}."
+ )
+ if kwargs.get("upscale_model"):
+ raise ValueError("Hires fix picks its upscaler in hires.upscaler, not upscale_model.")
+ if kwargs.get("upscale") is not None and float(kwargs["upscale"]) > 1.0:
+ raise ValueError("Hires fix runs on text to image only; use either Hires fix or Upscale.")
+ controlnet = kwargs.get("controlnet")
+ if controlnet is not None and controlnet[3] not in (None, 0, 0.0):
+ raise ValueError("Hires fix cannot be combined with ControlNet yet.")
+
+
+def run_hires(
+ backend: Any, generate: Callable[..., dict], hires: HiresParams, kwargs: dict
+) -> dict:
+ """Base pass, upscale, refine pass, all inside ONE generation slot (no other render can run between them)."""
+ from core.inference.diffusion_families import DIFFUSION_CANCELLED_MSG, DIFFUSION_NOT_LOADED_MSG
+ from core.inference.diffusion_memory import (
+ ImageActivationShortfallError,
+ raise_on_image_activation_shortfall,
+ )
+ from core.inference.generation_ticket import bind_generation_cancel
+ from core.inference.diffusion_conditioning import check_output_size
+ from PIL import Image
+
+ _check_request(kwargs)
+ width = int(kwargs.get("width") or 1024)
+ height = int(kwargs.get("height") or 1024)
+ base_steps = int(kwargs.get("steps") or 9)
+ # Filled from the loaded family once the generation slot is held (a load cannot swap the model under the plan).
+ params = hires
+ refine_steps = 0
+ target = (width, height)
+ refine = False
+
+ def _plan() -> None:
+ nonlocal params, refine_steps, target, refine
+ state = getattr(backend, "_state", None)
+ if state is None:
+ raise RuntimeError(DIFFUSION_NOT_LOADED_MSG)
+ fam = state.family
+ if capability(fam) is None:
+ raise ValueError(
+ unavailable_reason(fam)
+ or f"Hires fix is not supported for the '{fam.name}' model family."
+ )
+ params = resolve_params(hires, fam.name)
+ refine_steps = int(params.steps or base_steps)
+ target = hires_target_size(
+ width,
+ height,
+ params.scale,
+ multiple = int(getattr(fam, "dimension_multiple", 16) or 16),
+ max_side = min(MAX_SIDE, int(getattr(fam, "max_output_side", MAX_SIDE) or MAX_SIDE)),
+ max_pixels = int(getattr(fam, "max_output_pixels", 0) or 0) or None,
+ )
+ check_output_size(fam, *target)
+ if upscalers.is_model_upscaler(params.upscaler) and not upscalers.spandrel_available():
+ raise ValueError(
+ "Model upscalers need the spandrel package, which is not installed. Pick Lanczos instead."
+ )
+ refine = float(params.denoise) > 0.0
+
+ def _preflight(guard_kwargs: dict) -> None:
+ if not refine:
+ return
+ try:
+ raise_on_image_activation_shortfall(
+ **{
+ **guard_kwargs,
+ "width": target[0],
+ "height": target[1],
+ "batch_size": 1,
+ "source_driven": False,
+ "condition_pixels": 0,
+ "controlnet": False,
+ }
+ )
+ except ImageActivationShortfallError as exc:
+ raise ImageActivationShortfallError(
+ f"Hires fix: the refine pass at {target[0]}x{target[1]} does not fit where the base pass at "
+ f"{width}x{height} does. {exc}"
+ ) from exc
+
+ cancel = threading.Event()
+ bind_generation_cancel(cancel)
+ t0 = time.perf_counter()
+ with (
+ backend._generation_slot(cancel),
+ _progress_cleared_on_exit(backend),
+ contextlib.ExitStack() as after_base,
+ ):
+ _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)
+ 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
+ # stopped (the last refine kicks it on success; a repeat kick is a no-op).
+ after_base.callback(_kick_deferred_bg_compile, backend)
+ t_base = time.perf_counter() - t0
+ images = list(base["images"])
+ seeds = list(base.get("seeds") or [base["seed"]] * len(images))
+ prompts = kwargs.get("prompts") or None
+ refined: list[Any] = []
+ upscale_s = 0.0
+ refine_s = 0.0
+ upscale_info: dict = {}
+ refine_negative: Optional[str] = None
+ state = getattr(backend, "_state", None)
+ keep_resident = state is not None and getattr(state, "offload_policy", "none") in (
+ None,
+ "none",
+ )
+ device = getattr(state, "device", "cpu") if state is not None else "cpu"
+ for index, image in enumerate(images):
+ if cancel.is_set():
+ raise RuntimeError(DIFFUSION_CANCELLED_MSG)
+ _rearm_cancel(backend, cancel)
+ _publish_upscale_phase(backend, refine_steps)
+ 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.
+ source = Image.new("RGB", target)
+ latent_from = image
+ elif params.upscaler == upscalers.LANCZOS:
+ source = image.convert("RGB").resize(target, Image.LANCZOS)
+ else:
+ outcome = upscalers.upscale_with_model(
+ image,
+ params.upscaler,
+ target,
+ device = device,
+ # Small (33 MB fp16): kept resident unless the load offloads.
+ keep_resident = keep_resident,
+ cancel = cancel,
+ )
+ source = outcome.image
+ upscale_info = {
+ "model_scale": outcome.model_scale,
+ "tiles": outcome.tiles,
+ "dtype": outcome.dtype,
+ "released": outcome.released,
+ }
+ upscale_s += time.perf_counter() - t_up
+ if not refine:
+ # Stop may land during the resize itself; an accepted cancel never returns an image.
+ if cancel.is_set():
+ raise RuntimeError(DIFFUSION_CANCELLED_MSG)
+ refined.append(source)
+ continue
+ t_ref = time.perf_counter()
+ pass_kwargs = dict(kwargs)
+ for drop in ("prompts", "seeds", "batch_size", "width", "height", "upscale"):
+ pass_kwargs.pop(drop, None)
+ pass_kwargs["prompt"] = (
+ prompts[index] if prompts and index < len(prompts) else kwargs.get("prompt")
+ )
+ pass_kwargs["seed"] = int(seeds[index])
+ pass_kwargs["batch_size"] = 1
+ pass_kwargs["strength"] = float(params.denoise)
+ pass_kwargs["width"], pass_kwargs["height"] = target
+ if params.guidance is not None:
+ pass_kwargs["guidance"] = float(params.guidance)
+ controls = pass_kwargs.get("sd_controls")
+ if controls is not None and getattr(controls, "variation_strength", None):
+ # A variation seed shapes the base pass's noise; the refine pass takes its noise from the source.
+ pass_kwargs["sd_controls"] = replace(
+ controls, variation_seed = None, variation_strength = None
+ )
+ pass_ctx = HiresPass(
+ cancel = cancel,
+ source = source,
+ latent_from = latent_from,
+ # Kick a deferred background compile only after the LAST refine (else the next image waits on it).
+ defer_bg_kick = index < len(images) - 1,
+ refine = True,
+ )
+ pass_ctx.stats["refine_steps"] = refine_steps
+ pass_kwargs["steps"] = refine_steps # converted to num_inference_steps inside the call
+ try:
+ from core.inference import diffusion_bg_compile
+ with diffusion_bg_compile.no_record():
+ out = generate(backend, **pass_kwargs, _hires_pass = pass_ctx)
+ except ImageActivationShortfallError as exc:
+ raise ImageActivationShortfallError(
+ f"Hires fix refine pass at {target[0]}x{target[1]}: {exc}"
+ ) from exc
+ refined.extend(out["images"])
+ refine_s += time.perf_counter() - t_ref
+ if out.get("negative_prompt") and not refine_negative:
+ refine_negative = out["negative_prompt"]
+ result = dict(base)
+ result["images"] = refined
+ if refine_negative and not result.get("negative_prompt"):
+ # Hires CFG engaged a negative the base pass's guidance left off; the recipe must still carry it.
+ result["negative_prompt"] = refine_negative
+ result["workflow"] = "txt2img"
+ result["hires"] = {
+ "scale": float(params.scale),
+ "denoise": float(params.denoise),
+ "steps": params.steps,
+ "upscaler": params.upscaler,
+ "guidance": params.guidance,
+ "base_width": width,
+ "base_height": height,
+ "width": target[0],
+ "height": target[1],
+ "refine_steps": refine_steps if refine else 0,
+ "timing": {
+ "base_s": round(t_base, 3),
+ "upscale_s": round(upscale_s, 3),
+ "refine_s": round(refine_s, 3),
+ "total_s": round(time.perf_counter() - t0, 3),
+ },
+ **({"model": upscale_info} if upscale_info else {}),
+ }
+ logger.info(
+ "diffusion.hires: %dx%d -> %dx%d via %s, denoise %.2f, %d refine steps, %d image(s), %.2fs base + %.2fs "
+ "upscale + %.2fs refine",
+ width,
+ height,
+ target[0],
+ target[1],
+ params.upscaler,
+ params.denoise,
+ refine_steps if refine else 0,
+ len(refined),
+ t_base,
+ upscale_s,
+ refine_s,
+ )
+ return result
+
+
+def with_hires(generate: Callable[..., dict]) -> Callable[..., dict]:
+ """Add a keyword-only ``hires`` to an engine's ``generate``. ``hires=None`` calls ``generate`` unchanged."""
+
+ @functools.wraps(generate)
+ def wrapper(
+ self: Any,
+ *args: Any,
+ hires: Optional[HiresParams] = None,
+ **kwargs: Any,
+ ) -> dict:
+ if hires is None:
+ return generate(self, *args, **kwargs)
+ if args:
+ raise TypeError("generate(hires=...) takes keyword arguments only")
+ return run_hires(self, generate, hires, kwargs)
+
+ sig = inspect.signature(generate)
+ params = [p for p in sig.parameters.values() if p.name != "_hires_pass"]
+ params.append(
+ inspect.Parameter(
+ "hires", inspect.Parameter.KEYWORD_ONLY, default = None, annotation = Optional[HiresParams]
+ )
+ )
+ wrapper.__signature__ = sig.replace(parameters = params) # type: ignore[attr-defined]
+ return wrapper
diff --git a/studio/backend/core/inference/diffusion_upscalers.py b/studio/backend/core/inference/diffusion_upscalers.py
new file mode 100644
index 00000000000..59ceba6fd68
--- /dev/null
+++ b/studio/backend/core/inference/diffusion_upscalers.py
@@ -0,0 +1,524 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Image upscalers for Hires fix and the Upscale workflow: Lanczos, latent, and ESRGAN-family models via spandrel.
+
+The catalog holds only redistributable weights (Real-ESRGAN, BSD-3-Clause, pinned by size and SHA-256); others
+(4x-UltraSharp is CC BY-NC-SA) stay user-supplied in ``<workspace>/upscale_models``. A request never carries a path.
+"""
+
+from __future__ import annotations
+
+import functools
+import hashlib
+import math
+import os
+import re
+import threading
+import time
+import urllib.error
+import urllib.request
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any, Callable, Iterator, Optional
+
+from loggers import get_logger
+
+logger = get_logger(__name__)
+
+LATENT = "latent"
+LANCZOS = "lanczos"
+LOCAL_PREFIX = "local:"
+# A1111 "Hires upscaler" strings (modules/shared.py latent_upscale_modes, modules/upscaler.py UpscalerLanczos).
+BUILTIN_LABELS = {LATENT: "Latent (nearest-exact)", LANCZOS: "Lanczos"}
+
+# ComfyUI ImageUpscaleWithModel tiling: 512 px tiles, 32 px overlap.
+DEFAULT_TILE = 512
+DEFAULT_OVERLAP = 32
+MIN_TILE = 64
+# ComfyUI ImageUpscaleWithModel halves the tile on an OOM and gives up below 128 px.
+OOM_MIN_TILE = 128
+
+DOWNLOAD_TIMEOUT_S = 600
+_SOCKET_TIMEOUT_S = 60
+
+
+@dataclass(frozen = True)
+class CatalogUpscaler:
+ id: str
+ label: str
+ filename: str
+ url: str
+ size: int
+ sha256: str
+ scale: int
+ license: str
+
+
+CATALOG: tuple[CatalogUpscaler, ...] = (
+ CatalogUpscaler(
+ id = "realesrgan_x4plus",
+ label = "R-ESRGAN 4x+",
+ filename = "RealESRGAN_x4plus.pth",
+ url = "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth",
+ size = 67040989,
+ sha256 = "4fa0d38905f75ac06eb49a7951b426670021be3018265fd191d2125df9d682f1",
+ scale = 4,
+ license = "BSD-3-Clause",
+ ),
+ CatalogUpscaler(
+ id = "realesrgan_x4plus_anime_6b",
+ label = "R-ESRGAN 4x+ Anime6B",
+ filename = "RealESRGAN_x4plus_anime_6B.pth",
+ url = "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.4/RealESRGAN_x4plus_anime_6B.pth",
+ size = 17938799,
+ sha256 = "f872d837d3c90ed2e05227bed711af5671a6fd1c9f7d7e91c911a61f155e99da",
+ scale = 4,
+ license = "BSD-3-Clause",
+ ),
+)
+_CATALOG_BY_ID = {entry.id: entry for entry in CATALOG}
+# Loadable without pickle by spandrel and resolvable by sd.cpp --hires-upscalers-dir.
+LOCAL_SUFFIXES = (".pth", ".pt", ".safetensors")
+_STEM_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9 _.+()\-]{0,127}$")
+
+
[email protected]_cache(maxsize = 1)
+def spandrel_available() -> bool:
+ """Cached: status polls call it, and a failed import is not cached by Python."""
+ try:
+ import spandrel # noqa: F401
+ except Exception: # noqa: BLE001 - any import failure means no model upscalers
+ return False
+ return True
+
+
+def models_dir() -> Path:
+ from utils.paths.storage_roots import account_path
+ return account_path("upscale_models")
+
+
+def _local_files() -> dict[str, Path]:
+ """Drop-in models by stem. Catalog file names are skipped (they show under their catalog id)."""
+ try:
+ root = models_dir()
+ entries = sorted(root.iterdir()) if root.is_dir() else []
+ except (OSError, ValueError):
+ return {}
+ catalog_names = {entry.filename.lower() for entry in CATALOG}
+ found: dict[str, Path] = {}
+ for path in entries:
+ if path.name.lower() in catalog_names or path.name.endswith(".part"):
+ continue
+ if path.suffix.lower() not in LOCAL_SUFFIXES or not path.is_file():
+ continue
+ if _STEM_RE.match(path.stem) and path.stem not in found:
+ found[path.stem] = path
+ return found
+
+
+def model_label(upscaler_id: Optional[str]) -> Optional[str]:
+ if upscaler_id is None:
+ return None
+ if upscaler_id in BUILTIN_LABELS:
+ return BUILTIN_LABELS[upscaler_id]
+ entry = _CATALOG_BY_ID.get(upscaler_id)
+ if entry is not None:
+ return entry.label
+ if upscaler_id.startswith(LOCAL_PREFIX):
+ return upscaler_id[len(LOCAL_PREFIX) :]
+ return upscaler_id
+
+
+def is_model_upscaler(upscaler_id: Optional[str]) -> bool:
+ return bool(upscaler_id) and upscaler_id not in BUILTIN_LABELS
+
+
+def model_upscalers() -> list[dict[str, Any]]:
+ if not spandrel_available():
+ return []
+ rows = [{"id": e.id, "label": e.label, "scale": e.scale} for e in CATALOG]
+ for stem in _local_files():
+ # The scale of a drop-in file is unknown until it loads; 4 is the common case and only labels the row.
+ rows.append({"id": LOCAL_PREFIX + stem, "label": stem, "scale": 4})
+ return rows
+
+
+def native_model_upscalers() -> list[dict[str, Any]]:
+ rows = [{"id": e.id, "label": e.label, "scale": e.scale} for e in CATALOG]
+ for stem, path in _local_files().items():
+ rows.append({"id": LOCAL_PREFIX + stem, "label": stem, "scale": 4})
+ return rows
+
+
+def check_upscaler_id(upscaler_id: str) -> None:
+ """Refuse an id that is not a built-in, a catalog entry or a well-formed drop-in name (ValueError -> 400)."""
+ if upscaler_id in BUILTIN_LABELS or upscaler_id in _CATALOG_BY_ID:
+ return
+ if upscaler_id.startswith(LOCAL_PREFIX):
+ stem = upscaler_id[len(LOCAL_PREFIX) :]
+ if _STEM_RE.match(stem) and ".." not in stem:
+ return
+ raise ValueError(
+ f"Unknown upscaler '{upscaler_id}'. Pick one the Images page lists, or drop a model file into the "
+ "upscale_models folder."
+ )
+
+
+def _offline() -> bool:
+ """Every offline switch the backend honours: HF_HUB_OFFLINE, TRANSFORMERS_OFFLINE and a force_hf_offline window."""
+ from utils.utils import hf_env_offline
+ return hf_env_offline()
+
+
+def _sha256(path: Path) -> str:
+ digest = hashlib.sha256()
+ with path.open("rb") as handle:
+ for chunk in iter(lambda: handle.read(1 << 20), b""):
+ digest.update(chunk)
+ return digest.hexdigest()
+
+
+_download_lock = threading.Lock()
+# (path, size, mtime) -> verified, so a resident file is hashed once per process.
+_verified: set[tuple[str, int, int]] = set()
+
+
+def _verified_file(path: Path, entry: CatalogUpscaler) -> bool:
+ try:
+ st = path.stat()
+ except OSError:
+ return False
+ if st.st_size != entry.size:
+ return False
+ key = (str(path), int(st.st_size), int(st.st_mtime_ns))
+ if key in _verified:
+ return True
+ if _sha256(path) != entry.sha256:
+ return False
+ _verified.add(key)
+ return True
+
+
+def _raise_cancelled() -> None:
+ """Stop raises the canonical message, which the generate route maps to its 409 cancellation."""
+ from core.inference.diffusion_families import DIFFUSION_CANCELLED_MSG
+ raise RuntimeError(DIFFUSION_CANCELLED_MSG)
+
+
+def _download(
+ entry: CatalogUpscaler,
+ dest: Path,
+ cancel: Any = None,
+) -> None:
+ part = dest.with_name(dest.name + ".part")
+ request = urllib.request.Request(entry.url, headers = {"User-Agent": "Unsloth-Studio"})
+ deadline = time.monotonic() + DOWNLOAD_TIMEOUT_S
+ digest = hashlib.sha256()
+ total = 0
+ try:
+ with (
+ urllib.request.urlopen(request, timeout = _SOCKET_TIMEOUT_S) as response,
+ part.open("wb") as handle,
+ ):
+ # read1: at most one socket read per call, so Stop and the deadline are rechecked between reads even
+ # when the server trickles bytes (read(n) waits until n bytes arrive).
+ read = getattr(response, "read1", None) or response.read
+ while True:
+ if cancel is not None and cancel.is_set():
+ _raise_cancelled()
+ if time.monotonic() > deadline:
+ raise RuntimeError(f"Timed out downloading the {entry.label} upscaler.")
+ chunk = read(1 << 16)
+ if not chunk:
+ break
+ total += len(chunk)
+ if total > entry.size:
+ raise RuntimeError(
+ f"The {entry.label} upscaler download is larger than expected."
+ )
+ digest.update(chunk)
+ handle.write(chunk)
+ if total != entry.size or digest.hexdigest() != entry.sha256:
+ raise RuntimeError(
+ f"The {entry.label} upscaler download failed its integrity check (size or SHA-256)."
+ )
+ os.replace(part, dest)
+ except (OSError, urllib.error.URLError) as exc:
+ raise RuntimeError(f"Could not download the {entry.label} upscaler: {exc}") from exc
+ finally:
+ if part.exists():
+ try:
+ part.unlink()
+ except OSError:
+ pass
+
+
+def resolve_model_path(upscaler_id: str, *, cancel: Any = None) -> Path:
+ check_upscaler_id(upscaler_id)
+ if upscaler_id in BUILTIN_LABELS:
+ raise ValueError(f"'{upscaler_id}' is not a model upscaler.")
+ entry = _CATALOG_BY_ID.get(upscaler_id)
+ if entry is None:
+ stem = upscaler_id[len(LOCAL_PREFIX) :]
+ path = _local_files().get(stem)
+ if path is None:
+ raise ValueError(f"Upscaler model '{stem}' is not in the upscale_models folder.")
+ return path
+ root = models_dir()
+ dest = root / entry.filename
+ with _download_lock:
+ if _verified_file(dest, entry):
+ return dest
+ if _offline():
+ raise ValueError(
+ f"The {entry.label} upscaler is not downloaded yet and Hugging Face offline mode is on."
+ )
+ root.mkdir(parents = True, exist_ok = True)
+ logger.info("diffusion.upscaler: downloading %s (%d bytes)", entry.filename, entry.size)
+ _download(entry, dest, cancel)
+ _verified_file(dest, entry)
+ return dest
+
+
+def tile_starts(length: int, tile: int, overlap: int) -> list[int]:
+ """Start offsets covering ``[0, length)`` with windows of ``tile`` that overlap by at least ``overlap``; the last
+ window ends exactly at ``length``. One window when ``length <= tile``."""
+ if length <= tile:
+ return [0]
+ stride = max(1, tile - overlap)
+ count = int(math.ceil((length - tile) / stride)) + 1
+ starts = [min(i * stride, length - tile) for i in range(count)]
+ out: list[int] = []
+ for s in starts:
+ if not out or s != out[-1]:
+ out.append(s)
+ return out
+
+
+def tile_boxes(width: int, height: int, tile: int, overlap: int) -> list[tuple[int, int, int, int]]:
+ tw, th = min(tile, width), min(tile, height)
+ return [
+ (x, y, x + tw, y + th)
+ for y in tile_starts(height, th, overlap)
+ for x in tile_starts(width, tw, overlap)
+ ]
+
+
+def _feather(length: int, ramp: int, at_start: bool, at_end: bool, torch: Any, device: Any) -> Any:
+ w = torch.ones(length, device = device, dtype = torch.float32)
+ ramp = min(ramp, length // 2)
+ if ramp > 0:
+ r = torch.arange(1, ramp + 1, device = device, dtype = torch.float32) / (ramp + 1)
+ if not at_start:
+ w[:ramp] = r
+ if not at_end:
+ w[-ramp:] = r.flip(0)
+ return w
+
+
+def tiled_apply(
+ image: Any,
+ fn: Callable[[Any], Any],
+ scale: int,
+ *,
+ tile: int = DEFAULT_TILE,
+ overlap: int = DEFAULT_OVERLAP,
+ cancel: Any = None,
+ output_device: Any = None,
+) -> Any:
+ """Run ``fn`` (BCHW -> BC(sH)(sW)) over overlapping tiles, blending seams linearly in float32.
+
+ The full-scale result accumulates on ``output_device`` (default: the input's device); ComfyUI's
+ ImageUpscaleWithModel keeps it on the intermediate (CPU) device the same way, so only one tile is on the GPU."""
+ import torch
+
+ _, c, h, w = image.shape
+ out_dev = image.device if output_device is None else torch.device(output_device)
+ boxes = tile_boxes(w, h, tile, overlap)
+ if len(boxes) == 1:
+ result = fn(image).float().to(out_dev)
+ if cancel is not None and cancel.is_set():
+ _raise_cancelled()
+ return result
+ out = None
+ weight = torch.zeros((1, 1, h * scale, w * scale), device = out_dev, dtype = torch.float32)
+ ramp = overlap * scale
+ for x0, y0, x1, y1 in boxes:
+ if cancel is not None and cancel.is_set():
+ _raise_cancelled()
+ piece = fn(image[:, :, y0:y1, x0:x1]).float().to(out_dev)
+ if out is None:
+ out = torch.zeros(
+ (image.shape[0], piece.shape[1], h * scale, w * scale),
+ device = out_dev,
+ dtype = torch.float32,
+ )
+ wy = _feather(piece.shape[2], ramp, y0 == 0, y1 == h, torch, out_dev)
+ wx = _feather(piece.shape[3], ramp, x0 == 0, x1 == w, torch, out_dev)
+ mask = (wy[:, None] * wx[None, :])[None, None]
+ ys, xs = y0 * scale, x0 * scale
+ out[:, :, ys : ys + piece.shape[2], xs : xs + piece.shape[3]] += piece * mask
+ weight[:, :, ys : ys + piece.shape[2], xs : xs + piece.shape[3]] += mask
+ # Stop may land while the last tile runs: never hand back a result for an accepted cancel.
+ if cancel is not None and cancel.is_set():
+ _raise_cancelled()
+ return out / weight.clamp_min(1e-8)
+
+
+_model_lock = threading.Lock()
+_resident: dict[tuple, Any] = {}
+
+
+def release_models() -> int:
+ with _model_lock:
+ count = len(_resident)
+ _resident.clear()
+ if count:
+ try:
+ import torch
+ if torch.cuda.is_available():
+ torch.cuda.empty_cache()
+ except Exception: # noqa: BLE001
+ pass
+ return count
+
+
+def _pick_dtype(descriptor: Any, device: Any) -> Any:
+ import torch
+
+ if getattr(device, "type", str(device)) != "cuda":
+ return torch.float32
+ if getattr(descriptor, "supports_half", False):
+ return torch.float16
+ if getattr(descriptor, "supports_bfloat16", False):
+ return torch.bfloat16
+ return torch.float32
+
+
+def _load(path: Path, device: Any) -> tuple[Any, Any]:
+ import torch
+ from spandrel import ImageModelDescriptor, ModelLoader
+
+ descriptor = ModelLoader(device = "cpu").load_from_file(str(path))
+ if not isinstance(descriptor, ImageModelDescriptor):
+ raise ValueError(f"'{path.name}' is not a single-image upscaler model.")
+ if int(getattr(descriptor, "input_channels", 3)) != 3:
+ raise ValueError(
+ f"'{path.name}' takes {descriptor.input_channels} channels; only RGB upscalers are supported."
+ )
+ dtype = _pick_dtype(descriptor, device)
+ descriptor.model.to(device = device, dtype = dtype)
+ descriptor.model.eval()
+ descriptor.model.requires_grad_(False)
+ return descriptor, dtype
+
+
+@dataclass
+class UpscaleOutcome:
+ image: Any
+ model_scale: int
+ tiles: int
+ dtype: str
+ seconds: float
+ released: bool
+
+
+def upscale_with_model(
+ image: Any,
+ upscaler_id: str,
+ target: tuple[int, int],
+ *,
+ device: Any,
+ keep_resident: bool = False,
+ tile: int = DEFAULT_TILE,
+ overlap: int = DEFAULT_OVERLAP,
+ cancel: Any = None,
+) -> UpscaleOutcome:
+ """Model upscale, then resize to ``target`` on the device (ComfyUI ImageUpscaleWithModel -> ImageScale)."""
+ import numpy as np
+ import torch
+ from PIL import Image
+
+ if not spandrel_available():
+ raise ValueError(
+ "Model upscalers need the spandrel package, which is not installed. Pick Lanczos instead."
+ )
+ t0 = time.perf_counter()
+ path = resolve_model_path(upscaler_id, cancel = cancel)
+ dev = torch.device(device) if not isinstance(device, torch.device) else device
+ st = path.stat()
+ # The file's size and mtime too: a drop-in overwritten in place loads again (A1111 reloads on every upscale).
+ key = (str(path), int(st.st_size), int(st.st_mtime_ns), str(dev), "auto")
+ with _model_lock:
+ cached = _resident.get(key)
+ if cached is None:
+ _resident.clear()
+ cached = _load(path, dev)
+ if keep_resident:
+ _resident[key] = cached
+ descriptor, dtype = cached
+ rgb = image.convert("RGB")
+ arr = torch.from_numpy(np.asarray(rgb, dtype = np.uint8).copy())
+ x = arr.permute(2, 0, 1).unsqueeze(0).to(device = dev, dtype = torch.float32) / 255.0
+ scale = int(descriptor.scale)
+ model = descriptor.model
+
+ def _run(piece: Any) -> Any:
+ return model(piece.to(dtype)).float()
+
+ boxes = tile_boxes(x.shape[3], x.shape[2], tile, overlap)
+ try:
+ with torch.inference_mode():
+ # A 4x model on a 2048 px source is an 8192 px float32 result (~1 GiB with its weights): keep it in
+ # host memory, so the GPU holds the model and one tile, as in ComfyUI.
+ while True:
+ try:
+ y = tiled_apply(
+ x,
+ _run,
+ scale,
+ tile = tile,
+ overlap = overlap,
+ cancel = cancel,
+ output_device = "cpu",
+ )
+ break
+ except Exception as exc: # noqa: BLE001 - only an allocator failure retries
+ from core.inference.diffusion_vae_oom import is_oom
+
+ if not is_oom(exc) or tile // 2 < OOM_MIN_TILE:
+ raise
+ tile //= 2
+ logger.info(
+ "diffusion.upscaler: out of memory, retrying with %d px tiles", tile
+ )
+ if dev.type == "cuda":
+ torch.cuda.empty_cache()
+ boxes = tile_boxes(x.shape[3], x.shape[2], tile, overlap)
+ finally:
+ if not keep_resident:
+ del model, descriptor, cached
+ _resident.pop(key, None)
+ tw, th = int(target[0]), int(target[1])
+ if (y.shape[3], y.shape[2]) != (tw, th):
+ # Resized where it accumulated (host), as ComfyUI's ImageScale after ImageUpscaleWithModel.
+ y = torch.nn.functional.interpolate(y, size = (th, tw), mode = "bicubic", antialias = True)
+ out = (y.clamp(0, 1) * 255.0).round().to(torch.uint8)[0].permute(1, 2, 0).cpu().numpy()
+ result = Image.fromarray(out, mode = "RGB")
+ del x, y
+ released = not keep_resident
+ if released and dev.type == "cuda":
+ torch.cuda.empty_cache()
+ return UpscaleOutcome(
+ image = result,
+ model_scale = scale,
+ tiles = len(boxes),
+ dtype = str(dtype).replace("torch.", ""),
+ seconds = time.perf_counter() - t0,
+ released = released,
+ )
+
+
+def iter_catalog() -> Iterator[CatalogUpscaler]:
+ return iter(CATALOG)
diff --git a/studio/backend/core/inference/image_gallery.py b/studio/backend/core/inference/image_gallery.py
index aac1f9a35bd..8327c7c3ba0 100644
--- a/studio/backend/core/inference/image_gallery.py
+++ b/studio/backend/core/inference/image_gallery.py
@@ -50,6 +50,10 @@ _IMG2IMG_WORKFLOWS = ("img2img", "inpaint", "outpaint", "edit", "upscale")
def _params_text(meta: dict[str, Any]) -> str:
"""Automatic1111-style ``parameters`` string for cross-tool interop."""
+ from core.inference.diffusion_hires import infotext_fields as hires_infotext, infotext_meta
+
+ # A Hires fix image is written the way A1111 writes one: Size is the base pass, Hires upscale the factor.
+ meta = infotext_meta(meta)
# The caption the model encoded (FLUX.3 prompt upsampler): other tools reproduce the image from this line. The
# typed prompt stays in the Unsloth chunk.
lines = [str(meta.get("enhanced_prompt") or meta.get("prompt", ""))]
@@ -95,6 +99,7 @@ def _params_text(meta: dict[str, Any]) -> str:
fields += ", Inpaint area: Only masked"
if meta.get("inpaint_padding") is not None:
fields += f", Masked area padding: {meta['inpaint_padding']}"
+ fields += hires_infotext(meta)
# Static flow shift, read back by the paste parser; base / max shift stay in the recipe chunk only.
if meta.get("shift") is not None:
fields += f", Shift: {meta['shift']}"
diff --git a/studio/backend/core/inference/mlx_diffusion_backend.py b/studio/backend/core/inference/mlx_diffusion_backend.py
index 3c08cc02849..0812e11aac2 100644
--- a/studio/backend/core/inference/mlx_diffusion_backend.py
+++ b/studio/backend/core/inference/mlx_diffusion_backend.py
@@ -998,7 +998,11 @@ class MlxDiffusionBackend:
controlnet: Optional[tuple[str, str, str, float, float, float]] = None,
expected_load: Optional[LoadIdentity] = None,
allow_oversized: bool = False,
+ # Interface parity with the other engines; status advertises no Hires fix here, so a request is refused.
+ hires: Any = None,
) -> dict[str, Any]:
+ if hires is not None:
+ raise ValueError("Hires fix is not available on the MLX engine.")
if (
init_image is not None
or mask_image is not None
diff --git a/studio/backend/core/inference/sd_cpp_args.py b/studio/backend/core/inference/sd_cpp_args.py
index 5d40be2cfd1..fc82db8f9c9 100644
--- a/studio/backend/core/inference/sd_cpp_args.py
+++ b/studio/backend/core/inference/sd_cpp_args.py
@@ -959,6 +959,7 @@ def build_img_gen_request(
ref_images: Optional[list[str]] = None,
qwen_image_layers: Optional[int] = None,
custom_sigmas: Optional[list[float]] = None,
+ hires: Optional[dict] = None,
) -> dict:
"""Build the ``POST /sdcpp/v1/img_gen`` JSON body for one text-to-image request.
@@ -1009,6 +1010,8 @@ def build_img_gen_request(
req["ref_images"] = list(ref_images)
if qwen_image_layers is not None:
req["qwen_image_layers"] = int(qwen_image_layers)
+ if hires:
+ req["hires"] = dict(hires)
return req
diff --git a/studio/backend/core/inference/sd_cpp_backend.py b/studio/backend/core/inference/sd_cpp_backend.py
index db43e62af89..68dda79edaa 100644
--- a/studio/backend/core/inference/sd_cpp_backend.py
+++ b/studio/backend/core/inference/sd_cpp_backend.py
@@ -2744,6 +2744,10 @@ class _SdGen:
step: int = 0
first_step_at: float = 0.0
eta_seconds: Optional[float] = None
+ # Per sampling pass denominators (Hires fix: base, refine); empty = one pass of ``total_steps``.
+ passes: tuple[int, ...] = ()
+ pass_index: int = 0
+ pass_offset: int = 0
def _estimate_eta(total_steps: int, step: int, first_step_at: float, now: float) -> Optional[float]:
@@ -4364,6 +4368,7 @@ class SdCppDiffusionBackend:
expected_load: Optional[LoadIdentity] = None,
# Interface parity only: the activation guard is diffusers-only.
allow_oversized: bool = False,
+ hires: Any = None,
) -> dict[str, Any]:
import tempfile
@@ -4508,6 +4513,24 @@ class SdCppDiffusionBackend:
else:
from core.inference.diffusion_conditioning import check_output_size
check_output_size(state.family, int(width), int(height))
+ hires_plan = None
+ if hires is not None:
+ from core.inference import diffusion_hires
+
+ if conditioned:
+ raise ValueError("Hires fix runs on text to image only.")
+ hires_plan = diffusion_hires.plan_sd_cpp(
+ state.family,
+ hires,
+ mode = state.mode,
+ binary = getattr(state.server, "binary", None),
+ width = int(width),
+ height = int(height),
+ steps = int(steps),
+ )
+ # sd.cpp samples the base and Hires schedules separately, each reporting its own denominator.
+ passes = (int(steps), int(hires_plan.refine_steps))
+ self._gen = _SdGen(total_steps = sum(passes), passes = passes)
if seed is None:
seed = int.from_bytes(os.urandom(6), "big") & ((1 << 53) - 1)
else:
@@ -4553,6 +4576,7 @@ class SdCppDiffusionBackend:
cancel = cancel,
ref_pngs = ref_pngs,
layers = _layer_count(state.family) or None,
+ hires_plan = hires_plan,
)
else:
images, seeds = self._generate_oneshot(
@@ -4626,6 +4650,8 @@ class SdCppDiffusionBackend:
if conditioned
else None,
}
+ if hires_plan is not None:
+ result["hires"] = diffusion_hires.result_block(hires_plan)
logger.info(
"diffusion.generated: %s",
format_generation_for_log(
@@ -4663,6 +4689,7 @@ class SdCppDiffusionBackend:
cancel: threading.Event,
ref_pngs: Optional[list[bytes]] = None,
layers: Optional[int] = None,
+ hires_plan: Any = None,
) -> tuple[list, list[int]]:
"""Generate via the resident sd-server (no model reload).
@@ -4712,7 +4739,36 @@ class SdCppDiffusionBackend:
# images per job, so each chunk gets whatever is left rather than its own full budget and a long batch still
# ends on time.
deadline = time.monotonic() + NATIVE_GENERATION_TIMEOUT_S
+ hires_payload: Optional[dict] = None
+ hires_staged: list[Path] = []
+
+ def _stage_hires(server: Any) -> Optional[dict]:
+ """The ``hires`` block, with a model upscaler staged into THIS server's upscaler dir."""
+ if hires_plan is None:
+ return None
+ from core.inference import diffusion_hires, diffusion_upscalers
+
+ upscaler_id = hires_plan.params.upscaler
+ staged_name = None
+ if diffusion_upscalers.is_model_upscaler(upscaler_id):
+ if not server.lora_dir:
+ raise ValueError(
+ "The native server has no upscaler directory for a model upscaler."
+ )
+ staged_name, staged = diffusion_hires.stage_sd_cpp_upscaler(
+ upscaler_id, server.lora_dir, cancel = cancel
+ )
+ hires_staged.append(staged)
+ return diffusion_hires.sd_cpp_payload(
+ hires_plan.params,
+ int(steps),
+ hires_plan.target,
+ diffusion_hires.sd_cpp_upscaler_name(upscaler_id, staged_name),
+ request_steps = hires_plan.request_steps,
+ )
+
try:
+ hires_payload = _stage_hires(state.server)
for offset in range(0, total, _MAX_SERVER_BATCH):
if cancel.is_set():
raise SdCppCancelled("sd-server generation was cancelled.")
@@ -4741,6 +4797,7 @@ class SdCppDiffusionBackend:
for b in ref_pngs or []
],
qwen_image_layers = layers,
+ hires = hires_payload,
)
try:
blobs = state.server.img_gen(
@@ -4759,6 +4816,10 @@ class SdCppDiffusionBackend:
with self._lock:
if self._state is not None and self._state.server is not None:
self._state = state
+ if hires_plan is not None:
+ # The replacement server has its own scratch dir: stage the upscaler there again.
+ hires_payload = _stage_hires(server)
+ payload["hires"] = dict(hires_payload)
blobs = server.img_gen(
payload,
on_step = self._on_log,
@@ -4783,6 +4844,11 @@ class SdCppDiffusionBackend:
finally:
if lora_stage is not None:
shutil.rmtree(lora_stage, ignore_errors = True)
+ for staged in hires_staged:
+ try:
+ staged.unlink()
+ except OSError:
+ pass
return images, seeds
def _restart_server_on_cpu_backend(
@@ -4973,12 +5039,30 @@ class SdCppDiffusionBackend:
if gen is None or gen.total_steps <= 0:
return
for a, b in _STEP_RE.findall(line):
- if int(b) == gen.total_steps:
- now = time.time()
- gen.step = min(int(a), gen.total_steps)
- if gen.first_step_at == 0.0:
- gen.first_step_at = now
- gen.eta_seconds = _estimate_eta(gen.total_steps, gen.step, gen.first_step_at, now)
+ a, b = int(a), int(b)
+ if gen.passes:
+ i = gen.pass_index
+ nxt = (i + 1) % len(gen.passes)
+ # The next pass (the next image's base pass after the last one) starts once this one completed; a
+ # repeat of this pass's last line is not a start.
+ if (
+ nxt != i
+ and b == gen.passes[nxt]
+ and gen.step >= gen.pass_offset + gen.passes[i]
+ and (b != gen.passes[i] or a < b)
+ ):
+ gen.pass_offset = gen.pass_offset + gen.passes[i] if nxt else 0
+ gen.pass_index = i = nxt
+ if b != gen.passes[i]:
+ continue
+ a += gen.pass_offset
+ elif b != gen.total_steps:
+ continue
+ now = time.time()
+ gen.step = min(a, gen.total_steps)
+ if gen.first_step_at == 0.0:
+ gen.first_step_at = now
+ gen.eta_seconds = _estimate_eta(gen.total_steps, gen.step, gen.first_step_at, now)
def generate_progress(self) -> dict[str, Any]:
gen = self._gen
@@ -5191,9 +5275,25 @@ class SdCppDiffusionBackend:
# txt2img always; reference and edit only where this build and its loaded assets run them.
"workflows": workflows,
"conditioning": conditioning,
+ **_native_hires_status(state),
}
+def _native_hires_status(state: Any) -> dict[str, Any]:
+ try:
+ from core.inference import diffusion_hires
+ hires, reason = diffusion_hires.sd_cpp_capability(
+ state.family,
+ mode = state.mode,
+ binary = getattr(getattr(state, "server", None), "binary", None),
+ )
+ except Exception as exc: # noqa: BLE001 - a broken probe hides the control, never the status
+ logger.debug("sd_cpp.hires: capability probe failed: %s", exc)
+ hires, reason = None, None
+ # No img2img on this engine, so the Upscale workflow (and its model upscalers) is not offered.
+ return {"hires": hires, "hires_unavailable_reason": reason, "upscale_models": []}
+
+
def _install_allowed() -> bool:
"""Whether lazy binary install is permitted (UNSLOTH_DIFFUSION_SD_CPP_INSTALL)."""
val = os.environ.get("UNSLOTH_DIFFUSION_SD_CPP_INSTALL", "auto").strip().lower()
diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.py
index 64b930e951b..8a0563275af 100644
--- a/studio/backend/models/inference.py
+++ b/studio/backend/models/inference.py
@@ -4889,6 +4889,38 @@ class DiffusionLoadRequest(BaseModel):
return self
+class HiresSpec(BaseModel):
+ """Hires fix: render, upscale, then refine with img2img at ``denoise`` (txt2img only).
+
+ ``steps`` is the exact refine count; None = the base pass's steps."""
+
+ scale: float = Field(1.5, ge = 1.0, le = 4.0, description = "Upscale factor (A1111 'Hires upscale')")
+ denoise: float = Field(
+ 0.5,
+ ge = 0.0,
+ le = 1.0,
+ description = "Refine-pass denoising strength (A1111 'Denoising strength'); 0 = upscale only",
+ )
+ steps: Optional[int] = Field(
+ None,
+ ge = 1,
+ le = 100,
+ description = "Exact refine-pass steps (A1111 'Hires steps'); omitted = the base pass's steps",
+ )
+ upscaler: Optional[str] = Field(
+ None,
+ max_length = 160,
+ description = "Upscaler id from status `hires.upscalers` (latent | lanczos | a model id); omitted = "
+ "status `hires.default_upscaler`",
+ )
+ guidance: Optional[float] = Field(
+ None,
+ ge = 0.0,
+ le = 20.0,
+ description = "Refine-pass guidance (Forge 'Hires CFG Scale'); omitted = guidance",
+ )
+
+
class LoraSpec(BaseModel):
"""One LoRA adapter to apply for a generation, referenced by its discovery id.
@@ -5233,6 +5265,17 @@ class DiffusionGenerateRequest(BaseModel):
le = 256,
description = "Padding (px) around the mask when `inpaint_only_masked` is set; omitted = 32.",
)
+ hires: Optional[HiresSpec] = Field(
+ None,
+ description = "Hires fix for text to image: upscale the render and refine it in the same request. "
+ "Requires status `hires` to be non-null; omitted = off.",
+ )
+ upscale_model: Optional[str] = Field(
+ None,
+ max_length = 160,
+ description = "Upscale workflow only: a model upscaler id from status `upscale_models` used in place of "
+ "the Lanczos resize. Omitted = Lanczos.",
+ )
provider_id: Optional[str] = Field(
None,
description = "[x-unsloth] Saved connection ID. When set, the prompt goes to that "
@@ -5409,6 +5452,22 @@ class GalleryImage(BaseModel):
None, description = "img2img/inpaint denoise strength, when the workflow used one"
)
upscale: Optional[float] = Field(None, description = "Upscale factor, for the upscale workflow")
+ upscale_model: Optional[str] = Field(
+ None, description = "Model upscaler id the upscale workflow used; null = Lanczos"
+ )
+ hires_scale: Optional[float] = Field(
+ None, description = "Hires fix upscale factor; null = no Hires fix"
+ )
+ hires_denoise: Optional[float] = Field(None, description = "Hires fix refine denoising strength")
+ hires_steps: Optional[int] = Field(
+ None, description = "Hires fix refine steps as requested; null = the base pass's steps"
+ )
+ hires_upscaler: Optional[str] = Field(None, description = "Hires fix upscaler id")
+ hires_guidance: Optional[float] = Field(
+ None, description = "Hires fix refine guidance; null = the base guidance"
+ )
+ hires_base_width: Optional[int] = Field(None, description = "Hires fix base-pass width")
+ hires_base_height: Optional[int] = Field(None, description = "Hires fix base-pass height")
controlnet_guidance: Optional[str] = Field(
None, description = "ControlNet guidance interval, formatted as 'start:end'"
)
@@ -5965,6 +6024,19 @@ class DiffusionStatusResponse(BaseModel):
"loaded value or null when resolution-dependent) or {node: 'flux', base_shift, max_shift} "
"(ComfyUI ModelSamplingFlux defaults). Diffusers engine only.",
)
+ hires: Optional[Dict[str, Any]] = Field(
+ None,
+ description = "The Hires fix control the loaded model takes, or null to hide it: {upscalers: [{id, label, "
+ "kind}], default_upscaler, defaults: {scale, denoise}, max_side}.",
+ )
+ hires_unavailable_reason: Optional[str] = Field(
+ None,
+ description = "Why Hires fix is hidden for the loaded model, when there is a reason worth showing",
+ )
+ upscale_models: list[Dict[str, Any]] = Field(
+ default_factory = list,
+ description = "Model upscalers ({id, label, scale}) the Upscale workflow can use; empty = Lanczos only.",
+ )
textual_inversion: Optional[str] = Field(
None,
description = "Textual-inversion embedding format the loaded model takes ('sdxl'), or null when "
diff --git a/studio/backend/requirements/extras-no-deps.txt b/studio/backend/requirements/extras-no-deps.txt
index 9cfe8645710..cbd68b3d21a 100644
--- a/studio/backend/requirements/extras-no-deps.txt
+++ b/studio/backend/requirements/extras-no-deps.txt
@@ -46,3 +46,6 @@ kernels==0.12.3
# kernels<3.11 imports tomli as its tomllib fallback; --no-deps skips its own
# marker dep, so list it here (no-op on the 3.12/3.13 default installs).
tomli==2.4.1; python_version < "3.11"
+# Model upscalers (ESRGAN family) for Images Hires fix / Upscale, as ComfyUI and InvokeAI load them. MIT, pure
+# Python; its deps (torch, torchvision, safetensors, numpy, einops, typing_extensions) are already installed.
+spandrel==0.4.2
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index a523da9a57e..65d5c291f78 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -52264,6 +52264,34 @@ def _inpaint_mask_kwargs(generate: Any, request: Any) -> dict:
return out
+def _hires_kwargs(generate: Any, request: Any) -> dict:
+ """Only the set Hires fix / upscaler kwargs; an engine that takes neither refuses (ValueError -> 400)."""
+ try:
+ import inspect
+ params = inspect.signature(generate).parameters
+ except (TypeError, ValueError):
+ params = {}
+ out: dict = {}
+ hires = getattr(request, "hires", None)
+ if hires is not None:
+ if "hires" not in params:
+ raise ValueError("Hires fix is not available on this image engine.")
+ from core.inference.diffusion_hires import HiresParams
+ out["hires"] = HiresParams(
+ scale = float(hires.scale),
+ denoise = float(hires.denoise),
+ steps = hires.steps,
+ upscaler = hires.upscaler,
+ guidance = hires.guidance,
+ )
+ upscale_model = getattr(request, "upscale_model", None)
+ if upscale_model:
+ if "upscale_model" not in params:
+ raise ValueError("Model upscalers are not available on this image engine.")
+ out["upscale_model"] = upscale_model
+ return out
+
+
# Count of finished generations still writing their PNG/gallery records; generate-progress reports active while above 0. Mutated only on the event loop, so no lock.
_diffusion_persist_active = 0
@@ -52373,6 +52401,8 @@ async def _external_image_generation(
or body.mask_blur is not None
or body.inpaint_only_masked is not None
or body.inpaint_padding is not None
+ or body.hires is not None
+ or body.upscale_model
):
raise HTTPException(
status_code = 400,
@@ -52595,6 +52625,7 @@ async def _generate_diffusion_image_run(
) -> DiffusionGenerateResponse:
from core.inference import image_gallery
from core.inference.diffusion_engine_router import get_active_diffusion_engine
+ from core.inference.diffusion_hires import record_fields as hires_record_fields
from core.inference.diffusion_families import (
DIFFUSION_CANCELLED_MSG,
DIFFUSION_NOT_LOADED_MSG,
@@ -52715,6 +52746,7 @@ async def _generate_diffusion_image_run(
**_sd_controls_kwargs(backend.generate, request),
**_shift_kwargs(backend.generate, request),
**_inpaint_mask_kwargs(backend.generate, request),
+ **_hires_kwargs(backend.generate, request),
)
break
except ImageActivationShortfallError as exc:
@@ -52821,6 +52853,8 @@ async def _generate_diffusion_image_run(
),
"strength": request.strength,
"upscale": request.upscale,
+ "upscale_model": result.get("upscale_model"),
+ **hires_record_fields(result.get("hires")),
"controlnet_guidance": (
f"{request.controlnet.guidance_start:g}:{request.controlnet.guidance_end:g}"
if request.controlnet and request.controlnet.strength > 0
diff --git a/studio/backend/tests/test_diffusion_hires.py b/studio/backend/tests/test_diffusion_hires.py
new file mode 100644
index 00000000000..d3f591229ea
--- /dev/null
+++ b/studio/backend/tests/test_diffusion_hires.py
@@ -0,0 +1,1329 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Hires fix and model upscalers."""
+
+from __future__ import annotations
+
+import inspect
+import re
+import types
+
+import pytest
+
+from core.inference import diffusion_hires as hires
+from core.inference import diffusion_upscalers as ups
+from core.inference.diffusion_families import _FAMILIES
+
+
+def _fam(name):
+ return next(f for f in _FAMILIES if f.name == name)
+
+
+def test_request_defaults_follow_the_comfyui_two_pass_example():
+ from models.inference import DiffusionGenerateRequest, HiresSpec
+
+ spec = HiresSpec()
+ assert (spec.scale, spec.denoise, spec.steps, spec.upscaler, spec.guidance) == (
+ 1.5,
+ 0.5,
+ None,
+ None,
+ None,
+ )
+ req = DiffusionGenerateRequest(prompt = "p", hires = {"scale": 2})
+ assert req.hires.scale == 2 and req.hires.denoise == 0.5
+ assert DiffusionGenerateRequest(prompt = "p").hires is None
+
+
+ "bad",
+ [
+ {"scale": 0.9},
+ {"scale": 4.5},
+ {"denoise": -0.1},
+ {"denoise": 1.1},
+ {"steps": 0},
+ {"steps": 101},
+ ],
+)
+def test_request_bounds(bad):
+ from pydantic import ValidationError
+
+ from models.inference import DiffusionGenerateRequest
+ with pytest.raises(ValidationError):
+ DiffusionGenerateRequest(prompt = "p", hires = bad)
+
+
+def test_route_refuses_hires_on_an_engine_without_it():
+ from models.inference import DiffusionGenerateRequest
+ from routes.inference import _hires_kwargs
+
+ def no_hires(*, prompt):
+ return None
+
+ def with_hires(
+ *,
+ prompt,
+ upscale_model = None,
+ hires = None,
+ ):
+ return None
+
+ req = DiffusionGenerateRequest(prompt = "p", hires = {"scale": 1.5, "upscaler": "lanczos"})
+ with pytest.raises(ValueError, match = "Hires fix is not available"):
+ _hires_kwargs(no_hires, req)
+ out = _hires_kwargs(with_hires, req)
+ assert out["hires"] == hires.HiresParams(scale = 1.5, denoise = 0.5, upscaler = "lanczos")
+ assert _hires_kwargs(no_hires, DiffusionGenerateRequest(prompt = "p")) == {}
+ with pytest.raises(ValueError, match = "Model upscalers are not available"):
+ _hires_kwargs(
+ no_hires, DiffusionGenerateRequest(prompt = "p", upscale_model = "realesrgan_x4plus")
+ )
+
+
+def test_engine_signature_advertises_hires_but_not_the_private_pass():
+ from core.inference.diffusion import DiffusionBackend
+ from core.inference.sd_cpp_backend import SdCppDiffusionBackend
+
+ params = inspect.signature(DiffusionBackend.generate).parameters
+ assert "hires" in params and "upscale_model" in params and "_hires_pass" not in params
+ assert "hires" in inspect.signature(SdCppDiffusionBackend.generate).parameters
+
+
+def test_hires_refuses_conditioned_requests():
+ for kwargs in (
+ {"init_image": "x"},
+ {"mask_image": "x"},
+ {"reference_images": ["x"]},
+ {"workflow": "edit"},
+ {"upscale": 2.0},
+ {"upscale_model": "realesrgan_x4plus"},
+ {"controlnet": ("id", "img", "canny", 1.0, 0.0, 1.0)},
+ ):
+ with pytest.raises(ValueError):
+ hires._check_request({"prompt": "p", **kwargs})
+ hires._check_request({"prompt": "p", "controlnet": ("id", "img", "canny", 0.0, 0.0, 1.0)})
+
+
[email protected]("rule", [hires.RULE_FLOOR, hires.RULE_FLOW])
[email protected]("steps", [1, 4, 9, 14, 20, 28, 50])
[email protected]("denoise", [0.05, 0.2, 0.3, 0.35, 0.5, 0.55, 0.7, 0.9, 1.0])
+def test_refine_runs_exactly_the_requested_steps(rule, steps, denoise):
+ n = hires.refine_inference_steps(steps, denoise, rule)
+ assert hires.steps_run(n, denoise, rule) == steps
+
+
+def test_denoise_below_the_a1111_comfyui_step_is_refused():
+ # A1111 "Denoising strength" and ComfyUI KSampler denoise step by 0.01; below it steps / denoise is unbounded.
+ for bad in (0.00001, 1e-300, 0.009):
+ with pytest.raises(ValueError, match = "at least 0.01"):
+ hires.resolve_params(hires.HiresParams(denoise = bad, upscaler = "lanczos"), "flux.1")
+ assert hires.resolve_params(hires.HiresParams(denoise = 0.0, upscaler = "lanczos"), "flux.1")
+ for rule in (hires.RULE_FLOOR, hires.RULE_FLOW):
+ n = hires.refine_inference_steps(100, hires.MIN_DENOISE, rule)
+ assert n <= 10004 and hires.steps_run(n, hires.MIN_DENOISE, rule) == 100
+
+
+def test_upscaler_stop_raises_the_canonical_cancellation():
+ import threading
+
+ import torch
+
+ from core.inference.diffusion_families import DIFFUSION_CANCELLED_MSG
+
+ cancel = threading.Event()
+ cancel.set()
+ with pytest.raises(RuntimeError) as exc:
+ ups.tiled_apply(
+ torch.zeros(1, 3, 64, 64), lambda x: x, 1, tile = 32, overlap = 8, cancel = cancel
+ )
+ assert str(exc.value) == DIFFUSION_CANCELLED_MSG
+
+
+def test_comfyui_example_numbers():
+ # hiresfix_latent_workflow.png: 768 -> 1152, KSampler 14 steps at denoise 0.5 (28-step schedule, last 14).
+ assert hires.hires_target_size(768, 768, 1.5) == (1152, 1152)
+ assert hires.refine_inference_steps(14, 0.5, hires.RULE_FLOOR) == 28
+ assert hires.refine_inference_steps(14, 0.5, hires.RULE_FLOW) == 28
+
+
+def test_target_size_rounds_to_16_and_caps_the_longest_side():
+ assert hires.hires_target_size(832, 1216, 1.5) == (1248, 1824)
+ assert hires.hires_target_size(832, 1216, 2.0) == (1408, 2048)
+ assert hires.hires_target_size(1024, 1024, 4.0) == (2048, 2048)
+ w, h = hires.hires_target_size(1024, 1024, 4.0, max_pixels = 2048 * 1536)
+ assert w * h <= 2048 * 1536 and w % 16 == 0 and h % 16 == 0
+
+
+def test_timestep_rule_reads_each_pipelines_rounding():
+ diffusers = pytest.importorskip("diffusers")
+ assert (
+ hires.timestep_rule(
+ diffusers.StableDiffusionXLImg2ImgPipeline.__new__(
+ diffusers.StableDiffusionXLImg2ImgPipeline
+ )
+ )
+ == hires.RULE_FLOOR
+ )
+ for name in ("FluxImg2ImgPipeline", "QwenImageImg2ImgPipeline", "ZImageImg2ImgPipeline"):
+ cls = getattr(diffusers, name)
+ assert hires.timestep_rule(cls.__new__(cls)) == hires.RULE_FLOW, name
+
+
+def test_capability_only_where_the_family_has_img2img():
+ sdxl = hires.capability(_fam("sdxl"))
+ assert sdxl["default_upscaler"] == "latent" and sdxl["defaults"] == {
+ "scale": 1.5,
+ "denoise": 0.5,
+ }
+ assert [u["id"] for u in sdxl["upscalers"]][:2] == ["latent", "lanczos"]
+ for name in ("flux.1", "qwen-image", "z-image"):
+ cap = hires.capability(_fam(name))
+ assert cap["default_upscaler"] == "lanczos", name
+ assert "latent" not in [u["id"] for u in cap["upscalers"]], name
+ for name in ("krea-2", "lumina-2", "flux.2-dev", "hidream-i1"):
+ assert hires.capability(_fam(name)) is None, name
+ assert "image-to-image" in hires.unavailable_reason(_fam(name))
+ assert hires.capability(_fam("qwen-image-edit")) is None
+ assert hires.unavailable_reason(_fam("qwen-image-edit")) is None
+
+
+def test_model_rows_join_the_upscaler_list():
+ cap = hires.capability(
+ _fam("flux.1"), model_rows = [{"id": "realesrgan_x4plus", "label": "R-ESRGAN 4x+"}]
+ )
+ assert cap["upscalers"][-1] == {
+ "id": "realesrgan_x4plus",
+ "label": "R-ESRGAN 4x+",
+ "kind": "model",
+ }
+
+
+def test_resolve_params_refuses_latent_off_sdxl_and_unknown_ids():
+ assert hires.resolve_params(hires.HiresParams(), "sdxl").upscaler == "latent"
+ assert hires.resolve_params(hires.HiresParams(), "flux.1").upscaler == "lanczos"
+ with pytest.raises(ValueError, match = "SDXL only"):
+ hires.resolve_params(hires.HiresParams(upscaler = "latent"), "flux.1")
+ with pytest.raises(ValueError, match = "needs a refine pass"):
+ hires.resolve_params(hires.HiresParams(upscaler = "latent", denoise = 0.0), "sdxl")
+ with pytest.raises(ValueError, match = "Unknown upscaler"):
+ hires.resolve_params(hires.HiresParams(upscaler = "../../etc/passwd"), "sdxl")
+
+
+ "bad", ["local:../x", "local:a/b", "local:", "/abs/path.pth", "local:..", "nope"]
+)
+def test_upscaler_ids_never_name_a_path(bad):
+ with pytest.raises(ValueError):
+ ups.check_upscaler_id(bad)
+
+
+def test_local_drop_in_resolves_only_inside_the_folder(tmp_path, monkeypatch):
+ monkeypatch.setattr(ups, "models_dir", lambda: tmp_path)
+ (tmp_path / "4x_Remacri.pth").write_bytes(b"x")
+ (tmp_path / "notes.txt").write_text("x")
+ (tmp_path / "RealESRGAN_x4plus.pth").write_bytes(
+ b"x"
+ ) # a catalog file shows under its catalog id
+ assert set(ups._local_files()) == {"4x_Remacri"}
+ assert ups.resolve_model_path("local:4x_Remacri") == tmp_path / "4x_Remacri.pth"
+ with pytest.raises(ValueError, match = "not in the upscale_models folder"):
+ ups.resolve_model_path("local:missing")
+
+
+def test_catalog_download_is_verified(tmp_path, monkeypatch):
+ monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)
+ monkeypatch.setattr(ups, "models_dir", lambda: tmp_path)
+ entry = ups.CATALOG[1]
+ payload = b"not the weights"
+
+ class _Resp:
+ def __init__(self):
+ self.chunks = [payload, b""]
+
+ def read(self, n):
+ return self.chunks.pop(0)
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *a):
+ return False
+
+ monkeypatch.setattr(ups.urllib.request, "urlopen", lambda *a, **k: _Resp())
+ with pytest.raises(RuntimeError, match = "integrity check"):
+ ups.resolve_model_path(entry.id)
+ assert not any(tmp_path.iterdir()) # no partial file is left behind
+ import threading
+
+ from core.inference.diffusion_families import DIFFUSION_CANCELLED_MSG
+
+ stop = threading.Event()
+ stop.set()
+ with pytest.raises(RuntimeError) as exc:
+ ups.resolve_model_path(entry.id, cancel = stop)
+ assert str(exc.value) == DIFFUSION_CANCELLED_MSG
+ assert not any(tmp_path.iterdir())
+ monkeypatch.setenv("HF_HUB_OFFLINE", "1")
+ with pytest.raises(ValueError, match = "offline"):
+ ups.resolve_model_path(entry.id)
+
+
+def test_catalog_entries_are_pinned():
+ for entry in ups.CATALOG:
+ assert entry.license == "BSD-3-Clause"
+ assert entry.url.startswith("https://github.com/xinntao/Real-ESRGAN/releases/download/")
+ assert re.fullmatch(r"[0-9a-f]{64}", entry.sha256) and entry.size > 1_000_000
+
+
+def _a1111_fields(line):
+ # modules/infotext_utils.py re_param
+ re_param = re.compile(r'\s*(\w[\w \-/]+):\s*("(?:\\.|[^\\"])+"|[^,]*)(?:,|$)')
+ return {k: v.strip() for k, v in re_param.findall(line)}
+
+
+def test_infotext_writes_a1111_hires_keys_and_the_base_size():
+ from core.inference import image_gallery
+
+ meta = {
+ "prompt": "a castle",
+ "steps": 28,
+ "guidance": 7.0,
+ "seed": 1,
+ "width": 1248,
+ "height": 1824,
+ "model": "m",
+ "workflow": "txt2img",
+ **hires.record_fields(
+ {
+ "scale": 1.5,
+ "denoise": 0.5,
+ "steps": 14,
+ "upscaler": "latent",
+ "guidance": None,
+ "base_width": 832,
+ "base_height": 1216,
+ }
+ ),
+ }
+ text = image_gallery._params_text(meta)
+ fields = _a1111_fields(text.splitlines()[-1])
+ assert fields["Size"] == "832x1216"
+ assert fields["Denoising strength"] == "0.5"
+ assert fields["Hires upscale"] == "1.5"
+ assert fields["Hires steps"] == "14"
+ assert fields["Hires upscaler"] == "Latent (nearest-exact)"
+ assert "Hires CFG Scale" not in fields
+ assert "Hires resize" not in fields
+ assert meta["width"] == 1248
+
+
+def test_infotext_writes_a_capped_target_as_a1111_hires_resize():
+ from core.inference import image_gallery
+
+ # 1536x1024 at 2x is capped to 2048 px: the factor alone would describe 3072x2048.
+ target = hires.hires_target_size(1536, 1024, 2.0)
+ assert target == (2048, 1360)
+ meta = {
+ "prompt": "p",
+ "steps": 20,
+ "seed": 1,
+ "width": target[0],
+ "height": target[1],
+ "model": "m",
+ "workflow": "txt2img",
+ **hires.record_fields(
+ {
+ "scale": 2.0,
+ "denoise": 0.5,
+ "upscaler": "lanczos",
+ "base_width": 1536,
+ "base_height": 1024,
+ }
+ ),
+ }
+ fields = _a1111_fields(image_gallery._params_text(meta).splitlines()[-1])
+ assert fields["Size"] == "1536x1024"
+ assert fields["Hires resize"] == "2048x1360"
+ assert "Hires upscale" not in fields
+
+
+def test_infotext_omits_hires_steps_when_same_and_names_models_like_a1111():
+ meta = {
+ "hires_scale": 2.0,
+ "hires_denoise": 0.3,
+ "hires_steps": None,
+ "hires_upscaler": "realesrgan_x4plus",
+ "hires_guidance": 4.0,
+ }
+ text = hires.infotext_fields(meta)
+ assert "Hires steps" not in text
+ assert "Hires upscaler: R-ESRGAN 4x+" in text
+ assert "Hires CFG Scale: 4.0" in text
+ assert hires.infotext_fields({"hires_scale": None}) == ""
+ assert ups.model_label("local:4x_foolhardy_Remacri") == "4x_foolhardy_Remacri"
+
+
+def test_gallery_round_trips_hires_fields(tmp_path, monkeypatch):
+ from PIL import Image
+
+ from core.inference import image_gallery
+ from models.inference import GalleryImage
+
+ monkeypatch.setattr(image_gallery, "gallery_dir", lambda: tmp_path)
+ fields = hires.record_fields(
+ {
+ "scale": 1.5,
+ "denoise": 0.5,
+ "steps": 14,
+ "upscaler": "lanczos",
+ "guidance": None,
+ "base_width": 256,
+ "base_height": 256,
+ }
+ )
+ rec = image_gallery.save(
+ Image.new("RGB", (384, 384)),
+ {
+ "prompt": "p",
+ "width": 384,
+ "height": 384,
+ "steps": 4,
+ "guidance": 0,
+ "seed": 1,
+ "created_at": 1.0,
+ "workflow": "txt2img",
+ **fields,
+ },
+ )
+ img = GalleryImage(**rec)
+ assert (img.hires_scale, img.hires_steps, img.hires_upscaler, img.hires_base_width) == (
+ 1.5,
+ 14,
+ "lanczos",
+ 256,
+ )
+ png = Image.open(tmp_path / f"{rec['id']}.png")
+ assert (
+ "Hires upscale: 1.5" in png.info["parameters"] and "Size: 256x256" in png.info["parameters"]
+ )
+
+
+ "length,tile,overlap",
+ [(100, 512, 32), (512, 512, 32), (513, 512, 32), (1500, 512, 32), (2048, 256, 16), (70, 64, 8)],
+)
+def test_tile_starts_cover_with_the_overlap(length, tile, overlap):
+ starts = ups.tile_starts(length, tile, overlap)
+ win = min(tile, length)
+ assert starts[0] == 0 and starts[-1] + win == length
+ covered = set()
+ for s in starts:
+ covered.update(range(s, s + win))
+ assert covered == set(range(length))
+ for a, b in zip(starts, starts[1:]):
+ assert a + win - b >= overlap # neighbours share at least the overlap
+
+
+def test_tiled_apply_matches_untiled_for_a_local_operator():
+ torch = pytest.importorskip("torch")
+
+ def up2(x):
+ return torch.nn.functional.interpolate(x, scale_factor = 2, mode = "nearest")
+
+ x = torch.rand(1, 3, 150, 97)
+ full = up2(x)
+ tiled = ups.tiled_apply(x, up2, 2, tile = 64, overlap = 8)
+ assert tiled.shape == full.shape
+ assert torch.allclose(tiled, full, atol = 1e-6)
+ assert len(ups.tile_boxes(97, 150, 64, 8)) > 1
+ assert ups.tiled_apply(x, up2, 2, tile = 64, overlap = 8, output_device = "cpu").device.type == "cpu"
+
+
[email protected]("tile", [512, 64])
+def test_stop_during_the_last_upscaler_tile_is_honoured(tile):
+ import threading
+
+ torch = pytest.importorskip("torch")
+ from core.inference.diffusion_families import DIFFUSION_CANCELLED_MSG
+
+ cancel = threading.Event()
+ calls = []
+
+ def up_then_stop(x):
+ calls.append(1)
+ if len(calls) == len(ups.tile_boxes(97, 150, tile, 8)):
+ cancel.set() # Stop lands while the final (or only) tile runs
+ return torch.nn.functional.interpolate(x, scale_factor = 2, mode = "nearest")
+
+ with pytest.raises(RuntimeError) as exc:
+ ups.tiled_apply(
+ torch.rand(1, 3, 150, 97), up_then_stop, 2, tile = tile, overlap = 8, cancel = cancel
+ )
+ assert str(exc.value) == DIFFUSION_CANCELLED_MSG
+
+
+def test_tiled_esrgan_matches_untiled_on_a_tiny_random_model(tmp_path, monkeypatch):
+ torch = pytest.importorskip("torch")
+ pytest.importorskip("spandrel")
+ from PIL import Image
+ from spandrel.architectures.ESRGAN import ESRGAN
+
+ torch.manual_seed(0)
+ net = ESRGAN(in_nc = 3, out_nc = 3, num_filters = 8, num_blocks = 1, scale = 4)
+ path = tmp_path / "tiny_esrgan.pth"
+ torch.save(net.state_dict(), path)
+ monkeypatch.setattr(ups, "models_dir", lambda: tmp_path)
+ img = Image.fromarray((torch.rand(96, 80, 3) * 255).to(torch.uint8).numpy())
+ seen_devices = []
+ real_tiled_apply = ups.tiled_apply
+
+ def spy(*a, **k):
+ seen_devices.append(k.get("output_device"))
+ return real_tiled_apply(*a, **k)
+
+ monkeypatch.setattr(ups, "tiled_apply", spy)
+ untiled = ups.upscale_with_model(img, "local:tiny_esrgan", (320, 384), device = "cpu", tile = 512)
+ tiled = ups.upscale_with_model(
+ img, "local:tiny_esrgan", (320, 384), device = "cpu", tile = 48, overlap = 16
+ )
+ assert untiled.tiles == 1 and tiled.tiles > 1
+ assert untiled.image.size == tiled.image.size == (320, 384)
+ import numpy as np
+
+ a = np.asarray(untiled.image, dtype = np.int16)
+ b = np.asarray(tiled.image, dtype = np.int16)
+ # The receptive field crosses the seams, so feathered blending is close, not exact.
+ assert np.abs(a - b).mean() < 2.0
+ assert untiled.released and not ups._resident # freed after use when not asked to stay
+ assert seen_devices == ["cpu", "cpu"] # the full-scale result accumulates in host memory
+
+
+def test_native_request_carries_the_hires_block():
+ from core.inference.sd_cpp_args import build_img_gen_request
+
+ block = hires.sd_cpp_payload(
+ hires.HiresParams(scale = 1.5, denoise = 0.5, steps = None, upscaler = "latent"),
+ 20,
+ (1248, 1824),
+ hires.sd_cpp_upscaler_name("latent"),
+ )
+ req = build_img_gen_request(prompt = "p", width = 832, height = 1216, steps = 20, hires = block)
+ assert req["hires"] == {
+ "enabled": True,
+ "upscaler": "Latent (nearest-exact)",
+ "scale": 1.5,
+ "target_width": 1248,
+ "target_height": 1824,
+ "steps": 20,
+ "denoising_strength": 0.5,
+ }
+ assert "hires" not in build_img_gen_request(prompt = "p")
+ assert hires.sd_cpp_upscaler_name("lanczos") == "Lanczos"
+ assert hires.sd_cpp_upscaler_name("realesrgan_x4plus", "hires_x") == "hires_x"
+
+
+def test_native_capability_needs_the_server_and_a_build_with_hires(monkeypatch):
+ monkeypatch.setattr(hires, "sd_cpp_supports_hires", lambda binary: binary == "new")
+ cap, reason = hires.sd_cpp_capability(_fam("sdxl"), mode = "server", binary = "new")
+ assert cap is not None and reason is None
+ # The control hides Hires CFG and upscale-only, which plan_sd_cpp refuses.
+ assert cap["supports_guidance"] is False and cap["min_denoise"] == hires.MIN_DENOISE
+ diffusers_cap = hires.capability(_fam("sdxl"))
+ assert diffusers_cap["supports_guidance"] is True and diffusers_cap["min_denoise"] == 0.0
+ assert hires.sd_cpp_capability(_fam("sdxl"), mode = "oneshot", binary = "new")[0] is None
+ cap, reason = hires.sd_cpp_capability(_fam("sdxl"), mode = "server", binary = "old")
+ assert cap is None and "no Hires fix support" in reason
+ assert hires.sd_cpp_capability(_fam("krea-2"), mode = "server", binary = "new")[0] is None
+ with pytest.raises(ValueError, match = "denoise above 0"):
+ hires.plan_sd_cpp(
+ _fam("sdxl"),
+ hires.HiresParams(denoise = 0.0, upscaler = "lanczos"),
+ mode = "server",
+ binary = "new",
+ width = 1024,
+ height = 1024,
+ steps = 20,
+ )
+ with pytest.raises(ValueError, match = "Hires CFG"):
+ hires.plan_sd_cpp(
+ _fam("sdxl"),
+ hires.HiresParams(guidance = 3.0),
+ mode = "server",
+ binary = "new",
+ width = 1024,
+ height = 1024,
+ steps = 20,
+ )
+ plan = hires.plan_sd_cpp(
+ _fam("flux.1"),
+ hires.HiresParams(steps = 6),
+ mode = "server",
+ binary = "new",
+ width = 832,
+ height = 1216,
+ steps = 20,
+ )
+ assert (
+ plan.target == (1248, 1824) and plan.refine_steps == 6 and plan.params.upscaler == "lanczos"
+ )
+
+
+def test_help_probe_fails_closed(monkeypatch, tmp_path):
+ import core.inference.sd_cpp_backend as scb
+
+ binary = tmp_path / "sd-server"
+ binary.write_text("")
+ monkeypatch.setattr(
+ scb, "_sd_cpp_probe_output", lambda b, *a: " --hires-denoising-strength x"
+ )
+ hires._sd_cpp_help_cache.clear()
+ assert hires.sd_cpp_supports_hires(str(binary)) is True
+ hires._sd_cpp_help_cache.clear()
+ monkeypatch.setattr(scb, "_sd_cpp_probe_output", lambda b, *a: None)
+ assert hires.sd_cpp_supports_hires(str(binary)) is False
+ assert hires.sd_cpp_supports_hires(None) is False
+
+
[email protected](scope = "module")
+def tiny_sdxl():
+ torch = pytest.importorskip("torch")
+ diffusers = pytest.importorskip("diffusers")
+ from huggingface_hub import snapshot_download
+
+ try:
+ path = snapshot_download("hf-internal-testing/tiny-stable-diffusion-xl-pipe")
+ except Exception as exc: # noqa: BLE001
+ pytest.skip(f"tiny pipeline not reachable: {exc}")
+ return diffusers.StableDiffusionXLPipeline.from_pretrained(path, torch_dtype = torch.float32)
+
+
+def _backend(pipe):
+ from core.inference.diffusion import DiffusionBackend, _LoadState
+
+ b = DiffusionBackend()
+ b._state = _LoadState(
+ pipe = pipe,
+ family = _fam("sdxl"),
+ repo_id = "tiny",
+ base_repo = "tiny",
+ device = "cpu",
+ dtype = "float32",
+ cpu_offload = False,
+ )
+ return b
+
+
+def test_tiny_sdxl_hires_sequencing(tiny_sdxl, monkeypatch):
+ import numpy as np
+ import diffusers
+
+ calls = []
+ orig = diffusers.StableDiffusionXLImg2ImgPipeline.__call__
+
+ import functools
+
+ @functools.wraps(orig) # keeps the signature the engine gates its kwargs on
+ def spy(self, *a, **k):
+ img = k.get("image")
+ calls.append(
+ (
+ k.get("num_inference_steps"),
+ k.get("strength"),
+ tuple(getattr(img, "shape", ())) or img.size,
+ )
+ )
+ steps_seen = []
+ cb = k.get("callback_on_step_end")
+
+ def counting(pipe, i, t, kw):
+ steps_seen.append(i)
+ totals.append(getattr(holder[0]._gen, "total_steps", None))
+ return cb(pipe, i, t, kw) if cb else kw
+
+ k["callback_on_step_end"] = counting
+ out = orig(self, *a, **k)
+ calls[-1] = calls[-1] + (len(steps_seen),)
+ return out
+
+ monkeypatch.setattr(diffusers.StableDiffusionXLImg2ImgPipeline, "__call__", spy)
+ b = _backend(tiny_sdxl)
+ holder, totals = [b], []
+ kw = dict(
+ prompt = "a cat", width = 256, height = 256, steps = 4, guidance = 5.0, seed = 7, live_preview = False
+ )
+ plain = b.generate(**kw)
+ again = b.generate(**kw, hires = None)
+ # hires=None is the unchanged path: same seed, same pixels, no img2img call.
+ assert np.array_equal(np.asarray(plain["images"][0]), np.asarray(again["images"][0]))
+ assert calls == [] and "hires" not in plain
+
+ out = b.generate(
+ **kw, hires = hires.HiresParams(scale = 1.5, denoise = 0.5, steps = 3, upscaler = "latent")
+ )
+ assert out["images"][0].size == (384, 384)
+ assert out["workflow"] == "txt2img"
+ assert out["hires"]["refine_steps"] == 3 and out["hires"]["base_width"] == 256
+ # One refine pass on 4-channel latents: 3 steps of a 6-step schedule at strength 0.5.
+ f = tiny_sdxl.vae_scale_factor
+ assert calls == [(6, 0.5, (1, 4, 384 // f, 384 // f), 3)]
+ # Progress counts the 3 steps the refine runs, not the 6-step schedule it enters halfway.
+ assert totals == [3, 3, 3]
+
+ calls.clear()
+ out = b.generate(
+ **kw, batch_size = 2, hires = hires.HiresParams(scale = 1.5, denoise = 0.35, upscaler = "lanczos")
+ )
+ assert [im.size for im in out["images"]] == [(384, 384)] * 2
+ assert len(calls) == 2 and all(c[1] == 0.35 and c[2] == (384, 384) and c[3] == 4 for c in calls)
+ assert out["seeds"] == plain["seeds"][:1] + [plain["seeds"][0] + 1]
+
+ calls.clear()
+ out = b.generate(**kw, hires = hires.HiresParams(scale = 2.0, denoise = 0.0, upscaler = "lanczos"))
+ assert out["images"][0].size == (512, 512) and calls == [] and out["hires"]["refine_steps"] == 0
+ from PIL import Image
+
+ expected = plain["images"][0].resize((512, 512), Image.LANCZOS)
+ assert np.array_equal(np.asarray(out["images"][0]), np.asarray(expected))
+ assert b._gen is None and b._active_generate_cancel is None
+
+
+def test_tiny_sdxl_hires_refusals(tiny_sdxl):
+ b = _backend(tiny_sdxl)
+ with pytest.raises(ValueError, match = "text to image only"):
+ b.generate(
+ prompt = "p", width = 256, height = 256, steps = 2, init_image = "x", hires = hires.HiresParams()
+ )
+ with pytest.raises(ValueError, match = "Unknown upscaler"):
+ b.generate(
+ prompt = "p", width = 256, height = 256, steps = 2, hires = hires.HiresParams(upscaler = "x")
+ )
+ with pytest.raises(ValueError, match = "SDXL only"):
+ hires.resolve_params(hires.HiresParams(upscaler = "latent"), "z-image")
+
+
+def test_preflight_refuses_before_the_base_pass(tiny_sdxl, monkeypatch):
+ import core.inference.diffusion_memory as dm
+
+ b = _backend(tiny_sdxl)
+ real = dm.raise_on_image_activation_shortfall
+ seen = []
+
+ def guard(**kw):
+ seen.append((kw["width"], kw["height"]))
+ if kw["width"] > 256:
+ raise dm.ImageActivationShortfallError("needs more memory")
+ return real(**kw)
+
+ monkeypatch.setattr(dm, "raise_on_image_activation_shortfall", guard)
+ monkeypatch.setattr("core.inference.diffusion.raise_on_image_activation_shortfall", guard)
+ ran = []
+ orig = type(tiny_sdxl).__call__
+ monkeypatch.setattr(
+ type(tiny_sdxl), "__call__", lambda self, *a, **k: ran.append(1) or orig(self, *a, **k)
+ )
+ with pytest.raises(
+ dm.ImageActivationShortfallError, match = "refine pass at 384x384 does not fit"
+ ):
+ b.generate(
+ prompt = "p",
+ width = 256,
+ height = 256,
+ steps = 2,
+ seed = 1,
+ live_preview = False,
+ hires = hires.HiresParams(upscaler = "lanczos"),
+ )
+ assert ran == [] # refused before the base pass denoised
+ assert (384, 384) in seen
+
+
+def test_run_hires_pass_kwargs_without_a_model(monkeypatch):
+ """Sequencing on a stand-in engine: per-image seeds, no variation seed, cancel re-armed, progress cleared."""
+ import contextlib
+ import threading
+
+ from PIL import Image
+
+ from core.inference.diffusion_sd_controls import SdControls
+
+ calls = []
+
+ class _Backend:
+ def __init__(self):
+ self._state = types.SimpleNamespace(
+ family = _fam("z-image"), offload_policy = "none", device = "cpu"
+ )
+ self._lock = threading.Lock()
+ self._generation_cancel_lock = threading.Lock()
+ self._gen = None
+ self._active_generate_cancel = None
+ self._active_generate_account = None
+
+ @contextlib.contextmanager
+ def _generation_slot(self, cancel):
+ yield
+
+ def fake_generate(backend, **kw):
+ ctx = kw.pop("_hires_pass")
+ calls.append(
+ (ctx.refine, ctx.defer_bg_kick, backend._active_generate_cancel is ctx.cancel, kw)
+ )
+ if not ctx.refine:
+ return {
+ "images": [Image.new("RGB", (256, 256))] * 2,
+ "seed": 5,
+ "seeds": [5, 6],
+ "workflow": "txt2img",
+ "negative_prompt": None, # base guidance 0 leaves the negative off
+ }
+ assert ctx.source.size == (384, 384)
+ return {
+ "images": [ctx.source],
+ "seed": kw["seed"],
+ "seeds": [kw["seed"]],
+ "negative_prompt": kw.get("negative_prompt"),
+ }
+
+ b = _Backend()
+ out = hires.run_hires(
+ b,
+ fake_generate,
+ hires.HiresParams(denoise = 0.4, steps = 6, guidance = 2.5),
+ {
+ "prompt": "p",
+ "prompts": ["a", "b"],
+ "width": 256,
+ "height": 256,
+ "steps": 8,
+ "guidance": 0.0,
+ "seed": 5,
+ "batch_size": 1,
+ "negative_prompt": "blurry",
+ "sd_controls": SdControls(variation_seed = 9, variation_strength = 0.3, clip_skip = 2),
+ },
+ )
+ assert [c[0] for c in calls] == [False, True, True]
+ assert calls[0][1] is True # the base pass defers a pending background compile
+ # ...and so does every refine but the last, or image two waits on the compile image one kicked.
+ assert [c[1] for c in calls[1:]] == [True, False]
+ assert out["negative_prompt"] == "blurry" # Hires CFG engaged it, so the recipe records it
+ assert calls[1][2] and calls[2][2] # Stop is registered again for each refine pass
+ refine = [c[3] for c in calls[1:]]
+ assert [k["prompt"] for k in refine] == ["a", "b"] and [k["seed"] for k in refine] == [5, 6]
+ assert all(k["steps"] == 6 and k["strength"] == 0.4 and k["guidance"] == 2.5 for k in refine)
+ assert all("prompts" not in k and "seeds" not in k and k["batch_size"] == 1 for k in refine)
+ assert all(
+ k["sd_controls"].variation_strength is None and k["sd_controls"].clip_skip == 2
+ for k in refine
+ )
+ assert calls[0][3]["sd_controls"].variation_strength == 0.3 # the base pass keeps it
+ assert out["hires"]["refine_steps"] == 6 and out["hires"]["upscaler"] == "lanczos"
+ assert [im.size for im in out["images"]] == [(384, 384)] * 2
+ assert b._gen is None
+
+
+def test_run_hires_plans_against_the_model_loaded_when_the_slot_is_held():
+ """A load that wins the slot first swaps the family; the plan must follow it (FLUX -> SDXL: latent default)."""
+ import contextlib
+ import threading
+
+ from PIL import Image
+
+ seen = []
+
+ class _Backend:
+ def __init__(self):
+ self._state = types.SimpleNamespace(
+ family = _fam("flux.1"), offload_policy = "none", device = "cpu"
+ )
+ self._lock = threading.Lock()
+ self._generation_cancel_lock = threading.Lock()
+ self._gen = None
+ self._active_generate_cancel = None
+ self._active_generate_account = None
+
+ @contextlib.contextmanager
+ def _generation_slot(self, cancel):
+ self._state = types.SimpleNamespace(
+ family = _fam("sdxl"), offload_policy = "none", device = "cpu"
+ )
+ yield
+
+ def fake_generate(backend, **kw):
+ ctx = kw.pop("_hires_pass")
+ seen.append(ctx)
+ if not ctx.refine:
+ return {"images": [Image.new("RGB", (256, 256))], "seed": 1, "seeds": [1]}
+ return {"images": [Image.new("RGB", ctx.source.size)], "seed": 1, "seeds": [1]}
+
+ out = hires.run_hires(
+ _Backend(),
+ fake_generate,
+ hires.HiresParams(),
+ {"prompt": "p", "width": 256, "height": 256, "steps": 8, "seed": 1, "batch_size": 1},
+ )
+ assert out["hires"]["upscaler"] == "latent"
+ assert seen[1].latent_from is not None
+
+
+def test_native_cpu_restart_restages_the_model_upscaler(tmp_path, monkeypatch):
+ import dataclasses
+ import io
+ import threading
+
+ from PIL import Image
+
+ import core.inference.sd_cpp_backend as scb
+
+ buf = io.BytesIO()
+ Image.new("RGB", (64, 64)).save(buf, format = "PNG")
+ png = buf.getvalue()
+ payloads = []
+
+ class _Server:
+ def __init__(self, lora_dir, fail):
+ self.lora_dir, self.fail = str(lora_dir), fail
+
+ def img_gen(self, payload, **kw):
+ payloads.append((self.lora_dir, dict(payload["hires"])))
+ if self.fail:
+ raise RuntimeError("ggml unsupported op abort")
+ return [png]
+
+ old_dir, new_dir = tmp_path / "old", tmp_path / "new"
+ old_dir.mkdir()
+ new_dir.mkdir()
+ staged_paths = []
+
+ def fake_stage(
+ upscaler_id,
+ scratch_dir,
+ *,
+ cancel = None,
+ ):
+ dest = tmp_path / scratch_dir / "hires_x.pth"
+ dest.write_bytes(b"w")
+ staged_paths.append(dest)
+ return "hires_x", dest
+
+ monkeypatch.setattr(hires, "stage_sd_cpp_upscaler", fake_stage)
+
+ @dataclasses.dataclass(frozen = True)
+ class _State:
+ family: object
+ server: object
+ sampling_method: object = None
+ flow_shift: object = None
+ sample_sigmas: object = None
+
+ b = scb.SdCppDiffusionBackend()
+ new_server = _Server(new_dir, fail = False)
+ monkeypatch.setattr(b, "_restart_server_on_cpu_backend", lambda state, text, cancel: new_server)
+ plan = hires.SdCppHiresPlan(
+ params = hires.HiresParams(upscaler = "realesrgan_x4plus"),
+ base_width = 64,
+ base_height = 64,
+ target = (96, 96),
+ refine_steps = 4,
+ )
+ images, _ = b._generate_server(
+ _State(family = _fam("sdxl"), server = _Server(old_dir, fail = True)),
+ prompt = "p",
+ negative_prompt = None,
+ width = 64,
+ height = 64,
+ steps = 4,
+ seed = 1,
+ batch_size = 1,
+ cfg_scale = None,
+ flux_guidance = None,
+ lora_resolved = [],
+ cancel = threading.Event(),
+ hires_plan = plan,
+ )
+ assert len(images) == 1
+ assert [d for d, _ in payloads] == [str(old_dir), str(new_dir)]
+ assert all(h["upscaler"] == "hires_x" for _, h in payloads)
+ assert [p.parent for p in staged_paths] == [
+ old_dir,
+ new_dir,
+ ] # staged again in the new server's dir
+ assert not any(p.exists() for p in staged_paths) # both removed after
+
+
+def test_diffusers_status_names_why_hires_is_hidden():
+ from core.inference.diffusion import _hires_status
+
+ assert "image-to-image" in _hires_status(_fam("krea-2"))["hires_unavailable_reason"]
+ shown = _hires_status(_fam("sdxl"))
+ assert shown["hires"] is not None and shown["hires_unavailable_reason"] is None
+
+
+def test_native_hires_progress_follows_each_sampling_pass():
+ import core.inference.sd_cpp_backend as scb
+
+ # sd.cpp make_hires_sigma_schedule: int(14 / 0.5) = 28 -> 14; int(20 / 0.35) = 57 -> int(19.95) = 19.
+ assert hires.sd_cpp_hires_sampled_steps(14, 0.5) == 14
+ assert hires.sd_cpp_hires_sampled_steps(20, 0.35) == 19
+ assert hires.sd_cpp_hires_sampled_steps(5, 1.0) == 4
+
+ b = scb.SdCppDiffusionBackend()
+ for base, refine in ((20, 14), (20, 20)):
+ b._gen = scb._SdGen(total_steps = base + refine, passes = (base, refine))
+ seen = []
+ for line in (
+ [f"|====| {i}/{base} - 1.0s/it" for i in range(1, base + 1)]
+ + [f"|====| {base}/{base} - 1.0s/it"] # a repeated last line is not the next pass
+ + [f"|====| {i}/{refine} - 1.0s/it" for i in range(1, refine + 1)]
+ ):
+ b._on_log(line)
+ seen.append(b._gen.step)
+ assert seen[base - 1] == base and seen[base] == base
+ assert seen[base + 1] == base + 1 and seen[-1] == base + refine
+ assert b.generate_progress()["fraction"] == 1.0
+ b._on_log(f"|=| 1/{base} - 1.0s/it") # a batch's next image starts its base pass again
+ assert b._gen.step == 1
+ b._gen = scb._SdGen(total_steps = 8)
+ b._on_log("|=| 3/8 - 1.0s/it")
+ assert b._gen.step == 3 # a plain render is unchanged
+
+
+def test_mlx_engine_takes_the_hires_keyword_and_refuses_it():
+ from core.inference.mlx_diffusion_backend import MlxDiffusionBackend
+ with pytest.raises(ValueError, match = "not available on the MLX engine"):
+ MlxDiffusionBackend.generate(types.SimpleNamespace(), prompt = "p", hires = hires.HiresParams())
+
+
+def test_native_hires_sends_the_steps_that_sample_the_requested_count(monkeypatch):
+ # sd.cpp samples int(int(n / s) * s) (capped at n / s - 1): 5 at 1.0 needs 6 sent; 20 at 0.35 has no exact
+ # count (20 -> 19, 21 -> 21), so the request is sent and the sampled 19 is what the plan reports.
+ assert hires.sd_cpp_hires_request_steps(5, 1.0) == 6
+ assert hires.sd_cpp_hires_request_steps(14, 0.5) == 14
+ assert hires.sd_cpp_hires_request_steps(20, 0.35) == 20
+ for steps, denoise in ((5, 1.0), (14, 0.5), (8, 0.3), (30, 0.7), (1, 0.5)):
+ sent = hires.sd_cpp_hires_request_steps(steps, denoise)
+ assert hires.sd_cpp_hires_sampled_steps(sent, denoise) == steps, (steps, denoise)
+ monkeypatch.setattr(hires, "sd_cpp_supports_hires", lambda binary: True)
+ plan = hires.plan_sd_cpp(
+ _fam("sdxl"),
+ hires.HiresParams(denoise = 1.0, steps = 5, upscaler = "lanczos"),
+ mode = "server",
+ binary = "new",
+ width = 512,
+ height = 512,
+ steps = 20,
+ )
+ assert (plan.request_steps, plan.refine_steps) == (6, 5)
+ block = hires.sd_cpp_payload(
+ plan.params, 20, plan.target, "Lanczos", request_steps = plan.request_steps
+ )
+ assert block["steps"] == 6
+ assert hires.result_block(plan)["refine_steps"] == 5 and hires.result_block(plan)["steps"] == 5
+
+
[email protected]("env", ["TRANSFORMERS_OFFLINE", "HF_HUB_OFFLINE"])
+def test_catalog_download_honours_every_offline_switch(tmp_path, monkeypatch, env):
+ monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)
+ monkeypatch.delenv("TRANSFORMERS_OFFLINE", raising = False)
+ monkeypatch.setenv(env, "1")
+ monkeypatch.setattr(ups, "models_dir", lambda: tmp_path)
+ monkeypatch.setattr(
+ ups.urllib.request, "urlopen", lambda *a, **k: pytest.fail("network used while offline")
+ )
+ with pytest.raises(ValueError, match = "offline"):
+ ups.resolve_model_path(ups.CATALOG[0].id)
+
+
+def test_upscale_only_with_a_model_upscaler_defers_the_compile_until_it_ran(monkeypatch):
+ import contextlib
+ import threading
+
+ from PIL import Image
+
+ order = []
+
+ class _Bg:
+ def kick(self):
+ order.append("kick")
+ return True
+
+ class _Backend:
+ def __init__(self):
+ self._state = types.SimpleNamespace(
+ family = _fam("flux.1"), offload_policy = "none", device = "cpu", bg_compile = _Bg()
+ )
+ self._lock = threading.Lock()
+ self._generation_cancel_lock = threading.Lock()
+ self._gen = None
+ self._active_generate_cancel = None
+ self._active_generate_account = None
+
+ @contextlib.contextmanager
+ def _generation_slot(self, cancel):
+ yield
+
+ def fake_upscale(image, upscaler_id, target, **kw):
+ order.append("upscale")
+ return ups.UpscaleOutcome(Image.new("RGB", target), 4, 1, "float32", 0.0, True)
+
+ monkeypatch.setattr(ups, "spandrel_available", lambda: True)
+ monkeypatch.setattr(ups, "upscale_with_model", fake_upscale)
+ seen = []
+
+ def fake_generate(backend, **kw):
+ ctx = kw.pop("_hires_pass")
+ seen.append(ctx.defer_bg_kick)
+ return {"images": [Image.new("RGB", (256, 256))] * 2, "seed": 1, "seeds": [1, 2]}
+
+ hires.run_hires(
+ _Backend(),
+ fake_generate,
+ hires.HiresParams(denoise = 0.0, upscaler = "realesrgan_x4plus"),
+ {"prompt": "p", "width": 256, "height": 256, "steps": 4, "seed": 1, "batch_size": 2},
+ )
+ assert seen == [True] # the base pass leaves the compile pending
+ assert order == ["upscale", "upscale", "kick"] # started only once the GPU upscales finished
+ order.clear()
+ hires.run_hires(
+ _Backend(),
+ fake_generate,
+ hires.HiresParams(denoise = 0.0, upscaler = "lanczos"),
+ {"prompt": "p", "width": 256, "height": 256, "steps": 4, "seed": 1, "batch_size": 1},
+ )
+ assert (
+ seen[-1] is False and order == []
+ ) # a CPU Lanczos upscale lets the base pass kick as before
+
+
+def test_stop_during_an_upscale_only_resize_returns_no_image(monkeypatch):
+ import contextlib
+ import threading
+
+ from PIL import Image
+
+ from core.inference.diffusion_families import DIFFUSION_CANCELLED_MSG
+
+ class _Backend:
+ def __init__(self):
+ self._state = types.SimpleNamespace(
+ family = _fam("flux.1"), offload_policy = "none", device = "cpu"
+ )
+ self._lock = threading.Lock()
+ self._generation_cancel_lock = threading.Lock()
+ self._gen = None
+ self._active_generate_cancel = None
+ self._active_generate_account = None
+
+ @contextlib.contextmanager
+ def _generation_slot(self, cancel):
+ yield
+
+ def stopped_upscale(image, upscaler_id, target, **kw):
+ kw["cancel"].set() # Stop accepted while the model's output is resized
+ return ups.UpscaleOutcome(Image.new("RGB", target), 4, 1, "float32", 0.0, True)
+
+ monkeypatch.setattr(ups, "spandrel_available", lambda: True)
+ monkeypatch.setattr(ups, "upscale_with_model", stopped_upscale)
+
+ def fake_generate(backend, **kw):
+ kw.pop("_hires_pass")
+ return {"images": [Image.new("RGB", (256, 256))], "seed": 1, "seeds": [1]}
+
+ with pytest.raises(RuntimeError) as exc:
+ hires.run_hires(
+ _Backend(),
+ fake_generate,
+ hires.HiresParams(denoise = 0.0, upscaler = "realesrgan_x4plus"),
+ {"prompt": "p", "width": 256, "height": 256, "steps": 4, "seed": 1, "batch_size": 1},
+ )
+ assert str(exc.value) == DIFFUSION_CANCELLED_MSG
+
+
+def test_a_resident_drop_in_reloads_when_its_file_is_replaced(tmp_path, monkeypatch):
+ import os
+
+ torch = pytest.importorskip("torch")
+ pytest.importorskip("spandrel")
+ import numpy as np
+ from PIL import Image
+ from spandrel.architectures.ESRGAN import ESRGAN
+
+ monkeypatch.setattr(ups, "models_dir", lambda: tmp_path)
+ path = tmp_path / "tiny_esrgan.pth"
+ img = Image.fromarray((torch.rand(32, 32, 3) * 255).to(torch.uint8).numpy())
+
+ def write(seed):
+ torch.manual_seed(seed)
+ torch.save(
+ ESRGAN(in_nc = 3, out_nc = 3, num_filters = 8, num_blocks = 1, scale = 4).state_dict(), path
+ )
+
+ def run(keep):
+ out = ups.upscale_with_model(
+ img, "local:tiny_esrgan", (128, 128), device = "cpu", keep_resident = keep
+ )
+ return np.asarray(out.image)
+
+ try:
+ write(0)
+ first = run(True)
+ st = path.stat()
+ write(1)
+ os.utime(
+ path, ns = (st.st_atime_ns, st.st_mtime_ns + 1_000_000_000)
+ ) # a distinct mtime on any fs
+ replaced = run(True)
+ assert not np.array_equal(first, replaced)
+ assert np.array_equal(replaced, run(False)) # the resident copy is the new file's weights
+ finally:
+ ups.release_models()
+
+
+def _fake_model_upscaler(tmp_path, monkeypatch, fn):
+ path = tmp_path / "fake.pth"
+ path.write_bytes(b"w")
+ import torch
+
+ monkeypatch.setattr(ups, "spandrel_available", lambda: True)
+ monkeypatch.setattr(ups, "resolve_model_path", lambda upscaler_id, cancel = None: path)
+ monkeypatch.setattr(
+ ups, "_load", lambda p, dev: (types.SimpleNamespace(scale = 2, model = fn), torch.float32)
+ )
+
+
+def test_model_upscaler_halves_the_tile_on_oom_like_comfyui(tmp_path, monkeypatch):
+ torch = pytest.importorskip("torch")
+ from PIL import Image
+
+ sizes = []
+
+ def needs_small_tiles(piece):
+ sizes.append(piece.shape[-1])
+ if piece.shape[-1] > 128:
+ raise torch.cuda.OutOfMemoryError("CUDA out of memory. Tried to allocate 2.00 GiB")
+ return torch.nn.functional.interpolate(piece, scale_factor = 2, mode = "nearest")
+
+ _fake_model_upscaler(tmp_path, monkeypatch, needs_small_tiles)
+ img = Image.new("RGB", (300, 300), (10, 20, 30))
+ out = ups.upscale_with_model(img, "local:fake", (600, 600), device = "cpu")
+ # 512 (one 300 px tile) and 256 run out of memory; 128 px tiles fit.
+ assert sizes[:2] == [300, 256] and set(sizes[2:]) == {128}
+ assert out.tiles == len(ups.tile_boxes(300, 300, 128, ups.DEFAULT_OVERLAP))
+ assert out.image.size == (600, 600) and out.image.getpixel((5, 5)) == (10, 20, 30)
+
+ sizes.clear()
+
+ def always_oom(piece):
+ sizes.append(piece.shape[-1])
+ raise torch.cuda.OutOfMemoryError("CUDA out of memory")
+
+ _fake_model_upscaler(tmp_path, monkeypatch, always_oom)
+ with pytest.raises(torch.cuda.OutOfMemoryError):
+ ups.upscale_with_model(img, "local:fake", (600, 600), device = "cpu")
+ assert sizes == [300, 256, 128] # gives up below ComfyUI's 128 px floor
+
+ calls = []
+
+ def broken(piece):
+ calls.append(1)
+ raise ValueError("bad weights")
+
+ _fake_model_upscaler(tmp_path, monkeypatch, broken)
+ with pytest.raises(ValueError):
+ ups.upscale_with_model(img, "local:fake", (600, 600), device = "cpu")
+ assert calls == [1] # only an OOM retries
+
+
+def test_download_rechecks_stop_between_short_reads(tmp_path, monkeypatch):
+ import threading
+
+ from core.inference.diffusion_families import DIFFUSION_CANCELLED_MSG
+
+ monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)
+ monkeypatch.delenv("TRANSFORMERS_OFFLINE", raising = False)
+ monkeypatch.setattr(ups, "models_dir", lambda: tmp_path)
+ stop = threading.Event()
+ reads = []
+
+ class _Trickle:
+ def read(self, n):
+ raise AssertionError("read(n) blocks until n bytes arrive")
+
+ def read1(self, n):
+ reads.append(n)
+ stop.set() # Stop pressed while the server trickles
+ return b"x"
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *a):
+ return False
+
+ monkeypatch.setattr(ups.urllib.request, "urlopen", lambda *a, **k: _Trickle())
+ with pytest.raises(RuntimeError) as exc:
+ ups.resolve_model_path(ups.CATALOG[0].id, cancel = stop)
+ assert str(exc.value) == DIFFUSION_CANCELLED_MSG
+ assert len(reads) == 1 and reads[0] <= 1 << 16
+ assert not any(tmp_path.iterdir())
+
+
[email protected]("fail_in", ["refine", "upscale"])
+def test_a_failed_pass_after_the_base_still_kicks_the_deferred_compile(monkeypatch, fail_in):
+ import contextlib
+ import threading
+
+ from PIL import Image
+
+ kicks = []
+
+ class _Backend:
+ def __init__(self):
+ self._state = types.SimpleNamespace(
+ family = _fam("flux.1"),
+ offload_policy = "none",
+ device = "cpu",
+ bg_compile = types.SimpleNamespace(kick = lambda: kicks.append(1)),
+ )
+ self._lock = threading.Lock()
+ self._generation_cancel_lock = threading.Lock()
+ self._gen = None
+ self._active_generate_cancel = None
+ self._active_generate_account = None
+
+ @contextlib.contextmanager
+ def _generation_slot(self, cancel):
+ yield
+
+ def broken_upscale(*a, **k):
+ raise RuntimeError("upscale failed")
+
+ monkeypatch.setattr(ups, "spandrel_available", lambda: True)
+ monkeypatch.setattr(ups, "upscale_with_model", broken_upscale)
+
+ def fake_generate(backend, **kw):
+ ctx = kw.pop("_hires_pass")
+ if ctx.refine:
+ raise RuntimeError("refine failed")
+ return {"images": [Image.new("RGB", (256, 256))], "seed": 1, "seeds": [1]}
+
+ params = (
+ hires.HiresParams(denoise = 0.5, upscaler = "lanczos")
+ if fail_in == "refine"
+ else hires.HiresParams(denoise = 0.0, upscaler = "realesrgan_x4plus")
+ )
+ kw = {"prompt": "p", "width": 256, "height": 256, "steps": 4, "seed": 1, "batch_size": 1}
+ with pytest.raises(RuntimeError, match = "failed"):
+ hires.run_hires(_Backend(), fake_generate, params, kw)
+ assert kicks == [1]
+
+ kicks.clear()
+
+ def base_fails(backend, **kw):
+ raise RuntimeError("base failed")
+
+ with pytest.raises(RuntimeError, match = "base failed"):
+ hires.run_hires(_Backend(), base_fails, params, kw)
+ assert kicks == [] # nothing was recorded, as a failed plain render
diff --git a/studio/frontend/src/features/images/api.ts b/studio/frontend/src/features/images/api.ts
index 5c32246a596..c1ae15d7100 100644
--- a/studio/frontend/src/features/images/api.ts
+++ b/studio/frontend/src/features/images/api.ts
@@ -12,6 +12,7 @@ import {
MemoryEstimateRefusalError,
} from "./lib/memory-refusal";
import type { PromptEnhancement } from "./lib/prompt-enhance";
+import type { HiresCapability, HiresRequest } from "./lib/hires-choice";
import type { SdControlsCapability } from "./lib/sd-controls";
import type { ShiftControl } from "./lib/shift-choice";
@@ -120,6 +121,11 @@ export interface DiffusionStatus {
// an older backend: no Enhance prompt toggle.
supports_prompt_upsampler?: boolean;
prompt_upsampler_default?: boolean;
+ // Hires fix the loaded model takes; null/absent = hidden (no img2img path, or an engine without it).
+ hires?: HiresCapability | null;
+ hires_unavailable_reason?: string | null;
+ // Model upscalers the Upscale workflow can use; empty/absent = Lanczos only.
+ upscale_models?: Array<{ id: string; label: string; scale: number }>;
}
export interface DiffusionSamplerOption {
@@ -286,6 +292,10 @@ export interface DiffusionGenerateRequest {
// Rewrite the prompt with the family's prompt upsampler first. null/absent = the family default. Sent only for a
// family that supports it.
enhance_prompt?: boolean | null;
+ // Hires fix (text to image only); omitted = off.
+ hires?: HiresRequest;
+ // Upscale workflow: a model upscaler id from status.upscale_models; omitted = Lanczos.
+ upscale_model?: string | null;
}
// One LoRA selection sent with a generation.
@@ -391,6 +401,15 @@ export interface GalleryImage {
mask_blur?: number | null;
inpaint_only_masked?: boolean | null;
inpaint_padding?: number | null;
+ upscale_model?: string | null;
+ // Hires fix; `width` / `height` stay the output size, hires_base_* the base pass.
+ hires_scale?: number | null;
+ hires_denoise?: number | null;
+ hires_steps?: number | null;
+ hires_upscaler?: string | null;
+ hires_guidance?: number | null;
+ hires_base_width?: number | null;
+ hires_base_height?: number | null;
created_at: number;
// Library state, not recipe: stored beside the PNG, absent on records written before this existed.
pinned?: boolean;
diff --git a/studio/frontend/src/features/images/hires-controls.tsx b/studio/frontend/src/features/images/hires-controls.tsx
new file mode 100644
index 00000000000..e8d0bc4f401
--- /dev/null
+++ b/studio/frontend/src/features/images/hires-controls.tsx
@@ -0,0 +1,238 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import type { ReactNode } from "react";
+import { InfoHint } from "@/components/ui/info-hint";
+import { Input } from "@/components/ui/input";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { Switch } from "@/components/ui/switch";
+import {
+ effectiveUpscaler,
+ hiresGuidanceSupported,
+ hiresMinDenoiseFor,
+ hiresTargetSize,
+ type HiresCapability,
+ type HiresChoice,
+} from "./lib/hires-choice";
+
+function Label({ label, hint }: { label: string; hint: ReactNode }) {
+ return (
+ <span className="flex items-center gap-1 text-xs font-medium text-muted-foreground">
+ {label}
+ <InfoHint>{hint}</InfoHint>
+ </span>
+ );
+}
+
+function NumberInput({
+ ariaLabel,
+ value,
+ placeholder,
+ min,
+ max,
+ step,
+ integer,
+ onChange,
+}: {
+ ariaLabel: string;
+ value: number | null;
+ placeholder?: string;
+ min: number;
+ max: number;
+ step: number;
+ integer?: boolean;
+ onChange: (v: number | null) => void;
+}) {
+ return (
+ <Input
+ aria-label={ariaLabel}
+ type="number"
+ inputMode={integer ? "numeric" : "decimal"}
+ className="h-8 w-24 text-xs"
+ min={min}
+ max={max}
+ step={step}
+ placeholder={placeholder}
+ value={value ?? ""}
+ onChange={(e) => {
+ const raw = e.target.value.trim();
+ if (raw === "") return onChange(null);
+ const n = Number(raw);
+ if (!Number.isFinite(n)) return;
+ const bounded = Math.min(max, Math.max(min, integer ? Math.round(n) : n));
+ onChange(bounded);
+ }}
+ />
+ );
+}
+
+export function HiresControls({
+ capability,
+ choice,
+ onChange,
+ width,
+ height,
+}: {
+ capability: HiresCapability;
+ choice: HiresChoice;
+ onChange: (next: HiresChoice) => void;
+ width: number;
+ height: number;
+}) {
+ const target = hiresTargetSize(width, height, choice.scale, capability.max_side);
+ const upscaler = effectiveUpscaler(choice, capability);
+ const minDenoise = hiresMinDenoiseFor(choice, capability);
+ return (
+ <div className="flex flex-col gap-2 pt-2">
+ <div className="flex items-center justify-between">
+ <Label
+ label="Hires fix"
+ hint="Render, enlarge, then redraw the enlarged image at a denoise, in one run (AUTOMATIC1111 Hires. fix, ComfyUI 2-pass). Adds detail a single pass at the large size would not."
+ />
+ <Switch
+ checked={choice.enabled}
+ onCheckedChange={(enabled) =>
+ onChange(
+ enabled && !choice.enabled
+ ? {
+ ...choice,
+ enabled,
+ scale: choice.scale || capability.defaults.scale,
+ denoise: choice.denoise ?? capability.defaults.denoise,
+ }
+ : { ...choice, enabled },
+ )
+ }
+ aria-label="Hires fix"
+ />
+ </div>
+ {choice.enabled && (
+ <div className="flex flex-col gap-2 rounded-md border border-border/60 p-2">
+ <div className="flex items-center justify-between gap-2">
+ <Label label="Upscale by" hint="Output size is the base size times this factor, rounded to a multiple of 16." />
+ <NumberInput
+ ariaLabel="Hires upscale by"
+ value={choice.scale}
+ min={1}
+ max={4}
+ step={0.05}
+ onChange={(v) => onChange({ ...choice, scale: v ?? capability.defaults.scale })}
+ />
+ </div>
+ <div className="flex items-center justify-between gap-2">
+ <Label
+ label="Denoise"
+ hint={
+ minDenoise > 0
+ ? "How much the second pass redraws. 0.5 is ComfyUI's two-pass default; the latent upscaler needs about 0.5 or more."
+ : "How much the second pass redraws. 0.5 is ComfyUI's two-pass default; the latent upscaler needs about 0.5 or more. 0 only upscales."
+ }
+ />
+ <NumberInput
+ ariaLabel="Hires denoise"
+ value={choice.denoise}
+ min={minDenoise}
+ max={1}
+ step={0.05}
+ onChange={(v) => onChange({ ...choice, denoise: v ?? capability.defaults.denoise })}
+ />
+ </div>
+ <div className="flex items-center justify-between gap-2">
+ <Label label="Hires steps" hint="Exactly how many steps the second pass runs. Empty uses the base Steps." />
+ <NumberInput
+ ariaLabel="Hires steps"
+ value={choice.steps}
+ placeholder="Same"
+ min={1}
+ max={100}
+ step={1}
+ integer
+ onChange={(steps) => onChange({ ...choice, steps })}
+ />
+ </div>
+ <div className="flex items-center justify-between gap-2">
+ <Label
+ label="Upscaler"
+ hint="Latent enlarges the latents (SDXL), Lanczos the pixels, R-ESRGAN runs an upscaling model first (downloaded on first use)."
+ />
+ <Select
+ value={upscaler}
+ onValueChange={(id) => {
+ const next = { ...choice, upscaler: id };
+ onChange({ ...next, denoise: Math.max(next.denoise, hiresMinDenoiseFor(next, capability)) });
+ }}
+ >
+ <SelectTrigger className="h-8 w-44 text-xs" aria-label="Hires upscaler">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {capability.upscalers.map((u) => (
+ <SelectItem key={u.id} value={u.id}>
+ {u.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ {hiresGuidanceSupported(capability) && (
+ <div className="flex items-center justify-between gap-2">
+ <Label label="Hires CFG" hint="Guidance for the second pass. Empty uses the base guidance." />
+ <NumberInput
+ ariaLabel="Hires CFG"
+ value={choice.guidance}
+ placeholder="Same"
+ min={0}
+ max={20}
+ step={0.5}
+ onChange={(guidance) => onChange({ ...choice, guidance })}
+ />
+ </div>
+ )}
+ <p className="text-xs text-muted-foreground" aria-label="Hires output size">
+ {width}x{height} {"->"} {target.width}x{target.height}
+ </p>
+ </div>
+ )}
+ </div>
+ );
+}
+
+export function UpscaleModelField({
+ models,
+ value,
+ onChange,
+}: {
+ models: Array<{ id: string; label: string }> | undefined;
+ value: string | null;
+ onChange: (id: string | null) => void;
+}) {
+ if (!models || models.length === 0) return null;
+ const current = value && models.some((m) => m.id === value) ? value : "lanczos";
+ return (
+ <div className="flex items-center justify-between gap-2 pt-2">
+ <Label
+ label="Upscaler"
+ hint="Lanczos resizes the pixels. A model upscaler (R-ESRGAN) enlarges first and keeps edges sharper; it downloads on first use."
+ />
+ <Select value={current} onValueChange={(id) => onChange(id === "lanczos" ? null : id)}>
+ <SelectTrigger className="h-8 w-44 text-xs" aria-label="Upscaler">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="lanczos">Lanczos</SelectItem>
+ {models.map((m) => (
+ <SelectItem key={m.id} value={m.id}>
+ {m.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ );
+}
diff --git a/studio/frontend/src/features/images/images-page.tsx b/studio/frontend/src/features/images/images-page.tsx
index d5f7ab7643d..79d72cf4f38 100644
--- a/studio/frontend/src/features/images/images-page.tsx
+++ b/studio/frontend/src/features/images/images-page.tsx
@@ -368,6 +368,22 @@ import {
import { listDiffusionEmbeddings } from "./embeddings-api";
import { addGalleryImageToProject, listDiffusionControlNets, moveGalleryImage } from "./images-page-api";
import { EmbeddingsField, ShiftField } from "./shift-embeddings-controls";
+import { HiresControls, UpscaleModelField } from "./hires-controls";
+import {
+ HIRES_OFF,
+ HIRES_UPSCALER_LABELS,
+ hiresBaseSize,
+ hiresEngagesNegative,
+ hiresFromRecipe,
+ hiresRecordUsedNegative,
+ hiresNotApplied,
+ hiresRequest,
+ hiresSummary,
+ hiresVisible,
+ resolveRestoredHires,
+ upscaleModelRequest,
+ type HiresChoice,
+} from "./lib/hires-choice";
import {
enhancePromptRequestField,
enhanceRestoreFor,
@@ -1404,6 +1420,12 @@ function RecipePopover({
{image.upscale != null && image.workflow === "upscale" ? (
<RecipeRow label="Upscale" value={`${image.upscale}×`} />
) : null}
+ {image.upscale_model && image.workflow === "upscale" ? (
+ <RecipeRow label="Upscaler" value={HIRES_UPSCALER_LABELS[image.upscale_model] ?? image.upscale_model.replace(/^local:/, "")} />
+ ) : null}
+ {image.hires_scale != null ? (
+ <RecipeRow label="Hires fix" value={hiresSummary(hiresFromRecipe(image))} wrap />
+ ) : null}
{image.reference_image_count != null &&
(image.workflow === "reference" || image.workflow === "edit") ? (
<RecipeRow label="References" value={String(image.reference_image_count)} />
@@ -1754,6 +1776,8 @@ export function ImagesPage({
// Upscale (hires fix): the enlargement factor and the low denoise strength that re-details the result.
const [upscaleFactor, setUpscaleFactor] = useState(2);
const [upscaleStrength, setUpscaleStrength] = useState(0.35);
+ const [upscaleModel, setUpscaleModel] = useState<string | null>(null);
+ const [hires, setHires] = useState<HiresChoice>(HIRES_OFF);
// Reference and Edit: the ADDITIONAL images after the source. "" holds a cleared slot so others do not renumber.
const [referenceImages, setReferenceImages] = useState<string[]>([]);
const [referenceResolution, setReferenceResolution] = useState<number | null>(null);
@@ -2228,8 +2252,15 @@ export function ImagesPage({
status?.loaded && status.negative_prompt_min_guidance !== undefined
? status.negative_prompt_min_guidance
: 0;
+ // A connection runs none of the local engine's Hires fix / model upscalers (the route refuses both).
+ const hiresCapability = !external && status?.loaded ? (status.hires ?? null) : null;
+ const upscaleModels = !external && status?.loaded ? status.upscale_models : undefined;
+ // Hires CFG can turn CFG on for the refine pass alone; that pass then reads the negative prompt.
const negativeEngaged =
- negativeCapable && (negativeMinGuidance === null || effectiveGuidance > negativeMinGuidance);
+ negativeCapable &&
+ (negativeMinGuidance === null ||
+ effectiveGuidance > negativeMinGuidance ||
+ hiresEngagesNegative(hires, hiresCapability, workflow, negativeMinGuidance));
const livePreviewUnavailable =
!external && status?.loaded === true && status.supports_live_preview === false;
const samplerOptions = (!external && status?.loaded ? status.samplers : null) ?? NO_SAMPLERS;
@@ -2808,8 +2839,10 @@ export function ImagesPage({
// `via`: "import" names what was not applied in its own toast; "vary" restores silently for the Vary run.
const restoreSettings = useCallback((image: GalleryImage, exactCaption = false, via: "restore" | "import" | "vary" = "restore") => {
const viaConnection = image.model_kind === "connection";
- // Negative prompt only applies when guidance>0; do not restore a hidden value.
- const restoredNegative = image.guidance > 0 ? (image.negative_prompt ?? "") : "";
+ // Negative prompt only applies when guidance>0 (the base pass's, or Hires CFG's for the refine pass); do not
+ // restore a hidden value.
+ const restoredNegative =
+ image.guidance > 0 || hiresRecordUsedNegative(image) ? (image.negative_prompt ?? "") : "";
setNegativePrompt(restoredNegative);
if (restoredNegative) setNegativeOpen(true);
if (!viaConnection) {
@@ -2826,7 +2859,11 @@ export function ImagesPage({
// Restore from the BASE batch seed, not this image's derived seed, or a replay with batch_size
// advances it again.
if (!viaConnection) setSeed(String(image.batch_seed ?? image.seed));
- const restored = restorableSize(image.width, image.height, image.workflow, sizeLimits);
+ // A Hires fix image records its output size; the Width / Height controls take the base pass.
+ const base = hiresBaseSize(image) ?? { width: image.width, height: image.height };
+ const restored = restorableSize(base.width, base.height, image.workflow, sizeLimits);
+ setHires(resolveRestoredHires(hiresFromRecipe(image), status?.hires));
+ setUpscaleModel(image.upscale_model ?? null);
setWidth(restored.width);
setHeight(restored.height);
// The batch shared one base seed, so a batch_index>0 image only reproduces by replaying the whole batch.
@@ -2885,7 +2922,7 @@ export function ImagesPage({
// The Recipe popover goes on showing the recorded size, so a restore that had to move it says
// so rather than leaving the two silently disagreeing.
const rescaled =
- restored.width !== image.width || restored.height !== image.height
+ restored.width !== base.width || restored.height !== base.height
? { description: `Size scaled to ${restored.width} × ${restored.height} to fit the ${MIN_DIM}-${sizeLimits.maxSide} range.` }
: undefined;
// Say so, rather than letting a conditioned image restore as a plain Create that generates something unrelated.
@@ -3036,6 +3073,7 @@ export function ImagesPage({
...lorasOverLimit(merged).map((id) => `LoRA ${id} (over the ${MAX_LORAS} adapter limit)`),
...tagged.notes,
...shiftNotApplied(recipe, shiftControl),
+ ...hiresNotApplied(hiresFromRecipe(settings), status?.loaded ? status.hires : null),
...unknownRecipeKeys(recipe),
];
if (tiMatch) {
@@ -5368,6 +5406,8 @@ export function ImagesPage({
strength: condStrength,
...condInpaint,
upscale: condUpscale,
+ upscale_model: isUpscale ? upscaleModelRequest(upscaleModel, upscaleModels) : undefined,
+ hires: hiresRequest(hires, hiresCapability, workflow),
allow_oversized: allowOversizedSent ? true : undefined,
live_preview: livePreview,
...samplerRequestFields(samplerOptions, samplerChoice),
@@ -5479,7 +5519,7 @@ export function ImagesPage({
setGenStep(null);
setStopping(false);
}
- }, [external, allowOversized, livePreview, enhanceOn, upsamplerCapability, prompt, negativePrompt, negativeEngaged, restoredSampler, samplerModelKey, samplerOptions, samplerChoice, sdCaps, sdChoice, shiftControl, shiftValue, width, height, steps, effectiveGuidance, seed, batchSize, count, workflow, initImage, maskImage, strength, maskBlur, inpaintOnlyMasked, inpaintPadding, status?.supports_inpaint_only_masked, extendPct, extendSides, upscaleFactor, upscaleStrength, referenceImages, loras, loraCapable, controlnetCapable, controlnetEngaged, controlnetId, controlImage, controlType, controlStrength, ensureSrc, loadGallery, refreshStatus, unifiedEdit, multiImageEdit, localizedMode, localizedLayer, maxExtras, referenceResolution, conditioning, editSize, editSizing, sizeLimits]);
+ }, [external, allowOversized, livePreview, enhanceOn, upsamplerCapability, prompt, negativePrompt, negativeEngaged, restoredSampler, samplerModelKey, samplerOptions, samplerChoice, sdCaps, sdChoice, shiftControl, shiftValue, width, height, steps, effectiveGuidance, seed, batchSize, count, workflow, initImage, maskImage, strength, maskBlur, inpaintOnlyMasked, inpaintPadding, status?.supports_inpaint_only_masked, extendPct, extendSides, upscaleFactor, upscaleStrength, upscaleModel, upscaleModels, hires, hiresCapability, referenceImages, loras, loraCapable, controlnetCapable, controlnetEngaged, controlnetId, controlImage, controlType, controlStrength, ensureSrc, loadGallery, refreshStatus, unifiedEdit, multiImageEdit, localizedMode, localizedLayer, maxExtras, referenceResolution, conditioning, editSize, editSizing, sizeLimits]);
// Stop the in-flight generation. Latch FIRST, so a multi-run request stops even if the POST
// races the run that is already finishing.
@@ -6362,6 +6402,7 @@ export function ImagesPage({
step={0.05}
onChange={setUpscaleStrength}
/>
+ <UpscaleModelField models={upscaleModels} value={upscaleModel} onChange={setUpscaleModel} />
</>
)}
@@ -6931,6 +6972,11 @@ export function ImagesPage({
</Field>
)}
<ShiftField control={shiftControl} value={shiftValue} onChange={setShiftValue} />
+ {hiresVisible(hiresCapability, workflow) ? (
+ <HiresControls capability={hiresCapability} choice={hires} onChange={setHires} width={width} height={height} />
+ ) : !external && workflow === "create" && status?.hires_unavailable_reason ? (
+ <p className="pt-2 text-xs text-muted-foreground">{status.hires_unavailable_reason}</p>
+ ) : null}
<EmbeddingsField
family={status?.family}
enabled={embeddingsEnabled}
diff --git a/studio/frontend/src/features/images/lib/hires-choice.ts b/studio/frontend/src/features/images/lib/hires-choice.ts
new file mode 100644
index 00000000000..fb23f34054c
--- /dev/null
+++ b/studio/frontend/src/features/images/lib/hires-choice.ts
@@ -0,0 +1,290 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/** Hires fix (backend diffusion_hires.py). Upscaler labels match A1111's `Hires upscaler` so infotext maps back. */
+
+export interface HiresUpscalerOption {
+ id: string;
+ label: string;
+ kind: "latent" | "pixel" | "model";
+}
+
+export interface HiresCapability {
+ upscalers: HiresUpscalerOption[];
+ default_upscaler: string;
+ defaults: { scale: number; denoise: number };
+ max_side: number;
+ /** false = no separate Hires CFG (native engine); absent = supported. */
+ supports_guidance?: boolean;
+ /** The smallest denoise the engine takes (native: no upscale-only 0); absent = 0. */
+ min_denoise?: number;
+}
+
+/** A1111's Denoising strength slider and ComfyUI's KSampler denoise both step by 0.01. */
+export const HIRES_DENOISE_STEP = 0.01;
+
+export function hiresMinDenoise(cap: HiresCapability): number {
+ return finite(cap.min_denoise) ?? 0;
+}
+
+/** The smallest denoise for this choice: the latent upscaler always needs a refine pass (the backend refuses 0). */
+export function hiresMinDenoiseFor(choice: HiresChoice, cap: HiresCapability): number {
+ const latent = cap.upscalers.find((u) => u.id === effectiveUpscaler(choice, cap))?.kind === "latent";
+ return Math.max(hiresMinDenoise(cap), latent ? HIRES_DENOISE_STEP : 0);
+}
+
+export function hiresGuidanceSupported(cap: HiresCapability): boolean {
+ return cap.supports_guidance !== false;
+}
+
+export interface HiresRequest {
+ scale: number;
+ denoise: number;
+ steps?: number | null;
+ upscaler?: string | null;
+ guidance?: number | null;
+}
+
+export interface HiresChoice {
+ enabled: boolean;
+ scale: number;
+ denoise: number;
+ /** null = the base pass's steps. */
+ steps: number | null;
+ /** null = the capability's default upscaler. */
+ upscaler: string | null;
+ /** null = the base guidance. */
+ guidance: number | null;
+}
+
+export const HIRES_DEFAULT_SCALE = 1.5;
+export const HIRES_DEFAULT_DENOISE = 0.5;
+
+export const HIRES_OFF: HiresChoice = {
+ enabled: false,
+ scale: HIRES_DEFAULT_SCALE,
+ denoise: HIRES_DEFAULT_DENOISE,
+ steps: null,
+ upscaler: null,
+ guidance: null,
+};
+
+export function hiresVisible(cap: HiresCapability | null | undefined, workflow: string): cap is HiresCapability {
+ return Boolean(cap) && workflow === "create";
+}
+
+/** The refine size the backend renders: round(side * scale / 16) * 16, scaled down to fit `maxSide`. */
+export function hiresTargetSize(
+ width: number,
+ height: number,
+ scale: number,
+ maxSide = 2048,
+ multiple = 16,
+): { width: number; height: number } {
+ const tw = width * scale;
+ const th = height * scale;
+ const fit = Math.min(1, maxSide / Math.max(tw, th));
+ return {
+ width: Math.max(multiple, Math.round((tw * fit) / multiple) * multiple),
+ height: Math.max(multiple, Math.round((th * fit) / multiple) * multiple),
+ };
+}
+
+export function effectiveUpscaler(choice: HiresChoice, cap: HiresCapability): string {
+ const picked = choice.upscaler;
+ return picked && cap.upscalers.some((u) => u.id === picked) ? picked : cap.default_upscaler;
+}
+
+/** The request's `hires` field; undefined when off or not offered (so the request is unchanged). */
+export function hiresRequest(
+ choice: HiresChoice,
+ cap: HiresCapability | null | undefined,
+ workflow: string,
+): HiresRequest | undefined {
+ if (!choice.enabled || !hiresVisible(cap, workflow)) return undefined;
+ // Snap to the 0.01 grid (a typed 0.004 would otherwise be refused), never below the engine's minimum.
+ const denoise = clamp(Math.round(choice.denoise / HIRES_DENOISE_STEP) * HIRES_DENOISE_STEP, hiresMinDenoiseFor(choice, cap), 1);
+ return {
+ scale: choice.scale,
+ denoise: Number(denoise.toFixed(2)),
+ steps: choice.steps && choice.steps > 0 ? choice.steps : null,
+ upscaler: effectiveUpscaler(choice, cap),
+ guidance: hiresGuidanceSupported(cap) ? choice.guidance : null,
+ };
+}
+
+/** Whether the refine pass's own guidance (Hires CFG) engages a negative prompt the base guidance leaves off. */
+export function hiresEngagesNegative(
+ choice: HiresChoice,
+ cap: HiresCapability | null | undefined,
+ workflow: string,
+ minGuidance: number | null,
+): boolean {
+ const req = hiresRequest(choice, cap, workflow);
+ if (!req || req.denoise <= 0 || req.guidance === null || req.guidance === undefined) return false;
+ return minGuidance === null || req.guidance > minGuidance;
+}
+
+/** A recorded image whose Hires CFG ran with CFG on, so its negative prompt shaped the refine pass. */
+export function hiresRecordUsedNegative(r: HiresRecord): boolean {
+ return finite(r.hires_scale) !== undefined && (finite(r.hires_guidance) ?? 0) > 0;
+}
+
+/** The Upscale workflow's `upscale_model`: only an id the status still lists (the selector shows Lanczos otherwise). */
+export function upscaleModelRequest(
+ id: string | null | undefined,
+ models: Array<{ id: string }> | null | undefined,
+): string | undefined {
+ return id && models?.some((m) => m.id === id) ? id : undefined;
+}
+
+export interface HiresRecord {
+ hires_scale?: number | null;
+ hires_denoise?: number | null;
+ hires_steps?: number | null;
+ hires_upscaler?: string | null;
+ hires_guidance?: number | null;
+ hires_base_width?: number | null;
+ hires_base_height?: number | null;
+ width?: number;
+ height?: number;
+}
+
+const finite = (v: unknown): number | undefined =>
+ typeof v === "number" && Number.isFinite(v) ? v : undefined;
+const clamp = (n: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, n));
+
+export function hiresFromRecipe(r: HiresRecord): HiresChoice {
+ const scale = finite(r.hires_scale);
+ if (scale === undefined) return HIRES_OFF;
+ const denoise = finite(r.hires_denoise);
+ const steps = finite(r.hires_steps);
+ const guidance = finite(r.hires_guidance);
+ return {
+ enabled: true,
+ scale: clamp(scale, 1, 4),
+ denoise: denoise === undefined ? HIRES_DEFAULT_DENOISE : clamp(denoise, 0, 1),
+ steps: steps !== undefined && Number.isInteger(steps) && steps > 0 ? Math.min(steps, 100) : null,
+ upscaler: typeof r.hires_upscaler === "string" && r.hires_upscaler ? r.hires_upscaler : null,
+ guidance: guidance === undefined ? null : clamp(guidance, 0, 20),
+ };
+}
+
+/** The base-pass size a hires recipe restores into the Width / Height controls (the record keeps the output size). */
+export function hiresBaseSize(r: HiresRecord): { width: number; height: number } | null {
+ const w = finite(r.hires_base_width);
+ const h = finite(r.hires_base_height);
+ if (finite(r.hires_scale) === undefined || !w || !h) return null;
+ return { width: w, height: h };
+}
+
+export function matchHiresUpscaler(name: string, cap: HiresCapability): string | null {
+ const byId = cap.upscalers.find((u) => u.id === name);
+ if (byId) return byId.id;
+ const lower = name.trim().toLowerCase();
+ const byLabel = cap.upscalers.find((u) => u.label.toLowerCase() === lower);
+ if (byLabel) return byLabel.id;
+ // AUTOMATIC1111's "Latent", "Latent (bicubic)", ... all upscale the latents; Studio runs nearest-exact.
+ if (lower.startsWith("latent")) return cap.upscalers.find((u) => u.kind === "latent")?.id ?? null;
+ return null;
+}
+
+export function hiresNotApplied(choice: HiresChoice, cap: HiresCapability | null | undefined): string[] {
+ if (!choice.enabled) return [];
+ if (!cap) return [`Hires fix (${hiresSummary(choice)})`];
+ const notes: string[] = [];
+ if (choice.upscaler && matchHiresUpscaler(choice.upscaler, cap) === null)
+ notes.push(`Hires upscaler ${choice.upscaler} (not available; using ${labelOf(cap.default_upscaler, cap)})`);
+ if (choice.guidance !== null && !hiresGuidanceSupported(cap))
+ notes.push(`Hires CFG Scale ${choice.guidance} (not available on this engine; using the base guidance)`);
+ if (choice.denoise < hiresMinDenoise(cap))
+ notes.push(`Hires denoise ${choice.denoise} (this engine needs at least ${hiresMinDenoise(cap)})`);
+ else if (choice.denoise < hiresMinDenoiseFor(resolveRestoredHires(choice, cap), cap))
+ notes.push(`Hires denoise ${choice.denoise} (the latent upscaler needs a refine pass; using ${hiresMinDenoiseFor(resolveRestoredHires(choice, cap), cap)})`);
+ return notes;
+}
+
+export function resolveRestoredHires(choice: HiresChoice, cap: HiresCapability | null | undefined): HiresChoice {
+ if (!choice.enabled || !cap || !choice.upscaler) return choice;
+ return { ...choice, upscaler: matchHiresUpscaler(choice.upscaler, cap) };
+}
+
+function labelOf(id: string, cap?: HiresCapability | null): string {
+ return cap?.upscalers.find((u) => u.id === id)?.label ?? HIRES_UPSCALER_LABELS[id] ?? id.replace(/^local:/, "");
+}
+
+export const HIRES_UPSCALER_LABELS: Record<string, string> = {
+ latent: "Latent (nearest-exact)",
+ lanczos: "Lanczos",
+ realesrgan_x4plus: "R-ESRGAN 4x+",
+ realesrgan_x4plus_anime_6b: "R-ESRGAN 4x+ Anime6B",
+};
+
+/** "1.5x, denoise 0.5, 14 steps, Latent (nearest-exact)" for the Recipe popover. */
+export function hiresSummary(choice: HiresChoice, cap?: HiresCapability | null): string {
+ const parts = [`${choice.scale}x`, `denoise ${choice.denoise}`];
+ parts.push(choice.steps ? `${choice.steps} steps` : "base steps");
+ if (choice.upscaler) parts.push(labelOf(choice.upscaler, cap));
+ if (choice.guidance !== null) parts.push(`CFG ${choice.guidance}`);
+ return parts.join(", ");
+}
+
+/** A1111 hires keys -> recipe fields; mapped labels are removed from `fields`, the rest reported unapplied. */
+export function parseHiresInfotext(
+ fields: Record<string, string>,
+ denoise: number | undefined,
+ size: { width?: unknown; height?: unknown },
+): Record<string, unknown> {
+ const out: Record<string, unknown> = {};
+ const take = (label: string): string | undefined => {
+ const key = Object.keys(fields).find((k) => k.toLowerCase() === label);
+ if (key === undefined) return undefined;
+ const value = fields[key];
+ delete fields[key];
+ return value;
+ };
+ const num = (v: string | undefined) => {
+ if (v === undefined || v.trim() === "") return undefined;
+ const n = Number(v);
+ return Number.isFinite(n) ? n : undefined;
+ };
+ let scale = num(take("hires upscale"));
+ const resizeKey = Object.keys(fields).find((k) => k.toLowerCase() === "hires resize");
+ const steps = num(take("hires steps"));
+ const upscaler = take("hires upscaler");
+ const cfg = num(take("hires cfg scale"));
+ // `Hires resize: WxH` (A1111's explicit size; Studio writes it for a capped target) maps to the factor that
+ // reaches it from Size; the backend's own cap lands on the same size again.
+ const wh = resizeKey === undefined ? null : fields[resizeKey].trim().match(/^(\d+)\s*x\s*(\d+)$/i);
+ if (scale === undefined && wh && typeof size.width === "number" && typeof size.height === "number" && size.width > 0 && size.height > 0) {
+ const rw = Number(wh[1]);
+ const rh = Number(wh[2]);
+ const factor = Math.round(Math.max(rw / size.width, rh / size.height) * 100) / 100;
+ // Only a size one factor reproduces (Studio's own export); A1111 crops another aspect, which Studio cannot.
+ const reaches = (maxSide: number) => {
+ const t = hiresTargetSize(size.width as number, size.height as number, factor, maxSide);
+ return t.width === rw && t.height === rh;
+ };
+ if (factor >= 1 && factor <= 4 && (reaches(2048) || reaches(Math.max(rw, rh)))) {
+ scale = factor;
+ delete fields[resizeKey as string];
+ }
+ }
+ // Without a factor or a usable size, Studio cannot size the pass: leave it all unapplied.
+ if (scale === undefined) {
+ if (steps !== undefined) fields["Hires steps"] = String(steps);
+ if (upscaler !== undefined) fields["Hires upscaler"] = upscaler;
+ if (cfg !== undefined) fields["Hires CFG Scale"] = String(cfg);
+ return out;
+ }
+ out.hires_scale = scale;
+ out.hires_denoise = denoise ?? HIRES_DEFAULT_DENOISE;
+ if (steps !== undefined && Number.isInteger(steps) && steps > 0) out.hires_steps = steps;
+ if (upscaler) out.hires_upscaler = upscaler;
+ if (cfg !== undefined) out.hires_guidance = cfg;
+ if (typeof size.width === "number" && typeof size.height === "number") {
+ out.hires_base_width = size.width;
+ out.hires_base_height = size.height;
+ }
+ return out;
+}
diff --git a/studio/frontend/src/features/images/lib/image-metadata.ts b/studio/frontend/src/features/images/lib/image-metadata.ts
index 6f6b163a55e..41157611162 100644
--- a/studio/frontend/src/features/images/lib/image-metadata.ts
+++ b/studio/frontend/src/features/images/lib/image-metadata.ts
@@ -1,5 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+import { parseHiresInfotext } from "./hires-choice.ts";
import { SAMPLER_LABELS, SCHEDULE_LABELS } from "./sampler-choice.ts";
import type { SdControlsCapability } from "./sd-controls.ts";
@@ -827,12 +828,15 @@ export function parseA1111Parameters(text: string): ImportedRecipe | null {
notApplied.push(`${label}: ${value}`);
}
out.schedule_type ??= legacySchedule;
+ const hadHires = Object.keys(hires).length > 0;
+ // Maps Hires upscale / steps / upscaler / CFG Scale; whatever stays in `hires` is named as not applied.
+ if (hadHires) Object.assign(out, parseHiresInfotext(hires, typeof out.strength === "number" ? out.strength : undefined, { width: out.width, height: out.height }));
const hiresKeys = Object.keys(hires);
if (hiresKeys.length > 0) out.hires = hires;
// txt2img hires fix also writes a denoising strength; without it the strength means img2img,
// or inpaint when A1111 wrote its mask-only fields.
if (out.strength !== undefined) {
- if (hiresKeys.length > 0) delete out.strength;
+ if (hadHires) delete out.strength;
else
out.workflow ??=
out.mask_blur !== undefined ||
@@ -921,6 +925,14 @@ export interface RestorableRecipe {
mask_blur?: number;
inpaint_only_masked?: boolean;
inpaint_padding?: number;
+ upscale_model?: string | null;
+ hires_scale?: number;
+ hires_denoise?: number;
+ hires_steps?: number;
+ hires_upscaler?: string;
+ hires_guidance?: number;
+ hires_base_width?: number;
+ hires_base_height?: number;
}
export const APPLIED_RECIPE_KEYS = [
@@ -954,6 +966,14 @@ export const APPLIED_RECIPE_KEYS = [
"mask_blur",
"inpaint_only_masked",
"inpaint_padding",
+ "upscale_model",
+ "hires_scale",
+ "hires_denoise",
+ "hires_steps",
+ "hires_upscaler",
+ "hires_guidance",
+ "hires_base_width",
+ "hires_base_height",
] as const;
/** Known but not applied: loading a model or a ControlNet image stays the user's call. */
@@ -1261,9 +1281,33 @@ export function recipeSettings(
? r.inpaint_only_masked
: undefined,
inpaint_padding: bounded(r, "inpaint_padding"),
+ ...hiresRecipeFields(r),
};
}
+function hiresRecipeFields(r: ImportedRecipe): Partial<RestorableRecipe> {
+ const out: Partial<RestorableRecipe> = {};
+ const upscaleModel = str(r.upscale_model);
+ if (upscaleModel) out.upscale_model = upscaleModel;
+ const scale = clamp(num(r.hires_scale), 1, 4);
+ if (scale === undefined) return out;
+ out.hires_scale = scale;
+ out.hires_denoise = clamp(num(r.hires_denoise), 0, 1);
+ const steps = int(r.hires_steps);
+ if (steps !== undefined && steps > 0) out.hires_steps = Math.min(steps, 100);
+ const upscaler = str(r.hires_upscaler);
+ if (upscaler) out.hires_upscaler = upscaler;
+ const cfg = clamp(num(r.hires_guidance), 0, 20);
+ if (cfg !== undefined) out.hires_guidance = cfg;
+ const w = int(r.hires_base_width);
+ const h = int(r.hires_base_height);
+ if (w && h && w > 0 && h > 0) {
+ out.hires_base_width = w;
+ out.hires_base_height = h;
+ }
+ return out;
+}
+
const LORA_EXTENSIONS = /\.(safetensors|gguf|ckpt|pt|bin)$/i;
const loraKey = (name: string) =>
name
diff --git a/studio/frontend/tests/image-a1111-infotext-keys.test.ts b/studio/frontend/tests/image-a1111-infotext-keys.test.ts
index 40dc69b79e5..d9bb65bcc5a 100644
--- a/studio/frontend/tests/image-a1111-infotext-keys.test.ts
+++ b/studio/frontend/tests/image-a1111-infotext-keys.test.ts
@@ -47,7 +47,8 @@ const KEYS: Array<[string, string, Handling]> = [
["Version", "v1.10.1", "ignored"],
["User", "someone", "ignored"],
// extra_generation_params (modules, scripts, extensions-builtin)
- ["Hires upscale", "2", "reported"],
+ // Maps onto Hires fix (lib/hires-choice.ts); the others need a factor beside them, so alone they are reported.
+ ["Hires upscale", "2", "applied"],
["Hires steps", "10", "reported"],
["Hires upscaler", "Latent", "reported"],
["Hires resize", "1024x1024", "reported"],
diff --git a/studio/frontend/tests/image-paste-parameters.test.ts b/studio/frontend/tests/image-paste-parameters.test.ts
index 416ad5d2483..cc03cf16207 100644
--- a/studio/frontend/tests/image-paste-parameters.test.ts
+++ b/studio/frontend/tests/image-paste-parameters.test.ts
@@ -85,7 +85,7 @@ test("the fields reader unquotes, keeps JSON whole and skips non-fields like re_
]);
});
-test("Clip skip, CFG rescale, variation seed and hires keys are read and named as not applied", () => {
+test("Clip skip, CFG rescale and variation seed are named as not applied; hires keys are read", () => {
const r = parseA1111Parameters(
"a cat\nSteps: 25, Sampler: Euler a, CFG scale: 5, Seed: 1, Size: 1024x1024, Clip skip: 3, CFG Rescale: 0.7, Variation seed: 99, Variation seed strength: 0.3, Hires upscale: 1.5, Hires steps: 10, Hires upscaler: R-ESRGAN 4x+, Denoising strength: 0.4, VAE: sdxl_vae.safetensors, ADetailer model: face_yolov8n.pt",
);
@@ -94,18 +94,18 @@ test("Clip skip, CFG rescale, variation seed and hires keys are read and named a
assert.equal(r.cfg_rescale, 0.7);
assert.equal(r.variation_seed, 99);
assert.equal(r.variation_strength, 0.3);
- assert.deepEqual(r.hires, {
- "Hires upscale": "1.5",
- "Hires steps": "10",
- "Hires upscaler": "R-ESRGAN 4x+",
- });
+ // The hires keys map onto Hires fix; the Denoising strength beside them is its denoise, not img2img.
+ assert.equal(r.hires, undefined);
+ assert.equal(r.hires_scale, 1.5);
+ assert.equal(r.hires_steps, 10);
+ assert.equal(r.hires_upscaler, "R-ESRGAN 4x+");
+ assert.equal(r.hires_denoise, 0.4);
assert.equal(r.strength, undefined);
assert.equal(r.workflow, undefined);
assert.deepEqual(importNotApplied(r), [
"Clip skip 3",
"CFG rescale 0.7",
"variation seed 99 (strength 0.3)",
- "hires fix (Hires upscale: 1.5, Hires steps: 10, Hires upscaler: R-ESRGAN 4x+)",
"VAE: sdxl_vae.safetensors",
"ADetailer model: face_yolov8n.pt",
]);
diff --git a/studio/frontend/tests/image-restore-settings-size.test.ts b/studio/frontend/tests/image-restore-settings-size.test.ts
index e2dc21f3c6d..82d5c86ac4c 100644
--- a/studio/frontend/tests/image-restore-settings-size.test.ts
+++ b/studio/frontend/tests/image-restore-settings-size.test.ts
@@ -85,8 +85,10 @@ test("restoreSettings puts the record through restorableSize", () => {
const body = restoreSettingsBody();
assert.match(
body,
- /restorableSize\(image\.width, image\.height, image\.workflow, sizeLimits\)/,
+ /restorableSize\(base\.width, base\.height, image\.workflow, sizeLimits\)/,
);
+ // A Hires fix record restores its base pass; every other record its own size.
+ assert.match(body, /const base = hiresBaseSize\(image\) \?\? \{ width: image\.width, height: image\.height \}/);
assert.doesNotMatch(
body,
/setWidth\(image\.width\)|setHeight\(image\.height\)/,
@@ -96,7 +98,7 @@ test("restoreSettings puts the record through restorableSize", () => {
test("a restore that had to move the size says so", () => {
const body = restoreSettingsBody();
- assert.match(body, /restored\.width !== image\.width/);
+ assert.match(body, /restored\.width !== base\.width/);
assert.match(body, /Size scaled to \$\{restored\.width\}/);
});
diff --git a/studio/frontend/tests/images-hires.test.ts b/studio/frontend/tests/images-hires.test.ts
new file mode 100644
index 00000000000..f7ba8a1e41c
--- /dev/null
+++ b/studio/frontend/tests/images-hires.test.ts
@@ -0,0 +1,278 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import {
+ HIRES_OFF,
+ hiresBaseSize,
+ hiresFromRecipe,
+ hiresNotApplied,
+ hiresRequest,
+ hiresSummary,
+ hiresTargetSize,
+ hiresEngagesNegative,
+ hiresMinDenoiseFor,
+ hiresRecordUsedNegative,
+ hiresVisible,
+ matchHiresUpscaler,
+ resolveRestoredHires,
+ upscaleModelRequest,
+ type HiresCapability,
+} from "../src/features/images/lib/hires-choice.ts";
+import {
+ importNotApplied,
+ parseA1111Parameters,
+ recipeSettings,
+ unknownRecipeKeys,
+} from "../src/features/images/lib/image-metadata.ts";
+
+const SDXL: HiresCapability = {
+ upscalers: [
+ { id: "latent", label: "Latent (nearest-exact)", kind: "latent" },
+ { id: "lanczos", label: "Lanczos", kind: "pixel" },
+ { id: "realesrgan_x4plus", label: "R-ESRGAN 4x+", kind: "model" },
+ { id: "realesrgan_x4plus_anime_6b", label: "R-ESRGAN 4x+ Anime6B", kind: "model" },
+ ],
+ default_upscaler: "latent",
+ defaults: { scale: 1.5, denoise: 0.5 },
+ max_side: 2048,
+};
+const FLUX: HiresCapability = {
+ ...SDXL,
+ upscalers: SDXL.upscalers.filter((u) => u.kind !== "latent"),
+ default_upscaler: "lanczos",
+};
+const DEFAULTS = { width: 1024, height: 1024, steps: 20, guidance: 5 };
+
+test("the control shows in Create only, and only with a capability", () => {
+ assert.equal(hiresVisible(SDXL, "create"), true);
+ assert.equal(hiresVisible(SDXL, "img2img"), false);
+ assert.equal(hiresVisible(SDXL, "upscale"), false);
+ assert.equal(hiresVisible(null, "create"), false);
+ assert.equal(hiresVisible(undefined, "create"), false);
+});
+
+test("off (the default) or hidden sends nothing", () => {
+ assert.equal(hiresRequest(HIRES_OFF, SDXL, "create"), undefined);
+ const on = { ...HIRES_OFF, enabled: true };
+ assert.equal(hiresRequest(on, null, "create"), undefined);
+ assert.equal(hiresRequest(on, SDXL, "edit"), undefined);
+ assert.deepEqual(hiresRequest(on, SDXL, "create"), {
+ scale: 1.5,
+ denoise: 0.5,
+ steps: null,
+ upscaler: "latent",
+ guidance: null,
+ });
+});
+
+test("latent is offered only where listed: a pick the model lacks falls back to its default", () => {
+ const choice = { ...HIRES_OFF, enabled: true, upscaler: "latent" };
+ assert.equal(hiresRequest(choice, FLUX, "create")?.upscaler, "lanczos");
+ assert.equal(matchHiresUpscaler("Latent", FLUX), null);
+ assert.equal(matchHiresUpscaler("Latent (bicubic antialiased)", SDXL), "latent");
+ assert.equal(matchHiresUpscaler("r-esrgan 4x+", FLUX), "realesrgan_x4plus");
+ assert.equal(matchHiresUpscaler("4x_foolhardy_Remacri", SDXL), null);
+});
+
+test("the size preview matches the backend rounding and cap", () => {
+ assert.deepEqual(hiresTargetSize(832, 1216, 1.5), { width: 1248, height: 1824 });
+ assert.deepEqual(hiresTargetSize(768, 768, 1.5), { width: 1152, height: 1152 });
+ // 1216 * 2 = 2432 > 2048: both sides scale by 2048 / 2432, then round to 16.
+ assert.deepEqual(hiresTargetSize(832, 1216, 2), { width: 1408, height: 2048 });
+});
+
+test("a gallery record restores the choice and the base size", () => {
+ const record = {
+ width: 1248,
+ height: 1824,
+ hires_scale: 1.5,
+ hires_denoise: 0.5,
+ hires_steps: 14,
+ hires_upscaler: "realesrgan_x4plus",
+ hires_guidance: null,
+ hires_base_width: 832,
+ hires_base_height: 1216,
+ };
+ assert.deepEqual(hiresFromRecipe(record), {
+ enabled: true,
+ scale: 1.5,
+ denoise: 0.5,
+ steps: 14,
+ upscaler: "realesrgan_x4plus",
+ guidance: null,
+ });
+ assert.deepEqual(hiresBaseSize(record), { width: 832, height: 1216 });
+ assert.equal(hiresFromRecipe({ width: 1024, height: 1024 }), HIRES_OFF);
+ assert.equal(hiresBaseSize({ width: 1024, height: 1024 }), null);
+ assert.equal(hiresSummary(hiresFromRecipe(record)), "1.5x, denoise 0.5, 14 steps, R-ESRGAN 4x+");
+});
+
+test("pasted AUTOMATIC1111 hires infotext round-trips into the Hires fix settings", () => {
+ const r = parseA1111Parameters(
+ "a castle\nSteps: 28, Sampler: Euler a, CFG scale: 7, Seed: 1, Size: 832x1216, Model: x, Denoising strength: 0.5, Hires upscale: 1.5, Hires steps: 14, Hires upscaler: Latent (nearest-exact)",
+ );
+ assert.ok(r);
+ assert.equal(r.strength, undefined);
+ assert.equal(r.workflow, undefined);
+ assert.deepEqual(unknownRecipeKeys(r), []);
+ assert.deepEqual(importNotApplied(r), []);
+ const settings = recipeSettings(r, DEFAULTS);
+ assert.equal(settings.width, 832);
+ assert.equal(settings.height, 1216);
+ const choice = resolveRestoredHires(hiresFromRecipe(settings), SDXL);
+ assert.deepEqual(choice, {
+ enabled: true,
+ scale: 1.5,
+ denoise: 0.5,
+ steps: 14,
+ upscaler: "latent",
+ guidance: null,
+ });
+ assert.deepEqual(hiresBaseSize(settings), { width: 832, height: 1216 });
+ assert.deepEqual(hiresNotApplied(choice, SDXL), []);
+ assert.deepEqual(hiresRequest(choice, SDXL, "create"), {
+ scale: 1.5,
+ denoise: 0.5,
+ steps: 14,
+ upscaler: "latent",
+ guidance: null,
+ });
+});
+
+test("an R-ESRGAN line maps to the model upscaler; Hires CFG Scale to the hires guidance", () => {
+ const r = parseA1111Parameters(
+ "x\nSteps: 20, Seed: 2, Size: 1024x1024, Denoising strength: 0.4, Hires upscale: 2, Hires upscaler: R-ESRGAN 4x+, Hires CFG Scale: 4",
+ );
+ assert.ok(r);
+ const choice = resolveRestoredHires(hiresFromRecipe(recipeSettings(r, DEFAULTS)), FLUX);
+ assert.equal(choice.upscaler, "realesrgan_x4plus");
+ assert.equal(choice.denoise, 0.4);
+ assert.equal(choice.scale, 2);
+ assert.equal(choice.steps, null);
+ assert.equal(choice.guidance, 4);
+});
+
+test("an unknown upscaler or a model without Hires fix is reported as not applied", () => {
+ const r = parseA1111Parameters(
+ "x\nSteps: 20, Seed: 2, Size: 1024x1024, Denoising strength: 0.4, Hires upscale: 2, Hires upscaler: 4x_foolhardy_Remacri",
+ );
+ assert.ok(r);
+ const restored = hiresFromRecipe(recipeSettings(r, DEFAULTS));
+ assert.deepEqual(hiresNotApplied(restored, SDXL), [
+ "Hires upscaler 4x_foolhardy_Remacri (not available; using Latent (nearest-exact))",
+ ]);
+ assert.equal(resolveRestoredHires(restored, SDXL).upscaler, null);
+ assert.deepEqual(hiresNotApplied(restored, null), [
+ "Hires fix (2x, denoise 0.4, base steps, 4x_foolhardy_Remacri)",
+ ]);
+ const resize = parseA1111Parameters("x\nSteps: 20, Seed: 2, Hires resize: 1024x1024, Hires sampler: Euler");
+ assert.ok(resize);
+ assert.deepEqual(importNotApplied(resize), ["hires fix (Hires resize: 1024x1024, Hires sampler: Euler)"]);
+});
+
+test("a Studio recipe's Hires fields and upscale model pass the import type checks", () => {
+ const settings = recipeSettings(
+ {
+ prompt: "p",
+ width: 1248,
+ height: 1824,
+ hires_scale: 9,
+ hires_denoise: 0.5,
+ hires_steps: 14,
+ hires_upscaler: "lanczos",
+ hires_base_width: 832,
+ hires_base_height: 1216,
+ upscale_model: "realesrgan_x4plus",
+ },
+ DEFAULTS,
+ );
+ assert.equal(settings.hires_scale, 4);
+ assert.equal(settings.hires_upscaler, "lanczos");
+ assert.equal(settings.upscale_model, "realesrgan_x4plus");
+ assert.deepEqual(hiresBaseSize(settings), { width: 832, height: 1216 });
+});
+
+test("the native capability drops Hires CFG and upscale-only from the request", () => {
+ const NATIVE: HiresCapability = { ...FLUX, supports_guidance: false, min_denoise: 0.01 };
+ const choice = { ...HIRES_OFF, enabled: true, denoise: 0, guidance: 4 };
+ assert.deepEqual(hiresRequest(choice, NATIVE, "create"), {
+ scale: 1.5,
+ denoise: 0.01,
+ steps: null,
+ upscaler: "lanczos",
+ guidance: null,
+ });
+ assert.deepEqual(hiresNotApplied(choice, NATIVE), [
+ "Hires CFG Scale 4 (not available on this engine; using the base guidance)",
+ "Hires denoise 0 (this engine needs at least 0.01)",
+ ]);
+ // The diffusers capability keeps both, and a typed value snaps to the 0.01 grid.
+ assert.equal(hiresRequest(choice, FLUX, "create")?.guidance, 4);
+ assert.equal(hiresRequest(choice, FLUX, "create")?.denoise, 0);
+ assert.equal(hiresRequest({ ...choice, denoise: 0.004 }, FLUX, "create")?.denoise, 0);
+ assert.equal(hiresRequest({ ...choice, denoise: 0.356 }, FLUX, "create")?.denoise, 0.36);
+});
+
+test("a model upscaler is sent only while the status still lists it", () => {
+ const models = [{ id: "realesrgan_x4plus", label: "R-ESRGAN 4x+", scale: 4 }];
+ assert.equal(upscaleModelRequest("realesrgan_x4plus", models), "realesrgan_x4plus");
+ assert.equal(upscaleModelRequest("local:gone", models), undefined);
+ assert.equal(upscaleModelRequest("realesrgan_x4plus", []), undefined);
+ assert.equal(upscaleModelRequest("realesrgan_x4plus", undefined), undefined);
+ assert.equal(upscaleModelRequest(null, models), undefined);
+});
+
+test("a capped target exported as Hires resize restores to the factor that reaches it", () => {
+ const r = parseA1111Parameters(
+ "x\nSteps: 20, Seed: 2, Size: 1536x1024, Denoising strength: 0.5, Hires resize: 2048x1360, Hires upscaler: Lanczos",
+ );
+ assert.ok(r);
+ assert.deepEqual(importNotApplied(r), []);
+ const settings = recipeSettings(r, DEFAULTS);
+ const choice = hiresFromRecipe(settings);
+ assert.equal(choice.scale, 1.33);
+ assert.deepEqual(hiresTargetSize(1536, 1024, choice.scale), { width: 2048, height: 1360 });
+ assert.deepEqual(hiresBaseSize(settings), { width: 1536, height: 1024 });
+});
+
+test("the latent upscaler never sends upscale-only denoise 0", () => {
+ const zero = { ...HIRES_OFF, enabled: true, denoise: 0 };
+ assert.equal(hiresMinDenoiseFor(zero, SDXL), 0.01); // SDXL's default upscaler is latent
+ assert.equal(hiresRequest(zero, SDXL, "create")?.denoise, 0.01);
+ assert.equal(hiresMinDenoiseFor({ ...zero, upscaler: "lanczos" }, SDXL), 0);
+ assert.equal(hiresRequest({ ...zero, upscaler: "lanczos" }, SDXL, "create")?.denoise, 0);
+ assert.deepEqual(hiresNotApplied(zero, SDXL), [
+ "Hires denoise 0 (the latent upscaler needs a refine pass; using 0.01)",
+ ]);
+});
+
+test("a Hires resize no single factor reproduces stays not applied", () => {
+ for (const line of [
+ "Size: 512x512, Denoising strength: 0.5, Hires resize: 1024x768", // A1111 crops to another aspect
+ "Size: 512x512, Denoising strength: 0.5, Hires resize: 256x256", // below 1x
+ "Size: 512x512, Denoising strength: 0.5, Hires resize: 4096x4096", // above 4x and the size cap
+ ]) {
+ const r = parseA1111Parameters(`x\nSteps: 20, Seed: 2, ${line}`);
+ assert.ok(r);
+ assert.equal(hiresFromRecipe(recipeSettings(r, DEFAULTS)).enabled, false, line);
+ assert.equal(importNotApplied(r).length, 1, line);
+ assert.match(importNotApplied(r)[0], /Hires resize/, line);
+ }
+});
+
+test("Hires CFG that turns CFG on engages and restores the negative prompt", () => {
+ const on = { ...HIRES_OFF, enabled: true, upscaler: "lanczos", guidance: 5 };
+ assert.equal(hiresEngagesNegative(on, FLUX, "create", 1), true);
+ assert.equal(hiresEngagesNegative({ ...on, guidance: 1 }, FLUX, "create", 1), false);
+ assert.equal(hiresEngagesNegative({ ...on, guidance: null }, FLUX, "create", 1), false);
+ assert.equal(hiresEngagesNegative({ ...on, denoise: 0 }, FLUX, "create", 1), false); // no refine pass
+ assert.equal(hiresEngagesNegative({ ...on, enabled: false }, FLUX, "create", 1), false);
+ assert.equal(hiresEngagesNegative(on, { ...FLUX, supports_guidance: false }, "create", 1), false);
+ assert.equal(hiresEngagesNegative(on, FLUX, "img2img", 1), false);
+ assert.equal(hiresRecordUsedNegative({ hires_scale: 1.5, hires_guidance: 5 }), true);
+ assert.equal(hiresRecordUsedNegative({ hires_scale: 1.5, hires_guidance: null }), false);
+ assert.equal(hiresRecordUsedNegative({ hires_guidance: 5 }), false);
+});