Skip to content

GRPO: opt-in zero-variance group exclusion and prompt-level loss aggregation - #13891

Merged
danielhanchen merged 4 commits into
mainfrom
dh/rl-losses
Oct 16, 2026
Merged

danielhanchen merged 4 commits into
mainfrom
dh/rl-losses

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Needs unslothai/unsloth-zoo#1790 (the loss side); with an older unsloth_zoo the options raise a clear error.

Two ScaleRL options for GRPO, both off by default.

UNSLOTH_GRPO_ZERO_VARIANCE_EXCLUDE=1 drops groups whose rewards are all equal from the loss and from its token count. Such groups have zero advantage, so they only dilute the token mean, and with a KL penalty they still pull towards the reference.

UNSLOTH_GRPO_LOSS_AGGREGATION=prompt averages the token losses within each group first and then over groups.

Groups only exist during generation, because the loss sees shuffled micro-batches. So the weights are computed inside _generate_and_score_completions, right after TRL logs frac_reward_zero_std, using TRL's zero-std test on the weighted rewards and the completion token counts gathered across processes. They travel with the batch as unsloth_sample_weight and replace the loss type normaliser in unsloth_zoo's GRPO loss.

Exclusion on its own applies to the token-normalised losses (bnpo, dapo, cispo, vespo). Prompt level applies to every loss type except luspo. Eval batches are unchanged. The share of excluded groups is logged as frac_reward_zero_std_excluded.

Tests run the shipped helper on synthetic groups, including all-equal rewards, a reward function that never applies and an unscorable completion, through TRL's shuffle and split and unsloth_zoo's loss over one to four simulated processes. Loss and gradients equal the ScaleRL formulas, and without degenerate groups the result is plain dapo. On a tiny model with half the groups degenerate, the gradient norm scales by exactly the predicted 1 / (1 - excluded fraction), and with the options unset the run is bitwise identical to main.

Not covered: a real multi-process job, prompt-level aggregation with unequal completion lengths end to end (the tiny model fills the max length), TRL 0.22.2 and torch 2.6.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 15, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-16T01:52:35.364883Z d05c232 New commits
🔒 Security Review ⚠️ Failed 2026-10-15T16:38:31.746503Z 365ceb1 PR opened
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@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: 365ceb146d

ℹ️ 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
Comment on lines +3318 to +3322
rewards = (
rewards_per_func * trainer.reward_weights.to(rewards_per_func.device).unsqueeze(0)
).nansum(dim = 1)
rewards[torch.isnan(rewards_per_func).all(dim = 1)] = torch.nan
grouped = rewards.view(-1, num_generations)

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 Respect normalize-then-sum reward aggregation

When TRL is configured with multi_objective_aggregation="normalize_then_sum", this recomputes a raw weighted sum instead of using the normalized per-function rewards that determine the actual advantages. For example, with unequal reward weights, two functions can have a constant raw weighted sum but a varying normalized sum, causing this code to exclude a group that has a real learning signal; the inverse can retain a zero-signal group. Either reproduce that aggregation before testing variance or reject this option.

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 3beeaeb: with multi_objective_aggregation="normalize_then_sum", zero-variance exclusion now uses TRL's formula: each reward function normalised within its group as (r - nanmean) / (nanstd + 1e-4), then weighted and nansummed, and the variance test runs on that sum. sum_then_normalize and TRL versions without the field keep the raw weighted sum. The forward case reproduced (a group with a constant raw sum but varying normalised sum was dropped); the inverse case cannot occur exactly because of the 1e-4 term, and following TRL's aggregation covers both. Test: test_exclusion_follows_normalize_then_sum.

