CS 285 HW4: RL for Language Models

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.

Train two learners on the same task

2

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.

Workbook progress
0 / 30 exercises (0%)
0
Day streak
Best: 0
30 exercises in five kinds: Derive, Trace, Build, Debug, Design. Build exercises run as JavaScript in your browser, with the matching Python shown beside them.

Chapter 0

The Map: What You Build

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.

Follow one rollout through the loop

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.

PartFunction in the starter codeThe ideaChapter
Token log-probscompute_per_token_logprobsrow t − 1 scores token t2
Completion maskbuild_completion_maskcount only what the model wrote2
KL estimateapprox_kl_from_logprobseΔ − Δ − 1 per sampled token3
Group advantagescompute_group_advantagesreshape to [prompts, G], then normalise4
GR-REINFORCEReinforce.updateone pass, one average per completion4
Minibatchesiter_minibatchesslice every field with one index5
GRPOGRPO.updatetwo clipped passes over one batch5

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.

The road

  1. One answer or many tokens: two ways to frame the model as a policy.
  2. Token log-probs and the mask: the shift by one, and what to count.
  3. The KL estimate: eΔ − Δ − 1, never negative.
  4. Group advantages and the average: the hero's purple bars.
  5. Use a batch once or twice: the hero's GRPO epochs.
  6. Rewards you can check: the hero's warm reward numbers, and hacks.
  7. Field guide: terms, checklist, the core loop.
The homework compares GR-REINFORCE and GRPO with the same batch size, learning rate and KL weight. What is the one setting that differs?

Workbook

Exercise 0.1: Count the token positions Derive
One rollout has 8 prompts and 6 completions per prompt. Each completion has at most 24 new tokens. At most how many completion tokens does one rollout score?
tokens
Show derivation
completions = 8 × 6 = 48
token positions = 48 × 24 = 1,152
Every per-token tensor in the loss has this many entries, before the mask removes the padding of short completions.
Exercise 0.2: Order one iteration Design
Tap the chips in the order one training iteration runs them.
?
→
?
→
?
→
?
→
?
group advantages loss and optimizer step sample G completions per prompt log-probs, mask and KL score each completion
Exercise 0.3: Advantages left at zero Trace
You write 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

One Answer or Many Tokens

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 πθ(a | s) = Σt log πθ(xt | s, x<t)
Say it aloud

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.

log πθ(a | s)
log pi-theta of a given s the log-chance that the model with weights theta writes the whole completion a after prompt s.
Σt
the sum over t one term per completion token, from 1 to T.
log πθ(xt | s, x<t)
log pi-theta of x-t given s and x before t the log-chance of token t, given the prompt and the tokens already written.
In plain words

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 numbers

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.

Switch the framing, watch the credit

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.

The trap: a critic that fits the prompt

symptom
The value loss falls nicely, yet the policy does not improve faster than with the group mean.
see it
Count the positions in the value loss. With 512-token prompts and short answers, most terms are prompt positions, where the model never acts.
fix
Multiply the value loss by the completion mask, as the policy loss does.
Your reward is a checker that reads only the final answer, and you have no critic. Which framing fits, and what is each token's advantage?

Workbook

Exercise 1.1: The log-chance of a completion Derive
A completion has three tokens with chances 0.5, 0.8 and 0.25. What is log π(a | s), with the natural log? Give 3 decimals.
nats
Show derivation
product = 0.5 × 0.8 × 0.25 = 0.1
log 0.1 = −0.693 − 0.223 − 1.386 = −2.303
Adding logs gives the same number as the log of the product, and it does not underflow on long completions.
Exercise 1.2: Credit from a value head Derive
A three-token completion gets reward 1 at the end. The value head says 0.2 before token 1, 0.2 after token 1, 0.9 after token 2. With discount 1, what is the one-step TD error of token 2?
advantage
Show derivation
δt = rt + V(after t) − V(before t)
token 1: 0 + 0.2 − 0.2 = 0
token 2: 0 + 0.9 − 0.2 = 0.7
token 3: 1 − 0.9 = 0.1
Token 2 gets most of the credit: it is where the head saw the answer become likely. The one-step view would give all three the same number.
Exercise 1.3: Which framing for which reward Trace
A process reward model scores each step of a worked solution as right or wrong. Which framing uses that signal?
Exercise 1.4: Why not train the critic on the prompt Trace
Why does Lecture 14 train the value head on the completion only?

