Repository navigation
GRPO: honour a trainer subclass's own _compute_loss (GMPO trained plain GRPO) - #18851
Conversation
…ing the fused GRPO loss
|
@codex review |
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 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".
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
…o entropy_from_logits [skip ci]
|
@codex review |
|
Codex Review: Didn't find any major issues. Hooray! 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". |
…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.
…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.
Summary
Unsloth's generated GRPO
compute_loss(grpo_trainer_compute_lossinunsloth/models/rl_replacements.py) computes the GRPO objective in the zoo's fused loss and never callsself._compute_loss. TRL's extension point for new objectives is exactly that method:GRPOTrainer.compute_lossonly doesreturn self._compute_loss(model, inputs), andtrl.experimental.gmpo.GMPOTrainerchanges nothing but_compute_loss. Under Unsloth the MRO isGMPOTrainer -> UnslothGRPOTrainer, the inheritedcompute_lossis 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_losshand the batch to a_compute_lossdefined below it in the MRO. Plain GRPO keeps the existing fused path unchanged.Changes
unsloth/models/_grpo_subclass_loss.py:grpo_subclass_compute_loss(trainer)finds the class that owns the fusedcompute_loss(by the name its body imports, so a subclass that overridescompute_lossand callssuper()is still handled) and returns a_compute_lossdefined 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_lossruns the subclass_compute_losswith_get_per_token_logps_and_entropiesbound on the instance, for that call only, togrpo_subclass_logps_and_entropies. This is needed because Unsloth's own scorer returns detached old / reference logprobs.grpo_subclass_logps_and_entropieskeeps TRL's contract (log-probs of the completion tokens underself.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 raiseNotImplementedErrorinstead of being sliced incorrectly.unsloth/models/rl_replacements.py:compute_lossdispatches right after thereturn_outputscheck._unsloth_grpo_rollout_logps_as_old,_unsloth_grpo_old_logps_from_newand_unsloth_grpo_old_logps_storestand down for subclass losses. Their markers are read only by the fused loss, and a subclass reads TRL'sold_per_token_logps, so TRL scores pi_old for it. Without this, GMPO withnum_iterations > 1would seeold_per_token_logps=Noneon later passes and use a ratio of 1.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.
GMPOTrainer._compute_losscompute_lossTests
CPU fp64 oracle
The test runs:
compute_losssource in a stand-in class;GMPOTrainer._compute_lossfrom TRL's installed source;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.
The fused kernel computes in float32, hence the 3e-8. The test bound is 1e-6.
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*.pyandtests/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 intests/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_losscall. 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).UNSLOTH_FUSED_LINEAR=0UNSLOTH_FUSED_LINEAR=0(logits route, 4 of 4)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):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_losscalls (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_callsis 0 for GRPO and 4 for GMPO.Not proven
UNSLOTH_GRPO_ROLLOUT_LOGPROBS_AS_OLD=1are covered by the CPU test only.NotImplementedErrorinstead of being supported.num_iterations > 1, a subclass loss now pays TRL's no-grad pi_old forward per generation instead of reusing the first pass.jobs/ab.py --perf-gateand 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_lossoverrides_compute_loss, Unsloth's generated_get_per_token_logps_and_entropies(and the legacy_get_per_token_logpson TRL 0.18 / 0.19) delegate every pass togrpo_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 callsself._compute_lossthrough normal method lookup, with no instance rebinding.Other changes:
find_unused_parameters=Trueand a trainable head: scores from the logits on every pass (PPO / RLOO guard).UNSLOTH_RETURN_HIDDEN_STATESis restored, not overwritten.importance_sampling_ratioexport 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.UNSLOTH_GRPO_TRUNCATED_SUPPORT) is refused for subclass objectives, with a warning.temperature=Nonefalls back toargs.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:
GMPOTrainer._compute_losscompute_policy_loss_geo_mean(geo_mean)+1e-8instead ofclamp(min=1)), and it multiplies by a geometric-mean rollout IS weightfp64 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.
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: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: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.RuntimeError: The size of tensor a (48) must match the size of tensor b (76)in GMPO'slog_ratioUNSLOTH_FUSED_LINEAR=0The 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:
compute_loss(MiB)Not covered: a live vLLM rollout (importance-sampling ratio,
sampling_maskfrom 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).