[BUG] GRPO REAL loss divides by all groups instead of valid groups, silently scaling gradients
Maintainers usually reply within 1 day
Assessment
- Difficulty
- 2/5
- Estimated time
- 1-3 hours
- Newbie friendliness
- 78/100
- Issue type
- Bug
- Clarity
- Clearly specified
- Activity status
- Active
- Domain
- machine-learning
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
- No Dockerfile or Docker Compose file
- Has a pull request template
- Read the contributing guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
More from modelscope/ms-swift
-
get_multimodal_target_regex(..., exclude_router=True) does not exclude shared_expert_gatePossibly taken @KonnyakuMatcha claimed this 1 day ago. Open
Difficulty 2/5 1-3 hours Newbie friendliness 78/100
modelscope/ms-swift#10696 ·
Maintainers usually reply within 1 day
-
[BUG] GRPO REAL loss crashes with beta>0 and kl_in_reward=True (NoneType * Tensor)Possibly taken @newcloud123 claimed this 1 day ago. Open
Difficulty 2/5 1-3 hours Newbie friendliness 85/100
modelscope/ms-swift#10690 ·
Maintainers usually reply within 1 day
-
enhancement
Difficulty 2/5 Half a day Newbie friendliness 62/100
modelscope/ms-swift#10621 ·
Maintainers usually reply within 1 day
-
[Bug] `get_seed` consumes a draw from the shared RandomState even when decision augmentation is disabled, changing the train/val split and dataset shufflePossibly taken @ryznren claimed this 38 days ago. Openbug
Difficulty 2/5 1-3 hours Newbie friendliness 75/100
modelscope/ms-swift#10466 · 1 comment ·
Maintainers usually reply within 1 day
-
[Bug] `swift --help` raises KeyError instead of showing CLI helpPossibly taken @haahy claimed this 64 days ago. Openbug
Difficulty 2/5 1-3 hours Newbie friendliness 76/100
modelscope/ms-swift#10287 ·
Maintainers usually reply within 1 day
All issues in modelscope/ms-swift
Similar issues
-
Test: to_hijri() accepts datetime.datetime and uses only the date partPossibly taken A pull request linked to this issue is open or already merged. Opengood first issue
Difficulty 1/5 Under an hour Newbie friendliness 95/100
omarelshamy25x/shamy-hijri#63 · 3 comments ·
Maintainers usually reply within 1 day
-
polish
Difficulty 2/5 1-3 hours Newbie friendliness 84/100
Maintainers usually reply within 1 day
-
Difficulty 2/5 1-3 hours Newbie friendliness 76/100
521xueweihan/HelloGitHub#4729 ·
-
[Bug]: Score parser reads parts of scientific notation as valid scoresPossibly taken @AshutoshSingh840 claimed this today. Open
Difficulty 2/5 1-3 hours Newbie friendliness 82/100
UKGovernmentBEIS/control-arena#992 ·
Maintainers usually reply within 3 days
-
Difficulty 1/5 Under an hour Newbie friendliness 92/100
mvalentsev/awesome-free-ai-coding#70 ·
Maintainers usually reply within 1 day