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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
GRPO PrefixGrouper: fit the flex kernel on 101 KB shared-memory GPUs and stop its silent eager fallback (#15854)
Daniel Han98c311426fb3
diff --git a/tests/test_prefix_grouper_compile_check.py b/tests/test_prefix_grouper_compile_check.pynew file mode 100644index 00000000000..6ce84ca5eda--- /dev/null+++ b/tests/test_prefix_grouper_compile_check.py@@ -0,0 +1,350 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved.++"""PrefixGrouper's one-time strict compile check.++unsloth_zoo sets dynamo's suppress_errors, so a flex kernel that fails to compile silently runs+eager flex_attention, which materialises the full T x T scores. The first compiled call per setup runs+with suppress_errors off, plus a forward + backward on copies of its inputs; a failure turns+PrefixGrouper off for the process.+"""++import importlib.util+import pathlib+import sys+import types++import pytest++torch = pytest.importorskip("torch")+flex = pytest.importorskip("torch.nn.attention.flex_attention")++UTILS = pathlib.Path(__file__).resolve().parents[1] / "unsloth" / "utils"+PKG = "_pg_check_pkg_under_test"+++def _load():+ """prefix_grouper.py + its kernel under a throwaway package (no full unsloth import)."""+ pkg = types.ModuleType(PKG)+ pkg.__path__ = [str(UTILS)]+ names = (PKG, f"{PKG}.prefix_grouper_kernel", f"{PKG}.prefix_grouper")+ sys.modules[PKG] = pkg+ try:+ name = f"{PKG}.prefix_grouper"+ spec = importlib.util.spec_from_file_location(name, UTILS / "prefix_grouper.py")+ module = importlib.util.module_from_spec(spec)+ sys.modules[name] = module+ spec.loader.exec_module(module)+ kernel = sys.modules[f"{PKG}.prefix_grouper_kernel"]+ finally:+ for n in names:+ sys.modules.pop(n, None)+ return module, kernel+++def _cpu_flex(q, k, v, **kwargs):+ """Eager flex forward; CPU flex has no backward, so grads flow through a zero-weighted sum."""+ if q.requires_grad:+ # The real kernel saves the block mask and the mask_mod's label tensors for backward.+ bm = kwargs["block_mask"]+ cells = [c.cell_contents for c in (bm.mask_mod.__closure__ or ())]+ saved = [x for x in (*bm.as_tuple(), *cells) if isinstance(x, torch.Tensor)]+ if any(x.is_inference() for x in saved):+ raise RuntimeError("Inference tensors cannot be saved for backward.")+ out = flex.flex_attention(q.detach(), k.detach(), v.detach(), **kwargs)+ if q.requires_grad:+ out = out + 0 * (q.sum() + k.sum() + v.sum())+ return out+++def mods(monkeypatch):+ monkeypatch.setenv("UNSLOTH_GRPO_PREFIX_GROUPER", "1")+ monkeypatch.setenv("UNSLOTH_GRPO_SEQ_PACKING", "1")+ monkeypatch.delenv("UNSLOTH_GRPO_PREFIX_GROUPER_COMPILE_CHECK", raising = False)+ config = torch._dynamo.config+ for name in ("recompile_limit", "accumulated_recompile_limit", "suppress_errors"):+ if hasattr(config, name):+ monkeypatch.setattr(config, name, getattr(config, name))+ config.suppress_errors = True # what unsloth_zoo sets+ pg, kernel = _load()+ calls = {"flex": 0, "strict": [], "mask": 0, "shapes": [], "grad": []}++ def eager_flex(+ *args,+ kernel_options = None,+ **kwargs,+ ):+ calls["flex"] += 1+ calls["strict"].append(torch._dynamo.config.suppress_errors)+ calls["shapes"].append(tuple(tuple(x.shape) for x in args[:3]))+ calls["grad"].append(args[0].requires_grad)+ return _cpu_flex(*args, **kwargs)++ def eager_mask(*args, **kwargs):+ calls["mask"] += 1+ return flex.create_block_mask(*args, **kwargs)++ monkeypatch.setattr(kernel, "_flex_attention_compiled", eager_flex)+ monkeypatch.setattr(kernel, "_create_block_mask_compiled", eager_mask)+ return pg, kernel, calls+++def _qkv(+ T,+ H = 4,+ KVH = 2,+ D = 16,+ seed = 0,+):+ g = torch.Generator().manual_seed(seed)+ return (+ torch.randn(1, T, H, D, generator = g),+ torch.randn(1, T, KVH, D, generator = g),+ torch.randn(1, T, KVH, D, generator = g),+ )+++def _seg(kernel, spec = ((20, [7, 13, 5]), (11, [9, 4]))):+ seg, _ = kernel.build_seg_info_multigroup([(p, list(r)) for p, r in spec], torch.device("cpu"))+ return seg+++def test_success_runs_the_check_once_and_keeps_numerics(mods, capsys):+ pg, kernel, calls = mods+ seg = _seg(kernel)+ Q, K, V = _qkv(seg.T)+ rng = torch.get_rng_state()+ out = kernel.flex_shared_prefix_attention(Q, K, V, seg)+ # First call: the real call, then a grad forward on copies, both under strict mode and with the+ # real shapes (so the compiled graphs are the ones later calls reuse).+ assert calls["strict"] == [False, False]+ assert calls["grad"] == [False, True]+ assert len(set(calls["shapes"])) == 1+ assert torch.equal(torch.get_rng_state(), rng) # the check draws no random numbers+ assert torch._dynamo.config.suppress_errors is True+ kernel.clear_block_mask_cache()+ again = kernel.flex_shared_prefix_attention(Q, K, V, seg)+ assert calls["flex"] == 3 and calls["strict"][-1] is True # no re-check+ assert torch.equal(out, again)+ assert pg.prefix_grouper_enabled() is True+ assert kernel.compile_check_failed() is None+ assert capsys.readouterr().out == ""++ # Same output as with the check switched off.+ kernel._COMPILE_CHECKED.clear()+ kernel._COMPILE_CHECK_ON = False+ kernel.clear_block_mask_cache()+ assert torch.equal(kernel.flex_shared_prefix_attention(Q, K, V, seg), out)+++def test_first_call_under_inference_mode(mods):+ """The trainer's first PrefixGrouper call is the no-grad logprob pass under inference_mode."""+ pg, kernel, calls = mods+ seg = _seg(kernel)+ Q, K, V = _qkv(seg.T)+ with torch.inference_mode():+ out = kernel.flex_shared_prefix_attention(Q, K, V, seg)+ assert kernel.compile_check_failed() is None and calls["flex"] == 2+ q, k, v = (x.clone().requires_grad_(True) for x in (Q, K, V))+ kernel.flex_shared_prefix_attention(q, k, v, seg).sum().backward()+ assert torch.equal(kernel.flex_shared_prefix_attention(Q, K, V, seg), out)+++def test_new_head_layout_is_checked_once(mods):+ pg, kernel, calls = mods+ seg = _seg(kernel)+ kernel.flex_shared_prefix_attention(*_qkv(seg.T), seg)+ kernel.flex_shared_prefix_attention(*_qkv(seg.T, H = 8, KVH = 8, D = 32), seg)+ kernel.flex_shared_prefix_attention(*_qkv(seg.T, H = 8, KVH = 8, D = 32), seg)+ assert calls["flex"] == 2 + 2 + 1+ assert all(kernel._COMPILE_CHECKED.values()) and len(kernel._COMPILE_CHECKED) == 2+++def test_compile_failure_turns_prefix_grouper_off_once(mods, monkeypatch, capsys):+ pg, kernel, calls = mods++ def broken(*args, **kwargs):+ calls["flex"] += 1+ raise RuntimeError(+ "Triton Error: out of resource: shared memory, Required: 104448, Hardware limit: 101376"+ )++ monkeypatch.setattr(kernel, "_flex_attention_compiled", broken)+ seg = _seg(kernel)+ Q, K, V = _qkv(seg.T)+ with pytest.raises(kernel.PrefixGrouperCompileError):+ kernel.flex_shared_prefix_attention(Q, K, V, seg)+ out = capsys.readouterr().out+ assert out.count("\n") == 1 and "PrefixGrouper is off" in out and "104448" in out+ assert pg.prefix_grouper_enabled() is False+ assert torch._dynamo.config.suppress_errors is True # patch restored after the failure+ # One retry with one-stage tiles, then later calls fail fast without a re-check or new log.+ with pytest.raises(kernel.PrefixGrouperCompileError):+ kernel.flex_shared_prefix_attention(Q, K, V, seg)+ assert calls["flex"] == 2+ assert capsys.readouterr().out == ""+++def test_shared_memory_overflow_retries_with_one_stage(mods, monkeypatch, capsys):+ """torch 2.7 / 2.8 on 101376 B smem cards: 3-stage tiles overflow, num_stages=1 fits."""+ pg, kernel, calls = mods+ stages = []++ def three_stage_overflows(+ *args,+ kernel_options = None,+ **kwargs,+ ):+ stages.append(kernel_options.get("num_stages"))+ if kernel_options.get("num_stages") != 1:+ raise RuntimeError(+ "No valid triton configs. OutOfResources: out of resource: shared memory"+ )+ return _cpu_flex(*args, **kwargs)++ monkeypatch.setattr(kernel, "_flex_attention_compiled", three_stage_overflows)+ seg = _seg(kernel)+ Q, K, V = _qkv(seg.T)+ out = kernel.flex_shared_prefix_attention(Q, K, V, seg)+ assert stages == [None, 1, 1]+ assert pg.prefix_grouper_enabled() is True and capsys.readouterr().out == ""+ assert torch.equal(kernel.flex_shared_prefix_attention(Q, K, V, seg), out)+ assert stages[-1] == 1 and len(stages) == 4+++def test_single_block_mask_is_built_eagerly(mods):+ """torch 2.7 Inductor fails when the first compiled mask is a single 128 block."""+ pg, kernel, calls = mods+ seg = _seg(kernel)+ assert seg.T_pad == 128+ kernel.get_block_mask(seg, torch.device("cpu"))+ assert calls["mask"] == 0+ kernel.get_block_mask(_seg(kernel, ((100, [30, 40]),)), torch.device("cpu"))+ assert calls["mask"] == 1+++def test_backward_compile_failure_is_caught(mods, monkeypatch):+ pg, kernel, calls = mods++ class _Boom(torch.autograd.Function):+ @staticmethod+ def forward(ctx, x):+ return x.clone()++ @staticmethod+ def backward(ctx, g):+ raise RuntimeError("backward kernel failed to compile")++ def fwd_ok_bwd_broken(+ *args,+ kernel_options = None,+ **kwargs,+ ):+ return _Boom.apply(_cpu_flex(*args, **kwargs))++ monkeypatch.setattr(kernel, "_flex_attention_compiled", fwd_ok_bwd_broken)+ seg = _seg(kernel)+ with pytest.raises(kernel.PrefixGrouperCompileError):+ kernel.flex_shared_prefix_attention(*_qkv(seg.T), seg)+ assert pg.prefix_grouper_enabled() is False+++def test_real_dynamo_failure_is_silent_without_the_check(mods, monkeypatch):+ """A backend failure is swallowed by suppress_errors on a plain call but caught by the check."""+ pg, kernel, calls = mods++ def failing_backend(gm, example_inputs):+ raise RuntimeError("simulated inductor codegen failure")++ compiled = torch.compile(flex.flex_attention, backend = failing_backend, dynamic = True)++ def via_dynamo(+ *args,+ kernel_options = None,+ **kwargs,+ ):+ return compiled(*args, **kwargs)++ torch._dynamo.reset()+ monkeypatch.setattr(kernel, "_flex_attention_compiled", via_dynamo)+ seg = _seg(kernel)+ Q, K, V = _qkv(seg.T)+ # Base behaviour: the failure is silent (eager fallback) when the check is off.+ kernel._COMPILE_CHECK_ON = False+ kernel.flex_shared_prefix_attention(Q, K, V, seg)+ assert kernel.compile_check_failed() is None+ kernel._COMPILE_CHECK_ON = True+ torch._dynamo.reset()+ with pytest.raises(kernel.PrefixGrouperCompileError):+ kernel.flex_shared_prefix_attention(Q, K, V, seg)+ assert "simulated inductor codegen failure" in kernel.compile_check_failed()+ assert pg.prefix_grouper_enabled() is False+ assert torch._dynamo.config.suppress_errors is True+ torch._dynamo.reset()+++def test_oom_in_the_check_is_not_cached(mods, monkeypatch):+ pg, kernel, calls = mods+ state = {"n": 0}++ def oom_once(+ *args,+ kernel_options = None,+ **kwargs,+ ):+ state["n"] += 1+ if state["n"] == 1:+ raise torch.cuda.OutOfMemoryError("CUDA out of memory")+ return _cpu_flex(*args, **kwargs)++ monkeypatch.setattr(kernel, "_flex_attention_compiled", oom_once)+ seg = _seg(kernel)+ with pytest.raises(torch.cuda.OutOfMemoryError):+ kernel.flex_shared_prefix_attention(*_qkv(seg.T), seg)+ assert pg.prefix_grouper_enabled() is True+ kernel.flex_shared_prefix_attention(*_qkv(seg.T), seg)+ assert kernel.compile_check_failed() is None+++def test_eager_path_skips_the_check(mods):+ pg, kernel, calls = mods+ seg = _seg(kernel)+ kernel.flex_shared_prefix_attention(*_qkv(seg.T), seg, compiled = False)+ assert calls["flex"] == 0 and not kernel._COMPILE_CHECKED+++def test_kill_switch(monkeypatch):+ monkeypatch.setenv("UNSLOTH_GRPO_PREFIX_GROUPER_COMPILE_CHECK", "0")+ pg, kernel = _load()+ assert kernel._COMPILE_CHECK_ON is False+++def test_oom_while_compiling_is_not_cached(mods, monkeypatch):+ """dynamo wraps an OOM raised while compiling in BackendCompilerFailed: still transient."""+ pg, kernel, calls = mods+ state = {"n": 0}++ def oom_backend(gm, example_inputs):+ state["n"] += 1+ if state["n"] == 1:+ raise torch.cuda.OutOfMemoryError("CUDA out of memory")+ return gm.forward++ compiled = torch.compile(flex.flex_attention, backend = oom_backend)++ def flex_oom_once(+ *args,+ kernel_options = None,+ **kwargs,+ ):+ return compiled(*args, **kwargs)++ monkeypatch.setattr(kernel, "_flex_attention_compiled", flex_oom_once)+ seg = _seg(kernel)+ with torch.no_grad(), pytest.raises(torch.cuda.OutOfMemoryError):+ kernel.flex_shared_prefix_attention(*_qkv(seg.T), seg)+ assert state["n"] == 1+ assert pg.prefix_grouper_enabled() is True+ assert kernel.compile_check_failed() is None and not kernel._COMPILE_CHECKED+ assert torch._dynamo.config.suppress_errors is Truediff --git a/unsloth/utils/prefix_grouper.py b/unsloth/utils/prefix_grouper.pyindex 1716784f2c7..3829337b270 100644--- a/unsloth/utils/prefix_grouper.py+++ b/unsloth/utils/prefix_grouper.py@@ -10,37 +10,13 @@# You should have received a copy of the GNU Affero General Public License# along with this program. If not, see <https://www.gnu.org/licenses/>.-"""PrefixGrouper layout builder + completion-logprob extraction for the Unsloth GRPO-packed path (all archs that route through the varlen attention dispatch).--Given the de-padded, LEFT-PACKED input_ids the packed GRPO path already works with, this-module:-- 1. Detects consecutive ``num_generations`` rows that share a prompt prefix (byte-- identical prompt precondition; falls back / returns None otherwise).- 2. Builds ONE flat shared-prefix stream across all groups- ``[ prefix_g0, suf_g0_0 .. suf_g0_{G-1}, prefix_g1, ... ]`` with position_ids that- continue each prefix positionally, plus a ``PrefixSegInfo`` segment table for the- FlexAttention shared-prefix kernel.- 3. Extracts completion logprobs via the index map (completion pos ``j==0`` predicted- from the shared prefix's last token; ``j>=1`` from the preceding suffix token) and- scatters them back into ``[total_rows, W]`` EXACTLY where the full-row packed path- puts them (dest = ``orig_row*L + orig_col``), so grpo_compute_loss / completion_mask- / TIS / metrics are byte-untouched.--The flat stream is built by GATHERING original (row, col) coordinates out of input_ids,-so the grad path's autograd flows to the same embedding rows as today (the shared prefix-now contributes grad once = the sum of the G repeats, which is mathematically identical).--``chunked_hidden_states_selective_log_softmax`` (from unsloth_zoo, passed in) is reused-verbatim over the gathered predicting-position hidden states, so fp32 accumulation,-logit_scale/softcapping/temperature are all preserved.--Env:- UNSLOTH_GRPO_PREFIX_GROUPER=1 engage (default ON; set 0 to disable). Auto-off under vLLM.- UNSLOTH_GRPO_PREFIX_GROUPER_TOKR=1.3 tok_r auto-gate threshold (env-overridable)- UNSLOTH_GRPO_PREFIX_GROUPER_VERIFY=1 first-step self-verify (default ON)- UNSLOTH_GRPO_PREFIX_GROUPER_TOL=0.7 self-verify PASS band (nats)+"""GRPO PrefixGrouper: each group of ``num_generations`` rows with a byte-identical prompt becomes+one flat stream ``[prefix_g, suffix_g_0 .. suffix_g_{G-1}, ...]`` gathered from the original+(row, col) coordinates, so the shared prefix gets grad once (= sum of the G repeats). Completion+logprobs are scattered back to ``orig_row * L + orig_col``, byte-compatible with the packed path.++Env: UNSLOTH_GRPO_PREFIX_GROUPER (default 1, off under vLLM), _TOKR (1.3), _VERIFY (1),+_TOL (0.7 nats), _COMPILE_CHECK (1)."""from __future__ import annotations@@ -53,6 +29,7 @@ import torchfrom .prefix_grouper_kernel import (build_seg_info_multigroup,+ compile_check_failed,PrefixSegInfo,PREFIX_GROUPER_MIN_TORCH,TORCH_SUPPORTS_PREFIX_GROUPER,@@ -75,7 +52,7 @@ _TOL_OK = float(os.environ.get("UNSLOTH_GRPO_PREFIX_GROUPER_TOL", "0.7"))def prefix_grouper_enabled() -> bool:- """Needs seq-packing (reuses its de-pad + scatter) and torch >= 2.7; unsloth_zoo gates on it too."""+ """Needs seq-packing, torch >= 2.7 and a flex kernel that passed its compile check."""global _OFF_LOGGEDif _ENV_ENABLED and not _ENABLED and not _OFF_LOGGED:_OFF_LOGGED = True@@ -85,7 +62,7 @@ def prefix_grouper_enabled() -> bool:"does not compile there); using the packed path.",flush = True,)- return _ENABLED+ return _ENABLED and compile_check_failed() is Nonedef verify_on() -> bool:@@ -111,7 +88,6 @@ class GroupLayout:flat_ids: torch.Tensor # [1, T] (T == seg.T)position_ids: torch.Tensor # [1, T]prefix_seg_info: PrefixSegInfo- # Per completion target token, aligned 1:1.tgt_rows: torch.Tensor # [N] original row indextgt_cols: torch.Tensor # [N] original padded column in that rowtgt_pred: torch.Tensor # [N] flat predicting index (into the T stream)@@ -159,16 +135,10 @@ class GroupLayout:def _build_groups(ids_cpu, real_cols_cpu, cstart_cpu, num_generations, total_rows):- """CPU-side grouping. Returns group dicts or None. Mirrors the packed _pk_* partition.-- A row's REAL tokens are the columns where input != pad. Its completion region (what- the packed path scatters, then completion_mask masks) is the real columns with- original col >= cstart_r, where cstart_r = (L - logits_to_keep) - left_pad_r. The- prompt is the real columns < cstart_r. Within a GRPO group all G rows share the same- prompt => same left_pad => same cstart => the prompt real columns are BYTE-IDENTICAL- across the group (the shared prefix). We require that byte-identity (falls back- otherwise). No prompt-tail special-casing: every suffix token is scattered exactly- like the packed path; completion_mask masks the leading prompt-tail positions.+ """CPU-side grouping mirroring the packed _pk_* partition, or None.++ Prompt = real columns < cstart_r = (L - logits_to_keep) - left_pad_r; every row of a group+ must have a byte-identical prompt. Suffix tokens scatter exactly like the packed path."""G = num_generationsif G is None or G < 2 or total_rows % G != 0:@@ -189,7 +159,6 @@ def _build_groups(ids_cpu, real_cols_cpu, cstart_cpu, num_generations, total_rowcomp_cols_per_row.append(c_cols)if any(len(p) == 0 for p in prompt_toks_per_row):return None- # Require BYTE-IDENTICAL prompts across the group, the shared-prefix precondition.P = len(prompt_toks_per_row[0])if any(len(prompt_toks_per_row[k]) != P for k in range(1, G)):return None@@ -235,14 +204,9 @@ def _build_group_layout_reference(apply_tokr_gate = True,max_segment_cap = None,):- """Build the shared-prefix GroupLayout, or return None to fall back to the packed path.- Token-by-token builder; build_group_layout's fallback for inputs its fast path skips.+ """Token-by-token shared-prefix GroupLayout (build_group_layout's fallback), or None.- input_ids : [B, L]. GRPO's layout is left-padded in the prompt and right-padded in- the completion. Real tokens of a row are a contiguous run not necessarily- starting at column 0.- logits_to_keep : int- left_pad_tokens_per_prompt : [B] long tensor (per-row left-pad count in the prompt).+ input_ids [B, L]: prompt left-padded, completion right-padded."""device = input_ids.devicetotal_rows, L = input_ids.shape@@ -290,7 +254,6 @@ def _build_group_layout_reference(if apply_tokr_gate and tok_r < tokr_threshold():return None # low reuse -> not worth it; use the full-row packed path- # Build flat stream by gathering original (row, col) coordinates.group_specs = [(gm["P"], gm["R_list"]) for gm in groups]seg, group_meta = build_seg_info_multigroup(group_specs, device)@@ -308,11 +271,9 @@ def _build_group_layout_reference(r0 = gm["prefix_row"]prefix_cols = gm["prefix_cols"] # ORIGINAL real prompt columns (len P) of row0plast = meta["prefix_last_index"] # base + P - 1- # Gather the shared prefix once, from row0.flat_src_rows.extend([r0] * P)flat_src_cols.extend(prefix_cols)pos_list.extend(range(P))- # Every suffix token is a completion-region target, scattered like the packed path; completion_mask hides prompt-tail positions.for i, r in enumerate(rows):cols = gm["suf_cols"][i]r_i = len(cols)diff --git a/unsloth/utils/prefix_grouper_kernel.py b/unsloth/utils/prefix_grouper_kernel.pyindex e76560d3767..fbbcfdd60fa 100644--- a/unsloth/utils/prefix_grouper_kernel.py+++ b/unsloth/utils/prefix_grouper_kernel.py@@ -10,8 +10,7 @@# You should have received a copy of the GNU Affero General Public License# along with this program. If not, see <https://www.gnu.org/licenses/>.-"""GRPO PrefixGrouper FlexAttention kernel, prefix stored once; self-contained (no temp dir-dependency); imported lazily only when prefix_seg_info is set, so default-off never imports it."""+"""GRPO PrefixGrouper FlexAttention kernel: shared prefix stored once. Imported lazily."""from __future__ import annotations@@ -56,25 +55,28 @@ if TORCH_SUPPORTS_PREFIX_GROUPER:_raise_dynamo_limit(("accumulated_recompile_limit", "accumulated_cache_size_limit"), 2048)-# dynamic=True is required: T changes almost every GRPO batch, and dynamic=False recompiles per T (~14s each).+# dynamic=True: T changes almost every batch; static recompiles per T (~14 s each)._flex_attention_compiled = torch.compile(flex_attention, dynamic = True)_create_block_mask_compiled = torch.compile(create_block_mask, dynamic = True)-# fp32 needs 32/32 for a ~1e-6 floor (two disjoint key runs stress online softmax); bf16 128/64 is ~5x faster; 128/128 OOMs Triton on B200.+# fp32 needs 32/32 for a ~1e-6 floor; bf16 128/64 is ~5x faster; 128/128 OOMs Triton on B200._FP32_BLOCK_M = int(os.environ.get("PG_FLEX_BLOCK_M", "32"))_FP32_BLOCK_N = int(os.environ.get("PG_FLEX_BLOCK_N", "32"))_BF16_BLOCK_M = int(os.environ.get("PG_FLEX_BF16_BLOCK_M", "128"))_BF16_BLOCK_N = int(os.environ.get("PG_FLEX_BF16_BLOCK_N", "64"))-def _kernel_options_for_dtype(dtype):+def _kernel_options_for_dtype(dtype, one_stage = False):"""Pick the numerically-safe flash block sizes for the Q dtype."""if dtype == torch.bfloat16 or dtype == torch.float16:- return {"BLOCK_M": _BF16_BLOCK_M, "BLOCK_N": _BF16_BLOCK_N}- return {"BLOCK_M": _FP32_BLOCK_M, "BLOCK_N": _FP32_BLOCK_N}+ options = {"BLOCK_M": _BF16_BLOCK_M, "BLOCK_N": _BF16_BLOCK_N}+ else:+ options = {"BLOCK_M": _FP32_BLOCK_M, "BLOCK_N": _FP32_BLOCK_N}+ if one_stage:+ options["num_stages"] = 1+ return options-# Backward-compat constant (fp32 default)._FLEX_KERNEL_OPTIONS = {"BLOCK_M": _FP32_BLOCK_M, "BLOCK_N": _FP32_BLOCK_N}# The compiled backward asserts unless T is a multiple of 128; pad tokens are fully masked and sliced off.@@ -88,27 +90,9 @@ def _pad_len(T: int) -> int:@dataclassclass PrefixSegInfo:- """Per-flat-token segment metadata driving the shared-prefix block mask.-- The label tensors are 1-D of length ``T_pad`` (>= real ``T``, padded up to a multiple- of 128 so the backward kernel compiles). Positions ``[T:T_pad)`` are pad tokens- (group/suffix == _PAD_GROUP) that attend to nothing.-- Attributes- ----------- group_of_kv : LongTensor [T_pad]- Group id per flat token (0..num_groups-1); _PAD_GROUP for pad tokens.- is_prefix : BoolTensor [T_pad]- True iff the token is a prefix token of its group (False for pad).- suffix_of_kv : LongTensor [T_pad]- Suffix id per flat token; -1 for prefix, _PAD_GROUP for pad. Suffix ids are- globally unique across groups.- signature : hashable- Cache key for the block mask (depends only on the labels + T_pad).- T : int- Real flat sequence length (Q/K/V of this length are padded internally).- T_pad : int- Padded length (multiple of 128) at which the block mask is built.+ """Per-token labels for the block mask, padded to T_pad (multiple of 128); pad tokens see nothing.++ suffix_of_kv is -1 for prefix tokens and globally unique across groups."""group_of_kv: torch.Tensor@@ -137,8 +121,7 @@ def _pad_labels(group_of_kv, is_prefix, suffix_of_kv, device):def build_seg_info_from_layout(layout, device: Optional[torch.device] = None) -> PrefixSegInfo:- """Build PrefixSegInfo for ONE group from an object with ``.flat_ids``, ``.P`` and- ``.suffix_slices`` (used by the parity test / oracle helpers)."""+ """PrefixSegInfo for one group (parity test / oracle helper)."""if device is None:device = layout.flat_ids.deviceT = int(layout.flat_ids.shape[1])@@ -168,19 +151,7 @@ def build_seg_info_from_layout(layout, device: Optional[torch.device] = None) ->def build_seg_info_multigroup(group_specs: List[Tuple[int, List[int]]], device: torch.device) -> Tuple[PrefixSegInfo, List[dict]]:- """Build PrefixSegInfo for several shared-prefix groups packed block-diagonally.-- Parameters- ----------- group_specs : list of (P_g, [R_{g,0}, R_{g,1}, ...])- For each group: prefix length and the list of suffix lengths.-- Returns- -------- seg : PrefixSegInfo- group_meta : list of dicts with 'base', 'P', 'prefix_last_index', 'suffix_slices'- (flat offsets), enough to build the completion index map.- """+ """group_specs: [(P_g, [R_g0, R_g1, ...])]. Returns (seg, per-group flat offsets)."""labels, T, T_pad, group_meta, sig_parts = _seg_labels_host(group_specs)group_of_kv, is_prefix, suffix_of_kv = _labels_to_device(labels, T_pad, device)sig = ("multi", T_pad, tuple(sig_parts))@@ -258,18 +229,10 @@ _BLOCK_MASK_CACHE: Dict[Tuple, BlockMask] = {}def _make_mask_mod(group_of_kv, is_prefix, suffix_of_kv):- """Return a mask_mod closure over the (device) label tensors.-- keep(q, kv) = same_group AND- ( is_prefix[kv] AND kv <= q # causal within/ into prefix- OR ( suffix_of_kv[kv] == suffix_of_kv[q] # same suffix ...- AND (not is_prefix[q]) # q is a suffix token ...- AND kv <= q ) ) # ... causal within it-- The single ``kv <= q`` guard on the is_prefix branch gives BOTH prefix-causal- behaviour (a prefix q sees only earlier prefix tokens) AND full-prefix-visibility for- suffixes (every prefix index < every suffix index in a group, so kv <= q always holds- for a suffix q vs a prefix kv of its group), matching the SDPA oracle exactly.+ """Same group and causal, and kv is a prefix token or in q's own suffix.++ Every prefix index precedes every suffix index of its group, so the one ``kv <= q`` guard+ gives prefix-causal and full-prefix visibility for suffixes, matching the SDPA oracle."""def mask_mod(b, h, q_idx, kv_idx):@@ -288,22 +251,15 @@ def get_block_mask(device: torch.device,compile_mask: bool = True,) -> BlockMask:- """Return a cached BlockMask for the segment signature (built once, reused).-- CRITICAL: the block mask is cached and shared across BOTH the no-grad old/ref logprob- forward (which runs under torch.inference_mode) and the grad training forward. If the- mask were first built under inference_mode, its tensors would be INFERENCE tensors that- "cannot be saved for backward" when reused in the grad forward. We therefore build the- mask with inference mode explicitly DISABLED, so the same cached BlockMask is a normal- tensor usable by autograd. (The mask depends only on integer labels; it needs no grad.)- """+ """Cached BlockMask per (signature, device), shared by the no-grad and grad forwards."""key = (seg.signature, str(device))bm = _BLOCK_MASK_CACHE.get(key)if bm is not None:return bm- # Move labels to the Q device (sharded models), outside inference mode: an inference tensor- # captured by mask_mod could not be saved for backward.+ # Outside inference mode: the no-grad pass builds it first, and backward must save it.+ # torch 2.7 Inductor emits a ZeroDivisionError when the first compiled mask is one 128 block.+ compile_mask = compile_mask and seg.T_pad > _PAD_MULTIPLEbuilder = _create_block_mask_compiled if compile_mask else create_block_maskwith torch.inference_mode(False):mask_mod = _make_mask_mod(@@ -317,7 +273,6 @@ def get_block_mask(KV_LEN = seg.T_pad,device = device,)- # FIFO bound: GRPO lengths change nearly every step, so evict the oldest to cap GPU pins.if len(_BLOCK_MASK_CACHE) >= 8:_BLOCK_MASK_CACHE.pop(next(iter(_BLOCK_MASK_CACHE)))_BLOCK_MASK_CACHE[key] = bm@@ -337,7 +292,18 @@ def _pad_qkv_seq(x: torch.Tensor, T_pad: int) -> torch.Tensor:return torch.cat([x, pad], dim = 2)-def _run_flex(q, k, v, block_mask, enable_gqa, scale, compiled, T, T_pad):+def _run_flex(+ q,+ k,+ v,+ block_mask,+ enable_gqa,+ scale,+ compiled,+ T,+ T_pad,+ one_stage = False,+):"""Pad q/k/v to T_pad, run flex, slice the output back to T. q/k/v: [B,H,T,D]."""qp = _pad_qkv_seq(q, T_pad)kp = _pad_qkv_seq(k, T_pad)@@ -350,10 +316,9 @@ def _run_flex(q, k, v, block_mask, enable_gqa, scale, compiled, T, T_pad):block_mask = block_mask,enable_gqa = enable_gqa,scale = scale,- kernel_options = _kernel_options_for_dtype(qp.dtype),+ kernel_options = _kernel_options_for_dtype(qp.dtype, one_stage),)else:- # Eager path (fp64 parity): dense scores, no kernel_options.out = flex_attention(qp,kp,@@ -365,6 +330,90 @@ def _run_flex(q, k, v, block_mask, enable_gqa, scale, compiled, T, T_pad):return out[:, :, :T, :]+class PrefixGrouperCompileError(RuntimeError):+ pass+++# unsloth_zoo's suppress_errors turns a failed compile into a silent eager flex fallback that+# materialises T x T scores (torch 2.6 codegen bugs, torch <= 2.8 tiles on 101376 B smem cards).+_COMPILE_CHECKED: Dict[Tuple, bool] = {}+# Setups whose 3-stage tiles overflow shared memory (sm86 / sm89 / sm120 on torch 2.7 / 2.8).+_ONE_STAGE_KEYS: set = set()+_COMPILE_FAILURE: Optional[str] = None+_CHECK_ENV = os.environ.get("UNSLOTH_GRPO_PREFIX_GROUPER_COMPILE_CHECK", "1")+_COMPILE_CHECK_ON = _CHECK_ENV.lower() not in ("0", "false", "no", "off")+++def compile_check_failed() -> Optional[str]:+ return _COMPILE_FAILURE+++def _root_exception(exc: BaseException) -> BaseException:+ root = exc+ for _ in range(8): # BackendCompilerFailed wraps the inductor / Triton error+ inner = getattr(root, "inner_exception", None) or root.__cause__+ if inner is None or inner is root:+ break+ root = inner+ return root+++def _compile_failure_reason(root: BaseException) -> str:+ lines = [+ line.strip()+ for line in str(root).splitlines()+ if line.strip()+ and not line.lstrip().startswith(("Set TORCHDYNAMO_VERBOSE", "For even more"))+ ]+ return f"{type(root).__name__}: {lines[0][:200] if lines else ''}"+++@torch._dynamo.disable+def _checked_first_call(q, k, v, seg, block_mask, enable_gqa, scale, T, T_pad, key):+ """Real call plus fwd + bwd on detached copies, strict, so later calls reuse those graphs."""+ global _COMPILE_FAILURE++ def strict_calls(one_stage):+ nonlocal block_mask+ with torch._dynamo.config.patch(suppress_errors = False):+ if block_mask is None:+ block_mask = get_block_mask(seg, q.device, compile_mask = True)+ out = _run_flex(q, k, v, block_mask, enable_gqa, scale, True, T, T_pad, one_stage)+ with torch.inference_mode(False), torch.enable_grad():+ qc, kc, vc = (x.detach().clone().requires_grad_(True) for x in (q, k, v))+ oc = _run_flex(qc, kc, vc, block_mask, enable_gqa, scale, True, T, T_pad, one_stage)+ torch.autograd.grad(oc.float().sum(), (qc, kc, vc))+ return out++ try:+ try:+ out = strict_calls(False)+ except torch.cuda.OutOfMemoryError:+ raise+ except Exception as exc:+ if "out of resource" not in str(_root_exception(exc)):+ raise+ out = strict_calls(True)+ _ONE_STAGE_KEYS.add(key)+ except torch.cuda.OutOfMemoryError:+ raise # transient: not cached, callers fall back+ except Exception as exc:+ root = _root_exception(exc)+ if isinstance(root, torch.cuda.OutOfMemoryError):+ raise root from exc+ reason = _compile_failure_reason(root)+ _COMPILE_CHECKED[key] = False+ _COMPILE_FAILURE = reason+ print(+ f"Unsloth: GRPO PrefixGrouper is off: its flex attention kernel does not compile with "+ f"torch {torch.__version__} on this GPU ({reason}); using the packed path.",+ flush = True,+ )+ raise PrefixGrouperCompileError(reason) from None+ _COMPILE_CHECKED[key] = True+ return out++def flex_shared_prefix_attention(Q: torch.Tensor,K: torch.Tensor,@@ -374,23 +423,9 @@ def flex_shared_prefix_attention(block_mask: Optional[BlockMask] = None,compiled: bool = True,) -> torch.Tensor:- """Shared-prefix attention via FlexAttention.-- Parameters- ----------- Q, K, V : Tensor [1, T, n_heads, head_dim]- (Q has n_heads, K/V have n_kv_heads for GQA).- prefix_seg_info : PrefixSegInfo- scale : optional float, softmax scale (defaults to 1/sqrt(head_dim)).- block_mask : optional precomputed BlockMask (else built/cached from seg info).-- Returns- -------- Tensor [1, T, n_heads, head_dim], identical semantics to the SDPA oracle branch.- """+ """Q [1, T, n_heads, D], K / V [1, T, n_kv_heads, D] -> [1, T, n_heads, D]."""assert Q.dim() == 4 and Q.shape[0] == 1, f"expected [1,T,H,D], got {tuple(Q.shape)}"device = Q.device- # FlexAttention wants [B, H, T, D].q = Q.transpose(1, 2) # [1, n_heads, T, D]k = K.transpose(1, 2) # [1, n_kv_heads, T, D]v = V.transpose(1, 2)@@ -402,11 +437,20 @@ def flex_shared_prefix_attention(T_pad = prefix_seg_info.T_padassert T == prefix_seg_info.T, f"Q length {T} != seg.T {prefix_seg_info.T}"- if block_mask is None:- block_mask = get_block_mask(prefix_seg_info, device, compile_mask = compiled)-- out = _run_flex(q, k, v, block_mask, enable_gqa, scale, compiled, T, T_pad)- # Back to [1, T, n_heads, D].+ out = None+ if compiled:+ if _COMPILE_FAILURE is not None:+ raise PrefixGrouperCompileError(_COMPILE_FAILURE)+ key = (str(device), q.dtype, n_heads, n_kv, q.shape[3], scale)+ if _COMPILE_CHECK_ON and key not in _COMPILE_CHECKED:+ out = _checked_first_call(+ q, k, v, prefix_seg_info, block_mask, enable_gqa, scale, T, T_pad, key+ )+ if out is None:+ if block_mask is None:+ block_mask = get_block_mask(prefix_seg_info, device, compile_mask = compiled)+ one_stage = compiled and key in _ONE_STAGE_KEYS+ out = _run_flex(q, k, v, block_mask, enable_gqa, scale, compiled, T, T_pad, one_stage)return out.transpose(1, 2).contiguous()@@ -420,4 +464,6 @@ __all__ = ["get_block_mask","clear_block_mask_cache","flex_shared_prefix_attention",+ "PrefixGrouperCompileError",+ "compile_check_failed",]