Track V · RL for LLMs & Agents · 03/10

KL 정규화 RL과 PPO for LMsKL-regularised RL and PPO for LMs

KL 정규화 목적함수의 닫힌 해 π* ∝ π_ref·exp(r/β)를 유도하고 β의 의미를 설명할 수 있다. KL을 보상에 넣을 때와 손실에 넣을 때의 차이, k1·k2·k3 추정량의 편향·분산, 그리고 LLM용 PPO의 구성 요소와 진단 지표를 안다.Derive the closed-form solution π* ∝ π_ref·exp(r/β) of the KL-regularised objective and explain what β means. Know the difference between putting the KL in the reward and putting it in the loss, the bias and variance of the k1, k2 and k3 estimators, and the components and diagnostics of PPO for LLMs.

45 분min rlhf · kl divergence · ppo · kl estimator · gae · value function 먼저 볼 것:Before this: 보상모델Reward models, Trust region에서 PPO까지From trust regions to PPO, Actor-critic과 GAEActor-critic and GAE, 확률로 보는 손실Losses through probability

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, rϕr_\phi 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.

J(π)=Ex∼D, y∼π(⋅∣x)[r(x,y)]−β DKL(π(⋅∣x) ∥ πref(⋅∣x))J(\pi) = \mathbb{E}_{x\sim\mathcal{D},\,y\sim\pi(\cdot\mid x)}\big[r(x,y)\big] - \beta\,\mathbb{D}_{\text{KL}}\big(\pi(\cdot\mid x)\,\|\,\pi_{\text{ref}}(\cdot\mid x)\big)

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 xx and let π(y)\pi(y) be any distribution over responses (forget the neural-network parameterisation for a moment). Expand the KL and combine everything into one expectation.

J(π)=∑yπ(y)[r(y)−βlog⁡π(y)πref(y)]=−β∑yπ(y)log⁡π(y)πref(y) er(y)/βJ(\pi) = \sum_y \pi(y)\Big[r(y) - \beta \log\frac{\pi(y)}{\pi_{\text{ref}}(y)}\Big] = -\beta \sum_y \pi(y)\log\frac{\pi(y)}{\pi_{\text{ref}}(y)\,e^{r(y)/\beta}}

The denominator πref(y)er(y)/β\pi_{\text{ref}}(y)e^{r(y)/\beta} does not sum to 1, so we define a distribution by dividing by the normalising constant Z=∑yπref(y) er(y)/βZ = \sum_y \pi_{\text{ref}}(y)\,e^{r(y)/\beta}.

π∗(y)=1Z πref(y) exp⁡ ⁣(r(y)β)\pi^*(y) = \frac{1}{Z}\,\pi_{\text{ref}}(y)\,\exp\!\Big(\frac{r(y)}{\beta}\Big)

Then πrefer/β=Zπ∗\pi_{\text{ref}}e^{r/\beta} = Z\pi^*, so

J(π)=−β∑yπ(y)log⁡π(y)π∗(y)+βlog⁡Z=−β DKL(π ∥ π∗)+βlog⁡ZJ(\pi) = -\beta \sum_y \pi(y)\log\frac{\pi(y)}{\pi^*(y)} + \beta\log Z = -\beta\,\mathbb{D}_{\text{KL}}(\pi\,\|\,\pi^*) + \beta\log Z

βlog⁡Z\beta\log Z does not depend on π\pi, and the KL is non-negative and zero only when π=π∗\pi = \pi^*. Therefore π∗\pi^* is the unique optimum, with optimal value J(π∗)=βlog⁡Z(x)J(\pi^*) = \beta\log Z(x). Several things follow immediately from this one-line derivation.

  • β → ∞: er/β→1e^{r/\beta} \to 1, so π∗→πref\pi^* \to \pi_{\text{ref}}. Nothing moves.
  • β → 0: all the mass piles onto the highest-reward response (ties are split in proportion to πref\pi_{\text{ref}}). Pure reward maximisation.
  • π∗\pi^* never leaves the support of πref\pi_{\text{ref}}. If πref(y)=0\pi_{\text{ref}}(y)=0, then π∗(y)=0\pi^*(y)=0 no matter how large the reward. Responses the reference policy almost never produces are almost never produced.
  • The reward and β enter only as r/βr/\beta. Doubling the reward is the same as halving β.
  • This is a Boltzmann distribution (energy −r-r, temperature β\beta), and βlog⁡Z\beta\log Z corresponds to the free energy.

