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.
For math, the final answer is normalised and compared with the reference answer ; 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 of roughly the same size as the policy. Nearly doubling memory and compute is one problem, but in RLVR the target must learn is itself hard. Since the reward exists only at the end, 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 responses for the same prompt and use their mean reward as the baseline. As we saw in policy gradients, a baseline does not change the expectation as long as it does not depend on the response .
With the reward only at the end and , GAE reduces to . Instead of learning this 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.
The KL is not mixed into the reward but added directly to the loss, using the per-token k3 estimator (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 per response and then a group mean. All three change the result.
Baseline: mean, leave-one-out, std
The group mean contains itself, so it seems to break the condition that “the baseline must not depend on ”. But rearranged, it differs only by a scale.
The term in parentheses is the advantage of RLOO (REINFORCE Leave-One-Out; Kool et al. 2019, Ahmadian et al. 2024). The other responses were drawn independently of , so RLOO is an unbiased estimator, and the mean baseline is times it. Same direction.
Dividing by the std is different. With binary rewards, a group with success rate has std , so the expected GRPO gradient
carries a per-prompt weight. Very easy or very hard problems, with 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 . 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 (), the gradient of the GRPO loss written out per token is:
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의 보상은 대개 이렇다.
수학이면 최종 답을 정규화해 정답 와 비교하고, 코드면 단위 테스트를 돌린다. DeepSeek-R1-Zero는 정답 보상에 <think> 태그 형식을 지켰는지 보는 형식 보상만 더했다. 학습된 RM과 비교하면 성질이 뚜렷이 다르다.
- 싸고 일관적이다. RM 추론이 필요 없고, 같은 응답에 언제나 같은 점수를 준다.
- 해킹하기 어렵다(불가능하지는 않다). RM처럼 분포 밖에서 엉뚱한 점수를 주지 않는다. 다만 테스트를 수정하거나 특수 처리하는 코드, 채점기 파서의 허점을 노리는 출력은 여전히 가능하다(과최적화 레슨).
- 희소하고 이진이다. 응답 하나에 0 또는 1, 그것도 마지막에 한 번 나온다.
왜 critic을 버리는가
PPO로 LLM을 학습하면 정책과 비슷한 크기의 value model 를 하나 더 들고 다닌다. 메모리와 연산이 거의 두 배가 되는 것도 문제지만, RLVR에서는 가 배워야 할 대상 자체가 어렵다. 보상이 마지막에만 있으니 는 “지금까지 쓴 풀이로부터 결국 정답에 도달할 확률”이다. 수천 토큰짜리 추론 중간에서 이것을 맞히는 것은 문제를 푸는 것만큼 어렵다.
대신 같은 프롬프트 에서 응답을 개 뽑아 그 보상 평균을 baseline으로 쓴다. 정책 경사에서 본 대로 baseline 가 그 응답 에 의존하지만 않으면 기대값을 바꾸지 않는다.
보상이 끝에만 있고 이면 GAE는 가 된다. GRPO는 이 를 토큰마다 학습하는 대신 프롬프트 수준의 Monte Carlo 추정치 하나로 바꾸고, 그 advantage를 응답의 모든 토큰에 똑같이 준다.
GRPO
GRPO(Group Relative Policy Optimization, Shao et al. 2024)의 목적함수는 PPO의 clip 목적함수를 그룹 단위로 쓴 것이다.
KL은 보상에 섞지 않고 손실에 직접 더하며, 토큰마다 k3 추정량 을 쓴다(KL 추정량). 세 가지 선택이 들어 있다. (1) baseline이 그룹 평균이고, (2) 그룹 std로 나누며, (3) 응답마다 토큰 평균 을 낸 뒤 그룹 평균을 낸다. 셋 다 결과를 바꾼다.
baseline: 평균, leave-one-out, std
그룹 평균에는 자신이 들어 있으니 “baseline이 에 의존하면 안 된다”는 조건을 어기는 것처럼 보인다. 하지만 정리해 보면 스케일만 다르다.
괄호 안이 RLOO(REINFORCE Leave-One-Out; Kool et al. 2019, Ahmadian et al. 2024)의 advantage다. 나머지 개는 와 독립으로 뽑혔으니 RLOO는 불편(unbiased) 추정량이고, 평균 baseline은 그것의 배다. 방향은 같다.
std로 나누는 것은 다르다. 이진 보상에서 정답률이 인 그룹의 std는 이므로, GRPO의 기대 gradient는
처럼 프롬프트마다 가중치가 붙는다. 가 0이나 1에 가까운, 아주 쉽거나 아주 어려운 문제가 더 큰 가중치를 받는다. 각 프롬프트 안에서 방향은 맞지만, 프롬프트 사이의 비중을 바꾸어 원래 목적함수 와 다른 것을 최적화한다. Dr. GRPO(Liu et al. 2025)는 이것을 question-level difficulty bias라고 부르고 std를 뺐다.
그림으로: advantage와 토큰당 가중치
clip이 걸리지 않은 상태()에서 GRPO 손실의 gradient를 토큰 단위로 풀어 쓰면 이렇다.
- 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 .
- 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.
- 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.
- 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 ‘s total log-probability is . An unbiased policy gradient would have , so in effect each response is multiplied by an extra . As a result
- correct answers () are pushed up harder the shorter they are, and
- wrong answers () 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 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 can barely grow low-probability tokens. With , a token with can rise only to in one update, whereas a token at has so much room that the upper bound is meaningless. The low-probability tokens needed for exploration are held down and entropy collapses quickly. DAPO widens only the upper bound, using .
Dynamic sampling. If every reward in a group is the same, 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 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 .
GSPO: a sequence-level ratio
GRPO’s 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, 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.
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 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 is all the same value is
At , it is 0.66 for and 0.008 for . 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.
- “긴 오답 + 짧은 정답”을 누르고 sequence-mean에서 막대 색을 보자. 길이 380짜리 오답의 토큰은 거의 흰색이다. 같은 오답이라도 길수록 토큰 하나가 받는 벌이 로 작아진다.
- token-sum이나 상수로 바꾸면 정답 토큰은 모두 같은 파랑, 오답 토큰은 모두 같은 빨강이 된다. 길이와 무관하게 토큰 하나는 토큰 하나다.
- “하나만 정답”에서 오른쪽 막대를 보면 GRPO의 정답 advantage가 RLOO보다 훨씬 크다. 정답이 드문 그룹일수록 std가 작아 GRPO가 신호를 증폭한다.
- “모두 정답”을 누르면 advantage가 전부 0이다. 그룹이 아무리 커도 이 프롬프트에서는 배울 것이 없다.
길이 정규화 편향
sequence-mean에서 응답 의 로그확률 전체 에 걸리는 계수는 다. 편향 없는 policy gradient라면 여야 하니, 응답마다 가 추가로 곱해진 셈이다. 그 결과
- 정답()은 짧을수록 더 강하게 밀어 올리고,
- 오답()은 길수록 덜 밀어 내린다.
두 번째 효과 때문에 틀린 응답이 길어지는 쪽으로 압력이 생긴다. Dr. GRPO 논문은 R1-Zero류 학습에서 관찰되는 응답 길이 증가 가운데 일부가 이 편향에서 올 수 있다고 지적하고, 를 상수로 바꾸면 비슷한 정확도에서 오답 길이가 계속 늘어나지 않는다고 보고했다. 길이가 늘어나는 현상 자체(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 은 확률이 작은 토큰을 거의 못 키운다. 일 때 인 토큰은 한 번의 업데이트로 최대 까지만 오르지만 인 토큰은 상한 이 의미 없을 만큼 여유가 있다. 탐색에 필요한 저확률 토큰이 묶이고 entropy가 빨리 무너진다. DAPO는 상한만 넓혀 을 쓴다.
Dynamic sampling. 그룹의 보상이 모두 같으면 이고 gradient가 0이다. 이런 그룹이 많으면 배치의 실효 크기가 줄어 gradient 분산이 커진다. 정답률이 0이나 1인 그룹은 버리고, 배치가 찰 때까지 더 뽑는다.
Token-level loss. 위 그림의 token-sum이다. 그룹 안의 모든 토큰을 한 번에 평균해서 긴 응답의 토큰이 희석되지 않게 한다.
Overlong reward shaping. 최대 길이 에서 잘린 응답은 풀이가 맞았을 수도 있는데 정답 추출에 실패해 0점을 받는다. 이 잡음을 줄이려고 잘린 샘플을 손실에서 빼거나(overlong filtering), 끝 구간 에서 부드러운 벌점을 준다.
GSPO: 시퀀스 단위 ratio
GRPO의 는 토큰마다 따로 계산한 ratio다. 그런데 보상은 응답 전체에 하나 붙어 있다. 토큰 위치마다 샘플이 하나뿐이니 는 분포 차이를 제대로 보정하지 못하고 잡음만 더하며, 그 잡음이 긴 응답에서 누적된다. MoE 모델에서는 업데이트마다 일부 토큰의 expert 선택이 바뀌어 토큰 ratio가 크게 흔들리기도 한다. GSPO(Zheng et al. 2025)는 보상의 단위와 최적화의 단위를 맞춰, 길이로 정규화한 시퀀스 ratio를 clip한다.
는 토큰 ratio의 기하평균이라 응답의 모든 토큰이 같은 가중치를 받는다. 길이로 정규화했으니 응답이 길어도 값이 폭발하지 않는다(이유는 학습–추론 불일치 레슨의 곱셈 ratio 그림에서 본다). clip이 응답 단위로 걸리기 때문에 범위도 GRPO의 0.2보다 훨씬 좁게(논문 실험에서는 수준) 잡는다. Qwen 팀은 이것으로 MoE RL을 routing replay 없이 안정화했다고 보고한다.
→ 더 깊이: 시퀀스냐 토큰이냐에서 네 가지 집계 방식과 토큰·시퀀스 단위 ratio를 나란히 비교하고, 각각이 긴 응답에 무엇을 하는지 본다.
신호 없는 그룹과 난이도
이진 보상에서 정답률이 인 프롬프트의 그룹이 전부 같은 값일 확률은
이다. 에서 이면 0.66, 이면 0.008이다. 너무 어려운 문제(전부 오답)와 너무 쉬운 문제(전부 정답)는 둘 다 gradient를 만들지 않는다. RLVR은 모델이 가끔은 맞히는 문제에서만 배운다.
→ 더 깊이: 보상과 환경 — 난이도 필터링과 curriculum, 다중 환경 RLVR, 검증기 설계.
Things to check in this figure:
- 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.
- 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.
- 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.
- 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 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.
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 is equal, then , so for GRPO, Dr. GRPO and RLOO alike. For GRPO the std is also 0, so implementations add 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.
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 regardless of length (the last column is 1, 1, −0.5, …), so per token it becomes . 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.
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.
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)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 , so it is . As whole responses, both receive a mass of , 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 responses to the same prompt as the baseline, and gives that advantage to every token. The mean baseline is times RLOO, so its direction is unbiased.
- Std normalisation weights easy or hard prompts more heavily, and sequence-mean aggregation multiplies each response by , 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 . RLVR learns only from problems the model sometimes gets right, so difficulty filtering is essential.
이 그림에서 확인할 것:
- D=0.75에서는 처음 수십 step 동안 대부분의 그룹이 전부 오답이다. 신호가 거의 없으니 정확도가 한동안 바닥에 붙어 있다가, 강한 전략을 몇 번 우연히 뽑아 맞힌 뒤에야 오르기 시작한다.
- D를 0.3 정도로 낮추면 초반은 빠르지만, 정책이 좋아질수록 전부 정답인 그룹이 늘어 오른쪽 곡선이 다시 올라간다. 학습 후반에는 쉬운 문제가 배치를 낭비한다.
- GRPO가 가장 빨리 오르는 것은 std 정규화가 정답이 드문 그룹의 advantage를 키우기 때문이다. 학습률을 크게 쓴 것과 비슷한 효과다. RLOO와 REINFORCE의 차이는 이 단순한 설정에서는 작다.
- G를 16으로 키우면 어려운 문제에서도 한 번쯤 맞히는 그룹이 늘어 정체가 짧아진다. 대신 프롬프트당 샘플 비용이 두 배다.
이것이 실전 RLVR에서 데이터 난이도 필터링이 중요한 이유다. 현재 모델로 프롬프트마다 몇 번 풀어 보고 정답률이 0이나 1인 문제를 빼거나, 학습이 진행되며 다시 고른다. 같은 이유로 RLVR은 base 모델이 이미 가끔은 풀 수 있는 문제의 확률을 끌어올리는 데 강하다. Yue et al.(2025)은 RLVR 후 모델이 pass@1은 높지만 가 아주 크면 pass@k는 base 모델이 더 높을 수 있다고 보고했다. RL이 새로운 풀이를 만들기보다 이미 있는 풀이를 더 자주 뽑게(sharpening) 만든다는 해석이다. 이 해석을 어디까지 일반화할지는 아직 논쟁 중이다.
G=8인 그룹에서 8개 응답이 모두 정답(r=1)이었다. KL 항이 없을 때 이 그룹이 GRPO gradient에 기여하는 양은?
모든 가 같으면 이므로 GRPO, Dr. GRPO, RLOO 모두 이다. GRPO는 std도 0이라 구현에서 을 더하거나 0으로 정의해 발산을 막는다. 이 그룹은 연산만 쓰고 신호는 주지 않는다. DAPO의 dynamic sampling이 이런 그룹을 버리고 다시 뽑는 이유다. (KL 항이 있으면 그 항의 gradient는 남는다.)
직접 구현하기
먼저 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에서는 응답별 총합이 길이와 무관하게 로 같고(마지막 열이 1, 1, −0.5, …), 그래서 토큰당으로는 가 된다. token-sum과 상수에서는 반대로 토큰당 값이 같고 총합이 길이에 비례한다. 편향 없는 policy gradient는 후자다.
다음은 그림과 같은 장난감 RLVR이다. 이번에는 정책이 실제로 답을 내고 verify가 정답과 비교한다. 네 가지 advantage를 같은 seed로 돌린다.
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 손실이다.
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 규모)sequence-mean 집계(GRPO 원본)에서 같은 그룹의 오답 두 개가 길이 100, 400이다. 두 응답의 advantage가 같을 때, 길이 400 오답의 토큰 하나가 받는 벌점은 길이 100 오답 토큰의 몇 배인가?
토큰당 가중치는 이므로 배다. 응답 전체로는 둘 다 의 질량을 받지만 긴 응답은 그것을 네 배 많은 토큰에 나눠 가진다. 그래서 긴 오답의 토큰 하나하나는 거의 벌을 받지 않고, 학습은 “틀릴 거면 길게” 쪽으로 기운다. token-level 집계나 상수 정규화에서는 두 토큰의 벌점이 같다.
정리
- RLVR은 채점 프로그램을 보상으로 쓴다. 싸고 일관적이며 RM보다 해킹이 어렵지만, 희소한 이진 보상이다.
- GRPO는 critic 대신 같은 프롬프트의 개 응답 평균을 baseline으로 쓰고, 그 advantage를 모든 토큰에 준다. 평균 baseline은 RLOO의 배라 방향은 불편이다.
- std 정규화는 쉽거나 어려운 프롬프트를 더 크게 가중하고, sequence-mean 집계는 응답마다 를 곱해 긴 오답을 덜 벌한다. Dr. GRPO는 둘을 빼고, DAPO는 token-level 집계를 쓴다.
- DAPO는 Clip-Higher(비대칭 clip), dynamic sampling, token-level loss, overlong shaping으로 대규모 학습을 안정화했다. GSPO는 길이 정규화된 시퀀스 ratio로 clip한다.
- 그룹의 보상이 모두 같으면 신호가 없다. 확률 . RLVR은 모델이 가끔 맞히는 문제에서만 배우므로 난이도 필터링이 핵심이다.
더 읽을거리Further reading
- Shao et al., DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models (2024) — GRPO를 처음 제안한 논문. 목적함수, group-normalized advantage, k3 KL 항의 원형.The paper that first proposed GRPO. The prototype of the objective, the group-normalised advantage and the k3 KL term.
- DeepSeek-AI, DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via Reinforcement Learning (2025) — base 모델에 규칙 기반 보상과 GRPO만으로 긴 추론이 생기는 R1-Zero, 응답 길이 증가와 "aha moment".R1-Zero, where long reasoning emerges from a base model with only rule-based rewards and GRPO; growing response length and the "aha moment".
- Lambert et al., Tülu 3: Pushing Frontiers in Open Language Model Post-Training (2024) — RLVR이라는 이름을 붙인 공개 사후학습 레시피.The open post-training recipe that gave RLVR its name.
- Ahmadian et al., Back to Basics: Revisiting REINFORCE Style Optimization for Learning from Human Feedback in LLMs (ACL 2024) — RLOO를 LLM에 가져와 PPO의 critic·clip이 꼭 필요하지 않음을 보였다. leave-one-out baseline의 원형은 Kool et al. (2019).Brought RLOO to LLMs and showed that PPO's critic and clip are not strictly necessary. The leave-one-out baseline goes back to Kool et al. (2019).
- Liu et al., Understanding R1-Zero-Like Training: A Critical Perspective (2025) — Dr. GRPO. 응답 길이 정규화와 std 정규화가 만드는 두 편향을 지적.Dr. GRPO. Points out two biases created by response-length normalisation and std normalisation.
- Yu et al., DAPO: An Open-Source LLM Reinforcement Learning System at Scale (2025) — Clip-Higher, dynamic sampling, token-level loss, overlong reward shaping.Clip-Higher, dynamic sampling, token-level loss, overlong reward shaping.
- Zheng et al., Group Sequence Policy Optimization (2025) — GSPO. 토큰 ratio 대신 길이 정규화된 시퀀스 ratio로 clip한다.GSPO. Clips a length-normalised sequence ratio instead of token ratios.
- Yue et al., Does Reinforcement Learning Really Incentivize Reasoning Capacity in LLMs Beyond the Base Model? (2025) — RLVR이 pass@1은 올리지만 큰 k의 pass@k는 base가 더 높을 수 있다는 관찰. "RL은 무엇을 배우는가"에 대한 반론.The observation that RLVR raises pass@1, but the base model can have higher pass@k at large k. A counterpoint on "what does RL learn".
- Lambert, RLHF Book — Reasoning chapter — RLVR과 추론 모델 학습을 교과서 표기로 정리.Covers RLVR and reasoning-model training in textbook notation.