Policy Gradients and RLHF
Policy-gradient methods optimize a parameterized policy directly by gradient ascent on the expected reward. The key result, the score-function (REINFORCE) estimator, turns the gradient of an expectation into an expectation of something we can sample, even when the reward is a black box. This is the mathematics behind reinforcement learning from human feedback (RLHF), where a language model is the policy and a learned reward model scores its answers.
The policy gradient theorem
For a one-step problem (a "bandit": choose an action, receive a reward), . Using :
Sample actions, and push up the log-probability of each in proportion to its reward. No derivative of is needed. For sequences (episodes, or tokens of a generated answer), of the whole trajectory is the sum of per-step log-probabilities.
Baselines reduce variance
Since , subtracting any constant from the reward leaves the gradient unbiased:
A good baseline (the average reward, or a learned value ) dramatically reduces the variance. is the advantage: how much better than expected the action was.
import numpy as np
rng = np.random.default_rng(0)
rewards = np.array([1.0, 2.0, 5.0]) # three-armed bandit (expected rewards)
theta = np.zeros(3)
def policy(th): e = np.exp(th - th.max()); return e / e.sum()
for use_baseline in (False, True):
grads = []
p = policy(theta)
for _ in range(5000):
a = rng.choice(3, p=p); R = rewards[a] + rng.normal(0, 1)
b = p @ rewards if use_baseline else 0.0
grad_logp = np.eye(3)[a] - p # gradient of log softmax
grads.append((R - b) * grad_logp)
g = np.array(grads)
print(f"baseline {use_baseline!s:5s}: mean gradient {np.round(g.mean(0), 3)}, total variance {g.var(0).sum():.3f}")
exact = p * (rewards - p @ rewards)
print("exact gradient:", np.round(exact, 3))baseline False: mean gradient [-0.558 -0.242 0.801], total variance 6.484
baseline True : mean gradient [-0.528 -0.25 0.778], total variance 1.610
exact gradient: [-0.556 -0.222 0.778]
Both estimators agree with the exact gradient on average; the baseline cuts the variance several-fold.
Training a policy
import numpy as np
rng = np.random.default_rng(1)
rewards = np.array([1.0, 2.0, 5.0])
theta, lr, avg = np.zeros(3), 0.05, 0.0
for step in range(1, 2001):
p = np.exp(theta - theta.max()); p /= p.sum()
a = rng.choice(3, p=p); R = rewards[a] + rng.normal(0, 1)
avg += 0.01 * (R - avg) # running-average baseline
theta += lr * (R - avg) * (np.eye(3)[a] - p) # REINFORCE ascent step
if step in (1, 200, 500, 2000):
print(f"step {step:4d}: policy {np.round(p, 3)}")step 1: policy [0.333 0.333 0.333]
step 200: policy [0.012 0.013 0.976]
step 500: policy [0.004 0.006 0.99 ]
step 2000: policy [0.001 0.001 0.998]
From REINFORCE to RLHF
RLHF for language models (InstructGPT, 2022) has three steps:
- Supervised fine-tuning on demonstrations (Language Modeling).
- Reward model: a network trained on human preference pairs with the Bradley-Terry loss , where was preferred over .
- RL: maximize with a policy-gradient method (PPO, which clips the update ratio for stability). The KL penalty (Entropy and KL) keeps the model close to the reference so it cannot exploit flaws in the reward model.
DPO (direct preference optimization) shows that this KL-regularized objective has a closed-form optimal policy, and turns preference learning into a simple classification loss on the policy itself, with no reward model or sampling: . GRPO uses the mean reward of a group of sampled answers to the same prompt as the baseline, removing the value network.
In software
- Hugging Face TRL provides
PPOTrainer,DPOTrainer,GRPOTrainerandRewardTrainer. - In code the policy gradient is implemented as the loss
-(advantage.detach() * logprob).mean(), whose gradient is the estimator above. - For tokens,
logprobis the sum of the log-softmax values of the sampled tokens.
Go further: Preference Tuning: Reward Models, RLHF and DPO builds the Bradley-Terry reward model and runs a tiny DPO training.
Exercises
Exercise 1: Score function of a softmax
For , show that .
Answer
.
Solution
The gradient of is and the gradient of log-sum-exp is the softmax . (The same identity as in Softmax and Cross-Entropy Gradient, with opposite sign.)
Exercise 2: Bradley-Terry
A reward model scores the preferred answer 2.0 and the other 0.5. What probability does it assign to the human's choice, and what is the loss?
Answer
; loss about .
Solution
, and .
Exercise 3: Baseline does not bias (code)
Check numerically that for .
Answer
The expectation is the zero vector.
Solution
.
import numpy as np
th = np.array([1.0, 0.0, -1.0]); p = np.exp(th) / np.exp(th).sum()
print(np.allclose(sum(p[a] * (np.eye(3)[a] - p) for a in range(3)), 0))True
Test yourself
The REINFORCE gradient estimate for one sampled action is…
Why subtract a baseline from the reward?
- To change the optimal policy
- To reduce the variance of the gradient estimate without biasing it
- To make rewards positive
- It is required for softmax
What does the KL penalty in RLHF do?
- Speeds up sampling
- Keeps the tuned policy close to the reference model so it does not exploit the reward model
- Removes the need for preferences
- Increases the vocabulary