Build per-token RLHF rewards with a KL penalty

MediumAlignmentPro

In PPO-based RLHF the reward model gives one score per response, but PPO needs a reward per token. A common recipe: every response token gets a KL penalty -beta * (logp - ref_logp) that keeps the policy close to the reference model, and the reward model score is added on the last response token only.

Write shaped_rewards(logp, ref_logp, mask, scores, beta). logp, ref_logp and mask have shape (B, T); mask is 1 for response tokens and 0 for prompt or padding. scores has length B.
- rewards = -beta * (logp - ref_logp) * mask
- add scores[b] at the LAST index t where mask[b, t] == 1. If a row has no response tokens, add nothing.
- kl[b] = sum((logp - ref_logp) * mask) / max(number of response tokens, 1)
Return (rewards, kl) as a (B, T) array and a length-B array.

Signaturedef shaped_rewards(logp, ref_logp, mask, scores, beta)

Understand the idea

In PPO-style RLHF the reward model gives one score per full response, but PPO wants a reward at every token. The usual recipe gives every response token a small KL penalty, -beta * (logp - ref_logp), which keeps the policy from drifting too far from the reference model, and adds the reward model score only on the last response token. Worked example: one row, T = 4, mask [0, 1, 1, 0], logp - ref_logp at the response tokens = [0.2, -0.1], beta = 0.1, score 2. Rewards: position 1 gets -0.02, position 2 gets +0.01 + 2 = 2.01, positions 0 and 3 get 0. So rewards = [0, -0.02, 2.01, 0]. KL for the row = (0.2 - 0.1) / 2 = 0.05. Rule: rewards = -beta * (logp - ref_logp) * mask; add scores[b] at the last t where mask is 1, skipping rows with no response tokens; kl[b] = sum of masked differences / max(count, 1). Putting the score at column T - 1 puts it on padding for most rows. This shaping is used in classic RLHF pipelines for chat models.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: padded batchshaped_rewards(_lp, _rf, _m, [1.0, -0.5, 2.0], 0.1)
  • Sample 2: empty response rowshaped_rewards(_lp[:2], _rf[:2], np.array([[0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 1, 1.0]]), [5.0, 1.0], 0.05)