Track IV · RL Fundamentals · 04/05

Actor-critic과 GAEActor-critic and GAE

REINFORCE의 Monte Carlo return을 학습된 가치함수(critic)로 대체해 분산을 줄이는 actor-critic을 유도하고, n-step advantage들의 지수 가중평균인 GAE(γ, λ)를 TD 오차의 합으로 정리한다. λ가 critic 오차(bias)와 보상 잡음(variance)을 어떻게 맞바꾸는지 식과 그림으로 보고, PPO-RLHF의 토큰 단위 critic과 그것을 버린 GRPO의 선택을 이해한다.Derives actor-critic, which lowers variance by replacing REINFORCE's Monte Carlo return with a learned value function (the critic), and writes GAE(γ, λ), an exponentially weighted average of n-step advantages, as a sum of TD errors. Shows in formulas and figures how λ trades critic error (bias) against reward noise (variance), and explains the token-level critic of PPO-RLHF and GRPO's choice to drop it.

35 분min actor-critic · advantage · TD error · n-step · GAE · value function · A2C · critic 먼저 볼 것:Before this: 정책 경사와 REINFORCEPolicy gradients and REINFORCE, TD 학습과 Q-learningTD learning and Q-learning

REINFORCE is unbiased but noisy. The reward-to-go G^t\hat G_t that weights action ata_t contains all the randomness that happened afterwards. In Lesson 2 we solved the same problem with TD: instead of waiting until the end, bootstrap from a learned value estimate. Training an actor that learns the policy together with a critic that learns values is the actor-critic architecture, and PPO is its most famous implementation.

What to multiply the policy gradient by

Write the general form of the policy gradient with a weight Ψt\Psi_t.

∇θJ=E[∑tΨt ∇θlog⁡πθ(at∣st)]\nabla_\theta J = \mathbb{E}\Big[\sum_t \Psi_t\, \nabla_\theta \log \pi_\theta(a_t \mid s_t)\Big]

In the previous lesson we saw that Ψt=R(τ)\Psi_t = R(\tau), G^t\hat G_t and G^t−b(st)\hat G_t - b(s_t) all give the same expectation. We add two more. By the tower property of conditional expectation, E[G^t∣st,at]=Qπ(st,at)\mathbb{E}[\hat G_t \mid s_t, a_t] = Q^\pi(s_t, a_t), so we may use Qπ(st,at)Q^\pi(s_t, a_t) instead of G^t\hat G_t; and subtracting Vπ(st)V^\pi(s_t) as the baseline gives

Ψt=Aπ(st,at)=Qπ(st,at)−Vπ(st)\Psi_t = A^\pi(s_t, a_t) = Q^\pi(s_t, a_t) - V^\pi(s_t)

the advantage. In terms of variance this is a nearly ideal choice. It keeps only “how much better than usual was this action in this state” and erases the luck of the state itself being good or bad. The problem is that we do not know AπA^\pi. This whole lesson is about estimating AπA^\pi well.

The TD error is an estimator of the advantage

Given a critic V≈VπV \approx V^\pi, look at the TD error

δt=rt+γV(st+1)−V(st)\delta_t = r_t + \gamma V(s_{t+1}) - V(s_t)

If V=VπV = V^\pi, then

E[δt∣st,at]=E[rt+γVπ(st+1)∣st,at]−Vπ(st)=Qπ(st,at)−Vπ(st)=Aπ(st,at)\begin{aligned} \mathbb{E}\big[\delta_t \mid s_t, a_t\big] &= \mathbb{E}\big[r_t + \gamma V^\pi(s_{t+1}) \mid s_t, a_t\big] - V^\pi(s_t) \\ &= Q^\pi(s_t, a_t) - V^\pi(s_t) = A^\pi(s_t, a_t) \end{aligned}

A single one-step sample gives an unbiased estimate of the advantage. The only randomness is one draw of rtr_t and st+1s_{t+1}, so the variance is small. In exchange it is biased to the extent that V≠VπV \ne V^\pi. It is exactly the same trade as MC versus TD in Lesson 2.

The critic is learned by regression: pick a target yty_t and minimise L(ϕ)=E[(Vϕ(st)−yt)2]\mathcal{L}(\phi) = \mathbb{E}[(V_\phi(s_t) - y_t)^2]. The target can be yt=G^ty_t = \hat G_t (MC), rt+γVϕ(st+1)r_t + \gamma V_{\phi}(s_{t+1}) (TD, with the gradient stopped on the target side), or the λ-return below. One iteration looks like this.

  1. Collect trajectories with the current policy πθ\pi_\theta.
  2. Compute A^t\hat A_t with the critic.
  3. actor: θ←θ+α∑tA^t∇θlog⁡πθ(at∣st)\theta \leftarrow \theta + \alpha \sum_t \hat A_t \nabla_\theta \log \pi_\theta(a_t \mid s_t)
  4. critic: ϕ←ϕ−β∇ϕ∑t(Vϕ(st)−yt)2\phi \leftarrow \phi - \beta \nabla_\phi \sum_t (V_\phi(s_t) - y_t)^2

This is Lesson 2’s generalised policy iteration as is: the critic does a little evaluation and the actor a little improvement. A3C/A2C of Mnih et al. (2016) runs this in parallel over many environments and adds an nn-step advantage and an entropy bonus on top.

n-step advantage

The 1-step δt\delta_t has large bias, and G^t−V(st)\hat G_t - V(s_t) has large variance. The nn-step advantage bridges the two:

A^t(n)=rt+γrt+1+⋯+γn−1rt+n−1+γnV(st+n)−V(st)\hat A^{(n)}_t = r_t + \gamma r_{t+1} + \cdots + \gamma^{n-1} r_{t+n-1} + \gamma^n V(s_{t+n}) - V(s_t)

Written in terms of TD errors, it becomes surprisingly simple. Expanding ∑l=0n−1γlδt+l\sum_{l=0}^{n-1} \gamma^l \delta_{t+l}, the intermediate VVs cancel each other (telescoping).

∑l=0n−1γlδt+l=∑l=0n−1γlrt+l+∑l=0n−1(γl+1V(st+l+1)−γlV(st+l))=∑l=0n−1γlrt+l+γnV(st+n)−V(st)  =  A^t(n)\begin{aligned} \sum_{l=0}^{n-1} \gamma^l \delta_{t+l} &= \sum_{l=0}^{n-1} \gamma^l r_{t+l} + \sum_{l=0}^{n-1}\big(\gamma^{l+1} V(s_{t+l+1}) - \gamma^l V(s_{t+l})\big) \\ &= \sum_{l=0}^{n-1} \gamma^l r_{t+l} + \gamma^n V(s_{t+n}) - V(s_t) \;=\; \hat A^{(n)}_t \end{aligned}

The nn-step advantage is the discounted sum of nn TD errors.

GAE: an exponentially weighted average over every n

