Track IX · Frontier RL: Algorithms & Stability · 02/10

시퀀스냐 토큰이냐 — 집계, 정규화, ratio 단위Sequence vs token — aggregation, normalisation and the unit of the ratio

손실 집계 방식이 실제로 최적화하는 목적함수를 유도하고(sequence-mean은 (r−b)/|y|를 최적화한다), GSPO·GMPO·SAPO가 ratio의 단위를 어떻게 바꾸는지, 토큰 ratio와 시퀀스 ratio의 bias·variance를 NumPy로 잰다. 신호 없는 그룹, dynamic sampling, 적응형 그룹 크기의 비용도 계산한다.Derive the objective each loss-aggregation mode actually optimises (sequence-mean optimises (r−b)/|y|), see how GSPO, GMPO and SAPO change the unit of the ratio, and measure the bias and variance of token versus sequence ratios in NumPy. Then compute the cost of zero-variance groups, dynamic sampling and adaptive group sizes.

The landscape lesson wrote every objective as a per-token weight wi,t=ci h(Ri,t,A^i) ui,t A^iw_{i,t} = c_i\,h(R_{i,t},\hat A_i)\,u_{i,t}\,\hat A_i. This lesson takes apart the two coordinates that decide at which unit the algorithm thinks: the aggregation cic_i, which sets how much a token weighs given the length of its response, and the unit of the ratio RR — 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 ℓi,t\ell_{i,t} for GG responses, frameworks offer four ways to reduce them to a scalar (verl calls the option loss_agg_mode):

ModeFormulaPer-token weight cic_iUsed by
seq-mean-token-mean1G∑i1∣yi∣∑tℓi,t\frac1G\sum_i \frac{1}{\lvert y_i\rvert}\sum_t \ell_{i,t}1G∣yi∣\frac{1}{G\lvert y_i\rvert}original GRPO, DeepSeek-V3.2, GLM-5 reasoning
token-mean1∑i∣yi∣∑i,tℓi,t\frac{1}{\sum_i\lvert y_i\rvert}\sum_{i,t}\ell_{i,t}1∑j∣yj∣\frac{1}{\sum_j\lvert y_j\rvert}DAPO, MiniMax, MiMo, MAI, Olmo 3, Kimi K2.5
seq-mean-token-sum1G∑i∑tℓi,t\frac1G\sum_i \sum_t \ell_{i,t}1G\frac1GREINFORCE on whole sequences, k1.5
seq-mean-token-sum-norm1GLmax⁡∑i,tℓi,t\frac{1}{G L_{\max}}\sum_{i,t}\ell_{i,t}1GLmax⁡\frac{1}{G L_{\max}}Dr. GRPO

What sequence-mean optimises

On-policy (ρ=1\rho=1, no clip), sequence-mean gives the gradient 1G∑iA^i∣yi∣∇log⁡πθ(yi)\frac1G\sum_i \frac{\hat A_i}{\lvert y_i\rvert}\nabla\log\pi_\theta(y_i), because the ∣yi∣\lvert y_i\rvert token gradients of a response sum to the gradient of its log-probability. With A^i=ri−b\hat A_i = r_i - b and bb held fixed (it is a statistic of the batch), its expectation is

Ey∼πθ[r(y)−b∣y∣ ∇log⁡πθ(y)]  =  ∇θ Ey∼πθ[r(y)−b∣y∣].\mathbb E_{y\sim\pi_\theta}\Big[\frac{r(y)-b}{\lvert y\rvert}\,\nabla\log\pi_\theta(y)\Big] \;=\; \nabla_\theta\,\mathbb E_{y\sim\pi_\theta}\Big[\frac{r(y)-b}{\lvert y\rvert}\Big].

So sequence-mean GRPO is an unbiased policy gradient for a different reward, r~(y)=(r(y)−b)/∣y∣\tilde r(y) = (r(y)-b)/\lvert y\rvert. For a correct answer (r=1>br=1>b) the reward is largest when the answer is short; for a wrong answer it is −b/∣y∣-b/\lvert y\rvert, 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: p⋅1−bL+(1−p)⋅−bL=0p\cdot\frac{1-b}{L} + (1-p)\cdot\frac{-b}{L} = 0 at b=pb=p. 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 r~\tilde r by σ\sigma changes per-prompt weights, not the length preference.

What the other modes optimise

Constant normalisation (Dr. GRPO) is the unbiased gradient of E[r]\mathbb E[r] up to the constant 1/(GLmax⁡)1/(GL_{\max}). Its catch is the step size: the signal part of ∑t∇ℓi,t\sum_t\nabla\ell_{i,t} 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 pp, so length never changes the reward. The update is the exact expected gradient of each aggregation mode.

지도 레슨은 모든 목적함수를 토큰당 가중치 wi,t=ci h(Ri,t,A^i) ui,t A^iw_{i,t} = c_i\,h(R_{i,t},\hat A_i)\,u_{i,t}\,\hat A_i로 썼다. 이 레슨은 알고리즘이 어떤 단위로 생각하는지를 정하는 두 좌표를 해부한다. 하나는 응답 길이에 따라 토큰 하나의 무게를 정하는 집계 cic_i, 다른 하나는 ratio RR의 단위 — 토큰, 시퀀스, 또는 그 사이 — 다. RLVR과 GRPO가 세 정규화와 길이 편향의 직관을 소개했다. 여기서는 각각이 무엇을 최적화하는지 유도하고, 시퀀스 단위 ratio가 왜 MoE 모델에서 인기를 얻었는지, 신호 없는 그룹을 걷어 내면 배치에 무엇이 남는지 본다.

