Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio video: pre-seed the denoiser compile's float specialisations on a returning load (#15406)

Daniel Hane417bfd22cad
diff --git a/studio/backend/core/inference/diffusion_bg_compile.py b/studio/backend/core/inference/diffusion_bg_compile.py
index 222f44ca966..8de5b8b5232 100644
--- a/studio/backend/core/inference/diffusion_bg_compile.py
+++ b/studio/backend/core/inference/diffusion_bg_compile.py
@@ -114,6 +114,14 @@ def _code_signature(module: Any) -> Optional[str]:
return None
+def _modules_signature(modules: Any) -> Optional[str]:
+ modules = list(modules) if isinstance(modules, (list, tuple)) else [modules]
+ sigs = [_code_signature(m) for m in modules]
+ if not sigs or any(s is None for s in sigs):
+ return None
+ return sigs[0] if len(sigs) == 1 else hashlib.sha256("|".join(sigs).encode("utf-8")).hexdigest()
+
+
def _read_float_seeds(path: Path, signature: str) -> set:
try:
data = json.loads(path.read_text(encoding = "utf-8"))
@@ -148,6 +156,91 @@ def _write_float_seeds(path: Path, signature: str, names: set) -> bool:
return False
+def _seed_floats(modules: Any, seed_dir: Optional[Path]) -> tuple[Optional[tuple], int]:
+ """Pre-seed the SymFloat names the last compile of this key learned; returns (keep state, names added)."""
+ if seed_dir is None or not float_seeds_enabled():
+ return None, 0
+ try:
+ state = _tensorify_state()
+ signature = _modules_signature(modules)
+ if state is None or signature is None:
+ return None, 0
+ path = Path(seed_dir) / FLOAT_SEEDS_FILE
+ before = set(state.force_specializations)
+ seeds = _read_float_seeds(path, signature)
+ for name in sorted(seeds - before):
+ state.specialize(name)
+ return (state, path, signature, before, seeds), len(seeds - before)
+ except Exception: # noqa: BLE001 - no seeds: the compile restarts as before
+ return None, 0
+
+
+def _keep_floats(seeded: Optional[tuple]) -> int:
+ """Save this compile's specialised names if changed; returns how many are new."""
+ if seeded is None:
+ return 0
+ state, path, signature, before, seeds = seeded
+ try:
+ names = {
+ n for n in set(state.force_specializations) - before if _SYMFLOAT_NAME.match(str(n))
+ }
+ names |= seeds & set(state.force_specializations)
+ if names and names != seeds:
+ _write_float_seeds(path, signature, names)
+ return len(names - seeds)
+ except Exception: # noqa: BLE001 - bookkeeping only
+ return 0
+
+
+class InlineFloatSeeds:
+ """Float seeds for a compile inside a render (video's first clip): ``seed`` at denoise entry, ``keep`` at decode
+ entry, so only the denoiser's names are saved. Never raises."""
+
+ def __init__(
+ self,
+ modules: Any,
+ seed_dir: Any,
+ *,
+ logger: Any = None,
+ ) -> None:
+ self.modules = list(modules) if isinstance(modules, (list, tuple)) else [modules]
+ self.seed_dir = Path(seed_dir) if seed_dir else None
+ self.logger = logger
+ self.float_seeds = 0
+ self.float_seeds_learned = 0
+ self.seeded = False
+ self.kept = False
+ self._seeds: Optional[tuple] = None
+
+ def seed(self) -> int:
+ if self.seeded:
+ return 0
+ self.seeded = True
+ self._seeds, self.float_seeds = _seed_floats(self.modules, self.seed_dir)
+ if self.float_seeds and self.logger is not None:
+ with contextlib.suppress(Exception):
+ self.logger.info(
+ "diffusion.float_seeds: %d float specialisation(s) pre-seeded for the %s compile",
+ self.float_seeds,
+ "/".join(type(m).__name__ for m in self.modules),
+ )
+ return self.float_seeds
+
+ def keep(self) -> None:
+ if not self.seeded or self.kept:
+ return
+ self.kept = True
+ self.float_seeds_learned = _keep_floats(self._seeds)
+ self._seeds = None
+ self.modules = []
+
+ def done(self) -> bool:
+ return self.kept
+
+ def describe(self) -> dict:
+ return {"float_seeds": self.float_seeds, "float_seeds_learned": self.float_seeds_learned}
+
+
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()
@@ -621,37 +714,11 @@ class BackgroundCompile:
def _seed_floats(self) -> Optional[tuple]:
"""Pre-seed the SymFloat specialisations this key's last compile learned; returns what ``_keep_floats`` needs."""
- if self.seed_dir is None or not float_seeds_enabled():
- return None
- try:
- state = _tensorify_state()
- signature = _code_signature(self.module)
- if state is None or signature is None:
- return None
- path = self.seed_dir / FLOAT_SEEDS_FILE
- before = set(state.force_specializations)
- seeds = _read_float_seeds(path, signature)
- for name in sorted(seeds - before):
- state.specialize(name)
- self.float_seeds = len(seeds - before)
- return (state, path, signature, before, seeds)
- except Exception: # noqa: BLE001 - no seeds: the compile restarts as before
- return None
+ seeded, self.float_seeds = _seed_floats(self.module, self.seed_dir)
+ return seeded
def _keep_floats(self, seeded: Optional[tuple]) -> None:
- if seeded is None:
- return
- state, path, signature, before, seeds = seeded
- try:
- names = {
- n for n in set(state.force_specializations) - before if _SYMFLOAT_NAME.match(str(n))
- }
- names |= seeds & set(state.force_specializations)
- self.float_seeds_learned = len(names - seeds)
- if names and names != seeds:
- _write_float_seeds(path, signature, names)
- except Exception: # noqa: BLE001 - bookkeeping only
- pass
+ self.float_seeds_learned = _keep_floats(seeded)
def close(self, timeout: Optional[float] = None) -> None:
"""Stop recording and wait for an in-flight compile (it holds the module); used on unload."""
diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.py
index 12f844f536a..b9a6915481a 100644
--- a/studio/backend/core/inference/video.py
+++ b/studio/backend/core/inference/video.py
@@ -1218,6 +1218,69 @@ def _settle_bg_compile(bg: Any, *, i2v: bool) -> None:
bg.abandon("an image-to-video render records no compile sample")
+def _float_seed_dits(pipe: Any) -> list:
+ """DiTs compiled with ``dynamic=True`` (SymFloat restarts); static and torchao compiles never restart."""
+ try:
+ from .diffusion_speed import _guarded_dits
+
+ dits = []
+ for dit in _guarded_dits(pipe):
+ kwargs = getattr(dit, "_unsloth_regional_compile_kwargs", None)
+ if isinstance(kwargs, dict) and kwargs.get("dynamic") is True:
+ dits.append(dit)
+ return dits
+ except Exception: # noqa: BLE001 - no seeds, main's compile
+ return []
+
+
+def _seed_before_first_forward(float_seeds: Any):
+ """Also seed at the first DiT forward: H3 modular's progress bar is its loop wrapper's, not the pipe's."""
+ handles = []
+
+ def _pre(*_args: Any) -> None:
+ float_seeds.seed()
+
+ try:
+ for module in list(getattr(float_seeds, "modules", None) or ()):
+ with contextlib.suppress(Exception):
+ handles.append(module.register_forward_pre_hook(_pre))
+ yield
+ finally:
+ for handle in handles:
+ with contextlib.suppress(Exception):
+ handle.remove()
+
+
+def _video_float_seed_dir(
+ pipe: Any, *, family: Any, dtype: Any, quant: Any, attention_backend: Any
+) -> tuple[list, Optional[Path]]:
+ """(DiTs, per-key seed dir keyed like the image compile cache), or ([], None). Video has no compile-cache ctx."""
+ from . import diffusion_bg_compile
+
+ if not diffusion_bg_compile.float_seeds_enabled():
+ return [], None
+ dits = _float_seed_dits(pipe)
+ if not dits:
+ return [], None
+ try:
+ from . import diffusion_compile_cache as cc
+
+ model_fp = cc.model_fingerprint(
+ family = family,
+ transformer = dits[0],
+ dtype = str(dtype).replace("torch.", ""),
+ quant = quant,
+ attention_backend = attention_backend,
+ compile_kwargs = dict(dits[0]._unsloth_regional_compile_kwargs),
+ )
+ model_fp["video_dits"] = [type(d).__name__ for d in dits]
+ key = cc.cache_key(cc.environment_fingerprint(), model_fp)
+ return dits, cc.cache_root() / "video_float_seeds" / key
+ except Exception: # noqa: BLE001 - no seeds, main's compile
+ return [], None
+
+
def assert_first_frame_pipeline_available(fam: VideoFamily) -> None:
if video_family_uses_i2v_pipeline(fam) and not _i2v_pipeline_available(fam.i2v_pipeline_class):
raise ValueError(
@@ -4514,6 +4577,7 @@ class VideoBackend:
# (load token, client) of an LTX-2.5 Gemma 4 encoder worker whose load has not committed yet; a failed load stops
# it.
self._ltx25_pending_encoder: Optional[tuple[Optional[int], Any]] = None
+ self._float_seeds: Optional[tuple[Any, Any]] = None
# How many unloads / superseding loads are waiting on _generate_lock to free this pipeline. A generation queued
# behind the active one holds no cancel event yet, so without this fence it could win the lock after an eject
# and denoise a whole new clip against a pipeline being freed. A count, so concurrent teardowns each own their
@@ -4539,6 +4603,29 @@ class VideoBackend:
apply_diffusion_device_ordinal(target)
return target
+ def _inline_float_seeds(self, state: Any) -> Any:
+ """This load's ``InlineFloatSeeds`` until its first compiled clip kept its names, else None."""
+ held = self._float_seeds
+ if held is not None and held[0] is state:
+ return None if held[1] is None or held[1].done() else held[1]
+ seeds = None
+ try:
+ if getattr(state, "bg_compile", None) is None:
+ from . import diffusion_bg_compile
+ dits, seed_dir = _video_float_seed_dir(
+ state.pipe,
+ family = getattr(state.family, "name", None),
+ dtype = state.dtype,
+ quant = state.transformer_quant,
+ attention_backend = state.attention_backend,
+ )
+ if seed_dir is not None:
+ seeds = diffusion_bg_compile.InlineFloatSeeds(dits, seed_dir, logger = logger)
+ except Exception: # noqa: BLE001 - no seeds, main's compile
+ seeds = None
+ self._float_seeds = (state, seeds)
+ return seeds
+
def _state_device_target(self, state: _VideoLoadState) -> DiffusionDeviceTarget:
"""The resident pipeline's target, pinned onto the calling thread. Every worker that
touches the loaded pipeline goes through this: the weights are on ``state.gpu_ordinal``
@@ -9967,7 +10054,19 @@ class VideoBackend:
)
)
load_bg_compile = (
- bg_compile.arm(bg_module, logger = logger) if bg_module is not None else None
+ bg_compile.arm(
+ bg_module,
+ logger = logger,
+ seed_dir = _video_float_seed_dir(
+ pipe,
+ family = fam.name,
+ dtype = dtype,
+ quant = transformer_quant_engaged,
+ attention_backend = attention_engaged,
+ )[1],
+ )
+ if bg_module is not None
+ else None
)
with self._lock:
if _load_token is not None and _load_token != self._load_token:
@@ -11690,6 +11789,7 @@ class VideoBackend:
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
+ float_seeds = None if bg_eager else self._inline_float_seeds(state)
# Closed in the finally so the pipeline is text-to-video again on return, cancel or failure.
i2v_swap = contextlib.ExitStack()
# Encodes Wan chunks while the VAE decodes; closed in the finally on cancel or failure.
@@ -12195,6 +12295,9 @@ class VideoBackend:
previewer = None
def _enter_denoise() -> None:
+ if float_seeds is not None:
+ # Before the first (compiling) denoiser forward.
+ float_seeds.seed()
if self._gen.get("phase") == "encode":
self._gen.update(phase = "denoise")
@@ -12237,6 +12340,9 @@ class VideoBackend:
def _on_decode() -> None:
"""Mark the decode boundary in the stream, retrying under contention; flip when
the GPU reaches it."""
+ if float_seeds is not None:
+ # Before the VAE decode's compile adds its own names.
+ float_seeds.keep()
marked = False
for _ in range(_BOUNDARY_MARK_ATTEMPTS):
with _hold_off_cuda_graph_capture() as clear:
@@ -12300,6 +12406,8 @@ class VideoBackend:
)
stack.enter_context(scheduler_step_preview(pipe, previewer))
stack.enter_context(_denoise_phase(pipe, _enter_denoise))
+ if float_seeds is not None:
+ stack.enter_context(_seed_before_first_forward(float_seeds))
# No video family has a denoise-to-decode callback, so the decoder itself reports the decode phase.
stack.enter_context(_decode_phase(pipe, _on_decode))
# NaN / inf pixels are refused at the decode, before a clamp or PIL / uint8 cast hides them.
@@ -13275,6 +13383,7 @@ class VideoBackend:
cannot observe a half-torn-down backend."""
release_load_budget_fraction("video")
state, self._state = self._state, None
+ self._float_seeds = None
if state is not None:
server_slot = getattr(getattr(state, "pipe", None), "server_slot", None)
if server_slot is not None:
diff --git a/studio/backend/tests/test_video_backend.py b/studio/backend/tests/test_video_backend.py
index cb300753d69..f51a1bd94c9 100644
--- a/studio/backend/tests/test_video_backend.py
+++ b/studio/backend/tests/test_video_backend.py
@@ -1780,6 +1780,93 @@ def test_load_wan_ti2v_5b_pipeline(fake_runtime):
assert backend._state.pipe.vae.decoder.hooks == []
+def test_first_clip_seeds_floats_before_the_denoise_and_keeps_them_before_the_decode(
+ fake_runtime, monkeypatch
+):
+ """Seeds go in at denoise entry and are kept at decode entry."""
+ backend = VideoBackend()
+ backend.load_pipeline("Wan-AI/Wan2.2-TI2V-5B-Diffusers", model_kind = "pipeline")
+ pipe = backend._state.pipe
+ events: list = []
+
+ class _Seeds:
+ def seed(self):
+ events.append("seed")
+
+ def keep(self):
+ events.append("keep")
+
+ asked: list = []
+ monkeypatch.setattr(
+ VideoBackend, "_inline_float_seeds", lambda self, state: asked.append(state) or _Seeds()
+ )
+ original_call = type(pipe).__call__
+
+ @functools.wraps(original_call) # keeps the signature generate() gates its kwargs on
+ def _call(self, *args, **kwargs):
+ with self.progress_bar(total = 2):
+ events.append("denoiser")
+ return original_call(self, *args, **kwargs)
+
+ pipe.__class__ = type("_LoopPipe", (type(pipe),), {"__call__": _call})
+ pipe.progress_bar = lambda *a, **k: contextlib.nullcontext()
+ pipe.vae.on_decode = lambda: events.append("decode")
+ backend.generate(prompt = "a fox", steps = 2)
+ assert asked == [backend._state]
+ assert events[:2] == ["seed", "denoiser"]
+ assert events.index("keep") < events.index("decode")
+ assert events.count("keep") == 1
+
+
+def test_first_clip_seeds_floats_at_the_first_dit_forward_without_a_pipe_progress_bar(
+ fake_runtime, monkeypatch
+):
+ """H3 modular's progress bar is its loop wrapper's: the first DiT forward still seeds first."""
+ backend = VideoBackend()
+ backend.load_pipeline("Wan-AI/Wan2.2-TI2V-5B-Diffusers", model_kind = "pipeline")
+ pipe = backend._state.pipe
+ events: list = []
+
+ class _Dit:
+ def __init__(self):
+ self.hooks = []
+
+ def register_forward_pre_hook(self, fn):
+ self.hooks.append(fn)
+ return types.SimpleNamespace(remove = lambda: self.hooks.remove(fn))
+
+ def __call__(self):
+ for hook in list(self.hooks):
+ hook(self, ())
+ events.append("denoiser")
+
+ dit = _Dit()
+
+ class _Seeds:
+ modules = [dit]
+
+ def seed(self):
+ if "seed" not in events:
+ events.append("seed")
+
+ def keep(self):
+ events.append("keep")
+
+ monkeypatch.setattr(VideoBackend, "_inline_float_seeds", lambda self, state: _Seeds())
+ original_call = type(pipe).__call__
+
+ @functools.wraps(original_call)
+ def _call(self, *args, **kwargs):
+ dit()
+ dit()
+ return original_call(self, *args, **kwargs)
+
+ pipe.__class__ = type("_ModularLikePipe", (type(pipe),), {"__call__": _call})
+ backend.generate(prompt = "a fox", steps = 2)
+ assert events[:3] == ["seed", "denoiser", "denoiser"]
+ assert dit.hooks == []
+
+
def _fits_in_memory_snapshot(device):
"""A memory snapshot big enough that no load is ever refused for size, so a test forcing a
device does not inherit the runner's own free memory as a precondition."""
diff --git a/studio/backend/tests/test_video_float_seeds.py b/studio/backend/tests/test_video_float_seeds.py
new file mode 100644
index 00000000000..45c114988f8
--- /dev/null
+++ b/studio/backend/tests/test_video_float_seeds.py
@@ -0,0 +1,245 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Video first-clip compile float seeds (CPU, ``aot_eager``): the inline counterpart of the background compile's."""
+
+from __future__ import annotations
+
+import json
+import types
+
+import pytest
+
+torch = pytest.importorskip("torch")
+pytest.importorskip("torch._dynamo.symbolic_convert")
+
+from core.inference import diffusion_bg_compile as bg # noqa: E402
+from core.inference import video as video_mod # noqa: E402
+
+if (
+ bg._tensorify_state() is None
+): # pragma: no cover - a torch without TensorifyState has nothing to seed
+ pytest.skip("this torch has no TensorifyState", allow_module_level = True)
+
+
+class Block(torch.nn.Module):
+ def __init__(self) -> None:
+ super().__init__()
+ self.norm = torch.nn.LayerNorm(16, eps = 1e-6)
+ self.lin = torch.nn.Linear(16, 16)
+
+ def forward(self, x):
+ return x + self.lin(self.norm(x))
+
+
+class OtherBlock(Block):
+ def forward(self, x):
+ return x - self.lin(self.norm(x))
+
+
+class Net(torch.nn.Module):
+ _repeated_blocks = ["Block"]
+
+ def __init__(self, dynamic = True) -> None:
+ super().__init__()
+ self.blocks = torch.nn.ModuleList([Block() for _ in range(3)])
+ self._unsloth_regional_compile_kwargs = {"fullgraph": True, "dynamic": dynamic}
+
+ def forward(self, x):
+ for block in self.blocks:
+ x = block(x)
+ return x
+
+
+class OtherNet(Net):
+ _repeated_blocks = ["OtherBlock"]
+
+ def __init__(self) -> None:
+ super().__init__()
+ self.blocks = torch.nn.ModuleList([OtherBlock() for _ in range(2)])
+
+
+def _net() -> Net:
+ torch.manual_seed(0)
+ net = Net().eval()
+ for block in net.blocks:
+ block.compile(backend = "aot_eager", dynamic = True)
+ return net
+
+
[email protected](autouse = True)
+def _fresh_dynamo(monkeypatch, tmp_path):
+ monkeypatch.delenv(bg.FLOAT_SEEDS_ENV, raising = False)
+ monkeypatch.setenv("UNSLOTH_DIFFUSION_COMPILE_CACHE_DIR", str(tmp_path / "cc"))
+ torch._dynamo.reset()
+ yield
+ torch._dynamo.reset()
+
+
+def restarts(monkeypatch):
+ count = {"n": 0}
+ cls = torch._dynamo.exc.TensorifyScalarRestartAnalysis
+ orig = cls.__init__
+
+ def counting(self, *args, **kwargs):
+ count["n"] += 1
+ orig(self, *args, **kwargs)
+
+ monkeypatch.setattr(cls, "__init__", counting)
+ return count
+
+
+def _clip(seed_dir, x):
+ """One load's first clip as video.py runs it: seed at the denoise entry, keep at the decode entry."""
+ net = _net()
+ seeds = bg.InlineFloatSeeds([net], seed_dir)
+ seeds.seed()
+ with torch.no_grad():
+ out = net(x)
+ seeds.keep()
+ return seeds, net, out
+
+
+def test_second_load_traces_once_into_the_same_graph(tmp_path, restarts):
+ x = torch.randn(2, 5, 16)
+ first, _, out_first = _clip(tmp_path, x)
+ assert restarts["n"] >= 1 # the unseeded first clip restarts, as on main
+ saved = json.loads((tmp_path / bg.FLOAT_SEEDS_FILE).read_text(encoding = "utf-8"))
+ assert saved["names"] and saved["signature"] == bg._code_signature(_net())
+ assert first.describe() == {"float_seeds": 0, "float_seeds_learned": len(saved["names"])}
+
+ torch._dynamo.reset()
+ restarts["n"] = 0
+ second, _, out_second = _clip(tmp_path, x)
+ assert restarts["n"] == 0
+ assert second.float_seeds == len(saved["names"]) and second.done()
+ assert torch.equal(out_first, out_second)
+
+
+def test_first_forward_hook_seeds_before_the_compile(tmp_path, restarts):
+ x = torch.randn(2, 5, 16)
+ _clip(tmp_path, x)
+ torch._dynamo.reset()
+ restarts["n"] = 0
+ net = _net()
+ seeds = bg.InlineFloatSeeds([net], tmp_path)
+ with video_mod._seed_before_first_forward(seeds), torch.no_grad():
+ net(x)
+ assert seeds.seeded and seeds.float_seeds > 0 and restarts["n"] == 0
+ assert not net._forward_pre_hooks
+
+
+def test_seeded_first_clip_does_not_recompile_on_later_clips(tmp_path):
+ from torch._dynamo.utils import counters
+
+ x = torch.randn(2, 5, 16)
+ _clip(tmp_path, x)
+ torch._dynamo.reset()
+ _, net, _ = _clip(tmp_path, x)
+ before = counters["stats"].get("unique_graphs", 0)
+ with torch.no_grad():
+ for length in (5, 7, 9):
+ net(torch.randn(2, length, 16))
+ assert counters["stats"].get("unique_graphs", 0) == before
+
+
+def test_seed_and_keep_run_once_and_later_names_are_not_kept(tmp_path):
+ x = torch.randn(2, 5, 16)
+ seeds, _, _ = _clip(tmp_path, x)
+ path = tmp_path / bg.FLOAT_SEEDS_FILE
+ saved = path.read_text(encoding = "utf-8")
+ # A later compile in the process (the VAE decode's, another backend's) adds names after the keep.
+ bg._tensorify_state().specialize("zf99")
+ assert seeds.seed() == 0
+ seeds.keep()
+ assert path.read_text(encoding = "utf-8") == saved
+ assert seeds.modules == [] # the DiTs are not held past the keep
+
+
+def test_kill_switch_keeps_the_restart(tmp_path, restarts, monkeypatch):
+ monkeypatch.setenv(bg.FLOAT_SEEDS_ENV, "0")
+ x = torch.randn(2, 5, 16)
+ _clip(tmp_path, x)
+ assert not (tmp_path / bg.FLOAT_SEEDS_FILE).exists()
+ torch._dynamo.reset()
+ restarts["n"] = 0
+ seeds, _, _ = _clip(tmp_path, x)
+ assert restarts["n"] >= 1 and seeds.float_seeds == 0
+
+
+def test_a_single_module_list_signs_like_the_background_compile():
+ a, b = Net(), OtherNet()
+ assert bg._modules_signature([a]) == bg._code_signature(a) == bg._modules_signature(a)
+ pair = bg._modules_signature([a, b])
+ assert pair not in (None, bg._code_signature(a), bg._code_signature(b))
+ assert bg._modules_signature([a, torch.nn.Linear(2, 2)]) is None
+
+
+def test_only_dynamic_regional_compiles_take_seeds():
+ dense, static, plain = Net(), Net(dynamic = False), torch.nn.Linear(2, 2)
+ assert video_mod._float_seed_dits(types.SimpleNamespace(transformer = dense)) == [dense]
+ # LTX-2 / 2.5 compile static: no SymFloat, no restart, nothing to seed.
+ assert video_mod._float_seed_dits(types.SimpleNamespace(transformer = static)) == []
+ assert video_mod._float_seed_dits(types.SimpleNamespace(transformer = plain)) == []
+ both = types.SimpleNamespace(transformer = dense, transformer_2 = Net())
+ assert video_mod._float_seed_dits(both) == [dense, both.transformer_2]
+
+
+def _seed_dir(pipe, **over):
+ kw = {
+ "family": "wan2.1-t2v-1.3b",
+ "dtype": "bfloat16",
+ "quant": None,
+ "attention_backend": None,
+ }
+ kw.update(over)
+ return video_mod._video_float_seed_dir(pipe, **kw)
+
+
+def test_seed_dir_is_keyed_like_the_compile_cache(tmp_path, monkeypatch):
+ net = Net()
+ pipe = types.SimpleNamespace(transformer = net)
+ dits, path = _seed_dir(pipe)
+ assert dits == [net]
+ assert path.parent == tmp_path / "cc" / "video_float_seeds" and len(path.name) == 32
+ assert _seed_dir(pipe, dtype = torch.bfloat16)[1] == path
+ assert _seed_dir(pipe, dtype = "float16")[1] != path
+ assert _seed_dir(pipe, quant = "int8")[1] != path
+ assert _seed_dir(pipe, family = "wan2.2-ti2v-5b")[1] != path
+ assert _seed_dir(types.SimpleNamespace(transformer = Net(dynamic = False))) == ([], None)
+ monkeypatch.setenv(bg.FLOAT_SEEDS_ENV, "0")
+ assert _seed_dir(pipe) == ([], None)
+
+
+def _state(pipe, bg_compile = None):
+ return types.SimpleNamespace(
+ pipe = pipe,
+ family = types.SimpleNamespace(name = "wan2.1-t2v-1.3b"),
+ dtype = "bfloat16",
+ transformer_quant = None,
+ attention_backend = None,
+ bg_compile = bg_compile,
+ )
+
+
+def test_backend_holds_one_seeder_per_load_until_it_kept():
+ backend = video_mod.VideoBackend()
+ state = _state(types.SimpleNamespace(transformer = Net()))
+ seeds = backend._inline_float_seeds(state)
+ assert isinstance(seeds, bg.InlineFloatSeeds)
+ assert backend._inline_float_seeds(state) is seeds
+ seeds.seed()
+ seeds.keep()
+ assert backend._inline_float_seeds(state) is None
+ other = _state(types.SimpleNamespace(transformer = Net()))
+ fresh = backend._inline_float_seeds(other)
+ assert fresh is not None and fresh is not seeds
+
+
+def test_backend_leaves_a_background_compile_its_own_seeds():
+ backend = video_mod.VideoBackend()
+ state = _state(types.SimpleNamespace(transformer = Net()), bg_compile = object())
+ assert backend._inline_float_seeds(state) is None
+ static = _state(types.SimpleNamespace(transformer = Net(dynamic = False)))
+ assert backend._inline_float_seeds(static) is None