Repository navigation
GRPO: wrap the model that owns the head when falling back to hidden states - #8231
danielhanchen merged 7 commits into
Conversation
…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.
There was a problem hiding this comment.
💡 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") |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| if not torch.cuda.is_available(): # unsloth needs an accelerator to import | ||
| pytest.skip("needs an accelerator to import unsloth", allow_module_level = True) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
… 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.
|
Un-gating the tests so they actually run on CPU surfaced a real bug in this change, which the Wrapping the head owner instead of the decoder body puts the fallback forward somewhere accelerate can see it. 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 Fix is to drop a leading argument that is the target module; The remaining red checks ( |
|
@codex review |
|
Codex Review: Didn't find any major issues. Bravo. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
Problem
Any GRPO run that is not PEFT (
full_finetuning = True) dies at the first reference-logprob computation:This is what the
NeMo-Gym-SudokuandNeMo-Gym-Multi-Environmentnotebooks hit. Both loadunsloth/Qwen2.5-1.5B-Instructwithfull_finetuning = True, andmodels/rl.pysets GRPO'sbetadefault to0.001, so TRL builds a reference model.Root cause
TRL builds
ref_modelwith a plainThat model's forward is a stock transformers one, so it does not honour
UNSLOTH_RETURN_HIDDEN_STATESand.logitsis a real[B, T, vocab]tensor._install_grpo_hidden_states_forward_wrapperexists exactly to cover this, and_wrap_grpo_hidden_states_fallbackdoes install it onref_model.It never took effect.
_grpo_hidden_states_wrap_targetwalked("base_model", "model")to find an adapter's wrapped model, and a bare*ForCausalLMalso has a.model-- its decoder body. So the wrapper landed onQwen2Model, which returns no.logitsat 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:
s33in 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()returnsNonefor the decoder bodies and the head module for the*ForCausalLMwrappers, so it separates the two without a model-name list, and adapter wrappers (PEFTbase_model/model) are unaffected because they proxy the head through.Test
tests/test_grpo_hidden_states_wrap_target.pybuilds a real tinyQwen2ForCausalLM, the same shape TRL hands over, and pins:hidden @ lm_head.t()matches the model's own logitsReverting 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:origin/maina and b must have same reduction dim, but got [((s47*s87 + 7)//8), s33] X [896, 151936]TRAIN_OKOn
mainthe 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_softmaxcall. That is the safety net; this is the reason the wrong-width input reached them.