Full PPO loss with GAE, advantage whitening and value clipping
The PPO step used in RLHF combines several pieces that each have a classic bug: advantages from GAE, whitening them, a clipped policy ratio, and a clipped value loss that stops the critic from moving too far in one update.
Write ppo_loss(rewards, old_values, new_values, old_logp, new_logp, gamma, lam, clip_eps, clip_v, vf_coef) for one trajectory of length T. old_values has length T + 1 (the last entry is the bootstrap value, 0 if the episode ended); everything else has length T.
1. GAE with old_values: delta_t = rewards[t] + gamma * V[t + 1] - V[t]; A_t = delta_t + gamma * lam * A_{t + 1}, with A_T = 0.
2. returns = A + V[:T] (use the raw advantages).
3. adv = (A - mean(A)) / (std(A) + 1e-8), population std.
4. ratio = exp(new_logp - old_logp); policy_loss = -mean(min(ratio * adv, clip(ratio, 1 - clip_eps, 1 + clip_eps) * adv)).
5. v_clip = V[:T] + clip(new_values - V[:T], -clip_v, clip_v); value_loss = 0.5 * mean(max((new_values - returns) ** 2, (v_clip - returns) ** 2)).
6. total = policy_loss + vf_coef * value_loss; clip_frac = mean(|ratio - 1| > clip_eps).
Return a dict with keys "policy_loss", "value_loss", "total", "clip_frac" (floats).
def ppo_loss(rewards, old_values, new_values, old_logp, new_logp, gamma, lam, clip_eps, clip_v, vf_coef)Understand the idea
GAE turns rewards and value estimates into advantages. Returns, the critic's targets, are raw advantages plus old values. The policy term uses whitened advantages and a clipped ratio; the value term is clipped too. Worked example: rewards [1, 1], V = [0.5, 0.5, 0], gamma = lam = 1. delta_1 = 1 + 0 - 0.5 = 0.5, delta_0 = 1 + 0.5 - 0.5 = 1. A_1 = 0.5, A_0 = 1 + 0.5 = 1.5. Returns = [2.0, 1.0]. Whitened: mean 1, std 0.5, so adv = [1, -1]. With clip_eps 0.2, a ratio of 1.3 on adv 1 gives min(1.3, 1.2) = 1.2; a ratio of 0.7 on adv -1 gives min(-0.7, -0.8) = -0.8. Value clip: V = 0.5, new = 1.5, clip_v = 0.2, so v_clip = 0.7; with return 2, max(0.25, 1.69) = 1.69. Rules: A_t = delta_t + gamma * lam * A_(t+1); policy_loss = -mean(min(ratio * adv, clipped ratio * adv)); value_loss = 0.5 * mean(max of the two squared errors); total adds vf_coef * value_loss; clip_frac = share with |ratio - 1| > clip_eps. Used in RLHF for chat models.