Skip to content

Stop the GRPO hidden-states wrapper paying for logits it discards - #8576

Merged
danielhanchen merged 8 commits into
mainfrom
fix/grpo-hidden-states-skip-lm-head
Aug 13, 2026
Merged

danielhanchen merged 8 commits into
mainfrom
fix/grpo-hidden-states-skip-lm-head

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

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.

`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.
@danielhanchen
danielhanchen requested a review from Datta0 as a code owner August 12, 2026 14:35

@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: 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".

Comment thread unsloth/models/rl.py
# 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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

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.

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.

Comment thread unsloth/models/rl.py
# hidden states entirely over an optimisation.
forward_kwargs.pop(logits_kwarg, None)
logits_kwarg = None
outputs = original_forward(*args, **forward_kwargs)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

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 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.

Comment thread unsloth/models/rl.py
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(

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

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 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.

Comment thread unsloth/models/rl.py
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:

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 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 👍 / 👎.

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 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.

@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: 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".

Comment thread unsloth/models/rl.py
Comment on lines +1838 to +1839
forward_kwargs[name] = 1
return name

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 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 👍 / 👎.

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.

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.

danielhanchen and others added 3 commits August 12, 2026 17:16
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.
@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. 🎉

Reviewed commit: 13a55a7f39

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

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.
@danielhanchen

Copy link
Copy Markdown
Member Author

Version-compat audit against the full stated bar, plus a correction to this PR and one behaviour fix.

The correction

I wrote that transformers 4.57.6 spells the limit num_logits_to_keep. That is wrong. inspect.signature(LlamaForCausalLM.forward) in real venvs:

transformers logits parameters declared
4.57.6 logits_to_keep
5.0.0 logits_to_keep
5.15.0 logits_to_keep

Same for Qwen2, Qwen3, Qwen3Moe, Gemma2 and Mistral. So num_logits_to_keep is not a transformers-era name at all within the support bar, and the legacy branch is not there for transformers. It is there for us: unsloth/models/llama.py:1383 and unsloth/models/mistral.py:176 patch in forwards declaring both, and unsloth/models/vision.py:576 probes the old name first because some VLM stacks still carry only it. The branch is justified, my reason for it was not, and 97addb0 states it correctly.

The behaviour fix in 97addb0

The detection loop skipped a name bound positionally and moved to the next one. On a forward that declares only logits_to_keep and sinks the rest into **kwargs, that means sending num_logits_to_keep = 1: accepted, ignored, no logits saved, and because the function returned a non-None name it also armed the absent-hidden-states re-run, buying a second full forward for nothing. It now gives up instead, on the principle that a caller who bound a width positionally has said what it wants. New test covers that exact shape. 27 tests pass.

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

  • The zero trap is real and this PR does not fall into it. One literal write, forward_kwargs[name] = 1. A caller's explicit logits_to_keep=0 is overwritten with 1, which is safe because _get_num_logits_to_keep captures the caller's width at rl.py:1929, before the mutation at :1932. The two places 0 is reintroduced are fallbacks that genuinely need full logits.
  • TRL. No new version anchor. The wrapper reads self.model / self.ref_model through getattr(..., None); both exist in 0.22.2 (grpo_trainer.py:423/427/432) and 1.9.2 (:957/961/971). No version found where the rewrite silently no-ops, which was the outcome worth hunting for. Verified by source reading, not runtime instantiation: TRL 0.22.2's grpo_trainer will not import without vLLM.
  • vLLM: no interaction. The wrapper region has no vllm / fast_inference / use_vllm reference, and every UNSLOTH_RETURN_HIDDEN_STATES=1 site sits inside the scoring forward and is reset before return. No vLLM install was made and none is needed to say that.
  • Platform: none. No os.name, sys.platform, path or line-ending assumption in the added rl.py lines. The only path handling in the diff is pathlib.Path in the test file.
  • Runtime check on a real tiny Llama under all three transformers: logits go (2,9,64) to (2,1,64) while hidden_states[-1] stays full length (2,9,32), no deprecation warnings.
  • Independent proof of the second half, spying on torch.Tensor.to around accelerate.utils.send_to_device (accelerate 1.14.0): 3 spare hidden-state tensors copied without the fix, 0 with it.

Stated plainly, what is not verified

No 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 GRPOTrainer instantiation, and no Windows or macOS execution.

One cost worth naming rather than burying: at rl.py:1977-1989, a forward that accepts the limiter but ignores output_hidden_states now runs the model twice per scoring call. That is deliberate and correctness demands it, but it cannot be memoised, because the degradation is a per-call property. I have not measured how common that model class is.

@danielhanchen
danielhanchen merged commit baa96a7 into main Aug 13, 2026
50 of 55 checks passed
@danielhanchen
danielhanchen deleted the fix/grpo-hidden-states-skip-lm-head branch August 13, 2026 12:15
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