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 NoneInspect 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()