Group-Based Policy Optimization › Implementing GRPO on a Toy Policy
Language AI HandbookAll chapters The objective is small enough to implement directly, but it requires an autoregressive policy, a sampling routine, a scoring routine, and a training loop. We build each piece in turn, using a deliberately tiny model so that everything runs on CPU. The implementation makes the mechanics inspectable: you can print every intermediate tensor, rerun with different seeds, and watch the effect of each design choice on the same toy problem.
The Toy Task
The toy task is chosen to expose the mechanisms that matter for understanding GRPO, without pretending to replicate real LLM training. The setup is:
- Vocabulary of five tokens, .
- Fixed prompt (implicit in the parameterization).
- Target response of length four.
- Reward is the fraction of positions that match the target.
- Group size .
- Reference policy is a frozen copy of the initial policy.
The reward takes one of five values from 0 through 1 because it grades each position separately. The graded reward can distinguish two completions that would both fail exact-match scoring. Under uniform independent token draws, exact match occurs with probability per response, so a group of eight has about a 1.27% chance of containing at least one exact match. That calculation is an illustration, not a measurement of the randomly initialized network.
The toy illustrates the original outcome-supervised GRPO objective with a tiny policy and fixed-length responses. It samples groups, standardizes their rewards, and uses the tokenwise clipped surrogate and a reference penalty. Tied reward groups become common during training in this run.
The Tiny Policy
The policy conditions on the position in the sequence and the previously generated token, and outputs a categorical distribution over the next token. This is enough to produce autoregressive behavior without needing a transformer. Position embeddings rather than a recurrent hidden state keep the focus on the learning signal rather than the architecture.
PythonIn [15]Expand
import torch
import torch.nn as nn
import torch.nn.functional as F
class TinyPolicy(nn.Module):
"""Autoregressive policy over a tiny vocabulary.
Given the position index and the previous token, outputs logits over the
next token. The model is deliberately minimal so the GRPO mechanics
dominate the training signal.
"""
def __init__(self, vocab_size=5, max_len=4, hidden=32):
super().__init__()
self.vocab_size = vocab_size
self.pos_emb = nn.Embedding(max_len, hidden)
self.tok_emb = nn.Embedding(vocab_size + 1, hidden) # +1 for BOS
self.net = nn.Sequential(
nn.Linear(2 * hidden, hidden),
nn.Tanh(),
nn.Linear(hidden, vocab_size),
)
def forward(self, prev_tokens, positions):
h = torch.cat(
[self.pos_emb(positions), self.tok_emb(prev_tokens)], dim=-1
)
return self.net(h) # (B, vocab_size)The embedding table for previous tokens has size so that index can be used as a begin-of-sequence token. Concatenating a position embedding and a token embedding is enough to distinguish, for example, "the first token is 3" from "the third token is 3," which matters because the model should be allowed to make different predictions at different positions. The hidden dimension of 32 is arbitrary; any small value works.
Sampling and Scoring
Sampling records the detached log-probability under the behavior policy for each sampled token. Scoring reuses those tokens and prefixes with gradients enabled under the learner policy. Subtract the behavior log-probability from the learner log-probability and exponentiate to obtain , the ratio of probabilities. The learner and behavior policies initially have the same weights and temperature. Rescoring after an update can change the ratio even though the original records are fixed.
PythonIn [16]Expand
sampling_temperature = 1.15
@torch.no_grad()
def sample_group(policy, group_size, seq_len, bos_id):
"""Sample `group_size` fixed-length responses and record their log-probs."""
B = group_size
prev = torch.full((B,), bos_id, dtype=torch.long)
tokens = torch.zeros(B, seq_len, dtype=torch.long)
log_probs = torch.zeros(B, seq_len)
for t in range(seq_len):
positions = torch.full((B,), t, dtype=torch.long)
logits = policy(prev, positions)
probs = F.softmax(logits / sampling_temperature, dim=-1)
sampled = torch.multinomial(probs, 1).squeeze(-1)
log_probs[:, t] = torch.log(
probs.gather(1, sampled.unsqueeze(-1))
).squeeze(-1)
tokens[:, t] = sampled
prev = sampled
return tokens, log_probs
def score_sequence(policy, tokens, bos_id):
"""Recompute per-token log-probs for a fixed token sequence (with grad)."""
B, T = tokens.shape
prev = torch.full((B,), bos_id, dtype=torch.long)
log_probs = torch.zeros(B, T)
for t in range(T):
positions = torch.full((B,), t, dtype=torch.long)
logits = policy(prev, positions)
log_probs[:, t] = (
torch.log_softmax(logits / sampling_temperature, dim=-1)
.gather(1, tokens[:, t : t + 1])
.squeeze(-1)
)
prev = tokens[:, t]
return log_probsThe two routines mirror each other token by token. Sampling uses torch.multinomial to draw a token and records ; scoring uses the same forward pass but looks up for a given token, building an autograd graph along the way. The @torch.no_grad() decorator on sample_group prevents backpropagation through the trajectory that generated the data; gradients flow only through the likelihood reassessment under the current policy.
The Reward and the Advantage
The reward function computes the fraction of matching tokens. The advantage function implements within-prompt normalization. Keeping the functions separate lets us change the advantage calculation in this toy while holding its reward fixed. Other recipes can change both. For example, DAPO also adjusts rewards for some long responses.
PythonIn [17]Expand
def compute_rewards(tokens, target):
"""Fraction of positions matching the target token sequence."""
matches = (tokens == target).float()
return matches.mean(dim=-1)
def group_advantages(rewards, eps=1e-4, use_std=True):
"""Center a nonempty group of finite rewards, with optional scaling."""
if (rewards == rewards[0]).all():
return torch.zeros_like(rewards)
centered = rewards - rewards.mean()
if use_std:
std = rewards.std(unbiased=False)
return centered / (std + eps)
return centeredThe use_std=True branch follows DeepSeekMath’s group standardization with two explicit implementation choices. It uses the population standard deviation and adds positive eps to the denominator. The published equation does not include the epsilon. Both branches return zeros if all stored rewards are equal, including a group of one response. Distinct rewards still use the usual centering and, when enabled, scaling. Setting use_std=False gives mean-only advantages. Dr. GRPO separately changes response-length weighting. For a nonconstant group of size , the sample standard deviation exceeds the population standard deviation by the factor .
The GRPO Loss
The code minimizes the negative clipped reward surrogate plus the coefficient-weighted penalty. This is the negative of the maximization objective above, where the penalty is subtracted.
PythonIn [18]Expand
def grpo_loss(
log_probs,
old_log_probs,
advantages,
ref_log_probs=None,
mask=None,
clip_eps=0.2,
kl_beta=0.01,
):
"""Compute the minimized loss for a nonempty group of responses."""
if log_probs.numel() == 0:
raise ValueError(
"The response group and its token dimension must be nonempty."
)
lengths = log_probs.size(1)
if mask is not None:
# Replace padded values before subtraction: -inf - -inf would be NaN.
mask = mask.to(dtype=torch.bool)
lengths = mask.sum(dim=-1)
if (lengths == 0).any():
raise ValueError(
"Each response must have at least one valid token."
)
log_probs = log_probs.masked_fill(~mask, 0.0)
old_log_probs = old_log_probs.masked_fill(~mask, 0.0)
log_ratio = log_probs - old_log_probs
ratio = torch.exp(log_ratio)
adv = advantages.unsqueeze(-1)
surr1 = ratio * adv
surr2 = torch.clamp(ratio, 1.0 - clip_eps, 1.0 + clip_eps) * adv
per_token = -torch.min(surr1, surr2)
if kl_beta != 0:
if ref_log_probs is None:
raise ValueError(
"A nonzero KL coefficient requires reference log-probabilities."
)
if mask is not None:
ref_log_probs = ref_log_probs.masked_fill(~mask, 0.0)
log_ratio_ref = ref_log_probs - log_probs
kl = torch.exp(log_ratio_ref) - log_ratio_ref - 1.0
per_token = per_token + kl_beta * kl
if mask is not None:
per_token = per_token.masked_fill(~mask, 0.0)
per_seq = per_token.sum(dim=-1) / lengths
return per_seq.mean()log_ratio is the current-minus-behavior log-probability, while ratio is . The vector adv broadcasts each response’s advantage to its token positions. surr1 is the unclipped operand and surr2 is the clipped operand. With a nonzero KL coefficient, log_ratio_ref is the reference-minus-current log-probability used in kl. At zero coefficient the helper skips reference arithmetic and accepts missing reference log-probabilities. If a mask is supplied, padding is replaced before ratio arithmetic and excluded from the numerator and token count. Every row represents a real response with at least one valid token. The helper rejects an all-padding row so it cannot dilute the average over responses. The toy uses four valid tokens in every row.
At with clipping inactive, the negative reward term contributes a derivative proportional to , with the same averaging as the loss. Its value can average to zero even when this derivative does not, because the token score gradients differ. The reference penalty contributes its own derivative when enabled; it vanishes if reference and current token probabilities coincide on the sampled prefixes.
Running the Training Loop
Each outer-loop iteration samples a new group from the learner’s current weights and records that group’s behavior log-probabilities. It immediately rescores the group with the same weights and temperature, so the likelihood ratios start at one, up to floating-point rounding, in every iteration. After the first optimizer step on that group, the second rescoring still uses the original behavior log-probabilities in the denominator. Those ratios can move away from one. The next outer iteration starts over with freshly recorded behavior probabilities. The evaluation also draws fresh responses from the updated policy on the same prompt.
PythonIn [19]Expand
torch.manual_seed(0)
policy = TinyPolicy()
ref_policy = TinyPolicy()
ref_policy.load_state_dict(policy.state_dict())
for p in ref_policy.parameters():
p.requires_grad = False
optimizer = torch.optim.Adam(policy.parameters(), lr=1e-2)
target = torch.tensor([1, 2, 3, 4])
group_size = 8
seq_len = 4
bos_id = 5
n_steps = 800
inner_epochs = 2
history = {
k: [] for k in ["step", "mean_reward", "group_std", "zero_var_frac", "loss"]
}
reward_snapshots = {}
reward_groups = []
eval_steps, eval_mean_rewards, eval_success = [], [], []
for step in range(n_steps):
tokens, old_log_probs = sample_group(policy, group_size, seq_len, bos_id)
rewards = compute_rewards(tokens, target)
adv = group_advantages(rewards, use_std=True)
with torch.no_grad():
ref_log_probs = score_sequence(ref_policy, tokens, bos_id)
group_std = rewards.std(unbiased=False).item()
zero_var = group_std < 1e-6
loss_val = 0.0
for _ in range(inner_epochs):
log_probs = score_sequence(policy, tokens, bos_id)
loss = grpo_loss(
log_probs,
old_log_probs,
adv,
ref_log_probs,
clip_eps=0.2,
kl_beta=0.01,
)
optimizer.zero_grad()
loss.backward()
optimizer.step()
loss_val = loss.item()
reward_groups.append(rewards.detach().clone())
history["step"].append(step)
history["mean_reward"].append(rewards.mean().item())
history["group_std"].append(group_std)
history["zero_var_frac"].append(float(zero_var))
history["loss"].append(loss_val)
if step in {0, n_steps // 2, n_steps - 1}:
reward_snapshots[step] = rewards.detach().clone()
if step % 50 == 0 or step == n_steps - 1:
eval_tokens, _ = sample_group(policy, 100, seq_len, bos_id)
eval_r = compute_rewards(eval_tokens, target)
eval_steps.append(step)
eval_mean_rewards.append(eval_r.mean().item())
eval_success.append((eval_r == 1.0).float().mean().item())ConsoleOut [20]Expand
Mean reward, first 50 steps: 0.926 Mean reward, final 50 steps: 0.998 Mean group std, final 50 steps: 0.005 Fraction of zero-variance groups: 0.900 Final exact-match rate on fresh draws: 1.000
The printed averages compare the first and last 50 rollout groups, and the exact-match rate comes from a fresh sample under the final policy. All draws use the same prompt, so this run checks training behavior without measuring generalization to new tasks.
What the Curves Show
The first figure plots the mean reward on the training batch against the fresh-sample evaluation.
VisualizationOut [21]Expand

Under a fixed policy and independent draws, averaging 100 rewards gives a more precise estimate than averaging eight. The two curves also use different policies. The evaluation at step zero follows both optimizer steps on the first group. It does not measure the untrained policy. A distribution drawing all five tokens uniformly would earn mean reward 0.2.
The second figure shows what happens to the group standard deviation over time.
VisualizationOut [22]Expand

Most late groups in this run have zero reward dispersion. They supply no reward-surrogate gradient, but the reference KL term or the optimizer’s prior state can still affect the parameter update. The line shows the actual groups, including occasional nonzero values late in training.
The histograms display advantages computed from the rewards actually recorded during training. At each checkpoint the code pools up to 40 preceding groups, including the checkpoint’s group. The first checkpoint has only one group.
PythonIn [23]Expand
# Pool recorded groups from each window ending at the selected checkpoint.
steps_sorted = sorted(reward_snapshots)
advantage_snapshot_by_step = {}
for step_key in steps_sorted:
start_step = max(0, step_key - 39)
groups = reward_groups[start_step : step_key + 1]
advantage_snapshot_by_step[step_key] = np.concatenate(
[group_advantages(group).numpy() for group in groups]
)VisualizationOut [24]Expand

The first group gives advantages ranging from about to . In this toy run the quarter-step rewards and groups of eight give a computed standard deviation of zero at exact ties. A single response can have zero advantage in a mixed group when its reward equals the group mean. Most groups in the final window receive tied rewards and contribute only zero advantages. A few still differ and provide a reward-surrogate signal. The histogram measures behavior on a specific toy prompt and seed. It cannot establish optimizer convergence or generalization.
Comments
Add to the conversation
A question, a correction, or an example from your own work.
No comments yet. Be the first to share your thoughts!