Track IV · RL Fundamentals · 03/05

정책 경사와 REINFORCEPolicy gradients and REINFORCE

기대 보상 J(θ)의 기울기를 log-derivative trick으로 유도하고, REINFORCE·reward-to-go·baseline이 왜 불편성을 유지하면서 분산을 줄이는지 증명한다. LLM에서는 이것이 "완성문의 토큰 log-prob 합에 (보상 − baseline)을 곱한 손실"이 된다.Derive the gradient of the expected reward J(θ) with the log-derivative trick, and prove why REINFORCE, reward-to-go and baselines reduce variance while staying unbiased. For an LLM this becomes "a loss that multiplies the sum of a completion's token log-probs by (reward − baseline)".

40 분min policy gradient · REINFORCE · log-derivative trick · score function · baseline · variance reduction · RLOO 먼저 볼 것:Before this: MDP와 Bellman 방정식MDPs and the Bellman equation, 확률로 보는 손실Losses through probability

Up to the last lesson we learned values first and extracted the policy from them (arg⁡max⁡aQ\arg\max_a Q). This lesson goes the other way. We parameterise the policy πθ\pi_\theta directly and do gradient ascent on θ\theta 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 τ=(s0,a0,s1,a1,… )\tau = (s_0, a_0, s_1, a_1, \dots) is a product of environment and policy terms.

pθ(τ)=ρ0(s0)∏tπθ(at∣st) P(st+1∣st,at)p_\theta(\tau) = \rho_0(s_0) \prod_{t} \pi_\theta(a_t \mid s_t)\, P(s_{t+1} \mid s_t, a_t)

The goal is the expected return. In this lesson we write R(τ)=∑trtR(\tau) = \sum_t r_t (γ=1\gamma = 1, finite length).

J(θ)=Eτ∼pθ[R(τ)]=∫pθ(τ) R(τ) dτJ(\theta) = \mathbb{E}_{\tau \sim p_\theta}\big[R(\tau)\big] = \int p_\theta(\tau)\, R(\tau)\, d\tau

The problem is that θ\theta sits inside the sampling distribution. Unlike supervised learning’s E(x,y)∼D[ℓθ(x,y)]\mathbb{E}_{(x,y) \sim \mathcal D}[\ell_\theta(x, y)], we cannot simply push the derivative inside the expectation. Moreover, actions are sampled discretely, so the reparameterization trick is unavailable too, and RR is not even differentiable (a verifier’s 0/1, a human’s preference).

The log-derivative trick

A single identity, ∇θpθ=pθ ∇θlog⁡pθ\nabla_\theta p_\theta = p_\theta\, \nabla_\theta \log p_\theta, solves this.

∇θJ(θ)=∫∇θpθ(τ) R(τ) dτ=∫pθ(τ) ∇θlog⁡pθ(τ) R(τ) dτ=Eτ∼pθ[∇θlog⁡pθ(τ) R(τ)]\begin{aligned} \nabla_\theta J(\theta) &= \int \nabla_\theta p_\theta(\tau)\, R(\tau)\, d\tau = \int p_\theta(\tau)\, \nabla_\theta \log p_\theta(\tau)\, R(\tau)\, d\tau \\ &= \mathbb{E}_{\tau \sim p_\theta}\big[\nabla_\theta \log p_\theta(\tau)\, R(\tau)\big] \end{aligned}

The gradient has become an expectation under the same distribution again, so it can be estimated from samples. And expanding log⁡pθ(τ)\log p_\theta(\tau),

log⁡pθ(τ)=log⁡ρ0(s0)+∑tlog⁡πθ(at∣st)+∑tlog⁡P(st+1∣st,at)\log p_\theta(\tau) = \log \rho_0(s_0) + \sum_t \log \pi_\theta(a_t \mid s_t) + \sum_t \log P(s_{t+1} \mid s_t, a_t)

the environment terms, which do not depend on θ\theta, vanish when differentiated. We do not need to know the transition model.

  ∇θJ(θ)=Eτ∼πθ[(∑t∇θlog⁡πθ(at∣st)) R(τ)]  \boxed{\;\nabla_\theta J(\theta) = \mathbb{E}_{\tau \sim \pi_\theta}\Big[\Big(\sum_t \nabla_\theta \log \pi_\theta(a_t \mid s_t)\Big)\, R(\tau)\Big]\;}