집계: 네 방식, 네 목적함수

응답 GG개의 토큰별 손실 ℓi,t\ell_{i,t}를 스칼라 하나로 줄이는 방법으로 프레임워크는 네 가지를 제공한다(verl의 옵션 이름은 loss_agg_mode).

방식식토큰당 가중치 cic_i쓰는 곳
seq-mean-token-mean1G∑i1∣yi∣∑tℓi,t\frac1G\sum_i \frac{1}{\lvert y_i\rvert}\sum_t \ell_{i,t}1G∣yi∣\frac{1}{G\lvert y_i\rvert}원래 GRPO, DeepSeek-V3.2, GLM-5 추론 단계
token-mean1∑i∣yi∣∑i,tℓi,t\frac{1}{\sum_i\lvert y_i\rvert}\sum_{i,t}\ell_{i,t}1∑j∣yj∣\frac{1}{\sum_j\lvert y_j\rvert}DAPO, MiniMax, MiMo, MAI, Olmo 3, Kimi K2.5
seq-mean-token-sum1G∑i∑tℓi,t\frac1G\sum_i \sum_t \ell_{i,t}1G\frac1G시퀀스 전체 REINFORCE, k1.5
seq-mean-token-sum-norm1GLmax⁡∑i,tℓi,t\frac{1}{G L_{\max}}\sum_{i,t}\ell_{i,t}1GLmax⁡\frac{1}{G L_{\max}}Dr. GRPO

Sequence-mean이 최적화하는 것

On-policy(ρ=1\rho=1, clip 없음)에서 sequence-mean의 gradient는 1G∑iA^i∣yi∣∇log⁡πθ(yi)\frac1G\sum_i \frac{\hat A_i}{\lvert y_i\rvert}\nabla\log\pi_\theta(y_i)다. 응답의 토큰 gradient ∣yi∣\lvert y_i\rvert개를 더하면 그 응답 log-확률의 gradient이기 때문이다. A^i=ri−b\hat A_i = r_i - b이고 bb를 고정하면(배치의 통계량이다) 기댓값은

Ey∼πθ[r(y)−b∣y∣ ∇log⁡πθ(y)]  =  ∇θ Ey∼πθ[r(y)−b∣y∣].\mathbb E_{y\sim\pi_\theta}\Big[\frac{r(y)-b}{\lvert y\rvert}\,\nabla\log\pi_\theta(y)\Big] \;=\; \nabla_\theta\,\mathbb E_{y\sim\pi_\theta}\Big[\frac{r(y)-b}{\lvert y\rvert}\Big].

즉 sequence-mean GRPO는 다른 보상 r~(y)=(r(y)−b)/∣y∣\tilde r(y) = (r(y)-b)/\lvert y\rvert에 대한 편향 없는 policy gradient다. 정답(r=1>br=1>b)이면 짧을수록 보상이 크다. 오답이면 보상이 −b/∣y∣-b/\lvert y\rvert이고 길수록 0에 가까워진다. 정책은 맞을 때 간결하고 틀릴 때 장황하도록 보상받는다. Dr. GRPO의 길이 편향을 정확한 명제로 쓴 것이다. 분산이나 clip이 만든 부작용이 아니다.

두 가지가 따라 나온다. 첫째, 이동이 생기려면 정책이 조절할 수 있는 길이와 정답 여부 사이의 상관이 필요하다. 시도의 성공과 무관하게 길이를 뽑는다면 두 힘은 기댓값에서 정확히 상쇄된다. b=pb=p에서 p⋅1−bL+(1−p)⋅−bL=0p\cdot\frac{1-b}{L} + (1-p)\cdot\frac{-b}{L} = 0. 추론 모델은 자기가 막혔다는 것을 안다. 그래서 실제로 편향이 나타난다. 둘째, GRPO의 std는 크기만 바꾼다. r~\tilde r을 σ\sigma로 나누면 프롬프트별 가중치가 바뀔 뿐 길이 선호는 그대로다.

다른 방식들이 최적화하는 것

상수 정규화(Dr. GRPO)는 상수 1/(GLmax⁡)1/(GL_{\max})을 빼면 E[r]\mathbb E[r]의 편향 없는 gradient다. 대가는 step 크기다. ∑t∇ℓi,t\sum_t\nabla\ell_{i,t}의 신호 부분은 응답 길이에 따라 커지므로, 응답이 2K에서 20K 토큰으로 길어지면 실효 학습률도 커진다. Token-mean은 배치에 실제로 나온 토큰 수로 나눈다. 분모의 무작위성을 빼면 역시 편향이 없고, step이 길이에 적응한다. 응답이 길어지면 토큰 하나의 무게가 비례해 줄어든다. 분모가 배치 안의 길이와 상관되어 있어서 긴 응답 하나가 자기를 포함한 모두의 무게를 조금 묽힌다. 약한 잔여 길이 선호이고, 그림에서 느린 이동으로 보인다. Sequence-sum(k1.5)은 편향이 없지만 step이 길이에 가장 크게 의존한다.

그림으로: 길이 이동

그림은 편향을 보일 수 있는 가장 작은 모델을 학습한다. 시도가 궤도에 올라 맞을 때는 한 분포에서, 막혔을 때는 다른 분포에서 응답 길이를 고르는 정책이다. 정답률은 pp로 고정이라 길이는 보상을 바꾸지 않는다. 업데이트는 각 집계 방식의 정확한 기대 gradient다.

