Skip to content

[Feature] Add GSPOLoss - #4653

Open
arun-elr wants to merge 2 commits into
pytorch:mainfrom
arun-elr:feat/gspo-loss
Open

arun-elr wants to merge 2 commits into
pytorch:mainfrom
arun-elr:feat/gspo-loss

Conversation

@arun-elr

@arun-elr arun-elr commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

Description

Adds GSPOLoss, GSPO as a GRPOLoss subclass, in the same shape as CISPOLoss.

  • Ratio. GSPO uses one importance ratio per sequence, s_i = exp(mean_t(log pi_theta - log pi_old)), in the GRPO clipped objective. GSPOLoss overrides only _log_weight and uses the paper's GSPO-token form: each valid token's log weight is sg[log s_i] + (log pi_theta(y_i,t) - sg[log pi_theta(y_i,t)]). The clipped objective, entropy, KL terms and aggregation come from GRPOLoss unchanged. With aggregation="prompt_mean" and an advantage that is constant over each sequence, this gives the paper's sequence-level objective.
  • Sequence. A sequence is one batch row: its valid tokens under masking_strategy, across turns for "rlhf".
  • Precision. The per-sequence sum runs in at least float32, so a long fp16 sequence does not overflow.
  • KL mask. kl_mask_threshold raises a ValueError, because GRPOLoss.forward applies the KL mask after the sequence ratio is computed.
  • Docs. Exported from torchrl.objectives.llm and listed in docs/source/reference/llms.rst.

Open questions from #4652, happy to adjust:

  1. A GSPOLoss subclass, or an option on GRPOLoss.
  2. Defaults. Following review, GSPOLoss now defaults to the paper's values, clip_epsilon=(3e-4, 4e-4) and aggregation="prompt_mean" (None also gives "prompt_mean"), instead of the GRPOLoss defaults (0.2, "token_mean"), with a test of the defaults. Happy to revert if you prefer the GRPOLoss defaults.
  3. Whether sota-implementations/grpo should get a config option to pick the loss, with smoke test coverage and a benchmark.

Motivation and Context

close #4652

verl (actor_rollout_ref.actor.policy_loss.loss_mode=gspo) and TRL (GRPOConfig(importance_sampling_level="sequence")) support GSPO. TorchRL has GRPO, DAPO and CISPO, all with per-token ratios.

  • I have raised an issue to propose this change (required for new features and bug fixes)

Types of changes

  • New feature (non-breaking change which adds core functionality)

Testing

CPU, Python 3.12, torch 2.11.0+cpu. New tests in test/llm/test_llm_objectives.py::TestLosses, using the existing _FixedLogProbPolicy helpers:

  • test_gspo_matches_sequence_objective: loss and gradient match the sequence-level objective written directly from the paper, for rows with different padding, with a wide clip and with the paper's clip. Padded tokens get zero gradient.
  • test_gspo_clips_whole_sequence: just past each clip bound, every token gradient of a sequence is zero when the advantage sign is the clipped one, and nonzero for the opposite sign.
  • test_gspo_token_advantages: with per-token advantages [1, -1], the token gradients are [-0.5, 0.5].
  • test_gspo_half_precision_long_sequence: a 32768-token fp16 sequence gives a finite loss.
  • test_gspo_rejects_kl_mask.
python -m pytest test/llm/test_llm_objectives.py -q -k "gspo or cispo"
8 passed, 80 deselected

python -m pytest test/llm/test_llm_objectives.py -q
2 failed, 71 passed, 14 skipped, 1 error

The 2 failures and the error (test_grpo, test_failure_missing_entries, test_sft_assistant_only) also happen on main without this change in the same environment: they import transformers, which is not installed there. Replacing GSPOLoss._log_weight with GRPO's per-token ratio, or letting the gradient flow through the sequence mean, or summing in fp16, makes the new tests fail.

Checklist

  • I have read the CONTRIBUTION guide (required)
  • My change requires a change to the documentation.
  • I have updated the tests accordingly (required for a bug fix or a new feature).
  • I have updated the documentation accordingly.

@pytorch-bot

pytorch-bot Bot commented Oct 31, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/pytorch/rl/4653

Note: Links to docs will display an error until the docs builds have been completed.

❗ 1 Active SEVs

There are 1 currently active SEVs. If your PR is affected, please view them below:

✅ You can merge normally! (1 Unrelated Failure)

As of commit 396bcc2 with merge base 2bb989f (image):

BROKEN TRUNK - The following job failed but were present on the merge base:

