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: make the image memory plan resolution-aware and stop reserving the text encoder during sampling (#8224)
Daniel Hanf55d7360e57d
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.pyindex cd7e0bbbac2..61526be2c64 100644--- a/studio/backend/core/inference/diffusion.py+++ b/studio/backend/core/inference/diffusion.py@@ -22,11 +22,12 @@ import inspectimport jsonimport osimport re+import sysimport threadingimport timefrom dataclasses import dataclassfrom pathlib import Path-from typing import Any, Callable, Optional+from typing import Any, Callable, Optional, Sequencefrom core._torchao_stub import (install_torchao_windows_rocm_stub,@@ -74,6 +75,8 @@ from .diffusion_memory import (normalize_memory_mode,plan_diffusion_memory,plan_fits_total_capacity,+ raise_on_image_activation_shortfall,+ reclaimable_snapshot_device_memory,refine_memory_plan_for_components,settled_snapshot_device_memory,)@@ -417,6 +420,29 @@ def _clamp_max_side(img: Any, max_side: int) -> Any:return img.resize((nw, nh), Image.LANCZOS)+def _image_variant_hint(+ family_name: Optional[str],+ single_file_name: Optional[str],+ repo_id: Optional[str],+ base: Optional[str],+) -> str:+ """The free-text hint ``estimate_image_runtime_mib`` scans for distilled / turbo / edit+ markers, built from every identifier this load carries.++ Both ``repo_id`` AND ``base`` go in. Picking one (``repo_id or base``) dropped the base+ whenever a repo id existed, which is every GGUF load, and the base is precisely where the+ marker usually lives: ``unsloth/Z-Image-GGUF`` says nothing while its base+ ``Tongyi-MAI/Z-Image-Turbo`` says turbo, so the 0.85 distilled discount never fired for the+ models most likely to be running on a card that needs it. Deduplicated (a pipeline load passes+ the same id as both) and order-stable, so the hint is a pure function of the load."""+ parts: list[str] = []+ for part in (family_name, single_file_name, repo_id, base):+ text = (part or "").strip()+ if text and text not in parts:+ parts.append(text)+ return " ".join(parts)++def _compile_shape_dims(workflow: str, init_pil: Any, width: int, height: int) -> tuple[int, int]:"""The (width, height) a generation's forward ACTUALLY runs at, for staticcompile-cache shape registration.@@ -714,6 +740,10 @@ class _LoadState:resolved: Optional[dict] = None# The single-file checkpoint basename this load committed (None for a pipeline). Part of the build identity.gguf_filename: Optional[str] = None+ # The exact variant hint the memory plan was built from (family + checkpoint name + repo ids).+ # Stored rather than rebuilt so generate()'s activation re-check budgets with the SAME+ # distilled / edit multipliers the load did, and the two can never drift apart.+ variant_hint: str = ""@dataclass@@ -861,6 +891,24 @@ def _uncached_prequant_repo(return None+def _activation_guard_batch(chunks: Sequence[Sequence[Any]]) -> int:+ """The batch size the generate-time activation guard budgets for.++ One image, normally. The OOM backoff halves a failed multi-image forward all the way down to+ SINGLETONS, so an oversized batch is already recoverable wherever torch raises; budgeting the+ whole chunk here would refuse batches that complete today (the measured batch-32 fast path).+ A single image that does not fit is the case no backoff can rescue, so that is the floor.++ Windows is the exception, and it is the exception this guard was written for. Under WDDM the+ driver satisfies a device overflow out of system RAM instead of raising, so no+ OutOfMemoryError ever reaches the backoff and an overrunning batch simply grows into tens of+ GB of host RAM and pagefile with the desktop unresponsive. Nothing recovers that after the+ fact, so the largest real chunk is budgeted up front there."""+ if sys.platform != "win32":+ return 1+ return max((len(chunk) for chunk in chunks), default = 1)++def _memory_request_forces_offload(memory_mode: Optional[str], cpu_offload: bool) -> bool:"""Whether this memory request offloads the transformer no matter what the weights measure.@@ -2194,6 +2242,36 @@ class DiffusionBackend:staged_dir,)+ @staticmethod+ def _local_dir_text_encoder_sizes(path: Path) -> dict[str, int]:+ """``{relative path: on-disk bytes}`` for the TEXT-ENCODER weight files under a diffusers+ directory: the ``text_encoder*`` subfolders of what ``_local_dir_weight_sizes`` returns.++ Derived from that same walk rather than a second one, so the text-encoder term is a strict+ subset of the companion term the planner subtracts it from. Deriving it independently could+ make the subtraction go negative on a tree where one walk saw a file the other did not."""+ return {+ rel: size+ for rel, size in DiffusionBackend._local_dir_weight_sizes(+ path, exclude_transformer = True+ ).items()+ # Prefix, not equality: families ship text_encoder, text_encoder_2, text_encoder_3.+ if rel.split("/", 1)[0].startswith("text_encoder")+ }++ @staticmethod+ def _text_encoder_cache_bytes(base: str, staged_dir: Optional[str] = None) -> int:+ """Text-encoder size for the memory plan: the share of ``_companion_cache_bytes`` the+ planner can move off the resident floor by streaming the encoders.++ Same union-over-cache-roots merge as the companion total, keyed on the same relative+ paths, so a repo split across two roots is counted once in BOTH terms."""+ return DiffusionBackend._union_over_cached_revs(+ base,+ DiffusionBackend._local_dir_text_encoder_sizes,+ staged_dir,+ )+@staticmethoddef _safetensors_param_count(path: Path) -> int:"""Total tensor elements in a safetensors file, read from its JSON header without@@ -2498,6 +2576,13 @@ class DiffusionBackend:),# Pass the companion estimate so prefetched base shards aren't double-counted.companion_override_mib = candidate.companions_mib,+ # ... and its text-encoder share, so the planner can still price+ # the streamed-encoder group tier on this path. getattr: a+ # candidate without the split (a duck-typed or older estimate)+ # passes None and keeps the previous decision.+ text_encoder_override_mib = getattr(+ candidate, "text_encoders_mib", None+ ),)if candidate is None:@@ -3278,6 +3363,14 @@ class DiffusionBackend:hf_token = hf_token,resolved = resolved,gguf_filename = gguf_filename,+ # Built from the artifact this load COMMITTED to, by the same helper+ # _plan_memory used, so the generate-time re-check reuses it verbatim.+ variant_hint = _image_variant_hint(+ fam.name,+ Path(single_file_path).name if single_file_path else None,+ repo_id,+ base,+ ),)state_committed = Truefinally:@@ -3552,6 +3645,7 @@ class DiffusionBackend:repo_id: Optional[str] = None,transformer_resident_override_mib: Optional[int] = None,companion_override_mib: Optional[int] = None,+ text_encoder_override_mib: Optional[int] = None,base_local_dir: Optional[str] = None,fetch_base: Optional[str] = None,):@@ -3571,7 +3665,10 @@ class DiffusionBackend:``companion_override_mib`` likewise replaces the cached companion total on thatre-plan, so the base repo's PREFETCHED transformer/ shards -- which land in thesame blob cache _companion_cache_bytes sums -- are not counted as companions on- top of transformer_resident_override_mib (a double-count of the transformer).+ top of transformer_resident_override_mib (a double-count of the transformer);+ ``text_encoder_override_mib`` carries that override's TEXT-ENCODER share, which the+ planner needs to price the streamed-text-encoder group tier. Both come from the same+ family component table, so they cannot disagree about what the companions are.``base_local_dir`` is the snapshot the load will actually read, carried into the size lookupsas an extra source alongside the cache roots. A prefetch split across roots hands back no@@ -3626,6 +3723,9 @@ class DiffusionBackend:table_mib if model_dense_mib is None else max(model_dense_mib, table_mib))companion_mib = None+ # No companion total on this branch (the whole repo IS the model), so there is no+ # split to hand the planner either. None, not a guess: it reproduces the old decision.+ text_encoder_mib = Noneelse:if transformer_resident_override_mib is not None:# Planning the dense-quant candidate: the auto-policy estimate replaces the file-size derivation.@@ -3644,31 +3744,40 @@ class DiffusionBackend:if companion_override_mib is not None:# Re-planning the dense candidate: the prefetched transformer/ shards land in the same cache, so use the estimate instead of double-counting.companion_mib = companion_override_mib+ # The text-encoder share of that same override, from the same family component+ # table, so the two terms cannot disagree. None when the caller has no split.+ text_encoder_mib = text_encoder_override_mibelse:# Scan the repo the bytes were staged from, and hand over the staged snapshot too: a# base served from the import-time root is invisible to a hub-id scan of the live# one, so the VAE + text encoders would load unbudgeted.companion = self._companion_cache_bytes(fetch_base or base, base_local_dir)companion_mib = int(companion // (1024 * 1024)) if companion else None+ # The text-encoder share of that companion total, from the SAME walk over the same+ # trees, so the subtraction the planner does is exact rather than two estimates+ # meeting in the middle. 0 bytes reads as "nothing cached", i.e. no split.+ text_encoder = self._text_encoder_cache_bytes(fetch_base or base, base_local_dir)+ text_encoder_mib = int(text_encoder // (1024 * 1024)) if text_encoder else Nonemodel_dense_mib = Noneif transformer_resident is not None:model_dense_mib = transformer_resident + (companion_mib or 0)# Feed the variant hint so estimate_image_runtime_mib sees distilled markers (distilled needs ~15% less headroom).- variant_hint = " ".join(- p- for p in (- fam.name,- Path(single_file_path).name if single_file_path else "",- repo_id or base or "",- )- if p+ variant_hint = _image_variant_hint(+ fam.name,+ Path(single_file_path).name if single_file_path else None,+ repo_id,+ base,)+ # No dimensions on purpose: load time genuinely does not know what the user will generate+ # at, so this budgets the 1024x1024 default for PLACEMENT. generate() re-checks the real+ # resolution against the free budget before it samples (raise_on_image_activation_shortfall).runtime_headroom = estimate_image_runtime_mib(width = None, height = None, family = variant_hint)return plan_diffusion_memory(target = target,device_memory = device_memory,model_dense_mib = model_dense_mib,companion_dense_mib = companion_mib,+ text_encoder_dense_mib = text_encoder_mib,runtime_headroom_mib = runtime_headroom,requested_mode = memory_mode,explicit_offload = cpu_offload,@@ -4363,6 +4472,46 @@ class DiffusionBackend:# Per-forward chunks: the whole job list in ONE forward by default (batch 32 on 4-step models is ~10-22x over# serial engines), bounded by an explicit batch_size cap; the OOM backoff below halves a failed chunk.chunks = chunk_jobs(jobs, batch_size)++ # Resolution-aware re-check, with the size this call ACTUALLY runs at. The load-time+ # plan budgeted the 1024x1024 default because load time cannot know the request, so+ # a much larger frame has never been compared against anything. Do it here, before+ # any latent is allocated: weights can be offloaded but activations cannot, so an+ # activation estimate over the free budget overruns at EVERY offload tier, and the+ # refusal is a fact rather than a tuning guess. Best-effort throughout -- a probe+ # that fails must never block a generation that would have worked.+ try:+ # The dimensions the forward runs at, not the sliders: img2img / inpaint /+ # upscale / edit take their output size from the input image. Same derivation+ # the compile-cache shape registration uses further down.+ guard_width, guard_height = _compile_shape_dims(+ workflow, init_pil, width, height+ )+ guard_batch = _activation_guard_batch(chunks)+ raise_on_image_activation_shortfall(+ # 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 -- it+ # releases every cached block, so the next forward re-cudaMallocs all of+ # its activations, defeating the caching allocator on every image. This+ # variant credits the same reclaimable bytes back arithmetically instead,+ # so a warm allocator does not read as a full card and nothing is flushed.+ device_memory = reclaimable_snapshot_device_memory(+ self._resolve_device_target(state.family)+ ),+ width = guard_width,+ height = guard_height,+ batch_size = guard_batch,+ # The hint the load planned with, so the distilled / edit multipliers match.+ family = state.variant_hint,+ logger = logger,+ )+ except ValueError:+ raise # the refusal itself: the route turns this into a 400 with the reason+ except Exception as exc: # noqa: BLE001 — fail OPEN on a broken probe+ logger.warning(+ "diffusion.generate: activation headroom re-check skipped (%s)", exc+ )+gen = _GenState(total_steps = 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]diff --git a/studio/backend/core/inference/diffusion_auto_policy.py b/studio/backend/core/inference/diffusion_auto_policy.pyindex 4e7e84b6aa7..b456917ba8d 100644--- a/studio/backend/core/inference/diffusion_auto_policy.py+++ b/studio/backend/core/inference/diffusion_auto_policy.py@@ -106,6 +106,11 @@ class DenseQuantEstimate:companions_mib: intprequant: booldownload_transformer_mib: int = 0+ # The TEXT-ENCODER share of ``companions_mib``. The memory planner needs it to price the+ # group tier that streams the encoders instead of keeping them resident, and this table is+ # the only place the split exists on the dense-candidate path. Defaulted so any construction+ # that predates it still works (the planner reads a 0 split as "no split", i.e. no new tier).+ text_encoders_mib: int = 0@propertydef transient_total_mib(self) -> int:@@ -141,6 +146,9 @@ def estimate_dense_quant(companions_mib = companions,prequant = prequant_available,download_transformer_mib = int(transformer_gb * hub_factor * _MIB_PER_GB),+ # Same conversion as `companions`, of which this is the text-encoder half, so the planner's+ # `companions - text_encoders` is the VAE and nothing else.+ text_encoders_mib = int(text_encoders_gb * _MIB_PER_GB),)diff --git a/studio/backend/core/inference/diffusion_memory.py b/studio/backend/core/inference/diffusion_memory.pyindex e034c93210c..dc224c85e5e 100644--- a/studio/backend/core/inference/diffusion_memory.py+++ b/studio/backend/core/inference/diffusion_memory.py@@ -105,6 +105,10 @@ class MemoryPlan:device_memory: DeviceMemoryestimates: dict[str, Optional[int]]reasons: tuple[str, ...] = ()+ # Under group offload, stream the TEXT ENCODERS alongside the transformer instead of keeping+ # them resident. Defaulted so every existing construction is unchanged; set only where that+ # is what makes group offload fit at all (see plan_diffusion_memory).+ stream_text_encoders: bool = False@propertydef engages_offload(self) -> bool:@@ -119,6 +123,7 @@ class MemoryPlan:"device_memory": self.device_memory.as_public_dict(),"estimates": dict(self.estimates),"reasons": list(self.reasons),+ "stream_text_encoders": self.stream_text_encoders,}@@ -146,6 +151,49 @@ def snapshot_device_memory(target: Any) -> DeviceMemory:return DeviceMemory(backend, device, "system_memory", free, total)+def reclaimable_snapshot_device_memory(target: Any) -> DeviceMemory:+ """``snapshot_device_memory`` with the caching allocator's RECLAIMABLE bytes credited back+ as free, without flushing it.++ ``torch.cuda.mem_get_info`` reports driver-level free memory, so every block the caching+ allocator is holding for reuse counts as used even though the next allocation would take it+ straight back. A generation that has already run therefore looks like it is on a much smaller+ card than it is. ``settled_snapshot_device_memory`` fixes that with ``empty_cache()``, which is+ right when it runs ONCE per load, but wrong on a per-generation path: releasing every cached+ block forces the next forward to go back to ``cudaMalloc`` for all of its activations, which is+ the exact cost the caching allocator exists to avoid.++ ``memory_reserved() - memory_allocated()`` is that same figure without the flush: bytes this+ process holds and is not using. Adding it back is the honest reading of "how much could this+ generation get". Deliberately an over-estimate at the margin -- fragmentation can stop some of+ it being handed to one large tensor -- because this feeds a REFUSAL, and over-estimating free+ memory can only make the guard quieter, never more trigger-happy.++ Only the process's own allocator is credited. Host memory pinned by ``enable_model_cpu_offload``+ lives outside it and is not counted here, which is correct: it is not device memory this+ generation can allocate into.++ Falls back to the plain snapshot on any failure or non-cuda device."""+ if getattr(target, "device", "cpu") != "cuda":+ return snapshot_device_memory(target)+ snapshot = snapshot_device_memory(target)+ if snapshot.free_mib is None:+ return snapshot+ try:+ import torch+ reclaimable = int(torch.cuda.memory_reserved()) - int(torch.cuda.memory_allocated())+ except Exception: # noqa: BLE001 -- no allocator reading: the plain snapshot still stands+ return snapshot+ if reclaimable <= 0:+ return snapshot+ free = int(snapshot.free_mib) + reclaimable // (1024 * 1024)+ if snapshot.total_mib is not None:+ free = min(free, int(snapshot.total_mib)) # never claim more than the card has+ return DeviceMemory(+ snapshot.backend, snapshot.device, snapshot.memory_kind, free, snapshot.total_mib+ )++def settled_snapshot_device_memory(target: Any,attempts: int = 3,@@ -366,6 +414,7 @@ def plan_diffusion_memory(model_dense_mib: Optional[int],runtime_headroom_mib: int,companion_dense_mib: Optional[int] = None,+ text_encoder_dense_mib: Optional[int] = None,base_overhead_mib: int = DEFAULT_BASE_OVERHEAD_MIB,requested_mode: Optional[str] = None,explicit_offload: bool = False,@@ -374,12 +423,17 @@ def plan_diffusion_memory(``model_dense_mib`` is the resident size of all weights; ``companion_dense_mib`` is just thecompanions, which stay resident under group offload while the transformer streams block by- block. ``explicit_offload`` is the back-compat ``cpu_offload=True`` request (forces model- offload).+ block. ``text_encoder_dense_mib`` is the TEXT-ENCODER share of that companion total, which+ unlocks a second group tier (below); None means "no split available" and reproduces the+ pre-split decision exactly. ``explicit_offload`` is the back-compat ``cpu_offload=True``+ request (forces model offload).Policies by speed/VRAM tradeoff:none - everything resident: fastest, highest VRAM.group - stream the transformer, companions resident: near-resident speed, moderate cut.+ group + streamed text encoders - as above, but the encoders stream too: they run ONCE,+ before step 0, so this costs one extra host-to-device pass per call rather than a+ per-step one, and it frees their bytes for every denoising step.model - offload every component: lowest VRAM, slow.streaming - stream transformer blocks and text-encoder leaves when one component cannot fit."""@@ -389,21 +443,62 @@ def plan_diffusion_memory(required = _sum_required(model_dense_mib, runtime_headroom_mib, base_overhead_mib)# The resident floor under group offload: companions stay, the transformer streams.group_floor = _sum_required(companion_dense_mib, runtime_headroom_mib, base_overhead_mib)+ # A SECOND floor, for the same tier with the text encoders streamed as well. The encoders are+ # the largest companion on most families (Z-Image: 8.0 of 8.2 GB) and they are used exactly+ # once, before step 0, so holding them resident for the whole denoise reserves their bytes for+ # nothing. Streaming them leaves the VAE as the only resident companion. Computed only when+ # BOTH terms are known: an unknown split must reproduce the previous decision, never guess a+ # smaller floor. Clamped at 0 because the two terms can come from different sources.+ group_floor_streamed_te = (+ _sum_required(+ max(0, int(companion_dense_mib) - int(text_encoder_dense_mib)),+ runtime_headroom_mib,+ base_overhead_mib,+ )+ if companion_dense_mib is not None and text_encoder_dense_mib is not None+ else None+ )reasons: list[str] = []+ stream_text_encoders = Falseestimates: dict[str, Optional[int]] = {"safe_device_budget_mib": budget,"model_dense_mib": model_dense_mib,"companion_dense_mib": companion_dense_mib,+ "text_encoder_dense_mib": text_encoder_dense_mib,"runtime_headroom_mib": runtime_headroom_mib,"base_overhead_mib": base_overhead_mib,"resident_required_mib": required,"group_floor_mib": group_floor,+ "group_floor_streamed_te_mib": group_floor_streamed_te,}def _group_fits() -> bool:# Group offload only helps if the resident companions fit; a too-big text encoder needs whole-module offload.return group_floor is not None and budget is not None and group_floor <= budget+ def _group_fits_streamed_te() -> bool:+ # The same tier once the text encoders stream too; only reachable with a known split.+ return (+ group_floor_streamed_te is not None+ and budget is not None+ and group_floor_streamed_te <= budget+ )++ # The best tier available when the weights do not fit resident, in speed order: plain group+ # (companions resident) beats group with streamed encoders (one extra host-to-device pass per+ # CALL) beats whole-module offload (every component paged per STEP -- the 48-minute case).+ def _offload_tier() -> tuple[str, bool]:+ if _group_fits():+ return OFFLOAD_GROUP, False+ if _group_fits_streamed_te():+ return OFFLOAD_GROUP, True+ return OFFLOAD_MODEL, False++ _STREAMED_TE_REASON = (+ "companions exceed budget, but they fit with the text encoders streamed too "+ "(they run once, before step 0); streaming them beats paging every component per step"+ )+if not can_offload or device_memory.is_unified:# MPS / CPU cannot stream to a separate device; on unified memory offload just shuffles bytes within the same pool.policy = OFFLOAD_NONE@@ -415,8 +510,10 @@ def plan_diffusion_memory(policy = OFFLOAD_NONEif budget is not None and required is not None and required > budget:# Doesn't fit resident: streamed transformer is the fastest offload.- policy = OFFLOAD_GROUP if _group_fits() else OFFLOAD_MODEL+ policy, stream_text_encoders = _offload_tier()reasons.append("fast requested but weights do not fit resident; offloading")+ if stream_text_encoders:+ reasons.append(_STREAMED_TE_REASON)else:reasons.append("fast requested; weights resident on device")elif mode == MEMORY_MODE_BALANCED:@@ -434,6 +531,10 @@ def plan_diffusion_memory(elif _group_fits():policy = OFFLOAD_GROUPreasons.append("tight fit; stream the transformer, companions resident")+ elif _group_fits_streamed_te():+ policy = OFFLOAD_GROUP+ stream_text_encoders = True+ reasons.append(_STREAMED_TE_REASON)else:policy = OFFLOAD_MODELreasons.append("companions exceed budget; whole-module offload of every component")@@ -461,6 +562,8 @@ def plan_diffusion_memory(device_memory = device_memory,estimates = estimates,reasons = tuple(reasons),+ # Only ever meaningful under group offload; every other tier already places the encoders.+ stream_text_encoders = stream_text_encoders and policy == OFFLOAD_GROUP,)@@ -587,7 +690,13 @@ def apply_memory_plan(if policy == OFFLOAD_MODEL:pipe.enable_model_cpu_offload(device = device)elif policy == OFFLOAD_GROUP:- if not _apply_group_offload(pipe, device, logger):+ # getattr, not attribute access: manually built / duck-typed plans predate this field.+ if not _apply_group_offload(+ pipe,+ device,+ logger,+ stream_text_encoders = bool(getattr(plan, "stream_text_encoders", False)),+ ):_fallback_to_model_offload()policy = OFFLOAD_MODELelif policy == OFFLOAD_STREAMING:@@ -625,9 +734,19 @@ def _enable_vae_saver(pipe: Any, pipe_method: str, vae_method: str, logger: Any)return False-def _apply_group_offload(pipe: Any, device: str, logger: Any) -> bool:+def _apply_group_offload(+ pipe: Any,+ device: str,+ logger: Any,+ *,+ stream_text_encoders: bool = False,+) -> bool:"""Stream the transformer a few blocks at a time via diffusers group offloading, keeping the- smaller components resident. Returns False (caller falls back to whole-module) on any failure."""+ smaller components resident. Returns False (caller falls back to whole-module) on any failure.++ ``stream_text_encoders`` extends the streamed set to every ``text_encoder*`` module. Off by+ default: keeping them resident is faster when there is room. The planner turns it on only+ where it is the difference between group offload and whole-module offload."""transformer = getattr(pipe, "transformer", None)if transformer is None:return False@@ -644,6 +763,18 @@ def _apply_group_offload(pipe: Any, device: str, logger: Any) -> bool:module = getattr(pipe, extra, None)if isinstance(module, torch.nn.Module):streamed[extra] = module+ # The text encoders are streamed SEPARATELY from the DiTs, and tolerantly (see the apply+ # loop below). Kept in their own dict so the resident placement loop still skips them.+ streamed_encoders: dict[str, Any] = {}+ if stream_text_encoders:+ # A text encoder runs ONCE, before step 0, so residency buys it nothing while it costs+ # its bytes for every step of the denoise. Streaming it does two things: the resident+ # loop below skips it (it is no longer placed with comp.to(onload)), and group hooks+ # page it in for that single encode. Component names, not attributes, so a family with+ # text_encoder / text_encoder_2 / text_encoder_3 is covered without a per-family list.+ for name, comp in getattr(pipe, "components", {}).items():+ if name.startswith("text_encoder") and isinstance(comp, torch.nn.Module):+ streamed_encoders[name] = componload = torch.device(device)use_stream = onload.type == "cuda" # overlap H2D copies with compute@@ -655,21 +786,61 @@ def _apply_group_offload(pipe: Any, device: str, logger: Any) -> bool:"use_stream": use_stream,}# On the CUDA stream path, overlap each block's H2D copy with compute. Lossless, and gated on the signature so older diffusers still works.+ _params = inspect.signature(apply_group_offloading).parametersif use_stream:- _params = inspect.signature(apply_group_offloading).parametersif "non_blocking" in _params:gkwargs["non_blocking"] = Trueif "record_stream" in _params:gkwargs["record_stream"] = True+ if stream_text_encoders and "low_cpu_mem_usage" in _params:+ # The streamed path PINS every offloaded parameter in host RAM when a copy stream is+ # in use (diffusers group_offloading `_init_cpu_param_dict`), which is a fine trade+ # when group offload was already the plan. It is not a fine trade here: this tier is+ # only ever reached as a rescue from whole-module offload, which pins nothing, on a+ # card small enough that the companions did not fit. Those hosts are not reliably+ # RAM-rich either, and silently converting a device-memory shortfall into ten-plus GB+ # of unswappable host RAM is how #8188's machine got into trouble in the first place.+ # low_cpu_mem_usage trades a slower host-to-device copy for not pinning; the encoders+ # this tier streams run ONCE per call, so that copy is paid once, not per step.+ gkwargs["low_cpu_mem_usage"] = True# Place the smaller components resident BEFORE attaching the transformer group-offload hooks: a companion .to() OOM then returns False with no hooks installed, and diffusers rejects enable_model_cpu_offload once group hooks exist.for name, comp in getattr(pipe, "components", {}).items():- if name in streamed:+ if name in streamed or name in streamed_encoders:continueif isinstance(comp, torch.nn.Module):comp.to(onload)for module in streamed.values():apply_group_offloading(module, **gkwargs)installed += 1+ # The encoders come AFTER the DiTs and are applied one by one, each failure absorbed. A+ # text encoder is a far less well-trodden target for block-level group offloading than a+ # DiT (a family whose encoder exposes no recognisable block list can simply refuse), and+ # this tier is a rescue: the alternative to streaming an encoder is keeping it resident,+ # which is what happened before this tier existed. Letting one refusal join the all-or-+ # nothing DiT loop would turn a slow-but-working load into a hard failure, because by then+ # hooks are installed and whole-module offload can no longer be used as a fallback. So a+ # refusal places that encoder resident instead: the plan's floor becomes optimistic by+ # that encoder's bytes, and the load still runs.+ # Leaf level, not the DiTs' block level: an encoder is not a stack of uniform blocks, so+ # _streamable_components and _apply_streaming_offload already classify every text_encoder*+ # that way. Reusing the transformer's kwargs here grouped the whole encoder as one unit,+ # which is the residency the planner's floor was chosen to avoid -- the plan said leaf and+ # the application said block. num_blocks_per_group goes with it: leaf level has no blocks.+ ekwargs = {k: v for k, v in gkwargs.items() if k != "num_blocks_per_group"}+ ekwargs["offload_type"] = "leaf_level"+ for name, module in streamed_encoders.items():+ try:+ apply_group_offloading(module, **ekwargs)+ installed += 1+ except Exception as exc: # noqa: BLE001 -- degrade this encoder, never fail the load+ if logger is not None:+ logger.warning(+ "diffusion.memory: group offload unavailable for %s (%s); "+ "keeping it resident",+ name,+ exc,+ )+ module.to(onload)return Trueexcept Exception as exc: # noqa: BLE001 — fall back to whole-module offloadif installed:@@ -691,6 +862,172 @@ def _apply_group_offload(pipe: Any, device: str, logger: Any) -> bool:return False+# ── generate-time activation guard ────────────────────────────────────────────+# The load-time plan cannot know the output resolution: a model is loaded once and 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. This is the second half: a per-generation re-check, 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.+OVERSIZED_GENERATE_ENV = "UNSLOTH_DIFFUSION_ALLOW_OVERSIZED_GENERATE"+++class ImageActivationShortfallError(ValueError):+ """This generation's activations cannot fit the free device budget.++ A ValueError subclass so ``/images/generate``'s existing mapping still turns it into a 400+ with the reason. The distinct type is what lets the OpenAI-compatible route, whose boundary+ sanitises 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."+ """+++def _oversized_generate_override() -> bool:+ return os.environ.get(OVERSIZED_GENERATE_ENV, "").strip().lower() in ("1", "true", "yes", "on")+++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,+) -> Optional[str]:+ """A user-facing refusal when this generation's ACTIVATIONS plus the flat base overhead+ cannot fit the free device budget, else None.++ Why this is a refusal and not another tuning knob: weights can be offloaded, activations+ cannot. Every offload tier moves WEIGHTS between host and device; 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 is an overrun at every tier, including+ the lowest one, rather than a hint that a different placement would help. There is nothing+ left to degrade to, which is exactly the situation where refusing beats trying.++ Refusing also 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+ not raise at all: the driver satisfies the overflow from system RAM as "non-local" GPU memory,+ so the process quietly grows past the card into tens of GB of host RAM and pagefile, and the+ desktop stops responding with no error anywhere. A ValueError here is a 400 with the reason,+ which is the clean refusal that failure mode never produces on its own.++ What it does NOT do is second-guess the load. The flat headroom this estimate is built on is a+ deliberately generous PLANNING figure whose job is to pick an offload tier, and the tier it+ picks already runs the 1024x1024 default on cards 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). Treating that figure as a hard limit at or below the default+ would refuse work that succeeds today. So the refusal needs BOTH conditions: over the free+ budget, and over what the load already budgeted. That confines it to the resolution-driven+ overrun it is for -- the load reserved a 1 MP frame and the request is several times that --+ and leaves every generation at or below the default resolution exactly as it is.++ Fail-open on anything unknown (no free reading, no budget) and on any device class where the+ estimate or the offload story means something different, so a broken probe can never block a+ generation that would have worked."""+ if _oversized_generate_override():+ return None+ 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+ # 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+ free = getattr(device_memory, "free_mib", None)+ if free is None:+ return None # no reading -> no verdict+ budget = _safe_device_budget_mib(device_memory)+ if budget is None:+ return None+ needed = estimate_image_runtime_mib(+ width = width,+ height = height,+ batch_size = batch_size,+ family = family,+ )+ # What the LOAD budgeted: the same estimator at the default resolution, i.e. the exact+ # call _plan_memory makes. Same function and same family hint, so the comparison is+ # between two points on one curve rather than between two different guesses.+ planned = estimate_image_runtime_mib(+ width = None,+ height = None,+ batch_size = 1,+ family = family,+ )+ except Exception: # noqa: BLE001 -- a broken probe must never block a generation+ return None+ # 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+ 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 ""+ # 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} 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"Generate at a smaller resolution{' or a smaller batch size' if batch > 1 else ''}, "+ "free device memory by closing other applications, or set "+ f"{OVERSIZED_GENERATE_ENV}=1 to attempt it anyway."+ )+++def raise_on_image_activation_shortfall(+ *,+ 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,+ 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.++ ``ValueError`` on purpose: ``/images/generate`` maps ValueError to HTTP 400 with the message+ as the reason, so this surfaces as an actionable refusal in the UI. RuntimeError there is+ reserved for the two client-state sentinels (not loaded / cancelled) and otherwise becomes an+ opaque 500."""+ message = image_activation_shortfall_message(+ device_memory = device_memory,+ width = width,+ height = height,+ batch_size = batch_size,+ family = family,+ base_overhead_mib = base_overhead_mib,+ )+ if message is None:+ return+ if logger is not None:+ logger.error("diffusion.memory: refusing oversized generation: %s", message)+ raise ImageActivationShortfallError(message)++def _apply_streaming_offload(pipe: Any, device: str, logger: Any) -> None:"""Stream transformer blocks and text-encoder leaves without whole-component onloads.diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex e237db9eca4..c3945b0c13e 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -20889,6 +20889,17 @@ async def openai_image_generations(# A RuntimeError with the model now unloaded means it was evicted mid-call (a race): 503. Every other failure is a real 500 whose raw message must not reach the client.if isinstance(exc, RuntimeError) and not backend.is_loaded:raise HTTPException(status_code = 503, detail = _NO_IMAGE_MODEL_MSG)+ # The activation refusal is the one message here written FOR the caller: it names the+ # resolution, the budget and the remedies. Sanitising it into "Image generation failed."+ # left an OpenAI client with a 500 for a request only they can fix, while the Studio+ # route showed the reason. Typed, so no other ValueError's raw text escapes.+ from core.inference.diffusion_memory import ImageActivationShortfallError++ if isinstance(exc, ImageActivationShortfallError):+ raise HTTPException(+ status_code = 400,+ detail = openai_error_body(str(exc), status = 400, param = "size"),+ )logger.error("openai_images.generate_failed: %s", exc)raise HTTPException(status_code = 500, detail = "Image generation failed.")diff --git a/studio/backend/tests/test_diffusion_backend.py b/studio/backend/tests/test_diffusion_backend.pyindex 41f386e9cf7..543fe3438d6 100644--- a/studio/backend/tests/test_diffusion_backend.py+++ b/studio/backend/tests/test_diffusion_backend.py@@ -6791,6 +6791,384 @@ def test_download_plan_skips_nothing_when_the_hub_reports_no_commit(monkeypatch)}+# ── the variant hint feeding the runtime-headroom estimate ────────────────────+++def test_variant_hint_carries_both_the_repo_id_and_the_base():+ # `repo_id or base` dropped the base whenever a repo id existed, which is every GGUF load, and+ # the base is exactly where the distilled marker lives: unsloth/Z-Image-GGUF says nothing while+ # Tongyi-MAI/Z-Image-Turbo says turbo, so the 0.85 discount never fired for these models.+ from core.inference.diffusion import _image_variant_hint+ from core.inference.diffusion_memory import estimate_image_runtime_mib++ hint = _image_variant_hint(+ "z-image", "Z-Image-Q4_K_S.gguf", "unsloth/Z-Image-GGUF", "Tongyi-MAI/Z-Image-Turbo"+ )+ assert "unsloth/Z-Image-GGUF" in hint and "Tongyi-MAI/Z-Image-Turbo" in hint+ # Worth ~1.2 GB of headroom on a card where 1.2 GB decides the offload tier.+ assert estimate_image_runtime_mib(width = None, height = None, family = hint) == 6963+ assert estimate_image_runtime_mib(width = None, height = None, family = "") == 8192+++def test_variant_hint_is_deduplicated_and_order_stable():+ # A pipeline load passes the same id as both repo and base; the hint must not repeat it, and+ # the order must be a pure function of the load so two identical loads plan identically.+ from core.inference.diffusion import _image_variant_hint++ assert (+ _image_variant_hint("z-image", None, "Tongyi-MAI/Z-Image-Turbo", "Tongyi-MAI/Z-Image-Turbo")+ == "z-image Tongyi-MAI/Z-Image-Turbo"+ )+ assert _image_variant_hint("z-image", " ", None, None) == "z-image"+ assert _image_variant_hint(None, None, None, None) == ""+++# ── the text-encoder share of the companion total ─────────────────────────────+++def _base_snapshot_with_sizes(tmp_path, monkeypatch, sizes):+ """A base repo cached only under the other cache root, with the given ``{relative path: MiB}``."""+ _live, other = _split_cache_roots(tmp_path, monkeypatch)+ snapshot = other / "models--bfl--base" / "snapshots" / ("a" * 40)+ for rel, mib in sizes.items():+ path = snapshot / rel+ path.parent.mkdir(parents = True, exist_ok = True)+ with open(path, "wb") as fh:+ fh.truncate(mib * 1024 * 1024)+ return snapshot+++def test_text_encoder_cache_bytes_is_a_subset_of_the_companion_total(tmp_path, monkeypatch):+ # The planner SUBTRACTS this from the companion total, so it has to come off the same walk:+ # a second, independent derivation could see a file the companion walk did not and drive the+ # difference negative.+ snapshot = _base_snapshot_with_sizes(+ tmp_path,+ monkeypatch,+ {+ "text_encoder/model.safetensors": 150,+ "text_encoder_2/model.safetensors": 90,+ "vae/diffusion_pytorch_model.safetensors": 50,+ # Never a companion on a GGUF load: the single file supplies the transformer.+ "transformer/diffusion_pytorch_model.safetensors": 4096,+ },+ )+ sizes = DiffusionBackend._local_dir_text_encoder_sizes(snapshot)+ # Both encoder folders, and nothing else.+ assert sorted(sizes) == ["text_encoder/model.safetensors", "text_encoder_2/model.safetensors"]+ assert DiffusionBackend._text_encoder_cache_bytes(str(snapshot)) == 240 * 1024 * 1024+ assert DiffusionBackend._companion_cache_bytes(str(snapshot)) == 290 * 1024 * 1024+++def test_plan_memory_hands_the_planner_the_text_encoder_split(monkeypatch, tmp_path):+ # 150 MiB of encoders inside a 200 MiB companion total, so the streamed-encoder floor is the+ # VAE (50) + headroom (100) + overhead (2048).+ from core.inference.diffusion_memory import OFFLOAD_GROUP++ snapshot = _other_root_base_snapshot(tmp_path, monkeypatch)+ target = _small_card(monkeypatch)++ plan = DiffusionBackend()._plan_memory(+ target,+ None,+ "bfl/base",+ types.SimpleNamespace(name = "flux.1"),+ None,+ False,+ kind = "gguf",+ transformer_resident_override_mib = 300,+ base_local_dir = str(snapshot),+ )+ assert plan.estimates["companion_dense_mib"] == 200+ assert plan.estimates["text_encoder_dense_mib"] == 150+ assert plan.estimates["group_floor_streamed_te_mib"] == 2198+ # The companions fit as they are, so the cheaper tier still wins and nothing streams.+ assert plan.offload_policy == OFFLOAD_GROUP and plan.stream_text_encoders is False+++def test_plan_memory_streams_the_text_encoders_instead_of_offloading_everything(+ monkeypatch, tmp_path+):+ # 8081's shape at this fixture's scale: a text encoder that alone busts the group floor. Before+ # the split that meant whole-module offload of every component, measured at 48m25s for a+ # 20-step 1024x1024 image; the VAE-only floor of 2198 fits the 2952 MiB budget.+ snapshot = _base_snapshot_with_sizes(+ tmp_path,+ monkeypatch,+ {+ "text_encoder/model.safetensors": 2800,+ "vae/diffusion_pytorch_model.safetensors": 50,+ },+ )+ target = _small_card(monkeypatch)+ from core.inference.diffusion_memory import OFFLOAD_GROUP++ def _plan(**kw):+ return DiffusionBackend()._plan_memory(+ target,+ None,+ "bfl/base",+ types.SimpleNamespace(name = "flux.1"),+ None,+ False,+ kind = "gguf",+ transformer_resident_override_mib = 300,+ base_local_dir = str(snapshot),+ **kw,+ )++ plan = _plan()+ # group floor 2850 + 100 + 2048 = 4998, over the 2952 budget: this is the whole-module case.+ assert plan.estimates["group_floor_mib"] == 4998+ assert plan.estimates["group_floor_streamed_te_mib"] == 2198+ assert plan.offload_policy == OFFLOAD_GROUP and plan.stream_text_encoders is True+++def test_plan_memory_keeps_the_split_on_the_dense_candidate_path(monkeypatch, tmp_path):+ # The reported plan came from the dense int8 candidate replan, which overrides the companion+ # total from the family component table. Without the matching text-encoder override that path+ # keeps landing on whole-module offload however good the cache-walk split is.+ from core.inference.diffusion_memory import OFFLOAD_GROUP++ _base_snapshot_with_sizes(tmp_path, monkeypatch, {})+ target = _small_card(monkeypatch)++ plan = DiffusionBackend()._plan_memory(+ target,+ None,+ "bfl/base",+ types.SimpleNamespace(name = "flux.1"),+ None,+ False,+ kind = "gguf",+ transformer_resident_override_mib = 300,+ companion_override_mib = 2850,+ text_encoder_override_mib = 2800,+ )+ assert plan.estimates["text_encoder_dense_mib"] == 2800+ assert plan.offload_policy == OFFLOAD_GROUP and plan.stream_text_encoders is True+++def test_dense_quant_estimate_carries_the_text_encoder_share():+ # The override above is only as good as the table it comes from: companions minus text encoders+ # has to be the VAE and nothing else, or the streamed floor is wrong on every dense candidate.+ from core.inference.diffusion_auto_policy import estimate_dense_quant++ estimate = estimate_dense_quant(types.SimpleNamespace(name = "z-image"), "int8")+ # The reported numbers: transformer 6451 int8, companions 7820, of which 7629 is the encoders.+ assert estimate.steady_transformer_mib == 6451+ assert estimate.companions_mib == 7820+ assert estimate.text_encoders_mib == 7629+ assert estimate.companions_mib - estimate.text_encoders_mib == 191 # the VAE+++# ── generate(): the resolution-aware re-check ─────────────────────────────────+# The load-time plan budgets the 1024x1024 default because load time cannot know the request. At+# 1088x1920 the pass needs ~2x that, and on Windows WDDM the overrun does not raise: the driver+# serves it from system RAM, so ~27 GB lands on a 16 GB card with no exception and the desktop+# stops responding. generate() re-checks with the real dimensions before it samples.++# The reported card: free 15,870 of 16,305 MiB, so the safe budget is 13,822 MiB.+_ROCM_16G = (15_870, 16_305)+++def _loaded_backend_on_a_16g_card(+ tmp_path,+ monkeypatch,+ *,+ base_repo = "base/repo",+):+ """A loaded GGUF pipeline, then a 16 GB discrete-CUDA memory snapshot. Patched AFTER the load+ so the load itself still plans against the fixture's CPU target and is unaffected."""+ from core.inference import diffusion as dmod+ from core.inference.diffusion_memory import DeviceMemory++ (tmp_path / "model.gguf").write_bytes(b"weights")+ backend = DiffusionBackend()+ backend.load_pipeline(+ str(tmp_path),+ gguf_filename = "model.gguf",+ base_repo = base_repo,+ family_override = "z-image",+ )+ free, total = _ROCM_16G+ snapshot = lambda target, **kw: DeviceMemory("cuda", "cuda", "discrete_vram", free, total)+ monkeypatch.setattr(dmod, "settled_snapshot_device_memory", snapshot)+ # The generate-time guard reads the RECLAIMABLE snapshot (no empty_cache on a per-image path),+ # so pin that one too or it falls through to the host's real card.+ monkeypatch.setattr(dmod, "reclaimable_snapshot_device_memory", snapshot)+ return backend+++def test_generate_refuses_a_resolution_whose_activations_cannot_fit(+ fake_runtime, tmp_path, monkeypatch+):+ backend = _loaded_backend_on_a_16g_card(tmp_path, monkeypatch)++ with pytest.raises(ValueError) as excinfo:+ backend.generate(prompt = "a sloth", width = 1088, height = 1920, steps = 4)+ message = str(excinfo.value)+ # ValueError, so /images/generate answers 400 with this text rather than a 500 or, worse,+ # nothing at all while the machine swaps itself to death.+ assert "1088x1920" in message+ assert "smaller resolution" in message+ assert "UNSLOTH_DIFFUSION_ALLOW_OVERSIZED_GENERATE" in message++ # The same model on the same card at the default resolution is untouched.+ assert len(backend.generate(prompt = "a sloth", width = 1024, height = 1024, steps = 4)["images"]) == 1+++def test_generate_guard_measures_the_input_image_not_the_sliders(+ fake_runtime, tmp_path, monkeypatch+):+ # img2img / inpaint / upscale / edit take their OUTPUT size from the uploaded image, so reading+ # the width/height kwargs would check a frame this call never renders. A 2048x2048 upload with+ # the sliders left at 1024 is four times the planned area.+ backend = _loaded_backend_on_a_16g_card(tmp_path, monkeypatch)++ with pytest.raises(ValueError, match = "2048x2048"):+ backend.generate(+ prompt = "a sloth",+ width = 1024,+ height = 1024,+ steps = 4,+ init_image = _png_b64(2048),+ )+++def test_generate_guard_uses_the_hint_the_load_planned_with(fake_runtime, tmp_path, monkeypatch):+ # The distilled discount has to apply at generate time too, or a turbo model is budgeted 18%+ # high and refused where it would have run. Same hint, stored on the load state.+ backend = _loaded_backend_on_a_16g_card(+ tmp_path, monkeypatch, base_repo = "Tongyi-MAI/Z-Image-Turbo"+ )+ assert "Tongyi-MAI/Z-Image-Turbo" in backend._state.variant_hint++ # 1280x1280 is 1.5625x the default: 12,800 MiB of activations undiscounted, which with the+ # 2048 MiB base overhead is 14,848 against a 13,822 MiB budget and would be refused. With the+ # distilled discount the same request is 10,880 + 2048 = 12,928 and goes straight through.+ assert len(backend.generate(prompt = "a sloth", width = 1280, height = 1280, steps = 4)["images"]) == 1+ # The reported 1088x1920 needs 13,872 MiB even discounted, so it is still refused.+ with pytest.raises(ValueError, match = "1088x1920"):+ backend.generate(prompt = "a sloth", width = 1088, height = 1920, steps = 4)+++def test_generate_guard_fails_open_when_the_probe_raises(fake_runtime, tmp_path, monkeypatch):+ # A broken memory probe must never cost a user a generation that would have worked.+ from core.inference import diffusion as dmod++ backend = _loaded_backend_on_a_16g_card(tmp_path, monkeypatch)++ def _boom(target, **kw):+ raise RuntimeError("mem_get_info exploded")++ monkeypatch.setattr(dmod, "reclaimable_snapshot_device_memory", _boom)+ assert len(backend.generate(prompt = "a sloth", width = 1088, height = 1920, steps = 4)["images"]) == 1+++def test_generate_guard_env_override(fake_runtime, tmp_path, monkeypatch):+ from core.inference.diffusion_memory import OVERSIZED_GENERATE_ENV++ backend = _loaded_backend_on_a_16g_card(tmp_path, monkeypatch)+ monkeypatch.setenv(OVERSIZED_GENERATE_ENV, "1")+ assert len(backend.generate(prompt = "a sloth", width = 1088, height = 1920, steps = 4)["images"]) == 1+++def test_generate_guard_leaves_a_large_batch_to_the_oom_backoff(+ fake_runtime, tmp_path, monkeypatch+):+ # The chunk loop halves a failed multi-image forward down to singletons, so budgeting the whole+ # chunk here would refuse batches that complete today (the measured batch-32 fast path). The+ # guard budgets one image, the case no backoff can rescue.+ backend = _loaded_backend_on_a_16g_card(tmp_path, monkeypatch)+ out = backend.generate(prompt = "a sloth", width = 1024, height = 1024, steps = 4, batch_size = 8)+ assert len(out["images"]) == 8+++def test_dense_quant_candidate_replan_prices_the_streamed_encoder_tier(+ fake_runtime, tmp_path, monkeypatch+):+ # 8081's reported plan came from THIS path, not the cache walk: transformer 6451 at int8 and+ # companions 7820 are the family component table's numbers, supplied as overrides. The+ # text-encoder share has to be threaded through the same override or the streamed-encoder tier+ # is unreachable on exactly the path that produced the 48-minute load.+ import dataclasses++ from core.inference import diffusion as dmod++ backend = DiffusionBackend()+ _force_cuda_target(backend, monkeypatch)+ monkeypatch.setattr(dmod, "dense_transformer_supported", lambda target: True)+ monkeypatch.setattr(+ dmod, "select_transformer_quant_scheme", lambda target, mode, family = None: "int8"+ )+ monkeypatch.setattr(+ dmod,+ "resolve_dense_quant_candidate",+ lambda **kw: types.SimpleNamespace(+ transient_transformer_mib = 6_451,+ companions_mib = 7_820,+ text_encoders_mib = 7_629,+ prequant = True,+ ),+ )+ seen = []+ orig_plan = DiffusionBackend._plan_memory++ def spy_plan(+ self,+ *a,+ transformer_resident_override_mib = None,+ **k,+ ):+ real = orig_plan(+ self, *a, transformer_resident_override_mib = transformer_resident_override_mib, **k+ )+ if transformer_resident_override_mib is None:+ # Initial GGUF plan: force offload so the candidate replan branch is entered.+ return dataclasses.replace(real, offload_policy = "model")+ seen.append(k.get("text_encoder_override_mib"))+ return dataclasses.replace(real, offload_policy = "model")++ monkeypatch.setattr(DiffusionBackend, "_plan_memory", spy_plan)+ monkeypatch.setattr(+ DiffusionBackend,+ "_load_dense_quant_pipeline",+ lambda self, *a, **k: (_ for _ in ()).throw(+ RuntimeError("test: stop after reaching the fast path")+ ),+ )+ (tmp_path / "m.gguf").write_bytes(b"x")+ # The spy forces offload on every replan, so the EXPLICIT int8 ends in the strict-precision+ # refusal. Immaterial here: the replan calls this asserts on all happen before it.+ with pytest.raises(RuntimeError, match = "transformer_quant='int8'"):+ backend.load_pipeline(+ str(tmp_path),+ gguf_filename = "m.gguf",+ family_override = "z-image",+ transformer_quant = "int8",+ )+ assert seen and all(value == 7_629 for value in seen)+++def test_the_activation_guard_budgets_the_real_batch_on_windows(monkeypatch):+ """The singleton floor rests on the OOM backoff halving a failed forward, and under WDDM+ there is no OOM to catch: the driver serves the overflow from system RAM, the desktop stops+ responding and nothing recovers it. So Windows budgets the largest chunk it will actually+ run, while every other platform keeps the batch-32 fast path it measures today."""+ from core.inference import diffusion as dmod++ chunks = [[object()] * 8, [object()] * 3]+ monkeypatch.setattr(dmod.sys, "platform", "linux")+ assert dmod._activation_guard_batch(chunks) == 1+ assert dmod._activation_guard_batch([]) == 1+ monkeypatch.setattr(dmod.sys, "platform", "win32")+ assert dmod._activation_guard_batch(chunks) == 8+ assert dmod._activation_guard_batch([[object()]]) == 1+ # An empty job list is still a valid batch of one, never a zero passed to the estimator.+ assert dmod._activation_guard_batch([]) == 1++# ── generate cancellation (issue #8187) ──────────────────────────────────────## The denoise loop already honoured the per-generation cancel event, but only unload() and adiff --git a/studio/backend/tests/test_diffusion_memory.py b/studio/backend/tests/test_diffusion_memory.pyindex 263771f9820..68781e9d14c 100644--- a/studio/backend/tests/test_diffusion_memory.py+++ b/studio/backend/tests/test_diffusion_memory.py@@ -770,6 +770,90 @@ def test_settled_snapshot_stops_early_when_device_already_idle(monkeypatch):assert calls == [1]+def _fake_torch_allocator(monkeypatch, *, reserved: int, allocated: int):+ """Stub torch.cuda's allocator counters for the reclaimable snapshot."""+ import sys++ torch = types.ModuleType("torch")+ torch.cuda = types.SimpleNamespace(+ memory_reserved = lambda: reserved,+ memory_allocated = lambda: allocated,+ )+ monkeypatch.setitem(sys.modules, "torch", torch)+++def test_reclaimable_snapshot_credits_cached_blocks_without_flushing(monkeypatch):+ # mem_get_info counts every block the caching allocator holds for reuse as USED, so a warm+ # card reads as nearly full. The generate-time guard must not mistake that for a shortfall,+ # and must not pay empty_cache() per image to find out.+ from core.inference import diffusion_memory as dm++ monkeypatch.setattr(+ dm,+ "snapshot_device_memory",+ lambda target: DeviceMemory(+ "cuda", "cuda", "discrete_vram", free_mib = 2_000, total_mib = 16_302+ ),+ )+ # 6 GiB reserved, 2 GiB in live tensors: 4 GiB is cached and reclaimable.+ _fake_torch_allocator(monkeypatch, reserved = 6 * 1024**3, allocated = 2 * 1024**3)+ snap = dm.reclaimable_snapshot_device_memory(_target(device = "cuda"))+ assert snap.free_mib == 2_000 + 4 * 1024+++def test_reclaimable_snapshot_never_claims_more_than_the_card(monkeypatch):+ # The credit is arithmetic, so a bogus allocator reading must not invent memory the card+ # does not have and talk the guard out of a real refusal.+ from core.inference import diffusion_memory as dm++ monkeypatch.setattr(+ dm,+ "snapshot_device_memory",+ lambda target: DeviceMemory(+ "cuda", "cuda", "discrete_vram", free_mib = 15_000, total_mib = 16_302+ ),+ )+ _fake_torch_allocator(monkeypatch, reserved = 40 * 1024**3, allocated = 0)+ assert dm.reclaimable_snapshot_device_memory(_target(device = "cuda")).free_mib == 16_302+++def test_reclaimable_snapshot_falls_back_when_the_allocator_is_unreadable(monkeypatch):+ # No allocator reading: the plain driver-level snapshot still stands, unchanged.+ from core.inference import diffusion_memory as dm+ import sys++ monkeypatch.setattr(+ dm,+ "snapshot_device_memory",+ lambda target: DeviceMemory(+ "cuda", "cuda", "discrete_vram", free_mib = 2_000, total_mib = 16_302+ ),+ )+ torch = types.ModuleType("torch")++ def _boom():+ raise RuntimeError("no cuda context")++ torch.cuda = types.SimpleNamespace(memory_reserved = _boom, memory_allocated = _boom)+ monkeypatch.setitem(sys.modules, "torch", torch)+ assert dm.reclaimable_snapshot_device_memory(_target(device = "cuda")).free_mib == 2_000+++def test_reclaimable_snapshot_passthrough_off_cuda(monkeypatch):+ # Only the CUDA caching allocator is modelled here; every other device keeps its plain read.+ from core.inference import diffusion_memory as dm++ monkeypatch.setattr(+ dm,+ "snapshot_device_memory",+ lambda target: DeviceMemory(+ "mps", "mps", "unified_memory", free_mib = 8_000, total_mib = 16_000+ ),+ )+ _fake_torch_allocator(monkeypatch, reserved = 6 * 1024**3, allocated = 0)+ assert dm.reclaimable_snapshot_device_memory(_target(device = "mps")).free_mib == 8_000++def test_settled_snapshot_passthrough_off_cuda(monkeypatch):# Non-cuda targets keep the single-read behaviour (no settle loop).from core.inference import diffusion_memory as dm@@ -808,3 +892,702 @@ def test_plan_fits_total_capacity():assert plan_fits_total_capacity(plan(None, 183_359)) is Falseassert plan_fits_total_capacity(plan(90_228, None)) is Falseassert plan_fits_total_capacity(types.SimpleNamespace()) is False+++# ── the streamed-text-encoder group tier ──────────────────────────────────────+# A text encoder runs ONCE, before step 0, but group offload places every non-streamed component+# resident, so its bytes are reserved for the whole denoise. Where that is the only thing pushing+# the group floor over budget, streaming the encoders too keeps the tier instead of dropping to+# whole-module offload (measured 48m25s for a 20-step 1024x1024 image on a 16 GB card).++# The 16 GB card from the report: free 15,870 of 16,305 MiB, reserve max(2048, 10%) = 2048, so the+# safe budget is exactly the 13,822 MiB the failing plan was measured against.+_16G_FREE_MIB = 15_870+_16G_TOTAL_MIB = 16_305+_16G_BUDGET_MIB = 13_822++# Z-Image at int8, straight from the report: transformer 6451 + companions 7820 = 14,271 resident,+# of which the text encoders are 7629 (8.0 of the 8.2 GB companion table) and the VAE is the rest.+_ZIMAGE_MODEL_DENSE_MIB = 14_271+_ZIMAGE_COMPANION_MIB = 7_820+_ZIMAGE_TEXT_ENCODER_MIB = 7_629+++def test_safe_budget_matches_the_reported_16g_card():+ # Anchors every number below: if the reserve rule changes, this fails first rather than+ # silently moving the floors the rest of this section is calibrated against.+ from core.inference.diffusion_memory import _safe_device_budget_mib+ assert _safe_device_budget_mib(_discrete(_16G_FREE_MIB, _16G_TOTAL_MIB)) == _16G_BUDGET_MIB+++def _zimage_plan(text_encoder_dense_mib):+ return plan_diffusion_memory(+ target = _target(),+ device_memory = _discrete(_16G_FREE_MIB, _16G_TOTAL_MIB),+ model_dense_mib = _ZIMAGE_MODEL_DENSE_MIB,+ companion_dense_mib = _ZIMAGE_COMPANION_MIB,+ text_encoder_dense_mib = text_encoder_dense_mib,+ runtime_headroom_mib = 8192,+ base_overhead_mib = 2048,+ )+++def test_streamed_text_encoders_rescue_the_48_minute_plan():+ # required 14,271 + 8192 + 2048 = 24,511 against a 13,822 budget: not resident either way.+ # group floor 7820 + 8192 + 2048 = 18,060 > 13,822, which is what dropped this to whole-module+ # offload. With the encoders streamed the floor is 191 + 8192 + 2048 = 10,431 and fits.+ before = _zimage_plan(None)+ assert before.offload_policy == OFFLOAD_MODEL+ assert before.stream_text_encoders is False+ assert before.estimates["group_floor_streamed_te_mib"] is None++ after = _zimage_plan(_ZIMAGE_TEXT_ENCODER_MIB)+ assert after.offload_policy == OFFLOAD_GROUP+ assert after.stream_text_encoders is True+ assert after.estimates["resident_required_mib"] == 24_511+ assert after.estimates["group_floor_mib"] == 18_060+ assert after.estimates["group_floor_streamed_te_mib"] == 10_431+ assert any("text encoders" in reason for reason in after.reasons)+ # Group keeps the VAE resident, so the decode stays bit-identical (sliced, not tiled).+ assert after.vae_slicing is True and after.vae_tiling is False+ # The flag has to reach the applier, which reads the public dict in status/logging too.+ assert after.as_public_dict()["stream_text_encoders"] is True++[email protected]("mode", [None, MEMORY_MODE_FAST])+def test_plain_group_is_preferred_over_streaming_the_text_encoders(mode):+ # Where the companions fit as they are, the encoders stay resident: streaming them is a small+ # loss for no gain, so the new tier must only engage as a rescue from whole-module offload.+ # Both branches that pick a tier have to agree on that order, hence both modes here: auto has+ # its own if/elif chain and `fast` goes through _offload_tier, so covering one leaves the+ # other free to prefer the wrong tier.+ plan = plan_diffusion_memory(+ target = _target(),+ device_memory = _discrete(_16G_FREE_MIB, _16G_TOTAL_MIB),+ model_dense_mib = 40_000,+ companion_dense_mib = 1_500,+ text_encoder_dense_mib = 1_400,+ runtime_headroom_mib = 8192,+ base_overhead_mib = 2048,+ requested_mode = mode,+ )+ assert plan.offload_policy == OFFLOAD_GROUP+ assert plan.stream_text_encoders is False+++def test_streamed_text_encoders_still_fall_through_when_even_that_floor_is_over():+ # A VAE alone over budget has nothing left to give up, so whole-module offload still wins.+ plan = plan_diffusion_memory(+ target = _target(),+ device_memory = _discrete(_16G_FREE_MIB, _16G_TOTAL_MIB),+ model_dense_mib = 40_000,+ companion_dense_mib = 20_000,+ text_encoder_dense_mib = 1_000,+ runtime_headroom_mib = 8192,+ base_overhead_mib = 2048,+ )+ assert plan.offload_policy == OFFLOAD_MODEL+ assert plan.stream_text_encoders is False+++def test_fast_mode_also_reaches_the_streamed_text_encoder_tier():+ # `fast` has its own does-not-fit branch; it must offer the same ladder as auto, or an explicit+ # fast request on a 16 GB card lands on the 48-minute tier the auto path now avoids.+ plan = plan_diffusion_memory(+ target = _target(),+ device_memory = _discrete(_16G_FREE_MIB, _16G_TOTAL_MIB),+ model_dense_mib = _ZIMAGE_MODEL_DENSE_MIB,+ companion_dense_mib = _ZIMAGE_COMPANION_MIB,+ text_encoder_dense_mib = _ZIMAGE_TEXT_ENCODER_MIB,+ runtime_headroom_mib = 8192,+ base_overhead_mib = 2048,+ requested_mode = MEMORY_MODE_FAST,+ )+ assert plan.offload_policy == OFFLOAD_GROUP+ assert plan.stream_text_encoders is True+++def test_text_encoder_split_larger_than_the_companions_clamps_at_zero():+ # The two terms can come from different sources (a cache walk and a family table), so a split+ # that exceeds the total must floor at 0 rather than produce a negative resident requirement.+ plan = plan_diffusion_memory(+ target = _target(),+ device_memory = _discrete(_16G_FREE_MIB, _16G_TOTAL_MIB),+ model_dense_mib = 40_000,+ companion_dense_mib = 7_820,+ text_encoder_dense_mib = 9_999,+ runtime_headroom_mib = 8192,+ base_overhead_mib = 2048,+ )+ assert plan.estimates["group_floor_streamed_te_mib"] == 10_240 # 0 + 8192 + 2048+++def _legacy_offload_policy(+ *, budget, model_dense_mib, companion_dense_mib, runtime_headroom_mib, base_overhead_mib+):+ """The auto-path decision as it stood BEFORE the streamed-text-encoder tier, written out+ independently. The back-compat fence below compares the shipped planner against it, so a+ change that leaks the new tier into a caller that passed no split fails here."""+ required = model_dense_mib + runtime_headroom_mib + base_overhead_mib+ if required <= int(budget * 0.85):+ return OFFLOAD_NONE+ if companion_dense_mib is None:+ return OFFLOAD_MODEL+ group_floor = companion_dense_mib + runtime_headroom_mib + base_overhead_mib+ return OFFLOAD_GROUP if group_floor <= budget else OFFLOAD_MODEL+++def test_no_text_encoder_split_reproduces_the_previous_decision():+ # The back-compat fence. Every existing caller passes no split (the keyword defaults to None),+ # so across the size matrix the planner must land exactly where it did before, and must never+ # report the new tier.+ from core.inference.diffusion_memory import _safe_device_budget_mib+ for free, total in ((6_000, 8_192), (11_000, 12_288), (15_870, 16_305), (80_000, 81_920)):+ for model_dense in (2_000, 14_271, 40_000):+ for companion in (None, 200, 7_820, 30_000):+ for headroom in (1_000, 8_192):+ memory = _discrete(free, total)+ plan = plan_diffusion_memory(+ target = _target(),+ device_memory = memory,+ model_dense_mib = model_dense,+ companion_dense_mib = companion,+ runtime_headroom_mib = headroom,+ base_overhead_mib = 2048,+ )+ expected = _legacy_offload_policy(+ budget = _safe_device_budget_mib(memory),+ model_dense_mib = model_dense,+ companion_dense_mib = companion,+ runtime_headroom_mib = headroom,+ base_overhead_mib = 2048,+ )+ where = (free, total, model_dense, companion, headroom)+ assert plan.offload_policy == expected, where+ assert plan.stream_text_encoders is False, where+ assert plan.estimates["group_floor_streamed_te_mib"] is None, where+++def _stream_te_pipe(monkeypatch):+ """A pipe with two text encoders and a VAE, plus a record of which modules got group-offload+ hooks and which were placed resident."""+ applied: list[Any] = []+ Mod = _install_fake_torch_and_hooks(monkeypatch, lambda module, **kw: applied.append(module))++ class _Comp(Mod):+ def __init__(self, name):+ self.name = name+ self.placed = None++ def to(self, device):+ self.placed = device+ return self++ transformer = _Comp("transformer")+ text_encoder = _Comp("text_encoder")+ text_encoder_2 = _Comp("text_encoder_2")+ vae = _Comp("vae")++ class _Pipe:+ pass++ pipe = _Pipe()+ pipe.transformer = transformer+ pipe.components = {+ "transformer": transformer,+ "text_encoder": text_encoder,+ "text_encoder_2": text_encoder_2,+ "vae": vae,+ }+ return pipe, applied, transformer, text_encoder, text_encoder_2, vae+++def test_apply_group_offload_leaves_text_encoders_resident_by_default(monkeypatch):+ # The unchanged path: only the transformer streams, every other component is placed resident.+ import core.inference.diffusion_memory as mem++ pipe, applied, transformer, te, te2, vae = _stream_te_pipe(monkeypatch)+ assert mem._apply_group_offload(pipe, "cuda", logger = None) is True+ assert applied == [transformer]+ assert te.placed is not None and te2.placed is not None and vae.placed is not None+++def test_apply_group_offload_streams_text_encoders_when_asked(monkeypatch):+ # With the flag on, every text_encoder* module gets group-offload hooks and is NOT placed+ # resident. Placing them would defeat the whole point: their bytes are what did not fit.+ import core.inference.diffusion_memory as mem++ pipe, applied, transformer, te, te2, vae = _stream_te_pipe(monkeypatch)+ assert mem._apply_group_offload(pipe, "cuda", logger = None, stream_text_encoders = True) is True+ assert applied == [transformer, te, te2]+ assert te.placed is None and te2.placed is None+ assert vae.placed is not None # the VAE is the companion the tier keeps resident+++def _stream_te_kwargs(monkeypatch, **call_kw):+ """The kwargs _apply_group_offload hands diffusers, with a signature-complete fake.++ The other fakes here take **kw, which makes the signature gating in _apply_group_offload read+ as "diffusers does not support this". This one declares the real parameters so the gate is+ actually exercised."""+ seen: dict = {}++ def _apply(+ module,+ onload_device = None,+ offload_device = None,+ offload_type = None,+ num_blocks_per_group = None,+ non_blocking = False,+ use_stream = False,+ record_stream = False,+ low_cpu_mem_usage = False,+ **_,+ ):+ seen[getattr(module, "name", "?")] = dict(+ use_stream = use_stream,+ non_blocking = non_blocking,+ record_stream = record_stream,+ low_cpu_mem_usage = low_cpu_mem_usage,+ offload_type = offload_type,+ num_blocks_per_group = num_blocks_per_group,+ )++ import core.inference.diffusion_memory as mem++ pipe, _applied, *_ = _stream_te_pipe(monkeypatch)+ # SWAP, never re-install: a second _install_fake_torch_and_hooks mints a fresh stand-in Module+ # class, and the components built by the first call then fail isinstance -- so only the+ # transformer (which is taken unconditionally) reached diffusers and every assertion here was+ # silently checking one module instead of four.+ _swap_group_offloading(monkeypatch, _apply)+ assert mem._apply_group_offload(pipe, "cuda", logger = None, **call_kw) is True+ return seen+++def test_the_split_leaves_the_weights_only_estimate_terms_untouched():+ # The unified-memory load refusal sizes a load from `model_dense_mib + base_overhead_mib`+ # against `safe_device_budget_mib`, and deliberately excludes the soft runtime headroom. The+ # text-encoder split adds a NEW term and a new floor; it must not move any of those three, or+ # a refusal calibrated against them would silently change meaning.+ without = _zimage_plan(None).estimates+ with_split = _zimage_plan(_ZIMAGE_TEXT_ENCODER_MIB).estimates+ for key in ("safe_device_budget_mib", "model_dense_mib", "base_overhead_mib"):+ assert without[key] == with_split[key], key+ # The split itself is additive: it is visible, and the pre-existing floor is unchanged.+ assert without["group_floor_mib"] == with_split["group_floor_mib"]+ assert without["text_encoder_dense_mib"] is None+ assert with_split["text_encoder_dense_mib"] == _ZIMAGE_TEXT_ENCODER_MIB+ assert with_split["group_floor_streamed_te_mib"] < with_split["group_floor_mib"]+++def test_streaming_the_text_encoders_does_not_pin_host_memory(monkeypatch):+ # diffusers pins EVERY offloaded parameter in host RAM on the copy-stream path. That is a fair+ # trade when group offload was already the plan, but this tier is only ever a rescue FROM+ # whole-module offload, which pins nothing, on a card too small to hold the companions. Those+ # hosts are not reliably RAM-rich, and #8188's machine got into trouble precisely by turning a+ # device shortfall into unswappable host memory. The encoders run once per call, so the slower+ # unpinned copy is paid once rather than per step.+ seen = _stream_te_kwargs(monkeypatch, stream_text_encoders = True)+ assert seen, "the applier never reached diffusers"+ assert all(kw["low_cpu_mem_usage"] is True for kw in seen.values()), seen+++def test_the_unchanged_group_tier_still_pins_for_speed(monkeypatch):+ # The existing group plan is untouched: it was chosen because the companions FIT, so the host+ # is not being rescued and the pinned fast copy is the right default.+ seen = _stream_te_kwargs(monkeypatch)+ assert seen, "the applier never reached diffusers"+ assert all(kw["low_cpu_mem_usage"] is False for kw in seen.values()), seen+ # ... and the CUDA copy-stream overlap is still requested, which is what makes pinning matter.+ assert all(kw["use_stream"] and kw["non_blocking"] for kw in seen.values()), seen+++def _swap_group_offloading(monkeypatch, apply_group_offloading):+ """Replace apply_group_offloading on the ALREADY-installed fake diffusers.hooks.++ _install_fake_torch_and_hooks mints a fresh stand-in Module class each call, so calling it a+ second time would leave the components built by the first call failing isinstance."""+ import sys+ monkeypatch.setattr(+ sys.modules["diffusers.hooks"], "apply_group_offloading", apply_group_offloading+ )+++def test_a_text_encoder_that_refuses_group_offload_stays_resident(monkeypatch):+ # A text encoder is a far less well-trodden target for block-level group offloading than a+ # DiT. Before this tier existed the encoders were simply resident, so a refusal must degrade+ # back to that, not fail the load: by the time the encoders are reached the transformer already+ # carries hooks, and whole-module offload is no longer available as a fallback, so joining the+ # all-or-nothing DiT loop would turn a slow-but-working load into a hard failure.+ import core.inference.diffusion_memory as mem++ applied: list[Any] = []++ def _apply(module, **kw):+ if getattr(module, "name", "").startswith("text_encoder"):+ raise ValueError("no block list on this text encoder")+ applied.append(module)++ pipe, _unused, transformer, te, te2, vae = _stream_te_pipe(monkeypatch)+ # Swap only the hook: re-installing the fake torch would mint a NEW Module class and every+ # isinstance check against the already-built components would go false.+ _swap_group_offloading(monkeypatch, _apply)++ assert mem._apply_group_offload(pipe, "cuda", logger = None, stream_text_encoders = True) is True+ # The transformer still streams, and the refusing encoders are placed resident instead.+ assert applied == [transformer]+ assert te.placed is not None and te2.placed is not None+ assert vae.placed is not None+++def test_one_refusing_text_encoder_does_not_cost_the_other_its_streaming(monkeypatch):+ # Each encoder is decided on its own: a family where one encoder refuses and another does not+ # must still stream the one that works, or a single awkward component silently reverts the+ # whole rescue.+ import core.inference.diffusion_memory as mem++ applied: list[Any] = []++ def _apply(module, **kw):+ if getattr(module, "name", "") == "text_encoder":+ raise ValueError("no block list on this text encoder")+ applied.append(module)++ pipe, _unused, transformer, te, te2, _vae = _stream_te_pipe(monkeypatch)+ _swap_group_offloading(monkeypatch, _apply)++ assert mem._apply_group_offload(pipe, "cuda", logger = None, stream_text_encoders = True) is True+ assert applied == [transformer, te2]+ assert te.placed is not None # the refusing one is resident+ assert te2.placed is None # the working one still streams+++def test_a_failing_dit_keeps_its_all_or_nothing_semantics(monkeypatch):+ # The tolerance is scoped to the encoders. A DiT that fails AFTER another installed hooks+ # still propagates, because a partially hooked denoiser is not something the pipeline can run+ # or fall back from. This is the pre-existing contract and the new tier must not soften it.+ import core.inference.diffusion_memory as mem++ calls = {"n": 0}++ def _apply(module, **kw):+ calls["n"] += 1+ if calls["n"] >= 2:+ raise RuntimeError("OOM on the second DiT")++ Mod = _install_fake_torch_and_hooks(monkeypatch, _apply)++ class _DualPipe:+ pass++ pipe = _DualPipe()+ pipe.transformer = Mod()+ pipe.transformer_2 = Mod()+ pipe.components = {"transformer": pipe.transformer, "transformer_2": pipe.transformer_2}++ with pytest.raises(RuntimeError, match = "OOM on the second DiT"):+ mem._apply_group_offload(pipe, "cuda", logger = None, stream_text_encoders = True)+++def test_apply_memory_plan_threads_the_stream_flag_to_the_group_applier(monkeypatch):+ # End of the wire: the planner's decision has to reach _apply_group_offload, or the plan says+ # group-with-streamed-encoders while the pipeline still places them resident and OOMs.+ import core.inference.diffusion_memory as mem++ seen = {}++ def _fake(+ pipe,+ device,+ logger,+ *,+ stream_text_encoders = False,+ ):+ seen["stream_text_encoders"] = stream_text_encoders+ return True++ monkeypatch.setattr(mem, "_apply_group_offload", _fake)+ apply_memory_plan(_RecordingPipe(), _zimage_plan(_ZIMAGE_TEXT_ENCODER_MIB), device = "cuda")+ assert seen["stream_text_encoders"] is True+ apply_memory_plan(_RecordingPipe(), _plan(OFFLOAD_GROUP, tiling = True), device = "cuda")+ assert seen["stream_text_encoders"] is False+++# ── the generate-time activation guard ────────────────────────────────────────+# The load-time plan budgets the 1024x1024 default because load time cannot know the request, so a+# much larger frame was never compared against anything: at 1088x1920 the plan reserved half the+# working memory the pass needs. On Linux that raises OutOfMemoryError; on Windows WDDM the driver+# serves the overflow from system RAM instead, so ~27 GB lands on a 16 GB card with no exception+# and the desktop stops responding. These cover the pre-sampling refusal that replaces that.++# The Z-Image-Turbo GGUF hint from the report: the base repo carries the distilled marker, so the+# estimate here is the discounted one (0.85), which is the honest 13,872 MiB the issue measured.+_TURBO_HINT = (+ "z-image Z-Image-Turbo-Q4_K_S.gguf unsloth/Z-Image-Turbo-GGUF Tongyi-MAI/Z-Image-Turbo"+)+++def _shortfall(+ width,+ height,+ memory = None,+ **kw,+):+ from core.inference.diffusion_memory import image_activation_shortfall_message+ return image_activation_shortfall_message(+ device_memory = memory if memory is not None else _discrete(_16G_FREE_MIB, _16G_TOTAL_MIB),+ width = width,+ height = height,+ family = kw.pop("family", _TURBO_HINT),+ **kw,+ )+++def test_estimate_image_runtime_scales_with_the_real_dimensions():+ # The regression fence for the estimator itself: it already scales, it was simply never called+ # with anything. 1088x1920 is 1.99x the area of 1024x1024, so the headroom must be ~2x.+ base = estimate_image_runtime_mib(width = 1024, height = 1024)+ tall = estimate_image_runtime_mib(width = 1088, height = 1920)+ assert base == 8192+ assert tall == 16_320+ assert 1.95 < tall / base < 2.05+ # And with the distilled discount that the base repo now contributes, the report's number.+ assert estimate_image_runtime_mib(width = 1088, height = 1920, family = _TURBO_HINT) == 13_872+++def test_guard_refuses_the_oversized_frame_and_passes_the_default_one():+ # 13,872 MiB of working memory against a 13,822 MiB budget on the reported card: refuse.+ message = _shortfall(1088, 1920)+ assert message is not None+ # Everything the user needs to act: what they asked for, what it costs, what they have.+ assert "1088x1920" in message+ # The TOTAL the decision compared, not the activations alone: 13,872 MiB of activations plus+ # the 2,048 MiB of fixed overhead. Quoting 13.55 GB against a 13.50 GB budget was a refusal+ # whose own numbers were close enough to read as a bug, and on the 15.92 GiB card in the+ # report (14,254 MiB usable) it read as an outright contradiction.+ assert "15.55 GB" in message # needed, overhead included+ assert "2.00 GB of fixed overhead" in message+ assert "13.50 GB" in message # usable+ assert "15.50 GB" in message # currently free+ assert "smaller resolution" in message+ assert "UNSLOTH_DIFFUSION_ALLOW_OVERSIZED_GENERATE" in message+ # The same card at the default resolution needs 6963 MiB and must go straight through.+ assert _shortfall(1024, 1024) is None+++def test_guard_counts_the_base_overhead_alongside_the_activations():+ # The CUDA context, scheduler state and fragmentation allowance have to coexist with this+ # pass's tensors, and the load-time plan already sums them additively. Leaving the overhead+ # out left the guard silent by a few hundred MiB on the exact card #8188 was reported from:+ # a 15.92 GiB card gives a 14,254 MiB budget, which 13,872 MiB of activations fits and+ # 13,872 + 2048 does not.+ from core.inference.diffusion_memory import _safe_device_budget_mib++ reported_card = _discrete(16_302, 16_302) # idle 15.92 GiB card+ assert _safe_device_budget_mib(reported_card) == 14_254+ assert _shortfall(1088, 1920, memory = reported_card) is not None+ # ... and setting the overhead to zero is exactly what makes it silent again, so the term is+ # load-bearing rather than decorative.+ assert _shortfall(1088, 1920, memory = reported_card, base_overhead_mib = 0) is None+++def test_guard_never_refuses_at_or_below_the_resolution_the_load_planned_for():+ # The load's flat headroom is a PLANNING figure: it picks an offload tier, and the tier it+ # picks runs 1024x1024 on cards whose entire budget is below that figure. Treating it as a+ # hard limit there would refuse generations that complete today, so the guard is confined to+ # requests LARGER than what was planned. An 8 GB card is the case that proves it.+ small = _discrete(+ int(8 * 1024 * 0.97), 8 * 1024+ ) # safe budget 5898 MiB, under the 6963 default+ assert _shortfall(1024, 1024, memory = small) is None+ assert _shortfall(512, 512, memory = small) is None+ # It still refuses the genuinely oversized frame on that same card.+ assert _shortfall(1088, 1920, memory = small) is not None+++def test_guard_scales_with_batch_size():+ # Batch multiplies the activations exactly as area does, so the same overrun must be caught.+ assert _shortfall(1024, 1024, batch_size = 1) is None+ assert _shortfall(1024, 1024, batch_size = 4) is not None+ assert "at a batch of 4" in _shortfall(1024, 1024, batch_size = 4)+++def test_guard_is_skipped_on_unified_memory():+ # Offload means something different where the CPU and GPU share one pool, "free" is a moving+ # target shared with the OS, and the load-time unified refusal already owns that device class.+ unified = DeviceMemory("cuda", "cuda", "unified_memory", _16G_FREE_MIB, _16G_TOTAL_MIB)+ assert _shortfall(1088, 1920, memory = unified) is None+ mps = DeviceMemory("mps", "mps", "unified_memory", _16G_FREE_MIB, _16G_TOTAL_MIB)+ assert _shortfall(1088, 1920, memory = mps) is None+++def test_guard_is_skipped_when_free_memory_is_unknown():+ # No reading, no verdict: the planner's own rule for an unknown budget is to stay out of it.+ blind = DeviceMemory("cuda", "cuda", "discrete_vram", None, _16G_TOTAL_MIB)+ assert _shortfall(1088, 1920, memory = blind) is None+++def test_guard_is_skipped_off_cuda_and_rocm():+ # ROCm reports device "cuda", so that stays covered. XPU / CPU keep today's behaviour: their+ # allocators differ and this estimate was measured against a discrete VRAM pool.+ xpu = DeviceMemory("xpu", "xpu", "discrete_vram", _16G_FREE_MIB, _16G_TOTAL_MIB)+ assert _shortfall(1088, 1920, memory = xpu) is None+ cpu = DeviceMemory("cpu", "cpu", "system_memory", _16G_FREE_MIB, _16G_TOTAL_MIB)+ assert _shortfall(1088, 1920, memory = cpu) is None+++def test_guard_env_override_lets_an_oversized_generation_through(monkeypatch):+ from core.inference.diffusion_memory import OVERSIZED_GENERATE_ENV+ for value in ("1", "true", "YES", " on "):+ monkeypatch.setenv(OVERSIZED_GENERATE_ENV, value)+ assert _shortfall(1088, 1920) is None, value+ # Anything else is not an override, so the refusal stands.+ for value in ("0", "false", "", "maybe"):+ monkeypatch.setenv(OVERSIZED_GENERATE_ENV, value)+ assert _shortfall(1088, 1920) is not None, value+++def test_guard_fails_open_when_the_probe_raises():+ # A broken probe must never cost a user a generation that would have worked.+ class _Exploding:+ device = "cuda"+ memory_kind = "discrete_vram"+ is_unified = False+ total_mib = _16G_TOTAL_MIB++ @property+ def free_mib(self):+ raise RuntimeError("mem_get_info exploded")++ assert _shortfall(1088, 1920, memory = _Exploding()) is None+++def test_raiser_raises_valueerror_so_the_route_answers_400():+ # ValueError, not RuntimeError: /images/generate maps ValueError to a 400 carrying the reason,+ # while RuntimeError there is reserved for the not-loaded / cancelled sentinels and otherwise+ # becomes an opaque 500 with the reason stripped.+ from core.inference.diffusion_memory import raise_on_image_activation_shortfall+ with pytest.raises(ValueError, match = "1088x1920"):+ raise_on_image_activation_shortfall(+ device_memory = _discrete(_16G_FREE_MIB, _16G_TOTAL_MIB),+ width = 1088,+ height = 1920,+ family = _TURBO_HINT,+ )+ # And it is a no-op wherever the message function declines to produce a verdict.+ raise_on_image_activation_shortfall(+ device_memory = _discrete(_16G_FREE_MIB, _16G_TOTAL_MIB),+ width = 1024,+ height = 1024,+ family = _TURBO_HINT,+ )+++def _zimage_plan_on(memory, text_encoder_dense_mib):+ return plan_diffusion_memory(+ target = _target(),+ device_memory = memory,+ model_dense_mib = _ZIMAGE_MODEL_DENSE_MIB,+ companion_dense_mib = _ZIMAGE_COMPANION_MIB,+ text_encoder_dense_mib = text_encoder_dense_mib,+ runtime_headroom_mib = 8192,+ base_overhead_mib = 2048,+ )+++def test_default_resolution_plans_identically_across_card_sizes():+ # The cross-check between the two fixes: at the default resolution the guard is silent on every+ # card, and the plan a discrete CUDA target reaches with no text-encoder split is the plan it+ # reached before either change. Neither fix leaks into the other's territory.+ from core.inference.diffusion_memory import _safe_device_budget_mib+ for gigabytes in (8, 12, 16, 24, 32, 48, 80):+ total = gigabytes * 1024+ memory = _discrete(int(total * 0.97), total)+ assert _shortfall(1024, 1024, memory = memory) is None, gigabytes+ expected = _legacy_offload_policy(+ budget = _safe_device_budget_mib(memory),+ model_dense_mib = _ZIMAGE_MODEL_DENSE_MIB,+ companion_dense_mib = _ZIMAGE_COMPANION_MIB,+ runtime_headroom_mib = 8192,+ base_overhead_mib = 2048,+ )+ assert _zimage_plan_on(memory, None).offload_policy == expected, gigabytes+++def test_the_refusal_reports_the_number_it_compared():+ """A refusal that quotes less than it compared reads as a bug in the guard. On the 15.92 GiB+ card in #8188 (14,254 MiB usable) it printed "needs about 13.55 GB ... only about 13.92 GB+ usable" and then refused, which is a contradiction on its face."""+ from core.inference.diffusion_memory import DEFAULT_BASE_OVERHEAD_MIB++ message = _shortfall(1088, 1920, base_overhead_mib = 1_024)+ assert message is not None+ # 13,872 MiB of activations + 1,024 MiB of overhead.+ assert "14.55 GB of working memory" in message+ assert "1.00 GB of fixed overhead" in message+ # And with no overhead at all the two numbers are the activations, unchanged.+ assert "13.55 GB of working memory" in _shortfall(1088, 1920, base_overhead_mib = 0)+ assert DEFAULT_BASE_OVERHEAD_MIB > 0+++def test_the_activation_refusal_is_its_own_error_type():+ """The OpenAI-compatible route sanitises every exception into a bare 500, so the one message+ written FOR the caller needs a type it can recognise. Still a ValueError, so /images/generate+ keeps mapping it to a 400 with the reason."""+ import pytest as _pytest++ from core.inference.diffusion_memory import (+ ImageActivationShortfallError,+ raise_on_image_activation_shortfall,+ )++ assert issubclass(ImageActivationShortfallError, ValueError)+ with _pytest.raises(ImageActivationShortfallError):+ raise_on_image_activation_shortfall(+ device_memory = _discrete(_16G_FREE_MIB, _16G_TOTAL_MIB),+ width = 1088,+ height = 1920,+ family = _TURBO_HINT,+ )+ # A request the guard passes still raises nothing at all.+ raise_on_image_activation_shortfall(+ device_memory = _discrete(_16G_FREE_MIB, _16G_TOTAL_MIB),+ width = 1024,+ height = 1024,+ family = _TURBO_HINT,+ )+++def test_the_streamed_encoders_are_hooked_leaf_by_leaf(monkeypatch):+ # A text encoder is not a stack of uniform blocks, which is why _streamable_components and+ # _apply_streaming_offload both classify every text_encoder* as leaf_level. Handing this path+ # the DiTs' block_level kwargs made the plan and the application disagree: block level on an+ # encoder with no top-level ModuleList groups the whole thing as one unit, which is the+ # residency the streamed-encoder floor was picked to avoid.+ seen = _stream_te_kwargs(monkeypatch, stream_text_encoders = True)+ assert seen, "the applier never reached diffusers"+ encoders = {name: kw for name, kw in seen.items() if str(name).startswith("text_encoder")}+ denoisers = {name: kw for name, kw in seen.items() if not str(name).startswith("text_encoder")}+ assert encoders and denoisers, seen+ for name, kw in encoders.items():+ assert kw["offload_type"] == "leaf_level", name+ # leaf level has no blocks; diffusers only requires the count for block_level.+ assert kw["num_blocks_per_group"] is None, name+ for name, kw in denoisers.items():+ assert kw["offload_type"] == "block_level", name+ assert kw["num_blocks_per_group"] is not None, name+++def test_the_batch_remedy_appears_only_when_a_batch_was_budgeted():+ """The guard budgets one image everywhere except a Windows multi-image chunk, so a refusal+ almost always means one image does not fit. Telling that caller to use a smaller batch points+ them at the one change that provably cannot alter the decision."""+ single = _shortfall(1088, 1920)+ assert single is not None+ assert "smaller batch size" not in single+ assert "smaller resolution," in single+ batched = _shortfall(1024, 1024, batch_size = 4)+ assert batched is not None+ assert "at a batch of 4" in batched+ assert "or a smaller batch size" in batcheddiff --git a/studio/backend/tests/test_openai_images_generations_route.py b/studio/backend/tests/test_openai_images_generations_route.pyindex befe80b8f4d..916fc3d8aaf 100644--- a/studio/backend/tests/test_openai_images_generations_route.py+++ b/studio/backend/tests/test_openai_images_generations_route.py@@ -436,3 +436,26 @@ def test_signed_image_link_rejects_tampering_and_expiry(monkeypatch, tmp_path):monkeypatch.setattr(inference_routes, "_IMAGE_LINK_TTL", -1)expired = inference_routes._sign_image_id("img0")assert cli.get(f"{base}/img0/file-signed?token={expired}").status_code == 401+++def test_activation_shortfall_is_an_actionable_400(monkeypatch):+ """The one exception here whose text is written FOR the caller. Sanitising it into a bare 500+ left an OpenAI client with a server error for a request only they can fix, while the Studio+ route showed them the resolution, the budget and the remedies."""+ from core.inference.diffusion_memory import ImageActivationShortfallError++ reason = (+ "Generating at 2048x2048 needs about 15.55 GB of working memory, but only about "+ "13.50 GB is usable on this device. Generate at a smaller resolution."+ )+ backend = _FakeBackend(generate_error = ImageActivationShortfallError(reason))+ monkeypatch.setattr(diffusion_module, "get_diffusion_backend", lambda: backend)+ cli, store, _save = _make_client(backend)+ monkeypatch.setattr(gallery_module, "save", _save)+ resp = cli.post("/v1/images/generations", json = {"prompt": "p", "size": "256x256"})+ assert resp.status_code == 400+ err = resp.json()["error"]+ assert err["message"] == reason+ assert err["param"] == "size"+ # Still typed: an ordinary ValueError keeps its sanitized 500 (test above), so no other raw+ # exception text rides out on the back of this.