Skip to content

GRPO: honour a trainer subclass's own _compute_loss (GMPO trained plain GRPO) - #18851

Merged
danielhanchen merged 3 commits into
mainfrom
grpo-subclass-loss
Nov 22, 2026
Merged

danielhanchen merged 3 commits into
mainfrom
grpo-subclass-loss

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 22, 2026 •

Copy link
Copy Markdown
Member

Summary

Unsloth's generated GRPO compute_loss (grpo_trainer_compute_loss in unsloth/models/rl_replacements.py) computes the GRPO objective in the zoo's fused loss and never calls self._compute_loss. TRL's extension point for new objectives is exactly that method: GRPOTrainer.compute_loss only does return self._compute_loss(model, inputs), and trl.experimental.gmpo.GMPOTrainer changes nothing but _compute_loss. Under Unsloth the MRO is GMPOTrainer -> UnslothGRPOTrainer, the inherited compute_loss is Unsloth's, and GMPO's objective is dead code: the run trains plain GRPO with GMPO's clip range and prints nothing. The same happens to any user subclass that overrides _compute_loss.

This PR makes the fused compute_loss hand the batch to a _compute_loss defined below it in the MRO. Plain GRPO keeps the existing fused path unchanged.

Changes

  • New unsloth/models/_grpo_subclass_loss.py:
    • grpo_subclass_compute_loss(trainer) finds the class that owns the fused compute_loss (by the name its body imports, so a subclass that overrides compute_loss and calls super() is still handled) and returns a _compute_loss defined strictly below it, else None. The generated class carries TRL's own _compute_loss, so plain GRPO and subclasses that override other methods get None.
    • grpo_run_subclass_compute_loss runs the subclass _compute_loss with _get_per_token_logps_and_entropies bound on the instance, for that call only, to grpo_subclass_logps_and_entropies. This is needed because Unsloth's own scorer returns detached old / reference logprobs.
    • grpo_subclass_logps_and_entropies keeps TRL's contract (log-probs of the completion tokens under self.temperature, entropies detached as TRL computes them under no_grad, 3-tuple on TRL >= 1.7 and 2-tuple below). Text batches are scored from the final hidden states with the zoo's fused linear kernel (_fused_rl_logprobs.score_hidden_states, already used for PPO / RLOO), so no tokens x vocab logits tensor is kept. Heads the kernel cannot read (hooks, ZeRO-3, FSDP / DeepSpeed, UNSLOTH_FUSED_LINEAR=0) and forwards that return real logits fall back to TRL's math on the logits. Vision tensors, token type ids and sampling masks raise NotImplementedError instead of being sliced incorrectly.
  • unsloth/models/rl_replacements.py:
    • The generated GRPO compute_loss dispatches right after the return_outputs check.
    • _unsloth_grpo_rollout_logps_as_old, _unsloth_grpo_old_logps_from_new and _unsloth_grpo_old_logps_store stand down for subclass losses. Their markers are read only by the fused loss, and a subclass reads TRL's old_per_token_logps, so TRL scores pi_old for it. Without this, GMPO with num_iterations > 1 would see old_per_token_logps=None on later passes and use a ratio of 1.
  • New CPU test tests/test_grpo_subclass_compute_loss.py.

Math parity

GMPO (arXiv 2507.20673) exists only in TRL among the reference frameworks; verl, SkyRL and miles have no GMPO loss.

Framework Symbol Formula This branch
TRL 1.15.0 / 1.18.2 GMPOTrainer._compute_loss token log-ratio clipped in log space to [-eps_low, eps_high], sign-aware min / max, coef = exp(masked mean over the completion), loss = mean_i(-coef_i A_i) (+ beta x sequence-mean k3 KL) / GA TRL's own code runs, unchanged
Unsloth base fused compute_loss GRPO token-mean of the PPO-clipped ratio was used for GMPO (the defect)

Tests

CPU fp64 oracle

The test runs:

  • Unsloth's real generated compute_loss source in a stand-in class;
  • TRL's GMPOTrainer._compute_loss from TRL's installed source;
  • an independent float64 GMPO oracle written from the paper.

It uses a tiny float64 model, a left-padded prompt, a right-padded completion and a one-token completion. Old logps are offset so ratios land on both sides of the clip, with beta 0 and 0.04 and GA 2.