정답 평균 길이mean length, correct – 오답 평균 길이mean length, wrong – 전체 토큰/응답tokens per response –
A toy policy that can make its length depend on whether it is on track: when the attempt will succeed it draws a length from the green distribution, when it is stuck from the red one. Accuracy is fixed at p, so length never changes the reward. With sequence-mean aggregation the gradient is exactly that of the reward (r − b)/|y|: correct answers are pushed short, wrong answers are pushed long, and tokens per response grow even though nothing was gained. Switch to token-mean or the constant normaliser and both distributions stay put. Lower p and the drift of wrong answers gets stronger (b = p sets the size of their penalty). Thin lines on the right are the other two aggregations. 궤도에 올랐는지에 따라 길이를 바꿀 수 있는 장난감 정책이다. 시도가 성공할 때는 초록 분포에서, 막혔을 때는 빨강 분포에서 길이를 뽑는다. 정답률은 p로 고정이라 길이는 보상을 바꾸지 않는다. sequence-mean 집계의 gradient는 정확히 보상 (r − b)/|y|의 gradient다. 정답은 짧은 쪽으로, 오답은 긴 쪽으로 밀리고, 얻은 것이 없는데도 응답당 토큰이 늘어난다. token-mean이나 상수 정규화로 바꾸면 두 분포가 그대로다. p를 낮추면 오답의 이동이 더 강해진다(b = p가 오답 벌의 크기). 오른쪽의 가는 선은 다른 두 집계다.
  1. 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.
  2. Switch to the constant normaliser: nothing moves. Token-mean drifts only slightly (the correlated denominator).
  3. Lower pp to 0.1: b=pb=p is small, so the wrong-answer reward −b/∣y∣-b/\lvert y\rvert is small at every length and the drift of wrong answers slows; the correct answers, with reward (1−b)/∣y∣(1-b)/\lvert y\rvert, are pushed short much harder. Raise pp 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.

NumPy Length drift from the aggregation mode (sampled, not expected)
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, ρi,t\rho_{i,t}. Three alternatives move toward the sequence.

GSPO (Zheng et al. 2025) clips the 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−εl,1+εh)A^i)].s_i = \Big(\frac{\pi_\theta(y_i\mid x)}{\pi_{\text{old}}(y_i\mid x)}\Big)^{1/\lvert y_i\rvert} = \exp\Big(\frac{1}{\lvert y_i\rvert}\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_l,1+\varepsilon_h)\hat A_i\big)\Big].

Since ∇si=si⋅1∣yi∣∑t∇log⁡πθ(yi,t)\nabla s_i = s_i\cdot\frac{1}{\lvert y_i\rvert}\sum_t\nabla\log\pi_\theta(y_{i,t}), the per-token weight inside the band is

wi,tGSPO=si A^iG ∣yi∣vs.wi,tGRPO=ρi,t A^iG ∣yi∣.w^{\text{GSPO}}_{i,t} = \frac{s_i\,\hat A_i}{G\,\lvert y_i\rvert}\qquad\text{vs.}\qquad w^{\text{GRPO}}_{i,t} = \frac{\rho_{i,t}\,\hat A_i}{G\,\lvert y_i\rvert}.

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 1/∣yi∣1/\lvert y_i\rvert and hence the (r−b)/∣y∣(r-b)/\lvert y\rvert reward from the previous section come back through the derivative of the geometric mean. The paper’s clip range is 3×10−43\times10^{-4} / 4×10−44\times10^{-4}, 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 si,t=sg⁡[si]⋅πθ(yi,t)/sg⁡[πθ(yi,t)]s_{i,t} = \operatorname{sg}[s_i]\cdot\pi_\theta(y_{i,t})/\operatorname{sg}[\pi_\theta(y_{i,t})], whose value equals sis_i but which allows a per-token advantage A^i,t\hat A_{i,t}.

GMPO (Zhao et al. 2025) keeps the token-level clip but replaces GRPO’s arithmetic mean over tokens with a geometric mean:

JGMPO=E[1G∑i{∏t∣min⁡(ρi,tA^i, clip⁡(ρi,t,εl,εh)A^i)∣}1/∣yi∣sgn⁡(A^i)],J_{\text{GMPO}} = \mathbb E\Big[\frac1G\sum_i\Big\{\prod_{t}\big\lvert\min\big(\rho_{i,t}\hat A_i,\ \operatorname{clip}(\rho_{i,t},\varepsilon_l,\varepsilon_h)\hat A_i\big)\big\rvert\Big\}^{1/\lvert y_i\rvert}\operatorname{sgn}(\hat A_i)\Big],

with the clip range (e−0.4,e0.4)(e^{-0.4}, e^{0.4}) in log space. Differentiating the log⁡\log of the product shows that an unclipped token gets w=s~iA^i/(G∣yi∣)w=\tilde s_i\hat A_i/(G\lvert y_i\rvert), where s~i\tilde s_i 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 s~i\tilde s_i by a bounded amount.

SAPO (Gao et al. 2025) removes the hard edge altogether. Each token’s weight is multiplied by a smooth gate,

