A model writes six answers to one prompt. A program checks each answer. Each answer is then pushed up or down by how it did against the other five. GRPO uses each batch of answers twice, so it needs fewer batches to learn.
A lesson with a workbook. Each chapter explains one part of Homework 4, then gives you exercises on our own toy data.
Press Train. Both learners start from the same tiny model and see new prompts each step. Switch the group view to watch one prompt's six answers get their rewards and advantages. Drag GRPO epochs to 1 and the two curves become one. Then we build each part.
You need the GRPO chapters of RL for Reasoning and the policy gradient. The exercises run JavaScript in your browser.
A supplement to UC Berkeley CS 185/285, Deep Reinforcement Learning, Sergey Levine. Based on Homework 4, Lecture 14 and Section 7. The words, toys and numbers are our own.
Our toy: a 12-token model copies a two-digit number into <a> </a> tags. Rewards +1, +0.2 and +0.1 follow the homework's format_copy scheme. 8 prompts and 6 answers per step, Adam at 0.15, KL weight 0.05, clip 0.2: our settings. Curves are illustrative.
Chapter 0
Follow one prompt through the loop and see which chapter builds each part
A base model gets a prompt: copy the number 47 inside answer tags. It writes six completions, the text it adds after the prompt. A program checks each one and returns a number, the reward. No person and no learned reward model take part. The reward is verifiable: code computes it from the text.
The homework builds the code between the rewards and the weight update. Two learners share all of it. GR-REINFORCE uses each batch of completions for one update. GRPO reuses the batch for two updates, with a clip. That one setting is the experiment.
Each box is one stage. The label under an arrow is the shape of the data that moves. Choose a stage to see what goes in, what comes out, and where it is taught.
Shapes for 8 prompts, 6 completions each and at most 24 new tokens, the homework's format_copy setting. N is prompts, G completions per prompt, T completion length.
| Part | Function in the starter code | The idea | Chapter |
|---|---|---|---|
| Token log-probs | compute_per_token_logprobs | row t − 1 scores token t | 2 |
| Completion mask | build_completion_mask | count only what the model wrote | 2 |
| KL estimate | approx_kl_from_logprobs | eΔ − Δ − 1 per sampled token | 3 |
| Group advantages | compute_group_advantages | reshape to [prompts, G], then normalise | 4 |
| GR-REINFORCE | Reinforce.update | one pass, one average per completion | 4 |
| Minibatches | iter_minibatches | slice every field with one index | 5 |
| GRPO | GRPO.update | two clipped passes over one batch | 5 |
Two tasks feed the loop. The first, format_copy, is a fast check: copy an integer into XML tags. The second, math_hard, asks hard competition maths and wants a final answer in a box. Our toys mirror both: the 12-token copy model in the hero, and two-digit addition in Chapter 6.
Reinforce.update first and leave every advantage at 0. The run starts with the policy equal to the reference. What does training do?Chapter 1
Choose how to frame the model as a policy, and see where a critic may learn
The prompt is "what is the capital of France?" The model writes "Paris", then an end token. What is the action here: the whole answer, or each token?
Both framings are correct. In the one-step framing, the state is the prompt, the action is the whole completion, and one reward arrives at the end. This is a contextual bandit: one choice per prompt, no later states. In the per-token framing, each token is an action and the state is the prompt plus the tokens so far.
Why are they the same policy? Call the prompt s and the completion tokens x1 to xT. The chance of the whole completion is a product of token chances.
Log pi-theta of a given s equals the sum over t of log pi-theta of x-t given s and x before t.
Read off the chance of each token x-t at the moment the model wrote it. Take the log of each and add them. The total is the log-chance of the completion a.
With made-up numbers: "Paris" has chance 0.6 and the end token 0.9. log 0.6 + log 0.9 = −0.511 − 0.105 = −0.616, which is log 0.54. One completion in about two is "Paris" then stop.
The framing decides the credit. With a final reward only, the one-step view gives every token of a completion the same advantage. The per-token view can give each token its own advantage, if a value head predicts the final reward at each prefix. Lecture 14 adds such a critic as a second head and trains it on the completion positions only.
Grey tokens are the prompt; blue tokens are the completion. Switch the framing. Then press Train the critic on the prompt to see a value head that also fits prompt positions.
Made-up values: the value head says 0.5 before "Paris" and 0.95 after it; the reward is 1 and the group mean is 0.5. Discount 1 and one-step TD errors, for clarity.
Worked on the device: the value head says 0.5 before "Paris" and 0.95 after it, and the reward is 1. The token "Paris" earns 0.95 − 0.5 = 0.45. The end token earns 1 − 0.95 = 0.05. In the one-step view with a group mean of 0.5, both tokens earn 1 − 0.5 = 0.5.
Chapter 2
Read each token's chance from the position before it, and count only the completion
Every loss in this homework needs log πθ of each completion token. The model gives one row of logits at every position: a score for each token of the vocabulary. The row at position t is a guess about the token at position t + 1.
So the chance of token t comes from row t − 1. Call the logits row at position t − 1 zt−1 and the token at position t xt.
Log pi-theta of x-t given x before t equals z at t minus one, indexed at x-t, minus the log of the sum over v of e to the z at t minus one, indexed at v.
Take the logits row from one position earlier. Pick its entry for the token x-t that came next. Subtract the log-sum-exp of that row. The result is the log-chance of x-t.
With made-up numbers: a 3-token vocabulary has row z = [2, 1, 0], and the next token is token 0. Then log(e2 + e1 + e0) = log 11.107 = 2.408. So log π = 2 − 2.408 = −0.408, a chance of 0.665.
A batch row also holds the prompt and padding. The completion mask is 1 on generated tokens and 0 on prompt and padding tokens. Every average over tokens uses it: the log-prob average, the KL and the clip fraction.
The bottom row is the sequence: prompt, completion, padding. Each arrow joins a logits row to the token it scores; the number is that token's chance. Turn the shift or the mask off and watch the sum.
Our toy sequence and made-up chances. "copy" is a prompt token we add for the picture; the real format_copy prompt is longer.
Worked on the device: the four completion tokens have chances 0.5, 0.6, 0.7 and 0.8. The sum of their logs is log 0.168 = −1.784. The average per token is −0.446. In PyTorch, compare logits[:, :-1] with tokens[:, 1:], then gather.
lp[t][v] is the log-chance that row t gives token v for position t + 1. tokens is the whole sequence; padding is −1.promptLen to the end.tokens[t] is −1, skip it.lp[t - 1][tokens[t]]. Return the sum.numpy, the same idearows = lp[:-1] # row t-1 ... nxt = tokens[1:] # ... scores token t mask = (np.arange(1, len(tokens)) >= prompt_len) & (nxt >= 0) return rows[np.arange(len(nxt)), np.maximum(nxt, 0)][mask].sum()
javascriptfunction completionLogprob(lp, tokens, promptLen) {
let s = 0;
for (let t = promptLen; t < tokens.length; t++) {
if (tokens[t] === -1) continue;
s += lp[t - 1][tokens[t]];
}
return s;
}
n. The prompt has p tokens and pad padding tokens sit at the end. The average log-prob comes out far too negative. Click the buggy line.def completion_mask(n, p, pad): mask = np.zeros(n) mask[:n - pad] = 1.0 return mask
mask[p:n - pad] = 1.0.Chapter 3
Estimate the distance to the reference from one sampled token, and never get a negative value
Both learners pull the model toward a frozen copy of itself, the reference πref. Without that pull, a model chasing a reward drifts into text that scores well and reads as nonsense. The penalty is the KL divergence KL(πθ ‖ πref): how surprised the reference is, on average, by what the policy writes.
The exact KL at one position sums over the whole vocabulary, for both models. With a made-up vocabulary of 50,000 tokens, 64 completions of 512 tokens need 64 × 512 × 50,000 = 1.6 billion numbers per model. The sampled estimate needs one number per token: 32,768.
At one position, call the sampled token a. Call the log-ratio Δ = log πref(a) − log πθ(a). The plain estimate −Δ is correct on average. But one sample of it is negative whenever the policy gives the token less chance than the reference. The homework uses this one instead.
K-hat of a equals e to the delta, minus delta, minus one.
Take the ratio e-to-the-delta of the reference's chance to the policy's chance. Subtract delta, its log, and subtract 1. A ratio of 1 gives 0. Any other ratio gives a positive number.
With made-up numbers: πθ(a) = 0.2 and πref(a) = 0.4, so Δ = log 2 = 0.693. The plain estimate is −0.693, a negative distance. k̂ = 2 − 0.693 − 1 = 0.307.
Why is it still correct on average? Draw a from the policy. The average of eΔ is the sum of πθ(a) × πref(a) / πθ(a), which is the sum of πref, which is 1.
The expected k-hat equals the expected e to the delta, minus the expected delta, minus one, which equals the KL of pi-theta from pi-ref.
Average the three parts of k-hat separately. E-to-the-delta averages to 1 and cancels the minus 1. What is left is minus the average delta, which is the KL.
With made-up numbers: two tokens, πθ = (0.8, 0.2) and πref = (0.5, 0.5). k̂ is 0.095 on token 1 and 0.584 on token 2. The average is 0.8 × 0.095 + 0.2 × 0.584 = 0.193, equal to the exact KL.
Top: the policy (blue) and the reference (teal) over 4 tokens. Bottom: one dot per sampled token for each estimate. The tall tick is the exact KL and the orange arrow is the mean. Drag the drift, then sample.
Illustrative distributions we chose. The reference is (0.4, 0.3, 0.2, 0.1); drift moves the policy toward (0.1, 0.2, 0.3, 0.4).
p is the policy, q the reference, both over a small vocabulary. samples lists token ids drawn from p.numpy, the same idead = np.log(q[samples]) - np.log(p[samples]) return (np.exp(d) - d - 1).mean()
javascriptfunction k3Mean(samples, p, q) {
let s = 0;
for (const a of samples) {
const d = Math.log(q[a]) - Math.log(p[a]);
s += Math.exp(d) - d - 1;
}
return s / samples.length;
}
Chapter 4
Score each completion against its group, then weigh it once, whatever its length
RL for Reasoning derives the group advantage: subtract the group's mean reward, divide by its spread. The homework fixes three details. The spread is the population standard deviation, which divides by G. A small ε sits under the division, so a group with equal rewards gives 0, not an error. And you reshape the flat reward list to [prompts, G] before the mean.
The rewards arrive prompt by prompt: all G completions of prompt 0, then prompt 1. Take 2 prompts and G = 3 with rewards 1, 0, 0, 1, 1, 1. Reshaped to [2, 3], the groups are (1, 0, 0) and (1, 1, 1). The advantages are 1.41, −0.71, −0.71, then 0, 0, 0. Reshape to [3, 2] by mistake and the first group is (1, 0): two different prompts, compared as if they were one.
Now the length. Call completion i's advantage Ai and its length Ti tokens. GR-REINFORCE averages the token log-probs inside each completion before it multiplies by Ai.
L-pg equals minus one over N times the sum over i of A-i, times one over T-i times the sum over t of log pi-theta of y-i-t given x-i and the earlier tokens.
For each completion i, average its token log-probs over its T-i tokens. Multiply by its advantage A-i. Average over the batch and flip the sign, so that lowering L-pg raises good completions.
With made-up numbers: completion 1 has A = +1 and 4 tokens; completion 2 has A = −1 and 16 tokens. With a plain sum over tokens, completion 2 gets 16 token terms against 4: 80% of the push. With the average, each gets 50%.
Each row is one completion: its tokens as cells, its reward and its advantage. The bar on the right is its share of the update. Switch how the update combines tokens.
Our toy group: rewards 1.1, 0.1, 1.1, 0 and lengths 4, 9, 6, 24 tokens. Population standard deviation, ε = 10−6.
A long wrong answer, 24 tokens of rambling, takes 59% of the push under the sum and 27% under the average. The per-completion average has its own bias: a long wrong answer gets a smaller push on each token. Dr. GRPO (2025) studies this.
numpy, the same idear = rewards.reshape(-1, G) # [prompts, G] return (r - r.mean(axis=1, keepdims=True)).ravel()
javascriptfunction meanBaseline(rewards, G) {
const out = [];
for (let i = 0; i < rewards.length; i += G) {
const g = rewards.slice(i, i + G);
const m = g.reduce((a, b) => a + b, 0) / G;
for (const r of g) out.push(r - m);
}
return out;
}
r holds n_prompts × G rewards, prompt by prompt. The advantages of one prompt do not add to 0. Click the buggy line.def group_norm(r, n_prompts, G, eps=1e-6): m = r.reshape(G, n_prompts) mu = m.mean(axis=1, keepdims=True) sd = m.std(axis=1, keepdims=True) return ((m - mu) / (sd + eps)).ravel()
r.reshape(n_prompts, G).Chapter 5
Count the optimizer steps each rollout buys, and clip the steps that reuse old samples
Sampling is the slow part. The model writes each completion token by token, up to 512 tokens on math_hard. Lecture 14 asks: once you have paid for a batch, why use it for one step only?
GR-REINFORCE takes one optimizer step per batch. It is strictly on-policy: every sample comes from the current weights. GRPO runs the batch through E epochs. Each epoch splits the batch into minibatches of M completions. Gradient accumulation sums the gradients of K minibatches before each step. Call the prompts N and the completions per prompt G.
U equals E times N times G over M, all over K.
Count the completions, N times G. Cut them into minibatches of M. Take one step every K minibatches. Do that E times.
The homework's math commands: N = 8, G = 8, M = 8, K = 8. That is 64 completions in 8 minibatches, so one step per epoch. GR-REINFORCE (E = 1) takes U = 1; GRPO (E = 2) takes U = 2.
Each cell is one completion, coloured by its minibatch. Below, each epoch is a lane and each tick is an optimizer step. Ticks after the first step reuse samples from older weights.
N is fixed at 8 prompts. "K = all" sums every minibatch of an epoch, as the homework's commands do. A partial last group of minibatches still gets a step.
Reuse has a price. In the second epoch the weights have moved, so the samples are from an older policy πold. Each token gets a ratio ρ = πθ / πold, and the PPO clip limits how far it may push. The homework averages the clipped term over each completion's tokens, then over the batch.
L equals minus one over N times the sum over i, of one over T-i times the sum over t, of the min of rho-i-t A-i and clip of rho-i-t between one minus epsilon and one plus epsilon, times A-i.
For each token, multiply its ratio rho by the completion's advantage A. If rho has already moved past 1 ± epsilon in the helpful direction, use the clipped value instead. Average over the tokens, then over completions, and flip the sign.
With made-up numbers: three tokens with ratios 1.30, 0.95, 1.05 and A = +1. The terms are 1.2 (clipped), 0.95 and 1.05. Their mean is 1.067, so L = −1.067. The clip catches one token in three.
In the first epoch the weights have not moved yet, so every ρ is exactly 1. The clip is inactive and the gradient equals GR-REINFORCE's. GRPO with E = 1 is GR-REINFORCE. Try it in the hero: set GRPO epochs to 1.
numpy, the same ideac = np.clip(ratios, 1 - eps, 1 + eps) return np.minimum(ratios * A, c * A).mean()
javascriptfunction clippedSeqObjective(ratios, A, eps) {
let s = 0;
for (const r of ratios) {
const c = Math.min(Math.max(r, 1 - eps), 1 + eps);
s += Math.min(r * A, c * A);
}
return s / ratios.length;
}
Chapter 6
Shape the reward so learning can start, then check the parser the policy will exploit
On math_hard the base model is right about one time in four, and on format_copy it almost never writes the tags at first. A group where every completion scores 0 has zero advantages and teaches nothing (Chapter 4). So both tasks add small shaping terms: rewards for steps toward the right form.
Our addition toy uses the homework's math scheme. The prompt is "What is 47 + 38?" and the right answer is 85. The reward adds three checks, each 1 or 0:
r equals one times c-box, plus zero point one times c-tag, plus zero point one times c-last times one minus c-box.
Give 1 for a right boxed answer. Add 0.1 for writing a box at all. Add 0.1 for a right last number, but only when the box missed.
"The answer is 85 \boxed{" has no closed box, so c-box = 0. It has the tag, so c-tag = 1. Its last number is 85, so c-last = 1. r = 0 + 0.1 + 0.1 = 0.2, more than a wrong boxed answer earns.
Seven completions to "What is 47 + 38?". Bars are rewards; the ring marks the best-paid completion, which a policy learns to write. Switch the reward function.
Our toy completions and parsers. The first scheme copies the weights of the homework's math_hard reward.
Reward hacking is a policy that raises the reward without doing the task. With a buggy parser, "\boxed{185}" earns as much as "\boxed{85}", so nothing pushes the model toward the right sum. Two rules keep shaping safe. First, the right answer earns every shaping term too. Second, the shaping terms add to less than the main reward: here 0.2 against 1.
def reward(text, target): r = 0.0 if str(target) in text: r += 1.0 if "\\boxed{" in text: r += 0.1 return r
Chapter 7
Keep the terms and numbers at hand, tick what you can build, and pick the next experiment
Sample a group and score it with code. Normalise within the group and average each completion's token log-probs. Add the sampled KL. Then choose how many times to reuse the batch.
| Term | Meaning | Value |
|---|---|---|
| G | completions per prompt | 6 on format_copy, 8 on math_hard |
| advantage | (r − group mean) / (population std + ε) | adds to 0 in each group |
| k̂ | eΔ − Δ − 1, Δ = log πref − log πθ | weight β = 0.05 |
| ρ, clip | new over old token chance; its band | ε = 0.2 |
| U | optimizer steps per rollout, E(NG/M)/K | 1 for GR-REINFORCE, 2 for GRPO |
| format_copy reward | integer right, has <answer>, strict XML | +1, +0.2, +0.1; most 1.3 |
| math_hard reward | boxed right, has "\boxed{", last number right | +1, +0.1, +0.1; most 1.1 |
| course result | math_hard held-out exact match | the course reports about 0.23 before RL, about 0.31 after 201 GR-REINFORCE steps, above 0.37 after 501 GRPO steps |
pseudocodefor it in range(steps): prompts = sample(N) comps = policy.generate(prompts, G) # N*G completions r = reward_fn(comps) # Chapter 6 A = group_normalise(r.reshape(N, G)) # Chapter 4 lp_old = token_logprobs(policy, comps) * mask # Chapter 2, cached lp_ref = token_logprobs(reference, comps) for epoch in range(E): # E = 1: GR-REINFORCE for mb in minibatches(comps, M): # Chapter 5 lp = token_logprobs(policy, mb) loss = clipped_term(lp - lp_old, A) + beta * k_hat(lp_ref - lp) # Ch 3, 5 accumulate(loss); step_every(K)
Teach it back with Teach, or go back to the hero and train again with 1 epoch, then 4. This page supplements UC Berkeley CS 185/285, Deep Reinforcement Learning, Sergey Levine, at rail.eecs.berkeley.edu/deeprlcourse. It draws on Homework 4 (pages 2 to 13), Lecture 14 (pages 13 to 39) and Section 7 (pages 2 to 4). The handout, slides and starter code belong to the course; the words, toys and numbers here are our own.