Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: plan image offload on measured activations so more VRAM is never slower (#12043)

Daniel Han856af9e0cff9
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.py
index fd5f1dc078c..668d1f29c69 100644
--- a/studio/backend/core/inference/diffusion.py
+++ b/studio/backend/core/inference/diffusion.py
@@ -18,6 +18,7 @@ in the arbiter the routes call, not here.
from __future__ import annotations
from contextlib import contextmanager
+import contextvars
import functools
import inspect
import json
@@ -111,6 +112,7 @@ from .diffusion_memory import (
OFFLOAD_NONE,
OFFLOAD_STREAMING,
apply_memory_plan,
+ calibrated_image_activation,
engage_vae_tiling,
estimate_gguf_resident_mib,
estimate_image_runtime_mib,
@@ -176,6 +178,7 @@ from .diffusion_attention import (
apply_attention_backend,
normalize_attention_backend,
sdpa_math_only,
+ sdpa_subquadratic_confirmed,
select_attention_backend,
_ensure_attention_backend_installed,
)
@@ -1052,6 +1055,8 @@ class _LoadState:
# 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.
variant_hint: str = ""
+ # Promoted tiers leave no room for a later ControlNet.
+ calibrated_placement: bool = False
@dataclass
@@ -1633,6 +1638,50 @@ def _dense_candidate_is_prequant(
return False
+# Unset outside a load, which then plans on the max tier's (larger) activations.
+_PLANNED_SPEED_MODE: contextvars.ContextVar[Any] = contextvars.ContextVar("_PLANNED_SPEED_MODE")
+_SPEED_UNKNOWN = object()
+
+
+def _plans_at_requested_speed(fn: Callable[..., Any]) -> Callable[..., Any]:
+ @functools.wraps(fn)
+ def wrapper(*args: Any, **kwargs: Any) -> Any:
+ token = _PLANNED_SPEED_MODE.set(kwargs.get("speed_mode"))
+ try:
+ return fn(*args, **kwargs)
+ finally:
+ _PLANNED_SPEED_MODE.reset(token)
+
+ return wrapper
+
+
+def _calibrated_activation(fam: Any, target: Any) -> Any:
+ """Measured activations apply only where measured: NVIDIA with a sub-quadratic attention kernel."""
+ if getattr(target, "backend", None) != "cuda" or getattr(target, "vendor", None) != "nvidia":
+ return None
+ # Measured without input images: references the guard cannot size (no reference_resolutions) would overflow.
+ if getattr(fam, "reference", False) and not tuple(
+ getattr(fam, "reference_resolutions", ()) or ()
+ ):
+ return None
+ # Measured at 16-bit only; fp32-promoted families (Z-Image pre-Ampere) do not qualify.
+ compute = _resolve_diffusion_compute_dtype(fam, getattr(target, "dtype", None))
+ if (_float_load_itemsize(compute) or 2) > 2:
+ return None
+ requested = _PLANNED_SPEED_MODE.get(_SPEED_UNKNOWN)
+ try:
+ max_speed = requested is _SPEED_UNKNOWN or normalize_speed_mode(requested) == SPEED_MAX
+ except ValueError:
+ max_speed = True
+ activation = calibrated_image_activation(getattr(fam, "name", None), max_speed = max_speed)
+ if activation is None:
+ return None
+ try:
+ return activation if sdpa_subquadratic_confirmed(target) else None
+ except Exception: # noqa: BLE001 - unprobed attention keeps the flat estimate
+ return None
+
+
def _quadratic_attention(target: Any, engaged_backend: Optional[str] = None) -> bool:
"""Whether attention can only run on SDPA math (quadratic memory); False when unknown.
Any engaged non-native backend is a fused kernel, so the SDPA probe only speaks for native."""
@@ -3445,6 +3494,7 @@ class DiffusionBackend:
logger.warning("diffusion.te_prequant_plan_failed: %s", exc)
return {}
+ @_plans_at_requested_speed
def _pipeline_planned_denoiser_scheme(
self,
fam: Any,
@@ -5088,6 +5138,7 @@ class DiffusionBackend:
@_invalidates_gpu_memory("diffusion load")
@_account_owned_load
+ @_plans_at_requested_speed
def load_pipeline(
self,
repo_id: str,
@@ -7096,6 +7147,7 @@ class DiffusionBackend:
kind = kind,
cpu_offload = effective_policy != OFFLOAD_NONE,
offload_policy = effective_policy,
+ calibrated_placement = "calibrated_headroom_mib" in plan.estimates,
vae_tiling = effective_tiling,
memory_mode = plan.requested_mode,
speed_mode = effective_speed,
@@ -8121,6 +8173,7 @@ class DiffusionBackend:
runtime_headroom_mib = runtime_headroom,
requested_mode = memory_mode,
explicit_offload = cpu_offload,
+ calibrated_activation = _calibrated_activation(fam, target),
)
@staticmethod
@@ -8215,11 +8268,20 @@ class DiffusionBackend:
del cn_model
raise RuntimeError(DIFFUSION_CANCELLED_MSG)
# Placement follows the base offload policy (resident base -> resident, offloaded -> group offload).
- # Best-effort.
- if getattr(state, "offload_policy", OFFLOAD_NONE) != OFFLOAD_NONE and (
+ # Calibrated tiers budget only the base model: ControlNet must stream, no resident fallback.
+ calibrated = bool(getattr(state, "calibrated_placement", False))
+ if (getattr(state, "offload_policy", OFFLOAD_NONE) != OFFLOAD_NONE or calibrated) and (
_offload_controlnet_module(cn_model, state.device, logger)
):
pass
+ elif calibrated:
+ del cn_model
+ clear_gpu_cache()
+ raise ValueError(
+ "This ControlNet could not be streamed from system memory, and loading it fully onto "
+ "the GPU beside the model could run out of memory. Reload the model with the balanced "
+ "memory mode to use ControlNet, or generate without it."
+ )
else:
cn_model = cn_model.to(state.device)
if cancel.is_set():
@@ -9093,6 +9155,8 @@ class DiffusionBackend:
guard_target, getattr(state, "attention_backend", None)
),
allow_oversized = allow_oversized,
+ calibrated_placement = bool(getattr(state, "calibrated_placement", False)),
+ controlnet = workflow == "controlnet" and control_pil is not None,
logger = logger,
)
verdict = raise_on_image_activation_shortfall(**guard_kwargs)
@@ -9803,7 +9867,7 @@ def _offload_controlnet_module(cn_model: Any, device: str, logger: Any) -> bool:
base model was loaded with an offload policy: forcing the ControlNet fully resident with
``.to(device)`` would defeat that low-VRAM placement and can OOM. Group offloading is applied
to this single module, so it is isolated and reversible. Returns True on success; on any
- failure the caller falls back to a resident placement, so this never blocks a load."""
+ failure the caller falls back to a resident placement (a calibrated tier refuses instead)."""
try:
import torch
from diffusers.hooks import apply_group_offloading
diff --git a/studio/backend/core/inference/diffusion_attention.py b/studio/backend/core/inference/diffusion_attention.py
index 28e02891924..91339218315 100644
--- a/studio/backend/core/inference/diffusion_attention.py
+++ b/studio/backend/core/inference/diffusion_attention.py
@@ -208,6 +208,11 @@ def sdpa_math_only(target: Any) -> bool:
return SDPA_MATH in available and not any(k in available for k in _SDPA_SUBQUADRATIC)
+def sdpa_subquadratic_confirmed(target: Any) -> bool:
+ """True only when a sub-quadratic SDPA kernel was seen to run; an unanswered probe is False."""
+ return any(k in _SDPA_SUBQUADRATIC for k in available_sdpa_kernels(target))
+
+
SDPA_MATH_ONLY_MESSAGE = (
"attention has no fused kernel on this device, so it will run on the SDPA math backend, "
"which materialises the full attention score matrix (batch x heads x tokens x tokens, 4 bytes "
diff --git a/studio/backend/core/inference/diffusion_memory.py b/studio/backend/core/inference/diffusion_memory.py
index 7e66f32d259..7cf126e8ed6 100644
--- a/studio/backend/core/inference/diffusion_memory.py
+++ b/studio/backend/core/inference/diffusion_memory.py
@@ -242,13 +242,22 @@ def _host_empty_cache() -> None:
pass
+def _pinnable_layout(data: Any) -> bool:
+ if data.is_contiguous():
+ return True
+ import torch
+
+ fmt = {4: torch.channels_last, 5: torch.channels_last_3d}.get(data.dim())
+ return fmt is not None and data.is_contiguous(memory_format = fmt)
+
+
def _pin_host_weights(
module: Any,
host: dict,
logger: Any = None,
buffer_host: Optional[dict] = None,
) -> int:
- """Pack kept host weights and buffers into page-locked chunks; returns bytes pinned. Contiguous only, so channels_last survives."""
+ """Pack kept host weights and buffers into page-locked chunks; returns bytes pinned. Each copy keeps its source strides."""
import torch
mode = _pin_mode()
@@ -260,7 +269,7 @@ def _pin_host_weights(
if host.get(name) is not None
and p.device.type == "cpu"
and _keepable(p)
- and p.data.is_contiguous()
+ and _pinnable_layout(p.data)
and not p.data.is_pinned()
]
buffers = [
@@ -319,7 +328,12 @@ def _pin_host_weights(
for (name, p), (index, start) in zip(params, slots):
if index == len(bufs):
bufs.append(torch.empty(chunks[index], dtype = torch.uint8, pin_memory = True))
- view = bufs[index][start : start + p.data.nbytes].view(p.dtype).view(p.shape)
+ view = bufs[index][start : start + p.data.nbytes].view(p.dtype)
+ view = (
+ view.view(p.shape)
+ if p.data.is_contiguous()
+ else view.as_strided(p.shape, p.data.stride())
+ )
view.copy_(p.data)
placed.append((name, p, view))
except Exception as exc: # noqa: BLE001 - e.g. a WSL pinned-memory cap: keep the pageable weights
@@ -1008,6 +1022,48 @@ def estimate_video_runtime_mib(
return max(3072, int(4096 + 3.0 * decoded_mib))
+@dataclass(frozen = True)
+class CalibratedImageActivation:
+ """MiB above the resident weights, margin included: each phase at 1024x1024, then the 2048x2048 worst case."""
+
+ text_encoder_mib: int
+ denoise_mib: int
+ decode_mib: int
+ tiled_decode_mib: int
+ max_canvas_mib: int
+
+ def headroom(self, tiled: bool) -> int:
+ return max(
+ self.text_encoder_mib,
+ self.denoise_mib,
+ self.tiled_decode_mib if tiled else self.decode_mib,
+ )
+
+
+# NVIDIA worst case per (off / eager / default, max) tier; U-Nets unlisted (cannot stream encoders).
+_ACTIVATION_MARGIN = 1.2
+_MEASURED_IMAGE_ACTIVATION_MIB: dict[
+ str, tuple[tuple[int, int, int, int, int], tuple[int, int, int, int, int]]
+] = {
+ # text encoder, denoise, untiled decode, tiled decode (all at 1024x1024), max(denoise, tiled decode) at 2048x2048
+ "qwen-image-2.1": ((1_849, 666, 7_648, 449, 2_479), (1_849, 2_489, 7_648, 449, 9_602)),
+ "flux.1": ((288, 892, 2_666, 2_456, 2_674), (288, 892, 2_666, 2_456, 2_674)),
+ "flux.2-klein": ((1_516, 1_160, 2_645, 2_456, 3_876), (1_516, 1_205, 2_677, 2_456, 3_924)),
+ "z-image": ((744, 1_199, 2_666, 2_456, 4_327), (744, 1_271, 2_669, 2_456, 4_327)),
+}
+
+
+def calibrated_image_activation(
+ family: Optional[str], *, max_speed: bool = True
+) -> Optional[CalibratedImageActivation]:
+ measured = _MEASURED_IMAGE_ACTIVATION_MIB.get(str(family or ""))
+ if measured is None:
+ return None
+ return CalibratedImageActivation(
+ *(int(v * _ACTIVATION_MARGIN) for v in measured[1 if max_speed else 0])
+ )
+
+
def _reserve_mib(memory_kind: str, base: int) -> int:
if memory_kind == "unified_memory":
return max(2048, int(base * 0.20)) # OS + CPU share this pool
@@ -1592,6 +1648,7 @@ def plan_diffusion_memory(
base_overhead_mib: int = DEFAULT_BASE_OVERHEAD_MIB,
requested_mode: Optional[str] = None,
explicit_offload: bool = False,
+ calibrated_activation: Optional[CalibratedImageActivation] = None,
) -> MemoryPlan:
"""Pick an offload policy plus VAE memory savers for the current load.
@@ -1778,6 +1835,29 @@ def plan_diffusion_memory(
# keeps the VAE resident.
any_offload = policy != OFFLOAD_NONE or device_memory.backend in ("mps", "cpu")
tile = policy in (OFFLOAD_MODEL, OFFLOAD_SEQUENTIAL) or device_memory.backend in ("mps", "cpu")
+ if (
+ calibrated_activation is not None
+ and mode == MEMORY_MODE_AUTO
+ and not (explicit_offload and normalize_memory_mode(requested_mode) is None)
+ and can_offload
+ and not device_memory.is_unified
+ ):
+ faster = _calibrated_faster_tier(
+ calibrated_activation,
+ budget = budget,
+ model_dense_mib = model_dense_mib,
+ companion_dense_mib = companion_dense_mib,
+ text_encoder_dense_mib = text_encoder_dense_mib,
+ base_overhead_mib = base_overhead_mib,
+ free_mib = device_memory.free_mib,
+ policy = policy,
+ stream_transformer = stream_transformer,
+ )
+ if faster is not None:
+ policy, stream_text_encoders, stream_transformer, tile, reason = faster
+ any_offload = policy != OFFLOAD_NONE
+ reasons.append(reason)
+ estimates["calibrated_headroom_mib"] = calibrated_activation.headroom(tile)
return MemoryPlan(
requested_mode = mode,
offload_policy = policy,
@@ -1792,6 +1872,106 @@ def plan_diffusion_memory(
)
+def _calibrated_faster_tier(
+ act: CalibratedImageActivation,
+ *,
+ budget: Optional[int],
+ model_dense_mib: Optional[int],
+ companion_dense_mib: Optional[int],
+ text_encoder_dense_mib: Optional[int],
+ base_overhead_mib: int,
+ free_mib: Optional[int],
+ policy: str,
+ stream_transformer: bool,
+) -> Optional[tuple[str, bool, bool, bool, str]]:
+ """Strictly faster tier than the flat pick, else None; resident tiers must fit the 2048 denoise (it cannot tile).
+ Every check grows with the budget, so more VRAM never picks a slower tier."""
+ if budget is None or free_mib is None or model_dense_mib is None or companion_dense_mib is None:
+ return None
+ te = max(0, int(text_encoder_dense_mib or 0))
+ transformer = max(0, int(model_dense_mib) - int(companion_dense_mib))
+ others = max(0, int(companion_dense_mib) - te)
+ overhead = max(0, int(base_overhead_mib))
+ budget = int(budget)
+ free = int(free_mib) - overhead
+ room = free - act.max_canvas_mib
+ if policy == OFFLOAD_NONE:
+ flat_rank = 0
+ elif policy == OFFLOAD_GROUP and not stream_transformer:
+ flat_rank = 1
+ elif policy == OFFLOAD_MODEL:
+ flat_rank = 4
+ elif policy == OFFLOAD_GROUP:
+ flat_rank = 5
+ else:
+ return None
+ model_viable = max(transformer, te, others) <= budget and (
+ flat_rank < 5
+ or (
+ transformer <= room
+ and te + act.text_encoder_mib <= free
+ and others + act.tiled_decode_mib <= free
+ )
+ )
+ resident_streamed_te = te > 0 and transformer + others <= room
+ candidates = (
+ (
+ transformer + te + others + act.headroom(False) + overhead <= int(budget * 0.85)
+ and transformer + te + others <= room,
+ (OFFLOAD_NONE, False, True, False, "measured activations fit resident with headroom"),
+ ),
+ (
+ resident_streamed_te
+ and transformer + others + act.headroom(False) + overhead <= budget,
+ (
+ OFFLOAD_GROUP,
+ True,
+ False,
+ False,
+ "measured activations keep the transformer resident with the text encoders streamed",
+ ),
+ ),
+ (
+ resident_streamed_te and transformer + others + act.headroom(True) + overhead <= budget,
+ (
+ OFFLOAD_GROUP,
+ True,
+ False,
+ True,
+ "measured activations keep the transformer resident with the text encoders "
+ "streamed and the VAE decode tiled",
+ ),
+ ),
+ (
+ model_viable and others + act.decode_mib + overhead <= budget,
+ (
+ OFFLOAD_MODEL,
+ False,
+ True,
+ False,
+ "whole-module offload uploads the transformer once per call, and the measured "
+ "VAE decode fits untiled",
+ ),
+ ),
+ (
+ model_viable,
+ (
+ OFFLOAD_MODEL,
+ False,
+ True,
+ True,
+ "whole-module offload uploads the transformer once per call instead of every step",
+ ),
+ ),
+ )
+ for rank, (fits, tier) in enumerate(candidates):
+ if rank >= flat_rank:
+ return None
+ if fits:
+ return tier
+ return None
+
+
def _streamable_components(pipe: Any, torch: Any) -> dict[str, tuple[Any, str]]:
"""Component name -> (module, group-offload type) for what streaming keeps off the device.
@@ -3587,9 +3767,13 @@ def _activation_refusal_message(
source_driven: bool,
condition_pixels: int,
tiled: bool,
+ controlnet: bool = False,
+ calibrated: bool = False,
) -> str:
batch_note = f" at a batch of {batch}" if batch > 1 else ""
- cond_note = " with its input images" if condition_pixels else ""
+ cond_note = (
+ " with ControlNet" if controlnet else " with its input images" if condition_pixels else ""
+ )
if source_driven:
remedy = (
"Upload a smaller source image (this workflow takes its output size from the image, "
@@ -3608,7 +3792,9 @@ def _activation_refusal_message(
# Smaller-batch hint only when batch > 1: a one-image refusal cannot be fixed by asking for fewer.
f"{remedy}"
f"{' or a smaller batch size' if batch > 1 else ''}"
- f"{', use fewer input images or a lower reference detail' if condition_pixels else ''}, "
+ f"{', use fewer input images or a lower reference detail' if condition_pixels else ''}"
+ f"{', generate without ControlNet' if controlnet else ''}"
+ f"{', reload the model with the balanced memory mode' if calibrated else ''}, "
"or free GPU memory by closing other applications. To try anyway, turn on "
f"'{OVERSIZED_GENERATE_SETTING_LABEL}' under Advanced on the Images page "
"(API callers of /api/inference/images/generate can send allow_oversized; server installs "
@@ -3630,6 +3816,8 @@ def image_activation_verdict(
vae_sliced: bool = False,
quadratic_attention: bool = False,
allow_oversized: bool = False,
+ calibrated_placement: bool = False,
+ controlnet: bool = False,
) -> ImageActivationVerdict:
"""Decide whether this generation's ACTIVATIONS fit the free device budget: run it as loaded,
run it with the VAE tiled, or refuse.
@@ -3679,6 +3867,13 @@ def image_activation_verdict(
budget = _safe_device_budget_mib(device_memory)
if budget is None:
return ImageActivationVerdict(ACTIVATION_RUN)
+ # Calibrated tiers measured only the unconditioned denoise; a ControlNet counts as one output-sized image.
+ input_pixels = max(0, int(condition_pixels or 0))
+ conditioned = bool(calibrated_placement) and (input_pixels > 0 or bool(controlnet))
+ if calibrated_placement and controlnet:
+ condition_pixels = input_pixels + max(64, int(width or DEFAULT_IMAGE_WIDTH)) * max(
+ 64, int(height or DEFAULT_IMAGE_HEIGHT)
+ )
needed = estimate_image_runtime_mib(
width = width,
height = height,
@@ -3716,9 +3911,11 @@ def image_activation_verdict(
# false refusal at or below the default resolution, because the `needed <= planned` arm already exempts every
# request the load itself budgeted for.
numbers = dict(needed_mib = int(needed), tiled_needed_mib = tiled, budget_mib = int(budget))
- if int(needed) + overhead <= int(budget) or needed <= planned:
+ if int(needed) + overhead <= int(budget) or (not conditioned and needed <= planned):
return ImageActivationVerdict(ACTIVATION_RUN, **numbers)
- if tiled is not None and (int(tiled) + overhead <= int(budget) or tiled <= planned):
+ if tiled is not None and (
+ int(tiled) + overhead <= int(budget) or (not conditioned and tiled <= planned)
+ ):
return ImageActivationVerdict(ACTIVATION_TILE, **numbers)
if override:
# Tile even under quadratic attention: the estimate is untrusted there, but tiling still lowers the peak.
@@ -3738,8 +3935,10 @@ def image_activation_verdict(
budget_mib = int(budget),
free_mib = int(free),
source_driven = source_driven,
- condition_pixels = condition_pixels,
+ condition_pixels = input_pixels,
tiled = tiled is not None,
+ controlnet = bool(controlnet),
+ calibrated = conditioned,
)
return ImageActivationVerdict(ACTIVATION_REFUSE, message = message, **numbers)
@@ -3758,6 +3957,8 @@ def image_activation_shortfall_message(
vae_sliced: bool = False,
quadratic_attention: bool = False,
allow_oversized: bool = False,
+ calibrated_placement: bool = False,
+ controlnet: bool = False,
) -> Optional[str]:
return image_activation_verdict(
device_memory = device_memory,
@@ -3772,6 +3973,8 @@ def image_activation_shortfall_message(
vae_sliced = vae_sliced,
quadratic_attention = quadratic_attention,
allow_oversized = allow_oversized,
+ calibrated_placement = calibrated_placement,
+ controlnet = controlnet,
).message
@@ -3789,6 +3992,8 @@ def raise_on_image_activation_shortfall(
vae_sliced: bool = False,
quadratic_attention: bool = False,
allow_oversized: bool = False,
+ calibrated_placement: bool = False,
+ controlnet: bool = False,
logger: Any = None,
) -> ImageActivationVerdict:
"""Refuse a generation whose activations cannot fit the free device budget; else return the verdict.
@@ -3810,6 +4015,8 @@ def raise_on_image_activation_shortfall(
vae_sliced = vae_sliced,
quadratic_attention = quadratic_attention,
allow_oversized = allow_oversized,
+ calibrated_placement = calibrated_placement,
+ controlnet = controlnet,
)
if verdict.action == ACTIVATION_REFUSE:
if logger is not None:
diff --git a/studio/backend/tests/test_diffusion_calibrated_activation.py b/studio/backend/tests/test_diffusion_calibrated_activation.py
new file mode 100644
index 00000000000..0c61a57c130
--- /dev/null
+++ b/studio/backend/tests/test_diffusion_calibrated_activation.py
@@ -0,0 +1,543 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+from __future__ import annotations
+
+import types
+
+import pytest
+
+import core.inference.diffusion_memory as dm
+from core.inference.diffusion_memory import (
+ MEMORY_MODE_BALANCED,
+ MEMORY_MODE_FAST,
+ MEMORY_MODE_LOW_VRAM,
+ OFFLOAD_GROUP,
+ OFFLOAD_MODEL,
+ OFFLOAD_NONE,
+ CalibratedImageActivation,
+ DeviceMemory,
+ calibrated_image_activation,
+ plan_diffusion_memory,
+)
+
+# Planner inputs logged by real loads (MiB): transformer + companions, companions, text encoders.
+QWEN21_GGUF = dict(model_dense_mib = 17_897, companion_dense_mib = 10_247, text_encoder_dense_mib = 8_959)
+ZIMAGE_BF16 = dict(model_dense_mib = 31_326, companion_dense_mib = 7_820, text_encoder_dense_mib = 7_629)
+FLUX1_BF16 = dict(model_dense_mib = 32_184, companion_dense_mib = 9_478, text_encoder_dense_mib = 9_318)
+QWEN21_GGUF_BF16_TE = dict(
+ model_dense_mib = 25_627, companion_dense_mib = 17_977, text_encoder_dense_mib = 16_689
+)
+LARGE_TE = dict(model_dense_mib = 19_288, companion_dense_mib = 12_288, text_encoder_dense_mib = 11_000)
+SDXL = dict(model_dense_mib = 13_235, companion_dense_mib = 13_232, text_encoder_dense_mib = 3_119)
+QWEN21_ACT = CalibratedImageActivation(
+ text_encoder_mib = 1_498,
+ denoise_mib = 794,
+ decode_mib = 9_172,
+ tiled_decode_mib = 590,
+ max_canvas_mib = 2_960,
+)
+SMALL_VAE_ACT = CalibratedImageActivation(
+ text_encoder_mib = 1_200,
+ denoise_mib = 900,
+ decode_mib = 3_000,
+ tiled_decode_mib = 3_000,
+ max_canvas_mib = 3_600,
+)
+GIB = 1024
+
+
+def _target():
+ return types.SimpleNamespace(device = "cuda", backend = "cuda", supports_model_cpu_offload = True)
+
+
+def _card(total_gib, kind = "discrete_vram"):
+ total = int(total_gib * GIB)
+ return DeviceMemory("cuda", "cuda", kind, total - 1_229, total)
+
+
+def _plan(
+ total_gib,
+ sizes,
+ act,
+ mode = None,
+ explicit = False,
+ kind = "discrete_vram",
+):
+ return plan_diffusion_memory(
+ target = _target(),
+ device_memory = _card(total_gib, kind),
+ runtime_headroom_mib = 8192,
+ requested_mode = mode,
+ explicit_offload = explicit,
+ calibrated_activation = act,
+ **sizes,
+ )
+
+
+def _rank(plan, sizes):
+ budget = plan.estimates["safe_device_budget_mib"]
+ transformer = sizes["model_dense_mib"] - sizes["companion_dense_mib"]
+ if plan.offload_policy == OFFLOAD_NONE:
+ return 0
+ if plan.offload_policy == OFFLOAD_GROUP and not plan.stream_transformer:
+ return 2 if plan.vae_tiling else 1
+ if plan.offload_policy == OFFLOAD_MODEL:
+ if max(transformer, sizes["text_encoder_dense_mib"]) > budget:
+ return 6
+ return 4 if plan.vae_tiling else 3
+ return 5
+
+
+def test_16gb_qwen_image_21_keeps_the_transformer_resident_instead_of_streaming_every_step():
+ flat = _plan(16, QWEN21_GGUF, None)
+ assert flat.offload_policy == OFFLOAD_GROUP and flat.stream_transformer
+ plan = _plan(16, QWEN21_GGUF, QWEN21_ACT)
+ assert plan.offload_policy == OFFLOAD_GROUP
+ assert plan.stream_transformer is False and plan.stream_text_encoders is True
+ assert plan.vae_tiling is True and plan.vae_slicing is True
+ assert "tiled" in plan.reasons[-1]
+
+
+def test_14gb_qwen_image_21_offloads_whole_modules_instead_of_streaming_every_step():
+ flat = _plan(15, QWEN21_GGUF, None)
+ assert flat.offload_policy == OFFLOAD_GROUP and flat.stream_transformer
+ plan = _plan(15, QWEN21_GGUF, QWEN21_ACT)
+ assert plan.offload_policy == OFFLOAD_MODEL and plan.vae_tiling is True
+
+
+def test_12gb_keeps_tiling_when_the_measured_decode_does_not_fit():
+ flat = _plan(12, QWEN21_GGUF, None)
+ plan = _plan(12, QWEN21_GGUF, QWEN21_ACT)
+ assert flat.offload_policy == plan.offload_policy == OFFLOAD_MODEL
+ assert flat.vae_tiling is plan.vae_tiling is True
+ assert plan == flat
+
+
+def test_whole_module_offload_untiles_a_decode_that_fits():
+ flat = _plan(12, QWEN21_GGUF, None)
+ plan = _plan(12, QWEN21_GGUF, SMALL_VAE_ACT)
+ assert flat.offload_policy == plan.offload_policy == OFFLOAD_MODEL
+ assert flat.vae_tiling is True and plan.vae_tiling is False
+
+
+def test_whole_module_offload_untiles_when_the_resident_transformer_does_not_fit():
+ act = CalibratedImageActivation(1_000, 800, 3_000, 600, 2_000)
+ sizes = dict(model_dense_mib = 23_897, companion_dense_mib = 10_247, text_encoder_dense_mib = 8_959)
+ plan = _plan(19, sizes, act)
+ assert plan.offload_policy == OFFLOAD_MODEL and plan.vae_tiling is False
+
+
+ "sizes, act, strict",
+ [
+ (QWEN21_GGUF, QWEN21_ACT, True),
+ (QWEN21_GGUF, SMALL_VAE_ACT, True),
+ (ZIMAGE_BF16, SMALL_VAE_ACT, True),
+ (FLUX1_BF16, SMALL_VAE_ACT, True),
+ (SDXL, SMALL_VAE_ACT, True),
+ (ZIMAGE_BF16, CalibratedImageActivation(1_000, 800, 30_000, 600, 1_000), True),
+ (QWEN21_GGUF, CalibratedImageActivation(1_000, 800, 3_000, 600, 9_000), False),
+ ],
+)
+def test_more_vram_is_never_slower_and_never_slower_than_the_flat_plan(sizes, act, strict):
+ last = None
+ for step in range(4 * 8, 96 * 8 + 1):
+ gib = step / 8
+ flat = _plan(gib, sizes, None)
+ plan = _plan(gib, sizes, act)
+ rank = _rank(plan, sizes)
+ assert rank <= _rank(flat, sizes), (gib, plan.reasons)
+ if last is not None:
+ assert rank <= last[1] or (not strict and plan == flat), (gib, last, plan.reasons)
+ last = (gib, rank)
+
+
[email protected]("max_speed", [False, True])
[email protected]("family", ["qwen-image-2.1", "flux.1", "flux.2-klein", "z-image"])
+ "sizes", [QWEN21_GGUF, QWEN21_GGUF_BF16_TE, LARGE_TE, ZIMAGE_BF16, FLUX1_BF16]
+)
+def test_a_module_taken_off_streaming_fits_beside_its_own_phase(sizes, family, max_speed):
+ act = calibrated_image_activation(family, max_speed = max_speed)
+ transformer = sizes["model_dense_mib"] - sizes["companion_dense_mib"]
+ te = sizes["text_encoder_dense_mib"]
+ others = sizes["companion_dense_mib"] - te
+ for step in range(4 * 8, 96 * 8 + 1):
+ gib = step / 8
+ flat = _plan(gib, sizes, None)
+ plan = _plan(gib, sizes, act)
+ if plan == flat or flat.offload_policy != OFFLOAD_GROUP or not flat.stream_transformer:
+ continue
+ free = _card(gib).free_mib - dm.DEFAULT_BASE_OVERHEAD_MIB
+ assert transformer + act.max_canvas_mib <= free, (gib, plan.reasons)
+ if plan.offload_policy == OFFLOAD_MODEL:
+ assert te + act.text_encoder_mib <= free and others + act.tiled_decode_mib <= free, (
+ gib,
+ plan.reasons,
+ )
+
+
+def test_a_largest_canvas_denoise_that_would_not_fit_keeps_the_transformer_off_the_resident_tiers():
+ act = CalibratedImageActivation(1_000, 800, 3_000, 600, 6_000)
+ assert _plan(16, QWEN21_GGUF, act) == _plan(16, QWEN21_GGUF, None)
+ assert _plan(17, QWEN21_GGUF, act).offload_policy == OFFLOAD_MODEL
+ plan = _plan(18, QWEN21_GGUF, act)
+ assert plan.offload_policy == OFFLOAD_GROUP and plan.stream_transformer is False
+
+
+def test_an_unknown_free_reading_keeps_the_flat_plan():
+ card = DeviceMemory("cuda", "cuda", "discrete_vram", None, 16 * GIB)
+ kw = dict(target = _target(), device_memory = card, runtime_headroom_mib = 8192, **QWEN21_GGUF)
+ assert plan_diffusion_memory(calibrated_activation = QWEN21_ACT, **kw) == plan_diffusion_memory(
+ **kw
+ )
+
+
+ "mode, explicit",
+ [
+ (MEMORY_MODE_LOW_VRAM, False),
+ (MEMORY_MODE_BALANCED, False),
+ (MEMORY_MODE_FAST, False),
+ (None, True),
+ ],
+)
+def test_explicit_modes_keep_the_flat_plan(mode, explicit):
+ for gib in (6, 8, 12, 16, 20, 24, 48):
+ assert _plan(gib, QWEN21_GGUF, QWEN21_ACT, mode, explicit) == _plan(
+ gib, QWEN21_GGUF, None, mode, explicit
+ )
+
+
+def test_unified_memory_keeps_the_flat_plan():
+ for gib in (8, 16, 32):
+ assert _plan(gib, QWEN21_GGUF, QWEN21_ACT, kind = "unified_memory") == _plan(
+ gib, QWEN21_GGUF, None, kind = "unified_memory"
+ )
+
+
+def test_an_unknown_split_keeps_the_flat_plan():
+ sizes = dict(QWEN21_GGUF, companion_dense_mib = None, text_encoder_dense_mib = None)
+ for gib in (8, 16, 24):
+ assert _plan(gib, sizes, QWEN21_ACT) == _plan(gib, sizes, None)
+
+
+def test_only_measured_families_are_calibrated():
+ assert calibrated_image_activation(None) is None
+ assert calibrated_image_activation("hidream-i1") is None
+ assert calibrated_image_activation("qwen-image-edit") is None
+ assert calibrated_image_activation("qwen-image") is None
+ assert calibrated_image_activation("sdxl") is None
+ for family, tiers in dm._MEASURED_IMAGE_ACTIVATION_MIB.items():
+ for max_speed, raw in zip((False, True), tiers):
+ act = calibrated_image_activation(family, max_speed = max_speed)
+ assert act.tiled_decode_mib <= act.decode_mib
+ assert act.headroom(False) >= max(raw[:4]) and act.max_canvas_mib >= raw[4]
+ assert all(m >= d for m, d in zip(tiers[1], tiers[0]))
+ assert calibrated_image_activation("qwen-image-2.1") == calibrated_image_activation(
+ "qwen-image-2.1", max_speed = True
+ )
+
+
+def test_a_text_encoder_that_cannot_run_whole_keeps_streaming():
+ act = calibrated_image_activation("qwen-image-2.1", max_speed = False)
+ assert _plan(15, LARGE_TE, act) == _plan(15, LARGE_TE, None)
+
+
+def test_16gb_qwen_image_21_at_the_max_speed_tier_keeps_streaming_the_transformer():
+ act = calibrated_image_activation("qwen-image-2.1", max_speed = True)
+ assert _plan(16, QWEN21_GGUF, act) == _plan(16, QWEN21_GGUF, None)
+ plan = _plan(22, QWEN21_GGUF, act)
+ assert plan.offload_policy == OFFLOAD_MODEL and plan.vae_tiling is False
+
+
+def test_the_shipped_qwen_image_21_figures_never_stream_the_transformer_on_16gb():
+ act = calibrated_image_activation("qwen-image-2.1", max_speed = False)
+ plan = _plan(16, QWEN21_GGUF, act)
+ assert plan.offload_policy == OFFLOAD_MODEL and plan.vae_tiling is False
+ card = DeviceMemory("cuda", "cuda", "discrete_vram", 16 * GIB - 512, 16 * GIB)
+ plan = plan_diffusion_memory(
+ target = _target(),
+ device_memory = card,
+ runtime_headroom_mib = 8192,
+ calibrated_activation = act,
+ **QWEN21_GGUF,
+ )
+ assert plan.offload_policy == OFFLOAD_GROUP and plan.stream_transformer is False
+ assert plan.vae_tiling is True
+ for gib in (18, 20):
+ plan = _plan(gib, QWEN21_GGUF, act)
+ assert plan.offload_policy == OFFLOAD_GROUP and plan.stream_transformer is False
+
+
+def test_the_requested_speed_tier_picks_the_figures(monkeypatch):
+ import inspect
+
+ import core.inference.diffusion as d
+
+ monkeypatch.setattr(d, "sdpa_subquadratic_confirmed", lambda target: True)
+ fam = types.SimpleNamespace(name = "qwen-image-2.1")
+ nvidia = types.SimpleNamespace(backend = "cuda", vendor = "nvidia")
+ default = calibrated_image_activation("qwen-image-2.1", max_speed = False)
+ maxed = calibrated_image_activation("qwen-image-2.1", max_speed = True)
+ assert default != maxed
+ assert d._calibrated_activation(fam, nvidia) == maxed
+ seen = []
+
+ @d._plans_at_requested_speed
+ def load(**kwargs):
+ seen.append(d._calibrated_activation(fam, nvidia))
+
+ cases = [(None, default), ("off", default), ("eager", default), ("default", default)]
+ cases += [("max", maxed), (" MAX ", maxed), ("bogus", maxed)]
+ for mode, want in cases:
+ load(speed_mode = mode)
+ assert seen.pop() == want, mode
+ load()
+ assert seen.pop() == default
+ assert d._calibrated_activation(fam, nvidia) == maxed
+ for fn in (
+ d.DiffusionBackend.load_pipeline,
+ d.DiffusionBackend._pipeline_planned_denoiser_scheme,
+ ):
+ assert "speed_mode" in inspect.signature(fn).parameters
+ assert fn.__wrapped__ is not None
+
+
+def test_only_nvidia_with_a_confirmed_subquadratic_kernel_is_calibrated(monkeypatch):
+ import core.inference.diffusion as d
+
+ fam = types.SimpleNamespace(name = "qwen-image-2.1")
+ monkeypatch.setattr(d, "sdpa_subquadratic_confirmed", lambda target: True)
+ for backend, vendor in (
+ ("cuda", "amd"),
+ ("cuda", None),
+ ("xpu", "intel"),
+ ("mps", "apple"),
+ ("cpu", None),
+ ):
+ assert (
+ d._calibrated_activation(fam, types.SimpleNamespace(backend = backend, vendor = vendor))
+ is None
+ )
+ nvidia = types.SimpleNamespace(backend = "cuda", vendor = "nvidia")
+ assert d._calibrated_activation(types.SimpleNamespace(name = "hidream-i1"), nvidia) is None
+ monkeypatch.setattr(d, "sdpa_subquadratic_confirmed", lambda target: False)
+ assert d._calibrated_activation(fam, nvidia) is None
+
+ def boom(target):
+ raise RuntimeError("probe failed")
+
+ monkeypatch.setattr(d, "sdpa_subquadratic_confirmed", boom)
+ assert d._calibrated_activation(fam, nvidia) is None
+
+
+def test_an_fp32_promoted_family_keeps_the_flat_plan(monkeypatch):
+ import torch
+
+ import core.inference.diffusion as d
+ from core.inference.diffusion_families import detect_family
+
+ monkeypatch.setattr(d, "sdpa_subquadratic_confirmed", lambda target: True)
+ zimage = detect_family("unsloth/Z-Image-Turbo-GGUF")
+ assert zimage.name == "z-image" and zimage.fp16_incompatible
+ flux = types.SimpleNamespace(name = "flux.1")
+
+ def on(dtype):
+ return types.SimpleNamespace(backend = "cuda", vendor = "nvidia", dtype = dtype)
+
+ assert d._calibrated_activation(zimage, on(torch.float16)) is None
+ assert d._calibrated_activation(zimage, on(torch.float32)) is None
+ assert d._calibrated_activation(zimage, on(torch.bfloat16)) is not None
+ assert d._calibrated_activation(flux, on(torch.float16)) is not None
+
+
+def test_a_reference_family_the_guard_cannot_size_keeps_the_flat_plan(monkeypatch):
+ # Klein's references are unsized by the guard (no reference_resolutions); Qwen-Image-2.1 declares them.
+ import core.inference.diffusion as d
+ from core.inference.diffusion_families import detect_family
+
+ monkeypatch.setattr(d, "sdpa_subquadratic_confirmed", lambda target: True)
+ nvidia = types.SimpleNamespace(backend = "cuda", vendor = "nvidia")
+ klein = detect_family("black-forest-labs/FLUX.2-klein-4B")
+ assert klein.name == "flux.2-klein" and klein.reference and not klein.reference_resolutions
+ assert d._calibrated_activation(klein, nvidia) is None
+ qwen = detect_family("Qwen/Qwen-Image-2.1")
+ assert qwen.name == "qwen-image-2.1" and qwen.reference_resolutions
+ assert d._calibrated_activation(qwen, nvidia) is not None
+
+
+def test_an_explicit_auto_mode_ignores_the_legacy_offload_flag():
+ for gib in (12, 16, 20):
+ assert _plan(gib, QWEN21_GGUF, QWEN21_ACT, "auto", True) == _plan(
+ gib, QWEN21_GGUF, QWEN21_ACT, "auto"
+ )
+ assert _plan(16, QWEN21_GGUF, QWEN21_ACT, "auto", True) != _plan(
+ 16, QWEN21_GGUF, None, "auto", True
+ )
+
+
+def _resident_after_placement(plan, sizes):
+ if plan.offload_policy == OFFLOAD_NONE:
+ return sizes["model_dense_mib"]
+ if plan.offload_policy == OFFLOAD_GROUP and not plan.stream_transformer:
+ return sizes["model_dense_mib"] - sizes["text_encoder_dense_mib"]
+ return 0
+
+
[email protected]("max_speed", [False, True])
[email protected]("tile_side", [256, dm.DEFAULT_VAE_TILE_SIDE])
[email protected]("sizes", [QWEN21_GGUF, QWEN21_GGUF_BF16_TE])
+def test_generation_guard_never_refuses_the_calibrated_2048_canvas_on_a_promoted_tier(
+ max_speed, tile_side, sizes
+):
+ # Resident transformer lowers the free VRAM the guard reads; the 2048 canvas must still run tiled, not 400.
+ act = calibrated_image_activation("qwen-image-2.1", max_speed = max_speed)
+ promoted = 0
+ for step in range(10 * 4, 48 * 4 + 1):
+ gib = step / 4
+ plan = _plan(gib, sizes, act)
+ if "calibrated_headroom_mib" not in plan.estimates:
+ continue
+ promoted += 1
+ total = int(gib * GIB)
+ free = max(0, total - 1_229 - _resident_after_placement(plan, sizes))
+ verdict = dm.raise_on_image_activation_shortfall(
+ device_memory = DeviceMemory("cuda", "cuda", "discrete_vram", free, total),
+ width = 2048,
+ height = 2048,
+ family = "qwen-image-2.1",
+ vae_tile_side = tile_side,
+ vae_sliced = True,
+ )
+ assert verdict.action in (dm.ACTIVATION_RUN, dm.ACTIVATION_TILE), (gib, plan.reasons)
+ assert promoted > 0
+
+
+def _guard(
+ free,
+ total,
+ *,
+ calibrated,
+ tile_side = 256,
+ **kw,
+):
+ return dm.image_activation_verdict(
+ device_memory = DeviceMemory("cuda", "cuda", "discrete_vram", free, total),
+ family = kw.pop("family", "qwen-image-2.1"),
+ vae_tile_side = tile_side,
+ vae_sliced = True,
+ calibrated_placement = calibrated,
+ **kw,
+ )
+
+
+def _fits(verdict):
+ overhead = dm.DEFAULT_BASE_OVERHEAD_MIB
+ if verdict.needed_mib + overhead <= verdict.budget_mib:
+ return True
+ return verdict.tiled_needed_mib is not None and (
+ verdict.tiled_needed_mib + overhead <= verdict.budget_mib
+ )
+
+
+# Six 512px references at the Qwen-Image-2.1 condition weight: ~5980 MiB untiled, under the flat 8192 MiB plan.
+SIX_REFS = dict(width = 512, height = 512, condition_pixels = int(6 * 512 * 512 * 0.32))
+
+
+def test_references_on_a_calibrated_tier_are_checked_against_the_free_budget():
+ total = 16 * GIB
+ free = 4_266 + 1_229
+ flat = _guard(free, total, calibrated = False, **SIX_REFS)
+ assert flat.action != dm.ACTIVATION_REFUSE # the flat plan budgeted 8192 MiB for it
+ verdict = _guard(free, total, calibrated = True, **SIX_REFS)
+ assert verdict.action == dm.ACTIVATION_REFUSE
+ assert "balanced memory mode" in verdict.message
+ assert "fewer input images" in verdict.message
+
+
+def test_references_on_a_calibrated_tier_run_when_they_fit():
+ verdict = _guard(20 * GIB, 24 * GIB, calibrated = True, **SIX_REFS)
+ assert verdict.action == dm.ACTIVATION_RUN
+
+
[email protected]("sizes", [QWEN21_GGUF, QWEN21_GGUF_BF16_TE])
+def test_conditioned_requests_on_every_promoted_tier_never_skip_the_budget(sizes):
+ act = calibrated_image_activation("qwen-image-2.1", max_speed = True)
+ for step in range(10 * 4, 48 * 4 + 1):
+ gib = step / 4
+ plan = _plan(gib, sizes, act)
+ if "calibrated_headroom_mib" not in plan.estimates:
+ continue
+ total = int(gib * GIB)
+ free = max(0, total - 1_229 - _resident_after_placement(plan, sizes))
+ for kw in (SIX_REFS, dict(width = 1024, height = 1024, controlnet = True)):
+ verdict = _guard(free, total, calibrated = True, **kw)
+ assert verdict.action == dm.ACTIVATION_REFUSE or _fits(verdict), (gib, kw)
+
+
[email protected]("family", ["flux.1", "qwen-image-2.1"])
+def test_controlnet_on_a_calibrated_tier_budgets_its_forward_and_residuals(family):
+ total = 24 * GIB
+ free = 6 * GIB
+ kw = dict(width = 1024, height = 1024, family = family)
+ plain = _guard(free, total, calibrated = True, **kw)
+ assert plain.action != dm.ACTIVATION_REFUSE
+ verdict = _guard(free, total, calibrated = True, controlnet = True, **kw)
+ assert verdict.action == dm.ACTIVATION_REFUSE
+ assert verdict.needed_mib > plain.needed_mib
+ assert "with ControlNet" in verdict.message
+ assert "without ControlNet" in verdict.message
+ assert "balanced memory mode" in verdict.message
+ assert "fewer input images" not in verdict.message
+ roomy = _guard(40 * GIB, 48 * GIB, calibrated = True, controlnet = True, **kw)
+ assert roomy.action == dm.ACTIVATION_RUN
+
+
[email protected]("free", [1_500, 3_000, 5_000, 8_000, 12_000, 30_000])
[email protected]("tile_side", [None, 256, dm.DEFAULT_VAE_TILE_SIDE])
+ "kw",
+ [
+ dict(width = 512, height = 512),
+ dict(width = 1024, height = 1024),
+ dict(width = 2048, height = 2048),
+ dict(width = 1024, height = 1024, batch_size = 2),
+ dict(width = 1344, height = 768, family = "flux.1"),
+ ],
+)
+def test_unconditioned_requests_on_a_calibrated_tier_are_unchanged(free, tile_side, kw):
+ flat = _guard(free, 16 * GIB, calibrated = False, tile_side = tile_side, **dict(kw))
+ cal = _guard(free, 16 * GIB, calibrated = True, tile_side = tile_side, **dict(kw))
+ assert cal == flat
+
+
[email protected]("free", [1_500, 3_000, 5_000, 8_000, 12_000, 30_000])
+ "kw",
+ [
+ SIX_REFS,
+ dict(width = 1024, height = 1024, condition_pixels = 1024 * 1024),
+ dict(width = 1024, height = 1024),
+ ],
+)
+def test_flat_tiers_ignore_the_controlnet_flag(free, kw):
+ # Flat tiers keep today's verdict: the flat plan already budgets conditioned work.
+ base = _guard(free, 16 * GIB, calibrated = False, **dict(kw))
+ with_cn = _guard(free, 16 * GIB, calibrated = False, controlnet = True, **dict(kw))
+ assert with_cn.action == base.action
+ assert (with_cn.needed_mib, with_cn.tiled_needed_mib) == (
+ base.needed_mib,
+ base.tiled_needed_mib,
+ )
+
+
+def test_generate_passes_the_calibrated_placement_and_controlnet_to_the_guard():
+ import inspect
+
+ import core.inference.diffusion as d
+
+ src = inspect.getsource(d)
+ assert 'calibrated_placement = bool(getattr(state, "calibrated_placement", False)),' in src
+ assert 'controlnet = workflow == "controlnet" and control_pil is not None,' in src
diff --git a/studio/backend/tests/test_diffusion_controlnet.py b/studio/backend/tests/test_diffusion_controlnet.py
index 663315b648e..67c8381562b 100644
--- a/studio/backend/tests/test_diffusion_controlnet.py
+++ b/studio/backend/tests/test_diffusion_controlnet.py
@@ -405,3 +405,57 @@ def test_controlnet_pipe_not_cached_after_unload_race(monkeypatch):
with pytest.raises(RuntimeError, match = "cancelled"):
b._controlnet_pipe(st, resolved, threading.Event())
assert b._cn_pipes == {}
+
+
+ "policy, calibrated, streamed",
+ [("none", False, False), ("none", True, True), ("group", False, True)],
+)
+def test_controlnet_streams_beside_a_calibrated_resident_tier(
+ monkeypatch, policy, calibrated, streamed
+):
+ # Calibrated tiers stream the ControlNet; flat resident tiers keep it resident.
+ import threading
+
+ from core.inference import diffusion as d
+
+ monkeypatch.setitem(sys.modules, "diffusers", _fake_diffusers())
+ _allow_cn_security(monkeypatch)
+ calls = []
+ monkeypatch.setattr(
+ d, "_offload_controlnet_module", lambda m, device, logger: calls.append(m) or True
+ )
+ b = d.DiffusionBackend()
+ st = _state()
+ st.offload_policy = policy
+ st.calibrated_placement = calibrated
+ b._state = st
+ p = b._controlnet_pipe(
+ st, dc.ResolvedControlNet("flux-union-pro", "repo/id", is_local = False), threading.Event()
+ )
+ assert bool(calls) is streamed
+ assert hasattr(p.controlnet, "device") is not streamed
+
+
+def test_a_calibrated_tier_refuses_a_controlnet_it_cannot_stream(monkeypatch):
+ # The resident fallback is only safe on tiers that budgeted flat headroom; a calibrated tier refuses instead.
+ import threading
+
+ from core.inference import diffusion as d
+
+ monkeypatch.setitem(sys.modules, "diffusers", _fake_diffusers())
+ _allow_cn_security(monkeypatch)
+ monkeypatch.setattr(d, "_offload_controlnet_module", lambda m, device, logger: False)
+ b = d.DiffusionBackend()
+ st = _state()
+ st.offload_policy = "none"
+ st.calibrated_placement = True
+ b._state = st
+ resolved = dc.ResolvedControlNet("flux-union-pro", "repo/id", is_local = False)
+ with pytest.raises(ValueError, match = "balanced memory mode"):
+ b._controlnet_pipe(st, resolved, threading.Event())
+ assert b._cn_models == {} and b._cn_pipes == {}
+ st.calibrated_placement = False
+ st.offload_policy = "group"
+ p = b._controlnet_pipe(st, resolved, threading.Event())
+ assert hasattr(p.controlnet, "device")
diff --git a/studio/backend/tests/test_diffusion_offload_keep_cpu.py b/studio/backend/tests/test_diffusion_offload_keep_cpu.py
index 7a71b410572..5573708eefe 100644
--- a/studio/backend/tests/test_diffusion_offload_keep_cpu.py
+++ b/studio/backend/tests/test_diffusion_offload_keep_cpu.py
@@ -260,6 +260,53 @@ def test_a_non_contiguous_weight_keeps_its_layout(monkeypatch):
assert lin.weight.stride() == (1, 8)
+@cuda
+ "conv, fmt, shape",
+ [
+ (torch.nn.Conv2d, torch.channels_last, (1, 4, 6, 6)),
+ (torch.nn.Conv3d, torch.channels_last_3d, (1, 4, 3, 6, 6)),
+ ],
+)
+def test_a_channels_last_conv_weight_is_pinned_in_its_layout(monkeypatch, conv, fmt, shape):
+ monkeypatch.setenv(dm.OFFLOAD_PIN_ENV, "1")
+ x = torch.randn(*shape)
+ seen = []
+
+ def build():
+ torch.manual_seed(0)
+ module = conv(4, 4, 3, padding = 1).to(memory_format = fmt)
+ module.register_forward_pre_hook(
+ lambda mod, args: seen.append(mod.weight.is_contiguous(memory_format = fmt))
+ )
+ pipe = types.SimpleNamespace(components = {"vae": module}, vae = module)
+
+ def enable_model_cpu_offload(device = "cuda"):
+ hooks.remove_hook_from_module(module)
+ module.to("cpu")
+ hooks.add_hook_to_module(module, hooks.CpuOffload(execution_device = device))
+
+ pipe.enable_model_cpu_offload = enable_model_cpu_offload
+ pipe.enable_model_cpu_offload()
+ return pipe
+
+ def render(pipe):
+ out = pipe.vae(x).detach().cpu()
+ pipe.vae._hf_hook.init_hook(pipe.vae)
+ pipe.enable_model_cpu_offload()
+ return out
+
+ ref = render(build())
+ pipe = build()
+ dm.keep_cpu_weights_on_offload(pipe)
+ for _ in range(2):
+ assert torch.equal(render(pipe), ref)
+ weight = pipe.vae.weight
+ assert weight.device.type == "cpu" and weight.is_pinned()
+ assert weight.is_contiguous(memory_format = fmt)
+ assert all(seen)
+
+
@cuda
def test_a_parameter_replaced_on_the_device_is_copied_back():
pipe = _pipe("cuda", "transformer")