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.

GRPO trainer: follow zoo's torch < 2.12 gate for persistent TMA matmul (#15100)

Daniel Han9f68d57b4e1a
diff --git a/tests/test_grpo_persistent_tma_gate.py b/tests/test_grpo_persistent_tma_gate.py
new file mode 100644
index 00000000000..5b979119ac3
--- /dev/null
+++ b/tests/test_grpo_persistent_tma_gate.py
@@ -0,0 +1,112 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""The GRPO trainer's `triton.enable_persistent_tma_matmul` follows unsloth_zoo's torch < 2.12
+gate (unslothai/unsloth-zoo#2043), so torch 2.10 / 2.11 emit exactly the previous options."""
+
+import ast
+import sys
+import types
+from pathlib import Path
+
+import pytest
+
+torch = pytest.importorskip("torch")
+
+from packaging.version import Version
+
+RL_PY = Path(__file__).resolve().parents[1] / "unsloth" / "models" / "rl.py"
+SOURCE = RL_PY.read_text(encoding = "utf-8")
+KEY = '"triton.enable_persistent_tma_matmul"'
+SM90 = "<all_sm90>"
+
+VERSIONS = [
+ ("2.10.0+cu128", True),
+ ("2.11.0", True),
+ ("2.11.1+cu130", True),
+ ("2.12.0", False),
+ ("2.12.0a0+git1234", False),
+ ("2.14.1+cu130", False),
+ ("3.0.0", False),
+]
+
+
+def _load_gate(torch_version):
+ tree = ast.parse(SOURCE)
+ (node,) = [
+ n
+ for n in tree.body
+ if isinstance(n, ast.FunctionDef) and n.name == "_persistent_tma_matmul_ok"
+ ]
+ ns = {"Version": Version, "torch_version": torch_version}
+ exec(compile(ast.Module(body = [node], type_ignores = []), str(RL_PY), "exec"), ns)
+ return ns["_persistent_tma_matmul_ok"]
+
+
+def _parse(raw):
+ return Version(raw.split("+")[0].split("a")[0].split("b")[0])
+
+
+def _fake_zoo(monkeypatch, version, with_helper):
+ def gate():
+ major, minor = (int(x) for x in version.split(".")[:2])
+ return (major, minor) < (2, 12)
+
+ common = types.ModuleType("unsloth_zoo.temporary_patches.common")
+ if with_helper:
+ common._persistent_tma_matmul_ok = gate
+ patches = types.ModuleType("unsloth_zoo.temporary_patches")
+ patches.common = common
+ zoo = types.ModuleType("unsloth_zoo")
+ zoo.temporary_patches = patches
+ monkeypatch.setitem(sys.modules, "unsloth_zoo", zoo)
+ monkeypatch.setitem(sys.modules, "unsloth_zoo.temporary_patches", patches)
+ monkeypatch.setitem(sys.modules, "unsloth_zoo.temporary_patches.common", common)
+
+
+def _emit(gate_value):
+ # The CUDA options text the GRPO patch builds, run from the live rl.py source.
+ start = SOURCE.index(" tma_matmul = ")
+ end = SOURCE.index(" new_options = base_options + cuda_options", start)
+ block = "if True:\n" + SOURCE[start:end]
+ ns = {
+ "all_sm90": SM90,
+ "_persistent_tma_matmul_ok": lambda: gate_value,
+ "torch_version": Version("2.11.0"),
+ "Version": Version,
+ }
+ exec(block, ns)
+ return ns["cuda_options"]
+
+
[email protected]("version,ok", VERSIONS)
+def test_gate_follows_zoo(monkeypatch, version, ok):
+ _fake_zoo(monkeypatch, version, with_helper = True)
+ assert _load_gate(_parse(version))() is ok
+
+
[email protected]("version,ok", VERSIONS)
+def test_gate_without_zoo_helper_uses_same_cutoff(monkeypatch, version, ok):
+ _fake_zoo(monkeypatch, version, with_helper = False)
+ assert _load_gate(_parse(version))() is ok
+
+
[email protected]("version,ok", VERSIONS)
+def test_gate_matches_real_zoo(monkeypatch, version, ok):
+ common = pytest.importorskip("unsloth_zoo.temporary_patches.common")
+ if not hasattr(common, "_persistent_tma_matmul_ok"):
+ pytest.skip("installed unsloth_zoo predates unslothai/unsloth-zoo#2043")
+ monkeypatch.setattr(torch, "__version__", version)
+ assert common._persistent_tma_matmul_ok() is ok
+ assert _load_gate(_parse(version))() is ok
+
+
+def test_options_keep_sm90_expression_below_2_12():
+ # torch 2.10 / 2.11: the emitted option is unchanged, still the every-card sm90+ check.
+ assert f"{KEY}: {SM90}," in _emit(True)
+
+
+def test_options_disable_tma_from_2_12():
+ out = _emit(False)
+ assert f"{KEY}: False," in out
+ assert SM90 not in out.split(KEY, 1)[1].split("\n", 1)[0]
diff --git a/unsloth/models/rl.py b/unsloth/models/rl.py
index 2412b633b01..364749fb46e 100644
--- a/unsloth/models/rl.py
+++ b/unsloth/models/rl.py
@@ -90,6 +90,17 @@ try:
except Exception:
torch_version = Version("0.0.0")
+
+def _persistent_tma_matmul_ok():
+ # zoo's gate: torch 2.12+ guards every GEMM size once Inductor considers TMA templates
+ # (pytorch/pytorch#172925), so a compiled matmul recompiles per token count.
+ try:
+ from unsloth_zoo.temporary_patches.common import _persistent_tma_matmul_ok as zoo_gate
+ except Exception:
+ return tuple(torch_version.release[:2]) < (2, 12) # 2.12 nightlies count as 2.12
+ return bool(zoo_gate())
+
+
try:
from transformers import __version__ as _transformers_version_raw
transformers_version = Version(_transformers_version_raw)
@@ -3744,8 +3755,10 @@ def _patch_trl_rl_trainers_impl(trainer_file = "grpo_trainer"):
'(__import__("unsloth.device_type", fromlist = ["cuda_visible_capabilities"])'
".cuda_visible_capabilities())"
)
+ # The sm90+ check only applies where zoo would request TMA at all; otherwise emit False.
+ tma_matmul = all_sm90 if _persistent_tma_matmul_ok() else "False"
cuda_options = f"""
- "triton.enable_persistent_tma_matmul": {all_sm90},"""
+ "triton.enable_persistent_tma_matmul": {tma_matmul},"""
# cutlass options were added in PyTorch 2.8.0.
if torch_version >= Version("2.8.0"):
cuda_options += f"""