Instead of choosing one nn, Schulman et al. (2016) average over all nn with weights λn−1\lambda^{n-1} (the (1−λ)(1-\lambda) normalises the weights to sum to 1).

A^tGAE(γ,λ)=(1−λ)(A^t(1)+λA^t(2)+λ2A^t(3)+⋯)\hat A^{\text{GAE}(\gamma, \lambda)}_t = (1-\lambda)\big(\hat A^{(1)}_t + \lambda \hat A^{(2)}_t + \lambda^2 \hat A^{(3)}_t + \cdots\big)

Substitute the TD-error sum above for each A^t(n)\hat A^{(n)}_t and collect the coefficient of γlδt+l\gamma^l \delta_{t+l}. Since δt+l\delta_{t+l} appears in every A^(n)\hat A^{(n)} with n>ln > l, the coefficient is

(1−λ)∑n=l+1∞λn−1=(1−λ)⋅λl1−λ=λl(1-\lambda) \sum_{n=l+1}^{\infty} \lambda^{n-1} = (1-\lambda) \cdot \frac{\lambda^l}{1-\lambda} = \lambda^l

Therefore

  A^tGAE(γ,λ)=∑l=0∞(γλ)l δt+l  ⟺A^t=δt+γλ A^t+1\boxed{\;\hat A^{\text{GAE}(\gamma, \lambda)}_t = \sum_{l=0}^{\infty} (\gamma\lambda)^l\, \delta_{t+l}\;} \qquad\Longleftrightarrow\qquad \hat A_t = \delta_t + \gamma\lambda\, \hat A_{t+1}

Thanks to the recursion on the right, a single backward sweep over the trajectory yields the advantage for every tt in O(T)O(T). If the episode terminated, V(sT)=0V(s_T) = 0; if it was cut off by a time limit, bootstrap with V(sT)V(s_T) (failing to distinguish the two is a common bug).

The two extremes are:

  • λ = 0: A^t=δt\hat A_t = \delta_t. 1-step TD. Minimum variance, biased by however wrong the critic is.
  • λ = 1: A^t=∑lγlδt+l=∑lγlrt+l−V(st)\hat A_t = \sum_l \gamma^l \delta_{t+l} = \sum_l \gamma^l r_{t+l} - V(s_t). Telescoping removes all the intermediate VVs, leaving the MC return minus a baseline. Unbiased (even a wrong critic only acts as a baseline), maximum variance.

The target for the critic comes out of the same computation: R^t=A^t+V(st)\hat R_t = \hat A_t + V(s_t) is the λ-return.

In a picture: δ and Â

REINFORCE는 불편하지만 시끄럽다. 행동 ata_t의 가중치로 쓰는 reward-to-go G^t\hat G_t에는 그 뒤에 일어난 모든 무작위성이 들어 있다. 2강에서 같은 문제를 TD로 풀었다. 끝까지 기다리지 말고 학습된 가치 추정으로 bootstrapping 하자. 정책을 배우는 actor 와 가치를 배우는 critic 을 함께 학습하는 이 구조가 actor-critic 이고, PPO는 그 가장 유명한 구현이다.

정책 경사에 무엇을 곱할 것인가

정책 경사의 일반형을 Ψt\Psi_t라는 가중치로 쓰자.

∇θJ=E[∑tΨt ∇θlog⁡πθ(at∣st)]\nabla_\theta J = \mathbb{E}\Big[\sum_t \Psi_t\, \nabla_\theta \log \pi_\theta(a_t \mid s_t)\Big]

지난 레슨에서 Ψt=R(τ)\Psi_t = R(\tau), G^t\hat G_t, G^t−b(st)\hat G_t - b(s_t)가 모두 같은 기댓값을 준다는 것을 봤다. 여기에 두 가지를 더한다. 조건부 기댓값의 탑 성질로 E[G^t∣st,at]=Qπ(st,at)\mathbb{E}[\hat G_t \mid s_t, a_t] = Q^\pi(s_t, a_t)이므로 G^t\hat G_t 대신 Qπ(st,at)Q^\pi(s_t, a_t)를 써도 되고, baseline으로 Vπ(st)V^\pi(s_t)를 빼면

Ψt=Aπ(st,at)=Qπ(st,at)−Vπ(st)\Psi_t = A^\pi(s_t, a_t) = Q^\pi(s_t, a_t) - V^\pi(s_t)

advantage 가 된다. 이것이 분산 측면에서 거의 이상적인 선택이다. “이 행동이 이 상태에서 평소보다 얼마나 나았나”만 남기고, 상태 자체가 좋았거나 나빴던 운은 지운다. 문제는 AπA^\pi를 모른다는 것이다. 이 레슨은 전부 AπA^\pi를 잘 추정하는 방법에 관한 것이다.

TD 오차는 advantage의 추정량이다

critic V≈VπV \approx V^\pi가 있다면 TD 오차

δt=rt+γV(st+1)−V(st)\delta_t = r_t + \gamma V(s_{t+1}) - V(s_t)

를 보자. V=VπV = V^\pi이면

E[δt∣st,at]=E[rt+γVπ(st+1)∣st,at]−Vπ(st)=Qπ(st,at)−Vπ(st)=Aπ(st,at)\begin{aligned} \mathbb{E}\big[\delta_t \mid s_t, a_t\big] &= \mathbb{E}\big[r_t + \gamma V^\pi(s_{t+1}) \mid s_t, a_t\big] - V^\pi(s_t) \\ &= Q^\pi(s_t, a_t) - V^\pi(s_t) = A^\pi(s_t, a_t) \end{aligned}

한 step짜리 샘플 하나로 advantage의 불편 추정을 얻는다. 무작위성은 rtr_t와 st+1s_{t+1} 한 번뿐이라 분산이 작다. 대신 V≠VπV \ne V^\pi인 만큼 편향된다. 2강의 MC 대 TD와 정확히 같은 거래다.

critic은 회귀로 배운다. 타깃 yty_t를 정하고 L(ϕ)=E[(Vϕ(st)−yt)2]\mathcal{L}(\phi) = \mathbb{E}[(V_\phi(s_t) - y_t)^2]를 줄인다. yt=G^ty_t = \hat G_t(MC)일 수도, rt+γVϕ(st+1)r_t + \gamma V_{\phi}(s_{t+1})(TD, 타깃 쪽은 기울기를 끊는다)일 수도, 아래의 λ-return일 수도 있다. 한 번의 반복은 다음과 같다.

  1. 현재 정책 πθ\pi_\theta로 궤적들을 모은다.
  2. critic으로 A^t\hat A_t를 계산한다.
  3. actor: θ←θ+α∑tA^t∇θlog⁡πθ(at∣st)\theta \leftarrow \theta + \alpha \sum_t \hat A_t \nabla_\theta \log \pi_\theta(a_t \mid s_t)
  4. critic: ϕ←ϕ−β∇ϕ∑t(Vϕ(st)−yt)2\phi \leftarrow \phi - \beta \nabla_\phi \sum_t (V_\phi(s_t) - y_t)^2

