Track V · RL for LLMs & Agents · 06/10

RLVR과 추론 — GRPO, RLOO, Dr. GRPO, DAPO, GSPORLVR and reasoning — GRPO, RLOO, Dr. GRPO, DAPO, GSPO

채점 프로그램이 보상을 주는 RLVR에서 critic 없이 그룹 평균을 baseline으로 쓰는 GRPO를 유도하고, 길이 정규화·std 정규화·대칭 clip이 만드는 편향과 그 수정(Dr. GRPO, DAPO, GSPO), 신호 없는 그룹 문제를 직접 계산해 본다.In RLVR, where a grading program provides the reward, derive GRPO — which uses the group mean as a baseline instead of a critic — and compute for yourself the biases created by length normalisation, std normalisation and symmetric clipping, their fixes (Dr. GRPO, DAPO, GSPO), and the problem of signal-free groups.

In RLHF-PPO the reward came from a reward model (RM) learned from human preferences. But whether a math answer is right or a piece of code passes its tests does not need a human to judge. A program grades it. Reinforcement learning with rewards given by a grader (a verifier) is called RLVR (Reinforcement Learning with Verifiable Rewards) — a name coined in Tülu 3. DeepSeek-R1 used GRPO, which drops the critic and uses the group mean as the baseline, to draw out long chains of thought in this setting, and since 2025 it has become the standard for training reasoning models. This lesson derives GRPO directly from the policy gradient, and checks by computation the biases hidden in its formula and the variants that fix them.

Verifiable rewards

The RLVR reward usually looks like this.

r(x,y)=1[verify(extract(y), yx⋆)](+ format reward)r(x, y) = \mathbb{1}\big[\texttt{verify}(\texttt{extract}(y),\ y^\star_x)\big] \quad(+\ \text{format reward})

For math, the final answer is normalised and compared with the reference answer yx⋆y^\star_x; for code, unit tests are run. DeepSeek-R1-Zero added only a format reward, checking that the <think> tag format was followed, to the correctness reward. Compared with a learned RM, its properties are clearly different.

  • Cheap and consistent. No RM inference is needed, and the same response always gets the same score.
  • Hard to hack (not impossible). It does not give wild scores out of distribution the way an RM does. But outputs that modify the tests, special-case them in code, or exploit holes in the grader’s parser are still possible (the over-optimisation lesson).
  • Sparse and binary. 0 or 1 per response, and only once, at the end.

Why drop the critic

Training an LLM with PPO means carrying around a value model VϕV_\phi of roughly the same size as the policy. Nearly doubling memory and compute is one problem, but in RLVR the target VϕV_\phi must learn is itself hard. Since the reward exists only at the end, V(st)V(s_t) is “the probability of eventually reaching the right answer from the solution written so far”. Predicting that in the middle of a reasoning trace thousands of tokens long is as hard as solving the problem.

Instead, sample GG responses for the same prompt xx and use their mean reward as the baseline. As we saw in policy gradients, a baseline bb does not change the expectation as long as it does not depend on the response yiy_i.

Ey∼πθ[b ∇θlog⁡πθ(y∣x)]=b ∇θ∑yπθ(y∣x)=b ∇θ1=0\mathbb{E}_{y\sim\pi_\theta}\big[b\,\nabla_\theta \log\pi_\theta(y\mid x)\big] = b\,\nabla_\theta \sum_y \pi_\theta(y\mid x) = b\,\nabla_\theta 1 = 0

With the reward only at the end and γ=λ=1\gamma=\lambda=1, GAE reduces to A^t=R−V(st)\hat A_t = R - V(s_t). Instead of learning this V(st)V(s_t) per token, GRPO replaces it with a single prompt-level Monte Carlo estimate, and gives that advantage equally to every token of the response.

GRPO

The objective of GRPO (Group Relative Policy Optimization, Shao et al. 2024) is PPO’s clipped objective written per group.

JGRPO(θ)=Ex, {yi}i=1G∼πold[1G∑i=1G1∣yi∣∑t=1∣yi∣(min⁡(ρi,tA^i, clip⁡(ρi,t,1−ε,1+ε)A^i)−β D^KL(i,t))]J_{\text{GRPO}}(\theta)=\mathbb{E}_{x,\ \{y_i\}_{i=1}^G\sim\pi_{\text{old}}}\left[\frac{1}{G}\sum_{i=1}^{G}\frac{1}{|y_i|}\sum_{t=1}^{|y_i|}\Big(\min\big(\rho_{i,t}\hat A_i,\ \operatorname{clip}(\rho_{i,t},1-\varepsilon,1+\varepsilon)\hat A_i\big)-\beta\,\hat D_{\text{KL}}^{(i,t)}\Big)\right]ρi,t=πθ(yi,t∣x,yi,<t)πold(yi,t∣x,yi,<t),A^i=ri−mean⁡(r1,…,rG)std⁡(r1,…,rG)\rho_{i,t}=\frac{\pi_\theta(y_{i,t}\mid x,y_{i,<t})}{\pi_{\text{old}}(y_{i,t}\mid x,y_{i,<t})},\qquad \hat A_i=\frac{r_i-\operatorname{mean}(r_1,\dots,r_G)}{\operatorname{std}(r_1,\dots,r_G)}

The KL is not mixed into the reward but added directly to the loss, using the per-token k3 estimator D^KL=πrefπθ−log⁡πrefπθ−1\hat D_{\text{KL}} = \frac{\pi_{\text{ref}}}{\pi_\theta} - \log\frac{\pi_{\text{ref}}}{\pi_\theta} - 1 (KL estimators). Three choices are built in: (1) the baseline is the group mean, (2) it divides by the group std, and (3) it takes a token mean 1/∣yi∣1/|y_i| per response and then a group mean. All three change the result.

Baseline: mean, leave-one-out, std

The group mean contains rir_i itself, so it seems to break the condition that “the baseline must not depend on yiy_i”. But rearranged, it differs only by a scale.

ri−1G∑jrj=G−1G(ri−1G−1∑j≠irj⏟leave-one-out)r_i-\frac{1}{G}\sum_{j} r_j=\frac{G-1}{G}\Big(r_i-\underbrace{\frac{1}{G-1}\sum_{j\ne i}r_j}_{\text{leave-one-out}}\Big)

The term in parentheses is the advantage of RLOO (REINFORCE Leave-One-Out; Kool et al. 2019, Ahmadian et al. 2024). The other G−1G-1 responses were drawn independently of yiy_i, so RLOO is an unbiased estimator, and the mean baseline is G−1G\frac{G-1}{G} times it. Same direction.

Dividing by the std is different. With binary rewards, a group with success rate pp has std p(1−p)\sqrt{p(1-p)}, so the expected GRPO gradient

∇JGRPO∝∑x1px(1−px) ∇Jx\nabla J_{\text{GRPO}} \propto \sum_x \frac{1}{\sqrt{p_x(1-p_x)}}\,\nabla J_x

carries a per-prompt weight. Very easy or very hard problems, with pxp_x near 0 or 1, get larger weight. Within each prompt the direction is right, but it changes the relative weight across prompts and so optimises something other than the original objective Ex[px]\mathbb{E}_x[p_x]. Dr. GRPO (Liu et al. 2025) calls this question-level difficulty bias and removes the std.

In a picture: advantages and per-token weights

Without clipping (ρ=1\rho=1), the gradient of the GRPO loss written out per token is:

