Skip to content

GRPO: dispatch on width at the remaining lm_head matmul call sites - #8204

Merged
danielhanchen merged 9 commits into
unslothai:mainfrom
danielhanchen:fix/grpo-width-dispatch-remaining-call-sites
Aug 11, 2026
Merged

danielhanchen merged 9 commits into
unslothai:mainfrom
danielhanchen:fix/grpo-width-dispatch-remaining-call-sites

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

What

_get_per_token_logps_and_entropies sets UNSLOTH_RETURN_HIDDEN_STATES=1 and then treats outputs.logits as hidden states. That only holds when the forward that ran 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]

The VLM arm of the padded loop already dispatched on width:

if logits_chunk.shape[-1] == lm_head.shape[1]:

Three sites in the same function did not:

  • the sequence-packing flattened forward
  • the packing first-use verifier
  • the text arm of the padded loop, pixel_values is None

This PR gives all three the guard the VLM arm already has.

Why the text arm is the one that crashes

The two packing sites sit inside except Exception, so the raise there is swallowed: the batch drops 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. Wrong, but quiet.

The text arm has no enclosing try, so it is what surfaces to the user. Qwen2.5 in nb/NeMo-Gym-Sudoku.ipynb is a text model, so that is the notebook's failure.

On the error message

s33 is not an unprovable free symbol. Compiling the helper with dynamic = True, fullgraph = True against a genuine nn.Parameter lm_head and correct-width hidden states succeeds across shapes: the hidden-size symbol is backed and Eq(s33, 1536) specialises on the real value. The message only appears when the tensor genuinely is the wrong width, and the 151936 in it is the vocab size. So this is a missing dispatch at the call site, not a compile or guard problem.

Companion

unslothai/unsloth-zoo#1019 fixes the same gap on zoo's side, at the PrefixGrouper forward in grpo_accumulated_loss.

Zoo alone does not fix the notebook. The two are separate copies of the machinery: zoo's grpo_accumulated_loss is the grad path, and this function is the no-grad path that computes the old and reference logprobs. The live crash is in this file, which never received the width dispatch that zoo's compute_logprobs_chunk has had. The hardware run below pins zoo to unmodified main for exactly that reason.

The PrefixGrouper call in this function is the same shape of gap and is left alone here. It is inside the same except Exception, so it degrades to the padded result rather than crashing, and it needs the wrapper approach zoo #1019 uses rather than an inline branch. Keeping this PR to the crash path.

Compatibility

No new imports and no new mechanism: chunked_selective_log_softmax is already imported at the top of this file and already called by the VLM arm, and the generated trainer module already defines it. The guard is the same lm_head.shape[1] the function already computes as hidden_dim for the chunk autotuner. lm_head is get_output_embeddings().weight, so it stays a 2-D [vocab, hidden] parameter whether the head is an nn.Linear, a bare nn.Parameter or tied to the input embeddings.

The raw-logits branch skips the matmul and also the scale and softcapping, because the model forward already applied them. That is the same contract the VLM arm's fallback has.

Hardware

nb/NeMo-Gym-Sudoku.ipynb on Colab, unsloth-zoo pinned to unmodified main, torch 2.11.0+cu128, transformers 5.5.0, trl 0.24.0, peft 0.19.1.

Before, on the same harness: CONFIRMED_REGRESSION at code cell 11, the TorchRuntimeError above.

After: PASS. Three finite GRPO losses logged through UnslothGRPOTrainer, then inference, merge_16bit and a Q4_K_M GGUF export all verified.

The notebook also needs unslothai/notebooks#326 to reach the failing cell at all.

Tests

