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: write the offloaded native int8 build to the prequant cache after the load (Wan2.2-A14B first clip 97 s sooner) (#15331)

Daniel Hanb759a5b13b91
diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.py
index 1e0ad93233f..a694fef82db 100644
--- a/studio/backend/core/inference/video.py
+++ b/studio/backend/core/inference/video.py
@@ -3307,6 +3307,126 @@ def _save_native_quant_to_cache(
logger.warning("diffusion.prequant_cache: native skipped (%s)", exc)
+# "0": the offloaded native build is written to the local prequant cache inside the load, as before.
+VIDEO_NATIVE_CACHE_BACKGROUND_ENV = "UNSLOTH_VIDEO_NATIVE_CACHE_BACKGROUND"
+_NATIVE_WRITES_ATTR = "_unsloth_native_writes"
+
+
+def _native_cache_background() -> bool:
+ raw = (os.environ.get(VIDEO_NATIVE_CACHE_BACKGROUND_ENV) or "").strip().lower()
+ if raw in ("0", "off", "false", "no"):
+ return False
+ try:
+ from .diffusion_prequant_cache import async_enabled
+ return bool(async_enabled())
+ except Exception: # noqa: BLE001
+ return False
+
+
+class _NativeCacheWrites:
+ """Offloaded native build's cache writes, run after the load is published.
+
+ Waits for the background pins so the writer reads the pinned copies, not pageable tensors it would keep alive."""
+
+ def __init__(
+ self,
+ pipe: Any,
+ fam: Any,
+ views: Any,
+ spec: dict,
+ *,
+ base: Optional[str],
+ source: Optional[str],
+ ):
+ import threading
+
+ self._pipe = pipe
+ self._args = (fam, list(views or ()), spec, base, source)
+ self._lock = threading.Lock()
+ self._closed = False
+ self._writes: list = []
+ self._thread: Optional[Any] = None
+
+ def start(self) -> None:
+ import threading
+ self._thread = threading.Thread(
+ target = self._run, name = "video-native-cache-write", daemon = True
+ )
+ self._thread.start()
+
+ def _run(self) -> None:
+ try:
+ finish_background_pins(self._pipe)
+ fam, views, spec, base, source = self._args
+ from .diffusion_native_cache import save_deferred
+ from .video_denoiser_prequant import denoiser_components
+
+ components = denoiser_components(fam)
+ if len(components) != len(views):
+ logger.info(
+ "diffusion.prequant_cache: native skipped (denoiser views != components)"
+ )
+ return
+ logger.info(
+ "diffusion.prequant_cache: writing the native %s build of %s in the background, after the load",
+ spec.get("scheme"),
+ ", ".join(components),
+ )
+ for component, view in zip(components, views):
+ with self._lock:
+ if self._closed:
+ return
+ write = save_deferred(
+ getattr(view, "transformer", None),
+ fam,
+ base_repo = base,
+ source_base = source,
+ component = component,
+ logger = logger,
+ )
+ if write is None or not hasattr(write, "start"):
+ continue
+ self._writes.append(write)
+ write.start()
+ write.wait()
+ except Exception as exc: # noqa: BLE001 - a cache write never surfaces
+ logger.warning("diffusion.prequant_cache: native background write skipped (%s)", exc)
+ finally:
+ self._args = None
+ self._pipe = None
+
+ def finish(self, timeout: Optional[float] = None) -> None:
+ """Teardown: let a running write finish (bounded), then cancel; a write not yet begun never begins."""
+ try:
+ from .diffusion_prequant_cache import FINISH_TIMEOUT_SECONDS
+ timeout = FINISH_TIMEOUT_SECONDS if timeout is None else timeout
+ except Exception: # noqa: BLE001
+ timeout = 600.0 if timeout is None else timeout
+ with self._lock:
+ self._closed = True
+ writes = list(self._writes)
+ for write in writes:
+ try:
+ if not write.wait(timeout):
+ write.cancel()
+ write.wait(30.0)
+ except Exception: # noqa: BLE001 - teardown is best effort
+ pass
+ if self._thread is not None:
+ self._thread.join(30.0)
+
+
+def _finish_native_writes(pipe: Any) -> None:
+ writes = getattr(pipe, _NATIVE_WRITES_ATTR, None)
+ if writes is None:
+ return
+ try:
+ writes.finish()
+ setattr(pipe, _NATIVE_WRITES_ATTR, None)
+ except Exception: # noqa: BLE001 - teardown is best effort
+ pass
+
+
def _read_native_quant_from_cache(
fam: Any,
spec: Optional[dict],
@@ -9214,6 +9334,7 @@ class VideoBackend:
# The encoder runs in the worker; the enhancer, processor and duration head are never used.
pipe_kwargs.update({name: None for name in LTX25_NONE_COMPONENTS})
cast_writes = None
+ native_writes = None
if kind == "pipeline":
cast_missed = _read_cast_cache(
pipe_kwargs,
@@ -9782,14 +9903,24 @@ class VideoBackend:
== _native_spec_for(native_scheme, fam, native_kwargs.get("act_int8"))
):
# The native build is read back under auto too: the cache replays the pick, never makes it.
- _save_native_quant_to_cache(
- fam,
- views,
- native_cache_spec,
- base = base,
- source = _base_local_dir or fetch_base,
- cancel_check = lambda: self._raise_if_video_load_superseded(_load_token),
- )
+ if _native_cache_background():
+ native_writes = _NativeCacheWrites(
+ pipe,
+ fam,
+ views,
+ native_cache_spec,
+ base = base,
+ source = _base_local_dir or fetch_base,
+ )
+ else:
+ _save_native_quant_to_cache(
+ fam,
+ views,
+ native_cache_spec,
+ base = base,
+ source = _base_local_dir or fetch_base,
+ cancel_check = lambda: self._raise_if_video_load_superseded(_load_token),
+ )
self._raise_if_video_load_superseded(_load_token)
# Only explicit schemes read the cache back, so an auto save would be a write nothing opens.
elif transformer_quant_pinned is not None:
@@ -10475,6 +10606,9 @@ class VideoBackend:
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()
return self.status()
@staticmethod
@@ -14026,6 +14160,7 @@ class VideoBackend:
stop_background_pins(getattr(state, "pipe", None))
# A cast cache write still reads the components the teardown frees.
_finish_cast_writes(getattr(state, "pipe", None))
+ _finish_native_writes(getattr(state, "pipe", None))
uninstall_cfg_parallel(getattr(state, "pipe", None))
# Before clear_gpu_cache(), or the graph pool stays reserved.
diffusion_cuda_graph.uninstall_all(
diff --git a/studio/backend/tests/test_video_native_cache_background.py b/studio/backend/tests/test_video_native_cache_background.py
new file mode 100644
index 00000000000..efb753e9dfd
--- /dev/null
+++ b/studio/backend/tests/test_video_native_cache_background.py
@@ -0,0 +1,150 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Offloaded video loads write the native int8 build after the load is published, not inside it."""
+
+import ast
+import inspect
+import threading
+import types
+
+import pytest
+
+pytest.importorskip("torch")
+
+import core.inference.video as V
+from core.inference import diffusion_native_cache as dnc
+from core.inference import video_denoiser_prequant as vdp
+
+_ENV = getattr(V, "VIDEO_NATIVE_CACHE_BACKGROUND_ENV", "UNSLOTH_VIDEO_NATIVE_CACHE_BACKGROUND")
+
+
+class _Write:
+ def __init__(self, log, name):
+ self.log, self.name = log, name
+ self.done = threading.Event()
+ self.cancelled = False
+
+ def start(self):
+ self.log.append(("start", self.name))
+ self.done.set()
+ return True
+
+ def wait(self, timeout = None):
+ return self.done.wait(timeout)
+
+ def cancel(self):
+ self.cancelled = True
+
+
+def fake(monkeypatch):
+ log = []
+ monkeypatch.delenv(_ENV, raising = False)
+ monkeypatch.setattr(vdp, "denoiser_components", lambda fam: ["transformer", "transformer_2"])
+ monkeypatch.setattr(
+ V, "finish_background_pins", lambda pipe, cancel = None: log.append(("pins",)) or 0.0
+ )
+
+ def save_deferred(transformer, fam, **kw):
+ log.append(("deferred", kw["component"], transformer))
+ return _Write(log, kw["component"])
+
+ monkeypatch.setattr(dnc, "save_deferred", save_deferred)
+ views = [types.SimpleNamespace(transformer = "hi"), types.SimpleNamespace(transformer = "lo")]
+ return log, views
+
+
+def test_the_kill_switches_keep_the_write_inside_the_load(monkeypatch):
+ monkeypatch.delenv(_ENV, raising = False)
+ monkeypatch.delenv("UNSLOTH_DIFFUSION_PREQUANT_CACHE_ASYNC", raising = False)
+ assert V._native_cache_background()
+ monkeypatch.setenv(_ENV, "0")
+ assert not V._native_cache_background()
+ monkeypatch.delenv(_ENV)
+ monkeypatch.setenv("UNSLOTH_DIFFUSION_PREQUANT_CACHE_ASYNC", "0")
+ assert not V._native_cache_background()
+
+
+def test_the_writes_start_after_the_pins_one_expert_at_a_time(fake):
+ log, views = fake
+ w = V._NativeCacheWrites(
+ types.SimpleNamespace(), object(), views, {"scheme": "int8"}, base = "b", source = "s"
+ )
+ assert log == [] # nothing is written until the load is published
+ w.start()
+ w._thread.join(10)
+ assert log == [
+ ("pins",),
+ ("deferred", "transformer", "hi"),
+ ("start", "transformer"),
+ ("deferred", "transformer_2", "lo"),
+ ("start", "transformer_2"),
+ ]
+ w.finish(timeout = 1.0)
+
+
+def test_an_unload_before_the_start_writes_nothing(fake):
+ log, views = fake
+ w = V._NativeCacheWrites(
+ types.SimpleNamespace(), object(), views, {"scheme": "int8"}, base = "b", source = "s"
+ )
+ w.finish(timeout = 1.0)
+ w.start()
+ w._thread.join(10)
+ assert not [e for e in log if e[0] in ("deferred", "start")]
+
+
+def test_a_write_still_running_at_unload_is_waited_for_then_cancelled(fake, monkeypatch):
+ log, views = fake
+ hang = _Write(log, "transformer")
+ hang.start = lambda: log.append(("start", "transformer")) or True # never completes
+ monkeypatch.setattr(dnc, "save_deferred", lambda *a, **k: hang)
+ w = V._NativeCacheWrites(
+ types.SimpleNamespace(), object(), views[:1] * 2, {"scheme": "int8"}, base = None, source = None
+ )
+ w.start()
+ for _ in range(200):
+ if ("start", "transformer") in log:
+ break
+ threading.Event().wait(0.01)
+ w.finish(timeout = 0.05)
+ assert hang.cancelled
+
+
+def test_the_load_defers_the_native_save_and_starts_it_after_the_pins():
+ src = inspect.getsource(V.VideoBackend.load_pipeline)
+ tree = ast.parse("class _X:\n" + src if src.startswith(" ") else src)
+ calls = [
+ (
+ node.lineno,
+ node.func.id if isinstance(node.func, ast.Name) else getattr(node.func, "attr", None),
+ )
+ for node in ast.walk(tree)
+ if isinstance(node, ast.Call)
+ ]
+ names = [n for _l, n in calls]
+ assert "_NativeCacheWrites" in names and "_save_native_quant_to_cache" in names
+ # the sync save is only the kill-switch branch
+ for node in ast.walk(tree):
+ if isinstance(node, ast.If) and "_native_cache_background" in ast.unparse(node.test):
+ assert "_NativeCacheWrites" in ast.unparse(node.body[0])
+ assert "_save_native_quant_to_cache" in ast.unparse(node.orelse[0])
+ break
+ 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
+
+
+def test_the_unload_finishes_the_native_writes():
+ src = inspect.getsource(V)
+ assert '_finish_native_writes(getattr(state, "pipe", None))' in src