wi,tSAPO∝ρi,t⋅4p(1−p)⋅A^i,p=σ(τ(ρi,t−1))  ⇒  4p(1−p)=sech⁡2 ⁣(τ(ρi,t−1)2),w^{\text{SAPO}}_{i,t} \propto \rho_{i,t}\cdot 4p(1-p)\cdot\hat A_i,\qquad p=\sigma\big(\tau(\rho_{i,t}-1)\big) \;\Rightarrow\; 4p(1-p) = \operatorname{sech}^2\!\Big(\frac{\tau(\rho_{i,t}-1)}{2}\Big),

which is 1 at ρ=1\rho=1 and decays smoothly. The temperature depends on the sign of the advantage, τ+=1.0\tau_{+}=1.0 and τ−=1.05\tau_{-}=1.05 in the paper’s controlled runs, so negative-advantage tokens fade faster (the paper reports τ−>τ+\tau_{-}>\tau_{+} 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 sech⁡2(τ2log⁡si)\operatorname{sech}^2(\frac{\tau}{2}\log s_i) — 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 A^\hat A), 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).

  1. sequence-mean에서 400 step 뒤 오답은 약 2,400에서 3,000토큰을 훌쩍 넘게 자라고 정답은 줄었다. 정답률은 한 번도 바뀌지 않았는데 응답당 토큰은 늘었다.
  2. 상수 정규화로 바꾸면 아무것도 움직이지 않는다. token-mean은 아주 조금만 움직인다(상관된 분모).
  3. pp를 0.1로 낮추면 b=pb=p가 작아서 오답 보상 −b/∣y∣-b/\lvert y\rvert이 모든 길이에서 작고, 오답의 이동이 느려진다. 보상이 (1−b)/∣y∣(1-b)/\lvert y\rvert인 정답은 훨씬 세게 짧아진다. pp를 0.8로 올리면 반대다.

같은 메커니즘 때문에 길이 편향을 일부러 쓸 수도 있다. MiMo-V2.6은 길이 증가를 늦추려고 일부러 프롬프트별로 평균하고, MiniMax-M1 보고서는 오답이 더 빨리 길어지는 pattern collapse를 sample 단위 손실과 토큰 단위 정규화를 섞어서 고쳤다(둘 다 Track VI 리뷰에서). 시퀀스 단위 가중치는 적어 두지 않은 길이 패널티다. 그것을 원하는지 알고 써라.

NumPy 집계 방식이 만드는 길이 이동 (기댓값이 아닌 샘플링)
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 ρi,t\rho_{i,t} 하나를 쓴다. 세 대안이 시퀀스 쪽으로 움직인다.

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−εl,1+εh)A^i)].s_i = \Big(\frac{\pi_\theta(y_i\mid x)}{\pi_{\text{old}}(y_i\mid x)}\Big)^{1/\lvert y_i\rvert} = \exp\Big(\frac{1}{\lvert y_i\rvert}\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_l,1+\varepsilon_h)\hat A_i\big)\Big].

∇si=si⋅1∣yi∣∑t∇log⁡πθ(yi,t)\nabla s_i = s_i\cdot\frac{1}{\lvert y_i\rvert}\sum_t\nabla\log\pi_\theta(y_{i,t})이므로 band 안에서 토큰당 가중치는

wi,tGSPO=si A^iG ∣yi∣대wi,tGRPO=ρi,t A^iG ∣yi∣.w^{\text{GSPO}}_{i,t} = \frac{s_i\,\hat A_i}{G\,\lvert y_i\rvert}\qquad\text{대}\qquad w^{\text{GRPO}}_{i,t} = \frac{\rho_{i,t}\,\hat A_i}{G\,\lvert y_i\rvert}.

이 한 줄에서 두 사실이 보인다. 응답의 모든 토큰이 같은 가중치를 받는다(토큰 단위 잡음이 gradient에 곱해지지 않는다). 그리고 GSPO는 sequence-mean 집계를 물려받는다. 1/∣yi∣1/\lvert y_i\rvert, 따라서 앞 절의 (r−b)/∣y∣(r-b)/\lvert y\rvert 보상이 기하평균의 미분을 통해 돌아온다. 논문의 clip 범위는 3×10−43\times10^{-4} / 4×10−44\times10^{-4}로 GRPO보다 세 자릿수 좁고, GRPO보다 두 자릿수 많은 토큰을 clip하면서도 더 효율적으로 학습했다고 보고한다. 멀티턴용 GSPO-token은 si,t=sg⁡[si]⋅πθ(yi,t)/sg⁡[πθ(yi,t)]s_{i,t} = \operatorname{sg}[s_i]\cdot\pi_\theta(y_{i,t})/\operatorname{sg}[\pi_\theta(y_{i,t})]로, 값은 sis_i와 같지만 토큰별 advantage A^i,t\hat A_{i,t}를 허용한다.

GMPO(Zhao et al. 2025)는 토큰 단위 clip을 유지하되 토큰에 대한 GRPO의 산술평균을 기하평균으로 바꾼다.

JGMPO=E[1G∑i{∏t∣min⁡(ρi,tA^i, clip⁡(ρi,t,εl,εh)A^i)∣}1/∣yi∣sgn⁡(A^i)],J_{\text{GMPO}} = \mathbb E\Big[\frac1G\sum_i\Big\{\prod_{t}\big\lvert\min\big(\rho_{i,t}\hat A_i,\ \operatorname{clip}(\rho_{i,t},\varepsilon_l,\varepsilon_h)\hat A_i\big)\big\rvert\Big\}^{1/\lvert y_i\rvert}\operatorname{sgn}(\hat A_i)\Big],