Three files, 20 tests.

  • tests/test_grpo_padded_raw_logits.py, 9 tests. Lifts the padded loop out of the live source with ast and execs it against a stub forward. Covers the text arm at both widths, the VLM arm at both widths, temperature, and that the raw-logits path skips softcapping while the hidden-states path applies it.
  • tests/test_grpo_packed_raw_logits_nograd.py, 4 tests. Same approach for the packing block. Because the failure there is swallowed, the assertions read the block's own locals: _pk_use, _pk_result, _pk_ref, _pk_diff and the per-row forward count, so the verifier call site is covered on its own rather than incidentally.
  • tests/test_grpo_width_dispatch_sites.py, 7 tests. Structural, over the AST: every call to the hidden-states helper in this function is inside a width comparison against lm_head.shape[1], every such guard has a raw-logits else, and no fallback passes the scale or softcap arguments.

All three locate their target by AST shape, never by searching source text, so a comment cannot satisfy them. Both behavioural files use the real zoo helpers when importable and eager mirrors when not, so they run on a CPU-only runner and never skip.

Reverting each of the three guards individually turns tests red:

reverted site red
text arm 8
packing forward 7
packing verifier 7

Reverting the text arm reproduces the reported error in the test output. In each case the tests that stay green are the ones that should: the hidden-states paths and the untouched VLM arm.

Repo CPU suite, same invocation as the repo-cpu-tests job:

  • origin/main at 161a3017d: 6 failed, 5210 passed, 112 skipped, 23 deselected
  • this branch: 6 failed, 5230 passed, 112 skipped, 23 deselected

Same 6 failures either way, all in tests/studio/test_model_picker_contracts.py and tests/studio/test_update_release_notes.py, unrelated to this change and already addressed by #8197 and #8190. The delta is exactly the 20 tests added here.

@danielhanchen
danielhanchen requested a review from Datta0 as a code owner August 8, 2026 22:50

@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: 06a804ce65

ℹ️ About Codex in GitHub

Your team has set up Codex to 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 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread unsloth/models/rl_replacements.py Outdated
temperature = temperature,
)
# Guard: check if model returned hidden states or logits
if logits_chunk.shape[-1] == lm_head.shape[1]:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Disambiguate equal vocabulary and hidden widths

When an unpatched model has vocab_size == hidden_size, its real logits satisfy this width test and are incorrectly sent through chunked_hidden_states_selective_log_softmax, applying the lm_head a second time. This silently produces incorrect GRPO log probabilities; in the packed path, the per-row verifier makes the same misclassification and therefore still accepts the corrupted result. Use an explicit signal that the forward honored UNSLOTH_RETURN_HIDDEN_STATES, rather than relying solely on an ambiguous dimension comparison.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Correct. Fixed in f9b2449.

lm_head here is self.model.get_output_embeddings().weight, shape [vocab_size, hidden_size], so lm_head.shape[1] is the hidden size and a square head makes the test vacuous. There were four sites with the same guard, all inside _get_per_token_logps_and_entropies: the packed varlen forward (1878), the packed per-row verifier (1944), and the two padded branches (2134 text, 2173 VLM). With vocab_size == hidden_size the verifier misreads its own reference the same way, so _pk_diff compares corrupted against corrupted, comes out near zero, and it sets _unsloth_seq_packing_nograd_ok = True and stops re-verifying, exactly as you describe.

The explicit signals, both set outside this file:

  • __UNSLOTH_SUPPORTS_RETURN_HIDDEN_STATES__, written by unsloth_zoo.compiler (compiler.py:1806 on current zoo main) onto the generated class, and only on the path where apply_fused_lm_head actually substituted a cross_entropy_replacement_* template. Those templates are the ones that emit if RETURN_HIDDEN_STATES: logits = hidden_states, so the marker means precisely "this forward branches on the flag".
  • _unsloth_grpo_hidden_states_forward_wrapped, set by _install_grpo_hidden_states_forward_wrapper in unsloth/models/rl.py:733-734 for models the compiler did not rewrite. That wrapper can degrade to real logits, and it records the degradation as _unsloth_grpo_hidden_states_warning_issued before returning, so reading the pair right after a forward describes the call that just finished.