∇θlog⁡πθ(a∣s)\nabla_\theta \log \pi_\theta(a \mid s) 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 NN samples gives Williams’s (1992) REINFORCE.

g^=1N∑i=1NR(τi)∑t∇θlog⁡πθ(ati∣sti),θ←θ+α g^\hat g = \frac{1}{N} \sum_{i=1}^{N} R(\tau^i) \sum_t \nabla_\theta \log \pi_\theta(a^i_t \mid s^i_t), \qquad \theta \leftarrow \theta + \alpha\, \hat g

How you read it matters. ∑t∇log⁡πθ(at∣st)\sum_t \nabla \log \pi_\theta(a_t \mid s_t) 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.

L(θ)=−1N∑iR(τi)∑tlog⁡πθ(ati∣sti)(R treated as a constant)\mathcal{L}(\theta) = -\frac{1}{N}\sum_i R(\tau^i)\sum_t \log \pi_\theta(a^i_t \mid s^i_t) \quad (R\text{ treated as a constant})

The value of this loss means nothing by itself. Only its gradient does.

The softmax policy case. For a bandit with KK actions, logits θ∈RK\theta \in \mathbb{R}^K and π=softmax(θ)\pi = \mathrm{softmax}(\theta), we have log⁡π(a)=θa−log⁡∑keθk\log \pi(a) = \theta_a - \log \sum_k e^{\theta_k}, so

∇θlog⁡πθ(a)=ea−π\nabla_\theta \log \pi_\theta(a) = e_a - \pi

This direction raises the chosen action’s logit by (1−πa)(1 - \pi_a) and lowers each of the others by πk\pi_k. Multiply it by RR. 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

Ea∼πθ[∇θlog⁡πθ(a∣s)]=∑aπθ(a∣s) ∇θπθ(a∣s)πθ(a∣s)=∇θ∑aπθ(a∣s)=∇θ1=0\mathbb{E}_{a \sim \pi_\theta}\big[\nabla_\theta \log \pi_\theta(a \mid s)\big] = \sum_a \pi_\theta(a \mid s)\, \frac{\nabla_\theta \pi_\theta(a \mid s)}{\pi_\theta(a \mid s)} = \nabla_\theta \sum_a \pi_\theta(a \mid s) = \nabla_\theta 1 = 0

(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 tt cannot affect rewards rt′r_{t'} received before it (t′<tt' < t). To check this in equations: for t′<tt' < t, conditioning on the history hth_t up to sts_t makes rt′r_{t'} a constant, so

E[∇θlog⁡πθ(at∣st) rt′]=Eht[rt′  Eat∼πθ[∇θlog⁡πθ(at∣st)]⏟=0]=0\mathbb{E}\big[\nabla_\theta \log \pi_\theta(a_t \mid s_t)\, r_{t'}\big] = \mathbb{E}_{h_t}\Big[r_{t'}\; \underbrace{\mathbb{E}_{a_t \sim \pi_\theta}\big[\nabla_\theta \log \pi_\theta(a_t \mid s_t)\big]}_{=0}\Big] = 0

Removing terms with zero expectation keeps the estimator unbiased and only reduces noise. So instead of R(τ)R(\tau) we use the reward-to-go G^t=∑t′≥trt′\hat G_t = \sum_{t' \ge t} r_{t'}.

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

2. Baseline

By the same argument, subtracting any function b(st)b(s_t) that does not depend on the action ata_t leaves the expectation unchanged.

E[∇θlog⁡πθ(at∣st) b(st)]=Est[b(st) Eat[∇θlog⁡πθ(at∣st)]]=0\mathbb{E}\big[\nabla_\theta \log \pi_\theta(a_t \mid s_t)\, b(s_t)\big] = \mathbb{E}_{s_t}\Big[b(s_t)\, \mathbb{E}_{a_t}\big[\nabla_\theta \log \pi_\theta(a_t \mid s_t)\big]\Big] = 0∇θJ=E[∑t∇θlog⁡πθ(at∣st) (G^t−b(st))]\nabla_\theta J = \mathbb{E}\Big[\sum_t \nabla_\theta \log \pi_\theta(a_t \mid s_t)\, \big(\hat G_t - b(s_t)\big)\Big]

