Up to the last lesson we learned values first and extracted the policy from them (). This lesson goes the other way. We parameterise the policy directly and do gradient ascent on in the direction that increases the expected reward. This is the policy gradient. It is the natural fit for LLMs: a pretrained language model is already an excellent stochastic policy, and what we want to do is move that policy “a little towards higher reward”.
The objective
The probability of a trajectory is a product of environment and policy terms.
The goal is the expected return. In this lesson we write (, finite length).
The problem is that sits inside the sampling distribution. Unlike supervised learning’s , we cannot simply push the derivative inside the expectation. Moreover, actions are sampled discretely, so the reparameterization trick is unavailable too, and is not even differentiable (a verifier’s 0/1, a human’s preference).
The log-derivative trick
A single identity, , solves this.
The gradient has become an expectation under the same distribution again, so it can be estimated from samples. And expanding ,
the environment terms, which do not depend on , vanish when differentiated. We do not need to know the transition model.
is called the score function, which is why this estimator is also called the score function estimator, or the likelihood-ratio estimator.
REINFORCE
Replacing the expectation with samples gives Williams’s (1992) REINFORCE.
How you read it matters. is “the direction that makes this trajectory’s actions more likely”, i.e. the maximum-likelihood gradient on data the policy sampled itself. REINFORCE weights it by the reward. Read it as reward-weighted SFT on your own samples. With a 0/1 reward the direction is the same as picking out only the successful samples and doing SFT on them (the only difference is dividing by the total number of samples rather than the number of successes). So the implementation is one line that hands the following “surrogate loss” to autograd.
The value of this loss means nothing by itself. Only its gradient does.
The softmax policy case. For a bandit with actions, logits and , we have , so
This direction raises the chosen action’s logit by and lowers each of the others by . Multiply it by . But what happens if every reward is positive? Whatever is drawn, that action’s logit goes up; good actions just go up a bit more. Learning does work in the end, but the difference is buried in the noise of “which action happened to be drawn a few times”. This problem leads to the baseline.
The key lemma: the score has zero mean
(Spinning Up calls this the EGLP lemma.) Both of the policy gradient’s variance-reduction techniques come from this one line.
1. Causality: reward-to-go
The action at time cannot affect rewards received before it (). To check this in equations: for , conditioning on the history up to makes a constant, so
Removing terms with zero expectation keeps the estimator unbiased and only reduces noise. So instead of we use the reward-to-go .
2. Baseline
By the same argument, subtracting any function that does not depend on the action leaves the expectation unchanged.
There is exactly one condition: must not depend on that action . It may depend on the state, the past, and the rewards of other samples.
How much does the variance drop, and which is good? For a single parameter (one component of ), write ; the variance of the single-sample estimator is
The second term does not depend on (). Differentiating the first term with respect to and setting it to 0,
This is the average reward weighted by the size of the score. In practice one simply uses the expected reward . The weight then becomes an estimate of the advantage , and the policy gradient becomes “raise actions that did better than average, lower the ones that did worse”. This is the starting point of actor-critic in the next lesson.
This also shows what happens when you add a constant to the reward. Without a baseline, grows by . The expected gradient is unchanged; only the variance grows, by .
In a picture: the effect of a baseline
Below, a 5-armed bandit is trained with softmax-policy REINFORCE. The same setting is run with 40 seeds, showing the mean and the spread together.
지난 레슨까지는 가치를 먼저 배우고 정책을 거기서 꺼냈다(). 이 레슨은 반대로 간다. 정책 를 직접 매개화하고, 기대 보상이 커지는 방향으로 를 경사 상승시킨다. 정책 경사(policy gradient) 다. LLM에는 이쪽이 자연스럽다. 사전학습된 언어 모델이 이미 훌륭한 확률적 정책이고, 우리가 하고 싶은 일은 그 정책을 “보상이 높은 쪽으로 조금” 옮기는 것이기 때문이다.
목적함수
궤적 의 확률은 환경과 정책의 곱이다.
목표는 기대 return이다. 이 레슨에서는 로 쓴다(, 유한 길이).
문제는 가 샘플링 분포 안에 들어 있다는 것이다. 지도학습의 와 달리 기댓값 안으로 그냥 미분을 넣을 수 없다. 게다가 행동은 이산적으로 샘플되니 reparameterization trick도 쓸 수 없고, 은 미분 가능하지도 않다(검증기의 0/1, 사람의 선호).
Log-derivative trick
항등식 하나로 해결된다.
기울기가 다시 같은 분포에 대한 기댓값 이 되었으니 샘플로 추정할 수 있다. 그리고 를 펼치면
와 무관한 환경 항은 미분하면 사라진다. 전이 모델을 몰라도 된다.
를 score function 이라 부른다. 이 추정량은 그래서 score function estimator, 또는 likelihood-ratio estimator라고도 불린다.
REINFORCE
샘플 개로 기댓값을 바꾸면 Williams(1992)의 REINFORCE 다.
읽는 법이 중요하다. 는 “이 궤적의 행동들을 더 그럴듯하게 만드는 방향”, 즉 자기가 샘플한 데이터에 대한 최대우도 기울기 다. REINFORCE는 그것을 보상으로 가중한다. 보상으로 가중한 자기 샘플 SFT 라고 읽으면 된다. 보상이 0/1이면 성공한 샘플만 골라 SFT를 하는 것과 방향이 같다(성공 개수가 아니라 전체 샘플 수로 나눈다는 점만 다르다). 그래서 구현은 다음 “가짜 손실(surrogate loss)“을 autograd에 맡기는 한 줄이다.
이 손실의 값 자체는 아무 의미가 없다. 기울기만 의미가 있다.
Softmax 정책의 경우. 행동 개에 로짓 , 인 bandit이면 이므로
뽑힌 행동의 로짓은 만큼 올리고 나머지는 만큼 내리는 방향이다. 여기에 을 곱한다. 그런데 모든 보상이 양수면 어떻게 될까? 무엇을 뽑든 그 행동의 로짓을 올린다. 좋은 행동은 조금 더 많이 올릴 뿐이다. 학습은 결국 되지만, 그 차이가 “어떤 행동이 우연히 몇 번 뽑혔는가”의 잡음에 묻힌다. 이 문제가 baseline으로 이어진다.
핵심 보조정리: score의 기댓값은 0
(Spinning Up은 이것을 EGLP 보조정리라 부른다.) 정책 경사의 분산 감소 기법 두 가지가 모두 이 한 줄에서 나온다.
1. 인과성: reward-to-go
시각 의 행동은 그 전에 받은 보상 ()에 영향을 줄 수 없다. 수식으로 확인하면, 일 때 까지의 역사 를 조건으로 두면 은 상수이므로
기댓값이 0인 항을 빼도 불편성은 그대로이고, 잡음만 줄어든다. 그래서 대신 reward-to-go 를 쓴다.
2. Baseline
같은 논리로, 행동 에 의존하지 않는 어떤 함수 를 빼도 기댓값은 변하지 않는다.
조건은 딱 하나, 가 그 행동 에 의존하지 않을 것 이다. 상태, 과거, 다른 샘플들의 보상에는 의존해도 된다.
분산은 얼마나 줄고, 어떤 가 좋은가? 매개변수 하나(의 한 성분)에 대해 로 쓰면 단일 샘플 추정량 의 분산은
둘째 항은 와 무관하다(). 첫째 항을 로 미분해 0으로 두면
score 크기로 가중한 평균 보상이다. 실전에서는 그냥 기대 보상 를 쓴다. 그러면 가중치 는 advantage 의 추정이 되고, 정책 경사는 “평균보다 나은 행동은 올리고 못한 행동은 내린다”가 된다. 이것이 다음 레슨 actor-critic의 출발점이다.
보상에 상수 를 더하면 무슨 일이 생기는지도 여기서 보인다. baseline 없이 은 만큼 커진다. 기대 기울기는 그대로인데 분산만 로 커진다.
그림으로: baseline의 효과
아래는 팔 5개짜리 bandit을 softmax 정책 REINFORCE로 학습한다. 같은 설정을 seed 40개로 돌려 평균과 퍼짐을 함께 보여 준다.
Things to try:
- c = 0: the two methods differ little. The mean reward is already near 0, so the baseline has little to do.
- c at 5–10: the red band widens a lot and some seeds get stuck on a bad arm. The variance ratio jumps to tens of times. Blue stays the same.
- Increase the batch B and both improve; variance falls as . The baseline has the effect of “growing the batch tens of times for free”.
- Make η large and the side without a baseline becomes unstable first. The higher an estimator’s variance, the smaller the learning rate it tolerates.
- Drag one arm’s μ far above the others and both find it quickly. Variance reduction is decisive when the differences between arms are small relative to the noise.
Implementing it
First the bandit. We draw tens of thousands of estimates at one θ and check directly that their mean equals the true gradient (unbiased) and only their variance differs. The baseline is the mean of the other samples in the same batch (leave-one-out). It does not use the sample’s own reward, so it is independent of the action and unbiasedness is preserved.
import numpy as np
mu = np.array([1.0, 1.5, 2.0, 1.2, 0.8]) + 5.0 # every reward is around +5
sigma, K = 1.0, 5
def softmax(z):
z = z - z.max(-1, keepdims=True)
e = np.exp(z)
return e / e.sum(-1, keepdims=True)
def loo(R):
"""leave-one-out mean: the mean of the rest of the same batch, excluding oneself"""
B = R.shape[-1]
return (R.sum(-1, keepdims=True) - R) / (B - 1)
def grad_estimate(theta, B, rng, use_baseline):
"""ĝ = (1/B) Σ_i (R_i - b_i) ∇log π(a_i), ∇_θ log π(a) = onehot(a) - π
theta: (N, K) — computes N independent runs at once."""
pi = softmax(theta) # (N, K)
u = rng.random(theta.shape[:1] + (B, 1))
a = (u > pi.cumsum(-1)[:, None, :]).sum(-1) # (N, B) categorical sampling
R = mu[a] + sigma * rng.standard_normal(a.shape)
A = R - loo(R) if use_baseline else R
score = np.eye(K)[a] - pi[:, None, :] # (N, B, K)
return (A[..., None] * score).mean(1) # (N, K)
def train(use_baseline, lr=0.05, B=8, iters=300, runs=200, seed=0):
rng = np.random.default_rng(seed)
theta = np.zeros((runs, K))
for _ in range(iters):
theta += lr * grad_estimate(theta, B, rng, use_baseline)
return softmax(theta) @ mu # per-run J(θ) = Σ π_k μ_k
for name, ub in [("no baseline", False), ("LOO baseline", True)]:
J = train(ub)
print(f"{name:12s} J after 300 steps = {J.mean():.3f} ± {J.std():.3f} (max {mu.max():.1f})")
rng = np.random.default_rng(1)
theta0 = np.zeros((50000, K)) # 50,000 estimates at the uniform policy
pi0 = softmax(theta0[0])
print(f"\ntrue gradient ∇J = π(μ - J) = {np.round(pi0 * (mu - pi0 @ mu), 3)}")
for name, ub in [("no baseline", False), ("LOO baseline", True)]:
G = grad_estimate(theta0, 8, rng, ub)
se = np.sqrt(G.var(0).max() / len(G)) # standard error of the mean
print(f"{name:12s} estimator mean = {np.round(G.mean(0), 3)} (±{se:.3f}) tr Cov[ĝ] = {G.var(0).sum():.4f}")Now a small task that imitates an LLM. We generate length-4 sequences autoregressively from a 3-token vocabulary and receive a reward only once, at the end (the fraction of positions that match a target sequence — as if a verifier gave partial credit). A sequence’s score is the sum of token scores , and every token receives the same weight . We also look at what happens when a constant is added to the reward (for example, a “format reward” given to every response).
V, T = 3, 4 # vocabulary {0,1,2}, length 4 → 81 possible sequences
target = np.array([2, 0, 2, 1])
BOS = V # start symbol used in the 'previous token' slot at t=0
def sample(theta, B, rng):
"""autoregressive policy π(y_t | y_{t-1}, t). theta: (N, T, V+1, V) logits, N runs at once.
returns: y (N,B,T), per-sequence ∇_θ log π(y) = Σ_t ∇ log π(y_t | ·) (N,B,T,V+1,V)"""
N = theta.shape[0]
n = np.arange(N)[:, None]
y = np.zeros((N, B, T), dtype=int)
prev = np.full((N, B), BOS)
grads = np.zeros((N, B) + theta.shape[1:])
for t in range(T):
p = softmax(theta[n, t, prev]) # (N, B, V) next-token distribution
tok = (rng.random((N, B, 1)) > p.cumsum(-1)).sum(-1) # sample
grads[n, np.arange(B), t, prev] += np.eye(V)[tok] - p # add the token score
y[..., t] = tok
prev = tok
return y, grads
def train_seq(use_baseline, shift=0.0, lr=2.0, B=16, iters=60, runs=20, seed=0):
rng = np.random.default_rng(seed)
theta = np.zeros((runs, T, V + 1, V))
for _ in range(iters):
y, grads = sample(theta, B, rng)
R = (y == target).mean(-1) + shift # terminal reward (+ constant)
A = R - loo(R) if use_baseline else R # every token of a sequence gets the same A
theta += lr * (A[..., None, None, None] * grads).mean(1)
y, _ = sample(theta, 500, rng)
return (y == target).all(-1).mean(-1) # per-run P(correct sequence)
print("P(correct sequence) after 60 training steps (mean ± std over 20 runs)")
for shift in [0.0, 1.0]:
for name, ub in [("no baseline", False), ("LOO baseline", True)]:
acc = train_seq(ub, shift)
print(f" reward + {shift:.0f} {name:12s} {acc.mean():.3f} ± {acc.std():.3f}")
rng = np.random.default_rng(2)
theta0 = np.zeros((4000, T, V + 1, V))
y, grads = sample(theta0, 16, rng)
R = (y == target).mean(-1)
for name, A in [("no baseline", R), ("LOO baseline", R - loo(R))]:
G = (A[..., None, None, None] * grads).mean(1).reshape(4000, -1)
print(f"at initial θ, {name:12s} tr Cov[ĝ] = {G.var(0).sum():.4f}")Adding just 1 to the reward is enough for REINFORCE without a baseline to lock a good fraction of runs into a wrong sequence: a sequence that happened to be drawn early keeps getting reinforced “because its reward is positive”. With a baseline the constant shift is cancelled exactly, mathematically.
In LLM RL we sample 4 responses for each prompt x. If we use r_i − b as the advantage of response i, which b biases the policy gradient?
The baseline must not depend on the action (here, the response ). Response length is a function of , so and the gradient is biased (it is the same as directly rewarding/penalising length). The mean of the other responses (RLOO), , and a moving average of past rewards are all independent of . Note that subtracting the group mean that includes the sample itself gives , a constant multiple of an unbiased estimator.
REINFORCE for LLMs
In an LLM the actions are tokens, and the log-prob of a completion is the sum of token log-probs.
With reward only at the end and , every token’s reward-to-go is the same . The causality trick changes nothing, and the policy gradient is
Sample completions per prompt and use the mean of the other as the baseline and you have RLOO; subtract the group mean and divide by the group standard deviation and you have the GRPO advantage (dividing by the standard deviation changes the gradient’s magnitude per prompt, so it is not an unbiased estimate of the original objective; Track V covers this). The implementation looks like this.
import torch
def rloo_loss(logits, tokens, mask, rewards, k):
"""logits: (B, T, V) logits at completion positions (already shifted by one, prompt excluded)
tokens: (B, T) sampled completion tokens, mask: (B, T) 1 = real token, 0 = padding
rewards: (B,) sequence rewards. The batch holds k consecutive samples per prompt."""
logp = torch.log_softmax(logits.float(), dim=-1)
logp_tok = logp.gather(-1, tokens.unsqueeze(-1)).squeeze(-1) # (B, T) log π(y_t | x, y_<t)
seq_logp = (logp_tok * mask).sum(-1) # (B,) log π(y | x)
r = rewards.view(-1, k) # (P, k)
baseline = (r.sum(1, keepdim=True) - r) / (k - 1) # leave-one-out
adv = (r - baseline).view(-1) # (B,)
# gradient 'ascent', so flip the sign. adv is a constant: no gradient may flow into the reward.
return -(adv.detach() * seq_logp).mean()Summary
- : the log-derivative trick turns the gradient into an expectation we can sample, and the environment model drops out of the derivative.
- REINFORCE = reward-weighted maximum likelihood on your own samples. The implementation is autograd of .
- alone proves that reward-to-go and baselines keep the estimator unbiased. A baseline just must not depend on the action.
- A baseline removes variance, in particular the variance that comes from a constant shift in the reward. Baselines in practice are , the leave-one-out mean, and the group mean.
- For LLMs, the loss multiplies by . With a terminal reward every token gets the same advantage.
해 볼 것:
- c = 0: 두 방법의 차이가 작다. 보상의 평균이 이미 0 근처라 baseline이 할 일이 적다.
- c를 5–10으로: 빨간 띠가 크게 벌어지고 일부 seed는 나쁜 팔에 갇힌다. 분산 비율이 수십 배로 뛴다. 파랑은 그대로다.
- 배치 B를 키우면 둘 다 좋아진다. 분산은 로 준다. baseline은 “공짜로 배치를 수십 배 키운 효과”를 낸다.
- η를 크게 하면 baseline 없는 쪽부터 불안정해진다. 분산이 큰 추정량일수록 허용되는 학습률이 작다.
- 한 팔의 μ를 다른 팔들보다 아주 높게 끌어 올리면 둘 다 금방 찾는다. 팔들의 차이가 잡음에 비해 작을 때 분산 감소가 결정적이다.
직접 구현하기
먼저 bandit이다. 추정량 수만 개를 한 θ에서 뽑아 평균은 참 기울기와 같고(불편), 분산만 다르다 는 것을 직접 확인한다. baseline은 같은 배치의 다른 샘플들의 평균(leave-one-out)을 쓴다. 자기 자신의 보상을 쓰지 않으니 행동과 독립이고, 불편성이 유지된다.
import numpy as np
mu = np.array([1.0, 1.5, 2.0, 1.2, 0.8]) + 5.0 # 모든 보상이 +5 근처
sigma, K = 1.0, 5
def softmax(z):
z = z - z.max(-1, keepdims=True)
e = np.exp(z)
return e / e.sum(-1, keepdims=True)
def loo(R):
"""leave-one-out 평균: 같은 배치에서 자기 자신을 뺀 나머지의 평균"""
B = R.shape[-1]
return (R.sum(-1, keepdims=True) - R) / (B - 1)
def grad_estimate(theta, B, rng, use_baseline):
"""ĝ = (1/B) Σ_i (R_i - b_i) ∇log π(a_i), ∇_θ log π(a) = onehot(a) - π
theta: (N, K) — 독립 실행 N개를 한꺼번에 계산한다."""
pi = softmax(theta) # (N, K)
u = rng.random(theta.shape[:1] + (B, 1))
a = (u > pi.cumsum(-1)[:, None, :]).sum(-1) # (N, B) 범주 샘플링
R = mu[a] + sigma * rng.standard_normal(a.shape)
A = R - loo(R) if use_baseline else R
score = np.eye(K)[a] - pi[:, None, :] # (N, B, K)
return (A[..., None] * score).mean(1) # (N, K)
def train(use_baseline, lr=0.05, B=8, iters=300, runs=200, seed=0):
rng = np.random.default_rng(seed)
theta = np.zeros((runs, K))
for _ in range(iters):
theta += lr * grad_estimate(theta, B, rng, use_baseline)
return softmax(theta) @ mu # 실행별 J(θ) = Σ π_k μ_k
for name, ub in [("baseline 없음", False), ("LOO baseline", True)]:
J = train(ub)
print(f"{name:12s} 300 step 후 J = {J.mean():.3f} ± {J.std():.3f} (최댓값 {mu.max():.1f})")
rng = np.random.default_rng(1)
theta0 = np.zeros((50000, K)) # 균등 정책에서 5만 번 추정
pi0 = softmax(theta0[0])
print(f"\n참 기울기 ∇J = π(μ - J) = {np.round(pi0 * (mu - pi0 @ mu), 3)}")
for name, ub in [("baseline 없음", False), ("LOO baseline", True)]:
G = grad_estimate(theta0, 8, rng, ub)
se = np.sqrt(G.var(0).max() / len(G)) # 평균의 표본 오차
print(f"{name:12s} 추정량 평균 = {np.round(G.mean(0), 3)} (±{se:.3f}) tr Cov[ĝ] = {G.var(0).sum():.4f}")이제 LLM을 흉내 낸 작은 과제다. 어휘 3개로 길이 4 시퀀스를 자기회귀적으로 생성하고, 끝에서 한 번만 보상을 받는다(목표 시퀀스와 맞은 자리의 비율, 검증기가 부분 점수를 주는 셈). 시퀀스의 score는 토큰 score의 합 이고, 모든 토큰이 같은 가중치 를 받는다. 보상에 상수를 더했을 때(예: 모든 응답에 주는 “형식 보상”) 무슨 일이 생기는지도 본다.
V, T = 3, 4 # 어휘 {0,1,2}, 길이 4 → 가능한 시퀀스 81개
target = np.array([2, 0, 2, 1])
BOS = V # t=0에서 '이전 토큰' 자리에 쓰는 시작 기호
def sample(theta, B, rng):
"""자기회귀 정책 π(y_t | y_{t-1}, t). theta: (N, T, V+1, V) 로짓, N개 실행을 동시에.
반환: y (N,B,T), 시퀀스별 ∇_θ log π(y) = Σ_t ∇ log π(y_t | ·) (N,B,T,V+1,V)"""
N = theta.shape[0]
n = np.arange(N)[:, None]
y = np.zeros((N, B, T), dtype=int)
prev = np.full((N, B), BOS)
grads = np.zeros((N, B) + theta.shape[1:])
for t in range(T):
p = softmax(theta[n, t, prev]) # (N, B, V) 다음 토큰 분포
tok = (rng.random((N, B, 1)) > p.cumsum(-1)).sum(-1) # 샘플
grads[n, np.arange(B), t, prev] += np.eye(V)[tok] - p # 토큰 score를 더한다
y[..., t] = tok
prev = tok
return y, grads
def train_seq(use_baseline, shift=0.0, lr=2.0, B=16, iters=60, runs=20, seed=0):
rng = np.random.default_rng(seed)
theta = np.zeros((runs, T, V + 1, V))
for _ in range(iters):
y, grads = sample(theta, B, rng)
R = (y == target).mean(-1) + shift # 종단 보상 (+ 상수)
A = R - loo(R) if use_baseline else R # 시퀀스의 모든 토큰이 같은 A
theta += lr * (A[..., None, None, None] * grads).mean(1)
y, _ = sample(theta, 500, rng)
return (y == target).all(-1).mean(-1) # 실행별 P(정답 시퀀스)
print("60 step 학습 후 정답 시퀀스 확률 (실행 20개의 평균 ± 표준편차)")
for shift in [0.0, 1.0]:
for name, ub in [("baseline 없음", False), ("LOO baseline", True)]:
acc = train_seq(ub, shift)
print(f" 보상 + {shift:.0f} {name:12s} {acc.mean():.3f} ± {acc.std():.3f}")
rng = np.random.default_rng(2)
theta0 = np.zeros((4000, T, V + 1, V))
y, grads = sample(theta0, 16, rng)
R = (y == target).mean(-1)
for name, A in [("baseline 없음", R), ("LOO baseline", R - loo(R))]:
G = (A[..., None, None, None] * grads).mean(1).reshape(4000, -1)
print(f"초기 θ에서 {name:12s} tr Cov[ĝ] = {G.var(0).sum():.4f}")보상에 1만 더해도 baseline 없는 REINFORCE는 실행의 상당수가 틀린 시퀀스로 굳어 버린다. 초반에 우연히 뽑힌 시퀀스가 “보상이 양수니까” 계속 강화되기 때문이다. baseline이 있으면 상수 이동은 수학적으로 완전히 지워진다.
LLM RL에서 프롬프트 x마다 응답 4개를 샘플한다. 응답 i의 advantage로 r_i − b를 쓸 때, 정책 경사를 편향시키는 b는?
baseline은 그 행동(여기서는 응답 )에 의존하면 안 된다. 응답 길이는 의 함수이므로 이 되어 기울기가 편향된다(길이를 직접 보상/처벌하는 것과 같다). 나머지 응답들의 평균(RLOO), , 과거 보상의 이동평균은 모두 와 독립이다. 참고로 자기 자신을 포함한 그룹 평균 을 빼는 것은 라서 불편 추정량의 상수배다.
LLM에서의 REINFORCE
LLM에서 행동은 토큰이고, 완성문 의 log-prob은 토큰 log-prob의 합이다.
보상이 끝에만 있고 이면 모든 토큰의 reward-to-go가 똑같이 다. 인과성 트릭은 아무것도 바꾸지 않고, 정책 경사는
이다. 한 프롬프트에 대해 개를 샘플하고 나머지 개의 평균을 baseline으로 쓰면 RLOO, 그룹 평균을 빼고 그룹 표준편차로 나누면 GRPO 의 advantage다(표준편차로 나누는 것은 프롬프트마다 기울기의 크기를 바꾸므로 원래 목적함수의 불편 추정은 아니다. Track V에서 다룬다). 구현은 이렇다.
import torch
def rloo_loss(logits, tokens, mask, rewards, k):
"""logits: (B, T, V) 완성문 위치의 로짓 (한 칸 shift 완료, prompt 제외)
tokens: (B, T) 샘플된 완성문 토큰, mask: (B, T) 1 = 실제 토큰, 0 = padding
rewards: (B,) 시퀀스 보상. 배치는 프롬프트마다 k개 샘플이 연속으로 놓여 있다."""
logp = torch.log_softmax(logits.float(), dim=-1)
logp_tok = logp.gather(-1, tokens.unsqueeze(-1)).squeeze(-1) # (B, T) log π(y_t | x, y_<t)
seq_logp = (logp_tok * mask).sum(-1) # (B,) log π(y | x)
r = rewards.view(-1, k) # (P, k)
baseline = (r.sum(1, keepdim=True) - r) / (k - 1) # leave-one-out
adv = (r - baseline).view(-1) # (B,)
# 경사 '상승'이므로 부호를 뒤집는다. adv는 상수: 기울기가 보상 쪽으로 흐르면 안 된다.
return -(adv.detach() * seq_logp).mean()정리
- : log-derivative trick으로 기울기를 샘플 가능한 기댓값으로 바꾸고, 환경 모델은 미분에서 사라진다.
- REINFORCE = 보상 가중 자기 샘플 최대우도. 구현은 의 autograd.
- 하나로 reward-to-go와 baseline이 불편성을 유지한다는 것이 증명된다. baseline은 행동에만 의존하지 않으면 된다.
- baseline은 분산을, 특히 보상의 상수 이동에서 오는 분산을 없앤다. 실전의 baseline은 , leave-one-out 평균, 그룹 평균이다.
- LLM에서는 에 를 곱한 손실. 종단 보상이면 모든 토큰이 같은 advantage를 받는다.
더 읽을거리Further reading
- Williams, Simple Statistical Gradient-Following Algorithms for Connectionist Reinforcement Learning (Machine Learning 8, 1992) — REINFORCE의 원 논문. baseline(reinforcement comparison)도 여기서 나온다.The original REINFORCE paper. The baseline (reinforcement comparison) also comes from here.
- Sutton, McAllester, Singh, Mansour, Policy Gradient Methods for Reinforcement Learning with Function Approximation (NeurIPS 1999) — 정책 경사 정리(policy gradient theorem).The policy gradient theorem.
- OpenAI Spinning Up, Part 3: Intro to Policy Optimization — log-derivative trick, EGLP 보조정리, reward-to-go를 짧게 증명한다. 이 레슨의 유도 순서와 같다.Short proofs of the log-derivative trick, the EGLP lemma and reward-to-go, in the same order as this lesson's derivation.
- Greensmith, Bartlett, Baxter, Variance Reduction Techniques for Gradient Estimates in Reinforcement Learning (JMLR, 2004) — baseline의 분산 감소와 최적 baseline 분석.Variance reduction from baselines and an analysis of the optimal baseline.
- Kool, van Hoof, Welling, Buy 4 REINFORCE Samples, Get a Baseline for Free! (ICLR DeepRLStructPred Workshop, 2019) — leave-one-out baseline. LLM의 RLOO가 여기서 왔다.The leave-one-out baseline. LLM RLOO comes from here.
- Ahmadian et al., Back to Basics: Revisiting REINFORCE Style Optimization for Learning from Human Feedback in LLMs (ACL 2024) — RLHF에서 REINFORCE/RLOO가 PPO와 경쟁력이 있음을 보였다.Showed that REINFORCE/RLOO are competitive with PPO in RLHF.
- Nathan Lambert, Reinforcement Learning from Human Feedback — Policy Gradient Algorithms chapter (rlhfbook.com) — REINFORCE, RLOO, PPO, GRPO를 LLM 표기로 한 자리에 정리.REINFORCE, RLOO, PPO and GRPO in one place, in LLM notation.