Chapter 2

Token Log-Probs and the Completion Mask

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 πθ(xt | x<t) = zt−1[xt] − log Σv ezt−1[v]
Say it aloud

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.

log πθ(xt | x<t)
log pi-theta of x-t given x before t the log-chance of the token at position t, given all tokens before it.
zt−1[xt]
z at t minus one, at x-t the logit that the row one position earlier gives to the token that came next.
log Σv ez
the log of the sum over v of e to the z the normaliser. It turns logits into chances that add to 1; v runs over the vocabulary.
In plain words

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 numbers

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.

Line up the rows and the tokens

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.

The trap: no shift

symptom
Reward stays flat. Generations start to repeat a token: "4 4 7 7".
see it
Print the chance of an easy token, such as the closing tag after the digits. With the shift it is near 1. Without it, it is near 0.
fix
Score token t with row t − 1. Without the shift, the loss rewards each row for predicting its own input, so the model learns to repeat.
A sequence has 3 prompt tokens, then 4 completion tokens at positions 3 to 6. Which logits rows score the completion?

Workbook

Exercise 2.1: One log-softmax Derive
A 3-token vocabulary. The row before the token reads z = [0, 3, 1], and the next token is token 2. What is its log-chance? Give 3 decimals.
nats
Show derivation
e0 + e3 + e1 = 1 + 20.086 + 2.718 = 23.804
log 23.804 = 3.170
log π = z[2] − 3.170 = 1 − 3.170 = −2.170
A chance of 0.114. Subtract the row maximum before the exponent in code; the answer does not change and nothing overflows.
Exercise 2.2: The log-chance of a completion from a table Build
A neighbouring version on plain arrays. 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.
  1. Loop over positions t from promptLen to the end.
  2. If tokens[t] is −1, skip it.
  3. Otherwise add 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()
Show solution
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;
}
Exercise 2.3: The mask that counts the prompt Debug
A neighbouring helper builds a 0/1 mask for one sequence of length 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
Show why
Line 3 starts at 0, so it marks the prompt as completion. The model gets credit or blame for prompt tokens it never chose, which are often unlikely. Use mask[p:n - pad] = 1.0.
Exercise 2.4: What the missing shift teaches Trace
Your code scores token t with row t, not row t − 1. Advantages and the rest are right. What does training push the model toward?

Chapter 3

The KL Estimate: eΔ − Δ − 1

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̂(a) = eΔ − Δ − 1
Say it aloud

K-hat of a equals e to the delta, minus delta, minus one.

k̂(a)
k-hat of a the KL estimate from one sampled token a. Always 0 or more.
eΔ
e to the delta the ratio πref(a) / πθ(a). Its average over tokens drawn from the policy is exactly 1.
Δ
delta log πref(a) minus log πθ(a): reference minus policy, in that order.
1
one the average of e to the delta, subtracted so that the estimate is 0 when the two models agree.
In plain words

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 numbers

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.

E[k̂] = E[eΔ] − E[Δ] − 1 = KL(πθ ‖ πref)
Say it aloud

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.

E[k̂]
the expected k-hat the average of the estimate over many tokens drawn from the policy.
E[eΔ]
the expected e to the delta exactly 1, by the sum above. It cancels the minus 1.
E[Δ]
the expected delta the average of log πref minus log πθ. Minus this is the KL.
KL(πθ ‖ πref)
the KL of pi-theta from pi-ref the average of log πθ minus log πref, with tokens drawn from the policy.
In plain words

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 numbers

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.

Sample tokens, compare the estimates

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.

0.50

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).

The trap: delta the wrong way round

symptom
The KL plot looks smooth and is never negative, so nothing looks wrong. But it does not estimate KL(πθ ‖ πref).
see it
Test on the two-token toy. With Δ flipped, the average is 1.36 − 0.193 − 1 = 0.167, not 0.193.
fix
Δ is reference minus policy. Only then does eΔ average to 1 under the policy's samples.
The policy gives a sampled token 0.5 and the reference gives it 0.25. What is k̂ for that token?

