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: dispatch on width at the remaining lm_head matmul call sites (#8204)
Daniel Han42ed15f4cc5a
diff --git a/tests/_grpo_dispatch_source.py b/tests/_grpo_dispatch_source.pynew file mode 100644index 00000000000..91b1c287193--- /dev/null+++ b/tests/_grpo_dispatch_source.py@@ -0,0 +1,88 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Load the GRPO hidden-states dispatch helpers straight out of the live source.++``_unsloth_grpo_returns_hidden_states`` and ``_unsloth_grpo_hidden_states_signal``+are shipped to the generated trainer as text (``RL_PRE_ITEMS``), so the tests+that ``exec`` a block of ``_get_per_token_logps_and_entropies`` need them in the+namespace exactly as the generated module would have them.++Lifting them with ``ast`` instead of importing ``unsloth`` keeps these tests+CPU-only and import-free, and keeps them tracking the shipped code rather than a+copy of it.+"""++from __future__ import annotations++import ast+import textwrap+from pathlib import Path+++SOURCE_PATH = Path(__file__).resolve().parents[1] / "unsloth" / "models" / "rl_replacements.py"++HELPER_NAMES = (+ "_unsloth_grpo_returns_hidden_states",+ "_unsloth_grpo_hidden_states_signal",+)+++def load_dispatch_helpers():+ """Return ``{name: function}`` for the helpers, exec'd from the live source."""+ text = SOURCE_PATH.read_text(encoding = "utf-8")+ tree = ast.parse(text, filename = str(SOURCE_PATH))+ wanted = []+ for name in HELPER_NAMES:+ found = [+ node+ for node in tree.body+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name == name+ ]+ if len(found) != 1:+ raise AssertionError(+ f"expected exactly one module-level def {name} in {SOURCE_PATH}, found {len(found)}"+ )+ wanted.append(found[0])++ namespace: dict = {}+ exec(compile(ast.Module(body = wanted, type_ignores = []), str(SOURCE_PATH), "exec"), namespace)+ return {name: namespace[name] for name in HELPER_NAMES}+++def load_padded_loop_source():+ """Dedented source of the padded logprob loop, located structurally.++ The one ``with`` statement inside ``_get_per_token_logps_and_entropies``+ whose direct body holds ``for ... in zipped_inputs``. No text search, so a+ comment quoting the same code cannot match.+ """+ text = SOURCE_PATH.read_text(encoding = "utf-8")+ tree = ast.parse(text, filename = str(SOURCE_PATH))+ functions = [+ node+ for node in ast.walk(tree)+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))+ and node.name == "_get_per_token_logps_and_entropies"+ ]+ if len(functions) != 1:+ raise AssertionError(+ f"expected exactly one def _get_per_token_logps_and_entropies, found {len(functions)}"+ )+ loops = [+ node+ for node in ast.walk(functions[0])+ if isinstance(node, ast.With)+ and any(+ isinstance(stmt, ast.For)+ and isinstance(stmt.iter, ast.Name)+ and stmt.iter.id == "zipped_inputs"+ for stmt in node.body+ )+ ]+ if len(loops) != 1:+ raise AssertionError(f"expected exactly one padded loop, found {len(loops)}")+ segment = ast.get_source_segment(text, loops[0], padded = True)+ if segment is None:+ raise AssertionError("could not recover the padded-loop source segment")+ return textwrap.dedent(segment)diff --git a/tests/_rl_source.py b/tests/_rl_source.pynew file mode 100644index 00000000000..b3e66cc6366--- /dev/null+++ b/tests/_rl_source.py@@ -0,0 +1,73 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Load the GRPO hidden-states forward wrapper out of ``unsloth/models/rl.py``.++Same trick as ``_grpo_dispatch_source``: lift the module-level defs with ``ast``+rather than importing ``unsloth``, so the tests stay CPU-only and import-free+while still tracking the shipped code.+"""++from __future__ import annotations++import ast+import inspect+import logging+import os+from pathlib import Path+++SOURCE_PATH = Path(__file__).resolve().parents[1] / "unsloth" / "models" / "rl.py"++WRAPPER_NAMES = (+ "_module_returns_logits",+ "_grpo_hidden_states_wrap_target",+ "_model_supports_unsloth_return_hidden_states",+ "_drop_forward_kwargs_consumed_positionally",+ "_get_num_logits_to_keep",+ "_warn_grpo_hidden_states_fallback_once",+ "_note_grpo_hidden_states_success",+ "_replace_outputs_logits",+ "_install_grpo_hidden_states_forward_wrapper",+)++# present only once the per-call degradation fix has landed+OPTIONAL_NAMES = ("_note_grpo_hidden_states_success",)++CONSTANT_NAMES = (+ "_UNSLOTH_RETURN_HIDDEN_STATES_SUPPORT_MARKER",+ "_UNSLOTH_GRPO_HIDDEN_STATES_WRAPPED_ATTR",+ "_UNSLOTH_GRPO_HIDDEN_STATES_WARNING_ATTR",+ "_UNSLOTH_GRPO_HIDDEN_STATES_DEGRADED_ATTR",+)+++def load_rl_wrapper(names = WRAPPER_NAMES):+ """Return ``{name: object}`` for the wrapper helpers, exec'd from live source."""+ text = SOURCE_PATH.read_text(encoding = "utf-8")+ tree = ast.parse(text, filename = str(SOURCE_PATH))++ wanted = []+ for node in tree.body:+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name in names:+ wanted.append(node)+ elif isinstance(node, ast.Assign) and any(+ isinstance(t, ast.Name) and t.id in CONSTANT_NAMES for t in node.targets+ ):+ wanted.append(node)++ found = {+ node.name for node in wanted if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))+ }+ missing = set(names) - found - set(OPTIONAL_NAMES)+ names = tuple(name for name in names if name in found)+ if missing:+ raise AssertionError(f"missing module-level defs in {SOURCE_PATH}: {sorted(missing)}")++ namespace: dict = {+ "os": os,+ "inspect": inspect,+ "logger": logging.getLogger("unsloth-repro"),+ }+ exec(compile(ast.Module(body = wanted, type_ignores = []), str(SOURCE_PATH), "exec"), namespace)+ return {name: namespace[name] for name in names}diff --git a/tests/test_grpo_accumulated_loss_hidden_states_signal.py b/tests/test_grpo_accumulated_loss_hidden_states_signal.pynew file mode 100644index 00000000000..327a38ce70b--- /dev/null+++ b/tests/test_grpo_accumulated_loss_hidden_states_signal.py@@ -0,0 +1,247 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""The gradient GRPO path must share the no-grad hidden-state signal.++The generated trainer embeds ``unsloth_zoo.grpo_accumulated_loss`` as source.+Zoo's raw-logits branches dispatch on width, which cannot distinguish logits+from hidden states when ``vocab_size == hidden_size``. These tests exercise the+source patch that replaces those comparisons before the function is embedded.+"""++from __future__ import annotations++import ast+import inspect+import re+from pathlib import Path+from types import SimpleNamespace++import pytest+++torch = pytest.importorskip("torch")++SOURCE_PATH = Path(__file__).resolve().parents[1] / "unsloth" / "models" / "rl_replacements.py"+PATCH_HELPER = "_patch_grpo_accumulated_loss_hidden_states_dispatch"+DISPATCH_HELPER = "_unsloth_grpo_returns_hidden_states"+SIGNAL_HELPER = "_unsloth_grpo_hidden_states_signal"+PATTERN_NAME = "_GRPO_HIDDEN_STATES_WIDTH_DISPATCH"+CANDIDATE_PATTERN_NAME = "_GRPO_HIDDEN_STATES_WIDTH_DISPATCH_CANDIDATE"+MARKER = "__UNSLOTH_SUPPORTS_RETURN_HIDDEN_STATES__"+WRAPPED = "_unsloth_grpo_hidden_states_forward_wrapped"+DEGRADED = "_unsloth_grpo_hidden_states_warning_issued"+++def _load_helpers():+ text = SOURCE_PATH.read_text(encoding = "utf-8")+ tree = ast.parse(text, filename = str(SOURCE_PATH))+ body = []+ for node in tree.body:+ if isinstance(node, ast.Assign) and any(+ isinstance(target, ast.Name) and target.id in {PATTERN_NAME, CANDIDATE_PATTERN_NAME}+ for target in node.targets+ ):+ body.append(node)+ elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name in {+ PATCH_HELPER,+ DISPATCH_HELPER,+ SIGNAL_HELPER,+ }:+ body.append(node)+ names = {+ target.id+ for node in body+ if isinstance(node, ast.Assign)+ for target in node.targets+ if isinstance(target, ast.Name)+ }+ names |= {+ node.name for node in body if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))+ }+ expected = {+ PATTERN_NAME,+ CANDIDATE_PATTERN_NAME,+ PATCH_HELPER,+ DISPATCH_HELPER,+ SIGNAL_HELPER,+ }+ assert names == expected, (names, expected)+ namespace = {"inspect": inspect, "re": re}+ exec(compile(ast.Module(body = body, type_ignores = []), str(SOURCE_PATH), "exec"), namespace)+ return namespace+++_HELPERS = _load_helpers()+patch_gradient_source = _HELPERS[PATCH_HELPER]+returns_hidden_states = _HELPERS[DISPATCH_HELPER]+++_FOUR_SITE_SOURCE = """+def grpo_accumulated_loss(unwrapped_model, lm_head, tensors):+ _pack_h, _pack_rh, _h, new_hidden_states_chunk = tensors+ paths = []+ if _pack_h.shape[-1] == lm_head.shape[1]:+ paths.append("hidden")+ else:+ paths.append("raw")+ if _pack_rh.shape[-1] == lm_head.shape[1]:+ paths.append("hidden")+ else:+ paths.append("raw")+ _pg_fn = "hidden"+ if _h.shape[-1] != lm_head.shape[1]:+ _pg_fn = "raw"+ paths.append(_pg_fn)+ if new_hidden_states_chunk.shape[-1] == lm_head.shape[1]:+ paths.append("hidden")+ else:+ paths.append("raw")+ return paths+""".lstrip()+++_NUMERIC_SOURCE = """+def grpo_accumulated_loss(unwrapped_model, lm_head, output, index):+ new_hidden_states_chunk = output+ if new_hidden_states_chunk.shape[-1] == lm_head.shape[1]:+ logits = new_hidden_states_chunk @ lm_head.t()+ else:+ logits = new_hidden_states_chunk+ return torch.gather(+ torch.log_softmax(logits.float(), dim = -1),+ dim = -1,+ index = index.unsqueeze(-1),+ ).squeeze(-1)+""".lstrip()+++def _compile_gradient_function(source):+ namespace = {"torch": torch, DISPATCH_HELPER: returns_hidden_states}+ exec(+ compile(patch_gradient_source(source), "<patched grpo_accumulated_loss>", "exec"), namespace+ )+ return namespace["grpo_accumulated_loss"]+++def _degraded_model():+ return SimpleNamespace(+ forward = lambda *args, **kwargs: None,+ **{WRAPPED: True, DEGRADED: True},+ )+++class _CompiledModel:+ __UNSLOTH_SUPPORTS_RETURN_HIDDEN_STATES__ = True++ def forward(self, *args, **kwargs):+ raise NotImplementedError+++def test_all_four_gradient_dispatches_use_the_explicit_signal():+ patched = patch_gradient_source(_FOUR_SITE_SOURCE)+ assert patched.count(f"{DISPATCH_HELPER}(unwrapped_model,") == 4+ assert ".shape[-1] == lm_head.shape[1]" not in patched+ assert ".shape[-1] != lm_head.shape[1]" not in patched+++def test_degraded_square_logits_take_the_raw_path_at_every_gradient_site():+ function = _compile_gradient_function(_FOUR_SITE_SOURCE)+ square = torch.zeros(1, 2, 8)+ head = torch.zeros(8, 8)+ assert function(_degraded_model(), head, (square,) * 4) == ["raw"] * 4+++def test_compiled_square_hidden_states_stay_on_the_hidden_path():+ function = _compile_gradient_function(_FOUR_SITE_SOURCE)+ square = torch.zeros(1, 2, 8)+ head = torch.zeros(8, 8)+ assert function(_CompiledModel(), head, (square,) * 4) == ["hidden"] * 4+++def test_degraded_square_logits_are_not_projected_twice_in_the_gradient_path():+ function = _compile_gradient_function(_NUMERIC_SOURCE)+ generator = torch.Generator().manual_seed(20260810)+ head = torch.randn(8, 8, generator = generator)+ logits = torch.randn(2, 4, 8, generator = generator)+ index = torch.randint(0, 8, (2, 4), generator = generator)++ actual = function(_degraded_model(), head, logits, index)+ expected = torch.gather(+ torch.log_softmax(logits.float(), dim = -1),+ dim = -1,+ index = index.unsqueeze(-1),+ ).squeeze(-1)+ doubled = torch.gather(+ torch.log_softmax((logits @ head.t()).float(), dim = -1),+ dim = -1,+ index = index.unsqueeze(-1),+ ).squeeze(-1)++ torch.testing.assert_close(actual, expected)+ assert not torch.allclose(actual, doubled, rtol = 1e-3, atol = 1e-3)+++def test_source_patch_fails_loudly_if_zoo_removes_the_width_dispatch_contract():+ source = "def grpo_accumulated_loss():\n return None\n"+ with pytest.raises(RuntimeError, match = "could not find the GRPO gradient"):+ patch_gradient_source(source)+++def test_source_patch_rejects_a_partially_patched_zoo():+ """One surviving match must not license the others to stay width-only.++ A zoo that respells some of its dispatches still leaves at least one the+ strict pattern recognises, which is enough to make `replacements == 0`+ false. The respelled sites would then keep deciding on width alone, back to+ silently wrong gradients for a square lm_head.+ """+ source = _FOUR_SITE_SOURCE.replace(+ " if _pack_h.shape[-1] == lm_head.shape[1]:",+ " if _pack_h.shape[-1] == lm_head.shape[-1]:",+ ).replace(+ " if _pack_rh.shape[-1] != lm_head.shape[1]:",+ " if lm_head.shape[-1] != _pack_rh.shape[-1]:",+ )+ assert source != _FOUR_SITE_SOURCE+ with pytest.raises(RuntimeError, match = r"patched only \d+ of \d+"):+ patch_gradient_source(source)+++def test_source_patch_still_accepts_the_installed_zoo():+ """The stricter guard must not reject the zoo actually installed here."""+ zoo = pytest.importorskip("importlib.util")+ spec = zoo.find_spec("unsloth_zoo")+ if spec is None or spec.origin is None:+ pytest.skip("unsloth_zoo is not installed")+ zoo_source = (Path(spec.origin).parent / "rl_replacements.py").read_text(encoding = "utf-8")+ lines = zoo_source.splitlines()+ functions = [+ node+ for node in ast.walk(ast.parse(zoo_source))+ if isinstance(node, ast.FunctionDef) and node.name == "grpo_accumulated_loss"+ ]+ if len(functions) != 1:+ pytest.skip("this unsloth_zoo has no single grpo_accumulated_loss")+ body = "\n".join(lines[functions[0].lineno - 1 : functions[0].end_lineno])+ patched = patch_gradient_source(body)+ assert DISPATCH_HELPER in patched+++def test_generated_trainer_embeds_the_patched_gradient_function():+ text = SOURCE_PATH.read_text(encoding = "utf-8")+ tree = ast.parse(text, filename = str(SOURCE_PATH))+ calls = [+ node+ for node in ast.walk(tree)+ if isinstance(node, ast.Call)+ and isinstance(node.func, ast.Attribute)+ and node.func.attr == "append"+ and ast.unparse(node.func.value) == "RL_PRE_ITEMS['grpo_trainer']"+ and node.args+ and isinstance(node.args[0], ast.Call)+ and isinstance(node.args[0].func, ast.Name)+ and node.args[0].func.id == PATCH_HELPER+ ]+ assert len(calls) == 1+ assert ast.unparse(calls[0].args[0].args[0]) == "grpo_accumulated_loss"diff --git a/tests/test_grpo_hidden_states_per_call_degradation.py b/tests/test_grpo_hidden_states_per_call_degradation.pynew file mode 100644index 00000000000..1353c313ad8--- /dev/null+++ b/tests/test_grpo_hidden_states_per_call_degradation.py@@ -0,0 +1,193 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Degradation is a property of the CALL, not of the model.++`_install_grpo_hidden_states_forward_wrapper` asks the model for hidden states+and falls back to real logits when it cannot get them. The dispatch helper reads+that outcome right after the forward returns, so the flag it reads has to+describe the call that just finished.++`_warn_grpo_hidden_states_fallback_once` is warn-once bookkeeping: it only ever+sets its flag. Reading it as the per-call outcome makes it mean "ever degraded",+and a forward can degrade on one batch and succeed on the next -- a+*ForConditionalGeneration that splats **kwargs into a vision tower rejects the+extra flags only on the batches carrying pixel_values. With+`vocab_size == hidden_size` the width test cannot correct that, so every later+hidden-state tensor gets routed to the raw-logits helper: the lm_head matmul is+skipped, log probabilities are wrong and the head gets no gradient.++CPU-only: the model here is a few `torch.randn` calls behind a square head.+"""++from __future__ import annotations++import os+import sys+from pathlib import Path++import pytest+++torch = pytest.importorskip("torch")++sys.path.insert(0, str(Path(__file__).resolve().parent))++from _grpo_dispatch_source import load_dispatch_helpers # noqa: E402+from _rl_source import load_rl_wrapper # noqa: E402+++returns_hidden_states = load_dispatch_helpers()["_unsloth_grpo_returns_hidden_states"]+_RL = load_rl_wrapper()+install_wrapper = _RL["_install_grpo_hidden_states_forward_wrapper"]+drop_positional_kwargs = _RL["_drop_forward_kwargs_consumed_positionally"]++DEGRADED = "_unsloth_grpo_hidden_states_degraded"+WARNED = "_unsloth_grpo_hidden_states_warning_issued"+WIDTH = 8 # square lm_head: vocab_size == hidden_size, the ambiguous case+++class _Output:+ def __init__(+ self,+ logits,+ hidden_states = None,+ ):+ self.logits = logits+ self.hidden_states = hidden_states+++class _Head(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.weight = torch.nn.Parameter(torch.zeros(WIDTH, WIDTH))+++class _SquareModel(torch.nn.Module):+ """Degrades only on the batches that carry `pixel_values`."""++ def __init__(self, mode):+ super().__init__()+ self.lm_head = _Head()+ self.mode = mode++ def get_output_embeddings(self):+ return self.lm_head++ def forward(+ self,+ input_ids = None,+ pixel_values = None,+ **kwargs,+ ):+ batch, length = input_ids.shape+ hidden = torch.full((batch, length, WIDTH), 0.5)+ logits = torch.full((batch, length, WIDTH), -0.5)+ if pixel_values is not None:+ if self.mode == "typeerror" and (+ "return_dict" in kwargs or "output_hidden_states" in kwargs+ ):+ raise TypeError(+ "VisionTower.forward() got an unexpected keyword argument 'return_dict'"+ )+ if self.mode == "no_hidden_states":+ return _Output(logits = logits, hidden_states = None)+ return _Output(logits = logits, hidden_states = (hidden,))+++def hidden_states_env():+ previous = os.environ.get("UNSLOTH_RETURN_HIDDEN_STATES")+ os.environ["UNSLOTH_RETURN_HIDDEN_STATES"] = "1"+ try:+ yield+ finally:+ if previous is None:+ os.environ.pop("UNSLOTH_RETURN_HIDDEN_STATES", None)+ else:+ os.environ["UNSLOTH_RETURN_HIDDEN_STATES"] = previous++[email protected]("mode", ["no_hidden_states", "typeerror"])+def test_a_degraded_call_does_not_poison_the_next_call(hidden_states_env, mode):+ model = _SquareModel(mode)+ assert install_wrapper(model) is True+ head = model.lm_head.weight+ ids = torch.zeros(1, 3, dtype = torch.long)++ degraded = model.forward(input_ids = ids, pixel_values = torch.zeros(1, 3, 4, 4))+ assert returns_hidden_states(model, degraded.logits, head) is False++ honoured = model.forward(input_ids = ids)+ assert torch.equal(+ honoured.logits, torch.full((1, 3, WIDTH), 0.5)+ ), "the second call really did hand back hidden states"+ assert returns_hidden_states(model, honoured.logits, head) is True++[email protected]("mode", ["no_hidden_states", "typeerror"])+def test_the_warn_once_flag_stays_sticky_for_logging(hidden_states_env, mode):+ model = _SquareModel(mode)+ install_wrapper(model)+ ids = torch.zeros(1, 3, dtype = torch.long)+ model.forward(input_ids = ids, pixel_values = torch.zeros(1, 3, 4, 4))+ model.forward(input_ids = ids)+ assert getattr(model, WARNED) is True, "the warning must not be re-emitted per call"+ assert getattr(model, DEGRADED) is False, "the per-call flag must track the last call"+++def test_a_forward_run_with_the_flag_off_reports_real_logits():+ model = _SquareModel("no_hidden_states")+ install_wrapper(model)+ previous = os.environ.get("UNSLOTH_RETURN_HIDDEN_STATES")+ os.environ["UNSLOTH_RETURN_HIDDEN_STATES"] = "0"+ try:+ out = model.forward(input_ids = torch.zeros(1, 3, dtype = torch.long))+ finally:+ if previous is None:+ os.environ.pop("UNSLOTH_RETURN_HIDDEN_STATES", None)+ else:+ os.environ["UNSLOTH_RETURN_HIDDEN_STATES"] = previous+ assert torch.equal(out.logits, torch.full((1, 3, WIDTH), -0.5))+ assert returns_hidden_states(model, out.logits, model.lm_head.weight) is False+++def test_the_fallback_retry_does_not_reuse_the_rejected_kwargs(hidden_states_env):+ """The retry has to send the caller's original kwargs.++ `_drop_forward_kwargs_consumed_positionally` returns the caller's dict itself+ when there is nothing to drop, which every GRPO call site hits: they pass+ everything by keyword. Mutating it to add `output_hidden_states`/`return_dict`+ would make the fallback re-send exactly what the model just rejected, so the+ TypeError branch would re-raise instead of degrading.+ """+ model = _SquareModel("typeerror")+ install_wrapper(model)+ kwargs = {+ "input_ids": torch.zeros(1, 3, dtype = torch.long),+ "pixel_values": torch.zeros(1, 3, 4, 4),+ }+ out = model.forward(**kwargs) # must not raise+ assert torch.equal(out.logits, torch.full((1, 3, WIDTH), -0.5))+ assert "return_dict" not in kwargs and "output_hidden_states" not in kwargs+++def test_dropping_positional_kwargs_never_hands_back_the_callers_dict():+ import inspect++ def forward(+ input_ids = None,+ pixel_values = None,+ **kwargs,+ ):+ pass++ signature = inspect.signature(forward)+ for args in ((), (1,)):+ kwargs = {"input_ids": 1, "pixel_values": 2}+ assert drop_positional_kwargs(signature, args, kwargs) is not None+ # the wrapper copies before mutating, so the caller's dict survives a forward+ kwargs = {"input_ids": 1}+ result = drop_positional_kwargs(signature, (), kwargs)+ dict(result)["output_hidden_states"] = True+ assert "output_hidden_states" not in kwargsdiff --git a/tests/test_grpo_hidden_states_signal.py b/tests/test_grpo_hidden_states_signal.pynew file mode 100644index 00000000000..af3c35d6aff--- /dev/null+++ b/tests/test_grpo_hidden_states_signal.py@@ -0,0 +1,392 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""A width comparison cannot answer `vocab_size == hidden_size`.++`_get_per_token_logps_and_entropies` sets UNSLOTH_RETURN_HIDDEN_STATES=1 and+then has to decide, per call site, whether `.logits` came back as hidden states+(apply the lm_head) or as real logits (do not). Comparing the last dim against+`lm_head.shape[1]` answers that for every model whose vocab is wider than its+hidden size, which is nearly all of them -- but a model with+`vocab_size == hidden_size` returns real logits that are exactly as wide as its+hidden states. Those logits pass the width test, go through+`chunked_hidden_states_selective_log_softmax`, and get the lm_head applied a+second time. Nothing raises: the matmul is square, so the run keeps going with+silently wrong GRPO log probabilities. In the packed path the per-row verifier+misreads the width the same way, agrees with the corrupted packed result, and+marks the shape trusted.++`_unsloth_grpo_returns_hidden_states` therefore prefers an explicit signal that+the forward honoured the flag, and only falls back to the width comparison when+there is no signal to read. The signal is not invented here: it is the+`__UNSLOTH_SUPPORTS_RETURN_HIDDEN_STATES__` marker `unsloth_zoo.compiler` writes+onto a generated class, and the+`_unsloth_grpo_hidden_states_forward_wrapped` / `..._warning_issued` pair that+`_install_grpo_hidden_states_forward_wrapper` in `unsloth/models/rl.py` keeps on+models the compiler did not rewrite.++Both halves are covered below: the signal decides the ambiguous case, and an+absent signal leaves today's behaviour untouched. CPU-only, tiny shapes, never+skips beyond torch.+"""++from __future__ import annotations++import contextlib+import os+import sys+from pathlib import Path+from types import SimpleNamespace++import pytest+++torch = pytest.importorskip("torch")++sys.path.insert(0, str(Path(__file__).resolve().parent))+from _grpo_dispatch_source import ( # noqa: E402+ load_dispatch_helpers,+ load_padded_loop_source,+)++_HELPERS = load_dispatch_helpers()+returns_hidden_states = _HELPERS["_unsloth_grpo_returns_hidden_states"]+hidden_states_signal = _HELPERS["_unsloth_grpo_hidden_states_signal"]++MARKER = "__UNSLOTH_SUPPORTS_RETURN_HIDDEN_STATES__"+WRAPPED = "_unsloth_grpo_hidden_states_forward_wrapped"+DEGRADED = "_unsloth_grpo_hidden_states_warning_issued"+++# ── The signal itself ────────────────────────────────────────────────────────+++class _Plain:+ """A model Unsloth never touched: no marker, no wrapper.++ `forward` is here because the signal only descends into children that have+ one, which is how it avoids walking into configs and buffers; every real+ nn.Module qualifies.+ """++ def forward(self, *args, **kwargs):+ raise NotImplementedError+++class _Compiled(_Plain):+ """What unsloth_zoo.compiler emits: the marker lives on the class."""+++setattr(_Compiled, MARKER, True)+++def _wrapped(degraded = False):+ """What _install_grpo_hidden_states_forward_wrapper leaves on the model."""+ model = _Plain()+ setattr(model, WRAPPED, True)+ if degraded:+ setattr(model, DEGRADED, True)+ return model+++def test_an_untouched_model_gives_no_signal():+ assert hidden_states_signal(_Plain()) is None+++def test_the_compiler_marker_is_a_positive_signal():+ assert hidden_states_signal(_Compiled()) is True+++def test_the_marker_is_found_through_the_peft_base_model():+ """PEFT: the marker sits on the class the compiler rewrote, not the wrapper."""+ peft = SimpleNamespace(get_base_model = lambda: _Compiled())+ assert hidden_states_signal(peft) is True+++def test_the_marker_is_found_through_the_ddp_module():+ assert hidden_states_signal(SimpleNamespace(module = _Compiled())) is True+++def test_the_trainer_wrapper_is_a_positive_signal():+ assert hidden_states_signal(_wrapped()) is True+++def test_a_degraded_trainer_wrapper_is_a_negative_signal():+ """The wrapper records that it could not get hidden states, before returning.++ That is the case the width comparison silently gets wrong.+ """+ assert hidden_states_signal(_wrapped(degraded = True)) is False+++def test_the_degradation_is_found_through_the_base_model():+ """The wrapper sets WRAPPED on both objects but DEGRADED only on its target."""+ base = _Plain()+ setattr(base, WRAPPED, True)+ setattr(base, DEGRADED, True)+ outer = SimpleNamespace(base_model = base, forward = lambda: None)+ setattr(outer, WRAPPED, True)+ assert hidden_states_signal(outer) is False+++def test_a_broken_get_base_model_does_not_escape():+ def _raise():+ raise RuntimeError("no base model here")++ model = SimpleNamespace(get_base_model = _raise)+ assert hidden_states_signal(model) is None+++def test_a_self_referencing_wrapper_chain_terminates():+ model = SimpleNamespace(forward = lambda: None)+ model.model = model+ assert hidden_states_signal(model) is None+++# ── The dispatch decision ────────────────────────────────────────────────────+++def _lm_head(vocab, hidden):+ return torch.zeros(vocab, hidden)+++def _tensor(width):+ return torch.zeros(1, 2, width)+++class _Poison:+ """Any attribute read raises, so a test can prove the signal was not consulted."""++ def __getattr__(self, name):+ raise RuntimeError(f"the signal should not have been consulted ({name})")+++def test_a_vocab_wide_tensor_is_never_hidden_states():+ head = _lm_head(17, 8)+ assert returns_hidden_states(_Compiled(), _tensor(17), head) is False+++def test_a_hidden_wide_tensor_is_hidden_states_when_the_width_decides():+ head = _lm_head(17, 8)+ assert returns_hidden_states(_Plain(), _tensor(8), head) is True++[email protected]("width", [8, 17])+def test_the_signal_is_not_consulted_when_the_width_decides(width):+ """vocab_size != hidden_size: the shape is exact, so nothing may override it."""+ head = _lm_head(17, 8)+ assert returns_hidden_states(_Poison(), _tensor(width), head) == (width == 8)+++def test_a_square_lm_head_without_a_signal_keeps_todays_behaviour():+ """The documented fallback: an unsloth_zoo too old to write the marker."""+ head = _lm_head(12, 12)+ assert returns_hidden_states(_Plain(), _tensor(12), head) is True+++def test_a_square_lm_head_with_a_positive_signal_stays_on_the_hidden_path():+ head = _lm_head(12, 12)+ assert returns_hidden_states(_Compiled(), _tensor(12), head) is True+++def test_a_square_lm_head_with_a_negative_signal_takes_the_raw_logits_path():+ """The bug: real logits that are hidden-width because vocab_size == hidden_size."""+ head = _lm_head(12, 12)+ assert returns_hidden_states(_wrapped(degraded = True), _tensor(12), head) is False+++def test_a_negative_signal_cannot_overrule_a_decisive_width_test():+ """vocab_size != hidden_size and the tensor is hidden-wide: it is hidden states.++ Trusting the signal here would send hidden states into the plain+ log-softmax, whose gather indexes with token ids far past the hidden dim.+ """+ head = _lm_head(17, 8)+ assert returns_hidden_states(_wrapped(degraded = True), _tensor(8), head) is True+++# ── End to end through the shipped padded loop ───────────────────────────────++SQUARE = 12 # vocab_size == hidden_size: the width comparison cannot decide+BATCH, SEQ = 2, 7+KEEP, MAX_LEFT_PAD, MULTIPLIER = 3, 1, 1++_BLOCK = compile(load_padded_loop_source(), "<rl_replacements padded loop>", "exec")+++def _eager_hidden_states_log_softmax(+ hidden_states,+ lm_head,+ index,+ chunks = 4,+ logit_scale_multiply = 0.0,+ logit_scale_divide = 0.0,+ logit_softcapping = 0.0,+ temperature = 1.0,+):+ logits = hidden_states.to(lm_head.dtype) @ lm_head.t()+ if logit_scale_multiply != 0.0:+ logits = logits * logit_scale_multiply+ if logit_scale_divide != 0.0:+ logits = logits / logit_scale_divide+ if logit_softcapping != 0.0:+ logits = logit_softcapping * torch.tanh(logits / logit_softcapping)+ return _eager_log_softmax(logits, index, temperature)+++def _eager_log_softmax(+ logits,+ index,+ temperature = 1.0,+ chunks = 4,+):+ logits = logits.to(torch.float32)+ if temperature != 1.0:+ logits = logits / temperature+ return torch.gather(+ torch.log_softmax(logits, dim = -1), dim = -1, index = index.unsqueeze(-1)+ ).squeeze(-1)+++def _load_zoo_helpers():+ """Prefer the shipped helpers; the eager mirrors above keep this CPU-portable."""+ try:+ from unsloth_zoo.rl_replacements import (+ chunked_hidden_states_selective_log_softmax as zoo_hidden,+ chunked_selective_log_softmax as zoo_raw,+ )+ zoo_hidden(+ torch.zeros(1, 2, SQUARE),+ torch.zeros(SQUARE, SQUARE),+ torch.zeros(1, 2, dtype = torch.long),+ 1,+ 0.0,+ 0.0,+ 0.0,+ 1.0,+ )+ zoo_raw(torch.zeros(1, 2, SQUARE), torch.zeros(1, 2, dtype = torch.long), 1.0, 1)+ except Exception:+ return _eager_hidden_states_log_softmax, _eager_log_softmax+ return zoo_hidden, zoo_raw+++_ZOO_HIDDEN, _ZOO_RAW = _load_zoo_helpers()+++class _SquareModel:+ """vocab_size == hidden_size, so both outputs have the same shape."""++ def __init__(self, embedding, lm_head, returns_hidden_states, signal):+ self.embedding = embedding+ self.lm_head = lm_head+ self.returns_hidden_states = returns_hidden_states+ if signal == "compiled":+ # the compiler writes the marker onto the class it generated, so give+ # this instance its own class rather than marking every _SquareModel+ self.__class__ = type("_CompiledSquareModel", (_SquareModel,), {MARKER: True})+ elif signal in ("wrapped", "degraded"):+ setattr(self, WRAPPED, True)+ if signal == "degraded":+ setattr(self, DEGRADED, True)++ def __call__(+ self,+ input_ids = None,+ logits_to_keep = None,+ **kwargs,+ ):+ hidden = self.embedding[input_ids]+ out = hidden if self.returns_hidden_states else hidden @ self.lm_head.t()+ assert out.shape[-1] == SQUARE # the whole point: indistinguishable by width+ return SimpleNamespace(logits = out)+++def _run_padded_loop(*, returns_hidden_states, signal):+ generator = torch.Generator().manual_seed(20260803)+ embedding = torch.randn(SQUARE, SQUARE, generator = generator)+ lm_head = torch.randn(SQUARE, SQUARE, generator = generator)+ input_ids = torch.randint(0, SQUARE, (BATCH, SEQ), generator = generator)+ model = _SquareModel(embedding, lm_head, returns_hidden_states, signal)++ namespace = {+ "torch": torch,+ "os": os,+ **_HELPERS,+ "chunked_hidden_states_selective_log_softmax": _ZOO_HIDDEN,+ "chunked_selective_log_softmax": _ZOO_RAW,+ "device_synchronize": lambda *a, **k: None,+ "_get_inference_mode_context_manager": lambda _model: contextlib.nullcontext(),+ "model": model,+ "unwrapped_model": model,+ "self": SimpleNamespace(_autocast_dtype = torch.float32),+ "pixel_values": None,+ "lm_head": lm_head,+ "zipped_inputs": [+ (input_ids[i : i + 1], torch.ones(1, SEQ, dtype = torch.long)) + (None,) * 6+ for i in range(BATCH)+ ],+ "logits_to_keep": KEEP,+ "max_left_pad": MAX_LEFT_PAD,+ "multiplier": MULTIPLIER,+ "logit_scale_multiply": 0,+ "logit_scale_divide": 0,+ "logit_softcapping": 0,+ "temperature": 1.0,+ "all_logprobs_list": [],+ "logprobs": None,+ }+ exec(_BLOCK, namespace)+ return namespace["logprobs"], embedding, lm_head, input_ids+++def _reference(embedding, lm_head, input_ids):+ """The only correct answer: one lm_head application, then log-softmax."""+ logits = (embedding[input_ids] @ lm_head.t()).to(torch.float32)+ width = KEEP + MAX_LEFT_PAD+ predictions = torch.log_softmax(logits, dim = -1)[:, -(width + 1) : -1, :]+ targets = input_ids[:, -width:]+ return torch.gather(predictions, dim = -1, index = targets.unsqueeze(-1)).squeeze(-1)+++def test_square_lm_head_raw_logits_are_not_run_through_the_lm_head_twice():+ """The regression. Without the signal this returns log_softmax(logits @ W.T).++ Nothing raises, because a square lm_head makes the second matmul legal; the+ run just carries on with wrong log probabilities.+ """+ logprobs, embedding, lm_head, input_ids = _run_padded_loop(+ returns_hidden_states = False, signal = "degraded"+ )+ expected = _reference(embedding, lm_head, input_ids)+ assert logprobs.shape == (BATCH, KEEP + MAX_LEFT_PAD)+ torch.testing.assert_close(logprobs, expected, rtol = 1e-5, atol = 1e-5)+++def test_square_lm_head_double_application_is_actually_detectable():+ """Guard against a vacuous assertion above: the wrong answer must differ."""+ generator = torch.Generator().manual_seed(20260803)+ embedding = torch.randn(SQUARE, SQUARE, generator = generator)+ lm_head = torch.randn(SQUARE, SQUARE, generator = generator)+ input_ids = torch.randint(0, SQUARE, (BATCH, SEQ), generator = generator)+ correct = _reference(embedding, lm_head, input_ids)+ doubled = _reference(embedding @ lm_head.t(), lm_head, input_ids)+ assert not torch.allclose(correct, doubled, rtol = 1e-2, atol = 1e-2)++[email protected]("signal", ["compiled", "wrapped"])+def test_square_lm_head_hidden_states_still_take_the_fused_path(signal):+ logprobs, embedding, lm_head, input_ids = _run_padded_loop(+ returns_hidden_states = True, signal = signal+ )+ expected = _reference(embedding, lm_head, input_ids)+ torch.testing.assert_close(logprobs, expected, rtol = 1e-5, atol = 1e-5)+++def test_square_lm_head_without_a_signal_falls_back_to_the_width_test():+ """No marker and no wrapper: unchanged from before, hidden states still work."""+ logprobs, embedding, lm_head, input_ids = _run_padded_loop(+ returns_hidden_states = True, signal = "none"+ )+ expected = _reference(embedding, lm_head, input_ids)+ torch.testing.assert_close(logprobs, expected, rtol = 1e-5, atol = 1e-5)diff --git a/tests/test_grpo_packed_raw_logits_nograd.py b/tests/test_grpo_packed_raw_logits_nograd.pynew file mode 100644index 00000000000..ee60f317c3c--- /dev/null+++ b/tests/test_grpo_packed_raw_logits_nograd.py@@ -0,0 +1,476 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""The GRPO packed (no-grad) path needs the width guard on both of its call sites.++`_get_per_token_logps_and_entropies` sets UNSLOTH_RETURN_HIDDEN_STATES=1, but+`.logits` only carries hidden states when the forward is Unsloth's generated+one. Any other forward hands back a real [.., vocab] tensor, and sending that+into the lm_head matmul helper raises on the reduction dim.++Both packed call sites (the flattened forward and the first-use verifier below+it) sit inside one `except Exception`, so the raise is swallowed: the batch is+silently dropped back to the padded loop, `_unsloth_seq_packing_nograd_ok` is+pinned False, and a whole packed forward is wasted every step for the rest of+the run. The symptom is therefore not a crash but packing going away, so the+real block is exec'd here against a stub forward that returns vocab logits and+the assertions read the locals the block itself produced.++The verifier runs on the first packed batch of every run, so without the guard+on that second site the packed raw-logits branch would never be reachable at+all. Runs on CPU with tiny shapes and never skips.+"""++from __future__ import annotations++import ast+import sys+import textwrap+from pathlib import Path+from types import SimpleNamespace++import pytest+++torch = pytest.importorskip("torch")++sys.path.insert(0, str(Path(__file__).resolve().parent))+from _grpo_dispatch_source import load_dispatch_helpers # noqa: E402++_DISPATCH_HELPERS = load_dispatch_helpers()++_REPO = Path(__file__).resolve().parents[1]+_SOURCE = _REPO / "unsloth" / "models" / "rl_replacements.py"++VOCAB, HIDDEN = 17, 8+PAD_ID, SEQ_LEN, KEEP = 0, 8, 4+++# ---------------------------------------------------------------------------+# Helpers: the real unsloth_zoo ones when importable, otherwise eager mirrors+# with identical semantics so a runner without unsloth_zoo still exercises the+# same arithmetic.+# ---------------------------------------------------------------------------+++def _fallback_chunked_selective_log_softmax(+ logits,+ index,+ temperature = 1.0,+ chunks = 4,+):+ chunked_logits = torch.chunk(logits.reshape(-1, logits.shape[-1]), chunks = chunks, dim = 0)+ chunked_index = torch.chunk(index.reshape(-1), chunks = chunks, dim = 0)+ all_per_token_logps = []+ for chunk_logits, chunk_index in zip(chunked_logits, chunked_index):+ chunk_logits = chunk_logits.to(torch.float32)+ if temperature != 1.0:+ chunk_logits = chunk_logits / temperature+ selected_logits = torch.gather(+ chunk_logits,+ dim = -1,+ index = chunk_index.unsqueeze(-1),+ ).squeeze(-1)+ logsumexp_values = torch.logsumexp(chunk_logits, dim = -1)+ all_per_token_logps.append(selected_logits - logsumexp_values)+ all_per_token_logps = torch.concat(all_per_token_logps)+ return all_per_token_logps.reshape((logits.shape[0], logits.shape[1]))+++def _fallback_chunked_hidden_states_selective_log_softmax(+ hidden_states,+ lm_head,+ index,+ chunks = 4,+ logit_scale_multiply = 0.0,+ logit_scale_divide = 0.0,+ logit_softcapping = 0.0,+ temperature = 1.0,+):+ flat_hidden_states = hidden_states.reshape(-1, hidden_states.shape[-1])+ chunked_hidden_states = torch.chunk(flat_hidden_states, chunks = chunks, dim = 0)+ chunked_index = torch.chunk(index.reshape(-1), chunks = chunks, dim = 0)+ all_per_token_logps = []+ for chunk_hidden_states, chunk_index in zip(chunked_hidden_states, chunked_index):+ chunk_logits = chunk_hidden_states.to(lm_head.dtype) @ lm_head.t()+ if logit_scale_multiply != 0.0:+ chunk_logits = chunk_logits * logit_scale_multiply+ if logit_scale_divide != 0.0:+ chunk_logits = chunk_logits / logit_scale_divide+ if logit_softcapping != 0.0:+ chunk_logits = logit_softcapping * torch.tanh(chunk_logits / logit_softcapping)+ chunk_logits = chunk_logits.to(torch.float32)+ if temperature != 1.0:+ chunk_logits = chunk_logits / temperature+ selected_logits = torch.gather(+ chunk_logits,+ dim = -1,+ index = chunk_index.unsqueeze(-1),+ ).squeeze(-1)+ logsumexp_values = torch.logsumexp(chunk_logits, dim = -1)+ all_per_token_logps.append(selected_logits - logsumexp_values)+ all_per_token_logps = torch.concat(all_per_token_logps)+ return all_per_token_logps.reshape((hidden_states.shape[0], hidden_states.shape[1]))+++def _fallback_calculate_pad_tokens_in_prompt(input_ids, logits_to_keep, pad_token_id):+ if logits_to_keep >= input_ids.shape[1]:+ raise ValueError("logits_to_keep must be smaller than the sequence length.")+ return (input_ids[:, :-logits_to_keep] == pad_token_id).sum(dim = 1)+++def _fallback_create_completion_attention_mask(+ completion_input_ids, left_pad_tokens_per_prompt, max_left_pad, pad_token_id+):+ completion_len = completion_input_ids.shape[1]+ num_tokens_to_mask = max_left_pad - left_pad_tokens_per_prompt+ indices = torch.arange(completion_len, device = completion_input_ids.device).unsqueeze(0)+ shift_mask = indices >= num_tokens_to_mask.unsqueeze(1)+ return shift_mask & (completion_input_ids != pad_token_id)+++def _resolve_helpers():+ names = (+ "chunked_hidden_states_selective_log_softmax",+ "chunked_selective_log_softmax",+ "create_completion_attention_mask",+ "calculate_pad_tokens_in_prompt",+ )+ fallbacks = {+ "chunked_hidden_states_selective_log_softmax": _fallback_chunked_hidden_states_selective_log_softmax,+ "chunked_selective_log_softmax": _fallback_chunked_selective_log_softmax,+ "create_completion_attention_mask": _fallback_create_completion_attention_mask,+ "calculate_pad_tokens_in_prompt": _fallback_calculate_pad_tokens_in_prompt,+ }+ try:+ import unsloth_zoo.rl_replacements as zoo+ except Exception:+ zoo = None+ return {name: getattr(zoo, name, None) or fallbacks[name] for name in names}+++HELPERS = _resolve_helpers()+_completion_mask_of = HELPERS["create_completion_attention_mask"]+_left_pad_of = HELPERS["calculate_pad_tokens_in_prompt"]+++# ---------------------------------------------------------------------------+# Stub model+# ---------------------------------------------------------------------------+++class _Model(torch.nn.Module):+ """`hidden_states = False` ignores UNSLOTH_RETURN_HIDDEN_STATES and returns+ real [.., vocab] logits; True is Unsloth's generated forward.++ Position-local, so the packed block-diagonal forward and the per-row+ forward agree exactly and the verifier's own tolerance is not what is under+ test. Every call is recorded so a test can pin which sites actually ran.+ """++ def __init__(+ self,+ hidden_states = False,+ vocab = VOCAB,+ hidden = HIDDEN,+ degraded = False,+ ):+ super().__init__()+ torch.manual_seed(0)+ self.emb = torch.nn.Embedding(vocab, hidden)+ self.head = torch.nn.Linear(hidden, vocab, bias = False)+ self.hidden_states = hidden_states+ self.calls = []+ if degraded:+ # what _install_grpo_hidden_states_forward_wrapper in unsloth/models/rl.py+ # leaves behind when it could not get hidden states out of the model+ self._unsloth_grpo_hidden_states_forward_wrapped = True+ self._unsloth_grpo_hidden_states_warning_issued = True++ def forward(+ self,+ input_ids = None,+ position_ids = None,+ attention_mask = None,+ packed_seq_lengths = None,+ use_cache = None,+ **kwargs,+ ):+ self.calls.append(+ SimpleNamespace(+ shape = tuple(input_ids.shape),+ packed = packed_seq_lengths is not None,+ )+ )+ h = torch.tanh(self.emb(input_ids))+ return SimpleNamespace(logits = h if self.hidden_states else self.head(h))+++# ---------------------------------------------------------------------------+# Structural extraction of the packed block+# ---------------------------------------------------------------------------+++def _statement_lists(node):+ for child in ast.walk(node):+ for field in ("body", "orelse", "finalbody"):+ seq = getattr(child, field, None)+ if isinstance(seq, list) and seq and all(isinstance(s, ast.stmt) for s in seq):+ yield seq+++def _named_function(node, name):+ for child in ast.walk(node):+ if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef)) and child.name == name:+ return child+ raise AssertionError(f"function {name} not found in {_SOURCE}")+++def _assigns_none(stmt, name):+ return (+ isinstance(stmt, ast.Assign)+ and len(stmt.targets) == 1+ and isinstance(stmt.targets[0], ast.Name)+ and stmt.targets[0].id == name+ and isinstance(stmt.value, ast.Constant)+ and stmt.value.value is None+ )+++def _guards_with_handler(stmt, handler_name):+ """True if `stmt` is an `if` whose body holds a `try/except ... as <name>`."""+ if not isinstance(stmt, ast.If):+ return False+ return any(+ handler.name == handler_name+ for node in ast.walk(stmt)+ if isinstance(node, ast.Try)+ for handler in node.handlers+ )+++def _packed_block_source():+ """Return the dedented source of the packed no-grad block.++ Located structurally: the statement run inside+ `_get_per_token_logps_and_entropies` that begins with `_pk_result = None`+ and ends with the `if` holding the `except ... as _pk_err` handler. No text+ search, so a comment that happens to quote the same code cannot match.+ """+ text = _SOURCE.read_text(encoding = "utf-8")+ tree = ast.parse(text)+ factory = _named_function(tree, "grpo_trainer__get_per_token_logps_and_entropies")+ inner = _named_function(factory, "_get_per_token_logps_and_entropies")++ found = []+ for seq in _statement_lists(inner):+ start = next(+ (i for i, s in enumerate(seq) if _assigns_none(s, "_pk_result")),+ None,+ )+ if start is None:+ continue+ end = next(+ (j for j in range(start + 1, len(seq)) if _guards_with_handler(seq[j], "_pk_err")),+ None,+ )+ if end is not None:+ found.append((seq[start], seq[end]))+ assert len(found) == 1, f"expected one packed no-grad block, found {len(found)}"++ first, last = found[0]+ lines = text.splitlines(keepends = True)[first.lineno - 1 : last.end_lineno]+ return textwrap.dedent("".join(lines))+++# ---------------------------------------------------------------------------+# Driver+# ---------------------------------------------------------------------------+++def _batch():+ # already left-padded by the caller, uneven pad counts across rows+ return torch.tensor(+ [+ [PAD_ID, PAD_ID, 3, 5, 7, 9, 11, 13],+ [PAD_ID, 2, 4, 6, 8, 10, 12, 14],+ ]+ )+++def _run_packed_block(hidden_states = False, model = None):+ """Exec the real packed + verify block and hand back its locals."""+ if model is None:+ model = _Model(hidden_states = hidden_states)+ lm_head = model.head.weight # [vocab, hidden]+ input_ids = _batch()+ left_pad = _left_pad_of(input_ids, KEEP, PAD_ID)+ max_left_pad = int(left_pad.max())++ namespace = {+ "os": __import__("os"),+ "torch": torch,+ **_DISPATCH_HELPERS,+ "chunked_hidden_states_selective_log_softmax": HELPERS[+ "chunked_hidden_states_selective_log_softmax"+ ],+ "chunked_selective_log_softmax": HELPERS["chunked_selective_log_softmax"],+ "create_completion_attention_mask": HELPERS["create_completion_attention_mask"],+ "calculate_pad_tokens_in_prompt": HELPERS["calculate_pad_tokens_in_prompt"],+ "_get_inference_mode_context_manager": lambda _model: torch.no_grad(),+ "device_synchronize": lambda *args, **kwargs: None,+ "UNSLOTH_ENABLE_LOGGING": False,+ "UNSLOTH_GRPO_SEQ_PACKING_ON": True,+ "UNSLOTH_ZOO_HAS_MASKED_COL_GUARD": True,+ "self": SimpleNamespace(+ processing_class = SimpleNamespace(pad_token_id = PAD_ID),+ _autocast_dtype = torch.bfloat16,+ ),+ "model": model,+ "unwrapped_model": model,+ "lm_head": lm_head,+ "input_ids": input_ids,+ "left_pad_tokens_per_prompt": left_pad,+ "max_left_pad": max_left_pad,+ "logits_to_keep": KEEP,+ "total_rows": input_ids.shape[0],+ "batch_size": input_ids.shape[0],+ "seq_len": input_ids.shape[1],+ "multiplier": 1,+ "pixel_values": None,+ "token_type_ids": None,+ "mm_token_type_ids": None,+ "_pg_skip_pk": False,+ "logit_scale_multiply": 0.0,+ "logit_scale_divide": 0.0,+ "logit_softcapping": 0.0,+ "temperature": 1.0,+ }+ exec(_packed_block_source(), namespace)+ return namespace, model, input_ids, max_left_pad+++def _reference_logprobs(model, input_ids, max_left_pad):+ """Per-row logprobs straight from the model, no packing involved.++ Pads are dropped first, so a row's leading token has no predecessor and+ stays 0, exactly as both the packed scatter and the padded loop leave it.+ """+ width = KEEP + max_left_pad+ out = torch.zeros(input_ids.shape[0], input_ids.shape[1])+ for row in range(input_ids.shape[0]):+ cols = (input_ids[row] != PAD_ID).nonzero(as_tuple = False).squeeze(1)+ real = input_ids[row][cols].unsqueeze(0)+ with torch.no_grad():+ raw = model(input_ids = real).logits.float()+ if model.hidden_states:+ raw = raw @ model.head.weight.t().float()+ logps = torch.log_softmax(raw, dim = -1)[0]+ for j in range(1, real.shape[1]):+ out[row, cols[j]] = logps[j - 1, real[0, j]]+ return out[:, -width:]+++# ---------------------------------------------------------------------------+# Tests+# ---------------------------------------------------------------------------+++def test_packed_path_survives_a_forward_that_returns_real_logits():+ namespace, model, _input_ids, _max_left_pad = _run_packed_block(hidden_states = False)+ assert getattr(model, "_unsloth_seq_packing_nograd_ok", None) is not False, (+ "a packed call site sent raw vocab logits into the lm_head matmul, the "+ "outer handler swallowed the raise and pinned packing off for the run"+ )+ assert namespace["_pk_use"] is True+ assert namespace["_pk_result"] is not None+ assert namespace["_pk_result"].shape == (2, KEEP + 2)++[email protected]("hidden_states", [False, True])+def test_packed_result_matches_the_per_row_logprobs(hidden_states):+ namespace, model, input_ids, max_left_pad = _run_packed_block(hidden_states = hidden_states)+ if not namespace["_pk_use"]:+ pytest.fail("packed path declined the batch, so there is nothing to compare")+ mask = _completion_mask_of(+ input_ids[:, -(KEEP + max_left_pad) :],+ _left_pad_of(input_ids, KEEP, PAD_ID),+ max_left_pad,+ PAD_ID,+ ).float()+ reference = _reference_logprobs(model, input_ids, max_left_pad)+ got = namespace["_pk_result"].detach().float()+ assert torch.allclose(got * mask, reference * mask, atol = 1e-5), (+ got * mask,+ reference * mask,+ )+++def test_square_lm_head_raw_logits_are_routed_by_the_explicit_signal():+ """vocab_size == hidden_size: the width comparison cannot tell them apart.++ Real logits are then hidden-width, so a width-only guard sends them through+ the lm_head a second time. The packed matmul is square, so nothing raises,+ and the per-row verifier misreads the width in exactly the same way, agrees+ with the corrupted packed result and marks the shape trusted. Both call+ sites therefore have to defer to the explicit+ UNSLOTH_RETURN_HIDDEN_STATES signal instead.+ """+ model = _Model(hidden_states = False, vocab = VOCAB, hidden = VOCAB, degraded = True)+ namespace, model, input_ids, max_left_pad = _run_packed_block(model = model)++ assert namespace["_pk_use"] is True+ assert namespace["_pk_ref"] is not None, "the per-row verifier never ran"+ mask = _completion_mask_of(+ input_ids[:, -(KEEP + max_left_pad) :],+ _left_pad_of(input_ids, KEEP, PAD_ID),+ max_left_pad,+ PAD_ID,+ ).float()+ reference = _reference_logprobs(model, input_ids, max_left_pad)+ got = namespace["_pk_result"].detach().float()+ assert torch.allclose(got * mask, reference * mask, atol = 1e-5), (+ got * mask,+ reference * mask,+ )+++def test_square_lm_head_double_application_is_actually_detectable():+ """Guard against the assertion above passing vacuously."""+ model = _Model(hidden_states = False, vocab = VOCAB, hidden = VOCAB)+ input_ids = _batch()+ with torch.no_grad():+ logits = model(input_ids = input_ids).logits.float()+ doubled = logits @ model.head.weight.t().float()+ assert not torch.allclose(+ torch.log_softmax(logits, dim = -1),+ torch.log_softmax(doubled, dim = -1),+ atol = 1e-2,+ )+++def test_first_use_verify_branch_runs_the_per_row_forwards():+ """Without this, the raw-logits test above would never reach the second+ call site: a model already inside the trusted envelope takes the shortcut+ and the verifier never runs."""+ namespace, model, input_ids, _max_left_pad = _run_packed_block(hidden_states = False)++ assert (+ "_pk_ref" in namespace and namespace["_pk_ref"] is not None+ ), "the first-use verify branch never ran, so the verifier call site is untested"+ assert (+ "_pk_diff" in namespace+ ), "the verifier raised before it could compare packed against per-row"+ packed_calls = [call for call in model.calls if call.packed]+ per_row_calls = [call for call in model.calls if not call.packed]+ assert len(packed_calls) == 1+ assert (+ len(per_row_calls) == input_ids.shape[0]+ ), f"expected one per-row verify forward per row, got {per_row_calls}"+ assert namespace["_pk_diff"] < 7e-1+ assert namespace["_pk_use"] is True+ assert getattr(model, "_unsloth_seq_packing_nograd_ok", None) is True+++if __name__ == "__main__":+ raise SystemExit(pytest.main([__file__, "-q"]))diff --git a/tests/test_grpo_padded_raw_logits.py b/tests/test_grpo_padded_raw_logits.pynew file mode 100644index 00000000000..3fd3f526b76--- /dev/null+++ b/tests/test_grpo_padded_raw_logits.py@@ -0,0 +1,463 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""The GRPO padded loop must survive a forward that returns real logits.++``_get_per_token_logps_and_entropies`` sets ``UNSLOTH_RETURN_HIDDEN_STATES=1``,+but ``outputs.logits`` only carries hidden states when the forward that ran is+Unsloth's generated one. Any other forward (a plain transformers model, a+wrapper, a model Unsloth did not patch) honours the name and returns a real+``[batch, seq, vocab]`` tensor. Feeding that into the hidden-states helper hits+the ``lm_head`` matmul with a vocab-wide operand and blows up:++ a and b must have same reduction dim, but got [((s47*s87 + 255)//256), s33] X [1536, 151936]++So both arms of the padded loop dispatch on width: hidden states (last dim ==+``lm_head.shape[1]``) go through the fused hidden-states helper, real logits go+straight to the plain log-softmax helper, which skips the ``lm_head`` matmul and+the scale/softcap (the model forward already applied those).++The loop body is lifted out of the live source with ``ast`` and executed here+against a stub model, so the test tracks the shipped code instead of a copy of+it. Everything is tiny and CPU-only; ``unsloth_zoo`` supplies the two helpers+when it is importable, and eager mirrors stand in when it is not.+"""++from __future__ import annotations++import ast+import builtins+import contextlib+import os+import sys+import textwrap+from pathlib import Path+from types import SimpleNamespace++import pytest+++torch = pytest.importorskip("torch")++sys.path.insert(0, str(Path(__file__).resolve().parent))+from _grpo_dispatch_source import load_dispatch_helpers # noqa: E402++_DISPATCH_HELPERS = load_dispatch_helpers()+++# ── The block under test, lifted structurally out of the live source ─────────++_SOURCE_PATH = Path(__file__).resolve().parents[1] / "unsloth" / "models" / "rl_replacements.py"+_TARGET_FUNCTION = "_get_per_token_logps_and_entropies"+_LOOP_ITERABLE = "zipped_inputs"+++def _find_target_function(tree: ast.AST) -> ast.FunctionDef:+ found = [+ node+ for node in ast.walk(tree)+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))+ and node.name == _TARGET_FUNCTION+ ]+ if len(found) != 1:+ raise AssertionError(+ f"expected exactly one def {_TARGET_FUNCTION} in {_SOURCE_PATH}, found {len(found)}"+ )+ return found[0]+++def _find_padded_loop_with(function: ast.AST) -> ast.With:+ """The ``with`` statement whose direct body holds the ``for ... in zipped_inputs`` loop."""+ found = [+ node+ for node in ast.walk(function)+ if isinstance(node, ast.With)+ and any(+ isinstance(stmt, ast.For)+ and isinstance(stmt.iter, ast.Name)+ and stmt.iter.id == _LOOP_ITERABLE+ for stmt in node.body+ )+ ]+ if len(found) != 1:+ raise AssertionError(+ f"expected exactly one padded-loop `with` inside {_TARGET_FUNCTION}, found {len(found)}"+ )+ return found[0]+++def _extract_padded_loop_source() -> str:+ source = _SOURCE_PATH.read_text(encoding = "utf-8")+ tree = ast.parse(source, filename = str(_SOURCE_PATH))+ node = _find_padded_loop_with(_find_target_function(tree))+ segment = ast.get_source_segment(source, node, padded = True)+ if segment is None:+ raise AssertionError("could not recover the padded-loop source segment")+ return textwrap.dedent(segment)+++def _free_variables(block_source: str) -> set[str]:+ """Names the block reads without ever binding them itself."""+ tree = ast.parse(block_source)+ loaded, stored = set(), set()+ for node in ast.walk(tree):+ if isinstance(node, ast.Name):+ if isinstance(node.ctx, ast.Load):+ loaded.add(node.id)+ else:+ stored.add(node.id)+ return {name for name in loaded - stored if not hasattr(builtins, name)}+++_BLOCK_SOURCE = _extract_padded_loop_source()+_BLOCK_CODE = compile(_BLOCK_SOURCE, "<rl_replacements padded loop>", "exec")+++# ── Helpers: the real unsloth_zoo ones when available, eager mirrors when not ─+++def _eager_chunked_hidden_states_selective_log_softmax(+ hidden_states,+ lm_head,+ index,+ chunks = 4,+ logit_scale_multiply = 0.0,+ logit_scale_divide = 0.0,+ logit_softcapping = 0.0,+ temperature = 1.0,+):+ flat_hidden_states = hidden_states.reshape(-1, hidden_states.shape[-1])+ flat_index = index.reshape(-1)+ all_per_token_logps = []+ for chunk_hidden_states, chunk_index in zip(+ torch.chunk(flat_hidden_states, chunks = chunks, dim = 0),+ torch.chunk(flat_index, chunks = chunks, dim = 0),+ ):+ chunk_logits = chunk_hidden_states.to(lm_head.dtype) @ lm_head.t()+ if logit_scale_multiply != 0.0:+ chunk_logits = chunk_logits * logit_scale_multiply+ if logit_scale_divide != 0.0:+ chunk_logits = chunk_logits / logit_scale_divide+ if logit_softcapping != 0.0:+ chunk_logits = logit_softcapping * torch.tanh(chunk_logits / logit_softcapping)+ chunk_logits = chunk_logits.to(torch.float32)+ if temperature != 1.0:+ chunk_logits = chunk_logits / temperature+ selected = torch.gather(chunk_logits, dim = -1, index = chunk_index.unsqueeze(-1)).squeeze(-1)+ all_per_token_logps.append(selected - torch.logsumexp(chunk_logits, dim = -1))+ out = torch.concat(all_per_token_logps)+ return out.reshape((hidden_states.shape[0], hidden_states.shape[1]))+++def _eager_chunked_selective_log_softmax(+ logits,+ index,+ temperature = 1.0,+ chunks = 4,+):+ all_per_token_logps = []+ for chunk_logits, chunk_index in zip(+ torch.chunk(logits.reshape(-1, logits.shape[-1]), chunks = chunks, dim = 0),+ torch.chunk(index.reshape(-1), chunks = chunks, dim = 0),+ ):+ chunk_logits = chunk_logits.to(torch.float32)+ if temperature != 1.0:+ chunk_logits = chunk_logits / temperature+ selected = torch.gather(chunk_logits, dim = -1, index = chunk_index.unsqueeze(-1)).squeeze(-1)+ all_per_token_logps.append(selected - torch.logsumexp(chunk_logits, dim = -1))+ out = torch.concat(all_per_token_logps)+ return out.reshape((logits.shape[0], logits.shape[1]))+++def _load_helpers():+ """Prefer the shipped helpers; fall back to the eager mirrors above.++ The real ones are ``torch.compile``d, so they are smoke-called once on the+ shapes this file uses before being accepted.+ """+ try:+ from unsloth_zoo.rl_replacements import (+ chunked_hidden_states_selective_log_softmax as real_hidden,+ chunked_selective_log_softmax as real_raw,+ )++ probe_hidden = torch.zeros(1, 2, _HIDDEN)+ probe_head = torch.zeros(_VOCAB, _HIDDEN)+ probe_index = torch.zeros(1, 2, dtype = torch.long)+ real_hidden(probe_hidden, probe_head, probe_index, 1, 0.0, 0.0, 0.0, 1.0)+ real_raw(torch.zeros(1, 2, _VOCAB), probe_index, 1.0, 1)+ except Exception:+ return (+ _eager_chunked_hidden_states_selective_log_softmax,+ _eager_chunked_selective_log_softmax,+ "eager mirrors",+ )+ return real_hidden, real_raw, "unsloth_zoo"+++# ── Stub model and reference ─────────────────────────────────────────────────++_VOCAB = 17+_HIDDEN = 8+_BATCH = 2+_SEQ = 9+_LOGITS_TO_KEEP = 3+_MAX_LEFT_PAD = 2+_MULTIPLIER = 2++_HELPER_HIDDEN, _HELPER_RAW, _HELPER_SOURCE = _load_helpers()+++class _StubModel:+ """A forward whose ``.logits`` is either hidden states or real logits.++ ``logits_to_keep`` is honoured because the VLM arm of the loop passes it and+ then slices the returned tensor assuming the forward already trimmed it.+ """++ def __init__(self, embedding, lm_head, returns_hidden_states):+ self.embedding = embedding+ self.lm_head = lm_head+ self.returns_hidden_states = returns_hidden_states+ self.calls = []++ def __call__(+ self,+ input_ids = None,+ logits_to_keep = None,+ **kwargs,+ ):+ hidden = self.embedding[input_ids]+ out = (+ hidden+ if self.returns_hidden_states+ else hidden.to(self.lm_head.dtype) @ self.lm_head.t()+ )+ if logits_to_keep is not None:+ out = out[:, -logits_to_keep:, :]+ self.calls.append({"logits_to_keep": logits_to_keep, "width": out.shape[-1]})+ return SimpleNamespace(logits = out)+++def _make_data():+ generator = torch.Generator().manual_seed(1234)+ return SimpleNamespace(+ embedding = torch.randn(_VOCAB, _HIDDEN, generator = generator),+ lm_head = torch.randn(_VOCAB, _HIDDEN, generator = generator),+ input_ids = torch.randint(0, _VOCAB, (_BATCH, _SEQ), generator = generator),+ attention_mask = torch.ones(_BATCH, _SEQ, dtype = torch.long),+ )+++def _reference_logprobs(+ data,+ *,+ is_vlm,+ temperature = 1.0,+ logit_scale_multiply = 0.0,+ logit_scale_divide = 0.0,+ logit_softcapping = 0.0,+):+ """Per-row expected result, computed independently with ``torch.log_softmax``."""+ logits = data.embedding[data.input_ids].to(data.lm_head.dtype) @ data.lm_head.t()+ if logit_scale_multiply != 0.0:+ logits = logits * logit_scale_multiply+ if logit_scale_divide != 0.0:+ logits = logits / logit_scale_divide+ if logit_softcapping != 0.0:+ logits = logit_softcapping * torch.tanh(logits / logit_softcapping)+ logits = logits.to(torch.float32)+ if temperature != 1.0:+ logits = logits / temperature+ width = _LOGITS_TO_KEEP if is_vlm else _LOGITS_TO_KEEP + _MAX_LEFT_PAD+ predictions = torch.log_softmax(logits, dim = -1)[:, -(width + 1) : -1, :]+ targets = data.input_ids[:, -width:]+ return torch.gather(predictions, dim = -1, index = targets.unsqueeze(-1)).squeeze(-1)+++def _build_namespace(+ data, stub, *, is_vlm, temperature, logit_softcapping, logit_scale_multiply, logit_scale_divide+):+ rows = [+ (+ data.input_ids[i : i + 1],+ data.attention_mask[i : i + 1],+ torch.zeros(1, 3) if is_vlm else None, # pixel_values_chunk (the stub ignores it)+ None, # image_grid_thw_chunk+ None, # pixel_attention_mask_chunk+ None, # image_sizes_chunk+ None, # token_type_ids_chunk+ None, # mm_token_type_ids_chunk+ )+ for i in range(_BATCH)+ ]+ return {+ "torch": torch,+ "os": os,+ **_DISPATCH_HELPERS,+ "chunked_hidden_states_selective_log_softmax": _HELPER_HIDDEN,+ "chunked_selective_log_softmax": _HELPER_RAW,+ "device_synchronize": lambda *a, **k: None,+ "_get_inference_mode_context_manager": lambda _model: contextlib.nullcontext(),+ "model": stub,+ "unwrapped_model": stub,+ "self": SimpleNamespace(_autocast_dtype = torch.float32),+ "pixel_values": torch.zeros(1, 3) if is_vlm else None,+ "lm_head": data.lm_head,+ "zipped_inputs": rows,+ "logits_to_keep": _LOGITS_TO_KEEP,+ "max_left_pad": _MAX_LEFT_PAD,+ "multiplier": _MULTIPLIER,+ "logit_scale_multiply": logit_scale_multiply,+ "logit_scale_divide": logit_scale_divide,+ "logit_softcapping": logit_softcapping,+ "temperature": temperature,+ "all_logprobs_list": [],+ "logprobs": None,+ }+++def _run_padded_loop(+ *,+ returns_hidden_states,+ is_vlm,+ temperature = 1.0,+ logit_softcapping = 0.0,+ logit_scale_multiply = 0.0,+ logit_scale_divide = 0.0,+):+ data = _make_data()+ stub = _StubModel(data.embedding, data.lm_head, returns_hidden_states)+ namespace = _build_namespace(+ data,+ stub,+ is_vlm = is_vlm,+ temperature = temperature,+ logit_softcapping = logit_softcapping,+ logit_scale_multiply = logit_scale_multiply,+ logit_scale_divide = logit_scale_divide,+ )+ exec(_BLOCK_CODE, namespace)+ return SimpleNamespace(+ data = data,+ stub = stub,+ logprobs = namespace["logprobs"],+ entropies = namespace["entropies"],+ )+++# ── Tests ────────────────────────────────────────────────────────────────────+++def test_extracted_block_is_the_padded_loop():+ """The lifted segment is the padded loop, located by shape and not by text search."""+ tree = ast.parse(_BLOCK_SOURCE)+ assert len(tree.body) == 1+ with_node = tree.body[0]+ assert isinstance(with_node, ast.With)+ loops = [stmt for stmt in with_node.body if isinstance(stmt, ast.For)]+ assert len(loops) == 1+ assert isinstance(loops[0].iter, ast.Name) and loops[0].iter.id == _LOOP_ITERABLE++ # Both arms of the branch inside the loop must dispatch through the shared+ # helper, which is what compares the width and consults the explicit+ # UNSLOTH_RETURN_HIDDEN_STATES signal. Counted structurally, never by text+ # search.+ dispatch_tests = [+ node+ for node in ast.walk(loops[0])+ if isinstance(node, ast.If)+ and isinstance(node.test, ast.Call)+ and isinstance(node.test.func, ast.Name)+ and node.test.func.id == "_unsloth_grpo_returns_hidden_states"+ ]+ assert (+ len(dispatch_tests) >= 2+ ), f"expected a hidden-states dispatch in both the text and the VLM arm, found {len(dispatch_tests)}"+++def test_block_free_variables_are_all_stubbed():+ """Every name the live block reads is supplied, so the exec cannot silently drift."""+ data = _make_data()+ namespace = _build_namespace(+ data,+ _StubModel(data.embedding, data.lm_head, True),+ is_vlm = False,+ temperature = 1.0,+ logit_softcapping = 0.0,+ logit_scale_multiply = 0.0,+ logit_scale_divide = 0.0,+ )+ missing = sorted(_free_variables(_BLOCK_SOURCE) - set(namespace))+ assert missing == [], f"padded loop reads names this test does not stub: {missing}"+++def test_text_branch_with_raw_logits_matches_reference():+ """Regression: a forward returning real logits must not reach the lm_head matmul."""+ result = _run_padded_loop(returns_hidden_states = False, is_vlm = False)+ expected = _reference_logprobs(result.data, is_vlm = False)+ assert result.logprobs.shape == (_BATCH, _LOGITS_TO_KEEP + _MAX_LEFT_PAD)+ assert result.entropies is None+ assert [call["width"] for call in result.stub.calls] == [_VOCAB] * _BATCH+ torch.testing.assert_close(result.logprobs, expected, rtol = 1e-5, atol = 1e-5)+++def test_text_branch_with_hidden_states_matches_reference():+ """The unchanged path: hidden states still go through the fused helper."""+ result = _run_padded_loop(returns_hidden_states = True, is_vlm = False)+ expected = _reference_logprobs(result.data, is_vlm = False)+ assert [call["width"] for call in result.stub.calls] == [_HIDDEN] * _BATCH+ torch.testing.assert_close(result.logprobs, expected, rtol = 1e-5, atol = 1e-5)+++ "returns_hidden_states", [True, False], ids = ["hidden_states", "raw_logits"]+)+def test_vlm_branch_matches_reference(returns_hidden_states):+ """The VLM arm keeps its own slicing and stays correct at both widths."""+ result = _run_padded_loop(returns_hidden_states = returns_hidden_states, is_vlm = True)+ expected = _reference_logprobs(result.data, is_vlm = True)+ assert result.logprobs.shape == (_BATCH, _LOGITS_TO_KEEP)+ assert [call["logits_to_keep"] for call in result.stub.calls] == [_LOGITS_TO_KEEP + 1] * _BATCH+ torch.testing.assert_close(result.logprobs, expected, rtol = 1e-5, atol = 1e-5)+++def test_temperature_is_applied_on_both_widths():+ """Temperature is the one transform both helpers apply."""+ expected = _reference_logprobs(_make_data(), is_vlm = False, temperature = 0.7)+ for returns_hidden_states in (True, False):+ result = _run_padded_loop(+ returns_hidden_states = returns_hidden_states,+ is_vlm = False,+ temperature = 0.7,+ )+ torch.testing.assert_close(result.logprobs, expected, rtol = 1e-5, atol = 1e-5)++[email protected]("is_vlm", [False, True], ids = ["text", "vlm"])+def test_raw_logits_skip_scale_and_softcap(is_vlm):+ """Real logits are final: the model forward already scaled and softcapped them.++ Only the hidden-states helper owns those transforms, because only it does the+ lm_head matmul that produces unfinished logits.+ """+ softcapping = 3.0+ data = _make_data()+ with_softcap = _reference_logprobs(data, is_vlm = is_vlm, logit_softcapping = softcapping)+ without_softcap = _reference_logprobs(data, is_vlm = is_vlm, logit_softcapping = 0.0)+ assert not torch.allclose(+ with_softcap, without_softcap, rtol = 1e-3, atol = 1e-3+ ), "the two references are indistinguishable, so this test would prove nothing"++ raw = _run_padded_loop(+ returns_hidden_states = False,+ is_vlm = is_vlm,+ logit_softcapping = softcapping,+ )+ hidden = _run_padded_loop(+ returns_hidden_states = True,+ is_vlm = is_vlm,+ logit_softcapping = softcapping,+ )+ torch.testing.assert_close(raw.logprobs, without_softcap, rtol = 1e-5, atol = 1e-5)+ torch.testing.assert_close(hidden.logprobs, with_softcap, rtol = 1e-5, atol = 1e-5)diff --git a/tests/test_grpo_width_dispatch_sites.py b/tests/test_grpo_width_dispatch_sites.pynew file mode 100644index 00000000000..54d8aa4a715--- /dev/null+++ b/tests/test_grpo_width_dispatch_sites.py@@ -0,0 +1,268 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Every lm_head matmul in the no-grad GRPO logprob path dispatches on width.++`_get_per_token_logps_and_entropies` sets UNSLOTH_RETURN_HIDDEN_STATES=1, but+`.logits` carries hidden states only when the model's forward is the Unsloth+generated one. When it is not, `.logits` is a real [.., vocab] tensor, and+handing that to `chunked_hidden_states_selective_log_softmax` runs it into the+lm_head matmul:++ a and b must have same reduction dim, but got+ [((s47*s87 + 255)//256), s33] X [1536, 151936]++`s33` there is a backed symbol that specialises to the hidden size; the message+only appears when the tensor genuinely is the wrong width, and 151936 is the+vocab. The VLM branch of the padded loop already dispatched on+`logits_chunk.shape[-1] == lm_head.shape[1]`; the text branch of the same loop+and both sequence-packing call sites did not.++All four now go through `_unsloth_grpo_returns_hidden_states`, which prefers the+explicit signal that the forward honoured the flag and keeps the width+comparison as its fallback. Width alone cannot answer the question for a model+whose `vocab_size` equals its `hidden_size`.++These checks are structural (AST), not textual, so that neither a comment+mentioning the guard nor a reformat can satisfy them.+"""++from __future__ import annotations++import ast+import os++REPO_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))+SOURCE_PATH = os.path.join(REPO_ROOT, "unsloth", "models", "rl_replacements.py")++HIDDEN_STATES_HELPER = "chunked_hidden_states_selective_log_softmax"+RAW_LOGITS_HELPER = "chunked_selective_log_softmax"+DISPATCH_HELPER = "_unsloth_grpo_returns_hidden_states"+SIGNAL_HELPER = "_unsloth_grpo_hidden_states_signal"++# One shared parse: nodes from separate parses never compare equal, which would+# silently make every containment check below vacuously true.+TREE = ast.parse(open(SOURCE_PATH, "r", encoding = "utf-8").read())+++def _logprob_function():+ for node in ast.walk(TREE):+ if isinstance(node, ast.FunctionDef) and node.name == "_get_per_token_logps_and_entropies":+ return node+ return None+++def _matmul_calls(scope):+ """Calls to the hidden-states helper, i.e. the ones that hit the matmul.++ The PrefixGrouper site passes the helper to `extract_logps` as a bare Name+ rather than calling it, so it is deliberately not one of these.+ """+ return [+ node+ for node in ast.walk(scope)+ if isinstance(node, ast.Call)+ and isinstance(node.func, ast.Name)+ and node.func.id == HIDDEN_STATES_HELPER+ ]+++def _is_dispatch_test(test):+ """`_unsloth_grpo_returns_hidden_states(<model>, <tensor>, lm_head)`.++ The width comparison itself lives inside that helper, next to the explicit+ UNSLOTH_RETURN_HIDDEN_STATES signal it defers to; see+ `test_the_dispatch_helper_prefers_the_explicit_signal` below.+ """+ if not (isinstance(test, ast.Call) and isinstance(test.func, ast.Name)):+ return False+ if test.func.id != DISPATCH_HELPER:+ return False+ if len(test.args) != 3 or test.keywords:+ return False+ return ast.unparse(test.args[2]) == "lm_head"+++def _guard_for(call):+ """The nearest enclosing `if` that dispatches and holds `call` in its body."""+ best = None+ for node in ast.walk(TREE):+ if not isinstance(node, ast.If) or not _is_dispatch_test(node.test):+ continue+ if not any(call is inner for stmt in node.body for inner in ast.walk(stmt)):+ continue+ if best is None or node.lineno > best.lineno:+ best = node+ return best+++def _called_names(statements):+ names = set()+ for stmt in statements:+ for node in ast.walk(stmt):+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Name):+ names.add(node.func.id)+ return names+++def test_the_logprob_function_is_present():+ assert _logprob_function() is not None, (+ "_get_per_token_logps_and_entropies not found; this file's other "+ "checks would pass vacuously"+ )+++def test_the_matmul_call_sites_are_all_accounted_for():+ """Four sites: packed, packed verifier, padded text, padded VLM.++ Pinned so that a new unguarded call site added later fails here rather than+ slipping past the per-site checks below.+ """+ calls = _matmul_calls(_logprob_function())+ assert len(calls) == 4, [call.lineno for call in calls]+++def test_every_matmul_call_site_dispatches_on_the_shared_helper():+ calls = _matmul_calls(_logprob_function())+ unguarded = [call.lineno for call in calls if _guard_for(call) is None]+ assert not unguarded, (+ f"lines {unguarded} call {HIDDEN_STATES_HELPER} without first asking "+ f"{DISPATCH_HELPER} whether the tensor is hidden states, so a forward "+ "that returns real logits reaches the lm_head matmul"+ )+++def test_the_dispatch_helper_prefers_the_explicit_signal():+ """The helper is what makes the four sites correct, so pin its shape.++ It must (a) still compare the tensor's last dim against `lm_head.shape[1]`,+ which is the fallback for an unsloth_zoo old enough never to write the+ marker, and (b) consult `_unsloth_grpo_hidden_states_signal`, which is the+ only thing that can separate real logits from hidden states when+ `vocab_size == hidden_size`.+ """+ helpers = {+ node.name: node+ for node in TREE.body+ if isinstance(node, ast.FunctionDef) and node.name in (DISPATCH_HELPER, SIGNAL_HELPER)+ }+ assert sorted(helpers) == sorted((DISPATCH_HELPER, SIGNAL_HELPER)), sorted(helpers)++ dispatch = helpers[DISPATCH_HELPER]+ compared = {+ ast.unparse(operand)+ for node in ast.walk(dispatch)+ if isinstance(node, ast.Compare)+ for operand in [node.left, *node.comparators]+ }+ assert {"tensor.shape[-1]", "lm_head.shape[1]"} <= compared, sorted(compared)+ assert {"lm_head.shape[0]", "lm_head.shape[1]"} <= compared, (+ "the helper does not check whether vocab_size == hidden_size, so it "+ "either never consults the signal or lets it overrule a width "+ "comparison that was already decisive"+ )+ assert SIGNAL_HELPER in _called_names(dispatch.body), (+ f"{DISPATCH_HELPER} never calls {SIGNAL_HELPER}, so it is back to "+ "dispatching on an ambiguous dimension comparison alone"+ )++ # The signal has to come from an explicit marker, not from a shape.+ signal_source = ast.unparse(helpers[SIGNAL_HELPER])+ for marker in (+ "__UNSLOTH_SUPPORTS_RETURN_HIDDEN_STATES__",+ "_unsloth_grpo_hidden_states_forward_wrapped",+ "_unsloth_grpo_hidden_states_warning_issued",+ ):+ assert marker in signal_source, f"{SIGNAL_HELPER} no longer reads {marker}"+++def test_both_helpers_reach_the_generated_trainer():+ """`RL_PRE_ITEMS` is how the call sites see them; without it, NameError."""+ shipped = {+ ast.unparse(node.value.args[0].args[0])+ for node in ast.walk(TREE)+ if isinstance(node, ast.Expr)+ and isinstance(node.value, ast.Call)+ and ast.unparse(node.value.func) == "RL_PRE_ITEMS['grpo_trainer'].append"+ and node.value.args+ and isinstance(node.value.args[0], ast.Call)+ and ast.unparse(node.value.args[0].func) == "inspect.getsource"+ and node.value.args[0].args+ }+ assert {DISPATCH_HELPER, SIGNAL_HELPER} <= shipped, sorted(shipped)+++def test_every_dispatch_guard_falls_back_to_the_raw_logits_helper():+ calls = _matmul_calls(_logprob_function())+ for call in calls:+ guard = _guard_for(call)+ assert guard is not None, call.lineno+ assert RAW_LOGITS_HELPER in _called_names(guard.orelse), (+ f"the guard at line {guard.lineno} has no {RAW_LOGITS_HELPER} "+ "fallback, so the raw-logits case is unhandled"+ )+++def test_the_raw_logits_fallback_skips_scaling_and_softcapping():+ """The forward already applied them, so re-applying would double them."""+ forbidden = {"logit_scale_multiply", "logit_scale_divide", "logit_softcapping"}+ calls = _matmul_calls(_logprob_function())+ for call in calls:+ guard = _guard_for(call)+ assert guard is not None, call.lineno+ for node in ast.walk(ast.Module(body = guard.orelse, type_ignores = [])):+ if not (isinstance(node, ast.Call) and isinstance(node.func, ast.Name)):+ continue+ if node.func.id != RAW_LOGITS_HELPER:+ continue+ passed = {ast.unparse(arg) for arg in node.args}+ passed |= {kw.arg for kw in node.keywords if kw.arg is not None}+ passed |= {ast.unparse(kw.value) for kw in node.keywords}+ leaked = forbidden & passed+ assert not leaked, (+ f"the raw-logits fallback at line {node.lineno} passes {leaked}; "+ "the model forward already applied them"+ )+++def test_the_padded_text_branch_is_guarded():+ """The crash site: pixel_values is None, so no enclosing try catches it.++ Located by structure rather than by line number: the `if pixel_values is+ None` inside the padded loop.+ """+ function = _logprob_function()+ branches = [+ node+ for node in ast.walk(function)+ if isinstance(node, ast.If)+ and isinstance(node.test, ast.Compare)+ and ast.unparse(node.test) == "pixel_values is None"+ and _matmul_calls(ast.Module(body = node.body, type_ignores = []))+ ]+ assert len(branches) == 1, [node.lineno for node in branches]+ (text_branch,) = branches+ calls = _matmul_calls(ast.Module(body = text_branch.body, type_ignores = []))+ assert len(calls) == 1, [call.lineno for call in calls]+ assert _guard_for(calls[0]) is not None, (+ "the text branch of the padded loop reaches the lm_head matmul "+ "unguarded, and unlike the packing sites it is not inside a try, so "+ "this is what surfaces as a TorchRuntimeError during training"+ )+++def test_the_packing_sites_are_guarded():+ """Both `_pk_` sites: the packed forward and its first-use verifier.++ They sit inside `except Exception`, so a failure here is swallowed into a+ permanent packing-disable rather than a crash.+ """+ function = _logprob_function()+ packed = [+ call+ for call in _matmul_calls(function)+ if any(isinstance(node, ast.Name) and node.id.startswith("_pk_") for node in ast.walk(call))+ ]+ assert len(packed) == 2, [call.lineno for call in packed]+ unguarded = [call.lineno for call in packed if _guard_for(call) is None]+ assert not unguarded, unguardeddiff --git a/unsloth/models/rl.py b/unsloth/models/rl.pyindex dcacbf97cd8..52f0a75e1e8 100644--- a/unsloth/models/rl.py+++ b/unsloth/models/rl.py@@ -1666,6 +1666,11 @@ def _wrap_sft_evaluate_cap(trainer_cls):_UNSLOTH_RETURN_HIDDEN_STATES_SUPPORT_MARKER = "__UNSLOTH_SUPPORTS_RETURN_HIDDEN_STATES__"_UNSLOTH_GRPO_HIDDEN_STATES_WRAPPED_ATTR = "_unsloth_grpo_hidden_states_forward_wrapped"_UNSLOTH_GRPO_HIDDEN_STATES_WARNING_ATTR = "_unsloth_grpo_hidden_states_warning_issued"+# Whether the *most recent* forward handed back real logits instead of hidden+# states. The warning attribute above is warn-once bookkeeping and is never+# cleared, so it answers "ever degraded", not "degraded on the call the caller+# is about to dispatch on".+_UNSLOTH_GRPO_HIDDEN_STATES_DEGRADED_ATTR = "_unsloth_grpo_hidden_states_degraded"def _module_returns_logits(module):@@ -1774,12 +1779,24 @@ def _get_num_logits_to_keep(forward_signature, args, kwargs):def _warn_grpo_hidden_states_fallback_once(model, message):+ # The degradation flag is per call: whether the tensor this forward is about+ # to return is real logits. Degradation is not a property of the model -- a+ # forward that splats **kwargs into a sub-module only reached by some inputs+ # (a vision tower, say) raises for the batches that reach it and succeeds for+ # the rest -- so a sticky flag would keep routing later, genuine hidden+ # states through the raw-logits helper, skipping the lm_head matmul.+ setattr(model, _UNSLOTH_GRPO_HIDDEN_STATES_DEGRADED_ATTR, True)if getattr(model, _UNSLOTH_GRPO_HIDDEN_STATES_WARNING_ATTR, False):returnsetattr(model, _UNSLOTH_GRPO_HIDDEN_STATES_WARNING_ATTR, True)logger.warning(message)+def _note_grpo_hidden_states_success(model):+ """Record that the forward about to return really is handing back hidden states."""+ setattr(model, _UNSLOTH_GRPO_HIDDEN_STATES_DEGRADED_ATTR, False)++def _replace_outputs_logits(outputs, hidden_states):if hasattr(outputs, "logits"):outputs.logits = hidden_states@@ -1815,9 +1832,17 @@ def _install_grpo_hidden_states_forward_wrapper(model):while len(args) != 0 and args[0] is target_model:args = args[1:]if os.environ.get("UNSLOTH_RETURN_HIDDEN_STATES", "0") != "1":+ # nobody asked for hidden states, so this returns real logits+ setattr(target_model, _UNSLOTH_GRPO_HIDDEN_STATES_DEGRADED_ATTR, True)return original_forward(*args, **kwargs)- forward_kwargs = _drop_forward_kwargs_consumed_positionally(forward_signature, args, kwargs)+ # copy: _drop_forward_kwargs_consumed_positionally hands `kwargs` straight+ # back when there is nothing to drop, so mutating it below would poison the+ # caller's dict and make the fallback calls further down re-send the very+ # kwargs the model just rejected.+ forward_kwargs = dict(+ _drop_forward_kwargs_consumed_positionally(forward_signature, args, kwargs)+ )num_logits_to_keep = _get_num_logits_to_keep(forward_signature, args, forward_kwargs)forward_kwargs["output_hidden_states"] = Trueforward_kwargs["return_dict"] = True@@ -1843,6 +1868,7 @@ def _install_grpo_hidden_states_forward_wrapper(model):hidden_states = hidden_states[-1]if num_logits_to_keep != 0:hidden_states = hidden_states[:, -num_logits_to_keep:, :]+ _note_grpo_hidden_states_success(target_model)return _replace_outputs_logits(outputs, hidden_states)wrapped_forward._unsloth_grpo_hidden_states_forward_wrapped = Truediff --git a/unsloth/models/rl_replacements.py b/unsloth/models/rl_replacements.pyindex c6355a14cb3..a2c87b1a45c 100644--- a/unsloth/models/rl_replacements.py+++ b/unsloth/models/rl_replacements.py@@ -1980,16 +1980,30 @@ def grpo_trainer__get_per_token_logps_and_entropies(function_name, function):),use_cache = False,).logits- _pk_sel = chunked_hidden_states_selective_log_softmax(- _pk_hidden[0, :-1, :][_pk_ctgt].unsqueeze(0),- lm_head,- _pk_flat[0, 1:][_pk_ctgt].unsqueeze(0),- _pk_chunks,- logit_scale_multiply,- logit_scale_divide,- logit_softcapping,- temperature,- )[0]+ _pk_out = _pk_hidden[0, :-1, :][_pk_ctgt].unsqueeze(0)+ _pk_ids = _pk_flat[0, 1:][_pk_ctgt].unsqueeze(0)+ # Guard: check if model returned hidden states or logits+ if _unsloth_grpo_returns_hidden_states(+ unwrapped_model, _pk_out, lm_head+ ):+ _pk_sel = chunked_hidden_states_selective_log_softmax(+ _pk_out,+ lm_head,+ _pk_ids,+ _pk_chunks,+ logit_scale_multiply,+ logit_scale_divide,+ logit_softcapping,+ temperature,+ )[0]+ else:+ # Model returned logits directly - scaling/softcapping already applied by model forward+ _pk_sel = chunked_selective_log_softmax(+ _pk_out,+ _pk_ids,+ temperature,+ _pk_chunks,+ )[0]# GPT-OSS offload race guard (matches the padded loop)device_synchronize()# scatter each logprob back to its (row, col) so [:, -_pk_W:] matches padded@@ -2037,16 +2051,29 @@ def grpo_trainer__get_per_token_logps_and_entropies(function_name, function):position_ids = _pk_rpos,use_cache = False,).logits- _pk_rsel = chunked_hidden_states_selective_log_softmax(- _pk_rh[:, :-1, :],- lm_head,- _pk_real[:, 1:],- 1,- logit_scale_multiply,- logit_scale_divide,- logit_softcapping,- temperature,- )[0]+ _pk_rout = _pk_rh[:, :-1, :]+ # Guard: check if model returned hidden states or logits+ if _unsloth_grpo_returns_hidden_states(+ unwrapped_model, _pk_rout, lm_head+ ):+ _pk_rsel = chunked_hidden_states_selective_log_softmax(+ _pk_rout,+ lm_head,+ _pk_real[:, 1:],+ 1,+ logit_scale_multiply,+ logit_scale_divide,+ logit_softcapping,+ temperature,+ )[0]+ else:+ # Model returned logits directly - scaling/softcapping already applied by model forward+ _pk_rsel = chunked_selective_log_softmax(+ _pk_rout,+ _pk_real[:, 1:],+ temperature,+ 1,+ )[0]_pk_rcols = _pk_rmask.nonzero(as_tuple = False).squeeze(1)[1:] - (_pk_L - _pk_W)@@ -2221,16 +2248,28 @@ def grpo_trainer__get_per_token_logps_and_entropies(function_name, function)::, -(logits_to_keep + max_left_pad + 1) :, :]logits_chunk = logits_chunk[:, :-1, :]- logprobs_chunk = chunked_hidden_states_selective_log_softmax(- logits_chunk,- lm_head,- completion_input_ids_chunk,- chunks = input_ids_chunk.shape[0] * multiplier,- logit_scale_multiply = logit_scale_multiply,- logit_scale_divide = logit_scale_divide,- logit_softcapping = logit_softcapping,- temperature = temperature,- )+ # Guard: check if model returned hidden states or logits+ if _unsloth_grpo_returns_hidden_states(+ unwrapped_model, logits_chunk, lm_head+ ):+ logprobs_chunk = chunked_hidden_states_selective_log_softmax(+ logits_chunk,+ lm_head,+ completion_input_ids_chunk,+ chunks = input_ids_chunk.shape[0] * multiplier,+ logit_scale_multiply = logit_scale_multiply,+ logit_scale_divide = logit_scale_divide,+ logit_softcapping = logit_softcapping,+ temperature = temperature,+ )+ else:+ # Model returned logits directly - scaling/softcapping already applied by model forward+ logprobs_chunk = chunked_selective_log_softmax(+ logits_chunk,+ completion_input_ids_chunk,+ temperature,+ input_ids_chunk.shape[0] * multiplier,+ )else:# Essentially, for VLMs we do not go via the optimized path in models/,# so we don't encounter the Flash Attn left-padding issue.@@ -2251,7 +2290,9 @@ def grpo_trainer__get_per_token_logps_and_entropies(function_name, function):logits_chunk = logits_chunk[:, :-1, :]completion_input_ids_chunk = input_ids_chunk[:, -logits_to_keep:]# Guard: check if model returned hidden states or logits- if logits_chunk.shape[-1] == lm_head.shape[1]:+ if _unsloth_grpo_returns_hidden_states(+ unwrapped_model, logits_chunk, lm_head+ ):logprobs_chunk = chunked_hidden_states_selective_log_softmax(logits_chunk,lm_head,@@ -2360,6 +2401,167 @@ def _unsloth_get_final_logit_softcapping(model):return 0 if softcap is None else softcap+def _unsloth_grpo_returns_hidden_states(model, tensor, lm_head):+ """Does ``tensor`` (a forward's ``.logits``) carry hidden states or real logits?++ ``_get_per_token_logps_and_entropies`` sets ``UNSLOTH_RETURN_HIDDEN_STATES=1``,+ but only a forward that honours the name hands hidden states back as+ ``.logits``; any other forward returns a real ``[.., vocab]`` tensor that must+ not reach the ``lm_head`` matmul.++ Primary test is an explicit signal that the forward honours the flag. Two+ exist, both set outside this file:++ * ``__UNSLOTH_SUPPORTS_RETURN_HIDDEN_STATES__`` on the generated class,+ written by ``unsloth_zoo.compiler.create_standalone_class`` exactly when+ ``apply_fused_lm_head`` gave that forward its own ``RETURN_HIDDEN_STATES``+ branch.+ * ``_unsloth_grpo_hidden_states_forward_wrapped``, set by+ ``_install_grpo_hidden_states_forward_wrapper`` in ``unsloth/models/rl.py``+ for models the compiler did not rewrite. That wrapper degrades to real+ logits when the model cannot produce hidden states, and records whether+ it did so in ``_unsloth_grpo_hidden_states_degraded`` before it returns,+ so reading the pair after a forward describes the call that just+ finished. Degradation is per call, not per model: a forward that splats+ ``**kwargs`` into a sub-module only some inputs reach can reject the+ request on one batch and honour it on the next.++ The width comparison stays as the fallback, for an ``unsloth_zoo`` old enough+ that it never writes the marker. It is decisive on its own whenever+ ``vocab_size != hidden_size``, and the signal is only allowed to overrule it+ when it is not: a model with ``vocab_size == hidden_size`` produces real+ logits that are the same width as its hidden states, which is the one case+ the shape cannot answer.+ """+ if tensor.shape[-1] != lm_head.shape[1]:+ return False # vocab-wide: real logits, whatever any signal claims+ if lm_head.shape[0] != lm_head.shape[1]:+ return True # hidden-wide and vocab_size != hidden_size: hidden states+ return _unsloth_grpo_hidden_states_signal(model) is not False+++def _unsloth_grpo_hidden_states_signal(model):+ """``True``/``False`` if the forward honours ``UNSLOTH_RETURN_HIDDEN_STATES``.++ ``None`` when neither marker is present, i.e. there is no signal to read.+ See ``_unsloth_grpo_returns_hidden_states`` for where each marker is set.+ Walks the wrapper chain because the markers are set on whichever object the+ trainer saw, which may be the DDP module or the PEFT base model rather than+ the object handed to the logprob loop.+ """+ candidates = []+ pending = [model]+ while pending and len(candidates) < 8:+ candidate = pending.pop(0)+ if candidate is None or any(candidate is seen for seen in candidates):+ continue+ candidates.append(candidate)+ get_base_model = getattr(candidate, "get_base_model", None)+ if callable(get_base_model):+ try:+ pending.append(get_base_model())+ except Exception:+ pass+ for _attr in ("module", "base_model", "model"):+ child = getattr(candidate, _attr, None)+ if child is not None and hasattr(child, "forward"):+ pending.append(child)+ for candidate in candidates:+ if getattr(candidate, "__UNSLOTH_SUPPORTS_RETURN_HIDDEN_STATES__", False):+ return True+ if getattr(type(candidate), "__UNSLOTH_SUPPORTS_RETURN_HIDDEN_STATES__", False):+ return True+ if any(+ getattr(candidate, "_unsloth_grpo_hidden_states_forward_wrapped", False)+ for candidate in candidates+ ):+ # the wrapper honours the flag unless it recorded that this call could not+ if any(+ hasattr(candidate, "_unsloth_grpo_hidden_states_degraded") for candidate in candidates+ ):+ return not any(+ getattr(candidate, "_unsloth_grpo_hidden_states_degraded", False)+ for candidate in candidates+ )+ # an `unsloth/models/rl.py` predating the per-call attribute only ever set+ # the warn-once flag; it is the best signal such a wrapper offers+ return not any(+ getattr(candidate, "_unsloth_grpo_hidden_states_warning_issued", False)+ for candidate in candidates+ )+ return None+++_GRPO_HIDDEN_STATES_WIDTH_DISPATCH = re.compile(+ r"^(?P<indent>[ \t]*)if[ \t]+"+ r"(?P<tensor>[_A-Za-z][_A-Za-z0-9]*)\.shape\[-1\][ \t]*"+ r"(?P<operator>==|!=)[ \t]*lm_head\.shape\[1\][ \t]*:$",+ flags = re.MULTILINE,+)++# Deliberately loose: any branch header that decides something off an ``lm_head``+# dimension. Used only to count how many decisions the strict pattern above was+# supposed to rewrite, so that a zoo which respells *some* of them is rejected+# rather than half-patched.+_GRPO_HIDDEN_STATES_WIDTH_DISPATCH_CANDIDATE = re.compile(+ r"^[ \t]*(?:el)?if[ \t]+[^\n]*\blm_head\.shape\[[^\]\n]+\][^\n]*:[ \t]*$",+ flags = re.MULTILINE,+)+++def _patch_grpo_accumulated_loss_hidden_states_dispatch(function):+ """Give zoo's gradient path the same model-aware dispatch as the no-grad path.++ ``grpo_accumulated_loss`` is embedded into the generated trainer with+ ``inspect.getsource`` below. Zoo revisions with raw-logits support choose+ between the two log-softmax helpers by comparing the forward output width+ with ``lm_head.shape[1]``. That comparison is ambiguous for a square head,+ so replace every such decision before embedding the function.++ The expression is intentionally limited to a named tensor's last dimension+ against the lm_head input dimension. If zoo changes that contract entirely,+ fail at trainer generation instead of silently restoring the wrong dispatch.++ Partial matches have to fail too. A zoo that respells only some of its+ dispatches would still give this one match, which is enough to satisfy a+ "did anything match?" check while the respelled sites keep deciding on width+ alone -- silently wrong gradients again for a square ``lm_head``. So count+ the branch headers that decide off an ``lm_head`` dimension before and after+ substituting, and require that none survive.+ """+ source = function if isinstance(function, str) else inspect.getsource(function)+ candidates = len(_GRPO_HIDDEN_STATES_WIDTH_DISPATCH_CANDIDATE.findall(source))+ replacements = 0++ def replace_width_dispatch(match):+ nonlocal replacements+ replacements += 1+ decision = (+ "_unsloth_grpo_returns_hidden_states("+ f"unwrapped_model, {match.group('tensor')}, lm_head)"+ )+ if match.group("operator") == "!=":+ decision = f"not {decision}"+ return f"{match.group('indent')}if {decision}:"++ source = _GRPO_HIDDEN_STATES_WIDTH_DISPATCH.sub(replace_width_dispatch, source)+ if replacements == 0:+ raise RuntimeError(+ "Unsloth: could not find the GRPO gradient hidden-state dispatches in "+ "this unsloth_zoo version. Please upgrade unsloth_zoo."+ )+ unpatched = _GRPO_HIDDEN_STATES_WIDTH_DISPATCH_CANDIDATE.findall(source)+ if len(unpatched) != 0:+ raise RuntimeError(+ f"Unsloth: patched only {replacements} of {candidates} GRPO gradient "+ "hidden-state dispatches in this unsloth_zoo version; "+ f"{len(unpatched)} still decide on width alone "+ f"({', '.join(line.strip() for line in unpatched)}). "+ "Please upgrade unsloth_zoo."+ )+ return source++grpo_compute_loss = RL_REPLACEMENTS["grpo_compute_loss"]grpo_compute_loss_slow = RL_REPLACEMENTS["grpo_compute_loss_slow"]UnslothEfficientGRPO = RL_REPLACEMENTS["UnslothEfficientGRPO"]@@ -2369,12 +2571,16 @@ RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(_unsloth_grpo_autocast))RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(_unsloth_grpo_autocast_kwargs))RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(_unsloth_get_model_config))RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(_unsloth_get_final_logit_softcapping))+RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(_unsloth_grpo_returns_hidden_states))+RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(_unsloth_grpo_hidden_states_signal))RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(_unsloth_get_mm_token_id))RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(_unsloth_fix_mm_token_type_ids))RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(_unsloth_clear_stateful_mrope))RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(grpo_compute_loss))RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(UnslothEfficientGRPO))-RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(grpo_accumulated_loss))+RL_PRE_ITEMS["grpo_trainer"].append(+ _patch_grpo_accumulated_loss_hidden_states_dispatch(grpo_accumulated_loss)+)RL_PRE_ITEMS["grpo_trainer"].append(grpo_compute_loss_slow)RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(grpo_update_SamplingParams))RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(_get_inference_mode_context_manager))