Build per-token RLHF rewards with a KL penalty
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.
def 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.