Workbook

Exercise 3.1: The exact KL Derive
πθ = (0.7, 0.3) and πref = (0.4, 0.6). Compute KL(πθ ‖ πref) with the natural log. Give 3 decimals.
nats
Show derivation
token 1: 0.7 × log(0.7 / 0.4) = 0.7 × 0.5596 = 0.3917
token 2: 0.3 × log(0.3 / 0.6) = 0.3 × (−0.6931) = −0.2079
KL = 0.3917 − 0.2079 = 0.184
One term is negative, the total is not. That is the gap a single sample of −Δ falls into.
Exercise 3.2: k-hat on the same pair Derive
Same pair as 3.1. Compute the average of k̂ over tokens drawn from πθ. Give 3 decimals.
nats
Show derivation
token 1: x = 0.4 / 0.7 = 0.5714; k̂ = 0.5714 − log 0.5714 − 1 = 0.5714 + 0.5596 − 1 = 0.1310
token 2: x = 0.6 / 0.3 = 2; k̂ = 2 − 0.6931 − 1 = 0.3069
average = 0.7 × 0.1310 + 0.3 × 0.3069 = 0.0917 + 0.0921 = 0.184
Both samples are positive and the average equals the exact KL from 3.1.
Exercise 3.3: A negative penalty Trace
You use −Δ as the per-token penalty. On a token where the policy's chance is below the reference's, what does the penalty do to the update?
Exercise 3.4: Average k-hat from samples Build
A neighbouring version with full distributions. p is the policy, q the reference, both over a small vocabulary. samples lists token ids drawn from p.
  1. For each sampled id a, set d = log q[a] − log p[a].
  2. Add ed − d − 1.
  3. Return the mean over the samples.
numpy, the same idead = np.log(q[samples]) - np.log(p[samples])
return (np.exp(d) - d - 1).mean()
Show solution
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

Group Advantages and the Per-Completion Average

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.

Lpg = −(1/N) Σi Ai · (1/Ti) Σt log πθ(yi,t | xi, yi,<t)
Say it aloud

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.

Lpg
L-pg the policy-gradient loss of GR-REINFORCE. The optimizer lowers it.
(1/N) Σi
one over N times the sum over i the average over the N completions in the batch.
Ai
A-i completion i's group advantage: positive if it beat its group.
(1/Ti) Σt
one over T-i times the sum over t the average over completion i's own T-i tokens, masked.
log πθ(yi,t | …)
log pi-theta of y-i-t the log-chance of token t of completion i, given the prompt x-i and its earlier tokens.
In plain words

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 numbers

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%.

Weigh by tokens or by completion

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.

The trap: the wrong reshape

symptom
Training is slow and noisy. Advantages do not add to 0 within a prompt.
see it
Sum the advantages of each prompt's G completions. Each sum is 0 when the groups are right.
fix
Reshape to [num_groups, group_size], prompt first, the order the sampler used.
Why does GR-REINFORCE divide each completion's log-prob sum by its length Ti?

Workbook

Exercise 4.1: Share of the push Derive
Two completions: A = +1 with 5 tokens, and A = −1 with 15 tokens. With a plain sum over tokens, what share of the total push goes to the long one? Give a fraction between 0 and 1.
share
Show derivation
sum: |A| × T = 1 × 5 = 5 and 1 × 15 = 15
share = 15 / (5 + 15) = 0.75
With the per-completion average each term is |A| × 1, so the share is 0.5.
Exercise 4.2: The lecture's mean baseline Build
A neighbouring version: Lecture 14 and Section 7 write GRPO's advantage as the reward minus the group mean, with no division. The flat list holds G rewards for prompt 0, then G for prompt 1, and so on.
  1. Walk the list in blocks of G.
  2. For each block, compute its mean.
  3. Return each reward minus its own block's mean, in the original order.