clip 범위는 log 공간에서 (e−0.4,e0.4)(e^{-0.4}, e^{0.4})다. 곱의 log⁡\log를 미분하면 clip되지 않은 토큰은 w=s~iA^i/(G∣yi∣)w=\tilde s_i\hat A_i/(G\lvert y_i\rvert)를 받고(s~i\tilde s_i는 clip된 ratio들의 기하평균) clip된 토큰은 0을 받는다. GRPO의 토큰 단위 clip 판정을 단 GSPO의 가중치다. 이상치 토큰은 응답 전체를 데려가지 않고 혼자 꺼지며, s~i\tilde s_i를 제한된 만큼만 움직일 수 있다.

SAPO(Gao et al. 2025)는 딱딱한 경계를 아예 없앤다. 토큰마다 가중치에 부드러운 gate를 곱한다.

wi,tSAPO∝ρi,t⋅4p(1−p)⋅A^i,p=σ(τ(ρi,t−1))  ⇒  4p(1−p)=sech⁡2 ⁣(τ(ρi,t−1)2),w^{\text{SAPO}}_{i,t} \propto \rho_{i,t}\cdot 4p(1-p)\cdot\hat A_i,\qquad p=\sigma\big(\tau(\rho_{i,t}-1)\big) \;\Rightarrow\; 4p(1-p) = \operatorname{sech}^2\!\Big(\frac{\tau(\rho_{i,t}-1)}{2}\Big),

ρ=1\rho=1에서 1이고 부드럽게 줄어든다. 온도는 advantage 부호에 따라 다르고(논문의 통제 실험에서 τ+=1.0\tau_{+}=1.0, τ−=1.05\tau_{-}=1.05), 음의 advantage 토큰이 더 빨리 흐려진다. 논문은 τ−>τ+\tau_{-}>\tau_{+}가 가장 안정적이었다고 보고하며, 음의 토큰 gradient가 관련 없는 많은 어휘 항목으로 퍼지기 때문이라고 설명한다. 논문의 가정 아래 토큰 gate의 평균은 시퀀스 gate sech⁡2(τ2log⁡si)\operatorname{sech}^2(\frac{\tau}{2}\log s_i)로 모인다. 이상치 토큰 하나를 여전히 낮출 수 있는 부드러운 GSPO다.

그림으로: 토큰 ratio 대 시퀀스 ratio

기하평균이 왜 토큰보다 나은 단위일까? 토큰의 log-ratio를 세 부분으로 나눠 보자. 체계적 부분(업데이트가 의도한 움직임, A^\hat A와 같은 부호), 토큰 단위 잡음(위치마다 샘플 하나; MoE라면 작은 routing 흔들림도), 드문 큰 도약(expert가 바뀐 토큰; GSPO 논문은 48층 MoE에서 gradient 업데이트 한 번 뒤 활성 expert의 약 10%가 바뀐다고 보고한다)이다.

The same 160 responses (half with  > 0, half with  < 0) seen two ways. Each token's log-ratio is a systematic drift μ in the direction of its advantage (what the update intended), plus token noise σ, plus rare routing flips (an MoE token whose expert changed, |log ρ| ≈ 1.5). Left: token log-ratios against the DAPO band [0.8, 1.28]; the clip fires on noise and flips, at a rate that does not depend on length. Right: log si, the mean log-ratio of each response, against GSPO's band [1−3·10⁻⁴, 1+4·10⁻⁴] (drawn exaggerated if too thin). Drag T up: the sequence histogram narrows as σ/√T and separates by the sign of Â, so GSPO's decision increasingly follows the systematic drift. Note how narrow the band is: at realistic noise many responses of both signs are clipped. 같은 응답 160개(절반은  > 0, 절반은  < 0)를 두 가지로 본다. 토큰의 log-ratio는 advantage 방향의 체계적 이동 μ(업데이트가 의도한 것) + 토큰 잡음 σ + 드문 routing 뒤집힘(expert가 바뀐 MoE 토큰, |log ρ| ≈ 1.5)이다. 왼쪽: DAPO band [0.8, 1.28]에 대한 토큰 log-ratio. clip은 잡음과 뒤집힘에 반응하고, 그 비율은 길이와 무관하다. 오른쪽: 응답별 평균 log-ratio log si와 GSPO band [1−3·10⁻⁴, 1+4·10⁻⁴](너무 얇으면 과장해 그림). T를 올리면 시퀀스 히스토그램이 σ/√T로 좁아지고 Â의 부호로 갈라져서, GSPO의 판정이 점점 체계적 이동을 따른다. band가 얼마나 좁은지도 보라. 현실적인 잡음에서는 두 부호의 응답이 많이 clip된다.
  1. 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.
  2. The sequence histogram is a different object. Its width is about σ/T\sigma/\sqrt T (the flips are averaged down the same way), and its centre is the systematic drift ±μ\pm\mu. 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.
  3. Now look at the width of GSPO’s band. At 33–4×10−44\times10^{-4} it is narrower than σ/T\sigma/\sqrt T 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.
  4. 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 log⁡si\log s_i by 1.5/T1.5/T — at T=1,000T=1{,}000 that is 1.5×10−31.5\times10^{-3}, 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 sis_i is a better importance weight. It is not one. The block below measures this.

