REINFORCE is unbiased but noisy. The reward-to-go that weights action 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 .
In the previous lesson we saw that , and all give the same expectation. We add two more. By the tower property of conditional expectation, , so we may use instead of ; and subtracting as the baseline gives
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 . This whole lesson is about estimating well.
The TD error is an estimator of the advantage
Given a critic , look at the TD error
If , then
A single one-step sample gives an unbiased estimate of the advantage. The only randomness is one draw of and , so the variance is small. In exchange it is biased to the extent that . It is exactly the same trade as MC versus TD in Lesson 2.
The critic is learned by regression: pick a target and minimise . The target can be (MC), (TD, with the gradient stopped on the target side), or the λ-return below. One iteration looks like this.
- Collect trajectories with the current policy .
- Compute with the critic.
- actor:
- critic:
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 -step advantage and an entropy bonus on top.
n-step advantage
The 1-step has large bias, and has large variance. The -step advantage bridges the two:
Written in terms of TD errors, it becomes surprisingly simple. Expanding , the intermediate s cancel each other (telescoping).
The -step advantage is the discounted sum of TD errors.
GAE: an exponentially weighted average over every n
Instead of choosing one , Schulman et al. (2016) average over all with weights (the normalises the weights to sum to 1).
Substitute the TD-error sum above for each and collect the coefficient of . Since appears in every with , the coefficient is
Therefore
Thanks to the recursion on the right, a single backward sweep over the trajectory yields the advantage for every in . If the episode terminated, ; if it was cut off by a time limit, bootstrap with (failing to distinguish the two is a common bug).
The two extremes are:
- λ = 0: . 1-step TD. Minimum variance, biased by however wrong the critic is.
- λ = 1: . Telescoping removes all the intermediate s, 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: is the λ-return.
In a picture: δ and Â
REINFORCE는 불편하지만 시끄럽다. 행동 의 가중치로 쓰는 reward-to-go 에는 그 뒤에 일어난 모든 무작위성이 들어 있다. 2강에서 같은 문제를 TD로 풀었다. 끝까지 기다리지 말고 학습된 가치 추정으로 bootstrapping 하자. 정책을 배우는 actor 와 가치를 배우는 critic 을 함께 학습하는 이 구조가 actor-critic 이고, PPO는 그 가장 유명한 구현이다.
정책 경사에 무엇을 곱할 것인가
정책 경사의 일반형을 라는 가중치로 쓰자.
지난 레슨에서 , , 가 모두 같은 기댓값을 준다는 것을 봤다. 여기에 두 가지를 더한다. 조건부 기댓값의 탑 성질로 이므로 대신 를 써도 되고, baseline으로 를 빼면
advantage 가 된다. 이것이 분산 측면에서 거의 이상적인 선택이다. “이 행동이 이 상태에서 평소보다 얼마나 나았나”만 남기고, 상태 자체가 좋았거나 나빴던 운은 지운다. 문제는 를 모른다는 것이다. 이 레슨은 전부 를 잘 추정하는 방법에 관한 것이다.
TD 오차는 advantage의 추정량이다
critic 가 있다면 TD 오차
를 보자. 이면
한 step짜리 샘플 하나로 advantage의 불편 추정을 얻는다. 무작위성은 와 한 번뿐이라 분산이 작다. 대신 인 만큼 편향된다. 2강의 MC 대 TD와 정확히 같은 거래다.
critic은 회귀로 배운다. 타깃 를 정하고 를 줄인다. (MC)일 수도, (TD, 타깃 쪽은 기울기를 끊는다)일 수도, 아래의 λ-return일 수도 있다. 한 번의 반복은 다음과 같다.
- 현재 정책 로 궤적들을 모은다.
- critic으로 를 계산한다.
- actor:
- critic:
2강의 일반화된 정책 반복 그대로다. critic이 평가를, actor가 개선을 조금씩 한다. Mnih et al.(2016)의 A3C/A2C는 이것을 여러 환경에서 병렬로 돌리고 -step advantage와 entropy 보너스를 얹은 형태다.
n-step advantage
1-step 는 편향이 크고, 는 분산이 크다. 그 사이를 잇는 -step advantage는
이것을 TD 오차로 쓰면 놀랍게 간단해진다. 을 펼치면 중간의 들이 서로 상쇄된다(telescoping).
-step advantage는 TD 오차 개의 할인 합이다.
GAE: 모든 n의 지수 가중평균
어떤 을 고를지 정하는 대신, Schulman et al.(2016)은 모든 을 로 가중평균한다(는 가중치 합을 1로 맞추는 정규화).
각 에 위의 TD 오차 합을 넣고 의 계수를 모으자. 은 인 모든 에 들어 있으므로 계수는
따라서
오른쪽 재귀식 덕분에 궤적을 뒤에서부터 한 번 훑으면 모든 의 advantage가 에 나온다. 에피소드가 끝나면 , 시간 제한으로 잘렸으면 로 bootstrapping한다(이 둘을 구분하지 않는 것이 흔한 버그다).
두 극단은 이렇다.
- λ = 0: . 1-step TD. 분산 최소, critic이 틀린 만큼 편향.
- λ = 1: . telescoping으로 중간의 가 모두 사라지고 MC return에서 baseline을 뺀 것이 된다. 불편(critic이 틀려도 baseline 역할만 하므로), 분산 최대.
critic에 쓰는 타깃도 같은 계산에서 나온다. 가 λ-return이다.
그림으로: δ와 Â
Things to try:
- 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.
- λ to 1: every cell’s  becomes (= 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 λ.
- λ = 0.9, γ = 1, select t = 0: the purple weights below decay as . The actual reward 11 steps later gets a weight of only . For a 1000-token response it is — effectively 0.
- 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 the critic is , with at termination. Take the expectation of the λ-return and subtract the true value; after simplifying with , the coefficient of that remains is .
( 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 held fixed. At λ = 1 the bias is exactly 0; as λ shrinks, the variance sum gets geometrically shorter, but critic error leaks in at rate . The figure below plots the variance and, for critics whose errors are drawn independently as , the squared bias averaged over critics, . 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.
해 볼 것:
- 종단 보상 프리셋, λ = 0: δ는 대부분 “다음 V − 지금 V”뿐이고, 마지막 step만 실제 보상을 본다. advantage가 critic의 오르내림을 그대로 따라간다.
- λ를 1로: 모든 칸의 Â가 (= G − V)가 된다. 이제 파란 점 하나를 끌어 보자. 그 칸의 Â만 바뀐다. λ = 0에서 끌면 그 칸과 바로 앞 칸이 함께 바뀐다. critic 오차가 advantage로 새어 들어가는 경로가 λ에 따라 다르다.
- λ = 0.9, γ = 1, t = 0을 선택: 아래 보라색 가중치가 로 줄어든다. 11 step 뒤의 실제 보상은 의 가중치만 받는다. 길이가 1000 토큰이면 , 사실상 0이다.
- V ← MC return: critic이 이 궤적의 결과를 정확히 예측하면 모든 δ와 Â가 0이다. 예측과 결과의 차이가 곧 학습 신호다.
Bias와 variance를 식으로
위 그림은 궤적 하나다. 여러 궤적에 걸친 통계를 보자. 참 가치 에 대해 critic이 이고 종단에서는 이라고 하자. λ-return 의 기댓값에서 참값을 빼면, 을 써서 정리했을 때 의 계수가 로 남는다.
(은 정확히 상쇄된다. 단순화를 위해 보상 잡음만 무작위라고 두었다.) 두 식 모두 critic을 고정한 조건부 값이다. 기댓값과 분산은 오차 를 고정한 채 보상에 대해 취한다. λ = 1이면 bias가 정확히 0이고, λ를 줄일수록 variance의 합이 기하급수적으로 짧아지는 대신 critic 오차가 비율로 섞여 들어온다. 아래 그림은 variance와, 오차를 로 독립하게 뽑은 critic들에 대해 bias의 제곱을 평균한 를 그린다. bias 자체를 critic에 대해 평균하면 0이 된다. 중요한 것은 실제로 가진 critic 하나의 bias이므로 그 제곱을 평균한다.
Schulman et al. treat γ as a knob of the same kind. Even when you want to optimise an undiscounted objective, using 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.
γ = λ = 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, . Every token receives the same advantage. That is exactly REINFORCE with a baseline, and replacing 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 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 (). 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).
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 and of response 2 is . 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.
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.
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, returnsThe 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 . The per-token reward is the KL penalty against the reference model, , with added on the last token. , 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 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 . 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 . 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 erases the luck of the state and lowers variance. Actor-critic estimates it with a learned critic .
- If , then . The -step advantage is the discounted sum of TD errors.
- GAE: . λ = 0 is TD (biased), λ = 1 is MC − baseline (high variance). The critic target is .
- The bias, , comes from critic error; the variance, , 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.은 γ도 같은 성격의 손잡이로 본다. 할인 없는 목적함수를 최적화하고 싶어도 을 쓰면 먼 미래 보상의 잡음이 줄어든다. 대신 목적함수 자체가 바뀌는 편향을 받아들인다. 그들의 실험에서 가장 좋은 λ는 γ보다 눈에 띄게 작았다(3D 보행에서는 γ ∈ [0.99, 0.995], λ ∈ [0.96, 0.99], cart-pole에서는 γ ∈ [0.96, 0.99], λ ∈ [0.92, 0.99]). critic이 어느 정도 정확하면 λ가 만드는 편향이 γ가 만드는 편향보다 훨씬 작기 때문이라고 해석한다.
γ = λ = 1이고 critic이 같은 프롬프트의 모든 토큰 상태에 같은 값 b(x)를 출력한다. 종단 보상 r(x, y)만 있을 때 토큰 t의 GAE advantage는?
λ = 1이면 . 모든 토큰이 같은 advantage를 받는다. 이것이 정확히 REINFORCE with baseline이고, 를 같은 프롬프트의 샘플들의 평균 보상으로 바꾸면 GRPO/RLOO의 advantage다. 즉 GRPO는 “critic을 프롬프트별 상수로 두고, 그 상수를 학습 대신 MC로 추정한 GAE(1, 1)“로 볼 수 있다. 참고로 첫 번째 선택지의 는 λ = 0일 때의 advantage이고, 이 critic에서는 실제로 마지막 토큰 외에 0이 된다.
직접 구현하기
GAE를 역방향 재귀로 구현하고, 정의()를 직접 계산한 값과 비교한다. 두 극단도 확인하고, 응답 두 개를 이어 붙인 LLM 스타일 배치(종단 표시 dones)에서 토큰별 advantage를 본다.
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는 , 응답 2는 다. critic이 “이미 성공할 것 같다”고 본 뒤쪽 토큰일수록 성공의 공을 덜 받는다. λ = 0이면 공이 critic 값이 크게 오른 토큰들로 몰린다. 이것이 critic이 정확할 때 토큰 단위 credit assignment가 주는 이득이고, 부정확할 때 생기는 위험이다.
다음은 bias/variance 식의 검증이다. critic 300개(각각 다른 오차)와 critic마다 궤적 300개를 뽑아 λ-return의 bias²와 분산을 재고 해석식과 비교한다.
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, 토큰별 보상)로 쓰면 다음과 같다.
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, returnsLLM RL에서의 critic
PPO-RLHF(Ziegler et al. 2019, Stiennon et al. 2020, Ouyang et al. 2022)는 이 레슨의 actor-critic을 그대로 토큰 MDP에 올린다. value 모델은 정책과 비슷한 크기의 트랜스포머에 스칼라 head를 단 것이고, 흔히 보상모델에서 초기화한다. 매 토큰 위치에서 를 예측한다. 토큰별 보상은 reference 모델과의 KL 페널티 이고 마지막 토큰에 가 더해진다. , λ는 1이나 0.95 근처가 흔하다. 이렇게 하면 토큰마다 다른 advantage, 즉 응답 안에서의 credit assignment가 가능해진다(Track V rlhf/rlhf-ppo).
GRPO 계열은 critic을 버렸다. 이유는 이 레슨에서 본 것들이다.
- 비용: critic은 정책만 한 모델 하나, 그 optimizer 상태, 그 forward/backward를 더 요구한다.
- 학습 난이도: 0/1 검증기 보상에서 토큰 단위 는 “이 prefix에서 정답에 도달할 확률”이다. 수천 토큰짜리 풀이의 중간에서 이것을 정확히 예측하기는 어렵고, λ < 1이면 그 오차가 advantage로 직접 들어간다(bias).
- 긴 응답과 λ: 위 그림처럼 λ < 1이면 앞쪽 토큰은 실제 보상을 만큼만 본다. 긴 chain-of-thought에서 앞부분의 학습 신호가 거의 전부 critic에서 온다.
- 대안이 싸다: 프롬프트마다 응답을 여러 개 샘플하면 그 평균이 의 MC 추정이 된다. 퀴즈에서 본 것처럼 이것은 GAE(1, 1)에 상수 baseline을 쓰는 것과 같다.
대가는 응답 안의 모든 토큰이 같은 advantage를 받는다는 것이다. 이 공백을 메우려는 시도들, 예를 들어 중간 상태에서 추가로 rollout을 해서 가치를 MC로 추정하는 VinePPO나 과정 보상모델(PRM)이 Track V에서 나온다.
정리
- 정책 경사의 가중치로 advantage 를 쓰면 상태의 운이 지워져 분산이 작아진다. actor-critic은 이를 학습된 critic 로 추정한다.
- 이면 . -step advantage는 TD 오차 개의 할인 합이다.
- GAE: . λ = 0은 TD(편향), λ = 1은 MC − baseline(고분산). critic 타깃은 .
- bias는 로 critic 오차에서, variance는 로 보상 잡음에서 온다.
- PPO-RLHF는 토큰 단위 critic + GAE를 쓰고, GRPO/RLOO는 critic 대신 그룹 MC baseline을 쓴다. 이는 GAE(1, 1)에 프롬프트별 상수 baseline을 쓰는 것과 같다.
더 읽을거리Further reading
- Schulman, Moritz, Levine, Jordan, Abbeel, High-Dimensional Continuous Control Using Generalized Advantage Estimation (ICLR 2016) — GAE의 원 논문. Ψ_t의 여러 선택지, γ와 λ의 해석, λ-return과의 관계.The original GAE paper. The choices for Ψ_t, how to read γ and λ, and the relation to the λ-return.
- Mnih et al., Asynchronous Methods for Deep Reinforcement Learning (ICML 2016) — A3C. n-step advantage actor-critic, 병렬 actor, entropy 보너스.A3C. n-step advantage actor-critic, parallel actors, an entropy bonus.
- Konda & Tsitsiklis, Actor-Critic Algorithms (NeurIPS 1999) — 두 시간 척도(two-timescale) actor-critic의 수렴 분석.Convergence analysis of two-timescale actor-critic.
- Sutton & Barto, Reinforcement Learning: An Introduction, 2nd ed. (2018) Ch. 7, 12, 13 — n-step 방법, λ-return과 eligibility trace, actor-critic.n-step methods, the λ-return and eligibility traces, actor-critic.
- Ouyang et al., Training language models to follow instructions with human feedback (NeurIPS 2022) — InstructGPT. 토큰 단위 value 모델을 쓰는 PPO-RLHF의 표준 레시피.InstructGPT. The standard PPO-RLHF recipe with a token-level value model.
- Shao et al., DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models (2024) — GRPO. critic을 그룹 평균 baseline으로 대체했다.GRPO. Replaces the critic with a group-mean baseline.
- Nathan Lambert, Reinforcement Learning from Human Feedback (rlhfbook.com) — value 모델과 GAE를 LLM 학습 맥락에서 설명한다.Explains the value model and GAE in the context of LLM training.