Skip to content

Fix GRPO full finetuning returning logits instead of hidden states - #5898

Closed
danielhanchen wants to merge 5 commits into
mainfrom
grpo-fullft-return-hidden-states
Closed

danielhanchen wants to merge 5 commits into
mainfrom
grpo-fullft-return-hidden-states

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

Fixes unslothai/unsloth-zoo#708. GRPO full finetuning crashes in the log-probability step because the model returns logits instead of hidden states, so the chunked selective log-softmax tries to project already projected logits through lm_head again:

RuntimeError: mat1 and mat2 shapes cannot be multiplied (Nx151936 and 896x151936)

(151936 = vocab, 896 = hidden). Under torch.compile the same site shows a Dynamo "same reduction dim" error.

Root cause

GRPO sets UNSLOTH_RETURN_HIDDEN_STATES=1 and expects the forward to return last hidden states; the trainer projects them in chunks itself. There are two ways a model satisfies this:

  • Native: a compiled or fast forward carrying the __UNSLOTH_SUPPORTS_RETURN_HIDDEN_STATES__ marker returns hidden states directly.
  • Fallback: _install_grpo_hidden_states_forward_wrapper wraps the forward to request output_hidden_states=True and swap logits <- hidden_states[-1].

In full finetuning the model is a plain *ForCausalLM with the stock HF forward (no marker), so the fallback is supposed to handle it, but:

  1. _grpo_hidden_states_wrap_target descends into the inner trunk (model.model, a *Model with no lm_head) for a non-PEFT CausalLM. The wrapper then sits below lm_head; the outer forward re-applies lm_head and still returns logits. (LoRA/QLoRA avoid this because get_base_model() returns the CausalLM head, which is why they were unaffected.)
  2. Even if retargeted to the head, wrapping the accelerate-managed top-level forward collides with accelerate's _ForwardRedirection, which injects the module as a leading positional arg (embedding(): indices must be Tensor, not ...ForCausalLM).

Changes (unsloth/models/rl.py)

  • Prefer an lm_head passthrough (_install_grpo_lm_head_passthrough): when UNSLOTH_RETURN_HIDDEN_STATES=1, short-circuit lm_head to return its input, so the stock forward yields .logits == hidden and the full vocab projection is skipped. This is the memory-efficient path (it matches the intent of the chunked log-prob approach) and it does not wrap the accelerate-managed top-level forward, so there is no bound-self collision. The lm_head weight is untouched. It sets the support marker so the forward wrapper is not additionally installed.
  • Harden the forward-wrapper fallback for models without a discoverable lm_head: _grpo_hidden_states_wrap_target no longer descends past the module that owns lm_head, and wrapped_forward strips an injected leading module argument.

Behavior

  • Full finetuning GRPO: the forward now returns hidden states (hidden dim), the chunked log-softmax projects them itself, and the run trains. The vocab projection is skipped in the log-prob forward, so it is also more memory efficient.
  • LoRA / QLoRA: unchanged. They already returned hidden states via the PEFT get_base_model() path; the passthrough only changes behavior when UNSLOTH_RETURN_HIDDEN_STATES=1 and is a no-op otherwise.
  • Compiled / native path: unchanged. When the marker is set the fallback is skipped entirely.

Validation