NumPy Token ratio, sequence product and GSPO's geometric mean as gradient corrections
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 πold\pi_{\text{old}}, 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 πθ\pi_\theta is computed with binomial sums. Read the columns:

  • Sequence product ∏tρt\prod_t\rho_t 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 ρt\rho_t is biased, because it corrects only token tt‘s own distribution while the reward also depends on the other T−1T-1 tokens, whose shift it ignores; the bias grows with T (0.02 → 0.21), but its variance stays flat.
  • GSPO’s sis_i is almost exactly as biased as no correction at all. With a per-token drift this small, si≈1s_i\approx1. 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 ε\varepsilon 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 pp carries no signal with probability pG+(1−p)Gp^G+(1-p)^G (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 Psignal(p)=1−pG−(1−p)GP_{\text{signal}}(p)=1-p^G-(1-p)^G. The surviving distribution of pass rates is tilted toward p≈12p\approx\tfrac12; 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 1/σ1/\sigma.

The alternative to resampling is rescaling. GPG keeps the batch as it is and multiplies the gradient by B/(B−M)B/(B-M), where MM 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 [0.05,0.8][0.05, 0.8]; GLM-4.5’s hard stage uses prompts with pass@8 = 0 but pass@512 > 0 and 512 samples per prompt. Large GG is the only way to get signal from a prompt with p=0.002p=0.002 (Psignal≈0.03P_{\text{signal}}\approx0.03 at G=16G=16, ≈0.64\approx0.64 at G=512G=512).

NumPy Zero-variance groups, dynamic sampling and two-stage group sizes
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 G=8G=8 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 GG 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 GG times; outputs and gradients are identical to standard GRPO, so it changes cost, not the algorithm. With long agentic prompts and G=16G=16 the saving is large.

Implementing the sequence-level objectives

PyTorch PyTorch: GSPO, GSPO-token, GMPO and SAPO losses 로컬에서 실행run locally (pip install torch)
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 min⁡(ρA,clip⁡(ρ)A)\min(\rho A, \operatorname{clip}(\rho)A) inside the absolute value: for A^>0\hat A>0 the effective ratio is min⁡(ρ,e0.4)\min(\rho, e^{0.4}), for A^<0\hat A<0 it is max⁡(ρ,e−0.4)\max(\rho, e^{-0.4}), so the gradient vanishes exactly on the clipped tokens. In sapo_loss, differentiating f(r)=4τσ(τ(r−1))f(r)=\frac4\tau\sigma(\tau(r-1)) with respect to log⁡π\log\pi gives r⋅4σ(1−σ)r\cdot 4\sigma(1-\sigma), the gate in the equation above.

확인 문제Check yourself

You switch a GRPO run with sequence-mean aggregation to GSPO. Which statement about length bias is right?

Differentiating si=exp⁡(1∣yi∣∑tlog⁡ρi,t)s_i=\exp(\frac{1}{\lvert y_i\rvert}\sum_t\log\rho_{i,t}) gives every token the weight siA^i/(G∣yi∣)s_i\hat A_i/(G\lvert y_i\rvert) — exactly sequence-mean aggregation with ρi,t\rho_{i,t} replaced by sis_i. So the expected update is still the gradient of E[(r−b)/∣y∣]\mathbb E[(r-b)/\lvert y\rvert] near on-policy. To remove it you would have to change the outer 1G∑i\frac1G\sum_i to a token-count normaliser, which is no longer GSPO as published.

확인 문제Check yourself

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 ∏tρt\prod_t\rho_t. Its TT-th root sis_i shrinks every deviation by 1/T1/T 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 sis_i as a low-noise measure of how far a response has moved and simply refuses (clips) responses beyond a 10−410^{-4}-wide band.

Summary

  • Each aggregation mode optimises its own objective. Sequence-mean is the exact gradient of E[(r−b)/∣y∣]\mathbb E[(r-b)/\lvert y\rvert]: 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 siA^i/(G∣yi∣)s_i\hat A_i/(G\lvert y_i\rvert): uniform within a response, and carrying sequence-mean’s 1/∣yi∣1/\lvert y_i\rvert. 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 (σ/T\sigma/\sqrt T), so GSPO’s clip tests the systematic drift. It is not an importance weight: only ∏tρt\prod_t\rho_t is unbiased (with exploding variance), token ratios are biased with flat variance, and sis_i barely corrects at all.
  • Zero-variance groups shrink the batch; dynamic sampling refills it but tilts the objective toward p≈12p\approx\tfrac12; GPG rescales instead; adaptive group sizes buy signal on rare-success prompts. Prefix Grouper changes only the cost of the group’s shared prompt.
  1. T = 1000에서 토큰 히스토그램은 잡음이 지배한다. DAPO clip은 두 부호 모두 토큰의 몇 %에 작동하고, 뒤집힘은 꼬리에 있다. T를 끌어도 그 비율은 바뀌지 않는다.
  2. 시퀀스 히스토그램은 다른 대상이다. 폭이 대략 σ/T\sigma/\sqrt T이고(뒤집힘도 같은 식으로 평균된다), 중심은 체계적 이동 ±μ\pm\mu다. T를 4,000으로 끌면 두 부호가 두 봉우리로 갈라지고, clip 판정은 어떤 토큰이 우연히 시끄럽게 샘플되었는지가 아니라 업데이트가 응답 전체에 한 일을 따른다.
  3. 이제 GSPO band의 폭을 보라. 33–4×10−44\times10^{-4}이면 현실적인 잡음과 길이에서 σ/T\sigma/\sqrt T보다 좁아서, 두 부호의 응답 상당 부분이 clip된다. GSPO가 GRPO보다 약 두 자릿수 많은 토큰을 clip한다는 논문의 보고와 맞는다. 이 설계는 많은 clip을 받아들이는 대신 응답 단위로 일관된 판정을 얻는다.
  4. T를 10까지 내려라. 시퀀스 ratio가 토큰 몇 개만큼 시끄러워지고 판정이 동전 던지기가 된다. 이 방법은 긴 응답을 위한 설계다.

이것이 GSPO의 MoE 주장을 읽는 방법이다. 토큰 하나의 log-ratio를 1.5 움직이는 routing 뒤집힘은 log⁡si\log s_i를 1.5/T1.5/T만큼 움직인다. T=1,000T=1{,}000이면 1.5×10−31.5\times10^{-3}로 여전히 band보다 넓다. GSPO가 MoE 잡음을 없애지는 않는다. 뒤집힌 토큰을 하나씩 clip할지 말지 정하는 대신, 양방향 뒤집힘이 일부 상쇄되는 모든 토큰 이동의 합으로 판정하게 만든다. 그렇다고 sis_i가 더 나은 importance weight라는 뜻은 아니다. 애초에 importance weight가 아니다. 아래 블록이 이것을 잰다.

NumPy Gradient 보정으로서의 토큰 ratio, 시퀀스 곱, GSPO 기하평균
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}")
 

