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: size streamed SDXL UNet leaves from the denoise peak and lend them to the VAE decode (#16620)

Daniel Han38a8d1248603
diff --git a/studio/backend/core/inference/diffusion_memory.py b/studio/backend/core/inference/diffusion_memory.py
index e6ca5119f95..bf2ac66e2ec 100644
--- a/studio/backend/core/inference/diffusion_memory.py
+++ b/studio/backend/core/inference/diffusion_memory.py
@@ -6009,6 +6009,28 @@ _MEASURED_UNET_STREAMED_PEAK_MIB = 2435
# force_upcast fp16 VAE (T4) decodes in fp32.
_MEASURED_UNET_STREAMED_FP32_DECODE_PEAK_MIB = 3228
_UNET_STREAM_SLACK_MIB = 512
+# Streamed denoise: 333 MiB above the weights at 1024^2 (L4 bf16, CFG pair, incl. the ~168 MiB prefetch window), the
+# activations scaled linearly to 2048^2 so a larger canvas still fits beside the resident leaves: 168 + 4 x 165.
+_MEASURED_UNET_STREAMED_DENOISE_MIB = 828
+# =0: size the resident leaves from the decode peak for the whole render (no lending, the #16295 sizing).
+UNET_STREAM_LEND_ENV = "UNSLOTH_DIFFUSION_UNET_STREAM_LEND"
+
+
+def unet_stream_lends_decode() -> bool:
+ """Resident UNet leaves are sized from the denoise peak and lent to the VAE decode (release_for_decode streams the
+ shortfall again before the decode and re-pins it after), as ComfyUI unloads part of the UNet for its decode."""
+ return not _env_off(UNET_STREAM_LEND_ENV)
+
+
+def unet_decode_lend(fp32_decode: bool = False) -> tuple[int, int, int, bool]:
+ """The ``DECODE_LEND_ATTR`` tuple of a streamed UNet: the decode's measured peak above the weights at 1024^2,
+ scaled linearly with the canvas (a tiled decode grows slower: it releases more than it needs, never less)."""
+ peak = (
+ _MEASURED_UNET_STREAMED_FP32_DECODE_PEAK_MIB
+ if fp32_decode
+ else _MEASURED_UNET_STREAMED_PEAK_MIB
+ )
+ return (peak, peak, DEFAULT_IMAGE_WIDTH * DEFAULT_IMAGE_HEIGHT, False)
def _measured_reserve_mib(peak_mib: int) -> int:
@@ -6022,16 +6044,23 @@ def unet_stream_room_mib(
vae_mib: int,
*,
fp32_decode: bool = False,
+ lend: Optional[bool] = None,
) -> Optional[int]:
- """None if whole-module offload fits; else MiB of UNet leaves to keep resident. The decode must fit too: leaf
- groups released by a decode OOM do not survive the round trip."""
+ """None if whole-module offload fits; else MiB of UNet leaves to keep resident. ``lend`` (default: the kill switch
+ ``UNSLOTH_DIFFUSION_UNET_STREAM_LEND``): sized from the denoise peak, the decode borrows the shortfall through
+ release_for_decode; off: sized so the decode fits beside every resident leaf for the whole render."""
if unet_mib + _measured_reserve_mib(_MEASURED_UNET_OFFLOAD_DENOISE_MIB) <= free_mib:
return None
- peak = (
- _MEASURED_UNET_STREAMED_FP32_DECODE_PEAK_MIB
- if fp32_decode
- else _MEASURED_UNET_STREAMED_PEAK_MIB
- )
+ if lend is None:
+ lend = unet_stream_lends_decode()
+ if lend:
+ peak = _MEASURED_UNET_STREAMED_DENOISE_MIB
+ else:
+ peak = (
+ _MEASURED_UNET_STREAMED_FP32_DECODE_PEAK_MIB
+ if fp32_decode
+ else _MEASURED_UNET_STREAMED_PEAK_MIB
+ )
reserve = _measured_reserve_mib(peak) + _UNET_STREAM_SLACK_MIB
return max(0, int(free_mib) - int(vae_mib) - reserve)
@@ -6077,8 +6106,10 @@ def _stream_unet_instead_of_model_offload(
unet_mib = _mib(unet)
vae = getattr(pipe, "vae", None)
+ fp32_decode = vae is not None and _vae_decodes_in_fp32(vae)
+ lend = unet_stream_lends_decode()
room = unet_stream_room_mib(
- free_mib, unet_mib, _mib(vae), fp32_decode = vae is not None and _vae_decodes_in_fp32(vae)
+ free_mib, unet_mib, _mib(vae), fp32_decode = fp32_decode, lend = lend
)
if room is None:
return False
@@ -6099,6 +6130,13 @@ def _stream_unet_instead_of_model_offload(
pipe._unsloth_unet_streamed = True
except Exception: # noqa: BLE001
pass
+ try:
+ # the leaves were sized from the denoise peak: the decode borrows its shortfall (release_for_decode)
+ setattr(
+ pipe, DECODE_LEND_ATTR, unet_decode_lend(fp32_decode) if lend and room else None
+ )
+ except Exception: # noqa: BLE001
+ pass
if logger is not None:
logger.info(
"diffusion.memory: UNet (%d MiB) does not fit %d MiB free for whole-module offload; %s",
diff --git a/studio/backend/tests/test_diffusion_unet_stream.py b/studio/backend/tests/test_diffusion_unet_stream.py
index 28fc870aaf7..70f468b23b0 100644
--- a/studio/backend/tests/test_diffusion_unet_stream.py
+++ b/studio/backend/tests/test_diffusion_unet_stream.py
@@ -65,7 +65,7 @@ def _plan(policy = dm.OFFLOAD_MODEL):
@pytest.mark.parametrize("budget_mib, free_mib", [(4096, 3684), (6144, 5700)])
def test_sdxl_streams_where_whole_module_offload_cannot_fit(budget_mib, free_mib):
- room = dm.unet_stream_room_mib(free_mib, SDXL_UNET_MIB, SDXL_VAE_MIB)
+ room = dm.unet_stream_room_mib(free_mib, SDXL_UNET_MIB, SDXL_VAE_MIB, lend = False)
assert (
room is not None
), f"{budget_mib} MiB budget: whole-module offload of the 4.8 GiB UNet OOMs"
@@ -90,8 +90,8 @@ def test_more_free_vram_keeps_more_leaves_resident():
def test_fp32_decode_of_an_fp16_vae_keeps_fewer_leaves_resident():
for free_mib in (5700, 8000 - 1):
- r16 = dm.unet_stream_room_mib(free_mib, 7000, SDXL_VAE_MIB)
- r32 = dm.unet_stream_room_mib(free_mib, 7000, SDXL_VAE_MIB, fp32_decode = True)
+ r16 = dm.unet_stream_room_mib(free_mib, 7000, SDXL_VAE_MIB, lend = False)
+ r32 = dm.unet_stream_room_mib(free_mib, 7000, SDXL_VAE_MIB, fp32_decode = True, lend = False)
assert r16 is not None and r32 is not None and r32 < r16
assert dm._MEASURED_UNET_STREAMED_FP32_DECODE_PEAK_MIB > dm._MEASURED_UNET_STREAMED_PEAK_MIB
@@ -215,3 +215,78 @@ def test_deferred_speed_profile_skipped_only_for_a_streamed_unet(monkeypatch):
dmod.DiffusionBackend._engage_deferred_speed(backend, states[streamed])
assert states[streamed].speed_deferred is False
assert ran == [states[False]]
+
+
+# ---- the decode borrows the resident leaves (UNSLOTH_DIFFUSION_UNET_STREAM_LEND)
+
+
[email protected]("free_mib", [3684, 5732])
+def test_lending_sizes_the_leaves_from_the_denoise_peak(free_mib, monkeypatch):
+ monkeypatch.delenv(dm.UNET_STREAM_LEND_ENV, raising = False)
+ lent = dm.unet_stream_room_mib(free_mib, SDXL_UNET_MIB, SDXL_VAE_MIB)
+ kept = dm.unet_stream_room_mib(free_mib, SDXL_UNET_MIB, SDXL_VAE_MIB, lend = False)
+ reserve = (
+ dm._measured_reserve_mib(dm._MEASURED_UNET_STREAMED_DENOISE_MIB) + dm._UNET_STREAM_SLACK_MIB
+ )
+ assert lent == free_mib - SDXL_VAE_MIB - reserve
+ assert lent > kept
+ # the decode's own peak no longer has to fit beside every leaf; the 2048^2 denoise still does
+ assert dm._MEASURED_UNET_STREAMED_DENOISE_MIB < dm._MEASURED_UNET_STREAMED_PEAK_MIB
+
+
+def test_lend_kill_switch_restores_the_decode_sized_reserve(monkeypatch):
+ monkeypatch.setenv(dm.UNET_STREAM_LEND_ENV, "0")
+ assert dm.unet_stream_room_mib(3684, SDXL_UNET_MIB, SDXL_VAE_MIB) == dm.unet_stream_room_mib(
+ 3684, SDXL_UNET_MIB, SDXL_VAE_MIB, lend = False
+ )
+
+
[email protected]("env, lent", [(None, True), ("0", False)])
+def test_streamed_unet_lends_its_leaves_to_the_decode(cuda_free, monkeypatch, env, lent):
+ if env is None:
+ monkeypatch.delenv(dm.UNET_STREAM_LEND_ENV, raising = False)
+ else:
+ monkeypatch.setenv(dm.UNET_STREAM_LEND_ENV, env)
+ pipe = _pipe(unet_mib = 4)
+ pipe.unet = pipe.components["unet"] = torch.nn.Linear(
+ 512, 512 * 8000, bias = False, device = "meta"
+ )
+ cuda_free["free"] = 8000
+ policy, _ = dm.apply_memory_plan(pipe, _plan(), device = "cuda")
+ assert policy == dm.OFFLOAD_GROUP
+ lend = getattr(pipe, dm.DECODE_LEND_ATTR, None)
+ if not lent:
+ assert lend is None
+ return
+ assert lend == dm.unet_decode_lend(False)
+ # a 1024^2 decode needs the measured decode peak x margin; 4x the pixels needs 4x (tiled: an over-release)
+ need = dm.decode_need_mib(lend, width = 1024, height = 1024)
+ assert need >= dm._MEASURED_UNET_STREAMED_PEAK_MIB * dm._MEASURED_PEAK_MARGIN
+ assert dm.decode_need_mib(lend, width = 2048, height = 2048) >= 4 * need - 4
+
+
+def test_fp32_decode_lends_the_fp32_peak():
+ assert dm.unet_decode_lend(True)[1] == dm._MEASURED_UNET_STREAMED_FP32_DECODE_PEAK_MIB
+ assert dm.unet_decode_lend(False)[1] == dm._MEASURED_UNET_STREAMED_PEAK_MIB
+
+
+def test_release_for_decode_streams_the_unet_shortfall(monkeypatch):
+ """At decode start with 1500 MiB free, the 1024^2 decode (2435 x 1.15 + slack) borrows the shortfall."""
+ pipe = types.SimpleNamespace(components = {})
+ setattr(pipe, dm.DECODE_LEND_ATTR, dm.unet_decode_lend(False))
+ monkeypatch.setattr(torch.cuda, "mem_get_info", lambda device = None: (1500 << 20, 24 << 30))
+ monkeypatch.setattr(torch.cuda, "memory_reserved", lambda device = None: 0)
+ monkeypatch.setattr(torch.cuda, "memory_allocated", lambda device = None: 0)
+ monkeypatch.setattr(torch.cuda, "current_device", lambda: 0)
+ monkeypatch.setattr(dm, "_graph_held_cache_bytes", lambda index: 0)
+ monkeypatch.setattr(dm, "user_budget_reserve_bytes", lambda dev, total: 0)
+ asked = []
+ monkeypatch.setattr(
+ dm,
+ "release_resident_groups",
+ lambda p, need, logger = None, **kw: asked.append(need) or (lambda: None),
+ )
+ restore = dm.release_for_decode(pipe, width = 1024, height = 1024, device = "cuda")
+ assert callable(restore)
+ need = dm.decode_need_mib(dm.unet_decode_lend(False), width = 1024, height = 1024)
+ assert asked == [need + dm._DECODE_SLACK_MIB - 1500]