v9.1.1
Menu

RLHF Reward Shaping

hardPROPreference OptimizationLLM 2: Training & Alignment

Implement reward shaping for RLHF with KL penalty.

The shaped reward at each token position t is: Rt={−β⋅kltif t<Trreward−β⋅kltif t=TR_t = \begin{cases} -\beta \cdot \text{kl}_t & \text{if } t < T \\ r_{\text{reward}} - \beta \cdot \text{kl}_t & \text{if } t = T \end{cases}

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: Gt=∑k=0T−tγkRt+kG_t = \sum_{k=0}^{T-t} \gamma^k R_{t+k}

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

Input
0.1 0.99
2.0
3
0.5 0.3 0.1
Output
-0.0500 -0.0300 1.9900
1.9008 1.9706 1.9900
Reasoning
  • First, we calculate the shaped rewards RtR_t for each position tt using the given formula:
    • For t<Tt < T, Rt=−β⋅klt=−0.1⋅kltR_t = -\beta \cdot \text{kl}_t = -0.1 \cdot \text{kl}_t
    • For t=Tt = T, RT=rreward−β⋅klT=2.0−0.1⋅0.1=1.99R_T = r_{\text{reward}} - \beta \cdot \text{kl}_T = 2.0 - 0.1 \cdot 0.1 = 1.99
    • This results in R1=−0.1⋅0.5=−0.05R_1 = -0.1 \cdot 0.5 = -0.05, R2=−0.1⋅0.3=−0.03R_2 = -0.1 \cdot 0.3 = -0.03, R3=2.0−0.1⋅0.1=1.99R_3 = 2.0 - 0.1 \cdot 0.1 = 1.99
  • Then, we calculate the discounted returns GtG_t for each position tt using the formula: Gt=∑k=0T−tγkRt+kG_t = \sum_{k=0}^{T-t} \gamma^k R_{t+k}
    • For t=1t = 1, G1=R1+γR2+γ2R3=−0.05+0.99⋅(−0.03)+0.992⋅1.99G_1 = R_1 + \gamma R_2 + \gamma^2 R_3 = -0.05 + 0.99 \cdot (-0.03) + 0.99^2 \cdot 1.99
    • For t=2t = 2, G2=R2+γR3=−0.03+0.99⋅1.99G_2 = R_2 + \gamma R_3 = -0.03 + 0.99 \cdot 1.99
    • For t=3t = 3, G3=R3=1.99G_3 = R_3 = 1.99
  • The calculated shaped rewards are −0.05-0.05, −0.03-0.03, 1.991.99 and the calculated discounted returns are −0.05+0.99⋅(−0.03)+0.992⋅1.99≈1.9008-0.05 + 0.99 \cdot (-0.03) + 0.99^2 \cdot 1.99 \approx 1.9008, −0.03+0.99⋅1.99≈1.9706-0.03 + 0.99 \cdot 1.99 \approx 1.9706, 1.991.99
  • The final output is the shaped rewards and discounted returns rounded to 4 decimal places: −0.0500-0.0500, −0.0300-0.0300, 1.99001.9900 and 1.90081.9008,

Constraints

  • 0 < beta <= 1, 0 < gamma <= 1
  • 1 <= T <= 20
  • Round to 4 decimal places

Learn this in

More from LLM 2: Training & Alignment

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.