Run PPO epochs with the clipped objective and KL early stopping
Why it matters KL early stopping is a common safety valve in PPO implementations for both robotics and RLHF.
PPO reuses one batch for several epochs. If the new policy drifts too far from the policy that collected the data, training on that batch should stop early.
Write ppo_epochs(old_logp, epochs_logp, adv, clip, target_kl).
- old_logp: (B,) log probs under the data-collecting policy. adv: (B,) advantages.
- epochs_logp: list of (B,) arrays, the new log probs at the start of each epoch.
For epoch e in order:
1. ratio = exp(new - old).
2. approx_kl = mean((ratio - 1) - log(ratio)).
3. If approx_kl > 1.5 * target_kl, stop and return (objectives so far, e).
4. Otherwise append the clipped objective mean(min(ratio * adv, clip(ratio, 1 - clip, 1 + clip) * adv)) as a float.
If no epoch triggers the stop, return (objectives, -1).
def ppo_epochs(old_logp, epochs_logp, adv, clip, target_kl)Example
old [-1, -0.5, -2, -1.2], adv [1, -1, 0.5, 2], epochs [[-0.9, -0.6, -1.9, -1.1], [-0.7, -0.8, -1.8, -0.9]], clip 0.2, target_kl 0.02 gives ([0.7408], 1).
Understand the idea
PPO squeezes more learning out of each batch by doing several passes over it. The danger is that the policy changes so much that the old data no longer describes it. The clipped objective limits how much each sample can push, and KL early stopping adds a second brake: measure how far the new policy has moved and stop the epochs when it moves too far.
Example: if log probs rise by 0.1 on every sample, the ratio is e^0.1 = 1.105 and the KL estimate is 1.105 - 1 - 0.1 = 0.005, small. A jump of 0.7 gives 2.014 - 1 - 0.7 = 0.31, far too big.
Rules:
ratio = exp(logp_new - logp_old)
kl ~ mean((ratio - 1) - log ratio), stop if kl > 1.5 * target
L = mean(min(ratio * A, clip(ratio, 1 - c, 1 + c) * A))
The same objective trains LLMs with RLHF, where policies that drift too far start producing reward-hacked text.
Shapes and data flow
old, adv, epochs_logp[e]: (B,) -> ratio: (B,) -> kl, objective: scalars