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: split Z-Image guided steps only while the denoiser is compiled or replaying graphs (#14868)

Daniel Hanae3dc791f69e
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.py
index 04ab354c560..f05a623562a 100644
--- a/studio/backend/core/inference/diffusion.py
+++ b/studio/backend/core/inference/diffusion.py
@@ -10252,8 +10252,11 @@ class DiffusionBackend:
install_cfg_batch(
pipe, offload_policy = effective_policy, speed_mode = speed_mode, logger = logger
)
- # Z-Image guided steps at the guidance-off batch: turning CFG on compiles and records nothing new
- install_zimage_cfg_split(pipe, offload_policy = effective_policy, logger = logger)
+ # Z-Image guided steps at the guidance-off batch: turning CFG on compiles and records nothing new.
+ # compiled_only: an eager denoiser keeps the batched guided call (no graph to protect).
+ install_zimage_cfg_split(
+ pipe, offload_policy = effective_policy, logger = logger, compiled_only = True
+ )
te_releaser = te_release.maybe_install(pipe, plan, logger = logger)
state = _LoadState(
pipe = pipe,
diff --git a/studio/backend/core/inference/diffusion_zimage_cfg_split.py b/studio/backend/core/inference/diffusion_zimage_cfg_split.py
index bba4abeefe6..ae1b1cfa111 100644
--- a/studio/backend/core/inference/diffusion_zimage_cfg_split.py
+++ b/studio/backend/core/inference/diffusion_zimage_cfg_split.py
@@ -20,6 +20,14 @@ Engaged per render (``render``: Studio knows the images per call, so ``2 * B`` s
only on a resident denoiser: a block-streamed one would upload its weights twice per step, which costs more than the
recompile. Declined per call under a step cache and a static step skip that cannot key a step's two calls apart.
Under a CFG-parallel router the halves go to ``run_pair`` (identity pairing never matches fresh tensors). Kill switch: ``UNSLOTH_DIFFUSION_ZIMAGE_CFG_SPLIT=0``.
+
+Studio arms it ``compiled_only``: a render splits only while the denoiser runs compiled code or replays CUDA graphs,
+checked per render since a deferred compile can engage after the load. An eager denoiser has no graph to keep, and
+there the two serial calls cost more than one batched guided call (B200, eager, random weights: ~2x at 256px,
+~1.3-1.5x at 512px, parity at 1024px). An eager guided call that runs out of memory batched retries as the two
+calls (half the activations) for the rest of that render. An active CFG-parallel router keeps the split eager too:
+its replica runs the guidance-off half concurrently, and it cannot pair one batched call. Graphs are read from the
+denoiser too: an img2img / inpaint pipeline built by ``from_pipe`` shares the transformer and its graph wrapper but not the root pipe's handles.
"""
from __future__ import annotations
@@ -36,6 +44,10 @@ _STREAMED_POLICIES = ("group", "streaming", "sequential")
_ARMED_ATTR = "_unsloth_zimage_cfg_split"
_SAMPLES_ATTR = "_unsloth_zimage_cfg_samples"
_STATS_ATTR = "_unsloth_zimage_cfg_split_stats"
+_COMPILED_ONLY_ATTR = "_unsloth_zimage_cfg_split_compiled_only"
+# During an eager compiled_only render: the guided call runs batched and splits only once it ran out of memory.
+_EAGER_ATTR = "_unsloth_zimage_cfg_eager"
+_OOM_ATTR = "_unsloth_zimage_cfg_oom"
# Keyword arguments a split call may carry (anything else, e.g. siglip / controlnet / noise masks, runs batched).
_PLAIN_KWARGS = frozenset({"return_dict", "joint_attention_kwargs", "patch_size", "f_patch_size"})
@@ -79,6 +91,68 @@ def _declined_now(module: Any) -> Optional[str]:
return None
+def _live_graph_wrapper(denoiser: Any) -> bool:
+ """Whether an enabled CUDA-graph wrapper sits on ``denoiser`` or one of its blocks. Read from the module, not a
+ pipeline: an img2img / inpaint pipeline built by ``from_pipe`` shares the transformer but not the handle tuple."""
+ from .diffusion_cuda_graph import _LIVE_WRAPPERS
+
+ owned = {id(m) for m in denoiser.modules()}
+ return any(
+ getattr(w, "enabled", False)
+ and not getattr(w, "poisoned", False)
+ and id(getattr(w, "module", None)) in owned
+ for w in tuple(_LIVE_WRAPPERS)
+ )
+
+
+def _graph_handle_live(handle: Any) -> bool:
+ """A pipe graph handle that can still replay: enabled, and not poisoned unless a per-block fallback remains."""
+ if not getattr(handle, "enabled", True):
+ return False
+ if not getattr(handle, "poisoned", False):
+ return True
+ if getattr(handle, "fallback", None) is not None:
+ return True
+ fallback = getattr(handle, "fallback_handle", None)
+ return fallback is not None and _graph_handle_live(fallback)
+
+
+def _graphs_engaged(pipe: Any, denoiser: Any) -> bool:
+ """Whether ``denoiser`` runs compiled code or replays CUDA graphs now, the only case a split saves anything."""
+ try:
+ from .diffusion_bg_compile import eager_forced
+
+ # A render recording for a pending background compile bypasses compiled calls and graphs alike.
+ if eager_forced():
+ return False
+ except Exception: # noqa: BLE001 - unknown: read the denoiser
+ pass
+ try:
+ from .diffusion_cfg_batch import compiled_denoiser
+ except Exception: # noqa: BLE001 - unknown: keep the split
+ return True
+ try:
+ # A capture that failed for good leaves its poisoned handle in the tuple: it replays nothing.
+ if any(
+ _graph_handle_live(h) for h in tuple(getattr(pipe, "_unsloth_cuda_graphs", None) or ())
+ ):
+ return True
+ if _live_graph_wrapper(denoiser):
+ return True
+ # A compile that failed at its first forward left marks on the transformer but runs eager.
+ guard = getattr(denoiser, "__dict__", {}).get("_unsloth_compile_guard")
+ if guard is not None and getattr(guard, "error", None):
+ return False
+ if compiled_denoiser(denoiser) is not None:
+ return True
+ return any(
+ hasattr(getattr(sub, "__dict__", {}).get("forward"), "_torchdynamo_orig_callable")
+ for sub in denoiser.modules()
+ )
+ except Exception: # noqa: BLE001 - unknown: keep the split
+ return True
+
+
def _halves(samples: int, args: tuple, kwargs: dict) -> Optional[tuple]:
"""``(cond_args, uncond_args, kwargs)`` when this is a guided call of ``2 * samples`` plain samples, else None."""
if samples < 1 or len(args) != 3 or not set(kwargs) <= _PLAIN_KWARGS:
@@ -109,6 +183,67 @@ def _join(a: Any, b: Any) -> Any:
raise TypeError(f"unexpected Z-Image output {type(a).__name__}")
+def _is_oom(exc: BaseException) -> bool:
+ try:
+ from .diffusion_batched import is_oom_error
+ return bool(is_oom_error(exc))
+ except Exception: # noqa: BLE001
+ return "out of memory" in str(exc).lower()
+
+
+def _drop_tracebacks(exc: BaseException) -> None:
+ try:
+ from .diffusion_vae_oom import drop_tracebacks
+ drop_tracebacks(exc)
+ except Exception: # noqa: BLE001 - best effort
+ pass
+
+
+def _empty_cache() -> None:
+ try:
+ import torch
+ if torch.cuda.is_available():
+ torch.cuda.empty_cache()
+ except Exception: # noqa: BLE001 - best effort
+ pass
+
+
+def _router_declines_now() -> bool:
+ """A CFG-parallel router runs no pair under a background compile's eager or capture gate."""
+ try:
+ from .diffusion_multigpu import _background_compile_call
+ return bool(_background_compile_call())
+ except Exception: # noqa: BLE001
+ return False
+
+
+def _static_skip_state(slots: dict) -> Optional[tuple]:
+ skip = slots.get("_unsloth_static_skip")
+ if skip is None or not hasattr(skip, "ordinal"):
+ return None
+ counters = getattr(skip, "counters", None)
+ stats = getattr(skip, "stats", None)
+ return (
+ skip,
+ skip.ordinal,
+ dict(counters) if isinstance(counters, dict) else None,
+ dict(stats) if isinstance(stats, dict) else None,
+ )
+
+
+def _restore_static_skip(slots: dict, state: Optional[tuple]) -> None:
+ if state is None:
+ return
+ skip, ordinal, counters, stats = state
+ if slots.get("_unsloth_static_skip") is not skip:
+ return
+ skip.ordinal = ordinal
+ if counters is not None:
+ skip.counters = counters
+ if stats is not None:
+ skip.stats = stats
+
+
def _make_call(orig_call: Any) -> Any:
def __call__(self, *args, **kwargs):
slots = getattr(self, "__dict__", {})
@@ -123,10 +258,33 @@ def _make_call(orig_call: Any) -> Any:
if stats is not None:
stats["batched"] += 1
return orig_call(self, *args, **kwargs)
- cond, uncond, kw = parts
router = slots.get("_unsloth_cfg_router")
+ routed = (
+ router is not None
+ and slots.get("forward") is router
+ and getattr(router, "disabled_reason", None) is None
+ and not _router_declines_now()
+ )
+ # A CFG-parallel router needs the halves even eager: it cannot pair one batched call.
+ if slots.get(_EAGER_ATTR) and not slots.get(_OOM_ATTR) and not routed:
+ # Eager: one batched call is faster; two calls at half the activations only when it does not fit.
+ skip_state = _static_skip_state(slots)
+ try:
+ return orig_call(self, *args, **kwargs)
+ except Exception as exc: # noqa: BLE001 - reraised unless an OOM
+ if not _is_oom(exc):
+ raise
+ _drop_tracebacks(exc)
+ # The failed call consumed a static-skip ordinal; the halves must land under this step's keys.
+ _restore_static_skip(slots, skip_state)
+ # Outside the handler, so the failed call's frames are gone before the split runs.
+ self.__dict__[_OOM_ATTR] = True
+ _empty_cache()
+ if stats is not None:
+ stats["oom_split"] = stats.get("oom_split", 0) + 1
+ cond, uncond, kw = parts
pair = None
- if router is not None and slots.get("forward") is router:
+ if routed:
pair = router.run_pair(lambda: orig_call(self, *cond, **kw), uncond, dict(kw))
if pair is not None:
out_cond, out_uncond = pair
@@ -164,7 +322,14 @@ def uninstall_zimage_cfg_split(pipe: Any = None) -> None:
denoiser = getattr(pipe, "transformer", None) if pipe is not None else None
slots = getattr(denoiser, "__dict__", None)
if isinstance(slots, dict):
- for name in (_ARMED_ATTR, _SAMPLES_ATTR, _STATS_ATTR):
+ for name in (
+ _ARMED_ATTR,
+ _SAMPLES_ATTR,
+ _STATS_ATTR,
+ _COMPILED_ONLY_ATTR,
+ _EAGER_ATTR,
+ _OOM_ATTR,
+ ):
slots.pop(name, None)
with _LOCK:
for cls, (own, patched) in list(_PATCHED.items()):
@@ -181,8 +346,10 @@ def install_zimage_cfg_split(
*,
offload_policy: str,
logger: Any = None,
+ compiled_only: bool = False,
) -> Optional[str]:
- """Arm the split on ``pipe.transformer``; the decline reason, or None when armed. Never fails a load."""
+ """Arm the split on ``pipe.transformer``; the decline reason, or None when armed. Never fails a load.
+ ``compiled_only``: a render splits only while the denoiser is compiled or replays CUDA graphs."""
try:
denoiser = getattr(pipe, "transformer", None)
if denoiser is None or not _is_zimage(denoiser):
@@ -199,6 +366,7 @@ def install_zimage_cfg_split(
_patch_class(type(denoiser))
denoiser.__dict__[_ARMED_ATTR] = True
denoiser.__dict__[_STATS_ATTR] = {"split": 0, "batched": 0}
+ denoiser.__dict__[_COMPILED_ONLY_ATTR] = bool(compiled_only)
else:
denoiser.__dict__.pop(_ARMED_ATTR, None)
if logger is not None:
@@ -227,12 +395,18 @@ def zimage_cfg_split_status(pipe: Any) -> Optional[dict]:
def render(pipe: Any, samples: int):
"""For one pipeline call whose guidance-off transformer call carries ``samples`` images."""
denoiser = getattr(pipe, "transformer", None)
- armed = denoiser is not None and bool(getattr(denoiser, "__dict__", {}).get(_ARMED_ATTR))
+ slots = getattr(denoiser, "__dict__", {}) if denoiser is not None else {}
+ armed = bool(slots.get(_ARMED_ATTR))
if not armed:
yield
return
+ # Eager (compiled_only, nothing compiled or graphed): batched, split only after the batched call ran out of memory.
+ eager = bool(slots.get(_COMPILED_ONLY_ATTR)) and not _graphs_engaged(pipe, denoiser)
denoiser.__dict__[_SAMPLES_ATTR] = int(samples)
+ if eager:
+ denoiser.__dict__[_EAGER_ATTR] = True
try:
yield
finally:
- denoiser.__dict__.pop(_SAMPLES_ATTR, None)
+ for name in (_SAMPLES_ATTR, _EAGER_ATTR, _OOM_ATTR):
+ denoiser.__dict__.pop(name, None)
diff --git a/studio/backend/tests/test_diffusion_cfg_parallel_tier.py b/studio/backend/tests/test_diffusion_cfg_parallel_tier.py
index 564d50fb961..9412adea7e2 100644
--- a/studio/backend/tests/test_diffusion_cfg_parallel_tier.py
+++ b/studio/backend/tests/test_diffusion_cfg_parallel_tier.py
@@ -254,6 +254,24 @@ def test_zimage_split_runs_its_halves_as_one_parallel_pair(_zs):
assert status["split"] == 8 and status["batched"] == 0 and status["parallel"] == 4
+def test_zimage_compiled_only_eager_split_still_runs_the_parallel_pair(_zs):
+ # Studio arms compiled_only; on an eager denoiser the batched fast path must not bypass an active router.
+ model = _zimage()
+ pipe = types.SimpleNamespace(transformer = model)
+ assert _zs.install_zimage_cfg_split(pipe, offload_policy = "none", compiled_only = True) is None
+ reference = _zimage_steps(model, pipe, 4)
+ eager = _zs.zimage_cfg_split_status(pipe)
+ assert eager["split"] == 0 and eager.get("parallel", 0) == 0
+ router, replicas = _router(model)
+ out = _zimage_steps(model, pipe, 4)
+ for a, b in zip(out, reference):
+ assert torch.allclose(a, b, atol = 1e-4, rtol = 1e-4)
+ assert len(replicas) == 1 and router.disabled_reason is None
+ assert router.stats["pairs_parallel"] == 4 and router.stats["replica_calls"] == 4
+ status = _zs.zimage_cfg_split_status(pipe)
+ assert status["parallel"] == 4
+
+
def test_zimage_pair_falls_back_to_the_source_when_the_replica_fails(_zs):
model = _zimage()
pipe = types.SimpleNamespace(transformer = model)
diff --git a/studio/backend/tests/test_diffusion_zimage_cfg_split.py b/studio/backend/tests/test_diffusion_zimage_cfg_split.py
index 7d03d727fe7..7b04220fb89 100644
--- a/studio/backend/tests/test_diffusion_zimage_cfg_split.py
+++ b/studio/backend/tests/test_diffusion_zimage_cfg_split.py
@@ -322,3 +322,241 @@ def test_cfg_parallel_router_splits_and_keeps_both_branches_on_the_primary():
for a, b in zip(routed, plain):
assert torch.equal(a, b)
assert zs.zimage_cfg_split_status(pipe)["batched"] == 0
+
+
+def test_compiled_only_keeps_an_eager_denoiser_batched_and_splits_once_compiled():
+ """Eager tier: the split has no graph to protect and two serial calls are slower, so the guided call stays batched;
+ a compile engaged after the load (deferred / auto compile) splits from the next render on."""
+ torch._dynamo.reset()
+ model = _model()
+ pipe = types.SimpleNamespace(transformer = model)
+ assert zs.install_zimage_cfg_split(pipe, offload_policy = "none", compiled_only = True) is None
+ args = _guided_args(_latent(10), torch.tensor([0.4]), 9, 12, 10)
+ with zs.render(pipe, 1):
+ eager = _run(model, *args)
+ assert zs.zimage_cfg_split_status(pipe) == {"armed": True, "split": 0, "batched": 0}
+ with torch.no_grad():
+ batched = model(*args, return_dict = False)[0]
+ for a, b in zip(eager, batched):
+ assert torch.equal(a, b)
+ _compile_blocks(model)
+ with zs.render(pipe, 1):
+ _run(model, *args)
+ assert zs.zimage_cfg_split_status(pipe)["split"] == 1
+
+
[email protected]("engage", ["regional_mark", "compiled_block", "cuda_graphs"])
+def test_compiled_only_splits_every_engaged_form(engage):
+ model = _model()
+ pipe = types.SimpleNamespace(transformer = model)
+ zs.install_zimage_cfg_split(pipe, offload_policy = "none", compiled_only = True)
+ if engage == "regional_mark":
+ model._unsloth_regional_compile_kwargs = {"dynamic": True}
+ elif engage == "compiled_block":
+ model.layers[0].compile(backend = "eager", dynamic = True)
+ else:
+ pipe._unsloth_cuda_graphs = (object(),)
+ with zs.render(pipe, 1):
+ _run(model, *_guided_args(_latent(11), torch.tensor([0.4]), 45, 9, 11))
+ assert zs.zimage_cfg_split_status(pipe)["split"] == 1
+
+
+def test_studio_load_arms_the_split_compiled_only():
+ import ast
+ import pathlib
+
+ source = pathlib.Path(zs.__file__).with_name("diffusion.py").read_text()
+ calls = [
+ node
+ for node in ast.walk(ast.parse(source))
+ if isinstance(node, ast.Call)
+ and getattr(node.func, "id", None) == "install_zimage_cfg_split"
+ ]
+ assert calls
+ for call in calls:
+ flags = {k.arg: k.value for k in call.keywords}
+ assert (
+ isinstance(flags.get("compiled_only"), ast.Constant)
+ and flags["compiled_only"].value is True
+ )
+
+
+def test_compiled_only_failed_compile_runs_batched():
+ """A compile that fell back to eager at its first forward leaves the regional-compile marks on the transformer; the
+ load runs eager, so the guided call stays batched."""
+ model = _model()
+ pipe = types.SimpleNamespace(transformer = model)
+ zs.install_zimage_cfg_split(pipe, offload_policy = "none", compiled_only = True)
+ model._unsloth_regional_compile_kwargs = {"dynamic": True}
+ model._unsloth_compile_guard = types.SimpleNamespace(error = "BackendCompilerFailed: boom")
+ with zs.render(pipe, 1):
+ _run(model, *_guided_args(_latent(12), torch.tensor([0.4]), 9, 12, 12))
+ assert zs.zimage_cfg_split_status(pipe)["split"] == 0
+ model._unsloth_compile_guard.error = None
+ with zs.render(pipe, 1):
+ _run(model, *_guided_args(_latent(12), torch.tensor([0.4]), 9, 12, 12))
+ assert zs.zimage_cfg_split_status(pipe)["split"] == 1
+
+
+def test_compiled_only_sees_graphs_on_a_shared_workflow_transformer():
+ """img2img / inpaint pipelines built by from_pipe share the transformer (and its graph wrapper) but not the root
+ pipe's ``_unsloth_cuda_graphs``: the live wrapper on the denoiser keeps the split."""
+ from core.inference import diffusion_cuda_graph as cg
+
+ model = _model()
+ root = types.SimpleNamespace(transformer = model)
+ zs.install_zimage_cfg_split(root, offload_policy = "none", compiled_only = True)
+ wrapper = cg.GraphedForward(model)
+ wrapper.enabled = True # armed but never installed: the test runs eager on CPU
+ workflow = types.SimpleNamespace(transformer = model)
+ try:
+ with zs.render(workflow, 1):
+ _run(model, *_guided_args(_latent(13), torch.tensor([0.4]), 9, 12, 13))
+ assert zs.zimage_cfg_split_status(root)["split"] == 1
+ wrapper.enabled = False
+ with zs.render(workflow, 1):
+ _run(model, *_guided_args(_latent(13), torch.tensor([0.4]), 9, 12, 13))
+ assert zs.zimage_cfg_split_status(root)["split"] == 1
+ finally:
+ cg._LIVE_WRAPPERS.discard(wrapper)
+
+
+def test_compiled_only_eager_oom_retries_split_for_the_render(monkeypatch):
+ """An eager guided call that runs out of memory batched retries as the two half-batch calls, and keeps splitting
+ for the rest of that render; the next render tries batched again."""
+ model = _model()
+ pipe = types.SimpleNamespace(transformer = model)
+ zs.install_zimage_cfg_split(pipe, offload_policy = "none", compiled_only = True)
+ args = _guided_args(_latent(14), torch.tensor([0.4]), 9, 12, 14)
+ want = _run(model, *args)
+ real = type(model).forward
+ batches = []
+
+ def forward(self, x, t, cap, **kw):
+ batches.append(len(x))
+ if len(x) == 2:
+ raise torch.OutOfMemoryError("CUDA out of memory. Tried to allocate 2.00 GiB")
+ return real(self, x, t, cap, **kw)
+
+ monkeypatch.setattr(type(model), "forward", forward)
+ with zs.render(pipe, 1):
+ got = _run(model, *args)
+ _run(model, *args)
+ assert batches == [2, 1, 1, 1, 1]
+ for a, b in zip(got, want):
+ assert torch.allclose(a, b, atol = 1e-5)
+ assert zs.zimage_cfg_split_status(pipe)["oom_split"] == 1
+ batches.clear()
+ with zs.render(pipe, 1):
+ _run(model, *args)
+ assert batches[0] == 2
+ monkeypatch.setattr(
+ type(model), "forward", lambda self, *a, **k: (_ for _ in ()).throw(ValueError("x"))
+ )
+ with pytest.raises(ValueError), zs.render(pipe, 1):
+ _run(model, *args)
+
+
+def test_eager_oom_split_keeps_static_skip_branch_keys(monkeypatch):
+ """A batched eager call that runs out of memory consumed a static-skip ordinal; the two halves still key cond as
+ ``#0`` and uncond as ``#1``, so a later skipped step reuses each branch's own prediction."""
+ from core.inference import diffusion_step_skip as ss
+
+ class ZImageTransformer2DModel(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.fail_batched = False
+ self.batches = []
+
+ def forward(
+ self,
+ x,
+ t,
+ cap,
+ return_dict = False,
+ ):
+ self.batches.append(len(x))
+ if self.fail_batched and len(x) == 2:
+ raise torch.OutOfMemoryError("CUDA out of memory")
+ return ([torch.full_like(item, float(c.item())) for item, c in zip(x, cap)],)
+
+ monkeypatch.setattr(zs, "_empty_cache", lambda: None)
+ model = ZImageTransformer2DModel().eval()
+ pipe = types.SimpleNamespace(transformer = model)
+ ss.install_static_step_skip(pipe)
+ try:
+ zs.install_zimage_cfg_split(pipe, offload_policy = "none", compiled_only = True)
+ ss.reset_static_step_skip(pipe, 12, step_signal = True)
+ skip = model._unsloth_static_skip
+ outputs = []
+ with zs.render(pipe, 1), torch.no_grad():
+ for step in range(4):
+ model.fail_batched = step == 2
+ out = model(
+ [torch.zeros(1), torch.zeros(1)],
+ torch.tensor([1.0 - step / 12] * 2),
+ [torch.tensor([10.0]), torch.tensor([-10.0])],
+ return_dict = False,
+ )[0]
+ outputs.append([x.item() for x in out])
+ ss.mark_step_end(pipe)
+ assert not skip.plan[3] and skip.stats["skipped"] > 0
+ assert outputs == [[10.0, -10.0]] * 4
+ assert zs.zimage_cfg_split_status(pipe)["oom_split"] == 1
+ finally:
+ zs.uninstall_zimage_cfg_split(pipe)
+ ss.uninstall_static_step_skip(pipe)
+
+
+def test_compiled_only_eager_with_a_disabled_router_runs_batched():
+ """A CFG-parallel router that gave up (replica build or run failed) pairs nothing: the eager call stays batched."""
+ from core.inference.diffusion_multigpu import CfgParallelRouter
+
+ model = _model()
+ pipe = types.SimpleNamespace(transformer = model)
+ zs.install_zimage_cfg_split(pipe, offload_policy = "none", compiled_only = True)
+ router = CfgParallelRouter(model, primary = "cpu", secondary = "cpu")
+ router.disabled_reason = "replica failed"
+ model.__dict__["forward"] = router
+ model.__dict__["_unsloth_cfg_router"] = router
+ try:
+ with zs.render(pipe, 1):
+ _run(model, *_guided_args(_latent(14), torch.tensor([0.4]), 9, 12, 14))
+ assert zs.zimage_cfg_split_status(pipe)["split"] == 0
+ finally:
+ model.__dict__.pop("forward", None)
+ model.__dict__.pop("_unsloth_cfg_router", None)
+
+
+def test_compiled_only_ignores_a_poisoned_graph_handle():
+ """A whole-step capture that failed for good stays in ``_unsloth_cuda_graphs`` but replays nothing."""
+ model = _model()
+ pipe = types.SimpleNamespace(transformer = model)
+ zs.install_zimage_cfg_split(pipe, offload_policy = "none", compiled_only = True)
+ handle = types.SimpleNamespace(enabled = True, poisoned = True, fallback = None, fallback_handle = None)
+ pipe._unsloth_cuda_graphs = (handle,)
+ args = _guided_args(_latent(15), torch.tensor([0.4]), 9, 12, 15)
+ with zs.render(pipe, 1):
+ _run(model, *args)
+ assert zs.zimage_cfg_split_status(pipe)["split"] == 0
+ handle.fallback_handle = types.SimpleNamespace(enabled = True, poisoned = False)
+ with zs.render(pipe, 1):
+ _run(model, *args)
+ assert zs.zimage_cfg_split_status(pipe)["split"] == 1
+
+
+def test_compiled_only_honours_the_background_compile_eager_gate():
+ """A render recording for a pending background compile bypasses compiled calls and graphs: it runs batched."""
+ from core.inference import diffusion_bg_compile as bg
+
+ model = _model()
+ pipe = types.SimpleNamespace(transformer = model)
+ zs.install_zimage_cfg_split(pipe, offload_policy = "none", compiled_only = True)
+ pipe._unsloth_cuda_graphs = (object(),)
+ args = _guided_args(_latent(16), torch.tensor([0.4]), 9, 12, 16)
+ with bg.force_eager(), zs.render(pipe, 1):
+ _run(model, *args)
+ assert zs.zimage_cfg_split_status(pipe)["split"] == 0
+ with zs.render(pipe, 1):
+ _run(model, *args)
+ assert zs.zimage_cfg_split_status(pipe)["split"] == 1