So why not just use this formula? Z(x)Z(x) is a sum over all possible response sequences, so it cannot be computed, and there is no way to sample from π∗\pi^* 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 π∗\pi^*.

보상모델이 생겼으니 이제 정책이 그 보상을 높이도록 학습시킬 차례다. 하지만 앞 레슨에서 본 것처럼 rϕr_\phi는 대리 목표이고, 그것만 최대화하면 RM의 허점을 파고든다. 그래서 RLHF의 목적함수는 처음부터 KL 항을 달고 나왔다.

J(π)=Ex∼D, y∼π(⋅∣x)[r(x,y)]−β DKL(π(⋅∣x) ∥ πref(⋅∣x))J(\pi) = \mathbb{E}_{x\sim\mathcal{D},\,y\sim\pi(\cdot\mid x)}\big[r(x,y)\big] - \beta\,\mathbb{D}_{\text{KL}}\big(\pi(\cdot\mid x)\,\|\,\pi_{\text{ref}}(\cdot\mid x)\big)

이 레슨은 세 부분이다. 먼저 이 목적함수의 정확한 최적해를 구한다. 그 해가 이 트랙의 나머지(rejection sampling, DPO)를 묶는 중심이다. 다음으로 실제 학습에서 KL을 어떻게 추정하고 어디에 넣는지 본다. 마지막으로 이것을 최적화하는 PPO의 LLM 버전을 조립한다.

닫힌 해: 기준 정책을 보상으로 기울이기

prompt xx를 하나 고정하고 π(y)\pi(y)를 응답 위의 아무 분포라고 하자(신경망 parameterization은 잠시 잊는다). KL을 풀어 쓰고 한 기댓값으로 묶는다.

J(π)=∑yπ(y)[r(y)−βlog⁡π(y)πref(y)]=−β∑yπ(y)log⁡π(y)πref(y) er(y)/βJ(\pi) = \sum_y \pi(y)\Big[r(y) - \beta \log\frac{\pi(y)}{\pi_{\text{ref}}(y)}\Big] = -\beta \sum_y \pi(y)\log\frac{\pi(y)}{\pi_{\text{ref}}(y)\,e^{r(y)/\beta}}

분모 πref(y)er(y)/β\pi_{\text{ref}}(y)e^{r(y)/\beta}는 합이 1이 아니므로 정규화 상수 Z=∑yπref(y) er(y)/βZ = \sum_y \pi_{\text{ref}}(y)\,e^{r(y)/\beta}로 나눈 분포를 정의한다.

π∗(y)=1Z πref(y) exp⁡ ⁣(r(y)β)\pi^*(y) = \frac{1}{Z}\,\pi_{\text{ref}}(y)\,\exp\!\Big(\frac{r(y)}{\beta}\Big)

그러면 πrefer/β=Zπ∗\pi_{\text{ref}}e^{r/\beta} = Z\pi^*이므로

J(π)=−β∑yπ(y)log⁡π(y)π∗(y)+βlog⁡Z=−β DKL(π ∥ π∗)+βlog⁡ZJ(\pi) = -\beta \sum_y \pi(y)\log\frac{\pi(y)}{\pi^*(y)} + \beta\log Z = -\beta\,\mathbb{D}_{\text{KL}}(\pi\,\|\,\pi^*) + \beta\log Z

