Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: tile the VAE instead of refusing oversized upscales, and in-app remedies for image refusals (#11798)
Daniel Hanac1c4da4d06f
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.pyindex 5c35347921d..a85c22d786d 100644--- a/studio/backend/core/inference/diffusion.py+++ b/studio/backend/core/inference/diffusion.py@@ -98,10 +98,12 @@ from .diffusion_krea2 import KREA2_FAMILY_NAME, load_krea2_pipelinefrom .diffusion_memory import (MEMORY_MODE_BALANCED,MEMORY_MODE_LOW_VRAM,+ ACTIVATION_TILE,DeviceMemory,OFFLOAD_NONE,OFFLOAD_STREAMING,apply_memory_plan,+ engage_vae_tiling,estimate_gguf_resident_mib,estimate_image_runtime_mib,estimate_safetensors_dense_mib,@@ -119,6 +121,9 @@ from .diffusion_memory import (settled_snapshot_device_memory,snapshot_device_memory,unified_memory_shortfall_message,+ vae_tile_side,+ vae_can_slice,+ vae_is_sliced,)from .diffusion_torchao_patches import install_torchao_int_mm_patchfrom .diffusion_speed import (@@ -144,6 +149,7 @@ from .diffusion_speed import (from .diffusion_attention import (apply_attention_backend,normalize_attention_backend,+ sdpa_math_only,select_attention_backend,_ensure_attention_backend_installed,)@@ -1496,6 +1502,17 @@ def _dense_candidate_is_prequant(return False+def _quadratic_attention(target: Any, engaged_backend: Optional[str] = None) -> bool:+ """Whether attention can only run on SDPA math (quadratic memory); False when unknown.+ Any engaged non-native backend is a fused kernel, so the SDPA probe only speaks for native."""+ if engaged_backend is not None and str(engaged_backend) != "native":+ return False+ try:+ return bool(sdpa_math_only(target))+ except Exception: # noqa: BLE001 - a broken probe must never block a generation+ return False++def _activation_guard_batch(chunks: Sequence[Sequence[Any]]) -> int:"""The batch size the generate-time activation guard budgets for.@@ -7647,6 +7664,7 @@ class DiffusionBackend:controlnet: Optional[tuple[str, str, str, float, float, float]] = None,# load_identity() of the caller's status() read; refuse rather than run a different load (#9448)expected_load: Optional[LoadIdentity] = None,+ allow_oversized: bool = False,) -> dict[str, Any]:import torchfrom PIL import Image@@ -7667,6 +7685,7 @@ class DiffusionBackend:# Publish an active (step 0) state before the slow pre-denoise setup so a reload mount probe does not# read idle.self._gen = _GenState(total_steps = steps)+ restore_vae: Optional[Callable[[], None]] = Nonetry:self._state_device_target(state)# The local `state` ref keeps the pipe alive even if unload() nulls _state. Resolve the per-image@@ -7986,15 +8005,14 @@ class DiffusionBackend:workflow, init_pil, width, height, fam)guard_batch = _activation_guard_batch(chunks)- raise_on_image_activation_shortfall(+ guard_target = self._state_device_target(state)+ guard_kwargs = dict(# NOT the settled snapshot the load uses: that one calls empty_cache(), which is right once# per load but wrong on a per-generation path, since it releases every cached block and the# next forward re-cudaMallocs all of its activations. This variant credits the same# reclaimable bytes back arithmetically instead, so a warm allocator does not read as a full# card.- device_memory = reclaimable_snapshot_device_memory(- self._state_device_target(state)- ),+ device_memory = reclaimable_snapshot_device_memory(guard_target),width = guard_width,height = guard_height,batch_size = guard_batch,@@ -8014,8 +8032,31 @@ class DiffusionBackend:if ref_resolution is not Noneelse 0),+ vae_tile_side = vae_tile_side(getattr(pipe, "vae", None)),+ vae_sliced = vae_can_slice(getattr(pipe, "vae", None)),+ quadratic_attention = _quadratic_attention(+ guard_target, getattr(state, "attention_backend", None)+ ),+ allow_oversized = allow_oversized,logger = logger,)+ verdict = raise_on_image_activation_shortfall(**guard_kwargs)+ if verdict.action == ACTIVATION_TILE:+ restore_vae, vae_tiled = engage_vae_tiling(pipe, logger = logger)+ if not vae_tiled and not verdict.overridden:+ # Passed only because it would be tiled; tiling failed, so refuse on the untiled figure.+ raise_on_image_activation_shortfall(+ **{**guard_kwargs, "vae_tile_side": None}+ )+ elif (+ guard_batch > 1+ and guard_kwargs["vae_sliced"]+ and not verdict.overridden+ and not vae_is_sliced(getattr(pipe, "vae", None))+ ):+ raise_on_image_activation_shortfall(+ **{**guard_kwargs, "vae_sliced": False}+ )except ValueError:raise # the refusal itself: the route turns this into a 400 with the reasonexcept Exception as exc: # noqa: BLE001 - fail OPEN on a broken probe@@ -8238,6 +8279,8 @@ class DiffusionBackend:"localized_edit": localized_edit.mode if localized_edit is not None else None,}finally:+ if restore_vae is not None:+ restore_vae()with self._generation_cancel_lock:if self._active_generate_cancel is cancel:self._active_generate_cancel = Nonediff --git a/studio/backend/core/inference/diffusion_families.py b/studio/backend/core/inference/diffusion_families.pyindex 5407dd6afa1..9b68946f529 100644--- a/studio/backend/core/inference/diffusion_families.py+++ b/studio/backend/core/inference/diffusion_families.py@@ -1330,6 +1330,18 @@ _DIFFUSERS_MAIN_COMMIT_RE = re.compile()+# Leads every refusal: a desktop install has no terminal, so pip spellings come second.+DIFFUSERS_UPDATE_REMEDY = (+ "Update Unsloth to install it (in the desktop app: Settings, Check for updates; from a "+ "terminal: unsloth studio update), then restart Unsloth."+)+DIFFUSERS_MAIN_RESTART_REMEDY = (+ "Restart Unsloth: on start it installs this pinned build by itself when it can reach "+ "github.com. If that still fails, update Unsloth (in the desktop app: Settings, Check for "+ "updates)."+)++def _diffusers_main_archive_remedy() -> str:"""A remedy line a reader can actually run, naming the commit this build wants.@@ -1346,8 +1358,9 @@ def _diffusers_main_archive_remedy() -> str:cannot name the SHA."""generic = (- "Re-run the Unsloth installer (leaving UNSLOTH_DIFFUSERS_MAIN unset), which installs it "- "from a zip archive when git is missing."+ f"{DIFFUSERS_MAIN_RESTART_REMEDY} On a pip or server install, re-run the Unsloth installer "+ "(leaving UNSLOTH_DIFFUSERS_MAIN unset), which installs it from a zip archive when git is "+ "missing.")try:text = _DIFFUSERS_MAIN_PIN.read_text(encoding = "utf-8-sig")@@ -1365,7 +1378,7 @@ def _diffusers_main_archive_remedy() -> str:f"{found.group('commit').lower()}.zip")return (- f"{generic} To install it by hand with no git at all: "+ f"{generic} To install it by hand from a terminal with no git at all: "f'pip install "diffusers @ {url}"')return generic@@ -1378,7 +1391,8 @@ def _too_old_message(pipeline_class: str, family_name: str, installed: str) -> sif minimum is None:return (f"'{family_name}' needs a newer diffusers ({pipeline_class}); this environment has "- f"diffusers {installed}. Upgrade with: pip install -U diffusers."+ f"diffusers {installed}. {DIFFUSERS_UPDATE_REMEDY} On a plain pip install: "+ "pip install -U diffusers.")if minimum in _UNRELEASED_MIN_DIFFUSERS:remedy = _diffusers_main_archive_remedy()@@ -1386,10 +1400,12 @@ def _too_old_message(pipeline_class: str, family_name: str, installed: str) -> sf"'{family_name}' needs diffusers >= {minimum} ({pipeline_class}), which has not been "f"released yet; this environment has diffusers {installed}. Unsloth installs a pinned ""build of diffusers main for this and that build is not here, which almost always "- "means the install had no working git (run: git --version) or could not reach "+ "means the install had no working git (check with: git --version) or could not reach "f"github.com. {remedy}")- remedy = f"Upgrade with: pip install -U 'diffusers>={minimum}'."+ remedy = (+ f"{DIFFUSERS_UPDATE_REMEDY} On a plain pip install: pip install -U 'diffusers>={minimum}'."+ )if needs_py310:remedy += (f" diffusers dropped Python 3.9 in {_DIFFUSERS_DROPPED_PY39}, so that release needs "@@ -1482,7 +1498,8 @@ def assert_pipeline_class_available(if strict:raise ValueError(f"'{family_name}' needs diffusers ({pipeline_class}), which this environment "- f"cannot import: {exc}. Install or repair it with: pip install -U diffusers."+ f"cannot import: {exc}. {DIFFUSERS_UPDATE_REMEDY} On a plain pip install, repair it "+ "with: pip install -U diffusers.") from Nonereturndiff --git a/studio/backend/core/inference/diffusion_krea2.py b/studio/backend/core/inference/diffusion_krea2.pyindex b5b2af06a2b..69a9346d659 100644--- a/studio/backend/core/inference/diffusion_krea2.py+++ b/studio/backend/core/inference/diffusion_krea2.py@@ -192,10 +192,11 @@ def load_krea2_pipeline(# diffusers gained Krea2Pipeline in 0.39; on an older install the getattr chain below dies with a bare# AttributeError, so fail first with the fix.if not hasattr(diffusers, "Krea2Pipeline"):+ from .diffusion_families import DIFFUSERS_UPDATE_REMEDYraise RuntimeError(f"Krea 2 needs diffusers >= 0.39.0 (Krea2Pipeline); this environment has "f"diffusers {getattr(diffusers, '__version__', 'unknown')}. "- f"Upgrade with: pip install -U diffusers"+ f"{DIFFUSERS_UPDATE_REMEDY} On a plain pip install: pip install -U diffusers")token = hf_token or Nonediff --git a/studio/backend/core/inference/diffusion_memory.py b/studio/backend/core/inference/diffusion_memory.pyindex 24a6018f23a..d058f05ded3 100644--- a/studio/backend/core/inference/diffusion_memory.py+++ b/studio/backend/core/inference/diffusion_memory.py@@ -849,13 +849,7 @@ def estimate_image_runtime_mib(batch = max(1, int(batch_size or 1))cond = max(0, int(condition_pixels or 0))pixel_scale = ((w * h + cond) * batch) / float(DEFAULT_IMAGE_WIDTH * DEFAULT_IMAGE_HEIGHT)- fam = (family or "").lower()- multiplier = 1.0- if "edit" in fam:- multiplier *= 1.35- if "turbo" in fam or "distilled" in fam or "schnell" in fam:- multiplier *= 0.85- return max(1024, int(8192 * max(0.25, pixel_scale) * multiplier))+ return max(1024, int(8192 * max(0.25, pixel_scale) * _family_activation_multiplier(family)))def estimate_video_runtime_mib(@@ -973,9 +967,10 @@ def unified_memory_shortfall_message(plan: Any, *, family: Optional[str] = None)f"about {int(budget) / 1024:.0f} GB is usable on this device ({free_note}). This device ""has unified memory, so the CPU and GPU share one pool: offloading weights to the CPU ""frees nothing, and the operating system stops an oversized load outright instead of "- "reporting an out-of-memory error. Use a smaller or more quantized model, free memory "- f"by closing other applications, or set {UNIFIED_OVERSIZE_ENV}=1 to attempt the load "- "anyway."+ "reporting an out-of-memory error. Use a smaller or more quantized model (for example a "+ "lower GGUF quant), or free memory by closing other applications. (Server "+ f"installs that know this estimate is wrong can set {UNIFIED_OVERSIZE_ENV}=1 to attempt "+ "the load anyway.)")@@ -1731,9 +1726,26 @@ def _apply_group_offload(# then generates at whatever size the sliders say, so ``_plan_memory`` budgets the 1024x1024 default. That is the# right call for PLACEMENT, but it means a request for a much larger frame is never checked against anything, so this# re-checks per generation with the real dimensions. Opt-in escape hatch, mirroring the load-time one: the activation-# estimate is coarse, so an operator who believes it is wrong keeps a way through.+# estimate is coarse, so an operator who believes it is wrong keeps a way through. Also sent per request+# (``allow_oversized``): a desktop install has no terminal.OVERSIZED_GENERATE_ENV = "UNSLOTH_DIFFUSION_ALLOW_OVERSIZED_GENERATE"+# Must match the Images page setting label (frontend memory-refusal.ts).+OVERSIZED_GENERATE_SETTING_LABEL = "Allow oversized generations"++# Exposed through CORS in main.py: the desktop app is cross-origin (tauri://localhost).+IMAGE_REFUSAL_HEADER = "X-Unsloth-Refusal"+IMAGE_REFUSAL_MEMORY_ESTIMATE = "memory-estimate"++ACTIVATION_RUN = "run"+ACTIVATION_TILE = "tile"+ACTIVATION_REFUSE = "refuse"++# Denoiser MiB per output megapixel per image; linear only for sub-quadratic (flash / mem-efficient) attention.+DENOISE_MIB_PER_MEGAPIXEL = 1024++DEFAULT_VAE_TILE_SIDE = 1024+class ImageActivationShortfallError(ValueError):"""This generation's activations cannot fit the free device budget.@@ -1741,15 +1753,193 @@ class ImageActivationShortfallError(ValueError):A ValueError subclass so ``/images/generate``'s existing mapping still turns it into a 400with the reason. The distinct type is what lets the OpenAI-compatible route, whose boundarysanitises every other exception into a bare 500, recognise the one message here that is- written FOR the caller and hand it back instead of "Image generation failed."+ written FOR the caller and hand it back instead of "Image generation failed." The Images page+ recognises it too (the route tags the 400), so it can offer a retry with the override."""+@dataclass(frozen = True)+class ImageActivationVerdict:+ """Generate-time guard decision (MiB figures); ACTIVATION_TILE = tile and slice the VAE for this call."""++ action: str+ message: Optional[str] = None+ needed_mib: Optional[int] = None+ tiled_needed_mib: Optional[int] = None+ budget_mib: Optional[int] = None+ overridden: bool = False++def _oversized_generate_override() -> bool:return os.environ.get(OVERSIZED_GENERATE_ENV, "").strip().lower() in ("1", "true", "yes", "on")-def image_activation_shortfall_message(+def vae_tile_side(vae: Any) -> Optional[int]:+ """The pixel side a VAE tiles at, or None when it cannot tile at all."""+ if vae is None or not callable(getattr(vae, "enable_tiling", None)):+ return None+ sides: list[int] = []+ for attr in ("tile_sample_min_size", "tile_sample_min_height", "tile_sample_min_width"):+ value = getattr(vae, attr, None)+ values = value if isinstance(value, (list, tuple)) else (value,)+ for item in values:+ if isinstance(item, bool):+ continue+ try:+ side = int(item)+ except (TypeError, ValueError):+ continue+ if side > 0:+ sides.append(side)+ if not sides:+ return DEFAULT_VAE_TILE_SIDE+ return max(64, min(4096, max(sides)))+++def vae_can_slice(vae: Any) -> bool:+ if vae is None:+ return False+ return bool(getattr(vae, "use_slicing", False)) or callable(+ getattr(vae, "enable_slicing", None)+ )+++def vae_is_sliced(vae: Any) -> bool:+ if vae is None:+ return False+ return bool(getattr(vae, "use_slicing", callable(getattr(vae, "enable_slicing", None))))+++def engage_vae_tiling_for_call(pipe: Any, logger: Any = None) -> Optional[Callable[[], None]]:+ """Tile and slice ``pipe``'s VAE for one generation; returns the undo, or None if nothing changed."""+ return engage_vae_tiling(pipe, logger = logger)[0]+++def engage_vae_tiling(pipe: Any, logger: Any = None) -> tuple[Optional[Callable[[], None]], bool]:+ """``engage_vae_tiling_for_call`` plus whether tiling is actually on (``enable_tiling()`` may fail)."""+ vae = getattr(pipe, "vae", None)+ if vae is None:+ return None, False+ tiled = bool(getattr(vae, "use_tiling", False))+ undo: list[str] = []+ for flag, enable, disable in (+ ("use_tiling", "enable_tiling", "disable_tiling"),+ ("use_slicing", "enable_slicing", "disable_slicing"),+ ):+ if bool(getattr(vae, flag, False)):+ continue+ fn = getattr(vae, enable, None)+ if not callable(fn):+ continue+ try:+ fn()+ except Exception as exc: # noqa: BLE001 - a VAE saver is an optimisation, never fatal+ if logger is not None:+ logger.warning("diffusion.memory: %s() failed: %s", enable, exc)+ continue+ undo.append(disable)+ if enable == "enable_tiling":+ tiled = bool(getattr(vae, flag, True))+ if not undo:+ return None, tiled++ def _restore() -> None:+ for method in undo:+ fn = getattr(vae, method, None)+ if not callable(fn):+ continue+ try:+ fn()+ except Exception as exc: # noqa: BLE001 - restoring is best-effort+ if logger is not None:+ logger.warning("diffusion.memory: %s() failed: %s", method, exc)++ return _restore, tiled+++def _family_activation_multiplier(family: Optional[str]) -> float:+ fam = (family or "").lower()+ multiplier = 1.0+ if "edit" in fam:+ multiplier *= 1.35+ if "turbo" in fam or "distilled" in fam or "schnell" in fam:+ multiplier *= 0.85+ return multiplier+++def estimate_tiled_image_runtime_mib(+ *,+ width: Optional[int],+ height: Optional[int],+ batch_size: int = 1,+ family: Optional[str] = None,+ condition_pixels: int = 0,+ tile_side: Optional[int] = None,+ vae_sliced: bool = False,+) -> int:+ """Per-call MiB with the VAE tiled: max(one-tile decode, denoiser); unsliced tiles carry the whole batch.+ Invalid under the SDPA math fallback, whose score matrix grows with the square of the tokens."""+ w = max(64, int(width or DEFAULT_IMAGE_WIDTH))+ h = max(64, int(height or DEFAULT_IMAGE_HEIGHT))+ batch = max(1, int(batch_size or 1))+ cond = max(0, int(condition_pixels or 0))+ side = int(tile_side or DEFAULT_VAE_TILE_SIDE)+ megapixel = float(DEFAULT_IMAGE_WIDTH * DEFAULT_IMAGE_HEIGHT)+ vae = estimate_image_runtime_mib(+ width = min(w, side),+ height = min(h, side),+ batch_size = 1 if vae_sliced else batch,+ family = family,+ )+ denoise = batch * (+ DENOISE_MIB_PER_MEGAPIXEL * (w * h / megapixel) * _family_activation_multiplier(family)+ + 8192 * (cond / megapixel)+ )+ return max(1024, vae, int(denoise))+++def _activation_refusal_message(+ *,+ width: int,+ height: int,+ batch: int,+ total_mib: int,+ overhead_mib: int,+ budget_mib: int,+ free_mib: int,+ source_driven: bool,+ condition_pixels: int,+ tiled: bool,+) -> str:+ batch_note = f" at a batch of {batch}" if batch > 1 else ""+ cond_note = " with its input images" if condition_pixels else ""+ if source_driven:+ remedy = (+ "Upload a smaller source image (this workflow takes its output size from the image, "+ "not the Resolution setting)"+ )+ else:+ remedy = "Generate at a smaller resolution"+ # Two decimals and overhead included: refusals are decided by tens of MiB and must not contradict themselves.+ return (+ f"Generating at {width}x{height}{batch_note}{cond_note} needs about {total_mib / 1024:.2f} GB "+ f"of working memory{' even with tiled VAE decoding' if tiled else ''} (including about "+ f"{overhead_mib / 1024:.2f} GB of fixed overhead), but only about {budget_mib / 1024:.2f} GB "+ f"is usable on this device (of the {free_mib / 1024:.2f} GB currently free, after reserving "+ "room for fragmentation and other processes). Working memory holds the image being "+ "generated, so unlike model weights it cannot be moved to the CPU. "+ # Smaller-batch hint only when batch > 1: a one-image refusal cannot be fixed by asking for fewer.+ f"{remedy}"+ f"{' or a smaller batch size' if batch > 1 else ''}"+ f"{', use fewer input images or a lower reference detail' if condition_pixels else ''}, "+ "or free GPU memory by closing other applications. To try anyway, turn on "+ f"'{OVERSIZED_GENERATE_SETTING_LABEL}' under Advanced on the Images page "+ "(API callers of /api/inference/images/generate can send allow_oversized; server installs "+ f"can set {OVERSIZED_GENERATE_ENV}=1)."+ )+++def image_activation_verdict(*,device_memory: DeviceMemory,width: Optional[int],@@ -1759,19 +1949,24 @@ def image_activation_shortfall_message(base_overhead_mib: int = DEFAULT_BASE_OVERHEAD_MIB,source_driven: bool = False,condition_pixels: int = 0,-) -> Optional[str]:- """A user-facing refusal when this generation's ACTIVATIONS plus the flat base overhead cannot fit- the free device budget, else None.+ vae_tile_side: Optional[int] = None,+ vae_sliced: bool = False,+ quadratic_attention: bool = False,+ allow_oversized: bool = False,+) -> ImageActivationVerdict:+ """Decide whether this generation's ACTIVATIONS fit the free device budget: run it as loaded,+ run it with the VAE tiled, or refuse.``source_driven`` says the refused size comes from an UPLOADED image rather than the Resolutioncontrol (inpaint / extend / upscale / edit); telling those callers to generate at a smallerresolution points them at a control that cannot change the number in the refusal. Same verdicteither way, only the remedy sentence differs.- Why a refusal and not another knob: weights can be offloaded, activations cannot. Every offload- tier moves WEIGHTS between host and device, while the latents, attention buffers and VAE- intermediates a forward pass allocates have to be on the device while it runs, so an activation- estimate above the free budget overruns at every tier including the lowest.+ Why tiling and not another offload tier: weights can be offloaded, activations cannot. Every+ offload tier moves WEIGHTS between host and device, while the latents, attention buffers and VAE+ intermediates a forward pass allocates have to be on the device while it runs. What CAN shrink+ is the VAE decode, by tiling (as ComfyUI does); not under ``quadratic_attention``, where the+ denoiser is what grows.Refusing has to happen HERE rather than being left to torch. On Linux the overrun raises``torch.OutOfMemoryError`` and the job dies cleanly; on Windows WDDM (including ROCm) it does@@ -1782,32 +1977,31 @@ def image_activation_shortfall_message(It does NOT second-guess the load. The flat headroom this estimate is built on is a deliberatelygenerous PLANNING figure for picking a tier, and that tier already runs the 1024x1024 default oncards whose whole budget is under 8 GB (measured: a 8 GB card's safe budget is 5898 MiB against- a 6963 MiB default-resolution estimate, and those generations complete). So the refusal needs+ a 6963 MiB default-resolution estimate, and those generations complete). So a refusal needsBOTH conditions -- over the free budget AND over what the load already budgeted -- which- confines it to the resolution-driven overrun it is for.+ confines it to the resolution-driven overrun it is for. The tiled look applies the same rule.Fail-open on anything unknown (no free reading, no budget) and on any device class where theestimate or the offload story means something different, so a broken probe can never block ageneration that would have worked."""- if _oversized_generate_override():- return None+ override = bool(allow_oversized) or _oversized_generate_override()try:# Unified / system memory: offload moves bytes within one pool, "free" is a moving target shared with the OS,# and the load-time unified refusal already owns that device class.if getattr(device_memory, "is_unified", False):- return None+ return ImageActivationVerdict(ACTIVATION_RUN)# CUDA / ROCm only. ROCm's torch reports device "cuda", so this covers both. XPU / MPS / CPU keep today's# behaviour exactly: their allocators and offload semantics differ and this estimate was measured against a# discrete VRAM pool.if getattr(device_memory, "device", None) != "cuda":- return None+ return ImageActivationVerdict(ACTIVATION_RUN)free = getattr(device_memory, "free_mib", None)if free is None:- return None+ return ImageActivationVerdict(ACTIVATION_RUN)budget = _safe_device_budget_mib(device_memory)if budget is None:- return None+ return ImageActivationVerdict(ACTIVATION_RUN)needed = estimate_image_runtime_mib(width = width,height = height,@@ -1824,41 +2018,84 @@ def image_activation_shortfall_message(batch_size = 1,family = family,)+ tiled = None+ if vae_tile_side is not None and not quadratic_attention:+ tiled = estimate_tiled_image_runtime_mib(+ width = width,+ height = height,+ batch_size = batch_size,+ family = family,+ condition_pixels = condition_pixels,+ tile_side = vae_tile_side,+ vae_sliced = vae_sliced,+ )except Exception: # noqa: BLE001 -- a broken probe must never block a generation- return None+ return ImageActivationVerdict(ACTIVATION_RUN)+ overhead = max(0, int(base_overhead_mib))# The flat base overhead rides along with the activations: the CUDA context, the scheduler state and the# fragmentation allowance all have to coexist with this pass's tensors, and the load-time plan already sums them# additively for exactly that reason. Leaving it out made the guard silent by a few hundred MiB on the very card# #8188 was reported from (15.92 GiB: 13,872 MiB of activations against a 14,254 MiB budget). It cannot cause a# false refusal at or below the default resolution, because the `needed <= planned` arm already exempts every# request the load itself budgeted for.- if int(needed) + max(0, int(base_overhead_mib)) <= int(budget) or needed <= planned:- return None+ numbers = dict(needed_mib = int(needed), tiled_needed_mib = tiled, budget_mib = int(budget))+ if int(needed) + overhead <= int(budget) or needed <= planned:+ return ImageActivationVerdict(ACTIVATION_RUN, **numbers)+ if tiled is not None and (int(tiled) + overhead <= int(budget) or tiled <= planned):+ return ImageActivationVerdict(ACTIVATION_TILE, **numbers)+ if override:+ # Tile even under quadratic attention: the estimate is untrusted there, but tiling still lowers the peak.+ return ImageActivationVerdict(+ ACTIVATION_TILE if vae_tile_side is not None else ACTIVATION_RUN,+ overridden = True,+ **numbers,+ )w = max(64, int(width or DEFAULT_IMAGE_WIDTH))h = max(64, int(height or DEFAULT_IMAGE_HEIGHT))- batch = max(1, int(batch_size or 1))- batch_note = f" at a batch of {batch}" if batch > 1 else ""- cond_note = " with its input images" if condition_pixels else ""- # Two decimals, not one: the refusal is often decided by tens of MiB (the 1088x1920 report needed 13,872 MiB against- # a 13,822 MiB budget), and one decimal prints both as "13.5 GB". The overhead is part of the comparison above, so- # it has to be part of the number reported. Quoting the activations alone printed a refusal that contradicted- # itself: 13.55 GB needed against 13.92 GB usable, refused.- total = int(needed) + max(0, int(base_overhead_mib))- return (- f"Generating at {w}x{h}{batch_note}{cond_note} needs about {total / 1024:.2f} GB of working memory "- f"(including about {max(0, int(base_overhead_mib)) / 1024:.2f} GB of fixed overhead), "- f"but only about {int(budget) / 1024:.2f} GB is usable on this device (of the "- f"{int(free) / 1024:.2f} GB currently free, after reserving room for fragmentation and "- "other processes). Working memory holds this pass's latents and attention buffers, which "- "cannot be offloaded to the CPU the way weights can, so no memory mode recovers this. "- # Only when the batch is what was budgeted. A refusal measured on ONE image cannot be answered by asking for- # fewer, and pointing there sends the caller at the one change that provably will not help.- f"{'Upload a smaller source image (this workflow takes its output size from the image, not the Resolution setting)' if source_driven else 'Generate at a smaller resolution'}"- f"{' or a smaller batch size' if batch > 1 else ''}"- f"{', use fewer input images or a lower reference detail' if condition_pixels else ''}, "- "free device memory by closing other applications, or set "- f"{OVERSIZED_GENERATE_ENV}=1 to attempt it anyway."+ message = _activation_refusal_message(+ width = w,+ height = h,+ batch = max(1, int(batch_size or 1)),+ total_mib = int(tiled if tiled is not None else needed) + overhead,+ overhead_mib = overhead,+ budget_mib = int(budget),+ free_mib = int(free),+ source_driven = source_driven,+ condition_pixels = condition_pixels,+ tiled = tiled is not None,)+ return ImageActivationVerdict(ACTIVATION_REFUSE, message = message, **numbers)+++def image_activation_shortfall_message(+ *,+ device_memory: DeviceMemory,+ width: Optional[int],+ height: Optional[int],+ batch_size: int = 1,+ family: Optional[str] = None,+ base_overhead_mib: int = DEFAULT_BASE_OVERHEAD_MIB,+ source_driven: bool = False,+ condition_pixels: int = 0,+ vae_tile_side: Optional[int] = None,+ vae_sliced: bool = False,+ quadratic_attention: bool = False,+ allow_oversized: bool = False,+) -> Optional[str]:+ return image_activation_verdict(+ device_memory = device_memory,+ width = width,+ height = height,+ batch_size = batch_size,+ family = family,+ base_overhead_mib = base_overhead_mib,+ source_driven = source_driven,+ condition_pixels = condition_pixels,+ vae_tile_side = vae_tile_side,+ vae_sliced = vae_sliced,+ quadratic_attention = quadratic_attention,+ allow_oversized = allow_oversized,+ ).messagedef raise_on_image_activation_shortfall(@@ -1871,16 +2108,19 @@ def raise_on_image_activation_shortfall(base_overhead_mib: int = DEFAULT_BASE_OVERHEAD_MIB,source_driven: bool = False,condition_pixels: int = 0,+ vae_tile_side: Optional[int] = None,+ vae_sliced: bool = False,+ quadratic_attention: bool = False,+ allow_oversized: bool = False,logger: Any = None,-) -> None:- """Refuse a generation whose activations cannot fit the free device budget. No-op whenever- ``image_activation_shortfall_message`` declines to produce a verdict.+) -> ImageActivationVerdict:+ """Refuse a generation whose activations cannot fit the free device budget; else return the verdict.``ValueError`` on purpose: ``/images/generate`` maps ValueError to HTTP 400 with the messageas the reason, so this surfaces as an actionable refusal in the UI. RuntimeError there isreserved for the two client-state sentinels (not loaded / cancelled) and otherwise becomes anopaque 500."""- message = image_activation_shortfall_message(+ verdict = image_activation_verdict(device_memory = device_memory,width = width,height = height,@@ -1889,12 +2129,30 @@ def raise_on_image_activation_shortfall(base_overhead_mib = base_overhead_mib,source_driven = source_driven,condition_pixels = condition_pixels,+ vae_tile_side = vae_tile_side,+ vae_sliced = vae_sliced,+ quadratic_attention = quadratic_attention,+ allow_oversized = allow_oversized,)- if message is None:- return- if logger is not None:- logger.error("diffusion.memory: refusing oversized generation: %s", message)- raise ImageActivationShortfallError(message)+ if verdict.action == ACTIVATION_REFUSE:+ if logger is not None:+ logger.error("diffusion.memory: refusing oversized generation: %s", verdict.message)+ raise ImageActivationShortfallError(verdict.message)+ if logger is not None and (verdict.action == ACTIVATION_TILE or verdict.overridden):+ logger.warning(+ "diffusion.memory: %dx%d needs ~%s MiB untiled, ~%s MiB tiled, budget %s MiB: %s",+ int(width or DEFAULT_IMAGE_WIDTH),+ int(height or DEFAULT_IMAGE_HEIGHT),+ verdict.needed_mib,+ verdict.tiled_needed_mib,+ verdict.budget_mib,+ (+ "running anyway (allow_oversized)"+ if verdict.overridden+ else "tiling the VAE for this generation"+ ),+ )+ return verdictdef _apply_streaming_offload(pipe: Any, device: str, logger: Any) -> None:diff --git a/studio/backend/core/inference/sd_cpp_backend.py b/studio/backend/core/inference/sd_cpp_backend.pyindex 1d5e5367ee0..61115f69ae2 100644--- a/studio/backend/core/inference/sd_cpp_backend.py+++ b/studio/backend/core/inference/sd_cpp_backend.py@@ -3397,6 +3397,8 @@ class SdCppDiffusionBackend:controlnet: Optional[tuple[str, str, str, float, float, float]] = None,# load_identity() of the caller's status() read; refuse rather than run a different load (#9448)expected_load: Optional[LoadIdentity] = None,+ # Interface parity only: the activation guard is diffusers-only.+ allow_oversized: bool = False,) -> dict[str, Any]:import tempfilediff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.pyindex 615d3a58c84..d6937499225 100644--- a/studio/backend/core/inference/video.py+++ b/studio/backend/core/inference/video.py@@ -817,8 +817,10 @@ def _ensure_mp4_encoder_available() -> None:import av # noqa: F401except Exception as exc: # noqa: BLE001 -- any import failure means no encoderraise ValueError(- "Video generation needs the 'av' package (PyAV) to encode MP4s. "- "Install it with: pip install av"+ "Video generation needs the 'av' package (PyAV) to encode MP4s, and this install "+ "is missing it. Update Unsloth to restore it (in the desktop app: Settings, Check for "+ "updates; from a terminal: unsloth studio update). On a plain pip install: "+ "pip install av") from excdiff --git a/studio/backend/main.py b/studio/backend/main.pyindex 91083fe32c0..d864c804401 100644--- a/studio/backend/main.py+++ b/studio/backend/main.py@@ -1575,7 +1575,7 @@ app.add_middleware(allow_headers = ["*"],# allow_headers is the REQUEST side; a response header is unreadable to JS unless# exposed, and Studio is cross-origin from tauri://localhost and tunnels.- expose_headers = ["X-Unsloth-Conflict-Kind"],+ expose_headers = ["X-Unsloth-Conflict-Kind", "X-Unsloth-Refusal"],# is_allowed_origin closes the moment the tunnel URL clears, but a preflight already cached by the browser# does not. Measured in WebKit: with Starlette's 600s default, a state-changing request still REACHED the# server after remote access was stopped. Keep the stale window short.diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.pyindex f1a84494804..0627b6967eb 100644--- a/studio/backend/models/inference.py+++ b/studio/backend/models/inference.py@@ -4119,6 +4119,14 @@ class DiffusionGenerateRequest(BaseModel):"by this multiple and re-denoises at low strength. Requires init_image; ""ignored for txt2img/inpaint/edit.",)+ allow_oversized: bool = Field(+ False,+ description = "Run even when the generate-time memory check estimates this size will not "+ "fit the free GPU memory. Sizes that fit once the VAE decodes tile by tile already run "+ "without it; this is for the rest. An oversized run can fail with an out-of-memory error, "+ "or on Windows spill into system RAM and run very slowly. Same effect as the server's "+ "UNSLOTH_DIFFUSION_ALLOW_OVERSIZED_GENERATE=1, per request.",+ )reference_images: Optional[list[str]] = Field(None,max_length = 9,diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 18aa872c967..d278c7ed016 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -40497,6 +40497,11 @@ async def generate_diffusion_image()from core.inference.diffusion_conditioning import LocalizedEdit+ from core.inference.diffusion_memory import (+ IMAGE_REFUSAL_HEADER,+ IMAGE_REFUSAL_MEMORY_ESTIMATE,+ ImageActivationShortfallError,+ )backend = get_active_diffusion_engine()if account_access.managed_account():@@ -40547,6 +40552,10 @@ async def generate_diffusion_image(workflow = request.workflow,reference_resolution = request.reference_resolution,localized_edit = localized_edit,+ # Owner only: on Windows an oversized run spills into RAM instead of raising OOM, so a managed+ # account could stall the shared host. The operator env var still applies to everyone.+ allow_oversized = request.allow_oversized+ and not account_access.managed_account(),loras = [(l.id, l.weight) for l in request.loras] if request.loras else None,controlnet = ((@@ -40562,6 +40571,13 @@ async def generate_diffusion_image(),)break+ except ImageActivationShortfallError as exc:+ # Tagged so the Images page can offer "Generate anyway".+ raise HTTPException(+ status_code = 400,+ detail = str(exc),+ headers = {IMAGE_REFUSAL_HEADER: IMAGE_REFUSAL_MEMORY_ESTIMATE},+ )except ValueError as exc:raise HTTPException(status_code = 400, detail = str(exc))except DiffusionModelReplacedError as exc:diff --git a/studio/backend/tests/test_diffusion_backend.py b/studio/backend/tests/test_diffusion_backend.pyindex 4f62104cb77..502180ab115 100644--- a/studio/backend/tests/test_diffusion_backend.py+++ b/studio/backend/tests/test_diffusion_backend.py@@ -10941,6 +10941,221 @@ def test_generate_guard_env_override(fake_runtime, tmp_path, monkeypatch):assert len(backend.generate(prompt = "a sloth", width = 1088, height = 1920, steps = 4)["images"]) == 1+class _TilingVae:+ """A VAE that can tile, like every diffusers AutoencoderKL*: records its saver calls."""++ tile_sample_min_height = 256+ tile_sample_min_width = 256++ def __init__(self) -> None:+ self.use_tiling = False+ self.use_slicing = False+ self.calls: list = []++ def enable_tiling(self):+ self.calls.append("enable_tiling")+ self.use_tiling = True++ def disable_tiling(self):+ self.calls.append("disable_tiling")+ self.use_tiling = False++ def enable_slicing(self):+ self.calls.append("enable_slicing")+ self.use_slicing = True++ def disable_slicing(self):+ self.calls.append("disable_slicing")+ self.use_slicing = False+++def _upscale_with_tiling_vae(backend, monkeypatch, **kw):+ """Run a 1024 -> 2048 Upscale whose img2img pipe shares a tiling VAE; returns (vae, tiled_during_call)."""+ from core.inference import diffusion as dmod++ vae = _TilingVae()+ monkeypatch.setattr(_FakeImg2ImgPipe, "vae", vae, raising = False)+ monkeypatch.setattr(dmod, "_quadratic_attention", lambda target, backend = None: False)+ seen = {}+ real_call = _FakeImg2ImgPipe.__call__++ def _spy(self, **kwargs):+ seen["tiled"] = vae.use_tiling+ seen["sliced"] = vae.use_slicing+ return real_call(self, **kwargs)++ monkeypatch.setattr(_FakeImg2ImgPipe, "__call__", _spy)+ out = backend.generate(+ prompt = "a sloth", steps = 4, seed = 1, init_image = _png_b64(1024), upscale = 2.0, **kw+ )+ return out, vae, seen+++def test_generate_upscale_that_was_refused_runs_with_the_vae_tiled(+ fake_runtime, tmp_path, monkeypatch+):+ backend = _loaded_backend_on_a_16g_card(tmp_path, monkeypatch)+ with pytest.raises(ValueError, match = "2048x2048"):+ backend.generate(prompt = "a sloth", steps = 4, seed = 1, init_image = _png_b64(1024), upscale = 2.0)+ out, vae, seen = _upscale_with_tiling_vae(backend, monkeypatch)+ assert len(out["images"]) == 1+ assert _FakeImg2ImgPipe.last_kwargs["image"].size == (2048, 2048)+ assert seen == {"tiled": True, "sliced": True}+ assert not vae.use_tiling and not vae.use_slicing+ assert vae.calls == ["enable_tiling", "enable_slicing", "disable_tiling", "disable_slicing"]+++def test_generate_upscale_that_fits_is_not_tiled(fake_runtime, tmp_path, monkeypatch):+ backend = _loaded_backend_on_a_16g_card(tmp_path, monkeypatch)+ from core.inference import diffusion as dmod++ vae = _TilingVae()+ monkeypatch.setattr(_FakeImg2ImgPipe, "vae", vae, raising = False)+ monkeypatch.setattr(dmod, "_quadratic_attention", lambda target, backend = None: False)+ backend.generate(prompt = "a sloth", steps = 4, seed = 1, init_image = _png_b64(512), upscale = 2.0)+ assert vae.calls == []+++def test_generate_upscale_restores_the_vae_when_the_render_fails(+ fake_runtime, tmp_path, monkeypatch+):+ backend = _loaded_backend_on_a_16g_card(tmp_path, monkeypatch)+ from core.inference import diffusion as dmod++ vae = _TilingVae()+ monkeypatch.setattr(_FakeImg2ImgPipe, "vae", vae, raising = False)+ monkeypatch.setattr(dmod, "_quadratic_attention", lambda target, backend = None: False)++ def _boom(self, **kwargs):+ raise RuntimeError("decode failed")++ monkeypatch.setattr(_FakeImg2ImgPipe, "__call__", _boom)+ with pytest.raises(RuntimeError, match = "decode failed"):+ backend.generate(prompt = "a sloth", steps = 4, seed = 1, init_image = _png_b64(1024), upscale = 2.0)+ assert not vae.use_tiling and not vae.use_slicing+++def test_generate_upscale_on_math_only_attention_still_refuses(fake_runtime, tmp_path, monkeypatch):+ from core.inference import diffusion as dmod++ backend = _loaded_backend_on_a_16g_card(tmp_path, monkeypatch)+ monkeypatch.setattr(_FakeImg2ImgPipe, "vae", _TilingVae(), raising = False)+ monkeypatch.setattr(dmod, "_quadratic_attention", lambda target, backend = None: True)+ with pytest.raises(ValueError) as excinfo:+ backend.generate(prompt = "a sloth", steps = 4, seed = 1, init_image = _png_b64(1024), upscale = 2.0)+ message = str(excinfo.value)+ assert "Upload a smaller source image" in message+ assert "Allow oversized generations" in message+++class _UnslicedTilingVae(_TilingVae):+ """Tiles at 1024 (AutoencoderKL) but its enable_slicing() leaves slicing off."""++ tile_sample_min_height = 1024+ tile_sample_min_width = 1024++ def enable_slicing(self):+ self.calls.append("enable_slicing")++[email protected]("vae_cls", [_TilingVae, _UnslicedTilingVae])+def test_generate_windows_batch_prices_tiles_at_the_batch_without_slicing(+ fake_runtime, tmp_path, monkeypatch, vae_cls+):+ from core.inference import diffusion as dmod++ backend = _loaded_backend_on_a_16g_card(tmp_path, monkeypatch)+ vae = vae_cls()+ monkeypatch.setattr(_FakeImg2ImgPipe, "vae", vae, raising = False)+ monkeypatch.setattr(dmod, "_quadratic_attention", lambda target, backend = None: False)+ monkeypatch.setattr(dmod.sys, "platform", "win32")+ kw = dict(prompt = "a sloth", steps = 4, init_image = _png_b64(1024), upscale = 2.0, seeds = [1, 2])+ if vae_cls is _TilingVae:+ assert len(backend.generate(**kw)["images"]) == 2+ else:+ with pytest.raises(ValueError, match = "2048x2048 at a batch of 2"):+ backend.generate(**kw)+ assert not vae.use_tiling and not vae.use_slicing+++class _BrokenTilingVae(_TilingVae):+ """A VAE that claims to tile but whose enable_tiling() raises."""++ def enable_tiling(self):+ self.calls.append("enable_tiling")+ raise RuntimeError("tiling unsupported")+++def test_generate_upscale_refuses_when_the_vae_tiling_does_not_engage(+ fake_runtime, tmp_path, monkeypatch+):+ from core.inference import diffusion as dmod++ backend = _loaded_backend_on_a_16g_card(tmp_path, monkeypatch)+ vae = _BrokenTilingVae()+ monkeypatch.setattr(_FakeImg2ImgPipe, "vae", vae, raising = False)+ monkeypatch.setattr(dmod, "_quadratic_attention", lambda target, backend = None: False)+ calls = []+ real_call = _FakeImg2ImgPipe.__call__++ def _spy(self, **kwargs):+ calls.append(kwargs)+ return real_call(self, **kwargs)++ monkeypatch.setattr(_FakeImg2ImgPipe, "__call__", _spy)+ with pytest.raises(ValueError) as excinfo:+ backend.generate(prompt = "a sloth", steps = 4, seed = 1, init_image = _png_b64(1024), upscale = 2.0)+ assert "2048x2048" in str(excinfo.value)+ assert "even with tiled VAE decoding" not in str(excinfo.value)+ assert calls == []+ assert not vae.use_slicing and not vae.use_tiling+ out = backend.generate(+ prompt = "a sloth",+ steps = 4,+ seed = 1,+ init_image = _png_b64(1024),+ upscale = 2.0,+ allow_oversized = True,+ )+ assert len(out["images"]) == 1+++def test_quadratic_attention_follows_the_engaged_backend(monkeypatch):+ from core.inference import diffusion as dmod++ monkeypatch.setattr(dmod, "sdpa_math_only", lambda target: True)+ assert dmod._quadratic_attention(object()) is True+ assert dmod._quadratic_attention(object(), None) is True+ assert dmod._quadratic_attention(object(), "native") is True+ for engaged in ("aiter", "sage", "xformers", "_native_cudnn", "flash"):+ assert dmod._quadratic_attention(object(), engaged) is False+++def test_generate_upscale_with_an_engaged_backend_on_a_math_only_device_runs_tiled(+ fake_runtime, tmp_path, monkeypatch+):+ from core.inference import diffusion as dmod++ backend = _loaded_backend_on_a_16g_card(tmp_path, monkeypatch)+ monkeypatch.setattr(dmod, "sdpa_math_only", lambda target: True)+ vae = _TilingVae()+ monkeypatch.setattr(_FakeImg2ImgPipe, "vae", vae, raising = False)+ with pytest.raises(ValueError, match = "2048x2048"):+ backend.generate(prompt = "a sloth", steps = 4, seed = 1, init_image = _png_b64(1024), upscale = 2.0)+ object.__setattr__(backend._state, "attention_backend", "aiter")+ out = backend.generate(+ prompt = "a sloth", steps = 4, seed = 1, init_image = _png_b64(1024), upscale = 2.0+ )+ assert len(out["images"]) == 1+ assert vae.calls[:2] == ["enable_tiling", "enable_slicing"]+++def test_generate_allow_oversized_runs_a_refused_request(fake_runtime, tmp_path, monkeypatch):+ backend = _loaded_backend_on_a_16g_card(tmp_path, monkeypatch)+ out = backend.generate(prompt = "a sloth", width = 1088, height = 1920, steps = 4, allow_oversized = True)+ assert len(out["images"]) == 1++def test_generate_guard_leaves_a_large_batch_to_the_oom_backoff(fake_runtime, tmp_path, monkeypatch):diff --git a/studio/backend/tests/test_diffusion_routes.py b/studio/backend/tests/test_diffusion_routes.pyindex e2fc133be46..bbb7afce0c9 100644--- a/studio/backend/tests/test_diffusion_routes.py+++ b/studio/backend/tests/test_diffusion_routes.py@@ -692,6 +692,45 @@ def test_generate_execution_error_with_cancelled_substring_is_sanitized_500(clieassert "cancelled" not in detail and "models" not in detail and "/home/u" not in detail+def test_generate_memory_refusal_is_a_tagged_400_and_allow_oversized_reaches_the_backend(+ client, monkeypatch+):+ from core.inference.diffusion_memory import (+ IMAGE_REFUSAL_HEADER,+ IMAGE_REFUSAL_MEMORY_ESTIMATE,+ ImageActivationShortfallError,+ )++ backend = diffusion_module.get_diffusion_backend()+ backend.loaded = True+ seen = []++ def _guarded(**kwargs):+ seen.append(kwargs.get("allow_oversized"))+ if not kwargs.get("allow_oversized"):+ raise ImageActivationShortfallError("Generating at 2048x2048 needs about 34.00 GB")+ return {"images": [], "seed": 1, "seeds": []}++ monkeypatch.setattr(backend, "generate", _guarded)+ refused = client.post("/api/inference/images/generate", json = {"prompt": "p"})+ assert refused.status_code == 400+ assert refused.headers.get(IMAGE_REFUSAL_HEADER) == IMAGE_REFUSAL_MEMORY_ESTIMATE+ assert "2048x2048" in refused.json()["detail"]+ retried = client.post(+ "/api/inference/images/generate", json = {"prompt": "p", "allow_oversized": True}+ )+ assert retried.status_code == 200+ assert seen == [False, True]++ def _plain(**kwargs):+ raise ValueError("width and height are required for this workflow.")++ monkeypatch.setattr(backend, "generate", _plain)+ other = client.post("/api/inference/images/generate", json = {"prompt": "p"})+ assert other.status_code == 400+ assert IMAGE_REFUSAL_HEADER not in other.headers++def test_generate_user_cancellation_returns_409(client, monkeypatch):# The exact cancellation sentinel both engines raise is client-state (409).backend = diffusion_module.get_diffusion_backend()@@ -2707,3 +2746,25 @@ def test_generate_schema_bounds_for_unified_editing(client):assert _post_generate(client, prompt = "p", width = 2768).status_code == 422bad_mode = _post_generate(client, prompt = "p", localized_edit = {"mode": "lasso", "image": "QUJD"})assert bad_mode.status_code == 422+++def test_a_managed_account_cannot_send_allow_oversized(client, monkeypatch):+ from hub.services.models import account_access++ backend = diffusion_module.get_diffusion_backend()+ backend.loaded = True+ seen = []+ monkeypatch.setattr(account_access, "managed_account", lambda: True)+ monkeypatch.setattr(account_access, "require_media_adapters", lambda *a, **k: None)+ monkeypatch.setattr(account_access, "require_media_generation_access", lambda *a, **k: None)+ monkeypatch.setattr(+ backend,+ "generate",+ lambda **kw: seen.append(kw.get("allow_oversized"))+ or {"images": [], "seed": 1, "seeds": []},+ )+ resp = client.post(+ "/api/inference/images/generate", json = {"prompt": "p", "allow_oversized": True}+ )+ assert resp.status_code == 200+ assert seen == [False]diff --git a/studio/backend/tests/test_diffusion_upscale_gate.py b/studio/backend/tests/test_diffusion_upscale_gate.pynew file mode 100644index 00000000000..484c5cf4dd1--- /dev/null+++ b/studio/backend/tests/test_diffusion_upscale_gate.py@@ -0,0 +1,314 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""CPU-only tests for the generate-time activation guard's tiled look and its per-request override."""++from __future__ import annotations++import pytest++from core.inference import diffusion_memory as dm+from core.inference.diffusion_memory import (+ ACTIVATION_REFUSE,+ ACTIVATION_RUN,+ ACTIVATION_TILE,+ DeviceMemory,+ OVERSIZED_GENERATE_ENV,+ OVERSIZED_GENERATE_SETTING_LABEL,+ estimate_image_runtime_mib,+ estimate_tiled_image_runtime_mib,+ image_activation_shortfall_message,+ image_activation_verdict,+)++_QWEN_HINT = "qwen-image|unsloth/Qwen-Image-2512-GGUF|Qwen/Qwen-Image"+_ZIMAGE_HINT = "z-image|unsloth/Z-Image-Turbo-GGUF|Tongyi-MAI/Z-Image-Turbo"+_Q21_HINT = "qwen-image-2.1|unsloth/Qwen-Image-2.1-GGUF|Qwen/Qwen-Image-2.1"+_Q21_COND_WEIGHT = 0.32 # diffusion_families: qwen-image-2.1 condition_pixel_weight+++def _card(gigabytes: float, free_fraction: float = 0.97) -> DeviceMemory:+ total = int(gigabytes * 1024)+ return DeviceMemory("cuda", "cuda", "discrete_vram", int(total * free_fraction), total)+++def _verdict(width, height, memory, **kw):+ kw.setdefault("family", _QWEN_HINT)+ return image_activation_verdict(device_memory = memory, width = width, height = height, **kw)++[email protected](autouse = True)+def _no_env_override(monkeypatch):+ monkeypatch.delenv(OVERSIZED_GENERATE_ENV, raising = False)++[email protected]("gigabytes", [8, 12, 16])+def test_a_2048_upscale_that_was_refused_now_runs_tiled(gigabytes):+ card = _card(gigabytes)+ before = _verdict(2048, 2048, card, source_driven = True)+ assert before.action == ACTIVATION_REFUSE+ after = _verdict(2048, 2048, card, source_driven = True, vae_tile_side = 256)+ assert after.action == ACTIVATION_TILE+ assert after.message is None+ assert after.tiled_needed_mib < after.needed_mib+++ "hint,tile", [(_ZIMAGE_HINT, 1024), ("flux|x|black-forest-labs/FLUX.1-dev", 1024)]+)+def test_autoencoderkl_families_run_tiled_on_an_8gb_card(hint, tile):+ v = _verdict(2048, 2048, _card(8), family = hint, source_driven = True, vae_tile_side = tile)+ assert v.action == ACTIVATION_TILE+++def test_sizes_that_fit_untiled_are_left_alone():+ for gigabytes in (8, 12, 16, 24, 48, 80):+ assert _verdict(1024, 1024, _card(gigabytes), vae_tile_side = 256).action == ACTIVATION_RUN+ assert _verdict(2048, 2048, _card(80), vae_tile_side = 256).action == ACTIVATION_RUN+++def _ten_2048_references() -> int:+ return int(10 * 2048 * 2048 * _Q21_COND_WEIGHT)+++def test_a_request_that_cannot_run_even_tiled_still_refuses_with_an_in_app_action():+ v = _verdict(+ 2400,+ 1792,+ _card(16),+ family = _Q21_HINT,+ source_driven = True,+ condition_pixels = _ten_2048_references(),+ vae_tile_side = 256,+ )+ assert v.action == ACTIVATION_REFUSE+ message = v.message+ assert "2400x1792" in message+ assert "even with tiled VAE decoding" in message+ assert "fewer input images" in message+ assert OVERSIZED_GENERATE_SETTING_LABEL in message+ assert OVERSIZED_GENERATE_ENV in message+ assert message.index(OVERSIZED_GENERATE_SETTING_LABEL) < message.index(OVERSIZED_GENERATE_ENV)+ assert "server" in message[message.index(OVERSIZED_GENERATE_SETTING_LABEL) :]+ assert f"{(v.tiled_needed_mib + dm.DEFAULT_BASE_OVERHEAD_MIB) / 1024:.2f} GB" in message+++def test_the_sdpa_math_fallback_gets_no_tiled_relief():+ v = _verdict(2048, 2048, _card(16), vae_tile_side = 256, quadratic_attention = True)+ assert v.action == ACTIVATION_REFUSE+ assert "even with tiled VAE decoding" not in v.message+++def test_a_vae_that_cannot_tile_keeps_the_old_verdict():+ v = _verdict(2048, 2048, _card(16), vae_tile_side = None)+ assert v.action == ACTIVATION_REFUSE+ assert "even with tiled VAE decoding" not in v.message+++def test_allow_oversized_turns_a_refusal_into_a_tiled_attempt():+ kw = dict(+ family = _Q21_HINT,+ condition_pixels = _ten_2048_references(),+ vae_tile_side = 256,+ )+ v = _verdict(2400, 1792, _card(16), allow_oversized = True, **kw)+ assert v.action == ACTIVATION_TILE+ assert v.overridden+ assert v.message is None+ kw["vae_tile_side"] = None+ v = _verdict(2400, 1792, _card(16), allow_oversized = True, **kw)+ assert v.action == ACTIVATION_RUN and v.overridden+++def test_an_override_under_quadratic_attention_still_tiles_the_vae():+ v = _verdict(+ 2048, 2048, _card(16), vae_tile_side = 256, quadratic_attention = True, allow_oversized = True+ )+ assert v.action == ACTIVATION_TILE and v.overridden+ assert v.tiled_needed_mib is None+++def test_the_env_var_still_overrides_for_server_installs(monkeypatch):+ monkeypatch.setenv(OVERSIZED_GENERATE_ENV, "1")+ v = _verdict(2048, 2048, _card(16), vae_tile_side = None)+ assert v.action == ACTIVATION_RUN and v.overridden+ assert (+ image_activation_shortfall_message(+ device_memory = _card(16), width = 2048, height = 2048, family = _QWEN_HINT+ )+ is None+ )+++def test_the_override_does_not_change_requests_that_fit():+ v = _verdict(1024, 1024, _card(16), vae_tile_side = 256, allow_oversized = True)+ assert v.action == ACTIVATION_RUN and not v.overridden+++def test_raiser_returns_the_verdict_and_raises_only_on_refuse():+ tile = dm.raise_on_image_activation_shortfall(+ device_memory = _card(16), width = 2048, height = 2048, family = _QWEN_HINT, vae_tile_side = 256+ )+ assert tile.action == ACTIVATION_TILE+ with pytest.raises(dm.ImageActivationShortfallError):+ dm.raise_on_image_activation_shortfall(+ device_memory = _card(16), width = 2048, height = 2048, family = _QWEN_HINT+ )+++# (hint, tile side, side, measured denoise peak, measured tiled VAE peak), MiB, diffusers img2img.+_MEASURED = [+ (_QWEN_HINT, 256, 1024, 369, 275),+ (_QWEN_HINT, 256, 1536, 819, 285),+ (_QWEN_HINT, 256, 2048, 1456, 304),+ (_ZIMAGE_HINT, 1024, 1024, 478, 2434),+ (_ZIMAGE_HINT, 1024, 1536, 1071, 2434),+ (_ZIMAGE_HINT, 1024, 2048, 1899, 2455),+ ("flux|x|black-forest-labs/FLUX.1-schnell", 1024, 2048, 1701, 2455),+ ("sdxl|x|stabilityai/sdxl-turbo", 1024, 2048, 645, 4908),+]++[email protected]("hint,tile,side,denoise,vae", _MEASURED)+def test_the_tiled_estimate_covers_every_measured_peak(hint, tile, side, denoise, vae):+ est = estimate_tiled_image_runtime_mib(width = side, height = side, family = hint, tile_side = tile)+ assert est >= 1.2 * max(denoise, vae), (hint, side, est)+++def test_the_tiled_estimate_covers_the_measured_edit_with_a_condition_image():+ cond = int(1024 * 1024 * _Q21_COND_WEIGHT)+ for side, measured in ((1024, 3228), (2048, 4957)):+ est = estimate_tiled_image_runtime_mib(+ width = side, height = side, family = _Q21_HINT, condition_pixels = cond, tile_side = 256+ )+ assert est >= 1.1 * measured, (side, est)+++def test_the_tiled_estimate_never_undercuts_the_untiled_one_at_or_below_a_tile():+ for side in (256, 512, 1024):+ untiled = estimate_image_runtime_mib(width = side, height = side, family = _ZIMAGE_HINT)+ tiled = estimate_tiled_image_runtime_mib(+ width = side, height = side, family = _ZIMAGE_HINT, tile_side = 1024+ )+ assert tiled >= untiled+++def test_the_tiled_estimate_scales_with_batch_and_area():+ one = estimate_tiled_image_runtime_mib(width = 2048, height = 2048, tile_side = 256)+ four = estimate_tiled_image_runtime_mib(width = 2048, height = 2048, batch_size = 4, tile_side = 256)+ assert four >= 4 * dm.DENOISE_MIB_PER_MEGAPIXEL * 4+ assert four > one+++def test_a_tiled_vae_without_slicing_is_priced_at_the_whole_batch():+ sliced = estimate_tiled_image_runtime_mib(+ width = 2048, height = 2048, batch_size = 2, family = _ZIMAGE_HINT, tile_side = 1024, vae_sliced = True+ )+ unsliced = estimate_tiled_image_runtime_mib(+ width = 2048, height = 2048, batch_size = 2, family = _ZIMAGE_HINT, tile_side = 1024+ )+ one = estimate_image_runtime_mib(width = 1024, height = 1024, family = _ZIMAGE_HINT)+ assert sliced == one+ assert unsliced >= 2 * one+ card = _card(16)+ kw = dict(family = _ZIMAGE_HINT, batch_size = 2, vae_tile_side = 1024, source_driven = True)+ assert _verdict(2048, 2048, card, vae_sliced = True, **kw).action == ACTIVATION_TILE+ assert _verdict(2048, 2048, card, vae_sliced = False, **kw).action == ACTIVATION_REFUSE+++class _Vae:+ def __init__(self, **attrs):+ self.use_tiling = False+ self.use_slicing = False+ self.calls: list[str] = []+ for k, v in attrs.items():+ setattr(self, k, v)++ def enable_tiling(self):+ self.calls.append("enable_tiling")+ self.use_tiling = True++ def disable_tiling(self):+ self.calls.append("disable_tiling")+ self.use_tiling = False++ def enable_slicing(self):+ self.calls.append("enable_slicing")+ self.use_slicing = True++ def disable_slicing(self):+ self.calls.append("disable_slicing")+ self.use_slicing = False+++class _NoTileVae:+ pass+++def test_vae_tile_side_reads_diffusers_attributes():+ assert dm.vae_tile_side(_Vae(tile_sample_min_size = 1024)) == 1024+ assert dm.vae_tile_side(_Vae(tile_sample_min_height = 256, tile_sample_min_width = 256)) == 256+ assert dm.vae_tile_side(_Vae()) == dm.DEFAULT_VAE_TILE_SIDE+ assert dm.vae_tile_side(_Vae(tile_sample_min_size = (512, 768))) == 768+ assert dm.vae_tile_side(_NoTileVae()) is None+ assert dm.vae_tile_side(None) is None+++def test_tiling_is_engaged_for_one_call_and_undone():+ vae = _Vae()++ class _Pipe:+ pass++ pipe = _Pipe()+ pipe.vae = vae+ restore = dm.engage_vae_tiling_for_call(pipe)+ assert vae.use_tiling and vae.use_slicing+ restore()+ assert not vae.use_tiling and not vae.use_slicing+ assert vae.calls == ["enable_tiling", "enable_slicing", "disable_tiling", "disable_slicing"]+++def test_a_vae_the_load_already_tiled_is_left_tiled():+ vae = _Vae()+ vae.use_tiling = vae.use_slicing = True++ class _Pipe:+ pass++ pipe = _Pipe()+ pipe.vae = vae+ assert dm.engage_vae_tiling_for_call(pipe) is None+ assert vae.use_tiling and vae.calls == []+++def test_a_vae_whose_tiling_fails_reports_it_is_not_tiled():+ class _BrokenTilingVae(_Vae):+ def enable_tiling(self):+ raise RuntimeError("no tiling on this build")++ vae = _BrokenTilingVae()++ class _Pipe:+ pass++ pipe = _Pipe()+ pipe.vae = vae+ restore, tiled = dm.engage_vae_tiling(pipe)+ assert tiled is False+ assert vae.use_slicing and not vae.use_tiling+ restore()+ assert not vae.use_slicing+ vae = _Vae()+ vae.use_tiling = True+ pipe.vae = vae+ assert dm.engage_vae_tiling(pipe)[1] is True+ pipe.vae = _Vae()+ assert dm.engage_vae_tiling(pipe)[1] is True+++def test_vae_slicing_helpers():+ assert dm.vae_can_slice(_Vae()) and not dm.vae_is_sliced(_Vae())+ assert dm.vae_is_sliced(_Vae(use_slicing = True))+ assert not dm.vae_can_slice(_NoTileVae()) and not dm.vae_is_sliced(_NoTileVae())+ assert not dm.vae_can_slice(None) and not dm.vae_is_sliced(None)diff --git a/studio/frontend/src/features/images/api.ts b/studio/frontend/src/features/images/api.tsindex 2224e8cf7bc..03577549876 100644--- a/studio/frontend/src/features/images/api.ts+++ b/studio/frontend/src/features/images/api.ts@@ -4,6 +4,11 @@import { withBackgroundLoadNotice } from "@/lib/model-lifecycle-events";import { authFetch } from "@/features/auth";import { readFastApiError } from "@/lib/format-fastapi-error";+import {+ isMemoryEstimateRefusal,+ MEMORY_REFUSAL_HEADER,+ MemoryEstimateRefusalError,+} from "./lib/memory-refusal";// One Advanced control's resolved value and provenance, for the Advanced-panel badges. `value` is the engaged// value (null when off), `requested` is what the caller asked for (null = left to the backend), `source` is "auto"@@ -159,6 +164,7 @@ export interface DiffusionGenerateRequest {strength?: number;// Upscale (hires fix): factor > 1 with an init_image enlarges the source and re-denoises at low strength.upscale?: number;+ allow_oversized?: boolean;// Additional images after init_image, in order, for the reference and edit workflows.reference_images?: string[];workflow?: "edit" | "reference";@@ -407,6 +413,12 @@ export async function generateDiffusionImage(}throw new GenerateResponseLostError(detail);}+ if (+ !response.ok &&+ isMemoryEstimateRefusal(response.status, response.headers.get(MEMORY_REFUSAL_HEADER))+ ) {+ throw new MemoryEstimateRefusalError(await readFastApiError(response));+ }return parseJson(response);}diff --git a/studio/frontend/src/features/images/images-page.tsx b/studio/frontend/src/features/images/images-page.tsxindex 86831bab290..15cec320780 100644--- a/studio/frontend/src/features/images/images-page.tsx+++ b/studio/frontend/src/features/images/images-page.tsx@@ -219,6 +219,15 @@ import {shouldContinueGenerating,shouldReportGenerateError,} from "./lib/generation-stop";+import {+ ALLOW_OVERSIZED_HINT,+ ALLOW_OVERSIZED_LABEL,+ allowOversizedField,+ GENERATE_ANYWAY_LABEL,+ MEMORY_REFUSAL_TITLE,+ shouldOfferGenerateAnyway,+ shouldRunQueuedOversizedRetry,+} from "./lib/memory-refusal";import { useNavigate, useSearch } from "@tanstack/react-router";import { useStagedDownload, type StagedDownloadEntry } from "@/features/hub/download-manager";import { DiffusionTrainPanel } from "./train/diffusion-train-panel";@@ -1245,7 +1254,7 @@ export function ImagesPage({}) {const initialReadySent = useRef(false);const [rememberedModel, setRememberedModel] = useState(readImageModel);- const pendingRecalledGeneration = useRef<{ model: RememberedImageModel; load: number; workflow: WorkflowId } | null>(null);+ const pendingRecalledGeneration = useRef<{ model: RememberedImageModel; load: number; workflow: WorkflowId; allowOversized?: boolean } | null>(null);const { isMobile, pinned } = useSidebar();const hostClass = useHostClass();const denseQuantSchemes = useDenseQuantSchemes();@@ -1390,6 +1399,12 @@ export function ImagesPage({const [advancedOpen, setAdvancedOpen] = usePersistedToggle("unsloth_images_advanced_open",);+ const [allowOversized, setAllowOversized] = usePersistedToggle(+ "unsloth_images_allow_oversized",+ );+ const oversizedOnce = useRef(false);+ // Queued: "Generate anyway" is clickable before the refused run releases busy.+ const [oversizedRetryQueued, setOversizedRetryQueued] = useState(false);// Advanced (load-time) options; "auto"/"off"/"none" map to the backend defaults. Changing one// while loaded shows "Reapply".const [modelSelectionAction, setModelSelectionAction] = useState<"load" | "download">("load");@@ -3830,6 +3845,9 @@ export function ImagesPage({);const handleGenerate = useCallback(async () => {+ // Consume before any early return so it never leaks into a later run.+ const allowOversizedSent = allowOversizedField(allowOversized, oversizedOnce.current) === true;+ oversizedOnce.current = false;if (!prompt.trim()) {toast.error("Prompt is empty");return;@@ -4049,6 +4067,7 @@ export function ImagesPage({mask_image: condMask,strength: condStrength,upscale: condUpscale,+ allow_oversized: allowOversizedSent ? true : undefined,...condFields,// Drop empty and zero-weight rows and trim hand-typed repo ids, so the recipe records only// adapters that applied. Gated on loraCapable, since a restore can leave adapters in state.@@ -4102,13 +4121,20 @@ export function ImagesPage({// The user's own Stop comes back as the backend's cancelled sentinel (409), so it is not// toasted. Only a Stop the backend confirmed explains an error away: a POST that never// landed, or {cancelled: false}, means whatever it raised is a real failure.- if (- shouldReportGenerateError({- message: msg,- stopRequested: cancelRequested.current && cancelAcked.current,- })- )- toast.error(msg);+ const report = shouldReportGenerateError({+ message: msg,+ stopRequested: cancelRequested.current && cancelAcked.current,+ });+ if (report && shouldOfferGenerateAnyway({ error: err, allowOversizedSent })) {+ toast.error(MEMORY_REFUSAL_TITLE, {+ description: msg,+ duration: 20_000,+ action: {+ label: GENERATE_ANYWAY_LABEL,+ onClick: () => setOversizedRetryQueued(true),+ },+ });+ } else if (report) toast.error(msg);} finally {if (genPollTimer.current) clearInterval(genPollTimer.current);genPollTimer.current = null;@@ -4126,7 +4152,7 @@ export function ImagesPage({setGenDone(null);setGenStep(null);}- }, [prompt, negativePrompt, width, height, steps, guidance, seed, batchSize, count, workflow, initImage, maskImage, strength, extendPct, extendSides, upscaleFactor, upscaleStrength, referenceImages, loras, loraCapable, controlnetCapable, controlnetId, controlImage, controlType, controlStrength, ensureSrc, loadGallery, refreshStatus, unifiedEdit, localizedMode, localizedLayer, maxExtras, referenceResolution, conditioning, editSize, editSizing, sizeLimits]);+ }, [allowOversized, prompt, negativePrompt, width, height, steps, guidance, seed, batchSize, count, workflow, initImage, maskImage, strength, extendPct, extendSides, upscaleFactor, upscaleStrength, referenceImages, loras, loraCapable, controlnetCapable, controlnetId, controlImage, controlType, controlStrength, ensureSrc, loadGallery, refreshStatus, unifiedEdit, 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.@@ -4188,6 +4214,8 @@ export function ImagesPage({model: rememberedModel,load: loadSeq.current + 1,workflow,+ // "Generate anyway" on an unloaded model: the retry's finally clears the one-shot before this runs.+ allowOversized: oversizedOnce.current,};const started = await handleLoad(rememberedModel.repoId,@@ -4206,6 +4234,14 @@ export function ImagesPage({status,workflow,]);+ useEffect(() => {+ if (!shouldRunQueuedOversizedRetry({ queued: oversizedRetryQueued, busy })) return;+ setOversizedRetryQueued(false);+ oversizedOnce.current = true;+ void handleGenerateWithRecall().finally(() => {+ oversizedOnce.current = false;+ });+ }, [oversizedRetryQueued, busy, handleGenerateWithRecall]);useEffect(() => {const pending = pendingRecalledGeneration.current;@@ -4229,7 +4265,11 @@ export function ImagesPage({);return;}- if (matchesRememberedModel(pending.model, status)) void handleGenerate();+ if (!matchesRememberedModel(pending.model, status)) return;+ oversizedOnce.current = pending.allowOversized === true;+ void handleGenerate().finally(() => {+ oversizedOnce.current = false;+ });}, [active, busy, handleGenerate, status, workflow]);// Publish what the loaded model can do, so the sidebar submenu dims the rest. null while@@ -4404,6 +4444,17 @@ export function ImagesPage({</span><Switch checked={cpuOffload} onCheckedChange={setCpuOffload} /></div>+ <div className="flex items-center justify-between">+ <span className="flex items-center gap-1 text-xs font-medium text-muted-foreground">+ {ALLOW_OVERSIZED_LABEL}+ <InfoHint>{ALLOW_OVERSIZED_HINT}</InfoHint>+ </span>+ <Switch+ checked={allowOversized}+ onCheckedChange={setAllowOversized}+ aria-label={ALLOW_OVERSIZED_LABEL}+ />+ </div><LoadedBuildSummary status={status} />{/* A resident full pipeline is reloadable by repo id alone, so it keeps Reapply even before auser-initiated load; GGUF/single_file residents hide the button. */}diff --git a/studio/frontend/src/features/images/lib/memory-refusal.ts b/studio/frontend/src/features/images/lib/memory-refusal.tsnew file mode 100644index 00000000000..4032b82dca0--- /dev/null+++ b/studio/frontend/src/features/images/lib/memory-refusal.ts@@ -0,0 +1,55 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++/** Backend: diffusion_memory.IMAGE_REFUSAL_HEADER. */+export const MEMORY_REFUSAL_HEADER = "X-Unsloth-Refusal";+export const MEMORY_REFUSAL_KIND = "memory-estimate";++/** The backend quotes this label in the refusal text; keep the two identical. */+export const ALLOW_OVERSIZED_LABEL = "Allow oversized generations";+export const ALLOW_OVERSIZED_HINT =+ "Run a generation even when the memory check estimates it will not fit this GPU. Applies to the next generation, no reload needed. Sizes that fit with tiled VAE decoding already run without this. An oversized run can stop with an out-of-memory error, or on Windows spill into system RAM and slow the whole computer.";+export const MEMORY_REFUSAL_TITLE = "Not enough GPU memory for this size";+export const GENERATE_ANYWAY_LABEL = "Generate anyway";++export class MemoryEstimateRefusalError extends Error {+ constructor(message: string) {+ super(message);+ this.name = "MemoryEstimateRefusalError";+ }+}++export function isMemoryEstimateRefusal(+ status: number,+ refusalHeader: string | null | undefined,+): boolean {+ return (+ status === 400 &&+ (refusalHeader ?? "").trim().toLowerCase() === MEMORY_REFUSAL_KIND+ );+}++/** Not when the run already sent the override: then the refusal means something else changed. */+export function shouldOfferGenerateAnyway(input: {+ error: unknown;+ allowOversizedSent: boolean;+}): boolean {+ return (+ input.error instanceof MemoryEstimateRefusalError && !input.allowOversizedSent+ );+}++export function allowOversizedField(+ persistedSetting: boolean,+ oneShot: boolean,+): true | undefined {+ return persistedSetting || oneShot ? true : undefined;+}++/** A retry started while the refused run is still busy is dropped by the generate guard. */+export function shouldRunQueuedOversizedRetry(input: {+ queued: boolean;+ busy: unknown;+}): boolean {+ return input.queued && input.busy === null;+}diff --git a/studio/frontend/tests/image-memory-refusal.test.ts b/studio/frontend/tests/image-memory-refusal.test.tsnew file mode 100644index 00000000000..fa3ac4a9a7e--- /dev/null+++ b/studio/frontend/tests/image-memory-refusal.test.ts@@ -0,0 +1,86 @@+// 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 {+ ALLOW_OVERSIZED_LABEL,+ allowOversizedField,+ isMemoryEstimateRefusal,+ MEMORY_REFUSAL_HEADER,+ MEMORY_REFUSAL_KIND,+ MemoryEstimateRefusalError,+ shouldOfferGenerateAnyway,+ shouldRunQueuedOversizedRetry,+} from "../src/features/images/lib/memory-refusal.ts";+import { readSrc, readText } from "./helpers/kit.ts";++test("only a 400 tagged as the memory estimate is the memory refusal", () => {+ assert.equal(isMemoryEstimateRefusal(400, MEMORY_REFUSAL_KIND), true);+ assert.equal(isMemoryEstimateRefusal(400, " Memory-Estimate "), true);+ assert.equal(isMemoryEstimateRefusal(400, null), false);+ assert.equal(isMemoryEstimateRefusal(400, "something-else"), false);+ assert.equal(isMemoryEstimateRefusal(500, MEMORY_REFUSAL_KIND), false);+ assert.equal(isMemoryEstimateRefusal(409, MEMORY_REFUSAL_KIND), false);+});++test("Generate anyway is offered for the refusal, and not again once the override was sent", () => {+ const refusal = new MemoryEstimateRefusalError("Generating at 2048x2048 needs about 34 GB");+ assert.equal(shouldOfferGenerateAnyway({ error: refusal, allowOversizedSent: false }), true);+ assert.equal(shouldOfferGenerateAnyway({ error: refusal, allowOversizedSent: true }), false);+ assert.equal(+ shouldOfferGenerateAnyway({ error: new Error("width is required"), allowOversizedSent: false }),+ false,+ );+});++test("allow_oversized is sent only when the setting or the one-shot retry asks for it", () => {+ assert.equal(allowOversizedField(false, false), undefined);+ assert.equal(allowOversizedField(true, false), true);+ assert.equal(allowOversizedField(false, true), true);+});++test("the setting label matches the one the backend quotes in its refusal", () => {+ const backend = readText("../../backend/core/inference/diffusion_memory.py");+ assert.ok(+ backend.includes(`OVERSIZED_GENERATE_SETTING_LABEL = "${ALLOW_OVERSIZED_LABEL}"`),+ "the refusal would point at a setting the page does not show",+ );+ assert.ok(backend.includes(`IMAGE_REFUSAL_HEADER = "${MEMORY_REFUSAL_HEADER}"`));+ assert.ok(backend.includes(`IMAGE_REFUSAL_MEMORY_ESTIMATE = "${MEMORY_REFUSAL_KIND}"`));+ const main = readText("../../backend/main.py");+ assert.match(main, /expose_headers = \[[^\]]*"X-Unsloth-Refusal"/);+});++test("the page wires the setting, the request field and the toast action", () => {+ const page = readSrc("features/images/images-page.tsx");+ assert.match(page, /usePersistedToggle\(\s*"unsloth_images_allow_oversized"/);+ assert.match(page, /allow_oversized: allowOversizedSent \? true : undefined/);+ assert.match(page, /label: GENERATE_ANYWAY_LABEL/);+ assert.match(page, /checked=\{allowOversized\}/);+ const api = readSrc("features/images/api.ts");+ assert.match(api, /allow_oversized\?: boolean;/);+ assert.match(api, /throw new MemoryEstimateRefusalError\(/);+});++test("Generate anyway clicked during the refused run's cleanup waits for busy to clear", () => {+ assert.equal(shouldRunQueuedOversizedRetry({ queued: true, busy: "generating" }), false);+ assert.equal(shouldRunQueuedOversizedRetry({ queued: true, busy: null }), true);+ assert.equal(shouldRunQueuedOversizedRetry({ queued: false, busy: null }), false);+ const page = readSrc("features/images/images-page.tsx");+ assert.match(page, /onClick: \(\) => setOversizedRetryQueued\(true\)/);+ assert.match(+ page,+ /shouldRunQueuedOversizedRetry\(\{ queued: oversizedRetryQueued, busy \}\)[\s\S]*?\}, \[oversizedRetryQueued, busy, handleGenerateWithRecall\]\);/,+ );+});++test("Generate anyway on an unloaded model keeps the override for the recalled generation", () => {+ const page = readSrc("features/images/images-page.tsx");+ assert.match(page, /load: loadSeq\.current \+ 1,[\s\S]*?allowOversized: oversizedOnce\.current,/);+ assert.match(+ page,+ /oversizedOnce\.current = pending\.allowOversized === true;\s*void handleGenerate\(\)/,+ );+});diff --git a/studio/frontend/tests/image-model-recall.test.ts b/studio/frontend/tests/image-model-recall.test.tsindex 3707c9ac796..c171a0e0f7d 100644--- a/studio/frontend/tests/image-model-recall.test.ts+++ b/studio/frontend/tests/image-model-recall.test.ts@@ -70,6 +70,7 @@ test("recalling a quantized model carries the selected adapters into its load",prompt: "a teapot",rememberedModel: model,pendingRecalledGeneration: { current: null },+ oversizedOnce: { current: false },loadSeq: { current: 3 },workflow: "txt2img",handleGenerate: () => {@@ -84,6 +85,8 @@ test("recalling a quantized model carries the selected adapters into its load",...Object.values(scope),);await callbacks.handleGenerateWithRecall();+ const pending = scope.pendingRecalledGeneration.current as { allowOversized?: boolean } | null;+ assert.equal(pending?.allowOversized, false);assert.equal(loads.length, 1);assert.equal(loads[0][0], model.repoId);assert.deepEqual(loads[0][1], {