TExcelTAD
Home › Math for Deep Learning & LLMs › Policy Gradients and RLHF

Policy Gradients and RLHF

Policy-gradient methods optimize a parameterized policy πθ(a∣s)\pi_{\boldsymbol{\theta}}(a \mid s) 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), J(θ)=Ea∼πθ[R(a)]J(\boldsymbol{\theta}) = \mathbb{E}_{a \sim \pi_{\boldsymbol{\theta}}}[R(a)]. Using ∇π=π∇log⁡π\nabla\pi = \pi\nabla\log\pi:

∇θJ=∑aR(a)∇θπθ(a)=Ea∼πθ[R(a) ∇θlog⁡πθ(a)]\nabla_{\boldsymbol{\theta}}J = \sum_a R(a)\nabla_{\boldsymbol{\theta}}\pi_{\boldsymbol{\theta}}(a) = \mathbb{E}_{a \sim \pi_{\boldsymbol{\theta}}}\left[R(a)\,\nabla_{\boldsymbol{\theta}}\log\pi_{\boldsymbol{\theta}}(a)\right]

Sample actions, and push up the log-probability of each in proportion to its reward. No derivative of RR is needed. For sequences (episodes, or tokens of a generated answer), log⁡π\log\pi of the whole trajectory is the sum of per-step log-probabilities.

Baselines reduce variance

Since E[∇log⁡π]=∑a∇π(a)=∇1=0\mathbb{E}[\nabla\log\pi] = \sum_a\nabla\pi(a) = \nabla 1 = 0, subtracting any constant bb from the reward leaves the gradient unbiased:

∇J=E[(R(a)−b)∇log⁡π(a)]\nabla J = \mathbb{E}\left[(R(a) - b)\nabla\log\pi(a)\right]

A good baseline (the average reward, or a learned value V(s)V(s)) dramatically reduces the variance. R−bR - b is the advantage: how much better than expected the action was.

python · try it yourself
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

python · try it yourself
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:

  1. Supervised fine-tuning on demonstrations (Language Modeling).
  2. Reward model: a network rϕ(x,y)r_\phi(x, y) trained on human preference pairs with the Bradley-Terry loss −log⁡σ(rϕ(x,yw)−rϕ(x,yl))-\log\sigma(r_\phi(x, y_w) - r_\phi(x, y_l)), where ywy_w was preferred over yly_l.
  3. RL: maximize Ey∼πθ[rϕ(x,y)]−β DKL(πθ∥πref)\mathbb{E}_{y \sim \pi_{\boldsymbol{\theta}}}[r_\phi(x, y)] - \beta\,D_{\mathrm{KL}}(\pi_{\boldsymbol{\theta}} \Vert \pi_{\text{ref}}) with a policy-gradient method (PPO, which clips the update ratio πθ/πold\pi_{\boldsymbol{\theta}}/\pi_{\text{old}} 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: −log⁡σ(βlog⁡πθ(yw)πref(yw)−βlog⁡πθ(yl)πref(yl))-\log\sigma\left(\beta\log\frac{\pi_{\boldsymbol{\theta}}(y_w)}{\pi_{\text{ref}}(y_w)} - \beta\log\frac{\pi_{\boldsymbol{\theta}}(y_l)}{\pi_{\text{ref}}(y_l)}\right). 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, GRPOTrainer and RewardTrainer.
  • In code the policy gradient is implemented as the loss -(advantage.detach() * logprob).mean(), whose gradient is the estimator above.
  • For tokens, logprob is 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 π=softmax⁡(θ)\pi = \operatorname{softmax}(\boldsymbol{\theta}), show that ∇θlog⁡π(a)=ea−π\nabla_{\boldsymbol{\theta}}\log\pi(a) = \mathbf{e}_a - \boldsymbol{\pi}.

Answer

log⁡π(a)=θa−LSE⁡(θ)\log\pi(a) = \theta_a - \operatorname{LSE}(\boldsymbol{\theta}).

Solution

The gradient of θa\theta_a is ea\mathbf{e}_a and the gradient of log-sum-exp is the softmax π\boldsymbol{\pi}. (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

σ(1.5)≈0.818\sigma(1.5) \approx 0.818; loss about 0.2010.201.

Solution

σ(1.5)=1/(1+e−1.5)=0.8176\sigma(1.5) = 1/(1 + e^{-1.5}) = 0.8176, and −ln⁡0.8176=0.2014-\ln 0.8176 = 0.2014.

Exercise 3: Baseline does not bias (code)

Check numerically that Ea∼π[∇log⁡π(a)]=0\mathbb{E}_{a \sim \pi}[\nabla\log\pi(a)] = \mathbf{0} for π=softmax⁡(1,0,−1)\pi = \operatorname{softmax}(1, 0, -1).

Answer

The expectation is the zero vector.

Solution

∑aπ(a)(ea−π)=π−π=0\sum_a\pi(a)(\mathbf{e}_a - \boldsymbol{\pi}) = \boldsymbol{\pi} - \boldsymbol{\pi} = \mathbf{0}.

python · try it yourself
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…

  1. ∇R(a)\nabla R(a)
  2. R(a)∇θlog⁡πθ(a)R(a)\nabla_{\boldsymbol{\theta}}\log\pi_{\boldsymbol{\theta}}(a)
  3. log⁡R(a)\log R(a)
  4. π(a)R(a)\pi(a)R(a)

Why subtract a baseline from the reward?

  1. To change the optimal policy
  2. To reduce the variance of the gradient estimate without biasing it
  3. To make rewards positive
  4. It is required for softmax

What does the KL penalty in RLHF do?

  1. Speeds up sampling
  2. Keeps the tuned policy close to the reference model so it does not exploit the reward model
  3. Removes the need for preferences
  4. Increases the vocabulary