On unsloth/Qwen2.5-0.5B-Instruct, eager (with unsloth-zoo#707 applied so the rollout reaches the log-prob step):

  • Full finetuning GRPO, before: mat1 and mat2 shapes cannot be multiplied (4x151936 and 896x151936).
  • Full finetuning GRPO, after: the log-prob forward returns hidden states (896), and the run trains to a finite loss.
  • LoRA GRPO: trains, identical with and without the change.

Related

In full finetuning the model reaches GRPO as a plain *ForCausalLM with the
stock forward, so it has no UNSLOTH_RETURN_HIDDEN_STATES branch and no
support marker. The fallback then mis-targets the inner trunk (no lm_head)
via _grpo_hidden_states_wrap_target, so the outer forward re-applies lm_head
and the chunked log-softmax receives logits (vocab) instead of hidden states
(hidden), crashing in the lm_head matmul.

Prefer an lm_head passthrough: when UNSLOTH_RETURN_HIDDEN_STATES=1, short
circuit lm_head to return its input so the forward yields logits == hidden
and the vocab projection is skipped (memory efficient). Also harden the
forward-wrapper fallback for models without a discoverable lm_head: do not
descend past the lm_head owner, and tolerate an injected leading module arg
from accelerate. No-op for LoRA/QLoRA and when the flag is unset.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a preferred hidden-states path for plain causal language models during GRPO training by short-circuiting the lm_head to return its input (hidden states) when UNSLOTH_RETURN_HIDDEN_STATES is enabled. This avoids wrapping the top-level forward method and prevents logits from leaking. Feedback on this PR highlights a potential issue in passthrough_forward where, if invoked as a bound method, args[0] would incorrectly return the lm_head module itself instead of the input tensor. A robust code suggestion is provided to handle this case and gracefully manage empty arguments.

Comment thread unsloth/models/rl.py
Comment on lines +737 to +740

original_lm_head_forward = lm_head.forward

def passthrough_forward(*args, **kwargs):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

If passthrough_forward is invoked as a bound method (or if self is explicitly passed as the first positional argument, which can happen under certain execution frameworks or tracing/compilation wrappers), args[0] will be the lm_head module instance itself. In this scenario, returning args[0] would incorrectly return the module instead of the actual input tensor (which would be args[1]).

Additionally, if both args and kwargs are empty, calling next(iter(kwargs.values())) will raise a StopIteration exception instead of a standard TypeError.

We can make this robust by checking if args[0] is lm_head and handling empty arguments gracefully.

Suggested change
original_lm_head_forward = lm_head.forward
def passthrough_forward(*args, **kwargs):
def passthrough_forward(*args, **kwargs):
if os.environ.get("UNSLOTH_RETURN_HIDDEN_STATES", "0") == "1":
actual_args = args[1:] if (args and args[0] is lm_head) else args
if actual_args:
return actual_args[0]
if kwargs:
return next(iter(kwargs.values()))
raise TypeError("forward() missing 1 required positional argument: 'input'")
return original_lm_head_forward(*args, **kwargs)

@danielhanchen

Copy link
Copy Markdown
Member Author

Validated end-to-end on a real Tesla T4 (sm_75, no native bf16, torch 2.11.0+cu128, transformers 4.57.6, trl 0.25.1). I stacked all four GRPO full finetuning fixes into one test branch per repo (unsloth #5880 + #5898, unsloth_zoo #707 + #709) and ran tiny GRPO on unsloth/Qwen2.5-0.5B (dtype=float16, num_generations=2, max_steps=10, length reward).

Versions: unsloth 2026.5.8 (940fe0b), unsloth_zoo 2026.5.4 (14b0e30).

Results, all with DECISION fp16=True bf16=False AMP=fp16:

  • full finetuning, eager (UNSLOTH_COMPILE_DISABLE=1): TRAINED OK, 10/10 steps, train_loss 0.009076, finite.
  • full finetuning, compiled: TRAINED OK, 10/10 steps, train_loss 0.010111, finite.
  • LoRA: TRAINED OK, 10/10 steps, train_loss 0.010101, finite.

No index_copy_(): self Float vs source Half (that is the rollout cache fix, unsloth_zoo #707), and no mat1 and mat2 shapes cannot be multiplied (8x151936 and 896x151936). With this PR the chunked log-softmax receives hidden states again, so #708 is gone in both the eager and compiled paths.

The rollout is computing real signal: KL grows from 0 to about 0.065 over 10 steps, and the full finetuning completion length moves from 32 toward the length target (32 to 19.5 by step 10, reward from -8.5 to -2.5). LoRA shows the same pattern. LGTM.

@Datta0

Datta0 commented Jun 1, 2026

Copy link
Copy Markdown
Contributor

#5142
unslothai/unsloth-zoo#609
I previously made compiler fixes to address the same. I think these should be enough for this? If not I'd like to understand why

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 82e1468dcb

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +1118 to +1121
with (
_temporary_unsloth_return_hidden_states(),
torch.amp.autocast(device_type = DEVICE_TYPE, dtype = self._autocast_dtype),
):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Avoid Python 3.10-only parenthesized with syntax

Because pyproject.toml declares support for Python >=3.9, this parenthesized multi-context with ( syntax makes rl_replacements.py fail to parse on Python 3.9 before any tests or training code can run; the same syntax is also introduced later in this file. Use nested with statements or a backslash-continued multi-context with to keep the module importable on the supported Python range.

Useful? React with 👍 / 👎.

@danielhanchen

Copy link
Copy Markdown
Member Author

Main already declines to descend past the module owning lm_head in _grpo_hidden_states_wrap_target and strips the injected leading module arg in wrapped_forward, so those two parts overlap. Could you rebase and narrow this to the lm_head passthrough plus the UNSLOTH_RETURN_HIDDEN_STATES restore, which main still leaves set?

@danielhanchen

Copy link
Copy Markdown
Member Author

Closing this as superseded, and thanks for the root cause work, which is what pointed at the right fix.

Both causes described here are fixed on main. #8231 stopped _grpo_hidden_states_wrap_target descending into the decoder body, so a plain *ForCausalLM in full finetuning resolves to the module that owns lm_head; it decides that by behaviour, asking get_output_embeddings(), rather than by model name, which also makes it right for the vision classes and for Llama4ForConditionalGeneration, whose head lives behind an override. The same PR added the leading positional argument strip in wrapped_forward for accelerate's extract_model_from_parallel rebind.

The memory motive is covered by #8576, which pins logits_to_keep to 1 whenever the logits are about to be replaced and drops the unread hidden state layers through the mapping rather than the attribute. That measured 1094 to 990 MiB on Qwen2.5-0.5B with an identical returned tensor. Both live inside the fallback wrapper installed for exactly the non-PEFT full finetuning model this was about, so the full finetune path is covered and not only LoRA, and the vision path shares the install site.

Main also carries tests/test_grpo_hidden_states_wrap_target.py and tests/test_grpo_hidden_states_logits_cost.py pinning both behaviours.

One piece here has no equivalent on main: the scoped context manager for UNSLOTH_RETURN_HIDDEN_STATES. We still set and reset that flag with plain assignments, so an exception in between leaks it and the reset writes "0" rather than restoring the previous value. That is a small separate cleanup and I will pick it up on its own.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

GRPO full finetuning: chunked log-softmax receives logits instead of hidden states

2 participants