There is exactly one condition: bb must not depend on that action ata_t. It may depend on the state, the past, and the rewards of other samples.

How much does the variance drop, and which bb is good? For a single parameter (one component of θ\theta), write s=∂θlog⁡πθ(a)s = \partial_\theta \log \pi_\theta(a); the variance of the single-sample estimator g=s (R−b)g = s\,(R - b) is

Var⁡[g]=E[s2(R−b)2]−(E[sR])2\operatorname{Var}[g] = \mathbb{E}\big[s^2 (R - b)^2\big] - \big(\mathbb{E}[s R]\big)^2

The second term does not depend on bb (E[s b]=0\mathbb{E}[s\, b] = 0). Differentiating the first term with respect to bb and setting it to 0,

−2 E[s2(R−b)]=0⟹b⋆=E[s2R]E[s2]-2\, \mathbb{E}\big[s^2 (R - b)\big] = 0 \quad\Longrightarrow\quad b^\star = \frac{\mathbb{E}[s^2 R]}{\mathbb{E}[s^2]}

This is the average reward weighted by the size of the score. In practice one simply uses the expected reward b(s)≈Vπ(s)b(s) \approx V^\pi(s). The weight G^t−Vπ(st)\hat G_t - V^\pi(s_t) then becomes an estimate of the advantage Aπ(st,at)A^\pi(s_t, a_t), 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 cc to the reward. Without a baseline, E[s2(R+c)2]\mathbb{E}[s^2 (R + c)^2] grows by c2 E[s2]c^2\,\mathbb{E}[s^2]. The expected gradient is unchanged; only the variance grows, by c2c^2.

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.

지난 레슨까지는 가치를 먼저 배우고 정책을 거기서 꺼냈다(arg⁡max⁡aQ\arg\max_a Q). 이 레슨은 반대로 간다. 정책 πθ\pi_\theta를 직접 매개화하고, 기대 보상이 커지는 방향으로 θ\theta를 경사 상승시킨다. 정책 경사(policy gradient) 다. LLM에는 이쪽이 자연스럽다. 사전학습된 언어 모델이 이미 훌륭한 확률적 정책이고, 우리가 하고 싶은 일은 그 정책을 “보상이 높은 쪽으로 조금” 옮기는 것이기 때문이다.

목적함수

궤적 τ=(s0,a0,s1,a1,… )\tau = (s_0, a_0, s_1, a_1, \dots)의 확률은 환경과 정책의 곱이다.

pθ(τ)=ρ0(s0)∏tπθ(at∣st) P(st+1∣st,at)p_\theta(\tau) = \rho_0(s_0) \prod_{t} \pi_\theta(a_t \mid s_t)\, P(s_{t+1} \mid s_t, a_t)

목표는 기대 return이다. 이 레슨에서는 R(τ)=∑trtR(\tau) = \sum_t r_t로 쓴다(γ=1\gamma = 1, 유한 길이).

J(θ)=Eτ∼pθ[R(τ)]=∫pθ(τ) R(τ) dτJ(\theta) = \mathbb{E}_{\tau \sim p_\theta}\big[R(\tau)\big] = \int p_\theta(\tau)\, R(\tau)\, d\tau

문제는 θ\theta가 샘플링 분포 안에 들어 있다는 것이다. 지도학습의 E(x,y)∼D[ℓθ(x,y)]\mathbb{E}_{(x,y) \sim \mathcal D}[\ell_\theta(x, y)]와 달리 기댓값 안으로 그냥 미분을 넣을 수 없다. 게다가 행동은 이산적으로 샘플되니 reparameterization trick도 쓸 수 없고, RR은 미분 가능하지도 않다(검증기의 0/1, 사람의 선호).

Log-derivative trick

항등식 ∇θpθ=pθ ∇θlog⁡pθ\nabla_\theta p_\theta = p_\theta\, \nabla_\theta \log p_\theta 하나로 해결된다.

