Skip to content

GRPO: wrap the model that owns the head when falling back to hidden states - #8231

Merged
danielhanchen merged 7 commits into
unslothai:mainfrom
danielhanchen:fix/grpo-hidden-states-wrap-target
Aug 9, 2026
Merged

danielhanchen merged 7 commits into
unslothai:mainfrom
danielhanchen:fix/grpo-hidden-states-wrap-target

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Problem

Any GRPO run that is not PEFT (full_finetuning = True) dies at the first reference-logprob computation:

TorchRuntimeError: RuntimeError when making fake tensor call
Dynamo failed to run FX node with fake tensors: call_function <built-in function matmul>(
  FakeTensor(device='cuda:0', size=(((s47*s87 + 255)//256), s33), dtype=torch.bfloat16),
  FakeTensor(device='cuda:0', size=(1536, 151936), dtype=torch.bfloat16, requires_grad=True))
got RuntimeError('a and b must have same reduction dim, but got [((s47*s87 + 255)//256), s33] X [1536, 151936].')

from user code:
  File "unsloth_compiled_cache/UnslothGRPOTrainer.py", line 161,
    in chunked_hidden_states_selective_log_softmax
      chunk_logits = chunk_hidden_states.to(lm_head.dtype) @ lm_head.t()

This is what the NeMo-Gym-Sudoku and NeMo-Gym-Multi-Environment notebooks hit. Both load unsloth/Qwen2.5-1.5B-Instruct with full_finetuning = True, and models/rl.py sets GRPO's beta default to 0.001, so TRL builds a reference model.

Root cause

TRL builds ref_model with a plain

architecture = getattr(transformers, config.architectures[0])
self.ref_model = architecture.from_pretrained(model_id, **model_init_kwargs)

That model's forward is a stock transformers one, so it does not honour UNSLOTH_RETURN_HIDDEN_STATES and .logits is a real [B, T, vocab] tensor. _install_grpo_hidden_states_forward_wrapper exists exactly to cover this, and _wrap_grpo_hidden_states_fallback does install it on ref_model.

It never took effect. _grpo_hidden_states_wrap_target walked ("base_model", "model") to find an adapter's wrapped model, and a bare *ForCausalLM also has a .model -- its decoder body. So the wrapper landed on Qwen2Model, which returns no .logits at all; the head above it then ran untouched and the caller still got vocab-width logits. Nothing raised, so neither of the two "using logits directly" warnings fired either.

Measured on the model TRL actually builds:

REF class           : Qwen2ForCausalLM | transformers.models.qwen2.modeling_qwen2
REF supports marker : False
REF wrap target     : Qwen2Model          <- the decoder, not the head owner
REF wrapped attr    : True
lm_head             : (151936, 896)
REF .logits width   : (1, 6, 151936)      <- expected (1, 6, 896)

s33 in the error is the backed symbol the hidden-size dim collapses to once the policy call (896) and the reference call (151936) have made Dynamo mark that axis dynamic; the mismatch is a plain width mismatch underneath.

Fix

Descend only into a child that still owns an output head. PreTrainedModel.get_output_embeddings() returns None for the decoder bodies and the head module for the *ForCausalLM wrappers, so it separates the two without a model-name list, and adapter wrappers (PEFT base_model / model) are unaffected because they proxy the head through.

Test

tests/test_grpo_hidden_states_wrap_target.py builds a real tiny Qwen2ForCausalLM, the same shape TRL hands over, and pins:

  • the decoder body is not a wrap target, an adapter-shaped wrapper still is
  • with the switch on, the model returns hidden states of the head's input width
  • those hidden states are the ones the head consumes: hidden @ lm_head.t() matches the model's own logits
  • with the switch off, the output is unchanged

Reverting the one-line predicate turns tests 1 and 3 red.

Verification

Qwen2.5-0.5B-Instruct, full_finetuning = True, GRPO, 1 step, one A100. Same tree, only this commit differing:

tree result
origin/main exit 1, a and b must have same reduction dim, but got [((s47*s87 + 7)//8), s33] X [896, 151936]
this branch exit 0, TRAIN_OK

On main the sequence-packing and PrefixGrouper no-grad paths also log the same mismatch and fall back before the padded loop raises for real. With this commit none of them appear: the reference model now returns hidden states, so the memory-efficient chunked path is used rather than being fallen back off.

Related: #8204 adds the missing width dispatch at the remaining call sites, which turns the same input into a correct-but-slower chunked_selective_log_softmax call. That is the safety net; this is the reason the wrong-width input reached them.

…tates

TRL builds GRPO's ref_model with a plain architecture.from_pretrained(model_id),
so on every non-PEFT run the hidden-states fallback has to catch a bare
*ForCausalLM. _grpo_hidden_states_wrap_target walked ("base_model", "model")
looking for an adapter's wrapped model and landed on that model's decoder body,
which returns no .logits, so the head above it ran untouched and the wrapper
became a silent no-op. The reference logprob path then received [B, T, vocab]
where it expects [B, T, hidden] and died in the lm_head matmul.

Descend only into a child that still owns an output head.
@danielhanchen
danielhanchen requested a review from Datta0 as a code owner August 9, 2026 08:06

@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: 74cdb3d3f2

ℹ️ 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".

"""A real transformers `*ForCausalLM`, shaped like TRL's `ref_model`."""
from transformers.models.qwen2.modeling_qwen2 import Qwen2ForCausalLM

config = AutoConfig.from_pretrained("unsloth/Qwen2.5-0.5B-Instruct")

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 Construct the tiny config without contacting the Hub

On a GPU-enabled test runner without network access or a pre-populated Hugging Face cache, this from_pretrained call fails before any regression assertion runs. The test overwrites all model-shape fields it needs, so constructing a local Qwen2Config would keep the unit test hermetic and prevent unrelated Hub availability from breaking it.

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.

Agreed, and it also cuts against that job's own policy: it explicitly deselects test_model_registration for hitting huggingface_hub. The config was overwritten field by field anyway, so 9763a56 builds a Qwen2Config() directly. Verified with HF_HUB_OFFLINE=1: 5 passed.

Comment on lines +29 to +30
if not torch.cuda.is_available(): # unsloth needs an accelerator to import
pytest.skip("needs an accelerator to import unsloth", allow_module_level = True)

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 Let the regression tests run on CPU

On every CPU-only test run, this module-level gate skips all four tests even though tests/conftest.py provides the repository's GPU-free Unsloth import harness and the tiny Qwen forwards used here are CPU-capable. As a result, the new regression receives no coverage in the common CPU test environment; remove the CUDA gate and run the tiny model on the available device.

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, and it made the regression vacuous: studio-backend-ci's "Repo tests (CPU)" auto-discovers tests/ (only qlora, saving, utils, sh, vllm_compat and version_compat are --ignored), so this file was collected and then skipped on the one job that runs it. Gate removed in 9763a56; the five tests now pass with CUDA_VISIBLE_DEVICES="" under the tests/conftest.py harness, and unchanged on a real GPU.

with torch.no_grad():
wrapped = model(input_ids = input_ids).logits
finally:
os.environ["UNSLOTH_RETURN_HIDDEN_STATES"] = previous

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 Force the switch off for the reference forward

When the test process starts with UNSLOTH_RETURN_HIDDEN_STATES=1, this restoration re-enables the wrapper before the later reference call, so reference contains hidden states rather than vocabulary logits and the shape assertion fails. Compute the reference under an explicit UNSLOTH_RETURN_HIDDEN_STATES=0 context, then restore the caller's original environment afterward.

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.

Confirmed by running the old file with UNSLOTH_RETURN_HIDDEN_STATES=1 exported: test_plain_causal_lm_returns_hidden_states_after_the_wrapper failed on assert torch.Size([2, 6, 64]) == (2, 6, 128), exactly as described. 9763a56 replaces the save/restore with a _return_hidden_states context manager, computes the reference under an explicit "0", and restores an originally-unset variable by popping it rather than writing "0" back. Passes with the variable set to 1 and with it unset.

danielhanchen and others added 5 commits August 9, 2026 08:55
… forward

Wrapping the head owner puts the fallback forward where accelerate can see it.
extract_model_from_parallel(keep_fp32_wrapper = False), which the GRPO loop calls
on every step, rebinds an instance-level forward as MethodType(forward, model),
so the wrapper is re-entered with the module as its leading positional argument
and the head owner passes it on as input_ids. Drop a leading argument that is the
target module.

Also make the regression tests real: build the tiny config locally instead of
fetching it from the Hub, drop the CUDA gate so they run in the CPU job that
collects tests/, and pin the switch per block so a process that starts with
UNSLOTH_RETURN_HIDDEN_STATES=1 does not read hidden states as the reference.
@danielhanchen

Copy link
Copy Markdown
Member Author

Un-gating the tests so they actually run on CPU surfaced a real bug in this change, which the GRPO fake-run (latest + main TRL, CPU spoof) job was already red on:

FAILED tests/version_compat/test_trl_fake_train_cpu.py::test_grpo_trains_on_cpu
  TypeError: embedding(): argument 'indices' (position 2) must be Tensor, not LlamaForCausalLM

Wrapping the head owner instead of the decoder body puts the fallback forward somewhere accelerate can see it. grpo_accumulated_loss calls trainer.accelerator.unwrap_model(trainer.model, keep_fp32_wrapper = False) every step, and extract_model_from_parallel ends that path with

model.forward = MethodType(forward, model)

so the plain function installed on the instance is rebound as a method and re-entered with the module as its leading positional argument. The head owner then passes it straight on as input_ids. That line is identical in accelerate 0.34.0 (the floor in pyproject) and on accelerate main, so it is not version specific. Previously the wrapper sat on the decoder body, which accelerate never rebinds, which is why the no-op version never tripped it.

Fix is to drop a leading argument that is the target module; original_forward is already bound. test_survives_the_accelerate_forward_rebind covers it and fails with the same TypeError without the fix, and tests/version_compat/test_trl_fake_train_cpu.py is back to 3 passed.

The remaining red checks (Core python-floor gate, studio backend, Chat UI) come from studio/backend/vendor/truststore, which is on main and untouched here; #8252 addresses that one.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 2e0d67c929

ℹ️ 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 4a02eb6 into unslothai:main Aug 9, 2026
46 of 50 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.

1 participant