설정: 토큰은 πold\pi_{\text{old}}에서 뽑았고, 정책은 그 뒤 토큰당 KL 0.0045만큼 움직였으며, 보상은 모든 토큰에 함께 의존한다(“평균보다 좋은 토큰을 더 썼나”라는 부드러운 점수). πθ\pi_\theta에서의 정확한 gradient는 이항 합으로 계산한다. 열을 읽자.

  • 시퀀스 곱 ∏tρt\prod_t\rho_t만이 편향 없는 보정이고, 퍼짐이 T와 함께 커진다(여기서 상대 std 0.25 → 0.58. 현실적인 길이와 불일치에서는 쓸 수 없다는 것을 불일치 레슨이 보였다).
  • 토큰 ratio ρt\rho_t는 편향이 있다. 토큰 tt 자신의 분포만 보정하는데 보상은 나머지 T−1T-1개 토큰에도 의존하고 그 이동은 무시하기 때문이다. 편향은 T와 함께 자라지만(0.02 → 0.21) 분산은 평평하다.
  • **GSPO의 sis_i**는 보정을 전혀 안 한 것과 거의 똑같이 편향되어 있다. 토큰당 이동이 이만큼 작으면 si≈1s_i\approx1이다. GSPO는 off-policy gradient를 보정하지 않는다. 이동이 아주 좁은 band를 넘은 응답을 쓰기를 거부하고, 보정이 필요 없을 만큼 on-policy 가까이에 머문다. 그래서 ε\varepsilon이 아주 작아야 하고, rollout당 minibatch 업데이트가 적은 설정과 자연스럽게 어울린다.

신호 없는 그룹: 배치에 무엇이 남나

집계는 토큰의 무게를 정하고, 배치는 어떤 토큰이 존재하는지를 정한다. 이진 보상에서 통과율 pp인 그룹은 확률 pG+(1−p)Gp^G+(1-p)^G로 신호가 없다(유도). 식보다 덜 뻔한 결과가 셋 있다.

Dynamic sampling은 목적함수를 바꾼다. 신호 없는 그룹을 버리고 다시 샘플하면(DAPO) 배치는 꽉 차지만, 살아남은 프롬프트는 Psignal(p)=1−pG−(1−p)GP_{\text{signal}}(p)=1-p^G-(1-p)^G로 가중된다. 살아남은 통과율 분포는 p≈12p\approx\tfrac12 쪽으로 기울고, 어려운 데이터셋이면 실효 평균 통과율이 눈에 띄게 오른다. 대개 원하는 것이지만(배울 수 있는 프롬프트들이다) 재가중이고, GRPO의 1/σ1/\sigma와 겹친다.

다시 샘플하는 대신 크기를 맞출 수도 있다. GPG는 배치를 그대로 두고 gradient에 B/(B−M)B/(B-M)을 곱한다(MM은 advantage 0 그룹의 샘플 수). 죽은 그룹이 step을 줄이지 못하게 한다. Olmo 3의 active sampling은 0이 아닌 그룹이 충분히 모일 때까지 비동기 큐에서 끝난 그룹을 계속 꺼내므로, 동기식 과샘플링 비용을 치르지 않는다.

그룹 크기는 프롬프트마다 적응할 수 있다. MAI는 먼저 16개를 뽑고 관찰한 통과율이 [0.05,0.8][0.05, 0.8]일 때만 128개로 늘린다. GLM-4.5의 어려운 단계는 pass@8 = 0이지만 pass@512 > 0인 프롬프트에 프롬프트당 512개 샘플을 쓴다. p=0.002p=0.002인 프롬프트에서 신호를 얻는 방법은 큰 GG뿐이다(G=16G=16에서 Psignal≈0.03P_{\text{signal}}\approx0.03, G=512G=512에서 ≈0.64\approx0.64).

NumPy 신호 없는 그룹, dynamic sampling, 2단계 그룹 크기
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)에서 G=8G=8 그룹의 68%만 신호를 싣고, dynamic sampling은 학습 분포의 평균 통과율을 0.33에서 약 0.40으로 조용히 옮긴다. 2단계 방식은 프롬프트당 약 95번, 신호 있는 프롬프트당 120번의 rollout을 쓴다. 늘 128개를 뽑으면 136번이다. 절약은 이미 풀었거나 가망 없다고 일찍 알아본 프롬프트에서 나온다(정확한 숫자는 난이도 분포에 달렸으니 예시로 읽어라).