2강의 일반화된 정책 반복 그대로다. critic이 평가를, actor가 개선을 조금씩 한다. Mnih et al.(2016)의 A3C/A2C는 이것을 여러 환경에서 병렬로 돌리고 nn-step advantage와 entropy 보너스를 얹은 형태다.

n-step advantage

1-step δt\delta_t는 편향이 크고, G^t−V(st)\hat G_t - V(s_t)는 분산이 크다. 그 사이를 잇는 nn-step advantage는

A^t(n)=rt+γrt+1+⋯+γn−1rt+n−1+γnV(st+n)−V(st)\hat A^{(n)}_t = r_t + \gamma r_{t+1} + \cdots + \gamma^{n-1} r_{t+n-1} + \gamma^n V(s_{t+n}) - V(s_t)

이것을 TD 오차로 쓰면 놀랍게 간단해진다. ∑l=0n−1γlδt+l\sum_{l=0}^{n-1} \gamma^l \delta_{t+l}을 펼치면 중간의 VV들이 서로 상쇄된다(telescoping).

∑l=0n−1γlδt+l=∑l=0n−1γlrt+l+∑l=0n−1(γl+1V(st+l+1)−γlV(st+l))=∑l=0n−1γlrt+l+γnV(st+n)−V(st)  =  A^t(n)\begin{aligned} \sum_{l=0}^{n-1} \gamma^l \delta_{t+l} &= \sum_{l=0}^{n-1} \gamma^l r_{t+l} + \sum_{l=0}^{n-1}\big(\gamma^{l+1} V(s_{t+l+1}) - \gamma^l V(s_{t+l})\big) \\ &= \sum_{l=0}^{n-1} \gamma^l r_{t+l} + \gamma^n V(s_{t+n}) - V(s_t) \;=\; \hat A^{(n)}_t \end{aligned}

nn-step advantage는 TD 오차 nn개의 할인 합이다.

GAE: 모든 n의 지수 가중평균

어떤 nn을 고를지 정하는 대신, Schulman et al.(2016)은 모든 nn을 λn−1\lambda^{n-1}로 가중평균한다((1−λ)(1-\lambda)는 가중치 합을 1로 맞추는 정규화).

A^tGAE(γ,λ)=(1−λ)(A^t(1)+λA^t(2)+λ2A^t(3)+⋯)\hat A^{\text{GAE}(\gamma, \lambda)}_t = (1-\lambda)\big(\hat A^{(1)}_t + \lambda \hat A^{(2)}_t + \lambda^2 \hat A^{(3)}_t + \cdots\big)

각 A^t(n)\hat A^{(n)}_t에 위의 TD 오차 합을 넣고 γlδt+l\gamma^l \delta_{t+l}의 계수를 모으자. δt+l\delta_{t+l}은 n>ln > l인 모든 A^(n)\hat A^{(n)}에 들어 있으므로 계수는

(1−λ)∑n=l+1∞λn−1=(1−λ)⋅λl1−λ=λl(1-\lambda) \sum_{n=l+1}^{\infty} \lambda^{n-1} = (1-\lambda) \cdot \frac{\lambda^l}{1-\lambda} = \lambda^l

따라서

  A^tGAE(γ,λ)=∑l=0∞(γλ)l δt+l  ⟺A^t=δt+γλ A^t+1\boxed{\;\hat A^{\text{GAE}(\gamma, \lambda)}_t = \sum_{l=0}^{\infty} (\gamma\lambda)^l\, \delta_{t+l}\;} \qquad\Longleftrightarrow\qquad \hat A_t = \delta_t + \gamma\lambda\, \hat A_{t+1}

오른쪽 재귀식 덕분에 궤적을 뒤에서부터 한 번 훑으면 모든 tt의 advantage가 O(T)O(T)에 나온다. 에피소드가 끝나면 V(sT)=0V(s_T) = 0, 시간 제한으로 잘렸으면 V(sT)V(s_T)로 bootstrapping한다(이 둘을 구분하지 않는 것이 흔한 버그다).

두 극단은 이렇다.

  • λ = 0: A^t=δt\hat A_t = \delta_t. 1-step TD. 분산 최소, critic이 틀린 만큼 편향.
  • λ = 1: A^t=∑lγlδt+l=∑lγlrt+l−V(st)\hat A_t = \sum_l \gamma^l \delta_{t+l} = \sum_l \gamma^l r_{t+l} - V(s_t). telescoping으로 중간의 VV가 모두 사라지고 MC return에서 baseline을 뺀 것이 된다. 불편(critic이 틀려도 baseline 역할만 하므로), 분산 최대.

critic에 쓰는 타깃도 같은 계산에서 나온다. R^t=A^t+V(st)\hat R_t = \hat A_t + V(s_t)가 λ-return이다.

그림으로: δ와 Â

선택한 tselected t 0 δt – Ât – Gt − V(st) – 유효 길이effective length 1/(1−γλ) –
Top: the rewards rt of one trajectory (grey bars), the critic's estimates V(st) (blue dots — drag them up and down), and the actual return Gt (dashed). Middle: the TD error δt = rt + γV(st+1) − V(st) (orange) and the GAE Ât (blue). Bottom: the weights (γλ)k that Ât at the time t you clicked in the middle plot puts on future δ. Set λ to 0 and  = δ, so errors in V become the advantage as they are. Set λ to 1 and the intermediate Vs cancel, giving  = G − V(st); dragging one dot then changes only that cell's Â. With a terminal reward and λ < 1, the early tokens barely see the actual reward and rely on the critic alone. 위: 한 궤적의 보상 rt(회색 막대), critic의 추정 V(st)(파란 점, 위아래로 끌 수 있다), 실제 return Gt(점선). 가운데: TD 오차 δt = rt + γV(st+1) − V(st)(주황)와 GAE Ât(파랑). 아래: 가운데 그림에서 클릭한 시각 t의 Ât가 미래 δ에 주는 가중치 (γλ)k. λ를 0으로 두면  = δ라서 V의 오차가 그대로 advantage가 된다. λ를 1로 두면 중간 V들이 상쇄되어  = G − V(st)가 되고, 점 하나를 끌어도 그 칸의 Â만 변한다. 종단 보상에서 λ < 1이면 앞쪽 토큰들은 실제 보상을 거의 보지 못하고 critic만 믿는다.

Things to try:

  1. Terminal-reward preset, λ = 0: δ is mostly just “next V − current V”, and only the last step sees the actual reward. The advantage tracks the critic’s ups and downs.
  2. λ to 1: every cell’s  becomes 1−V(st)1 - V(s_t) (= G − V). Now drag one blue dot: only that cell’s  changes. Drag it at λ = 0 and that cell and the one before it change together. How critic error leaks into the advantage depends on λ.
  3. λ = 0.9, γ = 1, select t = 0: the purple weights below decay as 0.9k0.9^k. The actual reward 11 steps later gets a weight of only 0.911≈0.310.9^{11} \approx 0.31. For a 1000-token response it is 0.99990.9^{999} — effectively 0.
  4. V ← MC return: if the critic predicts this trajectory’s outcome exactly, every δ and  is 0. The gap between prediction and outcome is the learning signal.