∇θJ(θ)=∫∇θpθ(τ) R(τ) dτ=∫pθ(τ) ∇θlog⁡pθ(τ) R(τ) dτ=Eτ∼pθ[∇θlog⁡pθ(τ) R(τ)]\begin{aligned} \nabla_\theta J(\theta) &= \int \nabla_\theta p_\theta(\tau)\, R(\tau)\, d\tau = \int p_\theta(\tau)\, \nabla_\theta \log p_\theta(\tau)\, R(\tau)\, d\tau \\ &= \mathbb{E}_{\tau \sim p_\theta}\big[\nabla_\theta \log p_\theta(\tau)\, R(\tau)\big] \end{aligned}

기울기가 다시 같은 분포에 대한 기댓값 이 되었으니 샘플로 추정할 수 있다. 그리고 log⁡pθ(τ)\log p_\theta(\tau)를 펼치면

log⁡pθ(τ)=log⁡ρ0(s0)+∑tlog⁡πθ(at∣st)+∑tlog⁡P(st+1∣st,at)\log p_\theta(\tau) = \log \rho_0(s_0) + \sum_t \log \pi_\theta(a_t \mid s_t) + \sum_t \log P(s_{t+1} \mid s_t, a_t)

θ\theta와 무관한 환경 항은 미분하면 사라진다. 전이 모델을 몰라도 된다.

  ∇θJ(θ)=Eτ∼πθ[(∑t∇θlog⁡πθ(at∣st)) R(τ)]  \boxed{\;\nabla_\theta J(\theta) = \mathbb{E}_{\tau \sim \pi_\theta}\Big[\Big(\sum_t \nabla_\theta \log \pi_\theta(a_t \mid s_t)\Big)\, R(\tau)\Big]\;}

∇θlog⁡πθ(a∣s)\nabla_\theta \log \pi_\theta(a \mid s)를 score function 이라 부른다. 이 추정량은 그래서 score function estimator, 또는 likelihood-ratio estimator라고도 불린다.

REINFORCE

샘플 NN개로 기댓값을 바꾸면 Williams(1992)의 REINFORCE 다.

g^=1N∑i=1NR(τi)∑t∇θlog⁡πθ(ati∣sti),θ←θ+α g^\hat g = \frac{1}{N} \sum_{i=1}^{N} R(\tau^i) \sum_t \nabla_\theta \log \pi_\theta(a^i_t \mid s^i_t), \qquad \theta \leftarrow \theta + \alpha\, \hat g

읽는 법이 중요하다. ∑t∇log⁡πθ(at∣st)\sum_t \nabla \log \pi_\theta(a_t \mid s_t)는 “이 궤적의 행동들을 더 그럴듯하게 만드는 방향”, 즉 자기가 샘플한 데이터에 대한 최대우도 기울기 다. REINFORCE는 그것을 보상으로 가중한다. 보상으로 가중한 자기 샘플 SFT 라고 읽으면 된다. 보상이 0/1이면 성공한 샘플만 골라 SFT를 하는 것과 방향이 같다(성공 개수가 아니라 전체 샘플 수로 나눈다는 점만 다르다). 그래서 구현은 다음 “가짜 손실(surrogate loss)“을 autograd에 맡기는 한 줄이다.

L(θ)=−1N∑iR(τi)∑tlog⁡πθ(ati∣sti)(R은 상수 취급)\mathcal{L}(\theta) = -\frac{1}{N}\sum_i R(\tau^i)\sum_t \log \pi_\theta(a^i_t \mid s^i_t) \quad (R\text{은 상수 취급})

이 손실의 값 자체는 아무 의미가 없다. 기울기만 의미가 있다.

Softmax 정책의 경우. 행동 KK개에 로짓 θ∈RK\theta \in \mathbb{R}^K, π=softmax(θ)\pi = \mathrm{softmax}(\theta)인 bandit이면 log⁡π(a)=θa−log⁡∑keθk\log \pi(a) = \theta_a - \log \sum_k e^{\theta_k}이므로

∇θlog⁡πθ(a)=ea−π\nabla_\theta \log \pi_\theta(a) = e_a - \pi

