RLHF Reward Shaping
Implement reward shaping for RLHF with KL penalty.
The shaped reward at each token position t is:
where kl_t = log(π_θ(token_t|context)) - log(π_ref(token_t|context)) is the per-token KL, r_reward is the terminal reward from the reward model, β is the KL penalty coefficient, and T is the last token position.
Then compute the discounted returns (rewards-to-go) for each position:
Input:
- Line 1: beta gamma (KL coefficient, discount factor)
- Line 2: r_reward (terminal reward)
- Line 3: T (sequence length)
- Line 4: space-separated per-token KL values (T values)
Output:
- Line 1: Shaped rewards for each position, rounded to 4 decimal places
- Line 2: Discounted returns for each position, rounded to 4 decimal places
Example
0.1 0.99 2.0 3 0.5 0.3 0.1
-0.0500 -0.0300 1.9900 1.9008 1.9706 1.9900
- First, we calculate the shaped rewards for each position using the given formula:
- For ,
- For ,
- This results in , ,
- Then, we calculate the discounted returns for each position using the formula:
- For ,
- For ,
- For ,
- The calculated shaped rewards are , , and the calculated discounted returns are , ,
- The final output is the shaped rewards and discounted returns rounded to 4 decimal places: , , and ,
Constraints
- 0 < beta <= 1, 0 < gamma <= 1
- 1 <= T <= 20
- Round to 4 decimal places