βlog⁡Z\beta\log Z는 π\pi와 무관하고 KL은 0 이상이며 π=π∗\pi = \pi^*일 때만 0이다. 따라서 π∗\pi^*가 유일한 최적해이고 최적값은 J(π∗)=βlog⁡Z(x)J(\pi^*) = \beta\log Z(x) 다. 이 한 줄짜리 유도에서 몇 가지가 바로 나온다.

  • β → ∞: er/β→1e^{r/\beta} \to 1이므로 π∗→πref\pi^* \to \pi_{\text{ref}}. 움직이지 않는다.
  • β → 0: 보상이 가장 큰 응답에 모든 질량이 몰린다(동점이면 πref\pi_{\text{ref}} 비율로 나눈다). 순수 보상 최대화.
  • π∗\pi^*는 πref\pi_{\text{ref}}의 지지집합(support) 밖으로 나가지 않는다. πref(y)=0\pi_{\text{ref}}(y)=0이면 보상이 아무리 커도 π∗(y)=0\pi^*(y)=0이다. 기준 정책이 거의 내지 않는 응답은 거의 내지 않는다.
  • 보상과 β는 r/βr/\beta로만 들어간다. 보상을 2배 하는 것과 β를 절반으로 하는 것은 같다.
  • 이것은 볼츠만 분포(에너지 −r-r, 온도 β\beta)이고, βlog⁡Z\beta\log Z는 자유 에너지에 해당한다.

그런데 왜 그냥 이 공식을 쓰지 않을까? Z(x)Z(x)는 가능한 모든 응답 시퀀스에 대한 합이라 계산할 수 없고, π∗\pi^*에서 직접 샘플링할 방법도 없다. RL(PPO), 샘플링 근사(best-of-N, 다음 레슨), 선호 데이터에서 직접 맞추기(DPO, 레슨 5)는 모두 이 계산할 수 없는 π∗\pi^*에 다가가는 서로 다른 방법이다.

Eπ*[r] – KL(π*‖πref) – J(π*) = β log Z – Eπref[r] –
Drag the reward bars at top left up and down to change the rewards, and move β. The grey outlines below are πref; the violet bars are π* = πref·exp(r/β)/Z. With large β, π* sticks to πref; as β shrinks, mass piles onto the high-reward responses. The curve on the right traces (KL, expected reward) as β sweeps — no policy can get above this curve. Raise the reward of a response πref almost never gives (H), and getting to it costs a lot of KL. 왼쪽 위 보상 막대를 위아래로 끌어 보상을 바꾸고, β를 움직여 보자. 아래쪽 회색 테두리는 πref, 보라색은 π* = πref·exp(r/β)/Z. β가 크면 π*는 πref에 붙어 있고, β가 작아질수록 보상이 큰 응답으로 질량이 몰린다. 오른쪽 곡선은 β를 훑을 때의 (KL, 기대 보상) — 어떤 정책도 이 곡선 위로는 갈 수 없다. πref가 거의 주지 않는 응답(H)의 보상을 키우면, 그 응답으로 가는 데 KL이 많이 든다.

What to check in the figure:

  1. 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.
  2. The curve on the right is concave, and the slope of the tangent at the current point is exactly β. The contours of J=E[r]−β KLJ = \mathbb{E}[r] - \beta\,\text{KL} are straight lines of slope β, so π* is the point where such a line touches the curve.
  3. Press Inflate one reward and the reward of H, which πref\pi_{\text{ref}} 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.
NumPy Compute π* and check against random perturbations that it really is optimal
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)
 

J(π∗)=βlog⁡ZJ(\pi^*) = \beta\log Z checks out numerically, and none of the 2000 perturbations beats π∗\pi^*. At β = 0.5, π∗\pi^* moves mass to D and F, which have high rewards. B’s reward is less than half of F’s, but because πref\pi_{\text{ref}} 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, π(y∣x)=∏tπ(yt∣x,y<t)\pi(y\mid x) = \prod_t \pi(y_t \mid x, y_{<t}), so the log splits into a sum.

DKL(πθ(⋅∣x) ∥ πref(⋅∣x))=Ey∼πθ[∑t=1Tlog⁡πθ(yt∣st)πref(yt∣st)],st=(x,y<t)\mathbb{D}_{\text{KL}}\big(\pi_\theta(\cdot|x)\,\|\,\pi_{\text{ref}}(\cdot|x)\big) = \mathbb{E}_{y\sim\pi_\theta}\Big[\sum_{t=1}^{T} \log\frac{\pi_\theta(y_t\mid s_t)}{\pi_{\text{ref}}(y_t\mid s_t)}\Big], \qquad s_t = (x, y_{<t})

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 y∼πθy \sim \pi_\theta and the ratio r=πref(y)/πθ(y)r = \pi_{\text{ref}}(y)/\pi_\theta(y), there are three estimators, as summarised by Schulman (2020). The target is KL(πθ∥πref)=Eπθ[−log⁡r]\text{KL}(\pi_\theta\|\pi_{\text{ref}}) = \mathbb{E}_{\pi_\theta}[-\log r].

