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: static step skip for image models that keeps CUDA graphs (#11737)

Daniel Han66c7a81c0756
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.py
index a85c22d786d..5338fd1b92b 100644
--- a/studio/backend/core/inference/diffusion.py
+++ b/studio/backend/core/inference/diffusion.py
@@ -168,8 +168,10 @@ from .diffusion_batched import (
from .diffusion_cache import (
FBCACHE_MIN_STEPS,
TC_AUTO,
+ TC_STATIC,
apply_step_cache,
auto_step_cache_allowed,
+ cache_breaks_graph,
effective_denoise_steps,
effective_request_strength,
maybe_toggle_step_cache,
@@ -177,6 +179,14 @@ from .diffusion_cache import (
resolve_auto_step_cache,
step_cache_supported,
)
+from .diffusion_step_skip import (
+ install_static_step_skip,
+ mark_step_end,
+ reset_static_step_skip,
+ static_skip_stats,
+ static_skip_view,
+ uninstall_static_step_skip,
+)
from .diffusion_precision import (
TE_QUANT_FP8,
effective_te_quant,
@@ -976,6 +986,7 @@ class _LoadState:
attention_backend: Optional[str] = None
# Caller original attention request, so deferred engagement re-runs the same selection.
attention_request: Optional[str] = None
+ # Step cache engaged ("fbcache" | "static") or None; only fbcache breaks the graph.
transformer_cache: Optional[str] = None
# Auto only: generate() toggles it across FBCACHE_MIN_STEPS; explicit never toggles
cache_auto: bool = False
@@ -5938,17 +5949,22 @@ class DiffusionBackend:
gguf_filename, repo_id, base, fam.name
)
cache_request = resolve_auto_step_cache(effective_speed, default_steps)
- cache_engaged = apply_step_cache(
- pipe,
- mode = cache_request,
- threshold = transformer_cache_threshold,
- # GGUF transformers are quantized too, so the cache needs the higher threshold.
- quant_active = cache_quant_active,
- # Prefix-KV families (Qwen-Image-2.1) cache only when asked: at 40 steps the default
- # threshold skips about half the steps, too lossy for an automatic default.
- length_changes_ok = not cache_auto,
- logger = logger,
- )
+ if cache_request == TC_STATIC:
+ # Explicit only: auto never resolves to static.
+ cache_engaged = install_static_step_skip(pipe, logger = logger)
+ else:
+ cache_engaged = apply_step_cache(
+ pipe,
+ mode = cache_request,
+ threshold = transformer_cache_threshold,
+ # GGUF transformers are quantized too, so the cache needs the higher threshold.
+ quant_active = cache_quant_active,
+ # Prefix-KV families (Qwen-Image-2.1) cache only when asked: at 40 steps the default
+ # threshold skips about half the steps, too lossy for an automatic default.
+ length_changes_ok = not cache_auto,
+ logger = logger,
+ )
+ cache_graph_break = cache_breaks_graph(cache_engaged)
self._raise_if_load_cancelled(_load_token)
# Arm only where FBCache can engage: a live toggle drops fullgraph and retries every generation.
cache_may_toggle = cache_auto_live and (
@@ -6017,7 +6033,7 @@ class DiffusionBackend:
compile_kwargs = {
# Mirrors apply_speed_optims' fullgraph decision (a step cache or planned offload
# graph-breaks), so the bundle keys on the same setting.
- "fullgraph": cache_engaged is None
+ "fullgraph": not cache_graph_break
and not cache_may_toggle
and plan.offload_policy == OFFLOAD_NONE,
# max compiles DiTs with automatic dynamic (None), as does the default tier for
@@ -6041,8 +6057,8 @@ class DiffusionBackend:
is_gguf = gguf_transformer,
family = fam,
speed_mode = effective_speed,
- cache_active = cache_engaged is not None or cache_may_toggle,
- cache_engaged = cache_engaged is not None,
+ cache_active = cache_graph_break or cache_may_toggle,
+ cache_engaged = cache_graph_break,
offload_active = plan.offload_policy != OFFLOAD_NONE,
logger = logger,
)
@@ -6317,6 +6333,7 @@ class DiffusionBackend:
compile_cache.restore(compile_ctx, logger = logger)
gguf_compile.uninstall_all() # idempotent
cuda_graph.uninstall_all(getattr(pipe, "_unsloth_cuda_graphs", ()) or ())
+ uninstall_static_step_skip(pipe)
if eager_patched:
uninstall_patches()
uninstall_arch_patches()
@@ -7583,7 +7600,7 @@ class DiffusionBackend:
attention_backend = attention_engaged,
compile_kwargs = {
# Mirrors the load-time fullgraph decision: a step cache or an offload graph-breaks.
- "fullgraph": state.transformer_cache is None
+ "fullgraph": not cache_breaks_graph(state.transformer_cache)
and not state.cache_auto
and state.offload_policy == OFFLOAD_NONE,
"dynamic": compile_dynamic(getattr(state.pipe, "transformer", None), True),
@@ -7598,8 +7615,8 @@ class DiffusionBackend:
is_gguf = gguf_transformer,
family = state.family,
speed_mode = SPEED_DEFAULT,
- cache_active = state.transformer_cache is not None or state.cache_auto,
- cache_engaged = state.transformer_cache is not None,
+ cache_active = cache_breaks_graph(state.transformer_cache) or state.cache_auto,
+ cache_engaged = cache_breaks_graph(state.transformer_cache),
offload_active = state.offload_policy != OFFLOAD_NONE,
logger = logger,
)
@@ -7685,6 +7702,8 @@ class DiffusionBackend:
# Publish an active (step 0) state before the slow pre-denoise setup so a reload mount probe does not
# read idle.
self._gen = _GenState(total_steps = steps)
+ # Reset in the finally, so a failed or cancelled generation frees its reused outputs.
+ static_skip_pipe = None
restore_vae: Optional[Callable[[], None]] = None
try:
self._state_device_target(state)
@@ -8069,7 +8088,12 @@ class DiffusionBackend:
# _on_step).
steps_done = [0]
+ static_skip = state.transformer_cache == TC_STATIC
+ static_chunks_run = 0
+
def _on_step(pipe, step_index, timestep, callback_kwargs):
+ if static_skip:
+ mark_step_end(state.pipe)
# Monotonic: a wall-clock adjustment (NTP) mid-denoise would skew the ETA.
now = time.monotonic()
gen.step = steps_done[0] + step_index + 1
@@ -8085,10 +8109,9 @@ class DiffusionBackend:
if "callback_on_step_end" in call_params:
kwargs["callback_on_step_end"] = _on_step
- # Re-check an AUTO cache decision against the ACTUAL step count; explicit choices never toggle.
- if state.cache_auto:
- # Key on the EFFECTIVE denoise steps: img2img at strength < 1 denoises a fraction of `steps`, so
- # fold it in to keep FBCache off short trajectories.
+ # EFFECTIVE steps (img2img at strength < 1 runs fewer): the AUTO cache and the static schedule key on it.
+ denoise_steps = steps
+ if state.cache_auto or static_skip:
strength_applied = effective_request_strength(
strength,
init_pil is not None,
@@ -8096,6 +8119,8 @@ class DiffusionBackend:
call_params["strength"].default if "strength" in call_params else None,
)
denoise_steps = effective_denoise_steps(steps, strength_applied)
+ # Re-check an AUTO cache decision against the ACTUAL step count; explicit choices never toggle.
+ if state.cache_auto:
toggled = maybe_toggle_step_cache(
state.pipe,
steps = denoise_steps,
@@ -8151,10 +8176,21 @@ class DiffusionBackend:
# A step cache keys residuals on the cond/uncond context, which a graph key
# cannot see. Per chunk because an AUTO decision is re-taken per generation.
if state.cuda_graphs:
- cuda_graph.set_bypass(state.cuda_graphs, bool(state.transformer_cache))
- # Start every forward from a clean step cache: diffusers only resets FBCache after a SUCCESSFUL
- # __call__, so a raised call leaves a residual the next forward trips over.
- if state.transformer_cache:
+ cuda_graph.set_bypass(
+ state.cuda_graphs, cache_breaks_graph(state.transformer_cache)
+ )
+ if static_skip:
+ reset_static_step_skip(
+ state.pipe,
+ denoise_steps,
+ step_signal = "callback_on_step_end" in chunk_kwargs,
+ keep_stats = static_chunks_run > 0,
+ owner = current_account_id(),
+ )
+ static_chunks_run += 1
+ static_skip_pipe = state.pipe
+ elif state.transformer_cache:
+ # diffusers resets FBCache only after a SUCCESSFUL __call__; a raised call leaves a stale residual.
self._reset_step_cache(state.pipe)
try:
# inference_mode is faster than no_grad and numerically identical here.
@@ -8209,6 +8245,8 @@ class DiffusionBackend:
except Exception: # noqa: BLE001 - bookkeeping must not mask the render's own error
pass
raise
+ if static_skip:
+ logger.debug("diffusion.step_skip: %s", static_skip_stats(state.pipe))
# Keep progress ACTIVE through the post-denoise work: the route persists the image after this returns,
# so a mount probe reading idle would refresh the gallery too early. Persist the warm compile bundle;
# a STATIC compile makes new artifacts per (w,h,batch), so register this shape. The write itself is
@@ -8279,6 +8317,11 @@ class DiffusionBackend:
"localized_edit": localized_edit.mode if localized_edit is not None else None,
}
finally:
+ if static_skip_pipe is not None:
+ try:
+ reset_static_step_skip(static_skip_pipe, None)
+ except Exception as exc: # noqa: BLE001
+ logger.debug("diffusion.step_skip: reset failed: %s", exc)
if restore_vae is not None:
restore_vae()
with self._generation_cancel_lock:
@@ -8432,6 +8475,7 @@ class DiffusionBackend:
compile_cache.restore(state.compile_cache_ctx, logger = logger)
# Before clear_gpu_cache(), or the graph pool stays reserved for the life of the process.
cuda_graph.uninstall_all(state.cuda_graphs)
+ uninstall_static_step_skip(state.pipe)
prompt_cache.release(state.pipe)
for aux in (*self._aux_pipes.values(), *self._cn_pipes.values()):
prompt_cache.release(aux)
@@ -8458,6 +8502,11 @@ class DiffusionBackend:
# Must follow clear_gpu_cache() (runs gc) so the freed staging buffers can be returned.
reclaim_host_memory(logger = logger)
+ def static_skip_view(self) -> tuple:
+ """(owner, ``transformer_cache_stats``) from one read; the owner is never part of status()."""
+ state = self._state
+ return static_skip_view(state.pipe) if state is not None else (None, None)
+
def status(self) -> dict[str, Any]:
state = self._state
if state is None:
@@ -8480,6 +8529,7 @@ class DiffusionBackend:
"transformer_quant": None,
"attention_backend": None,
"transformer_cache": None,
+ "transformer_cache_stats": None,
"workflows": [],
"conditioning": None,
"supports_lora": False,
@@ -8516,6 +8566,7 @@ class DiffusionBackend:
"transformer_quant": state.transformer_quant,
"attention_backend": state.attention_backend,
"transformer_cache": state.transformer_cache,
+ "transformer_cache_stats": static_skip_stats(state.pipe),
"resolved": resolved,
# Workflows the loaded family supports, so the UI can gate its tabs.
"workflows": _family_workflows(state.family),
diff --git a/studio/backend/core/inference/diffusion_cache.py b/studio/backend/core/inference/diffusion_cache.py
index 1ad2603608d..52a40c80188 100644
--- a/studio/backend/core/inference/diffusion_cache.py
+++ b/studio/backend/core/inference/diffusion_cache.py
@@ -24,7 +24,9 @@ from typing import Any, Optional
TC_OFF = "off"
TC_AUTO = "auto"
TC_FBCACHE = "fbcache"
-TC_MODES = (TC_FBCACHE,)
+# Fixed-schedule step skip (diffusion_step_skip.py); explicit opt-in only, auto never picks it.
+TC_STATIC = "static"
+TC_MODES = (TC_FBCACHE, TC_STATIC)
# FBCache residual thresholds: higher skips more steps (faster, lower quality). Quantised transformers shift the
# residual distribution, so they need a higher threshold.
@@ -50,6 +52,11 @@ def resolve_auto_step_cache(speed_mode: Optional[str], default_steps: int) -> Op
return None
+def cache_breaks_graph(mode: Optional[str]) -> bool:
+ """Whether an engaged mode decides inside the forward (FBCache), costing fullgraph and the CUDA graph."""
+ return bool(mode) and mode != TC_STATIC
+
+
def normalize_transformer_cache(value: Optional[str]) -> Optional[str]:
"""Lower/strip a cache mode; None / "" / "none" / "off" -> None, "auto" -> TC_AUTO (loader
decides from step count). Raises ValueError for an unsupported value."""
@@ -459,6 +466,9 @@ def apply_step_cache(
if mode is None or mode == TC_AUTO:
# AUTO is resolved by the loader before this; treat a stray auto as off.
return None
+ if mode == TC_STATIC:
+ _warn(logger, mode, RuntimeError("static step skip is not supported on this backend"))
+ return None
transformer = getattr(pipe, "transformer", None)
if transformer is None:
return None
diff --git a/studio/backend/core/inference/diffusion_cuda_graph.py b/studio/backend/core/inference/diffusion_cuda_graph.py
index 34909524c8a..ede2c4b3682 100644
--- a/studio/backend/core/inference/diffusion_cuda_graph.py
+++ b/studio/backend/core/inference/diffusion_cuda_graph.py
@@ -201,6 +201,15 @@ def _warn(logger: Any, what: str, exc: Any) -> None:
logger.warning("diffusion.cuda_graph: %s failed: %s", what, exc)
+def _outer_layer(module: Any) -> Any:
+ """The ``_unsloth_outer_forward`` layer in ``module``'s forward slot (its ``inner`` None = class forward)."""
+ try:
+ slot = module.__dict__.get("forward")
+ except Exception: # noqa: BLE001 - no instance dict, nothing layered
+ return None
+ return slot if getattr(slot, "_unsloth_outer_forward", False) is True else None
+
+
class _Entry:
"""One captured graph plus the static buffers it replays into."""
@@ -264,11 +273,20 @@ class GraphedForward:
_LIVE_WRAPPERS.add(self)
def install(self) -> "GraphedForward":
- """Write ``forward`` into the instance ``__dict__``; ``__setattr__`` would inspect it."""
+ """Set ``forward`` via ``__dict__`` (``__setattr__`` would inspect it), under any outer step-skip layer."""
+ outer = _outer_layer(self.module)
+ if outer is not None:
+ outer.inner = self
+ return self
self.module.__dict__["forward"] = self
return self
def uninstall(self) -> "GraphedForward":
+ outer = _outer_layer(self.module)
+ if outer is not None:
+ if outer.inner is self:
+ outer.inner = None
+ return self
self.module.__dict__.pop("forward", None)
return self
diff --git a/studio/backend/core/inference/diffusion_step_skip.py b/studio/backend/core/inference/diffusion_step_skip.py
new file mode 100644
index 00000000000..446c3e56dd0
--- /dev/null
+++ b/studio/backend/core/inference/diffusion_step_skip.py
@@ -0,0 +1,566 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Opt-in static step skip (``transformer_cache="static"``): a schedule fixed per generation, decided outside the
+forward, so compile fullgraph and the CUDA graph are kept. A GraphedForward installed later goes under this layer."""
+
+from __future__ import annotations
+
+import contextlib
+import inspect
+import os
+from functools import update_wrapper
+from typing import Any, Optional
+
+from .diffusion_cache import TC_STATIC
+
+MODE_REUSE = "reuse"
+MODE_TAYLOR1 = "taylor1"
+SKIP_MODES = (MODE_REUSE, MODE_TAYLOR1)
+
+DEFAULT_MODE = MODE_TAYLOR1
+DEFAULT_HEAD = 0.2
+DEFAULT_TAIL = 0.1
+DEFAULT_EVERY = 2
+
+# Fewer steps leave no middle worth skipping, and a distilled few-step model has no step to spare.
+STATIC_MIN_STEPS = 12
+# Prefix-KV DiTs (Qwen-Image-2.1, FLUX.2 klein KV) return extra prompt rows on step 0, so reuse starts at step 1.
+MIN_HEAD_STEPS = 2
+
+ENV_MODE = "UNSLOTH_STATIC_SKIP_MODE"
+ENV_HEAD = "UNSLOTH_STATIC_SKIP_HEAD"
+ENV_TAIL = "UNSLOTH_STATIC_SKIP_TAIL"
+ENV_EVERY = "UNSLOTH_STATIC_SKIP_EVERY"
+
+_SLOT = "_unsloth_static_skip"
+
+
+def _torch():
+ import torch
+ return torch
+
+
+def _is_tensor(obj: Any) -> bool:
+ try:
+ is_tensor = getattr(_torch(), "is_tensor", None)
+ except Exception: # noqa: BLE001 - no torch, no tensors
+ return False
+ return bool(callable(is_tensor) and is_tensor(obj))
+
+
+def static_schedule(
+ steps: Optional[int],
+ *,
+ head: float = DEFAULT_HEAD,
+ tail: float = DEFAULT_TAIL,
+ every: int = DEFAULT_EVERY,
+) -> tuple:
+ """Per step, compute (True) or skip (False); empty (compute all) below ``STATIC_MIN_STEPS``."""
+ try:
+ n = int(steps) # type: ignore[arg-type]
+ every = int(every)
+ except (TypeError, ValueError):
+ return ()
+ if n < STATIC_MIN_STEPS or every < 2:
+ return ()
+ first = max(MIN_HEAD_STEPS, round(n * float(head)))
+ last = max(1, round(n * float(tail)))
+ return tuple(i < first or i >= n - last or (i - first) % every == 0 for i in range(n))
+
+
+def static_skip_settings(env: Optional[dict] = None, logger: Any = None) -> dict:
+ env = os.environ if env is None else env
+ out = {
+ "mode": DEFAULT_MODE,
+ "head": DEFAULT_HEAD,
+ "tail": DEFAULT_TAIL,
+ "every": DEFAULT_EVERY,
+ }
+ mode = str(env.get(ENV_MODE, "") or "").strip().lower()
+ if mode in SKIP_MODES:
+ out["mode"] = mode
+ elif mode and logger is not None:
+ logger.warning("diffusion.step_skip: ignoring %s=%r", ENV_MODE, mode)
+ for key, name in (("head", ENV_HEAD), ("tail", ENV_TAIL)):
+ raw = env.get(name)
+ if raw in (None, ""):
+ continue
+ try:
+ value = float(raw)
+ if not 0.0 <= value < 1.0:
+ raise ValueError(raw)
+ out[key] = value
+ except (TypeError, ValueError):
+ if logger is not None:
+ logger.warning("diffusion.step_skip: ignoring %s=%r", name, raw)
+ if out["head"] + out["tail"] >= 1.0:
+ out["head"], out["tail"] = DEFAULT_HEAD, DEFAULT_TAIL
+ raw = env.get(ENV_EVERY)
+ if raw not in (None, ""):
+ try:
+ value = int(raw)
+ if value < 2:
+ raise ValueError(raw)
+ out["every"] = value
+ except (TypeError, ValueError):
+ if logger is not None:
+ logger.warning("diffusion.step_skip: ignoring %s=%r", ENV_EVERY, raw)
+ return out
+
+
+def _call_signature(args: tuple, kwargs: dict) -> tuple:
+ """Reuse key: latent shape, prefix-KV mode (an ``extract`` call returns a longer sequence), container."""
+ hidden = kwargs.get("hidden_states", args[0] if args else None)
+ if _is_tensor(hidden):
+ shape = tuple(hidden.shape)
+ elif isinstance(hidden, (list, tuple)) and hidden and all(_is_tensor(h) for h in hidden):
+ shape = tuple(tuple(h.shape) for h in hidden)
+ else:
+ shape = None
+ mode = kwargs.get("kv_cache_mode")
+ if not isinstance(mode, (str, type(None))):
+ mode = repr(mode)
+ return (shape, mode, kwargs.get("return_dict", True) is False)
+
+
+def _same_shape_tensors(items: list) -> bool:
+ return (
+ bool(items)
+ and all(_is_tensor(t) for t in items)
+ and len({(tuple(t.shape), t.dtype, t.device) for t in items}) == 1
+ )
+
+
+def _split_output(out: Any) -> tuple:
+ """(noise prediction, rebuild) for a reproducible container, else (None, None) (FLUX.2 klein KV's extract step)."""
+ if _is_tensor(out):
+ return out, lambda v: v
+ if type(out) is tuple:
+ if len(out) == 1 and _is_tensor(out[0]):
+ return out[0], lambda v: (v,)
+ if len(out) == 1 and type(out[0]) is list and _same_shape_tensors(out[0]):
+ return _torch().stack(out[0]), lambda v: (list(v.unbind(0)),)
+ return None, None
+ keys = getattr(out, "keys", None)
+ if callable(keys) and callable(getattr(out, "to_tuple", None)):
+ try:
+ names = list(keys())
+ if len(names) != 1:
+ return None, None
+ name = names[0]
+ value = out[name]
+ except Exception: # noqa: BLE001 - not the mapping it looked like
+ return None, None
+ cls = type(out)
+ if _is_tensor(value):
+ return value, lambda v: cls(**{name: v})
+ # Z-Image img2img / inpaint omit return_dict=False: Transformer2DModelOutput(sample=list).
+ if type(value) is list and _same_shape_tensors(value):
+ return _torch().stack(value), lambda v: cls(**{name: list(v.unbind(0))})
+ return None, None
+ return None, None
+
+
+_TIMESTEP_NAMES = ("timestep", "timesteps", "t")
+
+
+def _timestep_slot(signature: Any) -> tuple:
+ """(name, positional index or None) of the timestep parameter; Z-Image passes it positionally."""
+ try:
+ params = list(signature.parameters.values())
+ except Exception: # noqa: BLE001
+ return "timestep", None
+ names = {p.name: i for i, p in enumerate(params)}
+ for name in _TIMESTEP_NAMES:
+ if name in names:
+ index = names[name]
+ positional = all(
+ p.kind in (p.POSITIONAL_ONLY, p.POSITIONAL_OR_KEYWORD) for p in params[: index + 1]
+ )
+ return name, index if positional else None
+ return "timestep", None
+
+
+def _timestep_of(
+ args: tuple,
+ kwargs: dict,
+ slot: tuple = ("timestep", None),
+) -> Any:
+ """The call's timestep as a one-element float32 tensor on its own device (no host sync)."""
+ name, index = slot
+ t = kwargs.get(name)
+ if t is None and index is not None and index < len(args):
+ t = args[index]
+ try:
+ if _is_tensor(t):
+ return t.detach().reshape(-1)[:1].to(dtype = _torch().float32).clone()
+ if isinstance(t, (int, float)) and not isinstance(t, bool):
+ return _torch().tensor([float(t)], dtype = _torch().float32)
+ except Exception: # noqa: BLE001 - no timestep, taylor1 falls back to reuse
+ return None
+ return None
+
+
+def _extrapolate(v0: Any, t0: Any, v1: Any, t1: Any, t: Any) -> Any:
+ torch = _torch()
+ device = v1.device
+ t0, t1, t = t0.to(device), t1.to(device), t.to(device)
+ step = t1 - t0
+ safe = torch.where(step != 0, step, torch.ones_like(step))
+ ratio = torch.where(step != 0, (t - t1) / safe, torch.zeros_like(step))
+ ratio = ratio.reshape([1] * v1.ndim) if v1.ndim else ratio.reshape(())
+ v1f = v1.float()
+ return (v1f + (v1f - v0.float()) * ratio).to(v1.dtype)
+
+
+class _Stored:
+ __slots__ = ("sig", "t", "value", "rebuild")
+
+ def __init__(self, sig: tuple, t: Any, value: Any, rebuild: Any) -> None:
+ self.sig, self.t, self.value, self.rebuild = sig, t, value, rebuild
+
+
+class StaticStepSkip:
+ """Outer forward layer skipping scheduled calls per CFG branch (``cache_context`` name, else call ordinal)."""
+
+ _unsloth_outer_forward = True
+
+ def __init__(
+ self,
+ module: Any,
+ *,
+ inner: Any = None,
+ mode: str = DEFAULT_MODE,
+ head: float = DEFAULT_HEAD,
+ tail: float = DEFAULT_TAIL,
+ every: int = DEFAULT_EVERY,
+ logger: Any = None,
+ ) -> None:
+ # First, so nothing update_wrapper copies over can shadow the state set below.
+ cls_forward = type(module).forward.__get__(module)
+ try:
+ update_wrapper(self, cls_forward)
+ except Exception: # noqa: BLE001
+ pass
+ self._t_slot = ("timestep", None)
+ try:
+ # Pipelines filter kwargs by inspect.signature(transformer.forward); keep the real one visible.
+ self.__signature__ = inspect.signature(cls_forward)
+ self._t_slot = _timestep_slot(self.__signature__)
+ except Exception: # noqa: BLE001
+ pass
+ self.module = module
+ self.inner = inner
+ self.mode = mode if mode in SKIP_MODES else DEFAULT_MODE
+ self.head, self.tail, self.every = float(head), float(tail), int(every)
+ self.logger = logger
+ self.armed = True
+ self.context: Any = None
+ self._warned_container = False
+ self.stats = {"calls": 0, "computed": 0, "skipped": 0}
+ self.last_stats = dict(self.stats)
+ # Account whose generation produced the counters; status shows them to that account only.
+ self.owner: Optional[str] = None
+ # Of the last armed forward: the post-render reset empties the plan but status still reports it.
+ self.planned_skips = 0
+ self.reset(None)
+
+ def reset(
+ self,
+ steps: Optional[int],
+ *,
+ step_signal: bool = False,
+ keep_stats: bool = False,
+ owner: Optional[str] = None,
+ ) -> "StaticStepSkip":
+ """Start a forward of ``steps`` denoise steps (None: compute all); ``keep_stats`` sums across chunks.
+ ``owner`` (arming only) rebinds the counters; a new owner never inherits the previous one's."""
+ self.plan = (
+ static_schedule(steps, head = self.head, tail = self.tail, every = self.every)
+ if self.armed
+ else ()
+ )
+ skips = [i for i, compute in enumerate(self.plan) if not compute]
+ self.last_skip = skips[-1] if skips else -1
+ if steps is not None:
+ self.planned_skips = len(skips)
+ self.step_signal = bool(step_signal)
+ # An empty schedule still counts, so status never reports the previous generation's skips.
+ self.counting = steps is not None
+ self.steps_ended = 0
+ self.ordinal = 0
+ self.counters: dict = {}
+ self.history: dict = {}
+ if keep_stats:
+ return self
+ if self.stats["calls"]:
+ self.last_stats = dict(self.stats)
+ self.stats = {"calls": 0, "computed": 0, "skipped": 0}
+ if steps is not None and owner != self.owner:
+ # Counters cleared before the owner moves: static_skip_view reads the owner first.
+ self.last_stats = dict(self.stats)
+ self.owner = owner
+ return self
+
+ def step_end(self) -> None:
+ self.steps_ended += 1
+ self.ordinal = 0
+
+ def describe(self) -> dict:
+ return {
+ "mode": self.mode,
+ "head": self.head,
+ "tail": self.tail,
+ "every": self.every,
+ "armed": bool(self.armed),
+ "planned_skips": self.planned_skips,
+ "stats": dict(self.stats if self.stats["calls"] else self.last_stats),
+ }
+
+ def _forward(self, args: tuple, kwargs: dict) -> Any:
+ inner = self.inner
+ if inner is None:
+ return type(self.module).forward(self.module, *args, **kwargs)
+ return inner(*args, **kwargs)
+
+ def __call__(self, *args, **kwargs):
+ if not self.plan:
+ if self.counting:
+ self.stats["calls"] += 1
+ self.stats["computed"] += 1
+ return self._forward(args, kwargs)
+ if self.context is not None:
+ key = self.context
+ else:
+ key = f"#{self.ordinal}" if self.step_signal else None
+ self.ordinal += 1
+ if self.step_signal:
+ step = self.steps_ended
+ else:
+ step = self.counters.get(key, 0)
+ self.counters[key] = step + 1
+ self.stats["calls"] += 1
+ sig = _call_signature(args, kwargs)
+ history = self.history.get(key)
+ if (
+ 0 <= step < len(self.plan)
+ and not self.plan[step]
+ and history
+ and history[-1].sig == sig
+ ):
+ try:
+ out = self._skipped(history, args, kwargs)
+ except Exception as exc: # noqa: BLE001 - a skip that cannot be built computes instead
+ out = None
+ if self.logger is not None:
+ self.logger.debug("diffusion.step_skip: computing step %s (%s)", step, exc)
+ if out is not None:
+ self.stats["skipped"] += 1
+ return out
+ out = self._forward(args, kwargs)
+ self.stats["computed"] += 1
+ if step < self.last_skip:
+ self._remember(key, sig, args, kwargs, out)
+ return out
+
+ def _remember(self, key: Any, sig: tuple, args: tuple, kwargs: dict, out: Any) -> None:
+ value, rebuild = _split_output(out)
+ if value is None:
+ self.history.pop(key, None)
+ if not self._warned_container and self.logger is not None:
+ self._warned_container = True
+ self.logger.info(
+ "diffusion.step_skip: %s returned a %s, which a skipped step cannot "
+ "reproduce; those calls compute",
+ type(self.module).__name__,
+ type(out).__name__,
+ )
+ return
+ # Cloned: the pipeline may keep or modify the tensor it was handed.
+ stored = _Stored(
+ sig, _timestep_of(args, kwargs, self._t_slot), value.detach().clone(), rebuild
+ )
+ keep = 2 if self.mode == MODE_TAYLOR1 else 1
+ history = self.history.setdefault(key, [])
+ history.append(stored)
+ del history[:-keep]
+
+ def _skipped(self, history: list, args: tuple, kwargs: dict) -> Any:
+ last = history[-1]
+ value = None
+ if self.mode == MODE_TAYLOR1 and len(history) >= 2:
+ prev = history[-2]
+ t = _timestep_of(args, kwargs, self._t_slot)
+ # Only same-shape outputs combine: a prefix-KV step 0 is longer than every later step.
+ if (
+ prev.sig == last.sig
+ and tuple(prev.value.shape) == tuple(last.value.shape)
+ and None not in (t, prev.t, last.t)
+ ):
+ value = _extrapolate(prev.value, prev.t, last.value, last.t, t)
+ if value is None:
+ value = last.value.clone()
+ return last.rebuild(value)
+
+
+def _context_wrapper(skip: StaticStepSkip, module: Any, prior: Any) -> Any:
+ target = prior if prior is not None else getattr(type(module), "cache_context")
+
+ @contextlib.contextmanager
+ def cache_context(*args, **kwargs):
+ name = args[0] if args else kwargs.get("name")
+ previous = skip.context
+ skip.context = name
+ try:
+ if prior is not None:
+ with target(*args, **kwargs):
+ yield
+ else:
+ with target(module, *args, **kwargs):
+ yield
+ finally:
+ skip.context = previous
+
+ cache_context._unsloth_static_skip = skip
+ return cache_context
+
+
+def _find(pipe: Any) -> Optional[StaticStepSkip]:
+ transformer = getattr(pipe, "transformer", None)
+ try:
+ skip = transformer.__dict__.get(_SLOT) if transformer is not None else None
+ except Exception: # noqa: BLE001 - no instance dict
+ return None
+ return skip if isinstance(skip, StaticStepSkip) else None
+
+
+def install_static_step_skip(
+ pipe: Any,
+ *,
+ settings: Optional[dict] = None,
+ logger: Any = None,
+) -> Optional[str]:
+ """``TC_STATIC`` or None (uncached). Never sets ``_unsloth_step_cache``, which runs the CUDA graph eager."""
+ transformer = getattr(pipe, "transformer", None)
+ if transformer is None:
+ _warn(logger, "pipeline has no transformer")
+ return None
+ # A second denoiser takes part of the CFG trajectory this layer would not see.
+ for attr in ("transformer_2", "unconditional_transformer"):
+ other = getattr(pipe, attr, None)
+ if other is not None and other is not transformer:
+ _warn(logger, f"pipeline runs a second denoiser ({attr})")
+ return None
+ if not callable(getattr(type(transformer), "forward", None)):
+ _warn(logger, "transformer has no forward")
+ return None
+ knobs = settings if settings is not None else static_skip_settings(logger = logger)
+ existing = _find(pipe)
+ if existing is not None:
+ existing.armed = True
+ existing.mode = knobs.get("mode", existing.mode)
+ existing.head = float(knobs.get("head", existing.head))
+ existing.tail = float(knobs.get("tail", existing.tail))
+ existing.every = int(knobs.get("every", existing.every))
+ existing.reset(None)
+ return TC_STATIC
+ try:
+ slots = transformer.__dict__
+ skip = StaticStepSkip(
+ transformer,
+ inner = slots.get("forward"),
+ mode = knobs.get("mode", DEFAULT_MODE),
+ head = knobs.get("head", DEFAULT_HEAD),
+ tail = knobs.get("tail", DEFAULT_TAIL),
+ every = knobs.get("every", DEFAULT_EVERY),
+ logger = logger,
+ )
+ prior_ctx = slots.get("cache_context")
+ skip._prior_ctx = prior_ctx
+ skip._ctx = None
+ if prior_ctx is not None or callable(getattr(type(transformer), "cache_context", None)):
+ skip._ctx = _context_wrapper(skip, transformer, prior_ctx)
+ slots["cache_context"] = skip._ctx
+ # Written into the instance dict, like GraphedForward: nn.Module.__setattr__ would inspect it.
+ slots["forward"] = skip
+ slots[_SLOT] = skip
+ except Exception as exc: # noqa: BLE001 - best-effort, the load proceeds uncached
+ _warn(logger, str(exc))
+ return None
+ if logger is not None:
+ logger.info(
+ "diffusion.step_skip: static engaged (mode=%s head=%s tail=%s every=%s)",
+ skip.mode,
+ skip.head,
+ skip.tail,
+ skip.every,
+ )
+ return TC_STATIC
+
+
+def reset_static_step_skip(
+ pipe: Any,
+ steps: Optional[int],
+ *,
+ step_signal: bool = False,
+ keep_stats: bool = False,
+ owner: Optional[str] = None,
+) -> bool:
+ skip = _find(pipe)
+ if skip is None:
+ return False
+ skip.reset(steps, step_signal = step_signal, keep_stats = keep_stats, owner = owner)
+ return True
+
+
+def mark_step_end(pipe: Any) -> None:
+ skip = _find(pipe)
+ if skip is not None:
+ skip.step_end()
+
+
+def static_skip_stats(pipe: Any) -> Optional[dict]:
+ skip = _find(pipe)
+ return skip.describe() if skip is not None else None
+
+
+def static_skip_view(pipe: Any) -> tuple:
+ """(owner, stats) read in that order, so a new owner is never paired with the previous owner's counts."""
+ skip = _find(pipe)
+ if skip is None:
+ return None, None
+ owner = skip.owner
+ return owner, skip.describe()
+
+
+def uninstall_static_step_skip(pipe: Any) -> bool:
+ """Restore what the layer wrapped; if something wrapped it later (an offload hook), disarm to a passthrough."""
+ skip = _find(pipe)
+ if skip is None:
+ return False
+ skip.armed = False
+ skip.reset(None)
+ try:
+ slots = skip.module.__dict__
+ if slots.get("forward") is skip:
+ if skip.inner is None:
+ slots.pop("forward", None)
+ else:
+ slots["forward"] = skip.inner
+ ctx = getattr(skip, "_ctx", None)
+ if ctx is not None and slots.get("cache_context") is ctx:
+ prior = getattr(skip, "_prior_ctx", None)
+ if prior is None:
+ slots.pop("cache_context", None)
+ else:
+ slots["cache_context"] = prior
+ slots.pop(_SLOT, None)
+ except Exception: # noqa: BLE001 - unload must not fail; a disarmed layer is a passthrough
+ return False
+ return True
+
+
+def _warn(logger: Any, why: str) -> None:
+ if logger is not None:
+ logger.warning("diffusion.step_skip: static unavailable (%s); running uncached", why)
diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.py
index 0627b6967eb..3c8e85a5825 100644
--- a/studio/backend/models/inference.py
+++ b/studio/backend/models/inference.py
@@ -3886,14 +3886,17 @@ class DiffusionLoadRequest(BaseModel):
"friendly); xformers/aiter are memory-efficient (NVIDIA) / AMD ROCm. An "
"unavailable kernel falls back to the default.",
)
- transformer_cache: Optional[Literal["off", "fbcache"]] = Field(
+ transformer_cache: Optional[Literal["off", "fbcache", "static"]] = Field(
None,
description = "Step caching. fbcache = First-Block-Cache: reuse the transformer tail "
"across denoise steps when the first block's residual barely changes (~1.4x on Flux "
"28-step at LPIPS ~0.08). Unset = auto: engages only on speed_mode=max with a 20+ step "
"schedule, otherwise uncached. An explicit fbcache engages on every speed tier; off "
"never caches. Composes with compile (drops fullgraph automatically); incompatible "
- "models run uncached.",
+ "models run uncached. static = skip denoiser calls on a fixed schedule (first 20% and "
+ "last 10% of the steps always run, every other middle step is extrapolated from the "
+ "last two outputs; 12+ steps only), which keeps compile fullgraph and the CUDA graph. "
+ "Never picked automatically.",
)
transformer_cache_threshold: Optional[float] = Field(
None,
@@ -3901,7 +3904,7 @@ class DiffusionLoadRequest(BaseModel):
le = 1.0,
description = "FBCache residual threshold (higher = skips more steps = faster, lower "
"quality). null auto-picks 0.08 (0.12 when the transformer is quantised, which "
- "shifts the residual distribution).",
+ "shifts the residual distribution). Ignored by static.",
)
gpu_ids: Optional[List[int]] = Field(
None,
@@ -4514,7 +4517,14 @@ class DiffusionStatusResponse(BaseModel):
description = "Attention backend engaged via the diffusers dispatcher (e.g. "
"_native_cudnn), or null for the default SDPA",
)
- transformer_cache: Optional[str] = Field(None, description = "Step cache engaged: fbcache | null")
+ transformer_cache: Optional[str] = Field(
+ None, description = "Step cache engaged: fbcache | static | null"
+ )
+ transformer_cache_stats: Optional[dict] = Field(
+ None,
+ description = "Static step skip only: mode, schedule and the last generation's "
+ "calls / computed / skipped transformer calls; null for any other cache",
+ )
workflows: list[str] = Field(
default_factory = list,
description = "Image workflows the loaded family supports (drives UI tab gating): "
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index d278c7ed016..3a72c08685e 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -41148,6 +41148,18 @@ async def diffusion_status(
status_dict = active_status()
if account_access.resident_hidden("diffusion", status_dict.get("repo_id")):
return account_access.hidden_resident_response()
+ # Step-skip counters trace a render as it runs, which generate-progress hides from other accounts:
+ # shown only to the account whose generation produced them, from one owner-then-stats read.
+ if (
+ status_dict.get("transformer_cache_stats") is not None
+ and account_access.account_scope() is not None
+ ):
+ from core.inference.diffusion_engine_router import get_active_diffusion_engine
+
+ view = getattr(get_active_diffusion_engine(), "static_skip_view", None)
+ owner, stats = view() if callable(view) else (None, status_dict["transformer_cache_stats"])
+ visible = owner is None or owner == current_account_id()
+ status_dict = {**status_dict, "transformer_cache_stats": stats if visible else None}
# Answered long after the resolving request ended, so no handle is in context.
return redact_host_paths(DiffusionStatusResponse(**status_dict), via_api_key = via_api_key)
diff --git a/studio/backend/tests/test_diffusion_static_skip.py b/studio/backend/tests/test_diffusion_static_skip.py
new file mode 100644
index 00000000000..693a4b51bbd
--- /dev/null
+++ b/studio/backend/tests/test_diffusion_static_skip.py
@@ -0,0 +1,933 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Hermetic CPU tests for the static step skip (``transformer_cache="static"``)."""
+
+from __future__ import annotations
+
+import contextlib
+import sys
+import types
+
+import pytest
+
+from core.inference import diffusion_cache as dcache
+from core.inference import diffusion_cuda_graph as cg
+from core.inference import diffusion_step_skip as ss
+
+from .test_diffusion_backend import ( # noqa: F401 - fake_runtime is a fixture
+ _FakePipe,
+ _load_into,
+ fake_runtime,
+)
+from .test_diffusion_cuda_graph import _build_stub_torch, _FakeTensor
+
+
+def test_schedule_matches_the_measured_prototype_at_25_steps():
+ plan = ss.static_schedule(25)
+ assert len(plan) == 25
+ # head round(5.0) = 5, tail round(2.5) = 2 (banker's), the middle computes every other step.
+ assert plan[:6] == (True,) * 6
+ assert plan[-2:] == (True, True)
+ assert [i for i, c in enumerate(plan) if not c] == list(range(6, 23, 2))
+
+
[email protected]("steps", [None, 0, 1, 8, 11, "x"])
+def test_short_or_unknown_trajectories_compute_every_step(steps):
+ assert ss.static_schedule(steps) == ()
+
+
+def test_schedule_keeps_two_head_steps_for_prefix_kv():
+ plan = ss.static_schedule(12, head = 0.0)
+ assert plan[:3] == (True, True, True)
+ assert [i for i, c in enumerate(plan) if not c] == [3, 5, 7, 9]
+
+
+def test_schedule_every_below_two_is_off():
+ assert ss.static_schedule(30, every = 1) == ()
+
+
+def test_settings_defaults_and_env_overrides():
+ assert ss.static_skip_settings({}) == {
+ "mode": "taylor1",
+ "head": 0.2,
+ "tail": 0.1,
+ "every": 2,
+ }
+ env = {
+ ss.ENV_MODE: "Reuse",
+ ss.ENV_HEAD: "0.3",
+ ss.ENV_TAIL: "0.2",
+ ss.ENV_EVERY: "3",
+ }
+ assert ss.static_skip_settings(env) == {"mode": "reuse", "head": 0.3, "tail": 0.2, "every": 3}
+ bad = {ss.ENV_MODE: "magic", ss.ENV_HEAD: "2", ss.ENV_TAIL: "x", ss.ENV_EVERY: "1"}
+ assert ss.static_skip_settings(bad) == ss.static_skip_settings({})
+
+
+torch = pytest.importorskip("torch")
+
+
+class _Out(dict):
+ def __init__(self, sample = None):
+ super().__init__(sample = sample)
+
+ def to_tuple(self):
+ return tuple(self.values())
+
+ @property
+ def sample(self):
+ return self["sample"]
+
+
+class _DiT:
+ def __init__(
+ self,
+ *,
+ container = "tuple",
+ prefix = 0,
+ ):
+ self.calls: list = []
+ self.contexts: list = []
+ self.container = container
+ self.prefix = prefix # extra rows returned on an extract call (prefix-KV DiT)
+
+ @contextlib.contextmanager
+ def cache_context(self, name):
+ self.contexts.append(name)
+ yield
+
+ def forward(
+ self,
+ hidden_states,
+ timestep = None,
+ kv_cache_mode = None,
+ return_dict = True,
+ ):
+ t = float(timestep.reshape(-1)[0])
+ self.calls.append((t, kv_cache_mode))
+ rows = hidden_states.shape[1] + (self.prefix if kv_cache_mode == "extract" else 0)
+ out = torch.full((hidden_states.shape[0], rows, 2), t)
+ if self.container == "pair":
+ return (out, {"kv": 1}) if return_dict is False else _Out(sample = out)
+ if self.container == "tensor":
+ return out
+ return (out,) if return_dict is False else _Out(sample = out)
+
+
+def _pipe(dit, **extra):
+ return types.SimpleNamespace(transformer = dit, **extra)
+
+
+def _run(
+ pipe,
+ steps,
+ *,
+ contexts = ("cond",),
+ signal = True,
+ kv = False,
+ return_dict = False,
+ owner = None,
+):
+ dit = pipe.transformer
+ ss.reset_static_step_skip(pipe, steps, step_signal = signal, owner = owner)
+ outs: dict = {c: [] for c in contexts}
+ x = torch.zeros(1, 4, 2)
+ for i in range(steps):
+ t = torch.tensor([1.0 - i / steps])
+ mode = ("extract" if i == 0 else "cached") if kv else None
+ for name in contexts:
+ cm = dit.cache_context(name) if name is not None else contextlib.nullcontext()
+ with cm:
+ out = dit.forward(
+ hidden_states = x, timestep = t, kv_cache_mode = mode, return_dict = return_dict
+ )
+ outs[name].append(out)
+ if signal:
+ ss.mark_step_end(pipe)
+ return outs
+
+
+def _installed(dit = None, **settings):
+ dit = dit or _DiT()
+ pipe = _pipe(dit)
+ knobs = {**ss.static_skip_settings({}), "mode": "reuse", **settings}
+ assert ss.install_static_step_skip(pipe, settings = knobs) == dcache.TC_STATIC
+ return pipe
+
+
+def test_install_is_outermost_and_never_sets_the_step_cache_marker():
+ pipe = _installed()
+ dit = pipe.transformer
+ assert isinstance(dit.__dict__["forward"], ss.StaticStepSkip)
+ assert dit.forward is dit.__dict__["forward"]
+ assert getattr(dit, "_unsloth_step_cache", None) is None
+ import inspect
+
+ assert list(inspect.signature(dit.forward).parameters) == [
+ "hidden_states",
+ "timestep",
+ "kv_cache_mode",
+ "return_dict",
+ ]
+
+
+def test_cfg_contexts_are_counted_per_branch():
+ pipe = _installed()
+ outs = _run(pipe, 25, contexts = ("cond", "uncond"), signal = False)
+ dit = pipe.transformer
+ assert len(dit.calls) == 32
+ stats = ss.static_skip_stats(pipe)["stats"]
+ assert stats == {"calls": 50, "computed": 32, "skipped": 18}
+ # A skipped step returns the SAME branch's last output, never the other branch's.
+ plan = ss.static_schedule(25)
+ for i, compute in enumerate(plan):
+ if not compute:
+ for name in ("cond", "uncond"):
+ assert torch.equal(outs[name][i][0], outs[name][i - 1][0])
+ assert dit.contexts.count("cond") == 25
+
+
+def test_step_signal_counts_branches_by_ordinal_without_contexts():
+ # FluxImg2Img / Kontext / Krea2: two calls per step and no cache_context.
+ pipe = _installed()
+ _run(pipe, 25, contexts = (None, None), signal = True)
+ assert len(pipe.transformer.calls) == 32
+
+
+def test_single_counter_fallback_without_context_or_signal():
+ pipe = _installed()
+ _run(pipe, 25, contexts = (None,), signal = False)
+ assert len(pipe.transformer.calls) == 16
+
+
+def test_reset_per_generation_restarts_the_schedule():
+ pipe = _installed()
+ _run(pipe, 25)
+ _run(pipe, 25)
+ assert len(pipe.transformer.calls) == 32
+ _run(pipe, 8)
+ assert len(pipe.transformer.calls) == 40
+ ss.reset_static_step_skip(pipe, None)
+ x = torch.zeros(1, 4, 2)
+ for _ in range(3):
+ pipe.transformer.forward(hidden_states = x, timestep = torch.tensor([0.5]), return_dict = False)
+ assert len(pipe.transformer.calls) == 43
+
+
+def test_reuse_returns_a_clone_of_the_last_output():
+ pipe = _installed()
+ outs = _run(pipe, 25)["cond"]
+ skipped = outs[6][0]
+ assert torch.equal(skipped, outs[5][0])
+ assert skipped.data_ptr() != outs[5][0].data_ptr()
+
+
+def test_taylor1_extrapolates_in_timestep():
+ pipe = _installed(mode = "taylor1")
+ outs = _run(pipe, 25)["cond"]
+ # The fake output equals its timestep, so a first-order extrapolation is exact.
+ for i in range(6, 23, 2):
+ assert torch.allclose(outs[i][0], torch.full((1, 4, 2), 1.0 - i / 25), atol = 1e-6)
+
+
+def test_prefix_kv_extract_step_is_never_reused():
+ for mode in ("reuse", "taylor1"):
+ pipe = _installed(_DiT(prefix = 3), mode = mode, head = 0.0)
+ outs = _run(pipe, 12, kv = True)["cond"]
+ assert outs[0][0].shape[1] == 7
+ assert all(o[0].shape[1] == 4 for o in outs[1:])
+ assert pipe.transformer.calls[0][1] == "extract"
+ assert ss.static_skip_stats(pipe)["stats"]["skipped"] == 4
+
+
+def test_taylor1_falls_back_to_reuse_across_a_shape_change():
+ pipe = _installed(_DiT(prefix = 3), mode = "taylor1")
+ layer = pipe.transformer.__dict__["forward"]
+ real_reset = layer.reset
+
+ def reset(steps, **kwargs):
+ # Force a skip at step 2, whose history is step 0 (7 rows, extract) and step 1 (4 rows).
+ real_reset(steps, **kwargs)
+ layer.plan = (True, True, False) + (True,) * (steps - 3)
+ layer.last_skip = 2
+ return layer
+
+ layer.reset = reset
+ outs = _run(pipe, 12, kv = True)["cond"]
+ assert len(layer.history["cond"]) == 2
+ assert torch.equal(outs[2][0], outs[1][0])
+ assert layer.stats["skipped"] == 1
+
+
+def test_container_types_are_preserved():
+ for return_dict in (False, True):
+ pipe = _installed()
+ outs = _run(pipe, 25, return_dict = return_dict)["cond"]
+ kind = tuple if return_dict is False else _Out
+ assert all(type(o) is kind for o in outs)
+ pipe = _installed(_DiT(container = "tensor"))
+ outs = _run(pipe, 25)["cond"]
+ assert all(torch.is_tensor(o) for o in outs)
+ assert ss.static_skip_stats(pipe)["stats"]["skipped"] == 9
+
+
+def test_real_diffusers_output_class_is_rebuilt():
+ outputs = pytest.importorskip("diffusers.models.modeling_outputs")
+ value, rebuild = ss._split_output(outputs.Transformer2DModelOutput(sample = torch.ones(1)))
+ rebuilt = rebuild(torch.zeros(1))
+ assert type(rebuilt) is outputs.Transformer2DModelOutput
+ assert torch.equal(rebuilt.sample, torch.zeros(1))
+
+
+class _ListDiT(_DiT):
+ def forward(
+ self,
+ hidden_states,
+ timestep = None,
+ kv_cache_mode = None,
+ return_dict = True,
+ ):
+ out = super().forward(hidden_states, timestep, kv_cache_mode, return_dict = False)[0]
+ return (list(out.unbind(0)),)
+
+
+def test_z_image_list_outputs_are_skipped_and_rebuilt():
+ value, rebuild = ss._split_output(([torch.ones(4, 2), torch.zeros(4, 2)],))
+ assert value.shape == (2, 4, 2)
+ rebuilt = rebuild(value * 2)
+ assert type(rebuilt) is tuple and type(rebuilt[0]) is list and len(rebuilt[0]) == 2
+ assert torch.equal(rebuilt[0][0], torch.full((4, 2), 2.0))
+ assert ss._split_output(([torch.ones(4, 2), torch.ones(3, 2)],)) == (None, None)
+ assert ss._call_signature(([torch.ones(1, 4), torch.ones(1, 4)],), {})[0] == ((1, 4), (1, 4))
+
+ pipe = _installed(_ListDiT())
+ outs = _run(pipe, 25)["cond"]
+ assert ss.static_skip_stats(pipe)["stats"]["skipped"] == 9
+ assert all(type(o) is tuple and type(o[0]) is list for o in outs)
+
+
+def test_z_image_list_in_output_dataclass_is_skipped_and_rebuilt():
+ # ZImageImg2ImgPipeline / ZImageInpaintPipeline call the transformer without return_dict=False.
+ outputs = pytest.importorskip("diffusers.models.modeling_outputs")
+ out_cls = outputs.Transformer2DModelOutput
+ value, rebuild = ss._split_output(out_cls(sample = [torch.ones(4, 2), torch.zeros(4, 2)]))
+ assert value.shape == (2, 4, 2)
+ rebuilt = rebuild(value * 2)
+ assert type(rebuilt) is out_cls and type(rebuilt.sample) is list and len(rebuilt.sample) == 2
+ assert torch.equal(rebuilt.sample[0], torch.full((4, 2), 2.0))
+ assert ss._split_output(out_cls(sample = [torch.ones(4, 2), torch.ones(3, 2)])) == (None, None)
+
+ class _ListOutDiT(_DiT):
+ def forward(
+ self,
+ hidden_states,
+ timestep = None,
+ kv_cache_mode = None,
+ return_dict = True,
+ ):
+ out = super().forward(hidden_states, timestep, kv_cache_mode, return_dict = False)[0]
+ return out_cls(sample = list(out.unbind(0)))
+
+ pipe = _installed(_ListOutDiT())
+ outs = _run(pipe, 25)["cond"]
+ assert ss.static_skip_stats(pipe)["stats"]["skipped"] == 9
+ assert all(type(o) is out_cls and type(o.sample) is list for o in outs)
+
+
+class _PositionalDiT(_DiT):
+ def forward(
+ self,
+ x,
+ t,
+ cap_feats,
+ return_dict = True,
+ ):
+ return super().forward(x, timestep = t, return_dict = return_dict)
+
+
+def test_taylor1_reads_a_positional_timestep():
+ assert ss._timestep_slot(ss.inspect.signature(_PositionalDiT().forward)) == ("t", 1)
+ assert ss._timestep_slot(ss.inspect.signature(_DiT().forward)) == ("timestep", 1)
+ pipe = _installed(_PositionalDiT(), mode = "taylor1")
+ dit = pipe.transformer
+ ss.reset_static_step_skip(pipe, 25, step_signal = True)
+ x = torch.zeros(1, 4, 2)
+ outs = []
+ for i in range(25):
+ outs.append(dit.forward(x, torch.tensor([1.0 - i / 25]), None, return_dict = False))
+ ss.mark_step_end(pipe)
+ assert ss.static_skip_stats(pipe)["stats"]["skipped"] == 9
+ # Extrapolated, not reused: a skipped step matches its own timestep, not the previous step's.
+ for i in range(6, 23, 2):
+ assert torch.allclose(outs[i][0], torch.full((1, 4, 2), 1.0 - i / 25), atol = 1e-6)
+
+
+def test_multi_value_outputs_are_never_skipped():
+ # FLUX.2 klein KV's (noise, kv_cache): nothing a skip could reproduce.
+ pipe = _installed(_DiT(container = "pair"))
+ _run(pipe, 25)
+ assert len(pipe.transformer.calls) == 25
+ assert ss.static_skip_stats(pipe)["stats"]["skipped"] == 0
+
+
+def test_a_second_denoiser_or_missing_transformer_declines():
+ assert ss.install_static_step_skip(_pipe(_DiT(), transformer_2 = _DiT())) is None
+ assert ss.install_static_step_skip(_pipe(_DiT(), unconditional_transformer = _DiT())) is None
+ assert ss.install_static_step_skip(types.SimpleNamespace()) is None
+
+
+def test_uninstall_restores_forward_and_cache_context():
+ dit = _DiT()
+ pipe = _installed(dit)
+ assert "cache_context" in dit.__dict__
+ assert ss.uninstall_static_step_skip(pipe) is True
+ assert "forward" not in dit.__dict__
+ assert "cache_context" not in dit.__dict__
+ assert "_unsloth_static_skip" not in dit.__dict__
+ assert ss.uninstall_static_step_skip(pipe) is False
+ _installed(dit)
+ _run(pipe, 25)
+ assert len(dit.calls) == 16
+
+
+def test_uninstall_restores_a_prior_instance_forward():
+ dit = _DiT()
+ seen = []
+
+ def prior(*args, **kwargs):
+ seen.append(1)
+ return type(dit).forward(dit, *args, **kwargs)
+
+ dit.__dict__["forward"] = prior
+ pipe = _installed(dit)
+ _run(pipe, 25)
+ assert len(seen) == 16
+ ss.uninstall_static_step_skip(pipe)
+ assert dit.__dict__["forward"] is prior
+
+
+def test_uninstall_under_a_later_wrapper_disarms_in_place():
+ dit = _DiT()
+ pipe = _installed(dit)
+ layer = dit.__dict__["forward"]
+
+ def hook(*args, **kwargs):
+ return layer(*args, **kwargs)
+
+ dit.__dict__["forward"] = hook
+ ss.uninstall_static_step_skip(pipe)
+ assert dit.__dict__["forward"] is hook
+ x = torch.zeros(1, 4, 2)
+ for i in range(25):
+ dit.forward(hidden_states = x, timestep = torch.tensor([1.0 - i / 25]), return_dict = False)
+ assert len(dit.calls) == 25
+
+
+def test_reinstall_is_idempotent():
+ dit = _DiT()
+ pipe = _installed(dit)
+ layer = dit.__dict__["forward"]
+ assert ss.install_static_step_skip(pipe, settings = ss.static_skip_settings({})) == "static"
+ assert dit.__dict__["forward"] is layer
+ assert layer.inner is None
+
+
+class _GraphDiT:
+ def __init__(self):
+ self.calls = 0
+
+ def forward(
+ self,
+ hidden_states,
+ timestep = None,
+ return_dict = True,
+ ):
+ self.calls += 1
+ return (_FakeTensor((1, 4), value = ("out", self.calls), tag = "out"),)
+
+
+def stub_torch(monkeypatch):
+ stub = _build_stub_torch()
+ stub.float32 = "float32"
+ monkeypatch.setitem(sys.modules, "torch", stub)
+ monkeypatch.setattr(_FakeTensor, "detach", lambda self: self, raising = False)
+ cg._POOL_BOX[0] = None
+ cg._LIVE_WRAPPERS.clear()
+ yield stub
+ cg._POOL_BOX[0] = None
+ cg._LIVE_WRAPPERS.clear()
+
+
+def _graph_loop(pipe, steps):
+ ss.reset_static_step_skip(pipe, steps, step_signal = True)
+ for _ in range(steps):
+ pipe.transformer.forward(_FakeTensor((1, 4)), timestep = _FakeTensor((1,)), return_dict = False)
+ ss.mark_step_end(pipe)
+
+
[email protected]("graph_first", [False, True])
+def test_graph_sits_under_the_layer_and_sees_only_computed_steps(stub_torch, graph_first):
+ dit = _GraphDiT()
+ pipe = types.SimpleNamespace(transformer = dit)
+ knobs = ss.static_skip_settings({})
+ if graph_first:
+ handles = cg.install_cuda_graphs(pipe)
+ ss.install_static_step_skip(pipe, settings = knobs)
+ else:
+ ss.install_static_step_skip(pipe, settings = knobs)
+ handles = cg.install_cuda_graphs(pipe)
+ layer = dit.__dict__["forward"]
+ assert isinstance(layer, ss.StaticStepSkip)
+ assert layer.inner is handles[0]
+ assert getattr(dit, "_unsloth_step_cache", None) is None
+
+ _graph_loop(pipe, 25)
+ stats = handles[0].stats
+ assert stats["captures"] == 1
+ assert stats["replays"] == 16
+ assert stats["eager_calls"] == 0
+ assert len(handles[0].cache) == 1
+ assert layer.stats["skipped"] == 9
+
+
+def test_graph_uninstall_then_layer_uninstall_leaves_the_class_forward(stub_torch):
+ dit = _GraphDiT()
+ pipe = types.SimpleNamespace(transformer = dit)
+ ss.install_static_step_skip(pipe, settings = ss.static_skip_settings({}))
+ handles = cg.install_cuda_graphs(pipe)
+ cg.uninstall_all(handles)
+ layer = dit.__dict__["forward"]
+ assert isinstance(layer, ss.StaticStepSkip) and layer.inner is None
+ ss.uninstall_static_step_skip(pipe)
+ assert "forward" not in dit.__dict__
+
+
+def test_layer_uninstall_hands_the_slot_back_to_the_graph(stub_torch):
+ dit = _GraphDiT()
+ pipe = types.SimpleNamespace(transformer = dit)
+ ss.install_static_step_skip(pipe, settings = ss.static_skip_settings({}))
+ handles = cg.install_cuda_graphs(pipe)
+ ss.uninstall_static_step_skip(pipe)
+ assert dit.__dict__["forward"] is handles[0]
+ handles[0].enable()
+ assert dit.__dict__["forward"] is handles[0]
+ cg.uninstall_all(handles)
+ assert "forward" not in dit.__dict__
+ ss.install_static_step_skip(pipe, settings = ss.static_skip_settings({}))
+ handles = cg.install_cuda_graphs(pipe)
+ assert dit.__dict__["forward"].inner is handles[0]
+
+
+def test_graph_disable_and_reenable_under_the_layer(stub_torch):
+ dit = _GraphDiT()
+ pipe = types.SimpleNamespace(transformer = dit)
+ ss.install_static_step_skip(pipe, settings = ss.static_skip_settings({}))
+ handle = cg.install_cuda_graphs(pipe)[0]
+ layer = dit.__dict__["forward"]
+ handle.disable()
+ assert dit.__dict__["forward"] is layer and layer.inner is None
+ handle.enable()
+ assert dit.__dict__["forward"] is layer and layer.inner is handle
+
+
+def test_normalize_accepts_static_and_auto_stays_distinct():
+ assert dcache.normalize_transformer_cache("static") == dcache.TC_STATIC
+ assert dcache.normalize_transformer_cache(" Static ") == dcache.TC_STATIC
+ assert dcache.normalize_transformer_cache("auto") == dcache.TC_AUTO
+
+
+def test_only_fbcache_breaks_the_graph():
+ assert dcache.cache_breaks_graph(None) is False
+ assert dcache.cache_breaks_graph("static") is False
+ assert dcache.cache_breaks_graph("fbcache") is True
+
+
+def test_apply_step_cache_refuses_static():
+ dit = _DiT()
+ assert dcache.apply_step_cache(_pipe(dit), mode = "static") is None
+ assert "forward" not in dit.__dict__
+
+
+def test_auto_toggle_only_ever_engages_fbcache(monkeypatch):
+ seen = []
+
+ def fake_apply(pipe, *, mode, **kwargs):
+ seen.append(mode)
+ return mode
+
+ monkeypatch.setattr(dcache, "apply_step_cache", fake_apply)
+ pipe = types.SimpleNamespace(transformer = types.SimpleNamespace(enable_cache = lambda c: None))
+ dcache.maybe_toggle_step_cache(pipe, steps = 50)
+ assert seen == [dcache.TC_FBCACHE]
+
+
+def _record_speed(monkeypatch, dmod):
+ seen: dict = {}
+
+ def fake_speed(pipe, target, **kwargs):
+ seen["speed"] = kwargs
+ return {"compiled": True}
+
+ def fake_begin(**kwargs):
+ seen["begin"] = kwargs["compile_kwargs"]
+ return None
+
+ monkeypatch.setattr(dmod, "compile_eligible", lambda *a, **k: True)
+ monkeypatch.setattr(dmod, "apply_speed_optims", fake_speed)
+ monkeypatch.setattr(dmod.compile_cache, "begin", fake_begin)
+ return seen
+
+
[email protected]("request_cache", ["off", "static"])
+def test_static_load_keeps_the_uncached_graph_decisions(
+ fake_runtime, tmp_path, monkeypatch, request_cache
+):
+ from core.inference import diffusion as dmod
+
+ seen = _record_speed(monkeypatch, dmod)
+ installs = []
+ monkeypatch.setattr(
+ dmod,
+ "install_static_step_skip",
+ lambda pipe, logger = None: installs.append(pipe) or dcache.TC_STATIC,
+ )
+ (tmp_path / "model.gguf").write_bytes(b"weights")
+ backend = dmod.DiffusionBackend()
+ status = _load_into(backend, tmp_path, speed_mode = "default", transformer_cache = request_cache)
+ assert seen["speed"]["cache_active"] is False
+ assert seen["speed"]["cache_engaged"] is False
+ assert seen["begin"]["fullgraph"] is True
+ if request_cache == "static":
+ assert len(installs) == 1
+ assert status["transformer_cache"] == "static"
+ assert status["resolved"]["transformer_cache"]["value"] == "static"
+ else:
+ assert installs == []
+ assert status["transformer_cache"] is None
+ assert backend._state.cache_auto is False
+ backend.unload()
+
+
+def test_fbcache_load_still_breaks_the_graph(fake_runtime, tmp_path, monkeypatch):
+ from core.inference import diffusion as dmod
+
+ seen = _record_speed(monkeypatch, dmod)
+ monkeypatch.setattr(dmod, "apply_step_cache", lambda pipe, mode = None, **k: mode)
+ (tmp_path / "model.gguf").write_bytes(b"weights")
+ backend = dmod.DiffusionBackend()
+ _load_into(backend, tmp_path, speed_mode = "default", transformer_cache = "fbcache")
+ assert seen["speed"]["cache_active"] is True
+ assert seen["speed"]["cache_engaged"] is True
+ assert seen["begin"]["fullgraph"] is False
+ backend.unload()
+
+
[email protected]("request_cache", [None, "auto"])
+def test_auto_load_never_installs_static(fake_runtime, tmp_path, monkeypatch, request_cache):
+ from core.inference import diffusion as dmod
+
+ modes = []
+ monkeypatch.setattr(dmod, "default_generation_params", lambda *a, **k: (50, 4.0))
+ monkeypatch.setattr(
+ dmod, "apply_step_cache", lambda pipe, mode = None, **k: modes.append(mode) or None
+ )
+ monkeypatch.setattr(
+ dmod, "install_static_step_skip", lambda *a, **k: pytest.fail("auto picked static")
+ )
+ (tmp_path / "model.gguf").write_bytes(b"weights")
+ backend = dmod.DiffusionBackend()
+ _load_into(backend, tmp_path, transformer_cache = request_cache)
+ # Auto resolves per speed tier (FBCache on max, else uncached); never to static.
+ assert len(modes) == 1 and modes[0] in (None, dcache.TC_FBCACHE)
+ backend.unload()
+
+
+class _Tensorish:
+ def __init__(self, value):
+ self.value = value
+ self.shape = (1, 4)
+
+ def detach(self):
+ return self
+
+ def clone(self):
+ return _Tensorish(self.value)
+
+
+class _LoopDiT:
+ def __init__(self):
+ self.calls = 0
+
+ @contextlib.contextmanager
+ def cache_context(self, name):
+ yield
+
+ def forward(
+ self,
+ hidden_states = None,
+ timestep = None,
+ return_dict = True,
+ ):
+ self.calls += 1
+ return (_Tensorish(self.calls),)
+
+
+class _LoopPipe(_FakePipe):
+ def __init__(self):
+ super().__init__()
+ self.transformer = _LoopDiT()
+
+ def __call__(
+ self,
+ *,
+ prompt = None,
+ negative_prompt = None,
+ callback_on_step_end = None,
+ guidance_scale = None,
+ true_cfg_scale = None,
+ cfg_trunc_ratio = None,
+ **kwargs,
+ ):
+ for i in range(kwargs["num_inference_steps"]):
+ for name in ("cond", "uncond"):
+ with self.transformer.cache_context(name):
+ self.transformer.forward(hidden_states = None, timestep = None, return_dict = False)
+ if callback_on_step_end is not None:
+ callback_on_step_end(self, i, None, {})
+ return super().__call__(
+ prompt = prompt,
+ negative_prompt = negative_prompt,
+ callback_on_step_end = callback_on_step_end,
+ guidance_scale = guidance_scale,
+ true_cfg_scale = true_cfg_scale,
+ cfg_trunc_ratio = cfg_trunc_ratio,
+ **kwargs,
+ )
+
+
+def _static_backend(tmp_path, monkeypatch):
+ from core.inference import diffusion as dmod
+
+ (tmp_path / "model.gguf").write_bytes(b"weights")
+ backend = dmod.DiffusionBackend()
+ _load_into(backend, tmp_path)
+ pipe = _LoopPipe()
+ sys.modules["torch"].is_tensor = lambda obj: isinstance(obj, _Tensorish)
+ assert ss.install_static_step_skip(pipe, settings = ss.static_skip_settings({})) == "static"
+ object.__setattr__(backend._state, "pipe", pipe)
+ object.__setattr__(backend._state, "transformer_cache", dcache.TC_STATIC)
+ return backend, pipe
+
+
+def test_generate_runs_the_schedule_and_keeps_the_graph(fake_runtime, tmp_path, monkeypatch):
+ from core.inference import diffusion as dmod
+
+ backend, pipe = _static_backend(tmp_path, monkeypatch)
+ bypass, resets = [], []
+ monkeypatch.setattr(dmod.cuda_graph, "set_bypass", lambda handles, on: bypass.append(on))
+ object.__setattr__(backend._state, "cuda_graphs", ("handle",))
+ monkeypatch.setattr(
+ type(backend), "_reset_step_cache", staticmethod(lambda p: resets.append(p))
+ )
+ backend.generate(prompt = "a sloth", steps = 25)
+ assert pipe.transformer.calls == 32
+ assert bypass == [False]
+ assert resets == []
+ backend.generate(prompt = "a sloth", steps = 25)
+ assert pipe.transformer.calls == 64
+ backend.generate(prompt = "a sloth", steps = 9)
+ assert pipe.transformer.calls == 82
+ backend.unload()
+ assert "forward" not in pipe.transformer.__dict__
+
+
+def test_generate_arms_the_schedule_with_the_effective_steps(fake_runtime, tmp_path, monkeypatch):
+ from core.inference import diffusion as dmod
+
+ backend, pipe = _static_backend(tmp_path, monkeypatch)
+ armed = []
+ real_reset = dmod.reset_static_step_skip
+ monkeypatch.setattr(
+ dmod,
+ "reset_static_step_skip",
+ lambda p, steps, **k: armed.append((steps, k.get("step_signal")))
+ or real_reset(p, steps, **k),
+ )
+ # img2img at strength 0.5 denoises int(25 * 0.5) = 12 steps.
+ monkeypatch.setattr(dmod, "effective_request_strength", lambda *a, **k: 0.5)
+ backend.generate(prompt = "a sloth", steps = 25)
+ assert armed[0] == (12, True)
+ assert armed[-1] == (None, None)
+ backend.unload()
+
+
+def test_generate_fbcache_still_bypasses_and_resets(fake_runtime, tmp_path, monkeypatch):
+ from core.inference import diffusion as dmod
+
+ (tmp_path / "model.gguf").write_bytes(b"weights")
+ backend = dmod.DiffusionBackend()
+ _load_into(backend, tmp_path)
+ bypass, resets = [], []
+ monkeypatch.setattr(dmod.cuda_graph, "set_bypass", lambda handles, on: bypass.append(on))
+ object.__setattr__(backend._state, "cuda_graphs", ("handle",))
+ object.__setattr__(backend._state, "transformer_cache", dcache.TC_FBCACHE)
+ monkeypatch.setattr(
+ type(backend), "_reset_step_cache", staticmethod(lambda p: resets.append(p))
+ )
+ backend.generate(prompt = "a sloth", steps = 25)
+ assert bypass == [True]
+ assert len(resets) == 1
+ backend.unload()
+
+
+def test_image_load_request_accepts_static_and_video_does_not():
+ from pydantic import ValidationError
+
+ from models.inference import DiffusionLoadRequest, VideoLoadRequest
+
+ assert (
+ DiffusionLoadRequest(model_path = "org/model", transformer_cache = "static").transformer_cache
+ == "static"
+ )
+ with pytest.raises(ValidationError):
+ VideoLoadRequest(model_path = "org/model", transformer_cache = "static")
+
+
+def test_stats_of_the_last_generation_survive_the_post_render_reset():
+ pipe = _installed()
+ _run(pipe, 25)
+ live = ss.static_skip_stats(pipe)["stats"]
+ assert live["calls"] == 25 and live["skipped"] > 0
+ ss.reset_static_step_skip(pipe, None)
+ assert ss.static_skip_stats(pipe)["stats"] == live
+
+
+def test_status_route_carries_the_last_generation_skip_counts():
+ import inspect
+
+ from core.inference import diffusion
+ from models.inference import DiffusionStatusResponse
+
+ pipe = _installed()
+ _run(pipe, 25)
+ ss.reset_static_step_skip(pipe, None)
+ stats = ss.static_skip_stats(pipe)
+ assert stats["stats"]["skipped"] > 0
+ body = DiffusionStatusResponse(
+ loaded = True, transformer_cache = "static", transformer_cache_stats = stats
+ )
+ assert body.model_dump()["transformer_cache_stats"]["stats"] == stats["stats"]
+ assert DiffusionStatusResponse().transformer_cache_stats is None
+ src = inspect.getsource(diffusion.DiffusionBackend.status)
+ assert '"transformer_cache_stats": static_skip_stats(state.pipe)' in src
+
+
+def test_stats_add_up_over_the_chunks_of_one_generation():
+ # Two pipeline calls of one generation (a batch cap or an OOM split): the status keeps both chunks' counts.
+ pipe = _installed()
+ _run(pipe, 25)
+ one = dict(ss.static_skip_stats(pipe)["stats"])
+ skip = ss._find(pipe)
+ real_reset = skip.reset
+ skip.reset = lambda steps, **kw: real_reset(steps, **{**kw, "keep_stats": True})
+ _run(pipe, 25)
+ skip.reset = real_reset
+ ss.reset_static_step_skip(pipe, None)
+ assert ss.static_skip_stats(pipe)["stats"] == {k: 2 * v for k, v in one.items()}
+ _run(pipe, 25)
+ assert ss.static_skip_stats(pipe)["stats"] == one
+
+
+def test_generate_keeps_stats_after_its_first_chunk():
+ import inspect
+
+ from core.inference import diffusion
+
+ src = inspect.getsource(diffusion.DiffusionBackend.generate)
+ assert "keep_stats = static_chunks_run > 0" in src
+
+
+def test_generate_drops_static_state_on_every_exit():
+ import ast
+ import inspect
+ import textwrap
+
+ from core.inference import diffusion
+
+ tree = ast.parse(textwrap.dedent(inspect.getsource(diffusion.DiffusionBackend.generate)))
+ finals = [
+ ast.unparse(stmt)
+ for node in ast.walk(tree)
+ if isinstance(node, ast.Try)
+ for stmt in node.finalbody
+ ]
+ assert any("reset_static_step_skip(static_skip_pipe, None)" in f for f in finals)
+
+
+def test_a_short_generation_reports_its_own_uncached_counts():
+ pipe = _installed()
+ _run(pipe, 25)
+ ss.reset_static_step_skip(pipe, None)
+ assert ss.static_skip_stats(pipe)["stats"]["skipped"] == 9
+ _run(pipe, 8)
+ ss.reset_static_step_skip(pipe, None)
+ assert ss.static_skip_stats(pipe)["stats"] == {"calls": 8, "computed": 8, "skipped": 0}
+
+
+ "scope, owner, shown",
+ [(None, "b", True), ("scoped", "a", True), ("scoped", "b", False), ("scoped", None, True)],
+)
+def test_status_route_shows_skip_counts_only_to_their_producer(monkeypatch, scope, owner, shown):
+ import asyncio
+
+ from core.inference import diffusion_engine_router
+ from hub.services.models import account_access
+ from routes import inference as routes
+
+ stats = {
+ "mode": "taylor1",
+ "planned_skips": 9,
+ "stats": {"calls": 25, "computed": 16, "skipped": 9},
+ }
+ monkeypatch.setattr(
+ diffusion_engine_router,
+ "active_status",
+ lambda: {"loaded": True, "transformer_cache": "static", "transformer_cache_stats": stats},
+ )
+ # The view's snapshot, not the earlier status() read, is what the caller gets.
+ fresh = {**stats, "stats": {"calls": 30, "computed": 19, "skipped": 11}}
+ engine = types.SimpleNamespace(static_skip_view = lambda: (owner, fresh))
+ monkeypatch.setattr(diffusion_engine_router, "get_active_diffusion_engine", lambda: engine)
+ monkeypatch.setattr(account_access, "resident_hidden", lambda *a, **k: False)
+ monkeypatch.setattr(account_access, "account_scope", lambda: scope)
+ monkeypatch.setattr(routes, "current_account_id", lambda: "a")
+ body = asyncio.run(routes.diffusion_status(current_subject = "u", via_api_key = False))
+ assert body.transformer_cache == "static"
+ assert body.transformer_cache_stats == ((fresh if scope else stats) if shown else None)
+
+
+def test_a_new_owner_never_inherits_the_previous_owners_counts():
+ pipe = _installed()
+ _run(pipe, 25, owner = "a")
+ ss.reset_static_step_skip(pipe, None)
+ owner, stats = ss.static_skip_view(pipe)
+ assert owner == "a" and stats["stats"]["skipped"] > 0
+ ss.reset_static_step_skip(pipe, 25, owner = "b")
+ owner, stats = ss.static_skip_view(pipe)
+ assert owner == "b"
+ assert stats["stats"] == {"calls": 0, "computed": 0, "skipped": 0}
+ # The same owner's next generation keeps its last counts visible until it calls.
+ ss.reset_static_step_skip(pipe, None)
+ ss.reset_static_step_skip(pipe, 25, owner = "b")
+ assert ss.static_skip_view(pipe)[0] == "b"
+
+
+def test_planned_skips_survive_the_post_render_reset():
+ pipe = _installed()
+ _run(pipe, 25)
+ ss.reset_static_step_skip(pipe, None)
+ stats = ss.static_skip_stats(pipe)
+ assert stats["stats"]["skipped"] == stats["planned_skips"] == 9
diff --git a/studio/frontend/src/features/images/api.ts b/studio/frontend/src/features/images/api.ts
index 03577549876..8dfc2fb19dc 100644
--- a/studio/frontend/src/features/images/api.ts
+++ b/studio/frontend/src/features/images/api.ts
@@ -141,7 +141,7 @@ export interface DiffusionLoadRequest {
// CUDA / ROCm physical indices this load may use; omit for automatic. Neither engine shards a
// checkpoint, so several cards resolve to the one with the most free VRAM.
gpu_ids?: number[];
- transformer_cache?: "off" | "fbcache";
+ transformer_cache?: "off" | "fbcache" | "static";
// LoRA adapters to BAKE into a torchao int8/fp8 build: they can only attach to the dense transformer BEFORE
// quantisation and compile, so a quantized load that omits them rejects every generation. Ignored by bf16 /
// bnb-4bit, which apply at generate time.
diff --git a/studio/frontend/src/features/images/images-page.tsx b/studio/frontend/src/features/images/images-page.tsx
index 15cec320780..cac249e9f97 100644
--- a/studio/frontend/src/features/images/images-page.tsx
+++ b/studio/frontend/src/features/images/images-page.tsx
@@ -1427,7 +1427,7 @@ export function ImagesPage({
"auto",
);
const gpuChoices = useDiffusionGpuChoices();
- const [transformerCache, setTransformerCache] = useState<"auto" | "off" | "fbcache">("auto");
+ const [transformerCache, setTransformerCache] = useState<"auto" | "off" | "fbcache" | "static">("auto");
const [cpuOffload, setCpuOffload] = useState(false);
// The last load descriptor, so "Reapply" can reload the same model with new advanced options without re-picking it.
const lastLoad = useRef<{ repoId: string; kind: "gguf" | "single_file" | "pipeline"; filename?: string } | null>(
@@ -4426,7 +4426,7 @@ export function ImagesPage({
)}
<AdvancedSelect
label="Step cache"
- hint="First-Block-Cache reuses the transformer tail across steps for many-step models (~1.4x, small quality cost). Auto turns it on only on the Max speed tier at 20+ steps, re-checked per image."
+ hint="First-Block-Cache reuses the transformer tail across steps for many-step models (~1.4x, small quality cost). Auto turns it on only on the Max speed tier at 20+ steps, re-checked per image. Static skip extrapolates every other middle step on a fixed schedule (12+ steps) and keeps the CUDA graph; never picked by Auto."
badge={<ResolvedBadge status={status} controlKey="transformer_cache" />}
value={transformerCache}
onValueChange={(v) => setTransformerCache(v as typeof transformerCache)}
@@ -4434,6 +4434,7 @@ export function ImagesPage({
["auto", "Auto"],
["off", "Off"],
["fbcache", "First-Block-Cache"],
+ ["static", "Static skip"],
]}
/>
<div className="flex items-center justify-between">