Repository navigation
Stop the GRPO hidden-states wrapper paying for logits it discards - #8576
Conversation
`Kaggle-Muse_Glimmer_(30B)-GRPO` dies on a 2 x T4 kernel at the first training
step:
accelerate/hooks.py:429 AlignDevicesHook.post_forward
-> send_to_device(output, self.input_device)
OutOfMemoryError: Tried to allocate 1002.00 MiB.
GPU 0 has 14.56 GiB capacity, of which 768.81 MiB is free.
It was reported before that as `CUDA error: an illegal memory access was
encountered` inside `transformers.masking_utils.fast_all`, which is a
`tensor.sum()` and therefore the first synchronising op after the real fault.
Re-running with CUDA_LAUNCH_BLOCKING=1 resolved it to the OOM above.
Two costs meet in that copy, and this wrapper creates both.
UnslothEfficientGRPO never sees a logits tensor: it takes per-token logps plus
`lm_head` and chunks the projection itself, and this wrapper exists to hand it
hidden states in place of logits. But it forwarded the caller's
`logits_to_keep` unchanged, and the GRPO trainer does not pass one:
outputs = unwrapped_model(
input_ids = input_ids_chunk,
attention_mask = attention_mask_chunk,
...
)
logits_chunk = outputs.logits
del outputs
transformers reads a missing or zero value as `slice(-0, None)`, which is
`slice(0, None)`: every position. So the model projected the whole prompt and
completion over a 202048-wide vocabulary, softcapped the result twice, and the
wrapper then overwrote it with hidden states.
`output_hidden_states = True` also returns every layer. Only `[-1]` is read and
the rest stayed attached to the output.
On one card neither cost is visible; `del outputs` frees both a line later.
Under an accelerate layer-split dispatch, `io_same_device` walks the whole
returned object and copies every tensor in it to the input device first, so both
cross the bus and the first card runs out.
## The repair
`_minimise_logits_kwarg` pins the limit to 1 when we are going to replace the
logits anyway. 1 rather than 0 because 0 means "all of them". It prefers
`logits_to_keep`, falls back to the legacy `num_logits_to_keep`, and does
nothing when the forward takes neither, when the caller passed the value
positionally (passing it again by keyword is a TypeError), or when `labels` is
present, since a model computing its own loss needs real logits. If a forward
advertises the parameter and then rejects the value, the call is retried
without it rather than losing hidden states over an optimisation.
`_drop_spare_hidden_states` clears the layers nobody reads. Note that
`outputs.hidden_states = None` does NOT do this. ModelOutput.__setattr__ is
if name in field_names and value is not None:
super().__setitem__(name, value)
super().__setattr__(name, value)
so assigning None updates the attribute and leaves the mapping entry holding
the full tuple, and `__delitem__`, `pop`, `update` and `setdefault` all raise.
Anything that walks the object as a mapping -- `send_to_device`, which is the
one that matters -- still sees and copies all of it. Writing through
`OrderedDict.__setitem__` is what actually clears it.
## Measured
Real forward, `unsloth/Qwen2.5-0.5B-Instruct`, 401 positions, 151936 vocab,
transformers 4.57.6:
lm_head rows peak MiB hidden_states entry returned shape
before 401 1094.1 tuple (1, 401, 896)
after 1 989.6 None (1, 401, 896)
The returned tensor is identical, so nothing downstream sees a difference.
## Scope
The wrapper is only installed for models that do not natively honour
UNSLOTH_RETURN_HIDDEN_STATES; `_model_supports_unsloth_return_hidden_states`
short-circuits the ones unsloth patches itself, so llama, mistral and the rest
of the fast paths are untouched. The `outputs.hidden_states` reads in
`llama.py` and `mistral.py` are inside their own forwards, on the inner model's
output, and run before this wrapper's return.
## Tests
`tests/test_grpo_hidden_states_logits_cost.py`, 23 tests. The fake output
object reproduces ModelOutput's assignment semantics exactly, and one test
asserts the trap still exists so the rest cannot pass vacuously. Both spellings
of the kwarg, the positional case, the `labels` case, var-keyword forwards, the
reject-and-retry path, and an unrelated TypeError still propagating.
Mutation-checked: dropping the minimisation turns 3 red, and replacing the
mapping write with the naive `= None` turns the layer-drop test red.
1019 GRPO and hidden-state tests pass together.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 296af5a943
ℹ️ 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".
| # AlignDevicesHook.post_forward walks the whole returned object and | ||
| # copies every tensor in it to the input device, so keeping them costs a | ||
| # cross-device copy per layer as well as the memory. | ||
| _drop_spare_hidden_states(outputs) |
There was a problem hiding this comment.
Clear hidden states before the Accelerate post-forward hook
For a layer-split device_map model whose AlignDevicesHook was installed during model loading, original_forward is already Accelerate's hooked forward, so its post_forward and send_to_device complete before control reaches this call. Clearing the tuple here therefore happens only after every layer tensor has already been copied to the input device, leaving the hidden-state OOM cost in precisely the multi-GPU path this change targets; the unused layers need to be suppressed or cleared inside the hook boundary.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The ordering is right - original_forward is accelerate's hooked forward, so post_forward's send_to_device has already run - but the conclusion is not. After post_forward the originals are unreachable and one copy of the tuple is resident on the input device, and dropping it there is what keeps it out of the chunked lm_head work where the OOM landed. Suppressing the tuple inside the hook boundary would mean not building it, which output_hidden_states = True cannot express.
| # hidden states entirely over an optimisation. | ||
| forward_kwargs.pop(logits_kwarg, None) | ||
| logits_kwarg = None | ||
| outputs = original_forward(*args, **forward_kwargs) |
There was a problem hiding this comment.
Handle hidden-state rejection on the retry
When a forwarding model first rejects the inserted logits limiter and also cannot honor output_hidden_states, this retry raises its second TypeError outside the surrounding handler. Before this change, the hidden-state error would trigger the supported raw-logits fallback, but now the GRPO step aborts; this can occur with wrappers or conditional vision paths that expose the logits parameter while forwarding these keywords to a submodule that rejects them. Route the retry failure through the same hidden-state fallback handling.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in f4644ec. Reproduced with a forward that splats **kwargs into a sub-module: it refuses logits_to_keep, then refuses output_hidden_states, and the second TypeError escaped the wrapper. The retry now has its own handler and routes into the same raw-logits fallback.
| num_logits_to_keep = _get_num_logits_to_keep(forward_signature, args, forward_kwargs) | ||
| forward_kwargs["output_hidden_states"] = True | ||
| forward_kwargs["return_dict"] = True | ||
| logits_kwarg = _minimise_logits_kwarg( |
There was a problem hiding this comment.
Restore full logits when hidden states are absent
If a forward accepts the limiter but returns hidden_states=None or an empty tuple, this call succeeds with only one raw-logit position and the later degradation branch returns that truncated output directly. GRPO's raw-logit paths require the requested completion window and often remove the final next-token position, so the one-position result becomes empty or shape-mismatched and the step fails or computes invalid per-token log probabilities; retry with the caller's original logits arguments before returning the raw-logits fallback.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in f4644ec. Reproduced: a forward that takes the limiter and returns no hidden states handed back (1, 1, 7) where the caller asked for 4 rows, and TRL does logits[:, :-1, :] then logits[:, -logits_to_keep:, :], so that is empty. The wrapper now re-runs on the caller's own arguments whenever it was the one that truncated.
| 1, not 0: 0 means "all of them", and a model that computes its own loss from | ||
| `labels` needs real logits, so that case is left alone. | ||
| """ | ||
| if forward_kwargs.get("labels") is not None: |
There was a problem hiding this comment.
Detect labels supplied positionally
When labels is passed as a positional forward argument, this check misses it even though the subsequent signature binding records it in bound.arguments, so the wrapper still forces logits_to_keep=1. Causal-LM loss computation then receives a single-position logits tensor alongside the full labels sequence, which can either raise a shape error or compute the wrong loss; inspect the bound arguments for non-None labels before adding the limiter.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in f4644ec. bind_partial does record it, so the guard now reads labels off bound.arguments as well as the kwargs. Positional labels no longer get logits_to_keep=1.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 1a4d2c6355
ℹ️ 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".
| forward_kwargs[name] = 1 | ||
| return name |
There was a problem hiding this comment.
Override every active logits-limit alias
When a forward declares both aliases and the caller supplies num_logits_to_keep=N, this loop selects logits_to_keep and adds it as 1 but leaves the legacy value at N. Implementations that merge the aliases with max—as Unsloth's causal-LM forwards do—therefore still project N vocabulary-wide positions before the wrapper discards them, preserving the memory cost this change is meant to eliminate. Prefer the caller-populated alias or pin every declared/populated alias to one.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The behaviour reproduces, but only for a caller that supplies the legacy spelling with a value above 1, and nothing in the supported window does that.
transformers renamed num_logits_to_keep to logits_to_keep in the 4.49/4.50 cycle and TRL followed well before the 0.22.2 floor this PR supports (huggingface/trl#2770). TRL 0.25.1's GRPO builds model_inputs["logits_to_keep"] only, gated on self.model_kwarg_keys, and never emits the legacy name. Unsloth's own two emitters do not produce this shape either: unsloth_fast_generate writes num_logits_to_keep only in the elif _has_old branch, which is exactly the case where logits_to_keep is not declared, so it is mutually exclusive with "declares both"; and PeftModel_fast_forward forwards both at their 0 defaults, where max(0, 1) is 1.
Granting the shape anyway, the cost described cannot occur on the forwards cited. unsloth/models/llama.py is the forward that merges the aliases with max (line 1439), and it is also the one that returns at line 1447 under UNSLOTH_RETURN_HIDDEN_STATES=1, before self.lm_head(...) at line 1461. The wrapper only minimises while that variable is 1, so there the merged value picks a hidden-state slice width, not a vocabulary-wide projection, and there is no lm_head allocation left to preserve. Pinning every declared alias to 1 would instead narrow that returned slice from N to 1 for a direct caller, which is the wrong direction.
Measured against the real _minimise_logits_kwarg at head, driving a forward that declares both aliases and merges them with max:
caller passes nothing -> injected logits_to_keep=1, forward projects 1 position
caller passes logits_to_keep=64 -> injected logits_to_keep=1, forward projects 1 position
caller passes num_logits_to_keep=64 -> injected logits_to_keep=1, forward projects 64 positions
Only the third row shows the effect, and no supported caller produces it.
The wrapper now asks for one logit position because it overwrites them with hidden states. Three paths still hand those logits back: - a forward that refuses the limiter and then also refuses output_hidden_states raised its second TypeError outside the handler, where the first would have fallen back to raw logits. Route the retry through the same fallback. - a forward that accepts the limiter but returns no hidden states returned the one-position tensor as the result. GRPO drops the last position and slices the completion window out of the rest, so it had nothing left. Re-run on the caller's own arguments instead. - labels supplied positionally never reached the keyword lookup that keeps the logits intact, so the model computed its own loss over one position. Read them off the bound arguments.
The caller's own kwargs could carry a value already bound positionally; the minimised kwargs are the ones the forward has just accepted, so put the caller's limit back into those and reuse them.
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. 🎉 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". |
Two things, both from measuring the transformers range this has to work across rather than assuming it. The comment was wrong. It said 4.57.6 spells the limit num_logits_to_keep. inspect.signature on LlamaForCausalLM.forward in real 4.57.6, 5.0.0 and 5.15.0 venvs says all three declare logits_to_keep and none declares the other name. So the legacy branch is not there for transformers; it is there for us. unsloth/models/llama.py and mistral.py patch in forwards declaring both, and unsloth/models/vision.py probes the old name first because some VLM stacks still carry only it. The branch stays; the reason is now stated correctly. The behaviour change: when the modern name is already bound positionally, give up instead of falling through to the legacy one. On a forward that declares only the modern name and sinks the rest into **kwargs, the legacy name is accepted and ignored -- no logits saved -- and returning a non-None name arms the absent-hidden-states re-run, so we would buy a second full forward for nothing. A caller that bound a width positionally has said what it wants; leave it alone. New test covers exactly that shape. 27 tests pass.
|
Version-compat audit against the full stated bar, plus a correction to this PR and one behaviour fix. The correctionI wrote that transformers 4.57.6 spells the limit
Same for Qwen2, Qwen3, Qwen3Moe, Gemma2 and Mistral. So The behaviour fix in 97addb0The detection loop skipped a name bound positionally and moved to the next one. On a forward that declares only I could not construct a live path into it; every GRPO call site passes keywords. Recording it as a latent hole closed, not a bug anyone hit. What the audit did confirm
Stated plainly, what is not verifiedNo GPU was used, so the 1002 MiB figure in the description is a mechanism I have confirmed and a magnitude I have not re-measured here. transformers 5.1 through 5.14 were not individually installed. No live One cost worth naming rather than burying: at rl.py:1977-1989, a forward that accepts the limiter but ignores |
Kaggle-Muse_Glimmer_(30B)-GRPOdies on a 2 x T4 kernel at the first trainingstep:
It was reported before that as
CUDA error: an illegal memory access was encounteredinsidetransformers.masking_utils.fast_all, which is atensor.sum()and therefore the first synchronising op after the real fault.Re-running with CUDA_LAUNCH_BLOCKING=1 resolved it to the OOM above.
Two costs meet in that copy, and this wrapper creates both.
UnslothEfficientGRPO never sees a logits tensor: it takes per-token logps plus
lm_headand chunks the projection itself, and this wrapper exists to hand ithidden states in place of logits. But it forwarded the caller's
logits_to_keepunchanged, and the GRPO trainer does not pass one:transformers reads a missing or zero value as
slice(-0, None), which isslice(0, None): every position. So the model projected the whole prompt andcompletion over a 202048-wide vocabulary, softcapped the result twice, and the
wrapper then overwrote it with hidden states.
output_hidden_states = Truealso returns every layer. Only[-1]is read andthe rest stayed attached to the output.
On one card neither cost is visible;
del outputsfrees both a line later.Under an accelerate layer-split dispatch,
io_same_devicewalks the wholereturned object and copies every tensor in it to the input device first, so both
cross the bus and the first card runs out.
The repair
_minimise_logits_kwargpins the limit to 1 when we are going to replace thelogits anyway. 1 rather than 0 because 0 means "all of them". It prefers
logits_to_keep, falls back to the legacynum_logits_to_keep, and doesnothing when the forward takes neither, when the caller passed the value
positionally (passing it again by keyword is a TypeError), or when
labelsispresent, since a model computing its own loss needs real logits. If a forward
advertises the parameter and then rejects the value, the call is retried
without it rather than losing hidden states over an optimisation.
_drop_spare_hidden_statesclears the layers nobody reads. Note thatoutputs.hidden_states = Nonedoes NOT do this. ModelOutput.setattr isso assigning None updates the attribute and leaves the mapping entry holding
the full tuple, and
__delitem__,pop,updateandsetdefaultall raise.Anything that walks the object as a mapping --
send_to_device, which is theone that matters -- still sees and copies all of it. Writing through
OrderedDict.__setitem__is what actually clears it.Measured
Real forward,
unsloth/Qwen2.5-0.5B-Instruct, 401 positions, 151936 vocab,transformers 4.57.6:
The returned tensor is identical, so nothing downstream sees a difference.
Scope
The wrapper is only installed for models that do not natively honour
UNSLOTH_RETURN_HIDDEN_STATES;
_model_supports_unsloth_return_hidden_statesshort-circuits the ones unsloth patches itself, so llama, mistral and the rest
of the fast paths are untouched. The
outputs.hidden_statesreads inllama.pyandmistral.pyare inside their own forwards, on the inner model'soutput, and run before this wrapper's return.
Tests
tests/test_grpo_hidden_states_logits_cost.py, 23 tests. The fake outputobject reproduces ModelOutput's assignment semantics exactly, and one test
asserts the trap still exists so the rest cannot pass vacuously. Both spellings
of the kwarg, the positional case, the
labelscase, var-keyword forwards, thereject-and-retry path, and an unrelated TypeError still propagating.
Mutation-checked: dropping the minimisation turns 3 red, and replacing the
mapping write with the naive
= Noneturns the layer-drop test red.1019 GRPO and hidden-state tests pass together.