∇J=∑i=1G A^i ci⏟per-token weight ∑t=1∣yi∣∇log⁡πθ(yi,t∣x,yi,<t),ci={1G ∣yi∣sequence-mean (original GRPO)1∑j∣yj∣token-sum (DAPO)1G Lmax⁡constant (Dr. GRPO)\nabla J = \sum_{i=1}^{G}\ \underbrace{\hat A_i\, c_i}_{\text{per-token weight}}\ \sum_{t=1}^{|y_i|}\nabla\log\pi_\theta(y_{i,t}\mid x, y_{i,<t}),\qquad c_i=\begin{cases}\dfrac{1}{G\,|y_i|} & \text{sequence-mean (original GRPO)}\\[6pt] \dfrac{1}{\sum_j |y_j|} & \text{token-sum (DAPO)}\\[6pt] \dfrac{1}{G\,L_{\max}} & \text{constant (Dr. GRPO)}\end{cases}

RLHF-PPO에서는 보상이 사람 선호로 학습한 보상모델(reward model, RM)에서 나왔다. 그런데 수학 문제의 답이나 코드의 테스트 통과 여부는 사람이 판단할 필요가 없다. 프로그램이 채점한다. 보상을 채점기(verifier)로 주는 강화학습을 RLVR(Reinforcement Learning with Verifiable Rewards) 이라고 부른다(Tülu 3에서 붙인 이름). DeepSeek-R1은 이 설정에서 critic 없이 그룹 평균을 baseline으로 쓰는 GRPO로 긴 사고 과정(chain of thought)을 끌어냈고, 2025년 이후 추론 모델 학습의 표준이 되었다. 이 레슨은 GRPO를 policy gradient에서 직접 유도하고, 그 식 안에 숨은 편향들과 그것을 고친 변형들을 계산으로 확인한다.

검증 가능한 보상

RLVR의 보상은 대개 이렇다.

r(x,y)=1[verify(extract(y), yx⋆)](+ 형식 보상)r(x, y) = \mathbb{1}\big[\texttt{verify}(\texttt{extract}(y),\ y^\star_x)\big] \quad(+\ \text{형식 보상})

수학이면 최종 답을 정규화해 정답 yx⋆y^\star_x와 비교하고, 코드면 단위 테스트를 돌린다. DeepSeek-R1-Zero는 정답 보상에 <think> 태그 형식을 지켰는지 보는 형식 보상만 더했다. 학습된 RM과 비교하면 성질이 뚜렷이 다르다.

  • 싸고 일관적이다. RM 추론이 필요 없고, 같은 응답에 언제나 같은 점수를 준다.
  • 해킹하기 어렵다(불가능하지는 않다). RM처럼 분포 밖에서 엉뚱한 점수를 주지 않는다. 다만 테스트를 수정하거나 특수 처리하는 코드, 채점기 파서의 허점을 노리는 출력은 여전히 가능하다(과최적화 레슨).
  • 희소하고 이진이다. 응답 하나에 0 또는 1, 그것도 마지막에 한 번 나온다.

왜 critic을 버리는가

PPO로 LLM을 학습하면 정책과 비슷한 크기의 value model VϕV_\phi를 하나 더 들고 다닌다. 메모리와 연산이 거의 두 배가 되는 것도 문제지만, RLVR에서는 VϕV_\phi가 배워야 할 대상 자체가 어렵다. 보상이 마지막에만 있으니 V(st)V(s_t)는 “지금까지 쓴 풀이로부터 결국 정답에 도달할 확률”이다. 수천 토큰짜리 추론 중간에서 이것을 맞히는 것은 문제를 푸는 것만큼 어렵다.

대신 같은 프롬프트 xx에서 응답을 GG개 뽑아 그 보상 평균을 baseline으로 쓴다. 정책 경사에서 본 대로 baseline bb가 그 응답 yiy_i에 의존하지만 않으면 기대값을 바꾸지 않는다.

Ey∼πθ[b ∇θlog⁡πθ(y∣x)]=b ∇θ∑yπθ(y∣x)=b ∇θ1=0\mathbb{E}_{y\sim\pi_\theta}\big[b\,\nabla_\theta \log\pi_\theta(y\mid x)\big] = b\,\nabla_\theta \sum_y \pi_\theta(y\mid x) = b\,\nabla_\theta 1 = 0

보상이 끝에만 있고 γ=λ=1\gamma=\lambda=1이면 GAE는 A^t=R−V(st)\hat A_t = R - V(s_t)가 된다. GRPO는 이 V(st)V(s_t)를 토큰마다 학습하는 대신 프롬프트 수준의 Monte Carlo 추정치 하나로 바꾸고, 그 advantage를 응답의 모든 토큰에 똑같이 준다.

GRPO

GRPO(Group Relative Policy Optimization, Shao et al. 2024)의 목적함수는 PPO의 clip 목적함수를 그룹 단위로 쓴 것이다.

JGRPO(θ)=Ex, {yi}i=1G∼πold[1G∑i=1G1∣yi∣∑t=1∣yi∣(min⁡(ρi,tA^i, clip⁡(ρi,t,1−ε,1+ε)A^i)−β D^KL(i,t))]J_{\text{GRPO}}(\theta)=\mathbb{E}_{x,\ \{y_i\}_{i=1}^G\sim\pi_{\text{old}}}\left[\frac{1}{G}\sum_{i=1}^{G}\frac{1}{|y_i|}\sum_{t=1}^{|y_i|}\Big(\min\big(\rho_{i,t}\hat A_i,\ \operatorname{clip}(\rho_{i,t},1-\varepsilon,1+\varepsilon)\hat A_i\big)-\beta\,\hat D_{\text{KL}}^{(i,t)}\Big)\right]ρi,t=πθ(yi,t∣x,yi,<t)πold(yi,t∣x,yi,<t),A^i=ri−mean⁡(r1,…,rG)std⁡(r1,…,rG)\rho_{i,t}=\frac{\pi_\theta(y_{i,t}\mid x,y_{i,<t})}{\pi_{\text{old}}(y_{i,t}\mid x,y_{i,<t})},\qquad \hat A_i=\frac{r_i-\operatorname{mean}(r_1,\dots,r_G)}{\operatorname{std}(r_1,\dots,r_G)}

KL은 보상에 섞지 않고 손실에 직접 더하며, 토큰마다 k3 추정량 D^KL=πrefπθ−log⁡πrefπθ−1\hat D_{\text{KL}} = \frac{\pi_{\text{ref}}}{\pi_\theta} - \log\frac{\pi_{\text{ref}}}{\pi_\theta} - 1을 쓴다(KL 추정량). 세 가지 선택이 들어 있다. (1) baseline이 그룹 평균이고, (2) 그룹 std로 나누며, (3) 응답마다 토큰 평균 1/∣yi∣1/|y_i|을 낸 뒤 그룹 평균을 낸다. 셋 다 결과를 바꾼다.

baseline: 평균, leave-one-out, std

그룹 평균에는 rir_i 자신이 들어 있으니 “baseline이 yiy_i에 의존하면 안 된다”는 조건을 어기는 것처럼 보인다. 하지만 정리해 보면 스케일만 다르다.

ri−1G∑jrj=G−1G(ri−1G−1∑j≠irj⏟leave-one-out)r_i-\frac{1}{G}\sum_{j} r_j=\frac{G-1}{G}\Big(r_i-\underbrace{\frac{1}{G-1}\sum_{j\ne i}r_j}_{\text{leave-one-out}}\Big)

괄호 안이 RLOO(REINFORCE Leave-One-Out; Kool et al. 2019, Ahmadian et al. 2024)의 advantage다. 나머지 G−1G-1개는 yiy_i와 독립으로 뽑혔으니 RLOO는 불편(unbiased) 추정량이고, 평균 baseline은 그것의 G−1G\frac{G-1}{G}배다. 방향은 같다.

std로 나누는 것은 다르다. 이진 보상에서 정답률이 pp인 그룹의 std는 p(1−p)\sqrt{p(1-p)}이므로, GRPO의 기대 gradient는

∇JGRPO∝∑x1px(1−px) ∇Jx\nabla J_{\text{GRPO}} \propto \sum_x \frac{1}{\sqrt{p_x(1-p_x)}}\,\nabla J_x

처럼 프롬프트마다 가중치가 붙는다. pxp_x가 0이나 1에 가까운, 아주 쉽거나 아주 어려운 문제가 더 큰 가중치를 받는다. 각 프롬프트 안에서 방향은 맞지만, 프롬프트 사이의 비중을 바꾸어 원래 목적함수 Ex[px]\mathbb{E}_x[p_x]와 다른 것을 최적화한다. Dr. GRPO(Liu et al. 2025)는 이것을 question-level difficulty bias라고 부르고 std를 뺐다.

그림으로: advantage와 토큰당 가중치

clip이 걸리지 않은 상태(ρ=1\rho=1)에서 GRPO 손실의 gradient를 토큰 단위로 풀어 쓰면 이렇다.

∇J=∑i=1G A^i ci⏟토큰당 가중치 ∑t=1∣yi∣∇log⁡πθ(yi,t∣x,yi,<t),ci={1G ∣yi∣sequence-mean (GRPO 원본)1∑j∣yj∣token-sum (DAPO)1G Lmax⁡상수 (Dr. GRPO)\nabla J = \sum_{i=1}^{G}\ \underbrace{\hat A_i\, c_i}_{\text{토큰당 가중치}}\ \sum_{t=1}^{|y_i|}\nabla\log\pi_\theta(y_{i,t}\mid x, y_{i,<t}),\qquad c_i=\begin{cases}\dfrac{1}{G\,|y_i|} & \text{sequence-mean (GRPO 원본)}\\[6pt] \dfrac{1}{\sum_j |y_j|} & \text{token-sum (DAPO)}\\[6pt] \dfrac{1}{G\,L_{\max}} & \text{상수 (Dr. GRPO)}\end{cases}
mean r – std r – 토큰당 |가중치| 정답 평균per-token |weight|, mean over correct – 오답 평균mean over wrong –
Click a circle on the left to change the reward ri, and drag a bar left or right to change the response length |yi|. The bar colour is the gradient weight one token of that response receives, Âi·ci (blue = raises probability, red = lowers it; normalised by the maximum within the group). The three bars on the right are the GRPO, Dr. GRPO and RLOO advantages for the same rewards. Pick sequence-mean under "long wrong + short right" and you can see that the tokens of long wrong answers are barely penalised. Switch to token-sum or constant normalisation and every token is treated with the same magnitude. Make all rewards equal and every advantage becomes 0. 왼쪽 원을 클릭하면 보상 ri가 바뀌고, 막대를 좌우로 끌면 응답 길이 |yi|가 바뀐다. 막대 색은 그 응답의 토큰 하나가 받는 gradient 가중치 Âi·ci다(파랑 = 확률을 올림, 빨강 = 내림; 그룹 안 최대값으로 정규화). 오른쪽 세 막대는 같은 보상에 대한 GRPO·Dr. GRPO·RLOO advantage. "긴 오답 + 짧은 정답"에서 sequence-mean을 고르면 긴 오답의 토큰이 거의 벌을 받지 않는 것이 보인다. token-sum이나 상수 정규화로 바꾸면 모든 토큰이 같은 크기로 다뤄진다. 모든 보상을 같게 만들면 advantage가 전부 0이 된다.
  1. Press “long wrong + short right” and look at the bar colours under sequence-mean. The tokens of the 380-long wrong answer are almost white. For the same wrong answer, the longer it is, the smaller the penalty each token receives, by 1/∣yi∣1/|y_i|.
  2. Switch to token-sum or constant, and every correct token is the same blue and every wrong token the same red. Regardless of length, one token is one token.
  3. In “only one right”, look at the right-hand bars: GRPO’s advantage for the correct answer is much larger than RLOO’s. The rarer the correct answer in a group, the smaller the std, and GRPO amplifies the signal.
  4. Press “all right”: every advantage is 0. However large the group, there is nothing to learn from this prompt.

Length-normalisation bias

Under sequence-mean, the coefficient on response ii‘s total log-probability log⁡πθ(yi∣x)=∑tlog⁡πθ(yi,t∣⋅)\log\pi_\theta(y_i\mid x)=\sum_t\log\pi_\theta(y_{i,t}\mid\cdot) is A^i/(G∣yi∣)\hat A_i/(G|y_i|). An unbiased policy gradient would have A^i/G\hat A_i/G, so in effect each response is multiplied by an extra 1/∣yi∣1/|y_i|. As a result

  • correct answers (A^i>0\hat A_i>0) are pushed up harder the shorter they are, and
  • wrong answers (A^i<0\hat A_i<0) are pushed down less the longer they are.

The second effect creates pressure towards longer wrong responses. The Dr. GRPO paper pointed out that part of the response-length growth observed in R1-Zero-style training may come from this bias, and reported that replacing 1/∣yi∣1/|y_i| with a constant keeps wrong-answer length from growing indefinitely at similar accuracy. This does not mean the length growth itself (in R1-Zero, responses grow longer as training proceeds and self-checking sentences appear — the “aha moment”) is entirely a bias. It does mean that before reading “length went up = it learned to reason”, you should check the loss normalisation first.

DAPO: four fixes at scale

DAPO (Yu et al. 2025) summarised the problems it hit while running GRPO at scale on the Qwen2.5-32B base as four fixes. In this setting it scored 50 on AIME 2024, and reports beating DeepSeek-R1-Zero-Qwen-32B (47) from the same base with half the training steps. It dropped the KL term entirely, because while learning long reasoning, moving far from the initial model is the very goal.

Clip-Higher. The symmetric clip [1−ε,1+ε][1-\varepsilon, 1+\varepsilon] can barely grow low-probability tokens. With ε=0.2\varepsilon=0.2, a token with πold=0.01\pi_{\text{old}}=0.01 can rise only to 0.0120.012 in one update, whereas a token at 0.90.9 has so much room that the upper bound 1.081.08 is meaningless. The low-probability tokens needed for exploration are held down and entropy collapses quickly. DAPO widens only the upper bound, using εlow=0.2, εhigh=0.28\varepsilon_{\text{low}}=0.2,\ \varepsilon_{\text{high}}=0.28.

Dynamic sampling. If every reward in a group is the same, A^i=0\hat A_i=0 and the gradient is 0. With many such groups the effective batch size shrinks and gradient variance grows. Drop groups whose success rate is 0 or 1, and keep sampling until the batch is full.

Token-level loss. The token-sum in the figure above. Averaging all tokens in the group at once keeps the tokens of long responses from being diluted.

Overlong reward shaping. A response truncated at the maximum length Lmax⁡L_{\max} might have had a correct solution, but scores 0 because the answer could not be extracted. To reduce this noise, either drop truncated samples from the loss (overlong filtering), or give a soft penalty over the final stretch LcacheL_{\text{cache}}.

Rlength(y)={0∣y∣≤Lmax⁡−Lcache(Lmax⁡−Lcache)−∣y∣LcacheLmax⁡−Lcache<∣y∣≤Lmax⁡−1∣y∣>Lmax⁡R_{\text{length}}(y)=\begin{cases}0 & |y|\le L_{\max}-L_{\text{cache}}\\[2pt] \dfrac{(L_{\max}-L_{\text{cache}})-|y|}{L_{\text{cache}}} & L_{\max}-L_{\text{cache}}<|y|\le L_{\max}\\[6pt] -1 & |y|>L_{\max}\end{cases}

GSPO: a sequence-level ratio

GRPO’s ρi,t\rho_{i,t} is a ratio computed separately for each token. But the reward is attached once to the whole response. With only one sample per token position, ρi,t\rho_{i,t} cannot properly correct for the distribution difference and just adds noise, which accumulates over long responses. In MoE models, the expert selection of some tokens changes with every update, so token ratios can also swing wildly. GSPO (Zheng et al. 2025) matches the unit of optimisation to the unit of reward and clips a length-normalised sequence ratio.

si(θ)=(πθ(yi∣x)πold(yi∣x))1/∣yi∣=exp⁡(1∣yi∣∑tlog⁡ρi,t),JGSPO=E[1G∑imin⁡(siA^i, clip⁡(si,1−ε,1+ε)A^i)]s_i(\theta)=\left(\frac{\pi_\theta(y_i\mid x)}{\pi_{\text{old}}(y_i\mid x)}\right)^{1/|y_i|}=\exp\Big(\frac{1}{|y_i|}\sum_t\log\rho_{i,t}\Big),\qquad J_{\text{GSPO}}=\mathbb{E}\Big[\frac1G\sum_i\min\big(s_i\hat A_i,\ \operatorname{clip}(s_i,1-\varepsilon,1+\varepsilon)\hat A_i\big)\Big]

sis_i is the geometric mean of the token ratios, so every token of the response gets the same weight. Because it is length-normalised, it does not explode for long responses (see why in the product-ratio figure of the training–inference mismatch lesson). Since the clip acts per response, the range is set much narrower than GRPO’s 0.2 (around 10−410^{-4} in the paper’s experiments). The Qwen team reports that this stabilised MoE RL without routing replay.

→ Go deeper: Sequence vs token compares the four aggregation modes and token- versus sequence-level ratios side by side, including what each does to long responses.

Signal-free groups and difficulty

With binary rewards, the probability that a group for a prompt with success rate pp is all the same value is

P(zero-variance)=pG+(1−p)GP(\text{zero-variance}) = p^G + (1-p)^G

At G=8G=8, it is 0.66 for p=0.05p=0.05 and 0.008 for p=0.5p=0.5. Problems that are too hard (all wrong) and too easy (all right) both produce no gradient. RLVR learns only from problems the model gets right some of the time.

→ Go deeper: Rewards and environments — difficulty filtering and curricula, multi-environment RLVR, verifier design.

  1. “긴 오답 + 짧은 정답”을 누르고 sequence-mean에서 막대 색을 보자. 길이 380짜리 오답의 토큰은 거의 흰색이다. 같은 오답이라도 길수록 토큰 하나가 받는 벌이 1/∣yi∣1/|y_i|로 작아진다.
  2. token-sum이나 상수로 바꾸면 정답 토큰은 모두 같은 파랑, 오답 토큰은 모두 같은 빨강이 된다. 길이와 무관하게 토큰 하나는 토큰 하나다.
  3. “하나만 정답”에서 오른쪽 막대를 보면 GRPO의 정답 advantage가 RLOO보다 훨씬 크다. 정답이 드문 그룹일수록 std가 작아 GRPO가 신호를 증폭한다.
  4. “모두 정답”을 누르면 advantage가 전부 0이다. 그룹이 아무리 커도 이 프롬프트에서는 배울 것이 없다.

길이 정규화 편향

sequence-mean에서 응답 ii의 로그확률 전체 log⁡πθ(yi∣x)=∑tlog⁡πθ(yi,t∣⋅)\log\pi_\theta(y_i\mid x)=\sum_t\log\pi_\theta(y_{i,t}\mid\cdot)에 걸리는 계수는 A^i/(G∣yi∣)\hat A_i/(G|y_i|)다. 편향 없는 policy gradient라면 A^i/G\hat A_i/G여야 하니, 응답마다 1/∣yi∣1/|y_i|가 추가로 곱해진 셈이다. 그 결과

  • 정답(A^i>0\hat A_i>0)은 짧을수록 더 강하게 밀어 올리고,
  • 오답(A^i<0\hat A_i<0)은 길수록 덜 밀어 내린다.

두 번째 효과 때문에 틀린 응답이 길어지는 쪽으로 압력이 생긴다. Dr. GRPO 논문은 R1-Zero류 학습에서 관찰되는 응답 길이 증가 가운데 일부가 이 편향에서 올 수 있다고 지적하고, 1/∣yi∣1/|y_i|를 상수로 바꾸면 비슷한 정확도에서 오답 길이가 계속 늘어나지 않는다고 보고했다. 길이가 늘어나는 현상 자체(R1-Zero에서 학습이 진행될수록 응답이 길어지고 스스로 검토하는 문장이 나타나는 “aha moment”)가 전부 편향이라는 뜻은 아니다. 다만 “길이가 늘었다 = 추론을 배웠다”로 읽기 전에 손실의 정규화부터 확인해야 한다는 뜻이다.

DAPO: 대규모에서 고친 네 가지

DAPO(Yu et al. 2025)는 Qwen2.5-32B base에서 GRPO를 대규모로 돌리며 부딪힌 문제를 네 가지 수정으로 정리했다. 이 설정에서 AIME 2024 50점을 냈고, 같은 base의 DeepSeek-R1-Zero-Qwen-32B(47점)보다 절반의 학습 step으로 앞섰다고 보고한다. KL 항은 아예 뺐다. 긴 추론을 배우는 동안 정책이 초기 모델에서 크게 멀어지는 것이 오히려 목표이기 때문이다.

Clip-Higher. 대칭 clip [1−ε,1+ε][1-\varepsilon, 1+\varepsilon]은 확률이 작은 토큰을 거의 못 키운다. ε=0.2\varepsilon=0.2일 때 πold=0.01\pi_{\text{old}}=0.01인 토큰은 한 번의 업데이트로 최대 0.0120.012까지만 오르지만 0.90.9인 토큰은 상한 1.081.08이 의미 없을 만큼 여유가 있다. 탐색에 필요한 저확률 토큰이 묶이고 entropy가 빨리 무너진다. DAPO는 상한만 넓혀 εlow=0.2, εhigh=0.28\varepsilon_{\text{low}}=0.2,\ \varepsilon_{\text{high}}=0.28을 쓴다.

Dynamic sampling. 그룹의 보상이 모두 같으면 A^i=0\hat A_i=0이고 gradient가 0이다. 이런 그룹이 많으면 배치의 실효 크기가 줄어 gradient 분산이 커진다. 정답률이 0이나 1인 그룹은 버리고, 배치가 찰 때까지 더 뽑는다.

Token-level loss. 위 그림의 token-sum이다. 그룹 안의 모든 토큰을 한 번에 평균해서 긴 응답의 토큰이 희석되지 않게 한다.

Overlong reward shaping. 최대 길이 Lmax⁡L_{\max}에서 잘린 응답은 풀이가 맞았을 수도 있는데 정답 추출에 실패해 0점을 받는다. 이 잡음을 줄이려고 잘린 샘플을 손실에서 빼거나(overlong filtering), 끝 구간 LcacheL_{\text{cache}}에서 부드러운 벌점을 준다.

Rlength(y)={0∣y∣≤Lmax⁡−Lcache(Lmax⁡−Lcache)−∣y∣LcacheLmax⁡−Lcache<∣y∣≤Lmax⁡−1∣y∣>Lmax⁡R_{\text{length}}(y)=\begin{cases}0 & |y|\le L_{\max}-L_{\text{cache}}\\[2pt] \dfrac{(L_{\max}-L_{\text{cache}})-|y|}{L_{\text{cache}}} & L_{\max}-L_{\text{cache}}<|y|\le L_{\max}\\[6pt] -1 & |y|>L_{\max}\end{cases}

GSPO: 시퀀스 단위 ratio

GRPO의 ρi,t\rho_{i,t}는 토큰마다 따로 계산한 ratio다. 그런데 보상은 응답 전체에 하나 붙어 있다. 토큰 위치마다 샘플이 하나뿐이니 ρi,t\rho_{i,t}는 분포 차이를 제대로 보정하지 못하고 잡음만 더하며, 그 잡음이 긴 응답에서 누적된다. MoE 모델에서는 업데이트마다 일부 토큰의 expert 선택이 바뀌어 토큰 ratio가 크게 흔들리기도 한다. GSPO(Zheng et al. 2025)는 보상의 단위와 최적화의 단위를 맞춰, 길이로 정규화한 시퀀스 ratio를 clip한다.

si(θ)=(πθ(yi∣x)πold(yi∣x))1/∣yi∣=exp⁡(1∣yi∣∑tlog⁡ρi,t),JGSPO=E[1G∑imin⁡(siA^i, clip⁡(si,1−ε,1+ε)A^i)]s_i(\theta)=\left(\frac{\pi_\theta(y_i\mid x)}{\pi_{\text{old}}(y_i\mid x)}\right)^{1/|y_i|}=\exp\Big(\frac{1}{|y_i|}\sum_t\log\rho_{i,t}\Big),\qquad J_{\text{GSPO}}=\mathbb{E}\Big[\frac1G\sum_i\min\big(s_i\hat A_i,\ \operatorname{clip}(s_i,1-\varepsilon,1+\varepsilon)\hat A_i\big)\Big]

sis_i는 토큰 ratio의 기하평균이라 응답의 모든 토큰이 같은 가중치를 받는다. 길이로 정규화했으니 응답이 길어도 값이 폭발하지 않는다(이유는 학습–추론 불일치 레슨의 곱셈 ratio 그림에서 본다). clip이 응답 단위로 걸리기 때문에 범위도 GRPO의 0.2보다 훨씬 좁게(논문 실험에서는 10−410^{-4} 수준) 잡는다. Qwen 팀은 이것으로 MoE RL을 routing replay 없이 안정화했다고 보고한다.

→ 더 깊이: 시퀀스냐 토큰이냐에서 네 가지 집계 방식과 토큰·시퀀스 단위 ratio를 나란히 비교하고, 각각이 긴 응답에 무엇을 하는지 본다.

신호 없는 그룹과 난이도

이진 보상에서 정답률이 pp인 프롬프트의 그룹이 전부 같은 값일 확률은

P(zero-variance)=pG+(1−p)GP(\text{zero-variance}) = p^G + (1-p)^G

이다. G=8G=8에서 p=0.05p=0.05이면 0.66, p=0.5p=0.5이면 0.008이다. 너무 어려운 문제(전부 오답)와 너무 쉬운 문제(전부 정답)는 둘 다 gradient를 만들지 않는다. RLVR은 모델이 가끔은 맞히는 문제에서만 배운다.

→ 더 깊이: 보상과 환경 — 난이도 필터링과 curriculum, 다중 환경 RLVR, 검증기 설계.

step 0 GRPO – RLOO – REINFORCE – 신호 있는 그룹(초기)groups with signal (initial) –
The policy is a softmax over 6 "solution strategies". Strategies further right have higher skill, but the base policy prefers the ones on the left. On a problem of difficulty d, strategy s is correct with probability σ(12·(skills − d)), and the verifier returns 0/1. Raise D towards 0.9 and at first almost every group is all wrong (the right panel sits near 1), so learning stalls for a long time. Lower D and, conversely, as the policy improves, all-correct groups increase and the signal shrinks again. GRPO's std normalisation enlarges the advantage in groups where correct answers are rare, which speeds up the start. 정책은 6개 "풀이 전략"에 대한 softmax다. 오른쪽 전략일수록 실력(skill)이 높지만 base 정책은 왼쪽 전략을 선호한다. 난이도 d인 문제에서 전략 s의 정답 확률은 σ(12·(skills − d)), 검증기는 0/1을 돌려준다. D를 0.9 쪽으로 올리면 처음에는 거의 모든 그룹이 전부 오답이라(오른쪽 그림이 1 근처) 학습이 한참 정체된다. D를 낮추면 반대로 정책이 좋아질수록 전부 정답인 그룹이 늘어 신호가 다시 줄어든다. GRPO의 std 정규화는 정답이 드문 그룹에서 advantage를 키워 초반을 빠르게 한다.

Things to check in this figure:

  1. At D=0.75, most groups are all wrong for the first few dozen steps. With almost no signal, accuracy stays on the floor for a while and starts to rise only after the strong strategies are sampled by chance and get a few right.
  2. Lower D to about 0.3 and the start is fast, but as the policy improves, all-correct groups increase and the right-hand curve climbs again. Late in training, easy problems waste the batch.
  3. GRPO rises fastest because std normalisation enlarges the advantage in groups where correct answers are rare — an effect similar to using a large learning rate. In this simple setting the difference between RLOO and REINFORCE is small.
  4. Raise G to 16 and, even on hard problems, more groups get at least one right, so the plateau is shorter. In exchange, the sample cost per prompt doubles.

This is why data difficulty filtering matters in practical RLVR: solve each prompt a few times with the current model and drop problems with a success rate of 0 or 1, or re-select as training proceeds. For the same reason, RLVR is strong at raising the probability of problems the base model can already solve occasionally. Yue et al. (2025) reported that after RLVR, models have higher pass@1, but for very large kk the base model can have higher pass@k. The interpretation is that RL makes the model sample existing solutions more often (sharpening) rather than create new ones. How far this interpretation generalises is still debated.

확인 문제Check yourself

In a group with G=8, all 8 responses were correct (r=1). With no KL term, how much does this group contribute to the GRPO gradient?

If every rir_i is equal, then ri−mean⁡(r)=0r_i - \operatorname{mean}(r) = 0, so A^i=0\hat A_i = 0 for GRPO, Dr. GRPO and RLOO alike. For GRPO the std is also 0, so implementations add ε\varepsilon or define it as 0 to avoid divergence. This group spends compute but gives no signal. That is why DAPO’s dynamic sampling discards such groups and samples again. (With a KL term, that term’s gradient remains.)

Implementing it

First, transcribe the three advantages and three normalisations directly. The numbers are the same as the figure’s “long wrong + short right” setting.

NumPy Advantage variants and per-token weights
import numpy as np

def advantages(r, kind="grpo", eps=1e-6):
    r = np.asarray(r, float); G = len(r)
    if kind == "grpo":                       # (r - mean) / std
        return (r - r.mean()) / (r.std() + eps)
    if kind == "dr_grpo":                    # r - mean  (std removed)
        return r - r.mean()
    if kind == "rloo":                       # r - (mean of the other G-1)
        return r - (r.sum() - r) / (G - 1)
    raise ValueError(kind)

def token_weights(A, lengths, norm="seq", L_max=400):
    """Coefficient c_i * A_i that one token of response i receives (the factor in front of ∇log π(y_t))."""
    A, Ls = np.asarray(A, float), np.asarray(lengths, float); G = len(A)
    if norm == "seq":   c = 1.0 / (G * Ls)                   # original GRPO: token mean per response, then group mean
    elif norm == "tok": c = np.full(G, 1.0 / Ls.sum())       # DAPO: average all tokens in the group at once
    elif norm == "const": c = np.full(G, 1.0 / (G * L_max))  # Dr. GRPO: constant
    return A * c

r       = np.array([1, 1, 0, 0, 0, 0])
lengths = np.array([60, 80, 380, 360, 120, 300])

for kind in ["grpo", "dr_grpo", "rloo"]:
    print(f"{kind:8s} A =", np.round(advantages(r, kind), 3))
print("RLOO / Dr.GRPO ratio =", np.round(advantages(r, "rloo") / advantages(r, "dr_grpo"), 3), "(= G/(G-1))")

print("\nPer-token weights (GRPO advantage, normalised so the largest |value| = 1)")
A = advantages(r, "grpo")
for norm in ["seq", "tok", "const"]:
    w = token_weights(A, lengths, norm)
    w_rel = w / np.abs(w).max()
    total = w * lengths                      # mass on the whole log-prob of one response
    print(f"  {norm:5s} per-token:", np.round(w_rel, 2),
          "| per-response total ∝", np.round(total / np.abs(total).max(), 2))

w = token_weights(A, lengths, "seq")
print(f"\nseq-mean: per-token penalty of the length-360 wrong answer is {abs(w[3])/abs(w[4]):.2f}× that of the length-120 one")
 

Under sequence-mean the per-response total is the same A^i/G\hat A_i/G regardless of length (the last column is 1, 1, −0.5, …), so per token it becomes 1/∣yi∣1/|y_i|. Under token-sum and constant it is the opposite: the per-token value is the same and the total is proportional to length. The unbiased policy gradient is the latter.

Next is the same toy RLVR as in the figure. This time the policy actually produces answers and verify compares them with the reference. We run the four advantages with the same seed.

NumPy Toy RLVR: verifier, group sampling, advantage variants
SKILL  = np.array([0.10, 0.25, 0.40, 0.55, 0.70, 0.90])   # skill of each strategy
THETA0 = np.array([1.5, 1.2, 0.6, 0.0, -0.6, -1.2])       # the base policy prefers weak strategies
sigmoid = lambda z: 1 / (1 + np.exp(-z))

def generate(rng, s, d, gold):
    """Answer with strategy s. Correct with probability σ(12(skill − d)); otherwise a plausible wrong answer."""
    ok = rng.random(s.shape) < sigmoid(12 * (SKILL[s] - d[:, None]))
    return np.where(ok, gold[:, None], gold[:, None] + rng.integers(1, 20, size=s.shape))

def verify(answers, gold):                 # verifiable reward: a program grades it
    return (answers == gold[:, None]).astype(float)

def batch_adv(r, kind, eps=1e-6):          # r: (B, G) → advantage per group (row)
    m = r.mean(1, keepdims=True)
    if kind == "grpo":      return (r - m) / (r.std(1, keepdims=True) + eps)
    if kind == "dr_grpo":   return r - m
    if kind == "rloo":      return (r - m) * r.shape[1] / (r.shape[1] - 1)
    return r                               # reinforce: no baseline

def train(kind, D, G=8, B=16, lr=0.5, steps=200, seed=0):
    rng = np.random.default_rng(seed)
    th = THETA0.copy(); log = []; zv = []
    for step in range(steps + 1):
        pi = np.exp(th - th.max()); pi /= pi.sum()
        d = np.clip(rng.normal(D, 0.12, B), 0, 1)               # difficulty of B problems
        gold = rng.integers(100, 9999, B)                        # reference answers
        s = np.minimum(np.searchsorted(np.cumsum(pi), rng.random((B, G))), len(th) - 1)
        r = verify(generate(rng, s, d, gold), gold)              # (B, G) 0/1 rewards
        A = batch_adv(r, kind)
        onehot = np.eye(len(th))[s]                              # (B, G, S)
        grad = (A[..., None] * (onehot - pi)).mean((0, 1))       # Σ A ∇log π / (B·G)
        zv.append((r.std(1) == 0).mean())                        # fraction of signal-free groups
        if step % 50 == 0:
            acc = pi @ sigmoid(12 * (SKILL - D))                 # accuracy at the mean difficulty
            log.append((step, acc, np.mean(zv[-25:])))           # mean over the last 25 steps
        th += lr * grad
    return log

for D in [0.3, 0.85]:
    print(f"\ndifficulty D={D}   (step: accuracy / zero-variance group fraction)")
    for kind in ["grpo", "dr_grpo", "rloo", "reinforce"]:
        log = train(kind, D)
        print(f"  {kind:9s}", "  ".join(f"{s:3d}: {a:.2f}/{z:.2f}" for s, a, z in log))

for p in [0.05, 0.5, 0.95]:
    print(f"p={p:.2f}, G=8: P(zero-variance) = {p**8 + (1-p)**8:.3f}")
 

At D=0.85, up to step 50, RLOO, Dr. GRPO and REINFORCE barely move in accuracy, and close to two thirds of the groups are discarded with no signal. Only GRPO gets out quickly — the amplifying effect of std normalisation seen above. At D=0.3, by the end of training more than half the groups are all correct and carry no signal. Change G, or raise lr to match GRPO, to tell which differences are real algorithmic differences.

Real LLM training deals with token-level tensors and masks. Below is a PyTorch loss that covers the GRPO and DAPO families in one function.

PyTorch PyTorch: GRPO/DAPO-style token loss 로컬에서 실행run locally (pip install torch)
import torch

def group_advantages(rewards: torch.Tensor, G: int, mode: str = "grpo", eps: float = 1e-6):
    """rewards: (N,) — assumes the G responses to the same prompt are contiguous (N = B*G)."""
    r = rewards.view(-1, G)
    mean = r.mean(dim=1, keepdim=True)
    if mode == "grpo":
        adv = (r - mean) / (r.std(dim=1, keepdim=True) + eps)   # torch.std defaults to the unbiased (G-1) std
    elif mode == "dr_grpo":
        adv = r - mean
    elif mode == "rloo":
        adv = (r - mean) * G / (G - 1)
    else:
        raise ValueError(mode)
    keep = (r.std(dim=1) > 0).repeat_interleave(G)              # for dynamic sampling: groups with signal
    return adv.view(-1), keep

def policy_loss(logp, old_logp, adv, mask, ref_logp=None, beta=0.0,
                eps_low=0.2, eps_high=0.28, agg="token-mean", L_max=None):
    """logp, old_logp, ref_logp, mask: (N, T), mask=1 only at response-token positions. adv: (N,)"""
    ratio = torch.exp(logp - old_logp)                          # ρ_t
    A = adv.unsqueeze(1)                                        # sequence advantage to every token
    surr = torch.minimum(ratio * A, ratio.clamp(1 - eps_low, 1 + eps_high) * A)
    per_tok = -surr
    if beta > 0:                                                # GRPO: k3 KL directly in the loss
        log_r = ref_logp - logp
        per_tok = per_tok + beta * (torch.exp(log_r) - log_r - 1)
    m = mask.float()
    if agg == "seq-mean-token-mean":                            # original GRPO
        return ((per_tok * m).sum(1) / m.sum(1).clamp(min=1)).mean()
    if agg == "token-mean":                                     # DAPO: mean over all tokens
        return (per_tok * m).sum() / m.sum().clamp(min=1)
    if agg == "seq-mean-token-sum-norm":                        # Dr. GRPO: divide by a constant
        return (per_tok * m).sum() / (m.shape[0] * L_max)
    raise ValueError(agg)

def overlong_penalty(lengths: torch.Tensor, L_max: int, L_cache: int):
    """DAPO soft overlong punishment. Added to the correctness reward."""
    soft = ((L_max - L_cache) - lengths).float() / L_cache
    return torch.where(lengths <= L_max - L_cache, torch.zeros_like(soft),
                       torch.where(lengths <= L_max, soft, -torch.ones_like(soft)))

# For GSPO, make the ratio sequence-level:
#   log_s = ((logp - old_logp) * m).sum(1) / m.sum(1)       # (N,)
#   s = torch.exp(log_s)  ;  surr = min(s*adv, clip(s, 1-ε, 1+ε)*adv)  (ε on the order of 1e-4)
 
확인 문제Check yourself

Under sequence-mean aggregation (original GRPO), two wrong answers in the same group have lengths 100 and 400. With equal advantages, how many times the penalty of a length-100 token does a single token of the length-400 answer receive?

The per-token weight is A^i/(G∣yi∣)\hat A_i/(G|y_i|), so it is 100/400=1/4100/400 = 1/4. As whole responses, both receive a mass of A^i/G\hat A_i/G, but the long response spreads it over four times as many tokens. So each individual token of a long wrong answer is barely penalised, and learning leans towards “if you are going to be wrong, be long”. Under token-level aggregation or constant normalisation, the two tokens get the same penalty.

Summary

  • RLVR uses a grading program as the reward. It is cheap, consistent and harder to hack than an RM, but it is a sparse binary reward.
  • GRPO replaces the critic with the mean of GG responses to the same prompt as the baseline, and gives that advantage to every token. The mean baseline is G−1G\frac{G-1}{G} times RLOO, so its direction is unbiased.
  • Std normalisation weights easy or hard prompts more heavily, and sequence-mean aggregation multiplies each response by 1/∣yi∣1/|y_i|, penalising long wrong answers less. Dr. GRPO removes both; DAPO uses token-level aggregation.
  • DAPO stabilised large-scale training with Clip-Higher (asymmetric clip), dynamic sampling, token-level loss and overlong shaping. GSPO clips a length-normalised sequence ratio.
  • If every reward in a group is the same, there is no signal, with probability pG+(1−p)Gp^G+(1-p)^G. RLVR learns only from problems the model sometimes gets right, so difficulty filtering is essential.

이 그림에서 확인할 것:

  1. D=0.75에서는 처음 수십 step 동안 대부분의 그룹이 전부 오답이다. 신호가 거의 없으니 정확도가 한동안 바닥에 붙어 있다가, 강한 전략을 몇 번 우연히 뽑아 맞힌 뒤에야 오르기 시작한다.
  2. D를 0.3 정도로 낮추면 초반은 빠르지만, 정책이 좋아질수록 전부 정답인 그룹이 늘어 오른쪽 곡선이 다시 올라간다. 학습 후반에는 쉬운 문제가 배치를 낭비한다.
  3. GRPO가 가장 빨리 오르는 것은 std 정규화가 정답이 드문 그룹의 advantage를 키우기 때문이다. 학습률을 크게 쓴 것과 비슷한 효과다. RLOO와 REINFORCE의 차이는 이 단순한 설정에서는 작다.
  4. G를 16으로 키우면 어려운 문제에서도 한 번쯤 맞히는 그룹이 늘어 정체가 짧아진다. 대신 프롬프트당 샘플 비용이 두 배다.

이것이 실전 RLVR에서 데이터 난이도 필터링이 중요한 이유다. 현재 모델로 프롬프트마다 몇 번 풀어 보고 정답률이 0이나 1인 문제를 빼거나, 학습이 진행되며 다시 고른다. 같은 이유로 RLVR은 base 모델이 이미 가끔은 풀 수 있는 문제의 확률을 끌어올리는 데 강하다. Yue et al.(2025)은 RLVR 후 모델이 pass@1은 높지만 kk가 아주 크면 pass@k는 base 모델이 더 높을 수 있다고 보고했다. RL이 새로운 풀이를 만들기보다 이미 있는 풀이를 더 자주 뽑게(sharpening) 만든다는 해석이다. 이 해석을 어디까지 일반화할지는 아직 논쟁 중이다.

확인 문제Check yourself

G=8인 그룹에서 8개 응답이 모두 정답(r=1)이었다. KL 항이 없을 때 이 그룹이 GRPO gradient에 기여하는 양은?

모든 rir_i가 같으면 ri−mean⁡(r)=0r_i - \operatorname{mean}(r) = 0이므로 GRPO, Dr. GRPO, RLOO 모두 A^i=0\hat A_i = 0이다. GRPO는 std도 0이라 구현에서 ε\varepsilon을 더하거나 0으로 정의해 발산을 막는다. 이 그룹은 연산만 쓰고 신호는 주지 않는다. DAPO의 dynamic sampling이 이런 그룹을 버리고 다시 뽑는 이유다. (KL 항이 있으면 그 항의 gradient는 남는다.)

직접 구현하기

먼저 advantage 세 가지와 정규화 세 가지를 그대로 옮긴다. 그림의 “긴 오답 + 짧은 정답” 설정과 같은 숫자다.

NumPy advantage 변형과 토큰당 가중치
import numpy as np

def advantages(r, kind="grpo", eps=1e-6):
    r = np.asarray(r, float); G = len(r)
    if kind == "grpo":                       # (r - mean) / std
        return (r - r.mean()) / (r.std() + eps)
    if kind == "dr_grpo":                    # r - mean  (std 제거)
        return r - r.mean()
    if kind == "rloo":                       # r - (나머지 G-1개의 평균)
        return r - (r.sum() - r) / (G - 1)
    raise ValueError(kind)

def token_weights(A, lengths, norm="seq", L_max=400):
    """응답 i의 토큰 하나가 받는 계수 c_i * A_i (∇log π(y_t) 앞에 곱해지는 값)."""
    A, Ls = np.asarray(A, float), np.asarray(lengths, float); G = len(A)
    if norm == "seq":   c = 1.0 / (G * Ls)                   # GRPO 원본: 응답마다 토큰 평균 후 그룹 평균
    elif norm == "tok": c = np.full(G, 1.0 / Ls.sum())       # DAPO: 그룹의 모든 토큰을 한 번에 평균
    elif norm == "const": c = np.full(G, 1.0 / (G * L_max))  # Dr. GRPO: 상수
    return A * c

r       = np.array([1, 1, 0, 0, 0, 0])
lengths = np.array([60, 80, 380, 360, 120, 300])

for kind in ["grpo", "dr_grpo", "rloo"]:
    print(f"{kind:8s} A =", np.round(advantages(r, kind), 3))
print("RLOO / Dr.GRPO 비 =", np.round(advantages(r, "rloo") / advantages(r, "dr_grpo"), 3), "(= G/(G-1))")

print("\n토큰당 가중치 (GRPO advantage, 가장 큰 |값|=1로 정규화)")
A = advantages(r, "grpo")
for norm in ["seq", "tok", "const"]:
    w = token_weights(A, lengths, norm)
    w_rel = w / np.abs(w).max()
    total = w * lengths                      # 응답 하나의 log-prob 전체에 걸리는 질량
    print(f"  {norm:5s} per-token:", np.round(w_rel, 2),
          "| 응답별 총합 ∝", np.round(total / np.abs(total).max(), 2))

w = token_weights(A, lengths, "seq")
print(f"\nseq-mean: 길이 360 오답의 토큰당 벌점은 길이 120 오답의 {abs(w[3])/abs(w[4]):.2f}배")
 

sequence-mean에서는 응답별 총합이 길이와 무관하게 A^i/G\hat A_i/G로 같고(마지막 열이 1, 1, −0.5, …), 그래서 토큰당으로는 1/∣yi∣1/|y_i|가 된다. token-sum과 상수에서는 반대로 토큰당 값이 같고 총합이 길이에 비례한다. 편향 없는 policy gradient는 후자다.

다음은 그림과 같은 장난감 RLVR이다. 이번에는 정책이 실제로 답을 내고 verify가 정답과 비교한다. 네 가지 advantage를 같은 seed로 돌린다.

NumPy 장난감 RLVR: 검증기, 그룹 샘플링, advantage 변형
SKILL  = np.array([0.10, 0.25, 0.40, 0.55, 0.70, 0.90])   # 전략별 실력
THETA0 = np.array([1.5, 1.2, 0.6, 0.0, -0.6, -1.2])       # base 정책은 약한 전략을 선호
sigmoid = lambda z: 1 / (1 + np.exp(-z))

def generate(rng, s, d, gold):
    """전략 s로 답을 낸다. 맞을 확률 σ(12(skill − d)), 틀리면 그럴듯한 오답."""
    ok = rng.random(s.shape) < sigmoid(12 * (SKILL[s] - d[:, None]))
    return np.where(ok, gold[:, None], gold[:, None] + rng.integers(1, 20, size=s.shape))

def verify(answers, gold):                 # 검증 가능한 보상: 프로그램이 채점한다
    return (answers == gold[:, None]).astype(float)

def batch_adv(r, kind, eps=1e-6):          # r: (B, G) → 그룹(행)마다 advantage
    m = r.mean(1, keepdims=True)
    if kind == "grpo":      return (r - m) / (r.std(1, keepdims=True) + eps)
    if kind == "dr_grpo":   return r - m
    if kind == "rloo":      return (r - m) * r.shape[1] / (r.shape[1] - 1)
    return r                               # reinforce: baseline 없음

def train(kind, D, G=8, B=16, lr=0.5, steps=200, seed=0):
    rng = np.random.default_rng(seed)
    th = THETA0.copy(); log = []; zv = []
    for step in range(steps + 1):
        pi = np.exp(th - th.max()); pi /= pi.sum()
        d = np.clip(rng.normal(D, 0.12, B), 0, 1)               # B개 문제의 난이도
        gold = rng.integers(100, 9999, B)                        # 정답
        s = np.minimum(np.searchsorted(np.cumsum(pi), rng.random((B, G))), len(th) - 1)
        r = verify(generate(rng, s, d, gold), gold)              # (B, G) 0/1 보상
        A = batch_adv(r, kind)
        onehot = np.eye(len(th))[s]                              # (B, G, S)
        grad = (A[..., None] * (onehot - pi)).mean((0, 1))       # Σ A ∇log π / (B·G)
        zv.append((r.std(1) == 0).mean())                        # 신호 없는 그룹 비율
        if step % 50 == 0:
            acc = pi @ sigmoid(12 * (SKILL - D))                 # 평균 난이도에서의 정확도
            log.append((step, acc, np.mean(zv[-25:])))           # 최근 25 step 평균
        th += lr * grad
    return log

for D in [0.3, 0.85]:
    print(f"\n난이도 D={D}   (step: 정확도 / zero-variance 그룹 비율)")
    for kind in ["grpo", "dr_grpo", "rloo", "reinforce"]:
        log = train(kind, D)
        print(f"  {kind:9s}", "  ".join(f"{s:3d}: {a:.2f}/{z:.2f}" for s, a, z in log))

for p in [0.05, 0.5, 0.95]:
    print(f"p={p:.2f}, G=8: P(zero-variance) = {p**8 + (1-p)**8:.3f}")
 

D=0.85에서 step 50까지 RLOO·Dr. GRPO·REINFORCE는 정확도가 거의 그대로이고 그룹의 3분의 2 가까이가 신호 없이 버려진다. GRPO만 빨리 빠져나오는데, 위에서 본 std 정규화의 증폭 효과다. D=0.3에서는 학습이 끝날 무렵 그룹의 절반 이상이 전부 정답이라 신호가 없다. G를 바꾸거나 lr을 GRPO와 맞춰 키워 보면 어떤 차이가 진짜 알고리즘 차이인지 가려낼 수 있다.

실제 LLM 학습에서는 토큰 단위 텐서와 마스크를 다룬다. 아래는 GRPO와 DAPO 계열을 하나의 함수로 쓴 PyTorch 손실이다.

PyTorch PyTorch: GRPO/DAPO 스타일 토큰 손실 로컬에서 실행run locally (pip install torch)
import torch

def group_advantages(rewards: torch.Tensor, G: int, mode: str = "grpo", eps: float = 1e-6):
    """rewards: (N,) — 같은 프롬프트의 G개 응답이 연속으로 놓여 있다고 가정 (N = B*G)."""
    r = rewards.view(-1, G)
    mean = r.mean(dim=1, keepdim=True)
    if mode == "grpo":
        adv = (r - mean) / (r.std(dim=1, keepdim=True) + eps)   # torch.std 기본값은 불편(G-1) std
    elif mode == "dr_grpo":
        adv = r - mean
    elif mode == "rloo":
        adv = (r - mean) * G / (G - 1)
    else:
        raise ValueError(mode)
    keep = (r.std(dim=1) > 0).repeat_interleave(G)              # dynamic sampling용: 신호 있는 그룹
    return adv.view(-1), keep

def policy_loss(logp, old_logp, adv, mask, ref_logp=None, beta=0.0,
                eps_low=0.2, eps_high=0.28, agg="token-mean", L_max=None):
    """logp, old_logp, ref_logp, mask: (N, T) 응답 토큰 위치만 mask=1. adv: (N,)"""
    ratio = torch.exp(logp - old_logp)                          # ρ_t
    A = adv.unsqueeze(1)                                        # 시퀀스 advantage를 모든 토큰에
    surr = torch.minimum(ratio * A, ratio.clamp(1 - eps_low, 1 + eps_high) * A)
    per_tok = -surr
    if beta > 0:                                                # GRPO: k3 KL을 손실에 직접
        log_r = ref_logp - logp
        per_tok = per_tok + beta * (torch.exp(log_r) - log_r - 1)
    m = mask.float()
    if agg == "seq-mean-token-mean":                            # GRPO 원본
        return ((per_tok * m).sum(1) / m.sum(1).clamp(min=1)).mean()
    if agg == "token-mean":                                     # DAPO: 모든 토큰 평균
        return (per_tok * m).sum() / m.sum().clamp(min=1)
    if agg == "seq-mean-token-sum-norm":                        # Dr. GRPO: 상수로 나눔
        return (per_tok * m).sum() / (m.shape[0] * L_max)
    raise ValueError(agg)

def overlong_penalty(lengths: torch.Tensor, L_max: int, L_cache: int):
    """DAPO soft overlong punishment. 정답 보상에 더한다."""
    soft = ((L_max - L_cache) - lengths).float() / L_cache
    return torch.where(lengths <= L_max - L_cache, torch.zeros_like(soft),
                       torch.where(lengths <= L_max, soft, -torch.ones_like(soft)))

# GSPO라면 ratio를 시퀀스 단위로:
#   log_s = ((logp - old_logp) * m).sum(1) / m.sum(1)       # (N,)
#   s = torch.exp(log_s)  ;  surr = min(s*adv, clip(s, 1-ε, 1+ε)*adv)  (ε ~ 1e-4 규모)
 
확인 문제Check yourself

sequence-mean 집계(GRPO 원본)에서 같은 그룹의 오답 두 개가 길이 100, 400이다. 두 응답의 advantage가 같을 때, 길이 400 오답의 토큰 하나가 받는 벌점은 길이 100 오답 토큰의 몇 배인가?

토큰당 가중치는 A^i/(G∣yi∣)\hat A_i/(G|y_i|)이므로 100/400=1/4100/400 = 1/4배다. 응답 전체로는 둘 다 A^i/G\hat A_i/G의 질량을 받지만 긴 응답은 그것을 네 배 많은 토큰에 나눠 가진다. 그래서 긴 오답의 토큰 하나하나는 거의 벌을 받지 않고, 학습은 “틀릴 거면 길게” 쪽으로 기운다. token-level 집계나 상수 정규화에서는 두 토큰의 벌점이 같다.

정리

  • RLVR은 채점 프로그램을 보상으로 쓴다. 싸고 일관적이며 RM보다 해킹이 어렵지만, 희소한 이진 보상이다.
  • GRPO는 critic 대신 같은 프롬프트의 GG개 응답 평균을 baseline으로 쓰고, 그 advantage를 모든 토큰에 준다. 평균 baseline은 RLOO의 G−1G\frac{G-1}{G}배라 방향은 불편이다.
  • std 정규화는 쉽거나 어려운 프롬프트를 더 크게 가중하고, sequence-mean 집계는 응답마다 1/∣yi∣1/|y_i|를 곱해 긴 오답을 덜 벌한다. Dr. GRPO는 둘을 빼고, DAPO는 token-level 집계를 쓴다.
  • DAPO는 Clip-Higher(비대칭 clip), dynamic sampling, token-level loss, overlong shaping으로 대규모 학습을 안정화했다. GSPO는 길이 정규화된 시퀀스 ratio로 clip한다.
  • 그룹의 보상이 모두 같으면 신호가 없다. 확률 pG+(1−p)Gp^G+(1-p)^G. RLVR은 모델이 가끔 맞히는 문제에서만 배우므로 난이도 필터링이 핵심이다.

더 읽을거리Further reading