REAL PYTORCH · CPU TRAINING AND AUTOGRAD

Own grouped advantages and the clipped policy surrogate

Implement the GRPO-style clipped surrogate core for [prompts,completions,tokens] sampled log probabilities. Use detached within-prompt reward advantages normalized by population standard deviation plus 1e-8. Compute exp(logp-old_logp.detach()), take the minimum of unclipped and [1-clip,1+clip] clipped ratio times advantage, average over valid tokens within each response, then equally over prompts/completions. Detach rewards. Require each response to contain a token, at least two completions, 0<clip<1 and absolute log-ratio<=20. This exercise isolates the surrogate; rollout collection, a reference-KL penalty and reward design are separate components.

Run this Lab in Pythilo

Open Labs, choose its topic and tap Download entire topic, or Download entire category for all its Labs, including the required Python packages, then load the starter or worked answer and tap Trace. Progress, pause, resume and removal are in Downloads. Independent checks execute real CPU training and gradients.

No GPU, external model weights or API key is required. After downloading the topic and packages, this Lab runs offline.

PyTorch is unavailable in this browser runtime. The code and lessons are readable here; execution and checks run in the app.

Pythilo on the App Store →

Read lesson: Own grouped advantages and the clipped policy surrogate →

Your task

Implement the GRPO-style clipped surrogate core for [prompts,completions,tokens] sampled log probabilities. Use detached within-prompt reward advantages normalized by population standard deviation plus 1e-8. Compute exp(logp-old_logp.detach()), take the minimum of unclipped and [1-clip,1+clip] clipped ratio times advantage, average over valid tokens within each response, then equally over prompts/completions. Detach rewards. Require each response to contain a token, at least two completions, 0<clip<1 and absolute log-ratio<=20. This exercise isolates the surrogate; rollout collection, a reference-KL penalty and reward design are separate components.

Starter

import math
import torch

def group_policy_loss(logp, old_logp, rewards, mask, clip=.2):
    # TODO: implement group_policy_loss under the declared contract.
    return None
Inspect the worked answer
import math
import torch

def group_policy_loss(logp, old_logp, rewards, mask, clip=.2):
    if logp.ndim!=3 or min(logp.shape)==0 or logp.shape[1]<2 or old_logp.shape!=logp.shape or mask.shape!=logp.shape or rewards.shape!=logp.shape[:2]:raise ValueError('Expected aligned [prompts, completions>=2, tokens] tensors.')
    if mask.dtype!=torch.bool or not logp.is_floating_point() or not math.isfinite(clip) or not 0<clip<1 or any(not x.is_floating_point() or not torch.isfinite(x).all() for x in (logp,old_logp,rewards)):raise ValueError('Expected finite floating policy scores/rewards, boolean masks and 0<clip<1.')
    if (mask.sum(-1)==0).any() or ((logp-old_logp).detach().abs()>20).any():raise ValueError('Each response needs tokens and bounded finite log ratios.')
    centered=rewards.detach()-rewards.detach().mean(-1,keepdim=True)
    advantage=centered/(rewards.detach().std(-1,correction=0,keepdim=True)+1e-8)
    ratio=(logp-old_logp.detach()).exp()
    raw=ratio*advantage.unsqueeze(-1)
    bounded=ratio.clamp(1-clip,1+clip)*advantage.unsqueeze(-1)
    token=torch.minimum(raw,bounded)
    response=(token*mask).sum(-1)/mask.sum(-1)
    return -response.mean()

About this algorithm

How Own grouped advantages and the clipped policy surrogate works

The idea

Group Relative Policy Optimization (GRPO) trains a language model from rewards without a separate value network. Each prompt gets a group of sampled completions, each with a reward. The group is its own baseline: a completion's advantage is its reward minus the group mean, divided by the group standard deviation. Completions that beat their siblings get positive advantages.

The update is PPO's clipped surrogate. ratio is the new probability of a sampled token divided by its old one, and the objective takes the smaller of ratio * advantage and the same product with the ratio clamped to [1 - clip, 1 + clip]. Past the clip range in the favourable direction the gradient is zero, so one batch cannot pull the policy far from the one that sampled it.

How it works

  1. Validate aligned [prompts, completions, tokens] tensors with at least two completions, a boolean mask, 0 < clip < 1 and log ratios no larger than 20 in size.
  2. Detach rewards, subtract each prompt's mean and divide by its population standard deviation plus 1e-8 to get advantage.
  3. Compute ratio = (logp - old_logp.detach()).exp() for every sampled token.
  4. Form raw = ratio * advantage and bounded with the ratio clamped to [1 - clip, 1 + clip], then take their elementwise minimum.
  5. Average over each response's valid tokens using mask.
  6. Return the negative mean over all prompts and completions, so minimizing the loss raises the surrogate.

What it costs

Loss work
O(P·C·T)
Samples
C completions per prompt
Value network
none needed

The loss is elementwise over sampled tokens; the real expense is generating and scoring several completions for every prompt, which stands in for a learned value model.

Where it is used

  • The DeepSeekMath paper (Shao et al., 2024) introduced GRPO as a variant of PPO without a value model.
  • DeepSeek-R1 was trained with GRPO as its reinforcement learning algorithm.
  • Hugging Face's TRL library includes a GRPOTrainer.

Watch out for

  • Letting gradients flow through old_logp or rewards: only the new log probabilities may receive gradients, and the Lab checks this.
  • Normalizing advantages over the whole batch instead of within each prompt, which mixes easy and hard prompts and loses the group baseline.
  • Averaging over every token slot instead of the valid ones in mask, so padded positions dilute or distort a response's score.