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: per-block CUDA graphs under every offload mode, and compile below the offload hooks (#12694)

Daniel Han81f1a43321f1
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.py
index 566aaeadebc..b8db11b6af8 100644
--- a/studio/backend/core/inference/diffusion.py
+++ b/studio/backend/core/inference/diffusion.py
@@ -205,6 +205,7 @@ from . import diffusion_prompt_cache as prompt_cache
from . import diffusion_gguf_compile as gguf_compile
from . import diffusion_bg_compile as bg_compile
from . import diffusion_cuda_graph as cuda_graph
+from .diffusion_block_graph import compile_below_hooks_enabled, compile_pipe_below_offload_hooks
from . import diffusion_render_thread as render_thread
from .diffusion_batched import (
chunk_jobs,
@@ -7143,6 +7144,14 @@ class DiffusionBackend:
if effective_speed == SPEED_MAX
else "default",
"vae_decode": vae_decode_compile_allowed(pipe, effective_speed),
+ # An offloaded denoiser compiles its blocks below the hooks, a different graph than a
+ # bundle from the traced-hook compile holds.
+ **(
+ {"below_hooks": True}
+ if plan.offload_policy != OFFLOAD_NONE
+ and compile_below_hooks_enabled()
+ else {}
+ ),
},
logger = logger,
reduction_filter = family_filters_reductions(fam),
@@ -7317,16 +7326,27 @@ class DiffusionBackend:
placement_device = target.torch_device,
logger = logger,
)
- if speed_applied.get("cuda_graph") and _denoiser_hooked(pipe):
- cuda_graph.uninstall_all(getattr(pipe, "_unsloth_cuda_graphs", ()) or ())
- pipe._unsloth_cuda_graphs = ()
- pipe._unsloth_cuda_graph_reason = "offload active"
- speed_applied["cuda_graph"] = False
# streams the whole-resident denoiser back to the flat room while the encoders run
install_encode_release(pipe, plan, logger)
# the speed layer saw only the plan; placement may have pinned every denoiser group since
if denoisers_pinned_resident(pipe):
engage_pinned_denoisers(pipe, speed_applied, logger)
+ # Placement decides the graph layer: a whole-forward recording holds only while no hook moves the
+ # denoiser; otherwise (and for a forward that is not capture-safe) its blocks are recorded instead.
+ if not speed_deferred:
+ if _denoiser_hooked(pipe):
+ compile_pipe_below_offload_hooks(pipe, logger)
+ cuda_graph.arm_block_graphs(
+ pipe,
+ speed_applied,
+ target = target,
+ family = fam,
+ hooked = _denoiser_hooked(pipe),
+ pinned = denoisers_pinned_resident(pipe),
+ cache_engaged = bool(cache_graph_break),
+ speed_mode = effective_speed,
+ logger = logger,
+ )
# Per-control provenance for status. cpu_offload=False is the unset default, so only True is
# explicit.
@@ -7429,11 +7449,8 @@ class DiffusionBackend:
"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"
+ cuda_graph.status_reason(
+ pipe, bool(speed_applied.get("cuda_graph"))
),
),
"cpu_offload": (
@@ -9258,6 +9275,11 @@ class DiffusionBackend:
"dynamic": compile_dynamic(getattr(state.pipe, "transformer", None), True),
"mode": "default",
"vae_decode": vae_decode_compile_allowed(state.pipe, SPEED_DEFAULT),
+ **(
+ {"below_hooks": True}
+ if state.offload_policy != OFFLOAD_NONE and compile_below_hooks_enabled()
+ else {}
+ ),
},
logger = logger,
reduction_filter = family_filters_reductions(state.family),
@@ -9279,6 +9301,19 @@ class DiffusionBackend:
)
if denoisers_pinned_resident(state.pipe):
engage_pinned_denoisers(state.pipe, speed_applied, logger)
+ if _denoiser_hooked(state.pipe):
+ compile_pipe_below_offload_hooks(state.pipe, logger)
+ cuda_graph.arm_block_graphs(
+ state.pipe,
+ speed_applied,
+ target = target,
+ family = state.family,
+ hooked = _denoiser_hooked(state.pipe),
+ pinned = denoisers_pinned_resident(state.pipe),
+ cache_engaged = cache_breaks_graph(state.transformer_cache),
+ speed_mode = SPEED_DEFAULT,
+ logger = logger,
+ )
if getattr(getattr(state.pipe, "vae", None), "_unsloth_fp16_decode", False):
speed_applied["vae_fp16_decode"] = True
object.__setattr__(state, "speed_mode", SPEED_DEFAULT)
@@ -9302,13 +9337,8 @@ class DiffusionBackend:
graph = (state.resolved or {}).get("cuda_graph")
if isinstance(graph, dict):
graph["value"] = "on" if speed_applied.get("cuda_graph") else "off"
- graph["reason"] = (
- "denoiser step captured per input shape, replayed bit-identically"
- if speed_applied.get("cuda_graph")
- else str(
- getattr(state.pipe, "_unsloth_cuda_graph_reason", None)
- or "speed tier does not capture"
- )
+ graph["reason"] = cuda_graph.status_reason(
+ state.pipe, bool(speed_applied.get("cuda_graph"))
)
bg_module = _bg_compile_module(
state.pipe,
diff --git a/studio/backend/core/inference/diffusion_block_graph.py b/studio/backend/core/inference/diffusion_block_graph.py
new file mode 100644
index 00000000000..6e8777aa606
--- /dev/null
+++ b/studio/backend/core/inference/diffusion_block_graph.py
@@ -0,0 +1,1035 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""CUDA graphs per denoiser block, for denoisers whose weights an offload tier moves.
+
+A whole-forward graph only holds while every weight stays at one address. Here each repeated block records on its
+own, keyed by its inputs AND the device addresses of its weights: moved weights run eagerly once, then record again.
+Streamed blocks get fixed addresses from the prefetcher's slot ring (``GroupPrefetcher.enable_slots``). The offload
+hooks stay eager around the recorded compute. Static inputs are shared per (block class, layout) since replays never
+overlap, and all recordings share one pool per denoiser.
+"""
+
+from __future__ import annotations
+
+import os
+import traceback
+from collections import OrderedDict
+from typing import Any, Callable, Optional
+
+from .diffusion_bg_compile import capture_suppressed as _bg_capture_suppressed
+from .diffusion_bg_compile import eager_forced as _bg_eager_forced
+
+BLOCK_GRAPHS_ENV = "UNSLOTH_DIFFUSION_BLOCK_GRAPHS"
+
+# Recordings kept per block (input layouts x weight placements); the least recently replayed goes first.
+MAX_GRAPHS_PER_BLOCK = 6
+
+# Distinct weight placements a block may see without one replay before it stops trying (address churn: a streaming
+# path without the slot ring, or disk offload). Each attempt costs one eager call, never a recording.
+MAX_UNREPLAYED_PLACEMENTS = 6
+
+_OFF = ("0", "off", "false", "no")
+
+
+def _torch():
+ import torch
+ return torch
+
+
+def block_graphs_disabled() -> bool:
+ return (os.environ.get(BLOCK_GRAPHS_ENV) or "").strip().lower() in _OFF
+
+
+def block_graphs_requested() -> bool:
+ """Forced on everywhere, streamed and model-offloaded denoisers included."""
+ return (os.environ.get(BLOCK_GRAPHS_ENV) or "").strip().lower() in ("1", "on", "true", "yes")
+
+
+# Default: only where every block stays on the device. Streamed steps are copy-bound (no gain, extra VRAM); model
+# offload re-uploads the weights every render, so every block would record again.
+OPT_IN_REASON = (
+ "offloaded denoiser streams its blocks: per-block CUDA graphs measured no faster (streamed steps are "
+ "copy-bound) and hold extra VRAM; set " + BLOCK_GRAPHS_ENV + "=1 to record per block"
+)
+MODEL_OFFLOAD_REASON = (
+ "model offload re-uploads the denoiser every render, so every block would record again; set "
+ + BLOCK_GRAPHS_ENV
+ + "=1 to record per block"
+)
+
+
+# Call trees. Like diffusion_cuda_graph's, plus the per-layer prefix K/V caches Qwen-Image-2.1 passes to each block:
+# read-only on a cached step, so their two tensors become static buffers too.
+
+
+def _kv_layer_cache(obj: Any) -> bool:
+ name = type(obj).__name__
+ return name.endswith("KVLayerCache") and hasattr(obj, "k") and hasattr(obj, "v")
+
+
+def _flatten(obj: Any, out: list) -> tuple:
+ torch = _torch()
+ 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)
+ if _kv_layer_cache(obj) and torch.is_tensor(obj.k) and torch.is_tensor(obj.v):
+ return ("kv", type(obj), _flatten(obj.k, out), _flatten(obj.v, out))
+ 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]}
+ if kind == "kv":
+ cache = spec[1].__new__(spec[1])
+ cache.k = _rebuild(spec[2], tensors)
+ cache.v = _rebuild(spec[3], tensors)
+ return cache
+ return spec[1]
+
+
+def _walk(obj: Any, live: list) -> tuple:
+ """Hashable key of a call tree, appending its tensors to ``live`` (compiled blocks guard on inference mode)."""
+ torch = _torch()
+ if torch.is_tensor(obj):
+ live.append(obj)
+ return (
+ "t",
+ tuple(obj.shape),
+ tuple(obj.stride()),
+ obj.dtype,
+ obj.device.type,
+ obj.device.index,
+ bool(obj.is_inference()),
+ )
+ if isinstance(obj, (list, tuple)):
+ return ("l", isinstance(obj, tuple), tuple(_walk(o, live) for o in obj))
+ if isinstance(obj, dict):
+ return ("d", tuple((k, _walk(v, live)) for k, v in obj.items()))
+ if isinstance(obj, (int, float, bool, str, bytes)) or obj is None:
+ return ("v", obj)
+ if _kv_layer_cache(obj) and torch.is_tensor(obj.k) and torch.is_tensor(obj.v):
+ return ("kv", type(obj), _walk(obj.k, live), _walk(obj.v, live))
+ return ("o", type(obj).__name__, id(obj))
+
+
+def _unwalk(key: tuple, tensors: Any) -> Any:
+ kind = key[0]
+ if kind == "t":
+ return next(tensors)
+ if kind == "l":
+ values = [_unwalk(k, tensors) for k in key[2]]
+ return tuple(values) if key[1] else values
+ if kind == "d":
+ return {k: _unwalk(v, tensors) for k, v in key[1]}
+ if kind == "kv":
+ cache = key[1].__new__(key[1])
+ cache.k = _unwalk(key[2], tensors)
+ cache.v = _unwalk(key[3], tensors)
+ return cache
+ return key[1]
+
+
+def graph_key(obj: Any) -> tuple:
+ return _walk(obj, [])
+
+
+def _refusal(key: tuple, kwargs: dict) -> Optional[str]:
+ def walk(k: tuple) -> Optional[str]:
+ kind = k[0]
+ if kind == "o":
+ return "object"
+ if kind == "v" and isinstance(k[1], float):
+ return "float"
+ if kind == "l":
+ for sub in k[2]:
+ why = walk(sub)
+ if why:
+ return why
+ if kind == "d":
+ for _, sub in k[1]:
+ why = walk(sub)
+ if why:
+ return why
+ return None
+
+ why = walk(key)
+ if why:
+ return why
+ # A prefix K/V cache is only read on a cached step; the prefill writes it from Python.
+ if _has_kv(key) and kwargs.get("kv_cache_mode") != "cached":
+ return "kv_write"
+ return None
+
+
+def _has_kv(key: tuple) -> bool:
+ kind = key[0]
+ if kind == "kv":
+ return True
+ if kind == "l":
+ return any(_has_kv(k) for k in key[2])
+ if kind == "d":
+ return any(_has_kv(k) for _, k in key[1])
+ return False
+
+
+def _is_wrapper_subclass(t: Any) -> bool:
+ try:
+ from torch.utils._python_dispatch import is_traceable_wrapper_subclass
+ return bool(is_traceable_wrapper_subclass(t))
+ except Exception: # noqa: BLE001
+ return False
+
+
+class _WeightView:
+ """The block's weights as device addresses, through every level of torchao inner tensors (a wrapper's own
+ ``data_ptr`` is 0; torchao 0.17's int8 nests two)."""
+
+ __slots__ = ("tensors",)
+
+ def __init__(self, module: Any) -> None:
+ seen: set = set()
+ tensors: list = []
+ for t in list(module.parameters()) + list(module.buffers()):
+ if id(t) not in seen:
+ seen.add(id(t))
+ tensors.append(t)
+ self.tensors = tensors
+
+ def placement(self, device_index: Optional[int]) -> Optional[tuple]:
+ """Data pointers of every plain tensor under the weights, or None when one is off ``device_index``."""
+ ptrs: list = []
+ for t in self.tensors:
+ for p in _leaves(t):
+ dev = p.device
+ if dev.type != "cuda" or (device_index is not None and dev.index != device_index):
+ return None
+ ptrs.append(p.data_ptr())
+ return tuple(ptrs)
+
+
+def _leaves(t: Any) -> list:
+ if not _is_wrapper_subclass(t):
+ return [t]
+ try:
+ names, _ = t.__tensor_flatten__()
+ except Exception: # noqa: BLE001 - unflattenable: key on what it reports
+ return [t]
+ out: list = []
+ for n in names:
+ x = getattr(t, n, None)
+ if x is not None:
+ out.extend(_leaves(x))
+ return out
+
+
+_UNSEEN = object()
+
+
+class _Entry:
+ __slots__ = ("graph", "static_in", "static_out", "out_spec", "replays", "slots")
+
+
+import weakref
+
+_LIVE: "weakref.WeakSet" = weakref.WeakSet()
+
+
+def pool_bytes(device: Optional[int] = None) -> int:
+ """Device bytes held in every live block-graph pool (on CUDA ``device`` when given): reserved by the allocator yet
+ never free for other work, so the memory guard must not credit them back as reclaimable."""
+ total = 0
+ for shared in tuple(_LIVE):
+ index = getattr(shared, "device_index", None)
+ if device is not None and index is not None and index != device:
+ continue
+ total += int(getattr(shared, "pool_bytes", 0) or 0)
+ return total
+
+
+class _Shared:
+ """Pool, capture stream and static buffers per (block class, layout), shared by one denoiser's blocks."""
+
+ def __init__(
+ self,
+ device_index: Optional[int],
+ logger: Any = None,
+ ) -> None:
+ self.device_index = device_index
+ self.logger = logger
+ self.root: Any = None # the denoiser, for its NVFP4 per-step precision branch
+ self.pool = None
+ self.stream = None
+ self.static_in: dict = {}
+ self.static_out: dict = {}
+ self.static_refs: dict = {} # slot -> recordings reading its buffers
+ self.warmed: set = set()
+ self.pool_bytes = 0
+ self.static_bytes = 0
+ _LIVE.add(self)
+
+ def capture_stream(self) -> Any:
+ if self.stream is None:
+ torch = _torch()
+ self.stream = torch.cuda.Stream(device = self.device_index)
+ return self.stream
+
+ def graph_pool(self) -> Any:
+ if self.pool is None:
+ torch = _torch()
+ self.pool = torch.cuda.graph_pool_handle()
+ return self.pool
+
+ def statics_for(self, slot: tuple, live: list) -> list:
+ buffers = self.static_in.get(slot)
+ if buffers is None:
+ buffers = [_static_like(t) for t in live]
+ self.static_in[slot] = buffers
+ self.static_bytes += sum(_nbytes(b) for b in buffers)
+ return buffers
+
+ def outputs_for(self, slot: tuple, metas: list) -> list:
+ buffers = self.static_out.get(slot)
+ if buffers is None:
+ torch = _torch()
+ buffers = []
+ for shape, stride, dtype, device, inference in metas:
+ with torch.inference_mode(inference):
+ buffers.append(torch.empty_strided(shape, stride, dtype = dtype, device = device))
+ self.static_out[slot] = buffers
+ self.static_bytes += sum(_nbytes(b) for b in buffers)
+ return buffers
+
+ def hold(self, slots: tuple) -> None:
+ for slot in slots:
+ self.static_refs[slot] = self.static_refs.get(slot, 0) + 1
+
+ def drop(self, slots: tuple) -> None:
+ """Free the static buffers of ``slots`` no recording reads any more (an evicted layout)."""
+ for slot in slots:
+ left = self.static_refs.get(slot, 0) - 1
+ if left > 0:
+ self.static_refs[slot] = left
+ continue
+ self.static_refs.pop(slot, None)
+ buffers = self.static_in.pop(slot, None) or self.static_out.pop(slot, None) or ()
+ self.static_bytes = max(0, self.static_bytes - sum(_nbytes(b) for b in buffers))
+ self.warmed.discard(slot)
+
+ def release(self) -> None:
+ self.static_in.clear()
+ self.static_out.clear()
+ self.static_refs.clear()
+ self.warmed.clear()
+ self.pool = None
+ self.pool_bytes = 0
+ self.static_bytes = 0
+
+
+def _static_like(t: Any) -> Any:
+ """A buffer the compiled block cannot tell from ``t``: same shape, stride, dtype, inference mode AND storage
+ offset (a view such as Qwen-Image-2.1's ``full[:, prefix_len:]`` is guarded on its offset; a fresh tensor at
+ offset 0 recompiles the block)."""
+ torch = _torch()
+ shape, stride, offset = tuple(t.shape), tuple(t.stride()), int(t.storage_offset())
+ extent = 0 if t.numel() == 0 else 1 + sum((n - 1) * st for n, st in zip(shape, stride) if n > 0)
+ with torch.inference_mode(bool(t.is_inference())):
+ base = torch.empty(offset + extent, dtype = t.dtype, device = t.device)
+ return base.as_strided(shape, stride, offset)
+
+
+def _nbytes(t: Any) -> int:
+ try:
+ return int(t.untyped_storage().nbytes())
+ except Exception: # noqa: BLE001
+ return 0
+
+
+def _meta(t: Any) -> tuple:
+ return (tuple(t.shape), tuple(t.stride()), t.dtype, t.device, bool(t.is_inference()))
+
+
+class BlockGraph:
+ """Replaces one block's compute callable (below its offload hooks) with a recording keyed by inputs and weight
+ placement. Any refusal or failure runs ``compute`` itself, so the block is never worse than ungraphed."""
+
+ def __init__(
+ self,
+ block: Any,
+ compute: Callable,
+ shared: _Shared,
+ *,
+ max_graphs: int = MAX_GRAPHS_PER_BLOCK,
+ ) -> None:
+ self.block = block
+ self.compute = compute
+ self.shared = shared
+ self.cls = type(block).__name__
+ self.weights = _WeightView(block)
+ self.max_graphs = int(max_graphs)
+ self.cache: "OrderedDict[tuple, _Entry]" = OrderedDict()
+ self.enabled = True
+ self.bypassed = False
+ self.poisoned = False
+ self.capture_error: Optional[dict] = None
+ # (layout, placement) -> output meta of its first call; several, since CFG alternates two text lengths
+ self.seen: "OrderedDict[tuple, tuple]" = OrderedDict()
+ self.unreplayed_placements = 0
+ self.churned = False
+ self.protect: Any = None # None until resolved, then False or the NVFP4 step controller
+ self.placements: set = set()
+ self.refusals: dict = {}
+ self.stats = {
+ "captures": 0,
+ "recaptures": 0,
+ "replays": 0,
+ "eager_calls": 0,
+ "warmups": 0,
+ "fallbacks": 0,
+ "evictions": 0,
+ "refused_float": 0,
+ "refused_object": 0,
+ "refused_host_input": 0,
+ "refused_kv_write": 0,
+ "refused_host_weight": 0,
+ "refused_grad": 0,
+ "refused_output": 0,
+ "address_churn": 0,
+ }
+ try:
+ from functools import update_wrapper
+ update_wrapper(self, compute)
+ except Exception: # noqa: BLE001
+ pass
+
+ def set_bypass(self, on: bool) -> "BlockGraph":
+ self.bypassed = bool(on)
+ return self
+
+ def reset(self) -> "BlockGraph":
+ """Drop every recording (the weights changed: a LoRA load or scale, an unload) and re-read which tensors the
+ block owns, since an adapter adds parameters the placement key must cover."""
+ self._forget_all()
+ try:
+ self.weights = _WeightView(self.block)
+ except Exception: # noqa: BLE001
+ pass
+ self.seen.clear()
+ self.unreplayed_placements = 0
+ self.placements.clear()
+ self.refusals.clear()
+ return self
+
+ def _eager(self, args: tuple, kwargs: dict) -> Any:
+ self.stats["eager_calls"] += 1
+ return self.compute(*args, **kwargs)
+
+ def __call__(self, *args: Any, **kwargs: Any) -> Any:
+ if _bg_capture_suppressed():
+ return self.compute(*args, **kwargs)
+ if not self.enabled or self.bypassed or self.poisoned or self.churned or _bg_eager_forced():
+ return self._eager(args, kwargs)
+ torch = _torch()
+ if torch.is_grad_enabled():
+ self.stats["refused_grad"] += 1
+ return self._eager(args, kwargs)
+ live: list = []
+ try:
+ key = _walk((args, kwargs), live)
+ why = self.refusals.get(key, _UNSEEN)
+ if why is _UNSEEN:
+ why = _refusal(key, kwargs)
+ if len(self.refusals) < 64:
+ self.refusals[key] = why
+ except Exception: # noqa: BLE001
+ why = "object"
+ key = None
+ if why:
+ self.stats["refused_" + why] += 1
+ return self._eager(args, kwargs)
+ placement = self.weights.placement(self.shared.device_index)
+ if placement is None:
+ self.stats["refused_host_weight"] += 1
+ return self._eager(args, kwargs)
+ if any(t.device.type != "cuda" for t in live):
+ # A capture never records a host read, so a replay would keep the recorded value.
+ self.stats["refused_host_input"] += 1
+ return self._eager(args, kwargs)
+ if self.protect is None:
+ self.protect = self._protect_controller()
+ if self.protect:
+ # One recording per precision branch: a W4A4 replay at a W4A16 step would skip the protection.
+ from .diffusion_cuda_graph import protect_graph_key
+ placement = (placement, protect_graph_key(self.protect))
+ full = (key, placement)
+ entry = self.cache.get(full)
+ if entry is None:
+ if full not in self.seen:
+ # First call at this layout and placement: run it for real (the warm-up), record on the next one.
+ return self._first_sighting(full, args, kwargs)
+ entry = self._record(full, live)
+ if entry is None:
+ return self._eager(args, kwargs)
+ else:
+ self.cache.move_to_end(full)
+ return self._replay(entry, live)
+
+ def _protect_controller(self) -> Any:
+ root = self.shared.root
+ try:
+ from .diffusion_cuda_graph import _protect_keyed
+
+ if root is None or not _protect_keyed(root):
+ return False
+ from .diffusion_nvfp4_protect import module_controller
+
+ return module_controller(root)
+ except Exception: # noqa: BLE001
+ return False
+
+ def _first_sighting(self, full: tuple, args: tuple, kwargs: dict) -> Any:
+ placement = full[1]
+ if placement not in self.placements:
+ self.placements.add(placement)
+ self.unreplayed_placements += 1
+ if self.unreplayed_placements > MAX_UNREPLAYED_PLACEMENTS:
+ self.churned = True
+ self.stats["address_churn"] += 1
+ return self._eager(args, kwargs)
+ out = self._eager(args, kwargs)
+ try:
+ flat: list = []
+ spec = _flatten(out, flat)
+ self.seen[full] = (spec, [_meta(t) for t in flat])
+ while len(self.seen) > 4:
+ self.seen.popitem(last = False)
+ except Exception: # noqa: BLE001 - an output the graph cannot hand back (a dataclass, an object)
+ self.stats["refused_output"] += 1
+ return out
+
+ def _record(self, full: tuple, live: list) -> Optional[_Entry]:
+ from .diffusion_cuda_graph import _capturing, refuse_if_exhausted, retire_failed_capture
+
+ torch = _torch()
+ key = full[0]
+ slot = (self.cls, key)
+ out_spec, metas = self.seen.pop(full)
+ entry = _Entry()
+ out_slot = (self.cls, key, "out", tuple(metas))
+ try:
+ entry.static_in = self.shared.statics_for(slot, live)
+ entry.static_out = self.shared.outputs_for(out_slot, metas)
+ for dst, src in zip(entry.static_in, live):
+ dst.copy_(src)
+ static_args, static_kwargs = _unwalk(key, iter(entry.static_in))
+ if slot not in self.shared.warmed:
+ # Once per block class and layout, on the compute stream (its cached blocks stay reusable): any guard
+ # the static buffers trip recompiles here, never inside the recording.
+ self.compute(*static_args, **static_kwargs)
+ self.shared.warmed.add(slot)
+ self.stats["warmups"] += 1
+ current = torch.cuda.current_stream()
+ stream = self.shared.capture_stream()
+ stream.wait_stream(current)
+ refuse_if_exhausted(self.shared.logger)
+ graph = torch.cuda.CUDAGraph()
+ pool = self.shared.graph_pool()
+ with torch.cuda.stream(stream):
+ before = torch.cuda.memory_reserved()
+ with _capturing():
+ try:
+ # Inside the try: a capture_begin that raised after taking the pool is abandoned too.
+ graph.capture_begin(pool = pool, capture_error_mode = "thread_local")
+ try:
+ out = self.compute(*static_args, **static_kwargs)
+ flat: list = []
+ spec = _flatten(out, flat)
+ if spec != out_spec or len(flat) != len(entry.static_out):
+ raise RuntimeError("block output layout changed between calls")
+ for dst, src in zip(entry.static_out, flat):
+ dst.copy_(src)
+ finally:
+ graph.capture_end()
+ except BaseException as exc:
+ # Later blocks record into a fresh pool; this one stays with the graphs already in it.
+ retire_failed_capture(graph, pool, exc)
+ if self.shared.pool == pool:
+ self.shared.pool = None
+ raise
+ del out, flat
+ current.wait_stream(stream)
+ self.shared.pool_bytes += max(0, torch.cuda.memory_reserved() - before)
+ except Exception as exc: # noqa: BLE001 - a block that cannot record runs its compute for the load's life
+ self._poison(exc)
+ return None
+ entry.slots = (slot, out_slot)
+ self.shared.hold(entry.slots)
+ entry.graph = graph
+ entry.out_spec = out_spec
+ entry.replays = 0
+ if any(k[0] == full[0] for k in self.cache):
+ self.stats["recaptures"] += 1
+ self.cache[full] = entry
+ self.stats["captures"] += 1
+ while len(self.cache) > self.max_graphs:
+ _, evicted = self.cache.popitem(last = False)
+ self._forget(evicted)
+ self.stats["evictions"] += 1
+ return entry
+
+ def _forget(self, entry: _Entry) -> None:
+ entry.graph = None
+ self.shared.drop(getattr(entry, "slots", ()))
+
+ def _forget_all(self) -> None:
+ for entry in self.cache.values():
+ self._forget(entry)
+ self.cache.clear()
+
+ def _replay(self, entry: _Entry, live: list) -> Any:
+ for dst, src in zip(entry.static_in, live):
+ if dst.data_ptr() != src.data_ptr():
+ dst.copy_(src)
+ entry.graph.replay()
+ entry.replays += 1
+ self.stats["replays"] += 1
+ self.unreplayed_placements = 0
+ self.placements.clear()
+ return _rebuild(entry.out_spec, [t.clone() for t in entry.static_out])
+
+ def _poison(self, exc: BaseException) -> None:
+ self.capture_error = {
+ "type": type(exc).__name__,
+ "msg": str(exc)[:4000],
+ "traceback": traceback.format_exc()[-6000:],
+ }
+ self.poisoned = True
+ self._forget_all()
+ self.stats["fallbacks"] += 1
+ logger = self.shared.logger
+ if logger is not None:
+ logger.warning(
+ "diffusion.block_graph: recording %s failed (%s: %s); this block runs ungraphed",
+ self.cls,
+ type(exc).__name__,
+ exc,
+ )
+ exc.__traceback__ = None
+
+
+def _group_offload_hook(module: Any) -> Any:
+ try:
+ from diffusers.hooks import group_offloading as go
+
+ registry = getattr(module, "_diffusers_hook", None)
+ if registry is None:
+ return None
+ return registry.get_hook(getattr(go, "_GROUP_OFFLOADING", "group_offloading"))
+ except Exception: # noqa: BLE001
+ return None
+
+
+def _is_original_forward(fn: Any, module: Any) -> bool:
+ return getattr(fn, "__self__", None) is module and getattr(fn, "__func__", None) is getattr(
+ type(module), "forward", None
+ )
+
+
+def _inner_hook_reason(block: Any) -> Optional[str]:
+ """Why a block's own subtree moves weights mid-forward (per-layer offload), which no recording can hold."""
+ for name, sub in block.named_modules():
+ if sub is block:
+ continue
+ if getattr(sub, "_hf_hook", None) is not None:
+ return "per-layer offload hooks inside the block"
+ if _group_offload_hook(sub) is not None:
+ return "per-layer group offload inside the block"
+ hook = getattr(block, "_hf_hook", None)
+ if hook is not None:
+ return "an accelerate hook on the block"
+ return None
+
+
+def repeated_blocks(transformer: Any) -> list:
+ names = set(getattr(transformer, "_repeated_blocks", None) or ())
+ if not names:
+ return []
+ return [m for m in transformer.modules() if type(m).__name__ in names and m is not transformer]
+
+
+class BlockGraphSet:
+ """Every ``BlockGraph`` of one denoiser, behind the handle interface of ``diffusion_cuda_graph``."""
+
+ def __init__(
+ self,
+ transformer: Any,
+ shared: _Shared,
+ logger: Any = None,
+ ) -> None:
+ self.module = transformer
+ self.shared = shared
+ self.logger = logger
+ self.graphs: list = []
+ self.restores: list = []
+ self.enabled = True
+ self.bypassed = False
+ self.slots_mib = 0
+ self._prefetcher = None
+ self.mode = "blocks"
+ self.max_graphs = MAX_GRAPHS_PER_BLOCK
+
+ @property
+ def cache(self) -> dict:
+ out: dict = {}
+ for i, g in enumerate(self.graphs):
+ for k, v in g.cache.items():
+ out[(i, k)] = v
+ return out
+
+ @property
+ def stats(self) -> dict:
+ total: dict = {}
+ for g in self.graphs:
+ for k, v in g.stats.items():
+ total[k] = total.get(k, 0) + int(v)
+ # The whole-forward wrapper's names, so diffusion_cuda_graph.stats aggregates both kinds alike.
+ total["refused_host_tensor"] = total.get("refused_host_weight", 0)
+ total["cap_skips"] = total.get("evictions", 0)
+ return total
+
+ @property
+ def poisoned(self) -> bool:
+ return bool(self.graphs) and all(g.poisoned or g.churned for g in self.graphs)
+
+ @property
+ def capture_error(self) -> Optional[dict]:
+ for g in self.graphs:
+ if g.capture_error:
+ return g.capture_error
+ return None
+
+ def set_bypass(self, on: bool) -> "BlockGraphSet":
+ self.bypassed = bool(on)
+ for g in self.graphs:
+ g.set_bypass(on)
+ return self
+
+ def reset(self) -> "BlockGraphSet":
+ for g in self.graphs:
+ g.reset()
+ self.shared.release()
+ _release_cached()
+ return self
+
+ def free(self) -> "BlockGraphSet":
+ for g in self.graphs:
+ g.reset()
+ g.enabled = False
+ for restore in reversed(self.restores):
+ try:
+ restore()
+ except Exception: # noqa: BLE001
+ pass
+ self.restores.clear()
+ self.graphs.clear()
+ self.shared.release()
+ self.enabled = False
+ try:
+ from .diffusion_offload_prefetch import module_prefetcher
+ pf = module_prefetcher(self.module)
+ if pf is not None:
+ pf.disable_slots()
+ except Exception: # noqa: BLE001
+ pass
+ _release_cached()
+ return self
+
+ def describe(self) -> dict:
+ s = self.stats
+ return {
+ "module": type(self.module).__name__,
+ "mode": self.mode,
+ "blocks": len(self.graphs),
+ "enabled": bool(self.enabled),
+ "bypassed": bool(self.bypassed),
+ "poisoned": bool(self.poisoned),
+ "graphs": sum(len(g.cache) for g in self.graphs),
+ "max_graphs": self.max_graphs,
+ "stats": s,
+ "slot_ring_mib": int(self.slots_mib),
+ "slot_ring_allocated_mib": int(
+ getattr(getattr(self, "_prefetcher", None), "slot_bytes", 0) or 0
+ )
+ >> 20,
+ "pool_mib": int(self.shared.pool_bytes >> 20),
+ "static_mib": int(self.shared.static_bytes >> 20),
+ "capture_error": None
+ if not self.capture_error
+ else {
+ "type": str(self.capture_error.get("type")),
+ "msg": str(self.capture_error.get("msg")),
+ },
+ }
+
+ def why_off(self) -> Optional[str]:
+ """Why no block has replayed, once a render has run; None while any replays or before the first call."""
+ s = self.stats
+ if s.get("replays") or not (s.get("eager_calls") or s.get("captures")):
+ return None
+ churned = sum(1 for g in self.graphs if g.churned)
+ poisoned = sum(1 for g in self.graphs if g.poisoned)
+ parts = []
+ if churned:
+ parts.append(f"{churned} block(s) find their weights at a new address every call")
+ if poisoned:
+ err = self.capture_error or {}
+ parts.append(f"{poisoned} block(s) failed to record ({err.get('type') or 'error'})")
+ for field, label in (
+ ("refused_host_weight", "weights not on the GPU"),
+ ("refused_kv_write", "prefix K/V prefill steps"),
+ ("refused_float", "a float argument"),
+ ("refused_object", "a non-tensor argument"),
+ ("refused_output", "an output the graph cannot hand back"),
+ ):
+ if s.get(field):
+ parts.append(f"{s[field]} call(s) with {label}")
+ detail = "; ".join(parts) or "every call so far was a first sighting"
+ return f"armed per block, but all {s.get('eager_calls', 0)} block call(s) ran their compute ({detail})"
+
+ def held_bytes(self) -> int:
+ """Device memory this layer holds that the caching allocator cannot hand to anything else."""
+ pf = getattr(self, "_prefetcher", None)
+ slots = int(getattr(pf, "slot_bytes", 0) or 0) if pf is not None else 0
+ return int(self.shared.pool_bytes + self.shared.static_bytes + slots)
+
+
+def _release_cached() -> None:
+ try:
+ import gc
+
+ gc.collect()
+ torch = _torch()
+ if torch.cuda.is_available():
+ torch.cuda.empty_cache()
+ except Exception: # noqa: BLE001
+ pass
+
+
+def _device_index(transformer: Any, fallback: Any = None) -> Optional[int]:
+ torch = _torch()
+ for cand in (getattr(transformer, "_unsloth_resident_device", None), fallback):
+ if cand is None:
+ continue
+ try:
+ dev = torch.device(cand)
+ except Exception: # noqa: BLE001
+ continue
+ if dev.type == "cuda":
+ return dev.index # None: whichever CUDA device is current when the block runs
+ return None
+
+
+def install_block_graphs(
+ transformer: Any,
+ *,
+ device: Any = None,
+ logger: Any = None,
+ slots: bool = True,
+) -> tuple[Optional[BlockGraphSet], str]:
+ """Arm one ``BlockGraph`` per repeated block of ``transformer``. Returns (handle or None, reason)."""
+ if block_graphs_disabled():
+ return None, f"block graphs disabled by {BLOCK_GRAPHS_ENV}"
+ blocks = repeated_blocks(transformer)
+ if not blocks:
+ return None, "no repeated blocks to record"
+ torch = _torch()
+ shared = _Shared(_device_index(transformer, device), logger)
+ shared.root = transformer
+ handle = BlockGraphSet(transformer, shared, logger)
+ compile_below_offload_hooks(transformer, logger)
+ refused: dict = {}
+ for block in blocks:
+ why = _inner_hook_reason(block)
+ if why:
+ refused[why] = refused.get(why, 0) + 1
+ continue
+ compiled = getattr(block, "_compiled_call_impl", None)
+ hook = _group_offload_hook(block)
+ if hook is not None and compiled is not None:
+ # compiled through its hooks (UNSLOTH_DIFFUSION_COMPILE_BELOW_HOOKS=0): the compute is inside a dynamo frame
+ why = "compiled through its offload hooks"
+ refused[why] = refused.get(why, 0) + 1
+ continue
+ try:
+ if hook is not None:
+ # Below the hook: the onload / offload stay eager Python and the recording holds only the compute.
+ registry = getattr(block, "_diffusers_hook", None)
+ refs = list(getattr(registry, "_fn_refs", None) or ())
+ target = getattr(block, "_unsloth_below_hook_ref", None)
+ if target not in refs:
+ target = next(
+ (
+ r
+ for r in refs
+ if _is_original_forward(getattr(r, "forward", None), block)
+ ),
+ None,
+ )
+ if target is None:
+ refused["a stacked hook chain"] = refused.get("a stacked hook chain", 0) + 1
+ continue
+ compute = target.forward
+ graph = BlockGraph(block, compute, shared)
+ target.forward = graph
+
+ def restore(ref: Any = target, fn: Any = compute) -> None:
+ if ref.forward is not fn:
+ ref.forward = fn
+ elif compiled is not None:
+ graph = BlockGraph(block, compiled, shared)
+ block._compiled_call_impl = graph
+
+ def restore(
+ m: Any = block,
+ c: Any = compiled,
+ g: Any = graph,
+ ) -> None:
+ if getattr(m, "_compiled_call_impl", None) is g:
+ m._compiled_call_impl = c
+ else:
+ slot = block.__dict__.get("forward")
+ fwd = slot if slot is not None else type(block).forward.__get__(block)
+ graph = BlockGraph(block, fwd, shared)
+ block.__dict__["forward"] = graph
+
+ def restore(
+ m: Any = block,
+ s: Any = slot,
+ g: Any = graph,
+ ) -> None:
+ if m.__dict__.get("forward") is g:
+ if s is None:
+ m.__dict__.pop("forward", None)
+ else:
+ m.__dict__["forward"] = s
+ except Exception as exc: # noqa: BLE001
+ refused[f"install failed ({type(exc).__name__})"] = (
+ refused.get(f"install failed ({type(exc).__name__})", 0) + 1
+ )
+ continue
+ handle.graphs.append(graph)
+ handle.restores.append(restore)
+ if not handle.graphs:
+ reason = (
+ ", ".join(f"{n} block(s): {w}" for w, n in refused.items()) or "no block could be armed"
+ )
+ return None, reason
+ if slots and torch.cuda.is_available():
+ try:
+ from .diffusion_offload_prefetch import module_prefetcher
+ pf = module_prefetcher(transformer)
+ if pf is not None:
+ planned = pf.enable_slots(logger = logger)
+ handle._prefetcher = pf
+ handle.slots_mib = planned if getattr(pf, "slot_streamed", 1) else 0
+ except Exception as exc: # noqa: BLE001 - streamed blocks then simply churn and run their compute
+ if logger is not None:
+ logger.warning("diffusion.block_graph: slot ring unavailable (%s)", exc)
+ if logger is not None:
+ logger.info(
+ "diffusion.block_graph: armed %d of %d %s block(s)%s%s",
+ len(handle.graphs),
+ len(blocks),
+ type(transformer).__name__,
+ f"; streamed blocks read a {handle.slots_mib} MiB slot ring"
+ if handle.slots_mib
+ else "",
+ ("; refused " + ", ".join(f"{n}: {w}" for w, n in refused.items())) if refused else "",
+ )
+ return handle, "armed"
+
+
+COMPILE_BELOW_HOOKS_ENV = "UNSLOTH_DIFFUSION_COMPILE_BELOW_HOOKS"
+
+
+def compile_below_hooks_enabled() -> bool:
+ return (os.environ.get(COMPILE_BELOW_HOOKS_ENV) or "").strip().lower() not in _OFF
+
+
+def compile_below_offload_hooks(transformer: Any, logger: Any = None) -> int:
+ """Compile each offload-hooked block's own ``forward`` so the hooks stay eager outside the compiled region.
+
+ Traced through, the hooks graph-break the block and put residency state into the guards, so every release /
+ re-pin recompiles. Idempotent; returns the blocks moved."""
+ if not compile_below_hooks_enabled():
+ return 0
+ kwargs = getattr(transformer, "_unsloth_regional_compile_kwargs", None)
+ if not isinstance(kwargs, dict):
+ return 0
+ torch = _torch()
+ guard = getattr(transformer, "_unsloth_compile_guard", None)
+ moved = 0
+ for block in repeated_blocks(transformer):
+ compiled = getattr(block, "_compiled_call_impl", None)
+ if compiled is None or _group_offload_hook(block) is None:
+ continue
+ registry = getattr(block, "_diffusers_hook", None)
+ target = next(
+ (
+ r
+ for r in list(getattr(registry, "_fn_refs", None) or ())
+ if _is_original_forward(getattr(r, "forward", None), block)
+ ),
+ None,
+ )
+ if target is None:
+ continue
+ original = target.forward
+ fn = torch.compile(original, **dict(kwargs))
+ if guard is not None and callable(getattr(guard, "wrap", None)):
+ fn = guard.wrap(fn, original, transformer)
+ guard.restores.append(lambda ref = target, f = original: setattr(ref, "forward", f))
+ from . import diffusion_block_restride
+
+ if diffusion_block_restride.is_wrapped(compiled):
+ # FLUX.1's block 0 keeps the slice layout of the others, so all of them share one compiled graph.
+ fn = diffusion_block_restride.wrap(fn)
+ target.forward = fn
+ block._compiled_call_impl = None
+ block._unsloth_below_hook_ref = target
+ moved += 1
+ if moved and logger is not None:
+ logger.info(
+ "diffusion.speed: %d offloaded %s blocks compile below their offload hooks",
+ moved,
+ type(transformer).__name__,
+ )
+ return moved
+
+
+def compile_pipe_below_offload_hooks(pipe: Any, logger: Any = None) -> int:
+ try:
+ from .diffusion_speed import _denoiser_dits
+ except Exception: # noqa: BLE001
+ return 0
+ moved = 0
+ for transformer in _denoiser_dits(pipe):
+ try:
+ moved += compile_below_offload_hooks(transformer, logger)
+ except Exception as exc: # noqa: BLE001
+ if logger is not None:
+ logger.warning("diffusion.speed: compile below offload hooks failed (%s)", exc)
+ return moved
diff --git a/studio/backend/core/inference/diffusion_block_restride.py b/studio/backend/core/inference/diffusion_block_restride.py
index 556e40886ec..2a309bf6885 100644
--- a/studio/backend/core/inference/diffusion_block_restride.py
+++ b/studio/backend/core/inference/diffusion_block_restride.py
@@ -58,6 +58,25 @@ def _restrided(hidden: Any, encoder: Any) -> Any:
return buf[:, text:], buf[:, :text]
+def wrap(compiled: Any) -> Any:
+ """``compiled`` behind the restride: its block-0 inputs arrive as slices of one buffer."""
+
+ def restride(*args: Any, **kwargs: Any) -> Any:
+ if not args and "hidden_states" in kwargs and "encoder_hidden_states" in kwargs:
+ pair = _restrided(kwargs["hidden_states"], kwargs["encoder_hidden_states"])
+ if pair is not None:
+ kwargs = dict(kwargs)
+ kwargs["hidden_states"], kwargs["encoder_hidden_states"] = pair
+ return compiled(*args, **kwargs)
+
+ setattr(restride, _MARK, True)
+ return restride
+
+
+def is_wrapped(fn: Any) -> bool:
+ return bool(getattr(fn, _MARK, False))
+
+
def install(transformer: Any, logger: Any = None) -> bool:
"""Wrap the first single block's compiled call. Idempotent; True when installed. Never raises."""
if not enabled():
@@ -78,16 +97,7 @@ def install(transformer: Any, logger: Any = None) -> bool:
return False
if getattr(compiled, _MARK, False):
return True
-
- def restride(*args: Any, **kwargs: Any) -> Any:
- if not args and "hidden_states" in kwargs and "encoder_hidden_states" in kwargs:
- pair = _restrided(kwargs["hidden_states"], kwargs["encoder_hidden_states"])
- if pair is not None:
- kwargs = dict(kwargs)
- kwargs["hidden_states"], kwargs["encoder_hidden_states"] = pair
- return compiled(*args, **kwargs)
-
- setattr(restride, _MARK, True)
+ restride = wrap(compiled)
# Keep the guard's identity visible: guard_compiled_blocks skips modules already wrapped.
guard = getattr(compiled, "_unsloth_compile_guard", None)
if guard is not None:
diff --git a/studio/backend/core/inference/diffusion_cuda_graph.py b/studio/backend/core/inference/diffusion_cuda_graph.py
index dd45ad299a5..71152e0471e 100644
--- a/studio/backend/core/inference/diffusion_cuda_graph.py
+++ b/studio/backend/core/inference/diffusion_cuda_graph.py
@@ -24,6 +24,8 @@ from .diffusion_bg_compile import capture_suppressed as _bg_capture_suppressed
from .diffusion_bg_compile import eager_forced as _bg_eager_forced
CUDA_GRAPH_DISABLE_ENV = "UNSLOTH_DISABLE_CUDA_GRAPH"
+# Master switch for every diffusion CUDA graph (whole-forward and per-block): "0" turns them all off.
+CUDA_GRAPHS_ENV = "UNSLOTH_DIFFUSION_CUDA_GRAPHS"
# Per module. Legitimate second keys exist, but each costs a pool-sized slice of VRAM.
MAX_GRAPHS_PER_MODULE = 4
@@ -41,10 +43,18 @@ def _torch():
def cuda_graph_disabled() -> bool:
- """Whether the env kill switch is set. Read before any torch or pipe inspection."""
+ """Whether an env kill switch is set. Read before any torch or pipe inspection."""
+ if os.environ.get(CUDA_GRAPHS_ENV, "").strip().lower() in ("0", "off", "false", "no"):
+ return True
return os.environ.get(CUDA_GRAPH_DISABLE_ENV, "").strip().lower() in _TRUE_TOKENS
+def _disabled_reason() -> str:
+ if os.environ.get(CUDA_GRAPHS_ENV, "").strip().lower() in ("0", "off", "false", "no"):
+ return f"disabled by {CUDA_GRAPHS_ENV}=0"
+ return f"disabled by {CUDA_GRAPH_DISABLE_ENV}"
+
+
# ``torch.cuda.graph`` begins its capture in CUDA's default global mode, which prohibits the
# "potentially unsafe" calls -- cudaEventQuery among them -- from EVERY thread for as long as it
# records. The denoise progress poller queries a CUDA event ten times a second and the denoiser
@@ -199,6 +209,112 @@ def _drop_pool_if_unused() -> None:
pass
+# A failed capture leaves the pinned host allocator (torch >= 2.11) recording to its pool for good, with a filter
+# holding a raw pointer to the failed CUDAGraph: so that graph is never freed and its pool never recorded into again.
+MAX_FAILED_CAPTURES = 16
+_FAILED_GRAPHS: list = []
+_COLLIDED_GRAPHS: list = []
+_FAILED_LOCK = threading.Lock()
+
+
+def captures_exhausted() -> bool:
+ """True once MAX_FAILED_CAPTURES recordings failed in this process; every later capture then runs eager."""
+ return len(_FAILED_GRAPHS) >= MAX_FAILED_CAPTURES
+
+
+def refuse_if_exhausted(logger: Any = None) -> None:
+ """Raise (the caller's failed-capture path then runs eager) once the failure budget is spent; log that once."""
+ global _EXHAUSTED_LOGGED
+ if not captures_exhausted():
+ return
+ with _FAILED_LOCK:
+ first = not _EXHAUSTED_LOGGED
+ _EXHAUSTED_LOGGED = True
+ if first and logger is not None:
+ logger.warning(
+ "diffusion.cuda_graph: %d graph captures failed in this process; no further captures are attempted",
+ len(_FAILED_GRAPHS),
+ )
+ raise RuntimeError(
+ f"{len(_FAILED_GRAPHS)} graph captures failed in this process; capture is off"
+ )
+
+
+_EXHAUSTED_LOGGED = False
+
+
+def _abandon_capture_pool(pool: Any) -> bool:
+ """After a capture that raised: take the device allocator off the capture's pool if ``capture_end`` never did.
+
+ ``CUDAGraph::capture_end`` checks ``cudaStreamEndCapture`` before ``endAllocateToPool``, so an invalidated capture
+ leaves the pool in the allocator's ``captures_underway``: on torch 2.6 every later ``empty_cache`` then trips
+ ``INTERNAL ASSERT captures_underway.empty()``; later torch skips the global release instead, so ``empty_cache``
+ frees nothing. That failed graph never releases the reference its ``capture_begin`` took (its reset releases only
+ once ``capture_end`` got past the pool), so it is released here, and ONLY when this call ended the recording: had
+ ``capture_end`` got that far the graph owns the reference and releases it itself. True when this call ended it."""
+ torch = _torch()
+ end = getattr(torch._C, "_cuda_endAllocateToPool", None) or getattr(
+ torch._C, "_cuda_endAllocateCurrentStreamToPool", None
+ )
+ if end is None or pool is None:
+ return False
+ try:
+ device = torch.cuda.current_device()
+ end(device, pool)
+ except Exception: # noqa: BLE001 - capture_end already took it off, or capture_begin never put it on
+ return False
+ try:
+ torch._C._cuda_releasePool(device, pool)
+ except Exception: # noqa: BLE001
+ pass
+ return True
+
+
+def _heal_generators() -> None:
+ """Take every CUDA default generator out of graph-capture mode after a FAILED capture.
+
+ ``CUDAGraph.capture_end`` ends the generators' capture only after ``cudaStreamEndCapture`` succeeds. When the
+ capture was invalidated (a host sync inside it, a kernel that may not be recorded) it raises first, and every later
+ eager draw from the generator (``torch.randn(device = "cuda")``, a pipeline's noise) fails with "Offset increment
+ outside graph capture encountered unexpectedly" for the rest of the process. A clone of the state keeps the seed
+ and the eager offset, so the eager sequence continues as if the capture had never run."""
+ try:
+ torch = _torch()
+ for gen in getattr(torch.cuda, "default_generators", ()) or ():
+ clone = getattr(gen, "clone_state", None)
+ restore = getattr(gen, "graphsafe_set_state", None)
+ if callable(clone) and callable(restore):
+ restore(clone())
+ except Exception: # noqa: BLE001
+ pass
+
+
+def retire_failed_capture(
+ graph: Any,
+ pool: Any,
+ exc: Optional[BaseException] = None,
+) -> None:
+ """Clean up after a capture into ``pool`` that raised. The caller must stop handing ``pool`` to captures.
+
+ "already recording" comes from ``capture_begin`` finding the pool in another capture: that recording is not ours
+ to end. A graph whose recording did end (the forward raised, instantiate failed) is reset, which releases its pool
+ reference and graph, and kept as an empty husk like the rest."""
+ begun_elsewhere = exc is not None and "already recording" in str(exc)
+ ended_here = False if begun_elsewhere else _abandon_capture_pool(pool)
+ if not begun_elsewhere: # the generators then belong to the other thread's live capture
+ _heal_generators()
+ if not ended_here and not begun_elsewhere:
+ try:
+ graph.reset()
+ except Exception: # noqa: BLE001
+ pass
+ with _FAILED_LOCK:
+ # A collision with another recording left nothing behind: kept alive, but not a failure the budget counts.
+ (_COLLIDED_GRAPHS if begun_elsewhere else _FAILED_GRAPHS).append(graph)
+ if pool is not None and _POOL_BOX[0] == pool:
+ _POOL_BOX[0] = None
+
+
def _nvfp4_flashinfer_linears(module: Any) -> list:
try:
from .diffusion_nvfp4_linear import is_nvfp4_flashinfer_linear
@@ -580,10 +696,18 @@ class GraphedForward:
torch.cuda.current_stream().wait_stream(side)
torch.cuda.synchronize()
+ refuse_if_exhausted(self.logger)
graph = torch.cuda.CUDAGraph()
- # ``pool = None`` is identical to omitting the argument, so both captures take one path.
- with _capturing(), torch.cuda.graph(graph, pool = _POOL_BOX[0]):
- out = self.orig(*static_args, **static_kwargs)
+ # An explicit pool id, never None: a capture that fails must hand its pool back (retire_failed_capture).
+ pool = _POOL_BOX[0]
+ if pool is None and callable(getattr(torch.cuda, "graph_pool_handle", None)):
+ pool = torch.cuda.graph_pool_handle()
+ try:
+ with _capturing(), torch.cuda.graph(graph, pool = pool):
+ out = self.orig(*static_args, **static_kwargs)
+ except BaseException as exc:
+ retire_failed_capture(graph, pool, exc)
+ raise
if _POOL_BOX[0] is None:
try:
_POOL_BOX[0] = graph.pool()
@@ -643,7 +767,7 @@ def graph_eligible(
) -> 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}"
+ return False, _disabled_reason()
device = getattr(target, "device", None)
if device != "cuda":
@@ -813,6 +937,9 @@ def never_engaged(handles: Any) -> Optional[str]:
"""Why the armed graphs never replayed a step; None before the first call or once any engaged."""
if not handles:
return None
+ reasons = [h.why_off() for h in handles if callable(getattr(h, "why_off", None))]
+ if reasons and len(reasons) == len(handles):
+ return None if any(r is None for r in reasons) else "; ".join(reasons)
s = stats(handles)
if all(getattr(h, "poisoned", False) for h in handles):
error = s["capture_error"] or {}
@@ -846,3 +973,172 @@ def live_status(resolved: Any, speed_optims: Any, handles: Any) -> tuple:
"cuda_graph": {**resolved["cuda_graph"], "value": "off", "reason": why},
}
return resolved, optims
+
+
+# Per-block graphs (diffusion_block_graph) for the loads the whole-forward recording cannot hold.
+
+WHOLE_REASON = "denoiser step captured per input shape, replayed bit-identically"
+
+
+def _block_basics(
+ target: Any, family: Any, cache_engaged: bool, speed_mode: str, family_default: bool
+) -> Optional[str]:
+ """The whole-forward checks that also bind per-block recording (everything except offload and capture-safety)."""
+ if cuda_graph_disabled():
+ return _disabled_reason()
+ if getattr(target, "device", None) != "cuda":
+ return f"device is {getattr(target, 'device', None) or 'unknown'}"
+ backend = getattr(target, "backend", "cuda")
+ if backend != "cuda":
+ return f"backend is {backend}"
+ if cache_engaged:
+ return "step cache active"
+ mode = str(speed_mode or "").strip().lower()
+ if mode not in ("default", "max"):
+ return f"speed tier {mode or 'off'}"
+ if not bool(getattr(family, "supports_cuda_graph", family_default)):
+ return "family opts out"
+ try:
+ torch = _torch()
+ if not torch.cuda.is_available() or not hasattr(torch.cuda, "graph_pool_handle"):
+ return "torch.cuda unavailable"
+ except Exception: # noqa: BLE001
+ return "torch.cuda unavailable"
+ return None
+
+
+def arm_block_graphs(
+ pipe: Any,
+ applied: dict,
+ *,
+ target: Any,
+ family: Any,
+ hooked: bool,
+ pinned: bool = False,
+ cache_engaged: bool = False,
+ speed_mode: str = "default",
+ family_default: bool = True,
+ logger: Any = None,
+) -> tuple:
+ """After placement: keep a whole-forward recording where it holds, else record per block.
+
+ Per-block recording is the default only where every block stays on the device (``not hooked``, or ``pinned``
+ resident under its hooks); streamed and model-offloaded denoisers need ``UNSLOTH_DIFFUSION_BLOCK_GRAPHS=1``.
+
+ A whole forward cannot be recorded once an offload hook moves the denoiser (``hooked``) or when the forward is
+ not capture-safe (Qwen-Image-2.1's prefix K/V object); its repeated blocks still can, keyed by where their weights
+ sit. Updates ``applied["cuda_graph"]`` and the pipe's reason / handles; returns the handles now armed."""
+ handles = tuple(getattr(pipe, "_unsloth_cuda_graphs", ()) or ())
+ whole = [h for h in handles if isinstance(h, GraphedForward)]
+ prior = str(getattr(pipe, "_unsloth_cuda_graph_reason", None) or "")
+ if not hooked and (whole or "not capture-safe" not in prior):
+ # Nothing moves the denoiser: the speed layer's decision stands, except a forward that is not capture-safe,
+ # whose blocks still record.
+ return handles
+ why = _block_basics(target, family, cache_engaged, speed_mode, family_default)
+ if whole:
+ uninstall_all(whole, logger = logger)
+ pipe._unsloth_cuda_graph_mode = None
+ if why is not None:
+ _set_reason(pipe, why)
+ applied["cuda_graph"] = False
+ pipe._unsloth_cuda_graphs = ()
+ return ()
+ try:
+ from .diffusion_block_graph import (
+ MODEL_OFFLOAD_REASON,
+ OPT_IN_REASON,
+ block_graphs_disabled,
+ block_graphs_requested,
+ install_block_graphs,
+ )
+ from .diffusion_speed import _denoiser_dits
+ except Exception as exc: # noqa: BLE001
+ _warn(logger, "block graph import", exc)
+ applied["cuda_graph"] = False
+ pipe._unsloth_cuda_graphs = ()
+ _set_reason(pipe, "offload active" if hooked else prior or "block graphs unavailable")
+ return ()
+ if any(
+ getattr(t, "_unsloth_attention_backend", None) in ("sage", "sage_hub")
+ for t in _denoiser_dits(pipe)
+ ):
+ applied["cuda_graph"] = False
+ pipe._unsloth_cuda_graphs = ()
+ _set_reason(pipe, "SageAttention is not CUDA-graph safe")
+ return ()
+ model_offload = any(getattr(t, "_hf_hook", None) is not None for t in _denoiser_dits(pipe))
+ stays = (not hooked or bool(pinned)) and not model_offload
+ if block_graphs_disabled() or not (stays or block_graphs_requested()):
+ applied["cuda_graph"] = False
+ pipe._unsloth_cuda_graphs = ()
+ if block_graphs_disabled():
+ _set_reason(pipe, "disabled by UNSLOTH_DIFFUSION_BLOCK_GRAPHS=0")
+ else:
+ _set_reason(pipe, MODEL_OFFLOAD_REASON if model_offload else OPT_IN_REASON)
+ return ()
+ armed: list = []
+ reasons: list = []
+ for transformer in _denoiser_dits(pipe):
+ try:
+ handle, reason = install_block_graphs(
+ transformer, device = getattr(target, "torch_device", None), logger = logger
+ )
+ except Exception as exc: # noqa: BLE001
+ _warn(logger, "block graph install", exc)
+ handle, reason = None, f"install failed ({type(exc).__name__})"
+ if handle is not None:
+ armed.append(handle)
+ else:
+ reasons.append(reason)
+ pipe._unsloth_cuda_graphs = tuple(armed)
+ applied["cuda_graph"] = bool(armed)
+ if armed:
+ where = (
+ "pinned denoiser"
+ if hooked and pinned
+ else "offloaded denoiser"
+ if hooked
+ else "denoiser"
+ )
+ slots = sum(int(getattr(h, "slots_mib", 0) or 0) for h in armed)
+ _set_reason(
+ pipe,
+ f"{where} recorded per block, keyed by input shape and weight placement"
+ + (f"; streamed blocks read a {slots} MiB slot ring" if slots else ""),
+ )
+ pipe._unsloth_cuda_graph_mode = "blocks"
+ else:
+ _set_reason(
+ pipe, "; ".join(r for r in reasons if r) or "no denoiser block could be recorded"
+ )
+ return tuple(armed)
+
+
+def _set_reason(pipe: Any, reason: str) -> None:
+ try:
+ pipe._unsloth_cuda_graph_reason = reason
+ except Exception: # noqa: BLE001
+ pass
+
+
+def status_reason(pipe: Any, on: bool) -> str:
+ """The cuda_graph badge text: the block layer's own sentence when it armed, else why graphs are off."""
+ if on:
+ if getattr(pipe, "_unsloth_cuda_graph_mode", None) == "blocks":
+ return str(getattr(pipe, "_unsloth_cuda_graph_reason", None) or WHOLE_REASON)
+ return WHOLE_REASON
+ return str(getattr(pipe, "_unsloth_cuda_graph_reason", None) or "speed tier does not capture")
+
+
+def held_bytes(handles: Any) -> int:
+ """Device bytes the armed graphs hold outside the caching allocator's reach (pools, static buffers, slot ring)."""
+ total = 0
+ for handle in handles or ():
+ fn = getattr(handle, "held_bytes", None)
+ if callable(fn):
+ try:
+ total += int(fn())
+ except Exception: # noqa: BLE001
+ pass
+ return total
diff --git a/studio/backend/core/inference/diffusion_memory.py b/studio/backend/core/inference/diffusion_memory.py
index a21ddc32331..5c5543fde4c 100644
--- a/studio/backend/core/inference/diffusion_memory.py
+++ b/studio/backend/core/inference/diffusion_memory.py
@@ -693,6 +693,16 @@ def reclaimable_snapshot_device_memory(target: Any) -> DeviceMemory:
reclaimable = int(torch.cuda.memory_reserved()) - int(torch.cuda.memory_allocated())
except Exception: # noqa: BLE001 -- no allocator reading: the plain snapshot still stands
return snapshot
+ try:
+ # Per-block graph pools are reserved, mostly unallocated between replays, and never reusable by anything else.
+ from .diffusion_block_graph import pool_bytes as _block_graph_pool_bytes
+ try:
+ device = torch.cuda.current_device()
+ except Exception: # noqa: BLE001 - no current CUDA device: count every pool
+ device = None
+ reclaimable -= _block_graph_pool_bytes(device)
+ except Exception: # noqa: BLE001
+ pass
if reclaimable <= 0:
return snapshot
free = int(snapshot.free_mib) + reclaimable // (1024 * 1024)
diff --git a/studio/backend/core/inference/diffusion_offload_prefetch.py b/studio/backend/core/inference/diffusion_offload_prefetch.py
index 7091650952e..a71189accf2 100644
--- a/studio/backend/core/inference/diffusion_offload_prefetch.py
+++ b/studio/backend/core/inference/diffusion_offload_prefetch.py
@@ -146,6 +146,132 @@ def _to_device(src: Any, device: Any) -> Any:
return src.to(device, non_blocking = True)
+def _inner(t: Any) -> list:
+ try:
+ from torch.utils._python_dispatch import is_traceable_wrapper_subclass
+ if is_traceable_wrapper_subclass(t):
+ names, _ = t.__tensor_flatten__()
+ return [(n, getattr(t, n)) for n in names]
+ except Exception: # noqa: BLE001
+ pass
+ return []
+
+
+_SLOT_ALIGN = 512
+
+
+def _plain_leaves(t: Any) -> list:
+ """The plain tensors holding ``t``'s data, depth first (a wrapper subclass's inner tensors)."""
+ inner = _inner(t)
+ if not inner:
+ return [t]
+ out: list = []
+ for _, x in inner:
+ out.extend(_plain_leaves(x))
+ return out
+
+
+def _packed_bytes(sources: list) -> Optional[int]:
+ """Bytes a group's tensors take packed into one slot (each leaf aligned); None if a leaf cannot be viewed in."""
+ total = 0
+ for src in sources:
+ for leaf in _plain_leaves(src):
+ if not leaf.is_contiguous():
+ return None
+ total = (total + _SLOT_ALIGN - 1) // _SLOT_ALIGN * _SLOT_ALIGN
+ total += leaf.numel() * leaf.element_size()
+ return total
+
+
+def _carve(raw: Any, offset: int, like: Any) -> tuple:
+ """A view of ``raw`` (uint8) shaped like ``like`` at the next aligned offset; returns (view, end offset)."""
+ offset = (offset + _SLOT_ALIGN - 1) // _SLOT_ALIGN * _SLOT_ALIGN
+ n = like.numel() * like.element_size()
+ view = raw[offset : offset + n].view(like.dtype).view(like.shape)
+ return view, offset + n
+
+
+def _slot_views(raw: Any, sources: list, device: Any) -> list:
+ """Device tensors laid out in ``raw`` mirroring ``sources`` (plain views, or wrapper subclasses whose inner
+ tensors are views), so a fill is an in-place copy and every fill of this group lands at the same addresses."""
+ offset = 0
+ views: list = []
+
+ def build(src: Any) -> Any:
+ nonlocal offset
+ inner = _inner(src)
+ if not inner:
+ view, offset = _carve(raw, offset, src)
+ return view
+ wrapper = _to_device(src, device)
+ for name, x in inner:
+ setattr(wrapper, name, build(x))
+ return wrapper
+
+ for src in sources:
+ views.append(build(src))
+ return views
+
+
+def _copy_into(dst: Any, src: Any) -> None:
+ inner = _inner(dst)
+ if inner:
+ for name, d in inner:
+ _copy_into(d, getattr(src, name))
+ return
+ dst.copy_(src, non_blocking = True)
+
+
+def _rewrap(buf: Any) -> Any:
+ """A new wrapper around ``buf``'s inner tensors (no copy), for ``swap_tensors`` to consume."""
+ names, ctx = buf.__tensor_flatten__()
+ return type(buf).__tensor_unflatten__(
+ {n: getattr(buf, n) for n in names}, ctx, buf.size(), buf.stride()
+ )
+
+
+def _point_at(t: Any, buf: Any, torchao: bool, swap: Any) -> None:
+ """Make parameter / buffer ``t`` read ``buf``'s storage, leaving ``buf`` itself untouched."""
+ if not torchao:
+ t.data = buf
+ return
+ inner = _inner(t)
+ if (
+ inner
+ and all(x.device.type == buf.device.type for _, x in _inner(buf))
+ and t.device == buf.device
+ ):
+ for name, _ in _inner(buf):
+ setattr(t, name, getattr(buf, name))
+ return
+ # First time on the device: the wrapper itself must report it, so swap in a fresh wrapper over the slot.
+ if swap is not None:
+ swap(t, _rewrap(buf))
+ else:
+ for name, _ in _inner(buf):
+ setattr(t, name, getattr(buf, name))
+
+
+def _detach_from_slot(group: Any, buffers: list) -> None:
+ ptrs = set()
+ for b in buffers:
+ for x in _plain_leaves(b):
+ ptrs.add(x.data_ptr())
+
+ def detach(obj: Any) -> None:
+ for name, x in _inner(obj):
+ if _inner(x):
+ detach(x)
+ elif x.data_ptr() in ptrs:
+ setattr(obj, name, x.clone())
+
+ for t in _group_tensors(group):
+ if _inner(t):
+ detach(t)
+ elif t.data_ptr() in ptrs:
+ t.data = t.data.clone()
+
+
def _group_nbytes(group: Any) -> int:
from .diffusion_memory import _storage_nbytes
@@ -191,6 +317,16 @@ class GroupPrefetcher:
self.stream = streams[0] if streams else None
self.fence_first = False
self.stats = {"forwards": 0, "copies": 0, "prefetched": 0, "missed": 0, "dropped": 0}
+ # Slot ring (``enable_slots``): group id -> slot index; a streamed group's copy lands in place in that slot,
+ # always at the same offsets, so the blocks a CUDA graph recorded read the same addresses every step.
+ self.slot_of: dict = {}
+ self.slot_buffers: dict = {} # group id -> its views into its slot
+ self.slot_raw: dict = {} # slot index -> uint8 device buffer
+ self.slot_owner: dict = {}
+ self.slot_size = 0
+ self.slot_bytes = 0
+ self.slot_bytes_planned = 0
+ self.slot_streamed = 0
def owns(self, group: Any) -> bool:
return getattr(group, "__dict__", {}).get("onload_") is getattr(
@@ -201,10 +337,37 @@ class GroupPrefetcher:
import torch
return torch.cuda.current_stream(self.device)
- def _issue(self, group: Any) -> None:
- """Queue ``group``'s host-to-device copy on its copy stream and point its tensors at the destinations."""
+ def _slot_free(self, group: Any, must: bool) -> Optional[bool]:
+ """Whether ``group``'s slot can take its copy now: True, False (wait: the occupant is on the device), or None
+ (no slot / a forced onload whose slot is busy: copy to fresh memory instead)."""
+ where = self.slot_of.get(id(group))
+ if where is None:
+ return None
+ owner = self.slot_owner.get(where)
+ if owner is None or owner == id(group) or owner not in self.ready:
+ return True
+ if not must:
+ return False
+ occupant = self.by_id.get(owner)
+ if occupant is not None and self.ready.get(owner) is not None:
+ # copied ahead but not yet run (the order changed): drop it, it is copied again when reached
+ self._release(occupant, self.ready.pop(owner))
+ return True
+ self.stats["slot_fallbacks"] = self.stats.get("slot_fallbacks", 0) + 1
+ return None
+
+ def _issue(
+ self,
+ group: Any,
+ must: bool = True,
+ ) -> bool:
+ """Queue ``group``'s host-to-device copy on its copy stream and point its tensors at the destinations.
+ False (nothing queued) only when ``must`` is False and the group's slot is still occupied."""
import torch
+ slot = self._slot_free(group, must) if getattr(self, "slot_of", None) else None
+ if slot is False:
+ return False
pinner = getattr(group, _BG_PIN_ATTR, None)
if pinner is not None:
pinner.wait(group)
@@ -213,18 +376,29 @@ class GroupPrefetcher:
swap = getattr(go, "_swap_torchao_tensor", None)
cpu = group.cpu_param_dict
stream = group.stream
+ where = self.slot_of.get(id(group)) if slot else None
with torch.cuda.stream(stream):
- for t in _group_tensors(group):
+ # made on the copy stream: a block the compute stream freed but has not finished reading is never handed
+ # to these copies (the allocator orders reuse per stream)
+ buffers = self._views_for(group, where) if where is not None else None
+ for i, t in enumerate(_group_tensors(group)):
src = cpu[t]
if not src.is_pinned():
src = (
src.pin_memory()
) # diffusers' low_cpu_mem_usage path: the host allocator fences reuse
+ if buffers is not None:
+ _copy_into(buffers[i], src)
+ _point_at(t, buffers[i], is_torchao(t), swap)
+ continue
moved = _to_device(src, self.device)
if is_torchao(t) and swap is not None:
swap(t, moved)
else:
t.data = moved
+ if buffers is not None:
+ self.slot_owner[where] = id(group)
+ self.stats["slot_fills"] = self.stats.get("slot_fills", 0) + 1
ready = torch.cuda.Event()
ready.record(stream)
gid = id(group)
@@ -232,6 +406,7 @@ class GroupPrefetcher:
self.inflight_bytes += self.nbytes.get(gid, 0)
self.peak_inflight_bytes = max(self.peak_inflight_bytes, self.inflight_bytes)
self.stats["copies"] += 1
+ return True
def onload(self, group: Any) -> None:
gid = id(group)
@@ -288,6 +463,8 @@ class GroupPrefetcher:
def _forget_disowned(self) -> None:
"""Groups made resident while on the device (their onload_ replaced) leave the window without a release."""
+ import torch
+
compute = None
for gid in list(self.ready):
group = self.by_id.get(gid)
@@ -298,6 +475,16 @@ class GroupPrefetcher:
compute = compute or self._compute()
compute.wait_event(event)
self.inflight_bytes -= self.nbytes.get(gid, 0)
+ if group is not None and getattr(self, "slot_of", None) and self._holds_slot(group):
+ # made resident while it sat in a slot: give it its own copy before the slot is refilled
+ compute = compute or self._compute()
+ with torch.cuda.stream(compute):
+ _detach_from_slot(group, self.slot_buffers[gid])
+ # the slot is refilled only after the compute that read it, and this clone, are done
+ done = torch.cuda.Event()
+ done.record(compute)
+ group.stream.wait_event(done)
+ self.slot_owner.pop(self.slot_of[gid], None)
def _fill(self) -> None:
if not (self.active and self.on_order):
@@ -314,9 +501,91 @@ class GroupPrefetcher:
continue
if self.inflight_bytes + self.nbytes.get(gid, 0) > self.window and self.ready:
break
- self._issue(group)
+ if getattr(self, "slot_of", None):
+ if not self._issue(group, must = False):
+ break # its slot still holds a group the compute has not finished with
+ else:
+ self._issue(group)
ahead += 1
+ def _holds_slot(self, group: Any) -> bool:
+ where = self.slot_of.get(id(group))
+ return where is not None and self.slot_owner.get(where) == id(group)
+
+ def enable_slots(self, logger: Any = None) -> int:
+ """Give every streamed block group one of ``depth + 1`` byte slots, round-robin in block order (the prefetch
+ never holds more groups than that), each slot as large as the largest packed group: the ring is the prefetch
+ window. A group's copies always land at the same offsets of its slot. Returns the ring's MiB (allocated on
+ first use). The top-level group keeps fresh copies: no graph reads it."""
+ if self.slot_of:
+ return self.slot_bytes_planned >> 20
+ members: list = []
+ size = 0
+ for group in self.groups:
+ if getattr(group, "offload_leader", None) is self.module:
+ continue
+ cpu = getattr(group, "cpu_param_dict", None) or {}
+ try:
+ need = _packed_bytes([cpu.get(t, t) for t in _group_tensors(group)])
+ except Exception: # noqa: BLE001
+ need = None
+ if need is None:
+ continue
+ members.append(group)
+ size = max(size, need)
+ if not members:
+ return 0
+ count = min(self.depth + 1, len(members))
+ # pinned groups never fill their slot unless a release streams them again; the ring is allocated on first use
+ self.slot_streamed = sum(1 for g in members if not getattr(g, "_unsloth_resident", False))
+ for i, group in enumerate(members):
+ self.slot_of[id(group)] = i % count
+ self.slot_size = size
+ self.slot_bytes_planned = count * size
+ if logger is not None:
+ logger.info(
+ "diffusion.memory: %s streams %d block groups through %d slots of %d MiB (the prefetch window)",
+ type(self.module).__name__,
+ len(members),
+ count,
+ size >> 20,
+ )
+ return self.slot_bytes_planned >> 20
+
+ def _views_for(self, group: Any, where: int) -> list:
+ gid = id(group)
+ views = self.slot_buffers.get(gid)
+ if views is not None:
+ return views
+ import torch
+
+ raw = self.slot_raw.get(where)
+ if raw is None:
+ raw = torch.empty(self.slot_size, dtype = torch.uint8, device = self.device)
+ self.slot_raw[where] = raw
+ self.slot_bytes += self.slot_size
+ cpu = group.cpu_param_dict
+ views = _slot_views(raw, [cpu[t] for t in _group_tensors(group)], self.device)
+ self.slot_buffers[gid] = views
+ return views
+
+ def disable_slots(self) -> None:
+ """Drop the ring. Only between forwards: every streamed group is back on the host by then."""
+ import torch
+
+ if self.active:
+ return
+ if self.slot_raw:
+ torch.cuda.synchronize(self.device)
+ self.slot_of = {}
+ self.slot_buffers = {}
+ self.slot_raw = {}
+ self.slot_owner = {}
+ self.slot_size = 0
+ self.slot_bytes = 0
+ self.slot_bytes_planned = 0
+ self.slot_streamed = 0
+
def begin(self) -> None:
self.stats["forwards"] += 1
self._forget_disowned()
diff --git a/studio/backend/tests/test_diffusion_block_graph.py b/studio/backend/tests/test_diffusion_block_graph.py
new file mode 100644
index 00000000000..fbc06dbe937
--- /dev/null
+++ b/studio/backend/tests/test_diffusion_block_graph.py
@@ -0,0 +1,878 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Per-block CUDA graphs for offloaded denoisers (``diffusion_block_graph.py``) and the prefetcher's slot ring.
+
+CPU cases cover the call-tree / key / refusal logic, the weight-placement read-back, installation below the
+offload hooks, the arming decision per placement and the slot assignment. CUDA cases record real blocks under
+Studio's ``_apply_group_offload`` (streamed through the event-fenced prefetcher, partially resident, released and
+restored) and check every replay against the ungraphed forward bit for bit.
+"""
+
+from __future__ import annotations
+
+import copy
+import types
+import warnings
+
+import pytest
+import torch
+
+import core.inference.diffusion_block_graph as bg
+import core.inference.diffusion_cuda_graph as cg
+import core.inference.diffusion_memory as dm
+import core.inference.diffusion_offload_prefetch as op
+
+
[email protected](autouse = True)
+def _clean_env(monkeypatch):
+ for name in (
+ bg.BLOCK_GRAPHS_ENV,
+ cg.CUDA_GRAPHS_ENV,
+ cg.CUDA_GRAPH_DISABLE_ENV,
+ op.ASYNC_PREFETCH_ENV,
+ op.PREFETCH_DEPTH_ENV,
+ "UNSLOTH_DIFFUSION_PARTIAL_RESIDENT",
+ "UNSLOTH_DIFFUSION_GROUP_OFFLOAD_PIN",
+ "UNSLOTH_DIFFUSION_PIN_TOP_GROUP",
+ ):
+ monkeypatch.delenv(name, raising = False)
+
+
+class QwenImage21KVLayerCache: # the diffusers class's shape: k / v set by store(), read by get()
+ def __init__(self):
+ self.k = None
+ self.v = None
+
+ def store(self, k, v):
+ self.k, self.v = k, v
+
+ def get(self):
+ return self.k, self.v
+
+
+class Block(torch.nn.Module):
+ def __init__(self, width = 64):
+ super().__init__()
+ self.lin = torch.nn.Linear(width, width)
+
+ def forward(
+ self,
+ x,
+ temb = None,
+ layer_cache = None,
+ kv_cache_mode = None,
+ ):
+ y = torch.nn.functional.gelu(self.lin(x))
+ if temb is not None:
+ y = y + temb
+ if layer_cache is not None and kv_cache_mode == "cached":
+ k, v = layer_cache.get()
+ y = y + k.sum() * 0 + v.mean(dim = 0, keepdim = True)
+ return y
+
+
+class Net(torch.nn.Module):
+ _repeated_blocks = ["Block"]
+
+ def __init__(
+ self,
+ width = 64,
+ blocks = 6,
+ ):
+ super().__init__()
+ self.proj_in = torch.nn.Linear(16, width)
+ self.blocks = torch.nn.ModuleList(Block(width) for _ in range(blocks))
+ self.proj_out = torch.nn.Linear(width, 16)
+
+ def forward(
+ self,
+ x,
+ temb = None,
+ caches = None,
+ ):
+ x = self.proj_in(x)
+ for i, block in enumerate(self.blocks):
+ if caches is not None:
+ x = block(x, temb = temb, layer_cache = caches[i], kv_cache_mode = "cached")
+ else:
+ x = block(x, temb = temb)
+ return self.proj_out(x)
+
+
+# --- call trees and keys ---------------------------------------------------------------------------------------
+
+
+def test_kv_layer_cache_flattens_to_its_two_tensors_and_rebuilds_a_fresh_cache():
+ cache = QwenImage21KVLayerCache()
+ cache.store(torch.ones(2, 3), torch.zeros(2, 3))
+ live: list = []
+ key = bg._walk(((torch.ones(1),), {"layer_cache": cache, "kv_cache_mode": "cached"}), live)
+ assert [t.shape for t in live] == [torch.Size([1]), torch.Size([2, 3]), torch.Size([2, 3])]
+ hash(key)
+ statics = [torch.full_like(t, 7.0) for t in live]
+ args, kwargs = bg._unwalk(key, iter(statics))
+ assert kwargs["kv_cache_mode"] == "cached"
+ rebuilt = kwargs["layer_cache"]
+ assert type(rebuilt) is QwenImage21KVLayerCache and rebuilt is not cache
+ assert rebuilt.k is statics[1] and rebuilt.v is statics[2]
+ assert cache.k is not statics[1] # the caller's cache is never touched
+
+
+def test_kv_cache_is_recordable_only_on_a_cached_step():
+ cache = QwenImage21KVLayerCache()
+ cache.store(torch.ones(2, 3), torch.zeros(2, 3))
+ cached = {"layer_cache": cache, "kv_cache_mode": "cached"}
+ extract = {"layer_cache": cache, "kv_cache_mode": "extract"}
+ assert bg._refusal(bg.graph_key(((), cached)), cached) is None
+ assert bg._refusal(bg.graph_key(((), extract)), extract) == "kv_write"
+
+
+def test_key_separates_inference_mode_shape_and_scalars_and_refuses_floats_and_objects():
+ a = torch.zeros(2, 3)
+ with torch.inference_mode():
+ b = torch.zeros(2, 3)
+ assert bg.graph_key(a) != bg.graph_key(b)
+ assert bg.graph_key(a) != bg.graph_key(torch.zeros(3, 2))
+ assert bg._refusal(bg.graph_key(((a,), {"scale": 0.5})), {}) == "float"
+ assert bg._refusal(bg.graph_key(((a,), {"thing": object()})), {}) == "object"
+ assert bg._refusal(bg.graph_key(((a,), {"n": 3, "mode": "x", "none": None})), {}) is None
+
+
[email protected]("version", [None, 2])
+def test_placement_reads_every_level_of_torchao_weights(version):
+ torchao = pytest.importorskip("torchao")
+ from torchao.quantization import quantize_
+
+ try:
+ from torchao.quantization import Int8WeightOnlyConfig as Cfg
+ cfg = Cfg() if version is None else Cfg(version = version)
+ except (ImportError, TypeError):
+ pytest.skip(f"torchao {torchao.__version__}: no such int8 config")
+ block = Block().to(torch.bfloat16)
+ quantize_(block, cfg)
+ leaves = bg._leaves(block.lin.weight)
+ # torchao 0.17's default nests two wrappers whose own data_ptr is 0: the key must reach the plain payload
+ assert leaves and all(not bg._is_wrapper_subclass(x) for x in leaves)
+ assert all(x.data_ptr() != 0 for x in leaves)
+
+
+def test_a_host_tensor_input_is_never_recorded():
+ _cuda()
+ net = _net(blocks = 1).cuda()
+ handle, _ = bg.install_block_graphs(net, device = "cuda", slots = False)
+ graph = handle.graphs[0]
+ width = graph.block.lin.in_features
+ x = torch.randn(4, width, device = "cuda")
+ with torch.inference_mode():
+ for i in range(4):
+ temb = torch.tensor(float(i)) # a 0-dim host scalar a CUDA op reads at launch
+ assert torch.equal(graph(x, temb = temb), graph.compute(x, temb = temb))
+ assert graph.stats["refused_host_input"] == 4 and graph.stats["captures"] == 0
+ handle.free()
+
+
+def test_weight_placement_is_none_while_a_weight_is_on_the_host():
+ view = bg._WeightView(Block())
+ assert view.placement(None) is None
+
+
+def test_block_on_the_host_runs_its_compute_and_never_records():
+ block = Block()
+ calls = []
+
+ def compute(*a, **k):
+ calls.append(1)
+ return Block.forward(block, *a, **k)
+
+ graph = bg.BlockGraph(block, compute, bg._Shared(None))
+ with torch.no_grad():
+ for _ in range(3):
+ out = graph(torch.randn(2, 64))
+ assert out.shape == (2, 64) and len(calls) == 3
+ assert graph.stats["refused_host_weight"] == 3 and graph.stats["captures"] == 0
+
+
+def test_grad_mode_runs_the_compute():
+ block = Block()
+ graph = bg.BlockGraph(block, block.forward, bg._Shared(None))
+ graph(torch.randn(2, 64))
+ assert graph.stats["refused_grad"] == 1
+
+
+# --- installation ----------------------------------------------------------------------------------------------
+
+
+def _hooked_net(blocks = 4):
+ pytest.importorskip("diffusers.hooks")
+ from diffusers.hooks import apply_group_offloading
+
+ net = Net(blocks = blocks)
+ try:
+ apply_group_offloading(
+ net,
+ onload_device = torch.device("cpu"),
+ offload_type = "block_level",
+ num_blocks_per_group = 1,
+ )
+ except (
+ RuntimeError
+ ) as exc: # torch < 2.7: diffusers' group offload needs an accelerator even onto the CPU
+ pytest.skip(f"diffusers group offload unavailable here: {exc}")
+ return net
+
+
+def test_install_sits_below_the_group_offload_hook_and_free_restores_it():
+ net = _hooked_net()
+ hook = bg._group_offload_hook(net.blocks[0])
+ assert hook is not None
+ handle, reason = bg.install_block_graphs(net, slots = False)
+ assert reason == "armed" and handle is not None and len(handle.graphs) == 4
+ refs = net.blocks[0]._diffusers_hook._fn_refs
+ assert any(isinstance(r.forward, bg.BlockGraph) for r in refs)
+ x = torch.randn(3, 16)
+ with torch.no_grad():
+ got = net(x)
+ # the hook chain still runs (onload / offload) and the compute is the block's own forward
+ assert all(g.stats["refused_host_weight"] == 1 for g in handle.graphs)
+ handle.free()
+ assert not any(isinstance(r.forward, bg.BlockGraph) for r in refs)
+ with torch.no_grad():
+ assert torch.equal(net(x), got)
+
+
+def test_compile_moves_below_the_offload_hook_and_the_kill_switch_keeps_it_traced(monkeypatch):
+ net = _hooked_net(blocks = 2)
+ net._unsloth_regional_compile_kwargs = {"fullgraph": False, "dynamic": True}
+ marker = lambda *a, **k: None # noqa: E731
+ for b in net.blocks:
+ b._compiled_call_impl = marker
+ monkeypatch.setenv(bg.COMPILE_BELOW_HOOKS_ENV, "0")
+ assert bg.compile_below_offload_hooks(net) == 0
+ assert all(b._compiled_call_impl is marker for b in net.blocks)
+ monkeypatch.delenv(bg.COMPILE_BELOW_HOOKS_ENV)
+ assert bg.compile_below_offload_hooks(net) == 2
+ for b in net.blocks:
+ assert b._compiled_call_impl is None
+ refs = b._diffusers_hook._fn_refs
+ assert not any(bg._is_original_forward(r.forward, b) for r in refs)
+ # idempotent, and the block graph layer still finds the (now compiled) compute below the hook
+ assert bg.compile_below_offload_hooks(net) == 0
+ handle, reason = bg.install_block_graphs(net, slots = False)
+ assert reason == "armed" and len(handle.graphs) == 2
+ for b, g in zip(net.blocks, handle.graphs):
+ assert b._unsloth_below_hook_ref.forward is g
+ handle.free()
+ assert not any(isinstance(b._unsloth_below_hook_ref.forward, bg.BlockGraph) for b in net.blocks)
+
+
+def test_compile_below_the_hook_keeps_the_block_restride():
+ from core.inference import diffusion_block_restride as restride
+
+ net = _hooked_net(blocks = 2)
+ net._unsloth_regional_compile_kwargs = {"fullgraph": False, "dynamic": True}
+ marker = lambda *a, **k: None # noqa: E731
+ net.blocks[0]._compiled_call_impl = restride.wrap(marker)
+ net.blocks[1]._compiled_call_impl = marker
+ assert bg.compile_below_offload_hooks(net) == 2
+ assert restride.is_wrapped(net.blocks[0]._unsloth_below_hook_ref.forward)
+ assert not restride.is_wrapped(net.blocks[1]._unsloth_below_hook_ref.forward)
+
+
+def test_static_buffers_keep_the_storage_offset_of_a_view():
+ full = torch.arange(24.0).view(2, 12)
+ view = full[:, 4:]
+ static = bg._static_like(view)
+ assert static.shape == view.shape and static.stride() == view.stride()
+ assert static.storage_offset() == view.storage_offset() == 4
+ static.copy_(view)
+ assert torch.equal(static, view)
+
+
+def test_install_on_an_unhooked_compiled_block_takes_the_compiled_call_slot():
+ net = Net(blocks = 2)
+ marker = lambda *a, **k: "compiled" # noqa: E731
+ for b in net.blocks:
+ b._compiled_call_impl = marker
+ handle, _ = bg.install_block_graphs(net, slots = False)
+ assert all(isinstance(b._compiled_call_impl, bg.BlockGraph) for b in net.blocks)
+ assert handle.graphs[0].compute is marker
+ handle.free()
+ assert all(b._compiled_call_impl is marker for b in net.blocks)
+
+
+def test_per_layer_offload_hooks_inside_a_block_are_refused():
+ net = Net(blocks = 2)
+ for b in net.blocks:
+ b.lin._hf_hook = object()
+ handle, reason = bg.install_block_graphs(net, slots = False)
+ assert handle is None and "per-layer offload hooks" in reason
+
+
+def test_kill_switches(monkeypatch):
+ net = Net(blocks = 2)
+ monkeypatch.setenv(bg.BLOCK_GRAPHS_ENV, "0")
+ handle, reason = bg.install_block_graphs(net, slots = False)
+ assert handle is None and bg.BLOCK_GRAPHS_ENV in reason
+ monkeypatch.delenv(bg.BLOCK_GRAPHS_ENV)
+ monkeypatch.setenv(cg.CUDA_GRAPHS_ENV, "0")
+ assert cg.cuda_graph_disabled()
+ ok, why = cg.graph_eligible(
+ types.SimpleNamespace(device = "cuda", backend = "cuda"),
+ family = None,
+ pipe = None,
+ offload_active = False,
+ cache_active = False,
+ speed_mode = "default",
+ )
+ assert not ok and cg.CUDA_GRAPHS_ENV in why
+
+
+# --- arming per placement --------------------------------------------------------------------------------------
+
+
+def _pipe_with(net):
+ return types.SimpleNamespace(transformer = net, components = {"transformer": net})
+
+
+def _arm(
+ pipe,
+ monkeypatch,
+ *,
+ hooked,
+ pinned = False,
+ backend = "cuda",
+ cache = False,
+ mode = "default",
+ cuda = True,
+ opt_in = True,
+):
+ monkeypatch.setattr(torch.cuda, "is_available", lambda: cuda)
+ if opt_in:
+ monkeypatch.setenv(bg.BLOCK_GRAPHS_ENV, "1")
+ applied = {"cuda_graph": False}
+ target = types.SimpleNamespace(device = "cuda", backend = backend, torch_device = "cuda")
+ handles = cg.arm_block_graphs(
+ pipe,
+ applied,
+ target = target,
+ family = types.SimpleNamespace(),
+ hooked = hooked,
+ pinned = pinned,
+ cache_engaged = cache,
+ speed_mode = mode,
+ )
+ return handles, applied
+
+
+def test_an_offloaded_denoiser_is_recorded_per_block(monkeypatch):
+ pipe = _pipe_with(Net(blocks = 3))
+ pipe._unsloth_cuda_graph_reason = "offload active"
+ handles, applied = _arm(pipe, monkeypatch, hooked = True)
+ assert applied["cuda_graph"] and len(handles) == 1 and len(handles[0].graphs) == 3
+ assert "recorded per block" in cg.status_reason(pipe, True)
+ cg.uninstall_all(handles)
+
+
+def test_per_block_graphs_are_opt_in_and_say_so(monkeypatch):
+ pipe = _pipe_with(Net(blocks = 3))
+ pipe._unsloth_cuda_graph_reason = "offload active"
+ handles, applied = _arm(pipe, monkeypatch, hooked = True, opt_in = False)
+ assert handles == () and not applied["cuda_graph"]
+ assert bg.BLOCK_GRAPHS_ENV + "=1" in cg.status_reason(pipe, False)
+ assert not any(
+ isinstance(b.__dict__.get("forward"), bg.BlockGraph) for b in pipe.transformer.blocks
+ )
+ monkeypatch.setenv(bg.BLOCK_GRAPHS_ENV, "0")
+ pipe2 = _pipe_with(Net(blocks = 3))
+ handles, applied = _arm(pipe2, monkeypatch, hooked = True, opt_in = False)
+ assert handles == () and "BLOCK_GRAPHS=0" in cg.status_reason(pipe2, False)
+
+
+def test_blocks_that_stay_on_the_device_record_by_default(monkeypatch):
+ monkeypatch.delenv(bg.BLOCK_GRAPHS_ENV, raising = False)
+ pipe = _pipe_with(Net(blocks = 3))
+ pipe._unsloth_cuda_graph_reason = "offload active"
+ handles, applied = _arm(pipe, monkeypatch, hooked = True, pinned = True, opt_in = False)
+ assert applied["cuda_graph"] and len(handles[0].graphs) == 3
+ assert cg.status_reason(pipe, True).startswith("pinned denoiser recorded per block")
+ cg.uninstall_all(handles)
+ pipe = _pipe_with(Net(blocks = 2))
+ pipe._unsloth_cuda_graph_reason = (
+ "QwenImage21Transformer2DModel forward is not capture-safe (prefix KV cache)"
+ )
+ handles, applied = _arm(pipe, monkeypatch, hooked = False, opt_in = False)
+ assert applied["cuda_graph"] and handles
+ cg.uninstall_all(handles)
+ monkeypatch.setenv(bg.BLOCK_GRAPHS_ENV, "0")
+ pipe = _pipe_with(Net(blocks = 2))
+ handles, applied = _arm(pipe, monkeypatch, hooked = True, pinned = True, opt_in = False)
+ assert handles == () and "BLOCK_GRAPHS=0" in cg.status_reason(pipe, False)
+
+
+def test_model_offload_stays_opt_in_and_says_why(monkeypatch):
+ monkeypatch.delenv(bg.BLOCK_GRAPHS_ENV, raising = False)
+ net = Net(blocks = 2)
+ net._hf_hook = object()
+ pipe = _pipe_with(net)
+ handles, applied = _arm(pipe, monkeypatch, hooked = True, opt_in = False)
+ assert handles == () and not applied["cuda_graph"]
+ assert "model offload re-uploads" in cg.status_reason(pipe, False)
+ handles, applied = _arm(_pipe_with(net), monkeypatch, hooked = True, opt_in = True)
+ assert applied["cuda_graph"] and handles
+ cg.uninstall_all(handles)
+
+
+def test_a_resident_whole_forward_recording_is_kept(monkeypatch):
+ net = Net(blocks = 2)
+ pipe = _pipe_with(net)
+ whole = cg.GraphedForward(net)
+ pipe._unsloth_cuda_graphs = (whole,)
+ handles, applied = _arm(pipe, monkeypatch, hooked = False)
+ assert handles == (whole,)
+ assert cg.status_reason(pipe, True) == cg.WHOLE_REASON
+
+
+def test_a_forward_that_is_not_capture_safe_is_recorded_per_block(monkeypatch):
+ pipe = _pipe_with(Net(blocks = 2))
+ pipe._unsloth_cuda_graph_reason = (
+ "QwenImage21Transformer2DModel forward is not capture-safe (prefix KV cache object)"
+ )
+ handles, applied = _arm(pipe, monkeypatch, hooked = False)
+ assert applied["cuda_graph"] and handles
+ cg.uninstall_all(handles)
+
+
+def test_unrelated_refusals_stay_off_with_their_reason(monkeypatch):
+ pipe = _pipe_with(Net(blocks = 2))
+ pipe._unsloth_cuda_graph_reason = "speed tier off"
+ handles, applied = _arm(pipe, monkeypatch, hooked = False, mode = "off")
+ assert handles == () and not applied["cuda_graph"]
+ for kw, want in (
+ ({"backend": "rocm"}, "backend is rocm"),
+ ({"cache": True}, "step cache active"),
+ ({"mode": "off"}, "speed tier off"),
+ ):
+ pipe = _pipe_with(Net(blocks = 2))
+ handles, applied = _arm(pipe, monkeypatch, hooked = True, **kw)
+ assert handles == () and not applied["cuda_graph"]
+ assert cg.status_reason(pipe, False) == want
+
+
+def test_a_sage_denoiser_is_never_recorded_per_block(monkeypatch):
+ net = Net(blocks = 2)
+ net._unsloth_attention_backend = "sage"
+ pipe = _pipe_with(net)
+ handles, applied = _arm(pipe, monkeypatch, hooked = True, pinned = True)
+ assert handles == () and not applied["cuda_graph"]
+ assert "SageAttention" in cg.status_reason(pipe, False)
+
+
+def test_the_master_switch_turns_block_graphs_off_with_its_name(monkeypatch):
+ monkeypatch.setenv(cg.CUDA_GRAPHS_ENV, "0")
+ pipe = _pipe_with(Net(blocks = 2))
+ handles, applied = _arm(pipe, monkeypatch, hooked = True)
+ assert handles == () and cg.CUDA_GRAPHS_ENV in cg.status_reason(pipe, False)
+
+
+def test_status_says_why_armed_blocks_never_replayed():
+ net = Net(blocks = 2)
+ handle, _ = bg.install_block_graphs(net, slots = False)
+ assert cg.never_engaged((handle,)) is None # nothing ran yet
+ with torch.no_grad():
+ net(torch.randn(2, 16))
+ why = cg.never_engaged((handle,))
+ assert why is not None and "weights not on the GPU" in why
+ resolved, optims = cg.live_status({"cuda_graph": {"value": "on"}}, ["cuda_graph"], (handle,))
+ assert resolved["cuda_graph"]["value"] == "off" and "cuda_graph" not in optims
+ handle.graphs[0].churned = True
+ assert "new address every call" in handle.why_off()
+ handle.free()
+
+
+# --- slot ring -------------------------------------------------------------------------------------------------
+
+
+class _G:
+ def __init__(self, name, shape):
+ self.name = name
+ self.modules = []
+ self.parameters = [torch.zeros(shape)]
+ self.buffers = []
+ self.cpu_param_dict = {}
+ self.offload_leader = None
+
+
+def _slot_prefetcher(shapes, depth = 2):
+ groups = [_G(str(i), s) for i, s in enumerate(shapes)]
+ pf = op.GroupPrefetcher.__new__(op.GroupPrefetcher)
+ pf.module = object()
+ pf.depth = depth
+ pf.groups = groups
+ pf.by_id = {id(g): g for g in groups}
+ pf.nbytes = {id(g): 10 for g in groups}
+ pf.ready = {}
+ pf.active = False
+ pf.stats = {"dropped": 0}
+ pf.slot_of, pf.slot_buffers, pf.slot_raw, pf.slot_owner = {}, {}, {}, {}
+ pf.slot_size, pf.slot_bytes, pf.slot_bytes_planned = 0, 0, 0
+ released = []
+ pf._release = lambda g, e, counted = True: released.append(g.name)
+ return pf, groups, released
+
+
+def test_slots_are_shared_round_robin_and_sized_like_the_prefetch_window():
+ pf, groups, _ = _slot_prefetcher([(4, 4)] * 5 + [(8, 4)] * 2, depth = 2)
+ pf.enable_slots()
+ # every layout shares the same depth + 1 slots, in block order
+ assert [pf.slot_of[id(g)] for g in groups] == [0, 1, 2, 0, 1, 2, 0]
+ # each slot holds the largest packed group (an (8, 4) float32 = 128 bytes): the ring is the prefetch window
+ assert pf.slot_size == 128 and pf.slot_bytes_planned == 3 * 128
+ assert pf.slot_streamed == 7 and pf.slot_bytes == 0 # planned, allocated on first fill
+
+
+def test_a_pinned_denoiser_counts_no_streamed_slot_groups():
+ pf, groups, _ = _slot_prefetcher([(4, 4)] * 3, depth = 2)
+ for g in groups:
+ g._unsloth_resident = True
+ pf.enable_slots()
+ assert pf.slot_streamed == 0 and pf.slot_bytes == 0
+
+
+def test_slot_views_pack_leaves_aligned_and_mirror_the_sources():
+ raw = torch.zeros(4096, dtype = torch.uint8)
+ srcs = [torch.arange(6, dtype = torch.float32).view(2, 3), torch.ones(5, dtype = torch.bfloat16)]
+ assert op._packed_bytes(srcs) == op._SLOT_ALIGN + 10
+ views = op._slot_views(raw, srcs, torch.device("cpu"))
+ assert [v.shape for v in views] == [torch.Size([2, 3]), torch.Size([5])]
+ assert views[1].data_ptr() - views[0].data_ptr() == op._SLOT_ALIGN
+ for v, src in zip(views, srcs):
+ op._copy_into(v, src)
+ assert torch.equal(v, src)
+ assert op._packed_bytes([torch.zeros(4, 4).t()]) is None # a strided leaf cannot be viewed in
+
+
+def test_a_slot_held_by_a_group_on_the_device_is_never_refilled_ahead():
+ pf, groups, released = _slot_prefetcher([(4, 4)] * 4, depth = 2)
+ pf.enable_slots()
+ a, d = groups[0], groups[3] # same slot
+ pf.slot_owner[pf.slot_of[id(a)]] = id(a)
+ pf.ready[id(a)] = None # onloaded, compute in flight
+ assert pf._slot_free(d, must = False) is False
+ # a forced onload of d copies to fresh memory instead (the block then runs ungraphed once)
+ assert pf._slot_free(d, must = True) is None and pf.stats["slot_fallbacks"] == 1
+ # copied ahead but not run yet: a forced onload drops it and takes the slot
+ pf.ready[id(a)] = object()
+ assert pf._slot_free(d, must = True) is True and released == ["0"]
+ # released (no longer on the device): free
+ pf.ready.clear()
+ assert pf._slot_free(d, must = False) is True
+
+
+def test_the_top_level_group_keeps_fresh_copies():
+ pf, groups, _ = _slot_prefetcher([(4, 4)] * 3)
+ groups[0].offload_leader = pf.module
+ pf.enable_slots()
+ assert id(groups[0]) not in pf.slot_of and len(pf.slot_of) == 2
+
+
+# --- memory guard ----------------------------------------------------------------------------------------------
+
+
+def test_pool_bytes_count_only_the_target_card(monkeypatch):
+ here, there = bg._Shared(0), bg._Shared(1)
+ here.pool_bytes, there.pool_bytes = 100, 900
+ monkeypatch.setattr(bg, "_LIVE", {here, there})
+ assert bg.pool_bytes(0) == 100 and bg.pool_bytes() == 1000
+
+
+def test_block_graph_pools_are_not_credited_as_reclaimable(monkeypatch):
+ target = types.SimpleNamespace(device = "cuda", backend = "cuda")
+ snap = dm.DeviceMemory("cuda", "cuda", "dedicated", 1000, 8000)
+ monkeypatch.setattr(dm, "snapshot_device_memory", lambda t: snap)
+ monkeypatch.setattr(torch.cuda, "memory_reserved", lambda *a, **k: 600 << 20)
+ monkeypatch.setattr(torch.cuda, "memory_allocated", lambda *a, **k: 100 << 20)
+ monkeypatch.setattr(bg, "pool_bytes", lambda device = None: 0)
+ assert dm.reclaimable_snapshot_device_memory(target).free_mib == 1500
+ monkeypatch.setattr(bg, "pool_bytes", lambda device = None: 300 << 20)
+ assert dm.reclaimable_snapshot_device_memory(target).free_mib == 1200
+
+
+# --- CUDA ------------------------------------------------------------------------------------------------------
+
+
+def _cuda():
+ if not torch.cuda.is_available():
+ pytest.skip("needs CUDA")
+ pytest.importorskip("diffusers.hooks")
+
+
+def _streamed(net, resident_mib = None):
+ pipe = _pipe_with(net)
+ kwargs = {}
+ if resident_mib:
+ kwargs["resident_transformer_mib"] = resident_mib
+ assert dm._apply_group_offload(pipe, "cuda", None, **kwargs)
+ return pipe
+
+
+def _no_syncs(fn):
+ prev = torch.cuda.get_sync_debug_mode()
+ torch.cuda.set_sync_debug_mode("warn")
+ try:
+ with warnings.catch_warnings(record = True) as caught:
+ warnings.simplefilter("always")
+ out = fn()
+ finally:
+ torch.cuda.set_sync_debug_mode(prev)
+ return out, sum(1 for w in caught if "synchroniz" in str(w.message).lower())
+
+
+def _net(
+ width = 256,
+ blocks = 8,
+ dtype = torch.float32,
+):
+ torch.manual_seed(0)
+ return Net(width = width, blocks = blocks).to(dtype)
+
+
[email protected]("resident_mib", [None, 1])
+def test_streamed_blocks_replay_from_the_slot_ring_bit_identically(resident_mib):
+ _cuda()
+ net = _net()
+ ref = copy.deepcopy(net).cuda()
+ _streamed(net, resident_mib)
+ pf = op.module_prefetcher(net)
+ assert pf is not None
+ handle, reason = bg.install_block_graphs(net, device = "cuda")
+ assert reason == "armed" and handle.slots_mib >= 0
+ x = torch.randn(4, 16, device = "cuda")
+ temb = torch.randn(1, 256, device = "cuda")
+ with torch.no_grad():
+ want = ref(x, temb = temb)
+ for i in range(4):
+ got, syncs = _no_syncs(lambda: net(x, temb = temb))
+ torch.cuda.synchronize()
+ assert torch.equal(got, want), i
+ if i >= 2:
+ assert syncs == 0
+ # a different input is copied into the same static buffers and replays the same recordings
+ x2 = torch.randn(4, 16, device = "cuda")
+ captures = handle.stats["captures"]
+ assert torch.equal(net(x2, temb = temb), ref(x2, temb = temb))
+ assert handle.stats["captures"] == captures
+ s = handle.stats
+ assert s["replays"] >= 8 and s["fallbacks"] == 0 and s["refused_host_weight"] == 0
+ # one recording per block (weights at their slot), each made once
+ assert s["captures"] == 8 and s["recaptures"] == 0
+ assert pf.stats["slot_fills"] > 0 and pf.stats.get("slot_fallbacks", 0) == 0
+ assert net.blocks[-1].lin.weight.device.type == "cpu"
+ handle.free()
+ with torch.no_grad():
+ assert torch.equal(net(x, temb = temb), want)
+
+
+class SlowBlock(Block):
+ def forward(
+ self,
+ x,
+ temb = None,
+ layer_cache = None,
+ kv_cache_mode = None,
+ ):
+ torch.cuda._sleep(
+ 200_000
+ ) # a slow GPU: the host queues later copies long before this block reads
+ return super().forward(x, temb = temb)
+
+
+def test_a_slow_gpu_never_reads_a_slot_the_copy_stream_is_refilling(monkeypatch):
+ _cuda()
+ monkeypatch.setenv(op.PREFETCH_DEPTH_ENV, "3")
+ torch.manual_seed(0)
+ net = Net(width = 512, blocks = 10)
+ net.blocks = torch.nn.ModuleList(SlowBlock(512) for _ in range(10))
+ Net._repeated_blocks = ["Block", "SlowBlock"]
+ try:
+ ref = copy.deepcopy(net).cuda()
+ _streamed(net)
+ handle, _ = bg.install_block_graphs(net, device = "cuda")
+ x = torch.randn(4, 16, device = "cuda")
+ with torch.no_grad():
+ want = ref(x)
+ for _ in range(5):
+ got = net(x)
+ torch.cuda.synchronize()
+ assert torch.equal(got, want)
+ assert handle.stats["replays"] > 0
+ handle.free()
+ finally:
+ Net._repeated_blocks = ["Block"]
+
+
+def test_compiled_streamed_blocks_record_below_their_hooks_with_no_graph_break():
+ _cuda()
+ import torch._dynamo.utils as du
+
+ net = _net(blocks = 6)
+ ref = copy.deepcopy(net).cuda()
+ kwargs = {"fullgraph": False, "dynamic": None}
+ for b in net.blocks:
+ b.compile(**kwargs)
+ net._unsloth_regional_compile_kwargs = kwargs
+ _streamed(net)
+ assert bg.compile_below_offload_hooks(net) == 6
+ handle, reason = bg.install_block_graphs(net, device = "cuda")
+ assert reason == "armed" and len(handle.graphs) == 6
+ breaks = sum(du.counters["graph_break"].values())
+ x = torch.randn(4, 16, device = "cuda")
+ with torch.no_grad():
+ want = ref(x)
+ for _ in range(4):
+ got = net(x)
+ torch.cuda.synchronize()
+ torch.testing.assert_close(got, want, rtol = 1e-4, atol = 1e-4)
+ first = got.clone()
+ for _ in range(2):
+ assert torch.equal(net(x), first) # replays are deterministic
+ assert (
+ sum(du.counters["graph_break"].values()) == breaks
+ ) # the hooks stay outside the compiled region
+ s = handle.stats
+ assert s["replays"] > 0 and s["fallbacks"] == 0 and s["captures"] == 6
+ handle.free()
+
+
+def test_alternating_layouts_both_record():
+ """True CFG calls each block with two text lengths in turn; each layout must still record and replay."""
+ _cuda()
+ net = _net(blocks = 2).cuda()
+ ref = copy.deepcopy(net)
+ handle, _ = bg.install_block_graphs(net, device = "cuda", slots = False)
+ xs = [torch.randn(7, 16, device = "cuda"), torch.randn(5, 16, device = "cuda")]
+ with torch.inference_mode():
+ for _ in range(4):
+ for x in xs:
+ assert torch.equal(net(x), ref(x))
+ s = handle.stats
+ assert s["captures"] == 4 and s["replays"] >= 8 and s["fallbacks"] == 0
+ handle.free()
+
+
+def test_evicted_layouts_free_their_static_buffers():
+ _cuda()
+ net = _net(blocks = 2).cuda()
+ ref = copy.deepcopy(net)
+ handle, _ = bg.install_block_graphs(net, device = "cuda", slots = False)
+ for g in handle.graphs:
+ g.max_graphs = 2
+ shared = handle.graphs[0].shared
+ with torch.inference_mode():
+ for rows in range(3, 11): # a new layout per render, as a new prompt length is
+ x = torch.randn(rows, 16, device = "cuda")
+ for _ in range(3):
+ assert torch.equal(net(x), ref(x))
+ assert handle.stats["evictions"] > 0
+ assert len(shared.static_in) == 2 and len(shared.static_out) == 2
+ handle.free()
+
+
+def test_each_nvfp4_precision_branch_records_its_own_graph():
+ _cuda()
+ net = _net(blocks = 2).cuda()
+ ref = copy.deepcopy(net)
+ handle, _ = bg.install_block_graphs(net, device = "cuda", slots = False)
+ ctl = types.SimpleNamespace(armed = True, protected = False)
+ for g in handle.graphs:
+ g.protect = ctl
+ x = torch.randn(4, 16, device = "cuda")
+ with torch.inference_mode():
+ for protected in (False, True, False, True, False, True):
+ ctl.protected = protected
+ assert torch.equal(net(x), ref(x))
+ assert handle.stats["captures"] == 2 * len(handle.graphs)
+ for g in handle.graphs:
+ assert {k[1][1] for k in g.cache} == {
+ (("nvfp4_protect", False),),
+ (("nvfp4_protect", True),),
+ }
+ handle.free()
+
+
+def test_a_block_whose_weights_moved_records_again_at_the_new_addresses():
+ _cuda()
+ net = _net(blocks = 3).cuda()
+ ref = copy.deepcopy(net)
+ handle, _ = bg.install_block_graphs(net, device = "cuda", slots = False)
+ x = torch.randn(4, 16, device = "cuda")
+ with torch.inference_mode():
+ want = ref(x)
+ for _ in range(3):
+ assert torch.equal(net(x), want)
+ assert handle.stats["captures"] == 3
+ # the 12 GB tier's encode release / restore and model offload's re-upload land weights elsewhere
+ for block in net.blocks:
+ block.lin.weight.data = block.lin.weight.data.clone()
+ for _ in range(3):
+ assert torch.equal(net(x), want)
+ # the moved weights change the result if a stale recording replayed them: perturb and compare
+ net.blocks[1].lin.weight.data = net.blocks[1].lin.weight.data * 2
+ ref.blocks[1].lin.weight.data = ref.blocks[1].lin.weight.data * 2
+ for _ in range(3):
+ assert torch.equal(net(x), ref(x))
+ assert handle.stats["recaptures"] >= 3 and handle.stats["fallbacks"] == 0
+ handle.free()
+
+
+def test_prefix_kv_cache_blocks_replay_on_cached_steps():
+ _cuda()
+ net = _net(blocks = 3).cuda()
+ ref = copy.deepcopy(net)
+ caches = []
+ for _ in range(3):
+ c = QwenImage21KVLayerCache()
+ c.store(torch.randn(5, 256, device = "cuda"), torch.randn(5, 256, device = "cuda"))
+ caches.append(c)
+ handle, _ = bg.install_block_graphs(net, device = "cuda", slots = False)
+ x = torch.randn(4, 16, device = "cuda")
+ with torch.inference_mode():
+ want = ref(x, caches = caches)
+ for _ in range(4):
+ assert torch.equal(net(x, caches = caches), want)
+ # new prefix values (a new prompt) are copied in; the recordings stay
+ for c in caches:
+ c.store(torch.randn(5, 256, device = "cuda"), torch.randn(5, 256, device = "cuda"))
+ captures = handle.stats["captures"]
+ assert torch.equal(net(x, caches = caches), ref(x, caches = caches))
+ assert handle.stats["captures"] == captures
+ assert handle.stats["replays"] > 0 and handle.stats["fallbacks"] == 0
+ handle.free()
+
+
+def test_torchao_int8_weights_stream_through_the_slot_ring_with_graphs():
+ _cuda()
+ torchao = pytest.importorskip("torchao")
+ from torchao.quantization import quantize_
+
+ try:
+ from torchao.quantization import Int8WeightOnlyConfig as Cfg
+ except ImportError:
+ pytest.skip(f"torchao {torchao.__version__} has no Int8WeightOnlyConfig")
+ net = _net(dtype = torch.bfloat16)
+ quantize_(net, Cfg())
+ ref = copy.deepcopy(net).cuda()
+ _streamed(net)
+ pf = op.module_prefetcher(net)
+ assert pf is not None
+ handle, _ = bg.install_block_graphs(net, device = "cuda")
+ x = torch.randn(4, 16, device = "cuda", dtype = torch.bfloat16)
+ with torch.no_grad():
+ want = ref(x)
+ for _ in range(4):
+ got = net(x)
+ torch.cuda.synchronize()
+ assert torch.equal(got, want)
+ assert handle.stats["replays"] > 0 and handle.stats["fallbacks"] == 0
+ assert pf.stats["slot_fills"] > 0
+ handle.free()
diff --git a/studio/backend/tests/test_diffusion_failed_capture_pool.py b/studio/backend/tests/test_diffusion_failed_capture_pool.py
new file mode 100644
index 00000000000..2745132638c
--- /dev/null
+++ b/studio/backend/tests/test_diffusion_failed_capture_pool.py
@@ -0,0 +1,125 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""A capture that fails must not break the captures after it.
+
+``capture_end`` raises in ``cudaStreamEndCapture`` before either caching allocator (device, and from torch 2.11 the
+pinned host one) leaves the capture's pool. Python can only take the device allocator off it, so the host allocator
+keeps "recording" to that pool for the rest of the process, with a filter that points at the failed CUDAGraph.
+Studio therefore retires the pool, records later captures into a fresh one, and keeps the failed graph alive.
+"""
+
+from __future__ import annotations
+
+import pytest
+import torch
+
+import core.inference.diffusion_block_graph as bg
+import core.inference.diffusion_cuda_graph as cg
+
+
+def _cuda():
+ if not torch.cuda.is_available():
+ pytest.skip("needs CUDA")
+
+
+class _Block(torch.nn.Module):
+ def __init__(self, sync: bool = False) -> None:
+ super().__init__()
+ torch.manual_seed(0)
+ self.lin = torch.nn.Linear(16, 16)
+ self.sync = sync
+
+ def forward(
+ self,
+ x,
+ return_dict = True,
+ ):
+ y = self.lin(x)
+ if self.sync and torch.cuda.is_current_stream_capturing():
+ y = y + float(y.sum().item()) * 0 # a host read: invalidates the recording
+ return (y,) if return_dict is False else y
+
+
+def _record_twice(graph, x):
+ with torch.inference_mode():
+ graph(x) # first sighting: eager
+ return graph(x) # records, then replays
+
+
+def test_a_block_records_after_another_block_failed_to(monkeypatch):
+ _cuda()
+ monkeypatch.setattr(cg, "_FAILED_GRAPHS", [], raising = False)
+ shared = bg._Shared(torch.cuda.current_device())
+ good_first = _Block().cuda()
+ bad = _Block(sync = True).cuda()
+ good = _Block().cuda()
+ x = torch.randn(4, 16, device = "cuda")
+ first = bg.BlockGraph(good_first, good_first.forward, shared)
+ _record_twice(first, x)
+ assert first.stats["captures"] == 1 # the shared pool now holds a live graph
+
+ failing = bg.BlockGraph(bad, bad.forward, shared)
+ _record_twice(failing, x)
+ assert failing.poisoned and failing.stats["captures"] == 0
+
+ after = bg.BlockGraph(good, good.forward, shared)
+ out = _record_twice(after, x)
+ assert after.capture_error is None, after.capture_error
+ assert after.stats["captures"] == 1 and not after.poisoned
+ with torch.inference_mode():
+ assert torch.equal(after(x), good(x))
+ assert torch.equal(first(x), good_first(x))
+ assert torch.equal(out, good(x))
+ assert (
+ len(cg._FAILED_GRAPHS) == 1
+ ) # the failed recording is kept, never freed under the allocator
+ torch.randn(4, device = "cuda") # the RNG left capture mode
+
+
+def test_a_step_graph_records_after_another_one_failed_to(monkeypatch):
+ _cuda()
+ monkeypatch.setattr(cg, "_FAILED_GRAPHS", [], raising = False)
+ monkeypatch.setattr(cg, "_POOL_BOX", [None])
+ x = torch.randn(4, 16, device = "cuda")
+ mods = [_Block().cuda(), _Block(sync = True).cuda(), _Block().cuda()]
+ handles = [cg.GraphedForward(m).install().enable() for m in mods]
+ with torch.inference_mode():
+ mods[0](x, return_dict = False)
+ assert handles[0].stats["captures"] == 1 # the shared step pool now holds a live graph
+ mods[1](x, return_dict = False)
+ assert handles[1].poisoned
+ out = mods[2](x, return_dict = False)[0]
+ assert handles[2].capture_error is None, handles[2].capture_error
+ assert handles[2].stats["captures"] == 1
+ assert torch.equal(out, mods[2].lin(x))
+ assert torch.equal(mods[0](x, return_dict = False)[0], mods[0].lin(x))
+ assert len(cg._FAILED_GRAPHS) == 1
+ for h in handles:
+ h.uninstall()
+
+
+def test_captures_stop_once_the_failure_budget_is_spent(monkeypatch):
+ _cuda()
+ monkeypatch.setattr(cg, "_FAILED_GRAPHS", [object()] * cg.MAX_FAILED_CAPTURES)
+ shared = bg._Shared(torch.cuda.current_device())
+ good = _Block().cuda()
+ graph = bg.BlockGraph(good, good.forward, shared)
+ x = torch.randn(4, 16, device = "cuda")
+ out = _record_twice(graph, x)
+ assert graph.stats["captures"] == 0 and graph.poisoned
+ assert "failed" in graph.capture_error["msg"]
+ assert torch.equal(out, good(x))
+
+
+def test_a_collision_with_another_recording_does_not_spend_the_failure_budget(monkeypatch):
+ monkeypatch.setattr(cg, "_FAILED_GRAPHS", [])
+ monkeypatch.setattr(cg, "_COLLIDED_GRAPHS", [], raising = False)
+ healed = []
+ monkeypatch.setattr(cg, "_heal_generators", lambda: healed.append(1))
+ for _ in range(cg.MAX_FAILED_CAPTURES + 1):
+ cg.retire_failed_capture(
+ object(), None, RuntimeError("beginAllocateToPool: already recording to mempool_id")
+ )
+ assert not cg.captures_exhausted()
+ assert healed == [] # the generators belong to the other thread's live capture