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.

Block CUDA graphs: only release the cudagraph pool for tree functions the block backend compiled (#15777)

Daniel Handda083b1e6b4
diff --git a/tests/test_block_cudagraphs_auto.py b/tests/test_block_cudagraphs_auto.py
index e14fc21bf7b..f481ee71189 100644
--- a/tests/test_block_cudagraphs_auto.py
+++ b/tests/test_block_cudagraphs_auto.py
@@ -9,6 +9,7 @@ stubbed, so this runs on CPU."""
import importlib.util
import os
import sys
+import types
import pytest
import torch
@@ -192,6 +193,52 @@ def test_auto_after_on_new_shapes_past_the_cap_turn_graphs_off(monkeypatch):
assert _step(layers, calls) == ["plain", "plain"]
+def test_auto_graphed_compile_owns_only_its_compile_ids(monkeypatch):
+ # The graphed region auto mode compiles once graphs turn on must use the owning backend too:
+ # a foreign reduce-overhead function first called inside the block is not ours.
+ from torch._guards import CompileContext, CompileId, compile_context
+
+ layers, calls, compiles, _ = _harness(monkeypatch)
+ monkeypatch.setattr(
+ torch._TorchCompileInductorWrapper, "__call__", lambda self, gm, inputs, **kw: gm
+ )
+ manager = types.SimpleNamespace(ids_to_funcs = {}, id_to_compile_id = {})
+ monkeypatch.setattr(bc, "_tree_manager", lambda device: manager)
+ block_cid = CompileId(frame_id = 1, frame_compile_id = 0)
+ foreign_cid = CompileId(frame_id = 2, frame_compile_id = 0)
+
+ def register(cid):
+ i = len(manager.ids_to_funcs)
+ manager.ids_to_funcs[i] = None
+ manager.id_to_compile_id[i] = cid
+
+ def fake_compile(fn, **kwargs):
+ compiles.append("graphs")
+ backend = kwargs.get("backend")
+
+ def run(*args, **kw):
+ calls.append("graphs")
+ if not manager.ids_to_funcs: # first call records the block's tree function
+ with compile_context(CompileContext(block_cid)):
+ if backend is not None:
+ backend("gm", [])
+ register(block_cid)
+ register(foreign_cid) # foreign region behind a graph break, first call
+ return fn(*args, **kw)
+
+ return run
+
+ monkeypatch.setattr(torch, "compile", fake_compile)
+ for _ in range(4):
+ assert "graphs" not in _step(layers, calls)
+ assert bc._CUDAGRAPH_STATE["auto"]["decision"] == "on"
+ assert not manager.ids_to_funcs
+ assert _step(layers, calls) == ["graphs", "graphs"]
+ assert compiles == ["plain", "graphs"]
+ assert bc._CUDAGRAPH_STATE["ours"] == {block_cid}
+ assert bc._pool_release_verdict([manager], bc._CUDAGRAPH_STATE["ours"]) == "foreign"
+
+
def test_auto_packed_rows_keep_graphs_off(monkeypatch):
layers, calls, _, timed = _harness(monkeypatch)
lengths = torch.tensor([8, 8])
diff --git a/tests/test_block_cudagraphs_clone.py b/tests/test_block_cudagraphs_clone.py
index 6f0081d44d9..efecb3ccaa4 100644
--- a/tests/test_block_cudagraphs_clone.py
+++ b/tests/test_block_cudagraphs_clone.py
@@ -711,6 +711,7 @@ def test_graphed_call_records_the_compile_ids_it_created(monkeypatch):
return n
monkeypatch.setattr(bc, "_tree_manager", tree_manager)
+ bc._CUDAGRAPH_STATE["built"].update({"a", "b", "x", "y"})
manager.ids_to_funcs[0], manager.id_to_compile_id[0] = None, "foreign" # made before us
assert bc._graphed_call(compiled, 0, 0, "x") == 0
bc._graphed_call(compiled, 0, 2, "a")
@@ -721,6 +722,56 @@ def test_graphed_call_records_the_compile_ids_it_created(monkeypatch):
assert bc._pool_release_verdict([manager], bc._CUDAGRAPH_STATE["ours"]) == "foreign"
+def test_foreign_function_first_called_inside_a_block_is_not_ours(monkeypatch):
+ # A foreign region behind a graph break registers a tree function during the block call.
+ manager = _FakeManager([])
+ monkeypatch.setattr(bc, "_tree_manager", lambda device: manager)
+ bc._CUDAGRAPH_STATE["built"].add("block")
+
+ def compiled(*cids):
+ for cid in cids:
+ i = len(manager.ids_to_funcs)
+ manager.ids_to_funcs[i] = None
+ manager.id_to_compile_id[i] = cid
+
+ bc._graphed_call(compiled, 0, "block", "foreign")
+ assert bc._CUDAGRAPH_STATE["ours"] == {"block"}
+ assert bc._pool_release_verdict([manager], bc._CUDAGRAPH_STATE["ours"]) == "foreign"
+
+
+def test_block_backend_notes_the_compile_ids_it_builds(monkeypatch):
+ from torch._guards import CompileContext, CompileId
+
+ seen = []
+ monkeypatch.setattr(
+ torch._TorchCompileInductorWrapper,
+ "__call__",
+ lambda self, gm, inputs, **kwargs: seen.append(kwargs) or gm,
+ )
+ backend = bc._block_backend({**bc._COMPILE_OPTIONS, "triton.cudagraphs": True})
+ assert backend.config["triton.cudagraphs"] is True
+ cid = CompileId(frame_id = 7, frame_compile_id = 0)
+ with torch._guards.compile_context(CompileContext(cid)):
+ assert backend("gm", [], options = {"triton.cudagraphs": True}) == "gm"
+ assert seen == [{}]
+ assert bc._CUDAGRAPH_STATE["built"] == {cid}
+
+
+def test_only_the_graphs_on_compile_gets_the_owning_backend(monkeypatch):
+ seen = []
+ monkeypatch.setattr(torch, "compile", lambda fn, **kwargs: seen.append(kwargs) or fn)
+ A = _linear_layer_class("OwnedDecoderLayer")
+ bc._wrap(A, {**bc._COMPILE_OPTIONS, "triton.cudagraphs": True})
+ graphs, plain = seen
+ assert isinstance(graphs["backend"], torch._TorchCompileInductorWrapper)
+ assert graphs["options"]["triton.cudagraphs"] is True
+ assert "backend" not in plain and plain["options"]["triton.cudagraphs"] is False
+ seen.clear()
+ B = _linear_layer_class("UngraphedDecoderLayer")
+ bc._wrap(B, bc._COMPILE_OPTIONS)
+ assert all("backend" not in kwargs for kwargs in seen)
+
+
def test_grad_trial_of_a_checkpointed_block_takes_the_recompute_path(monkeypatch):
# The first no-grad call (checkpoint forward) runs a grad-mode trial first; it stands in for the
# recompute, so it copies like the recompute does.
diff --git a/unsloth/models/_block_compile.py b/unsloth/models/_block_compile.py
index 76c13b79749..f41dd1f900c 100644
--- a/unsloth/models/_block_compile.py
+++ b/unsloth/models/_block_compile.py
@@ -50,12 +50,14 @@ except ValueError:
# Process wide: every block class shares one cudagraph tree (one pool per device).
# off: why graphs went off (None = on); release: None, "done" or "kept"; ours: compile ids of the
-# tree functions block calls created; managers: CUDA index -> the tree manager block graphs ran on.
+# tree functions block calls created; built: compile ids the graphs-on block backend compiled;
+# managers: CUDA index -> the tree manager block graphs ran on.
def _new_cudagraph_state():
return {
"off": None,
"release": None,
"ours": set(),
+ "built": set(),
"managers": {},
"notes": set(),
"auto": _new_auto_state(),
@@ -122,9 +124,31 @@ def _tree_manager(device):
return None
+def _block_backend(options):
+ """Inductor noting each compile id it builds, so foreign regions behind a graph break are not
+ counted as ours. None if unsupported (then the pool is kept)."""
+ try:
+ from torch._guards import CompileContext
+ class _BlockInductor(torch._TorchCompileInductorWrapper):
+ def __call__(
+ self,
+ *args,
+ options = None,
+ **kwargs,
+ ):
+ # options were already applied by the constructor.
+ _CUDAGRAPH_STATE["built"].add(CompileContext.current_compile_id())
+ return super().__call__(*args, **kwargs)
+
+ return _BlockInductor(None, options, None)
+ except Exception:
+ return None
+
+
def _graphed_call(compiled, device, *args, **kwargs):
"""Call the graphs-on region; note the compile ids of tree functions it created (forward here,
- the backward of the same compile later), so the release can tell its pool is only ours."""
+ the backward of the same compile later) that the block backend built, so the release can tell
+ its pool is only ours."""
managers = _CUDAGRAPH_STATE["managers"]
manager = managers.get(device)
if manager is None:
@@ -140,8 +164,9 @@ def _graphed_call(compiled, device, *args, **kwargs):
return out
managers[device] = manager
if len(manager.ids_to_funcs) > before:
- ids = list(manager.ids_to_funcs)[before:]
- _CUDAGRAPH_STATE["ours"].update(manager.id_to_compile_id.get(i) for i in ids)
+ built = _CUDAGRAPH_STATE["built"]
+ cids = (manager.id_to_compile_id.get(i) for i in list(manager.ids_to_funcs)[before:])
+ _CUDAGRAPH_STATE["ours"].update(cid for cid in cids if cid is not None and cid in built)
return out
@@ -1380,8 +1405,11 @@ def _wrap(
isolate = {}
if _ISOLATE_RECOMPILES:
isolate = dict(isolate_recompiles = True, recompile_limit = _region_recompile_limit(kinds))
+ graphs = bool(compile_options.get("triton.cudagraphs"))
+ backend = _block_backend(compile_options) if graphs else None
+ owned = {} if backend is None else {"backend": backend}
compiled = torch.compile(
- original, fullgraph = False, dynamic = None, options = compile_options, **isolate
+ original, fullgraph = False, dynamic = None, options = compile_options, **owned, **isolate
)
try:
from unsloth_zoo.temporary_patches.utils import UNSLOTH_DECODE_COMPILE as inline_flag
@@ -1397,7 +1425,6 @@ def _wrap(
state = {"reported": set(), "start": {}}
# Under Unsloth checkpointing each block call is a new cudagraph generation: the next replay
# overwrites this block's outputs and gradients, so they are cloned out of the pool.
- graphs = bool(compile_options.get("triton.cudagraphs"))
# Auto: `compiled` stays the graphs-off region; the graphed one is compiled once graphs turn on.
auto = not graphs and _CUDAGRAPH_MODE == "auto"
if graphs:
@@ -1414,11 +1441,15 @@ def _wrap(
def graphed():
if graphed_box[0] is None:
+ options = {**compile_options, "triton.cudagraphs": True}
+ backend = _block_backend(options)
+ owned = {} if backend is None else {"backend": backend}
graphed_box[0] = torch.compile(
original,
fullgraph = False,
dynamic = None,
- options = {**compile_options, "triton.cudagraphs": True},
+ options = options,
+ **owned,
**isolate,
)
return graphed_box[0]