뽑힌 행동의 로짓은 (1−πa)(1 - \pi_a)만큼 올리고 나머지는 πk\pi_k만큼 내리는 방향이다. 여기에 RR을 곱한다. 그런데 모든 보상이 양수면 어떻게 될까? 무엇을 뽑든 그 행동의 로짓을 올린다. 좋은 행동은 조금 더 많이 올릴 뿐이다. 학습은 결국 되지만, 그 차이가 “어떤 행동이 우연히 몇 번 뽑혔는가”의 잡음에 묻힌다. 이 문제가 baseline으로 이어진다.

핵심 보조정리: score의 기댓값은 0

Ea∼πθ[∇θlog⁡πθ(a∣s)]=∑aπθ(a∣s) ∇θπθ(a∣s)πθ(a∣s)=∇θ∑aπθ(a∣s)=∇θ1=0\mathbb{E}_{a \sim \pi_\theta}\big[\nabla_\theta \log \pi_\theta(a \mid s)\big] = \sum_a \pi_\theta(a \mid s)\, \frac{\nabla_\theta \pi_\theta(a \mid s)}{\pi_\theta(a \mid s)} = \nabla_\theta \sum_a \pi_\theta(a \mid s) = \nabla_\theta 1 = 0

(Spinning Up은 이것을 EGLP 보조정리라 부른다.) 정책 경사의 분산 감소 기법 두 가지가 모두 이 한 줄에서 나온다.

1. 인과성: reward-to-go

시각 tt의 행동은 그 전에 받은 보상 rt′r_{t'} (t′<tt' < t)에 영향을 줄 수 없다. 수식으로 확인하면, t′<tt' < t일 때 sts_t까지의 역사 hth_t를 조건으로 두면 rt′r_{t'}은 상수이므로

E[∇θlog⁡πθ(at∣st) rt′]=Eht[rt′  Eat∼πθ[∇θlog⁡πθ(at∣st)]⏟=0]=0\mathbb{E}\big[\nabla_\theta \log \pi_\theta(a_t \mid s_t)\, r_{t'}\big] = \mathbb{E}_{h_t}\Big[r_{t'}\; \underbrace{\mathbb{E}_{a_t \sim \pi_\theta}\big[\nabla_\theta \log \pi_\theta(a_t \mid s_t)\big]}_{=0}\Big] = 0

기댓값이 0인 항을 빼도 불편성은 그대로이고, 잡음만 줄어든다. 그래서 R(τ)R(\tau) 대신 reward-to-go G^t=∑t′≥trt′\hat G_t = \sum_{t' \ge t} r_{t'}를 쓴다.

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

2. Baseline

같은 논리로, 행동 ata_t에 의존하지 않는 어떤 함수 b(st)b(s_t)를 빼도 기댓값은 변하지 않는다.

E[∇θlog⁡πθ(at∣st) b(st)]=Est[b(st) Eat[∇θlog⁡πθ(at∣st)]]=0\mathbb{E}\big[\nabla_\theta \log \pi_\theta(a_t \mid s_t)\, b(s_t)\big] = \mathbb{E}_{s_t}\Big[b(s_t)\, \mathbb{E}_{a_t}\big[\nabla_\theta \log \pi_\theta(a_t \mid s_t)\big]\Big] = 0∇θJ=E[∑t∇θlog⁡πθ(at∣st) (G^t−b(st))]\nabla_\theta J = \mathbb{E}\Big[\sum_t \nabla_\theta \log \pi_\theta(a_t \mid s_t)\, \big(\hat G_t - b(s_t)\big)\Big]

조건은 딱 하나, bb가 그 행동 ata_t에 의존하지 않을 것 이다. 상태, 과거, 다른 샘플들의 보상에는 의존해도 된다.

분산은 얼마나 줄고, 어떤 bb가 좋은가? 매개변수 하나(θ\theta의 한 성분)에 대해 s=∂θlog⁡πθ(a)s = \partial_\theta \log \pi_\theta(a)로 쓰면 단일 샘플 추정량 g=s (R−b)g = s\,(R - b)의 분산은

Var⁡[g]=E[s2(R−b)2]−(E[sR])2\operatorname{Var}[g] = \mathbb{E}\big[s^2 (R - b)^2\big] - \big(\mathbb{E}[s R]\big)^2