EstimatorFormulaExpectationProperties
k1−log⁡r-\log rKL (unbiased)can be negative per sample; high variance
k212(log⁡r)2\tfrac12(\log r)^2matches KL to second order (biased)always ≥ 0, low variance; bias grows when the distributions are far apart
k3(r−1)−log⁡r(r - 1) - \log rKL (unbiased)always ≥ 0, usually low variance

That k3 is unbiased takes one line. Eπθ[r]=∑yπθ(y)πref(y)πθ(y)=1\mathbb{E}_{\pi_\theta}[r] = \sum_y \pi_\theta(y)\frac{\pi_{\text{ref}}(y)}{\pi_\theta(y)} = 1, so E[r−1]=0\mathbb{E}[r - 1] = 0, and k3 is k1 plus a zero-mean control variate r−1r - 1. And since log⁡r≤r−1\log r \le r - 1, k3≥0k3 \ge 0 for every sample. k2 estimates the f-divergence with f(u)=12(log⁡u)2f(u) = \tfrac12(\log u)^2, and when πθ≈πref\pi_\theta \approx \pi_{\text{ref}} that f-divergence agrees with the KL to second order, so the bias is small.

그림에서 확인할 것:

  1. β를 오른쪽 끝(β = 10)으로 밀면 보라색 막대가 회색 테두리와 겹친다. 왼쪽 끝(β ≈ 0.02)으로 밀면 보상이 가장 큰 F에 질량이 몰린다.
  2. 오른쪽 곡선은 오목하고, 현재 점에서의 접선 기울기가 정확히 β다. J=E[r]−β KLJ = \mathbb{E}[r] - \beta\,\text{KL}의 등고선이 기울기 β인 직선이므로, π*는 그 직선이 곡선에 접하는 점이다.
  3. “보상 하나만 크게”를 누르면 πref\pi_{\text{ref}}가 약 1%만 주는 H의 보상이 3.5가 된다. 작은 β에서는 H로 질량이 가지만, 곡선을 보면 그만큼 KL을 많이 쓴다. RM이 드문 응답 하나를 과대평가하는 것이 reward hacking의 가장 단순한 모형이다.
NumPy π*를 계산하고, 정말 최적인지 무작위 섭동과 비교
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)
 

J(π∗)=βlog⁡ZJ(\pi^*) = \beta\log Z가 숫자로 맞고, 2000개의 섭동 중 어느 것도 π∗\pi^*를 이기지 못한다. β = 0.5에서 π∗\pi^*는 보상이 높은 D와 F로 질량을 옮긴다. B는 보상이 F의 절반도 안 되지만 πref\pi_{\text{ref}}가 크게 주던 응답이라 15% 정도를 유지한다. 보상만이 아니라 기준 확률과의 곱이 결과를 정한다.

시퀀스의 KL은 토큰 KL의 합이다

LLM에서 π(y∣x)=∏tπ(yt∣x,y<t)\pi(y\mid x) = \prod_t \pi(y_t \mid x, y_{<t})이므로 로그가 합으로 풀린다.

DKL(πθ(⋅∣x) ∥ πref(⋅∣x))=Ey∼πθ[∑t=1Tlog⁡πθ(yt∣st)πref(yt∣st)],st=(x,y<t)\mathbb{D}_{\text{KL}}\big(\pi_\theta(\cdot|x)\,\|\,\pi_{\text{ref}}(\cdot|x)\big) = \mathbb{E}_{y\sim\pi_\theta}\Big[\sum_{t=1}^{T} \log\frac{\pi_\theta(y_t\mid s_t)}{\pi_{\text{ref}}(y_t\mid s_t)}\Big], \qquad s_t = (x, y_{<t})

전체 시퀀스 공간의 KL을 직접 계산할 수는 없지만, 정책에서 뽑은 응답 하나로 이 합을 계산하면 KL의 불편(unbiased) 추정치가 된다. 각 위치의 어휘 전체에 대한 KL을 정확히 계산하는 구현도 있지만(어휘 크기만큼의 비용), 대부분은 샘플된 토큰의 log-ratio만 쓴다. 여기서 “어떤 추정량을 쓰나”와 “그것을 어디에 넣나”라는 두 질문이 생긴다.