👉 Rebase onto the `viable/strict` branch to avoid these failures

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. label Oct 31, 2026
@github-actions github-actions Bot added Feature New feature Documentation Improvements or additions to documentation Objectives llm/ LLM-related PR, triggers LLM CI tests and removed Feature New feature labels Oct 31, 2026

@coder-jayp coder-jayp left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Overall LGTM!
I’ve left a few minor inline comments on setting the paper defaults and adding a default instantiation test.

Comment thread torchrl/objectives/llm/grpo.py Resolved
Comment thread torchrl/objectives/llm/grpo.py Resolved
Comment thread test/llm/test_llm_objectives.py Resolved
@github-actions github-actions Bot added the Feature New feature label Oct 31, 2026
@arun-elr

Copy link
Copy Markdown
Contributor Author

I've left a few minor inline comments on setting the paper defaults and adding a default instantiation test.

@coder-jayp thanks for the review! All three are in 6b55393:

  • GSPOLoss.__init__ now defaults to clip_epsilon=(3e-4, 4e-4) and aggregation="prompt_mean". aggregation=None also gives "prompt_mean", so it doesn't fall back to GRPO's "token_mean".
  • The docstring has Args and Keyword Args sections with both defaults, their types, and why the clip is so much tighter than GRPO's.
  • test_gspo_paper_defaults checks aggregation == "prompt_mean" and the clip buffers at 3e-4 and 4e-4, plus the None case.

test/llm/test_llm_objectives.py passes apart from the tests that need transformers or vllm, which aren't installed on this CPU machine. This settles question 2 from #4652 in favor of the paper's values; I've updated the PR description to match.

@arun-elr
arun-elr marked this pull request as ready for review October 31, 2026 20:18

@coder-jayp coder-jayp left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks for the contribution!

LGTM. The paper defaults, updated docstrings, and tests look great and pass locally.

@arun-elr

arun-elr commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

@coder-jayp thanks for the review!

the one red check is the Examples tests job, Dr.CI marks it as broken trunk (it fails on the merge base too).

@vmoens @theap06 could you take a look and merge?

@arun-elr

arun-elr commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

Correcting what I said about the red check: it is tests (3.12, 13.0, 2) / linux-job, and it failed before any test ran.

The log ends with "Credentials could not be loaded, please check your action inputs" followed by "Executing the custom container implementation failed. Please contact your self hosted runner administrator", so this is runner infrastructure on the 1 November run rather than anything in this PR.

A re-run should clear it. I cannot trigger one from a fork.

@arun-elr

Copy link
Copy Markdown
Contributor Author

@theap06 could you take a look when you get a chance? coder-jayp approved it and it still merges cleanly w/ main.

@theap06

theap06 commented Nov 23, 2026

Copy link
Copy Markdown
Collaborator

@theap06 could you take a look when you get a chance? coder-jayp approved it and it still merges cleanly w/ main.

Sorry for taking some time to get back to you! The PR looks great. I just ran some experiments for single and multi-turn for rlhf. The loss and gradients are in line with the paper Thanks for the PR!

@theap06 theap06 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for the PR! @coder-jayp thanks for reviewing the pr!

@theap06

theap06 commented Nov 23, 2026

Copy link
Copy Markdown
Collaborator

@arun-elr can you rebase onto main to re-trigger ci?

GSPO (https://arxiv.org/abs/2507.18071) uses one importance ratio per
sequence, the geometric mean of the token ratios, in the GRPO clipped
objective. GSPOLoss subclasses GRPOLoss and overrides only _log_weight,
using the paper's GSPO-token form so the existing objective and
aggregation are reused. kl_mask_threshold is rejected because the KL
mask is applied after the sequence ratio is computed.

Refs pytorch#4652
clip_epsilon=(3e-4, 4e-4) and aggregation="prompt_mean", as in the GSPO paper. With GRPO's 0.2 the sequence ratio rarely reaches the bounds. Document both in a Keyword Args section and test the defaults.
@arun-elr

Copy link
Copy Markdown
Contributor Author

@theap06 rebased cleanly onto latest main (2bb989ff) and force-pushed as 396bcc21, so CI should re-trigger now. Re-ran pytest test/llm/test_llm_objectives.py -k gspo locally (8 passed).

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. Documentation Improvements or additions to documentation Feature New feature llm/ LLM-related PR, triggers LLM CI tests Objectives

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature Request] GSPOLoss (sequence-level importance ratio for GRPO)

3 participants