둘째 항은 bb와 무관하다(E[s b]=0\mathbb{E}[s\, b] = 0). 첫째 항을 bb로 미분해 0으로 두면

−2 E[s2(R−b)]=0⟹b⋆=E[s2R]E[s2]-2\, \mathbb{E}\big[s^2 (R - b)\big] = 0 \quad\Longrightarrow\quad b^\star = \frac{\mathbb{E}[s^2 R]}{\mathbb{E}[s^2]}

score 크기로 가중한 평균 보상이다. 실전에서는 그냥 기대 보상 b(s)≈Vπ(s)b(s) \approx V^\pi(s)를 쓴다. 그러면 가중치 G^t−Vπ(st)\hat G_t - V^\pi(s_t)는 advantage Aπ(st,at)A^\pi(s_t, a_t)의 추정이 되고, 정책 경사는 “평균보다 나은 행동은 올리고 못한 행동은 내린다”가 된다. 이것이 다음 레슨 actor-critic의 출발점이다.

보상에 상수 cc를 더하면 무슨 일이 생기는지도 여기서 보인다. baseline 없이 E[s2(R+c)2]\mathbb{E}[s^2 (R + c)^2]은 c2 E[s2]c^2\,\mathbb{E}[s^2]만큼 커진다. 기대 기울기는 그대로인데 분산만 c2c^2로 커진다.

그림으로: baseline의 효과

아래는 팔 5개짜리 bandit을 softmax 정책 REINFORCE로 학습한다. 같은 설정을 seed 40개로 돌려 평균과 퍼짐을 함께 보여 준다.

균등 정책에서at the uniform policy, tr Cov[ĝ]: baseline 없음no baseline – b = E[R] – 비율ratio –
Drag the grey bars on the left up and down to change each arm's mean reward μk (reward = μk + c + N(0,1) noise). The coloured bars are the policy πk after 200 training steps (mean over 40 seeds). The right panel shows the expected reward J(θ) = Σ πkμk: its mean (line) and 10–90% band. Raise the offset c from 0 to 10 and only the side without a baseline (red) collapses. The expected gradient does not depend on c, but the variance grows in proportion to c². The baseline (blue, a moving average of past rewards) subtracts c, so it is unaffected. 왼쪽 회색 막대를 위아래로 끌어 각 팔의 평균 보상 μk를 바꿀 수 있다(보상 = μk + c + N(0,1) 잡음). 색 막대는 200 step 학습 후 정책 πk(seed 40개 평균). 오른쪽은 기대 보상 J(θ) = Σ πkμk의 평균(선)과 10–90% 구간(띠). 오프셋 c를 0에서 10으로 올려 보면 baseline이 없는 쪽(빨강)만 무너진다. 기울기의 기댓값은 c와 무관하지만 분산은 c²에 비례해 커지기 때문이다. baseline(파랑, 지난 보상의 이동평균)은 c를 빼 주므로 영향이 없다.

Things to try:

  1. c = 0: the two methods differ little. The mean reward is already near 0, so the baseline has little to do.
  2. 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.
  3. Increase the batch B and both improve; variance falls as 1/B1/B. The baseline has the effect of “growing the batch tens of times for free”.
  4. Make η large and the side without a baseline becomes unstable first. The higher an estimator’s variance, the smaller the learning rate it tolerates.
  5. 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.

NumPy REINFORCE: softmax bandit, with and without a baseline
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 ∑t∇log⁡πθ(yt∣yt−1,t)\sum_t \nabla \log \pi_\theta(y_t \mid y_{t-1}, t), and every token receives the same weight A=R−bA = R - b. We also look at what happens when a constant is added to the reward (for example, a “format reward” given to every response).

NumPy REINFORCE: length-4 token sequences, terminal reward
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.

확인 문제Check yourself

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 yiy_i). Response length is a function of yiy_i, so E[∇log⁡π(yi) b(yi)]≠0\mathbb{E}[\nabla \log \pi(y_i)\, b(y_i)] \ne 0 and the gradient is biased (it is the same as directly rewarding/penalising length). The mean of the other responses (RLOO), V(x)V(x), and a moving average of past rewards are all independent of yiy_i. Note that subtracting the group mean rˉ\bar r that includes the sample itself gives ri−rˉ=k−1k(ri−rˉ−i)r_i - \bar r = \frac{k-1}{k}(r_i - \bar r_{-i}), a constant multiple of an unbiased estimator.

