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: start a first video load's cache writes after its first render (#17001)

Daniel Han482514b1f0d9
diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.py
index a4b73440e8b..4f068441bfd 100644
--- a/studio/backend/core/inference/video.py
+++ b/studio/backend/core/inference/video.py
@@ -3419,22 +3419,148 @@ def _discard_resident_quant_write(owner: Any, token: Any = None) -> None:
pass
-def _start_resident_quant_write(owner: Any, pipe: Any, token: Any) -> None:
+def _take_resident_quant_write(owner: Any, token: Any) -> Any:
+ """This load's pending resident write, now owned by the caller (None if another load replaced it)."""
slot = getattr(owner, "_resident_quant_write", None)
if slot is None or slot[0] != token:
- return
+ return None
owner._resident_quant_write = None
+ return slot[1]
+
+
+def _start_resident_quant_write(owner: Any, pipe: Any, token: Any) -> None:
+ _start_taken_resident_write(pipe, _take_resident_quant_write(owner, token))
+
+
+def _start_taken_resident_write(pipe: Any, write: Any) -> None:
+ if write is None:
+ return
try:
- setattr(pipe, _RESIDENT_QUANT_WRITE_ATTR, slot[1])
- slot[1].start()
+ setattr(pipe, _RESIDENT_QUANT_WRITE_ATTR, write)
+ write.start()
except Exception as exc: # noqa: BLE001 - a cache write never fails a load
logger.warning("diffusion.prequant_cache: resident background write skipped (%s)", exc)
try:
- slot[1].discard()
+ write.discard()
except Exception: # noqa: BLE001
pass
+# "0": a first load's cache writes start as soon as it is published, beside its first render.
+VIDEO_CACHE_WRITES_AFTER_RENDER_ENV = "UNSLOTH_VIDEO_CACHE_WRITES_AFTER_RENDER"
+# Seconds a load with no render may sit before its held writes start anyway.
+VIDEO_CACHE_WRITE_IDLE_ENV = "UNSLOTH_VIDEO_CACHE_WRITE_IDLE_S"
+_VIDEO_CACHE_WRITE_IDLE_DEFAULT_S = 120.0
+_HELD_CACHE_WRITES_ATTR = "_unsloth_held_cache_writes"
+
+
+def _cache_writes_after_render() -> bool:
+ raw = (os.environ.get(VIDEO_CACHE_WRITES_AFTER_RENDER_ENV) or "").strip().lower()
+ return raw not in ("0", "off", "false", "no")
+
+
+def _cache_write_idle_s() -> float:
+ raw = (os.environ.get(VIDEO_CACHE_WRITE_IDLE_ENV) or "").strip()
+ try:
+ value = float(raw) if raw else _VIDEO_CACHE_WRITE_IDLE_DEFAULT_S
+ except ValueError:
+ value = _VIDEO_CACHE_WRITE_IDLE_DEFAULT_S
+ return max(0.0, value)
+
+
+def _start_cache_writes(
+ pipe: Any, cast_writes: Any, native_writes: Any, resident_write: Any
+) -> None:
+ if cast_writes is not None:
+ pipe._unsloth_cast_writes = cast_writes
+ cast_writes.start()
+ if native_writes is not None:
+ setattr(pipe, _NATIVE_WRITES_ATTR, native_writes)
+ native_writes.start()
+ _start_taken_resident_write(pipe, resident_write)
+
+
+class _HeldCacheWrites:
+ """A first load's cache writes, held until its first render ends or ``idle_s`` idle: beside that render they
+ contend with its compile and denoise for CPU, disk and host RAM."""
+
+ def __init__(self, pipe: Any, writes: tuple, busy: Callable[[], bool], idle_s: float):
+ import weakref
+
+ self._pipe = weakref.ref(pipe)
+ self._writes: Optional[tuple] = writes
+ self._busy = busy
+ self._lock = threading.Lock()
+ self._timer: Optional[threading.Timer] = None
+ if idle_s > 0:
+ self._timer = threading.Timer(idle_s, self._on_idle)
+ self._timer.daemon = True
+ self._timer.name = "video-cache-write-idle"
+
+ def arm(self) -> None:
+ if self._timer is not None:
+ self._timer.start()
+
+ def _take(self) -> Optional[tuple]:
+ # Caller holds self._lock.
+ writes, self._writes = self._writes, None
+ timer, self._timer = self._timer, None
+ if timer is not None:
+ timer.cancel()
+ return writes
+
+ def _on_idle(self) -> None:
+ # A render in flight releases them when it ends.
+ try:
+ if self._busy():
+ return
+ except Exception: # noqa: BLE001 - unreadable: start them
+ pass
+ self.release("the backend sat idle after the load")
+
+ def release(self, why: str) -> None:
+ # Started and registered on the pipe under the lock: a concurrent discard either cancels them first or runs
+ # after, so the teardown's finish calls see every started writer.
+ with self._lock:
+ writes = self._take()
+ pipe = self._pipe()
+ if writes is None or pipe is None:
+ return
+ logger.info("diffusion.prequant_cache: first-load cache writes start now (%s)", why)
+ try:
+ _start_cache_writes(pipe, *writes)
+ except Exception as exc: # noqa: BLE001 - a cache write never fails a render
+ logger.warning("diffusion.prequant_cache: held cache writes skipped (%s)", exc)
+
+ def discard(self) -> None:
+ with self._lock:
+ writes = self._take()
+ for write in writes or ():
+ if write is None:
+ continue
+ try:
+ write.discard() if hasattr(write, "discard") else write.finish(0.0)
+ except Exception: # noqa: BLE001 - teardown is best effort
+ pass
+
+
+def _release_held_cache_writes(pipe: Any, why: str) -> None:
+ held = getattr(pipe, _HELD_CACHE_WRITES_ATTR, None) if pipe is not None else None
+ if held is not None:
+ held.release(why)
+
+
+def _discard_held_cache_writes(pipe: Any) -> None:
+ held = getattr(pipe, _HELD_CACHE_WRITES_ATTR, None) if pipe is not None else None
+ if held is None:
+ return
+ try:
+ setattr(pipe, _HELD_CACHE_WRITES_ATTR, None)
+ except Exception: # noqa: BLE001
+ pass
+ held.discard()
+
+
def _finish_resident_quant_write(pipe: Any) -> None:
"""Teardown: let a running write finish (bounded), then cancel."""
write = getattr(pipe, _RESIDENT_QUANT_WRITE_ATTR, None)
@@ -10964,13 +11090,18 @@ class VideoBackend:
if fam.is_moe:
defer_late_expert_pins(pipe, (getattr(pipe, "transformer_2", None),), logger)
start_background_pins(pipe)
- if cast_writes is not None:
- pipe._unsloth_cast_writes = cast_writes
- cast_writes.start()
- if native_writes is not None:
- setattr(pipe, _NATIVE_WRITES_ATTR, native_writes)
- native_writes.start()
- _start_resident_quant_write(self, pipe, _load_token)
+ held = (cast_writes, native_writes, _take_resident_quant_write(self, _load_token))
+ if any(w is not None for w in held) and _cache_writes_after_render():
+ holder = _HeldCacheWrites(
+ pipe, held, busy = self._generate_lock.locked, idle_s = _cache_write_idle_s()
+ )
+ setattr(pipe, _HELD_CACHE_WRITES_ATTR, holder)
+ holder.arm()
+ logger.info(
+ "diffusion.prequant_cache: this first load's cache writes wait for its first render"
+ )
+ else:
+ _start_cache_writes(pipe, *held)
return self.status()
@staticmethod
@@ -13581,6 +13712,7 @@ class VideoBackend:
# The pinned clip and stream chunks (~3x the clip) otherwise stay in torch's host cache until unload.
output = video_frames = None
release_pinned_host_memory()
+ _release_held_cache_writes(getattr(state, "pipe", None), "the first render ended")
@staticmethod
def _resolve_keyframes(
@@ -14363,7 +14495,8 @@ class VideoBackend:
close_encoder(getattr(state, "pipe", None))
# A pinner still copying would hold its chunks past release_pinned_host_memory().
stop_background_pins(getattr(state, "pipe", None))
- # A cast cache write still reads the components the teardown frees.
+ # Cast writes still read the components the teardown frees.
+ _discard_held_cache_writes(getattr(state, "pipe", None))
_finish_cast_writes(getattr(state, "pipe", None))
_finish_native_writes(getattr(state, "pipe", None))
_finish_resident_quant_write(getattr(state, "pipe", None))
diff --git a/studio/backend/tests/test_video_cache_writes_after_render.py b/studio/backend/tests/test_video_cache_writes_after_render.py
new file mode 100644
index 00000000000..ce3926eecb3
--- /dev/null
+++ b/studio/backend/tests/test_video_cache_writes_after_render.py
@@ -0,0 +1,177 @@
+# Unsloth Zoo - Utilities for Unsloth
+# Copyright 2023-present Daniel Han-Chen, Michael Han-Chen & the Unsloth team. All rights reserved.
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published
+# by the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+"""A first video load's cache writes wait for its first render (or an idle window), and never begin after teardown."""
+
+import ast
+import inspect
+import threading
+import time
+
+import pytest
+
+from core.inference import video as V
+
+
+class _W:
+ def __init__(self, log, name):
+ self.log = log
+ self.name = name
+
+ def start(self):
+ self.log.append(("start", self.name))
+ return True
+
+ def discard(self):
+ self.log.append(("discard", self.name))
+
+
+class _Native:
+ def __init__(self, log):
+ self.log = log
+
+ def start(self):
+ self.log.append(("start", "native"))
+
+ def finish(self, timeout = None):
+ self.log.append(("finish", "native"))
+
+
+class _Pipe:
+ pass
+
+
+def _holder(
+ log,
+ busy = lambda: False,
+ idle_s = 0.0,
+):
+ pipe = _Pipe()
+ writes = (_W(log, "cast"), _Native(log), _W(log, "resident"))
+ holder = V._HeldCacheWrites(pipe, writes, busy = busy, idle_s = idle_s)
+ setattr(pipe, V._HELD_CACHE_WRITES_ATTR, holder)
+ return pipe, holder, writes
+
+
+def test_the_first_render_end_starts_them_once():
+ log = []
+ pipe, holder, writes = _holder(log)
+ holder.arm()
+ assert log == []
+ V._release_held_cache_writes(pipe, "the first render ended")
+ assert log == [("start", "cast"), ("start", "native"), ("start", "resident")]
+ assert pipe._unsloth_cast_writes is writes[0]
+ assert getattr(pipe, V._NATIVE_WRITES_ATTR) is writes[1]
+ assert getattr(pipe, V._RESIDENT_QUANT_WRITE_ATTR) is writes[2]
+ V._release_held_cache_writes(pipe, "a second render ended")
+ assert len(log) == 3
+
+
+def test_teardown_before_a_render_discards_them():
+ log = []
+ pipe, holder, _writes = _holder(log, idle_s = 30.0)
+ holder.arm()
+ V._discard_held_cache_writes(pipe)
+ assert ("start", "cast") not in log
+ assert sorted(log) == [("discard", "cast"), ("discard", "resident"), ("finish", "native")]
+ assert getattr(pipe, V._HELD_CACHE_WRITES_ATTR) is None
+ V._release_held_cache_writes(pipe, "late")
+ assert not any(kind == "start" for kind, _n in log)
+
+
+def test_an_idle_backend_starts_them_and_a_busy_one_waits_for_the_render():
+ log = []
+ busy = threading.Event()
+ busy.set()
+ pipe, holder, _writes = _holder(log, busy = busy.is_set, idle_s = 0.05)
+ holder.arm()
+ time.sleep(0.3)
+ assert log == [] # the render in flight releases them
+ V._release_held_cache_writes(pipe, "the first render ended")
+ assert [kind for kind, _n in log] == ["start"] * 3
+
+ log2 = []
+ pipe2, holder2, _w = _holder(log2, idle_s = 0.05)
+ holder2.arm()
+ deadline = time.time() + 5
+ while len(log2) < 3 and time.time() < deadline:
+ time.sleep(0.02)
+ assert [kind for kind, _n in log2] == ["start"] * 3
+
+
+def test_kill_switch_and_idle_env(monkeypatch):
+ monkeypatch.setenv(V.VIDEO_CACHE_WRITES_AFTER_RENDER_ENV, "0")
+ assert V._cache_writes_after_render() is False
+ monkeypatch.delenv(V.VIDEO_CACHE_WRITES_AFTER_RENDER_ENV)
+ assert V._cache_writes_after_render() is True
+ monkeypatch.setenv(V.VIDEO_CACHE_WRITE_IDLE_ENV, "bad")
+ assert V._cache_write_idle_s() == V._VIDEO_CACHE_WRITE_IDLE_DEFAULT_S
+ monkeypatch.setenv(V.VIDEO_CACHE_WRITE_IDLE_ENV, "-3")
+ assert V._cache_write_idle_s() == 0.0
+
+
+def test_generate_releases_and_unload_discards_before_finishing():
+ gen = inspect.getsource(V.VideoBackend.generate)
+ assert (
+ '_release_held_cache_writes(getattr(state, "pipe", None), "the first render ended")' in gen
+ )
+ # inside the finally, so a failed or cancelled first render releases them too
+ tree = ast.parse("class _X:\n" + gen if gen.startswith(" ") else gen)
+ finals = [
+ ast.unparse(stmt)
+ for node in ast.walk(tree)
+ if isinstance(node, ast.Try)
+ for stmt in node.finalbody
+ ]
+ assert any("_release_held_cache_writes" in text for text in finals)
+ src = inspect.getsource(V.VideoBackend)
+ discard = src.index('_discard_held_cache_writes(getattr(state, "pipe", None))')
+ assert discard < src.index('_finish_cast_writes(getattr(state, "pipe", None))')
+
+
+def test_a_discard_racing_a_release_waits_until_the_writers_are_registered():
+ log = []
+ gate = threading.Event()
+ entered = threading.Event()
+
+ class _Slow(_W):
+ def start(self):
+ entered.set()
+ gate.wait(5)
+ return super().start()
+
+ pipe = _Pipe()
+ writes = (_Slow(log, "cast"), None, None)
+ holder = V._HeldCacheWrites(pipe, writes, busy = lambda: False, idle_s = 0.0)
+ setattr(pipe, V._HELD_CACHE_WRITES_ATTR, holder)
+ releaser = threading.Thread(target = holder.release, args = ("idle",))
+ releaser.start()
+ assert entered.wait(5)
+ done = threading.Event()
+
+ def _teardown():
+ V._discard_held_cache_writes(pipe)
+ # what the unload's finish calls read next
+ log.append(("teardown sees", getattr(pipe, "_unsloth_cast_writes", None) is writes[0]))
+ done.set()
+
+ tearer = threading.Thread(target = _teardown)
+ tearer.start()
+ assert not done.wait(0.2) # blocked behind the release
+ gate.set()
+ releaser.join(5)
+ tearer.join(5)
+ assert log == [("start", "cast"), ("teardown sees", True)]
diff --git a/studio/backend/tests/test_video_native_cache_background.py b/studio/backend/tests/test_video_native_cache_background.py
index efb753e9dfd..e3b77b13335 100644
--- a/studio/backend/tests/test_video_native_cache_background.py
+++ b/studio/backend/tests/test_video_native_cache_background.py
@@ -134,15 +134,10 @@ def test_the_load_defers_the_native_save_and_starts_it_after_the_pins():
else:
raise AssertionError("no _native_cache_background branch in load_pipeline")
pins = min(line for line, n in calls if n == "start_background_pins")
- starts = [
- node.lineno
- for node in ast.walk(tree)
- if isinstance(node, ast.Call)
- and isinstance(node.func, ast.Attribute)
- and node.func.attr == "start"
- and ast.unparse(node.func.value) == "native_writes"
- ]
- assert starts and min(starts) > pins
+ held = [line for line, n in calls if n in ("_HeldCacheWrites", "_start_cache_writes")]
+ assert held and min(held) > pins
+ starter = inspect.getsource(V._start_cache_writes)
+ assert "native_writes.start()" in starter
def test_the_unload_finishes_the_native_writes():
diff --git a/studio/backend/tests/test_video_resident_quant_cache.py b/studio/backend/tests/test_video_resident_quant_cache.py
index f5003fc1390..0602b624dbc 100644
--- a/studio/backend/tests/test_video_resident_quant_cache.py
+++ b/studio/backend/tests/test_video_resident_quant_cache.py
@@ -521,8 +521,8 @@ def test_the_load_writes_auto_resident_builds_deferred_and_keeps_explicit_writes
assert needle in guard, needle
assert "defer = True" in src[auto_at : auto_at + 400]
assert "source = _base_local_dir or fetch_base," in src[auto_at : auto_at + 400]
- assert "_start_resident_quant_write(self, pipe, _load_token)" in src
- assert src.index("_start_resident_quant_write(") > src.index(
+ assert "_take_resident_quant_write(self, _load_token)" in src
+ assert src.index("_take_resident_quant_write(") > src.index(
'"video.loaded: %s (%s, %s, offload=%s'
)