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: faster cold start for image and video loads (first image on H100 7 to 37% sooner) (#12496)

Daniel Han01d9f5ae9041
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.py
index 041169f24fd..fd5f1dc078c 100644
--- a/studio/backend/core/inference/diffusion.py
+++ b/studio/backend/core/inference/diffusion.py
@@ -183,6 +183,7 @@ from . import diffusion_compile_cache as compile_cache
from . import diffusion_cond_cache as cond_cache
from . import diffusion_prompt_cache as prompt_cache
from . import diffusion_gguf_compile as gguf_compile
+from . import diffusion_bg_compile as bg_compile
from . import diffusion_cuda_graph as cuda_graph
from . import diffusion_render_thread as render_thread
from .diffusion_batched import (
@@ -1032,6 +1033,7 @@ class _LoadState:
generation_count: int = 0
# Pre-warmed torch.compile cache context when a compiled tier ran, else None.
compile_cache_ctx: Any = None
+ bg_compile: Any = None
# GraphedForward handles installed on the denoiser modules.
cuda_graphs: tuple = ()
# Token kept so LoRA adapters selected at generate time can be fetched.
@@ -1069,6 +1071,8 @@ class _LoadingState:
# ONE named file: the scan counts what this load adds, not every byte already in the repo.
asset_files: tuple[tuple[str, str, int, int], ...] = ()
account_id: Optional[str] = None
+ # (expected_bytes, downloaded) once every expected byte was on disk.
+ finalized_scan: Optional[tuple[int, int]] = None
def _account_owned_load(method):
@@ -1851,6 +1855,42 @@ def _dense_fast_path_reason(
return "engaged on the dense fast path"
+def _progress_latch_enabled() -> bool:
+ """UNSLOTH_DIFFUSION_PROGRESS_LATCH=0 rescans the cache on every load-progress poll, as before."""
+ return os.environ.get("UNSLOTH_DIFFUSION_PROGRESS_LATCH", "").strip().lower() not in (
+ "0",
+ "false",
+ "no",
+ "off",
+ )
+
+
+def _bg_compile_module(
+ pipe: Any,
+ *,
+ speed_optims: Any,
+ speed_mode: Any,
+ transformer_quant: Any,
+ gguf_transformer: bool,
+ offload_policy: Any,
+ transformer_cache: Any,
+ cache_auto: bool,
+ target: Any,
+) -> Any:
+ """The denoiser whose compile may run in the background (``diffusion_bg_compile.select_module``), or None."""
+ return bg_compile.select_module(
+ pipe,
+ speed_optims = speed_optims,
+ default_tier = speed_mode == SPEED_DEFAULT,
+ quantized = transformer_quant is not None,
+ gguf = bool(gguf_transformer),
+ step_cache = bool(transformer_cache) or bool(cache_auto),
+ device = getattr(target, "device", None),
+ backend = getattr(target, "backend", None),
+ denoiser_hooked = offload_policy != OFFLOAD_NONE and _denoiser_hooked(pipe),
+ )
+
+
class DiffusionBackend:
"""Holds at most one loaded diffusers pipeline. All mutations are serialised."""
@@ -3269,6 +3309,14 @@ class DiffusionBackend:
return _progress("error", error = loading.error)
if loading is None:
return _progress("ready" if self._state is not None else None)
+ finalized = loading.finalized_scan
+ if (
+ finalized is not None
+ and finalized[0] == loading.expected_bytes
+ and _progress_latch_enabled()
+ ):
+ # Nothing left to download: another tree walk only holds the GIL the load thread needs.
+ return _progress("finalizing", finalized[1], finalized[0], 1.0)
# Sum checkpoint + companion cache, scanning the repo the bytes LAND in (the mirror when one was swapped in),
# else a mirrored companion download reads as zero and the bar sits still.
@@ -3298,6 +3346,7 @@ class DiffusionBackend:
expected = loading.expected_bytes
# Downloads done, still finalizing. The cache scan can exceed the estimate, so clamp to 100%.
if expected > 0 and downloaded >= expected * 0.999:
+ loading.finalized_scan = (expected, min(downloaded, expected))
return _progress("finalizing", min(downloaded, expected), expected, 1.0)
if expected <= 0:
# No size estimate: report the phase with no byte claim, since `downloaded` scans what is PRESENT.
@@ -5988,6 +6037,7 @@ class DiffusionBackend:
eager_patched = False
compile_ctx = None
state_committed = False
+ load_bg_compile = None
state = None
try:
self._raise_if_load_cancelled(_load_token)
@@ -7014,6 +7064,25 @@ class DiffusionBackend:
# Beside ``source``, never in it: the frontend branches on "auto"/"explicit".
resolved["transformer_quant"]["artifact"] = transformer_quant_artifact
+ # Opt-in (UNSLOTH_DIFFUSION_BG_COMPILE=1): off by default so the same seed twice repeats.
+ bg_module = (
+ None
+ if not bg_compile.load_time_enabled()
+ else _bg_compile_module(
+ pipe,
+ speed_optims = tuple(k for k, v in speed_applied.items() if v),
+ speed_mode = effective_speed,
+ transformer_quant = transformer_quant_engaged,
+ gguf_transformer = gguf_transformer,
+ offload_policy = effective_policy,
+ transformer_cache = cache_engaged,
+ cache_auto = cache_may_toggle,
+ target = target,
+ )
+ )
+ load_bg_compile = (
+ bg_compile.arm(bg_module, logger = logger) if bg_module is not None else None
+ )
state = _LoadState(
pipe = pipe,
family = fam,
@@ -7044,6 +7113,7 @@ class DiffusionBackend:
eager_patched = eager_patched,
speed_deferred = speed_deferred,
compile_cache_ctx = compile_ctx,
+ bg_compile = load_bg_compile,
hf_token = hf_token,
resolved = resolved,
gguf_filename = gguf_filename,
@@ -7065,6 +7135,10 @@ class DiffusionBackend:
finally:
# Pre-commit failure: roll back the process-wide mutations (symmetric with _unload_locked).
if not state_committed:
+ # First: its gate sits in front of the CUDA-graph layer uninstalled by identity below.
+ if load_bg_compile is not None:
+ load_bg_compile.close()
+ load_bg_compile = None
restore_backend_flags(backend_flags_before)
compile_cache.restore(compile_ctx, logger = logger)
gguf_compile.uninstall_all() # idempotent
@@ -8542,10 +8616,26 @@ class DiffusionBackend:
or "speed tier does not capture"
)
)
+ bg_module = _bg_compile_module(
+ state.pipe,
+ speed_optims = state.speed_optims,
+ speed_mode = SPEED_DEFAULT,
+ transformer_quant = state.transformer_quant,
+ gguf_transformer = gguf_transformer,
+ offload_policy = state.offload_policy,
+ transformer_cache = state.transformer_cache,
+ cache_auto = state.cache_auto,
+ target = target,
+ )
+ if bg_module is not None:
+ object.__setattr__(state, "bg_compile", bg_compile.arm(bg_module, logger = logger))
logger.info(
- "diffusion.speed: deferred profile engaged on generation 3 (optims=%s, attention=%s)",
+ "diffusion.speed: deferred profile engaged on generation 3 (optims=%s, attention=%s%s)",
",".join(state.speed_optims) or "none",
attention_engaged or "native",
+ "; compiling in the background, this render runs eager"
+ if state.bg_compile is not None
+ else "",
)
@_release_render_on_unload
@@ -8593,6 +8683,16 @@ class DiffusionBackend:
# Per-generation cancel Event that unload()/a superseding load set (under _lock) to abort just this denoise.
cancel = threading.Event()
with self._generation_slot(cancel):
+ # Never render beside a background compile; wait outside the state lock so status polls keep answering.
+ pending_bg = getattr(self._state, "bg_compile", None)
+ if pending_bg is not None and pending_bg.compiling():
+ logger.info(
+ "diffusion.bg_compile: render waits for the background compile to finish"
+ )
+ waited = pending_bg.wait(cancel)
+ logger.info(
+ "diffusion.bg_compile: render waited %.1f s for the background compile", waited
+ )
with self._lock:
state = self._state
if state is None:
@@ -8610,6 +8710,9 @@ class DiffusionBackend:
static_skip_pipe = None
restore_vae: Optional[Callable[[], None]] = None
restore_resident: Optional[Callable[[], None]] = None
+ bg = None
+ bg_eager = False
+ bg_token = None
try:
self._state_device_target(state)
# The local `state` ref keeps the pipe alive even if unload() nulls _state. Resolve the per-image
@@ -8645,6 +8748,12 @@ class DiffusionBackend:
exc,
)
+ # Compile still pending: this generation runs eager and records the denoiser inputs for it.
+ bg = state.bg_compile
+ bg_eager = bg is not None and bg.pending()
+ if bg_eager:
+ bg_token = bg_compile._FORCE_EAGER.set(True)
+
# Apply/adjust LoRA before picking the workflow pipe; from_pipe pipes share the transformer.
self._apply_loras(state, loras, cancel)
@@ -9196,28 +9305,36 @@ class DiffusionBackend:
# a STATIC compile makes new artifacts per (w,h,batch), so register this shape. The write itself is
# QUEUED, not performed: nothing in this response depends on it (only the NEXT process reads the
# bundle), so save_async hands it to the shared worker and the user stops waiting on it.
- try:
- # Register the dims the forward ACTUALLY compiled with, and every distinct chunk size (a static
- # compile makes one artifact per batch size too).
- reg_width, reg_height = _compile_shape_dims(
- workflow, init_pil, width, height, fam
- )
- static_shapes = "compiled" in (
- state.speed_optims or ()
- ) and compiled_shapes_are_static(state.pipe, state.speed_mode)
- for chunk_batch in sorted(set(chunk_shapes)):
- compile_cache.register_shape(
- state.compile_cache_ctx,
- (reg_width, reg_height, int(chunk_batch)),
- static = static_shapes,
+ if bg_eager:
+ # Nothing compiled ran, so nothing to register or save yet.
+ bg.note_eager_generation()
+ bg.kick()
+ else:
+ try:
+ # Register the dims the forward ACTUALLY compiled with, and every distinct chunk size (a static
+ # compile makes one artifact per batch size too).
+ reg_width, reg_height = _compile_shape_dims(
+ workflow, init_pil, width, height, fam
)
- if auto_dynamic_active(state.pipe) and fresh_compile_count() > graphs_before:
- # Automatic dynamic recompiles on the first new text length at an already-registered
- # (width, height, batch): persist those graphs too, or every fresh process pays them again.
- compile_cache.mark_recompiled(state.compile_cache_ctx)
- compile_cache.save_async(state.compile_cache_ctx, logger = logger)
- except Exception: # noqa: BLE001 - cache persistence is best-effort
- pass
+ static_shapes = "compiled" in (
+ state.speed_optims or ()
+ ) and compiled_shapes_are_static(state.pipe, state.speed_mode)
+ for chunk_batch in sorted(set(chunk_shapes)):
+ compile_cache.register_shape(
+ state.compile_cache_ctx,
+ (reg_width, reg_height, int(chunk_batch)),
+ static = static_shapes,
+ )
+ if (
+ auto_dynamic_active(state.pipe)
+ and fresh_compile_count() > graphs_before
+ ):
+ # Automatic dynamic recompiles on the first new text length at an already-registered
+ # (width, height, batch): persist those graphs too, or every fresh process pays them again.
+ compile_cache.mark_recompiled(state.compile_cache_ctx)
+ compile_cache.save_async(state.compile_cache_ctx, logger = logger)
+ except Exception: # noqa: BLE001 - cache persistence is best-effort
+ pass
# Last word on cancellation, AFTER the post-denoise work: the event stays registered through the
# compile-cache bookkeeping and the page still shows Stop for as long as progress reads active, so a Stop
# landing there was answered cancelled = true and then contradicted by the image the route persisted.
@@ -9277,6 +9394,8 @@ class DiffusionBackend:
)
return result
finally:
+ if bg_token is not None:
+ bg_compile._FORCE_EAGER.reset(bg_token)
if static_skip_pipe is not None:
try:
reset_static_step_skip(static_skip_pipe, None)
@@ -9437,6 +9556,12 @@ class DiffusionBackend:
state = self._state
if state is None:
return
+ # An in-flight background compile still runs the denoiser the teardown below frees.
+ if state.bg_compile is not None:
+ try:
+ state.bg_compile.close()
+ except Exception: # noqa: BLE001 - teardown is best effort
+ pass
# Restore the process-wide backend flags this load flipped so the next `off` load is bit-identical. All
# idempotent.
restore_backend_flags(state.backend_flags_before)
@@ -9541,6 +9666,7 @@ class DiffusionBackend:
"memory_mode": state.memory_mode,
"speed_mode": state.speed_mode,
"speed_optims": speed_optims,
+ "bg_compile": state.bg_compile.describe() if state.bg_compile is not None else None,
"text_encoder_quant": state.text_encoder_quant,
"transformer_quant": state.transformer_quant,
**_nvfp4_backend_fields(_transformer_quant_backend(state), owner = self),
diff --git a/studio/backend/core/inference/diffusion_bg_compile.py b/studio/backend/core/inference/diffusion_bg_compile.py
new file mode 100644
index 00000000000..f8cb9ef7d05
--- /dev/null
+++ b/studio/backend/core/inference/diffusion_bg_compile.py
@@ -0,0 +1,373 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Compile a dense denoiser in the background while the user's renders keep running eager.
+
+``arm`` records the first few distinct denoiser inputs of a render run under ``force_eager`` (read by every compile
+guard and CUDA-graph wrapper); ``kick`` replays them through the compiled callable on a daemon thread with CUDA-graph
+capture suppressed, so the next render pays only the capture. A render arriving mid-compile waits for it: a render
+beside the compile was starved to 49-62 s on a B200. Any failure ends the attempt and the next render compiles inline.
+
+Dense, non-offloaded denoisers only: torchao ones are ~30x slower eager, and offload hooks would fight two forwards.
+By default only the deferred profile (generation 3, already eager -> compiled) uses it; UNSLOTH_DIFFUSION_BG_COMPILE=1
+also moves a load's first-render compile (render 1 then differs from render 2 for one seed), =0 disables it.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import contextvars
+import os
+import threading
+import time
+from typing import Any, Callable, Optional
+
+_ENV = "UNSLOTH_DIFFUSION_BG_COMPILE"
+_MAX_SAMPLES = 4
+
+# ContextVars, not thread-locals: diffusion_render_thread.run copies the caller's context onto the render thread.
+_FORCE_EAGER: contextvars.ContextVar[bool] = contextvars.ContextVar(
+ "unsloth_diffusion_force_eager", default = False
+)
+_NO_CAPTURE: contextvars.ContextVar[bool] = contextvars.ContextVar(
+ "unsloth_diffusion_no_capture", default = False
+)
+
+
+def enabled() -> bool:
+ raw = (os.environ.get(_ENV) or "").strip().lower()
+ return raw not in ("0", "false", "no", "off")
+
+
+def load_time_enabled() -> bool:
+ """Opt-in (``=1``): render 1 eager and render 2 compiled would break "same seed twice repeats"."""
+ raw = (os.environ.get(_ENV) or "").strip().lower()
+ return raw in ("1", "true", "yes", "on", "all")
+
+
+def eager_forced() -> bool:
+ """True inside a generation that must not touch the compiled callable (its compile is still in flight)."""
+ return _FORCE_EAGER.get()
+
+
+def capture_suppressed() -> bool:
+ """True on the background compile thread: run compiled, never record a CUDA graph."""
+ return _NO_CAPTURE.get()
+
+
+def force_eager(on: bool = True):
+ token = _FORCE_EAGER.set(bool(on))
+ try:
+ yield
+ finally:
+ _FORCE_EAGER.reset(token)
+
+
+def _cuda_graph_helpers() -> tuple[Callable, Callable, Callable]:
+ from .diffusion_cuda_graph import _flatten, _rebuild, graph_key
+ return _flatten, _rebuild, graph_key
+
+
+def _capture_armed(module: Any) -> bool:
+ """Whether a live CUDA-graph wrapper sits on ``module`` (forward slot for a DiT, compiled slot for a U-Net)."""
+ try:
+ from .diffusion_cuda_graph import GraphedForward, _outer_layer
+ except Exception: # noqa: BLE001
+ return False
+ candidates = [getattr(module, "_compiled_call_impl", None), module.__dict__.get("forward")]
+ gate = candidates[0]
+ pair = getattr(gate, "_unsloth_bg_inner", None)
+ if pair is not None:
+ candidates.append(pair)
+ try:
+ outer = _outer_layer(module)
+ if outer is not None:
+ candidates.append(getattr(outer, "inner", None))
+ except Exception: # noqa: BLE001
+ pass
+ return any(
+ isinstance(c, GraphedForward) and c.enabled and not c.poisoned and not c.bypassed
+ for c in candidates
+ )
+
+
+class BackgroundCompile:
+ """One armed denoiser: records eager inputs, then compiles from them on a daemon thread."""
+
+ def __init__(
+ self,
+ module: Any,
+ *,
+ logger: Any = None,
+ max_samples: int = _MAX_SAMPLES,
+ ) -> None:
+ self.module = module
+ self.logger = logger
+ self.max_samples = int(max_samples)
+ self.samples: list[tuple] = []
+ self._keys: set = set()
+ self._handle: Any = None
+ self._gate: Optional[tuple] = None
+ self._thread: Optional[threading.Thread] = None
+ self._lock = threading.Lock()
+ self._closed = threading.Event()
+ # recording -> compiling -> done | failed
+ self.state = "recording"
+ self.error: Optional[str] = None
+ self.compile_s: Optional[float] = None
+ self.eager_generations = 0
+
+ def install(self) -> bool:
+ try:
+ self._install_gate()
+ self._handle = self.module.register_forward_pre_hook(self._record, with_kwargs = True)
+ return True
+ except Exception as exc: # noqa: BLE001 - no hook, no background compile
+ self._finish("failed", f"pre-hook: {type(exc).__name__}: {exc}")
+ self._remove_gate()
+ return False
+
+ def _install_gate(self) -> None:
+ """``Module.compile`` serves every call from ``_compiled_call_impl``: route it eager under ``force_eager``."""
+ inner = getattr(self.module, "_compiled_call_impl", None)
+ if inner is None:
+ return
+ eager = self.module._call_impl
+
+ def gate(*args: Any, **kwargs: Any) -> Any:
+ if _FORCE_EAGER.get():
+ return eager(*args, **kwargs)
+ return inner(*args, **kwargs)
+
+ gate._unsloth_bg_gate = True # type: ignore[attr-defined]
+ gate._unsloth_bg_inner = inner # type: ignore[attr-defined]
+ self.module._compiled_call_impl = gate
+ self._gate = (gate, inner)
+
+ def _remove_gate(self) -> None:
+ pair, self._gate = self._gate, None
+ if pair is None or self.module is None:
+ return
+ gate, inner = pair
+ try:
+ if getattr(self.module, "_compiled_call_impl", None) is gate:
+ self.module._compiled_call_impl = inner
+ except Exception: # noqa: BLE001
+ pass
+
+ def _record(self, module: Any, args: tuple, kwargs: dict) -> None:
+ if not eager_forced() or len(self.samples) >= self.max_samples or self.state != "recording":
+ return None
+ try:
+ import torch
+
+ _flatten, _rebuild, graph_key = _cuda_graph_helpers()
+ key = graph_key((args, kwargs))
+ if key in self._keys:
+ return None
+ live: list = []
+ spec = _flatten((args, kwargs), live)
+ if _capture_armed(module):
+ # Like the capture's static buffers (made outside inference mode): dynamo guards on inference-ness.
+ with torch.inference_mode(False):
+ clones = [torch.empty_like(t) for t in live]
+ for dst, src in zip(clones, live):
+ dst.copy_(src)
+ else:
+ clones = [t.detach().clone() for t in live]
+ self._keys.add(key)
+ self.samples.append(
+ (
+ spec,
+ clones,
+ bool(torch.is_inference_mode_enabled()),
+ bool(torch.is_grad_enabled()),
+ torch.cuda.current_device() if torch.cuda.is_available() else None,
+ )
+ )
+ except Exception as exc: # noqa: BLE001 - an uncloneable tree just means no background compile
+ self.state = "failed"
+ self.error = f"record: {type(exc).__name__}: {exc}"
+ return None
+
+ def _remove_hook(self) -> None:
+ handle, self._handle = self._handle, None
+ if handle is not None:
+ try:
+ handle.remove()
+ except Exception: # noqa: BLE001
+ pass
+
+ def pending(self) -> bool:
+ return self.state in ("recording", "compiling")
+
+ def note_eager_generation(self) -> None:
+ self.eager_generations += 1
+
+ def compiling(self) -> bool:
+ thread = self._thread
+ return self.state == "compiling" and thread is not None and thread.is_alive()
+
+ def wait(
+ self,
+ cancel: Any = None,
+ poll_s: float = 0.25,
+ ) -> float:
+ """Block until an in-flight background compile ends; returns the seconds waited. ``cancel`` aborts the wait."""
+ t0 = time.perf_counter()
+ thread = self._thread
+ if thread is None or thread is threading.current_thread():
+ return 0.0
+ while thread.is_alive():
+ if cancel is not None and cancel.is_set():
+ break
+ thread.join(poll_s)
+ return time.perf_counter() - t0
+
+ def kick(self) -> bool:
+ """Start the background compile once samples exist. Idempotent; returns whether a thread is running."""
+ with self._lock:
+ if self.state == "compiling":
+ return True
+ if self.state != "recording":
+ self._remove_hook()
+ return False
+ if not self.samples:
+ # The generation never reached the denoiser (cancelled / failed early): keep recording.
+ return False
+ # Before the thread starts: the compiled trace must not contain the hook.
+ self._remove_hook()
+ self.state = "compiling"
+ self._thread = threading.Thread(
+ target = self._run, name = "unsloth-diffusion-bg-compile", daemon = True
+ )
+ self._thread.start()
+ return True
+
+ def _finish(
+ self,
+ state: str,
+ error: Optional[str] = None,
+ ) -> None:
+ self.state = state
+ self.error = error
+ self.samples = []
+ self._remove_hook()
+
+ def _run(self) -> None:
+ t0 = time.perf_counter()
+ token = _NO_CAPTURE.set(True)
+ try:
+ import torch
+
+ from . import diffusion_compile_config
+
+ # torch 2.12+ keeps compile config per context: a fresh thread would compile without the recorded knobs.
+ diffusion_compile_config.apply()
+ _flatten, _rebuild, graph_key = _cuda_graph_helpers()
+ for spec, clones, inference, grad, device in list(self.samples):
+ if self._closed.is_set():
+ self._finish("failed", "closed before the compile finished")
+ return
+ if device is not None:
+ torch.cuda.set_device(device)
+ args, kwargs = _rebuild(spec, clones)
+ mode = torch.inference_mode() if inference else torch.set_grad_enabled(grad)
+ with mode:
+ self.module(*args, **kwargs)
+ if torch.cuda.is_available():
+ torch.cuda.synchronize()
+ self.compile_s = time.perf_counter() - t0
+ self._finish("done")
+ if self.logger is not None:
+ self.logger.info(
+ "diffusion.bg_compile: %s compiled in the background in %.1f s; the next render runs compiled",
+ type(self.module).__name__,
+ self.compile_s,
+ )
+ except BaseException as exc: # noqa: BLE001 - never kills the process; the next render compiles inline
+ self.compile_s = time.perf_counter() - t0
+ self._finish(
+ "failed",
+ f"{type(exc).__name__}: {str(exc).splitlines()[0][:300] if str(exc) else ''}",
+ )
+ if self.logger is not None:
+ self.logger.warning(
+ "diffusion.bg_compile: background compile of %s failed after %.1f s (%s); the next render "
+ "compiles inline",
+ type(self.module).__name__,
+ self.compile_s,
+ self.error,
+ )
+ exc.__traceback__ = None
+ finally:
+ _NO_CAPTURE.reset(token)
+
+ def close(self, timeout: Optional[float] = None) -> None:
+ """Stop recording and wait for an in-flight compile (it holds the module); used on unload."""
+ self._closed.set()
+ self._remove_hook()
+ thread = self._thread
+ if thread is not None and thread.is_alive() and thread is not threading.current_thread():
+ if self.logger is not None:
+ self.logger.info(
+ "diffusion.bg_compile: waiting for the background compile before unloading"
+ )
+ thread.join(timeout)
+ if self.pending():
+ self._finish("failed", "closed")
+ # Unload uninstalls the CUDA-graph layer by identity: the gate in front of it goes first.
+ self._remove_gate()
+ self.module = None
+
+ def describe(self) -> dict:
+ return {
+ "state": self.state,
+ "samples": len(self.samples),
+ "compile_s": None if self.compile_s is None else round(self.compile_s, 2),
+ "eager_generations": self.eager_generations,
+ "error": self.error,
+ }
+
+
+def select_module(
+ pipe: Any,
+ *,
+ speed_optims: Any,
+ default_tier: bool,
+ quantized: bool,
+ gguf: bool,
+ step_cache: bool,
+ device: Any,
+ backend: Any,
+ denoiser_hooked: bool,
+) -> Any:
+ """The one dense, resident, default-tier CUDA denoiser whose compile may move off the render, or None.
+
+ Not torchao (~30x slower eager), GGUF (compiles only its dequant), a step cache (toggles graphs per step),
+ max-autotune (an explicit request to pay the compile) or an offloaded denoiser."""
+ if not enabled():
+ return None
+ if "compiled" not in tuple(speed_optims or ()) or not default_tier:
+ return None
+ if quantized or gguf or step_cache or denoiser_hooked:
+ return None
+ if device != "cuda" or backend == "rocm":
+ return None
+ try:
+ from .diffusion_cuda_graph import _denoiser_modules
+ modules = _denoiser_modules(pipe)
+ except Exception: # noqa: BLE001
+ return None
+ return modules[0] if len(modules) == 1 else None
+
+
+def arm(module: Any, *, logger: Any = None) -> Optional[BackgroundCompile]:
+ """A recording ``BackgroundCompile`` on ``module``, or None (disabled / no hook)."""
+ if module is None or not enabled():
+ return None
+ bg = BackgroundCompile(module, logger = logger)
+ if not bg.install():
+ return None
+ return bg
diff --git a/studio/backend/core/inference/diffusion_cuda_graph.py b/studio/backend/core/inference/diffusion_cuda_graph.py
index 59ab84f1135..5537d4311f7 100644
--- a/studio/backend/core/inference/diffusion_cuda_graph.py
+++ b/studio/backend/core/inference/diffusion_cuda_graph.py
@@ -20,6 +20,9 @@ import weakref
from functools import update_wrapper
from typing import Any, Optional
+from .diffusion_bg_compile import capture_suppressed as _bg_capture_suppressed
+from .diffusion_bg_compile import eager_forced as _bg_eager_forced
+
CUDA_GRAPH_DISABLE_ENV = "UNSLOTH_DISABLE_CUDA_GRAPH"
# Per module. Legitimate second keys exist, but each costs a pool-sized slice of VRAM.
@@ -433,8 +436,12 @@ class GraphedForward:
return self.orig(*args, **kwargs)
def __call__(self, *args, **kwargs):
+ if _bg_capture_suppressed():
+ # Background compile thread: never capture off the render thread.
+ return self.orig(*args, **kwargs)
if (
not self.enabled
+ or _bg_eager_forced()
or self.bypassed
or self.poisoned
# Belt to the caller's per-chunk bypass: one step's cond and uncond share a key.
diff --git a/studio/backend/core/inference/diffusion_memory.py b/studio/backend/core/inference/diffusion_memory.py
index 2651f7bfe06..e714658e97e 100644
--- a/studio/backend/core/inference/diffusion_memory.py
+++ b/studio/backend/core/inference/diffusion_memory.py
@@ -2652,6 +2652,102 @@ def _offload_groups(module: Any) -> list:
return groups
+# Video loads only. "0" restores the per-tensor ``pin_memory()``.
+FAST_PIN_ENV = "UNSLOTH_VIDEO_FAST_PIN"
+_FAST_PIN_REQUEST_ATTR = "_unsloth_fast_pin_requested"
+_FAST_PIN_THREADS = 8
+
+
+def request_fast_pins(pipe: Any) -> None:
+ """Ask the background pinners of ``pipe`` to use registered host memory."""
+ try:
+ setattr(pipe, _FAST_PIN_REQUEST_ATTR, True)
+ except Exception: # noqa: BLE001 - a pipe refusing attributes pins the default way
+ pass
+
+
+def _fast_pin_supported() -> bool:
+ if (os.environ.get(FAST_PIN_ENV) or "").strip().lower() in ("0", "off", "false", "no"):
+ return False
+ # WDDM / WSL2 cap page-locked memory; ROCm's register path is unmeasured.
+ if not sys.platform.startswith("linux") or _pinned_memory_capped():
+ return False
+ try:
+ import torch
+
+ if getattr(torch.version, "hip", None) or not torch.cuda.is_available():
+ return False
+ cudart = torch.cuda.cudart()
+ return hasattr(cudart, "cudaHostRegister") and hasattr(cudart, "cudaHostUnregister")
+ except Exception: # noqa: BLE001
+ return False
+
+
+class _RegisteredHostBuffer:
+ """Anonymous mapping page-locked with ``cudaHostRegister``; tensor views keep it alive, the last one unregisters it.
+
+ Torch's pinned allocator pins on one thread (10.9-13.1 s for LTX-2.3's 24.6 GiB Gemma3); 8 threads + register: 2.3 s."""
+
+ def __init__(self, nbytes: int):
+ import ctypes
+ import mmap
+
+ import torch
+
+ self._cudart = torch.cuda.cudart()
+ self._size = max(int(nbytes), 1)
+ self._map = mmap.mmap(-1, self._size)
+ self._anchor = ctypes.c_char.from_buffer(self._map)
+ self.ptr = ctypes.addressof(self._anchor)
+ self._registered = False
+ self._device: Optional[int] = None
+ self.__array_interface__ = {
+ "shape": (int(nbytes),),
+ "typestr": "|u1",
+ "data": (self.ptr, False),
+ "version": 3,
+ }
+
+ def register(self) -> None:
+ err = self._cudart.cudaHostRegister(self.ptr, self._size, 0)
+ if int(err) != 0:
+ raise RuntimeError(f"cudaHostRegister failed ({err})")
+ import torch
+
+ # A bare synchronize() on another thread would wait on (and open a context on) device 0.
+ self._device = torch.cuda.current_device()
+ self._registered = True
+
+ def __del__(self) -> None:
+ try:
+ if self._registered:
+ import torch
+
+ # An async upload may still read these pages; never unmap under it.
+ torch.cuda.synchronize(self._device)
+ self._cudart.cudaHostUnregister(self.ptr)
+ self._registered = False
+ except Exception: # noqa: BLE001 - interpreter teardown
+ pass
+ try:
+ del self._anchor
+ self._map.close()
+ except Exception: # noqa: BLE001
+ pass
+
+
+def registered_host_copy(src: Any) -> Any:
+ """A contiguous copy of host tensor ``src`` in CUDA-registered (pinned) memory."""
+ import numpy as np
+ import torch
+
+ holder = _RegisteredHostBuffer(src.numel() * src.element_size())
+ out = torch.from_numpy(np.asarray(holder)).view(src.dtype).view(src.shape)
+ out.copy_(src)
+ holder.register()
+ return out
+
+
class _GroupPinner:
"""Pins a streamed module's offload groups on a worker thread, first block first.
@@ -2666,9 +2762,11 @@ class _GroupPinner:
groups: list,
device: Any,
logger: Any = None,
+ fast: bool = False,
):
import threading
+ self.fast = bool(fast)
self.module = module
self.label = type(module).__name__
self.groups = groups
@@ -2729,6 +2827,13 @@ class _GroupPinner:
and not src.is_pinned()
]
+ @staticmethod
+ def _fast_result(future: Any, src: Any) -> Any:
+ try:
+ return future.result()
+ except Exception: # noqa: BLE001 - registration refused: the allocator's pin for this tensor
+ return src.pin_memory()
+
def _run(self) -> None:
import time
@@ -2736,17 +2841,43 @@ class _GroupPinner:
start = time.perf_counter()
failed = None
+ pool = None
try:
if (
getattr(self.device, "type", None) == "cuda"
and getattr(self.device, "index", None) is not None
):
torch.cuda.set_device(self.device)
+ copies: dict = {}
+ if self.fast:
+ from concurrent.futures import ThreadPoolExecutor
+
+ # Queued in group order, so the first group is ready first.
+ pool = ThreadPoolExecutor(
+ max_workers = _FAST_PIN_THREADS,
+ thread_name_prefix = "unsloth-fast-pin",
+ initializer = torch.cuda.set_device,
+ initargs = (torch.cuda.current_device(),),
+ )
+ for group in self.groups:
+ copies[id(group)] = [
+ (tensor, src, pool.submit(registered_host_copy, src))
+ for tensor, src in self._unpinned(group)
+ ]
for group in self.groups:
if self._stop.is_set():
break
- # One pin per tensor, exactly what the eager apply makes: chunk views streamed ~10% slower on LTX-2.3.
- placed = [(tensor, src, src.pin_memory()) for tensor, src in self._unpinned(group)]
+ if self.fast:
+ placed = [
+ (tensor, src, self._fast_result(future, src))
+ for tensor, src, future in copies.pop(id(group))
+ ]
+ else:
+ # One pin per tensor, exactly what the eager apply makes: chunk views streamed ~10% slower on
+ # LTX-2.3.
+ placed = [
+ (tensor, src, src.pin_memory()) for tensor, src in self._unpinned(group)
+ ]
cpu = group.cpu_param_dict
for tensor, src, pinned in placed:
if cpu.get(tensor) is src:
@@ -2758,6 +2889,8 @@ class _GroupPinner:
except Exception as exc: # noqa: BLE001 - diffusers pins what is left on each onload
failed = exc
finally:
+ if pool is not None:
+ pool.shutdown(wait = True, cancel_futures = True)
for event in self._done.values():
event.set()
if self.logger is not None:
@@ -2770,11 +2903,12 @@ class _GroupPinner:
)
self.logger.info(
"diffusion.memory: pinned %.1f GiB of %s host weights in the background in %.1f s "
- "(onloads waited %.1f s)",
+ "(onloads waited %.1f s%s)",
self.pinned / 2**30,
self.label,
time.perf_counter() - start,
self.waited_s,
+ ", registered" if self.fast else "",
)
except Exception: # noqa: BLE001
pass
@@ -2850,7 +2984,8 @@ def _defer_pinning(pipe: Any, module: Any, device: Any, logger: Any) -> bool:
groups = _offload_groups(module)
if not groups:
return False
- pinner = _GroupPinner(module, groups, device, logger)
+ fast = bool(getattr(pipe, _FAST_PIN_REQUEST_ATTR, False)) and _fast_pin_supported()
+ pinner = _GroupPinner(module, groups, device, logger, fast = fast)
pending = getattr(pipe, _PENDING_PINS_ATTR, None)
if pending is None:
pending = []
diff --git a/studio/backend/core/inference/diffusion_prequant.py b/studio/backend/core/inference/diffusion_prequant.py
index d22749586d1..2ccb68f8a08 100644
--- a/studio/backend/core/inference/diffusion_prequant.py
+++ b/studio/backend/core/inference/diffusion_prequant.py
@@ -347,6 +347,40 @@ def _load_prequant_checkpoint(path: str, **kwargs: Any) -> Any:
return _torch_load_prequant(path, **kwargs)
+# 0 reads a pickle checkpoint headed for an accelerator into host memory instead of mapping it.
+_PREQUANT_MMAP_ENV = "UNSLOTH_DIFFUSION_PREQUANT_MMAP"
+
+
+def prequant_mmap_enabled(destination: Any) -> bool:
+ """Map only for a non-CPU destination: a host-placed module would keep the file open (Windows then cannot delete it)."""
+ import os
+
+ raw = (os.environ.get(_PREQUANT_MMAP_ENV) or "").strip().lower()
+ if raw in ("0", "false", "no", "off"):
+ return False
+ dest = str(destination or "").strip().lower()
+ return bool(dest) and not dest.startswith("cpu") and dest != "meta"
+
+
+def _read_prequant_for(
+ path: str,
+ destination: Any,
+ logger: Any = None,
+) -> Any:
+ """``_load_prequant_checkpoint`` mapped when enabled; anything the mapping cannot open is re-read in full."""
+ if prequant_mmap_enabled(destination):
+ try:
+ return _load_prequant_checkpoint(path, map_location = "cpu", mmap = True)
+ except Exception as exc: # noqa: BLE001 - retried unmapped; the real error resurfaces there
+ if logger is not None:
+ logger.info(
+ "diffusion.prequant: mapped read failed (%s: %s); reading the checkpoint into memory",
+ type(exc).__name__,
+ str(exc).splitlines()[0][:200] if str(exc) else "",
+ )
+ return _load_prequant_checkpoint(path, map_location = "cpu")
+
+
_PREQUANT_TOGGLE_TOKENS = {"1", "true", "yes", "on", "0", "false", "no", "off"}
@@ -1157,7 +1191,7 @@ def load_prequantized_transformer(
# mutable, fetched over the network, and reached by loads that never asked for one (auto resolves an unset
# precision to a hosted checkpoint), so a mutated file must fail to load rather than run. Both containers
# hand back the same dict, so every check below applies to them equally.
- ckpt = _load_prequant_checkpoint(path, map_location = "cpu")
+ ckpt = _read_prequant_for(path, placement_device or device, logger)
if not _validate_checkpoint(
ckpt,
scheme,
diff --git a/studio/backend/core/inference/diffusion_probe_cache.py b/studio/backend/core/inference/diffusion_probe_cache.py
new file mode 100644
index 00000000000..83323e2e58d
--- /dev/null
+++ b/studio/backend/core/inference/diffusion_probe_cache.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
+
+"""Persist the transformer-quant smoke-probe verdicts across processes (4-5 s of every cold quantised load).
+
+Only a clean child table is stored, keyed by everything a verdict depends on (torch / CUDA / torchao / triton, driver,
+card UUID + capability, the probe sources, the quant env). Any difference, or a torn file, is a miss that runs the
+child as before. UNSLOTH_DIFFUSION_PROBE_CACHE=0 disables read and write.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import os
+import threading
+import time
+from pathlib import Path
+from typing import Any, Optional
+
+_ENV = "UNSLOTH_DIFFUSION_PROBE_CACHE"
+_FILE_NAME = "diffusion_quant_probe.json"
+_FORMAT = 1
+_MAX_ENTRIES = 32
+# Env prefixes that can change a verdict.
+_ENV_PREFIXES = ("UNSLOTH_DIFFUSION_", "UNSLOTH_NVFP4", "UNSLOTH_INT8", "TORCHAO", "TORCHINDUCTOR_")
+_ENV_IGNORED = frozenset({_ENV, "UNSLOTH_DIFFUSION_COMPILE_CACHE_DIR", "TORCHINDUCTOR_CACHE_DIR"})
+# Any edit to these invalidates every entry.
+_PROBE_SOURCES = (
+ "diffusion_transformer_quant.py",
+ "diffusion_torchao_patches.py",
+ "diffusion_native_quant.py",
+)
+
+_LOCK = threading.Lock()
+_SOURCE_DIGEST: Optional[str] = None
+
+
+def enabled() -> bool:
+ raw = (os.environ.get(_ENV) or "").strip().lower()
+ return raw not in ("0", "false", "no", "off")
+
+
+def _cache_file() -> Optional[Path]:
+ try:
+ from utils.paths.storage_roots import cache_root
+ except ImportError:
+ return None
+ try:
+ return Path(cache_root()) / _FILE_NAME
+ except Exception: # noqa: BLE001 - no resolvable root is a miss
+ return None
+
+
+def _source_digest() -> str:
+ global _SOURCE_DIGEST
+ if _SOURCE_DIGEST is None:
+ h = hashlib.sha256()
+ here = Path(__file__).resolve().parent
+ for name in _PROBE_SOURCES:
+ try:
+ h.update(name.encode())
+ h.update((here / name).read_bytes())
+ except OSError:
+ h.update(b"<missing>")
+ _SOURCE_DIGEST = h.hexdigest()
+ return _SOURCE_DIGEST
+
+
+def _version(module: str) -> Optional[str]:
+ try:
+ from importlib.metadata import version
+ return version(module)
+ except Exception: # noqa: BLE001
+ return None
+
+
+def _ordinal(card: str) -> Optional[int]:
+ if card == "cuda":
+ return None
+ if card.startswith("cuda:"):
+ try:
+ return int(card.split(":", 1)[1])
+ except ValueError:
+ return None
+ return None
+
+
+def fingerprint(card: str) -> Optional[dict[str, Any]]:
+ """Everything a verdict for ``card`` depends on, or None. Creates no CUDA context."""
+ if not str(card).startswith("cuda"):
+ return None
+ try:
+ import torch
+
+ if not torch.cuda.is_available():
+ return None
+ ordinal = _ordinal(str(card))
+ index = torch.cuda.current_device() if ordinal is None else ordinal
+ props = torch.cuda.get_device_properties(index)
+ uuid = str(getattr(props, "uuid", "") or "")
+ if not uuid:
+ return None
+ driver = None
+ get_driver = getattr(torch._C, "_cuda_getDriverVersion", None)
+ if callable(get_driver):
+ try:
+ driver = int(get_driver())
+ except Exception: # noqa: BLE001
+ driver = None
+ env = {
+ k: v
+ for k, v in sorted(os.environ.items())
+ if k.startswith(_ENV_PREFIXES) and k not in _ENV_IGNORED
+ }
+ return {
+ "format": _FORMAT,
+ "torch": str(torch.__version__),
+ "torch_cuda": str(torch.version.cuda),
+ "hip": str(getattr(torch.version, "hip", None)),
+ "torchao": _version("torchao"),
+ "triton": _version("triton"),
+ "driver": driver,
+ "gpu_name": str(props.name),
+ "gpu_uuid": uuid,
+ "capability": f"{props.major}.{props.minor}",
+ "probe_source": _source_digest(),
+ "env": env,
+ }
+ except Exception: # noqa: BLE001 - unidentifiable card: never persisted
+ return None
+
+
+def _key(fp: dict[str, Any]) -> str:
+ return hashlib.sha256(json.dumps(fp, sort_keys = True).encode()).hexdigest()[:32]
+
+
+def _read_all(path: Path) -> dict[str, Any]:
+ try:
+ data = json.loads(path.read_text(encoding = "utf-8"))
+ except Exception: # noqa: BLE001 - absent / torn / unreadable reads as empty
+ return {}
+ return data if isinstance(data, dict) else {}
+
+
+def load(card: str) -> Optional[dict[str, bool]]:
+ """The persisted verdict table for ``card`` in this exact environment, or None."""
+ if not enabled():
+ return None
+ path = _cache_file()
+ fp = fingerprint(card)
+ if path is None or fp is None:
+ return None
+ entry = _read_all(path).get(_key(fp))
+ if not isinstance(entry, dict) or entry.get("fingerprint") != fp:
+ return None
+ verdicts = entry.get("verdicts")
+ if not isinstance(verdicts, dict):
+ return None
+ table = {str(k): v for k, v in verdicts.items() if isinstance(v, bool)}
+ return table or None
+
+
+def store(card: str, table: dict[str, Any]) -> bool:
+ """Persist the definite (bool) verdicts of a clean child table. Best-effort; returns whether it was written."""
+ if not enabled() or not isinstance(table, dict):
+ return False
+ verdicts = {str(k): v for k, v in table.items() if isinstance(v, bool)}
+ # No scheme passed: a busy / unavailable device fails every scheme alike, so nothing durable was learned.
+ if not any(verdicts.values()):
+ return False
+ path = _cache_file()
+ fp = fingerprint(card)
+ if path is None or fp is None:
+ return False
+ with _LOCK:
+ try:
+ data = _read_all(path)
+ data[_key(fp)] = {"fingerprint": fp, "verdicts": verdicts, "t": time.time()}
+ if len(data) > _MAX_ENTRIES:
+ oldest = sorted(
+ data,
+ key = lambda k: (data[k] or {}).get("t", 0) if isinstance(data[k], dict) else 0,
+ )
+ for k in oldest[: len(data) - _MAX_ENTRIES]:
+ data.pop(k, None)
+ path.parent.mkdir(parents = True, exist_ok = True)
+ tmp = path.with_name(f".{path.name}.{os.getpid()}.{threading.get_ident()}.tmp")
+ tmp.write_text(json.dumps(data, sort_keys = True), encoding = "utf-8")
+ os.replace(tmp, path)
+ return True
+ except Exception: # noqa: BLE001 - a cache write never fails a load
+ try:
+ tmp.unlink() # type: ignore[possibly-undefined]
+ except Exception: # noqa: BLE001
+ pass
+ return False
diff --git a/studio/backend/core/inference/diffusion_speed.py b/studio/backend/core/inference/diffusion_speed.py
index fdd4faec045..977b487c82e 100644
--- a/studio/backend/core/inference/diffusion_speed.py
+++ b/studio/backend/core/inference/diffusion_speed.py
@@ -43,6 +43,7 @@ from functools import lru_cache
from typing import Any, Iterator, Optional
from . import diffusion_compile_config as compile_config
+from .diffusion_bg_compile import eager_forced as _bg_eager_forced
from . import diffusion_gguf_compile as gguf_compile
SPEED_OFF = "off"
@@ -1095,7 +1096,8 @@ class _CompileGuard:
guard = self
def guarded(*args: Any, **kwargs: Any) -> Any:
- if guard.error is None:
+ # Compile still in flight in the background: entering it here would compile inline.
+ if guard.error is None and not _bg_eager_forced():
compile_config.apply()
try:
return compiled(*args, **kwargs)
diff --git a/studio/backend/core/inference/diffusion_transformer_quant.py b/studio/backend/core/inference/diffusion_transformer_quant.py
index 23d45078861..23596a1edd2 100644
--- a/studio/backend/core/inference/diffusion_transformer_quant.py
+++ b/studio/backend/core/inference/diffusion_transformer_quant.py
@@ -1268,7 +1268,9 @@ def _scheme_supported(
# Re-checked under the lock: the route answers plans concurrently, and a burst of them must not each spawn
# a child that imports torch.
if (scheme, card) not in _SMOKE_CACHE:
- table = _child_probe_table(card)
+ table = _persisted_probe_table(card)
+ if table is None or scheme not in table:
+ table = _child_probe_table(card)
if table is not None:
for name, child_verdict in table.items():
# None is the child's out-of-memory: not a verdict, so not cached.
@@ -1403,7 +1405,64 @@ def _child_probe_table(device: str) -> Optional[dict[str, Optional[bool]]]:
break
finally:
_close_probe_child(proc, queue)
- return table if isinstance(table, dict) else _crashed_child_verdict(proc, device)
+ if isinstance(table, dict):
+ try:
+ from . import diffusion_probe_cache
+ diffusion_probe_cache.store(device, table)
+ except Exception: # noqa: BLE001 - persistence is best-effort
+ pass
+ return table
+ return _crashed_child_verdict(proc, device)
+
+
+def prewarm_probe_table(device: str = "cuda") -> bool:
+ """Resolve and persist this card's smoke-probe table at boot; True iff a child probe ran.
+
+ A load arriving mid-probe waits on the same lock and reads these verdicts. ``UNSLOTH_DIFFUSION_PROBE_PREWARM=0``
+ disables it."""
+ if (_os.environ.get("UNSLOTH_DIFFUSION_PROBE_PREWARM") or "").strip().lower() in (
+ "0",
+ "false",
+ "no",
+ "off",
+ ):
+ return False
+ try:
+ from . import diffusion_probe_cache
+
+ if not diffusion_probe_cache.enabled():
+ return False
+ import torch
+
+ if not torch.cuda.is_available():
+ return False
+ except Exception: # noqa: BLE001
+ return False
+ card = _smoke_cache_device_key(device)
+ schemes = without_nvfp4(TQ_SCHEMES)
+ if any((scheme, card) in _SMOKE_CACHE for scheme in schemes):
+ return False
+ if _persisted_probe_table(card) is not None:
+ return False
+ with _CHILD_PROBE_LOCK:
+ if any((scheme, card) in _SMOKE_CACHE for scheme in schemes):
+ return False
+ table = _child_probe_table(card)
+ if table is None:
+ return False
+ for name, verdict in table.items():
+ if verdict is not None:
+ _SMOKE_CACHE[(name, card)] = verdict
+ return True
+
+
+def _persisted_probe_table(card: str) -> Optional[dict[str, bool]]:
+ """A previous process's clean child table for this card and stack, or None."""
+ try:
+ from . import diffusion_probe_cache
+ return diffusion_probe_cache.load(card)
+ except Exception: # noqa: BLE001 - a miss, never an error
+ return None
# SIGKILL may be OOM and SIGTERM is timeout cleanup, so neither is a scheme verdict.
diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.py
index c48135d6780..b25f7fab4f6 100644
--- a/studio/backend/core/inference/video.py
+++ b/studio/backend/core/inference/video.py
@@ -110,6 +110,7 @@ from .diffusion_memory import (
finish_background_pins,
release_pinned_host_memory,
request_background_pins,
+ request_fast_pins,
safetensors_prefix_mib,
settled_snapshot_device_memory,
start_background_pins,
@@ -964,6 +965,21 @@ def _ensure_mp4_encoder_available() -> None:
) from exc
+def _video_denoiser_hooked(pipe: Any) -> bool:
+ """Whether an offload hook moves one of ``pipe``'s denoisers."""
+ for name in ("transformer", "transformer_2"):
+ module = getattr(pipe, name, None)
+ if module is None:
+ continue
+ if getattr(module, "_hf_hook", None) is not None:
+ return True
+ registry = getattr(module, "_diffusers_hook", None)
+ hooks = getattr(registry, "hooks", None) or {}
+ if any("offload" in str(key) for key in hooks):
+ return True
+ return False
+
+
@dataclass(frozen = True)
class _VideoLoadState:
"""Everything about the currently-loaded video pipeline, swapped as one unit."""
@@ -1025,6 +1041,7 @@ class _VideoLoadState:
# MiniMax-H3: video_minimax_h3_residency.H3Residency of a streamed denoiser, re-fitted per request.
h3_residency: Any = None
resolved: Optional[dict] = None
+ bg_compile: Any = None
@dataclass(frozen = True)
@@ -2335,6 +2352,42 @@ def _video_family_capabilities() -> tuple[tuple[str, ...], tuple[str, ...]]:
)
+def _return_direct_loaded_modules(
+ pipe: Any,
+ plan: Any,
+ logger: Any = None,
+) -> None:
+ """Move what the LTX-2.3 direct load put on the card back to the host when a refined ``plan`` offloads it."""
+ try:
+ import torch
+ if not plan_keeps_transformer_resident(plan):
+ moved = ["pipeline"]
+ pipe.to("cpu")
+ elif getattr(plan, "offload_policy", OFFLOAD_NONE) != OFFLOAD_NONE and bool(
+ getattr(plan, "stream_text_encoders", False)
+ ):
+ moved = []
+ for name, comp in getattr(pipe, "components", {}).items():
+ if not name.startswith("text_encoder") or not isinstance(comp, torch.nn.Module):
+ continue
+ if any(p.device.type != "cpu" for p in comp.parameters()):
+ comp.to("cpu")
+ moved.append(name)
+ else:
+ return
+ if moved and logger is not None:
+ logger.info(
+ "video.ltx23_direct_load: plan %s offloads %s; moved back to the host",
+ _video_plan_label(plan),
+ ", ".join(moved),
+ )
+ except Exception as exc: # noqa: BLE001 - placement below still applies the plan
+ if logger is not None:
+ logger.warning(
+ "video.ltx23_direct_load: could not return modules to the host (%s)", exc
+ )
+
+
class VideoBackend:
"""One loaded video pipeline; loads swap it atomically (same model as images)."""
@@ -5698,6 +5751,7 @@ class VideoBackend:
_nvfp4_install_wanted, denoiser_seed_scheme, device, local_files_only = local_files_only
)
denoiser_injected: dict[str, Any] = {}
+ ltx23_direct_loaded = False
if denoiser_seed_scheme is not None:
from .video_denoiser_prequant import denoiser_prequant_pipe_kwargs
@@ -5773,7 +5827,7 @@ class VideoBackend:
sf_kwargs["quantization_config"] = diffusers.GGUFQuantizationConfig(
compute_dtype = dtype
)
- from .video_ltx2 import is_ltx23_checkpoint, load_ltx23_pipeline
+ from .video_ltx2 import direct_load_device, is_ltx23_checkpoint, load_ltx23_pipeline
if fam.name == "ltx-2" and is_ltx23_checkpoint(checkpoint_path):
# Explicit fp8 takes the hosted DiT, resident only: offload hooks' Module.to() rejects torchao tensors.
@@ -5827,6 +5881,20 @@ class VideoBackend:
raise_on_unified_memory_shortfall(
plan, family = getattr(fam, "name", None), logger = logger
)
+ # Judged on the bf16 plan too: a single-file load never engages the runtime quant.
+ ltx23_device = None
+ ltx23_te_device = None
+ if kind != "gguf" and all(
+ plan_keeps_transformer_resident(p) for p in (plan, bf16_plan) if p is not None
+ ):
+ ltx23_device = direct_load_device(target.torch_device)
+ if all(
+ getattr(p, "offload_policy", None) == OFFLOAD_NONE
+ for p in (plan, bf16_plan)
+ if p is not None
+ ):
+ ltx23_te_device = ltx23_device
+ ltx23_direct_loaded = ltx23_device is not None
# 2.3 checkpoints need the full assembly: new config flags, key renames the stock converter lacks, and
# the 2.3 connectors/VAEs/vocoder.
pipe = load_ltx23_pipeline(
@@ -5843,6 +5911,8 @@ class VideoBackend:
# _base_local_dir is None for 2.3 by design -- so every component below resolves the hub id.
local_files_only = local_files_only,
transformer_override = ltx23_override,
+ device = ltx23_device,
+ text_encoder_device = ltx23_te_device,
)
else:
transformer = transformer_cls.from_single_file(str(checkpoint_path), **sf_kwargs)
@@ -6285,8 +6355,11 @@ class VideoBackend:
del pipe
clear_gpu_cache()
raise RuntimeError(shortfall)
+ if ltx23_direct_loaded:
+ _return_direct_loaded_modules(pipe, plan, logger)
# the streamed modules pin after the load returns, overlapping the first encode and compile
request_background_pins(pipe)
+ request_fast_pins(pipe)
offload_policy, vae_tiling = apply_memory_plan(
pipe,
plan,
@@ -6409,8 +6482,32 @@ class VideoBackend:
},
logger = logger,
)
+ # Opt-in (UNSLOTH_DIFFUSION_BG_COMPILE=1): off by default so the same seed twice repeats.
+ from . import diffusion_bg_compile as bg_compile
+
+ bg_module = (
+ None
+ if not bg_compile.load_time_enabled()
+ else bg_compile.select_module(
+ pipe,
+ speed_optims = speed_optims,
+ default_tier = effective_speed == SPEED_DEFAULT,
+ quantized = transformer_quant_engaged is not None,
+ gguf = kind == "gguf",
+ step_cache = bool(cache_engaged) or bool(cache_may_toggle),
+ device = getattr(target, "device", device),
+ backend = getattr(target, "backend", None),
+ denoiser_hooked = offload_policy != "none" and _video_denoiser_hooked(pipe),
+ )
+ )
+ load_bg_compile = (
+ bg_compile.arm(bg_module, logger = logger) if bg_module is not None else None
+ )
with self._lock:
if _load_token is not None and _load_token != self._load_token:
+ if load_bg_compile is not None:
+ load_bg_compile.close()
+ load_bg_compile = None
del pipe
clear_gpu_cache()
raise RuntimeError("Video load was cancelled or superseded.")
@@ -6458,6 +6555,7 @@ class VideoBackend:
phase = "decode",
),
resolved = resolved,
+ bg_compile = load_bg_compile,
)
self._precommit_globals = None
logger.info(
@@ -7913,6 +8011,14 @@ class VideoBackend:
# begin_generate passes its already-registered event; a direct call makes its own.
cancel = cancel_event if cancel_event is not None else threading.Event()
with self._generate_lock:
+ # Never render beside a background compile; wait outside the state lock so status polls keep answering.
+ pending_bg = getattr(self._state, "bg_compile", None)
+ if pending_bg is not None and pending_bg.compiling():
+ logger.info("video.bg_compile: render waits for the background compile to finish")
+ waited = pending_bg.wait(cancel)
+ logger.info(
+ "video.bg_compile: render waited %.1f s for the background compile", waited
+ )
with self._lock:
# A teardown is waiting for this lock and Python locks are not FIFO, so refuse rather than denoise
# against a pipeline that is already being torn down.
@@ -7927,6 +8033,12 @@ class VideoBackend:
# Bound below, once the request is resolved. None means the failure beat the resolution, and there is
# nothing truthful to report.
request_shape: Optional[dict[str, Any]] = None
+ # Compile still pending: this render runs eager and records the denoiser inputs for it.
+ from . import diffusion_bg_compile as bg_compile
+
+ bg = getattr(state, "bg_compile", None)
+ bg_eager = bg is not None and bg.pending()
+ bg_token = bg_compile._FORCE_EAGER.set(True) if bg_eager else None
try:
# FIRST, before any device object exists. begin_generate runs this on a fresh daemon thread, so until it
# is pinned the un-indexed state.device below -- the H3 memory probe and every torch.Generator --
@@ -8495,6 +8607,9 @@ class VideoBackend:
raise RuntimeError(VIDEO_CANCELLED_MSG)
if self._active_generate_cancel is cancel:
self._active_generate_cancel = None
+ if bg_eager:
+ bg.note_eager_generation()
+ bg.kick()
reclaim_offload_host_memory(state.offload_policy, logger = logger)
return {
"mp4_bytes": mp4_bytes,
@@ -8542,6 +8657,8 @@ class VideoBackend:
_log_failed_generation(request_shape, exc)
raise
finally:
+ if bg_token is not None:
+ bg_compile._FORCE_EAGER.reset(bg_token)
with self._lock:
if self._active_generate_cancel is cancel:
self._active_generate_cancel = None
@@ -9039,6 +9156,12 @@ class VideoBackend:
cannot observe a half-torn-down backend."""
state, self._state = self._state, None
if state is not None:
+ # An in-flight background compile still runs the denoiser the teardown frees.
+ if getattr(state, "bg_compile", None) is not None:
+ try:
+ state.bg_compile.close()
+ except Exception: # noqa: BLE001 -- teardown is best effort
+ pass
restore_backend_flags(state.backend_flags)
# A GGUF load may have installed the compiled GGUF dequantizer; restore the stock kernels so a later
# speed=off load is bit-identical.
@@ -9182,6 +9305,9 @@ class VideoBackend:
"memory_mode": state.memory_mode,
"speed_mode": state.speed_mode,
"speed_optims": speed_optims,
+ "bg_compile": state.bg_compile.describe()
+ if getattr(state, "bg_compile", None) is not None
+ else None,
"attention_backend": state.attention_backend,
"transformer_cache": state.transformer_cache,
"transformer_cache_stats": (
diff --git a/studio/backend/core/inference/video_ltx2.py b/studio/backend/core/inference/video_ltx2.py
index 8ddb13803ce..73968d52184 100644
--- a/studio/backend/core/inference/video_ltx2.py
+++ b/studio/backend/core/inference/video_ltx2.py
@@ -354,6 +354,241 @@ def _load_checkpoint_without_dit(checkpoint_path: Path | str) -> Optional[dict[s
}
+DIRECT_LOAD_ENV = "UNSLOTH_VIDEO_DIRECT_LOAD"
+_DIRECT_CHUNK_BYTES = 16 << 20
+_DIRECT_BUFFERS = 16
+_DIRECT_THREADS = 8
+_SAFETENSORS_DTYPES = {
+ "BF16": "bfloat16",
+ "F16": "float16",
+ "F32": "float32",
+ "F64": "float64",
+ "I8": "int8",
+ "U8": "uint8",
+ "I16": "int16",
+ "I32": "int32",
+ "I64": "int64",
+ "BOOL": "bool",
+ "F8_E4M3": "float8_e4m3fn",
+ "F8_E5M2": "float8_e5m2",
+}
+
+
+_SWITCH_OFF = ("0", "off", "false", "no")
+
+
+def direct_load_enabled() -> bool:
+ import os
+ return (os.environ.get(DIRECT_LOAD_ENV) or "").strip().lower() not in _SWITCH_OFF
+
+
+def direct_load_device(device: Any) -> Optional[Any]:
+ """The device a resident LTX-2.3 checkpoint is read straight onto, or None."""
+ if not direct_load_enabled() or device is None:
+ return None
+ try:
+ import torch
+
+ dev = torch.device(device)
+ if dev.type != "cuda" or not torch.cuda.is_available():
+ return None
+ if dev.index is None:
+ dev = torch.device("cuda", torch.cuda.current_device())
+ return dev
+ except Exception: # noqa: BLE001 - an unparseable device keeps the host load
+ return None
+
+
+def _read_safetensors_header(path: str) -> tuple[int, dict[str, Any]]:
+ import json
+ import struct
+
+ with open(path, "rb") as handle:
+ (size,) = struct.unpack("<Q", handle.read(8))
+ header = json.loads(handle.read(size))
+ header.pop("__metadata__", None)
+ return 8 + size, header
+
+
+def read_safetensors_to_device(
+ checkpoint_path: Path | str,
+ device: Any,
+ keep: Any = None,
+ *,
+ chunk_bytes: int = _DIRECT_CHUNK_BYTES,
+ buffers: int = _DIRECT_BUFFERS,
+ threads: int = _DIRECT_THREADS,
+) -> Optional[dict[str, Any]]:
+ """Read the safetensors tensors passing ``keep`` straight into ``device`` memory via a pinned ring (46 GB: 13.5 s
+ host path vs 2.5 s). None for a dtype this reader does not map."""
+ import torch
+
+ path = str(checkpoint_path)
+ data_start, header = _read_safetensors_header(path)
+ entries = []
+ for name, info in header.items():
+ if keep is not None and not keep(name):
+ continue
+ dtype_name = _SAFETENSORS_DTYPES.get(str(info.get("dtype")))
+ dtype = getattr(torch, dtype_name, None) if dtype_name else None
+ if dtype is None:
+ return None
+ begin, end = (int(x) for x in info["data_offsets"])
+ entries.append((begin, end, name, dtype, tuple(int(x) for x in info["shape"])))
+ entries.sort()
+ device = torch.device(device)
+ out: dict[str, Any] = {}
+ jobs: list[tuple[int, int, Any, int]] = []
+ for begin, end, name, dtype, shape in entries:
+ tensor = torch.empty(shape, dtype = dtype, device = device)
+ out[name] = tensor
+ nbytes = end - begin
+ if nbytes != tensor.numel() * tensor.element_size():
+ raise ValueError(f"safetensors entry {name} has {nbytes} bytes for shape {shape}")
+ if nbytes == 0:
+ continue
+ flat = tensor.view(-1).view(torch.uint8)
+ offset = 0
+ while offset < nbytes:
+ size = min(chunk_bytes, nbytes - offset)
+ jobs.append((data_start + begin + offset, size, flat, offset))
+ offset += size
+ if not jobs:
+ return out
+ _copy_file_chunks(path, jobs, device, chunk_bytes, buffers, threads)
+ return out
+
+
+def _copy_file_chunks(
+ path: str,
+ jobs: list[tuple[int, int, Any, int]],
+ device: Any,
+ chunk_bytes: int,
+ buffers: int,
+ threads: int,
+) -> None:
+ """Copy ``(file offset, size, uint8 view, view offset)`` jobs; reads overlap the async uploads."""
+ import queue
+ from concurrent.futures import ThreadPoolExecutor
+
+ import torch
+
+ if torch.device(device).type != "cuda":
+ with open(path, "rb", buffering = 0) as handle:
+ for offset, size, flat, at in jobs:
+ view = memoryview(flat.numpy())[at : at + size]
+ handle.seek(offset)
+ got = 0
+ while got < size:
+ read = handle.readinto(view[got:])
+ if not read:
+ raise EOFError(f"{path}: short read at {offset + got}")
+ got += read
+ return
+ buffers = max(1, min(buffers, len(jobs)))
+ staging = [torch.empty(chunk_bytes, dtype = torch.uint8, pin_memory = True) for _ in range(buffers)]
+ done_events: list[Any] = [None] * buffers
+ handles: "queue.SimpleQueue[Any]" = queue.SimpleQueue()
+ opened: list[Any] = []
+
+ def _read(slot: int, offset: int, size: int) -> None:
+ event = done_events[slot]
+ if event is not None:
+ event.synchronize()
+ try:
+ handle = handles.get_nowait()
+ except queue.Empty:
+ handle = open(path, "rb", buffering = 0)
+ opened.append(handle)
+ try:
+ view = memoryview(staging[slot].numpy())[:size]
+ handle.seek(offset)
+ got = 0
+ while got < size:
+ read = handle.readinto(view[got:])
+ if not read:
+ raise EOFError(f"{path}: short read at {offset + got}")
+ got += read
+ finally:
+ handles.put(handle)
+
+ stream = torch.cuda.Stream(device = device)
+ try:
+ with ThreadPoolExecutor(
+ max_workers = max(1, threads), thread_name_prefix = "unsloth-direct-load"
+ ) as pool:
+ pending = {}
+ for index in range(min(buffers, len(jobs))):
+ offset, size, _flat, _at = jobs[index]
+ pending[index] = pool.submit(_read, index % buffers, offset, size)
+ with torch.cuda.stream(stream):
+ for index, (offset, size, flat, at) in enumerate(jobs):
+ slot = index % buffers
+ pending.pop(index).result()
+ flat[at : at + size].copy_(staging[slot][:size], non_blocking = True)
+ event = torch.cuda.Event()
+ event.record(stream)
+ done_events[slot] = event
+ following = index + buffers
+ if following < len(jobs):
+ next_offset, next_size, _f, _a = jobs[following]
+ pending[following] = pool.submit(_read, slot, next_offset, next_size)
+ stream.synchronize()
+ finally:
+ try:
+ # A failed read leaves uploads queued from the staging ring.
+ stream.synchronize()
+ except Exception: # noqa: BLE001
+ pass
+ for handle in opened:
+ try:
+ handle.close()
+ except Exception: # noqa: BLE001
+ pass
+ # The side stream is synchronised above, so the default stream sees finished bytes.
+ del staging
+ try:
+ torch._C._host_emptyCache()
+ except Exception: # noqa: BLE001 - older torch keeps the 256 MiB ring cached
+ pass
+
+
+def _load_checkpoint_without_dit_to_device(
+ checkpoint_path: Path | str, device: Any
+) -> Optional[dict[str, Any]]:
+ """``_load_checkpoint_without_dit`` onto ``device``; None falls back to the host read."""
+ if not str(checkpoint_path).lower().endswith(".safetensors"):
+ return None
+ try:
+ return read_safetensors_to_device(
+ checkpoint_path, device, keep = lambda key: _checkpoint_group(key)[0] != "dit"
+ )
+ except Exception as exc: # noqa: BLE001 - a failed direct read degrades to the host load
+ logger.warning("video.ltx23_direct_load: falling back to the host load (%s)", exc)
+ _release_device_cache()
+ return None
+
+
+def _release_device_cache() -> None:
+ try:
+ import torch
+ torch.cuda.empty_cache()
+ except Exception: # noqa: BLE001
+ pass
+
+
+def load_checkpoint_to_device(checkpoint_path: Path | str, device: Any) -> Optional[dict[str, Any]]:
+ """Every tensor of a safetensors checkpoint on ``device``; None falls back to the host read."""
+ if not str(checkpoint_path).lower().endswith(".safetensors"):
+ return None
+ try:
+ return read_safetensors_to_device(checkpoint_path, device)
+ except Exception as exc: # noqa: BLE001 - a failed direct read degrades to the host load
+ logger.warning("video.ltx23_direct_load: falling back to the host load (%s)", exc)
+ _release_device_cache()
+ return None
+
+
def _load_extras_file(
filename: str,
hf_token: Optional[str],
@@ -848,6 +1083,7 @@ def load_ltx23_transformer(
is_gguf: bool,
hf_token: Optional[str],
local_files_only: bool = False,
+ device: Optional[Any] = None,
) -> Any:
import diffusers
from diffusers import LTX2VideoTransformer3DModel
@@ -868,6 +1104,9 @@ def load_ltx23_transformer(
}
if is_gguf:
kwargs["quantization_config"] = diffusers.GGUFQuantizationConfig(compute_dtype = torch_dtype)
+ elif device is not None:
+ # Else the meta load copies every tensor back to the host.
+ kwargs["device"] = device
return LTX2VideoTransformer3DModel.from_single_file(dit_state, **kwargs)
@@ -962,7 +1201,162 @@ def load_ltx23_audio_vae_and_vocoder(
return audio_vae, vocoder.to(torch_dtype)
+PREFETCH_ENV = "UNSLOTH_VIDEO_PREFETCH"
+_PREFETCH_THREADS = 8
+_PREFETCH_CHUNK_BYTES = 16 << 20
+
+
+def prefetch_enabled() -> bool:
+ import os
+ return (os.environ.get(PREFETCH_ENV) or "").strip().lower() not in _SWITCH_OFF
+
+
+def _uncached_bytes(
+ path: str,
+ stride: int = 64 << 20,
+ window: int = 1 << 20,
+) -> int:
+ """Estimated bytes of ``path`` not in the page cache (sampled Linux ``mincore``); 0 when it cannot tell."""
+ import ctypes
+ import mmap
+ import os
+ import sys
+
+ if not sys.platform.startswith("linux"):
+ return 0
+ size = os.path.getsize(path)
+ if size == 0:
+ return 0
+ page = mmap.PAGESIZE
+ window = max(page, window - window % page)
+ stride = max(window, stride - stride % page)
+ with open(path, "rb") as handle:
+ mapped = mmap.mmap(handle.fileno(), size, access = mmap.ACCESS_COPY)
+ try:
+ anchor = ctypes.c_char.from_buffer(mapped)
+ try:
+ base = ctypes.addressof(anchor)
+ libc = ctypes.CDLL(None, use_errno = True)
+ libc.mincore.argtypes = [ctypes.c_void_p, ctypes.c_size_t, ctypes.c_void_p]
+ vector = (ctypes.c_ubyte * (window // page))()
+ sampled = missing = 0
+ for offset in range(0, size, stride):
+ length = min(window, size - offset)
+ pages = (length + page - 1) // page
+ if libc.mincore(base + offset, ctypes.c_size_t(length), vector) != 0:
+ return 0
+ missing += bytes(vector)[:pages].count(0)
+ sampled += pages
+ return int(size * missing / sampled) if sampled else 0
+ finally:
+ del anchor
+ finally:
+ mapped.close()
+
+
+def _text_encoder_files(base_repo: str, cache_dir: Optional[str]) -> list[str]:
+ """The cached text encoder shards of ``base_repo`` (cache only, never a download)."""
+ import json
+ import os
+
+ try:
+ from huggingface_hub import try_to_load_from_cache
+
+ index = try_to_load_from_cache(
+ base_repo, "text_encoder/model.safetensors.index.json", cache_dir = cache_dir
+ )
+ if not isinstance(index, str):
+ return []
+ with open(index, "r", encoding = "utf-8") as handle:
+ shards = sorted(set(json.load(handle).get("weight_map", {}).values()))
+ except Exception: # noqa: BLE001 - not cached (the load downloads it) or an unreadable cache
+ return []
+ folder = os.path.dirname(index)
+ return [p for p in (os.path.join(folder, name) for name in shards) if os.path.isfile(p)]
+
+
+def start_prefetch(paths: list[str]) -> Optional[Any]:
+ """Warm the uncached parts of ``paths`` in the page cache on worker threads; a stop Event, or None when nothing
+ needs it or host RAM is too tight. Cold B200 cache: the Gemma3 shards otherwise read at ~1.7 GB/s after the checkpoint."""
+ import os
+ import threading
+
+ try:
+ uncached = [(path, _uncached_bytes(path)) for path in paths]
+ except Exception: # noqa: BLE001 - residency unknown: leave the reads to the loader
+ return None
+ pending = [path for path, missing in uncached if missing > 0]
+ need = sum(missing for _path, missing in uncached)
+ if not pending or need < 1 << 30:
+ return None
+ try:
+ from .diffusion_memory import _available_system_memory_mib
+ available = _available_system_memory_mib()
+ except Exception: # noqa: BLE001
+ available = None
+ if available is None or need > (int(available) << 20) // 2:
+ return None
+ stop = threading.Event()
+ jobs = []
+ for path in pending:
+ size = os.path.getsize(path)
+ jobs += [(path, offset) for offset in range(0, size, _PREFETCH_CHUNK_BYTES)]
+ lock = threading.Lock()
+ queue = iter(jobs)
+
+ def _worker() -> None:
+ buffer = bytearray(_PREFETCH_CHUNK_BYTES)
+ view = memoryview(buffer)
+ handles: dict[str, Any] = {}
+ try:
+ while not stop.is_set():
+ with lock:
+ job = next(queue, None)
+ if job is None:
+ return
+ path, offset = job
+ handle = handles.get(path)
+ if handle is None:
+ handle = handles[path] = open(path, "rb", buffering = 0)
+ handle.seek(offset)
+ handle.readinto(view)
+ except Exception: # noqa: BLE001 - a prefetch is only a hint
+ pass
+ finally:
+ for handle in handles.values():
+ handle.close()
+
+ for index in range(_PREFETCH_THREADS):
+ threading.Thread(target = _worker, name = f"unsloth-prefetch-{index}", daemon = True).start()
+ logger.info(
+ "video.ltx23_prefetch: warming %.1f GiB of %d text encoder file(s)",
+ need / 2**30,
+ len(pending),
+ )
+ return stop
+
+
def load_ltx23_pipeline(
+ checkpoint_path: Path | str,
+ *,
+ base_repo: str,
+ text_encoder: Optional[Any] = None,
+ **kwargs: Any,
+) -> Any:
+ """Full LTX-2.3 pipeline (``_assemble_ltx23_pipeline``), warming the text encoder files beside the checkpoint read."""
+ prefetch = None
+ if text_encoder is None and prefetch_enabled():
+ prefetch = start_prefetch(_text_encoder_files(base_repo, _live_cache_dir()))
+ try:
+ return _assemble_ltx23_pipeline(
+ checkpoint_path, base_repo = base_repo, text_encoder = text_encoder, **kwargs
+ )
+ finally:
+ if prefetch is not None:
+ prefetch.set()
+
+
+def _assemble_ltx23_pipeline(
checkpoint_path: Path | str,
*,
base_repo: str,
@@ -972,6 +1366,8 @@ def load_ltx23_pipeline(
text_encoder: Optional[Any] = None,
local_files_only: bool = False,
transformer_override: Optional[Any] = None,
+ device: Optional[Any] = None,
+ text_encoder_device: Optional[Any] = None,
) -> Any:
"""Full LTX-2.3 pipeline from a single-file/GGUF checkpoint. Assembled per-component
(constructor, not from_pretrained) because the base model_index pins LTX2Vocoder while 2.3
@@ -986,7 +1382,9 @@ def load_ltx23_pipeline(
base REPO ID rather than a staged snapshot (the 2.3 snapshot lacks the base VAEs, so
``_base_local_dir`` is deliberately None here), so without the flag the base config, the
scheduler, the tokenizer, the dense Gemma3 encoder and the companion VAE/vocoder artifacts are
- all fetched by a load that promised to fetch nothing."""
+ all fetched by a load that promised to fetch nothing.
+
+ ``device`` / ``text_encoder_device`` (resident plans only) read the checkpoint / build the Gemma3 encoder there."""
import transformers
from .ltx2_import_compat import ensure_ltx2_pipelines_importable
@@ -1003,7 +1401,24 @@ def load_ltx23_pipeline(
LTX23_EXTRAS_REPO,
)
state = None
- if transformer_override is not None and not is_gguf:
+ on_device = False
+ if device is not None and not is_gguf:
+ import time
+
+ began = time.perf_counter()
+ if transformer_override is not None:
+ state = _load_checkpoint_without_dit_to_device(checkpoint_path, device)
+ else:
+ state = load_checkpoint_to_device(checkpoint_path, device)
+ on_device = state is not None
+ if on_device:
+ logger.info(
+ "video.ltx23_direct_load: read %.1f GiB onto %s in %.1f s",
+ sum(t.numel() * t.element_size() for t in state.values()) / 2**30,
+ device,
+ time.perf_counter() - began,
+ )
+ if state is None and transformer_override is not None and not is_gguf:
state = _load_checkpoint_without_dit(checkpoint_path)
if state is None:
state = load_single_file_checkpoint(str(checkpoint_path))
@@ -1032,6 +1447,7 @@ def load_ltx23_pipeline(
is_gguf = is_gguf,
hf_token = hf_token,
local_files_only = local_files_only,
+ device = device if on_device else None,
)
connectors = load_ltx23_connectors(
groups["connectors"],
@@ -1081,7 +1497,10 @@ def load_ltx23_pipeline(
scheduler = _sub("scheduler")
tokenizer = _sub("tokenizer")
if text_encoder is None:
- text_encoder = _sub("text_encoder", torch_dtype = torch_dtype)
+ encoder_kwargs: dict[str, Any] = {"torch_dtype": torch_dtype}
+ if text_encoder_device is not None:
+ encoder_kwargs["device_map"] = {"": text_encoder_device}
+ text_encoder = _sub("text_encoder", **encoder_kwargs)
return LTX2Pipeline(
scheduler = scheduler,
diff --git a/studio/backend/tests/test_diffusion_cold_start.py b/studio/backend/tests/test_diffusion_cold_start.py
new file mode 100644
index 00000000000..f4214f9e1c3
--- /dev/null
+++ b/studio/backend/tests/test_diffusion_cold_start.py
@@ -0,0 +1,638 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Cold-start levers for the diffusion backend: background compile of a dense denoiser, the persisted quant smoke-probe
+table, the mapped pre-quant checkpoint read, and the deeper diffusers prewarm.
+
+CPU only. The background compile is driven through a real ``torch.compile`` with a counting backend, so "no compile on
+the render" is observed, not assumed.
+"""
+
+from __future__ import annotations
+
+import json
+import sys
+import threading
+import time
+import types
+
+import pytest
+
+torch = pytest.importorskip("torch")
+
+from core.inference import diffusion_bg_compile as bg # noqa: E402
+from core.inference import diffusion_cuda_graph as cg # noqa: E402
+from core.inference import diffusion_probe_cache as probe_cache # noqa: E402
+from core.inference import diffusion_speed as speed # noqa: E402
+
+
+class _Counter:
+ """A dynamo backend that counts compiles and runs the traced graph as is."""
+
+ def __init__(self) -> None:
+ self.compiles = 0
+
+ def __call__(self, gm, example_inputs):
+ self.compiles += 1
+ return gm.forward
+
+
+class _Net(torch.nn.Module):
+ def __init__(self) -> None:
+ super().__init__()
+ self.lin = torch.nn.Linear(8, 8)
+
+ def forward(
+ self,
+ x,
+ *,
+ scale = 1.0,
+ return_dict = True,
+ ):
+ return self.lin(x) * scale
+
+
[email protected](autouse = True)
+def _reset_dynamo():
+ torch._dynamo.reset()
+ yield
+ torch._dynamo.reset()
+
+
+def _whole_compiled(counter):
+ net = _Net().eval()
+ net.compile(backend = counter, fullgraph = True, dynamic = False)
+ return net
+
+
+# ---------------------------------------------------------------------------------------------- background compile
+
+
+_REAL_COMPILE = r"""
+import torch
+from core.inference import diffusion_bg_compile as bg
+
+
+class Counter:
+ def __init__(self):
+ self.compiles = 0
+
+ def __call__(self, gm, example_inputs):
+ self.compiles += 1
+ return gm.forward
+
+
+class Net(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.lin = torch.nn.Linear(8, 8)
+
+ def forward(self, x, *, scale = 1.0, return_dict = True):
+ return self.lin(x) * scale
+
+
+counter = Counter()
+net = Net().eval()
+net.compile(backend = counter, fullgraph = True, dynamic = False)
+job = bg.arm(net)
+assert job is not None and job.pending()
+
+x = torch.randn(2, 8)
+with torch.no_grad(), bg.force_eager():
+ eager_out = net(x, scale = 2.0, return_dict = False)
+assert counter.compiles == 0, "a render under force_eager compiled the denoiser"
+assert len(job.samples) == 1
+
+assert job.kick() is True
+job._thread.join(60)
+assert job.state == "done", job.error
+assert counter.compiles >= 1, "the background thread never compiled"
+compiled_after_bg = counter.compiles
+
+with torch.no_grad():
+ out = net(x, scale = 2.0, return_dict = False)
+assert counter.compiles == compiled_after_bg, "the first compiled render recompiled what the background built"
+assert torch.equal(out, eager_out)
+job.close()
+assert not hasattr(net._compiled_call_impl, "_unsloth_bg_gate"), "close() left the gate in front of the compile"
+print("BG_COMPILE_OK")
+"""
+
+
+def test_force_eager_never_reaches_dynamo_and_the_background_compile_does(monkeypatch):
+ # Own interpreter: a dynamo compile on a worker thread leaves torch state that crashes a later make_fx trace in
+ # the same process (seen with test_video_minimax_h3_adaln.py, also with plain torch and no Studio code).
+ import os
+ import subprocess
+ from pathlib import Path
+
+ monkeypatch.delenv("UNSLOTH_DIFFUSION_BG_COMPILE", raising = False)
+ backend = Path(__file__).resolve().parents[1]
+ env = dict(os.environ, CUDA_VISIBLE_DEVICES = "", PYTHONPATH = str(backend))
+ r = subprocess.run(
+ [sys.executable, "-c", _REAL_COMPILE],
+ cwd = str(backend),
+ env = env,
+ capture_output = True,
+ text = True,
+ timeout = 300,
+ )
+ assert r.returncode == 0 and "BG_COMPILE_OK" in r.stdout, r.stdout[-2000:] + r.stderr[-4000:]
+
+
+def test_recording_dedups_by_input_shape_and_ignores_unforced_calls():
+ counter = _Counter()
+ net = _whole_compiled(counter)
+ job = bg.arm(net)
+ with torch.no_grad():
+ with bg.force_eager():
+ net(torch.randn(2, 8), return_dict = False)
+ net(torch.randn(2, 8), return_dict = False) # same shape: not recorded again
+ net(
+ torch.randn(3, 8), return_dict = False
+ ) # a second shape (e.g. the CFG half with another length)
+ assert len(job.samples) == 2
+ job.close()
+
+
+def test_close_breaks_the_hook_job_cycle():
+ # An aborted load closes its job: the hook <-> job cycle would otherwise keep the pipeline's tensors alive.
+ net = _whole_compiled(_Counter())
+ job = bg.arm(net)
+ assert len(net._forward_pre_hooks) == 1
+ job.close()
+ assert len(net._forward_pre_hooks) == 0 and job.module is None
+
+
+def test_kick_without_samples_keeps_recording():
+ net = _whole_compiled(_Counter())
+ job = bg.arm(net)
+ assert job.kick() is False
+ assert job.state == "recording"
+ job.close()
+
+
+def test_kill_switch_disables_arming(monkeypatch):
+ monkeypatch.setenv("UNSLOTH_DIFFUSION_BG_COMPILE", "0")
+ assert bg.arm(_whole_compiled(_Counter())) is None
+
+
+ "raw, deferred, at_load",
+ [
+ (None, True, False),
+ ("", True, False),
+ ("1", True, True),
+ ("on", True, True),
+ ("0", False, False),
+ ],
+)
+def test_load_time_background_compile_is_opt_in(monkeypatch, raw, deferred, at_load):
+ # Render 1 eager + render 2 compiled would break "same seed twice repeats", so only the deferred profile (which
+ # already switched eager -> compiled at generation 3) compiles in the background unless =1 opts the load in.
+ if raw is None:
+ monkeypatch.delenv("UNSLOTH_DIFFUSION_BG_COMPILE", raising = False)
+ else:
+ monkeypatch.setenv("UNSLOTH_DIFFUSION_BG_COMPILE", raw)
+ assert bg.enabled() is deferred
+ assert bg.load_time_enabled() is at_load
+
+
+def test_a_render_waits_for_an_in_flight_compile_and_cancel_releases_it():
+ gate = threading.Event()
+
+ class _Slow(torch.nn.Module):
+ def forward(self, x):
+ if threading.current_thread().name == "unsloth-diffusion-bg-compile":
+ gate.wait(30)
+ return x
+
+ job = bg.BackgroundCompile(_Slow())
+ assert job.install()
+ with torch.no_grad(), bg.force_eager():
+ job.module(torch.zeros(1)) # recorded; only the background replay blocks on the gate
+ job.kick()
+ assert job.compiling()
+ cancel = threading.Event()
+ cancel.set()
+ assert job.wait(cancel) < 1.0, "a cancelled render kept waiting on the compile"
+ threading.Timer(0.3, gate.set).start()
+ assert job.wait() >= 0.2
+ assert job.state == "done" and not job.compiling()
+ job.close()
+
+
+def test_the_background_compile_sees_the_recorded_compile_knobs():
+ from core.inference import diffusion_compile_config as compile_config
+
+ seen = {}
+
+ class _Probe(torch.nn.Module):
+ def forward(self, x):
+ if threading.current_thread().name == "unsloth-diffusion-bg-compile":
+ seen["emulate"] = torch._inductor.config.emulate_precision_casts
+ return x
+
+ module, attr = "torch._inductor.config", "emulate_precision_casts"
+ before = compile_config.get_knob(module, attr)
+ was_recorded = compile_config.is_recorded(module, attr)
+ assert compile_config.set_knob(module, attr, True)
+ try:
+ job = bg.BackgroundCompile(_Probe())
+ assert job.install()
+ with torch.no_grad(), bg.force_eager():
+ job.module(torch.zeros(1))
+ job.kick()
+ job._thread.join(30)
+ assert job.state == "done", job.error
+ assert (
+ seen.get("emulate") is True
+ ), "the background compile ran without the recorded inductor knobs"
+ job.close()
+ finally:
+ if was_recorded:
+ compile_config.set_knob(module, attr, before)
+ else:
+ with compile_config._LOCK:
+ compile_config._KNOBS.pop((module, attr), None)
+ torch._inductor.config.emulate_precision_casts = before
+
+
+def test_a_failing_warm_forward_ends_the_attempt_without_raising():
+ class _Boom(torch.nn.Module):
+ def forward(self, x):
+ raise RuntimeError("boom")
+
+ net = _Boom()
+ job = bg.BackgroundCompile(net)
+ assert job.install()
+ # Record by hand: the eager call itself would raise too.
+ job.samples.append(
+ (("l", True, [("l", True, [("t", 0)]), ("d", [])]), [torch.zeros(1)], False, False, None)
+ )
+ job.kick()
+ job._thread.join(30)
+ assert job.state == "failed" and "boom" in (job.error or "")
+ assert not job.pending()
+
+
+def test_compile_guard_routes_to_eager_under_force_eager():
+ guard = speed._CompileGuard(None)
+ calls = []
+ wrapped = guard.wrap(
+ lambda *a, **k: calls.append("compiled"), lambda *a, **k: calls.append("eager"), object()
+ )
+ with bg.force_eager():
+ wrapped()
+ wrapped()
+ assert calls == ["eager", "compiled"]
+
+
+def test_graphed_forward_neither_captures_nor_poisons_under_force_eager():
+ net = _Net()
+ graphed = cg.GraphedForward(net).enable()
+ try:
+ with torch.no_grad(), bg.force_eager():
+ net(torch.randn(2, 8), return_dict = False)
+ assert graphed.stats["captures"] == 0
+ assert graphed.stats["eager_calls"] == 1
+ assert not graphed.poisoned
+ # The background thread runs the wrapped callable without counting an eager call or capturing.
+ token = bg._NO_CAPTURE.set(True)
+ try:
+ with torch.no_grad():
+ net(torch.randn(2, 8), return_dict = False)
+ finally:
+ bg._NO_CAPTURE.reset(token)
+ assert graphed.stats["eager_calls"] == 1 and graphed.stats["captures"] == 0
+ finally:
+ graphed.free()
+
+
+class _UNet2DConditionModel(torch.nn.Module):
+ """Named like the class on the whole-compile list."""
+
+
+ "override, expect",
+ [
+ ({}, True),
+ ({"transformer_quant": "int8"}, False),
+ ({"gguf_transformer": True}, False),
+ ({"offload_policy": "group", "_hooked": True}, False),
+ ({"offload_policy": "group"}, True), # encoders streamed, denoiser resident
+ ({"speed_mode": "max"}, False),
+ ({"speed_optims": ("cuda_graph",)}, False),
+ ({"transformer_cache": "fbcache"}, False),
+ ({"cache_auto": True}, False),
+ ({"target": types.SimpleNamespace(device = "cuda", backend = "rocm")}, False),
+ ({"target": types.SimpleNamespace(device = "mps", backend = "mps")}, False),
+ ],
+)
+def test_only_dense_resident_default_tier_cuda_loads_compile_in_the_background(
+ monkeypatch, override, expect
+):
+ from core.inference import diffusion as D
+
+ monkeypatch.delenv("UNSLOTH_DIFFUSION_BG_COMPILE", raising = False)
+ monkeypatch.setattr(
+ speed, "_UNET_WHOLE_COMPILE", frozenset({"_UNet2DConditionModel"}), raising = False
+ )
+ unet = _UNet2DConditionModel()
+ if override.pop("_hooked", False):
+ unet._hf_hook = object()
+ pipe = types.SimpleNamespace(unet = unet)
+ kwargs = dict(
+ speed_optims = ("compiled", "cuda_graph"),
+ speed_mode = D.SPEED_DEFAULT,
+ transformer_quant = None,
+ gguf_transformer = False,
+ offload_policy = D.OFFLOAD_NONE,
+ transformer_cache = None,
+ cache_auto = False,
+ target = types.SimpleNamespace(device = "cuda", backend = "cuda"),
+ )
+ kwargs.update(override)
+ got = D._bg_compile_module(pipe, **kwargs)
+ assert (got is unet) is expect
+
+
+# ---------------------------------------------------------------------------------------------- probe-table cache
+
+
+def probe_home(tmp_path, monkeypatch):
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))
+ monkeypatch.delenv("UNSLOTH_DIFFUSION_PROBE_CACHE", raising = False)
+ fp = {"torch": "x", "gpu_uuid": "GPU-1", "env": {}}
+ monkeypatch.setattr(probe_cache, "fingerprint", lambda card: dict(fp))
+ return fp
+
+
+def test_probe_table_round_trips_and_misses_on_any_stack_change(probe_home, monkeypatch):
+ assert probe_cache.load("cuda:0") is None
+ assert probe_cache.store("cuda:0", {"int8": True, "fp8": False, "mxfp8": None})
+ assert probe_cache.load("cuda:0") == {
+ "int8": True,
+ "fp8": False,
+ }, "an allocator failure (None) was persisted"
+
+ monkeypatch.setattr(probe_cache, "fingerprint", lambda card: {**probe_home, "torch": "y"})
+ assert probe_cache.load("cuda:0") is None
+
+
+def test_an_all_negative_table_is_not_persisted(probe_home):
+ # A busy / unavailable device at probe time fails every scheme; that must not outlive the process.
+ assert probe_cache.store("cuda:0", {"int8": False, "fp8": False, "mxfp8": None}) is False
+ assert probe_cache.load("cuda:0") is None
+
+
+def test_probe_table_kill_switch_and_torn_file(probe_home, monkeypatch):
+ probe_cache.store("cuda:0", {"int8": True})
+ path = probe_cache._cache_file()
+ path.write_text("{not json", encoding = "utf-8")
+ assert probe_cache.load("cuda:0") is None
+ probe_cache.store("cuda:0", {"int8": True})
+ monkeypatch.setenv("UNSLOTH_DIFFUSION_PROBE_CACHE", "0")
+ assert probe_cache.load("cuda:0") is None
+ assert json.loads(path.read_text(encoding = "utf-8"))
+
+
+def test_a_persisted_table_answers_without_spawning_the_child(probe_home, monkeypatch):
+ from core.inference import diffusion_transformer_quant as tq
+
+ probe_cache.store("cuda:0", {"int8": True, "fp8": False})
+ monkeypatch.setattr(tq, "_SMOKE_CACHE", {}, raising = False)
+ monkeypatch.setattr(tq, "_smoke_cache_device_key", lambda device, ordinal = None: "cuda:0")
+ monkeypatch.setattr(tq, "nvfp4_blocked", lambda scheme: False)
+ monkeypatch.setattr(torch.cuda, "is_available", lambda: True)
+
+ def _no_child(card):
+ raise AssertionError("spawned the probe child despite a persisted table")
+
+ monkeypatch.setattr(tq, "_child_probe_table", _no_child)
+ assert tq._scheme_supported("int8", "cuda") is True
+ assert tq._scheme_supported("fp8", "cuda") is False
+
+
+def test_a_clean_child_table_is_persisted(monkeypatch):
+ from core.inference import diffusion_transformer_quant as tq
+
+ stored = {}
+ monkeypatch.setattr(
+ probe_cache, "store", lambda card, table: stored.setdefault(card, dict(table))
+ )
+
+ # Drive the tail of _child_probe_table: a table read off the queue is persisted and returned.
+ class _Q:
+ def get(self, timeout = None):
+ return {"int8": True}
+
+ class _P:
+ pid = 1
+
+ def start(self):
+ pass
+
+ def is_alive(self):
+ return True
+
+ class _Ctx:
+ def Queue(self):
+ return _Q()
+
+ def Process(self, **kwargs):
+ return _P()
+
+ import multiprocessing as mp
+
+ monkeypatch.setattr(mp, "get_context", lambda name: _Ctx())
+ monkeypatch.setattr(tq, "_adopt_probe_pid", lambda pid: None, raising = False)
+ monkeypatch.setattr(tq, "_close_probe_child", lambda proc, queue: None, raising = False)
+ monkeypatch.setattr(tq, "_CHILD_PROBE_UNAVAILABLE", False, raising = False)
+ assert tq._child_probe_table("cuda:0") == {"int8": True}
+ assert stored == {"cuda:0": {"int8": True}}
+
+
+# ---------------------------------------------------------------------------------------------- mapped pre-quant read
+
+
+def test_mapped_read_only_for_an_accelerator_destination(monkeypatch):
+ from core.inference import diffusion_prequant as pq
+
+ monkeypatch.delenv("UNSLOTH_DIFFUSION_PREQUANT_MMAP", raising = False)
+ assert pq.prequant_mmap_enabled("cuda")
+ assert pq.prequant_mmap_enabled("cuda:1")
+ assert not pq.prequant_mmap_enabled("cpu")
+ assert not pq.prequant_mmap_enabled(None)
+ monkeypatch.setenv("UNSLOTH_DIFFUSION_PREQUANT_MMAP", "0")
+ assert not pq.prequant_mmap_enabled("cuda")
+
+
+def test_mapped_read_matches_the_full_read_and_falls_back(tmp_path, monkeypatch):
+ from core.inference import diffusion_prequant as pq
+
+ monkeypatch.delenv("UNSLOTH_DIFFUSION_PREQUANT_MMAP", raising = False)
+ ckpt = {
+ "format": pq.PREQUANT_FORMAT,
+ "state_dict": {"w": torch.arange(64, dtype = torch.int8).reshape(8, 8)},
+ "metadata": {"scheme": "int8"},
+ }
+ path = tmp_path / "x.pt"
+ torch.save(ckpt, path)
+
+ seen = []
+ real = pq._load_prequant_checkpoint
+
+ def spy(p, **kwargs):
+ seen.append(kwargs.get("mmap"))
+ return real(p, **kwargs)
+
+ monkeypatch.setattr(pq, "_load_prequant_checkpoint", spy)
+ mapped = pq._read_prequant_for(str(path), "cuda")
+ assert seen == [True]
+ assert torch.equal(mapped["state_dict"]["w"], ckpt["state_dict"]["w"])
+
+ seen.clear()
+ pq._read_prequant_for(str(path), "cpu")
+ assert seen == [None]
+
+ def mmap_refused(p, **kwargs):
+ seen.append(kwargs.get("mmap"))
+ if kwargs.get("mmap"):
+ raise RuntimeError("mmap can only be used with files saved with the zipfile format")
+ return real(p, **kwargs)
+
+ seen.clear()
+ monkeypatch.setattr(pq, "_load_prequant_checkpoint", mmap_refused)
+ out = pq._read_prequant_for(str(path), "cuda")
+ assert seen == [True, None]
+ assert torch.equal(out["state_dict"]["w"], ckpt["state_dict"]["w"])
+
+
+# ---------------------------------------------------------------------------------------------- deeper prewarm
+
+
+def _prewarm_ready(monkeypatch):
+ from utils import torch_warmup
+
+ monkeypatch.setattr(torch_warmup, "_diffusers_prewarmed", False, raising = False)
+ monkeypatch.delenv(torch_warmup.DIFFUSERS_PREWARM_DISABLE_ENV_VAR, raising = False)
+ monkeypatch.delenv(torch_warmup.DISABLE_ENV_VAR, raising = False)
+ monkeypatch.setattr(torch_warmup, "_a_local_model_would_load_through_diffusers", lambda: True)
+ d = types.ModuleType("diffusers")
+ hooks = types.ModuleType("diffusers.hooks")
+ monkeypatch.setitem(sys.modules, "diffusers", d)
+ monkeypatch.setitem(sys.modules, "diffusers.hooks", hooks)
+ imported = []
+ real_import = torch_warmup.importlib.import_module
+
+ def fake_import(name, *a, **k):
+ if name.startswith("diffusers.models"):
+ imported.append(name)
+ return types.ModuleType(name)
+ return real_import(name, *a, **k)
+
+ monkeypatch.setattr(torch_warmup.importlib, "import_module", fake_import)
+ return torch_warmup, imported
+
+
+def test_the_prewarm_also_imports_the_model_classes(monkeypatch):
+ torch_warmup, imported = _prewarm_ready(monkeypatch)
+ monkeypatch.delenv(torch_warmup.DIFFUSERS_PREWARM_MODELS_ENV_VAR, raising = False)
+ assert torch_warmup.prewarm_diffusers_if_image_models_exist() is True
+ assert imported == list(torch_warmup._DIFFUSERS_PREWARM_MODEL_MODULES)
+
+
+def test_the_model_prewarm_has_its_own_switch(monkeypatch):
+ torch_warmup, imported = _prewarm_ready(monkeypatch)
+ monkeypatch.setenv(torch_warmup.DIFFUSERS_PREWARM_MODELS_ENV_VAR, "0")
+ assert torch_warmup.prewarm_diffusers_if_image_models_exist() is True
+ assert imported == []
+
+
+# ---------------------------------------------------------------------------------------------- load-progress latch
+
+
+def test_load_progress_stops_rescanning_once_every_byte_is_on_disk(monkeypatch):
+ from core.inference import diffusion as D
+
+ monkeypatch.delenv("UNSLOTH_DIFFUSION_PROGRESS_LATCH", raising = False)
+ scans = []
+ loading = D._LoadingState(repo_id = "r", base_repo = "r", expected_bytes = 100)
+ fake = types.SimpleNamespace(
+ _loading = loading,
+ _state = None,
+ _cache_bytes = lambda repo: scans.append(repo) or 100,
+ _cache_file_bytes = lambda repo, filename: 0,
+ )
+ first = D.DiffusionBackend.load_progress(fake)
+ second = D.DiffusionBackend.load_progress(fake)
+ assert first["phase"] == second["phase"] == "finalizing"
+ assert len(scans) == 1, "a finished download was rescanned on every poll"
+ loading.expected_bytes = 200 # a revised estimate is a new question
+ D.DiffusionBackend.load_progress(fake)
+ assert len(scans) == 2
+ monkeypatch.setenv("UNSLOTH_DIFFUSION_PROGRESS_LATCH", "0")
+ loading.expected_bytes = 100
+ loading.finalized_scan = (100, 100)
+ D.DiffusionBackend.load_progress(fake)
+ assert len(scans) == 3
+
+
+def test_load_progress_keeps_scanning_while_downloading():
+ from core.inference import diffusion as D
+
+ scans = []
+ loading = D._LoadingState(repo_id = "r", base_repo = "r", expected_bytes = 100)
+ fake = types.SimpleNamespace(
+ _loading = loading,
+ _state = None,
+ _cache_bytes = lambda repo: scans.append(repo) or 40,
+ _cache_file_bytes = lambda repo, filename: 0,
+ )
+ for _ in range(3):
+ assert D.DiffusionBackend.load_progress(fake)["phase"] == "downloading"
+ assert len(scans) == 3 and loading.finalized_scan is None
+
+
+# ---------------------------------------------------------------------------------------------- boot-time probe
+
+
+def quant_probe(monkeypatch, probe_home):
+ from core.inference import diffusion_transformer_quant as tq
+
+ monkeypatch.delenv("UNSLOTH_DIFFUSION_PROBE_PREWARM", raising = False)
+ monkeypatch.setattr(tq, "_SMOKE_CACHE", {}, raising = False)
+ monkeypatch.setattr(tq, "_smoke_cache_device_key", lambda device, ordinal = None: "cuda:0")
+ monkeypatch.setattr(torch.cuda, "is_available", lambda: True)
+ spawned = []
+
+ def child(card):
+ spawned.append(card)
+ return {"int8": True, "fp8": None}
+
+ monkeypatch.setattr(tq, "_child_probe_table", child)
+ return tq, spawned
+
+
+def test_boot_probe_fills_the_cache_once(quant_probe):
+ tq, spawned = quant_probe
+ assert tq.prewarm_probe_table() is True
+ assert spawned == ["cuda:0"]
+ assert tq._SMOKE_CACHE == {
+ ("int8", "cuda:0"): True
+ }, "an allocator failure (None) was cached as a verdict"
+ assert tq.prewarm_probe_table() is False
+ assert spawned == ["cuda:0"]
+
+
+def test_boot_probe_skips_a_persisted_table_and_honours_its_switch(quant_probe, monkeypatch):
+ tq, spawned = quant_probe
+ probe_cache.store("cuda:0", {"int8": True})
+ assert tq.prewarm_probe_table() is False
+ probe_cache._cache_file().unlink()
+ monkeypatch.setenv("UNSLOTH_DIFFUSION_PROBE_PREWARM", "0")
+ assert tq.prewarm_probe_table() is False
+ assert spawned == []
diff --git a/studio/backend/tests/test_video_backend.py b/studio/backend/tests/test_video_backend.py
index ac7a2b69c9c..868319aba09 100644
--- a/studio/backend/tests/test_video_backend.py
+++ b/studio/backend/tests/test_video_backend.py
@@ -12409,3 +12409,75 @@ def test_ltx2_load_turns_cudnn_benchmark_back_off(fake_runtime, tmp_path, monkey
backend = _load_ltx23_from_dir(tmp_path)
assert calls == [1]
assert "cudnn_benchmark" not in backend.status()["speed_optims"]
+
+
+ "plan_fields, filename, direct, te_direct",
+ [
+ ({"offload_policy": "none"}, "ltx-2.3-22b-distilled.safetensors", True, True),
+ (
+ {"offload_policy": "group", "stream_transformer": False, "stream_text_encoders": True},
+ "ltx-2.3-22b-distilled.safetensors",
+ True,
+ False,
+ ),
+ (
+ {"offload_policy": "group", "stream_transformer": True},
+ "ltx-2.3-22b-distilled.safetensors",
+ False,
+ False,
+ ),
+ ({"offload_policy": "model"}, "ltx-2.3-22b-distilled.safetensors", False, False),
+ ({"offload_policy": "none"}, "ltx-2.3-22b-distilled-1.1-Q4_K_M.gguf", False, False),
+ ],
+ ids = ["resident", "streamed-encoders", "streamed-dit", "model-offload", "gguf"],
+)
+def test_ltx23_reads_the_checkpoint_onto_the_card_only_for_a_resident_dit(
+ fake_runtime, tmp_path, monkeypatch, plan_fields, filename, direct, te_direct
+):
+ # The direct read puts the weights where a resident plan places them anyway; any plan that moves the DiT (or a GGUF,
+ # which keeps its block-quantised host tensors) keeps the host load.
+ import dataclasses
+
+ from core.inference import video as video_mod, video_ltx2
+
+ monkeypatch.setattr(video_ltx2, "is_ltx23_checkpoint", lambda path: True)
+ _ltx23_official_file(monkeypatch)
+ sentinel = object()
+ asked: list = []
+
+ def _device(device):
+ asked.append(device)
+ return sentinel
+
+ monkeypatch.setattr(video_ltx2, "direct_load_device", _device)
+ real_plan = video_mod.plan_diffusion_memory
+ monkeypatch.setattr(
+ video_mod,
+ "plan_diffusion_memory",
+ lambda **kwargs: dataclasses.replace(real_plan(**kwargs), **plan_fields),
+ )
+ seen: dict = {}
+
+ def _assemble(checkpoint_path, **kwargs):
+ seen.update(kwargs)
+ return _FakePipeline.from_pretrained("Lightricks/LTX-2")
+
+ monkeypatch.setattr(video_ltx2, "load_ltx23_pipeline", _assemble)
+ monkeypatch.setattr(video_mod, "_return_direct_loaded_modules", lambda *a, **k: None)
+ # The fake pipeline has no offload hooks; placement is not what this test is about.
+ monkeypatch.setattr(
+ video_mod, "apply_memory_plan", lambda pipe, plan, **k: (plan.offload_policy, True)
+ )
+ (tmp_path / filename).write_bytes(b"w")
+ backend = VideoBackend()
+ backend.load_pipeline(
+ str(tmp_path),
+ gguf_filename = filename,
+ base_repo = "Lightricks/LTX-2",
+ family_override = "ltx-2",
+ )
+ assert seen["device"] is (sentinel if direct else None)
+ assert seen["text_encoder_device"] is (sentinel if te_direct else None)
+ assert bool(asked) is direct
+ backend.unload()
diff --git a/studio/backend/tests/test_video_fast_pin.py b/studio/backend/tests/test_video_fast_pin.py
new file mode 100644
index 00000000000..e359d7db47b
--- /dev/null
+++ b/studio/backend/tests/test_video_fast_pin.py
@@ -0,0 +1,188 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""The video loads' fast background pin: registered host memory filled on worker threads, same bytes and results."""
+
+import gc
+import types
+
+import pytest
+
+torch = pytest.importorskip("torch")
+
+import core.inference.diffusion_memory as mem # noqa: E402
+
+needs_cuda = pytest.mark.skipif(not torch.cuda.is_available(), reason = "needs a CUDA device")
+
+
+class _Pipe:
+ pass
+
+
+def test_fast_pins_are_requested_per_pipe_and_have_a_kill_switch(monkeypatch):
+ pipe = _Pipe()
+ assert not getattr(pipe, mem._FAST_PIN_REQUEST_ATTR, False)
+ mem.request_fast_pins(pipe)
+ assert getattr(pipe, mem._FAST_PIN_REQUEST_ATTR) is True
+ for off in ("0", "off", "false", "no"):
+ monkeypatch.setenv(mem.FAST_PIN_ENV, off)
+ assert mem._fast_pin_supported() is False
+ monkeypatch.delenv(mem.FAST_PIN_ENV)
+ monkeypatch.setattr(mem.sys, "platform", "win32")
+ assert mem._fast_pin_supported() is False
+
+
+def test_a_pipe_without_the_request_keeps_the_allocator_pin(monkeypatch):
+ # Image pipelines never ask, so their pinner is unchanged even where registration is supported.
+ monkeypatch.setattr(mem, "_fast_pin_supported", lambda: True)
+ monkeypatch.setattr(mem, "_offload_groups", lambda module: [types.SimpleNamespace()])
+ plain, fast = _Pipe(), _Pipe()
+ mem.request_fast_pins(fast)
+ assert mem._defer_pinning(plain, object(), "cuda", None)
+ assert mem._defer_pinning(fast, object(), "cuda", None)
+ assert getattr(plain, mem._PENDING_PINS_ATTR)[0].fast is False
+ assert getattr(fast, mem._PENDING_PINS_ATTR)[0].fast is True
+
+
+@needs_cuda
+ "src",
+ [
+ lambda: torch.randn(37, 41).to(torch.bfloat16),
+ lambda: torch.arange(5000, dtype = torch.int64),
+ lambda: torch.randn(3, 1),
+ lambda: torch.randn(8, 8)[:, ::2],
+ ],
+ ids = ["bf16", "int64", "tiny", "strided"],
+)
+def test_registered_copy_is_pinned_and_byte_identical(src):
+ src = src()
+ out = mem.registered_host_copy(src)
+ assert out.is_pinned() and out.device.type == "cpu"
+ assert out.dtype == src.dtype and out.shape == src.shape and torch.equal(out, src)
+ assert out.data_ptr() % 4096 == 0
+ up = out.to("cuda", non_blocking = True)
+ torch.cuda.synchronize()
+ assert torch.equal(up.cpu(), src)
+
+
+@needs_cuda
+def test_the_last_view_releasing_its_buffer_unregisters_it():
+ calls = []
+ real = torch.cuda.cudart()
+ proxy = types.SimpleNamespace(
+ cudaHostRegister = real.cudaHostRegister,
+ cudaHostUnregister = lambda ptr: (calls.append(ptr), real.cudaHostUnregister(ptr))[1],
+ )
+ holder = mem._RegisteredHostBuffer(1 << 20)
+ holder._cudart = proxy
+ holder.register()
+ import numpy as np
+
+ view = torch.from_numpy(np.asarray(holder))
+ ptr = holder.ptr
+ del holder
+ gc.collect()
+ assert calls == [] # the tensor still holds the buffer
+ del view
+ gc.collect()
+ assert calls == [ptr]
+
+
+@needs_cuda
+def test_a_fast_deferred_pin_renders_identically_and_ends_with_every_group_registered():
+ pytest.importorskip("diffusers")
+ from diffusers.hooks import apply_group_offloading
+
+ def _net():
+ torch.manual_seed(0)
+ net = torch.nn.Sequential(
+ *[
+ torch.nn.Sequential(
+ torch.nn.Linear(256, 384), torch.nn.GELU(), torch.nn.Linear(384, 256)
+ )
+ for _ in range(6)
+ ]
+ )
+ return net.to(torch.bfloat16)
+
+ def _offload(net, pinned):
+ apply_group_offloading(
+ net,
+ onload_device = torch.device("cuda"),
+ offload_device = torch.device("cpu"),
+ offload_type = "leaf_level",
+ use_stream = True,
+ low_cpu_mem_usage = not pinned,
+ )
+ return net
+
+ mem.install_group_pin_wait()
+ x = torch.randn(8, 256, dtype = torch.bfloat16, device = "cuda")
+ with torch.no_grad():
+ ref = _offload(_net(), pinned = True)(x)
+ pipe, net = _Pipe(), _offload(_net(), pinned = False)
+ mem.request_fast_pins(pipe)
+ before = {id(p): p.detach().clone() for p in net.parameters()}
+ assert mem._defer_pinning(pipe, net, torch.device("cuda"), None)
+ assert getattr(pipe, mem._PENDING_PINS_ATTR)[0].fast is mem._fast_pin_supported()
+ assert mem.start_background_pins(pipe) == 1
+ with torch.no_grad():
+ out = net(x)
+ again = net(x)
+ torch.cuda.synchronize()
+ mem.finish_background_pins(pipe)
+ assert torch.equal(out, ref) and torch.equal(again, ref)
+ groups = mem._offload_groups(net)
+ assert groups and all(t.is_pinned() for g in groups for t in g.cpu_param_dict.values())
+ for p in net.parameters():
+ assert torch.equal(p.detach(), before[id(p)])
+
+
+_OTHER_THREAD_RELEASE = r"""
+import ctypes, gc, threading
+import torch
+import core.inference.diffusion_memory as mem
+
+cuda = ctypes.CDLL("libcuda.so.1")
+
+
+def primary_active(dev):
+ flags, active = ctypes.c_uint(), ctypes.c_int()
+ cuda.cuDevicePrimaryCtxGetState(dev, ctypes.byref(flags), ctypes.byref(active))
+ return active.value
+
+
+torch.cuda.set_device(1)
+torch.zeros(1, device = "cuda:1")
+held = {"t": mem.registered_host_copy(torch.randn(1 << 16))}
+threading.Thread(target = lambda: (held.pop("t"), gc.collect())).start()
+for t in threading.enumerate():
+ if t is not threading.current_thread():
+ t.join()
+print("DEV0_CONTEXT", primary_active(0))
+"""
+
+
+ not torch.cuda.is_available() or torch.cuda.device_count() < 2 or torch.version.hip,
+ reason = "needs two CUDA devices",
+)
+def test_releasing_a_buffer_on_another_thread_syncs_its_own_card():
+ # A buffer registered for cuda:1 and freed on a thread still on device 0 must wait on cuda:1, never open a
+ # context on cuda:0 (a bare synchronize() did both wrong).
+ import os
+ import subprocess
+ import sys
+ from pathlib import Path
+
+ backend = Path(__file__).resolve().parents[1]
+ r = subprocess.run(
+ [sys.executable, "-c", _OTHER_THREAD_RELEASE],
+ cwd = str(backend),
+ env = dict(os.environ, PYTHONPATH = str(backend)),
+ capture_output = True,
+ text = True,
+ timeout = 300,
+ )
+ assert "DEV0_CONTEXT 0" in r.stdout, r.stdout[-2000:] + r.stderr[-2000:]
diff --git a/studio/backend/tests/test_video_ltx23_direct_load.py b/studio/backend/tests/test_video_ltx23_direct_load.py
new file mode 100644
index 00000000000..69204f58d9f
--- /dev/null
+++ b/studio/backend/tests/test_video_ltx23_direct_load.py
@@ -0,0 +1,156 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""The LTX-2.3 direct checkpoint read: same bytes, shapes and dtypes as the safetensors loader, in chunks."""
+
+import types
+
+import pytest
+
+torch = pytest.importorskip("torch")
+safetensors_torch = pytest.importorskip("safetensors.torch")
+
+from core.inference import video_ltx2 # noqa: E402
+
+
+def _write_checkpoint(path):
+ gen = torch.Generator().manual_seed(0)
+ tensors = {
+ "model.diffusion_model.a.weight": torch.randn(37, 41, generator = gen).to(torch.bfloat16),
+ "model.diffusion_model.scale_shift_table": torch.randn(9, 13, generator = gen),
+ "vae.decoder.conv.weight": torch.randn(3, 5, 7, generator = gen).to(torch.float16),
+ "model.diffusion_model.empty": torch.empty(0, 4),
+ "model.diffusion_model.ids": torch.arange(11, dtype = torch.int64),
+ "model.diffusion_model.mask": torch.tensor([True, False, True]),
+ "model.diffusion_model.scalar": torch.tensor(3.5),
+ }
+ safetensors_torch.save_file(tensors, str(path))
+ return tensors
+
+
+def _assert_same(got, want):
+ assert set(got) == set(want)
+ for name, tensor in want.items():
+ assert got[name].dtype == tensor.dtype, name
+ assert tuple(got[name].shape) == tuple(tensor.shape), name
+ assert torch.equal(got[name].cpu(), tensor), name
+
+
[email protected]("chunk_bytes", [7, 64, 1 << 20])
+def test_read_matches_the_safetensors_loader_on_the_host(tmp_path, chunk_bytes):
+ path = tmp_path / "ltx.safetensors"
+ want = _write_checkpoint(path)
+ got = video_ltx2.read_safetensors_to_device(path, "cpu", chunk_bytes = chunk_bytes)
+ _assert_same(got, want)
+
+
+def test_read_keeps_only_the_requested_tensors(tmp_path):
+ path = tmp_path / "ltx.safetensors"
+ want = _write_checkpoint(path)
+ got = video_ltx2.read_safetensors_to_device(
+ path, "cpu", keep = lambda key: video_ltx2._checkpoint_group(key)[0] != "dit", chunk_bytes = 16
+ )
+ _assert_same(got, {"vae.decoder.conv.weight": want["vae.decoder.conv.weight"]})
+
+
[email protected](not torch.cuda.is_available(), reason = "needs a CUDA device")
[email protected]("buffers, threads", [(1, 1), (2, 3), (16, 8)])
+def test_read_matches_the_safetensors_loader_on_cuda(tmp_path, buffers, threads):
+ # Tiny chunks and a small ring make every slot get reused many times while uploads are in flight.
+ path = tmp_path / "ltx.safetensors"
+ want = _write_checkpoint(path)
+ got = video_ltx2.read_safetensors_to_device(
+ path, "cuda", chunk_bytes = 32, buffers = buffers, threads = threads
+ )
+ assert all(t.device.type == "cuda" for t in got.values())
+ _assert_same(got, want)
+
+
+def test_unmapped_dtype_returns_none(tmp_path, monkeypatch):
+ path = tmp_path / "ltx.safetensors"
+ _write_checkpoint(path)
+ monkeypatch.delitem(video_ltx2._SAFETENSORS_DTYPES, "BF16")
+ assert video_ltx2.read_safetensors_to_device(path, "cpu") is None
+
+
+def test_full_checkpoint_reader_declines_gguf_and_falls_back_on_errors(tmp_path, monkeypatch):
+ assert video_ltx2.load_checkpoint_to_device(tmp_path / "ltx.gguf", "cpu") is None
+ path = tmp_path / "ltx.safetensors"
+ _write_checkpoint(path)
+
+ def _boom(*a, **k):
+ raise RuntimeError("CUDA out of memory")
+
+ monkeypatch.setattr(video_ltx2, "read_safetensors_to_device", _boom)
+ assert video_ltx2.load_checkpoint_to_device(path, "cpu") is None
+ assert video_ltx2._load_checkpoint_without_dit_to_device(path, "cpu") is None
+
+
+def test_direct_load_device_is_cuda_only_and_has_a_kill_switch(monkeypatch):
+ monkeypatch.delenv(video_ltx2.DIRECT_LOAD_ENV, raising = False)
+ assert video_ltx2.direct_load_device("cpu") is None
+ assert video_ltx2.direct_load_device("mps") is None
+ assert video_ltx2.direct_load_device(None) is None
+ if torch.cuda.is_available():
+ assert video_ltx2.direct_load_device("cuda") == torch.device(
+ "cuda", torch.cuda.current_device()
+ )
+ assert video_ltx2.direct_load_device("cuda:0") == torch.device("cuda", 0)
+ for off in ("0", "off", "false", "no"):
+ monkeypatch.setenv(video_ltx2.DIRECT_LOAD_ENV, off)
+ assert video_ltx2.direct_load_device("cuda:0") is None
+
+
+class _Module(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.weight = torch.nn.Parameter(torch.zeros(2))
+
+
+class _Pipe:
+ def __init__(self):
+ self.text_encoder = _Module()
+ self.transformer = _Module()
+ self.moved = []
+
+ @property
+ def components(self):
+ return {"text_encoder": self.text_encoder, "transformer": self.transformer}
+
+ def to(self, device):
+ self.moved.append(str(device))
+ return self
+
+
+def _plan(policy, **extra):
+ return types.SimpleNamespace(offload_policy = policy, reasons = (), **extra)
+
+
+def test_direct_loaded_modules_go_back_to_the_host_only_when_the_plan_moved_on(monkeypatch):
+ from core.inference import video as video_mod
+
+ monkeypatch.setattr(video_mod, "_video_plan_label", lambda plan: plan.offload_policy)
+ # Still resident: nothing moves.
+ pipe = _Pipe()
+ video_mod._return_direct_loaded_modules(pipe, _plan("none"))
+ assert pipe.moved == []
+ pipe = _Pipe()
+ video_mod._return_direct_loaded_modules(
+ pipe, _plan("group", stream_transformer = False, stream_text_encoders = False)
+ )
+ assert pipe.moved == []
+ # The DiT is offloaded now: the whole pipeline returns to the host, where offload starts from.
+ pipe = _Pipe()
+ video_mod._return_direct_loaded_modules(pipe, _plan("group", stream_transformer = True))
+ assert pipe.moved == ["cpu"]
+ pipe = _Pipe()
+ video_mod._return_direct_loaded_modules(pipe, _plan("model"))
+ assert pipe.moved == ["cpu"]
+ # The DiT stays but the encoders stream: only an encoder already on a device goes back (here: on the host).
+ pipe = _Pipe()
+ calls = []
+ pipe.text_encoder.to = lambda device: calls.append(device)
+ video_mod._return_direct_loaded_modules(
+ pipe, _plan("group", stream_transformer = False, stream_text_encoders = True)
+ )
+ assert pipe.moved == [] and calls == []
diff --git a/studio/backend/tests/test_video_ltx23_prefetch.py b/studio/backend/tests/test_video_ltx23_prefetch.py
new file mode 100644
index 00000000000..bc2983329af
--- /dev/null
+++ b/studio/backend/tests/test_video_ltx23_prefetch.py
@@ -0,0 +1,136 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Warming the base repo's text encoder shards in the page cache beside the LTX-2.3 checkpoint read."""
+
+import json
+import threading
+
+import pytest
+
+from core.inference import video_ltx2
+
+
+def _wait_for_prefetch_threads(timeout = 10.0):
+ for t in [t for t in threading.enumerate() if t.name.startswith("unsloth-prefetch")]:
+ t.join(timeout)
+ assert not t.is_alive(), "prefetch threads never finished"
+
+
+def _fake_cache(
+ tmp_path, shards = ("model-00001-of-00002.safetensors", "model-00002-of-00002.safetensors")
+):
+ commit = "a" * 40
+ repo = tmp_path / "models--Lightricks--LTX-2"
+ (repo / "refs").mkdir(parents = True)
+ (repo / "refs" / "main").write_text(commit)
+ folder = repo / "snapshots" / commit / "text_encoder"
+ folder.mkdir(parents = True)
+ weight_map = {f"w{i}": name for i, name in enumerate(shards)}
+ (folder / "model.safetensors.index.json").write_text(json.dumps({"weight_map": weight_map}))
+ for name in shards:
+ (folder / name).write_bytes(b"x" * 4096 * 3)
+ return folder
+
+
+def test_prefetch_has_a_kill_switch(monkeypatch):
+ monkeypatch.delenv(video_ltx2.PREFETCH_ENV, raising = False)
+ assert video_ltx2.prefetch_enabled()
+ for off in ("0", "off", "false", "no"):
+ monkeypatch.setenv(video_ltx2.PREFETCH_ENV, off)
+ assert not video_ltx2.prefetch_enabled()
+
+
+def test_text_encoder_files_come_from_the_cached_index_only(tmp_path):
+ folder = _fake_cache(tmp_path)
+ files = video_ltx2._text_encoder_files("Lightricks/LTX-2", str(tmp_path))
+ assert files == sorted(str(p) for p in folder.glob("model-*.safetensors"))
+ # A shard the index names but the cache lacks is left to the loader; an uncached repo yields nothing.
+ (folder / "model-00002-of-00002.safetensors").unlink()
+ assert video_ltx2._text_encoder_files("Lightricks/LTX-2", str(tmp_path)) == files[:1]
+ assert video_ltx2._text_encoder_files("Lightricks/LTX-2.3", str(tmp_path)) == []
+
+
+def test_uncached_bytes_reads_zero_once_a_file_was_read(tmp_path):
+ path = tmp_path / "w.safetensors"
+ path.write_bytes(b"y" * (1 << 20))
+ path.read_bytes()
+ assert video_ltx2._uncached_bytes(str(path)) == 0
+ empty = tmp_path / "empty"
+ empty.write_bytes(b"")
+ assert video_ltx2._uncached_bytes(str(empty)) == 0
+
+
+def _pretend_cold(monkeypatch, available_mib = 1 << 30):
+ from core.inference import diffusion_memory
+ monkeypatch.setattr(video_ltx2, "_uncached_bytes", lambda path: 2 << 30)
+ monkeypatch.setattr(diffusion_memory, "_available_system_memory_mib", lambda: available_mib)
+
+
+def test_prefetch_reads_every_uncached_file(tmp_path, monkeypatch):
+ folder = _fake_cache(tmp_path)
+ files = video_ltx2._text_encoder_files("Lightricks/LTX-2", str(tmp_path))
+ _pretend_cold(monkeypatch)
+ opened = []
+ real_open = open
+
+ def _open(path, *a, **k):
+ opened.append(str(path))
+ return real_open(path, *a, **k)
+
+ monkeypatch.setattr(video_ltx2, "open", _open, raising = False)
+ stop = video_ltx2.start_prefetch(files)
+ assert stop is not None
+ _wait_for_prefetch_threads()
+ assert sorted(set(opened)) == files
+ assert folder.exists()
+
+
+def test_prefetch_declines_a_warm_cache_or_a_small_host(tmp_path, monkeypatch):
+ _fake_cache(tmp_path)
+ files = video_ltx2._text_encoder_files("Lightricks/LTX-2", str(tmp_path))
+ monkeypatch.setattr(video_ltx2, "_uncached_bytes", lambda path: 0)
+ assert video_ltx2.start_prefetch(files) is None
+ # 4 GiB to warm against 6 GiB available: it would push other pages out, so it is left to the loader.
+ _pretend_cold(monkeypatch, available_mib = 6 << 10)
+ assert video_ltx2.start_prefetch(files) is None
+ _pretend_cold(monkeypatch, available_mib = None)
+ assert video_ltx2.start_prefetch(files) is None
+ assert video_ltx2.start_prefetch([]) is None
+
+
[email protected]("fails", [False, True])
+def test_the_pipeline_load_stops_its_prefetch(monkeypatch, fails):
+ stop = threading.Event()
+ started = []
+ monkeypatch.delenv(video_ltx2.PREFETCH_ENV, raising = False)
+ monkeypatch.setattr(video_ltx2, "_text_encoder_files", lambda repo, cache: ["a", "b"])
+ monkeypatch.setattr(video_ltx2, "_live_cache_dir", lambda: "cache")
+ monkeypatch.setattr(video_ltx2, "start_prefetch", lambda paths: started.append(paths) or stop)
+
+ def _assemble(checkpoint_path, **kwargs):
+ assert started == [["a", "b"]] and not stop.is_set()
+ if fails:
+ raise RuntimeError("CUDA out of memory")
+ return "pipe"
+
+ monkeypatch.setattr(video_ltx2, "_assemble_ltx23_pipeline", _assemble)
+ if fails:
+ with pytest.raises(RuntimeError):
+ video_ltx2.load_ltx23_pipeline("ltx.safetensors", base_repo = "Lightricks/LTX-2")
+ else:
+ assert (
+ video_ltx2.load_ltx23_pipeline("ltx.safetensors", base_repo = "Lightricks/LTX-2")
+ == "pipe"
+ )
+ assert stop.is_set()
+
+
+def test_a_supplied_encoder_needs_no_prefetch(monkeypatch):
+ calls = []
+ monkeypatch.setattr(video_ltx2, "start_prefetch", lambda paths: calls.append(paths))
+ monkeypatch.setattr(video_ltx2, "_assemble_ltx23_pipeline", lambda path, **kwargs: kwargs)
+ out = video_ltx2.load_ltx23_pipeline(
+ "ltx.safetensors", base_repo = "Lightricks/LTX-2", text_encoder = "fp8", is_gguf = False
+ )
+ assert calls == [] and out["text_encoder"] == "fp8" and out["is_gguf"] is False
diff --git a/studio/backend/utils/torch_warmup.py b/studio/backend/utils/torch_warmup.py
index 81149dbea19..f69646a6b00 100644
--- a/studio/backend/utils/torch_warmup.py
+++ b/studio/backend/utils/torch_warmup.py
@@ -469,6 +469,8 @@ def _clear_finished_warm_locked() -> None:
DIFFUSERS_PREWARM_DISABLE_ENV_VAR = "UNSLOTH_STUDIO_DISABLE_DIFFUSERS_PREWARM"
+DIFFUSERS_PREWARM_MODELS_ENV_VAR = "UNSLOTH_STUDIO_DIFFUSERS_PREWARM_MODELS"
+_DIFFUSERS_PREWARM_MODEL_MODULES = ("diffusers.models.transformers",)
# The catalog's own task identifiers, which _build_index compares with ==. Anything else
# (a friendly "image"/"video") silently builds an empty index and reads as "no models here",
@@ -549,6 +551,20 @@ def _is_native_video_pick(pick) -> bool:
return False
+def _prewarm_quant_probe() -> None:
+ """Run the 4-5 s quant smoke probe here instead of at the first image load; never fatal."""
+ try:
+ from core.inference.diffusion_transformer_quant import prewarm_probe_table # noqa: PLC0415
+ started = time.perf_counter()
+ if prewarm_probe_table():
+ logger.info(
+ "quant smoke probe prewarmed in %.0fms; the first quantised load skips it",
+ (time.perf_counter() - started) * 1000,
+ )
+ except Exception as exc: # noqa: BLE001 -- the load path probes again and reports
+ logger.debug("quant smoke probe prewarm skipped: %r", exc)
+
+
def prewarm_diffusers_if_image_models_exist() -> bool:
"""Import diffusers off the first image load. True iff this call did the import.
@@ -624,6 +640,22 @@ def prewarm_diffusers_if_image_models_exist() -> bool:
purge_partial_import("diffusers.hooks")
return False
+ # The model classes too (1.5-3.7 s of the first load); own scope for the same lock-order reason as above.
+ if os.environ.get(DIFFUSERS_PREWARM_MODELS_ENV_VAR, "").strip().lower() not in (
+ "0",
+ "false",
+ "no",
+ "off",
+ ):
+ for module_name in _DIFFUSERS_PREWARM_MODEL_MODULES:
+ with _ModuleLockManager(module_name):
+ try:
+ importlib.import_module(module_name)
+ except Exception as exc: # noqa: BLE001 -- the load path imports it again and reports
+ logger.debug("diffusers model prewarm of %s skipped: %r", module_name, exc)
+ purge_partial_import(module_name)
+ break
+
# Outside both locks: it imports nothing under diffusers. diffusers hard-codes
# diffusers hard-codes _tqdm_active = True and honours no env var, so without this
# its bars draw onto the structlog stream mid-record.
@@ -638,6 +670,7 @@ def prewarm_diffusers_if_image_models_exist() -> bool:
"diffusers prewarmed in %.0fms; the first image load skips that import",
(time.perf_counter() - started) * 1000,
)
+ _prewarm_quant_probe()
return True