Route beta |TRL - oracle| |Unsloth - TRL| (loss) max |d grad|
fused kernel (hidden states) 0 0 3.4e-08 7.0e-08
fused kernel (hidden states) 0.04 0 3.4e-08 8.2e-08
logits fallback 0 0 5.6e-17 3.9e-16
logits fallback 0.04 0 2.8e-17 3.3e-16

The fused kernel computes in float32, hence the 3e-8. The test bound is 1e-6.

TRL transformers base (f5dfe68) this branch
1.18.2 5.18.0 10 failed, 1 passed 11 passed
1.15.0 5.18.0 10 failed, 1 passed 11 passed
0.22.2 (no GMPO; user-subclass objective, TRL's stock scorer, 2-tuple) 4.57.6 6 failed, 5 skipped 6 passed, 5 skipped

On base the GMPO tests fail with the fused GRPO loss ran: the subclass _compute_loss was bypassed. The one test that passes on base checks that GMPO and GRPO differ on these inputs. Each arm imported its own tree.

Existing CPU suites tests/test_grpo*.py and tests/test_rl*.py (TRL 1.18.2): 893 passed, 9 failed, 9 skipped on both base and this branch. The same 9 IDs fail on both sides, all in tests/test_grpo_rollout_scope.py; they are pre-existing and not touched here.

GPU (Colab L4)

Setup: Qwen2.5-0.5B-Instruct bf16, LoRA r16, use_gradient_checkpointing="unsloth", HF generate. Batch 4 x 4 generations, 48 completion tokens, num_iterations=2, 4 steps, lr 2e-4, seed 0. Versions: unsloth f5dfe68, zoo 070570c, TRL 1.18.2. Arms ran in fresh processes; head = base package plus this branch's two modules, and each arm asserted its tree.

The reference recomputes GMPO and GRPO in float32 from the same inputs right after each compute_loss call. It does this from fp32 head projections of the hidden states (to match the fused route) and from bf16 logits (to match the logits route).

Arm step 2 loss GMPO ref GRPO ref step 4 loss GMPO ref GRPO ref trains
base, GMPOTrainer -6.4199530e-02 -6.3459076e-02 -6.4199448e-02 -2.8974747e-02 -2.9930800e-02 -2.8974557e-02 GRPO
head, GMPOTrainer (fused route, 4 of 4 calls) -6.3459128e-02 -6.3459076e-02 -6.4199448e-02 -3.0178666e-02 -3.0179054e-02 -2.9514352e-02 GMPO
base, UNSLOTH_FUSED_LINEAR=0 -6.4426623e-02 -6.3641161e-02 -6.4426742e-02 -1.7928451e-02 -1.8217303e-02 -1.7928459e-02 GRPO
head, UNSLOTH_FUSED_LINEAR=0 (logits route, 4 of 4) -6.3431300e-02 -6.3431501e-02 -6.3993245e-02 -2.5418758e-02 -2.5418878e-02 -2.4645559e-02 GMPO

The reported loss matches the bold reference to 8e-8 to 4e-7. The other objective is 6.6e-4 to 9.6e-4 away. Steps 1 and 3 are the first pass over each generation, where the ratio is 1 and both objectives are about 0.

Memory, peak allocated above the start of compute_loss (forward only):

Path MiB
plain GRPO, fused loss 23.2
GMPO, head, fused route 23.2
GMPO, head, logits route 121.9

Whole-run max allocated: 1.610 GiB for base and head GMPO on the fused route, 1.664 GiB on the logits route.

Plain GRPO is bit-identical: the base, base (A/A) and head arms return the same loss bits on all 4 compute_loss calls (0x0.0p+0, 0x0.0p+0, -0x1.5555560000000p-26, -0x1.49c8c00000000p-6) and the same logged grad norms (1.14010, 1.14010, 1.53871, 1.32575). On head, _unsloth_grpo_subclass_loss_calls is 0 for GRPO and 4 for GMPO.

Not proven

  • GPU ran only TRL 1.18.2 and one model (Qwen2.5-0.5B, 16-bit LoRA). TRL 1.15.0 and 0.22.2 are CPU only. GMPO needs TRL >= 1.15, so it was not run on transformers 4.x.
  • No vLLM run. The old-logprob shortcuts standing down under vLLM importance sampling and UNSLOTH_GRPO_ROLLOUT_LOGPROBS_AS_OLD=1 are covered by the CPU test only.
  • Not run: multi-GPU, DDP, FSDP, DeepSpeed, context parallel. FSDP / DeepSpeed take the logits route by design.
  • Vision GMPO and subclass losses that pass vision tensors, token type ids or sampling masks now raise NotImplementedError instead of being supported.
  • The subclass path scores the whole micro-batch in one forward, as TRL does. It does not use the fused loss's row mini-batching, so at large batch x length its peak can exceed plain GRPO's. Equal peaks were measured only at 4 x 48 tokens.
  • With num_iterations > 1, a subclass loss now pays TRL's no-grad pi_old forward per generation instead of reusing the first pass.
  • Not run: jobs/ab.py --perf-gate and the compile counters. The plain GRPO path only gains an MRO check before the unchanged body, and its loss and grad norms are bit-identical over 4 steps. There is no step-time claim.

Round 2: review fixes

Scoring for subclass objectives is now shared. When a class below Unsloth's fused compute_loss overrides _compute_loss, Unsloth's generated _get_per_token_logps_and_entropies (and the legacy _get_per_token_logps on TRL 0.18 / 0.19) delegate every pass to grpo_subclass_logps_and_entropies: the rollout's old-policy and reference scoring and the objective's gradient pass. All three tensors have the completion's width and come from the same forward and projection, so the ratio starts at exactly 1 even with mixed prompt lengths. The dispatch calls self._compute_loss through normal method lookup, with no instance rebinding.

Other changes:

  • DDP with find_unused_parameters=True and a trainable head: scores from the logits on every pass (PPO / RLOO guard).
  • The caller's UNSLOTH_RETURN_HIDDEN_STATES is restored, not overwritten.
  • TRL's vLLM importance-sampling ratio, metrics and importance_sampling_ratio export stay live for subclass objectives. Plain GRPO still uses Unsloth's own correction. TRL's GMPO formula ignores the ratio (upstream behaviour) and Unsloth warns once.
  • sampling_mask (TRL >= 1.18): log-probs are normalised over vLLM's candidate set, as TRL's fused head does.
  • Kept-set reconstruction (UNSLOTH_GRPO_TRUNCATED_SUPPORT) is refused for subclass objectives, with a warning.
  • TRL >= 1.15 contract: completion pads score 0 and the entropy keeps its gradient (zoo kernel lazy mode on the fused route). Older TRL computes the entropy under no_grad.
  • The head projection runs inside the forward's autocast, and the forward runs under the left-padding mask scope PPO and distillation use.
  • Fused-loss sample weighting stands down for subclass objectives.
  • temperature=None falls back to args.temperature, and an empty completion window returns empty scores.

Not changed: the process-wide forward-mode switch (UNSLOTH_RETURN_HIDDEN_STATES) shared by all Unsloth scorers. Moving to a per-forward keyword is a separate change.

Math parity:

Framework Symbol Formula Matches
TRL 1.15.0 / 1.18.2 GMPOTrainer._compute_loss sign-aware clip of the token log-ratio in log space, coef = exp(masked mean), loss = mean_i(-coef_i A_i) (+ beta x sequence-mean k3) / GA runs unchanged under Unsloth
verl compute_policy_loss_geo_mean (geo_mean) the same sign-aware log-space clip and masked geometric mean (denominator +1e-8 instead of clamp(min=1)), and it multiplies by a geometric-mean rollout IS weight objective yes; verl also applies the IS weight, TRL's GMPO does not
SkyRL GSPO sequence ratio first, then PPO clip different objective

fp64 oracle (CPU, TRL 1.18.2)

Inputs: a tiny float64 model; mixed prompt lengths (a left-padded prompt), a right-padded completion and a one-token completion; old logps offset so the ratios fall on both sides of the clip; GA 2. The ids now start at 1 so pads can be 0 for Unsloth's own scorer, which moved the fused-route number from 3.4e-8 to 6.0e-9.

Route beta |TRL - oracle| |Unsloth - TRL| (loss) max |d grad| rollout-scored old / ref: |loss - (-mean(A) / GA)|
fused kernel 0 0 6.0e-09 8.7e-08 0
fused kernel 0.04 0 5.9e-09 7.9e-08 0
logits 0 0 2.8e-17 1.4e-16 0
logits 0.04 0 2.8e-17 1.7e-16 0

The last column scores old (and ref) with the generated rollout scorer at the same weights: the ratio is exactly 1 and the KL exactly 0.

Tests

tests/test_grpo_subclass_compute_loss.py:

TRL transformers previous head 9c5b181 this head
0.18.2 (version_corners floor) 5.18.0 not run 10 passed, 20 skipped
0.22.2 4.57.6 15 failed, 8 passed, 7 skipped 23 passed, 7 skipped
1.15.0 5.18.0 19 failed, 10 passed, 1 skipped 29 passed, 1 skipped
1.18.2 (version_corners ceiling / latest) 5.18.0 19 failed, 10 passed, 1 skipped 29 passed, 1 skipped

On the previous head, the new tests fail for the reported reasons: torch.Size([4, 8]) != torch.Size([4, 6]), Expected to mark a variable ready only once, False and self.use_vllm and ..., NotImplementedError: ... got sampling_mask, assert '0' == None, and the legacy scorer returning None.

Existing tests/test_grpo*.py + tests/test_rl*.py, merge base f5dfe68 vs this head:

TRL base head
1.18.2 902 passed, 9 skipped 931 passed, 10 skipped
0.22.2 847 passed, 46 skipped, 9 failed 870 passed, 53 skipped, 9 failed

The head adds exactly the new file's counts. The 9 failures on TRL 0.22.2 are the same IDs on both sides, all in tests/test_grpo_rollout_scope.py. They are pre-existing and not touched here.

GPU (Colab L4)

Setup: Qwen2.5-0.5B-Instruct bf16, LoRA r16, HF generate. Four prompts per micro-batch as 2 prompts x 2 generations, one short and one long, so the batch carries 28 left-pad tokens. 48 completion tokens, num_iterations=2, 4 steps, seed 0. Versions: unsloth f5dfe68 + overlay, zoo 070570c, TRL 1.18.2, transformers 5.18.0. Each arm ran in a fresh process and asserted its tree.

Arm result
plain GRPO, base x2 and head loss and grad norm identical as floats on all 4 steps (grad norms 0.881, 0.881, 0.565, 0.554)
GMPO, base 0 subclass calls; old logps 76 wide against 48 completion tokens; trains the fused GRPO loss
GMPO, previous head 9c5b181 RuntimeError: The size of tensor a (48) must match the size of tensor b (76) in GMPO's log_ratio
GMPO, this head, fused route 4 subclass calls; old logps 48 wide; old equals the scorer at 0.0 max abs on each generation's first pass
GMPO, this head, UNSLOTH_FUSED_LINEAR=0 same, logits route
GMPO, this head, beta 0.04 ref logps 48 wide, equal to the scorer at step 1; trains
Arm step 2 loss GMPO ref GRPO ref step 4 loss GMPO ref GRPO ref
fused route -4.9653053e-02 -4.9653113e-02 -4.8836458e-02 -1.0575756e-02 -1.0575727e-02 -1.0519058e-02
logits route -4.9504310e-02 -4.9504161e-02 -4.8388127e-02 -8.8441372e-03 -8.8442266e-03 -8.9547038e-03

The references recompute both objectives in float32 from the same inputs right after each compute_loss: from fp32 head projections of the hidden states for the fused route, and from bf16 logits for the logits route.

Memory:

Arm peak above the start of compute_loss (MiB) whole-run max allocated (GiB)
plain GRPO (base, head) 25.3 / 11.4 0.985
GMPO base (fused GRPO loss) 1.612
GMPO head, fused route 27.8 to 36.1 1.633
GMPO head, logits route 126.4 to 134.5 1.695

Not covered: a live vLLM rollout (importance-sampling ratio, sampling_mask from a real sampler), multi-rank DDP on GPU (the DDP fallback ran on CPU gloo with world size 1), a real GPT-OSS model, and compile counters for the subclass path (it runs TRL's eager _compute_loss; plain GRPO's compiled path is unchanged and bit-identical above).

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-22T10:07:53.461717Z 0a3cc9b Manual request
ℹ️ 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: 9c5b1818aa

ℹ️ 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/_grpo_subclass_loss.py Resolved
When a subclass overrides _compute_loss, Unsloth's generated
_get_per_token_logps_and_entropies (and the legacy _get_per_token_logps on
TRL 0.18 / 0.19) delegate every pass to grpo_subclass_logps_and_entropies, so
old, reference and current logps have the completion's width and come from one
route; mixed prompt lengths no longer crash GMPO and the ratio starts at 1.

- dispatch through normal method lookup (no instance rebinding)
- DDP find_unused_parameters with a trainable head scores from the logits
- restore the caller's UNSLOTH_RETURN_HIDDEN_STATES
- keep TRL's vLLM importance-sampling ratio, metrics and export live for
  subclass objectives; warn once that GMPO ignores it
- score sampling_mask candidate sets like TRL's fused head
- refuse kept-set reconstruction for subclass objectives
- TRL >= 1.15 contract: zero completion-pad scores, differentiable entropy
- head projection inside autocast, left-padding mask scope on the forward
- sample weighting stands down for subclass objectives
- temperature=None and empty completion windows
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Hooray!

Reviewed commit: 0a3cc9bab9

ℹ️ 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 added a commit that referenced this pull request Nov 22, 2026
…d up front (intermittent diffusion-shard timeout) (#18885)

## Summary

`(Python 3.13, diffusion)` fails intermittently on unrelated PRs with
the same test:

```
studio/backend/tests/test_diffusion_ddp.py::test_all_reduce_averages_grads_and_loss_and_flags
tests/test_diffusion_ddp.py:55: in _spawn
    codes = [p.wait(timeout = timeout) for p in procs]
E   Failed: Timeout (>330.0s) from pytest-timeout.
```

It is the failing test in 3 of the last 6 failed Backend CI runs
(`studio-wan-vae-2frame`, `audio-cpp-accelerator-chosen-install`,
`perf/r37-translate-history-memo`) and on #18851 and #18702.

The test (from #18771) spawns two gloo ranks and joins them through a
`TCPStore` on a port that `_port()` found free by binding and closing a
socket in the parent. The port is only bound for real later, by rank 0
in its own process, after torch has imported. Under xdist another worker
can take that port in the meantime. Rank 0 then fails to bind, rank 1
waits out the store's 300 s timeout, and pytest-timeout kills the test
at 330 s. In the failing logs only one of the spawned pairs ever prints
the gloo "connected to 1 peer ranks" lines.

## Fix

The two spawned ranks rendezvous through a `FileStore` in a fresh temp
directory per spawn (same 300 s store timeout), so there is no port to
race for. `diffusion_ddp`'s gate only uses `store.set` / `store.wait`,
which `FileStore` provides. Production code is unchanged; this is the
test harness only.

## Testing

- `studio/backend/tests/test_diffusion_ddp.py`: 22 passed, including the
gradient all-reduce and the two-rank `train` spawns.
@danielhanchen
danielhanchen merged commit 3b052ab into main Nov 22, 2026
@danielhanchen
danielhanchen deleted the grpo-subclass-loss branch November 22, 2026 18:24
danielhanchen added a commit that referenced this pull request Nov 22, 2026
…e-12, not bit for bit (#18939)

## Summary


`tests/test_grpo_subclass_compute_loss.py::test_rollout_scores_feed_the_subclass_objective[logits_route-*]`,
added by #18851, failed in the `Repo tests (CPU, rest)` shard of a
staging run on `main` d10f9d6:

```
tests/test_grpo_subclass_compute_loss.py:521: in test_rollout_scores_feed_the_subclass_objective
    assert torch.equal(current[cm], scored[cm])
E   assert False
```

The two tensors in the failure print identical to four decimal places.
The test scores the rollout with `batch_size = 2`, then scores the same
weights again in a single batch, and asserts the two are bit for bit
equal. On the logits route those are float64 matmuls of different
shapes, and on some CPUs they can differ in the last bit. The code under
test is fine. The assertion asks for more than the contract does: the
scores have to match, not come from identically shaped kernels.

## Fix

`torch.equal` becomes `torch.testing.assert_close(..., rtol = 0, atol =
1e-12)`:

- **Logits route (float64):** tolerates a last-bit difference.
- **Fused route (float32):** still effectively exact, since 1e-12 is far
below a float32 ULP at these magnitudes.
- **The regression the test was written for:** the left-packed window
#18851 fixed is off by O(1), so it still fails.

The following `abs(loss - want) < 1e-12` check is unchanged.

## Testing

- `tests/test_grpo_subclass_compute_loss.py` with TRL 1.18.2,
transformers 5.18.0, torch 2.10 CPU and zoo `main`: 29 passed, 1
skipped.
- Sabotage, shifting the rollout scores before the comparison:
- By 1e-9: both float64 logits-route cases fail ("Greatest absolute
difference: 1.0e-09 (up to 1e-12 allowed)"). On the float32 fused route,
1e-9 rounds away, so it is not a real change there.
  - By 1e-4: all four cases fail.
- I could not reproduce the last-bit difference on this host (AVX2,
AVX-512 and default ATen kernels, 1 and 4 threads all pass), so the CI
log above is the only evidence of it.
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