New helper _unsloth_grpo_returns_hidden_states(model, tensor, lm_head) now backs all four sites, and both it and _unsloth_grpo_hidden_states_signal are registered in RL_PRE_ITEMS["grpo_trainer"] so they reach the generated UnslothGRPOTrainer.

One deliberate narrowing: the signal is consulted only when the width test cannot decide, rather than overruling it outright. A vocab-wide tensor is real logits whatever any marker says, and the env var is re-set mid call in this same function (2077, and again at 1792 in the PrefixGrouper failure handler), so a marker-bearing forward can legitimately return logits; obeying the signal there would reintroduce the a and b must have same reduction dim matmul crash. In the other direction, the temporary_patches MoE forwards honour the env var themselves but never set the compiler marker, so a hidden-width tensor with a negative signal is still hidden states. So the width comparison remains decisive whenever vocab_size != hidden_size, and the signal only settles the square case. That also keeps an older unsloth_zoo that writes no marker on exactly today's behaviour, and costs two shape comparisons on the normal path.

Evidence. tests/test_grpo_hidden_states_signal.py (22 tests) covers the signal itself (marker on the class, through the PEFT get_base_model() and the DDP .module, wrapper positive, degraded wrapper negative, broken get_base_model swallowed, self-referencing chain terminates) and the dispatch, including a model whose every attribute read raises, which proves the signal is not consulted when the widths already decide. It then execs the real padded loop lifted from the live source against a vocab == hidden == 12 stub and checks the log probabilities against an independent log_softmax reference. tests/test_grpo_packed_raw_logits_nograd.py gains the same for the packed block and its per-row verifier.

Sabotage checked, with only the helper body reverted to the pure width test: 4 failed, 42 passed, exit 1. The padded failure is numerical rather than a crash, which is the silent part of your report: Mismatched elements: 8 / 8 (100.0%), greatest absolute difference 29.07. The packed failure shows the verifier accepting the corrupted result. Restored: 46 passed, exit 0. Wider run of the GRPO tests: 60 passed, exit 0. ruff check clean.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in f9b2449, with 8d0ca8d extending the same dispatch to the gradient path.

The width comparison is no longer the sole decider: _unsloth_grpo_hidden_states_signal(model) reports True/False when the forward's honouring of UNSLOTH_RETURN_HIDDEN_STATES can be established, and the width test is consulted only when it cannot. So a model with vocab_size == hidden_size is classified by what the forward actually did rather than by an ambiguous shape, and the packed path's per-row verifier inherits the same signal instead of repeating the misclassification.

Independently confirmed by oobabooga on current main: the fallback really could return raw logits while three GRPO call sites treated them as hidden states, the explicit signal covers the equal-widths case, all four unsloth_zoo replacements apply and the generated source compiles. They then ran fast_inference=True GRPO on a GPU with Qwen3-0.6B, vLLM 0.25.1, LoRA, three steps and repeated adapter syncs: finite loss, gradients, rewards and KL.

Re-verified here after merging current main into the branch (it was 160 commits behind, which is what its stale Backend CI reds were): 52 passed across the five test files, CPU-only.

…cide

The dispatch guard compared the forward's last dim against lm_head.shape[1],
which is the hidden size. On a model whose vocab_size equals its hidden size,
real logits satisfy that test and were sent through
chunked_hidden_states_selective_log_softmax, applying the lm_head a second
time and silently corrupting the log probabilities. The packed path's per-row
verifier made the same misclassification, so it compared corrupted against
corrupted and accepted the result.

Route all four call sites through _unsloth_grpo_returns_hidden_states, which
reads an explicit signal that the forward honoured UNSLOTH_RETURN_HIDDEN_STATES:
__UNSLOTH_SUPPORTS_RETURN_HIDDEN_STATES__ written by the zoo compiler, or the
_unsloth_grpo_hidden_states_forward_wrapped pair set by the rl.py fallback
wrapper. The width comparison stays: it is decisive whenever vocab_size differs
from hidden_size, and the signal is only consulted for the square case the
shape cannot answer, so an unsloth_zoo old enough to write no marker keeps
today's behaviour.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Already looking forward to the next diff.

