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.

Decode graphs on by default for RL trainer generation, released on return to training (#15188)

Daniel Hancc1b758055af
diff --git a/tests/test_decode_cuda_graphs.py b/tests/test_decode_cuda_graphs.py
index 687c5a015a3..96fea0db791 100644
--- a/tests/test_decode_cuda_graphs.py
+++ b/tests/test_decode_cuda_graphs.py
@@ -1,14 +1,10 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-"""CUDA-graph decode (UNSLOTH_DECODE_CUDA_GRAPHS=1): a replayed step is bit for bit the eager step
+"""CUDA-graph decode (forced on / off per test through _decode_graphs.ENABLED): a replayed step is bit for bit the eager step
(greedy tokens and raw logits, 16-bit and 4-bit, batch 1 and a left-padded batch), graphs are
re-captured when LoRA weights change between generate() calls, and the KV cache may grow."""
-import os
-
-os.environ.setdefault("UNSLOTH_DECODE_CUDA_GRAPHS", "1")
-
import pytest
import unsloth # noqa: F401 (must precede transformers)
diff --git a/tests/test_decode_cuda_graphs_default.py b/tests/test_decode_cuda_graphs_default.py
new file mode 100644
index 00000000000..40b58682180
--- /dev/null
+++ b/tests/test_decode_cuda_graphs_default.py
@@ -0,0 +1,205 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""When CUDA-graph decode runs (decided per call): UNSLOTH_DECODE_CUDA_GRAPHS unset = off for plain
+model.generate(), on inside an RL trainer's generation (rl_generation(), entered by rl.py's
+unwrap_model_for_generation); =1 on everywhere, =0 off everywhere. Returning to training releases
+the graphs and every decode buffer."""
+
+import pytest
+
+import unsloth # noqa: F401 (must precede transformers)
+from unsloth import FastLanguageModel
+import torch
+
+import unsloth.models._decode_graphs as G
+
+cuda = pytest.mark.skipif(not torch.cuda.is_available(), reason = "CUDA only")
+# The unset default only turns graphs on for NVIDIA CUDA; ROCm keeps them off unless the flag is 1.
+rl_default = pytest.mark.skipif(not G._DEFAULT_OK, reason = "RL default is NVIDIA CUDA only")
+MODEL = "trl-internal-testing/tiny-Qwen3ForCausalLM"
+PROMPTS = ["Once upon a time there was", "def f(x):"]
+ENV = "UNSLOTH_DECODE_CUDA_GRAPHS"
+
+
+def runtime(monkeypatch):
+ # The runtime decision, not a programmatic override.
+ monkeypatch.setattr(G, "ENABLED", None)
+ monkeypatch.delenv(ENV, raising = False)
+ return monkeypatch
+
+
+def test_enabled_decision(runtime):
+ runtime.setattr(G, "_DEFAULT_OK", True)
+ assert G.enabled() is False
+ with G.rl_generation():
+ assert G.enabled() is True
+ with G.rl_generation():
+ assert G.enabled() is True
+ assert G.enabled() is True
+ assert G.enabled() is False
+ runtime.setenv(ENV, "0")
+ with G.rl_generation():
+ assert G.enabled() is False
+ runtime.setenv(ENV, "1")
+ assert G.enabled() is True
+ runtime.setattr(G, "ENABLED", False)
+ assert G.enabled() is False
+
+
+def test_rl_default_is_nvidia_cuda_only(runtime):
+ runtime.setattr(G, "_DEFAULT_OK", False) # ROCm / HIP, or no CUDA device
+ with G.rl_generation():
+ assert G.enabled() is False
+ runtime.setenv(ENV, "1")
+ assert G.enabled() is True
+ runtime.setattr(torch.version, "hip", "6.4.0", raising = False)
+ assert G._default_ok() is False
+
+
+def test_rl_scope_is_per_thread(runtime):
+ import threading
+
+ runtime.setattr(G, "_DEFAULT_OK", True)
+ seen = []
+ with G.rl_generation():
+ t = threading.Thread(target = lambda: seen.append(G.enabled()))
+ t.start()
+ t.join()
+ assert G.enabled() is True
+ assert seen == [False]
+
+
+def test_enabled_is_trace_safe(runtime):
+ def f(x):
+ return x + 1 if G.enabled() or G.static() is not None else x - 1
+
+ compiled = torch.compile(f, fullgraph = True, backend = "eager")
+ with G.rl_generation():
+ assert compiled(torch.zeros(2)).tolist() == [-1.0, -1.0]
+
+
+def _load():
+ model, tok = FastLanguageModel.from_pretrained(MODEL, max_seq_length = 2048, load_in_4bit = False)
+ model = FastLanguageModel.get_peft_model(
+ model, r = 8, lora_alpha = 16, random_state = 0,
+ target_modules = ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"],
+ ) # fmt: skip
+ tok.padding_side = "left"
+ if tok.pad_token is None:
+ tok.pad_token = tok.eos_token
+ return model, tok
+
+
+class _Stats:
+ def __init__(self, model):
+ self.model = model
+
+ def __call__(self):
+ for m in self.model.modules():
+ if "_unsloth_decode_graphs" in m.__dict__:
+ return G.stats(m)
+ return {}
+
+
+def _causal(model):
+ return model
+
+
+def _graph_buffers(model):
+ return sum("_unsloth_graph_buffers" in m.__dict__ for m in model.modules())
+
+
+def _decode_buffers(model):
+ return sum("paged_attention" in m.__dict__ for m in model.modules())
+
+
+def _gen(
+ model,
+ tok,
+ new = 24,
+):
+ enc = tok(PROMPTS, return_tensors = "pt", padding = True).to("cuda")
+ out = model.generate(
+ **enc, max_new_tokens = new, min_new_tokens = new, do_sample = False,
+ pad_token_id = tok.pad_token_id, output_logits = True, return_dict_in_generate = True,
+ ) # fmt: skip
+ return out.sequences.cpu(), torch.stack(out.logits).cpu()
+
+
+@rl_default
+def test_plain_generate_off_rl_generate_on_and_released(runtime):
+ model, tok = _load()
+ FastLanguageModel.for_inference(model)
+ eager = _gen(model, tok)
+ assert _Stats(model)().get("replays", 0) == 0
+ assert _graph_buffers(model) == 0
+
+ with G.rl_generation():
+ graph = _gen(model, tok)
+ stats = _Stats(model)()
+ assert stats["disabled"] is None and stats["replays"] == 24 - 2, stats
+ assert torch.equal(eager[0], graph[0]) and torch.equal(eager[1], graph[1])
+
+ # =0 wins inside the RL scope; =1 turns plain generate on.
+ runtime.setenv(ENV, "0")
+ replays = _Stats(model)()["replays"]
+ with G.rl_generation():
+ assert torch.equal(_gen(model, tok)[1], eager[1])
+ assert _Stats(model)()["replays"] == replays
+ runtime.setenv(ENV, "1")
+ assert torch.equal(_gen(model, tok)[1], eager[1])
+ assert _Stats(model)()["replays"] > replays
+
+ # generate() called on a model in training mode returns to training: everything released.
+ runtime.delenv(ENV)
+ FastLanguageModel.for_training(model)
+ with G.rl_generation():
+ _gen(model, tok)
+ assert model.training
+ assert _graph_buffers(model) == 0 and _decode_buffers(model) == 0
+ assert _Stats(model)()["graphs"] == 0
+
+
+@rl_default
+def test_grpo_generation_uses_graphs_and_releases(runtime, tmp_path):
+ """A real GRPOTrainer step: its generate() runs graphed with the variable unset, completions
+ match the eager rollout, and the decode buffers are gone before the loss is computed."""
+ from datasets import Dataset
+ from trl import GRPOConfig, GRPOTrainer
+
+ model, tok = _load()
+ rows = [{"prompt": p} for p in PROMPTS * 4]
+ seen = {"replays": [], "buffers_at_loss": []}
+
+ def reward(completions, **kw):
+ return [float(len(c)) for c in completions]
+
+ cfg = GRPOConfig(
+ output_dir = str(tmp_path), per_device_train_batch_size = 4, num_generations = 4,
+ max_completion_length = 16, max_steps = 2, logging_steps = 1, save_strategy = "no",
+ report_to = "none", seed = 0, bf16 = torch.cuda.is_bf16_supported(), learning_rate = 1e-4,
+ ) # fmt: skip
+ trainer = GRPOTrainer(model = model, reward_funcs = [reward], args = cfg,
+ train_dataset = Dataset.from_list(rows), processing_class = tok) # fmt: skip
+ # TRL >= 0.24 generates in _generate_single_turn; older TRL only has _generate_and_score_completions.
+ hook = (
+ "_generate_single_turn"
+ if hasattr(trainer, "_generate_single_turn")
+ else "_generate_and_score_completions"
+ )
+ gen = getattr(trainer, hook)
+
+ def recorded(*a, **k):
+ before = _Stats(model)().get("replays", 0)
+ out = gen(*a, **k)
+ seen["replays"].append(_Stats(model)().get("replays", 0) - before)
+ seen["buffers_at_loss"].append((_graph_buffers(model), _decode_buffers(model)))
+ return out
+
+ setattr(trainer, hook, recorded)
+ trainer.train()
+ assert len(seen["replays"]) == 2 and all(r > 0 for r in seen["replays"]), seen
+ assert seen["buffers_at_loss"] == [(0, 0), (0, 0)], seen
+ assert _Stats(model)()["disabled"] is None
diff --git a/unsloth/models/_decode_graphs.py b/unsloth/models/_decode_graphs.py
index b6e7fa6178e..ceedcaf26bc 100644
--- a/unsloth/models/_decode_graphs.py
+++ b/unsloth/models/_decode_graphs.py
@@ -1,7 +1,14 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved.
-"""CUDA-graph replay of the native one-token decode step (opt-in: UNSLOTH_DECODE_CUDA_GRAPHS=1).
+"""CUDA-graph replay of the native one-token decode step.
+
+When it runs (decided per call, enabled()): UNSLOTH_DECODE_CUDA_GRAPHS=1 everywhere, =0 nowhere; unset,
+only for the generate() calls an RL trainer makes on the training model (GRPO / RLOO / online DPO /
+GKD ... through rl.py's unwrap_model_for_generation, rl_generation()) on NVIDIA CUDA, not for plain
+model.generate() and not on ROCm / HIP (graph replay there is not verified bitwise; =1 still forces it).
+The decode buffers and graphs of such a call are released when it returns to training: the next
+optimizer step invalidates the graphs anyway, and training gets the memory back.
The eager decode step is host bound (hundreds of small launches per token). It is captured once per
batch size as n_layers + 1 graph segments split at each layer's attention core, which runs eagerly
@@ -27,7 +34,9 @@ import threading
import torch
-ENABLED = os.environ.get("UNSLOTH_DECODE_CUDA_GRAPHS", "0") == "1"
+# Programmatic override (tests, harnesses): True / False force graphs on / off, None (default) follows
+# the environment variable read at call time and the RL generation scope (enabled()).
+ENABLED = None
# KV-cache rows are allocated in multiples of this with graphs on.
BUCKET = 256
# Captured steps (one per batch size / autocast state) kept per model.
@@ -35,11 +44,14 @@ MAX_GRAPHS = int(os.environ.get("UNSLOTH_DECODE_GRAPH_MAX", "8"))
__all__ = [
"ENABLED",
+ "enabled",
+ "rl_generation",
"static",
"alloc_decode_buffers",
"decode_step",
"invalidate",
"release",
+ "release_for_training",
"register_attention",
"start_generation",
"end_generation",
@@ -60,8 +72,51 @@ _SUPPORTED_MODEL_TYPES = {"llama", "qwen3"}
_PROJ_NAMES = ("q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj")
+def enabled():
+ """Whether a decode step / prefill on this thread runs (and sizes its buffers) for graph replay."""
+ if ENABLED is not None:
+ return bool(ENABLED)
+ if torch.compiler.is_compiling():
+ # Traced code never replays graphs (decode_step bails too); keep the trace free of env / TLS reads.
+ return False
+ flag = os.environ.get("UNSLOTH_DECODE_CUDA_GRAPHS", "")
+ if flag == "1":
+ return True
+ if flag == "0":
+ return False
+ return _DEFAULT_OK and getattr(_TLS, "rl_depth", 0) > 0
+
+
+def _default_ok():
+ # The RL default is NVIDIA CUDA only: HIP graph replay is not verified bitwise against the eager
+ # step on ROCm (=1 still forces it), and XPU / MPS / CPU never take the graphed step.
+ try:
+ return torch.version.hip is None and torch.cuda.is_available()
+ except Exception:
+ return False
+
+
+_DEFAULT_OK = _default_ok()
+
+
+class rl_generation:
+ """Scope of an RL trainer's generate() call (per thread): graphs default on inside it."""
+
+ __slots__ = ()
+
+ def __enter__(self):
+ _TLS.rl_depth = getattr(_TLS, "rl_depth", 0) + 1
+ return self
+
+ def __exit__(self, *exc):
+ _TLS.rl_depth -= 1
+ return False
+
+
def static():
"""The _StepStatics of a graph-mode step running on this thread, else None (eager)."""
+ if torch.compiler.is_compiling():
+ return None
return getattr(_TLS, "statics", None)
@@ -115,7 +170,8 @@ def alloc_decode_buffers(
global BUFFER_EPOCH, GENERATION_EPOCH
seq_len = K1.shape[-2]
attention_size = n_heads * head_dim
- if not ENABLED:
+ config = getattr(attn, "config", None)
+ if not enabled() or getattr(config, "model_type", None) not in _SUPPORTED_MODEL_TYPES:
attn.paged_attention = torch.empty(
(increment + seq_len + 1, 2, bsz, n_kv_heads, head_dim),
dtype = dtype,
@@ -197,7 +253,7 @@ def resize_decode_buffers(attn, increment, bsz, n_heads, n_kv_heads, head_dim):
attn.paged_attention_K = attn.paged_attention[:, 0]
attn.paged_attention_V = attn.paged_attention[:, 1]
attn.attention.resize_((bsz, n_heads, 1, attn.attention.shape[-1] + increment))
- if ENABLED:
+ if "_unsloth_graph_buffers" in attn.__dict__:
attn.paged_attention[rows:].zero_()
BUFFER_EPOCH += 1
@@ -274,15 +330,32 @@ def invalidate(model):
def release(model):
"""Drops captured steps and the persistent decode buffers (frees their memory)."""
global BUFFER_EPOCH
- for state in _states(model):
- state.clear()
- state.statics.clear()
+ found = False
for module in model.modules():
- if "_unsloth_graph_buffers" in module.__dict__:
- del module.__dict__["_unsloth_graph_buffers"]
+ d = module.__dict__
+ state = d.get("_unsloth_decode_graphs")
+ if state is not None:
+ found = True
+ state.clear()
+ state.statics.clear()
+ if "_unsloth_graph_buffers" in d:
+ found = True
+ del d["_unsloth_graph_buffers"]
for name in _BUFFER_NAMES:
- module.__dict__.pop(name, None)
- BUFFER_EPOCH += 1
+ d.pop(name, None)
+ if found:
+ BUFFER_EPOCH += 1
+
+
+def release_for_training(model):
+ """release(), plus the eager decode buffers the last generate() left on the attention modules:
+ the next prefill allocates fresh ones, so training gets the KV cache memory back."""
+ release(model)
+ for module in model.modules():
+ d = module.__dict__
+ if "paged_attention" in d:
+ for name in _BUFFER_NAMES:
+ d.pop(name, None)
def _version(t):
diff --git a/unsloth/models/llama.py b/unsloth/models/llama.py
index 635f62eba02..3fa400b9030 100644
--- a/unsloth/models/llama.py
+++ b/unsloth/models/llama.py
@@ -543,7 +543,7 @@ def _fast_prepare_inputs_for_generation(
position_ids = original_attention_mask.long().cumsum(-1) - 1
position_ids.masked_fill_(original_attention_mask == 0, 1)
position_ids = position_ids[:, -seq_length:]
- if _decode_graphs.ENABLED:
+ if _decode_graphs.enabled():
# Positions from the mask stay below its length: graphed decode skips a host read.
position_ids._unsloth_position_bound = original_attention_mask.shape[-1]
kwargs["position_ids"] = position_ids
@@ -703,7 +703,7 @@ def LlamaAttention_fast_forward_inference(
hidden_size = self.config.hidden_size
attention_size = n_heads * head_dim
# Graph mode (a captured decode step): no host lengths, the cache slot is on the device.
- static = _decode_graphs.static() if _decode_graphs.ENABLED else None
+ static = _decode_graphs.static()
seq_len = K1.shape[-2]
kv_seq_len = seq_len + 1
@@ -1772,7 +1772,7 @@ def _LlamaModel_fast_forward_inference(
seq_len = past_key_values[0][0].shape[-2]
kv_seq_len = seq_len + 1
- static = _decode_graphs.static() if _decode_graphs.ENABLED else None
+ static = _decode_graphs.static()
if static is not None:
# Captured step: the runner builds this mask per step (_decode_step_mask), outside the graph.
attention_mask = None
@@ -2004,7 +2004,7 @@ def CausalLM_fast_forward(fast_forward_inference):
if past_key_values is not None and len(past_key_values) == 0:
past_key_values = None
if past_key_values is not None and input_ids is not None and input_ids.shape[1] == 1:
- if _decode_graphs.ENABLED and labels is None and shift_labels is None:
+ if labels is None and shift_labels is None and _decode_graphs.enabled():
graphed = _decode_graphs.decode_step(
self, fast_forward_inference, _decode_logits, _decode_step_mask, input_ids,
past_key_values, position_ids, attention_mask,
@@ -3031,7 +3031,9 @@ def unsloth_fast_generate(self, *args, **kwargs):
kwargs["pad_token_id"] = kwargs.pop("pad_token_id", model_eos_token_id)
- if _decode_graphs.ENABLED:
+ # Decided once per call (env / RL generation scope), so the prefill and every decode step agree.
+ graphs = _decode_graphs.enabled()
+ if graphs:
_decode_graphs.start_generation(_generation_max_len(self, args, kwargs))
# Mixed precision autocast.
try:
@@ -3041,9 +3043,13 @@ def unsloth_fast_generate(self, *args, **kwargs):
):
output = self._old_generate(*args, **kwargs)
finally:
- if _decode_graphs.ENABLED:
+ if graphs:
_decode_graphs.end_generation()
- if _decode_graphs.ENABLED and getattr(output, "past_key_values", None) is not None:
+ if graphs and restore_training_mode:
+ # Back to training: the next optimizer step invalidates the graphs anyway; free them and the
+ # decode buffers for training.
+ _decode_graphs.release_for_training(self)
+ elif graphs and getattr(output, "past_key_values", None) is not None:
# The returned cache views the persistent decode buffers: hand them over, so a later
# generate() allocates its own instead of overwriting a cache the caller kept.
_decode_graphs.release(self)
diff --git a/unsloth/models/qwen3.py b/unsloth/models/qwen3.py
index db63772289b..6ff87dad734 100644
--- a/unsloth/models/qwen3.py
+++ b/unsloth/models/qwen3.py
@@ -206,7 +206,7 @@ def Qwen3Attention_fast_forward_inference(
hidden_size = self.config.hidden_size
attention_size = n_heads * head_dim
# Graph mode (a captured decode step): no host lengths, the cache slot is on the device.
- static = _decode_graphs.static() if _decode_graphs.ENABLED else None
+ static = _decode_graphs.static()
seq_len = K1.shape[-2]
kv_seq_len = seq_len + 1
diff --git a/unsloth/models/rl.py b/unsloth/models/rl.py
index 031a1c675c2..bc11ba3fd44 100644
--- a/unsloth/models/rl.py
+++ b/unsloth/models/rl.py
@@ -36,6 +36,7 @@ from unsloth_zoo.log import logger
from unsloth_zoo.logging_utils import PatchRLStatistics
from unsloth_zoo.rl_replacements import RL_REPLACEMENTS
from ..device_type import DEVICE_COUNT, DEVICE_TYPE, clean_gpu_cache
+from . import _decode_graphs
from .rl_replacements import (
_unsloth_get_model_config,
_unsloth_text_configs,
@@ -292,7 +293,10 @@ def PatchRL(FastLanguageModel):
def generate_with_clone(*args, **kwargs):
if generating_model is not unwrapped_model:
kwargs = _caller_sampling_only(generating_model, kwargs)
- out = original_generate(*args, **kwargs)
+ # RL rollouts on the training model: CUDA-graph decode defaults on here
+ # (UNSLOTH_DECODE_CUDA_GRAPHS=0 opts out), off for plain model.generate().
+ with _decode_graphs.rl_generation():
+ out = original_generate(*args, **kwargs)
if isinstance(out, torch.Tensor):
return out.clone()
return out
@@ -303,6 +307,9 @@ def PatchRL(FastLanguageModel):
yield unwrapped_model
finally:
generating_model.generate = original_generate
+ # Back to training: the next optimizer step invalidates the decode graphs, so free
+ # them and their decode buffers (KV cache) for the backward pass now.
+ _decode_graphs.release_for_training(model)
FastLanguageModel.for_training(
model,
use_gradient_checkpointing = use_gradient_checkpointing,