Repository navigation
Fix GRPO full finetuning returning logits instead of hidden states - #5898
danielhanchen wants to merge 5 commits into
Conversation
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.
There was a problem hiding this comment.
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.
|
|
||
| original_lm_head_forward = lm_head.forward | ||
|
|
||
| def passthrough_forward(*args, **kwargs): |
There was a problem hiding this comment.
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.
| 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) |
|
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
No 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. |
|
#5142 |
There was a problem hiding this comment.
💡 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".
| with ( | ||
| _temporary_unsloth_return_hidden_states(), | ||
| torch.amp.autocast(device_type = DEVICE_TYPE, dtype = self._autocast_dtype), | ||
| ): |
There was a problem hiding this comment.
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 👍 / 👎.
|
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? |
|
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 The memory motive is covered by #8576, which pins Main also carries One piece here has no equivalent on main: the scoped context manager for |
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_headagain:(151936 = vocab, 896 = hidden). Under
torch.compilethe same site shows a Dynamo "same reduction dim" error.Root cause
GRPO sets
UNSLOTH_RETURN_HIDDEN_STATES=1and expects the forward to return last hidden states; the trainer projects them in chunks itself. There are two ways a model satisfies this:__UNSLOTH_SUPPORTS_RETURN_HIDDEN_STATES__marker returns hidden states directly._install_grpo_hidden_states_forward_wrapperwraps the forward to requestoutput_hidden_states=Trueand swaplogits <- hidden_states[-1].In full finetuning the model is a plain
*ForCausalLMwith the stock HF forward (no marker), so the fallback is supposed to handle it, but:_grpo_hidden_states_wrap_targetdescends into the inner trunk (model.model, a*Modelwith nolm_head) for a non-PEFT CausalLM. The wrapper then sits belowlm_head; the outer forward re-applieslm_headand still returns logits. (LoRA/QLoRA avoid this becauseget_base_model()returns the CausalLM head, which is why they were unaffected.)_ForwardRedirection, which injects the module as a leading positional arg (embedding(): indices must be Tensor, not ...ForCausalLM).Changes (
unsloth/models/rl.py)lm_headpassthrough (_install_grpo_lm_head_passthrough): whenUNSLOTH_RETURN_HIDDEN_STATES=1, short-circuitlm_headto return its input, so the stock forward yields.logits == hiddenand 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. Thelm_headweight is untouched. It sets the support marker so the forward wrapper is not additionally installed.lm_head:_grpo_hidden_states_wrap_targetno longer descends past the module that ownslm_head, andwrapped_forwardstrips an injected leading module argument.Behavior
get_base_model()path; the passthrough only changes behavior whenUNSLOTH_RETURN_HIDDEN_STATES=1and is a no-op otherwise.Validation
On
unsloth/Qwen2.5-0.5B-Instruct, eager (with unsloth-zoo#707 applied so the rollout reaches the log-prob step):mat1 and mat2 shapes cannot be multiplied (4x151936 and 896x151936).Related
chunked_hidden_states_selective_log_softmax(skip the projection when the input is already logits) as cheap insurance.