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: keep packed forwards off for models that mix tokens across packed rows (#16349)

Shubhankar Tripathy4624f4a39475
diff --git a/tests/test_grpo_metrics_bucket.py b/tests/test_grpo_metrics_bucket.py
index f43462e4542..ef87e974936 100644
--- a/tests/test_grpo_metrics_bucket.py
+++ b/tests/test_grpo_metrics_bucket.py
@@ -29,6 +29,7 @@ HELPERS = {
"_unsloth_grpo_nanmax",
"_unsloth_grpo_flush_metrics",
"_unsloth_grpo_defer_metric",
+ "_unsloth_grpo_refuse_boundary_blind_packing",
}
BATCH, PROMPT, COMPLETION = 2, 3, 4
diff --git a/tests/test_grpo_packing_boundary_blind.py b/tests/test_grpo_packing_boundary_blind.py
new file mode 100644
index 00000000000..753ceddaffc
--- /dev/null
+++ b/tests/test_grpo_packing_boundary_blind.py
@@ -0,0 +1,115 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""GRPO keeps its packed forwards off for models whose layers mix packed rows (packing_boundary_blocker)."""
+
+import ast
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+import torch
+
+SOURCE_PATH = Path(__file__).resolve().parents[1] / "unsloth" / "models" / "rl_replacements.py"
+HELPER = "_unsloth_grpo_refuse_boundary_blind_packing"
+FLAGS = (
+ "_unsloth_seq_packing_nograd_ok",
+ "_unsloth_seq_packing_grad_ok",
+ "_unsloth_prefix_grouper_nograd_disabled",
+)
+
+
[email protected](autouse = True)
+def packing_module(monkeypatch):
+ # The helper imports unsloth.utils.packing; load that file alone (importing unsloth needs a GPU).
+ import importlib.util
+ import sys
+ import types
+
+ path = SOURCE_PATH.parents[1] / "utils" / "packing.py"
+ spec = importlib.util.spec_from_file_location("unsloth.utils.packing", path)
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ for name in ("unsloth", "unsloth.utils"):
+ if name not in sys.modules:
+ stub = types.ModuleType(name)
+ stub.__path__ = []
+ monkeypatch.setitem(sys.modules, name, stub)
+ monkeypatch.setitem(sys.modules, "unsloth.utils.packing", module)
+
+
+def _helper():
+ tree = ast.parse(SOURCE_PATH.read_text(encoding = "utf-8"))
+ node = next(n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name == HELPER)
+ namespace = {}
+ exec(compile(ast.Module(body = [node], type_ignores = []), str(SOURCE_PATH), "exec"), namespace)
+ return namespace[HELPER]
+
+
+def _blind_module(name):
+ return type(name, (torch.nn.Module,), {})()
+
+
+class _Model(torch.nn.Module):
+ def __init__(
+ self,
+ inner,
+ model_type = "llama",
+ ):
+ super().__init__()
+ self.layer = inner
+ self.config = SimpleNamespace(model_type = model_type)
+
+
+def _trainer():
+ return SimpleNamespace(
+ accelerator = SimpleNamespace(unwrap_model = lambda m, keep_fp32_wrapper = False: m)
+ )
+
+
+ "model",
+ [
+ _Model(_blind_module("RecurrentGemmaRglru")),
+ _Model(_blind_module("ZayaCCAProjection")),
+ _Model(_blind_module("DeepseekV4CSACompressor")),
+ _Model(torch.nn.Linear(2, 2), model_type = "deepseek_v4"),
+ ],
+)
+def test_every_packed_path_is_refused_once(model):
+ trainer = _trainer()
+ _helper()(trainer, model)
+ assert model.__dict__["_unsloth_seq_packing_nograd_ok"] is False
+ assert model.__dict__["_unsloth_seq_packing_grad_ok"] is False
+ assert model.__dict__["_unsloth_prefix_grouper_nograd_disabled"] is True
+ # Decided once per model: a later call does not re-walk it.
+ model.__dict__["_unsloth_seq_packing_grad_ok"] = True
+ _helper()(trainer, model)
+ assert model.__dict__["_unsloth_seq_packing_grad_ok"] is True
+
+
+def test_ref_model_scored_first_still_protects_the_policy():
+ # TRL scores a separate ref_model before the policy when the old-logps pass is skipped.
+ trainer = _trainer()
+ ref = _Model(_blind_module("ZayaCCAProjection"))
+ policy = _Model(_blind_module("ZayaCCAProjection"))
+ _helper()(trainer, ref)
+ _helper()(trainer, policy)
+ for model in (ref, policy):
+ assert model.__dict__["_unsloth_seq_packing_grad_ok"] is False
+ assert model.__dict__["_unsloth_seq_packing_nograd_ok"] is False
+
+
+def test_an_ordinary_model_keeps_packing():
+ model = _Model(torch.nn.Linear(2, 2))
+ _helper()(_trainer(), model)
+ assert not any(flag in model.__dict__ for flag in FLAGS)
+
+
+def test_the_generated_trainer_defines_and_calls_the_check():
+ src = SOURCE_PATH.read_text(encoding = "utf-8")
+ assert f'RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource({HELPER}))' in src
+ tree = ast.parse(src)
+ for outer in ("grpo_trainer__get_per_token_logps_and_entropies", "grpo_trainer_compute_loss"):
+ node = next(n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name == outer)
+ assert f"{HELPER}(self, model)" in ast.unparse(node), outer
diff --git a/unsloth/models/rl_replacements.py b/unsloth/models/rl_replacements.py
index 82db7d57c25..fea96bcee4e 100644
--- a/unsloth/models/rl_replacements.py
+++ b/unsloth/models/rl_replacements.py
@@ -1664,6 +1664,28 @@ def _unsloth_grpo_autocast_forced_float32(self):
return forced
+def _unsloth_grpo_refuse_boundary_blind_packing(self, model):
+ """Packed GRPO forwards off, once per model (policy and a separate ref_model), for models whose compressors /
+ recurrences mix packed rows (packing_boundary_blocker). Their leak (~0.1 nats) passes the 0.7 packed
+ self-verify. Zoo's grad PrefixGrouper verifies only against the grad packed forward, so turning that off covers it."""
+ try:
+ unwrapped = self.accelerator.unwrap_model(model, keep_fp32_wrapper = False)
+ if getattr(unwrapped, "_unsloth_packing_boundary_checked", False):
+ return
+ unwrapped._unsloth_packing_boundary_checked = True
+ from unsloth.utils.packing import packing_boundary_blocker
+
+ config = getattr(unwrapped, "config", None)
+ blocker = packing_boundary_blocker(unwrapped, (getattr(config, "model_type", None),))
+ except Exception:
+ return
+ if blocker is None:
+ return
+ unwrapped._unsloth_seq_packing_nograd_ok = False
+ unwrapped._unsloth_seq_packing_grad_ok = False
+ unwrapped._unsloth_prefix_grouper_nograd_disabled = True
+
+
def _unsloth_grpo_autocast(self):
"""Decide the GRPO autocast once and latch it on the trainer. ACCELERATE_MIXED_PRECISION is process wide, so a trainer built later but run first would hand this trainer its precision; args belongs to this trainer."""
if not hasattr(self, "_autocast_enabled"):
@@ -3698,6 +3720,7 @@ def grpo_trainer__get_per_token_logps_and_entropies(function_name, function):
vision_inputs["mm_token_type_ids"] = mm_token_type_ids
unwrapped_model = self.accelerator.unwrap_model(model, keep_fp32_wrapper = False)
+ _unsloth_grpo_refuse_boundary_blind_packing(self, model)
from unsloth_zoo.rl_replacements import (
chunked_hidden_states_selective_log_softmax,
@@ -4956,6 +4979,7 @@ UnslothEfficientGRPO = RL_REPLACEMENTS["UnslothEfficientGRPO"]
grpo_accumulated_loss = RL_REPLACEMENTS["grpo_accumulated_loss"]
RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(_unsloth_grpo_autocast_forced_float32))
RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(_unsloth_grpo_autocast))
+RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(_unsloth_grpo_refuse_boundary_blind_packing))
RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(_unsloth_grpo_autocast_unscored))
RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(_unsloth_grpo_autocast_kwargs))
RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(_unsloth_grpo_support_mismatch))
@@ -5075,6 +5099,8 @@ def grpo_trainer_compute_loss(function_name, function):
sampling_per_token_logps = inputs.get("sampling_per_token_logps", None)
tool_mask = inputs.get("tool_mask", None)
_rollout_logps_as_old = inputs.get("unsloth_rollout_logps_as_old", None) is not None
+ # The logps pass is skipped under vLLM / beta = 0, but the zoo loss still packs.
+ _unsloth_grpo_refuse_boundary_blind_packing(self, model)
_loss_delta = getattr(self.args, "delta", None)
if _rollout_logps_as_old and _loss_delta is None:
# verl's dual-clip default (clip_ratio_c = 3.0).