Bias and variance in formulas

The figure above shows a single trajectory. Let us look at statistics over many trajectories. Suppose that relative to the true value VπV^\pi the critic is V(st)=Vπ(st)+etV(s_t) = V^\pi(s_t) + e_t, with eT=0e_T = 0 at termination. Take the expectation of the λ-return R^0=V(s0)+∑l(γλ)lδl\hat R_0 = V(s_0) + \sum_l (\gamma\lambda)^l \delta_l and subtract the true value; after simplifying with Vπ(sl)=E[rl]+γVπ(sl+1)V^\pi(s_l) = \mathbb{E}[r_l] + \gamma V^\pi(s_{l+1}), the coefficient of eje_j that remains is γjλj−1−γjλj\gamma^j\lambda^{j-1} - \gamma^j\lambda^j.

bias(λ)=(1−λ)∑j≥1γjλj−1ej,Var(λ)=∑l(γλ)2l Var⁡[rl]\text{bias}(\lambda) = (1 - \lambda) \sum_{j \ge 1} \gamma^j \lambda^{j-1} e_j, \qquad \text{Var}(\lambda) = \sum_{l} (\gamma\lambda)^{2l}\, \operatorname{Var}[r_l]

(e0e_0 cancels exactly. For simplicity we took only the reward noise to be random.) Both are conditional on the critic: the expectation and variance are over rewards, with the errors eje_j held fixed. At λ = 1 the bias is exactly 0; as λ shrinks, the variance sum gets geometrically shorter, but critic error leaks in at rate (1−λ)(1-\lambda). The figure below plots the variance and, for critics whose errors are drawn independently as ej∼N(0,ε2)e_j \sim \mathcal N(0, \varepsilon^2), the squared bias averaged over critics, Ecritic[bias(λ)2]=(1−λ)2ε2∑j≥1γ2jλ2(j−1)\mathbb{E}_{\text{critic}}[\text{bias}(\lambda)^2] = (1-\lambda)^2 \varepsilon^2 \sum_{j \ge 1} \gamma^{2j}\lambda^{2(j-1)}. Averaging the bias itself over critics would give 0; what matters is the bias of the one critic you actually have, so we average its square.

해 볼 것:

  1. 종단 보상 프리셋, λ = 0: δ는 대부분 “다음 V − 지금 V”뿐이고, 마지막 step만 실제 보상을 본다. advantage가 critic의 오르내림을 그대로 따라간다.
  2. λ를 1로: 모든 칸의 Â가 1−V(st)1 - V(s_t)(= G − V)가 된다. 이제 파란 점 하나를 끌어 보자. 그 칸의 Â만 바뀐다. λ = 0에서 끌면 그 칸과 바로 앞 칸이 함께 바뀐다. critic 오차가 advantage로 새어 들어가는 경로가 λ에 따라 다르다.
  3. λ = 0.9, γ = 1, t = 0을 선택: 아래 보라색 가중치가 0.9k0.9^k로 줄어든다. 11 step 뒤의 실제 보상은 0.911≈0.310.9^{11} \approx 0.31의 가중치만 받는다. 길이가 1000 토큰이면 0.99990.9^{999}, 사실상 0이다.
  4. V ← MC return: critic이 이 궤적의 결과를 정확히 예측하면 모든 δ와 Â가 0이다. 예측과 결과의 차이가 곧 학습 신호다.

Bias와 variance를 식으로

위 그림은 궤적 하나다. 여러 궤적에 걸친 통계를 보자. 참 가치 VπV^\pi에 대해 critic이 V(st)=Vπ(st)+etV(s_t) = V^\pi(s_t) + e_t이고 종단에서는 eT=0e_T = 0이라고 하자. λ-return R^0=V(s0)+∑l(γλ)lδl\hat R_0 = V(s_0) + \sum_l (\gamma\lambda)^l \delta_l의 기댓값에서 참값을 빼면, Vπ(sl)=E[rl]+γVπ(sl+1)V^\pi(s_l) = \mathbb{E}[r_l] + \gamma V^\pi(s_{l+1})을 써서 정리했을 때 eje_j의 계수가 γjλj−1−γjλj\gamma^j\lambda^{j-1} - \gamma^j\lambda^j로 남는다.

bias(λ)=(1−λ)∑j≥1γjλj−1ej,Var(λ)=∑l(γλ)2l Var⁡[rl]\text{bias}(\lambda) = (1 - \lambda) \sum_{j \ge 1} \gamma^j \lambda^{j-1} e_j, \qquad \text{Var}(\lambda) = \sum_{l} (\gamma\lambda)^{2l}\, \operatorname{Var}[r_l]

(e0e_0은 정확히 상쇄된다. 단순화를 위해 보상 잡음만 무작위라고 두었다.) 두 식 모두 critic을 고정한 조건부 값이다. 기댓값과 분산은 오차 eje_j를 고정한 채 보상에 대해 취한다. λ = 1이면 bias가 정확히 0이고, λ를 줄일수록 variance의 합이 기하급수적으로 짧아지는 대신 critic 오차가 (1−λ)(1-\lambda) 비율로 섞여 들어온다. 아래 그림은 variance와, 오차를 ej∼N(0,ε2)e_j \sim \mathcal N(0, \varepsilon^2)로 독립하게 뽑은 critic들에 대해 bias의 제곱을 평균한 Ecritic[bias(λ)2]=(1−λ)2ε2∑j≥1γ2jλ2(j−1)\mathbb{E}_{\text{critic}}[\text{bias}(\lambda)^2] = (1-\lambda)^2 \varepsilon^2 \sum_{j \ge 1} \gamma^{2j}\lambda^{2(j-1)}를 그린다. bias 자체를 critic에 대해 평균하면 0이 된다. 중요한 것은 실제로 가진 critic 하나의 bias이므로 그 제곱을 평균한다.