numpy, the same idear = rewards.reshape(-1, G)            # [prompts, G]
return (r - r.mean(axis=1, keepdims=True)).ravel()
Show solution
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;
}
Exercise 4.3: Groups that mix prompts Debug
A neighbouring helper. 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()
Show why
Line 2 reshapes to [G, n_prompts], so each row mixes completions of different prompts. With rewards 1, 0, 0, 1, 1, 1 and G = 3 the rows become (1, 0), (0, 1), (1, 1). Use r.reshape(n_prompts, G).
Exercise 4.4: One small reward in a group of zeros Derive
A group of 6 has rewards 0.2, 0, 0, 0, 0, 0. With the population standard deviation and ε near 0, what is the first completion's advantage? Give 3 decimals.
advantage
Show derivation
mean μ = 0.2 / 6 = 0.0333
variance = (0.1667² + 5 × 0.0333²) / 6 = (0.02778 + 0.00556) / 6 = 0.005556
σ = 0.0745
A1 = (0.2 − 0.0333) / 0.0745 = 2.236; the others are −0.447
The +0.2 for an answer tag gets the full-size push of a right answer. That is why a small shaping term starts learning on a task where every group scores 0.

Chapter 5

GR-REINFORCE vs GRPO: Use a Batch Once or Twice

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 = E × (N · G / M) / K
Say it aloud

U equals E times N times G over M, all over K.

U
U optimizer steps taken per rollout batch.
E
E the number of epochs, passes over the batch. 1 for GR-REINFORCE, 2 for GRPO here.
N · G / M
N times G over M minibatches per epoch: N prompts times G completions, cut into minibatches of M.
K
K gradient accumulation steps: minibatches summed before one step.
In plain words

Count the completions, N times G. Cut them into minibatches of M. Take one step every K minibatches. Do that E times.

With numbers

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.

Count the steps one rollout buys

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.

8
2

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 = −(1/N) Σi (1/Ti) Σt min(ρi,t Ai, clip(ρi,t, 1−ε, 1+ε) Ai)
Say it aloud

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.

L
L GRPO's policy loss for one minibatch of N completions.
(1/N) Σi
one over N times the sum over i the average over completions.
(1/Ti) Σt
one over T-i times the sum over t the average over completion i's masked tokens, as in Chapter 4.
min(ρA, clip(ρ)A)
the min of rho A and clipped rho A ρi,t is the token's new chance over its chance when sampled. The clip holds it within 1 ± ε, with ε = 0.2. The min keeps the more cautious term.
In plain words

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 numbers

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.

The trap: minibatch fields sliced apart

symptom
Reward stays flat, and the generations panel shows good answers with negative advantages.
see it
Inside one minibatch, print each completion's text next to its advantage and its cached old log-prob. They must belong together.
fix
Draw one index array per minibatch and use it to slice every field of the batch, including the debug lists.
In GRPO's first epoch over a fresh batch, what is every token's ratio ρ?

Workbook

Exercise 5.1: Steps with no accumulation Derive
GRPO with N = 8 prompts, G = 8, minibatches of M = 8, E = 2 epochs, and K = 1. How many optimizer steps does one rollout buy?
steps
Show derivation
completions = 8 × 8 = 64; minibatches = 64 / 8 = 8
U = 2 × 8 / 1 = 16
Only the first of the 16 steps is on-policy. The other 15 see ratios that drift from 1, so the clip fraction rises.
Exercise 5.2: The clipped term for one completion Build
A neighbouring version for one completion: its token ratios, its advantage and ε.
  1. For each ratio r, clip it to the range from 1 − eps to 1 + eps.
  2. Take the smaller of r × A and clipped r × A.
  3. Return the mean over the tokens. This is the objective; the loss is its negative.
numpy, the same ideac = np.clip(ratios, 1 - eps, 1 + eps)
return np.minimum(ratios * A, c * A).mean()
Show solution
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;
}
Exercise 5.3: The clip on a bad answer Trace
A completion has A = −1, ε = 0.2, and one token's ratio is 1.3. Which term does the min keep, and does that token still get a gradient?
Exercise 5.4: Order one GRPO iteration Design
Tap the chips in the order GRPO runs them for one batch.
?
→
?
→
?
→
?
→
?
per minibatch: clipped loss + β KL cache the old log-probs sample and score the batch step after K minibatches; repeat for E epochs group advantages

Chapter 6

Rewards You Can Check, and How They Get Hacked

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 = 1.0 · cbox + 0.1 · ctag + 0.1 · clast (1 − cbox)
Say it aloud

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.