Reviewed commit: f9b2449f27

ℹ️ About Codex in GitHub

Your team has set up Codex to 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 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@oobabooga

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 👍

Reviewed commit: 6c590d76b5

ℹ️ About Codex in GitHub

Your team has set up Codex to 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 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@oobabooga

Copy link
Copy Markdown
Member
  • Checked current main and confirmed the fallback can return raw logits while three GRPO call sites still treat the result as hidden states. The existing VLM path already has the correct guard.
  • Checked the follow-ups. The explicit signal covers the vocab_size == hidden_size case, and the same dispatch is applied to the gradient path. Verified all four unsloth_zoo replacements apply and the generated source compiles.
  • Merged the PR into current main and ran the 52 PR tests plus 3 related TRL CPU tests. All 55 passed.
  • Ran the actual GPU fast_inference=True GRPO test with Qwen3-0.6B, vLLM 0.25.1, LoRA, three training steps, and repeated adapter syncs. It passed with finite loss, gradients, rewards, and KL.

So this fixes a real issue and does not break the vLLM GRPO path.

I found no blockers and recommend merging the PR.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@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: 638c7353e2

ℹ️ About Codex in GitHub

Your team has set up Codex to 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 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +2519 to +2520
source = _GRPO_HIDDEN_STATES_WIDTH_DISPATCH.sub(replace_width_dispatch, source)
if replacements == 0:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Reject partially patched gradient dispatches

When a supported newer unsloth_zoo revision changes the formatting or expression at only some of these dispatch sites, this regex can still replace at least one site, so replacements != 0 suppresses the compatibility error while leaving the other width-only checks active. Since the dependency has no upper bound, that partial patch can silently restore incorrect gradients for square lm_heads; validate the expected number/all relevant dispatches rather than only rejecting zero matches.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Accepted, fixed in 61ec1c3. Confirmed against the installed unsloth_zoo 2026.8.3: grpo_accumulated_loss has three lm_head.shape references but only one of them is an if header, so replacements != 0 was equivalent to replacements != expected purely by accident of there being a single site.

CPU repro, pure text, no torch: lifted the patcher out with ast, took the real zoo source and injected two extra dispatch sites spelled the way a newer zoo plausibly would (lm_head.shape[-1], and a reversed comparison).

before: no error raised, 2 width-only dispatches left in the patched source
after: Unsloth: patched only 1 of 3 GRPO gradient hidden-state dispatches ... 2 still decide on width alone

The check is survivor-count, not a hardcoded expected count: a fixed number would reject any zoo that legitimately adds or removes a site, which is the forward-compatibility problem in reverse. A deliberately loose candidate regex counts if/elif headers referencing lm_head.shape before substituting, and zero must survive after.

Separately, and not fixable from this repo: zoo lines 1160, 1190, 1254 and 1566 call chunked_hidden_states_selective_log_softmax(..., lm_head, ...) with no width dispatch at all, so this regex cannot reach them and the zoo packed gradient path always takes the matmul. That needs an unsloth_zoo change.

114 passed, 1 skipped across the GRPO test files, CPU-only with CUDA_VISIBLE_DEVICES empty. Not verified: no live GRPO training step ran here (bitsandbytes fails to import with GPUs visible and unsloth refuses with them hidden), so the end-to-end patcher run is covered by a test that applies it to the real installed zoo source rather than by generating a trainer.