MSE 최소MSE-minimising λ* – λ=0: Ecritic[bias²] –, Varrewards – λ=1: Ecritic[bias²] –, Varrewards –
An analytic calculation of how well the λ-return (= Â0 + V(s0)) hits the true value on a trajectory of length T. Each reward has independent noise N(0, σ²). For a fixed critic with errors et = V(st) − Vπ(st), bias(λ) is the error of the estimator's mean over rewards, and the purple curve is the variance over rewards, Varrewards (it does not depend on the critic). The orange curve is Ecritic[bias²]: the square of that conditional bias, averaged over critics whose errors et are drawn independently from N(0, ε²). It is not the bias of the estimator averaged over critics, which is 0, since the errors have mean 0. MSE = Ecritic[bias²] + Varrewards. Set ε to 0 and the critic term vanishes, so λ = 0 is best; set σ to 0 and the reward variance vanishes, so λ = 1 is best. For example, at λ = 0, γ = 1, ε = 0.4, σ = 0 the λ-return is r0 + V(s1), whose conditional bias is e1, so the orange value is Ecritic[e1²] = ε² = 0.16. In reality both are present, and the optimum lies somewhere in between. Switch the reward position to 'end only' (LLM) and the reward noise enters only through (γλ)2(T−1), so the optimal λ* moves a long way towards 1, and sticks closer to 1 as T grows (with the defaults, about 0.96 at T = 40 and about 0.99 at T = 200). With a reward every step, λ* hardly depends on T. 길이 T의 궤적에서 λ-return(= Â0 + V(s0))이 참값을 얼마나 잘 맞히는지 해석적으로 계산했다. 각 보상에는 독립 잡음 N(0, σ²)이 있다. 오차가 et = V(st) − Vπ(st)인 critic 하나를 고정하면, bias(λ)는 보상에 대한 추정량 평균의 오차이고, 보라색 곡선은 보상에 대한 분산 Varrewards다(critic과 무관하다). 주황색 곡선은 Ecritic[bias²], 즉 오차 et를 N(0, ε²)에서 독립으로 뽑은 critic들에 대해 이 조건부 bias의 제곱을 평균한 값이다. critic에 대해 평균한 추정량의 bias가 아니다. 오차의 평균이 0이므로 그 bias는 0이다. MSE = Ecritic[bias²] + Varrewards. ε를 0으로 두면 critic 항이 사라져 λ = 0이 최선이고, σ를 0으로 두면 보상 분산이 사라져 λ = 1이 최선이다. 예를 들어 λ = 0, γ = 1, ε = 0.4, σ = 0에서 λ-return은 r0 + V(s1)이고 그 조건부 bias는 e1이므로, 주황색 값은 Ecritic[e1²] = ε² = 0.16이다. 실제로는 둘 다 있어서 그 사이 어딘가가 최적이다. 보상 위치를 '끝에만'으로 바꾸면(LLM) 보상 잡음은 (γλ)2(T−1)로만 들어와 최적 λ*가 1 쪽으로 크게 옮겨 가고, T를 키울수록 1에 더 붙는다(기본값에서 T = 40이면 약 0.96, T = 200이면 약 0.99). 매 step 보상일 때의 λ*는 T와 거의 무관하다.

Schulman et al. treat γ as a knob of the same kind. Even when you want to optimise an undiscounted objective, using γ<1\gamma < 1 reduces the noise from far-future rewards, at the cost of a bias that changes the objective itself. In their experiments the best λ was noticeably smaller than γ (in 3D locomotion, γ ∈ [0.99, 0.995] and λ ∈ [0.96, 0.99]; in cart-pole, γ ∈ [0.96, 0.99] and λ ∈ [0.92, 0.99]). They interpret this as: when the critic is reasonably accurate, the bias λ introduces is much smaller than the bias γ introduces.

확인 문제Check yourself

γ = λ = 1 and the critic outputs the same value b(x) for every token state of a given prompt. With only a terminal reward r(x, y), what is the GAE advantage of token t?

With λ = 1, A^t=∑lγlrt+l−V(st)=r(x,y)−b(x)\hat A_t = \sum_l \gamma^l r_{t+l} - V(s_t) = r(x,y) - b(x). Every token receives the same advantage. That is exactly REINFORCE with a baseline, and replacing b(x)b(x) with the mean reward of the samples for the same prompt gives the GRPO/RLOO advantage. So GRPO can be seen as “GAE(1, 1) with the critic set to a per-prompt constant that is estimated by MC instead of learned”. Incidentally, the δt\delta_t of the first choice is the advantage at λ = 0, and with this critic it is indeed 0 everywhere except the last token.

Implementing it

We implement GAE with the backward recursion and compare it with a direct computation of the definition (∑l(γλ)lδt+l\sum_l (\gamma\lambda)^l \delta_{t+l}). We also check the two extremes, and look at per-token advantages in an LLM-style batch of two concatenated responses (terminations marked by dones).

NumPy GAE: backward recursion vs direct sum
import numpy as np

def gae(rewards, values, dones, gamma=0.99, lam=0.95, last_value=0.0):
    """Backward recursion Â_t = δ_t + γλ(1-done_t) Â_{t+1}.
    values[t] = V(s_t). If dones[t]=1, s_{t+1} is terminal, so do not bootstrap.
    last_value: V of the state after the last one, when the rollout was truncated (not terminated)."""
    T = len(rewards)
    adv = np.zeros(T)
    next_adv, next_value = 0.0, last_value
    for t in reversed(range(T)):
        nonterm = 1.0 - dones[t]
        delta = rewards[t] + gamma * next_value * nonterm - values[t]
        next_adv = delta + gamma * lam * nonterm * next_adv
        adv[t] = next_adv
        next_value = values[t]
    return adv, adv + values            # advantage, and the critic target (λ-return)

def gae_direct(rewards, values, gamma, lam, last_value=0.0):
    """Straight from the definition: Â_t = Σ_l (γλ)^l δ_{t+l} (one segment, no terminations)"""
    T = len(rewards)
    delta = rewards + gamma * np.append(values[1:], last_value) - values
    return np.array([sum((gamma * lam) ** l * delta[t + l] for l in range(T - t)) for t in range(T)])

rng = np.random.default_rng(0)
T = 8
r, v = rng.normal(size=T), rng.normal(size=T)
for gamma, lam in [(0.99, 0.95), (1.0, 1.0), (0.9, 0.0)]:
    a_rec, _ = gae(r, v, np.zeros(T), gamma, lam, last_value=0.3)
    a_dir = gae_direct(r, v, gamma, lam, last_value=0.3)
    print(f"γ={gamma}, λ={lam}: max |recursion - direct sum| = {np.abs(a_rec - a_dir).max():.1e}")

gamma = 0.97
delta = r + gamma * np.append(v[1:], 0.3) - v
G = np.array([sum(gamma ** l * r[t + l] for l in range(T - t)) + gamma ** (T - t) * 0.3 for t in range(T)])
print(f"\nλ=0 → Â = δ_t            : {np.allclose(gae(r, v, np.zeros(T), gamma, 0.0, 0.3)[0], delta)}")
print(f"λ=1 → Â = G_t − V(s_t)   : {np.allclose(gae(r, v, np.zeros(T), gamma, 1.0, 0.3)[0], G - v)}")

# LLM style: γ=1, a single terminal reward. Two responses (lengths 5 and 4) concatenated, boundaries marked by dones
r_llm = np.array([0, 0, 0, 0, 1.0,   0, 0, 0, 0.0])
d_llm = np.array([0, 0, 0, 0, 1,     0, 0, 0, 1])
v_llm = np.array([.5, .55, .6, .7, .8,   .5, .4, .3, .2])
for lam in [1.0, 0.95, 0.0]:
    adv, _ = gae(r_llm, v_llm, d_llm, gamma=1.0, lam=lam)
    print(f"\nLLM, γ=1, λ={lam}:  response 1 (R=1) Â = {np.round(adv[:5], 2)}")
    print(f"                   response 2 (R=0) Â = {np.round(adv[5:], 2)}")
 