r
r the reward of one completion, from 0 to 1.1.
cbox
c-box 1 if the number inside \boxed{…} is the right answer, else 0. The main reward.
ctag
c-tag 1 if the text contains the string "\boxed{". A format hint.
clast(1 − cbox)
c-last times one minus c-box 1 only if the last number is right but the box is not.
In plain words

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.

With numbers

"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.

Pay the completions, find the hack

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.

The trap: a parser that matches a substring

symptom
Training reward climbs past 1, but held-out accuracy with a strict parser stays flat.
see it
Read ten top-reward generations. Look for wrong answers that contain the right digits, or lists of many numbers.
fix
Parse the boxed answer and compare it as a number. Track an eval metric that uses the strict parser.
Under the homework's scheme, what does "47 + 38 = 85" earn, with no box?

Workbook

Exercise 6.1: Pay a near miss Derive
Under the homework's scheme, what does "\boxed{75}, no wait, 85" earn for "What is 47 + 38?"
reward
Show derivation
cbox: the box holds 75, wrong, so 0
ctag: "\boxed{" is present, so 0.1
clast: the last number is 85 and the box missed, so 0.1
r = 0 + 0.1 + 0.1 = 0.2
Exercise 6.2: The parser that pays 185 Debug
A neighbouring reward for the addition toy. "\boxed{185}" gets the full point for target 85. Click the buggy line.
def reward(text, target):
    r = 0.0
    if str(target) in text:
        r += 1.0
    if "\\boxed{" in text:
        r += 0.1
    return r
Show why
Line 3 tests for the characters "85" anywhere, so "185", "850" and a list of numbers all pass. Extract the boxed content and compare it as a number with the target.
Exercise 6.3: The reward of a mixed policy Derive
A policy writes a right boxed answer 30% of the time, "The answer is 85 \boxed{" 50% of the time, and a wrong boxed answer 20% of the time. What is its average reward under the homework's scheme?
reward
Show derivation
right boxed: 1.1; near miss: 0.2; wrong boxed: 0.1
0.3 × 1.1 + 0.5 × 0.2 + 0.2 × 0.1 = 0.33 + 0.10 + 0.02 = 0.45
Moving the 50% to right answers adds 0.45. Moving it to the near miss adds nothing, so the shaping does not pay the hack.
Exercise 6.4: A safe shaping term Trace
You want a shaping term that helps exploration on the addition task. Which one is safe?

Chapter 7

Field Guide: Where Next

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.

TermMeaningValue
Gcompletions per prompt6 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
ρ, clipnew over old token chance; its bandε = 0.2
Uoptimizer steps per rollout, E(NG/M)/K1 for GR-REINFORCE, 2 for GRPO
format_copy rewardinteger right, has <answer>, strict XML+1, +0.2, +0.1; most 1.3
math_hard rewardboxed right, has "\boxed{", last number right+1, +0.1, +0.1; most 1.1
course resultmath_hard held-out exact matchthe course reports about 0.23 before RL, about 0.31 after 201 GR-REINFORCE steps, above 0.37 after 501 GRPO steps

What you can now build

The core loop

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)

Experiments worth running next

Keep going

One switch separates the two learners. Everything else is shared: the group advantage, the per-completion average, the KL estimate and the reward. GRPO buys more steps per batch, and the clip makes those steps safe.

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.

Workbook

Exercise 7.1: Steps over a whole run Derive
A format_copy GRPO run has 51 iterations, N = 8, G = 6, M = 8, K = 6 and E = 2. How many optimizer steps does it take in total?
steps
Show derivation
minibatches per epoch = 8 × 6 / 8 = 6
U = 2 × 6 / 6 = 2 per rollout
total = 51 × 2 = 102
GR-REINFORCE with the same settings takes 51.
Exercise 7.2: Read an unstable run Trace
You raise GRPO's epochs from 2 to 6. The KL to the reference climbs fast, the clip fraction is high, and reward falls after a peak. What is going on?
Exercise 7.3: Which curve compares the learners Trace
The rollout reward jumps up and down from one iteration to the next. Which curve do you use to compare GR-REINFORCE and GRPO?
CS 285 HW4: RL for Language Models (UC Berkeley)
The course site · Homework 4 PDF · Lecture 14 PDF · Back to Gleams