Comment thread unsloth/models/rl_replacements.py Outdated
Comment on lines +3324 to +3325
count = (~torch.isnan(grouped)).sum(dim = 1)
variance = torch.nansum(centred * centred, dim = 1) / (count - 1).clamp(min = 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 Retain groups with only one scored completion

When all but one completion in a group are unscorable (NaN), clamping count - 1 to one turns the undefined sample variance into zero, so zero-variance exclusion drops the group. TRL's sample-standard-deviation test yields NaN for this case and therefore does not classify it as zero, and the new test oracle likewise explicitly keeps groups with fewer than two scored rewards. Preserve that undefined-variance behavior rather than manufacturing a zero variance.

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 3beeaeb: the group variance now copies TRL's nanstd (Bessel corrected, NaN with fewer than two scored rewards); NaN never passes the isclose-to-zero test, so a group with one scored completion is kept instead of excluded. Test: test_group_with_one_scored_completion_is_kept.

@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: 3beeaeb91e

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

Copy link
Copy Markdown
Member Author

pre-commit.ci run

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

pre-commit.ci run

@danielhanchen
danielhanchen merged commit fe3370a into main Oct 16, 2026
@danielhanchen
danielhanchen deleted the dh/rl-losses branch October 16, 2026 07:31
yermakoffivan pushed a commit to yermakoffivan/unsloth that referenced this pull request Oct 16, 2026
…unslothai#14023)

Two follow-ups to PRs merged this week, each found by re-checking the
merged code against its parent.

## Changes

**GRPO: the reward locals alias no longer keeps rollout tensors alive**
(follow-up to unslothai#13891)

The reward rewrite (TRL 0.24 and newer) binds `_unsloth_reward_locals =
locals()` in `_generate_and_score_completions`. unslothai#13891 added a later
`locals().get('tool_mask')` call in the same frame. On CPython 3.12 and
older, `locals()` returns the frame's one dict and refreshes it, so the
second call stores that dict inside itself. The cycle keeps every local
of the step, including the concatenated prompt and completion ids and
the reward tensors, alive after the method returns, until the cyclic GC
happens to run. That is GPU memory carried into the training step and
the next rollout. Python 3.13 is not affected (PEP 667). The alias is
now deleted right after the reward call, before anything else calls
`locals()`.

**FSDP2: the automatic mixed precision repair also runs on torch 2.6**
(follow-up to unslothai#13865)

unslothai#13865 switches accelerate's automatic FSDP2 policy to fp32 gradient
reduction when it matches the compute dtype. torch 2.6
`MixedPrecisionPolicy.__post_init__` stores `reduce_dtype = None` when
it equals `param_dtype`, so the `reduce_dtype != compute` check returned
early and torch 2.6 kept reducing fp16 gradients in fp16. `None` means
the same thing there (reduce in the compute dtype), so it now counts as
a match.

## Tests

- `tests/test_grpo_reward_locals_cycle.py`: rewrites the installed TRL
`_generate_and_score_completions` and checks the alias is deleted before
any later `locals()` call (fails on main), plus a frame lifetime check.
A standalone repro of the pattern on CPython 3.12 keeps the object alive
before the change and frees it after; CPython 3.13 frees it either way.
- `test_torch_26_normalized_auto_policy_still_reduces_in_fp32` (fp16 and
bf16): fails on main, passes here.
- `tests/test_grpo_*.py` and `tests/test_fsdp2_*.py`: 380 passed, 25
skipped. `test_fsdp2_default_optim.py` fails the same way on main and on
the pre-week base in this environment, so it is left out here.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
danielhanchen added a commit to Etherll/unsloth that referenced this pull request Oct 19, 2026
…before 1.6 (unslothai#14123)

Follow-ups from a re-review of the merged GRPO changes (unslothai#13968, unslothai#13891,
unslothai#14023).

## Changes

1. **Latch the efficient-path autocast under vLLM only**
(`rl_replacements.py`, unslothai#13968).
unslothai#13968 latched the trainer precision whenever the efficient path skipped
the scoring forward. That latch is right for ordinary trainers (it keeps
each trainer's own precision when several run in one process), so it
stays; only a model forced to float32 without vLLM now records "no loss
autocast" on the trainer instead (what it effectively got before unslothai#13856,
without depending on process-wide env that a later model may change).
Before unslothai#13856 restored TRL's old-logprob gate, only vLLM runs always ran
that forward, so only they latched. Without vLLM and with `beta = 0`,
nothing latched and the loss ran without autocast. Latching there now
wraps models forced to float32 (Gemma3 on a T4, or `dtype = float16`) in
fp16 / bf16 autocast, which changes the numerics.
On a tiny Gemma3 with no vLLM and `beta = 0`, the step 1 grad norm went
from 0.8288910 to 0.8287503 with LoRA, and from 1.1988286 to 1.1986356
with full finetuning. With this change both runs are bitwise equal to
the code before unslothai#13856 again. vLLM runs and every non-forced trainer
latch exactly as on main.

2. **Zero-variance exclusion on TRL before 1.6**
(`_unsloth_grpo_sample_weight`, unslothai#13891, opt-in
`UNSLOTH_GRPO_ZERO_VARIANCE_EXCLUDE=1`).
TRL 1.6.0 added `unscorable_mask`: a completion no reward function
scored is left out of its group's statistics. TRL 0.22.2 to 1.5.1
instead score it 0 through `nansum`, so a group like `[None, 1, 1, 1]`
has variance and real advantages. The exclusion treated such a
completion as missing on every TRL version, so these groups were dropped
on older TRL. It now follows the installed TRL: missing on 1.6+, scored
0 before 1.6.

3. **Test only:** `test_grpo_reward_locals_cycle.py` always skipped once
unsloth was imported. It now reads TRL's own GRPO source. It fails on
unslothai#14023's parent and passes on the merge.

The default path is unchanged: change 2 is opt-in, and change 1 only
affects forced float32 models without vLLM that skip the scoring
forward, which now behave as they did before unslothai#13856.

## Tests

- New tests fail on current main and pass here:
`test_efficient_call_without_vllm_leaves_forced_float32_unlatched` and
`test_unscored_completion_counts_as_zero_on_trl_before_1_6` (main: 2
failed, 36 passed; this branch: 38 passed).
`test_efficient_call_without_vllm_still_latches_an_ordinary_trainer`
keeps the per-trainer latch for everything else.
- Neighbours `test_grpo_autocast_per_trainer.py`,
`test_grpo_old_logprob_gate.py`, `test_grpo_autocast_disabled.py` and
`test_grpo_sample_weight.py`: 94 passed, 1 skipped.
- TRL reference: `trl/trainer/grpo_trainer.py` at v0.22.2 (line 1392),
v1.3.0 (2183) and v1.5.1 (2201) uses `nansum` for every completion;
v1.6.0 (2168-2171) and v1.15.0 (2682-2685) add `unscorable_mask`.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
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