At λ = 1 the advantage of response 1 is 1−V(st)1 - V(s_t) and of response 2 is 0−V(st)0 - V(s_t). The later a token is — the more the critic already judged that success was likely — the less credit it gets for the success. At λ = 0 the credit concentrates on the tokens where the critic’s value rose sharply. That is the payoff of token-level credit assignment when the critic is accurate, and its danger when it is not.

Next we verify the bias/variance formulas. We draw 300 critics (each with a different error) and 300 trajectories per critic, measure the bias² and variance of the λ-return, and compare them with the analytic expressions.

NumPy Bias² and variance of the λ-return: simulation vs formula
T, gamma, sigma, eps = 40, 1.0, 0.15, 0.4           # length, discount, reward noise, critic error
m = rng.uniform(-0.2, 0.3, T)                       # mean reward at each step
V_true = np.cumsum(m[::-1])[::-1]                   # γ=1: V(s_t) = Σ_{l≥t} m_l
n_critics, n_traj = 300, 300
print(" λ    bias²(sim) bias²(eq)  var(sim)  var(eq)   MSE(eq)")
for lam in [0.0, 0.3, 0.5, 0.7, 0.8, 0.9, 1.0]:
    V_hat = V_true + eps * rng.standard_normal((n_critics, 1, T))      # critics with errors
    R = m + sigma * rng.standard_normal((n_critics, n_traj, T))        # reward samples
    V_next = np.concatenate([V_hat[..., 1:], np.zeros((n_critics, 1, 1))], -1)  # V(s_T)=0
    delta = R + gamma * V_next - V_hat
    est = V_hat[..., 0] + delta @ ((gamma * lam) ** np.arange(T))      # λ-return = Â_0 + V(s_0)
    var = est.var(1).mean()
    bias2 = max(0.0, ((est.mean(1) - V_true[0]) ** 2).mean() - var / n_traj)  # correct for sample-mean noise
    j = np.arange(1, T)
    b_th = (1 - lam) ** 2 * eps**2 * np.sum(gamma ** (2 * j) * lam ** (2 * (j - 1)))
    v_th = sigma**2 * np.sum((gamma * lam) ** (2 * np.arange(T)))
    print(f"{lam:4.2f}  {bias2:9.4f} {b_th:9.4f} {var:9.4f} {v_th:8.4f} {b_th + v_th:9.4f}")
 

In the batch layout used for LLM training (right padding, per-token rewards) it looks like this.

PyTorch GAE for token batches 로컬에서 실행run locally (pip install torch)
import torch

@torch.no_grad()
def compute_gae(rewards, values, mask, gamma=1.0, lam=0.95):
    """rewards, values, mask: (B, T), response tokens only, right-padded. mask=1 marks real tokens.
    rewards[b, t]: per-token reward (for RLHF-PPO, -β·KL_t, plus r(x, y) on the last real token)
    values[b, t] = V(s_t). The position after the last real token is treated as terminal (V=0)."""
    B, T = rewards.shape
    adv = torch.zeros_like(rewards)
    last = torch.zeros(B, device=rewards.device, dtype=rewards.dtype)
    zeros = torch.zeros_like(last)
    for t in reversed(range(T)):
        m_next = mask[:, t + 1] if t + 1 < T else zeros    # is the next position a real token?
        v_next = values[:, t + 1] if t + 1 < T else zeros
        delta = rewards[:, t] + gamma * v_next * m_next - values[:, t]
        last = delta + gamma * lam * m_next * last         # accumulation is cut when passing padding
        adv[:, t] = last
    adv = adv * mask
    returns = adv + values                                 # critic target (λ-return)
    return adv, returns
 

The critic in LLM RL

PPO-RLHF (Ziegler et al. 2019, Stiennon et al. 2020, Ouyang et al. 2022) puts this lesson’s actor-critic onto the token MDP as is. The value model is a transformer of roughly the policy’s size with a scalar head, often initialised from the reward model. At every token position it predicts Vϕ(x,y≤t)V_\phi(x, y_{\le t}). The per-token reward is the KL penalty against the reference model, −βlog⁡πθ(yt∣⋅)πref(yt∣⋅)-\beta \log \frac{\pi_\theta(y_t \mid \cdot)}{\pi_{\text{ref}}(y_t \mid \cdot)}, with r(x,y)r(x, y) added on the last token. γ=1\gamma = 1, and λ is commonly 1 or around 0.95. This gives each token a different advantage, i.e. credit assignment within the response (Track V rlhf/rlhf-ppo).

The GRPO family dropped the critic. The reasons are the ones we saw in this lesson.

  • Cost: the critic needs one more model the size of the policy, its optimizer state, and its forward/backward passes.
  • Hard to learn: with a 0/1 verifier reward, the token-level VV is “the probability of reaching the right answer from this prefix”. Predicting this accurately in the middle of a solution thousands of tokens long is hard, and with λ < 1 that error goes straight into the advantage (bias).
  • Long responses and λ: as in the figure above, with λ < 1 the early tokens see the actual reward only with weight (γλ)T(\gamma\lambda)^{T}. In a long chain of thought, almost all of the learning signal for the early part comes from the critic.
  • The alternative is cheap: sample several responses per prompt, and their mean is an MC estimate of V(x)V(x). As we saw in the quiz, this is the same as GAE(1, 1) with a constant baseline.

The price is that every token in a response receives the same advantage. Attempts to fill this gap — for example VinePPO, which runs extra rollouts from intermediate states to estimate values by MC, or process reward models (PRMs) — come up in Track V.

Summary

  • Weighting the policy gradient by the advantage Aπ=Qπ−VπA^\pi = Q^\pi - V^\pi erases the luck of the state and lowers variance. Actor-critic estimates it with a learned critic VϕV_\phi.
  • If V=VπV = V^\pi, then E[δt∣st,at]=Aπ(st,at)\mathbb{E}[\delta_t \mid s_t, a_t] = A^\pi(s_t, a_t). The nn-step advantage is the discounted sum of nn TD errors.
  • GAE: A^t=∑l(γλ)lδt+l=δt+γλA^t+1\hat A_t = \sum_l (\gamma\lambda)^l \delta_{t+l} = \delta_t + \gamma\lambda \hat A_{t+1}. λ = 0 is TD (biased), λ = 1 is MC − baseline (high variance). The critic target is A^t+V(st)\hat A_t + V(s_t).
  • The bias, (1−λ)∑jγjλj−1ej(1-\lambda)\sum_j \gamma^j\lambda^{j-1} e_j, comes from critic error; the variance, ∑l(γλ)2lVar⁡[rl]\sum_l (\gamma\lambda)^{2l}\operatorname{Var}[r_l], comes from reward noise.
  • PPO-RLHF uses a token-level critic + GAE; GRPO/RLOO use a group MC baseline instead of a critic, which is the same as GAE(1, 1) with a per-prompt constant baseline.

