Track IV · RL Fundamentals · 05/05

Trust region에서 PPO까지From trust regions to PPO

정책 경사를 크게 밟으면 왜 무너지는지(매개변수 공간의 거리 ≠ 정책 공간의 거리)에서 출발해, importance sampling surrogate, TRPO의 KL trust region, PPO의 clipped objective를 유도한다. A > 0, A < 0 두 경우의 clip을 분석하고, value clipping·entropy·minibatch epoch·approx KL·clip fraction까지 LLM RL에서 쓰는 PPO 손실을 끝까지 구현한다.Starting from why big policy-gradient steps collapse (distance in parameter space ≠ distance in policy space), derives the importance-sampling surrogate, TRPO's KL trust region and PPO's clipped objective. Analyses the clip in both cases, A > 0 and A < 0, and implements the full PPO loss used in LLM RL, down to value clipping, entropy, minibatch epochs, approx KL and clip fraction.

40 분min PPO · TRPO · trust region · importance sampling · surrogate objective · clipping · KL penalty · approx KL 먼저 볼 것:Before this: Actor-critic과 GAEActor-critic and GAE, 정책 경사와 REINFORCEPolicy gradients and REINFORCE

The policy gradients so far collected a batch, computed one gradient from it, and threw it away. The batch came from the policy πθ\pi_\theta 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 FF.

Es[KL(πθ(⋅∣s) ∥ πθ+Δ(⋅∣s))]≈12 Δ⊤F(θ) Δ\mathbb{E}_s\big[\mathrm{KL}\big(\pi_{\theta}(\cdot \mid s) \,\|\, \pi_{\theta + \Delta}(\cdot \mid s)\big)\big] \approx \tfrac{1}{2}\, \Delta^\top F(\theta)\, \DeltaF(θ)=Es, a∼πθ[∇θlog⁡πθ(a∣s) ∇θlog⁡πθ(a∣s)⊤]F(\theta) = \mathbb{E}_{s,\, a \sim \pi_\theta}\big[\nabla_\theta \log \pi_\theta(a \mid s)\, \nabla_\theta \log \pi_\theta(a \mid s)^\top\big]

The steepest ascent direction under the constraint “the policy may not change by more than δ in KL” is the natural gradient F−1∇JF^{-1} \nabla J, and TRPO is a practical version of this idea.

Importance sampling: estimating the gradient from someone else’s data

The batch came from πold\pi_{\text{old}}, and we want to evaluate πθ\pi_\theta. Changing only the action distribution in the same state can be corrected with importance sampling.

Ea∼πθ[A(s,a)]=Ea∼πold[πθ(a∣s)πold(a∣s) A(s,a)]=Ea∼πold[ρ(θ) A(s,a)]\mathbb{E}_{a \sim \pi_\theta}\big[A(s, a)\big] = \mathbb{E}_{a \sim \pi_{\text{old}}}\Big[\frac{\pi_\theta(a \mid s)}{\pi_{\text{old}}(a \mid s)}\, A(s, a)\Big] = \mathbb{E}_{a \sim \pi_{\text{old}}}\big[\rho(\theta)\, A(s, a)\big]

From this we build the surrogate objective. The state distribution is kept as that of πold\pi_{\text{old}}.

Lπold(θ)=E(st,at)∼πold[ρt(θ) A^t],ρt(θ)=πθ(at∣st)πold(at∣st)L_{\pi_{\text{old}}}(\theta) = \mathbb{E}_{(s_t, a_t) \sim \pi_{\text{old}}}\big[\rho_t(\theta)\, \hat A_t\big], \qquad \rho_t(\theta) = \frac{\pi_\theta(a_t \mid s_t)}{\pi_{\text{old}}(a_t \mid s_t)}

At θ=θold\theta = \theta_{\text{old}} we have ∇θρt=ρt∇θlog⁡πθ(at∣st)=∇θlog⁡πθ(at∣st)\nabla_\theta \rho_t = \rho_t \nabla_\theta \log \pi_\theta(a_t \mid s_t) = \nabla_\theta \log \pi_\theta(a_t \mid s_t), so ∇L=E[A^t∇log⁡πθ]\nabla L = \mathbb{E}[\hat A_t \nabla \log \pi_\theta] — exactly the policy gradient. The surrogate is an approximation that agrees with JJ to first order at θold\theta_{\text{old}}, 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.

J(π′)−J(π)=Eτ∼π′[∑tγtAπ(st,at)]J(\pi') - J(\pi) = \mathbb{E}_{\tau \sim \pi'}\Big[\sum_t \gamma^t A^\pi(s_t, a_t)\Big]

The new policy’s gain is the old policy’s advantage summed over the states the new policy visits. The surrogate swaps “the states π′\pi' visits” in this formula for “the states π\pi visits”, and the swap is justified only when the two policies are close. The TRPO paper quantified this and proved a lower bound.

