The policy gradients so far collected a batch, computed one gradient from it, and threw it away. The batch came from the policy of that moment, so after a single step it is no longer the updated policy’s “own data”. But data is expensive. In LLM RL, generating responses (rollouts) often takes much longer than a training step. We want to update several times on one batch, and at the same time we want no single update to wreck the policy. This lesson derives the methods that satisfy both demands together: TRPO and PPO.
Why large steps are dangerous
In supervised learning, a learning rate that is too large makes the loss spike. But the data stays the same, so the next step can recover. In RL the policy produces its own data. If one bad update collapses the policy, the data collected afterwards also comes from the collapsed policy, and the information needed to recover is gone (recall the runs in Lesson 3’s no-baseline experiment that locked onto the wrong sequence).
On top of that, the learning rate is a distance in parameter space, not in policy space. In a softmax policy, moving a logit by 0.5 changes the probabilities a little when the logits are similar, but changes almost nothing when one logit is already large. With a neural-network policy this relationship differs from parameter to parameter and from state to state. The natural way to measure distance in policy space is the KL divergence, and its second-order approximation is the Fisher information matrix .
The steepest ascent direction under the constraint “the policy may not change by more than δ in KL” is the natural gradient , and TRPO is a practical version of this idea.
Importance sampling: estimating the gradient from someone else’s data
The batch came from , and we want to evaluate . Changing only the action distribution in the same state can be corrected with importance sampling.
From this we build the surrogate objective. The state distribution is kept as that of .
At we have , so — exactly the policy gradient. The surrogate is an approximation that agrees with to first order at , and it is a “loss” we can optimise for several steps.
How far can we trust it, then? The performance difference lemma of Kakade & Langford (2002) gives the first clue.
The new policy’s gain is the old policy’s advantage summed over the states the new policy visits. The surrogate swaps “the states visits” in this formula for “the states visits”, and the swap is justified only when the two policies are close. The TRPO paper quantified this and proved a lower bound.
Here .
Maximising the right-hand side makes increase monotonically (minorize–maximize). The theoretical is so large that the steps become tiny, so practical TRPO turns the penalty into a constraint.
It is solved with the natural-gradient direction (computed with Fisher-vector products and conjugate gradient) and a line search. It works well, but it is complicated to implement, needs second-order information, and does not get along with architectures where the policy and value function share parameters, or with noise such as dropout.
PPO: imitating a trust region with a clip
PPO (Schulman et al., 2017) puts the constraint inside the objective. The idea is “do not credit any gain obtained by the ratio leaving ”.
Because of the min we have to split into cases. Call the term for one sample .
(a good action). The term is . If , then or they are equal, so and the gradient stays alive. If , then is a constant: zero gradient. The objective wants to raise the probability of a good action, but only up to a factor of . Conversely, if — the good action’s probability has actually dropped a lot — then , so the min picks the unclipped term and the live gradient pushes it back.
(a bad action). With , . If , then is a constant: zero gradient. The objective wants to lower the bad action’s probability, but only down to a factor of . If instead — the bad action’s probability has actually grown — then , so nothing is clipped and the sample is penalised in full.
In short, the clip switches off the gradient only for samples that have moved far in the direction that improves the objective. Changes in the direction that makes it worse are always counted in full. That is why (the IS surrogate) is a pessimistic lower bound, and the two coincide near .
지금까지의 정책 경사는 배치 하나를 모으면 기울기를 한 번 계산하고 버렸다. 그 배치는 그 순간의 정책 에서 나온 것이라, 한 step 움직인 뒤의 정책에 대해서는 더 이상 “자기 데이터”가 아니기 때문이다. 그런데 데이터는 비싸다. LLM RL에서는 응답 생성(rollout)이 학습 step보다 훨씬 오래 걸리는 경우가 흔하다. 한 배치로 여러 번 업데이트하고 싶고, 동시에 한 번의 업데이트가 정책을 망가뜨리지 않기를 바란다. 이 레슨은 그 두 요구를 함께 만족시키는 방법, TRPO 와 PPO 를 유도한다.
왜 큰 step이 위험한가
지도학습에서 학습률이 너무 크면 손실이 튄다. 그래도 데이터는 그대로라 다음 step에서 회복할 수 있다. RL에서는 정책이 자기 데이터를 만든다. 한 번의 나쁜 업데이트로 정책이 무너지면 이후 모이는 데이터도 무너진 정책의 것이고, 회복할 정보가 사라진다(3강 baseline 없는 실험에서 틀린 시퀀스로 굳어 버린 실행들을 떠올리자).
게다가 학습률은 매개변수 공간 의 거리이지 정책 공간 의 거리가 아니다. softmax 정책에서 로짓을 0.5 움직이는 것은, 로짓들이 비슷할 때는 확률을 조금 바꾸지만 한 로짓이 이미 크면 거의 아무것도 바꾸지 않는다. 신경망 정책이면 이 관계가 매개변수마다, 상태마다 다르다. 정책 공간에서 거리를 재는 자연스러운 방법은 KL divergence이고, 그 2차 근사가 Fisher 정보 행렬 다.
“정책이 KL로 δ 이상 변하지 않게” 제약한 가장 가파른 상승 방향이 natural gradient 이고, TRPO는 이 아이디어를 실용화한 것이다.
Importance sampling: 남의 데이터로 기울기 추정하기
배치는 에서 나왔고 우리는 를 평가하고 싶다. 같은 상태에서 행동 분포만 바꾸는 것은 importance sampling으로 보정할 수 있다.
이것으로 surrogate 목적함수 를 만든다. 상태 분포는 의 것을 그대로 쓴다.
에서 이므로 , 정확히 정책 경사 다. surrogate는 에서 와 1차까지 일치하는 근사이고, 여러 step 최적화할 수 있는 “손실”이다.
그러면 얼마나 멀리까지 믿을 수 있을까? Kakade & Langford(2002)의 performance difference lemma 가 답의 실마리다.
새 정책의 이득은 새 정책이 방문하는 상태에서 옛 정책의 advantage를 합한 것이다. surrogate는 이 식의 “이 방문하는 상태”를 “가 방문하는 상태”로 바꿔치기한 것이고, 두 정책이 가까울 때만 그 바꿔치기가 정당하다. TRPO 논문은 이를 정량화해 하한을 증명했다.
여기서 이다.
오른쪽을 최대화하면 가 단조 증가한다(minorize–maximize). 이론대로의 는 너무 커서 step이 아주 작아지므로, 실제 TRPO 는 페널티 대신 제약으로 바꾼다.
이것을 natural gradient 방향(Fisher-vector product와 conjugate gradient로 계산)과 line search로 푼다. 잘 작동하지만 구현이 복잡하고, 2차 정보가 필요하며, 정책과 가치함수가 매개변수를 공유하는 구조나 dropout 같은 잡음과 궁합이 나쁘다.
PPO: clip으로 trust region 흉내 내기
PPO(Schulman et al., 2017)는 제약을 목적함수 안에 넣는다. 아이디어는 “ratio가 를 벗어나서 얻는 이득은 인정하지 않는다”이다.
min 때문에 경우를 나눠야 한다. 한 샘플의 항을 라 하자.
(좋은 행동). 이다. 이면 또는 같으므로 , 기울기는 그대로 살아 있다. 이면 로 상수, 기울기 0. 좋은 행동의 확률을 올리되 배까지만 올리고 싶어 한다. 반대로 , 즉 좋은 행동의 확률이 오히려 크게 줄어든 경우에는 이므로 min이 unclipped 항을 고르고, 기울기가 살아서 되돌린다.
(나쁜 행동). 이면 다. 이면 , 상수, 기울기 0. 나쁜 행동의 확률은 배까지만 낮추고 싶어 한다. 하지만 , 나쁜 행동의 확률이 오히려 늘어난 경우는 라서 clip되지 않고 그대로 벌을 받는다.
정리하면 clip은 목적함수가 좋아지는 방향으로 멀리 간 샘플에서만 기울기를 끈다. 나빠지는 방향의 변화는 언제나 전부 반영한다. 그래서 (IS surrogate)인 비관적 하한이고, 근처에서는 둘이 같다.
Written in one line, the gradient for each sample is
Let us also be clear about what the clip does not do. The clip does not confine the ratio to . The probabilities of samples whose gradient has been switched off still move along with the updates from other samples (through softmax normalisation and shared parameters). So the actual ratio often leaves this interval (Engstrom et al., 2020), and in practice the KL is monitored separately.
ε = 0.2. A token has advantage  = −1, and after a few updates its ratio has become ρ = 1.5. What is the PPO-clip gradient of this token's term?
With the term is . At , picks the unclipped term, so the gradient stays alive and gradient ascent lowers . The clip switches off the gradient only when a sample has gone “too far in the direction that favours the objective”. Departures in the unfavourable direction are always corrected.
That unclipped branch has no ceiling: a token whose ratio has grown to 10 still contributes . Dual-clip PPO (Ye et al., 2020) caps it at (with ), which matters once data is noticeably off-policy, as in LLM RL. → Go deeper: Clipping and importance sampling compares PPO clip, dual-clip, clip-higher, CISPO and the newer rules as one gradient-weight function of and the sign of .
In a picture: many epochs on the same batch
Let us see directly the problem PPO is trying to solve. Below, on a 5-armed bandit, we draw a batch only once and maximise the surrogate on that batch over and over.
기울기를 한 줄로 쓰면, 샘플마다
clip이 하지 않는 일도 분명히 해 두자. clip은 ratio를 안에 가두지 않는다. 기울기가 꺼진 샘플의 확률도 다른 샘플의 업데이트를 따라 움직인다(softmax의 정규화, 공유된 매개변수). 그래서 실제 ratio는 이 구간을 벗어나곤 하고(Engstrom et al., 2020), 실무에서는 KL을 따로 감시한다.
ε = 0.2, 어떤 토큰의 advantage가 Â = −1이고 몇 번의 업데이트 뒤 ratio가 ρ = 1.5가 되었다. 이 토큰 항의 PPO-clip 기울기는?
이면 항은 이다. 에서 로 unclipped 항이 선택되므로 기울기 가 그대로 살아 있고, 경사 상승은 를 줄인다. clip은 “목적함수에 유리한 방향으로 너무 멀리 간 경우”에만 기울기를 끈다. 불리한 방향의 이탈은 항상 교정된다.
이 clip되지 않는 가지에는 천장이 없다. ratio가 10까지 커진 토큰도 를 그대로 보탠다. Dual-clip PPO(Ye et al., 2020)는 이를 ()로 막는데, LLM RL처럼 데이터가 눈에 띄게 off-policy일 때 중요해진다. → 더 깊이: Clipping과 importance sampling에서 PPO clip, dual-clip, clip-higher, CISPO와 이후 규칙들을 와 부호의 함수인 gradient 가중치 하나로 비교한다.
그림으로: 같은 배치로 여러 epoch
PPO가 해결하려는 문제를 직접 보자. 아래는 팔 5개짜리 bandit에서 배치를 한 번만 뽑고, 그 배치로 surrogate를 반복해서 최대화한다.
Without the clip, the IS surrogate is linear in the policy for this batch. Since , maximising it indefinitely piles all the probability onto the single arm with the largest bracketed value. That bracket is just an average of a few samples. Evaluating 5 arms with a batch of 16 gives three or four samples per arm, and the noise standard deviation is larger than the differences between arms. Going too far relative to the amount of information one batch holds — that is the intrinsic danger of data reuse. The clip switches off the gradient of samples whose ratio has passed a certain range, so the policy stays near the batch even as the number of epochs grows.
The rest of PPO
Adaptive KL penalty. The second variant in the PPO paper uses a KL penalty instead of the clip.
If the KL measured after the update exceeds 1.5 times the target , is doubled; if it is below times the target, is halved. In the paper’s experiments the clip did better, and most implementations since then use the clip. (The KL penalty you see in LLM RLHF is a different thing; see the callout below.)
The full loss. When the actor and critic share parameters or are optimised together,
is the λ-return from Lesson 4. The entropy bonus keeps the policy from hardening into a deterministic one too early.
Value clipping. The original implementation (OpenAI baselines) used a similar clip for the critic too: set and minimise . It is not in the body of the paper, and as Huang et al. (2022) summarise, later work reported that it does not improve performance and can even hurt it.
One iteration goes as follows.
- Collect rollouts with and store and for each action.
- Compute and with GAE. (Usually is normalised to mean 0, standard deviation 1 within a minibatch.)
- For epochs: shuffle the data, split it into minibatches, and take an Adam step on the loss above, with global gradient-norm clipping.
- (Optional) If approx KL exceeds the target, skip the remaining epochs (early stopping).
→ Go deeper: Anatomy of a training step — how rollout batch, mini-batch, micro-batch and epochs map onto a real LLM RL framework.
Always log these two diagnostics.
- approx KL: estimates from the stored log-probs. , the negated mean of , is unbiased, but individual samples can be negative and its variance is high. is still unbiased because , is always non-negative because , and has low variance (Schulman, 2020). Spinning Up’s PPO computes its approx KL as the simple mean and stops that iteration’s policy updates when it exceeds 1.5 times the target (default 0.01).
- clip fraction: the fraction of samples with . It is 0 in the first epoch and rises as epochs go by. If it stays large, the learning rate or number of epochs is more than the batch can support.
Implementing it
We implement the PPO-clip update on the same bandit as the figure. The gradient is a direct translation of the case analysis above into code (samples for which the min picked the constant term get live = False). Every epoch prints approx KL () and the clip fraction.
import numpy as np
mu = np.array([0.2, 0.5, 0.8, 0.4, 0.6]) # mean rewards of the 5 arms; the best is arm 2
K, sigma = len(mu), 1.0
def softmax(z):
e = np.exp(z - z.max())
return e / e.sum()
def ppo_update(theta_old, a, A, epochs=10, lr=0.5, eps=0.2, clip=True, log=False):
"""Gradient ascent on the surrogate for `epochs` steps on the same batch (a, A).
L(θ) = mean_i min(ρ_i A_i, clip(ρ_i, 1-ε, 1+ε) A_i), ρ_i = π_θ(a_i) / π_old(a_i)"""
theta = theta_old.copy()
logp_old = np.log(softmax(theta_old))[a]
for ep in range(epochs):
pi = softmax(theta)
logratio = np.log(pi)[a] - logp_old
ratio = np.exp(logratio)
if clip: # samples where min() picked the clipped constant term get zero gradient
live = ~(((A > 0) & (ratio > 1 + eps)) | ((A < 0) & (ratio < 1 - eps)))
else:
live = np.ones_like(ratio, dtype=bool)
score = np.eye(K)[a] - pi # ∇_θ log π(a) = e_a - π
grad = ((live * ratio * A)[:, None] * score).mean(0) # ∇_θ ρ = ρ ∇_θ log π
if log and ep in (0, 1, 2, 5, epochs - 1):
approx_kl = np.mean((ratio - 1) - logratio) # k3 ≥ 0
clipfrac = np.mean(np.abs(ratio - 1) > eps)
print(f" epoch {ep:2d} approx_kl={approx_kl:.4f} clipfrac={clipfrac:.2f} "
f"ρ∈[{ratio.min():.2f}, {ratio.max():.2f}] J(π)={pi @ mu:.3f}")
theta += lr * grad
return theta
def batch(theta, B, rng):
a = rng.choice(K, size=B, p=softmax(theta))
R = mu[a] + sigma * rng.standard_normal(B)
return a, (R - R.mean()) / (R.std() + 1e-8) # batch-normalised advantage
rng = np.random.default_rng(11)
theta_old = np.zeros(K)
a, A = batch(theta_old, 16, rng)
print("per-arm (sample count, mean advantage) in this batch:",
{k: (int((a == k).sum()), round(float(A[a == k].mean()), 2)) for k in range(K) if (a == k).any()})
for clip in [False, True]:
print("\n" + ("PPO-clip (ε=0.2)" if clip else "no clip: plain IS surrogate"))
th = ppo_update(theta_old, a, A, epochs=30, lr=1.0, clip=clip, log=True)
pi, p0 = softmax(th), softmax(theta_old)
print(f" → π = {np.round(pi, 3)}, exact KL(π_old‖π) = {np.sum(p0 * np.log(p0 / pi)):.3f}")In this batch the worst arm, arm 0 (μ = 0.2), got 6 samples with mean advantage +0.56 and looked like the best. The run without the clip collapses onto that arm and J drops from 0.5 to 0.21. The clipped run stays almost where it was. Also check that the clipped run’s ratio range leaves [0.8, 1.2]: the clip does not confine the ratio.
Now we repeat collect → many epochs → collect again, as in real training. With 1 epoch the clip does nothing (every ρ = 1 in the first epoch). The difference appears when we raise the epochs to 10.
def train(clip, epochs, iters=30, B=16, lr=1.0, seed=0):
rng = np.random.default_rng(seed)
theta = np.zeros(K)
for _ in range(iters): # collect → many epochs on the same batch → collect again
a, A = batch(theta, B, rng)
theta = ppo_update(theta, a, A, epochs=epochs, lr=lr, clip=clip)
return softmax(theta)
print("30 iterations (batch 16), 30 runs — mean final J / bottom 10% / runs collapsed onto a wrong arm (π_max > 0.9)")
for epochs in [1, 10]:
for clip in [False, True]:
pis = np.array([train(clip, epochs, seed=s) for s in range(30)])
J = pis @ mu
wrong = int(((pis.argmax(1) != mu.argmax()) & (pis.max(1) > 0.9)).sum())
print(f" epochs={epochs:2d} {'clip ' if clip else 'no clip'} J={J.mean():.3f} "
f"p10={np.percentile(J, 10):.3f} collapsed={wrong}")With the clip, running 10 epochs on the same data reaches a higher J than 1 epoch: sample efficiency has improved. Without the clip, the same 10 epochs collapse a good number of runs onto a wrong arm.
The PPO loss in LLM RL
In an LLM the actions are tokens, so the ratio is also computed per token: . Prompt tokens and padding are not actions, so they are excluded with a mask. Below is a condensed version of the core loss in PPO-RLHF implementations.
import torch
def masked_mean(x, mask):
return (x * mask).sum() / mask.sum().clamp(min=1)
def ppo_loss(logprobs, old_logprobs, advantages, mask,
values, old_values, returns,
clip_eps=0.2, vf_clip=0.2, vf_coef=0.5):
"""All tensors are (B, T), indexed by response-token position.
logprobs: log π_θ(y_t | x, y_<t) under the current policy (has grad)
old_logprobs: log-probs under the rollout-time policy (constant)
advantages, returns: GAE outputs (constant), values: current critic output (has grad)
mask: 1 = response token, 0 = prompt / padding"""
logratio = logprobs - old_logprobs
ratio = torch.exp(logratio) # per-token ρ_t
# policy loss: -min(ρA, clip(ρ)A) = max(-ρA, -clip(ρ)A)
pg_loss1 = -advantages * ratio
pg_loss2 = -advantages * torch.clamp(ratio, 1.0 - clip_eps, 1.0 + clip_eps)
pg_loss = masked_mean(torch.max(pg_loss1, pg_loss2), mask) # mean over all tokens in the batch
# value loss (clipped version; many implementations skip it)
v_clipped = old_values + torch.clamp(values - old_values, -vf_clip, vf_clip)
vf_loss = 0.5 * masked_mean(torch.max((values - returns) ** 2,
(v_clipped - returns) ** 2), mask)
with torch.no_grad(): # diagnostics
approx_kl = masked_mean((ratio - 1) - logratio, mask) # k3
clipfrac = masked_mean(((ratio - 1).abs() > clip_eps).float(), mask)
return pg_loss + vf_coef * vf_loss, {"approx_kl": approx_kl, "clipfrac": clipfrac}Whether masked_mean is taken over all tokens in the batch, or first per sequence and then across sequences, looks like a detail, but it changes the weight each token of a long versus a short response receives. It comes back in Track V as the length-bias problem.
During PPO training, as the epochs progress the clip fraction rises to 0.6 and approx KL to 0.3. What should you suspect first?
Clip fraction and approx KL both measure “how far the current policy has moved from the policy that produced the data”. If both are large together, you have optimised beyond the range in which the surrogate can be trusted. Lower the learning rate, reduce the epochs, or turn on KL-based early stopping. The no-clip case of the bandit experiment above is an extreme example.
Summary
- Step size in parameter space does not control how much the policy changes. In RL a large policy change damages the data distribution too, which makes recovery hard. Distance in policy space is measured by KL (whose second-order approximation is the Fisher matrix).
- The IS surrogate has the same gradient as the policy gradient at and can be trusted only while the policies are close. TRPO enforces this with a KL constraint.
- PPO-clip is . The gradient is switched off only at when , and only at when . It is a pessimistic lower bound, and it does not confine the ratio.
- Practical PPO = clip + critic (regression to λ-returns) + entropy + advantage normalisation + minibatch epochs + gradient clipping, monitored with approx KL () and the clip fraction.
- In LLMs we use per-token ratios and a mask, and distinguish the trust-region KL () from the regularising KL (). GRPO is PPO-clip with the critic replaced by a group baseline.
clip 없는 IS surrogate는 이 배치에 대해 선형 이다. 이니, 계속 최대화하면 대괄호 값이 가장 큰 팔 하나에 모든 확률을 몰아준다. 그 대괄호는 샘플 몇 개의 평균일 뿐이다. 배치 16개로 팔 5개를 평가하면 팔마다 샘플이 서너 개이고, 잡음 표준편차가 팔 사이 차이보다 크다. 한 배치가 담은 정보의 양에 비해 너무 멀리 가는 것, 이것이 data reuse의 본질적 위험이다. clip은 ratio가 일정 범위를 넘은 샘플의 기울기를 끄므로, epoch을 늘려도 정책이 배치 근처에 머문다.
PPO의 나머지 부품
적응형 KL 페널티. PPO 논문의 두 번째 변형은 clip 대신 KL을 페널티로 넣는다.
업데이트 뒤 측정한 KL 가 목표 의 1.5배를 넘으면 를 두 배로, 배보다 작으면 절반으로 바꾼다. 논문 실험에서는 clip 쪽이 더 좋았고, 이후 대부분의 구현이 clip을 쓴다. (LLM의 RLHF에서 보는 KL 페널티는 이것과 다르다. 아래 callout 참고.)
전체 손실. actor와 critic이 매개변수를 공유하거나 같이 최적화될 때
는 4강의 λ-return이다. entropy 보너스 는 정책이 너무 일찍 결정적으로 굳는 것을 막는다.
Value clipping. 원 구현(OpenAI baselines)은 critic에도 비슷한 clip을 썼다. 로 두고 를 줄인다. 논문 본문에는 없는 장치이고, Huang et al.(2022)이 정리한 대로 이후 연구들은 이것이 성능을 높이지 않거나 오히려 해칠 수 있다고 보고했다.
한 번의 반복 은 다음과 같다.
- 로 rollout을 모으고 각 행동의 , 를 저장한다.
- GAE로 , 를 계산한다. (보통 minibatch 안에서 를 평균 0, 표준편차 1로 정규화한다.)
- epoch 동안: 데이터를 섞어 minibatch로 나누고, 위 손실로 Adam step. 전역 gradient norm clipping.
- (선택) approx KL이 목표를 넘으면 남은 epoch을 건너뛴다(early stopping).
→ 더 깊이: 학습 step 해부 — rollout 배치, mini-batch, micro-batch, epoch이 실제 LLM RL 프레임워크에서 어떻게 대응되는지.
진단 지표 두 개는 꼭 기록한다.
- approx KL: 저장한 log-prob으로 를 추정한다. 의 평균에 음수를 붙인 는 불편하지만 샘플마다 음수가 될 수 있고 분산이 크다. 는 이라 여전히 불편하고, 이라 항상 0 이상이며 분산이 작다(Schulman, 2020). Spinning Up의 PPO는 approx KL을 단순한 평균으로 계산하고, 이 값이 목표(기본 0.01)의 1.5배를 넘으면 해당 반복의 정책 업데이트를 멈춘다.
- clip fraction: 인 샘플의 비율. 처음 epoch에서는 0이고 epoch이 지날수록 오른다. 이것이 계속 크다면 학습률이나 epoch 수가 배치가 감당할 수 있는 것보다 크다는 뜻이다.
직접 구현하기
그림과 같은 bandit에서 PPO-clip 업데이트를 구현한다. 기울기는 위의 경우 나누기를 그대로 코드로 옮긴 것이다(min이 상수 항을 고른 샘플은 live = False). 매 epoch approx KL()과 clip fraction을 출력한다.
import numpy as np
mu = np.array([0.2, 0.5, 0.8, 0.4, 0.6]) # 팔 5개의 평균 보상, 최선은 팔 2
K, sigma = len(mu), 1.0
def softmax(z):
e = np.exp(z - z.max())
return e / e.sum()
def ppo_update(theta_old, a, A, epochs=10, lr=0.5, eps=0.2, clip=True, log=False):
"""같은 배치 (a, A)로 surrogate를 epochs번 경사 상승한다.
L(θ) = mean_i min(ρ_i A_i, clip(ρ_i, 1-ε, 1+ε) A_i), ρ_i = π_θ(a_i) / π_old(a_i)"""
theta = theta_old.copy()
logp_old = np.log(softmax(theta_old))[a]
for ep in range(epochs):
pi = softmax(theta)
logratio = np.log(pi)[a] - logp_old
ratio = np.exp(logratio)
if clip: # min()이 clip된 상수 항을 고른 샘플은 기울기가 0
live = ~(((A > 0) & (ratio > 1 + eps)) | ((A < 0) & (ratio < 1 - eps)))
else:
live = np.ones_like(ratio, dtype=bool)
score = np.eye(K)[a] - pi # ∇_θ log π(a) = e_a - π
grad = ((live * ratio * A)[:, None] * score).mean(0) # ∇_θ ρ = ρ ∇_θ log π
if log and ep in (0, 1, 2, 5, epochs - 1):
approx_kl = np.mean((ratio - 1) - logratio) # k3 ≥ 0
clipfrac = np.mean(np.abs(ratio - 1) > eps)
print(f" epoch {ep:2d} approx_kl={approx_kl:.4f} clipfrac={clipfrac:.2f} "
f"ρ∈[{ratio.min():.2f}, {ratio.max():.2f}] J(π)={pi @ mu:.3f}")
theta += lr * grad
return theta
def batch(theta, B, rng):
a = rng.choice(K, size=B, p=softmax(theta))
R = mu[a] + sigma * rng.standard_normal(B)
return a, (R - R.mean()) / (R.std() + 1e-8) # 배치 정규화 advantage
rng = np.random.default_rng(11)
theta_old = np.zeros(K)
a, A = batch(theta_old, 16, rng)
print("이 배치의 팔별 (샘플 수, 평균 advantage):",
{k: (int((a == k).sum()), round(float(A[a == k].mean()), 2)) for k in range(K) if (a == k).any()})
for clip in [False, True]:
print("\n" + ("PPO-clip (ε=0.2)" if clip else "clip 없음: 순수 IS surrogate"))
th = ppo_update(theta_old, a, A, epochs=30, lr=1.0, clip=clip, log=True)
pi, p0 = softmax(th), softmax(theta_old)
print(f" → π = {np.round(pi, 3)}, 정확한 KL(π_old‖π) = {np.sum(p0 * np.log(p0 / pi)):.3f}")이 배치에서는 가장 나쁜 팔 0(μ = 0.2)이 샘플 6개, 평균 advantage +0.56으로 가장 좋아 보였다. clip 없는 쪽은 그 팔로 무너져 J가 0.5에서 0.21로 떨어진다. clip 쪽은 거의 제자리에 머문다. 그리고 clip 쪽의 ratio 범위가 [0.8, 1.2]를 벗어난다는 것도 확인하자. clip은 ratio를 가두지 않는다.
이제 실제 학습처럼 수집 → 여러 epoch → 다시 수집 을 반복한다. epoch 1이면 clip은 아무 일도 하지 않는다(첫 epoch에서는 모든 ρ = 1). epoch을 10으로 늘렸을 때 차이가 난다.
def train(clip, epochs, iters=30, B=16, lr=1.0, seed=0):
rng = np.random.default_rng(seed)
theta = np.zeros(K)
for _ in range(iters): # 수집 → 같은 배치로 여러 epoch → 다시 수집
a, A = batch(theta, B, rng)
theta = ppo_update(theta, a, A, epochs=epochs, lr=lr, clip=clip)
return softmax(theta)
print("30회 반복(배치 16), 실행 30개 — 최종 J 평균 / 하위 10% / 틀린 팔로 붕괴(π_max > 0.9)한 실행 수")
for epochs in [1, 10]:
for clip in [False, True]:
pis = np.array([train(clip, epochs, seed=s) for s in range(30)])
J = pis @ mu
wrong = int(((pis.argmax(1) != mu.argmax()) & (pis.max(1) > 0.9)).sum())
print(f" epochs={epochs:2d} {'clip ' if clip else 'no clip'} J={J.mean():.3f} "
f"p10={np.percentile(J, 10):.3f} 붕괴={wrong}")clip이 있으면 같은 데이터로 10 epoch을 돌려 1 epoch보다 높은 J에 도달한다. 샘플 효율이 좋아진 것이다. clip이 없으면 같은 10 epoch이 상당수 실행을 틀린 팔로 무너뜨린다.
LLM RL에서의 PPO 손실
LLM에서 행동은 토큰이므로 ratio도 토큰마다 계산한다. . 프롬프트 토큰과 padding은 행동이 아니므로 mask로 제외한다. 아래는 PPO-RLHF 구현들의 핵심 손실을 간추린 것이다.
import torch
def masked_mean(x, mask):
return (x * mask).sum() / mask.sum().clamp(min=1)
def ppo_loss(logprobs, old_logprobs, advantages, mask,
values, old_values, returns,
clip_eps=0.2, vf_clip=0.2, vf_coef=0.5):
"""모든 텐서는 (B, T), 응답 토큰 위치 기준.
logprobs: 현재 정책의 log π_θ(y_t | x, y_<t) (기울기 있음)
old_logprobs: rollout 시점 정책의 log-prob (상수)
advantages, returns: GAE 결과 (상수), values: 현재 critic 출력 (기울기 있음)
mask: 1 = 응답 토큰, 0 = prompt / padding"""
logratio = logprobs - old_logprobs
ratio = torch.exp(logratio) # 토큰별 ρ_t
# policy loss: -min(ρA, clip(ρ)A) = max(-ρA, -clip(ρ)A)
pg_loss1 = -advantages * ratio
pg_loss2 = -advantages * torch.clamp(ratio, 1.0 - clip_eps, 1.0 + clip_eps)
pg_loss = masked_mean(torch.max(pg_loss1, pg_loss2), mask) # 배치 전체 토큰 평균
# value loss (clipped 버전; 쓰지 않는 구현도 많다)
v_clipped = old_values + torch.clamp(values - old_values, -vf_clip, vf_clip)
vf_loss = 0.5 * masked_mean(torch.max((values - returns) ** 2,
(v_clipped - returns) ** 2), mask)
with torch.no_grad(): # 진단 지표
approx_kl = masked_mean((ratio - 1) - logratio, mask) # k3
clipfrac = masked_mean(((ratio - 1).abs() > clip_eps).float(), mask)
return pg_loss + vf_coef * vf_loss, {"approx_kl": approx_kl, "clipfrac": clipfrac}masked_mean을 배치 전체 토큰에 대해 취할지, 시퀀스마다 평균한 뒤 시퀀스들을 평균할지는 사소해 보이지만 긴 응답과 짧은 응답의 토큰 하나하나가 받는 가중치를 바꾼다. Track V에서 길이 편향 문제로 다시 나온다.
PPO 학습 중 epoch이 진행될수록 clip fraction이 0.6, approx KL이 0.3까지 오른다. 가장 먼저 의심할 것은?
clip fraction과 approx KL은 모두 “현재 정책이 데이터를 만든 정책에서 얼마나 멀어졌는가”를 잰다. 둘이 함께 크다면 surrogate를 믿을 수 있는 범위를 넘어 최적화한 것이다. 학습률을 낮추거나, epoch을 줄이거나, KL 기준 early stopping을 켠다. 위 bandit 실험의 clip 없는 경우가 극단적인 예다.
정리
- 매개변수 공간의 step 크기는 정책 공간의 변화량을 통제하지 못한다. RL에서 큰 정책 변화는 데이터 분포까지 망가뜨려 회복이 어렵다. 정책 공간의 거리는 KL(2차 근사는 Fisher)로 잰다.
- IS surrogate 는 에서 정책 경사와 같은 기울기를 주고, 정책이 가까울 때만 믿을 수 있다. TRPO는 이를 KL 제약으로 강제한다.
- PPO-clip은 . 이면 에서, 이면 에서만 기울기가 꺼진다. 비관적 하한이며, ratio를 가두지는 않는다.
- 실전 PPO = clip + critic(λ-return 회귀) + entropy + advantage 정규화 + minibatch epoch + gradient clipping. approx KL()과 clip fraction으로 감시한다.
- LLM에서는 토큰별 ratio와 mask를 쓰고, trust region의 KL()과 정규화 KL()을 구분한다. GRPO는 PPO-clip에서 critic을 그룹 baseline으로 바꾼 것이다.
더 읽을거리Further reading
- Schulman, Wolski, Dhariwal, Radford, Klimov, Proximal Policy Optimization Algorithms (2017) — PPO-clip과 적응형 KL 페널티. 이 레슨의 중심.PPO-clip and the adaptive KL penalty. The core of this lesson.
- Schulman, Levine, Moritz, Jordan, Abbeel, Trust Region Policy Optimization (ICML 2015) — surrogate 하한과 KL trust region, natural gradient + conjugate gradient 구현.The surrogate lower bound and the KL trust region, implemented with natural gradient + conjugate gradient.
- Kakade & Langford, Approximately Optimal Approximate Reinforcement Learning (ICML 2002) — performance difference lemma와 보수적 정책 갱신. TRPO의 이론적 출발점.The performance difference lemma and conservative policy updates; the theoretical starting point of TRPO.
- Huang et al., The 37 Implementation Details of Proximal Policy Optimization (ICLR Blog Track, 2022) — advantage 정규화, value clipping, approx KL 등 구현 세부를 원 코드와 대조해 정리했다.Implementation details such as advantage normalisation, value clipping and approx KL, checked against the original code.
- Engstrom et al., Implementation Matters in Deep Policy Gradients: A Case Study on PPO and TRPO (ICLR 2020) — PPO의 성능 상당 부분이 clip이 아닌 '코드 수준 최적화'에서 온다는 분석. clip이 ratio를 실제로 묶지 못함을 보였다.Shows that much of PPO's performance comes from 'code-level optimisations' rather than the clip, and that the clip does not actually bound the ratio.
- John Schulman, Approximating KL Divergence (blog, 2020) — k1, k2, k3 KL 추정량. approx_kl 진단과 GRPO의 KL 항이 여기서 왔다.The k1, k2, k3 KL estimators; where the approx_kl diagnostic and GRPO's KL term come from.
- OpenAI Spinning Up: Proximal Policy Optimization — clip 목적함수의 A > 0 / A < 0 분석과 간결한 구현.The A > 0 / A < 0 analysis of the clipped objective and a concise implementation.
- Nathan Lambert, Reinforcement Learning from Human Feedback (rlhfbook.com) — PPO를 LLM에 적용할 때의 토큰 단위 ratio, KL 보상, GRPO와의 관계.Per-token ratios, the KL reward, and the relation to GRPO when PPO is applied to LLMs.