[BUG] GRPO REAL loss divides by all groups instead of valid groups, silently scaling gradients

Open Beginner friendly
#10,688 0 comments 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 1 day

@newcloud123 is already working on this.

Since Dec 5, 2026.

  • #10689 by @newcloud123 — open

Assessment

Difficulty
2/5
Estimated time
1-3 hours
Newbie friendliness
78/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Active
Tech stack
python, pytorch

Research direction

Read the loss_type='real' branch in swift/rlhf_trainers/grpo_trainer.py, especially how valid_mask filters groups and how the denominator is computed. Compare the loss with the supplied pure tensor reproduction for batches containing invalid groups. Done means the loss is averaged over valid groups and the reproduction confirms the expected loss and gradient scale.

Written by the indexing model from the issue text.

Description

Describe the bug

swift/rlhf_trainers/grpo_trainer.py (main @ ece3bcc6), the loss_type='real' branch filters groups to keep only those containing both positive and negative samples (valid_mask), but the loss denominator is still group_rewards.size(0) — the total number of groups:

1105: valid_mask = (pos_mask.sum(dim=1) != 0) & (neg_mask.sum(dim=1) != 0)
1110: batch_scores = group_scores[valid_mask]           # only n_valid groups kept
1125: loss = (neg_loss + pos_loss).sum() / group_rewards.size(0)   # BUG: divides by n_total

Invalid groups (all-positive or all-negative) contribute zero to the numerator but still consume the denominator, so the loss and its gradient are silently multiplied by n_valid / n_total. Since the fraction of all-correct / all-wrong prompts changes during training, the effective learning rate drifts randomly with batch composition. This is a silent correctness bug.

Reproduction

Pure-tensor repro (4 groups of K=4; 2 valid, 2 all-positive):

import torch
B, K = 16, 4
adv = torch.tensor([1,1,1,1, 1,1,1,1, 1,-1,1,-1, 1,-1,-1,1], device='cuda', dtype=torch.float32)
g = adv.view(-1, K)
pos, neg = g > 0, g <= 0
valid = (pos.sum(1) != 0) & (neg.sum(1) != 0)     # n_valid=2, n_total=4
s = torch.arange(B, device='cuda', dtype=torch.float32).view(-1, K) / 10
bs = s[valid]; pn, nn = pos[valid], neg[valid]
neg_loss = torch.logsumexp(torch.cat([bs.masked_fill(~nn, float('-inf')), torch.zeros(len(bs),1,device='cuda')],1),1)
pos_loss = torch.logsumexp(torch.cat([(-bs).masked_fill(~pn, float('-inf')), torch.zeros(len(bs),1,device='cuda')],1),1)
bad  = (neg_loss+pos_loss).sum() / g.size(0)      # current implementation
good = (neg_loss+pos_loss).sum() / valid.sum()    # expected
print(bad.item(), good.item(), bad/good)          # 1.2628, 2.5256, 0.5

Verified on a single RTX 5090 (torch 2.7.0+cu128): the current implementation gives exactly half the expected loss/gradient.

Expected behavior

The denominator should count only the groups that contribute to the loss:

loss = (neg_loss + pos_loss).sum() / valid_mask.sum().clamp(min=1)

Environment

  • ms-swift main @ ece3bcc6
  • torch 2.7.0+cu128, CUDA / RTX 5090
  • loss_type='real'

Note: the competing refactor in PR #10683 still uses / group_rewards.size(0) in its compute_real_loss(), so this denominator bug is not covered there.

Dominant language
Python
Stars
16.2k
Forks
1.8k
Avg merge
1d 14h
Merged PRs (30d)
68

Getting set up

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from modelscope/ms-swift

All issues in modelscope/ms-swift

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.