Now that we have a reward model, it is time to train the policy to raise that reward. But as we saw in the previous lesson, is a proxy objective, and maximising it alone exploits the RM’s loopholes. That is why the RLHF objective came with a KL term from the start.
This lesson has three parts. First we find the exact optimum of this objective; that solution is the hub that ties together the rest of this track (rejection sampling, DPO). Next we see how the KL is estimated and where it goes in actual training. Finally we assemble the LLM version of PPO that optimises it.
The closed-form solution: tilting the reference policy by the reward
Fix a prompt and let be any distribution over responses (forget the neural-network parameterisation for a moment). Expand the KL and combine everything into one expectation.
The denominator does not sum to 1, so we define a distribution by dividing by the normalising constant .
Then , so
does not depend on , and the KL is non-negative and zero only when . Therefore is the unique optimum, with optimal value . Several things follow immediately from this one-line derivation.
- β → ∞: , so . Nothing moves.
- β → 0: all the mass piles onto the highest-reward response (ties are split in proportion to ). Pure reward maximisation.
- never leaves the support of . If , then no matter how large the reward. Responses the reference policy almost never produces are almost never produced.
- The reward and β enter only as . Doubling the reward is the same as halving β.
- This is a Boltzmann distribution (energy , temperature ), and corresponds to the free energy.
So why not just use this formula? is a sum over all possible response sequences, so it cannot be computed, and there is no way to sample from directly. RL (PPO), sampling approximations (best-of-N, next lesson) and fitting directly to preference data (DPO, lesson 5) are all different ways of approaching this uncomputable .
보상모델이 생겼으니 이제 정책이 그 보상을 높이도록 학습시킬 차례다. 하지만 앞 레슨에서 본 것처럼 는 대리 목표이고, 그것만 최대화하면 RM의 허점을 파고든다. 그래서 RLHF의 목적함수는 처음부터 KL 항을 달고 나왔다.
이 레슨은 세 부분이다. 먼저 이 목적함수의 정확한 최적해를 구한다. 그 해가 이 트랙의 나머지(rejection sampling, DPO)를 묶는 중심이다. 다음으로 실제 학습에서 KL을 어떻게 추정하고 어디에 넣는지 본다. 마지막으로 이것을 최적화하는 PPO의 LLM 버전을 조립한다.
닫힌 해: 기준 정책을 보상으로 기울이기
prompt 를 하나 고정하고 를 응답 위의 아무 분포라고 하자(신경망 parameterization은 잠시 잊는다). KL을 풀어 쓰고 한 기댓값으로 묶는다.
분모 는 합이 1이 아니므로 정규화 상수 로 나눈 분포를 정의한다.
그러면 이므로
는 와 무관하고 KL은 0 이상이며 일 때만 0이다. 따라서 가 유일한 최적해이고 최적값은 다. 이 한 줄짜리 유도에서 몇 가지가 바로 나온다.
- β → ∞: 이므로 . 움직이지 않는다.
- β → 0: 보상이 가장 큰 응답에 모든 질량이 몰린다(동점이면 비율로 나눈다). 순수 보상 최대화.
- 는 의 지지집합(support) 밖으로 나가지 않는다. 이면 보상이 아무리 커도 이다. 기준 정책이 거의 내지 않는 응답은 거의 내지 않는다.
- 보상과 β는 로만 들어간다. 보상을 2배 하는 것과 β를 절반으로 하는 것은 같다.
- 이것은 볼츠만 분포(에너지 , 온도 )이고, 는 자유 에너지에 해당한다.
그런데 왜 그냥 이 공식을 쓰지 않을까? 는 가능한 모든 응답 시퀀스에 대한 합이라 계산할 수 없고, 에서 직접 샘플링할 방법도 없다. RL(PPO), 샘플링 근사(best-of-N, 다음 레슨), 선호 데이터에서 직접 맞추기(DPO, 레슨 5)는 모두 이 계산할 수 없는 에 다가가는 서로 다른 방법이다.
What to check in the figure:
- Push β to the far right (β = 10) and the violet bars line up with the grey outlines. Push it to the far left (β ≈ 0.02) and the mass piles onto F, which has the largest reward.
- The curve on the right is concave, and the slope of the tangent at the current point is exactly β. The contours of are straight lines of slope β, so π* is the point where such a line touches the curve.
- Press Inflate one reward and the reward of H, which gives only about 1%, becomes 3.5. At small β the mass moves to H, but the curve shows that this costs a lot of KL. An RM overrating a single rare response is the simplest model of reward hacking.
import numpy as np
rng = np.random.default_rng(0)
def softmax(z):
e = np.exp(z - z.max()); return e / e.sum()
# a "language model" with 8 responses: π_ref and reward r
logits_ref = np.array([1.2, 0.8, 0.5, 0.3, 0.0, -0.3, -0.8, -1.5])
pi_ref = softmax(logits_ref)
r = np.array([0.1, 0.9, -0.4, 1.5, 0.3, 2.0, -1.0, 0.6])
def J(pi, beta):
"""KL-regularised objective: E_π[r] - β KL(π || π_ref)"""
return pi @ r - beta * np.sum(pi * np.log(pi / pi_ref))
def tilt(beta):
w = pi_ref * np.exp(r / beta)
return w / w.sum(), w.sum()
for beta in [2.0, 0.5, 0.1]:
pi_star, Z = tilt(beta)
kl = np.sum(pi_star * np.log(pi_star / pi_ref))
# among 2000 policies randomly perturbed around π*, does any have a larger J?
beaten = sum(J(softmax(np.log(pi_star) + rng.normal(0, 0.3, 8)), beta) > J(pi_star, beta) + 1e-12
for _ in range(2000))
print(f"β={beta:<4} E[r]={pi_star @ r:6.3f} KL={kl:6.3f} J(π*)={J(pi_star, beta):.4f}"
f" β·log Z={beta*np.log(Z):.4f} perturbations beating π*: {beaten}/2000")
print("\nπ_ref :", np.round(pi_ref, 3))
print("π*(β=0.5) :", np.round(tilt(0.5)[0], 3))
print("reward r :", r)checks out numerically, and none of the 2000 perturbations beats . At β = 0.5, moves mass to D and F, which have high rewards. B’s reward is less than half of F’s, but because gave it a lot of probability it keeps about 15%. It is not the reward alone but its product with the reference probability that decides the outcome.
The KL of a sequence is the sum of token KLs
In an LLM, , so the log splits into a sum.
The KL over the whole sequence space cannot be computed directly, but computing this sum on a single response sampled from the policy gives an unbiased estimate of the KL. Some implementations compute the exact KL over the whole vocabulary at each position (at a cost proportional to the vocabulary size), but most use only the log-ratio of the sampled token. Two questions arise here: “which estimator?” and “where does it go?”.
KL estimators: k1, k2, k3
For a sample and the ratio , there are three estimators, as summarised by Schulman (2020). The target is .
| Estimator | Formula | Expectation | Properties |
|---|---|---|---|
| k1 | KL (unbiased) | can be negative per sample; high variance | |
| k2 | matches KL to second order (biased) | always ≥ 0, low variance; bias grows when the distributions are far apart | |
| k3 | KL (unbiased) | always ≥ 0, usually low variance |
That k3 is unbiased takes one line. , so , and k3 is k1 plus a zero-mean control variate . And since , for every sample. k2 estimates the f-divergence with , and when that f-divergence agrees with the KL to second order, so the bias is small.
그림에서 확인할 것:
- β를 오른쪽 끝(β = 10)으로 밀면 보라색 막대가 회색 테두리와 겹친다. 왼쪽 끝(β ≈ 0.02)으로 밀면 보상이 가장 큰 F에 질량이 몰린다.
- 오른쪽 곡선은 오목하고, 현재 점에서의 접선 기울기가 정확히 β다. 의 등고선이 기울기 β인 직선이므로, π*는 그 직선이 곡선에 접하는 점이다.
- “보상 하나만 크게”를 누르면 가 약 1%만 주는 H의 보상이 3.5가 된다. 작은 β에서는 H로 질량이 가지만, 곡선을 보면 그만큼 KL을 많이 쓴다. RM이 드문 응답 하나를 과대평가하는 것이 reward hacking의 가장 단순한 모형이다.
import numpy as np
rng = np.random.default_rng(0)
def softmax(z):
e = np.exp(z - z.max()); return e / e.sum()
# 응답 8개짜리 "언어 모델": π_ref 와 보상 r
logits_ref = np.array([1.2, 0.8, 0.5, 0.3, 0.0, -0.3, -0.8, -1.5])
pi_ref = softmax(logits_ref)
r = np.array([0.1, 0.9, -0.4, 1.5, 0.3, 2.0, -1.0, 0.6])
def J(pi, beta):
"""KL 정규화 목적함수: E_π[r] - β KL(π || π_ref)"""
return pi @ r - beta * np.sum(pi * np.log(pi / pi_ref))
def tilt(beta):
w = pi_ref * np.exp(r / beta)
return w / w.sum(), w.sum()
for beta in [2.0, 0.5, 0.1]:
pi_star, Z = tilt(beta)
kl = np.sum(pi_star * np.log(pi_star / pi_ref))
# π* 주변을 무작위로 흔든 정책 2000개 중 J가 더 큰 것이 있는가?
beaten = sum(J(softmax(np.log(pi_star) + rng.normal(0, 0.3, 8)), beta) > J(pi_star, beta) + 1e-12
for _ in range(2000))
print(f"β={beta:<4} E[r]={pi_star @ r:6.3f} KL={kl:6.3f} J(π*)={J(pi_star, beta):.4f}"
f" β·log Z={beta*np.log(Z):.4f} π*를 이긴 섭동 {beaten}/2000")
print("\nπ_ref :", np.round(pi_ref, 3))
print("π*(β=0.5) :", np.round(tilt(0.5)[0], 3))
print("보상 r :", r)가 숫자로 맞고, 2000개의 섭동 중 어느 것도 를 이기지 못한다. β = 0.5에서 는 보상이 높은 D와 F로 질량을 옮긴다. B는 보상이 F의 절반도 안 되지만 가 크게 주던 응답이라 15% 정도를 유지한다. 보상만이 아니라 기준 확률과의 곱이 결과를 정한다.
시퀀스의 KL은 토큰 KL의 합이다
LLM에서 이므로 로그가 합으로 풀린다.
전체 시퀀스 공간의 KL을 직접 계산할 수는 없지만, 정책에서 뽑은 응답 하나로 이 합을 계산하면 KL의 불편(unbiased) 추정치가 된다. 각 위치의 어휘 전체에 대한 KL을 정확히 계산하는 구현도 있지만(어휘 크기만큼의 비용), 대부분은 샘플된 토큰의 log-ratio만 쓴다. 여기서 “어떤 추정량을 쓰나”와 “그것을 어디에 넣나”라는 두 질문이 생긴다.
KL 추정량: k1, k2, k3
샘플 와 비율 에 대해 Schulman(2020)이 정리한 세 가지 추정량이 있다. 목표는 이다.
| 추정량 | 식 | 기댓값 | 성질 |
|---|---|---|---|
| k1 | KL (불편) | 샘플마다 음수일 수 있다. 분산이 크다 | |
| k2 | KL과 2차까지 일치 (편향) | 항상 0 이상, 분산이 작다. 두 분포가 멀면 편향이 커진다 | |
| k3 | KL (불편) | 항상 0 이상, 대개 분산이 작다 |
k3가 불편이라는 것은 한 줄로 보인다. 이므로 이고, k3는 k1에 기댓값 0인 control variate 을 더한 것이다. 그리고 이므로 모든 샘플에서 이다. k2는 인 f-divergence의 추정량인데, 일 때 이 f-divergence가 KL과 2차까지 같아서 편향이 작다.
- At N = 1, μ = 0.5, the k1 histogram spreads widely, even below 0. This is how a “KL” measured from a single sample comes out negative.
- Raise μ to 2 or more and k2’s mean line drifts to the right of the black true-KL line.
- Raise σ to 1.5 or more and k3’s distribution grows a long right tail. When is wider, becomes very large on tail samples of .
# sample from π_θ = N(0, 1) and estimate KL(π_θ || π_ref) against π_ref = N(mu, 1).
def logpdf(x, mu, s=1.0):
return -0.5 * ((x - mu) / s) ** 2 - np.log(s * np.sqrt(2 * np.pi))
def estimators(x, mu):
logr = logpdf(x, mu) - logpdf(x, 0.0) # log r, r = π_ref(x) / π_θ(x)
k1 = -logr
k2 = 0.5 * logr ** 2
k3 = np.expm1(logr) - logr # (r - 1) - log r ≥ 0
return k1, k2, k3
print("mean and std of the per-sample estimate (200,000 samples)")
print(f"{'mu':>4} {'true KL':>8} | {'k1 mean':>8} {'k1 std':>7} | {'k2 mean':>8} {'k2 std':>7} | {'k3 mean':>8} {'k3 std':>7}")
for mu in [0.1, 0.5, 1.0, 2.0]:
true_kl = 0.5 * mu ** 2 # KL between two Gaussians with equal variance
x = rng.normal(0.0, 1.0, 200_000) # x ~ π_θ
row = " | ".join(f"{k.mean():8.4f} {k.std():7.4f}" for k in estimators(x, mu))
print(f"{mu:4.1f} {true_kl:8.4f} | {row}")When μ is small (when the policy has moved only a little from the reference, as in real RLHF), the standard deviations of k3 and k2 are about a tenth or less of k1’s. At μ = 2, k2 is biased to nearly twice the true KL, and k3’s variance also becomes larger than k1’s. No estimator is best in every situation.
Where does the KL go: reward vs loss
In the reward (the InstructGPT / PPO way). Define the reward at each token as follows.
This puts k1 in as a per-token reward, and the value is treated as a constant (no gradient flows through it). Even so, the gradient of the KL term comes out right. , and the second term is 0, so “a policy gradient with the KL as reward” is exactly the gradient of the KL. Also, because the KL penalty is summed into the return, earlier tokens take responsibility, through the advantage, for the KL incurred later too.
In the loss (the GRPO way). Separately from the policy-gradient loss, add the per-token estimator to the loss and differentiate it as is. The standard GRPO implementation uses k3.
It looks simple, but there is a subtlety. Estimating the value well and estimating the gradient well are different things. Fix a sample , differentiate each estimator with respect to , and take the expectation.
Differentiate k1, unbiased as a value, as a loss and the expected gradient is 0; differentiate k3 as a loss and you get the gradient not of the reverse KL we wanted but of the forward KL (on-policy, per token). k2, biased as a value, is the one that gives the exact gradient of the reverse KL. When the two distributions are close, the gradients of the forward and reverse KL are almost the same, so in practice it often does not matter much, but once the policy moves far it becomes a different regulariser. Several recent analyses have pointed this out.
# a softmax policy over 8 responses, π_θ = softmax(θ). θ sits a little away from π_ref.
theta = np.log(pi_ref) + rng.normal(0, 0.5, 8)
pi = softmax(theta)
L = np.log(pi / pi_ref)
grad_rev = pi * (L - pi @ L) # ∇_θ KL(π_θ || π_ref) (reverse: what we want)
grad_fwd = pi - pi_ref # ∇_θ KL(π_ref || π_θ) (forward)
ys = rng.choice(8, size=200_000, p=pi) # on-policy samples
G = np.eye(8)[ys] - pi # per sample, ∇_θ log π_θ(y) = onehot(y) - π
ratio = pi_ref[ys] / pi[ys]
E_grad = {
"k1": G.mean(0), # ∇(-log r) = ∇log π
"k2": (np.log(pi[ys] / pi_ref[ys])[:, None] * G).mean(0),
"k3": ((1 - ratio)[:, None] * G).mean(0), # ∇(r - 1 - log r)
}
rel = lambda a, b: np.linalg.norm(a - b) / np.linalg.norm(b)
print(f"|∇KL(π‖π_ref)| = {np.linalg.norm(grad_rev):.4f}")
for k, g in E_grad.items():
print(f"{k}: |E∇| = {np.linalg.norm(g):.4f} rel. error vs reverse-KL gradient {rel(g, grad_rev):.3f}"
f" rel. error vs forward-KL gradient {rel(g, grad_fwd):.3f}")k1’s expected gradient is at the level of Monte Carlo noise (almost 0); k2 matches the reverse-KL gradient and k3 the forward-KL gradient.
As in GRPO, a KL estimator is added to the loss and differentiated as is. On on-policy samples, which one's expected gradient equals the gradient of KL(π_θ‖π_ref) exactly?
, and its expectation is exactly . k1 and k3 are unbiased estimators of the value, but differentiated as losses, k1 has expected gradient 0 and k3 gives the gradient of the forward KL . When the KL is put in the reward (stop-gradient, then policy gradient), k1 gives the correct gradient. Whenever you say “estimator”, distinguish whether it estimates the value or the gradient.
→ Go deeper: Regularisation — KL, entropy and length works through value versus gradient estimators of the KL, anchoring to the previous policy (Kimi k1.5’s mirror descent), and the entropy and length regularisers that sit beside it.
PPO for LMs: putting it together
Now we fit PPO to LLMs. The MDP is as follows.
- State , action (one token of the vocabulary), and a deterministic transition (append the token).
- Reward is above: (log-ratio) at every token, plus at the last token (EOS). The discount is usually .
- One episode = one response. When the maximum length is reached with no EOS, it is common to penalise the reward or discard the sample.
Four models sit in memory.
| Model | Role | Trained? |
|---|---|---|
| Policy | generates responses; the thing being trained | yes |
| Reference | KL computation (usually the SFT model) | no |
| Reward model | score at the end of the response | no |
| Value model | expected return per token; advantage computation | yes (usually initialised from the RM) |
One iteration (1) generates responses for a batch of prompts, (2) computes per-token log-probs, rewards and values with the policy, reference, RM and value model, (3) computes advantages with GAE and whitens them over the whole batch (normalising to mean 0, variance 1), and (4) optimises the clipped surrogate and value loss for a few epochs on the same rollouts.
import torch
def masked_mean(x, mask):
return (x * mask).sum() / mask.sum()
def masked_whiten(x, mask, eps=1e-8):
mean = masked_mean(x, mask)
var = masked_mean((x - mean) ** 2, mask)
return (x - mean) * torch.rsqrt(var + eps) * mask
@torch.no_grad()
def per_token_rewards(rm_score, logp_old, logp_ref, mask, beta):
"""logp_*: (B, T) log-probs of the response tokens. mask: 1 for response tokens, 0 for right padding.
reward = -β·(log π_old − log π_ref) at every token + the RM score at the last token."""
kl = logp_old - logp_ref # k1, per token
rewards = -beta * kl
last = mask.sum(dim=1).long() - 1 # position of the last response token
rewards[torch.arange(rewards.size(0)), last] += rm_score
seq_kl = (kl * mask).sum(dim=1).mean() # for logging: mean per-response KL estimate
return rewards * mask, seq_kl
@torch.no_grad()
def gae(rewards, values, mask, gamma=1.0, lam=0.95):
values = values * mask # values after the response ends are 0
adv = torch.zeros_like(rewards)
last = torch.zeros(rewards.size(0), device=rewards.device)
T = rewards.size(1)
for t in reversed(range(T)):
next_v = values[:, t + 1] if t + 1 < T else 0.0
delta = rewards[:, t] + gamma * next_v - values[:, t]
last = delta + gamma * lam * last
adv[:, t] = last
returns = adv + values
return masked_whiten(adv, mask), returns # advantage whitening
def ppo_loss(logp, logp_old, adv, v_new, v_old, returns, mask, clip=0.2, vclip=0.2, vf_coef=0.1):
ratio = torch.exp(logp - logp_old) # ρ_t = π_θ / π_old
pg = -torch.min(ratio * adv, ratio.clamp(1 - clip, 1 + clip) * adv)
v_clipped = v_old + (v_new - v_old).clamp(-vclip, vclip)
vf = 0.5 * torch.max((v_new - returns) ** 2, (v_clipped - returns) ** 2)
loss = masked_mean(pg, mask) + vf_coef * masked_mean(vf, mask)
stats = {
"clipfrac": masked_mean(((ratio - 1).abs() > clip).float(), mask),
"approx_kl_old": masked_mean(0.5 * (logp - logp_old) ** 2, mask), # size of one step relative to π_old (k2)
}
return loss, stats
# GRPO-style alternative: KL in the loss rather than the reward (k3; the gradient flows through logp)
def kl_loss_k3(logp, logp_ref, mask):
log_r = logp_ref - logp # log(π_ref / π_θ)
return masked_mean(torch.exp(log_r) - 1 - log_r, mask)Several implementation details have a big effect on the result. Examples are initialising the value model from the RM (as in Stiennon et al. 2020 and InstructGPT), normalising or clipping the reward score, handling responses with no EOS, matching the temperature used at generation with the log-prob computation at training time (training–inference mismatch, lesson 9), and, like InstructGPT’s PPO-ptx, mixing in the pretraining loss to reduce the drop on public benchmarks (the alignment tax).
Summary
- The optimum of the KL-regularised objective is , with optimal value . Because cannot be computed, RL or an approximation is needed.
- β is the price of KL. The slope of the reward–KL curve is β, and the reward scale and β enter only together as .
- The sequence KL is estimated as a sum of token log-ratios. k1 is unbiased with high variance, k2 low-variance but biased, k3 unbiased, non-negative and usually low-variance.
- Putting the KL in the reward (stop-gradient, k1) gives the correct gradient and also assigns credit for the KL of future tokens. Putting it in the loss and differentiating gives 0 for k1 and the forward-KL gradient for k3.
- PPO for LMs = token MDP + EOS reward + per-token KL + value model and GAE + advantage whitening + clipped surrogate. Watch reward, KL, length and entropy together.
- N = 1, μ = 0.5에서 k1의 히스토그램이 0 아래까지 넓게 퍼진다. 샘플 하나로 잰 “KL”이 음수가 나오는 것이 이것이다.
- μ를 2 이상으로 올리면 k2의 평균선이 검은 진짜 KL 선 오른쪽으로 벗어난다.
- σ를 1.5 이상으로 키우면 k3의 분포에 긴 오른쪽 꼬리가 생긴다. 가 더 넓으면 의 꼬리 샘플에서 이 매우 커지기 때문이다.
# π_θ = N(0, 1) 에서 샘플링하고, π_ref = N(mu, 1) 과의 KL(π_θ || π_ref) 를 추정한다.
def logpdf(x, mu, s=1.0):
return -0.5 * ((x - mu) / s) ** 2 - np.log(s * np.sqrt(2 * np.pi))
def estimators(x, mu):
logr = logpdf(x, mu) - logpdf(x, 0.0) # log r, r = π_ref(x) / π_θ(x)
k1 = -logr
k2 = 0.5 * logr ** 2
k3 = np.expm1(logr) - logr # (r - 1) - log r ≥ 0
return k1, k2, k3
print("샘플 하나당 추정치의 평균·표준편차 (200,000개 샘플)")
print(f"{'mu':>4} {'true KL':>8} | {'k1 mean':>8} {'k1 std':>7} | {'k2 mean':>8} {'k2 std':>7} | {'k3 mean':>8} {'k3 std':>7}")
for mu in [0.1, 0.5, 1.0, 2.0]:
true_kl = 0.5 * mu ** 2 # 분산이 같은 두 가우시안의 KL
x = rng.normal(0.0, 1.0, 200_000) # x ~ π_θ
row = " | ".join(f"{k.mean():8.4f} {k.std():7.4f}" for k in estimators(x, mu))
print(f"{mu:4.1f} {true_kl:8.4f} | {row}")μ가 작을 때(실제 RLHF처럼 정책이 기준에서 조금만 움직였을 때) k3와 k2의 표준편차는 k1의 십여 분의 일이다. μ = 2에서는 k2가 진짜 KL의 두 배 가까이로 편향되고, k3의 분산도 k1보다 커진다. 어느 추정량도 모든 상황에서 최선은 아니다.
KL을 어디에 넣나: 보상 vs 손실
보상에 넣기 (InstructGPT·PPO 방식). 토큰마다 보상을 다음처럼 정의한다.
k1을 토큰별 보상으로 넣은 것이고, 이 값은 상수로 취급된다(gradient를 흘리지 않는다). 그런데도 KL 항의 gradient가 맞게 나온다. 이고 두 번째 항은 0이므로, “KL을 보상으로 둔 policy gradient”가 곧 KL의 gradient다. 또 KL 패널티가 return에 합산되므로, 앞쪽 토큰은 뒤에서 생길 KL까지 advantage로 책임진다.
손실에 넣기 (GRPO 방식). policy gradient 손실과 별도로, 토큰마다의 추정량을 손실에 더하고 그대로 미분한다. GRPO의 표준 구현은 k3를 쓴다.
간단해 보이지만 미묘한 점이 있다. 값을 잘 추정하는 것과 gradient를 잘 추정하는 것은 다르다. 샘플 를 고정하고 각 추정량을 로 미분해 기댓값을 내 보자.
값으로는 불편인 k1을 손실로 미분하면 기대 gradient가 0이 되고, k3를 손실로 미분하면 우리가 원한 역방향 KL이 아니라 순방향 KL 의 gradient가 된다(on-policy, 토큰 하나 기준). 값으로는 편향인 k2가 오히려 역방향 KL의 정확한 gradient를 준다. 두 분포가 가까우면 순방향과 역방향 KL의 gradient가 거의 같아서 실전에서는 큰 문제가 아닐 때가 많지만, 정책이 멀리 움직이면 다른 정규화가 된다. 최근 여러 분석이 이 점을 지적했다.
# 응답 8개짜리 softmax 정책 π_θ = softmax(θ). θ 는 π_ref 에서 조금 떨어진 곳.
theta = np.log(pi_ref) + rng.normal(0, 0.5, 8)
pi = softmax(theta)
L = np.log(pi / pi_ref)
grad_rev = pi * (L - pi @ L) # ∇_θ KL(π_θ || π_ref) (역방향: 우리가 원하는 것)
grad_fwd = pi - pi_ref # ∇_θ KL(π_ref || π_θ) (순방향)
ys = rng.choice(8, size=200_000, p=pi) # on-policy 샘플
G = np.eye(8)[ys] - pi # 샘플마다 ∇_θ log π_θ(y) = onehot(y) - π
ratio = pi_ref[ys] / pi[ys]
E_grad = {
"k1": G.mean(0), # ∇(-log r) = ∇log π
"k2": (np.log(pi[ys] / pi_ref[ys])[:, None] * G).mean(0),
"k3": ((1 - ratio)[:, None] * G).mean(0), # ∇(r - 1 - log r)
}
rel = lambda a, b: np.linalg.norm(a - b) / np.linalg.norm(b)
print(f"|∇KL(π‖π_ref)| = {np.linalg.norm(grad_rev):.4f}")
for k, g in E_grad.items():
print(f"{k}: |E∇| = {np.linalg.norm(g):.4f} 역방향 KL gradient와 상대오차 {rel(g, grad_rev):.3f}"
f" 순방향 KL gradient와 상대오차 {rel(g, grad_fwd):.3f}")k1의 기대 gradient는 몬테카를로 잡음 수준(거의 0)이고, k2는 역방향 KL gradient와, k3는 순방향 KL gradient와 일치한다.
GRPO식으로 KL 추정량을 손실에 더해 그대로 미분한다. on-policy 샘플에서 기대 gradient가 KL(π_θ‖π_ref)의 gradient와 정확히 같은 것은?
이고 그 기댓값이 정확히 다. k1과 k3는 값의 불편 추정량이지만, 손실로 미분하면 k1은 기대 gradient가 0, k3는 순방향 KL 의 gradient가 된다. KL을 보상에 넣는 방식(stop-gradient 후 policy gradient)에서는 k1이 올바른 gradient를 준다. “추정량”을 말할 때는 값의 추정인지 gradient의 추정인지를 구분해야 한다.
→ 더 깊이: 정규화 — KL, 엔트로피, 길이에서 KL의 값 추정량과 gradient 추정량, 직전 정책에 묶는 방식(Kimi k1.5의 mirror descent), 그 옆에 놓이는 엔트로피·길이 정규화를 다룬다.
PPO for LMs: 조립하기
이제 PPO를 LLM에 맞춘다. MDP는 다음과 같다.
- 상태 , 행동 (어휘 중 하나), 전이는 결정적(토큰을 이어 붙임).
- 보상은 위의 : 매 토큰 (log-ratio), 마지막 토큰(EOS)에 . 할인은 보통 .
- 에피소드 하나 = 응답 하나. 최대 길이에 도달해 EOS가 없으면 보상을 깎거나 버리는 처리가 흔하다.
메모리에는 모델 네 개가 올라간다.
| 모델 | 역할 | 학습? |
|---|---|---|
| 정책 | 응답 생성, 학습 대상 | O |
| 기준 | KL 계산 (보통 SFT 모델) | X |
| 보상모델 | 응답 끝에서 점수 | X |
| 가치모델 | 토큰마다 기대 return, advantage 계산 | O (보통 RM에서 초기화) |
한 iteration은 (1) prompt 배치로 응답을 생성하고, (2) 정책·기준·RM·가치모델로 토큰별 log-prob, 보상, 값을 계산하고, (3) GAE로 advantage를 구해 배치 전체에서 whitening(평균 0, 분산 1로 정규화)한 뒤, (4) 같은 rollout으로 몇 epoch 동안 clipped surrogate와 가치 손실을 최적화한다.
import torch
def masked_mean(x, mask):
return (x * mask).sum() / mask.sum()
def masked_whiten(x, mask, eps=1e-8):
mean = masked_mean(x, mask)
var = masked_mean((x - mean) ** 2, mask)
return (x - mean) * torch.rsqrt(var + eps) * mask
@torch.no_grad()
def per_token_rewards(rm_score, logp_old, logp_ref, mask, beta):
"""logp_*: (B, T) 응답 토큰의 log-prob. mask: 응답 토큰 1, 오른쪽 padding 0.
보상 = 토큰마다 -β·(log π_old − log π_ref) + 마지막 토큰에 RM 점수."""
kl = logp_old - logp_ref # k1, 토큰별
rewards = -beta * kl
last = mask.sum(dim=1).long() - 1 # 마지막 응답 토큰 위치
rewards[torch.arange(rewards.size(0)), last] += rm_score
seq_kl = (kl * mask).sum(dim=1).mean() # 로깅용: 응답당 KL 추정치 평균
return rewards * mask, seq_kl
@torch.no_grad()
def gae(rewards, values, mask, gamma=1.0, lam=0.95):
values = values * mask # 응답이 끝난 뒤의 값은 0
adv = torch.zeros_like(rewards)
last = torch.zeros(rewards.size(0), device=rewards.device)
T = rewards.size(1)
for t in reversed(range(T)):
next_v = values[:, t + 1] if t + 1 < T else 0.0
delta = rewards[:, t] + gamma * next_v - values[:, t]
last = delta + gamma * lam * last
adv[:, t] = last
returns = adv + values
return masked_whiten(adv, mask), returns # advantage whitening
def ppo_loss(logp, logp_old, adv, v_new, v_old, returns, mask, clip=0.2, vclip=0.2, vf_coef=0.1):
ratio = torch.exp(logp - logp_old) # ρ_t = π_θ / π_old
pg = -torch.min(ratio * adv, ratio.clamp(1 - clip, 1 + clip) * adv)
v_clipped = v_old + (v_new - v_old).clamp(-vclip, vclip)
vf = 0.5 * torch.max((v_new - returns) ** 2, (v_clipped - returns) ** 2)
loss = masked_mean(pg, mask) + vf_coef * masked_mean(vf, mask)
stats = {
"clipfrac": masked_mean(((ratio - 1).abs() > clip).float(), mask),
"approx_kl_old": masked_mean(0.5 * (logp - logp_old) ** 2, mask), # π_old 대비 한 step 크기 (k2)
}
return loss, stats
# GRPO식 대안: KL을 보상이 아니라 손실에 (k3, gradient가 logp를 통해 흐름)
def kl_loss_k3(logp, logp_ref, mask):
log_r = logp_ref - logp # log(π_ref / π_θ)
return masked_mean(torch.exp(log_r) - 1 - log_r, mask)몇 가지 구현 세부가 결과에 크게 영향을 준다. 가치모델을 RM에서 초기화하는 것(Stiennon et al. 2020과 InstructGPT의 방식), 보상 점수의 정규화나 clipping, EOS가 없는 응답의 처리, 생성 시 temperature와 학습 시 log-prob 계산의 일치(학습–추론 불일치, 레슨 9), 그리고 InstructGPT의 PPO-ptx처럼 사전학습 손실을 섞어 공개 벤치마크 성능 하락(alignment tax)을 줄이는 것이 그 예다.
정리
- KL 정규화 목적함수의 최적해는 이고 최적값은 다. 를 계산할 수 없어서 RL이나 근사가 필요하다.
- β는 KL의 가격이다. 보상–KL 곡선의 기울기가 β이고, 보상 스케일과 β는 로만 묶여 들어간다.
- 시퀀스 KL은 토큰 log-ratio의 합으로 추정한다. k1은 불편·고분산, k2는 저분산·편향, k3는 불편·비음수·대개 저분산이다.
- KL을 보상에 넣으면(stop-gradient, k1) 올바른 gradient가 나오고 미래 토큰의 KL까지 credit이 간다. 손실에 넣어 미분하면 k1은 0, k3는 순방향 KL의 gradient가 된다.
- PPO for LMs = 토큰 MDP + EOS 보상 + 토큰별 KL + 가치모델·GAE + advantage whitening + clipped surrogate. 보상·KL·길이·엔트로피를 함께 본다.
더 읽을거리Further reading
- Lambert, RLHF Book, Ch. 6 Reinforcement Learning (rlhfbook.com) — PPO·GRPO·RLOO에서 KL을 어디에 넣는지, 가치함수 초기화, whitening 등 실전 세부.Practical details: where the KL goes in PPO, GRPO and RLOO, value-function initialisation, whitening, and more.
- Schulman, Approximating KL Divergence (blog, 2020) — k1·k2·k3 추정량의 원전. 한 페이지짜리지만 RLHF 코드 대부분이 여기에 기댄다.The original source of the k1, k2 and k3 estimators. Only a page long, yet most RLHF code relies on it.
- Ziegler et al., Fine-Tuning Language Models from Human Preferences (2019) — 보상에 KL 패널티를 넣는 형식과 목표 KL에 맞추는 적응형 β.The format of putting a KL penalty in the reward, and an adaptive β that tracks a target KL.
- Ouyang et al., Training Language Models to Follow Instructions with Human Feedback (NeurIPS 2022) — InstructGPT의 PPO 목적함수(토큰별 KL, PPO-ptx).InstructGPT's PPO objective (per-token KL, PPO-ptx).
- Stiennon et al., Learning to Summarize from Human Feedback (NeurIPS 2020) — RM + PPO + KL의 구체적 구현과 과최적화 관찰.A concrete implementation of RM + PPO + KL, and observations of over-optimisation.
- Schulman et al., Proximal Policy Optimization Algorithms (2017) — clipped surrogate 목적함수.The clipped surrogate objective.
- Huang et al., The N+ Implementation Details of RLHF with PPO: A Case Study on TL;DR Summarization (2024) — OpenAI의 초기 RLHF 코드를 재현하며 정리한 구현 세부 목록.A list of implementation details compiled while reproducing OpenAI's early RLHF code.