Schulman et al.은 γ도 같은 성격의 손잡이로 본다. 할인 없는 목적함수를 최적화하고 싶어도 γ<1\gamma < 1을 쓰면 먼 미래 보상의 잡음이 줄어든다. 대신 목적함수 자체가 바뀌는 편향을 받아들인다. 그들의 실험에서 가장 좋은 λ는 γ보다 눈에 띄게 작았다(3D 보행에서는 γ ∈ [0.99, 0.995], λ ∈ [0.96, 0.99], cart-pole에서는 γ ∈ [0.96, 0.99], λ ∈ [0.92, 0.99]). critic이 어느 정도 정확하면 λ가 만드는 편향이 γ가 만드는 편향보다 훨씬 작기 때문이라고 해석한다.

확인 문제Check yourself

γ = λ = 1이고 critic이 같은 프롬프트의 모든 토큰 상태에 같은 값 b(x)를 출력한다. 종단 보상 r(x, y)만 있을 때 토큰 t의 GAE advantage는?

λ = 1이면 A^t=∑lγlrt+l−V(st)=r(x,y)−b(x)\hat A_t = \sum_l \gamma^l r_{t+l} - V(s_t) = r(x,y) - b(x). 모든 토큰이 같은 advantage를 받는다. 이것이 정확히 REINFORCE with baseline이고, b(x)b(x)를 같은 프롬프트의 샘플들의 평균 보상으로 바꾸면 GRPO/RLOO의 advantage다. 즉 GRPO는 “critic을 프롬프트별 상수로 두고, 그 상수를 학습 대신 MC로 추정한 GAE(1, 1)“로 볼 수 있다. 참고로 첫 번째 선택지의 δt\delta_t는 λ = 0일 때의 advantage이고, 이 critic에서는 실제로 마지막 토큰 외에 0이 된다.

직접 구현하기

GAE를 역방향 재귀로 구현하고, 정의(∑l(γλ)lδt+l\sum_l (\gamma\lambda)^l \delta_{t+l})를 직접 계산한 값과 비교한다. 두 극단도 확인하고, 응답 두 개를 이어 붙인 LLM 스타일 배치(종단 표시 dones)에서 토큰별 advantage를 본다.

NumPy GAE: 역방향 재귀와 직접 합
import numpy as np

def gae(rewards, values, dones, gamma=0.99, lam=0.95, last_value=0.0):
    """역방향 재귀 Â_t = δ_t + γλ(1-done_t) Â_{t+1}.
    values[t] = V(s_t). dones[t]=1이면 s_{t+1}이 종단이므로 bootstrap하지 않는다.
    last_value: 롤아웃이 (종단이 아니라) 잘린 경우 마지막 다음 상태의 V."""
    T = len(rewards)
    adv = np.zeros(T)
    next_adv, next_value = 0.0, last_value
    for t in reversed(range(T)):
        nonterm = 1.0 - dones[t]
        delta = rewards[t] + gamma * next_value * nonterm - values[t]
        next_adv = delta + gamma * lam * nonterm * next_adv
        adv[t] = next_adv
        next_value = values[t]
    return adv, adv + values            # advantage, 그리고 critic 타깃(λ-return)

def gae_direct(rewards, values, gamma, lam, last_value=0.0):
    """정의 그대로: Â_t = Σ_l (γλ)^l δ_{t+l} (종단 없는 한 조각)"""
    T = len(rewards)
    delta = rewards + gamma * np.append(values[1:], last_value) - values
    return np.array([sum((gamma * lam) ** l * delta[t + l] for l in range(T - t)) for t in range(T)])

rng = np.random.default_rng(0)
T = 8
r, v = rng.normal(size=T), rng.normal(size=T)
for gamma, lam in [(0.99, 0.95), (1.0, 1.0), (0.9, 0.0)]:
    a_rec, _ = gae(r, v, np.zeros(T), gamma, lam, last_value=0.3)
    a_dir = gae_direct(r, v, gamma, lam, last_value=0.3)
    print(f"γ={gamma}, λ={lam}: |재귀 - 직접 합| 최대 = {np.abs(a_rec - a_dir).max():.1e}")

gamma = 0.97
delta = r + gamma * np.append(v[1:], 0.3) - v
G = np.array([sum(gamma ** l * r[t + l] for l in range(T - t)) + gamma ** (T - t) * 0.3 for t in range(T)])
print(f"\nλ=0 → Â = δ_t            : {np.allclose(gae(r, v, np.zeros(T), gamma, 0.0, 0.3)[0], delta)}")
print(f"λ=1 → Â = G_t − V(s_t)   : {np.allclose(gae(r, v, np.zeros(T), gamma, 1.0, 0.3)[0], G - v)}")

# LLM 스타일: γ=1, 종단 보상 하나. 응답 두 개(길이 5, 4)를 이어 붙이고 dones로 경계를 표시
r_llm = np.array([0, 0, 0, 0, 1.0,   0, 0, 0, 0.0])
d_llm = np.array([0, 0, 0, 0, 1,     0, 0, 0, 1])
v_llm = np.array([.5, .55, .6, .7, .8,   .5, .4, .3, .2])
for lam in [1.0, 0.95, 0.0]:
    adv, _ = gae(r_llm, v_llm, d_llm, gamma=1.0, lam=lam)
    print(f"\nLLM, γ=1, λ={lam}:  응답1(R=1) Â = {np.round(adv[:5], 2)}")
    print(f"                   응답2(R=0) Â = {np.round(adv[5:], 2)}")
 

λ = 1에서 응답 1의 advantage는 1−V(st)1 - V(s_t), 응답 2는 0−V(st)0 - V(s_t)다. critic이 “이미 성공할 것 같다”고 본 뒤쪽 토큰일수록 성공의 공을 덜 받는다. λ = 0이면 공이 critic 값이 크게 오른 토큰들로 몰린다. 이것이 critic이 정확할 때 토큰 단위 credit assignment가 주는 이득이고, 부정확할 때 생기는 위험이다.

다음은 bias/variance 식의 검증이다. critic 300개(각각 다른 오차)와 critic마다 궤적 300개를 뽑아 λ-return의 bias²와 분산을 재고 해석식과 비교한다.

