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: capture the diffusion denoiser step into a CUDA graph (#10537)

Daniel Han178e1722f544
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.py
index 2fb841753b7..43ca1cb6e40 100644
--- a/studio/backend/core/inference/diffusion.py
+++ b/studio/backend/core/inference/diffusion.py
@@ -128,6 +128,7 @@ from .diffusion_attention import (
from . import diffusion_compile_cache as compile_cache
from . import diffusion_cond_cache as cond_cache
from . import diffusion_gguf_compile as gguf_compile
+from . import diffusion_cuda_graph as cuda_graph
from .diffusion_batched import (
chunk_jobs,
is_oom_error,
@@ -881,6 +882,8 @@ class _LoadState:
generation_count: int = 0
# Pre-warmed torch.compile cache context when a compiled tier ran, else None.
compile_cache_ctx: Any = None
+ # GraphedForward handles installed on the denoiser modules.
+ cuda_graphs: tuple = ()
# Token kept so LoRA adapters selected at generate time can be fetched.
hf_token: Optional[str] = None
# Per-control provenance {control: {value, source, reason}}, for status badges.
@@ -4466,6 +4469,7 @@ class DiffusionBackend:
family = fam,
speed_mode = effective_speed,
cache_active = cache_engaged is not None or cache_may_toggle,
+ cache_engaged = cache_engaged is not None,
offload_active = plan.offload_policy != OFFLOAD_NONE,
logger = logger,
)
@@ -4626,6 +4630,16 @@ class DiffusionBackend:
cache_engaged or "off",
cache_reason,
),
+ "cuda_graph": (
+ None,
+ "on" if speed_applied.get("cuda_graph") else "off",
+ "denoiser step captured per input shape, replayed bit-identically"
+ if speed_applied.get("cuda_graph")
+ else str(
+ getattr(pipe, "_unsloth_cuda_graph_reason", None)
+ or "speed tier does not capture"
+ ),
+ ),
"cpu_offload": (
True if cpu_offload else None,
effective_policy != OFFLOAD_NONE,
@@ -4650,6 +4664,7 @@ class DiffusionBackend:
memory_mode = plan.requested_mode,
speed_mode = effective_speed,
speed_optims = tuple(k for k, v in speed_applied.items() if v),
+ cuda_graphs = tuple(getattr(pipe, "_unsloth_cuda_graphs", ()) or ()),
backend_flags_before = backend_flags_before,
text_encoder_quant = te_quant,
transformer_quant = transformer_quant_engaged,
@@ -4679,6 +4694,7 @@ class DiffusionBackend:
restore_backend_flags(backend_flags_before)
compile_cache.restore(compile_ctx)
gguf_compile.uninstall_all() # idempotent
+ cuda_graph.uninstall_all(getattr(pipe, "_unsloth_cuda_graphs", ()) or ())
if eager_patched:
uninstall_patches()
uninstall_arch_patches()
@@ -5556,6 +5572,7 @@ class DiffusionBackend:
except Exception: # noqa: BLE001 -- best-effort clear
pass
pipe._unsloth_loras = ()
+ cuda_graph.reset_all(getattr(state, "cuda_graphs", ()))
return
if not diffusion_lora.supports_lora(
@@ -5598,8 +5615,13 @@ class DiffusionBackend:
except Exception: # noqa: BLE001
pass
pipe._unsloth_loras = ()
+ # The adapters the graphs were captured with are gone and the marker says none are applied,
+ # so no later call reaches the resets above; without this a base-model render replays them.
+ cuda_graph.reset_all(getattr(state, "cuda_graphs", ()))
raise ValueError(f"Failed to apply LoRA: {exc}") from exc
pipe._unsloth_loras = desired
+ # load_lora_weights can re-materialise parameters the graphs baked pointers to.
+ cuda_graph.reset_all(getattr(state, "cuda_graphs", ()))
def _adjust_baked_loras(
self,
@@ -5632,6 +5654,8 @@ class DiffusionBackend:
if any(w != 0 for (_n, _p, w) in current):
pipe.set_adapters(names, adapter_weights = [0.0] * len(names))
pipe._unsloth_loras = tuple((n, p, 0.0) for (n, p, _w) in current)
+ # Adapter scales are Python values read inside the LoRA forward, so a graph bakes them in.
+ cuda_graph.reset_all(getattr(state, "cuda_graphs", ()))
return
desired = self._resolve_lora_set(
specs,
@@ -5647,6 +5671,7 @@ class DiffusionBackend:
adapter_weights = [w for (_n, _p, w) in desired],
)
pipe._unsloth_loras = desired
+ cuda_graph.reset_all(getattr(state, "cuda_graphs", ()))
return
raise ValueError(
"The LoRA selection changed, but a quantized (int8/fp8) transformer bakes its "
@@ -5742,11 +5767,15 @@ class DiffusionBackend:
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,
offload_active = state.offload_policy != OFFLOAD_NONE,
logger = logger,
)
object.__setattr__(state, "speed_mode", SPEED_DEFAULT)
object.__setattr__(state, "speed_optims", tuple(k for k, v in speed_applied.items() if v))
+ object.__setattr__(
+ state, "cuda_graphs", tuple(getattr(state.pipe, "_unsloth_cuda_graphs", ()) or ())
+ )
entry = (state.resolved or {}).get("speed_mode")
if isinstance(entry, dict):
entry["value"] = SPEED_DEFAULT
@@ -6184,6 +6213,10 @@ class DiffusionBackend:
chunk_kwargs["negative_prompt"] = [
chunk_kwargs["negative_prompt"]
] * len(chunk)
+ # 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:
@@ -6193,7 +6226,15 @@ class DiffusionBackend:
with torch.inference_mode():
out = pipe(**chunk_kwargs).images
except Exception as exc: # noqa: BLE001 - reraised unless a splittable OOM
- if len(chunk) < 2 or not is_oom_error(exc):
+ oom = is_oom_error(exc)
+ if oom:
+ # Drop the graphs on ANY OOM, before the split decision: they are shaped for the failed
+ # attempt and empty_cache() cannot reclaim them (live statics and outputs, and a graph
+ # pool is segregated from the ordinary allocator), so the halved retry below and the
+ # user's next smaller request would both run a step's worth of VRAM short. The shape
+ # that finally renders re-captures on its first step.
+ cuda_graph.reset_all(state.cuda_graphs)
+ if len(chunk) < 2 or not oom:
raise
# OOM backoff: halve the failed chunk and retry; per-image seeds keep every retry reproducible.
empty_cache = getattr(getattr(torch, "cuda", None), "empty_cache", None)
@@ -6368,6 +6409,8 @@ class DiffusionBackend:
# idempotent.
restore_backend_flags(state.backend_flags_before)
compile_cache.restore(state.compile_cache_ctx)
+ # Before clear_gpu_cache(), or the graph pool stays reserved for the life of the process.
+ cuda_graph.uninstall_all(state.cuda_graphs)
gguf_compile.uninstall_all()
if state.eager_patched:
# Lazy import to keep diffusion.py torch-free to import.
diff --git a/studio/backend/core/inference/diffusion_cuda_graph.py b/studio/backend/core/inference/diffusion_cuda_graph.py
new file mode 100644
index 00000000000..03ba20e6a1f
--- /dev/null
+++ b/studio/backend/core/inference/diffusion_cuda_graph.py
@@ -0,0 +1,557 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Static-buffer CUDA-graph capture of ONE denoiser forward, for the diffusion backends.
+
+Each denoiser module gets a ``GraphedForward`` in its INSTANCE ``__dict__`` under ``forward``.
+Not a proxy: the pipelines read ``.dtype`` / ``.config`` / ``.cache_context`` off the transformer.
+Not a hook: hooks move ``nn.Module._call_impl`` off its fast path and offload owns the hook list.
+"""
+
+from __future__ import annotations
+
+import gc
+import inspect
+import os
+import traceback
+import weakref
+from functools import update_wrapper
+from typing import Any, Optional
+
+CUDA_GRAPH_DISABLE_ENV = "UNSLOTH_DISABLE_CUDA_GRAPH"
+
+# Per module. Legitimate second keys exist, but each costs a pool-sized slice of VRAM.
+MAX_GRAPHS_PER_MODULE = 4
+
+# Three per the PyTorch docs. The warmup forces lazy allocations OUTSIDE the capture.
+WARMUP_ITERS = 3
+
+_TRUE_TOKENS = ("1", "true", "yes", "on")
+
+
+def _torch():
+ """The torch module, imported lazily so this file imports on a torch-free host."""
+ import torch
+ return torch
+
+
+def cuda_graph_disabled() -> bool:
+ """Whether the env kill switch is set. Read before any torch or pipe inspection."""
+ return os.environ.get(CUDA_GRAPH_DISABLE_ENV, "").strip().lower() in _TRUE_TOKENS
+
+
+# Not ``torch.utils._pytree``: it makes an unregistered object a LEAF, which must stay visible.
+
+
+def _flatten(obj: Any, out: list) -> tuple:
+ """Append every tensor in ``obj`` to ``out``; return a spec that rebuilds ``obj``."""
+ if _torch().is_tensor(obj):
+ out.append(obj)
+ return ("t", len(out) - 1)
+ if isinstance(obj, (list, tuple)):
+ return ("l", isinstance(obj, tuple), [_flatten(o, out) for o in obj])
+ if isinstance(obj, dict):
+ return ("d", [(k, _flatten(v, out)) for k, v in obj.items()])
+ if isinstance(obj, (int, float, bool, str, bytes)) or obj is None:
+ return ("v", obj)
+ raise TypeError(f"cannot make a static buffer for a {type(obj).__name__} in the call tree")
+
+
+def _rebuild(spec: tuple, tensors: list) -> Any:
+ kind = spec[0]
+ if kind == "t":
+ return tensors[spec[1]]
+ if kind == "l":
+ values = [_rebuild(s, tensors) for s in spec[2]]
+ return tuple(values) if spec[1] else values
+ if kind == "d":
+ return {k: _rebuild(s, tensors) for k, s in spec[1]}
+ return spec[1]
+
+
+def graph_key(obj: Any) -> tuple:
+ """Hashable identity of a call: shape AND stride AND dtype AND device, because a graph replays
+ into the exact buffers it recorded against. Scalars key by VALUE, constants at capture time."""
+ if _torch().is_tensor(obj):
+ return (
+ "t",
+ tuple(obj.shape),
+ tuple(obj.stride()),
+ obj.dtype,
+ obj.device.type,
+ obj.device.index,
+ )
+ if isinstance(obj, (list, tuple)):
+ return ("l", isinstance(obj, tuple), tuple(graph_key(o) for o in obj))
+ if isinstance(obj, dict):
+ return ("d", tuple((k, graph_key(v)) for k, v in obj.items()))
+ if isinstance(obj, (int, float, bool, str, bytes)) or obj is None:
+ return ("v", obj)
+ return ("o", type(obj).__name__, id(obj))
+
+
+def _uncapturable(key: tuple) -> bool:
+ kind = key[0]
+ if kind == "o":
+ return True
+ if kind == "l":
+ return any(_uncapturable(k) for k in key[2])
+ if kind == "d":
+ return any(_uncapturable(k) for _, k in key[1])
+ return False
+
+
+def _has_float(key: tuple) -> bool:
+ """True when the key holds a float, ie a per-step timestep meaning one graph per step."""
+ kind = key[0]
+ if kind == "v":
+ return isinstance(key[1], float)
+ if kind == "l":
+ return any(_has_float(k) for k in key[2])
+ if kind == "d":
+ return any(_has_float(k) for _, k in key[1])
+ return False
+
+
+# Private pools per graph OOM a dual-DiT family; the graphs never replay concurrently, so share.
+_POOL_BOX: list = [None]
+
+# A pool id handed to a capture after the last graph recorded into it died is a dangling pointer.
+_LIVE_WRAPPERS: "weakref.WeakSet" = weakref.WeakSet()
+
+
+def _drop_pool_if_unused() -> None:
+ try:
+ for wrapper in tuple(_LIVE_WRAPPERS):
+ if wrapper.cache:
+ return
+ _POOL_BOX[0] = None
+ except Exception: # noqa: BLE001
+ pass
+
+
+def _warn(logger: Any, what: str, exc: Any) -> None:
+ if logger is not None:
+ logger.warning("diffusion.cuda_graph: %s failed: %s", what, exc)
+
+
+class _Entry:
+ """One captured graph plus the static buffers it replays into."""
+
+ __slots__ = ("graph", "static", "in_spec", "out_spec", "out_tensors")
+
+
+class GraphedForward:
+ """A callable that replaces one denoiser module's ``forward`` with a CUDA-graph replay.
+
+ It walks the ``(args, kwargs)`` tree rather than naming positions, so every family goes through
+ the identical object. A capture that raises poisons the wrapper rather than half-graphing."""
+
+ def __init__(
+ self,
+ module: Any,
+ *,
+ warmup: int = WARMUP_ITERS,
+ max_graphs: int = MAX_GRAPHS_PER_MODULE,
+ logger: Any = None,
+ ) -> None:
+ self.module = module
+ # The CLASS forward: the eager callable, whatever is already in the instance slot.
+ self.orig = type(module).forward.__get__(module)
+ try:
+ update_wrapper(self, self.orig)
+ except Exception: # noqa: BLE001
+ pass
+ try:
+ # LOAD-BEARING: H3's modular pipeline filters kwargs by ``inspect.signature(
+ # transformer.forward).parameters``, so a bare ``**kwargs`` signature drops tensors.
+ self.__signature__ = inspect.signature(self.orig)
+ except Exception: # noqa: BLE001
+ pass
+ self.warmup = int(warmup)
+ self.max_graphs = int(max_graphs)
+ self.logger = logger
+ self.enabled = False
+ self.bypassed = False
+ self.poisoned = False
+ self.capture_error: Optional[dict] = None
+ self.cache: dict = {}
+ self.cap_hit = False
+ self.stats = {
+ "captures": 0,
+ "replays": 0,
+ "eager_calls": 0,
+ "fallbacks": 0,
+ "refused_float": 0,
+ "refused_host_tensor": 0,
+ "refused_object": 0,
+ "cap_skips": 0,
+ }
+ _LIVE_WRAPPERS.add(self)
+
+ def install(self) -> "GraphedForward":
+ """Write ``forward`` into the instance ``__dict__``; ``__setattr__`` would inspect it."""
+ self.module.__dict__["forward"] = self
+ return self
+
+ def uninstall(self) -> "GraphedForward":
+ self.module.__dict__.pop("forward", None)
+ return self
+
+ def enable(self) -> "GraphedForward":
+ self.install()
+ self.enabled = True
+ return self
+
+ def disable(self) -> "GraphedForward":
+ """Disarm AND uninstall, so the call path matches a load that never built a wrapper."""
+ self.enabled = False
+ self.uninstall()
+ return self
+
+ def set_bypass(self, on: bool) -> "GraphedForward":
+ """Run eager without dropping the captured graphs (a chunk under a step cache)."""
+ self.bypassed = bool(on)
+ return self
+
+ def _release(self) -> None:
+ """Return the dropped graphs' pool segments to the device; ``gc.collect`` alone leaves them in the private pool."""
+ try:
+ gc.collect()
+ cuda = getattr(_torch(), "cuda", None)
+ if cuda is not None and hasattr(cuda, "empty_cache"):
+ cuda.empty_cache()
+ except Exception: # noqa: BLE001 - best effort
+ pass
+
+ def reset(self) -> "GraphedForward":
+ """Drop every captured graph (weights changed under us: LoRA load, unload, adapter switch)."""
+ self.cache.clear()
+ self._release()
+ return self
+
+ def poison(self, exc: BaseException) -> "GraphedForward":
+ """Record why capture failed and run eager for the rest of this wrapper's life."""
+ self.capture_error = {
+ "type": type(exc).__name__,
+ "msg": str(exc)[:4000],
+ "traceback": traceback.format_exc()[-6000:],
+ }
+ self.poisoned = True
+ # ``__call__`` short-circuits to eager on ``poisoned`` before it reads the cache, so every
+ # entry is now unreachable and only pins its statics, outputs and slice of the pool for the
+ # life of the load. Freeing is left to the caller's ``_release``, which runs once the failed
+ # capture's own frames are gone, so both go back in one pass.
+ self.cache.clear()
+ _drop_pool_if_unused()
+ return self
+
+ def free(self) -> "GraphedForward":
+ """Drop the graphs and the slot."""
+ self.reset()
+ self.uninstall()
+ self.enabled = False
+ _LIVE_WRAPPERS.discard(self)
+ return self
+
+ def describe(self) -> dict:
+ """A JSON-safe summary for the status payload, without the capture traceback."""
+ error = self.capture_error
+ return {
+ "module": type(self.module).__name__,
+ "enabled": bool(self.enabled),
+ "bypassed": bool(self.bypassed),
+ "poisoned": bool(self.poisoned),
+ "graphs": len(self.cache),
+ "warmup": int(self.warmup),
+ "max_graphs": int(self.max_graphs),
+ "cap_hit": bool(self.cap_hit),
+ "stats": dict(self.stats),
+ "capture_error": None
+ if not error
+ else {
+ "type": str(error.get("type")),
+ "msg": str(error.get("msg")),
+ },
+ }
+
+ def _eager(self, args: tuple, kwargs: dict) -> Any:
+ self.stats["eager_calls"] += 1
+ return self.orig(*args, **kwargs)
+
+ def __call__(self, *args, **kwargs):
+ if (
+ not self.enabled
+ or self.bypassed
+ or self.poisoned
+ # Belt to the caller's per-chunk bypass: one step's cond and uncond share a key.
+ or getattr(self.module, "_unsloth_step_cache", None)
+ ):
+ return self._eager(args, kwargs)
+
+ # True or absent builds an output dataclass, which a replay hands back frozen.
+ if kwargs.get("return_dict", True) is not False:
+ return self._eager(args, kwargs)
+
+ try:
+ key = graph_key((args, kwargs))
+ entry = self.cache.get(key)
+ except Exception: # noqa: BLE001 - an unhashable tree is simply not capturable
+ self.stats["refused_object"] += 1
+ return self._eager(args, kwargs)
+
+ if entry is None:
+ if _uncapturable(key):
+ self.stats["refused_object"] += 1
+ return self._eager(args, kwargs)
+ if _has_float(key):
+ self.stats["refused_float"] += 1
+ return self._eager(args, kwargs)
+ if len(self.cache) >= self.max_graphs:
+ # The recorded graphs keep replaying: one rare new key is no reason to drop them.
+ self.stats["cap_skips"] += 1
+ if not self.cap_hit:
+ self.cap_hit = True
+ if self.logger is not None:
+ self.logger.warning(
+ "diffusion.cuda_graph: graph cap of %d reached on %s; further input "
+ "shapes run eager",
+ self.max_graphs,
+ type(self.module).__name__,
+ )
+ return self._eager(args, kwargs)
+ captured = None
+ try:
+ captured = self._capture(args, kwargs)
+ except Exception as exc: # noqa: BLE001 - a failed capture must never fail the render
+ self.poison(exc)
+ self.stats["fallbacks"] += 1
+ if self.logger is not None:
+ self.logger.warning(
+ "diffusion.cuda_graph: capture failed on %s (%s: %s); this load runs eager",
+ type(self.module).__name__,
+ type(exc).__name__,
+ exc,
+ )
+ # The handled exception keeps _capture's frame, and with it the statics and the pool slice,
+ # alive through the eager retry, which then OOMs on a tight card. capture_error has the text.
+ exc.__traceback__ = None
+ if captured is None:
+ self._release()
+ return self._eager(args, kwargs)
+ entry = captured
+ self.cache[key] = entry
+ if self.logger is not None:
+ self.logger.debug(
+ "diffusion.cuda_graph: captured %s graph %d/%d over %d input tensor(s)",
+ type(self.module).__name__,
+ len(self.cache),
+ self.max_graphs,
+ len(entry.static),
+ )
+
+ live: list = []
+ _flatten((args, kwargs), live)
+ for dst, src in zip(entry.static, live):
+ dst.copy_(src)
+ entry.graph.replay()
+ self.stats["replays"] += 1
+ # Cloned: every replay writes the SAME buffers, which the pipeline holds across steps.
+ return _rebuild(entry.out_spec, [t.clone() for t in entry.out_tensors])
+
+ def _capture(self, args: tuple, kwargs: dict) -> _Entry:
+ torch = _torch()
+ entry = _Entry()
+ live: list = []
+ entry.in_spec = _flatten((args, kwargs), live)
+
+ bad = [(i, str(t.device)) for i, t in enumerate(live) if t.device.type != "cuda"]
+ if bad:
+ self.stats["refused_host_tensor"] += 1
+ raise RuntimeError(
+ f"{len(bad)} input tensor(s) are not on cuda ({bad[:4]}); a host tensor read "
+ f"inside a captured region is baked in at its recorded value"
+ )
+
+ # A tensor made under ``torch.inference_mode()``, which renders run in, refuses ``copy_``.
+ with torch.inference_mode(False):
+ entry.static = [torch.empty_like(t) for t in live]
+ for dst, src in zip(entry.static, live):
+ dst.copy_(src)
+ static_args, static_kwargs = _rebuild(entry.in_spec, entry.static)
+
+ # Side stream: a workspace first created DURING capture is only valid while recording.
+ side = torch.cuda.Stream()
+ side.wait_stream(torch.cuda.current_stream())
+ with torch.cuda.stream(side):
+ for _ in range(self.warmup):
+ self.orig(*static_args, **static_kwargs)
+ torch.cuda.current_stream().wait_stream(side)
+ torch.cuda.synchronize()
+
+ graph = torch.cuda.CUDAGraph()
+ # ``pool = None`` is identical to omitting the argument, so both captures take one path.
+ with torch.cuda.graph(graph, pool = _POOL_BOX[0]):
+ out = self.orig(*static_args, **static_kwargs)
+ if _POOL_BOX[0] is None:
+ try:
+ _POOL_BOX[0] = graph.pool()
+ except Exception: # noqa: BLE001 - a private pool per graph still works
+ pass
+
+ entry.graph = graph
+ out_tensors: list = []
+ entry.out_spec = _flatten(out, out_tensors)
+ entry.out_tensors = out_tensors
+ self.stats["captures"] += 1
+ return entry
+
+
+def graph_eligible(
+ target: Any,
+ *,
+ family: Any,
+ pipe: Any,
+ offload_active: bool,
+ cache_active: bool,
+ speed_mode: str,
+ family_default: bool = True,
+ logger: Any = None,
+) -> tuple[bool, str]:
+ """Whether this load may be graphed, and a short reason when it may not. Cheapest first."""
+ if cuda_graph_disabled():
+ return False, f"disabled by {CUDA_GRAPH_DISABLE_ENV}"
+
+ device = getattr(target, "device", None)
+ if device != "cuda":
+ return False, f"device is {device or 'unknown'}"
+
+ # ROCm reports device "cuda" and has no usable graph capture here; XPU / MPS / CPU never do.
+ backend = getattr(target, "backend", "cuda")
+ if backend != "cuda":
+ return False, f"backend is {backend}"
+
+ if offload_active:
+ # Onload hooks move weights host to card, so a graph's baked pointers go stale.
+ return False, "offload active"
+
+ if cache_active:
+ return False, "step cache active"
+
+ mode = str(speed_mode or "").strip().lower()
+ if mode not in ("default", "max"):
+ return False, f"speed tier {mode or 'off'}"
+
+ # Lazy: ``diffusion_speed`` imports this module, so a module-level import here is a cycle.
+ from .diffusion_speed import _denoiser_dits, _denoiser_unet
+
+ if _denoiser_unet(pipe) is not None:
+ # A whole-compiled U-Net serves from ``_compiled_call_impl``, which a slot swap bypasses.
+ return False, "denoiser is a U-Net"
+
+ if not _denoiser_dits(pipe):
+ return False, "no denoiser transformer"
+
+ try:
+ cuda = getattr(_torch(), "cuda", None)
+ if cuda is None or not hasattr(cuda, "CUDAGraph") or not cuda.is_available():
+ return False, "torch.cuda unavailable"
+ except Exception as exc: # noqa: BLE001
+ _warn(logger, "availability probe", exc)
+ return False, "torch.cuda unavailable"
+
+ if not bool(getattr(family, "supports_cuda_graph", family_default)):
+ return False, "family opts out"
+
+ return True, "eligible"
+
+
+def install_cuda_graphs(
+ pipe: Any,
+ *,
+ logger: Any = None,
+ max_graphs: int = MAX_GRAPHS_PER_MODULE,
+) -> tuple:
+ """Arm one ``GraphedForward`` per denoiser module; the first denoising step captures."""
+ from .diffusion_speed import _denoiser_dits
+
+ handles: list = []
+ for module in _denoiser_dits(pipe):
+ try:
+ handles.append(GraphedForward(module, max_graphs = max_graphs, logger = logger).enable())
+ except Exception as exc: # noqa: BLE001 - a second expert may fail without failing the load
+ _warn(logger, f"install on {type(module).__name__}", exc)
+
+ installed = tuple(handles)
+ try:
+ pipe._unsloth_cuda_graphs = installed
+ except Exception as exc: # noqa: BLE001
+ _warn(logger, "handle stash", exc)
+ if installed and logger is not None:
+ logger.info("diffusion.cuda_graph: armed on %d denoiser module(s)", len(installed))
+ return installed
+
+
+def set_bypass(handles: Any, on: bool) -> None:
+ """Run eager without dropping graphs, for every handle."""
+ for handle in handles or ():
+ try:
+ handle.set_bypass(on)
+ except Exception: # noqa: BLE001 - optimisation only
+ pass
+
+
+def reset_all(handles: Any) -> None:
+ """Drop every captured graph, for every handle (the weights changed).
+
+ Drops the pool token with the last graph: a stale token dies on the allocator's
+ "use_count > 0 INTERNAL ASSERT FAILED", raised after ``torch.cuda.graph`` entered its side
+ stream, so the thread is left off the default stream too."""
+ for handle in handles or ():
+ try:
+ handle.reset()
+ except Exception: # noqa: BLE001 - optimisation only
+ pass
+ _drop_pool_if_unused()
+
+
+def uninstall_all(handles: Any, *, logger: Any = None) -> None:
+ """Free every handle and forget the shared pool if nothing else holds a graph. Idempotent."""
+ for handle in handles or ():
+ try:
+ if logger is not None:
+ logger.debug("diffusion.cuda_graph: %s", handle.describe())
+ handle.free()
+ except Exception: # noqa: BLE001
+ pass
+ _drop_pool_if_unused()
+
+
+def stats(handles: Any) -> dict:
+ """JSON-safe aggregate over the handles, for the status payload."""
+ out = {
+ "graphs": 0,
+ "captures": 0,
+ "replays": 0,
+ "eager_calls": 0,
+ "fallbacks": 0,
+ "cap_skips": 0,
+ "poisoned": False,
+ "capture_error": None,
+ }
+ for handle in handles or ():
+ try:
+ out["graphs"] += len(handle.cache)
+ for field in ("captures", "replays", "eager_calls", "fallbacks", "cap_skips"):
+ out[field] += int(handle.stats.get(field, 0))
+ if handle.poisoned:
+ out["poisoned"] = True
+ error = handle.capture_error
+ if error and out["capture_error"] is None:
+ out["capture_error"] = {
+ "type": str(error.get("type")),
+ "msg": str(error.get("msg")),
+ }
+ except Exception: # noqa: BLE001
+ pass
+ return out
diff --git a/studio/backend/core/inference/diffusion_memory.py b/studio/backend/core/inference/diffusion_memory.py
index b2076b2aec4..123bfcfc5bb 100644
--- a/studio/backend/core/inference/diffusion_memory.py
+++ b/studio/backend/core/inference/diffusion_memory.py
@@ -270,6 +270,10 @@ def reclaimable_snapshot_device_memory(target: Any) -> DeviceMemory:
lives outside it and is not counted here, which is correct: it is not device memory this
generation can allocate into.
+ A captured CUDA graph's pool (``diffusion_cuda_graph``) is reserved but not allocated, so it is
+ credited here, yet ordinary allocations cannot reuse it while a graph holds it, so on a graphed
+ load the guard reads about one step of activations high.
+
Falls back to the plain snapshot on any failure or non-cuda device."""
if getattr(target, "device", "cpu") != "cuda":
return snapshot_device_memory(target)
diff --git a/studio/backend/core/inference/diffusion_speed.py b/studio/backend/core/inference/diffusion_speed.py
index 5d4b7af6f9c..1543ed3d125 100644
--- a/studio/backend/core/inference/diffusion_speed.py
+++ b/studio/backend/core/inference/diffusion_speed.py
@@ -236,13 +236,21 @@ def apply_speed_optims(
speed_mode: str = SPEED_OFF,
cache_active: bool = False,
offload_active: bool = False,
+ cuda_graph_default: bool = True,
+ cache_engaged: Optional[bool] = None,
logger: Any = None,
) -> dict[str, bool]:
"""Apply the opt-in speed optims for ``speed_mode`` to a built pipeline, BEFORE placement /
offload. Returns which engaged; every step is best-effort (unsupported ones are skipped).
``offload_active`` (offload policy != none) installs ``@torch.compiler.disable``d onload hooks,
- so the compile must drop ``fullgraph`` (like an active step cache) or it crashes at step 1."""
+ so the compile must drop ``fullgraph`` (like an active step cache) or it crashes at step 1.
+
+ ``cuda_graph_default`` is what the CUDA-graph arm assumes for a family that declares nothing:
+ True on the image backend, False on video, where ``supports_cuda_graph`` opts in.
+
+ ``cache_active`` also covers a step cache that may still toggle on at generation time. The
+ CUDA-graph arm refuses only on ``cache_engaged``: the caller bypasses per chunk if it toggles."""
applied = {
"channels_last": False,
"cudnn_benchmark": False,
@@ -252,6 +260,7 @@ def apply_speed_optims(
"compiled": False,
"compiled_dequant": False,
"compiled_vae_decode": False,
+ "cuda_graph": False,
}
mode = normalize_speed_mode(speed_mode)
# TF32 (max) and cudnn.benchmark are process-global
@@ -313,6 +322,35 @@ def apply_speed_optims(
applied["tf32"] = _enable_tf32(logger)
applied["fused_qkv"] = _fuse_qkv(pipe, logger)
+ # Deliberately NOT gated on applied["compiled"]: a launch-bound step survives the compile.
+ if mode in (SPEED_DEFAULT, SPEED_MAX):
+ cuda_graph = None
+ ok, reason = False, "cuda graph layer unavailable"
+ try:
+ from . import diffusion_cuda_graph as cuda_graph # noqa: PLC0415 - import cycle
+ ok, reason = cuda_graph.graph_eligible(
+ target,
+ family = family,
+ pipe = pipe,
+ offload_active = offload_active,
+ cache_active = cache_active if cache_engaged is None else bool(cache_engaged),
+ speed_mode = mode,
+ family_default = cuda_graph_default,
+ logger = logger,
+ )
+ except Exception as exc: # noqa: BLE001 - an unimportable graph layer means eager, never a failed load
+ _warn(logger, "cuda graph eligibility", exc)
+ # Stashed either way: status reports WHY graphs are off, not just that they are.
+ try:
+ pipe._unsloth_cuda_graph_reason = reason
+ except Exception: # noqa: BLE001
+ pass
+ if ok and cuda_graph is not None:
+ try:
+ applied["cuda_graph"] = bool(cuda_graph.install_cuda_graphs(pipe, logger = logger))
+ except Exception as exc: # noqa: BLE001 - the load proceeds eager
+ _warn(logger, "cuda graph capture", exc)
+
return applied
@@ -383,8 +421,9 @@ def _compile_repeated_blocks(
if not dits and unet is None:
return False
# default: dynamic=True, fast cold start, no recompile on resolution change. max: max-autotune-no-cudagraphs +
- # dynamic=False, a few % more for a longer compile and a recompile per resolution (CUDA-graph modes crash on the
- # regional block). fullgraph drops to False under a step cache or offload.
+ # dynamic=False, a few % more for a longer compile and a recompile per resolution. Inductor's own cudagraph modes
+ # fail on the regional block -- "accessing tensor output of CUDAGraphs that has been overwritten" -- so the tier
+ # stays on -no-cudagraphs and the capture is taken one level up, at the denoiser module.
kwargs: dict[str, Any] = {
"fullgraph": not (cache_active or offload_active),
"dynamic": not max_autotune,
diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.py
index 73ef1031983..06fc68b7ca2 100644
--- a/studio/backend/core/inference/video.py
+++ b/studio/backend/core/inference/video.py
@@ -112,6 +112,7 @@ from .diffusion_transformer_quant import (
select_transformer_quant_scheme,
)
from .diffusion import _memory_request_forces_offload
+from .diffusion_batched import is_oom_error
from .diffusion_precision import (
effective_te_quant,
normalize_te_quant,
@@ -4028,6 +4029,7 @@ class VideoBackend:
# crashes)
cache_active = cache_engaged is not None or cache_may_toggle,
offload_active = plan.offload_policy != "none",
+ cuda_graph_default = False,
)
if view is pipe:
attention_engaged = engaged
@@ -4772,6 +4774,8 @@ class VideoBackend:
types.SimpleNamespace(
device = device,
dtype = dtype,
+ # ROCm reports device "cuda"; the graph arm refuses it by backend, so keep the field.
+ backend = getattr(umem_target, "backend", "cuda"),
supports_default_torch_compile = getattr(
umem_target, "supports_default_torch_compile", False
),
@@ -4783,6 +4787,7 @@ class VideoBackend:
# The conditioner and the VAEs stay in the rotation even when the denoiser is pinned, so the onload
# hooks are live and fullgraph has to drop.
offload_active = offload_policy != "none",
+ cuda_graph_default = False,
logger = logger,
)
speed_optims = tuple(k for k, v in applied.items() if v)
@@ -4810,6 +4815,16 @@ class VideoBackend:
"cuDNN fused attention on NVIDIA when a speed profile is active",
),
"transformer_cache": (None, "off", "not supported by this modular workflow"),
+ "cuda_graph": (
+ None,
+ "on" if "cuda_graph" in speed_optims else "off",
+ "denoiser step captured per input shape, replayed bit-identically"
+ if "cuda_graph" in speed_optims
+ else str(
+ getattr(pipe, "_unsloth_cuda_graph_reason", None)
+ or "speed tier does not capture"
+ ),
+ ),
"transformer_quant": (
transformer_quant_requested,
transformer_quant_engaged or "off",
@@ -5772,6 +5787,18 @@ class VideoBackend:
}
except Exception as exc:
self._gen = {"active": False}
+ if is_oom_error(exc):
+ # Drop the graphs on ANY CUDA OOM, as the image backend does: a live graph pins its
+ # statics, outputs and slice of the private pool, which empty_cache() cannot reclaim, so
+ # the user's next smaller request would run a step's worth of activations short. The shape
+ # that finally renders re-captures on its first step; a non-OOM failure keeps its graphs.
+ try:
+ from . import diffusion_cuda_graph
+ diffusion_cuda_graph.reset_all(
+ getattr(getattr(state, "pipe", None), "_unsloth_cuda_graphs", ()) or ()
+ )
+ except Exception: # noqa: BLE001 -- cleanup must never mask the real failure
+ pass
_log_failed_generation(request_shape, exc)
raise
finally:
@@ -6228,8 +6255,13 @@ class VideoBackend:
# A GGUF load may have installed the compiled GGUF dequantizer; restore the stock kernels so a later
# speed=off load is bit-identical.
from . import diffusion_gguf_compile
+ from . import diffusion_cuda_graph
diffusion_gguf_compile.uninstall_all()
+ # Before clear_gpu_cache(), or the graph pool stays reserved.
+ diffusion_cuda_graph.uninstall_all(
+ getattr(getattr(state, "pipe", None), "_unsloth_cuda_graphs", ()) or ()
+ )
del state
clear_gpu_cache()
diff --git a/studio/backend/core/inference/video_families.py b/studio/backend/core/inference/video_families.py
index 942f72df4ac..5fe3ea58d6e 100644
--- a/studio/backend/core/inference/video_families.py
+++ b/studio/backend/core/inference/video_families.py
@@ -79,6 +79,9 @@ class VideoFamily:
bf16_components_gb: Optional[tuple[float, float, float]] = None
# true when the DiT compiles cleanly with regional torch.compile (declares _repeated_blocks)
supports_torch_compile: bool = True
+ # Opt-in to the CUDA-graph capture of the denoiser forward (diffusion_cuda_graph.py): only for a family that runs
+ # ONE forward per step with no CFG and no step cache, so a capture has one stable input tree to replay.
+ supports_cuda_graph: bool = False
# Video DiTs are bf16-native, so fp16 promotes to float32; defaults True.
fp16_incompatible: bool = True
# Wan VAE decodes in float32 (bf16 causes banding / black frames), so the loader pins it back. Its size term is
@@ -176,6 +179,7 @@ _FAMILIES: tuple[VideoFamily, ...] = (
# compiling inside a full CPU-offload rotation measured slower than eager, so that case stays on the no-compile
# tier.
supports_torch_compile = True,
+ supports_cuda_graph = True,
gguf_repo = "unsloth/MiniMax-H3-GGUF",
# the modular workflow builds each component through its own from_pretrained
# Hosted pre-quantized FL2VA denoisers. The modular workflow builds each component through its own
diff --git a/studio/backend/tests/test_diffusion_backend.py b/studio/backend/tests/test_diffusion_backend.py
index 407e6eb5d40..3bfcd4c015a 100644
--- a/studio/backend/tests/test_diffusion_backend.py
+++ b/studio/backend/tests/test_diffusion_backend.py
@@ -4362,6 +4362,59 @@ def test_apply_loras_quant_baked_matrix(monkeypatch):
backend._apply_loras(_quant_lora_state(pipe), [("other", 1.0)], ev)
+class _GraphHandle:
+ def __init__(self):
+ self.resets = 0
+
+ def reset(self):
+ self.resets += 1
+ return self
+
+
+def test_a_failed_lora_switch_drops_the_captured_graphs(monkeypatch):
+ """A failed switch records an empty applied set, so the later "none requested" reset never fires."""
+ backend = DiffusionBackend()
+ monkeypatch.setattr(
+ DiffusionBackend,
+ "_resolve_lora_set",
+ staticmethod(
+ lambda specs, **k: tuple((i, f"/adapters/{i}.safetensors", w) for (i, w) in specs)
+ ),
+ )
+
+ class _FailingPipe(_BakePipe):
+ def load_lora_weights(
+ self,
+ path,
+ adapter_name = None,
+ ):
+ raise RuntimeError("size mismatch for the adapter")
+
+ def unload_lora_weights(self):
+ self.calls.append(("unload",))
+
+ pipe = _FailingPipe()
+ pipe._unsloth_loras = (("sloth", "/adapters/sloth.safetensors", 1.0),)
+ handle = _GraphHandle()
+ state = types.SimpleNamespace(
+ pipe = pipe,
+ transformer_quant = None,
+ kind = "dense",
+ family = types.SimpleNamespace(name = "z-image"),
+ hf_token = None,
+ speed_optims = ("cuda_graph",),
+ cuda_graphs = (handle,),
+ )
+
+ with pytest.raises(ValueError, match = "Failed to apply LoRA"):
+ backend._apply_loras(state, [("other", 1.0)], threading.Event())
+
+ assert pipe._unsloth_loras == ()
+ assert handle.resets == 1
+ backend._apply_loras(state, [], threading.Event())
+ assert handle.resets == 1
+
+
def test_baked_lora_names_survive_being_disabled_at_generate_time(monkeypatch):
# A generate with no `loras` zeroes every baked adapter and _active_lora_pairs drops zero-weight entries, so a baked
# load's APPLIED set is always empty. Baked-and-disabled is not never-baked, so record it separately.
@@ -6182,6 +6235,35 @@ def test_generate_oom_backoff_halves_the_batch(fake_runtime, tmp_path):
assert out["seeds"] == [1, 2, 3, 4]
+def test_generate_oom_backoff_drops_the_batch_shaped_graphs(fake_runtime, tmp_path):
+ """A captured entry is batch-shaped and empty_cache() cannot reclaim it, so the retry OOMs too."""
+ backend = _load_zimage_backend(tmp_path)
+ pipe = _CountingPipe(max_images = 2)
+ object.__setattr__(backend._state, "pipe", pipe)
+
+ class _Handle:
+ def __init__(self):
+ self.reset_after = []
+
+ def reset(self):
+ # WHEN the reset landed, in forwards attempted so far.
+ self.reset_after.append(len(pipe.batch_attempts))
+ return self
+
+ def set_bypass(self, on):
+ return self
+
+ handle = _Handle()
+ object.__setattr__(backend._state, "cuda_graphs", (handle,))
+
+ out = backend.generate(prompt = "p", seeds = [1, 2, 3, 4])
+
+ assert pipe.batch_attempts == [4, 2, 2]
+ assert len(out["images"]) == 4 and out["seeds"] == [1, 2, 3, 4]
+ # Exactly once, after the batch of 4 failed and before either half ran.
+ assert handle.reset_after == [1]
+
+
class _BoomPipe(_CountingPipe):
"""Fails every forward with a NON-OOM error (must not trigger backoff)."""
@@ -6195,6 +6277,58 @@ class _BoomPipe(_CountingPipe):
raise RuntimeError("shape mismatch")
+def test_generate_single_image_oom_drops_the_graphs_before_raising(fake_runtime, tmp_path):
+ """A one-image OOM raises instead of splitting, so the graphs must be dropped on the way out."""
+ backend = _load_zimage_backend(tmp_path)
+ pipe = _CountingPipe(max_images = 0) # every forward OOMs, so a single image cannot be split
+ object.__setattr__(backend._state, "pipe", pipe)
+
+ class _Handle:
+ def __init__(self):
+ self.resets = 0
+
+ def reset(self):
+ self.resets += 1
+ return self
+
+ def set_bypass(self, on):
+ return self
+
+ handle = _Handle()
+ object.__setattr__(backend._state, "cuda_graphs", (handle,))
+
+ with pytest.raises(RuntimeError, match = "out of memory"):
+ backend.generate(prompt = "p", seed = 1)
+
+ assert pipe.batch_attempts == [1] # not splittable: raised, not retried
+ assert handle.resets == 1, "the graphs stayed pinned across the raise"
+
+
+def test_generate_non_oom_error_leaves_the_graphs_alone(fake_runtime, tmp_path):
+ """Only an OOM justifies throwing away working graphs; a shape mismatch does not."""
+ backend = _load_zimage_backend(tmp_path)
+ pipe = _BoomPipe()
+ object.__setattr__(backend._state, "pipe", pipe)
+
+ class _Handle:
+ def __init__(self):
+ self.resets = 0
+
+ def reset(self):
+ self.resets += 1
+ return self
+
+ def set_bypass(self, on):
+ return self
+
+ handle = _Handle()
+ object.__setattr__(backend._state, "cuda_graphs", (handle,))
+
+ with pytest.raises(RuntimeError, match = "shape mismatch"):
+ backend.generate(prompt = "p", seeds = [1, 2])
+ assert handle.resets == 0
+
+
def test_generate_non_oom_error_is_not_retried(fake_runtime, tmp_path):
backend = _load_zimage_backend(tmp_path)
pipe = _BoomPipe()
diff --git a/studio/backend/tests/test_diffusion_cuda_graph.py b/studio/backend/tests/test_diffusion_cuda_graph.py
new file mode 100644
index 00000000000..527b02c73d6
--- /dev/null
+++ b/studio/backend/tests/test_diffusion_cuda_graph.py
@@ -0,0 +1,825 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Unit tests for the denoiser CUDA-graph layer (``diffusion_cuda_graph.py``).
+
+Hermetic by default: the ``stub_torch`` fixture installs a fake torch into ``sys.modules``, so
+every refusal, the cap, poisoning and the lifecycle run without a GPU. The last test imports real
+torch inside the body, skips without CUDA, and asserts bit-identity.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import inspect
+import json
+import sys
+import types
+import weakref
+
+import pytest
+
+from core.inference import diffusion_cuda_graph as cg
+
+
+def _contiguous_stride(shape) -> tuple:
+ stride: list = []
+ acc = 1
+ for dim in reversed(shape):
+ stride.append(acc)
+ acc *= dim
+ return tuple(reversed(stride))
+
+
+class _FakeTensor:
+ """Everything the layer touches on a tensor: shape, stride(), dtype, device, copy_, clone."""
+
+ def __init__(
+ self,
+ shape = (1, 4),
+ *,
+ dtype = "bfloat16",
+ device_type = "cuda",
+ device_index = 0,
+ stride = None,
+ value = None,
+ tag = "in",
+ ):
+ self.shape = tuple(shape)
+ self._stride = tuple(stride) if stride is not None else _contiguous_stride(self.shape)
+ self.dtype = dtype
+ self.device = types.SimpleNamespace(type = device_type, index = device_index)
+ self.value = value
+ self.tag = tag
+ self.copied_from: list = []
+ self.clone_of = None
+
+ def stride(self):
+ return self._stride
+
+ def copy_(self, src):
+ self.copied_from.append(src)
+ self.value = src.value
+ return self
+
+ def clone(self):
+ out = _FakeTensor(
+ self.shape,
+ dtype = self.dtype,
+ device_type = self.device.type,
+ device_index = self.device.index,
+ stride = self._stride,
+ value = self.value,
+ tag = self.tag,
+ )
+ out.clone_of = self
+ return out
+
+ def __repr__(self): # pragma: no cover - debugging aid only
+ return f"_FakeTensor({self.shape}, {self.tag}, value = {self.value})"
+
+
+class _FakeGraph:
+ def __init__(self):
+ self.replays = 0
+ self._pool = ("pool", id(self))
+
+ def replay(self):
+ self.replays += 1
+
+ def pool(self):
+ return self._pool
+
+
+class _FakeStream:
+ def __init__(self):
+ self.waited: list = []
+
+ def wait_stream(self, other):
+ self.waited.append(other)
+
+
+def _build_stub_torch():
+ """Just enough torch for the capture path, plus a record of what the layer did to it."""
+ torch = types.ModuleType("torch")
+ records = {
+ "graphs": [], # (graph, pool) per torch.cuda.graph(...)
+ "streams": [],
+ "synchronize": 0,
+ "empty_cache": 0,
+ "inference_mode": [],
+ "graph_error": None, # set to an exception to make CUDAGraph() raise
+ }
+ torch._records = records
+
+ torch.is_tensor = lambda obj: isinstance(obj, _FakeTensor)
+
+ def _empty_like(tensor):
+ return _FakeTensor(
+ tensor.shape,
+ dtype = tensor.dtype,
+ device_type = tensor.device.type,
+ device_index = tensor.device.index,
+ stride = tensor.stride(),
+ tag = "static",
+ )
+
+ torch.empty_like = _empty_like
+
+ @contextlib.contextmanager
+ def _inference_mode(mode = True):
+ records["inference_mode"].append(mode)
+ yield
+
+ torch.inference_mode = _inference_mode
+
+ def _cuda_graph():
+ if records["graph_error"] is not None:
+ raise records["graph_error"]
+ return _FakeGraph()
+
+ @contextlib.contextmanager
+ def _graph(graph, pool = None):
+ records["graphs"].append((graph, pool))
+ yield
+
+ @contextlib.contextmanager
+ def _stream(stream):
+ records["streams"].append(stream)
+ yield
+
+ def _synchronize(*args, **kwargs):
+ records["synchronize"] += 1
+
+ def _empty_cache():
+ records["empty_cache"] += 1
+
+ current = _FakeStream()
+ torch.cuda = types.SimpleNamespace(
+ CUDAGraph = _cuda_graph,
+ graph = _graph,
+ Stream = _FakeStream,
+ stream = _stream,
+ current_stream = lambda: current,
+ synchronize = _synchronize,
+ empty_cache = _empty_cache,
+ is_available = lambda: True,
+ )
+ return torch
+
+
+class _FakeDiT:
+ """Stand-in for a denoiser module: a class-level ``forward`` and an instance ``__dict__``."""
+
+ def __init__(self):
+ self.calls = 0
+ self.seen: list = []
+
+ def forward(
+ self,
+ hidden_states,
+ timestep = None,
+ return_dict = True,
+ ):
+ self.calls += 1
+ self.seen.append((hidden_states, timestep, return_dict))
+ return (_FakeTensor((1, 4), value = ("out", self.calls), tag = "out"),)
+
+
+class UNet2DConditionModel: # noqa: N801 - the class NAME is what _denoiser_unet gates on
+ pass
+
+
+def stub_torch(monkeypatch):
+ torch = _build_stub_torch()
+ monkeypatch.setitem(sys.modules, "torch", torch)
+ return torch
+
+
[email protected](autouse = True)
+def _clean_module_globals():
+ """The shared pool and the live-wrapper set are process-wide, so no test may inherit them."""
+ cg._POOL_BOX[0] = None
+ cg._LIVE_WRAPPERS.clear()
+ yield
+ cg._POOL_BOX[0] = None
+ cg._LIVE_WRAPPERS.clear()
+
+
+def _t(shape = (1, 4), **kwargs):
+ return _FakeTensor(shape, **kwargs)
+
+
+def _armed(module = None, **kwargs):
+ handle = cg.GraphedForward(module if module is not None else _FakeDiT(), **kwargs)
+ return handle.enable()
+
+
+def test_flatten_rebuild_round_trip(stub_torch):
+ a, b, c = _t(), _t((2, 2)), _t((3,))
+ tree = ((a, [b, c]), {"guidance": None, "shapes": (1, 2), "attn": {"scale": 0.5}})
+ out: list = []
+ spec = cg._flatten(tree, out)
+ assert out == [a, b, c]
+ rebuilt = cg._rebuild(spec, out)
+ assert rebuilt == tree
+
+
+def test_flatten_keeps_tuple_and_list_apart(stub_torch):
+ out: list = []
+ spec = cg._flatten([_t(), (_t(),)], out)
+ rebuilt = cg._rebuild(spec, out)
+ assert isinstance(rebuilt, list)
+ assert isinstance(rebuilt[1], tuple)
+
+
+def test_flatten_refuses_unknown_object_and_keys_it_as_o(stub_torch):
+ class Weird:
+ pass
+
+ weird = Weird()
+ with pytest.raises(TypeError):
+ cg._flatten({"controlnet": weird}, [])
+ key = cg.graph_key(weird)
+ assert key[0] == "o" and key[1] == "Weird"
+ assert cg._uncapturable(cg.graph_key({"controlnet": weird})) is True
+ assert cg._uncapturable(cg.graph_key({"controlnet": _t()})) is False
+
+
+def test_graph_key_distinguishes_metadata(stub_torch):
+ base = cg.graph_key(_t((2, 4)))
+ assert base == cg.graph_key(_t((2, 4))) # equal metadata -> equal key -> one graph
+ assert base != cg.graph_key(_t((2, 8)))
+ assert base != cg.graph_key(_t((2, 4), stride = (1, 2)))
+ assert base != cg.graph_key(_t((2, 4), dtype = "float16"))
+ assert base != cg.graph_key(_t((2, 4), device_type = "cpu"))
+ assert base != cg.graph_key(_t((2, 4), device_index = 1))
+
+
+def test_has_float_only_for_real_floats(stub_torch):
+ assert cg._has_float(cg.graph_key({"timestep": 0.5})) is True
+ assert cg._has_float(cg.graph_key([1, True, "x", None, _t()])) is False
+ assert cg._has_float(cg.graph_key((1, [2, {"a": 3.0}]))) is True
+
+
+def test_return_dict_true_or_absent_runs_eager(stub_torch):
+ module = _FakeDiT()
+ handle = _armed(module)
+ handle(_t(), timestep = _t((1,))) # absent -> defaults to True
+ handle(_t(), timestep = _t((1,)), return_dict = True)
+ assert handle.stats["eager_calls"] == 2
+ assert handle.stats["captures"] == 0
+ assert module.calls == 2
+
+
+def test_capture_then_replay_uses_one_graph_and_copies_statics(stub_torch):
+ module = _FakeDiT()
+ handle = _armed(module)
+ first, second = _t(value = 1.0), _t(value = 2.0)
+ handle(first, timestep = _t((1,), value = 10.0), return_dict = False)
+ handle(second, timestep = _t((1,), value = 20.0), return_dict = False)
+
+ assert handle.stats["captures"] == 1
+ assert handle.stats["replays"] == 2
+ assert len(handle.cache) == 1
+ entry = next(iter(handle.cache.values()))
+ # One copy at capture, one per call: the live values reach the static buffers every time.
+ assert entry.static[0].copied_from == [first, first, second]
+ assert entry.static[0].value == 2.0
+ assert entry.graph.replays == 2
+ # Warm-ups plus the capture call, all on the ORIGINAL forward.
+ assert module.calls == cg.WARMUP_ITERS + 1
+ assert stub_torch._records["synchronize"] == 1
+ assert stub_torch._records["inference_mode"] == [False]
+
+
+def test_new_shape_adds_a_second_graph(stub_torch):
+ handle = _armed()
+ handle(_t((1, 4)), timestep = _t((1,)), return_dict = False)
+ handle(_t((2, 4)), timestep = _t((1,)), return_dict = False)
+ assert handle.stats["captures"] == 2
+ assert len(handle.cache) == 2
+ assert handle.poisoned is False
+
+
+def test_outputs_are_cloned_out_of_the_pool(stub_torch):
+ handle = _armed()
+ out = handle(_t(), timestep = _t((1,)), return_dict = False)
+ entry = next(iter(handle.cache.values()))
+ assert out[0] is not entry.out_tensors[0]
+ assert out[0].clone_of is entry.out_tensors[0]
+
+
+def test_float_leaf_refuses_without_capturing(stub_torch):
+ module = _FakeDiT()
+ handle = _armed(module)
+ handle(_t(), timestep = 0.5, return_dict = False)
+ assert handle.stats["refused_float"] == 1
+ assert handle.stats["captures"] == 0
+ assert handle.stats["eager_calls"] == 1
+ assert handle.poisoned is False
+ assert module.calls == 1
+
+
+def test_unknown_object_in_the_tree_refuses_without_capturing(stub_torch):
+ class Weird:
+ pass
+
+ handle = _armed()
+ handle(_t(), timestep = Weird(), return_dict = False)
+ assert handle.stats["refused_object"] == 1
+ assert handle.stats["captures"] == 0
+ assert handle.poisoned is False
+
+
+def test_host_tensor_poisons_with_capture_error(stub_torch):
+ module = _FakeDiT()
+ handle = _armed(module)
+ out = handle(_t(device_type = "cpu"), timestep = _t((1,)), return_dict = False)
+
+ assert handle.poisoned is True
+ assert handle.stats["refused_host_tensor"] == 1
+ assert handle.stats["fallbacks"] == 1
+ assert handle.capture_error["type"] == "RuntimeError"
+ assert "not on cuda" in handle.capture_error["msg"]
+ assert handle.capture_error["traceback"]
+ assert module.calls == 1 # eager, and nothing was warmed up first
+ assert out[0].value == ("out", 1)
+ # Poisoned means eager forever, with no further capture attempts.
+ handle(_t(), timestep = _t((1,)), return_dict = False)
+ assert handle.stats["captures"] == 0
+ assert module.calls == 2
+
+
+def test_capture_exception_poisons_and_returns_the_eager_result(stub_torch):
+ stub_torch._records["graph_error"] = RuntimeError("CUDA out of memory during capture")
+ module = _FakeDiT()
+ logged: list = []
+ logger = types.SimpleNamespace(
+ warning = lambda *a: logged.append(a),
+ info = lambda *a: None,
+ debug = lambda *a: None,
+ )
+ handle = cg.GraphedForward(module, logger = logger).enable()
+ out = handle(_t(), timestep = _t((1,)), return_dict = False)
+
+ assert handle.poisoned is True
+ assert handle.capture_error["type"] == "RuntimeError"
+ assert handle.stats["fallbacks"] == 1
+ assert module.calls == cg.WARMUP_ITERS + 1 # warm-ups ran, then CUDAGraph() raised
+ assert out[0].value == ("out", module.calls)
+ assert len(logged) == 1
+ assert "%s" in logged[0][0] and "capture failed" in logged[0][0]
+ # Type and message only in the log line; the traceback stays on capture_error.
+ assert all("Traceback" not in str(part) for part in logged[0][1:])
+
+
+def test_a_failed_capture_is_released_before_the_eager_fallback(stub_torch):
+ """The handled exception owns _capture's frame and so its statics; the eager fallback must run
+ after they are dropped, or an OOM capture turns into an OOM render."""
+ statics: list = []
+ plain_empty_like = stub_torch.empty_like
+
+ def _recording_empty_like(tensor):
+ out = plain_empty_like(tensor)
+ statics.append(weakref.ref(out))
+ return out
+
+ stub_torch.empty_like = _recording_empty_like
+ stub_torch._records["graph_error"] = RuntimeError("CUDA out of memory during capture")
+
+ seen: list = []
+
+ class _Probe(_FakeDiT):
+ def forward(
+ self,
+ hidden_states,
+ timestep = None,
+ return_dict = True,
+ ):
+ self.calls += 1
+ seen.append(
+ {
+ "live_statics": sum(1 for ref in statics if ref() is not None),
+ "empty_cache": stub_torch._records["empty_cache"],
+ }
+ )
+ return (_FakeTensor((1, 4), value = ("out", self.calls), tag = "out"),)
+
+ handle = _armed(_Probe())
+ out = handle(_t(), timestep = _t((1,)), return_dict = False)
+
+ assert handle.poisoned is True
+ assert out[0].value == ("out", cg.WARMUP_ITERS + 1)
+ assert statics
+ assert seen[0]["live_statics"] == len(statics)
+ assert seen[-1]["live_statics"] == 0
+ assert seen[-1]["empty_cache"] == 1
+ assert handle.capture_error["traceback"]
+ assert handle.capture_error["type"] == "RuntimeError"
+
+
+def test_poisoning_drops_the_graphs_it_can_no_longer_replay(stub_torch):
+ """Once poisoned, ``__call__`` never reads the cache again, so its entries only pin memory."""
+ module = _FakeDiT()
+ handle = _armed(module)
+ handle(_t((1, 4)), timestep = _t((1,)), return_dict = False)
+ assert len(handle.cache) == 1
+ assert cg._POOL_BOX[0] is not None
+
+ # A second shape fails to capture.
+ stub_torch._records["graph_error"] = RuntimeError("CUDA out of memory during capture")
+ out = handle(_t((2, 4)), timestep = _t((1,)), return_dict = False)
+
+ assert handle.poisoned is True
+ assert out[0].value[0] == "out" # the eager result still came back
+ assert handle.cache == {}, "graphs that can never replay again are still pinning memory"
+ assert cg._POOL_BOX[0] is None, "and the pool token outlived the last graph in it"
+ # Still eager from here on, and it does not try to capture again.
+ before = module.calls
+ handle(_t((1, 4)), timestep = _t((1,)), return_dict = False)
+ assert module.calls == before + 1
+ assert handle.stats["captures"] == 1
+
+
+def test_graph_cap_degrades_to_eager_without_poisoning(stub_torch):
+ module = _FakeDiT()
+ logged: list = []
+ logger = types.SimpleNamespace(
+ warning = lambda *a: logged.append(a),
+ info = lambda *a: None,
+ debug = lambda *a: None,
+ )
+ handle = cg.GraphedForward(module, max_graphs = 2, logger = logger).enable()
+ for width in (4, 8, 16, 32):
+ handle(_t((1, width)), timestep = _t((1,)), return_dict = False)
+
+ assert handle.stats["captures"] == 2
+ assert handle.stats["cap_skips"] == 2
+ assert handle.poisoned is False
+ assert len(handle.cache) == 2
+ assert len(logged) == 1 # one warning, not one per skipped shape
+
+ # The graphs already recorded keep replaying.
+ before = handle.stats["replays"]
+ handle(_t((1, 4)), timestep = _t((1,)), return_dict = False)
+ assert handle.stats["replays"] == before + 1
+ assert handle.stats["captures"] == 2
+
+
+def test_bypass_runs_eager_and_keeps_the_graphs(stub_torch):
+ module = _FakeDiT()
+ handle = _armed(module)
+ handle(_t(), timestep = _t((1,)), return_dict = False)
+ assert len(handle.cache) == 1
+
+ cg.set_bypass([handle], True)
+ handle(_t(), timestep = _t((1,)), return_dict = False)
+ assert handle.bypassed is True
+ assert handle.stats["eager_calls"] == 1
+ assert handle.stats["replays"] == 1
+ assert len(handle.cache) == 1 # graphs survive the bypass
+
+ cg.set_bypass([handle], False)
+ handle(_t(), timestep = _t((1,)), return_dict = False)
+ assert handle.stats["replays"] == 2
+ assert handle.stats["captures"] == 1
+
+
+def test_step_cache_marker_forces_eager(stub_torch):
+ module = _FakeDiT()
+ handle = _armed(module)
+ module._unsloth_step_cache = object()
+ handle(_t(), timestep = _t((1,)), return_dict = False)
+ assert handle.stats["eager_calls"] == 1
+ assert handle.stats["captures"] == 0
+
+ module._unsloth_step_cache = None
+ handle(_t(), timestep = _t((1,)), return_dict = False)
+ assert handle.stats["captures"] == 1
+
+
+def test_disabled_wrapper_runs_eager_and_uninstalls(stub_torch):
+ module = _FakeDiT()
+ handle = _armed(module)
+ handle.disable()
+ assert "forward" not in module.__dict__
+ handle(_t(), timestep = _t((1,)), return_dict = False)
+ assert handle.stats["eager_calls"] == 1
+
+
+def test_reset_drops_the_graphs(stub_torch):
+ handle = _armed()
+ handle(_t(), timestep = _t((1,)), return_dict = False)
+ cg.reset_all([handle])
+ assert handle.cache == {}
+ assert stub_torch._records["empty_cache"] == 1
+
+ handle(_t(), timestep = _t((1,)), return_dict = False)
+ assert handle.stats["captures"] == 2 # a LoRA swap re-captures rather than serving old weights
+
+
+def test_install_uninstall_restores_the_class_forward(stub_torch):
+ module = _FakeDiT()
+ pipe = types.SimpleNamespace(transformer = module)
+ handles = cg.install_cuda_graphs(pipe)
+
+ assert len(handles) == 1
+ assert pipe._unsloth_cuda_graphs == handles
+ assert module.__dict__["forward"] is handles[0]
+ assert module.forward is handles[0]
+
+ handles[0](_t(), timestep = _t((1,)), return_dict = False)
+ cg.uninstall_all(handles)
+
+ assert "forward" not in module.__dict__
+ assert module.forward.__func__ is _FakeDiT.forward
+ assert handles[0].cache == {}
+ cg.uninstall_all(handles) # idempotent
+ cg.uninstall_all(())
+ cg.uninstall_all(None)
+
+
+def test_install_covers_every_denoiser_module(stub_torch):
+ pipe = types.SimpleNamespace(
+ transformer = _FakeDiT(),
+ transformer_2 = _FakeDiT(),
+ unconditional_transformer = _FakeDiT(),
+ )
+ handles = cg.install_cuda_graphs(pipe)
+ assert len(handles) == 3
+ assert all(h.enabled for h in handles)
+
+
+def test_second_wrapper_reuses_the_shared_pool(stub_torch):
+ first, second = _armed(), _armed()
+ first(_t(), timestep = _t((1,)), return_dict = False)
+ pool = cg._POOL_BOX[0]
+ assert pool is not None
+ second(_t((2, 4)), timestep = _t((1,)), return_dict = False)
+
+ recorded = stub_torch._records["graphs"]
+ assert recorded[0][1] is None # first capture seeds the pool
+ assert recorded[1][1] == pool # every later capture is handed it
+
+ cg.uninstall_all([first, second])
+ assert cg._POOL_BOX[0] is None # last wrapper freed -> the pool id is forgotten
+
+
+def test_pool_survives_while_another_wrapper_still_holds_a_graph(stub_torch):
+ first, second = _armed(), _armed()
+ first(_t(), timestep = _t((1,)), return_dict = False)
+ second(_t(), timestep = _t((1,)), return_dict = False)
+ pool = cg._POOL_BOX[0]
+ cg.uninstall_all([first])
+ assert cg._POOL_BOX[0] == pool
+
+
+def test_reset_all_forgets_the_pool_token_with_the_last_graph(stub_torch):
+ """A reset that destroys the last graph in the shared pool must forget its token, or the next
+ capture dies on the allocator's "use_count > 0 INTERNAL ASSERT FAILED"."""
+ first, second = _armed(), _armed()
+ first(_t(), timestep = _t((1,)), return_dict = False)
+ second(_t((2, 4)), timestep = _t((1,)), return_dict = False)
+ pool = cg._POOL_BOX[0]
+ assert pool is not None
+
+ # One wrapper still holds a graph: the pool is live and the token stays.
+ cg.reset_all([first])
+ assert cg._POOL_BOX[0] == pool
+
+ # Now nothing does.
+ cg.reset_all([second])
+ assert cg._POOL_BOX[0] is None
+
+ # And the next capture seeds a fresh pool instead of replaying the dead token.
+ first(_t(), timestep = _t((1,)), return_dict = False)
+ assert stub_torch._records["graphs"][-1][1] is None
+
+
+def test_signature_is_the_original_forwards(stub_torch):
+ """H3 filters kwargs by ``inspect.signature``, so a ``(*args, **kwargs)`` wrapper drops them."""
+ module = _FakeDiT()
+ handle = _armed(module)
+ expected = inspect.signature(_FakeDiT.forward.__get__(module))
+ assert handle.__signature__ == expected
+ assert inspect.signature(module.forward) == expected
+ assert list(inspect.signature(module.forward).parameters) == [
+ "hidden_states",
+ "timestep",
+ "return_dict",
+ ]
+ assert handle.__wrapped__ == handle.orig
+ assert handle.__name__ == "forward"
+
+
+ "token, disabled",
+ [
+ ("1", True),
+ ("true", True),
+ ("YES", True),
+ ("On", True),
+ (" true ", True),
+ ("0", False),
+ ("", False),
+ ("no", False),
+ ],
+)
+def test_env_kill_switch(monkeypatch, token, disabled):
+ monkeypatch.setenv(cg.CUDA_GRAPH_DISABLE_ENV, token)
+ assert cg.cuda_graph_disabled() is disabled
+
+
+def test_kill_switch_unset_is_enabled(monkeypatch):
+ monkeypatch.delenv(cg.CUDA_GRAPH_DISABLE_ENV, raising = False)
+ assert cg.cuda_graph_disabled() is False
+
+
+def _target(*, device = "cuda", backend = "cuda"):
+ return types.SimpleNamespace(device = device, backend = backend, dtype = "bfloat16")
+
+
+def _eligible(monkeypatch, **overrides):
+ monkeypatch.delenv(cg.CUDA_GRAPH_DISABLE_ENV, raising = False)
+ kwargs = {
+ "family": types.SimpleNamespace(),
+ "pipe": types.SimpleNamespace(transformer = _FakeDiT()),
+ "offload_active": False,
+ "cache_active": False,
+ "speed_mode": "default",
+ }
+ target = overrides.pop("target", _target())
+ kwargs.update(overrides)
+ return cg.graph_eligible(target, **kwargs)
+
+
+def test_graph_eligible_happy_path(stub_torch, monkeypatch):
+ ok, reason = _eligible(monkeypatch)
+ assert ok is True
+ assert reason == "eligible"
+ assert _eligible(monkeypatch, speed_mode = "max")[0] is True
+
+
+ "overrides, reason",
+ [
+ ({"target": _target(device = "mps", backend = "mps")}, "device is mps"),
+ ({"target": _target(device = "cpu", backend = "cpu")}, "device is cpu"),
+ ({"target": _target(backend = "rocm")}, "backend is rocm"),
+ ({"offload_active": True}, "offload active"),
+ ({"cache_active": True}, "step cache active"),
+ ({"speed_mode": "eager"}, "speed tier eager"),
+ ({"speed_mode": "off"}, "speed tier off"),
+ ({"speed_mode": None}, "speed tier off"),
+ (
+ {"pipe": types.SimpleNamespace(unet = UNet2DConditionModel(), transformer = _FakeDiT())},
+ "denoiser is a U-Net",
+ ),
+ ({"pipe": types.SimpleNamespace()}, "no denoiser transformer"),
+ (
+ {"family": types.SimpleNamespace(supports_cuda_graph = False)},
+ "family opts out",
+ ),
+ ({"family_default": False}, "family opts out"),
+ ],
+)
+def test_graph_eligible_refusals(stub_torch, monkeypatch, overrides, reason):
+ ok, got = _eligible(monkeypatch, **overrides)
+ assert ok is False
+ assert got == reason
+
+
+def test_graph_eligible_refuses_under_the_kill_switch(stub_torch, monkeypatch):
+ monkeypatch.setenv(cg.CUDA_GRAPH_DISABLE_ENV, "1")
+ ok, reason = cg.graph_eligible(
+ _target(),
+ family = types.SimpleNamespace(),
+ pipe = types.SimpleNamespace(transformer = _FakeDiT()),
+ offload_active = False,
+ cache_active = False,
+ speed_mode = "default",
+ )
+ assert ok is False
+ assert reason == f"disabled by {cg.CUDA_GRAPH_DISABLE_ENV}"
+
+
+def test_graph_eligible_needs_torch_cuda(stub_torch, monkeypatch):
+ stub_torch.cuda.is_available = lambda: False
+ assert _eligible(monkeypatch)[1] == "torch.cuda unavailable"
+
+ del stub_torch.cuda
+ assert _eligible(monkeypatch)[1] == "torch.cuda unavailable"
+
+
+def test_graph_eligible_family_opt_in_on_the_video_backend(stub_torch, monkeypatch):
+ opted_in = types.SimpleNamespace(supports_cuda_graph = True)
+ assert _eligible(monkeypatch, family = opted_in, family_default = False)[0] is True
+ bare = types.SimpleNamespace()
+ assert _eligible(monkeypatch, family = bare, family_default = False)[0] is False
+
+
+def test_stats_and_describe_are_json_safe(stub_torch):
+ module = _FakeDiT()
+ handle = _armed(module)
+ handle(_t(), timestep = _t((1,)), return_dict = False)
+ handle(_t((2, 4)), timestep = _t((1,)), return_dict = False)
+ handle(_t(), timestep = _t((1,)), return_dict = True)
+
+ aggregate = cg.stats([handle])
+ assert aggregate == {
+ "graphs": 2,
+ "captures": 2,
+ "replays": 2,
+ "eager_calls": 1,
+ "fallbacks": 0,
+ "cap_skips": 0,
+ "poisoned": False,
+ "capture_error": None,
+ }
+ assert json.loads(json.dumps(aggregate)) == aggregate
+
+ described = handle.describe()
+ assert described["module"] == "_FakeDiT"
+ assert described["graphs"] == 2
+ assert described["enabled"] is True
+ assert json.loads(json.dumps(described)) == described
+
+
+def test_stats_reports_the_capture_error_without_the_traceback(stub_torch):
+ handle = _armed()
+ handle(_t(device_type = "cpu"), timestep = _t((1,)), return_dict = False)
+ aggregate = cg.stats([handle])
+
+ assert aggregate["poisoned"] is True
+ assert aggregate["capture_error"]["type"] == "RuntimeError"
+ assert "traceback" not in aggregate["capture_error"]
+ assert json.loads(json.dumps(aggregate)) == aggregate
+ assert cg.stats(())["graphs"] == 0
+
+
+def test_real_cuda_capture_replays_bit_identically():
+ torch = pytest.importorskip("torch")
+ if not getattr(torch, "cuda", None) or not torch.cuda.is_available():
+ pytest.skip("needs CUDA")
+
+ import torch.nn as nn
+
+ class TinyDiT(nn.Module):
+ def __init__(self, dim):
+ super().__init__()
+ self.proj_in = nn.Linear(dim, dim)
+ self.act = nn.SiLU()
+ self.proj_out = nn.Linear(dim, dim)
+
+ def forward(
+ self,
+ hidden_states,
+ timestep,
+ return_dict = True,
+ ):
+ out = self.proj_out(self.act(self.proj_in(hidden_states))) + timestep
+ if return_dict:
+ return types.SimpleNamespace(sample = out)
+ return (out,)
+
+ torch.manual_seed(0)
+ dim = 64
+ module = TinyDiT(dim).to("cuda", torch.bfloat16).eval()
+ handle = cg.GraphedForward(module).enable()
+ try:
+ for _ in range(3):
+ hidden = torch.randn(2, 8, dim, device = "cuda", dtype = torch.bfloat16)
+ timestep = torch.randn(1, 1, device = "cuda", dtype = torch.bfloat16)
+ with torch.inference_mode():
+ want = handle.orig(hidden_states = hidden, timestep = timestep, return_dict = False)[0]
+ got = module(hidden_states = hidden, timestep = timestep, return_dict = False)[0]
+ assert torch.equal(got, want)
+
+ assert handle.stats["captures"] == 1
+ assert handle.stats["replays"] == 3
+ assert len(handle.cache) == 1
+
+ # A second shape records a second graph rather than replaying the first.
+ hidden = torch.randn(2, 16, dim, device = "cuda", dtype = torch.bfloat16)
+ timestep = torch.randn(1, 1, device = "cuda", dtype = torch.bfloat16)
+ with torch.inference_mode():
+ want = handle.orig(hidden_states = hidden, timestep = timestep, return_dict = False)[0]
+ got = module(hidden_states = hidden, timestep = timestep, return_dict = False)[0]
+ assert torch.equal(got, want)
+ assert handle.stats["captures"] == 2
+ assert cg.stats([handle])["graphs"] == 2
+
+ # return_dict = True stays eager and still returns the dataclass-shaped output.
+ with torch.inference_mode():
+ assert hasattr(module(hidden_states = hidden, timestep = timestep), "sample")
+ assert handle.stats["eager_calls"] == 1
+
+ cg.uninstall_all([handle])
+ assert "forward" not in module.__dict__
+ with torch.inference_mode():
+ after = module(hidden_states = hidden, timestep = timestep, return_dict = False)[0]
+ assert torch.equal(after, want)
+ finally:
+ cg.uninstall_all([handle])
diff --git a/studio/backend/tests/test_diffusion_speed.py b/studio/backend/tests/test_diffusion_speed.py
index 455fb0b965e..40d9d6f6065 100644
--- a/studio/backend/tests/test_diffusion_speed.py
+++ b/studio/backend/tests/test_diffusion_speed.py
@@ -85,6 +85,8 @@ def _stub_torch(monkeypatch):
cuda = types.SimpleNamespace(matmul = types.SimpleNamespace(allow_tf32 = False)),
cudnn = types.SimpleNamespace(allow_tf32 = False, benchmark = False),
)
+ # Said explicitly so the CUDA-graph arm refuses deterministically, whatever the host has.
+ torch.cuda = types.SimpleNamespace(is_available = lambda: False)
# The VAE-decode compile wraps a bound method; identity wrap is enough for tests.
torch.compile = lambda fn, **kwargs: fn
monkeypatch.setitem(sys.modules, "torch", torch)
@@ -245,6 +247,7 @@ def test_speed_off_applies_nothing(monkeypatch):
"compiled_dequant": False,
"compiled_vae_decode": False,
"fp16_accum": False,
+ "cuda_graph": False,
}
assert pipe.vae.mem_format is None and pipe.compiled is False
# off must not touch any process-wide flag (the bit-identical reference path).
@@ -989,3 +992,128 @@ def test_video_snapshot_precedes_transformer_quant():
raise AssertionError(
"no video.py function calls both snapshot_backend_flags and quantize_transformer"
)
+
+
+def _stub_cuda_graph(
+ monkeypatch,
+ *,
+ eligible = True,
+ reason = "ok",
+):
+ """Replace ``core.inference.diffusion_cuda_graph`` with a recorder that captures nothing.
+
+ Into BOTH sys.modules and the package attribute: ``from . import X`` reads the attribute when
+ an earlier import already bound it, and falls back to sys.modules only when it has not."""
+ import core.inference as inference_pkg
+
+ calls = {"eligible": [], "installs": 0}
+
+ stub = types.ModuleType("core.inference.diffusion_cuda_graph")
+
+ def _graph_eligible(target, **kwargs):
+ calls["eligible"].append(kwargs)
+ return eligible, reason
+
+ def _install_cuda_graphs(pipe, *, logger = None):
+ calls["installs"] += 1
+ return ("h",)
+
+ stub.graph_eligible = _graph_eligible
+ stub.install_cuda_graphs = _install_cuda_graphs
+ monkeypatch.setitem(sys.modules, "core.inference.diffusion_cuda_graph", stub)
+ monkeypatch.setattr(inference_pkg, "diffusion_cuda_graph", stub, raising = False)
+ return calls
+
+
[email protected]("mode", [SPEED_DEFAULT, SPEED_MAX])
+def test_cuda_graph_engages_on_compile_tiers(monkeypatch, mode):
+ _stub_torch(monkeypatch)
+ _stub_gguf_accel(monkeypatch)
+ calls = _stub_cuda_graph(monkeypatch)
+ pipe = _Pipe(with_compile = True)
+ applied = apply_speed_optims(pipe, _target(), is_gguf = False, family = _family(), speed_mode = mode)
+ assert applied["cuda_graph"] is True
+ assert calls["installs"] == 1
+ assert pipe._unsloth_cuda_graph_reason == "ok"
+
+
[email protected]("mode", [SPEED_OFF, SPEED_EAGER])
+def test_cuda_graph_skipped_below_the_compile_tiers(monkeypatch, mode):
+ _stub_torch(monkeypatch)
+ _stub_gguf_accel(monkeypatch)
+ calls = _stub_cuda_graph(monkeypatch)
+ pipe = _Pipe(with_compile = True)
+ applied = apply_speed_optims(pipe, _target(), is_gguf = False, family = _family(), speed_mode = mode)
+ assert applied["cuda_graph"] is False
+ assert calls["installs"] == 0 and calls["eligible"] == []
+
+
+def test_cuda_graph_refusal_stashes_the_reason(monkeypatch):
+ _stub_torch(monkeypatch)
+ _stub_gguf_accel(monkeypatch)
+ calls = _stub_cuda_graph(monkeypatch, eligible = False, reason = "cpu offload active")
+ pipe = _Pipe(with_compile = True)
+ applied = apply_speed_optims(
+ pipe, _target(), is_gguf = False, family = _family(), speed_mode = SPEED_DEFAULT
+ )
+ assert applied["cuda_graph"] is False
+ assert calls["installs"] == 0
+ assert pipe._unsloth_cuda_graph_reason == "cpu offload active"
+
+
+def test_cuda_graph_default_is_forwarded_as_family_default(monkeypatch):
+ _stub_torch(monkeypatch)
+ _stub_gguf_accel(monkeypatch)
+ calls = _stub_cuda_graph(monkeypatch)
+ apply_speed_optims(
+ _Pipe(with_compile = True),
+ _target(),
+ is_gguf = False,
+ family = _family(),
+ speed_mode = SPEED_DEFAULT,
+ cuda_graph_default = False,
+ )
+ assert calls["eligible"][0]["family_default"] is False
+ apply_speed_optims(
+ _Pipe(with_compile = True),
+ _target(),
+ is_gguf = False,
+ family = _family(),
+ speed_mode = SPEED_DEFAULT,
+ )
+ assert calls["eligible"][1]["family_default"] is True
+
+
+def test_cuda_graph_cache_engaged_overrides_cache_active_for_the_graph_arm(monkeypatch):
+ _stub_torch(monkeypatch)
+ _stub_gguf_accel(monkeypatch)
+ calls = _stub_cuda_graph(monkeypatch)
+ common = dict(is_gguf = False, family = _family(), speed_mode = SPEED_DEFAULT)
+ apply_speed_optims(
+ _Pipe(with_compile = True), _target(), cache_active = True, cache_engaged = False, **common
+ )
+ assert calls["eligible"][0]["cache_active"] is False
+ apply_speed_optims(
+ _Pipe(with_compile = True), _target(), cache_active = False, cache_engaged = True, **common
+ )
+ assert calls["eligible"][1]["cache_active"] is True
+ apply_speed_optims(_Pipe(with_compile = True), _target(), cache_active = True, **common)
+ assert calls["eligible"][2]["cache_active"] is True
+
+
+def test_cuda_graph_install_failure_leaves_the_load_usable(monkeypatch):
+ _stub_torch(monkeypatch)
+ _stub_gguf_accel(monkeypatch)
+ calls = _stub_cuda_graph(monkeypatch)
+
+ def _boom(pipe, *, logger = None):
+ calls["installs"] += 1
+ raise RuntimeError("CUDA out of memory during capture")
+
+ sys.modules["core.inference.diffusion_cuda_graph"].install_cuda_graphs = _boom
+ pipe = _Pipe(with_compile = True)
+ applied = apply_speed_optims(
+ pipe, _target(), is_gguf = False, family = _family(), speed_mode = SPEED_DEFAULT
+ )
+ assert applied["cuda_graph"] is False and calls["installs"] == 1
+ assert applied["compiled"] is True # the rest of the tier still engaged
diff --git a/studio/backend/tests/test_video_backend.py b/studio/backend/tests/test_video_backend.py
index 22e36dcaa31..1d4e484cb50 100644
--- a/studio/backend/tests/test_video_backend.py
+++ b/studio/backend/tests/test_video_backend.py
@@ -9105,3 +9105,78 @@ def test_a_direct_worker_call_keeps_its_cancellation(fake_runtime, tmp_path, mon
assert (
progress["error"] == VIDEO_CANCELLED_MSG
), f"a direct call reported {progress['error']!r} instead of the cancellation sentinel"
+
+
+def test_cuda_graph_is_a_per_family_opt_in():
+ from core.inference.video_families import detect_video_family
+
+ h3 = detect_video_family("MiniMaxAI/MiniMax-H3")
+ assert h3 is not None and h3.name == "minimax-h3"
+ assert h3.supports_cuda_graph is True
+
+ wan = detect_video_family("Wan-AI/Wan2.2-TI2V-5B-Diffusers")
+ assert wan is not None and wan.name == "wan2.2-ti2v-5b"
+ assert wan.supports_cuda_graph is False
+
+
+def test_every_rebuilt_speed_target_carries_the_backend():
+ """The CUDA-graph arm refuses ROCm by target.backend, which ROCm reports as device "cuda"."""
+ import ast
+ from pathlib import Path
+
+ source = Path(__file__).resolve().parents[1] / "core" / "inference" / "video.py"
+ tree = ast.parse(source.read_text(encoding = "utf-8"))
+ rebuilt = []
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.Call) or getattr(node.func, "id", None) != "apply_speed_optims":
+ continue
+ for arg in node.args:
+ if isinstance(arg, ast.Call) and getattr(arg.func, "attr", None) == "SimpleNamespace":
+ rebuilt.append(arg)
+ assert rebuilt
+ for call in rebuilt:
+ fields = {kw.arg for kw in call.keywords}
+ assert "backend" in fields, f"video.py:{call.lineno} target lacks backend: {sorted(fields)}"
+
+
+class _GraphHandle:
+ """Stands in for a captured denoiser graph: only reset() matters to generate()."""
+
+ def __init__(self):
+ self.resets = 0
+
+ def reset(self):
+ self.resets += 1
+ return self
+
+
+def test_h3_generate_oom_drops_the_graphs_before_raising(fake_runtime):
+ """H3 is the one video family that captures graphs; an OOM must not leave them pinned."""
+ backend = VideoBackend()
+ pipe = _load_h3_modular(backend)
+ handle = _GraphHandle()
+ pipe._unsloth_cuda_graphs = (handle,)
+
+ def _oom(_n):
+ raise RuntimeError("CUDA out of memory. Tried to allocate 1.70 GiB")
+
+ pipe.scheduler.on_step = _oom
+ with pytest.raises(RuntimeError, match = "out of memory"):
+ backend.generate(prompt = "a fox", steps = 4)
+ assert handle.resets == 1, "the graphs stayed pinned across the raise"
+
+
+def test_h3_generate_non_oom_error_leaves_the_graphs_alone(fake_runtime):
+ """Only an OOM justifies throwing away working graphs; a bad shape does not."""
+ backend = VideoBackend()
+ pipe = _load_h3_modular(backend)
+ handle = _GraphHandle()
+ pipe._unsloth_cuda_graphs = (handle,)
+
+ def _boom(_n):
+ raise RuntimeError("shape mismatch")
+
+ pipe.scheduler.on_step = _boom
+ with pytest.raises(RuntimeError, match = "shape mismatch"):
+ backend.generate(prompt = "a fox", steps = 4)
+ assert handle.resets == 0