Comment thread unsloth/models/rl_replacements.py Outdated
Comment on lines +2476 to +2479
# the wrapper honours the flag unless it recorded that it could not
return not any(
getattr(candidate, "_unsloth_grpo_hidden_states_warning_issued", False)
for candidate in candidates

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Track degradation per forward call

When a wrapped model falls back to logits for one input path but successfully returns hidden states on a later path—such as a packed/prefix call followed by the padded fallback—this reads _unsloth_grpo_hidden_states_warning_issued as though it described the latest call. The fresh evidence beyond the earlier width-only issue is that _warn_grpo_hidden_states_fallback_once in rl.py only sets this attribute and never clears it, so it actually means “ever degraded”; with a square lm_head, every later hidden-state tensor is consequently sent through the raw-logits helper, producing incorrect log probabilities or invalid token gathers.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Accepted, fixed in 61ec1c3. The flag really does mean "ever degraded": in rl.py there is exactly one getattr and one setattr(..., True) on _unsloth_grpo_hidden_states_warning_issued and nothing anywhere sets it back. The PR's own docstring claimed the opposite; that was wrong and is corrected.

Reachable because degradation is input-dependent, not model-dependent: a *ForConditionalGeneration that splats **kwargs into a vision tower only on batches carrying pixel_values rejects hidden states on image batches and honours them on text batches, which is an ordinary mixed GRPO batch stream.

CPU repro, square head (vocab_size == hidden_size == 16), no model load, call 1 an image batch that degrades and call 2 a text batch that does not:

pre-fix call 1 -> returns_hidden_states=False (expected False)
call 2 -> returns_hidden_states=False (expected True)
post-fix call 1 -> False, call 2 -> True

New _unsloth_grpo_hidden_states_degraded is set True on every degrade path and False right before the wrapper returns hidden states. The signal prefers it and falls back to the warn-once flag when it is absent, so a stale unsloth_compiled_cache trainer built against an older rl.py behaves exactly as it does today. The warn-once flag keeps its logging role.

One more bug fell out of building that repro and is fixed here too: _drop_forward_kwargs_consumed_positionally returned the caller's own dict whenever args was empty, which is always at the GRPO call sites. wrapped_forward then set output_hidden_states / return_dict on the caller's kwargs, so the TypeError fallback re-sent the exact kwargs the model had just rejected and re-raised instead of degrading. Copy before mutating; covered by test_the_fallback_retry_does_not_reuse_the_rejected_kwargs.

…ed zoo

The GRPO width dispatch reads two things the code assumed but did not hold.

_warn_grpo_hidden_states_fallback_once only ever set
_unsloth_grpo_hidden_states_warning_issued, so the flag the dispatch reads
after a forward meant "ever degraded", not "degraded on this call". Degradation
is per call: a forward that splats **kwargs into a sub-module only some inputs
reach rejects the hidden-state request on those batches and honours it on the
rest. With vocab_size == hidden_size the width test cannot correct that, so one
degraded batch sent every later hidden-state tensor to the raw-logits helper,
skipping the lm_head matmul. Record the outcome of each call in
_unsloth_grpo_hidden_states_degraded and keep the warning flag for warn-once
logging only; the signal reader falls back to the old flag when the attribute
is absent, so a stale generated trainer keeps working.

The fallback's TypeError retry also could not work: _drop_forward_kwargs_
consumed_positionally hands the caller's dict straight back when there is
nothing to drop, which every GRPO call site hits since they pass everything by
keyword, so adding output_hidden_states/return_dict poisoned the caller's
kwargs and the retry re-sent exactly what the model had just rejected. Copy
before mutating.

Finally, the source patch over zoo's gradient dispatches only failed when
nothing matched. A zoo that respells some of its dispatch sites still leaves
one the pattern recognises, which was enough to suppress the compatibility
error while the respelled sites kept deciding on width alone. Count the branch
headers that decide off an lm_head dimension and require that none survive the
substitution.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Breezy!

Reviewed commit: 61ec1c3945

ℹ️ About Codex in GitHub

Your team has set up Codex to 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 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen
danielhanchen merged commit 42ed15f into unslothai:main Aug 11, 2026
22 of 98 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants