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 video: a stored peak no longer widens a new process's first render; an out-of-memory render retries streamed (LTX-2.5 16 GiB returning home) (#17373)

Daniel Hane73c74b528e4
diff --git a/studio/backend/core/inference/diffusion_nvfp4_protect.py b/studio/backend/core/inference/diffusion_nvfp4_protect.py
index ba0bf8f977e..f4e314a91d8 100644
--- a/studio/backend/core/inference/diffusion_nvfp4_protect.py
+++ b/studio/backend/core/inference/diffusion_nvfp4_protect.py
@@ -184,6 +184,14 @@ class NVFP4StepController:
self.protected_steps_seen += 1
return self.index
+ def restart(self) -> None:
+ """Back to step 0 of the current generation (a retried render denoises from the start)."""
+ if not self.total:
+ return
+ self.index = 0
+ self.protected = 0 in self.steps
+ self.protected_steps_seen = 1 if self.protected else 0
+
def reset(self) -> "NVFP4StepController":
self.total = 0
self.steps = ()
@@ -339,6 +347,11 @@ def module_controller(module: Any) -> NVFP4StepController:
_DENOISER_ATTRS = ("transformer", "transformer_2", "unet")
+def restart_protect_generation(pipe: Any) -> None:
+ for c in pipeline_controllers(pipe):
+ c.restart()
+
+
def pipeline_controllers(pipe: Any) -> list:
found: list = []
for attr in _DENOISER_ATTRS:
diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.py
index 89a98170421..44fbd5786c8 100644
--- a/studio/backend/core/inference/video.py
+++ b/studio/backend/core/inference/video.py
@@ -14394,18 +14394,43 @@ class VideoBackend:
publish = _publish_preview,
total_steps = steps,
)
+ render_call = (
+ ltx25_render_call
+ if ltx25_render_call is not None
+ else (
+ lambda: _carried_call(pipe, kwargs, has_step_callback or carry_by_scheduler)
+ )
+ )
+
+ def _render_streamed_after_oom() -> Any:
+ try:
+ return render_call()
+ except Exception as exc: # noqa: BLE001
+ if static_skip or cancel.is_set() or not is_oom_error(exc):
+ raise
+ from . import video_stream_residency
+ if not video_stream_residency.may_stream_after_oom(state.pipe):
+ raise
+ from . import diffusion_cuda_graph, video_stream_residency
+
+ # outside the handler so the failed attempt's tensors are freed; graph pools escape empty_cache()
+ diffusion_cuda_graph.reset_all(
+ getattr(state.pipe, "_unsloth_cuda_graphs", ()) or ()
+ )
+ video_stream_residency.stream_after_oom(state.pipe, logger = logger)
+ from .diffusion_nvfp4_protect import restart_protect_generation
+
+ restart_protect_generation(pipe)
+ if state.transformer_cache:
+ self._reset_step_cache(pipe)
+ seeded = kwargs.get("generator")
+ if isinstance(seeded, torch.Generator):
+ seeded.manual_seed(int(seed))
+ return render_call()
+
try:
with grad_ctx, protect_ctx, progress_ctx(), sigma_ctx:
- output = render_thread.run(
- "video",
- ltx25_render_call
- if ltx25_render_call is not None
- else (
- lambda: _carried_call(
- pipe, kwargs, has_step_callback or carry_by_scheduler
- )
- ),
- )
+ output = render_thread.run("video", _render_streamed_after_oom)
except _VideoGenerationCancelled:
# Unwinding by exception skips maybe_free_model_hooks(); offloaded modules would stay on GPU.
free_hooks = getattr(pipe, "maybe_free_model_hooks", None)
diff --git a/studio/backend/core/inference/video_stream_residency.py b/studio/backend/core/inference/video_stream_residency.py
index 560f8abc00b..ed42b930cd9 100644
--- a/studio/backend/core/inference/video_stream_residency.py
+++ b/studio/backend/core/inference/video_stream_residency.py
@@ -4,7 +4,8 @@
"""Keeps top group and block prefix of a Wan, HunyuanVideo-1.5, LTX-2 or LTX-2.5 denoiser resident, re-fitted per
request; need estimate stays the lower bound; kill switches UNSLOTH_VIDEO_DIT_RESIDENT=0,
UNSLOTH_VIDEO_DIT_RESIDENT_BLOCKS=0 (top group only), UNSLOTH_VIDEO_DIT_RESIDENT_MEASURED=0
-(estimate only)."""
+(estimate only), UNSLOTH_VIDEO_DIT_RESIDENT_WARM_ONLY=0 (stored peaks widen a process's first render too),
+UNSLOTH_VIDEO_DIT_RESIDENT_OOM_RETRY=0 (an out-of-memory render with groups resident fails as is)."""
from __future__ import annotations
@@ -14,6 +15,8 @@ from typing import Any, Optional
VIDEO_DIT_RESIDENT_ENV = "UNSLOTH_VIDEO_DIT_RESIDENT"
VIDEO_DIT_RESIDENT_BLOCKS_ENV = "UNSLOTH_VIDEO_DIT_RESIDENT_BLOCKS"
VIDEO_DIT_RESIDENT_MEASURED_ENV = "UNSLOTH_VIDEO_DIT_RESIDENT_MEASURED"
+VIDEO_DIT_RESIDENT_WARM_ONLY_ENV = "UNSLOTH_VIDEO_DIT_RESIDENT_WARM_ONLY"
+VIDEO_DIT_RESIDENT_OOM_RETRY_ENV = "UNSLOTH_VIDEO_DIT_RESIDENT_OOM_RETRY"
RESIDENT_POLICIES = ("group", "streaming")
# Single-DiT families measured under the fit (MiniMax-H3 has its own controller, video_minimax_h3_residency).
RESIDENT_FAMILY_PREFIXES = ("wan", "hunyuanvideo-1.5")
@@ -31,6 +34,8 @@ _COUNTS: dict[str, int] = {
"released_mib": 0,
"resident_mib": 0,
"groups": 0,
+ "cold_skips": 0,
+ "oom_retries": 0,
}
@@ -54,6 +59,14 @@ def measured_enabled() -> bool:
return not _off(VIDEO_DIT_RESIDENT_MEASURED_ENV)
+def warm_only_enabled() -> bool:
+ return not _off(VIDEO_DIT_RESIDENT_WARM_ONLY_ENV)
+
+
+def oom_retry_enabled() -> bool:
+ return not _off(VIDEO_DIT_RESIDENT_OOM_RETRY_ENV)
+
+
def applies(
family_name: Optional[str],
*,
@@ -139,6 +152,13 @@ def measured_room_mib(
# calibration key -> {work (pixels x frames): peak MiB above the request's start}; survives a reload of the same model
_PEAKS: dict = {}
+# keys rendered in this process; a stored warm peak omits first-render compile/allocator cost, so only widens later renders
+_WARM: set = set()
+
+
+def _cold(module: Any) -> bool:
+ key = getattr(module, "_unsloth_video_calibration_key", None)
+ return warm_only_enabled() and key is not None and key not in _WARM
def calibration_key(
@@ -405,6 +425,9 @@ def record_request_peak(pipe: Any, *, logger: Any = None) -> Optional[int]:
module._unsloth_video_pending = None
work, start, dev = pending
extra = (int(torch.cuda.max_memory_allocated(dev)) - int(start)) >> 20
+ completed = getattr(module, "_unsloth_video_calibration_key", None)
+ if completed is not None:
+ _WARM.add(completed)
window = getattr(module, "_unsloth_video_window", None)
module._unsloth_video_window = None
if window is not None:
@@ -508,6 +531,15 @@ def fit_for_request(
frames = frames,
)
measured = _measured_extra_mib(module, work) if measured_enabled() else None
+ if measured is not None and _cold(module):
+ _COUNTS["cold_skips"] += 1
+ if logger is not None:
+ logger.info(
+ "video.dit_resident: stored peak %d MiB waits for this process's first render of the setup "
+ "(compile, kernel loads and a fresh allocator are not in it)",
+ measured,
+ )
+ measured = None
if measured is not None:
wider = measured_room_mib(
free_mib = int(free) >> 20,
@@ -583,3 +615,57 @@ def fit_for_request(
except Exception: # noqa: BLE001
pass
return None
+
+
+def may_stream_after_oom(pipe: Any) -> bool:
+ try:
+ return oom_retry_enabled() and resident_mib(getattr(pipe, "transformer", None)) > 0
+ except Exception: # noqa: BLE001
+ return False
+
+
+def stream_after_oom(pipe: Any, *, logger: Any = None) -> bool:
+ """Stream all resident groups for the rest of the request after an OOM; True = caller may retry. Never raises."""
+ module = getattr(pipe, "transformer", None)
+ if module is None or not oom_retry_enabled():
+ return False
+ try:
+ import gc
+
+ import torch
+
+ from .diffusion_memory import release_resident_groups
+
+ held = resident_mib(module)
+ if held <= 0:
+ return False
+ release_resident_groups(
+ pipe, 1 << 30, logger, denoisers_only = True, reason = "a render that ran out of memory"
+ )
+ left = resident_mib(module)
+ if left >= held:
+ return False
+ # no re-pin (encode lend restore, decode restore) until the next request's fit
+ module._unsloth_resident_room = None
+ gc.collect()
+ torch.cuda.empty_cache()
+ pending = getattr(module, "_unsloth_video_pending", None)
+ if pending is not None:
+ work, _start, dev = pending
+ torch.cuda.reset_peak_memory_stats(dev)
+ module._unsloth_video_pending = (work, int(torch.cuda.memory_allocated(dev)), dev)
+ _COUNTS["oom_retries"] += 1
+ _COUNTS["resident_mib"] = left
+ if logger is not None:
+ logger.warning(
+ "video.dit_resident: out of memory with %d MiB of the denoiser resident; streaming it and "
+ "rendering once more",
+ held,
+ )
+ return True
+ except Exception as exc: # noqa: BLE001 -- the original error is reported instead
+ if logger is not None:
+ logger.warning(
+ "video.dit_resident: could not stream the denoiser after the OOM (%s)", exc
+ )
+ return False
diff --git a/studio/backend/tests/test_video_resident_cold_start.py b/studio/backend/tests/test_video_resident_cold_start.py
new file mode 100644
index 00000000000..516e64f7734
--- /dev/null
+++ b/studio/backend/tests/test_video_resident_cold_start.py
@@ -0,0 +1,197 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""A stored warm peak must not widen residency on a new process's first render; an OOM with groups resident retries streamed."""
+
+from __future__ import annotations
+
+import ast
+import types
+from pathlib import Path
+
+import pytest
+
+import core.inference.diffusion_memory as dm
+import core.inference.video_stream_residency as vr
+
+torch = pytest.importorskip("torch")
+
+KEY = vr.calibration_key(
+ "ltx-2.5", "Lightricks/LTX-2.5-Diffusers", "streaming", "cuda:0", revision = "abc"
+)
+WORK = 768 * 512 * 49
+
+
[email protected](autouse = True)
+def _env(monkeypatch):
+ for name in (
+ vr.VIDEO_DIT_RESIDENT_ENV,
+ vr.VIDEO_DIT_RESIDENT_BLOCKS_ENV,
+ vr.VIDEO_DIT_RESIDENT_MEASURED_ENV,
+ "UNSLOTH_VIDEO_DIT_RESIDENT_WARM_ONLY",
+ "UNSLOTH_VIDEO_DIT_RESIDENT_OOM_RETRY",
+ ):
+ monkeypatch.delenv(name, raising = False)
+ monkeypatch.setattr(vr, "_PEAKS", {KEY: {WORK: 2031}})
+ if hasattr(vr, "_WARM"):
+ monkeypatch.setattr(vr, "_WARM", set())
+
+
+def _card(monkeypatch):
+ kept = []
+ monkeypatch.setattr(torch.cuda, "mem_get_info", lambda device = None: (7863 << 20, 23034 << 20))
+ monkeypatch.setattr(torch.cuda, "memory_allocated", lambda device = None: 7000 << 20)
+ monkeypatch.setattr(torch.cuda, "max_memory_allocated", lambda device = None: 9031 << 20)
+ monkeypatch.setattr(torch.cuda, "reset_peak_memory_stats", lambda device = None: None)
+ monkeypatch.setattr(torch.cuda, "empty_cache", lambda: None)
+ monkeypatch.setattr(dm, "cuda_reusable_cache_bytes", lambda device = None: 25 << 20)
+ monkeypatch.setattr(dm, "_user_budget_reserve_mib", lambda total: 0)
+ monkeypatch.setattr(
+ dm, "_keep_groups_resident", lambda module, room, dev, logger = None: kept.append(room)
+ )
+ monkeypatch.setattr(dm, "stream_window_pad_mib", lambda pipe: 0)
+ monkeypatch.setattr(dm, "_offload_groups", lambda module: [])
+ monkeypatch.setattr(vr, "resident_mib", lambda module: 0)
+ monkeypatch.setattr(vr, "room_mib", lambda **kw: 0)
+ monkeypatch.setattr(vr, "_open_window", lambda module, dev: dev)
+ monkeypatch.setattr(vr, "_failed_captures", lambda: 0)
+ monkeypatch.setattr(vr, "_store_key", lambda key: None)
+ module = types.SimpleNamespace(_unsloth_video_calibration_key = KEY)
+ pipe = types.SimpleNamespace(transformer = module, components = {"transformer": module})
+ return pipe, kept
+
+
+def _fit(pipe):
+ import logging
+ return vr.fit_for_request(
+ pipe,
+ device = "cuda:0",
+ floor_mib = 8938,
+ width = 768,
+ height = 512,
+ frames = 49,
+ logger = logging.getLogger("t"),
+ )
+
+
+def test_a_stored_peak_does_not_widen_the_first_render_of_a_new_process(monkeypatch):
+ pipe, kept = _card(monkeypatch)
+ _fit(pipe)
+ assert kept == []
+ assert vr.record_request_peak(pipe) == 2031
+ _fit(pipe)
+ assert (
+ kept and kept[-1] == 7863 + 25 - int(2031 * vr.MEASURED_PEAK_MARGIN) - vr.MEASURED_SLACK_MIB
+ )
+
+
+def test_warm_only_kill_switch_trusts_the_stored_peak_at_once(monkeypatch):
+ monkeypatch.setenv("UNSLOTH_VIDEO_DIT_RESIDENT_WARM_ONLY", "0")
+ pipe, kept = _card(monkeypatch)
+ _fit(pipe)
+ assert kept == [7863 + 25 - int(2031 * vr.MEASURED_PEAK_MARGIN) - vr.MEASURED_SLACK_MIB]
+
+
+def _resident_pipe(monkeypatch, held_mib):
+ state = {"held": held_mib}
+ monkeypatch.setattr(vr, "resident_mib", lambda module: state["held"])
+
+ def release(
+ pipe,
+ need,
+ logger = None,
+ denoisers_only = False,
+ reason = "",
+ device = None,
+ ):
+ assert denoisers_only
+ state["held"] = 0
+ return lambda: None
+
+ monkeypatch.setattr(dm, "release_resident_groups", release)
+ monkeypatch.setattr(torch.cuda, "empty_cache", lambda: None)
+ monkeypatch.setattr(torch.cuda, "reset_peak_memory_stats", lambda device = None: None)
+ monkeypatch.setattr(torch.cuda, "memory_allocated", lambda device = None: 7000 << 20)
+ module = types.SimpleNamespace(
+ _unsloth_resident_room = 4529, _unsloth_video_pending = (WORK, 11484 << 20, "cuda:0")
+ )
+ return types.SimpleNamespace(transformer = module), state
+
+
+def test_an_oom_with_groups_resident_streams_them_and_rearms_the_measurement(monkeypatch):
+ pipe, state = _resident_pipe(monkeypatch, 4484)
+ assert vr.may_stream_after_oom(pipe)
+ assert vr.stream_after_oom(pipe) is True
+ assert state["held"] == 0
+ assert pipe.transformer._unsloth_resident_room is None
+ assert pipe.transformer._unsloth_video_pending == (WORK, 7000 << 20, "cuda:0")
+ assert not vr.may_stream_after_oom(pipe) # once per request: nothing left to stream
+
+
+def test_oom_retry_kill_switch_and_a_fully_streamed_render(monkeypatch):
+ pipe, _ = _resident_pipe(monkeypatch, 0)
+ assert not vr.may_stream_after_oom(pipe)
+ assert vr.stream_after_oom(pipe) is False
+ pipe, state = _resident_pipe(monkeypatch, 4484)
+ monkeypatch.setenv("UNSLOTH_VIDEO_DIT_RESIDENT_OOM_RETRY", "0")
+ assert not vr.may_stream_after_oom(pipe)
+ assert vr.stream_after_oom(pipe) is False and state["held"] == 4484
+
+
+def test_video_render_runs_through_the_oom_retry():
+ src = (Path(__file__).resolve().parents[1] / "core" / "inference" / "video.py").read_text(
+ encoding = "utf-8"
+ )
+ tree = ast.parse(src)
+ runs = [
+ n
+ for n in ast.walk(tree)
+ if isinstance(n, ast.Call)
+ and isinstance(n.func, ast.Attribute)
+ and n.func.attr == "run"
+ and isinstance(n.func.value, ast.Name)
+ and n.func.value.id == "render_thread"
+ and n.args
+ and isinstance(n.args[0], ast.Constant)
+ and n.args[0].value == "video"
+ ]
+ assert len(runs) == 1
+ assert (
+ isinstance(runs[0].args[1], ast.Name) and runs[0].args[1].id == "_render_streamed_after_oom"
+ )
+ retry = next(
+ n
+ for n in ast.walk(tree)
+ if isinstance(n, ast.FunctionDef) and n.name == "_render_streamed_after_oom"
+ )
+ body = ast.unparse(retry)
+ assert body.index("may_stream_after_oom") < body.index(
+ "video_stream_residency.stream_after_oom("
+ )
+ assert body.index("video_stream_residency.stream_after_oom(") < body.index(
+ "manual_seed(int(seed))"
+ )
+ assert (
+ body.index("video_stream_residency.stream_after_oom(")
+ < body.index("restart_protect_generation(pipe)")
+ < body.rindex("render_call()")
+ )
+
+
+def test_a_retried_render_restarts_the_nvfp4_protect_schedule():
+ from core.inference.diffusion_nvfp4_protect import NVFP4StepController
+
+ ctl = NVFP4StepController("0,-1")
+ assert ctl.begin(5) == (0, 4)
+ ctl.advance()
+ ctl.advance()
+ ctl.restart()
+ seen = [ctl.protected]
+ for _ in range(4):
+ ctl.advance()
+ seen.append(ctl.protected)
+ assert seen == [True, False, False, False, True]
+ assert ctl.protected_steps_seen == 2
+ idle = NVFP4StepController("0,-1")
+ idle.restart() # no generation begun: stays idle
+ assert idle.index == 0 and not idle.protected