REINFORCE for LLMs

In an LLM the actions are tokens, and the log-prob of a completion yy is the sum of token log-probs.

log⁡πθ(y∣x)=∑t=0T−1log⁡πθ(yt∣x,y<t)\log \pi_\theta(y \mid x) = \sum_{t=0}^{T-1} \log \pi_\theta(y_t \mid x, y_{<t})

With reward only at the end and γ=1\gamma = 1, every token’s reward-to-go is the same r(x,y)r(x, y). The causality trick changes nothing, and the policy gradient is

∇θJ=Ex∼D,  y∼πθ(⋅∣x)[(r(x,y)−b(x))∑t∇θlog⁡πθ(yt∣x,y<t)]\nabla_\theta J = \mathbb{E}_{x \sim \mathcal D,\; y \sim \pi_\theta(\cdot \mid x)}\Big[\big(r(x, y) - b(x)\big) \sum_{t} \nabla_\theta \log \pi_\theta(y_t \mid x, y_{<t})\Big]

Sample kk completions per prompt and use the mean of the other k−1k-1 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.

PyTorch REINFORCE / RLOO loss for LLMs 로컬에서 실행run locally (pip install torch)
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

  • ∇θJ=E[∑t∇θlog⁡πθ(at∣st) R(τ)]\nabla_\theta J = \mathbb{E}[\sum_t \nabla_\theta \log \pi_\theta(a_t \mid s_t)\, R(\tau)]: 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 −R⋅log⁡π-R \cdot \log \pi.
  • Ea∼π[∇log⁡π(a)]=0\mathbb{E}_{a \sim \pi}[\nabla \log \pi(a)] = 0 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 c2c^2 variance that comes from a constant shift in the reward. Baselines in practice are V(s)V(s), the leave-one-out mean, and the group mean.
  • For LLMs, the loss multiplies log⁡πθ(y∣x)=∑tlog⁡πθ(yt∣x,y<t)\log \pi_\theta(y \mid x) = \sum_t \log \pi_\theta(y_t \mid x, y_{<t}) by (r−b)(r - b). With a terminal reward every token gets the same advantage.

해 볼 것:

  1. c = 0: 두 방법의 차이가 작다. 보상의 평균이 이미 0 근처라 baseline이 할 일이 적다.
  2. c를 5–10으로: 빨간 띠가 크게 벌어지고 일부 seed는 나쁜 팔에 갇힌다. 분산 비율이 수십 배로 뛴다. 파랑은 그대로다.
  3. 배치 B를 키우면 둘 다 좋아진다. 분산은 1/B1/B로 준다. baseline은 “공짜로 배치를 수십 배 키운 효과”를 낸다.
  4. η를 크게 하면 baseline 없는 쪽부터 불안정해진다. 분산이 큰 추정량일수록 허용되는 학습률이 작다.
  5. 한 팔의 μ를 다른 팔들보다 아주 높게 끌어 올리면 둘 다 금방 찾는다. 팔들의 차이가 잡음에 비해 작을 때 분산 감소가 결정적이다.

직접 구현하기

먼저 bandit이다. 추정량 수만 개를 한 θ에서 뽑아 평균은 참 기울기와 같고(불편), 분산만 다르다 는 것을 직접 확인한다. baseline은 같은 배치의 다른 샘플들의 평균(leave-one-out)을 쓴다. 자기 자신의 보상을 쓰지 않으니 행동과 독립이고, 불편성이 유지된다.

NumPy REINFORCE: softmax bandit, baseline 유무
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의 합 ∑t∇log⁡πθ(yt∣yt−1,t)\sum_t \nabla \log \pi_\theta(y_t \mid y_{t-1}, t)이고, 모든 토큰이 같은 가중치 A=R−bA = R - b를 받는다. 보상에 상수를 더했을 때(예: 모든 응답에 주는 “형식 보상”) 무슨 일이 생기는지도 본다.

NumPy REINFORCE: 길이 4 토큰 시퀀스, 종단 보상
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이 있으면 상수 이동은 수학적으로 완전히 지워진다.