NumPy λ-return의 bias²와 variance: 시뮬레이션 vs 식
T, gamma, sigma, eps = 40, 1.0, 0.15, 0.4           # 길이, 할인, 보상 잡음, critic 오차
m = rng.uniform(-0.2, 0.3, T)                       # 각 step 보상의 평균
V_true = np.cumsum(m[::-1])[::-1]                   # γ=1: V(s_t) = Σ_{l≥t} m_l
n_critics, n_traj = 300, 300
print(" λ    bias²(sim) bias²(식)  var(sim)  var(식)   MSE(식)")
for lam in [0.0, 0.3, 0.5, 0.7, 0.8, 0.9, 1.0]:
    V_hat = V_true + eps * rng.standard_normal((n_critics, 1, T))      # 오차 있는 critic들
    R = m + sigma * rng.standard_normal((n_critics, n_traj, T))        # 보상 샘플
    V_next = np.concatenate([V_hat[..., 1:], np.zeros((n_critics, 1, 1))], -1)  # V(s_T)=0
    delta = R + gamma * V_next - V_hat
    est = V_hat[..., 0] + delta @ ((gamma * lam) ** np.arange(T))      # λ-return = Â_0 + V(s_0)
    var = est.var(1).mean()
    bias2 = max(0.0, ((est.mean(1) - V_true[0]) ** 2).mean() - var / n_traj)  # 표본 평균 잡음 보정
    j = np.arange(1, T)
    b_th = (1 - lam) ** 2 * eps**2 * np.sum(gamma ** (2 * j) * lam ** (2 * (j - 1)))
    v_th = sigma**2 * np.sum((gamma * lam) ** (2 * np.arange(T)))
    print(f"{lam:4.2f}  {bias2:9.4f} {b_th:9.4f} {var:9.4f} {v_th:8.4f} {b_th + v_th:9.4f}")
 

LLM 학습에서 쓰는 배치 형태(오른쪽 padding, 토큰별 보상)로 쓰면 다음과 같다.

PyTorch 토큰 배치용 GAE 로컬에서 실행run locally (pip install torch)
import torch

@torch.no_grad()
def compute_gae(rewards, values, mask, gamma=1.0, lam=0.95):
    """rewards, values, mask: (B, T), 응답 토큰만, 오른쪽 padding. mask=1이 실제 토큰.
    rewards[b, t]: 토큰별 보상 (RLHF-PPO라면 -β·KL_t, 마지막 실제 토큰에는 + r(x, y))
    values[b, t] = V(s_t). 마지막 실제 토큰 다음은 종단(V=0)으로 본다."""
    B, T = rewards.shape
    adv = torch.zeros_like(rewards)
    last = torch.zeros(B, device=rewards.device, dtype=rewards.dtype)
    zeros = torch.zeros_like(last)
    for t in reversed(range(T)):
        m_next = mask[:, t + 1] if t + 1 < T else zeros    # 다음 위치가 실제 토큰인가
        v_next = values[:, t + 1] if t + 1 < T else zeros
        delta = rewards[:, t] + gamma * v_next * m_next - values[:, t]
        last = delta + gamma * lam * m_next * last         # padding을 지나며 누적이 끊긴다
        adv[:, t] = last
    adv = adv * mask
    returns = adv + values                                 # critic 타깃 (λ-return)
    return adv, returns
 

LLM RL에서의 critic

PPO-RLHF(Ziegler et al. 2019, Stiennon et al. 2020, Ouyang et al. 2022)는 이 레슨의 actor-critic을 그대로 토큰 MDP에 올린다. value 모델은 정책과 비슷한 크기의 트랜스포머에 스칼라 head를 단 것이고, 흔히 보상모델에서 초기화한다. 매 토큰 위치에서 Vϕ(x,y≤t)V_\phi(x, y_{\le t})를 예측한다. 토큰별 보상은 reference 모델과의 KL 페널티 −βlog⁡πθ(yt∣⋅)πref(yt∣⋅)-\beta \log \frac{\pi_\theta(y_t \mid \cdot)}{\pi_{\text{ref}}(y_t \mid \cdot)}이고 마지막 토큰에 r(x,y)r(x, y)가 더해진다. γ=1\gamma = 1, λ는 1이나 0.95 근처가 흔하다. 이렇게 하면 토큰마다 다른 advantage, 즉 응답 안에서의 credit assignment가 가능해진다(Track V rlhf/rlhf-ppo).

GRPO 계열은 critic을 버렸다. 이유는 이 레슨에서 본 것들이다.

  • 비용: critic은 정책만 한 모델 하나, 그 optimizer 상태, 그 forward/backward를 더 요구한다.
  • 학습 난이도: 0/1 검증기 보상에서 토큰 단위 VV는 “이 prefix에서 정답에 도달할 확률”이다. 수천 토큰짜리 풀이의 중간에서 이것을 정확히 예측하기는 어렵고, λ < 1이면 그 오차가 advantage로 직접 들어간다(bias).
  • 긴 응답과 λ: 위 그림처럼 λ < 1이면 앞쪽 토큰은 실제 보상을 (γλ)T(\gamma\lambda)^{T}만큼만 본다. 긴 chain-of-thought에서 앞부분의 학습 신호가 거의 전부 critic에서 온다.
  • 대안이 싸다: 프롬프트마다 응답을 여러 개 샘플하면 그 평균이 V(x)V(x)의 MC 추정이 된다. 퀴즈에서 본 것처럼 이것은 GAE(1, 1)에 상수 baseline을 쓰는 것과 같다.

대가는 응답 안의 모든 토큰이 같은 advantage를 받는다는 것이다. 이 공백을 메우려는 시도들, 예를 들어 중간 상태에서 추가로 rollout을 해서 가치를 MC로 추정하는 VinePPO나 과정 보상모델(PRM)이 Track V에서 나온다.

정리

  • 정책 경사의 가중치로 advantage Aπ=Qπ−VπA^\pi = Q^\pi - V^\pi를 쓰면 상태의 운이 지워져 분산이 작아진다. actor-critic은 이를 학습된 critic VϕV_\phi로 추정한다.
  • V=VπV = V^\pi이면 E[δt∣st,at]=Aπ(st,at)\mathbb{E}[\delta_t \mid s_t, a_t] = A^\pi(s_t, a_t). nn-step advantage는 TD 오차 nn개의 할인 합이다.
  • GAE: A^t=∑l(γλ)lδt+l=δt+γλA^t+1\hat A_t = \sum_l (\gamma\lambda)^l \delta_{t+l} = \delta_t + \gamma\lambda \hat A_{t+1}. λ = 0은 TD(편향), λ = 1은 MC − baseline(고분산). critic 타깃은 A^t+V(st)\hat A_t + V(s_t).
  • bias는 (1−λ)∑jγjλj−1ej(1-\lambda)\sum_j \gamma^j\lambda^{j-1} e_j로 critic 오차에서, variance는 ∑l(γλ)2lVar⁡[rl]\sum_l (\gamma\lambda)^{2l}\operatorname{Var}[r_l]로 보상 잡음에서 온다.
  • PPO-RLHF는 토큰 단위 critic + GAE를 쓰고, GRPO/RLOO는 critic 대신 그룹 MC baseline을 쓴다. 이는 GAE(1, 1)에 프롬프트별 상수 baseline을 쓰는 것과 같다.

더 읽을거리Further reading