KL 추정량: k1, k2, k3

샘플 y∼πθy \sim \pi_\theta와 비율 r=πref(y)/πθ(y)r = \pi_{\text{ref}}(y)/\pi_\theta(y)에 대해 Schulman(2020)이 정리한 세 가지 추정량이 있다. 목표는 KL(πθ∥πref)=Eπθ[−log⁡r]\text{KL}(\pi_\theta\|\pi_{\text{ref}}) = \mathbb{E}_{\pi_\theta}[-\log r]이다.

추정량식기댓값성질
k1−log⁡r-\log rKL (불편)샘플마다 음수일 수 있다. 분산이 크다
k212(log⁡r)2\tfrac12(\log r)^2KL과 2차까지 일치 (편향)항상 0 이상, 분산이 작다. 두 분포가 멀면 편향이 커진다
k3(r−1)−log⁡r(r - 1) - \log rKL (불편)항상 0 이상, 대개 분산이 작다

k3가 불편이라는 것은 한 줄로 보인다. Eπθ[r]=∑yπθ(y)πref(y)πθ(y)=1\mathbb{E}_{\pi_\theta}[r] = \sum_y \pi_\theta(y)\frac{\pi_{\text{ref}}(y)}{\pi_\theta(y)} = 1이므로 E[r−1]=0\mathbb{E}[r - 1] = 0이고, k3는 k1에 기댓값 0인 control variate r−1r - 1을 더한 것이다. 그리고 log⁡r≤r−1\log r \le r - 1이므로 모든 샘플에서 k3≥0k3 \ge 0이다. k2는 f(u)=12(log⁡u)2f(u) = \tfrac12(\log u)^2인 f-divergence의 추정량인데, πθ≈πref\pi_\theta \approx \pi_{\text{ref}}일 때 이 f-divergence가 KL과 2차까지 같아서 편향이 작다.

Draw N samples from πθ = N(0, 1) and estimate KL(πθ‖πref), repeated 500 times. The histograms on the right show the distribution of those 500 estimates; the black vertical line is the true KL. Raise μ and k2 is pushed to the right of the true value (bias). Set N to 1 and k1 spreads widely, even into negative values, while k3 is always ≥ 0. Raise σ so πref becomes wider, and r = πref/πθ grows in the tails, increasing k3's variance. πθ = N(0, 1)에서 N개를 뽑아 KL(πθ‖πref)를 추정하는 일을 500번 반복했다. 오른쪽 히스토그램은 그 500개 추정치의 분포, 검은 세로선은 진짜 KL. μ를 키우면 k2가 진짜 값보다 오른쪽으로 밀린다(편향). N을 1로 두면 k1이 음수까지 넓게 퍼지는 반면 k3는 항상 0 이상이다. σ를 키워 πref가 더 넓어지면 r = πref/πθ가 꼬리에서 커져 k3의 분산이 커진다.
  1. 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.
  2. Raise μ to 2 or more and k2’s mean line drifts to the right of the black true-KL line.
  3. Raise σ to 1.5 or more and k3’s distribution grows a long right tail. When πref\pi_{\text{ref}} is wider, rr becomes very large on tail samples of πθ\pi_\theta.
NumPy Monte Carlo comparison of k1 / k2 / k3
# 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.

r~t=−β log⁡πθ(yt∣st)πref(yt∣st)+1[t=T]  rϕ(x,y)\tilde r_t = -\beta\,\log\frac{\pi_\theta(y_t\mid s_t)}{\pi_{\text{ref}}(y_t\mid s_t)} + \mathbb{1}[t = T]\; r_\phi(x, y)

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. ∇θEπθ[log⁡πθπref]=E[log⁡πθπref ∇log⁡πθ]+E[∇log⁡πθ]\nabla_\theta \mathbb{E}_{\pi_\theta}[\log\frac{\pi_\theta}{\pi_{\text{ref}}}] = \mathbb{E}[\log\frac{\pi_\theta}{\pi_{\text{ref}}}\,\nabla\log\pi_\theta] + \mathbb{E}[\nabla\log\pi_\theta], 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.

