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 diffusion: pre-seed the background compile's float specialisations on a returning load (#15393)

Daniel Hanc4d100a3ae2d
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.py
index dca407c25ae..ba4aac6a7bc 100644
--- a/studio/backend/core/inference/diffusion.py
+++ b/studio/backend/core/inference/diffusion.py
@@ -10680,7 +10680,13 @@ class DiffusionBackend:
)
)
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 = getattr(compile_ctx, "dir", None),
+ )
+ if bg_module is not None
+ else None
)
# After every forward wrapper of the speed / graph layers, so the replica sees the final module.
install_cfg_parallel(pipe, offload_policy = effective_policy, logger = logger)
@@ -13069,7 +13075,15 @@ class DiffusionBackend:
target = target,
)
if bg_module is not None:
- object.__setattr__(state, "bg_compile", bg_compile.arm(bg_module, logger = logger))
+ object.__setattr__(
+ state,
+ "bg_compile",
+ bg_compile.arm(
+ bg_module,
+ logger = logger,
+ seed_dir = getattr(state.compile_cache_ctx, "dir", None),
+ ),
+ )
logger.info(
"diffusion.speed: deferred profile engaged on generation 3 (optims=%s, attention=%s%s)",
",".join(state.speed_optims) or "none",
diff --git a/studio/backend/core/inference/diffusion_bg_compile.py b/studio/backend/core/inference/diffusion_bg_compile.py
index 808eefba778..222f44ca966 100644
--- a/studio/backend/core/inference/diffusion_bg_compile.py
+++ b/studio/backend/core/inference/diffusion_bg_compile.py
@@ -12,15 +12,22 @@ Dense denoisers only: torchao ones are ~30x slower eager. Offloaded ones too: no
so offload hooks see one forward at a time (UNSLOTH_DIFFUSION_BG_COMPILE_OFFLOADED=0 opts out). 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.
+
+``dynamic=True`` SymFloats dynamo cannot tensorify (norm ``eps``) cost a restart per block type; their names are
+saved in the load's compile-cache dir and pre-seeded next load (UNSLOTH_DIFFUSION_BG_COMPILE_FLOAT_SEEDS=0 opts out).
"""
from __future__ import annotations
import contextlib
import contextvars
+import hashlib
+import json
import os
+import re
import threading
import time
+from pathlib import Path
from typing import Any, Callable, Optional
_ENV = "UNSLOTH_DIFFUSION_BG_COMPILE"
@@ -52,6 +59,95 @@ def offloaded_enabled() -> bool:
return raw not in ("0", "false", "no", "off")
+FLOAT_SEEDS_ENV = "UNSLOTH_DIFFUSION_BG_COMPILE_FLOAT_SEEDS"
+FLOAT_SEEDS_FILE = "bg_compile_float_specializations.json"
+_FLOAT_SEEDS_VERSION = 1
+_SYMFLOAT_NAME = re.compile(r"^zf\d+$")
+
+
+def float_seeds_enabled() -> bool:
+ raw = (os.environ.get(FLOAT_SEEDS_ENV) or "").strip().lower()
+ return raw not in ("0", "false", "no", "off")
+
+
+def _tensorify_state() -> Any:
+ """dynamo's set of SymFloat names to specialise on a (re)trace, or None on a torch without it."""
+ try:
+ from torch._dynamo.symbolic_convert import TensorifyState
+ except Exception: # noqa: BLE001 - older / newer torch: nothing to seed
+ return None
+ names = getattr(TensorifyState, "force_specializations", None)
+ if not isinstance(names, set) or not callable(getattr(TensorifyState, "specialize", None)):
+ return None
+ return TensorifyState
+
+
+def _code_digest(code: Any) -> str:
+ """Bytecode plus constants; a nested code object (lambda, genexpr) by its own digest, never its address."""
+ h = hashlib.sha256(code.co_code)
+ for const in code.co_consts:
+ if hasattr(const, "co_code"):
+ h.update(_code_digest(const).encode("utf-8"))
+ else:
+ h.update(repr(const).encode("utf-8"))
+ return h.hexdigest()
+
+
+def _code_signature(module: Any) -> Optional[str]:
+ """The traced code a seed list belongs to: torch build plus every repeated block class's forward bytecode."""
+ try:
+ import torch
+
+ from .diffusion_block_graph import repeated_blocks
+
+ parts = [str(torch.__version__), type(module).__qualname__]
+ for cls in sorted({type(b) for b in repeated_blocks(module)}, key = lambda c: c.__qualname__):
+ code = getattr(getattr(cls, "forward", None), "__code__", None)
+ if code is None:
+ return None
+ name = getattr(code, "co_qualname", code.co_name)
+ parts.append(f"{cls.__module__}.{cls.__qualname__}:{name}:{_code_digest(code)}")
+ if len(parts) < 3:
+ return None
+ return hashlib.sha256("|".join(parts).encode("utf-8")).hexdigest()
+ except Exception: # noqa: BLE001 - no signature, no seeds
+ return None
+
+
+def _read_float_seeds(path: Path, signature: str) -> set:
+ try:
+ data = json.loads(path.read_text(encoding = "utf-8"))
+ except Exception: # noqa: BLE001 - missing / torn file: learn again
+ return set()
+ if not isinstance(data, dict) or data.get("version") != _FLOAT_SEEDS_VERSION:
+ return set()
+ if data.get("signature") != signature:
+ return set()
+ names = data.get("names")
+ if not isinstance(names, list):
+ return set()
+ return {n for n in names if isinstance(n, str) and _SYMFLOAT_NAME.match(n)}
+
+
+def _write_float_seeds(path: Path, signature: str, names: set) -> bool:
+ tmp = path.with_name(f".{path.name}.{os.getpid()}.{threading.get_ident()}.tmp")
+ try:
+ path.parent.mkdir(parents = True, exist_ok = True)
+ tmp.write_text(
+ json.dumps(
+ {"version": _FLOAT_SEEDS_VERSION, "signature": signature, "names": sorted(names)},
+ indent = 1,
+ ),
+ encoding = "utf-8",
+ )
+ os.replace(tmp, path)
+ return True
+ except Exception: # noqa: BLE001 - bookkeeping for the next load only
+ with contextlib.suppress(Exception):
+ tmp.unlink()
+ return False
+
+
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()
@@ -278,9 +374,13 @@ class BackgroundCompile:
*,
logger: Any = None,
max_samples: int = _MAX_SAMPLES,
+ seed_dir: Any = None,
) -> None:
self.module = module
self.logger = logger
+ self.seed_dir = Path(seed_dir) if seed_dir else None
+ self.float_seeds = 0
+ self.float_seeds_learned = 0
self.max_samples = int(max_samples)
self.samples: list[tuple] = []
self._keys: set = set()
@@ -474,6 +574,7 @@ class BackgroundCompile:
# torch 2.12+ keeps compile config per context: a fresh thread would compile without the recorded knobs.
diffusion_compile_config.apply()
+ seeds = self._seed_floats()
_flatten, _rebuild, graph_key = _cuda_graph_helpers()
for spec, clones, inference, grad, device in list(self.samples):
if self._closed.is_set():
@@ -489,12 +590,16 @@ class BackgroundCompile:
from .diffusion_cuda_graph import synchronize_outside_capture
synchronize_outside_capture()
self.compile_s = time.perf_counter() - t0
+ self._keep_floats(seeds)
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",
+ "diffusion.bg_compile: %s compiled in the background in %.1f s%s; the next render runs compiled",
type(self.module).__name__,
self.compile_s,
+ f" ({self.float_seeds} float specialisation(s) pre-seeded)"
+ if self.float_seeds
+ else "",
)
except BaseException as exc: # noqa: BLE001 - never kills the process; the next render compiles inline
self.compile_s = time.perf_counter() - t0
@@ -514,6 +619,40 @@ class BackgroundCompile:
finally:
_NO_CAPTURE.reset(token)
+ 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
+
+ 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
+
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()
@@ -537,6 +676,7 @@ class BackgroundCompile:
"samples": len(self.samples),
"compile_s": None if self.compile_s is None else round(self.compile_s, 2),
"eager_generations": self.eager_generations,
+ "float_seeds": self.float_seeds,
"error": self.error,
}
@@ -573,11 +713,16 @@ def select_module(
return modules[0] if len(modules) == 1 else None
-def arm(module: Any, *, logger: Any = None) -> Optional[BackgroundCompile]:
+def arm(
+ module: Any,
+ *,
+ logger: Any = None,
+ seed_dir: 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)
+ bg = BackgroundCompile(module, logger = logger, seed_dir = seed_dir)
if not bg.install():
return None
return bg
diff --git a/studio/backend/tests/test_diffusion_bg_compile_float_seeds.py b/studio/backend/tests/test_diffusion_bg_compile_float_seeds.py
new file mode 100644
index 00000000000..6461000047c
--- /dev/null
+++ b/studio/backend/tests/test_diffusion_bg_compile_float_seeds.py
@@ -0,0 +1,194 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Background compile float seeds (CPU, ``aot_eager``)."""
+
+from __future__ import annotations
+
+import json
+
+import pytest
+
+torch = pytest.importorskip("torch")
+pytest.importorskip("torch._dynamo.symbolic_convert")
+
+from core.inference import diffusion_bg_compile as bg # 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 Net(torch.nn.Module):
+ _repeated_blocks = ["Block"]
+
+ def __init__(self) -> None:
+ super().__init__()
+ self.blocks = torch.nn.ModuleList([Block() for _ in range(3)])
+
+ def forward(self, x):
+ for block in self.blocks:
+ x = block(x)
+ return x
+
+
+def _net() -> Net:
+ torch.manual_seed(0)
+ net = Net().eval()
+ for block in net.blocks:
+ block.compile(backend = "aot_eager", dynamic = True)
+ # Studio's block compile guard honours force_eager: the recording render must not trace the blocks itself.
+ bg.gate_compiled_eager(list(net.blocks))
+ return net
+
+
[email protected](autouse = True)
+def _fresh_dynamo(monkeypatch):
+ monkeypatch.delenv(bg.FLOAT_SEEDS_ENV, raising = False)
+ monkeypatch.delenv("UNSLOTH_DIFFUSION_BG_COMPILE", raising = False)
+ 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 _background_compile(seed_dir, x):
+ net = _net()
+ job = bg.arm(net, seed_dir = seed_dir)
+ assert job is not None
+ with torch.no_grad(), bg.force_eager():
+ net(x)
+ assert job.kick()
+ job.wait()
+ assert job.state == "done", job.error
+ with torch.no_grad():
+ out = net(x)
+ return job, out
+
+
+def test_second_load_traces_once_into_the_same_graph(tmp_path, restarts):
+ x = torch.randn(2, 5, 16)
+ first, out_first = _background_compile(tmp_path, x)
+ assert restarts["n"] >= 1 # the unseeded compile restarts, as on main
+ saved = json.loads((tmp_path / bg.FLOAT_SEEDS_FILE).read_text(encoding = "utf-8"))
+ assert saved["names"] and all(n.startswith("zf") for n in saved["names"])
+ assert first.float_seeds == 0 and first.float_seeds_learned == len(saved["names"])
+
+ torch._dynamo.reset()
+ restarts["n"] = 0
+ second, out_second = _background_compile(tmp_path, x)
+ assert restarts["n"] == 0
+ assert second.float_seeds == len(saved["names"])
+ assert second.describe()["float_seeds"] == len(saved["names"])
+ assert torch.equal(out_first, out_second)
+ assert json.loads((tmp_path / bg.FLOAT_SEEDS_FILE).read_text(encoding = "utf-8")) == saved
+
+
+def test_no_recompile_after_a_seeded_compile(tmp_path):
+ from torch._dynamo.utils import counters
+
+ x = torch.randn(2, 5, 16)
+ _background_compile(tmp_path, x)
+ torch._dynamo.reset()
+ job, _ = _background_compile(tmp_path, x)
+ before = dict(counters["stats"])
+ with torch.no_grad():
+ for length in (5, 7, 9):
+ job.module(torch.randn(2, length, 16))
+ # dynamic=True: other lengths reuse the graph; nothing new is traced
+ assert counters["stats"].get("unique_graphs", 0) == before.get("unique_graphs", 0)
+
+
+def test_kill_switch_keeps_the_restart(tmp_path, restarts, monkeypatch):
+ monkeypatch.setenv(bg.FLOAT_SEEDS_ENV, "0")
+ x = torch.randn(2, 5, 16)
+ _background_compile(tmp_path, x)
+ assert not (tmp_path / bg.FLOAT_SEEDS_FILE).exists()
+ torch._dynamo.reset()
+ restarts["n"] = 0
+ job, _ = _background_compile(tmp_path, x)
+ assert restarts["n"] >= 1 and job.float_seeds == 0
+
+
+def test_seeds_for_other_code_are_ignored(tmp_path, restarts):
+ x = torch.randn(2, 5, 16)
+ _background_compile(tmp_path, x)
+ path = tmp_path / bg.FLOAT_SEEDS_FILE
+ data = json.loads(path.read_text(encoding = "utf-8"))
+ data["signature"] = "0" * 64
+ path.write_text(json.dumps(data), encoding = "utf-8")
+ torch._dynamo.reset()
+ restarts["n"] = 0
+ job, _ = _background_compile(tmp_path, x)
+ assert job.float_seeds == 0 and restarts["n"] >= 1
+ assert json.loads(path.read_text(encoding = "utf-8"))["signature"] == bg._code_signature(_net())
+
+
+ "payload",
+ [
+ "{not json",
+ json.dumps({"version": 99, "signature": "x", "names": ["zf1"]}),
+ json.dumps([1, 2]),
+ ],
+)
+def test_torn_or_foreign_files_are_ignored(tmp_path, restarts, payload):
+ (tmp_path / bg.FLOAT_SEEDS_FILE).write_text(payload, encoding = "utf-8")
+ job, _ = _background_compile(tmp_path, torch.randn(2, 5, 16))
+ assert job.float_seeds == 0 and restarts["n"] >= 1
+
+
+def test_only_symfloat_names_are_seeded(tmp_path):
+ sig = bg._code_signature(_net())
+ assert sig is not None
+ (tmp_path / bg.FLOAT_SEEDS_FILE).write_text(
+ json.dumps({"version": 1, "signature": sig, "names": ["zf3", "s4", "rm -rf", 7]}),
+ encoding = "utf-8",
+ )
+ assert bg._read_float_seeds(tmp_path / bg.FLOAT_SEEDS_FILE, sig) == {"zf3"}
+
+
+def test_no_seed_dir_is_main_behaviour(restarts):
+ job, _ = _background_compile(None, torch.randn(2, 5, 16))
+ assert job.float_seeds == 0 and restarts["n"] >= 1
+
+
+def test_signature_ignores_nested_code_addresses():
+ """A forward holding a lambda must sign the same in every process (no ``<code object ... at 0x..>``)."""
+ src = "def forward(self, x):\n return (lambda y: y + 1)(x)\n"
+
+ def code():
+ scope: dict = {}
+ exec(compile(src, "blocks.py", "exec"), scope)
+ return scope["forward"].__code__
+
+ first, second = code(), code()
+ assert first is not second
+ assert repr(first.co_consts) != repr(second.co_consts) # the nested lambda prints its address
+ assert bg._code_digest(first) == bg._code_digest(second)
+ other = compile(src.replace("+ 1", "+ 2"), "blocks.py", "exec").co_consts[0]
+ assert bg._code_digest(other) != bg._code_digest(first)