그룹에 관한 마지막, 순수하게 계산적인 메모. GG개 응답은 모두 같은 프롬프트를 공유한다. Prefix Grouper(Liu et al. 2025)는 self-attention을 공유 prefix 부분과 응답별 부분으로 나눠 프롬프트를 GG번이 아니라 한 번만 encode한다. 출력과 gradient가 표준 GRPO와 같으므로 알고리즘이 아니라 비용을 바꾼다. 긴 agentic 프롬프트와 G=16G=16이면 절약이 크다.

시퀀스 단위 목적함수 구현

PyTorch PyTorch: GSPO, GSPO-token, GMPO, SAPO 손실 로컬에서 실행run locally (pip install torch)
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는 절댓값 안의 min⁡(ρA,clip⁡(ρ)A)\min(\rho A, \operatorname{clip}(\rho)A)를 재현한다. A^>0\hat A>0이면 실효 ratio가 min⁡(ρ,e0.4)\min(\rho, e^{0.4}), A^<0\hat A<0이면 max⁡(ρ,e−0.4)\max(\rho, e^{-0.4})라서 clip된 토큰에서 정확히 gradient가 사라진다. sapo_loss에서 f(r)=4τσ(τ(r−1))f(r)=\frac4\tau\sigma(\tau(r-1))을 log⁡π\log\pi로 미분하면 r⋅4σ(1−σ)r\cdot 4\sigma(1-\sigma), 위 식의 gate가 나온다.

확인 문제Check yourself

sequence-mean 집계를 쓰던 GRPO 실험을 GSPO로 바꿨다. 길이 편향에 관해 맞는 말은?

si=exp⁡(1∣yi∣∑tlog⁡ρi,t)s_i=\exp(\frac{1}{\lvert y_i\rvert}\sum_t\log\rho_{i,t})를 미분하면 모든 토큰이 가중치 siA^i/(G∣yi∣)s_i\hat A_i/(G\lvert y_i\rvert)를 받는다. ρi,t\rho_{i,t}를 sis_i로 바꾼 sequence-mean 집계 그대로다. 그래서 on-policy 근처에서 기대 업데이트는 여전히 E[(r−b)/∣y∣]\mathbb E[(r-b)/\lvert y\rvert]의 gradient다. 없애려면 바깥의 1G∑i\frac1G\sum_i를 토큰 수 정규화로 바꿔야 하고, 그것은 더 이상 발표된 GSPO가 아니다.

확인 문제Check yourself

NumPy 실험에서 GSPO의 s_i가 보정을 안 한 것만큼 편향된 이유는?

시퀀스 전체의 정확한 보정은 ∏tρt\prod_t\rho_t다. 그 TT제곱근 sis_i는 log 공간에서 모든 편차를 1/T1/T로 줄이므로, 토큰당 KL 0.0045에서는 1과 1% 미만 차이이고 off-policy gradient를 거의 바꾸지 않는다. GSPO의 설계는 그것이 무언가를 보정할 필요가 없다. sis_i를 응답이 얼마나 움직였는지에 대한 잡음 적은 척도로 쓰고, 폭 10−410^{-4} band를 넘은 응답을 그냥 거부(clip)한다.

정리

  • 집계 방식마다 최적화하는 목적함수가 다르다. Sequence-mean은 E[(r−b)/∣y∣]\mathbb E[(r-b)/\lvert y\rvert]의 정확한 gradient다. 맞으면 짧게, 틀리면 길게. 상수 정규화는 편향이 없지만 step이 길이와 함께 커진다. Token-mean은 거의 편향이 없고 step이 길이에 적응하며, 분모를 통한 약한 잔여 편향이 있다.
  • “Token-mean”은 optimizer step마다 전역 분모 하나를 써야 한다. 장치별이나 micro-batch별 정규화는 평균의 평균 편향을 되살린다.
  • GSPO의 토큰당 가중치는 siA^i/(G∣yi∣)s_i\hat A_i/(G\lvert y_i\rvert)다. 응답 안에서 균일하고, sequence-mean의 1/∣yi∣1/\lvert y_i\rvert를 싣고 있다. GMPO는 GSPO의 기하평균 가중치에 토큰 단위 clip을 단다. SAPO는 hard clip을 부호에 따라 다른 부드러운 gate로 바꾸고, 그 gate는 부드러운 시퀀스 gate로 모인다.
  • 시퀀스 ratio는 토큰 잡음과 routing 뒤집힘을 평균으로 걷어 내므로(σ/T\sigma/\sqrt T) GSPO의 clip은 체계적 이동을 검정한다. importance weight는 아니다. ∏tρt\prod_t\rho_t만 편향이 없고(분산 폭발), 토큰 ratio는 편향이 있되 분산이 평평하며, sis_i는 거의 보정하지 않는다.
  • 신호 없는 그룹은 배치를 줄인다. Dynamic sampling은 다시 채우지만 목적함수를 p≈12p\approx\tfrac12 쪽으로 기울이고, GPG는 대신 크기를 맞추며, 적응형 그룹 크기는 성공이 드문 프롬프트에서 신호를 산다. Prefix Grouper는 그룹이 공유하는 프롬프트의 비용만 바꾼다.

더 읽을거리Further reading