L=LPG+β 1T∑t(πref(yt∣st)πθ(yt∣st)−1−log⁡πref(yt∣st)πθ(yt∣st))\mathcal{L} = \mathcal{L}_{\text{PG}} + \beta\,\frac{1}{T}\sum_t \Big(\frac{\pi_{\text{ref}}(y_t|s_t)}{\pi_\theta(y_t|s_t)} - 1 - \log\frac{\pi_{\text{ref}}(y_t|s_t)}{\pi_\theta(y_t|s_t)}\Big)

It looks simple, but there is a subtlety. Estimating the value well and estimating the gradient well are different things. Fix a sample y∼πθy\sim\pi_\theta, differentiate each estimator with respect to θ\theta, and take the expectation.

E[∇θk1]=E[∇log⁡πθ]=0E[∇θk2]=E[log⁡πθπref ∇log⁡πθ]=∇θ KL(πθ∥πref)E[∇θk3]=E[(1−πrefπθ)∇log⁡πθ]=−∑yπref∇log⁡πθ=∇θ KL(πref∥πθ)\begin{aligned} \mathbb{E}\big[\nabla_\theta k_1\big] &= \mathbb{E}[\nabla\log\pi_\theta] = 0 \\ \mathbb{E}\big[\nabla_\theta k_2\big] &= \mathbb{E}\Big[\log\tfrac{\pi_\theta}{\pi_{\text{ref}}}\,\nabla\log\pi_\theta\Big] = \nabla_\theta\,\text{KL}(\pi_\theta\|\pi_{\text{ref}}) \\ \mathbb{E}\big[\nabla_\theta k_3\big] &= \mathbb{E}\Big[\big(1 - \tfrac{\pi_{\text{ref}}}{\pi_\theta}\big)\nabla\log\pi_\theta\Big] = -\sum_y \pi_{\text{ref}}\nabla\log\pi_\theta = \nabla_\theta\,\text{KL}(\pi_{\text{ref}}\|\pi_\theta) \end{aligned}

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 KL(πref∥πθ)\text{KL}(\pi_{\text{ref}}\|\pi_\theta) (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.

NumPy Differentiating the estimators as losses: checking the expected gradient (softmax policy)
# 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.

확인 문제Check yourself

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?

∇θk2=log⁡πθπref∇log⁡πθ\nabla_\theta k_2 = \log\frac{\pi_\theta}{\pi_{\text{ref}}}\nabla\log\pi_\theta, and its expectation is exactly ∇ KL(πθ∥πref)\nabla\,\text{KL}(\pi_\theta\|\pi_{\text{ref}}). 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 KL(πref∥πθ)\text{KL}(\pi_{\text{ref}}\|\pi_\theta). 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 st=(x,y<t)s_t = (x, y_{<t}), action at=yta_t = y_t (one token of the vocabulary), and a deterministic transition (append the token).
  • Reward is r~t\tilde r_t above: −β⋅-\beta\cdot(log-ratio) at every token, plus rϕ(x,y)r_\phi(x,y) at the last token (EOS). The discount is usually γ=1\gamma = 1.
  • 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.

ModelRoleTrained?
Policy πθ\pi_\thetagenerates responses; the thing being trainedyes
Reference πref\pi_{\text{ref}}KL computation (usually the SFT model)no
Reward model rϕr_\phiscore at the end of the responseno
Value model VψV_\psiexpected return per token; advantage computationyes (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.

PyTorch PyTorch: the core computations of PPO for LMs 로컬에서 실행run locally (pip install torch)
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 π∗(y∣x)=πref(y∣x) er(x,y)/β/Z(x)\pi^*(y|x) = \pi_{\text{ref}}(y|x)\,e^{r(x,y)/\beta}/Z(x), with optimal value βlog⁡Z(x)\beta\log Z(x). Because ZZ 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 r/βr/\beta.
  • 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.
  1. N = 1, μ = 0.5에서 k1의 히스토그램이 0 아래까지 넓게 퍼진다. 샘플 하나로 잰 “KL”이 음수가 나오는 것이 이것이다.
  2. μ를 2 이상으로 올리면 k2의 평균선이 검은 진짜 KL 선 오른쪽으로 벗어난다.
  3. σ를 1.5 이상으로 키우면 k3의 분포에 긴 오른쪽 꼬리가 생긴다. πref\pi_{\text{ref}}가 더 넓으면 πθ\pi_\theta의 꼬리 샘플에서 rr이 매우 커지기 때문이다.
NumPy k1 / k2 / 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 방식). 토큰마다 보상을 다음처럼 정의한다.

r~t=−β log⁡πθ(yt∣st)πref(yt∣st)+1[t=T]  rϕ(x,y)\tilde r_t = -\beta\,\log\frac{\pi_\theta(y_t\mid s_t)}{\pi_{\text{ref}}(y_t\mid s_t)} + \mathbb{1}[t = T]\; r_\phi(x, y)

k1을 토큰별 보상으로 넣은 것이고, 이 값은 상수로 취급된다(gradient를 흘리지 않는다). 그런데도 KL 항의 gradient가 맞게 나온다. ∇θEπθ[log⁡πθπref]=E[log⁡πθπref ∇log⁡πθ]+E[∇log⁡πθ]\nabla_\theta \mathbb{E}_{\pi_\theta}[\log\frac{\pi_\theta}{\pi_{\text{ref}}}] = \mathbb{E}[\log\frac{\pi_\theta}{\pi_{\text{ref}}}\,\nabla\log\pi_\theta] + \mathbb{E}[\nabla\log\pi_\theta]이고 두 번째 항은 0이므로, “KL을 보상으로 둔 policy gradient”가 곧 KL의 gradient다. 또 KL 패널티가 return에 합산되므로, 앞쪽 토큰은 뒤에서 생길 KL까지 advantage로 책임진다.

손실에 넣기 (GRPO 방식). policy gradient 손실과 별도로, 토큰마다의 추정량을 손실에 더하고 그대로 미분한다. GRPO의 표준 구현은 k3를 쓴다.

L=LPG+β 1T∑t(πref(yt∣st)πθ(yt∣st)−1−log⁡πref(yt∣st)πθ(yt∣st))\mathcal{L} = \mathcal{L}_{\text{PG}} + \beta\,\frac{1}{T}\sum_t \Big(\frac{\pi_{\text{ref}}(y_t|s_t)}{\pi_\theta(y_t|s_t)} - 1 - \log\frac{\pi_{\text{ref}}(y_t|s_t)}{\pi_\theta(y_t|s_t)}\Big)

간단해 보이지만 미묘한 점이 있다. 값을 잘 추정하는 것과 gradient를 잘 추정하는 것은 다르다. 샘플 y∼πθy\sim\pi_\theta를 고정하고 각 추정량을 θ\theta로 미분해 기댓값을 내 보자.

E[∇θk1]=E[∇log⁡πθ]=0E[∇θk2]=E[log⁡πθπref ∇log⁡πθ]=∇θ KL(πθ∥πref)E[∇θk3]=E[(1−πrefπθ)∇log⁡πθ]=−∑yπref∇log⁡πθ=∇θ KL(πref∥πθ)\begin{aligned} \mathbb{E}\big[\nabla_\theta k_1\big] &= \mathbb{E}[\nabla\log\pi_\theta] = 0 \\ \mathbb{E}\big[\nabla_\theta k_2\big] &= \mathbb{E}\Big[\log\tfrac{\pi_\theta}{\pi_{\text{ref}}}\,\nabla\log\pi_\theta\Big] = \nabla_\theta\,\text{KL}(\pi_\theta\|\pi_{\text{ref}}) \\ \mathbb{E}\big[\nabla_\theta k_3\big] &= \mathbb{E}\Big[\big(1 - \tfrac{\pi_{\text{ref}}}{\pi_\theta}\big)\nabla\log\pi_\theta\Big] = -\sum_y \pi_{\text{ref}}\nabla\log\pi_\theta = \nabla_\theta\,\text{KL}(\pi_{\text{ref}}\|\pi_\theta) \end{aligned}

값으로는 불편인 k1을 손실로 미분하면 기대 gradient가 0이 되고, k3를 손실로 미분하면 우리가 원한 역방향 KL이 아니라 순방향 KL KL(πref∥πθ)\text{KL}(\pi_{\text{ref}}\|\pi_\theta)의 gradient가 된다(on-policy, 토큰 하나 기준). 값으로는 편향인 k2가 오히려 역방향 KL의 정확한 gradient를 준다. 두 분포가 가까우면 순방향과 역방향 KL의 gradient가 거의 같아서 실전에서는 큰 문제가 아닐 때가 많지만, 정책이 멀리 움직이면 다른 정규화가 된다. 최근 여러 분석이 이 점을 지적했다.

NumPy 추정량을 손실로 미분하면: 기대 gradient 확인 (softmax 정책)
# 응답 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와 일치한다.

확인 문제Check yourself

GRPO식으로 KL 추정량을 손실에 더해 그대로 미분한다. on-policy 샘플에서 기대 gradient가 KL(π_θ‖π_ref)의 gradient와 정확히 같은 것은?

∇θk2=log⁡πθπref∇log⁡πθ\nabla_\theta k_2 = \log\frac{\pi_\theta}{\pi_{\text{ref}}}\nabla\log\pi_\theta이고 그 기댓값이 정확히 ∇ KL(πθ∥πref)\nabla\,\text{KL}(\pi_\theta\|\pi_{\text{ref}})다. k1과 k3는 값의 불편 추정량이지만, 손실로 미분하면 k1은 기대 gradient가 0, k3는 순방향 KL KL(πref∥πθ)\text{KL}(\pi_{\text{ref}}\|\pi_\theta)의 gradient가 된다. KL을 보상에 넣는 방식(stop-gradient 후 policy gradient)에서는 k1이 올바른 gradient를 준다. “추정량”을 말할 때는 값의 추정인지 gradient의 추정인지를 구분해야 한다.

→ 더 깊이: 정규화 — KL, 엔트로피, 길이에서 KL의 값 추정량과 gradient 추정량, 직전 정책에 묶는 방식(Kimi k1.5의 mirror descent), 그 옆에 놓이는 엔트로피·길이 정규화를 다룬다.

PPO for LMs: 조립하기

이제 PPO를 LLM에 맞춘다. MDP는 다음과 같다.

  • 상태 st=(x,y<t)s_t = (x, y_{<t}), 행동 at=yta_t = y_t (어휘 중 하나), 전이는 결정적(토큰을 이어 붙임).
  • 보상은 위의 r~t\tilde r_t: 매 토큰 −β⋅-\beta\cdot(log-ratio), 마지막 토큰(EOS)에 rϕ(x,y)r_\phi(x,y). 할인은 보통 γ=1\gamma = 1.
  • 에피소드 하나 = 응답 하나. 최대 길이에 도달해 EOS가 없으면 보상을 깎거나 버리는 처리가 흔하다.

메모리에는 모델 네 개가 올라간다.

모델역할학습?
정책 πθ\pi_\theta응답 생성, 학습 대상O
기준 πref\pi_{\text{ref}}KL 계산 (보통 SFT 모델)X
보상모델 rϕr_\phi응답 끝에서 점수X
가치모델 VψV_\psi토큰마다 기대 return, advantage 계산O (보통 RM에서 초기화)

한 iteration은 (1) prompt 배치로 응답을 생성하고, (2) 정책·기준·RM·가치모델로 토큰별 log-prob, 보상, 값을 계산하고, (3) GAE로 advantage를 구해 배치 전체에서 whitening(평균 0, 분산 1로 정규화)한 뒤, (4) 같은 rollout으로 몇 epoch 동안 clipped surrogate와 가치 손실을 최적화한다.

PyTorch PyTorch: PPO for LMs의 핵심 계산 로컬에서 실행run locally (pip install torch)
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 정규화 목적함수의 최적해는 π∗(y∣x)=πref(y∣x) er(x,y)/β/Z(x)\pi^*(y|x) = \pi_{\text{ref}}(y|x)\,e^{r(x,y)/\beta}/Z(x)이고 최적값은 βlog⁡Z(x)\beta\log Z(x)다. ZZ를 계산할 수 없어서 RL이나 근사가 필요하다.
  • β는 KL의 가격이다. 보상–KL 곡선의 기울기가 β이고, 보상 스케일과 β는 r/βr/\beta로만 묶여 들어간다.
  • 시퀀스 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