확인 문제Check yourself

LLM RL에서 프롬프트 x마다 응답 4개를 샘플한다. 응답 i의 advantage로 r_i − b를 쓸 때, 정책 경사를 편향시키는 b는?

baseline은 그 행동(여기서는 응답 yiy_i)에 의존하면 안 된다. 응답 길이는 yiy_i의 함수이므로 E[∇log⁡π(yi) b(yi)]≠0\mathbb{E}[\nabla \log \pi(y_i)\, b(y_i)] \ne 0이 되어 기울기가 편향된다(길이를 직접 보상/처벌하는 것과 같다). 나머지 응답들의 평균(RLOO), V(x)V(x), 과거 보상의 이동평균은 모두 yiy_i와 독립이다. 참고로 자기 자신을 포함한 그룹 평균 rˉ\bar r을 빼는 것은 ri−rˉ=k−1k(ri−rˉ−i)r_i - \bar r = \frac{k-1}{k}(r_i - \bar r_{-i})라서 불편 추정량의 상수배다.

LLM에서의 REINFORCE

LLM에서 행동은 토큰이고, 완성문 yy의 log-prob은 토큰 log-prob의 합이다.

log⁡πθ(y∣x)=∑t=0T−1log⁡πθ(yt∣x,y<t)\log \pi_\theta(y \mid x) = \sum_{t=0}^{T-1} \log \pi_\theta(y_t \mid x, y_{<t})

보상이 끝에만 있고 γ=1\gamma = 1이면 모든 토큰의 reward-to-go가 똑같이 r(x,y)r(x, y)다. 인과성 트릭은 아무것도 바꾸지 않고, 정책 경사는

∇θJ=Ex∼D,  y∼πθ(⋅∣x)[(r(x,y)−b(x))∑t∇θlog⁡πθ(yt∣x,y<t)]\nabla_\theta J = \mathbb{E}_{x \sim \mathcal D,\; y \sim \pi_\theta(\cdot \mid x)}\Big[\big(r(x, y) - b(x)\big) \sum_{t} \nabla_\theta \log \pi_\theta(y_t \mid x, y_{<t})\Big]

이다. 한 프롬프트에 대해 kk개를 샘플하고 나머지 k−1k-1개의 평균을 baseline으로 쓰면 RLOO, 그룹 평균을 빼고 그룹 표준편차로 나누면 GRPO 의 advantage다(표준편차로 나누는 것은 프롬프트마다 기울기의 크기를 바꾸므로 원래 목적함수의 불편 추정은 아니다. Track V에서 다룬다). 구현은 이렇다.

PyTorch LLM용 REINFORCE / RLOO 손실 로컬에서 실행run locally (pip install torch)
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()
 

정리

  • ∇θJ=E[∑t∇θlog⁡πθ(at∣st) R(τ)]\nabla_\theta J = \mathbb{E}[\sum_t \nabla_\theta \log \pi_\theta(a_t \mid s_t)\, R(\tau)]: log-derivative trick으로 기울기를 샘플 가능한 기댓값으로 바꾸고, 환경 모델은 미분에서 사라진다.
  • REINFORCE = 보상 가중 자기 샘플 최대우도. 구현은 −R⋅log⁡π-R \cdot \log \pi의 autograd.
  • Ea∼π[∇log⁡π(a)]=0\mathbb{E}_{a \sim \pi}[\nabla \log \pi(a)] = 0 하나로 reward-to-go와 baseline이 불편성을 유지한다는 것이 증명된다. baseline은 행동에만 의존하지 않으면 된다.
  • baseline은 분산을, 특히 보상의 상수 이동에서 오는 c2c^2 분산을 없앤다. 실전의 baseline은 V(s)V(s), leave-one-out 평균, 그룹 평균이다.
  • LLM에서는 log⁡πθ(y∣x)=∑tlog⁡πθ(yt∣x,y<t)\log \pi_\theta(y \mid x) = \sum_t \log \pi_\theta(y_t \mid x, y_{<t})에 (r−b)(r - b)를 곱한 손실. 종단 보상이면 모든 토큰이 같은 advantage를 받는다.

더 읽을거리Further reading