J(π′)≥J(π)+Lπ(π′)−C⋅max⁡sKL(π(⋅∣s) ∥ π′(⋅∣s))J(\pi') \ge J(\pi) + L_\pi(\pi') - C \cdot \max_s \mathrm{KL}\big(\pi(\cdot \mid s) \,\|\, \pi'(\cdot \mid s)\big)

Here C=4γmax⁡s,a∣Aπ(s,a)∣/(1−γ)2C = 4\gamma \max_{s,a} |A^\pi(s,a)| / (1-\gamma)^2.

Maximising the right-hand side makes JJ increase monotonically (minorize–maximize). The theoretical CC is so large that the steps become tiny, so practical TRPO turns the penalty into a constraint.

max⁡θ  Lπold(θ)s.t.Es[KL(πold(⋅∣s) ∥ πθ(⋅∣s))]≤δ\max_\theta\; L_{\pi_{\text{old}}}(\theta) \quad \text{s.t.} \quad \mathbb{E}_s\big[\mathrm{KL}\big(\pi_{\text{old}}(\cdot \mid s) \,\|\, \pi_\theta(\cdot \mid s)\big)\big] \le \delta

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 [1−ε,1+ε][1-\varepsilon, 1+\varepsilon]”.

LCLIP(θ)=Et[min⁡(ρt(θ) A^t,  clip⁡(ρt(θ),1−ε,1+ε) A^t)]L^{\text{CLIP}}(\theta) = \mathbb{E}_t\Big[\min\big(\rho_t(\theta)\, \hat A_t,\; \operatorname{clip}(\rho_t(\theta), 1-\varepsilon, 1+\varepsilon)\, \hat A_t\big)\Big]

Because of the min we have to split into cases. Call the term for one sample ℓ(ρ)\ell(\rho).

A^>0\hat A > 0 (a good action). The term is min⁡(ρ,clip⁡(ρ))⋅A^\min(\rho, \operatorname{clip}(\rho))\cdot \hat A. If ρ≤1+ε\rho \le 1+\varepsilon, then ρ≤clip⁡(ρ)\rho \le \operatorname{clip}(\rho) or they are equal, so ℓ=ρA^\ell = \rho \hat A and the gradient stays alive. If ρ>1+ε\rho > 1+\varepsilon, then ℓ=(1+ε)A^\ell = (1+\varepsilon)\hat A is a constant: zero gradient. The objective wants to raise the probability of a good action, but only up to a factor of 1+ε1+\varepsilon. Conversely, if ρ<1−ε\rho < 1-\varepsilon — the good action’s probability has actually dropped a lot — then ρA^<(1−ε)A^\rho \hat A < (1-\varepsilon) \hat A, so the min picks the unclipped term and the live gradient pushes it back.

A^<0\hat A < 0 (a bad action). With A^<0\hat A < 0, min⁡(ρA^,cA^)=A^⋅max⁡(ρ,c)\min(\rho \hat A, c \hat A) = \hat A \cdot \max(\rho, c). If ρ<1−ε\rho < 1-\varepsilon, then max⁡(ρ,1−ε)=1−ε\max(\rho, 1-\varepsilon) = 1-\varepsilon is a constant: zero gradient. The objective wants to lower the bad action’s probability, but only down to a factor of 1−ε1-\varepsilon. If instead ρ>1+ε\rho > 1+\varepsilon — the bad action’s probability has actually grown — then max⁡(ρ,1+ε)=ρ\max(\rho, 1+\varepsilon) = \rho, 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 LCLIP≤LL^{\text{CLIP}} \le L (the IS surrogate) is a pessimistic lower bound, and the two coincide near ρ=1\rho = 1.

지금까지의 정책 경사는 배치 하나를 모으면 기울기를 한 번 계산하고 버렸다. 그 배치는 그 순간의 정책 πθ\pi_\theta에서 나온 것이라, 한 step 움직인 뒤의 정책에 대해서는 더 이상 “자기 데이터”가 아니기 때문이다. 그런데 데이터는 비싸다. LLM RL에서는 응답 생성(rollout)이 학습 step보다 훨씬 오래 걸리는 경우가 흔하다. 한 배치로 여러 번 업데이트하고 싶고, 동시에 한 번의 업데이트가 정책을 망가뜨리지 않기를 바란다. 이 레슨은 그 두 요구를 함께 만족시키는 방법, TRPO 와 PPO 를 유도한다.

왜 큰 step이 위험한가

지도학습에서 학습률이 너무 크면 손실이 튄다. 그래도 데이터는 그대로라 다음 step에서 회복할 수 있다. RL에서는 정책이 자기 데이터를 만든다. 한 번의 나쁜 업데이트로 정책이 무너지면 이후 모이는 데이터도 무너진 정책의 것이고, 회복할 정보가 사라진다(3강 baseline 없는 실험에서 틀린 시퀀스로 굳어 버린 실행들을 떠올리자).

게다가 학습률은 매개변수 공간 의 거리이지 정책 공간 의 거리가 아니다. softmax 정책에서 로짓을 0.5 움직이는 것은, 로짓들이 비슷할 때는 확률을 조금 바꾸지만 한 로짓이 이미 크면 거의 아무것도 바꾸지 않는다. 신경망 정책이면 이 관계가 매개변수마다, 상태마다 다르다. 정책 공간에서 거리를 재는 자연스러운 방법은 KL divergence이고, 그 2차 근사가 Fisher 정보 행렬 FF다.

Es[KL(πθ(⋅∣s) ∥ πθ+Δ(⋅∣s))]≈12 Δ⊤F(θ) Δ\mathbb{E}_s\big[\mathrm{KL}\big(\pi_{\theta}(\cdot \mid s) \,\|\, \pi_{\theta + \Delta}(\cdot \mid s)\big)\big] \approx \tfrac{1}{2}\, \Delta^\top F(\theta)\, \DeltaF(θ)=Es, a∼πθ[∇θlog⁡πθ(a∣s) ∇θlog⁡πθ(a∣s)⊤]F(\theta) = \mathbb{E}_{s,\, a \sim \pi_\theta}\big[\nabla_\theta \log \pi_\theta(a \mid s)\, \nabla_\theta \log \pi_\theta(a \mid s)^\top\big]

“정책이 KL로 δ 이상 변하지 않게” 제약한 가장 가파른 상승 방향이 natural gradient F−1∇JF^{-1} \nabla J이고, TRPO는 이 아이디어를 실용화한 것이다.

Importance sampling: 남의 데이터로 기울기 추정하기

배치는 πold\pi_{\text{old}}에서 나왔고 우리는 πθ\pi_\theta를 평가하고 싶다. 같은 상태에서 행동 분포만 바꾸는 것은 importance sampling으로 보정할 수 있다.

Ea∼πθ[A(s,a)]=Ea∼πold[πθ(a∣s)πold(a∣s) A(s,a)]=Ea∼πold[ρ(θ) A(s,a)]\mathbb{E}_{a \sim \pi_\theta}\big[A(s, a)\big] = \mathbb{E}_{a \sim \pi_{\text{old}}}\Big[\frac{\pi_\theta(a \mid s)}{\pi_{\text{old}}(a \mid s)}\, A(s, a)\Big] = \mathbb{E}_{a \sim \pi_{\text{old}}}\big[\rho(\theta)\, A(s, a)\big]

이것으로 surrogate 목적함수 를 만든다. 상태 분포는 πold\pi_{\text{old}}의 것을 그대로 쓴다.

Lπold(θ)=E(st,at)∼πold[ρt(θ) A^t],ρt(θ)=πθ(at∣st)πold(at∣st)L_{\pi_{\text{old}}}(\theta) = \mathbb{E}_{(s_t, a_t) \sim \pi_{\text{old}}}\big[\rho_t(\theta)\, \hat A_t\big], \qquad \rho_t(\theta) = \frac{\pi_\theta(a_t \mid s_t)}{\pi_{\text{old}}(a_t \mid s_t)}

θ=θold\theta = \theta_{\text{old}}에서 ∇θρt=ρt∇θlog⁡πθ(at∣st)=∇θlog⁡πθ(at∣st)\nabla_\theta \rho_t = \rho_t \nabla_\theta \log \pi_\theta(a_t \mid s_t) = \nabla_\theta \log \pi_\theta(a_t \mid s_t)이므로 ∇L=E[A^t∇log⁡πθ]\nabla L = \mathbb{E}[\hat A_t \nabla \log \pi_\theta], 정확히 정책 경사 다. surrogate는 θold\theta_{\text{old}}에서 JJ와 1차까지 일치하는 근사이고, 여러 step 최적화할 수 있는 “손실”이다.

그러면 얼마나 멀리까지 믿을 수 있을까? Kakade & Langford(2002)의 performance difference lemma 가 답의 실마리다.

J(π′)−J(π)=Eτ∼π′[∑tγtAπ(st,at)]J(\pi') - J(\pi) = \mathbb{E}_{\tau \sim \pi'}\Big[\sum_t \gamma^t A^\pi(s_t, a_t)\Big]

새 정책의 이득은 새 정책이 방문하는 상태에서 옛 정책의 advantage를 합한 것이다. surrogate는 이 식의 “π′\pi'이 방문하는 상태”를 “π\pi가 방문하는 상태”로 바꿔치기한 것이고, 두 정책이 가까울 때만 그 바꿔치기가 정당하다. TRPO 논문은 이를 정량화해 하한을 증명했다.

J(π′)≥J(π)+Lπ(π′)−C⋅max⁡sKL(π(⋅∣s) ∥ π′(⋅∣s))J(\pi') \ge J(\pi) + L_\pi(\pi') - C \cdot \max_s \mathrm{KL}\big(\pi(\cdot \mid s) \,\|\, \pi'(\cdot \mid s)\big)

여기서 C=4γmax⁡s,a∣Aπ(s,a)∣/(1−γ)2C = 4\gamma \max_{s,a} |A^\pi(s,a)| / (1-\gamma)^2이다.

오른쪽을 최대화하면 JJ가 단조 증가한다(minorize–maximize). 이론대로의 CC는 너무 커서 step이 아주 작아지므로, 실제 TRPO 는 페널티 대신 제약으로 바꾼다.

max⁡θ  Lπold(θ)s.t.Es[KL(πold(⋅∣s) ∥ πθ(⋅∣s))]≤δ\max_\theta\; L_{\pi_{\text{old}}}(\theta) \quad \text{s.t.} \quad \mathbb{E}_s\big[\mathrm{KL}\big(\pi_{\text{old}}(\cdot \mid s) \,\|\, \pi_\theta(\cdot \mid s)\big)\big] \le \delta

이것을 natural gradient 방향(Fisher-vector product와 conjugate gradient로 계산)과 line search로 푼다. 잘 작동하지만 구현이 복잡하고, 2차 정보가 필요하며, 정책과 가치함수가 매개변수를 공유하는 구조나 dropout 같은 잡음과 궁합이 나쁘다.

PPO: clip으로 trust region 흉내 내기

PPO(Schulman et al., 2017)는 제약을 목적함수 안에 넣는다. 아이디어는 “ratio가 [1−ε,1+ε][1-\varepsilon, 1+\varepsilon]를 벗어나서 얻는 이득은 인정하지 않는다”이다.

LCLIP(θ)=Et[min⁡(ρt(θ) A^t,  clip⁡(ρt(θ),1−ε,1+ε) A^t)]L^{\text{CLIP}}(\theta) = \mathbb{E}_t\Big[\min\big(\rho_t(\theta)\, \hat A_t,\; \operatorname{clip}(\rho_t(\theta), 1-\varepsilon, 1+\varepsilon)\, \hat A_t\big)\Big]

min 때문에 경우를 나눠야 한다. 한 샘플의 항을 ℓ(ρ)\ell(\rho)라 하자.

A^>0\hat A > 0 (좋은 행동). min⁡(ρ,clip⁡(ρ))⋅A^\min(\rho, \operatorname{clip}(\rho))\cdot \hat A이다. ρ≤1+ε\rho \le 1+\varepsilon이면 ρ≤clip⁡(ρ)\rho \le \operatorname{clip}(\rho) 또는 같으므로 ℓ=ρA^\ell = \rho \hat A, 기울기는 그대로 살아 있다. ρ>1+ε\rho > 1+\varepsilon이면 ℓ=(1+ε)A^\ell = (1+\varepsilon)\hat A로 상수, 기울기 0. 좋은 행동의 확률을 올리되 1+ε1+\varepsilon배까지만 올리고 싶어 한다. 반대로 ρ<1−ε\rho < 1-\varepsilon, 즉 좋은 행동의 확률이 오히려 크게 줄어든 경우에는 ρA^<(1−ε)A^\rho \hat A < (1-\varepsilon) \hat A이므로 min이 unclipped 항을 고르고, 기울기가 살아서 되돌린다.

A^<0\hat A < 0 (나쁜 행동). A^<0\hat A < 0이면 min⁡(ρA^,cA^)=A^⋅max⁡(ρ,c)\min(\rho \hat A, c \hat A) = \hat A \cdot \max(\rho, c)다. ρ<1−ε\rho < 1-\varepsilon이면 max⁡(ρ,1−ε)=1−ε\max(\rho, 1-\varepsilon) = 1-\varepsilon, 상수, 기울기 0. 나쁜 행동의 확률은 1−ε1-\varepsilon배까지만 낮추고 싶어 한다. 하지만 ρ>1+ε\rho > 1+\varepsilon, 나쁜 행동의 확률이 오히려 늘어난 경우는 max⁡(ρ,1+ε)=ρ\max(\rho, 1+\varepsilon) = \rho라서 clip되지 않고 그대로 벌을 받는다.

정리하면 clip은 목적함수가 좋아지는 방향으로 멀리 간 샘플에서만 기울기를 끈다. 나빠지는 방향의 변화는 언제나 전부 반영한다. 그래서 LCLIP≤LL^{\text{CLIP}} \le L(IS surrogate)인 비관적 하한이고, ρ=1\rho = 1 근처에서는 둘이 같다.

A = +1: L = –, ∂L/∂ρ = – A = −1: L = –, ∂L/∂ρ = –
The solid line is the PPO-clip objective, the grey dashed line the unclipped surrogate ρA, and the green segment the gradient-ascent direction. In the grey shaded region the gradient is 0. Move ρ and the gradient switches off the moment ρ passes 1+ε when A > 0, or drops below 1−ε when A < 0. The opposite direction (a good action whose probability has actually fallen, or a bad action whose probability has risen) is not clipped and is penalised in full, because the min always picks the more pessimistic side. 실선은 PPO-clip 목적함수, 회색 점선은 clip 없는 surrogate ρA, 초록 선분은 경사 상승 방향이다. 회색 음영 구간에서는 기울기가 0이다. ρ를 움직여 보면 A > 0일 때는 ρ가 1+ε를 넘는 순간, A < 0일 때는 1−ε 아래로 내려가는 순간 기울기가 꺼진다. 반대 방향(좋은 행동의 확률이 오히려 줄었거나, 나쁜 행동의 확률이 늘어난 경우)은 clip되지 않고 그대로 벌을 받는다. min이 항상 더 비관적인 쪽을 고르기 때문이다.

Written in one line, the gradient for each sample is

∇θℓt={0(A^t>0, ρt>1+ε) or (A^t<0, ρt<1−ε)A^t ρt ∇θlog⁡πθ(at∣st)otherwise\nabla_\theta \ell_t = \begin{cases} 0 & (\hat A_t > 0,\ \rho_t > 1+\varepsilon) \text{ or } (\hat A_t < 0,\ \rho_t < 1-\varepsilon) \\ \hat A_t\, \rho_t\, \nabla_\theta \log \pi_\theta(a_t \mid s_t) & \text{otherwise} \end{cases}

Let us also be clear about what the clip does not do. The clip does not confine the ratio to [1−ε,1+ε][1-\varepsilon, 1+\varepsilon]. 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.

확인 문제Check yourself

ε = 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 A^<0\hat A < 0 the term is A^⋅max⁡(ρ,clip⁡(ρ))\hat A \cdot \max(\rho, \operatorname{clip}(\rho)). At ρ=1.5>1.2\rho = 1.5 > 1.2, max⁡(1.5,1.2)=1.5\max(1.5, 1.2) = 1.5 picks the unclipped term, so the gradient A^ ∇ρ\hat A\, \nabla\rho stays alive and gradient ascent lowers ρ\rho. 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 A^<0\hat A<0 branch has no ceiling: a token whose ratio has grown to 10 still contributes 10 A^10\,\hat A. Dual-clip PPO (Ye et al., 2020) caps it at c A^c\,\hat A (with c≈3c \approx 3), 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 ρ\rho and the sign of A^\hat A.

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.

기울기를 한 줄로 쓰면, 샘플마다

∇θℓt={0(A^t>0, ρt>1+ε) 또는 (A^t<0, ρt<1−ε)A^t ρt ∇θlog⁡πθ(at∣st)그 외\nabla_\theta \ell_t = \begin{cases} 0 & (\hat A_t > 0,\ \rho_t > 1+\varepsilon) \text{ 또는 } (\hat A_t < 0,\ \rho_t < 1-\varepsilon) \\ \hat A_t\, \rho_t\, \nabla_\theta \log \pi_\theta(a_t \mid s_t) & \text{그 외} \end{cases}

clip이 하지 않는 일도 분명히 해 두자. clip은 ratio를 [1−ε,1+ε][1-\varepsilon, 1+\varepsilon] 안에 가두지 않는다. 기울기가 꺼진 샘플의 확률도 다른 샘플의 업데이트를 따라 움직인다(softmax의 정규화, 공유된 매개변수). 그래서 실제 ratio는 이 구간을 벗어나곤 하고(Engstrom et al., 2020), 실무에서는 KL을 따로 감시한다.

확인 문제Check yourself

ε = 0.2, 어떤 토큰의 advantage가 Â = −1이고 몇 번의 업데이트 뒤 ratio가 ρ = 1.5가 되었다. 이 토큰 항의 PPO-clip 기울기는?

A^<0\hat A < 0이면 항은 A^⋅max⁡(ρ,clip⁡(ρ))\hat A \cdot \max(\rho, \operatorname{clip}(\rho))이다. ρ=1.5>1.2\rho = 1.5 > 1.2에서 max⁡(1.5,1.2)=1.5\max(1.5, 1.2) = 1.5로 unclipped 항이 선택되므로 기울기 A^ ∇ρ\hat A\, \nabla\rho가 그대로 살아 있고, 경사 상승은 ρ\rho를 줄인다. clip은 “목적함수에 유리한 방향으로 너무 멀리 간 경우”에만 기울기를 끈다. 불리한 방향의 이탈은 항상 교정된다.

이 clip되지 않는 A^<0\hat A<0 가지에는 천장이 없다. ratio가 10까지 커진 토큰도 10 A^10\,\hat A를 그대로 보탠다. Dual-clip PPO(Ye et al., 2020)는 이를 c A^c\,\hat A(c≈3c \approx 3)로 막는데, LLM RL처럼 데이터가 눈에 띄게 off-policy일 때 중요해진다. → 더 깊이: Clipping과 importance sampling에서 PPO clip, dual-clip, clip-higher, CISPO와 이후 규칙들을 ρ\rho와 A^\hat A 부호의 함수인 gradient 가중치 하나로 비교한다.

그림으로: 같은 배치로 여러 epoch

PPO가 해결하려는 문제를 직접 보자. 아래는 팔 5개짜리 bandit에서 배치를 한 번만 뽑고, 그 배치로 surrogate를 반복해서 최대화한다.

clip 없음no clip: KL –, J – PPO-clip: KL –, J –, clip 비율clip fraction –, ρ ∈ –
On a 5-armed bandit (mean rewards μ under the bars) we draw a batch once from a uniform πold and maximise the surrogate on that batch for many epochs. Left: πold (grey outline) and the final π. Right: KL(πold‖π) and the true expected reward J(π) = Σπμ for each epoch. Without the clip (red), the policy collapses onto whichever arm happened to look good in the batch, and the KL grows without bound. The first batch shown was deliberately chosen so that this is a wrong arm. Press New batch and sometimes it is luckily the right one. Either way, the policy over-trusts the noise of a single batch. PPO-clip (blue) switches off the gradient of samples whose ratio has left [1−ε, 1+ε], so it stops by itself after a few epochs. 팔 5개(평균 보상 μ는 막대 아래)인 bandit에서 균등한 πold로 배치를 한 번 뽑고, 그 배치로 surrogate를 여러 epoch 최대화한다. 왼쪽: πold(회색 테두리)와 최종 π. 오른쪽: epoch마다 KL(πold‖π)와 참 기대 보상 J(π) = Σπμ. clip이 없으면(빨강) 배치에서 우연히 좋아 보인 팔로 정책이 무너지고 KL이 끝없이 커진다. 처음 보이는 배치는 그것이 틀린 팔인 경우를 일부러 골랐다. 새 배치를 눌러 보면 운 좋게 맞는 경우도 있다. 어느 쪽이든 한 배치의 잡음을 과신한다는 점은 같다. PPO-clip(파랑)은 ratio가 [1−ε, 1+ε]를 벗어난 샘플의 기울기를 끄므로 몇 epoch 뒤 스스로 멈춘다.

Without the clip, the IS surrogate is linear in the policy for this batch. Since 1B∑iρiA^i=∑aπθ(a)⋅[1Bπold(a)∑i:ai=aA^i]\frac{1}{B}\sum_i \rho_i \hat A_i = \sum_a \pi_\theta(a) \cdot \big[\frac{1}{B \pi_{\text{old}}(a)} \sum_{i: a_i = a} \hat A_i\big], 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.

LKLPEN(θ)=Et[ρt(θ) A^t−β KL(πold(⋅∣st) ∥ πθ(⋅∣st))]L^{\text{KLPEN}}(\theta) = \mathbb{E}_t\Big[\rho_t(\theta)\, \hat A_t - \beta\, \mathrm{KL}\big(\pi_{\text{old}}(\cdot \mid s_t) \,\|\, \pi_\theta(\cdot \mid s_t)\big)\Big]

If the KL dd measured after the update exceeds 1.5 times the target dtargd_{\text{targ}}, β\beta is doubled; if it is below 1/1.51/1.5 times the target, β\beta 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,

L(θ,ϕ)=−LCLIP(θ)+c1 Et[(Vϕ(st)−R^t)2]−c2 Et[H(πθ(⋅∣st))]\mathcal{L}(\theta, \phi) = -L^{\text{CLIP}}(\theta) + c_1\, \mathbb{E}_t\big[(V_\phi(s_t) - \hat R_t)^2\big] - c_2\, \mathbb{E}_t\big[\mathcal{H}(\pi_\theta(\cdot \mid s_t))\big]

R^t=A^t+Vold(st)\hat R_t = \hat A_t + V_{\text{old}}(s_t) 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 Vclip=Vold+clip⁡(Vϕ−Vold,−ε,ε)V^{\text{clip}} = V_{\text{old}} + \operatorname{clip}(V_\phi - V_{\text{old}}, -\varepsilon, \varepsilon) and minimise max⁡((Vϕ−R^)2,(Vclip−R^)2)\max\big((V_\phi - \hat R)^2, (V^{\text{clip}} - \hat R)^2\big). 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.

  1. Collect rollouts with πold\pi_{\text{old}} and store log⁡πold(at∣st)\log \pi_{\text{old}}(a_t \mid s_t) and Vold(st)V_{\text{old}}(s_t) for each action.
  2. Compute A^t\hat A_t and R^t\hat R_t with GAE. (Usually A^\hat A is normalised to mean 0, standard deviation 1 within a minibatch.)
  3. For KK epochs: shuffle the data, split it into minibatches, and take an Adam step on the loss above, with global gradient-norm clipping.
  4. (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 KL(πold∥πθ)\mathrm{KL}(\pi_{\text{old}} \| \pi_\theta) from the stored log-probs. k1=E[−log⁡ρ]k_1 = \mathbb{E}[-\log \rho], the negated mean of log⁡ρ\log\rho, is unbiased, but individual samples can be negative and its variance is high. k3=E[(ρ−1)−log⁡ρ]k_3 = \mathbb{E}[(\rho - 1) - \log \rho] is still unbiased because Eπold[ρ−1]=0\mathbb{E}_{\pi_{\text{old}}}[\rho - 1] = 0, is always non-negative because x−1−log⁡x≥0x - 1 - \log x \ge 0, and has low variance (Schulman, 2020). Spinning Up’s PPO computes its approx KL as the simple k1k_1 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 ∣ρ−1∣>ε|\rho - 1| > \varepsilon. 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 (k3k_3) and the clip fraction.

NumPy PPO-clip: many epochs on one batch
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.

NumPy Iterated training: data reuse pays off only together with the clip
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: ρt=πθ(yt∣x,y<t)/πold(yt∣x,y<t)\rho_t = \pi_\theta(y_t \mid x, y_{<t}) / \pi_{\text{old}}(y_t \mid x, y_{<t}). 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.

PyTorch PPO loss for LLMs: token ratios, mask, clip, value loss 로컬에서 실행run locally (pip install torch)
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.

확인 문제Check yourself

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 Eπold[ρtA^t]\mathbb{E}_{\pi_{\text{old}}}[\rho_t \hat A_t] has the same gradient as the policy gradient at θold\theta_{\text{old}} and can be trusted only while the policies are close. TRPO enforces this with a KL constraint.
  • PPO-clip is min⁡(ρA^,clip⁡(ρ,1±ε)A^)\min(\rho \hat A, \operatorname{clip}(\rho, 1\pm\varepsilon)\hat A). The gradient is switched off only at ρ>1+ε\rho > 1+\varepsilon when A^>0\hat A > 0, and only at ρ<1−ε\rho < 1-\varepsilon when A^<0\hat A < 0. 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 (k3k_3) and the clip fraction.
  • In LLMs we use per-token ratios and a mask, and distinguish the trust-region KL (πold\pi_{\text{old}}) from the regularising KL (πref\pi_{\text{ref}}). GRPO is PPO-clip with the critic replaced by a group baseline.

clip 없는 IS surrogate는 이 배치에 대해 선형 이다. 1B∑iρiA^i=∑aπθ(a)⋅[1Bπold(a)∑i:ai=aA^i]\frac{1}{B}\sum_i \rho_i \hat A_i = \sum_a \pi_\theta(a) \cdot \big[\frac{1}{B \pi_{\text{old}}(a)} \sum_{i: a_i = a} \hat A_i\big]이니, 계속 최대화하면 대괄호 값이 가장 큰 팔 하나에 모든 확률을 몰아준다. 그 대괄호는 샘플 몇 개의 평균일 뿐이다. 배치 16개로 팔 5개를 평가하면 팔마다 샘플이 서너 개이고, 잡음 표준편차가 팔 사이 차이보다 크다. 한 배치가 담은 정보의 양에 비해 너무 멀리 가는 것, 이것이 data reuse의 본질적 위험이다. clip은 ratio가 일정 범위를 넘은 샘플의 기울기를 끄므로, epoch을 늘려도 정책이 배치 근처에 머문다.

PPO의 나머지 부품

적응형 KL 페널티. PPO 논문의 두 번째 변형은 clip 대신 KL을 페널티로 넣는다.

LKLPEN(θ)=Et[ρt(θ) A^t−β KL(πold(⋅∣st) ∥ πθ(⋅∣st))]L^{\text{KLPEN}}(\theta) = \mathbb{E}_t\Big[\rho_t(\theta)\, \hat A_t - \beta\, \mathrm{KL}\big(\pi_{\text{old}}(\cdot \mid s_t) \,\|\, \pi_\theta(\cdot \mid s_t)\big)\Big]

업데이트 뒤 측정한 KL dd가 목표 dtargd_{\text{targ}}의 1.5배를 넘으면 β\beta를 두 배로, 1/1.51/1.5배보다 작으면 절반으로 바꾼다. 논문 실험에서는 clip 쪽이 더 좋았고, 이후 대부분의 구현이 clip을 쓴다. (LLM의 RLHF에서 보는 KL 페널티는 이것과 다르다. 아래 callout 참고.)

전체 손실. actor와 critic이 매개변수를 공유하거나 같이 최적화될 때

L(θ,ϕ)=−LCLIP(θ)+c1 Et[(Vϕ(st)−R^t)2]−c2 Et[H(πθ(⋅∣st))]\mathcal{L}(\theta, \phi) = -L^{\text{CLIP}}(\theta) + c_1\, \mathbb{E}_t\big[(V_\phi(s_t) - \hat R_t)^2\big] - c_2\, \mathbb{E}_t\big[\mathcal{H}(\pi_\theta(\cdot \mid s_t))\big]

R^t=A^t+Vold(st)\hat R_t = \hat A_t + V_{\text{old}}(s_t)는 4강의 λ-return이다. entropy 보너스 는 정책이 너무 일찍 결정적으로 굳는 것을 막는다.

Value clipping. 원 구현(OpenAI baselines)은 critic에도 비슷한 clip을 썼다. Vclip=Vold+clip⁡(Vϕ−Vold,−ε,ε)V^{\text{clip}} = V_{\text{old}} + \operatorname{clip}(V_\phi - V_{\text{old}}, -\varepsilon, \varepsilon)로 두고 max⁡((Vϕ−R^)2,(Vclip−R^)2)\max\big((V_\phi - \hat R)^2, (V^{\text{clip}} - \hat R)^2\big)를 줄인다. 논문 본문에는 없는 장치이고, Huang et al.(2022)이 정리한 대로 이후 연구들은 이것이 성능을 높이지 않거나 오히려 해칠 수 있다고 보고했다.

한 번의 반복 은 다음과 같다.

  1. πold\pi_{\text{old}}로 rollout을 모으고 각 행동의 log⁡πold(at∣st)\log \pi_{\text{old}}(a_t \mid s_t), Vold(st)V_{\text{old}}(s_t)를 저장한다.
  2. GAE로 A^t\hat A_t, R^t\hat R_t를 계산한다. (보통 minibatch 안에서 A^\hat A를 평균 0, 표준편차 1로 정규화한다.)
  3. KK epoch 동안: 데이터를 섞어 minibatch로 나누고, 위 손실로 Adam step. 전역 gradient norm clipping.
  4. (선택) approx KL이 목표를 넘으면 남은 epoch을 건너뛴다(early stopping).

→ 더 깊이: 학습 step 해부 — rollout 배치, mini-batch, micro-batch, epoch이 실제 LLM RL 프레임워크에서 어떻게 대응되는지.

진단 지표 두 개는 꼭 기록한다.

  • approx KL: 저장한 log-prob으로 KL(πold∥πθ)\mathrm{KL}(\pi_{\text{old}} \| \pi_\theta)를 추정한다. log⁡ρ\log\rho의 평균에 음수를 붙인 k1=E[−log⁡ρ]k_1 = \mathbb{E}[-\log \rho]는 불편하지만 샘플마다 음수가 될 수 있고 분산이 크다. k3=E[(ρ−1)−log⁡ρ]k_3 = \mathbb{E}[(\rho - 1) - \log \rho]는 Eπold[ρ−1]=0\mathbb{E}_{\pi_{\text{old}}}[\rho - 1] = 0이라 여전히 불편하고, x−1−log⁡x≥0x - 1 - \log x \ge 0이라 항상 0 이상이며 분산이 작다(Schulman, 2020). Spinning Up의 PPO는 approx KL을 단순한 k1k_1 평균으로 계산하고, 이 값이 목표(기본 0.01)의 1.5배를 넘으면 해당 반복의 정책 업데이트를 멈춘다.
  • clip fraction: ∣ρ−1∣>ε|\rho - 1| > \varepsilon인 샘플의 비율. 처음 epoch에서는 0이고 epoch이 지날수록 오른다. 이것이 계속 크다면 학습률이나 epoch 수가 배치가 감당할 수 있는 것보다 크다는 뜻이다.

직접 구현하기

그림과 같은 bandit에서 PPO-clip 업데이트를 구현한다. 기울기는 위의 경우 나누기를 그대로 코드로 옮긴 것이다(min이 상수 항을 고른 샘플은 live = False). 매 epoch approx KL(k3k_3)과 clip fraction을 출력한다.

NumPy PPO-clip: 한 배치로 여러 epoch
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으로 늘렸을 때 차이가 난다.

NumPy 반복 학습: data reuse는 clip과 함께일 때만 이득이다
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도 토큰마다 계산한다. ρt=πθ(yt∣x,y<t)/πold(yt∣x,y<t)\rho_t = \pi_\theta(y_t \mid x, y_{<t}) / \pi_{\text{old}}(y_t \mid x, y_{<t}). 프롬프트 토큰과 padding은 행동이 아니므로 mask로 제외한다. 아래는 PPO-RLHF 구현들의 핵심 손실을 간추린 것이다.

PyTorch LLM용 PPO 손실: 토큰 ratio, mask, clip, value loss 로컬에서 실행run locally (pip install torch)
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에서 길이 편향 문제로 다시 나온다.

확인 문제Check yourself

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 Eπold[ρtA^t]\mathbb{E}_{\pi_{\text{old}}}[\rho_t \hat A_t]는 θold\theta_{\text{old}}에서 정책 경사와 같은 기울기를 주고, 정책이 가까울 때만 믿을 수 있다. TRPO는 이를 KL 제약으로 강제한다.
  • PPO-clip은 min⁡(ρA^,clip⁡(ρ,1±ε)A^)\min(\rho \hat A, \operatorname{clip}(\rho, 1\pm\varepsilon)\hat A). A^>0\hat A > 0이면 ρ>1+ε\rho > 1+\varepsilon에서, A^<0\hat A < 0이면 ρ<1−ε\rho < 1-\varepsilon에서만 기울기가 꺼진다. 비관적 하한이며, ratio를 가두지는 않는다.
  • 실전 PPO = clip + critic(λ-return 회귀) + entropy + advantage 정규화 + minibatch epoch + gradient clipping. approx KL(k3k_3)과 clip fraction으로 감시한다.
  • LLM에서는 토큰별 ratio와 mask를 쓰고, trust region의 KL(πold\pi_{\text{old}})과 정규화 KL(πref\pi_{\text{ref}})을 구분한다. GRPO는 PPO-clip에서 critic을 그룹 baseline으로 바꾼 것이다.

더 읽을거리Further reading