Skip to content

[BugFix] [LLM] Detach clipped importance ratio in CISPOLoss to preserve token policy gradients - #4665

Open
davrens101 wants to merge 1 commit into
pytorch:mainfrom
davrens101:fix/cispo-detached-importance-gradient
Open

davrens101 wants to merge 1 commit into
pytorch:mainfrom
davrens101:fix/cispo-detached-importance-gradient

Conversation

@davrens101

@davrens101 davrens101 commented Nov 2, 2026 •

Copy link
Copy Markdown

Problem

Fixes #4664.

CISPOLoss computed its policy objective by multiplying the clamped importance ratio by the advantage, then taking gradients through that product:

ratio = torch.clamp(ratio, 1 - self.clip_epsilon, 1 + self.clip_epsilon)
objective = ratio * advantage

Autograd through torch.clamp zeroes out gradients for all tokens whose importance ratio falls outside [1 - ε, 1 + ε]. This contradicts the defining mathematical design of CISPO (MiniMax-M1 paper, eq. 4, https://arxiv.org/html/2506.13585v1#S3.E4), which requires detaching the clipped ratio and multiplying it by the current log-probability:

$$L_{\text{CISPO}}(\theta) = -\text{stop_gradient}\left(\text{clip}\left(\frac{\pi_\theta(y_t)}{\pi_{\text{old}}(y_t)}, 1-\epsilon, 1+\epsilon\right)\right) \cdot A_t \cdot \log \pi_\theta(y_t)$$

The previous implementation caused clipped tokens to contribute exactly zero gradient, destroying the policy updates for all tokens that CISPO was designed to continue updating with bounded weights.

Solution

  1. Extend the private _compute_policy_objective hook in torchrl/objectives/llm/grpo.py to accept cur_log_prob (computed in _log_weight and stored as _cur_log_prob).
  2. In GRPOLoss, the objective computation remains unchanged (standard PPO-style surrogate).
  3. In CISPOLoss, detach the clamped ratio and multiply by cur_log_prob * advantage:
    gain = ratio.detach() * cur_log_prob * advantage
  4. Update the docstring of CISPOLoss to document the detached importance ratio and non-vanishing out-of-interval gradients.
  5. Add native test_cispo_detached_importance_gradients in test/llm/test_llm_objectives.py checking loss values and exact parameter gradients against paper equation 4 across ratios below, inside, and above the clipping interval, with both positive and negative advantages and sequence padding masks.
  6. Remove the incidental test_cispo_no_min_clip_objective test which previously pinned the erroneous non-detached forward value.

Verification

  • Actual trainable model smoke before/after: A trainable 2-class nn.Linear token policy with LLMMaskedCategorical was evaluated on token 0 (current $p = 0.2$, behavior $p \in {0.4, 0.2, 0.1}$ giving ratios $0.5, 1.0, 2.0$ with $\epsilon = 0.2$).
    • Before fix: parameter gradients for ratios 0.5 and 2.0 were identically [0.0, 0.0].
    • After fix: parameter gradients match paper equation 4 exactly within float32 tolerance:
      • ratio 0.5: [-0.64, +0.64] (max error $7.45 \times 10^{-9}$)
      • ratio 1.0: [-0.80, +0.80] (max error $0.0$)
      • ratio 2.0: [-0.96, +0.96] (max error $6.33 \times 10^{-9}$)
  • TorchRL compiled smoke: Verified with torch.compile(backend="eager").
  • Targeted pytest: test/llm/test_llm_objectives.py -k "cispo or grpo or dapo": 15 passed, 2 skipped, 70 deselected.
  • Full non-integration CPU test suite: test/llm/test_llm_objectives.py: 82 passed, 1 skipped, 4 deselected, 40 warnings.
  • Code formatting and linting: ufmt check and flake8 pass cleanly on changed files.
  • Independent read-only AI review: verified no blocking defects; confirmed removal of legacy fallback and correct tensor shapes.

Review and assistance

I supervised and checked the AI-assisted work as it progressed. AI assistance was used for investigation, reproduction, implementation, and verification. No maintainer review or approval is claimed. CLA acceptance remains an account-holder action.

@pytorch-bot

pytorch-bot Bot commented Nov 2, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

⚠️ 16 Awaiting Approval

As of commit 6935656 with merge base 61cf3dc (image):

AWAITING APPROVAL - The following workflows need approval before CI can run:

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 Nov 2, 2026
@github-actions github-actions Bot added Objectives llm/ LLM-related PR, triggers LLM CI tests labels Nov 2, 2026
@github-actions

github-actions Bot commented Nov 2, 2026

Copy link
Copy Markdown
Contributor

⚠️ PR Title Label Error

PR title must start with a label prefix in brackets (e.g., [BugFix]).

Current title: Detach clipped importance ratio in CISPOLoss to preserve policy gradients

Supported Prefixes (case-sensitive)

Your PR title must start with exactly one of these prefixes:

Prefix Label Applied Example
[Algorithm] new algo [Algorithm] Add new RL objective
[BE] BE [BE] Improve error messages
[Benchmark] or [Benchmarks] Benchmarks [Benchmark] Add collector benchmark
[BugFix] BugFix [BugFix] Fix memory leak in collector
[Example] or [Examples] Examples [Example] Add training script
[Feature] Feature [Feature] Add new optimizer
[Doc] or [Docs] Documentation [Doc] Update installation guide
[Refactor] Refactoring [Refactor] Clean up module imports
[CI] CI [CI] Fix workflow permissions
[Test] or [Tests] Tests [Tests] Add unit tests for buffer
[Trainer] or [Trainers] Trainers [Trainer] Add trainer config
[Environment] or [Environments] Environments [Environments] Add Gymnasium support
[Data] Data [Data] Fix replay buffer sampling
[LLM] llm/ [LLM] Add reward model integration
[Minor] small change [Minor] Fix typo in error message
[Performance] or [Perf] Performance [Performance] Optimize tensor ops
[BC-Breaking] bc breaking [BC-Breaking] Remove deprecated API
[Deprecation] Deprecation [Deprecation] Mark old function
[Algorithm] or [Algorithms] new algo [Algorithm] Add new objective
[Quality] Quality [Quality] Fix typos and add codespell
[Versioning] versioning [Versioning] Bump release version
[WIP] WIP [WIP] Draft implementation

Note: Common variations like singular/plural are supported (e.g., [Doc] or [Docs]).

@davrens101 davrens101 changed the title Detach clipped importance ratio in CISPOLoss to preserve policy gradients [LLM] Detach clipped importance ratio in CISPOLoss to preserve policy gradients Nov 2, 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.

LGTM! Thanks for your contribution!

Tested locally — gradients for clamped tokens were indeed getting zeroed out on main because of autograd through clamp. The fix matches Eq. 4 from the paper, and the regression tests pass cleanly without breaking any of the other LLM objectives.

@davrens101 davrens101 changed the title [LLM] Detach clipped importance ratio in CISPOLoss to preserve policy gradients [LLM] Detach clipped importance ratio in CISPOLoss to preserve token policy gradients Nov 8, 2026
@davrens101 davrens101 changed the title [LLM] Detach clipped importance ratio in CISPOLoss to preserve token policy gradients [BugFix] [LLM] Detach clipped importance ratio in CISPOLoss to preserve token policy gradients Nov 13, 2026

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

BugFix CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. llm/ LLM-related PR, triggers LLM CI tests Objectives

Projects

None yet

Development

Successfully merging this pull request may close these issues.

CISPOLoss drops out-of-range token gradients instead of detaching IS weights

2 participants