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 video memory plan: count the forward's headroom before keeping whole-module offload (#16805)
Daniel Han44d366415080
diff --git a/studio/backend/core/inference/diffusion_memory.py b/studio/backend/core/inference/diffusion_memory.pyindex bf2ac66e2ec..96d5bdeffbf 100644--- a/studio/backend/core/inference/diffusion_memory.py+++ b/studio/backend/core/inference/diffusion_memory.py@@ -3281,8 +3281,16 @@ def refine_balanced_plan_for_components(pipe: Any, plan: MemoryPlan) -> MemoryPl)-def refine_memory_plan_for_components(pipe: Any, plan: MemoryPlan) -> MemoryPlan:- """Switches to granular streaming only when a loaded component cannot fit; keeps whole-module offload if all fit, and checks streamed parts fit together."""+def refine_memory_plan_for_components(+ pipe: Any,+ plan: MemoryPlan,+ *,+ headroom_mib: int = 0,+) -> MemoryPlan:+ """Switches to granular streaming only when a loaded component cannot fit; keeps whole-module offload if all fit, and checks streamed parts fit together.++ ``headroom_mib``: what the component's own phase holds beside it (a whole-module onload holds the component AND+ that phase's activations at once); the caller prices it per phase. 0 (the image path) is the bare size check."""if plan.offload_policy != OFFLOAD_MODEL:return planbudget = plan.estimates.get("safe_device_budget_mib")@@ -3313,9 +3321,18 @@ def refine_memory_plan_for_components(pipe: Any, plan: MemoryPlan) -> MemoryPlanstreamed_sizes = {n: m for n, m in sizes.items() if n in streamable}if not streamed_sizes:return plan- largest_name, largest_mib = max(streamed_sizes.items(), key = lambda item: item[1])- if largest_mib <= int(budget):+ beside = max(0, int(headroom_mib or 0))++ def need(name: str) -> int:+ # the headroom is the denoise phase's: a text encoder runs in its own phase and keeps the bare check+ return streamed_sizes[name] + (beside if streamable[name][1] == "block_level" else 0)++ largest_name = max(streamed_sizes, key = need)+ largest_mib = streamed_sizes[largest_name]+ if need(largest_name) <= int(budget):return plan+ if streamable[largest_name][1] != "block_level":+ beside = 0# what streaming leaves resident, all at once: over budget here means streaming OOMs tooresident_mib = sum(m for n, m in sizes.items() if n not in streamable)if resident_mib > int(budget):@@ -3330,8 +3347,9 @@ def refine_memory_plan_for_components(pipe: Any, plan: MemoryPlan) -> MemoryPlanestimates = estimates,reasons = plan.reasons+ (- f"loaded {largest_name} is {largest_mib} MiB, above the {int(budget)} MiB "- "device budget; streaming transformer blocks and text-encoder layers",+ f"loaded {largest_name} is {largest_mib} MiB"+ + (f" (+{beside} MiB runtime headroom)" if beside else "")+ + f", above the {int(budget)} MiB device budget; streaming transformer blocks and text-encoder layers",),)diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.pyindex 711aaa923b7..76adffd1244 100644--- a/studio/backend/core/inference/video.py+++ b/studio/backend/core/inference/video.py@@ -4161,6 +4161,15 @@ def _auto_offload_scheme(requested: Optional[str]) -> Optional[str]:_VIDEO_DENOISE_ACTIVATION_MIB = 4096+def _video_denoise_phase_headroom_mib(plan: Any) -> int:+ """What the denoise phase holds beside the DiT under whole-module offload (the same pricing as below)."""+ try:+ runtime = int(((getattr(plan, "estimates", None) or {}).get("runtime_headroom_mib")) or 0)+ except (TypeError, ValueError):+ runtime = 0+ return min(runtime, _VIDEO_DENOISE_ACTIVATION_MIB) + DEFAULT_BASE_OVERHEAD_MIB++def _video_prefer_whole_module(plan: Any,*,@@ -10370,7 +10379,10 @@ class VideoBackend:clear_gpu_cache()raise RuntimeError("Video load was cancelled or superseded.")# A component larger than the card OOMs at its first whole-module onload; fall back to leaf streaming.- refined = refine_memory_plan_for_components(pipe, plan)+ # priced as the denoise phase (_video_prefer_whole_module): the decoded-clip share is the VAE phase's+ refined = refine_memory_plan_for_components(+ pipe, plan, headroom_mib = _video_denoise_phase_headroom_mib(plan)+ )if refined is not plan:logger.info("video.memory: %s", refined.reasons[-1])plan = refineddiff --git a/studio/backend/tests/test_diffusion_memory.py b/studio/backend/tests/test_diffusion_memory.pyindex ff8e8ae8806..89bbef4d71b 100644--- a/studio/backend/tests/test_diffusion_memory.py+++ b/studio/backend/tests/test_diffusion_memory.py@@ -759,6 +759,35 @@ def test_refine_model_offload_streams_only_when_a_component_exceeds_budget(monkeassert any("text_encoder" in reason for reason in refined.reasons)+def test_refine_with_headroom_streams_a_component_that_fits_only_without_activations(monkeypatch):+ """Video: a GGUF DiT under the budget by itself but not with the forward's headroom beside it (LTX-2.5 Q4_K_M at a+ 16 GiB budget OOMed in its first forward under whole-module offload) streams; the bare check keeps the plan."""+ Module = _install_sized_torch(monkeypatch)+ plan = MemoryPlan(+ requested_mode = "auto",+ offload_policy = OFFLOAD_MODEL,+ vae_tiling = True,+ vae_slicing = True,+ device_memory = _discrete(16384),+ estimates = {+ "safe_device_budget_mib": 15000,+ "runtime_headroom_mib": 3000,+ "base_overhead_mib": 500,+ },+ )+ transformer = Module(13300)+ pipe = types.SimpleNamespace(+ transformer = transformer, components = {"transformer": transformer, "connectors": Module(6000)}+ )+ assert refine_memory_plan_for_components(pipe, plan) is plan+ refined = refine_memory_plan_for_components(pipe, plan, headroom_mib = 3500)+ assert refined.offload_policy == OFFLOAD_STREAMING+ assert any("runtime headroom" in reason for reason in refined.reasons)+ small = Module(9000)+ roomy = types.SimpleNamespace(transformer = small, components = {"transformer": small})+ assert refine_memory_plan_for_components(roomy, plan, headroom_mib = 3500) is plan++def test_largest_streamable_companion_mib_measures_only_the_text_encoders(monkeypatch):from core.inference.diffusion_memory import largest_streamable_companion_mib@@ -3086,3 +3115,30 @@ def test_both_offload_tiers_fall_back_to_the_no_copy_back_top_group():assert ("not _pin_top_level_group(module, logger, pinned_mib, device=onload)" in src), fn.__name__+++def test_refine_headroom_applies_to_the_denoiser_not_a_larger_text_encoder(monkeypatch):+ """The denoise headroom prices only denoisers: a text encoder larger than the DiT runs in its own phase, so a+ whole-module plan where each fits its phase stays whole-module."""+ Module = _install_sized_torch(monkeypatch)+ plan = MemoryPlan(+ requested_mode = "auto",+ offload_policy = OFFLOAD_MODEL,+ vae_tiling = True,+ vae_slicing = True,+ device_memory = _discrete(16384),+ estimates = {"safe_device_budget_mib": 14000},+ )+ transformer = Module(6000)+ pipe = types.SimpleNamespace(+ transformer = transformer,+ components = {"transformer": transformer, "text_encoder": Module(10000), "vae": Module(1000)},+ )+ assert refine_memory_plan_for_components(pipe, plan, headroom_mib = 6144) is plan+ big = Module(9000)+ tight = types.SimpleNamespace(+ transformer = big, components = {"transformer": big, "text_encoder": Module(10000)}+ )+ refined = refine_memory_plan_for_components(tight, plan, headroom_mib = 6144)+ assert refined.offload_policy == OFFLOAD_STREAMING+ assert "loaded transformer is 9000 MiB (+6144 MiB runtime headroom)" in refined.reasons[-1]diff --git a/studio/backend/tests/test_video_quantised_offload.py b/studio/backend/tests/test_video_quantised_offload.pyindex 640556cce04..959f97a7d2f 100644--- a/studio/backend/tests/test_video_quantised_offload.py+++ b/studio/backend/tests/test_video_quantised_offload.py@@ -979,3 +979,19 @@ def test_a_cancel_during_the_background_pin_wait_ends_the_render_promptly()assert time.perf_counter() - began < 10assert not rendered+++def test_refine_prices_the_denoise_phase_not_the_decoded_clip():+ """The whole-module refine charges the DiT the denoise share only: a plan _video_prefer_whole_module kept (10000 MiB+ DiT at 17000 MiB, 1280x704x121) stays whole-module; the LTX-2.5 Q4 DiT at a 16 GiB budget (OOM on main) streams."""+ import types++ import core.inference.video as V++ runtime = V.estimate_video_runtime_mib(width = 1280, height = 704, num_frames = 121)+ plan = types.SimpleNamespace(estimates = {"runtime_headroom_mib": runtime})+ headroom = V._video_denoise_phase_headroom_mib(plan)+ assert headroom == V._VIDEO_DENOISE_ACTIVATION_MIB + 2048 < runtime + 2048+ assert 10000 + headroom <= 17000+ assert 11642 + headroom > 13396+ assert V._video_denoise_phase_headroom_mib(types.SimpleNamespace(estimates = {})) == 2048