The landscape lesson wrote every objective as a per-token weight . This lesson takes apart the two coordinates that decide at which unit the algorithm thinks: the aggregation , which sets how much a token weighs given the length of its response, and the unit of the ratio — token, sequence, or something in between. RLVR and GRPO introduced the three normalisations and the length-bias intuition; here we derive what each one optimises, why sequence-level ratios became popular for MoE models, and what remains of a batch after zero-variance groups are removed.
Aggregation: four modes, four objectives
With per-token losses for responses, frameworks offer four ways to reduce them to a scalar (verl calls the option loss_agg_mode):
| Mode | Formula | Per-token weight | Used by |
|---|---|---|---|
seq-mean-token-mean | original GRPO, DeepSeek-V3.2, GLM-5 reasoning | ||
token-mean | DAPO, MiniMax, MiMo, MAI, Olmo 3, Kimi K2.5 | ||
seq-mean-token-sum | REINFORCE on whole sequences, k1.5 | ||
seq-mean-token-sum-norm | Dr. GRPO |
What sequence-mean optimises
On-policy (, no clip), sequence-mean gives the gradient , because the token gradients of a response sum to the gradient of its log-probability. With and held fixed (it is a statistic of the batch), its expectation is
So sequence-mean GRPO is an unbiased policy gradient for a different reward, . For a correct answer () the reward is largest when the answer is short; for a wrong answer it is , which goes to 0 as the answer gets longer. The policy is rewarded for being brief when right and for rambling when wrong. This is Dr. GRPO’s length bias, now as an exact statement: it is not an artefact of variance or of clipping.
Two consequences follow. First, the drift needs a correlation between length and correctness that the policy can control. If length were drawn independently of whether the attempt succeeds, the two pushes would cancel exactly in expectation: at . A reasoning model does know when it is stuck, which is why the bias shows up in practice. Second, the GRPO std only rescales: dividing by changes per-prompt weights, not the length preference.
What the other modes optimise
Constant normalisation (Dr. GRPO) is the unbiased gradient of up to the constant . Its catch is the step size: the signal part of grows with the response length, so as responses grow from 2K to 20K tokens the effective learning rate grows too. Token-mean divides by the batch’s realised token count. Up to the randomness of that denominator it is unbiased as well, with a length-adaptive step: as responses grow, each token’s weight shrinks in proportion. The denominator is correlated with the lengths in the batch, so a long response slightly dilutes everyone’s weight including its own — a mild residual length preference, visible in the figure as a slow drift. Sequence-sum (k1.5) is unbiased with the largest length-dependence of the step.
In a picture: the length drift
The figure trains the smallest model that can show the bias: a policy that picks its response length from one distribution when its attempt is on track (and will be correct) and from another when it is stuck. Accuracy is fixed at , so length never changes the reward. The update is the exact expected gradient of each aggregation mode.
지도 레슨은 모든 목적함수를 토큰당 가중치 로 썼다. 이 레슨은 알고리즘이 어떤 단위로 생각하는지를 정하는 두 좌표를 해부한다. 하나는 응답 길이에 따라 토큰 하나의 무게를 정하는 집계 , 다른 하나는 ratio 의 단위 — 토큰, 시퀀스, 또는 그 사이 — 다. RLVR과 GRPO가 세 정규화와 길이 편향의 직관을 소개했다. 여기서는 각각이 무엇을 최적화하는지 유도하고, 시퀀스 단위 ratio가 왜 MoE 모델에서 인기를 얻었는지, 신호 없는 그룹을 걷어 내면 배치에 무엇이 남는지 본다.
집계: 네 방식, 네 목적함수
응답 개의 토큰별 손실 를 스칼라 하나로 줄이는 방법으로 프레임워크는 네 가지를 제공한다(verl의 옵션 이름은 loss_agg_mode).
| 방식 | 식 | 토큰당 가중치 | 쓰는 곳 |
|---|---|---|---|
seq-mean-token-mean | 원래 GRPO, DeepSeek-V3.2, GLM-5 추론 단계 | ||
token-mean | DAPO, MiniMax, MiMo, MAI, Olmo 3, Kimi K2.5 | ||
seq-mean-token-sum | 시퀀스 전체 REINFORCE, k1.5 | ||
seq-mean-token-sum-norm | Dr. GRPO |
Sequence-mean이 최적화하는 것
On-policy(, clip 없음)에서 sequence-mean의 gradient는 다. 응답의 토큰 gradient 개를 더하면 그 응답 log-확률의 gradient이기 때문이다. 이고 를 고정하면(배치의 통계량이다) 기댓값은
즉 sequence-mean GRPO는 다른 보상 에 대한 편향 없는 policy gradient다. 정답()이면 짧을수록 보상이 크다. 오답이면 보상이 이고 길수록 0에 가까워진다. 정책은 맞을 때 간결하고 틀릴 때 장황하도록 보상받는다. Dr. GRPO의 길이 편향을 정확한 명제로 쓴 것이다. 분산이나 clip이 만든 부작용이 아니다.
두 가지가 따라 나온다. 첫째, 이동이 생기려면 정책이 조절할 수 있는 길이와 정답 여부 사이의 상관이 필요하다. 시도의 성공과 무관하게 길이를 뽑는다면 두 힘은 기댓값에서 정확히 상쇄된다. 에서 . 추론 모델은 자기가 막혔다는 것을 안다. 그래서 실제로 편향이 나타난다. 둘째, GRPO의 std는 크기만 바꾼다. 을 로 나누면 프롬프트별 가중치가 바뀔 뿐 길이 선호는 그대로다.
다른 방식들이 최적화하는 것
상수 정규화(Dr. GRPO)는 상수 을 빼면 의 편향 없는 gradient다. 대가는 step 크기다. 의 신호 부분은 응답 길이에 따라 커지므로, 응답이 2K에서 20K 토큰으로 길어지면 실효 학습률도 커진다. Token-mean은 배치에 실제로 나온 토큰 수로 나눈다. 분모의 무작위성을 빼면 역시 편향이 없고, step이 길이에 적응한다. 응답이 길어지면 토큰 하나의 무게가 비례해 줄어든다. 분모가 배치 안의 길이와 상관되어 있어서 긴 응답 하나가 자기를 포함한 모두의 무게를 조금 묽힌다. 약한 잔여 길이 선호이고, 그림에서 느린 이동으로 보인다. Sequence-sum(k1.5)은 편향이 없지만 step이 길이에 가장 크게 의존한다.
그림으로: 길이 이동
그림은 편향을 보일 수 있는 가장 작은 모델을 학습한다. 시도가 궤도에 올라 맞을 때는 한 분포에서, 막혔을 때는 다른 분포에서 응답 길이를 고르는 정책이다. 정답률은 로 고정이라 길이는 보상을 바꾸지 않는다. 업데이트는 각 집계 방식의 정확한 기대 gradient다.
- With sequence-mean, after 400 steps the wrong answers have grown from about 2,400 to well over 3,000 tokens while correct ones shrank, and the tokens spent per response went up although accuracy never changed.
- Switch to the constant normaliser: nothing moves. Token-mean drifts only slightly (the correlated denominator).
- Lower to 0.1: is small, so the wrong-answer reward is small at every length and the drift of wrong answers slows; the correct answers, with reward , are pushed short much harder. Raise to 0.8 and it is the other way around.
The same mechanism is why length bias can be used on purpose. MiMo-V2.6 averages per prompt in order to slow length growth, and the MiniMax-M1 report fixed a pattern collapse in which wrong responses grew longer faster by combining a sample-level loss with token-level normalisation (both from the Track VI reviews). A sequence-level weight is a length penalty you did not write down; make sure you know whether you want it.
import numpy as np
rng = np.random.default_rng(0)
LS = 500.0 * np.arange(1, 17) # 16 length bins, 500 … 8000 tokens
L_MAX = LS[-1]
softmax = lambda z: np.exp(z - z.max()) / np.exp(z - z.max()).sum()
def train(agg, p=0.3, B=64, G=8, steps=300, lr=0.5):
z0 = -(np.log(LS) - np.log(2000)) ** 2 / (2 * 0.35 ** 2)
zc, zw = z0.copy(), z0.copy() # length logits when on track (correct) / stuck (wrong)
log = []
for s in range(steps + 1):
pc, pw = softmax(zc), softmax(zw)
if s % 100 == 0:
log.append((pc @ LS, pw @ LS))
r = (rng.random((B, G)) < p).astype(float) # the attempt succeeds with prob p, independent of length
Lc = rng.choice(16, size=(B, G), p=pc).astype(np.intp)
Lw = rng.choice(16, size=(B, G), p=pw).astype(np.intp)
L_idx = np.where(r > 0, Lc, Lw)
L = LS[L_idx]
A = r - r.mean(1, keepdims=True) # group-mean baseline
if agg == "seq-mean": c = 1 / (G * L) # 1/(G|y_i|)
elif agg == "token-mean": c = np.broadcast_to(1 / L.sum(1, keepdims=True), L.shape) # 1/Σ_j|y_j|
else: c = np.full_like(L, 1 / (G * L_MAX)) # 1/(G·L_max)
w = (c * A * 2000).ravel() # weight on ∇ log π(L); ×2000 puts all three on one lr scale
onehot = np.eye(16)[L_idx.ravel()]
gc = ((w * (r.ravel() > 0))[:, None] * (onehot - pc)).sum(0) / B
gw = ((w * (r.ravel() == 0))[:, None] * (onehot - pw)).sum(0) / B
zc += lr * gc; zw += lr * gw
return log
print("mean length (correct / wrong) at steps 0, 100, 200, 300 — accuracy fixed at p = 0.3")
for agg in ["seq-mean", "token-mean", "constant"]:
log = train(agg)
print(f" {agg:10s}", " ".join(f"{a:5.0f}/{b:5.0f}" for a, b in log))
# the seq-mean gradient is the exact gradient of E[(r − b)/|y|]: the reward a wrong answer sees
p, b = 0.3, 0.3
print("\neffective reward (r − b)/|y| for a wrong answer:",
", ".join(f"L={L:.0f}: {(0 - b) / L * 1000:+.3f}e-3" for L in [500, 2000, 8000]))The sampled run agrees with the figure: under sequence-mean, wrong answers grow from 2,400 to about 2,850 tokens in 300 steps while correct answers shrink to about 1,700; the constant normaliser leaves both at 2,400; token-mean drifts by about 80 tokens. The last line is the whole story in three numbers: a wrong answer of 8,000 tokens is penalised 16 times less than one of 500.
The unit of the ratio
Sequence-mean was about how tokens are summed. The ratio question is about what is compared with the trust region. GRPO and DAPO use one ratio per token, . Three alternatives move toward the sequence.
GSPO (Zheng et al. 2025) clips the length-normalised sequence ratio
Since , the per-token weight inside the band is
Two facts are visible in this one line. Every token of a response gets the same weight (no token-level noise multiplies the gradient), and GSPO inherits sequence-mean aggregation: the and hence the reward from the previous section come back through the derivative of the geometric mean. The paper’s clip range is / , three orders of magnitude narrower than GRPO’s, and it reports clipping a fraction of tokens two orders of magnitude larger than GRPO while training more efficiently. For multi-turn use, GSPO-token sets , whose value equals but which allows a per-token advantage .
GMPO (Zhao et al. 2025) keeps the token-level clip but replaces GRPO’s arithmetic mean over tokens with a geometric mean:
with the clip range in log space. Differentiating the of the product shows that an unclipped token gets , where is the geometric mean of the clipped ratios, and a clipped token gets 0. It is GSPO’s weight with GRPO’s token-level clip decision: an outlier token is switched off on its own instead of taking the whole response with it, and it can only move by a bounded amount.
SAPO (Gao et al. 2025) removes the hard edge altogether. Each token’s weight is multiplied by a smooth gate,
which is 1 at and decays smoothly. The temperature depends on the sign of the advantage, and in the paper’s controlled runs, so negative-advantage tokens fade faster (the paper reports as the most stable setting, arguing that negative-token gradients spread over many irrelevant vocabulary entries). Under the paper’s assumptions the average token gate concentrates to a sequence-level gate — a soft GSPO that can still down-weight a single outlier token.
In a picture: token ratios against sequence ratios
Why would a geometric mean be a better unit than a token? Decompose each token’s log-ratio into a systematic part (the movement the update intended, which has the sign of ), token-level noise (one sample per position; for MoE also small routing jitter), and rare large jumps (a token whose expert changed; the GSPO paper reports that about 10% of the activated experts change after a gradient update in a 48-layer MoE).
- sequence-mean에서 400 step 뒤 오답은 약 2,400에서 3,000토큰을 훌쩍 넘게 자라고 정답은 줄었다. 정답률은 한 번도 바뀌지 않았는데 응답당 토큰은 늘었다.
- 상수 정규화로 바꾸면 아무것도 움직이지 않는다. token-mean은 아주 조금만 움직인다(상관된 분모).
- 를 0.1로 낮추면 가 작아서 오답 보상 이 모든 길이에서 작고, 오답의 이동이 느려진다. 보상이 인 정답은 훨씬 세게 짧아진다. 를 0.8로 올리면 반대다.
같은 메커니즘 때문에 길이 편향을 일부러 쓸 수도 있다. MiMo-V2.6은 길이 증가를 늦추려고 일부러 프롬프트별로 평균하고, MiniMax-M1 보고서는 오답이 더 빨리 길어지는 pattern collapse를 sample 단위 손실과 토큰 단위 정규화를 섞어서 고쳤다(둘 다 Track VI 리뷰에서). 시퀀스 단위 가중치는 적어 두지 않은 길이 패널티다. 그것을 원하는지 알고 써라.
import numpy as np
rng = np.random.default_rng(0)
LS = 500.0 * np.arange(1, 17) # 길이 구간 16개, 500 … 8000 토큰
L_MAX = LS[-1]
softmax = lambda z: np.exp(z - z.max()) / np.exp(z - z.max()).sum()
def train(agg, p=0.3, B=64, G=8, steps=300, lr=0.5):
z0 = -(np.log(LS) - np.log(2000)) ** 2 / (2 * 0.35 ** 2)
zc, zw = z0.copy(), z0.copy() # 궤도에 오름(정답) / 막힘(오답)일 때의 길이 logit
log = []
for s in range(steps + 1):
pc, pw = softmax(zc), softmax(zw)
if s % 100 == 0:
log.append((pc @ LS, pw @ LS))
r = (rng.random((B, G)) < p).astype(float) # 시도는 길이와 무관하게 확률 p로 성공
Lc = rng.choice(16, size=(B, G), p=pc).astype(np.intp)
Lw = rng.choice(16, size=(B, G), p=pw).astype(np.intp)
L_idx = np.where(r > 0, Lc, Lw)
L = LS[L_idx]
A = r - r.mean(1, keepdims=True) # 그룹 평균 baseline
if agg == "seq-mean": c = 1 / (G * L) # 1/(G|y_i|)
elif agg == "token-mean": c = np.broadcast_to(1 / L.sum(1, keepdims=True), L.shape) # 1/Σ_j|y_j|
else: c = np.full_like(L, 1 / (G * L_MAX)) # 1/(G·L_max)
w = (c * A * 2000).ravel() # ∇ log π(L)의 가중치; ×2000으로 세 방식을 같은 lr 눈금에
onehot = np.eye(16)[L_idx.ravel()]
gc = ((w * (r.ravel() > 0))[:, None] * (onehot - pc)).sum(0) / B
gw = ((w * (r.ravel() == 0))[:, None] * (onehot - pw)).sum(0) / B
zc += lr * gc; zw += lr * gw
return log
print("mean length (correct / wrong) at steps 0, 100, 200, 300 — accuracy fixed at p = 0.3")
for agg in ["seq-mean", "token-mean", "constant"]:
log = train(agg)
print(f" {agg:10s}", " ".join(f"{a:5.0f}/{b:5.0f}" for a, b in log))
# seq-mean gradient는 E[(r − b)/|y|]의 정확한 gradient: 오답이 보는 보상
p, b = 0.3, 0.3
print("\neffective reward (r − b)/|y| for a wrong answer:",
", ".join(f"L={L:.0f}: {(0 - b) / L * 1000:+.3f}e-3" for L in [500, 2000, 8000]))샘플링 실행이 그림과 맞는다. sequence-mean에서 300 step 동안 오답은 2,400에서 약 2,850토큰으로 자라고 정답은 약 1,700으로 준다. 상수 정규화는 둘 다 2,400에 둔다. token-mean은 약 80토큰 움직인다. 마지막 줄이 숫자 세 개로 된 요약이다. 8,000토큰 오답은 500토큰 오답보다 16배 덜 벌을 받는다.
Ratio의 단위
Sequence-mean은 토큰을 어떻게 더하느냐의 문제였다. Ratio 문제는 무엇을 trust region과 비교하느냐다. GRPO와 DAPO는 토큰마다 ratio 하나를 쓴다. 세 대안이 시퀀스 쪽으로 움직인다.
GSPO(Zheng et al. 2025)는 길이 정규화된 시퀀스 ratio를 clip한다.
이므로 band 안에서 토큰당 가중치는
이 한 줄에서 두 사실이 보인다. 응답의 모든 토큰이 같은 가중치를 받는다(토큰 단위 잡음이 gradient에 곱해지지 않는다). 그리고 GSPO는 sequence-mean 집계를 물려받는다. , 따라서 앞 절의 보상이 기하평균의 미분을 통해 돌아온다. 논문의 clip 범위는 / 로 GRPO보다 세 자릿수 좁고, GRPO보다 두 자릿수 많은 토큰을 clip하면서도 더 효율적으로 학습했다고 보고한다. 멀티턴용 GSPO-token은 로, 값은 와 같지만 토큰별 advantage 를 허용한다.
GMPO(Zhao et al. 2025)는 토큰 단위 clip을 유지하되 토큰에 대한 GRPO의 산술평균을 기하평균으로 바꾼다.
clip 범위는 log 공간에서 다. 곱의 를 미분하면 clip되지 않은 토큰은 를 받고(는 clip된 ratio들의 기하평균) clip된 토큰은 0을 받는다. GRPO의 토큰 단위 clip 판정을 단 GSPO의 가중치다. 이상치 토큰은 응답 전체를 데려가지 않고 혼자 꺼지며, 를 제한된 만큼만 움직일 수 있다.
SAPO(Gao et al. 2025)는 딱딱한 경계를 아예 없앤다. 토큰마다 가중치에 부드러운 gate를 곱한다.
에서 1이고 부드럽게 줄어든다. 온도는 advantage 부호에 따라 다르고(논문의 통제 실험에서 , ), 음의 advantage 토큰이 더 빨리 흐려진다. 논문은 가 가장 안정적이었다고 보고하며, 음의 토큰 gradient가 관련 없는 많은 어휘 항목으로 퍼지기 때문이라고 설명한다. 논문의 가정 아래 토큰 gate의 평균은 시퀀스 gate 로 모인다. 이상치 토큰 하나를 여전히 낮출 수 있는 부드러운 GSPO다.
그림으로: 토큰 ratio 대 시퀀스 ratio
기하평균이 왜 토큰보다 나은 단위일까? 토큰의 log-ratio를 세 부분으로 나눠 보자. 체계적 부분(업데이트가 의도한 움직임, 와 같은 부호), 토큰 단위 잡음(위치마다 샘플 하나; MoE라면 작은 routing 흔들림도), 드문 큰 도약(expert가 바뀐 토큰; GSPO 논문은 48층 MoE에서 gradient 업데이트 한 번 뒤 활성 expert의 약 10%가 바뀐다고 보고한다)이다.
- At T = 1000 the token histogram is dominated by noise: the DAPO clip fires on a few percent of tokens of both signs, and the flips sit in the tails. That fraction does not change when you drag T.
- The sequence histogram is a different object. Its width is about (the flips are averaged down the same way), and its centre is the systematic drift . Drag T to 4,000: the two signs separate into two peaks, and the clip decision follows what the update did to the response as a whole rather than which tokens happened to sample noisily.
- Now look at the width of GSPO’s band. At – it is narrower than for any realistic noise and length, so a large share of responses of both signs is clipped. That matches the paper’s report that GSPO clips about two orders of magnitude more tokens than GRPO; the design accepts many clips in exchange for a decision that is coherent per response.
- Drag T down to 10: the sequence ratio is as noisy as a handful of tokens and the decision becomes a coin flip. The method is designed for long responses.
This is how to read GSPO’s MoE claim: a routing flip that moves one token’s log-ratio by 1.5 moves by — at that is , still wider than the band. GSPO does not make MoE noise disappear; it makes the decision depend on the sum of every token’s movement, where flips in both directions partly cancel, instead of letting each flipped token be clipped (or not) on its own. It does not mean that is a better importance weight. It is not one. The block below measures this.
from math import comb
K = 4 # vocabulary; token 0 is the "good" token
th_old = np.array([0.0, 0.3, -0.2, 0.1])
delta = np.array([0.15, -0.05, 0.0, -0.1]) # the update that was made after sampling
pi_old, pi_new = softmax(th_old), softmax(th_old + delta)
def reward(n0, T):
"""smooth non-additive reward: did the response use the good token more than π_θ would on average?"""
q = pi_new[0]
return 1 / (1 + np.exp(-2 * (n0 - T * q) / np.sqrt(T * q * (1 - q))))
def true_grad(T):
"""∇_θ E_{π_θ}[r(n0)] for tokens iid ~ π_θ (shared logits), exact via binomial sums."""
q = pi_new[0]
j = np.arange(T) # count among the other T−1 tokens
pmf = np.array([comb(T - 1, int(i)) for i in j], float) * q**j * (1 - q)**(T - 1 - j)
cond = np.array([pmf @ reward(j + (k == 0), T) for k in range(K)]) # E[r | y_1 = k]
J = pi_new @ cond
return T * pi_new * (cond - J) # T × Σ_k π_k (e_k − π) E[r | y_1=k]
def estimates(T, B=256, reps=80):
out = {k: [] for k in ["no correction", "token ρ_t", "GSPO s_i", "sequence Πρ_t"]}
for _ in range(reps):
y = rng.choice(K, size=(B, T), p=pi_old).astype(np.intp) # sampled from π_old
r = reward((y == 0).sum(1), T)
lr = np.log(pi_new[y] / pi_old[y]) # token log-ratios
score = np.eye(K)[y] - pi_new # ∇_θ log π_θ(y_t), (B, T, K)
adv = r[:, None]
out["no correction"].append((adv * score.sum(1)).mean(0))
out["token ρ_t"].append((adv[:, :, None] * np.exp(lr)[:, :, None] * score).sum(1).mean(0))
out["GSPO s_i"].append((adv * np.exp(lr.mean(1))[:, None] * score.sum(1)).mean(0))
out["sequence Πρ_t"].append((adv * np.exp(lr.sum(1))[:, None] * score.sum(1)).mean(0))
return {k: np.array(v) for k, v in out.items()}
print(f"per-token KL(π_new‖π_old) = {np.sum(pi_new * np.log(pi_new / pi_old)):.4f}")
print(" T estimator rel.bias rel.std (relative to ‖true gradient‖)")
for T in [8, 32, 128]:
g = true_grad(T)
for k, v in estimates(T).items():
bias = np.linalg.norm(v.mean(0) - g) / np.linalg.norm(g)
sd = np.sqrt(((v - v.mean(0)) ** 2).sum(1).mean()) / np.linalg.norm(g)
print(f" {T:4d} {k:15s} {bias:8.3f} {sd:8.3f}")The setup: tokens are sampled from , the policy has since moved by a small per-token KL of 0.0045, and the reward depends on all tokens jointly (a smooth “used the good token more than average” score). The exact gradient at is computed with binomial sums. Read the columns:
- Sequence product is the only unbiased correction, and its spread grows with T (relative std 0.25 → 0.58 here; at realistic lengths and mismatch it is unusable, as the mismatch lesson showed).
- Token ratio is biased, because it corrects only token ‘s own distribution while the reward also depends on the other tokens, whose shift it ignores; the bias grows with T (0.02 → 0.21), but its variance stays flat.
- GSPO’s is almost exactly as biased as no correction at all. With a per-token drift this small, . GSPO does not correct the off-policy gradient; it refuses to use responses whose drift is beyond a tiny band, and stays close enough to on-policy that no correction is needed. That is why its must be tiny, and why it pairs naturally with few minibatch updates per rollout.
Zero-variance groups: what is left of the batch
Aggregation decides how tokens are weighed; the batch decides which tokens exist. With binary rewards, a group with pass rate carries no signal with probability (derivation). Three consequences are less obvious than the formula.
Dynamic sampling changes the objective. Dropping zero-variance groups and resampling (DAPO) keeps the batch full, but the prompts that survive are weighted by . The surviving distribution of pass rates is tilted toward ; with a hard dataset the effective mean pass rate rises noticeably. This is usually what you want (those are the learnable prompts), but it is a re-weighting, and it compounds with GRPO’s .
The alternative to resampling is rescaling. GPG keeps the batch as it is and multiplies the gradient by , where counts samples in zero-advantage groups, so that dead groups do not shrink the step. Olmo 3’s active sampling keeps pulling finished groups from an asynchronous queue until enough non-zero groups are collected, so it never pays the synchronous over-sampling cost.
The group size can adapt per prompt. MAI draws 16 samples first and extends to 128 only if the observed pass rate is in ; GLM-4.5’s hard stage uses prompts with pass@8 = 0 but pass@512 > 0 and 512 samples per prompt. Large is the only way to get signal from a prompt with ( at , at ).
p_data = rng.beta(0.6, 1.2, 200_000) # per-prompt pass rates: many hard prompts
def informative(p, G): return 1 - p**G - (1 - p)**G
for G in [4, 8, 16, 32]:
f = informative(p_data, G).mean()
print(f"G={G:2d}: informative groups {f:5.1%}, rollouts per informative group {G / f:6.1f}")
# dynamic sampling re-weights prompts by P(informative | p): the objective tilts towards p ≈ 1/2
w = informative(p_data, 8)
print(f"mean pass rate of prompts: all {p_data.mean():.3f}, as seen after dynamic sampling (G=8) {np.average(p_data, weights=w):.3f}")
# two-stage group size: draw 16, extend to 128 only if 0.05 ≤ pass rate ≤ 0.8
k16 = rng.binomial(16, p_data) / 16
extend = (k16 >= 0.05) & (k16 <= 0.8)
cost = 16 + 112 * extend
k128 = np.where(extend, rng.binomial(128, p_data) / 128, k16)
inf = (k128 > 0) & (k128 < 1)
print(f"two-stage 16→128: {extend.mean():.1%} of prompts extended, mean rollouts {cost.mean():.1f}, "
f"informative {inf.mean():.1%}, rollouts per informative prompt {cost.sum() / inf.sum():.1f}")
f128 = informative(p_data, 128).mean()
print(f"always 128: informative {f128:.1%}, rollouts per informative prompt {128 / f128:.1f}")With a dataset skewed toward hard prompts (Beta(0.6, 1.2), mean pass rate 0.33), only 68% of groups carry signal, and dynamic sampling quietly shifts the training distribution’s mean pass rate from 0.33 to about 0.40. The two-stage scheme spends about 95 rollouts per prompt and 120 per informative prompt, against 136 for always drawing 128. The saving comes from the prompts it recognises early as solved or hopeless (the exact numbers depend on the difficulty distribution, so treat them as an illustration).
A last, purely computational note on groups: all responses share the same prompt. Prefix Grouper (Liu et al. 2025) splits self-attention into a shared-prefix part and a per-response part so the prompt is encoded once rather than times; outputs and gradients are identical to standard GRPO, so it changes cost, not the algorithm. With long agentic prompts and the saving is large.
Implementing the sequence-level objectives
import torch
def _masked_seq_mean(x, m): # (B,T) → (B,)
return (x * m).sum(1) / m.sum(1).clamp(min=1)
def gspo_loss(logp, old_logp, adv, mask, eps_low=3e-4, eps_high=4e-4):
"""adv: (B,) sequence advantage. Ratio and clip at the sequence level (Zheng et al. 2025)."""
m = mask.float()
s = torch.exp(_masked_seq_mean(logp - old_logp, m)) # (B,) geometric-mean ratio
surr = torch.minimum(s * adv, s.clamp(1 - eps_low, 1 + eps_high) * adv)
return -surr.mean() # 1/G Σ_i; ∇s carries 1/|y_i|
def gspo_token_loss(logp, old_logp, adv_tok, mask, eps_low=3e-4, eps_high=4e-4):
"""GSPO-token: value of s_{i,t} equals s_i, gradient flows per token; adv_tok: (B,T)."""
m = mask.float()
s = torch.exp(_masked_seq_mean(logp - old_logp, m)).detach()[:, None]
s_tok = s * torch.exp(logp - logp.detach()) # sg[s_i] · π_θ / sg[π_θ]
surr = torch.minimum(s_tok * adv_tok, s_tok.clamp(1 - eps_low, 1 + eps_high) * adv_tok)
return -_masked_seq_mean(surr, m).mean()
def gmpo_loss(logp, old_logp, adv, mask, clip_log=0.4):
"""Geometric mean of token-clipped |ρ·A|, computed in log space (Zhao et al. 2025)."""
m = mask.float()
log_r = logp - old_logp
a = adv[:, None]
# PPO-style pessimism per token in log space: for A>0 cap log ρ above, for A<0 cap it below
log_r_c = torch.where(a > 0, torch.minimum(log_r, log_r.clamp(-clip_log, clip_log)),
torch.maximum(log_r, log_r.clamp(-clip_log, clip_log)))
log_geo = _masked_seq_mean(log_r_c, m) # log of (Π ρ̃_t)^{1/|y|}
return -(torch.sign(adv) * adv.abs() * torch.exp(log_geo)).mean()
def sapo_loss(logp, old_logp, adv, mask, tau_pos=1.0, tau_neg=1.05):
"""Soft gate f(r) = (4/τ)·σ(τ(r−1)); its derivative gives the weight r·4p(1−p) (Gao et al. 2025)."""
m = mask.float()
r = torch.exp(logp - old_logp)
tau = torch.where(adv[:, None] > 0, torch.full_like(r, tau_pos), torch.full_like(r, tau_neg))
f = 4.0 / tau * torch.sigmoid(tau * (r - 1.0))
return -_masked_seq_mean(f * adv[:, None], m).mean()In gmpo_loss, the torch.where reproduces the inside the absolute value: for the effective ratio is , for it is , so the gradient vanishes exactly on the clipped tokens. In sapo_loss, differentiating with respect to gives , the gate in the equation above.
You switch a GRPO run with sequence-mean aggregation to GSPO. Which statement about length bias is right?
Differentiating gives every token the weight — exactly sequence-mean aggregation with replaced by . So the expected update is still the gradient of near on-policy. To remove it you would have to change the outer to a token-count normaliser, which is no longer GSPO as published.
In the NumPy experiment, why is GSPO's s_i about as biased as no correction at all?
The exact correction for a whole sequence is . Its -th root shrinks every deviation by in log space, so with a per-token KL of 0.0045 it is within a fraction of a percent of 1 and leaves the off-policy gradient almost unchanged. GSPO’s design does not need it to correct anything: it uses as a low-noise measure of how far a response has moved and simply refuses (clips) responses beyond a -wide band.
Summary
- Each aggregation mode optimises its own objective. Sequence-mean is the exact gradient of : short when right, long when wrong. Constant normalisation is unbiased but its step grows with length; token-mean is nearly unbiased with a length-adaptive step and a weak residual bias through its denominator.
- “Token-mean” must use one global denominator per optimiser step; per-device or per-micro-batch normalisation reintroduces a mean-of-means bias.
- GSPO’s per-token weight is : uniform within a response, and carrying sequence-mean’s . GMPO keeps GSPO’s geometric-mean weight with a token-level clip; SAPO replaces the hard clip with a sign-dependent smooth gate that concentrates to a soft sequence gate.
- A sequence ratio averages token noise and routing flips away (), so GSPO’s clip tests the systematic drift. It is not an importance weight: only is unbiased (with exploding variance), token ratios are biased with flat variance, and barely corrects at all.
- Zero-variance groups shrink the batch; dynamic sampling refills it but tilts the objective toward ; GPG rescales instead; adaptive group sizes buy signal on rare-success prompts. Prefix Grouper changes only the cost of the group’s shared prompt.
- T = 1000에서 토큰 히스토그램은 잡음이 지배한다. DAPO clip은 두 부호 모두 토큰의 몇 %에 작동하고, 뒤집힘은 꼬리에 있다. T를 끌어도 그 비율은 바뀌지 않는다.
- 시퀀스 히스토그램은 다른 대상이다. 폭이 대략 이고(뒤집힘도 같은 식으로 평균된다), 중심은 체계적 이동 다. T를 4,000으로 끌면 두 부호가 두 봉우리로 갈라지고, clip 판정은 어떤 토큰이 우연히 시끄럽게 샘플되었는지가 아니라 업데이트가 응답 전체에 한 일을 따른다.
- 이제 GSPO band의 폭을 보라. –이면 현실적인 잡음과 길이에서 보다 좁아서, 두 부호의 응답 상당 부분이 clip된다. GSPO가 GRPO보다 약 두 자릿수 많은 토큰을 clip한다는 논문의 보고와 맞는다. 이 설계는 많은 clip을 받아들이는 대신 응답 단위로 일관된 판정을 얻는다.
- T를 10까지 내려라. 시퀀스 ratio가 토큰 몇 개만큼 시끄러워지고 판정이 동전 던지기가 된다. 이 방법은 긴 응답을 위한 설계다.
이것이 GSPO의 MoE 주장을 읽는 방법이다. 토큰 하나의 log-ratio를 1.5 움직이는 routing 뒤집힘은 를 만큼 움직인다. 이면 로 여전히 band보다 넓다. GSPO가 MoE 잡음을 없애지는 않는다. 뒤집힌 토큰을 하나씩 clip할지 말지 정하는 대신, 양방향 뒤집힘이 일부 상쇄되는 모든 토큰 이동의 합으로 판정하게 만든다. 그렇다고 가 더 나은 importance weight라는 뜻은 아니다. 애초에 importance weight가 아니다. 아래 블록이 이것을 잰다.
from math import comb
K = 4 # 어휘; 토큰 0이 "좋은" 토큰
th_old = np.array([0.0, 0.3, -0.2, 0.1])
delta = np.array([0.15, -0.05, 0.0, -0.1]) # 샘플링 뒤에 일어난 업데이트
pi_old, pi_new = softmax(th_old), softmax(th_old + delta)
def reward(n0, T):
"""부드럽고 가법적이지 않은 보상: π_θ의 평균보다 좋은 토큰을 더 썼나?"""
q = pi_new[0]
return 1 / (1 + np.exp(-2 * (n0 - T * q) / np.sqrt(T * q * (1 - q))))
def true_grad(T):
"""토큰 iid ~ π_θ(공유 logit)일 때 ∇_θ E_{π_θ}[r(n0)], 이항 합으로 정확히."""
q = pi_new[0]
j = np.arange(T) # 나머지 T−1개 중 토큰 0의 개수
pmf = np.array([comb(T - 1, int(i)) for i in j], float) * q**j * (1 - q)**(T - 1 - j)
cond = np.array([pmf @ reward(j + (k == 0), T) for k in range(K)]) # E[r | y_1 = k]
J = pi_new @ cond
return T * pi_new * (cond - J) # T × Σ_k π_k (e_k − π) E[r | y_1=k]
def estimates(T, B=256, reps=80):
out = {k: [] for k in ["no correction", "token ρ_t", "GSPO s_i", "sequence Πρ_t"]}
for _ in range(reps):
y = rng.choice(K, size=(B, T), p=pi_old).astype(np.intp) # π_old에서 샘플
r = reward((y == 0).sum(1), T)
lr = np.log(pi_new[y] / pi_old[y]) # 토큰 log-ratio
score = np.eye(K)[y] - pi_new # ∇_θ log π_θ(y_t), (B, T, K)
adv = r[:, None]
out["no correction"].append((adv * score.sum(1)).mean(0))
out["token ρ_t"].append((adv[:, :, None] * np.exp(lr)[:, :, None] * score).sum(1).mean(0))
out["GSPO s_i"].append((adv * np.exp(lr.mean(1))[:, None] * score.sum(1)).mean(0))
out["sequence Πρ_t"].append((adv * np.exp(lr.sum(1))[:, None] * score.sum(1)).mean(0))
return {k: np.array(v) for k, v in out.items()}
print(f"per-token KL(π_new‖π_old) = {np.sum(pi_new * np.log(pi_new / pi_old)):.4f}")
print(" T estimator rel.bias rel.std (relative to ‖true gradient‖)")
for T in [8, 32, 128]:
g = true_grad(T)
for k, v in estimates(T).items():
bias = np.linalg.norm(v.mean(0) - g) / np.linalg.norm(g)
sd = np.sqrt(((v - v.mean(0)) ** 2).sum(1).mean()) / np.linalg.norm(g)
print(f" {T:4d} {k:15s} {bias:8.3f} {sd:8.3f}")설정: 토큰은 에서 뽑았고, 정책은 그 뒤 토큰당 KL 0.0045만큼 움직였으며, 보상은 모든 토큰에 함께 의존한다(“평균보다 좋은 토큰을 더 썼나”라는 부드러운 점수). 에서의 정확한 gradient는 이항 합으로 계산한다. 열을 읽자.
- 시퀀스 곱 만이 편향 없는 보정이고, 퍼짐이 T와 함께 커진다(여기서 상대 std 0.25 → 0.58. 현실적인 길이와 불일치에서는 쓸 수 없다는 것을 불일치 레슨이 보였다).
- 토큰 ratio 는 편향이 있다. 토큰 자신의 분포만 보정하는데 보상은 나머지 개 토큰에도 의존하고 그 이동은 무시하기 때문이다. 편향은 T와 함께 자라지만(0.02 → 0.21) 분산은 평평하다.
- **GSPO의 **는 보정을 전혀 안 한 것과 거의 똑같이 편향되어 있다. 토큰당 이동이 이만큼 작으면 이다. GSPO는 off-policy gradient를 보정하지 않는다. 이동이 아주 좁은 band를 넘은 응답을 쓰기를 거부하고, 보정이 필요 없을 만큼 on-policy 가까이에 머문다. 그래서 이 아주 작아야 하고, rollout당 minibatch 업데이트가 적은 설정과 자연스럽게 어울린다.
신호 없는 그룹: 배치에 무엇이 남나
집계는 토큰의 무게를 정하고, 배치는 어떤 토큰이 존재하는지를 정한다. 이진 보상에서 통과율 인 그룹은 확률 로 신호가 없다(유도). 식보다 덜 뻔한 결과가 셋 있다.
Dynamic sampling은 목적함수를 바꾼다. 신호 없는 그룹을 버리고 다시 샘플하면(DAPO) 배치는 꽉 차지만, 살아남은 프롬프트는 로 가중된다. 살아남은 통과율 분포는 쪽으로 기울고, 어려운 데이터셋이면 실효 평균 통과율이 눈에 띄게 오른다. 대개 원하는 것이지만(배울 수 있는 프롬프트들이다) 재가중이고, GRPO의 와 겹친다.
다시 샘플하는 대신 크기를 맞출 수도 있다. GPG는 배치를 그대로 두고 gradient에 을 곱한다(은 advantage 0 그룹의 샘플 수). 죽은 그룹이 step을 줄이지 못하게 한다. Olmo 3의 active sampling은 0이 아닌 그룹이 충분히 모일 때까지 비동기 큐에서 끝난 그룹을 계속 꺼내므로, 동기식 과샘플링 비용을 치르지 않는다.
그룹 크기는 프롬프트마다 적응할 수 있다. MAI는 먼저 16개를 뽑고 관찰한 통과율이 일 때만 128개로 늘린다. GLM-4.5의 어려운 단계는 pass@8 = 0이지만 pass@512 > 0인 프롬프트에 프롬프트당 512개 샘플을 쓴다. 인 프롬프트에서 신호를 얻는 방법은 큰 뿐이다(에서 , 에서 ).
p_data = rng.beta(0.6, 1.2, 200_000) # 프롬프트별 통과율: 어려운 프롬프트가 많다
def informative(p, G): return 1 - p**G - (1 - p)**G
for G in [4, 8, 16, 32]:
f = informative(p_data, G).mean()
print(f"G={G:2d}: informative groups {f:5.1%}, rollouts per informative group {G / f:6.1f}")
# dynamic sampling은 P(informative | p)로 프롬프트를 재가중: 목적함수가 p ≈ 1/2 쪽으로 기운다
w = informative(p_data, 8)
print(f"mean pass rate of prompts: all {p_data.mean():.3f}, as seen after dynamic sampling (G=8) {np.average(p_data, weights=w):.3f}")
# 2단계 그룹 크기: 16개를 뽑고, 0.05 ≤ 통과율 ≤ 0.8일 때만 128로 확장
k16 = rng.binomial(16, p_data) / 16
extend = (k16 >= 0.05) & (k16 <= 0.8)
cost = 16 + 112 * extend
k128 = np.where(extend, rng.binomial(128, p_data) / 128, k16)
inf = (k128 > 0) & (k128 < 1)
print(f"two-stage 16→128: {extend.mean():.1%} of prompts extended, mean rollouts {cost.mean():.1f}, "
f"informative {inf.mean():.1%}, rollouts per informative prompt {cost.sum() / inf.sum():.1f}")
f128 = informative(p_data, 128).mean()
print(f"always 128: informative {f128:.1%}, rollouts per informative prompt {128 / f128:.1f}")어려운 프롬프트 쪽으로 치우친 데이터셋(Beta(0.6, 1.2), 평균 통과율 0.33)에서 그룹의 68%만 신호를 싣고, dynamic sampling은 학습 분포의 평균 통과율을 0.33에서 약 0.40으로 조용히 옮긴다. 2단계 방식은 프롬프트당 약 95번, 신호 있는 프롬프트당 120번의 rollout을 쓴다. 늘 128개를 뽑으면 136번이다. 절약은 이미 풀었거나 가망 없다고 일찍 알아본 프롬프트에서 나온다(정확한 숫자는 난이도 분포에 달렸으니 예시로 읽어라).
그룹에 관한 마지막, 순수하게 계산적인 메모. 개 응답은 모두 같은 프롬프트를 공유한다. Prefix Grouper(Liu et al. 2025)는 self-attention을 공유 prefix 부분과 응답별 부분으로 나눠 프롬프트를 번이 아니라 한 번만 encode한다. 출력과 gradient가 표준 GRPO와 같으므로 알고리즘이 아니라 비용을 바꾼다. 긴 agentic 프롬프트와 이면 절약이 크다.
시퀀스 단위 목적함수 구현
import torch
def _masked_seq_mean(x, m): # (B,T) → (B,)
return (x * m).sum(1) / m.sum(1).clamp(min=1)
def gspo_loss(logp, old_logp, adv, mask, eps_low=3e-4, eps_high=4e-4):
"""adv: (B,) 시퀀스 advantage. ratio와 clip을 시퀀스 단위로 (Zheng et al. 2025)."""
m = mask.float()
s = torch.exp(_masked_seq_mean(logp - old_logp, m)) # (B,) 기하평균 ratio
surr = torch.minimum(s * adv, s.clamp(1 - eps_low, 1 + eps_high) * adv)
return -surr.mean() # 1/G Σ_i; ∇s가 1/|y_i|를 실어 옴
def gspo_token_loss(logp, old_logp, adv_tok, mask, eps_low=3e-4, eps_high=4e-4):
"""GSPO-token: s_{i,t}의 값은 s_i와 같고 gradient는 토큰별로 흐른다; adv_tok: (B,T)."""
m = mask.float()
s = torch.exp(_masked_seq_mean(logp - old_logp, m)).detach()[:, None]
s_tok = s * torch.exp(logp - logp.detach()) # sg[s_i] · π_θ / sg[π_θ]
surr = torch.minimum(s_tok * adv_tok, s_tok.clamp(1 - eps_low, 1 + eps_high) * adv_tok)
return -_masked_seq_mean(surr, m).mean()
def gmpo_loss(logp, old_logp, adv, mask, clip_log=0.4):
"""토큰별로 clip한 |ρ·A|의 기하평균을 log 공간에서 계산 (Zhao et al. 2025)."""
m = mask.float()
log_r = logp - old_logp
a = adv[:, None]
# log 공간에서 토큰별 PPO식 비관: A>0이면 log ρ 위를, A<0이면 아래를 막음
log_r_c = torch.where(a > 0, torch.minimum(log_r, log_r.clamp(-clip_log, clip_log)),
torch.maximum(log_r, log_r.clamp(-clip_log, clip_log)))
log_geo = _masked_seq_mean(log_r_c, m) # (Π ρ̃_t)^{1/|y|}의 log
return -(torch.sign(adv) * adv.abs() * torch.exp(log_geo)).mean()
def sapo_loss(logp, old_logp, adv, mask, tau_pos=1.0, tau_neg=1.05):
"""부드러운 gate f(r) = (4/τ)·σ(τ(r−1)); 미분하면 가중치 r·4p(1−p) (Gao et al. 2025)."""
m = mask.float()
r = torch.exp(logp - old_logp)
tau = torch.where(adv[:, None] > 0, torch.full_like(r, tau_pos), torch.full_like(r, tau_neg))
f = 4.0 / tau * torch.sigmoid(tau * (r - 1.0))
return -_masked_seq_mean(f * adv[:, None], m).mean()gmpo_loss의 torch.where는 절댓값 안의 를 재현한다. 이면 실효 ratio가 , 이면 라서 clip된 토큰에서 정확히 gradient가 사라진다. sapo_loss에서 을 로 미분하면 , 위 식의 gate가 나온다.
sequence-mean 집계를 쓰던 GRPO 실험을 GSPO로 바꿨다. 길이 편향에 관해 맞는 말은?
를 미분하면 모든 토큰이 가중치 를 받는다. 를 로 바꾼 sequence-mean 집계 그대로다. 그래서 on-policy 근처에서 기대 업데이트는 여전히 의 gradient다. 없애려면 바깥의 를 토큰 수 정규화로 바꿔야 하고, 그것은 더 이상 발표된 GSPO가 아니다.
NumPy 실험에서 GSPO의 s_i가 보정을 안 한 것만큼 편향된 이유는?
시퀀스 전체의 정확한 보정은 다. 그 제곱근 는 log 공간에서 모든 편차를 로 줄이므로, 토큰당 KL 0.0045에서는 1과 1% 미만 차이이고 off-policy gradient를 거의 바꾸지 않는다. GSPO의 설계는 그것이 무언가를 보정할 필요가 없다. 를 응답이 얼마나 움직였는지에 대한 잡음 적은 척도로 쓰고, 폭 band를 넘은 응답을 그냥 거부(clip)한다.
정리
- 집계 방식마다 최적화하는 목적함수가 다르다. Sequence-mean은 의 정확한 gradient다. 맞으면 짧게, 틀리면 길게. 상수 정규화는 편향이 없지만 step이 길이와 함께 커진다. Token-mean은 거의 편향이 없고 step이 길이에 적응하며, 분모를 통한 약한 잔여 편향이 있다.
- “Token-mean”은 optimizer step마다 전역 분모 하나를 써야 한다. 장치별이나 micro-batch별 정규화는 평균의 평균 편향을 되살린다.
- GSPO의 토큰당 가중치는 다. 응답 안에서 균일하고, sequence-mean의 를 싣고 있다. GMPO는 GSPO의 기하평균 가중치에 토큰 단위 clip을 단다. SAPO는 hard clip을 부호에 따라 다른 부드러운 gate로 바꾸고, 그 gate는 부드러운 시퀀스 gate로 모인다.
- 시퀀스 ratio는 토큰 잡음과 routing 뒤집힘을 평균으로 걷어 내므로() GSPO의 clip은 체계적 이동을 검정한다. importance weight는 아니다. 만 편향이 없고(분산 폭발), 토큰 ratio는 편향이 있되 분산이 평평하며, 는 거의 보정하지 않는다.
- 신호 없는 그룹은 배치를 줄인다. Dynamic sampling은 다시 채우지만 목적함수를 쪽으로 기울이고, GPG는 대신 크기를 맞추며, 적응형 그룹 크기는 성공이 드문 프롬프트에서 신호를 산다. Prefix Grouper는 그룹이 공유하는 프롬프트의 비용만 바꾼다.
더 읽을거리Further reading
- Liu et al., Understanding R1-Zero-Like Training: A Critical Perspective (2025) — Dr. GRPO. 응답 길이 정규화가 긴 오답을 부풀린다는 지적과 상수 정규화.Dr. GRPO. Shows that per-response length normalisation inflates wrong answers, and replaces it with a constant.
- Yu et al., DAPO: An Open-Source LLM Reinforcement Learning System at Scale (2025) — token-level 손실, dynamic sampling.Token-level loss and dynamic sampling.
- Zheng et al., Group Sequence Policy Optimization (2025) — 길이 정규화된 시퀀스 ratio, GSPO-token, MoE에서 routing replay 없이 안정.Length-normalised sequence ratio, GSPO-token, stability on MoE without routing replay.
- Zhao et al., Geometric-Mean Policy Optimization (2025) — 토큰별로 clip한 항의 기하평균을 최대화한다.Maximises the geometric mean of token-clipped terms.
- Gao et al., Soft Adaptive Policy Optimization (2025) — hard clip 대신 온도로 조절하는 sigmoid gate. 음의 advantage에 더 높은 온도.A temperature-controlled sigmoid gate instead of a hard clip, with a higher temperature for negative advantages.
- Chu et al., GPG: A Simple and Strong Reinforcement Learning Baseline for Model Reasoning (2025) — 신호 없는 그룹에 의한 희석을 B/(B−M)로 되돌리는 재조정.Undoes the dilution by zero-advantage groups with a B/(B−M) rescale.
- Liu et al., Prefix Grouper: Efficient GRPO Training through Shared-Prefix Forward (2025) — 그룹이 공유하는 프롬프트를 한 번만 encode하고 같은 gradient를 낸다.Encodes a group's shared prompt once while producing identical gradients.
- verl documentation — loss_agg_mode — token-mean, seq-mean-token-mean, seq-mean-token-sum, seq-mean-token-sum-norm 구현.Implementations of token-mean, seq-mean-token-mean, seq-mean-token-sum and seq-mean-token-sum-norm.