Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Stop the GRPO hidden-states wrapper paying for logits it discards (#8576)

Daniel Hanbaa96a7160d5
diff --git a/tests/_rl_source.py b/tests/_rl_source.py
index b3e66cc6366..85a8a95c397 100644
--- a/tests/_rl_source.py
+++ b/tests/_rl_source.py
@@ -11,6 +11,7 @@ while still tracking the shipped code.
from __future__ import annotations
import ast
+import collections
import inspect
import logging
import os
@@ -28,6 +29,8 @@ WRAPPER_NAMES = (
"_warn_grpo_hidden_states_fallback_once",
"_note_grpo_hidden_states_success",
"_replace_outputs_logits",
+ "_minimise_logits_kwarg",
+ "_drop_spare_hidden_states",
"_install_grpo_hidden_states_forward_wrapper",
)
@@ -66,6 +69,7 @@ def load_rl_wrapper(names = WRAPPER_NAMES):
namespace: dict = {
"os": os,
+ "collections": collections,
"inspect": inspect,
"logger": logging.getLogger("unsloth-repro"),
}
diff --git a/tests/test_grpo_hidden_states_logits_cost.py b/tests/test_grpo_hidden_states_logits_cost.py
new file mode 100644
index 00000000000..882536f13aa
--- /dev/null
+++ b/tests/test_grpo_hidden_states_logits_cost.py
@@ -0,0 +1,536 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""The GRPO hidden-states wrapper must not pay for logits it throws away.
+
+`Kaggle-Muse_Glimmer_(30B)-GRPO` died on a 2 x T4 kernel with
+
+ accelerate/hooks.py:429 AlignDevicesHook.post_forward
+ -> send_to_device(output, self.input_device)
+ OutOfMemoryError: Tried to allocate 1002.00 MiB.
+ GPU 0 has 14.56 GiB capacity, of which 768.81 MiB is free.
+
+Two costs met there.
+
+The first is the lm_head. `UnslothEfficientGRPO` never sees a logits tensor --
+it takes per-token logps plus `lm_head` and chunks the projection itself -- and
+this wrapper exists to hand it hidden states instead of logits. But it forwarded
+the caller's `logits_to_keep` unchanged, and the GRPO trainer does not pass one:
+
+ outputs = unwrapped_model(
+ input_ids = input_ids_chunk,
+ attention_mask = attention_mask_chunk,
+ ...
+ )
+ logits_chunk = outputs.logits
+
+transformers reads a missing or zero value as `slice(-0, None)`, which is
+`slice(0, None)`: every position. So the model projected the whole prompt and
+completion over a 202048-wide vocabulary, softcapped it twice, and the wrapper
+then overwrote the result with hidden states.
+
+The second is the other layers. `output_hidden_states = True` returns every
+layer; only `[-1]` is read, and the rest stayed attached to the output.
+
+On one card neither cost is visible: the trainer's `del outputs` frees both a
+line later. Under an accelerate layer-split dispatch, `io_same_device` walks the
+whole returned object and copies every tensor in it to the input device first,
+so both ride across the bus and the first card runs out.
+
+These tests drive the real helpers, lifted from `unsloth/models/rl.py` with
+`ast` so they track the shipped source without importing unsloth.
+"""
+
+from __future__ import annotations
+
+import collections
+import inspect
+import os
+import sys
+from dataclasses import dataclass, fields
+from pathlib import Path
+
+import pytest
+
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+
+from _rl_source import load_rl_wrapper # noqa: E402
+
+WRAPPER = load_rl_wrapper()
+_minimise_logits_kwarg = WRAPPER["_minimise_logits_kwarg"]
+_drop_spare_hidden_states = WRAPPER["_drop_spare_hidden_states"]
+_install = WRAPPER["_install_grpo_hidden_states_forward_wrapper"]
+
+
+# --------------------------------------------------------------------------
+# a stand-in for transformers' ModelOutput, including the trap
+# --------------------------------------------------------------------------
+class FakeModelOutput(collections.OrderedDict):
+ """`ModelOutput`'s actual assignment semantics, which are the whole point.
+
+ def __setattr__(self, name, value):
+ if name in field_names and value is not None:
+ super().__setitem__(name, value)
+ super().__setattr__(name, value)
+
+ so assigning None updates the attribute and leaves the mapping entry alone,
+ and `__delitem__` / `pop` / `update` / `setdefault` all raise.
+ """
+
+ _fields = ("logits", "hidden_states")
+
+ def __init__(self, **kwargs):
+ super().__init__()
+ for name in self._fields:
+ value = kwargs.get(name)
+ object.__setattr__(self, name, value)
+ if value is not None:
+ collections.OrderedDict.__setitem__(self, name, value)
+
+ def __setattr__(self, name, value):
+ if name in self._fields and value is not None:
+ collections.OrderedDict.__setitem__(self, name, value)
+ object.__setattr__(self, name, value)
+
+ def __delitem__(self, *a, **kw):
+ raise Exception("You cannot use ``__delitem__`` on a FakeModelOutput instance.")
+
+ def pop(self, *a, **kw):
+ raise Exception("You cannot use ``pop`` on a FakeModelOutput instance.")
+
+ def update(self, *a, **kw):
+ raise Exception("You cannot use ``update`` on a FakeModelOutput instance.")
+
+ def setdefault(self, *a, **kw):
+ raise Exception("You cannot use ``setdefault`` on a FakeModelOutput instance.")
+
+
+def test_the_fake_output_really_does_reproduce_the_trap():
+ """If this stops holding, the test below proves nothing."""
+ out = FakeModelOutput(logits = "L", hidden_states = ("a", "b", "c"))
+ out.hidden_states = None
+ assert out.hidden_states is None, "the attribute should have taken the None"
+ assert out["hidden_states"] == (
+ "a",
+ "b",
+ "c",
+ ), "the mapping entry must survive -- that is the bug being guarded"
+ with pytest.raises(Exception):
+ out.pop("hidden_states")
+
+
+# --------------------------------------------------------------------------
+# dropping the spare layers
+# --------------------------------------------------------------------------
+def test_the_spare_layers_leave_the_mapping_not_just_the_attribute():
+ """A consumer that walks the object as a mapping is the one that matters."""
+ out = FakeModelOutput(logits = "L", hidden_states = ("a", "b", "c"))
+ _drop_spare_hidden_states(out)
+ assert out.hidden_states is None
+ assert out["hidden_states"] is None, (
+ "accelerate's send_to_device iterates .items(); a stale tuple here is "
+ "copied to the other device"
+ )
+ assert dict(out.items())["hidden_states"] is None
+
+
+def test_a_plain_dict_output_is_handled_too():
+ out = {"logits": "L", "hidden_states": ("a", "b")}
+ _drop_spare_hidden_states(out)
+ assert out["hidden_states"] is None
+
+
+def test_a_plain_object_output_is_handled_too():
+ @dataclass
+ class Out:
+ logits: str
+ hidden_states: tuple
+
+ out = Out(logits = "L", hidden_states = ("a", "b"))
+ _drop_spare_hidden_states(out)
+ assert out.hidden_states is None
+
+
+def test_an_output_without_hidden_states_is_left_alone():
+ out = {"logits": "L"}
+ _drop_spare_hidden_states(out)
+ assert out == {"logits": "L"}
+
+
+def test_an_unassignable_output_does_not_take_the_step_down():
+ """The caller already has the layer it needs; this is not worth raising."""
+
+ class Frozen:
+ __slots__ = ()
+
+ @property
+ def hidden_states(self):
+ return ("a",)
+
+ _drop_spare_hidden_states(Frozen()) # must not raise
+
+
+# --------------------------------------------------------------------------
+# not paying for the lm_head
+# --------------------------------------------------------------------------
+def _sig(fn):
+ import inspect
+ return inspect.signature(fn)
+
+
+def test_the_modern_kwarg_is_pinned_to_one():
+ def forward(
+ input_ids = None,
+ logits_to_keep = 0,
+ **kwargs,
+ ): ...
+
+ kwargs = {"input_ids": "x"}
+ name = _minimise_logits_kwarg(_sig(forward), (), kwargs)
+ assert name == "logits_to_keep"
+ assert (
+ kwargs["logits_to_keep"] == 1
+ ), "0 means every position, which is the whole cost being avoided"
+
+
+def test_the_legacy_kwarg_is_used_when_that_is_what_the_model_takes():
+ """Not transformers -- measured, 4.57.6 through 5.15.0 all take the modern
+ name and none takes this one. It is Unsloth's own patched forwards
+ (`models/llama.py`, `models/mistral.py`) and the VLM stacks
+ `models/vision.py` probes the old name for.
+ """
+
+ def forward(input_ids = None, num_logits_to_keep = 0): ...
+
+ kwargs = {"input_ids": "x"}
+ name = _minimise_logits_kwarg(_sig(forward), (), kwargs)
+ assert name == "num_logits_to_keep"
+ assert kwargs["num_logits_to_keep"] == 1
+ assert "logits_to_keep" not in kwargs, "must not send a kwarg this forward rejects"
+
+
+def test_a_positionally_bound_width_is_not_worked_around_via_the_other_name():
+ """The dangerous shape: positional modern name, plus a `**kwargs` sink.
+
+ Falling through to the legacy name here would set a kwarg this forward does
+ not declare. `**kwargs` accepts it silently, the model ignores it, no logits
+ are saved, and the non-None return arms the absent-hidden-states re-run --
+ a second full forward bought for nothing. Give up instead.
+ """
+
+ def forward(
+ input_ids = None,
+ logits_to_keep = 0,
+ **kwargs,
+ ): ...
+
+ kwargs = {}
+ name = _minimise_logits_kwarg(_sig(forward), ("x", 512), kwargs)
+ assert name is None
+ assert kwargs == {}, "the caller's positional width must stand untouched"
+
+
+def test_the_modern_name_wins_when_a_forward_takes_both():
+ def forward(
+ input_ids = None,
+ logits_to_keep = 0,
+ num_logits_to_keep = 0,
+ ): ...
+
+ kwargs = {"input_ids": "x"}
+ assert _minimise_logits_kwarg(_sig(forward), (), kwargs) == "logits_to_keep"
+ assert "num_logits_to_keep" not in kwargs
+
+
+def test_a_caller_supplied_value_is_overridden_because_we_discard_the_logits():
+ def forward(input_ids = None, logits_to_keep = 0): ...
+
+ kwargs = {"input_ids": "x", "logits_to_keep": 512}
+ _minimise_logits_kwarg(_sig(forward), (), kwargs)
+ assert kwargs["logits_to_keep"] == 1
+
+
+def test_a_positional_value_is_left_alone():
+ """Passing it positionally and again by keyword is a TypeError."""
+
+ def forward(input_ids = None, logits_to_keep = 0): ...
+
+ kwargs = {}
+ name = _minimise_logits_kwarg(_sig(forward), ("x", 512), kwargs)
+ assert name is None
+ assert kwargs == {}
+
+
+def test_a_forward_that_cannot_take_it_is_left_alone():
+ def forward(input_ids = None, attention_mask = None): ...
+
+ kwargs = {"input_ids": "x"}
+ assert _minimise_logits_kwarg(_sig(forward), (), kwargs) is None
+ assert kwargs == {"input_ids": "x"}
+
+
+def test_var_keyword_counts_as_accepting_it():
+ def forward(input_ids = None, **kwargs): ...
+
+ kwargs = {"input_ids": "x"}
+ assert _minimise_logits_kwarg(_sig(forward), (), kwargs) == "logits_to_keep"
+
+
+def test_a_forward_given_labels_keeps_its_logits():
+ """A model that computes its own loss needs the real thing."""
+
+ def forward(
+ input_ids = None,
+ labels = None,
+ logits_to_keep = 0,
+ ): ...
+
+ kwargs = {"input_ids": "x", "labels": "y"}
+ assert _minimise_logits_kwarg(_sig(forward), (), kwargs) is None
+ assert "logits_to_keep" not in kwargs
+
+
+def test_labels_of_none_does_not_count_as_labels():
+ def forward(
+ input_ids = None,
+ labels = None,
+ logits_to_keep = 0,
+ ): ...
+
+ kwargs = {"input_ids": "x", "labels": None}
+ assert _minimise_logits_kwarg(_sig(forward), (), kwargs) == "logits_to_keep"
+
+
+# --------------------------------------------------------------------------
+# end to end through the installed wrapper
+# --------------------------------------------------------------------------
+class _Recorder:
+ """A model whose lm_head cost is proportional to the positions it is asked for."""
+
+ def __init__(
+ self,
+ n_layers = 4,
+ seq = 8,
+ accepts = "logits_to_keep",
+ ):
+ self.n_layers, self.seq, self.accepts = n_layers, seq, accepts
+ self.projected_positions = None
+ self.calls = 0
+ if accepts == "logits_to_keep":
+
+ def forward(
+ input_ids = None,
+ logits_to_keep = 0,
+ output_hidden_states = False,
+ return_dict = False,
+ ):
+ return self._run(logits_to_keep, output_hidden_states)
+ elif accepts == "num_logits_to_keep":
+
+ def forward(
+ input_ids = None,
+ num_logits_to_keep = 0,
+ output_hidden_states = False,
+ return_dict = False,
+ ):
+ return self._run(num_logits_to_keep, output_hidden_states)
+ else:
+
+ def forward(
+ input_ids = None,
+ output_hidden_states = False,
+ return_dict = False,
+ ):
+ return self._run(0, output_hidden_states)
+
+ self.forward = forward
+
+ def _run(self, keep, output_hidden_states):
+ self.calls += 1
+ kept = self.seq if not keep else keep
+ self.projected_positions = kept
+ return FakeModelOutput(
+ logits = [["logit"] * 202048] * kept,
+ hidden_states = tuple(f"layer{i}" for i in range(self.n_layers + 1))
+ if output_hidden_states
+ else None,
+ )
+
+
+def hidden_states_on(monkeypatch):
+ monkeypatch.setenv("UNSLOTH_RETURN_HIDDEN_STATES", "1")
+
+
[email protected]("accepts", ["logits_to_keep", "num_logits_to_keep"])
+def test_the_wrapper_asks_for_one_position_not_the_whole_sequence(hidden_states_on, accepts):
+ model = _Recorder(accepts = accepts)
+ assert _install(model) is not False or True # install, whatever it returns
+ model.forward(input_ids = "x")
+ assert model.projected_positions == 1, (
+ f"projected {model.projected_positions} of {model.seq} positions over the "
+ f"full vocabulary, then discarded them"
+ )
+
+
+def test_the_wrapper_returns_the_last_layer_as_logits(hidden_states_on):
+ model = _Recorder()
+ _install(model)
+ out = model.forward(input_ids = "x")
+ assert out.logits == "layer4"
+
+
+def test_the_wrapper_leaves_no_spare_layers_on_the_output(hidden_states_on):
+ model = _Recorder()
+ _install(model)
+ out = model.forward(input_ids = "x")
+ assert (
+ out["hidden_states"] is None
+ ), "5 layer tensors would each be copied to the input device by accelerate"
+
+
+def test_a_model_that_takes_no_such_kwarg_still_gets_hidden_states(hidden_states_on):
+ model = _Recorder(accepts = None)
+ _install(model)
+ out = model.forward(input_ids = "x")
+ assert out.logits == "layer4"
+ assert out["hidden_states"] is None
+
+
+def test_nothing_changes_when_hidden_states_were_not_asked_for(monkeypatch):
+ monkeypatch.delenv("UNSLOTH_RETURN_HIDDEN_STATES", raising = False)
+ model = _Recorder()
+ _install(model)
+ out = model.forward(input_ids = "x")
+ assert (
+ model.projected_positions == model.seq
+ ), "outside the hidden-states path this must be the untouched forward"
+ assert out.logits != "layer4"
+
+
+def test_a_forward_that_rejects_the_value_is_retried_without_it(hidden_states_on):
+ """Signature says yes, forward says no. Losing hidden states over an
+ optimisation would be a worse outcome than not optimising."""
+ seen = []
+
+ class Fussy:
+ def forward(
+ self,
+ input_ids = None,
+ logits_to_keep = 0,
+ output_hidden_states = False,
+ return_dict = False,
+ ):
+ seen.append(logits_to_keep)
+ if logits_to_keep == 1:
+ raise TypeError("logits_to_keep must be 0 for this model")
+ return FakeModelOutput(
+ logits = "raw",
+ hidden_states = ("a", "b") if output_hidden_states else None,
+ )
+
+ model = Fussy()
+ _install(model)
+ out = model.forward(input_ids = "x")
+ assert seen == [1, 0], f"expected a retry without the kwarg, got {seen}"
+ assert out.logits == "b"
+
+
+def test_an_unrelated_type_error_still_propagates(hidden_states_on):
+ class Broken:
+ def forward(
+ self,
+ input_ids = None,
+ logits_to_keep = 0,
+ output_hidden_states = False,
+ return_dict = False,
+ ):
+ raise TypeError("something else entirely")
+
+ model = Broken()
+ _install(model)
+ with pytest.raises(TypeError, match = "something else entirely"):
+ model.forward(input_ids = "x")
+
+
+def test_a_retry_that_is_then_refused_hidden_states_still_falls_back(hidden_states_on):
+ """A forward can refuse the logits limiter and the hidden states one after
+ the other -- a wrapper that splats **kwargs into a sub-module does exactly
+ that. The second refusal must reach the same raw-logits fallback, not
+ escape the wrapper and take the GRPO step down with it."""
+ seen = []
+
+ class Splatter:
+ def forward(
+ self,
+ input_ids = None,
+ logits_to_keep = 0,
+ **kwargs,
+ ):
+ seen.append((logits_to_keep, kwargs.get("output_hidden_states", False)))
+ if logits_to_keep:
+ raise TypeError("sub_forward() got an unexpected keyword argument 'logits_to_keep'")
+ if kwargs.get("output_hidden_states"):
+ raise TypeError(
+ "sub_forward() got an unexpected keyword argument 'output_hidden_states'"
+ )
+ return FakeModelOutput(logits = "raw", hidden_states = None)
+
+ model = Splatter()
+ _install(model)
+ out = model.forward(input_ids = "x")
+ assert seen == [(1, True), (0, True), (0, False)], seen
+ assert out.logits == "raw"
+
+
+def test_a_forward_that_ignores_output_hidden_states_gets_its_logits_back(hidden_states_on):
+ """`logits_to_keep = 1` is only safe because the logits get overwritten. If
+ no hidden states come back they ARE the return value, and one position is
+ not the completion window GRPO asked for."""
+ seen = []
+
+ class Deaf:
+ def forward(
+ self,
+ input_ids = None,
+ logits_to_keep = 0,
+ output_hidden_states = False,
+ return_dict = False,
+ ):
+ seen.append(logits_to_keep)
+ kept = 4 if not logits_to_keep else logits_to_keep
+ return FakeModelOutput(logits = ["logit"] * kept, hidden_states = None)
+
+ model = Deaf()
+ _install(model)
+ out = model.forward(input_ids = "x", logits_to_keep = 4)
+ assert seen == [1, 4], f"expected a re-run on the caller's own value, got {seen}"
+ assert len(out.logits) == 4, "GRPO slices the completion window out of these"
+
+
+def test_labels_passed_positionally_still_keep_their_logits():
+ """The keyword lookup misses a positional `labels`, but the model's own loss
+ needs every position just the same."""
+
+ def forward(
+ input_ids = None,
+ attention_mask = None,
+ position_ids = None,
+ past_key_values = None,
+ inputs_embeds = None,
+ labels = None,
+ logits_to_keep = 0,
+ output_hidden_states = False,
+ return_dict = True,
+ ):
+ pass
+
+ signature = inspect.signature(forward)
+ forward_kwargs = {"output_hidden_states": True, "return_dict": True}
+ used = _minimise_logits_kwarg(
+ signature,
+ ("ids", None, None, None, None, "labels"),
+ forward_kwargs,
+ )
+ assert used is None, "a one-position logits tensor cannot serve a labels loss"
+ assert "logits_to_keep" not in forward_kwargs
diff --git a/unsloth/models/rl.py b/unsloth/models/rl.py
index 52f0a75e1e8..ad01d486c98 100644
--- a/unsloth/models/rl.py
+++ b/unsloth/models/rl.py
@@ -21,6 +21,7 @@ import torch
from typing import Any, Callable, Dict, List, Literal, Optional, Tuple, Union
import copyreg
import importlib
+import collections
import inspect
import os
import re
@@ -1797,6 +1798,98 @@ def _note_grpo_hidden_states_success(model):
setattr(model, _UNSLOTH_GRPO_HIDDEN_STATES_DEGRADED_ATTR, False)
+def _minimise_logits_kwarg(forward_signature, args, forward_kwargs):
+ """Ask the model for as few logits as it will give us, and say which kwarg did it.
+
+ We are about to overwrite `outputs.logits` with hidden states, so every
+ logit the forward computes is thrown away. transformers spells the limit
+ `logits_to_keep` -- measured on 4.57.6, 5.0.0 and 5.15.0, all three declare
+ that name and none declares `num_logits_to_keep`, so the second name is not
+ for them. It is for us: `unsloth/models/llama.py` and `mistral.py` patch in
+ forwards declaring both, and `unsloth/models/vision.py` probes for the old
+ name FIRST because some VLM stacks still carry only it. Whichever name a
+ forward takes, it reads the value as
+ `slice(-value, None)`, so the DEFAULT of 0 becomes `slice(0, None)` -- the
+ whole sequence. The GRPO trainer does not pass a value at all, so the
+ lm_head projects every prompt and completion position over the full
+ vocabulary and, for the softcapped models, multiplies the result twice more.
+
+ Muse Glimmer 30B on a Kaggle 2xT4 measured that at a 1002 MiB allocation
+ per chunk, over a 202048-wide vocabulary. On one card it is invisible: the
+ trainer's `del outputs` frees it a line later. On a layer-split model
+ accelerate copies it to the other card first and the run dies there.
+
+ 1, not 0: 0 means "all of them", and a model that computes its own loss from
+ `labels` needs real logits, so that case is left alone.
+ """
+ if forward_kwargs.get("labels") is not None:
+ return None
+ try:
+ bound = forward_signature.bind_partial(*args, **forward_kwargs)
+ except TypeError:
+ return None
+ # A forward given `labels` positionally lands it in `bound.arguments` and
+ # never in `forward_kwargs`, so the lookup above cannot see it, and the loss
+ # the model then computes for itself would be one position wide.
+ if bound.arguments.get("labels") is not None:
+ return None
+ accepts_var_keyword = any(
+ parameter.kind == inspect.Parameter.VAR_KEYWORD
+ for parameter in forward_signature.parameters.values()
+ )
+ for name in ("logits_to_keep", "num_logits_to_keep"):
+ declared = name in forward_signature.parameters
+ if not declared and not accepts_var_keyword:
+ continue
+ # Passing it positionally already and then also by keyword is a
+ # TypeError. Give up entirely rather than moving to the next name: a
+ # caller who bound a width positionally has said what it wants, and
+ # reaching for the OTHER spelling would either fight that width or, on a
+ # forward that only understands the one it was handed and swallows the
+ # rest in `**kwargs`, be accepted and ignored -- no saving, and a
+ # non-None return arms the re-run below for nothing.
+ if name in bound.arguments and name not in forward_kwargs:
+ return None
+ forward_kwargs[name] = 1
+ return name
+ return None
+
+
+def _drop_spare_hidden_states(outputs):
+ """Detach every hidden-state layer from `outputs`; the caller keeps the last.
+
+ `outputs.hidden_states = None` does NOT do this. `ModelOutput.__setattr__`
+ is
+
+ if name in field_names and value is not None:
+ super().__setitem__(name, value)
+ super().__setattr__(name, value)
+
+ so assigning None sets the attribute and leaves the mapping entry holding
+ the full tuple, and `ModelOutput` blocks `__delitem__`, `pop`, `update` and
+ `setdefault` outright. Every consumer that walks the object as a mapping --
+ accelerate's `send_to_device`, which is the one that matters here -- still
+ sees and copies all of it. Writing through `OrderedDict.__setitem__` is what
+ actually clears it, and leaves the mapping and the attribute agreeing on
+ None, which is the state a forward returns with `output_hidden_states=False`.
+ """
+ try:
+ if isinstance(outputs, collections.OrderedDict) and "hidden_states" in outputs:
+ collections.OrderedDict.__setitem__(outputs, "hidden_states", None)
+ object.__setattr__(outputs, "hidden_states", None)
+ elif isinstance(outputs, dict) and "hidden_states" in outputs:
+ outputs["hidden_states"] = None
+ elif hasattr(outputs, "hidden_states"):
+ outputs.hidden_states = None
+ except Exception:
+ # A frozen or exotic output object is not worth failing the step over;
+ # the caller has already taken the layer it needs.
+ logger.debug(
+ "Unsloth: could not drop spare GRPO hidden states.",
+ exc_info = True,
+ )
+
+
def _replace_outputs_logits(outputs, hidden_states):
if hasattr(outputs, "logits"):
outputs.logits = hidden_states
@@ -1846,28 +1939,74 @@ def _install_grpo_hidden_states_forward_wrapper(model):
num_logits_to_keep = _get_num_logits_to_keep(forward_signature, args, forward_kwargs)
forward_kwargs["output_hidden_states"] = True
forward_kwargs["return_dict"] = True
- try:
- outputs = original_forward(*args, **forward_kwargs)
- except TypeError as error:
- if "output_hidden_states" not in str(error) and "return_dict" not in str(error):
- raise
+ logits_kwarg = _minimise_logits_kwarg(
+ forward_signature,
+ args,
+ forward_kwargs,
+ )
+
+ def rejected_hidden_states(message):
+ return "output_hidden_states" in message or "return_dict" in message
+
+ def forward_without_hidden_states():
_warn_grpo_hidden_states_fallback_once(
target_model,
f"Unsloth: GRPO fallback could not request hidden states for unsupported model {model_name}; using logits directly.",
)
return original_forward(*args, **kwargs)
+ try:
+ outputs = original_forward(*args, **forward_kwargs)
+ except TypeError as error:
+ message = str(error)
+ if logits_kwarg is None or logits_kwarg not in message:
+ if not rejected_hidden_states(message):
+ raise
+ return forward_without_hidden_states()
+ # The signature advertised the parameter but the forward refuses
+ # the value. Retry without our minimisation rather than losing
+ # hidden states entirely over an optimisation -- and send the retry
+ # through the same fallback, since a forward that splats **kwargs
+ # into a sub-module can refuse the logits limiter and the hidden
+ # states one after the other.
+ forward_kwargs.pop(logits_kwarg, None)
+ logits_kwarg = None
+ try:
+ outputs = original_forward(*args, **forward_kwargs)
+ except TypeError as retry_error:
+ if not rejected_hidden_states(str(retry_error)):
+ raise
+ return forward_without_hidden_states()
+
hidden_states = getattr(outputs, "hidden_states", None)
if hidden_states is None or len(hidden_states) == 0:
_warn_grpo_hidden_states_fallback_once(
target_model,
f"Unsloth: GRPO fallback did not receive hidden states for unsupported model {model_name}; using logits directly.",
)
- return outputs
+ if logits_kwarg is None:
+ return outputs
+ # `outputs.logits` is the return value now, and we asked for a single
+ # position because we meant to throw the logits away. GRPO drops the
+ # last one and slices the completion window out of what is left, so
+ # one position leaves it nothing. Put the caller's own limit back --
+ # absent means every position, which is what a model that ignores
+ # `logits_to_keep` would have returned anyway -- and re-run.
+ if logits_kwarg in kwargs:
+ forward_kwargs[logits_kwarg] = kwargs[logits_kwarg]
+ else:
+ forward_kwargs.pop(logits_kwarg, None)
+ return original_forward(*args, **forward_kwargs)
hidden_states = hidden_states[-1]
if num_logits_to_keep != 0:
hidden_states = hidden_states[:, -num_logits_to_keep:, :]
+ # Only the last layer is ever read. Every earlier layer is still hanging
+ # off `outputs`, and on a multi-GPU dispatch accelerate's
+ # AlignDevicesHook.post_forward walks the whole returned object and
+ # copies every tensor in it to the input device, so keeping them costs a
+ # cross-device copy per layer as well as the memory.
+ _drop_spare_hidden_states(outputs)
_note_grpo_hidden_states_success(target_model)
return _replace_outputs_logits(outputs, hidden_states)