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

정규화 — KL, 엔트로피, 길이Regularisation — KL, entropy and length

KL 항을 손실에 넣을 때 추정량과 샘플 분포가 gradient를 어떻게 바꾸는지(k1·k2·k3, k3+, DeepSeek-V3.2의 ρ·k3, 보상 안의 KL과 손실 안의 KL), Kimi k1.5의 mirror descent와 제곱 log-ratio 정규화, 엔트로피 붕괴를 공분산으로 유도하고 clip-higher·엔트로피 보너스·Clip-Cov/KL-Cov·controller로 다루는 법, 그리고 길이 제어(overlong shaping, 길이 보상, budget)를 정리한다.How the estimator and the sampling distribution change the gradient of a KL loss (k1, k2, k3, k3+, DeepSeek-V3.2's ρ·k3, KL in the reward vs in the loss); Kimi k1.5's mirror descent and squared log-ratio regulariser; entropy collapse derived as a covariance and handled with clip-higher, entropy bonuses, Clip-Cov/KL-Cov and controllers; and length control (overlong shaping, length rewards, budgets).

The landscape table showed the reference KL nearly gone from frontier recipes. That does not mean regularisation is gone; it moved. This lesson follows it to four places: the KL term that remains (and the surprisingly subtle question of what gradient it produces), anchoring to the previous policy (Kimi’s mirror descent), entropy (why it collapses and the four ways labs keep it up), and length, the regulariser written into the reward. KL-regularised RL derived the k1/k2/k3 estimators and showed that differentiating k3 as a loss gives the gradient of the other KL; we start from there.

The KL term: value estimators are not gradient estimators

For a sampled token y∼qy\sim q and r=πref(y)/πθ(y)r=\pi_{\text{ref}}(y)/\pi_\theta(y), Schulman’s three estimators of KL(πθ∥πref)\mathrm{KL}(\pi_\theta\|\pi_{\text{ref}}) are k1=−log⁡rk_1=-\log r, k2=12(log⁡r)2k_2=\tfrac12(\log r)^2 and k3=r−1−log⁡rk_3=r-1-\log r. Used as a loss, what matters is not the estimator’s value but its derivative with respect to ℓ=log⁡πθ(y)\ell=\log\pi_\theta(y), which is the weight it puts on ∇log⁡πθ(y)\nabla\log\pi_\theta(y):

∂k1∂ℓ=1,∂k2∂ℓ=log⁡πθπref,∂k3∂ℓ=1−πrefπθ.\frac{\partial k_1}{\partial\ell}=1,\qquad \frac{\partial k_2}{\partial\ell}=\log\frac{\pi_\theta}{\pi_{\text{ref}}},\qquad \frac{\partial k_3}{\partial\ell}=1-\frac{\pi_{\text{ref}}}{\pi_\theta}.

With on-policy samples (q=πθq=\pi_\theta), E[1⋅∇log⁡π]=0\mathbb E[1\cdot\nabla\log\pi]=0, so k1 contributes nothing in expectation; k2k_2‘s weight is exactly the score-function form of ∇KL(πθ∥πref)\nabla\mathrm{KL}(\pi_\theta\|\pi_{\text{ref}}); and k3k_3‘s weight gives ∑y(πθ−πref)∇log⁡πθ=∇KL(πref∥πθ)\sum_y(\pi_\theta-\pi_{\text{ref}})\nabla\log\pi_\theta = \nabla\mathrm{KL}(\pi_{\text{ref}}\|\pi_\theta), the other direction (Tang & Munos 2025 make this point for the “variance-reduced” estimator GRPO uses). Two fixes are in use:

  • k3+ (straight-through). Keep k3’s value for logging and use k2’s gradient: loss=sg⁡[k3]+k2−sg⁡[k2]\text{loss}=\operatorname{sg}[k_3]+k_2-\operatorname{sg}[k_2], a value that is k3 and a derivative that is log⁡(πθ/πref)\log(\pi_\theta/\pi_{\text{ref}}). verl exposes it as kl_loss_type: k3+ (“straight-through to employ k2 for unbiased gradient estimation, regardless of the kl value estimation”). REINFORCE++-baseline uses a k2 loss directly.
  • ρ·k3 (DeepSeek-V3.2). The samples in a PPO-style step come from πold\pi_{\text{old}}, not πθ\pi_\theta. V3.2 multiplies the estimator by ρ=πθ/πold\rho=\pi_\theta/\pi_{\text{old}} (eq. 7 of the report):
D^=ρ(πrefπθ−log⁡πrefπθ−1),∂D^∂ℓ=ρ (k3+1−r)=ρlog⁡πθπref.\hat D=\rho\Big(\frac{\pi_{\text{ref}}}{\pi_\theta}-\log\frac{\pi_{\text{ref}}}{\pi_\theta}-1\Big),\qquad \frac{\partial\hat D}{\partial\ell}=\rho\,(k_3+1-r)=\rho\log\frac{\pi_\theta}{\pi_{\text{ref}}}.

Its expectation under πold\pi_{\text{old}} is ∑yπθ(y) k3(y)=KL(πθ∥πref)\sum_y\pi_\theta(y)\,k_3(y)=\mathrm{KL}(\pi_\theta\|\pi_{\text{ref}}) as a function of θ, so both the value and the gradient are exact, on- or off-policy. The report’s own argument is about the weight: plain k3’s weight 1−r1-r is unbounded as r→∞r\to\infty (tokens much more likely under the reference than under the policy), giving “disproportionately large, unbounded weights” to raise their probability.

The difference between the two fixes is the sample distribution. k3+ uses k2’s gradient, which is exact only on-policy; with several minibatch updates per rollout, or an asynchronous sampler, the samples come from πold\pi_{\text{old}} or μ\mu and the expectation is taken under the wrong distribution. The importance ratio is what makes V3.2’s estimator robust to that.

지도의 표에서 프론티어 레시피에서 reference KL이 거의 사라졌음을 봤다. 정규화가 사라졌다는 뜻은 아니다. 자리를 옮겼다. 이 레슨은 그것을 네 곳으로 따라간다. 남아 있는 KL 항(그리고 그것이 만드는 gradient가 무엇이냐는 뜻밖에 미묘한 질문), 직전 정책에 묶기(Kimi의 mirror descent), 엔트로피(왜 붕괴하는지, 랩들이 그것을 지키는 네 방법), 그리고 보상에 써 넣은 정규화인 길이다. KL 정규화 RL이 k1/k2/k3 추정량을 유도하고, k3를 손실로 미분하면 다른 방향 KL의 gradient가 나온다는 것을 보였다. 거기서 출발한다.

KL 항: 값 추정량은 gradient 추정량이 아니다

샘플 토큰 y∼qy\sim q와 r=πref(y)/πθ(y)r=\pi_{\text{ref}}(y)/\pi_\theta(y)에 대해 KL(πθ∥πref)\mathrm{KL}(\pi_\theta\|\pi_{\text{ref}})의 Schulman 추정량 셋은 k1=−log⁡rk_1=-\log r, k2=12(log⁡r)2k_2=\tfrac12(\log r)^2, k3=r−1−log⁡rk_3=r-1-\log r다. 손실로 쓸 때 중요한 것은 추정량의 값이 아니라 ℓ=log⁡πθ(y)\ell=\log\pi_\theta(y)에 대한 미분, 즉 ∇log⁡πθ(y)\nabla\log\pi_\theta(y)에 얹는 가중치다.

∂k1∂ℓ=1,∂k2∂ℓ=log⁡πθπref,∂k3∂ℓ=1−πrefπθ.\frac{\partial k_1}{\partial\ell}=1,\qquad \frac{\partial k_2}{\partial\ell}=\log\frac{\pi_\theta}{\pi_{\text{ref}}},\qquad \frac{\partial k_3}{\partial\ell}=1-\frac{\pi_{\text{ref}}}{\pi_\theta}.

On-policy 샘플(q=πθq=\pi_\theta)이면 E[1⋅∇log⁡π]=0\mathbb E[1\cdot\nabla\log\pi]=0이라 k1은 기댓값에서 아무것도 기여하지 않는다. k2k_2의 가중치는 정확히 ∇KL(πθ∥πref)\nabla\mathrm{KL}(\pi_\theta\|\pi_{\text{ref}})의 score-function 꼴이다. k3k_3의 가중치는 ∑y(πθ−πref)∇log⁡πθ=∇KL(πref∥πθ)\sum_y(\pi_\theta-\pi_{\text{ref}})\nabla\log\pi_\theta = \nabla\mathrm{KL}(\pi_{\text{ref}}\|\pi_\theta), 반대 방향을 준다(Tang & Munos 2025가 GRPO가 쓰는 “분산을 줄인” 추정량에 대해 이 점을 짚는다). 두 가지 수정이 쓰인다.

  • k3+ (straight-through). 기록용 값은 k3로 두고 gradient는 k2의 것을 쓴다. loss=sg⁡[k3]+k2−sg⁡[k2]\text{loss}=\operatorname{sg}[k_3]+k_2-\operatorname{sg}[k_2], 값은 k3이고 미분은 log⁡(πθ/πref)\log(\pi_\theta/\pi_{\text{ref}})인 손실이다. verl은 이것을 kl_loss_type: k3+로 제공한다(“KL 값 추정과 무관하게 straight-through로 k2를 써서 편향 없는 gradient를 추정”). REINFORCE++-baseline은 k2 손실을 바로 쓴다.
  • ρ·k3 (DeepSeek-V3.2). PPO식 step의 샘플은 πθ\pi_\theta가 아니라 πold\pi_{\text{old}}에서 왔다. V3.2는 추정량에 ρ=πθ/πold\rho=\pi_\theta/\pi_{\text{old}}를 곱한다(보고서 eq. 7).
D^=ρ(πrefπθ−log⁡πrefπθ−1),∂D^∂ℓ=ρ (k3+1−r)=ρlog⁡πθπref.\hat D=\rho\Big(\frac{\pi_{\text{ref}}}{\pi_\theta}-\log\frac{\pi_{\text{ref}}}{\pi_\theta}-1\Big),\qquad \frac{\partial\hat D}{\partial\ell}=\rho\,(k_3+1-r)=\rho\log\frac{\pi_\theta}{\pi_{\text{ref}}}.

πold\pi_{\text{old}} 아래 기댓값은 θ의 함수로서 ∑yπθ(y) k3(y)=KL(πθ∥πref)\sum_y\pi_\theta(y)\,k_3(y)=\mathrm{KL}(\pi_\theta\|\pi_{\text{ref}})이므로, on-policy든 off-policy든 값과 gradient가 모두 정확하다. 보고서 자신의 논증은 가중치에 관한 것이다. 보통 k3의 가중치 1−r1-r은 r→∞r\to\infty(정책보다 reference에서 훨씬 그럴듯한 토큰)에서 끝없이 커져, 그 확률을 올리는 데 “불균형하게 크고 유계가 아닌 가중치”를 준다.

두 수정의 차이는 샘플 분포다. k3+는 on-policy에서만 정확한 k2의 gradient를 쓴다. rollout당 minibatch 업데이트가 여러 번이거나 샘플러가 비동기면 샘플은 πold\pi_{\text{old}}나 μ\mu에서 오고 기댓값이 틀린 분포 아래에서 취해진다. V3.2의 추정량이 그에 강한 것은 importance ratio 덕분이다.

끌기:drag:
A three-token policy drawn on the probability simplex. The black arrow is the true descent direction of KL(πθ‖πref); the coloured arrows are the expected update of each way of putting a KL term in the loss, with tokens sampled from πold. Click or drag to move the selected point. On-policy (press the button), k2 and k3+ coincide with the true direction, k3 points along the other KL, KL(πref‖πθ), and k1 has zero expected gradient. Now drag πold away from πθ: only DeepSeek-V3.2's ρ·k3 stays exact, because the ratio ρ = πθ/πold turns samples from πold back into an expectation under πθ. 토큰 셋짜리 정책을 확률 simplex 위에 그렸다. 검은 화살표는 KL(πθ‖πref)의 진짜 하강 방향이고, 색 화살표는 πold에서 토큰을 샘플할 때 KL 항을 손실에 넣는 방식마다의 기대 업데이트다. 클릭하거나 끌어서 고른 점을 옮겨라. on-policy(버튼)에서는 k2와 k3+가 진짜 방향과 겹치고, k3는 다른 KL인 KL(πref‖πθ) 쪽을 가리키며, k1은 기대 gradient가 0이다. 이제 πold를 πθ에서 떼어 보라. DeepSeek-V3.2의 ρ·k3만 정확하다. ratio ρ = πθ/πold가 πold의 샘플을 πθ 아래 기댓값으로 되돌리기 때문이다.

Where the KL goes: reward or loss

There is a second, independent issue. A KL “loss” summed per token, ∑tD(πθ(⋅∣ht)∥πref(⋅∣ht))\sum_t D(\pi_\theta(\cdot\mid h_t)\|\pi_{\text{ref}}(\cdot\mid h_t)), is differentiated position by position as if the states hth_t were fixed. But yty_t also changes the distribution of all later states, and with it the later tokens’ KL. Tang & Munos show that a token-level KL loss is therefore at best a partial derivative of the sequence KL; the unbiased score-function estimator is the cumulative one,

∇ KLseq≈∑t(∑s≥tlog⁡πθ(ys∣hs)πref(ys∣hs))∇log⁡πθ(yt∣ht),\nabla\,\mathrm{KL}_{\text{seq}} \approx \sum_t\Big(\sum_{s\ge t}\log\frac{\pi_\theta(y_s\mid h_s)}{\pi_{\text{ref}}(y_s\mid h_s)}\Big)\nabla\log\pi_\theta(y_t\mid h_t),

which is exactly what putting k1 in the reward and propagating it through a return does (InstructGPT-style PPO, REINFORCE++). GRPO moved the KL into the loss for convenience; for short outputs near the reference the difference is small, for long reasoning traces far from the reference it is not. Ziegler et al.’s adaptive controller sets the coefficient of the in-reward KL by et=clip⁡(KLt−KLtargetKLtarget,−0.2,0.2)e_t=\operatorname{clip}\big(\frac{\mathrm{KL}_t-\mathrm{KL}_{\text{target}}}{\mathrm{KL}_{\text{target}}},-0.2,0.2\big), βt+1=βt(1+Kβet)\beta_{t+1}=\beta_t(1+K_\beta e_t) with Kβ=0.1K_\beta=0.1.

NumPy KL losses as gradient estimators: estimator, sample distribution, token vs sequence
import numpy as np
rng = np.random.default_rng(0)
V = 50
softmax = lambda z: np.exp(z - z.max()) / np.exp(z - z.max()).sum()
z_ref = rng.normal(0, 1.5, V)
z_th = z_ref + rng.normal(0, 0.6, V)                       # the policy has drifted from the reference
pi_ref, pi = softmax(z_ref), softmax(z_th)

def expected_grad(q, c):
    """E_{y~q}[c(y) (e_y − π)]: expected gradient wrt logits of a per-token loss with dLoss/dlog π(y) = c(y)."""
    return (q * c) - pi * (q * c).sum()

lr = np.log(pi_ref / pi)                                   # log r, r = π_ref/π_θ
kl = np.sum(pi * -lr)
true = pi * (-lr - kl)                                     # ∇_z KL(π_θ ‖ π_ref)
fwd = pi - pi_ref                                          # ∇_z KL(π_ref ‖ π_θ)
def report(q, tag):
    rho = pi / q
    rows = {"k1  = −log r": np.ones(V), "k2  = ½(log r)²": -lr, "k3  = r−1−log r": 1 - np.exp(lr),
            "k3+ (k3 value, k2 grad)": -lr, "ρ·k3 (V3.2)": rho * -lr}
    print(f"{tag}: KL(π_θ‖π_ref) = {kl:.3f}")
    for name, c in rows.items():
        g = expected_grad(q, c)
        cos = g @ true / (np.linalg.norm(g) * np.linalg.norm(true) + 1e-30)
        err = np.linalg.norm(g - true) / np.linalg.norm(true)
        cf = g @ fwd / (np.linalg.norm(g) * np.linalg.norm(fwd) + 1e-30)
        print(f"   {name:24s} cos(true) {cos:+.3f}   rel.err {err:5.2f}   cos(∇KL(π_ref‖π_θ)) {cf:+.3f}")
report(pi, "on-policy samples (q = π_θ)")
pi_old = softmax(z_th + rng.normal(0, 0.8, V))             # samples from a stale / different engine
report(pi_old, "\noff-policy samples (q = π_old)")

# the sequence view: a token-level KL loss misses how y_1 changes the KL of later tokens
A = 3
z1, r1 = rng.normal(0, 1, A), rng.normal(0, 1, A)
z2, r2 = rng.normal(0, 1, (A, A)), rng.normal(0, 1, (A, A))
p1, q1 = softmax(z1), softmax(r1)
p2 = np.array([softmax(z) for z in z2]); q2 = np.array([softmax(z) for z in r2])
kl2 = np.sum(p2 * np.log(p2 / q2), 1)                      # KL at step 2 given y1
# true ∇_{z1} of the sequence KL = KL(p1‖q1) + E_{y1}[kl2(y1)]
g_true = p1 * (np.log(p1 / q1) - np.sum(p1 * np.log(p1 / q1))) + p1 * (kl2 - p1 @ kl2)
g_token = p1 * (np.log(p1 / q1) - np.sum(p1 * np.log(p1 / q1)))  # per-token KL loss: only the step-1 term
c1 = np.log(p1 / q1) + kl2                                 # KL in the reward, reward-to-go weight of ∇log π(y1)
g_reward = p1 * c1 - p1 * (p1 @ c1)
for name, g in [("per-token KL loss", g_token), ("KL in reward (reward-to-go)", g_reward)]:
    print(f"\n{name:28s} rel.err vs ∇ sequence KL wrt step-1 logits: {np.linalg.norm(g - g_true) / np.linalg.norm(g_true):.3f}", end="")
print()
 

On-policy, k2, k3+ and ρ·k3 are exact, k3 has cosine 0.974 with the true gradient and 1.000 with ∇KL(πref∥πθ)\nabla\mathrm{KL}(\pi_{\text{ref}}\|\pi_\theta), and k1 is zero. Off-policy every estimator except ρ·k3 drifts to a relative error of 0.55–0.92. In the two-step toy the per-token KL loss misses 94% of the step-1 gradient (the part that flows through the second token’s KL), and the reward-to-go version gets it exactly.

Anchoring to the previous policy: Kimi k1.5’s mirror descent

Kimi k1.5 regularises toward the previous iterate πθi\pi_{\theta_i} rather than a fixed reference. Each iteration solves

max⁡θ Ey∼πθ[r(x,y)]−τ KL(πθ(⋅∣x) ∥ πθi(⋅∣x)),\max_\theta\ \mathbb E_{y\sim\pi_\theta}[r(x,y)]-\tau\,\mathrm{KL}\big(\pi_\theta(\cdot\mid x)\,\|\,\pi_{\theta_i}(\cdot\mid x)\big),

whose solution is π⋆∝πθiexp⁡(r/τ)\pi^\star\propto\pi_{\theta_i}\exp(r/\tau) (derivation). Taking logs, π⋆\pi^\star satisfies r−τlog⁡Z=τlog⁡π⋆πθir-\tau\log Z=\tau\log\frac{\pi^\star}{\pi_{\theta_i}} for every response, including responses sampled from πθi\pi_{\theta_i} — so the condition can be fitted off-policy with a squared loss:

L(θ)=Ey∼πθi[(r−τlog⁡Z−τlog⁡πθ(y∣x)πθi(y∣x))2],−∇L2τ=(r−τlog⁡Z−τlog⁡πθπθi)∇log⁡πθ(y∣x).L(\theta)=\mathbb E_{y\sim\pi_{\theta_i}}\Big[\Big(r-\tau\log Z-\tau\log\frac{\pi_\theta(y\mid x)}{\pi_{\theta_i}(y\mid x)}\Big)^2\Big],\qquad -\frac{\nabla L}{2\tau}=\Big(r-\tau\log Z-\tau\log\frac{\pi_\theta}{\pi_{\theta_i}}\Big)\nabla\log\pi_\theta(y\mid x).

k1.5 replaces τlog⁡Z\tau\log Z by the sample mean reward rˉ\bar r (which it equals as τ→∞\tau\to\infty). In the template the weight is the advantage minus a pull-back proportional to how far the response has already moved, A^−τlog⁡ρseq\hat A-\tau\log\rho_{\text{seq}}: a soft quadratic trust region in place of a clip. Kimi K2 keeps this loss; K2.5 and K3 move it to tokens, −τ(log⁡ρt)2-\tau(\log\rho_t)^2, together with a log-ratio mask. The same squared form appears offline as Direct Reward Optimisation (Richemond et al. 2024), with 12(r−V−τlog⁡ππref)2\tfrac12(r-V-\tau\log\frac{\pi}{\pi_{\text{ref}}})^2 and a learned value VV in place of rˉ\bar r.

NumPy The squared loss recovers π* ∝ π_i·exp(r/τ); replacing τ log Z by r̄ is exact only for large τ
M = 8
pi_i = softmax(rng.normal(0, 1, M))                        # current policy over 8 responses
r = (rng.random(M) < 0.4).astype(float)                    # binary rewards
for tau in [0.5, 2.0, 10.0]:
    target = pi_i * np.exp(r / tau); target /= target.sum()  # π* ∝ π_i exp(r/τ)
    logZ = np.log(np.sum(pi_i * np.exp(r / tau)))
    for base, b in [("τ log Z", tau * logZ), ("r̄ (k1.5)", pi_i @ r)]:
        th = np.log(pi_i).copy()                           # optimise the logits of π_θ
        for _ in range(3000):                              # E_{y~π_i}[(r − b − τ log π_θ/π_i)²]
            q = softmax(th)
            resid = r - b - tau * (np.log(q) - np.log(pi_i))
            c = -2 * tau * pi_i * resid                    # d loss / d log π_θ(y), weighted by π_i(y)
            th -= 0.1 / tau**2 * (c - q * c.sum())
        q = softmax(th)
        print(f"τ={tau:4.1f} baseline {base:9s}: KL(π*‖π_θ) = {abs(np.sum(target * np.log(target / q))):.2e}")
 

With the exact baseline τlog⁡Z\tau\log Z the squared loss lands on π⋆\pi^\star to machine precision for every τ\tau. With rˉ\bar r the fit is off by KL≈10−2\mathrm{KL}\approx10^{-2} at τ=0.5\tau=0.5 and 2×10−92\times10^{-9} at τ=10\tau=10. The Kimi review’s reading — “less mirror descent than mean-baseline REINFORCE plus an L2 penalty” at small τ\tau — is what this shows.

Entropy: why it collapses

Write the policy at one state as a softmax over logits zz. Since ∂H/∂za=−πa(log⁡πa+H)\partial H/\partial z_a=-\pi_a(\log\pi_a+H), a small logit change Δz\Delta z changes the entropy by

ΔH≈−∑aπa(log⁡πa+H) Δza=−Cov⁡a∼π(log⁡π(a), Δza).\Delta H\approx-\sum_a\pi_a(\log\pi_a+H)\,\Delta z_a=-\operatorname{Cov}_{a\sim\pi}\big(\log\pi(a),\ \Delta z_a\big).

For the policy gradient, the expected logit change is Δza=η πaA(a)\Delta z_a=\eta\,\pi_a A(a) (natural gradient: ηA(a)\eta A(a)), so ΔH≈−ηCov⁡(log⁡π(a), πaA(a))\Delta H\approx-\eta\operatorname{Cov}(\log\pi(a),\ \pi_aA(a)) (Cui et al. 2025). Entropy falls whenever likely tokens have high advantage or unlikely tokens have low advantage — which is what learning normally looks like. Cui et al. measure this covariance staying mostly positive throughout RLVR training, hence monotone entropy decline, and fit downstream performance as R=−a eH+bR=-a\,e^{H}+b: performance is bought with entropy, and the ceiling is reached at H=0H=0.

This one line explains every entropy-control method in use:

  • Clip-higher. A low-probability token with positive advantage has a negative log⁡πa\log\pi_a deviation and a positive Δza\Delta z_a, so it contributes positively to ΔH\Delta H. Those are exactly the tokens whose ratio rises fastest and hits PPO’s upper clip first (previous lesson). The symmetric clip preferentially removes entropy-increasing updates; widening εh\varepsilon_h gives them back.
  • Clip-Cov / KL-Cov (Cui et al.). Compute each token’s centred covariance (log⁡πt−log⁡π‾)(At−Aˉ)(\log\pi_t-\overline{\log\pi})(A_t-\bar A); Clip-Cov detaches the gradient of a random rr-fraction of tokens whose covariance lies in [ωlow,ωhigh][\omega_{\text{low}},\omega_{\text{high}}] (r=2×10−4r=2\times10^{-4}, bounds 1 and 5); KL-Cov puts a KL penalty to the old policy on the top-kk fraction (k=2×10−3k=2\times10^{-3} for 7B, 2×10−42\times10^{-4} for 32B, coefficient 1).
  • Entropy bonus +βH+\beta H (A3C, PPO’s Eq. 9): direct, but it pushes up the entropy of every state equally, including junk tokens. MAI reports that an entropy-bonus loss worked worse than its controller.
  • Entropy controllers. MAI-Thinking-1 estimates H^=1∣T∣∑(i,t)−log⁡πθ(yi,t) ρi,t\hat H=\frac{1}{\lvert\mathcal T\rvert}\sum_{(i,t)}-\log\pi_\theta(y_{i,t})\,\rho_{i,t} and moves the clip upper bound κ\kappa: κ←clip⁡(κ+δsign⁡(H⋆−H^),0,κmax⁡)\kappa\leftarrow\operatorname{clip}(\kappa+\delta\operatorname{sign}(H^\star-\hat H),0,\kappa_{\max}) with δ=0.25\delta=0.25, H⋆=0.3H^\star=0.3, κmax⁡=2.5\kappa_{\max}=2.5; the report shows entropy held near 0.3 for 800 steps. MiMo-V2.6 adapts separate bounds for positive and negative advantages from entropy (low entropy → widen the positive band, narrow the negative). GLM-4.5 raises the sampling temperature when the reward plateaus. All three use the clip or the sampler, not an extra loss.
NumPy ΔH = −Cov(log π, Δz): check the identity and see which tokens lower entropy
K = 12
z = rng.normal(0, 1.2, K); p = softmax(z)
Aadv = rng.normal(0, 1, K)                                  # advantage of each token
H = lambda q: -np.sum(q * np.log(q))
eta = 1e-3
for name, dz in [("policy gradient Δz = η π A", eta * p * Aadv), ("natural PG     Δz = η A", eta * Aadv)]:
    actual = H(softmax(z + dz)) - H(p)
    lp = np.log(p)
    cov = np.sum(p * (lp - p @ lp) * (dz - p @ dz))
    print(f"{name}: ΔH actual {actual:+.3e}   −Cov(log π, Δz) {-cov:+.3e}")
# contribution of token a: −π_a (log π_a − E log π)(Δz_a − E Δz)
dz = p * Aadv
contrib = -p * (np.log(p) - p @ np.log(p)) * (dz - p @ dz)
for a in np.argsort(-p)[:3].tolist() + np.argsort(p)[:2].tolist():
    print(f"  token π={p[a]:.3f} A={Aadv[a]:+.2f} → ΔH contribution {contrib[a] * eta:+.2e}")
 

The identity holds to the third significant digit for both gradient types. In this draw the most likely token has a negative advantage, so pushing it down raises entropy; flip its sign and it becomes the largest entropy sink. The figure below runs the full dynamics.

KL을 어디에 넣나: 보상이냐 손실이냐

독립적인 두 번째 문제가 있다. 토큰마다 더한 KL “손실” ∑tD(πθ(⋅∣ht)∥πref(⋅∣ht))\sum_t D(\pi_\theta(\cdot\mid h_t)\|\pi_{\text{ref}}(\cdot\mid h_t))은 상태 hth_t가 고정된 것처럼 위치별로 미분된다. 그러나 yty_t는 이후 모든 상태의 분포, 따라서 이후 토큰의 KL도 바꾼다. Tang & Munos는 그래서 토큰 단위 KL 손실이 시퀀스 KL의 부분 미분일 뿐임을 보인다. 편향 없는 score-function 추정량은 누적형이다.

∇ KLseq≈∑t(∑s≥tlog⁡πθ(ys∣hs)πref(ys∣hs))∇log⁡πθ(yt∣ht),\nabla\,\mathrm{KL}_{\text{seq}} \approx \sum_t\Big(\sum_{s\ge t}\log\frac{\pi_\theta(y_s\mid h_s)}{\pi_{\text{ref}}(y_s\mid h_s)}\Big)\nabla\log\pi_\theta(y_t\mid h_t),

이것은 정확히 k1을 보상에 넣고 return으로 전파하는 방식(InstructGPT식 PPO, REINFORCE++)이 하는 일이다. GRPO는 편의상 KL을 손실로 옮겼다. reference 근처의 짧은 출력이면 차이가 작고, reference에서 먼 긴 추론 궤적이면 작지 않다. Ziegler et al.의 적응형 controller는 보상 안 KL의 계수를 et=clip⁡(KLt−KLtargetKLtarget,−0.2,0.2)e_t=\operatorname{clip}\big(\frac{\mathrm{KL}_t-\mathrm{KL}_{\text{target}}}{\mathrm{KL}_{\text{target}}},-0.2,0.2\big), βt+1=βt(1+Kβet)\beta_{t+1}=\beta_t(1+K_\beta e_t), Kβ=0.1K_\beta=0.1로 정한다.

NumPy Gradient 추정량으로서의 KL 손실: 추정량, 샘플 분포, 토큰 대 시퀀스
import numpy as np
rng = np.random.default_rng(0)
V = 50
softmax = lambda z: np.exp(z - z.max()) / np.exp(z - z.max()).sum()
z_ref = rng.normal(0, 1.5, V)
z_th = z_ref + rng.normal(0, 0.6, V)                       # 정책이 reference에서 멀어졌다
pi_ref, pi = softmax(z_ref), softmax(z_th)

def expected_grad(q, c):
    """E_{y~q}[c(y) (e_y − π)]: dLoss/dlog π(y) = c(y)인 토큰별 손실의 logit에 대한 기대 gradient."""
    return (q * c) - pi * (q * c).sum()

lr = np.log(pi_ref / pi)                                   # log r, r = π_ref/π_θ
kl = np.sum(pi * -lr)
true = pi * (-lr - kl)                                     # ∇_z KL(π_θ ‖ π_ref)
fwd = pi - pi_ref                                          # ∇_z KL(π_ref ‖ π_θ)
def report(q, tag):
    rho = pi / q
    rows = {"k1  = −log r": np.ones(V), "k2  = ½(log r)²": -lr, "k3  = r−1−log r": 1 - np.exp(lr),
            "k3+ (k3 value, k2 grad)": -lr, "ρ·k3 (V3.2)": rho * -lr}
    print(f"{tag}: KL(π_θ‖π_ref) = {kl:.3f}")
    for name, c in rows.items():
        g = expected_grad(q, c)
        cos = g @ true / (np.linalg.norm(g) * np.linalg.norm(true) + 1e-30)
        err = np.linalg.norm(g - true) / np.linalg.norm(true)
        cf = g @ fwd / (np.linalg.norm(g) * np.linalg.norm(fwd) + 1e-30)
        print(f"   {name:24s} cos(true) {cos:+.3f}   rel.err {err:5.2f}   cos(∇KL(π_ref‖π_θ)) {cf:+.3f}")
report(pi, "on-policy samples (q = π_θ)")
pi_old = softmax(z_th + rng.normal(0, 0.8, V))             # 오래되었거나 다른 엔진에서 온 샘플
report(pi_old, "\noff-policy samples (q = π_old)")

# 시퀀스 관점: 토큰 단위 KL 손실은 y_1이 이후 토큰의 KL을 바꾸는 효과를 놓친다
A = 3
z1, r1 = rng.normal(0, 1, A), rng.normal(0, 1, A)
z2, r2 = rng.normal(0, 1, (A, A)), rng.normal(0, 1, (A, A))
p1, q1 = softmax(z1), softmax(r1)
p2 = np.array([softmax(z) for z in z2]); q2 = np.array([softmax(z) for z in r2])
kl2 = np.sum(p2 * np.log(p2 / q2), 1)                      # y1이 주어졌을 때 2단계의 KL
# 시퀀스 KL = KL(p1‖q1) + E_{y1}[kl2(y1)]의 진짜 ∇_{z1}
g_true = p1 * (np.log(p1 / q1) - np.sum(p1 * np.log(p1 / q1))) + p1 * (kl2 - p1 @ kl2)
g_token = p1 * (np.log(p1 / q1) - np.sum(p1 * np.log(p1 / q1)))  # 토큰별 KL 손실: 1단계 항만
c1 = np.log(p1 / q1) + kl2                                 # 보상 안의 KL: ∇log π(y1)의 reward-to-go 가중치
g_reward = p1 * c1 - p1 * (p1 @ c1)
for name, g in [("per-token KL loss", g_token), ("KL in reward (reward-to-go)", g_reward)]:
    print(f"\n{name:28s} rel.err vs ∇ sequence KL wrt step-1 logits: {np.linalg.norm(g - g_true) / np.linalg.norm(g_true):.3f}", end="")
print()
 

On-policy에서 k2, k3+, ρ·k3는 정확하고, k3는 진짜 gradient와 cosine 0.974, ∇KL(πref∥πθ)\nabla\mathrm{KL}(\pi_{\text{ref}}\|\pi_\theta)와 1.000이며, k1은 0이다. Off-policy에서는 ρ·k3를 뺀 모든 추정량이 상대 오차 0.55–0.92로 벗어난다. 2단계 장난감에서 토큰별 KL 손실은 1단계 gradient의 94%(두 번째 토큰의 KL을 거쳐 흐르는 부분)를 놓치고, reward-to-go 판은 정확히 맞힌다.

직전 정책에 묶기: Kimi k1.5의 mirror descent

Kimi k1.5는 고정된 reference가 아니라 직전 iterate πθi\pi_{\theta_i} 쪽으로 정규화한다. 매 iteration이 다음을 푼다.

max⁡θ Ey∼πθ[r(x,y)]−τ KL(πθ(⋅∣x) ∥ πθi(⋅∣x)),\max_\theta\ \mathbb E_{y\sim\pi_\theta}[r(x,y)]-\tau\,\mathrm{KL}\big(\pi_\theta(\cdot\mid x)\,\|\,\pi_{\theta_i}(\cdot\mid x)\big),

해는 π⋆∝πθiexp⁡(r/τ)\pi^\star\propto\pi_{\theta_i}\exp(r/\tau)다(유도). log를 취하면 π⋆\pi^\star는 πθi\pi_{\theta_i}에서 샘플한 응답을 포함해 모든 응답에 대해 r−τlog⁡Z=τlog⁡π⋆πθir-\tau\log Z=\tau\log\frac{\pi^\star}{\pi_{\theta_i}}를 만족한다. 그래서 이 조건을 제곱 손실로 off-policy에서 맞출 수 있다.

L(θ)=Ey∼πθi[(r−τlog⁡Z−τlog⁡πθ(y∣x)πθi(y∣x))2],−∇L2τ=(r−τlog⁡Z−τlog⁡πθπθi)∇log⁡πθ(y∣x).L(\theta)=\mathbb E_{y\sim\pi_{\theta_i}}\Big[\Big(r-\tau\log Z-\tau\log\frac{\pi_\theta(y\mid x)}{\pi_{\theta_i}(y\mid x)}\Big)^2\Big],\qquad -\frac{\nabla L}{2\tau}=\Big(r-\tau\log Z-\tau\log\frac{\pi_\theta}{\pi_{\theta_i}}\Big)\nabla\log\pi_\theta(y\mid x).

k1.5는 τlog⁡Z\tau\log Z를 샘플 평균 보상 rˉ\bar r로 바꾼다(τ→∞\tau\to\infty에서 같아진다). 틀로 쓰면 가중치는 advantage에서 응답이 이미 움직인 만큼에 비례해 끌어당기는 항을 뺀 것, A^−τlog⁡ρseq\hat A-\tau\log\rho_{\text{seq}}다. clip 대신 부드러운 이차 trust region이다. Kimi K2는 이 손실을 유지하고, K2.5와 K3는 log-ratio mask와 함께 토큰 단위 −τ(log⁡ρt)2-\tau(\log\rho_t)^2로 옮긴다. 같은 제곱 꼴이 offline에서는 Direct Reward Optimisation(Richemond et al. 2024)으로 나타난다. rˉ\bar r 대신 학습한 가치 VV를 쓴 12(r−V−τlog⁡ππref)2\tfrac12(r-V-\tau\log\frac{\pi}{\pi_{\text{ref}}})^2다.

NumPy 제곱 손실은 π* ∝ π_i·exp(r/τ)를 되찾는다; τ log Z를 r̄로 바꾸면 τ가 클 때만 정확하다
M = 8
pi_i = softmax(rng.normal(0, 1, M))                        # 응답 8개에 대한 현재 정책
r = (rng.random(M) < 0.4).astype(float)                    # 이진 보상
for tau in [0.5, 2.0, 10.0]:
    target = pi_i * np.exp(r / tau); target /= target.sum()  # π* ∝ π_i exp(r/τ)
    logZ = np.log(np.sum(pi_i * np.exp(r / tau)))
    for base, b in [("τ log Z", tau * logZ), ("r̄ (k1.5)", pi_i @ r)]:
        th = np.log(pi_i).copy()                           # π_θ의 logit을 최적화
        for _ in range(3000):                              # E_{y~π_i}[(r − b − τ log π_θ/π_i)²]
            q = softmax(th)
            resid = r - b - tau * (np.log(q) - np.log(pi_i))
            c = -2 * tau * pi_i * resid                    # d loss / d log π_θ(y), π_i(y)로 가중
            th -= 0.1 / tau**2 * (c - q * c.sum())
        q = softmax(th)
        print(f"τ={tau:4.1f} baseline {base:9s}: KL(π*‖π_θ) = {abs(np.sum(target * np.log(target / q))):.2e}")
 

정확한 baseline τlog⁡Z\tau\log Z를 쓰면 제곱 손실은 모든 τ\tau에서 기계 정밀도로 π⋆\pi^\star에 내려앉는다. rˉ\bar r을 쓰면 τ=0.5\tau=0.5에서 KL≈10−2\mathrm{KL}\approx10^{-2}, τ=10\tau=10에서 2×10−92\times10^{-9}만큼 어긋난다. 작은 τ\tau에서 “mirror descent라기보다 평균 baseline REINFORCE + L2 패널티”라는 Kimi 리뷰의 해석이 이것이다.

엔트로피: 왜 붕괴하나

한 상태의 정책을 logit zz에 대한 softmax로 쓰자. ∂H/∂za=−πa(log⁡πa+H)\partial H/\partial z_a=-\pi_a(\log\pi_a+H)이므로 작은 logit 변화 Δz\Delta z가 엔트로피를 바꾸는 양은

ΔH≈−∑aπa(log⁡πa+H) Δza=−Cov⁡a∼π(log⁡π(a), Δza).\Delta H\approx-\sum_a\pi_a(\log\pi_a+H)\,\Delta z_a=-\operatorname{Cov}_{a\sim\pi}\big(\log\pi(a),\ \Delta z_a\big).

Policy gradient에서 기대 logit 변화는 Δza=η πaA(a)\Delta z_a=\eta\,\pi_a A(a)(natural gradient면 ηA(a)\eta A(a))이므로 ΔH≈−ηCov⁡(log⁡π(a), πaA(a))\Delta H\approx-\eta\operatorname{Cov}(\log\pi(a),\ \pi_aA(a))다(Cui et al. 2025). 그럴듯한 토큰이 높은 advantage를, 드문 토큰이 낮은 advantage를 가질 때마다 엔트로피가 떨어진다. 보통의 학습이 바로 그렇다. Cui et al.은 RLVR 학습 내내 이 공분산이 대체로 양수로 머물러 엔트로피가 단조 감소함을 측정했고, 하류 성능을 R=−a eH+bR=-a\,e^{H}+b로 맞췄다. 성능은 엔트로피를 주고 사며, H=0H=0에서 천장에 닿는다.

이 한 줄이 쓰이고 있는 모든 엔트로피 제어를 설명한다.

  • Clip-higher. 양의 advantage를 가진 확률 낮은 토큰은 log⁡πa\log\pi_a 편차가 음이고 Δza\Delta z_a가 양이라 ΔH\Delta H에 양으로 기여한다. 바로 ratio가 가장 빨리 올라 PPO의 위쪽 clip에 먼저 걸리는 토큰이다(앞 레슨). 대칭 clip은 엔트로피를 올리는 업데이트를 골라서 지우고, εh\varepsilon_h를 넓히면 돌려준다.
  • Clip-Cov / KL-Cov(Cui et al.). 토큰마다 중심화한 공분산 (log⁡πt−log⁡π‾)(At−Aˉ)(\log\pi_t-\overline{\log\pi})(A_t-\bar A)를 계산한다. Clip-Cov는 공분산이 [ωlow,ωhigh][\omega_{\text{low}},\omega_{\text{high}}]에 있는 토큰 중 무작위 rr 비율의 gradient를 떼어 낸다(r=2×10−4r=2\times10^{-4}, 경계 1과 5). KL-Cov는 상위 kk 비율에 old 정책으로의 KL 패널티를 건다(7B에서 k=2×10−3k=2\times10^{-3}, 32B에서 2×10−42\times10^{-4}, 계수 1).
  • 엔트로피 보너스 +βH+\beta H(A3C, PPO Eq. 9): 직접적이지만 쓸모없는 토큰을 포함해 모든 상태의 엔트로피를 똑같이 올린다. MAI는 엔트로피 보너스 손실이 자기 controller보다 나빴다고 보고한다.
  • 엔트로피 controller. MAI-Thinking-1은 H^=1∣T∣∑(i,t)−log⁡πθ(yi,t) ρi,t\hat H=\frac{1}{\lvert\mathcal T\rvert}\sum_{(i,t)}-\log\pi_\theta(y_{i,t})\,\rho_{i,t}를 추정하고 clip 상한 κ\kappa를 κ←clip⁡(κ+δsign⁡(H⋆−H^),0,κmax⁡)\kappa\leftarrow\operatorname{clip}(\kappa+\delta\operatorname{sign}(H^\star-\hat H),0,\kappa_{\max})로 움직인다(δ=0.25\delta=0.25, H⋆=0.3H^\star=0.3, κmax⁡=2.5\kappa_{\max}=2.5). 보고서는 800 step 동안 엔트로피가 0.3 근처에 머문 것을 보인다. MiMo-V2.6은 양·음 advantage에 대한 별도 경계를 엔트로피로 조정한다(엔트로피가 낮으면 양의 band를 넓히고 음의 band를 좁힌다). GLM-4.5는 보상이 정체하면 샘플링 temperature를 올린다. 셋 다 추가 손실이 아니라 clip이나 샘플러를 쓴다.
NumPy ΔH = −Cov(log π, Δz): 항등식 확인과 엔트로피를 내리는 토큰
K = 12
z = rng.normal(0, 1.2, K); p = softmax(z)
Aadv = rng.normal(0, 1, K)                                  # 토큰마다의 advantage
H = lambda q: -np.sum(q * np.log(q))
eta = 1e-3
for name, dz in [("policy gradient Δz = η π A", eta * p * Aadv), ("natural PG     Δz = η A", eta * Aadv)]:
    actual = H(softmax(z + dz)) - H(p)
    lp = np.log(p)
    cov = np.sum(p * (lp - p @ lp) * (dz - p @ dz))
    print(f"{name}: ΔH actual {actual:+.3e}   −Cov(log π, Δz) {-cov:+.3e}")
# 토큰 a의 기여: −π_a (log π_a − E log π)(Δz_a − E Δz)
dz = p * Aadv
contrib = -p * (np.log(p) - p @ np.log(p)) * (dz - p @ dz)
for a in np.argsort(-p)[:3].tolist() + np.argsort(p)[:2].tolist():
    print(f"  token π={p[a]:.3f} A={Aadv[a]:+.2f} → ΔH contribution {contrib[a] * eta:+.2e}")
 

항등식은 두 gradient 모두에서 유효숫자 셋째 자리까지 맞는다. 이 추첨에서는 가장 그럴듯한 토큰의 advantage가 음수라서 그것을 내리면 엔트로피가 오른다. 부호를 뒤집으면 가장 큰 엔트로피 흡수원이 된다. 아래 그림이 전체 동역학을 돌린다.

40 prompts, 12 candidate answers each: a common answer that is right 60% of the time starts at probability ≈ 0.45, a rare one that is right 95% of the time at ≈ 0.02, and ten junk answers. Each step samples 16 answers per prompt and makes 4 PPO passes. Entropy always falls as the junk answers die; the question is where it lands. With the symmetric clip (thin grey line) most prompts lock onto the common answer and the reward ends near 0.64. Pick a method and its knob — εhigh for clip-higher, β for the entropy bonus, the target H* for an integral controller on the upper clip bound — and see whether the policy finds the rare answer. Raise β past about 0.1: the bonus keeps so much entropy that the reward drops again. The controller here, like MAI's, only moves the upper clip bound, so it rescues exploration but cannot hold H at H* once the junk answers are gone. 프롬프트 40개, 후보 답 12개씩: 60% 맞는 흔한 답이 확률 ≈ 0.45로, 95% 맞는 드문 답이 ≈ 0.02로 시작하고, 쓸모없는 답이 열 개 있다. 매 step 프롬프트마다 답 16개를 샘플하고 PPO 패스를 4번 한다. 쓸모없는 답이 사라지며 엔트로피는 늘 떨어진다. 문제는 어디에 내려앉느냐다. 대칭 clip(가는 회색 선)에서는 대부분의 프롬프트가 흔한 답에 묶이고 보상이 0.64 근처에서 끝난다. 방법과 손잡이 — clip-higher의 εhigh, 엔트로피 보너스의 β, 위쪽 clip 경계에 거는 적분 controller의 목표 H* — 를 고르고 정책이 드문 답을 찾는지 보라. β를 0.1 넘게 올리면 보너스가 엔트로피를 너무 많이 남겨 보상이 다시 떨어진다. 여기의 controller는 MAI처럼 위쪽 clip 경계만 움직이므로, 탐색은 살리지만 쓸모없는 답이 사라진 뒤에는 H를 H*에 붙잡지 못한다.

In this toy every method reduces entropy — ten of the twelve answers are useless and should die. What differs is where entropy lands. With the symmetric clip most prompts settle on the 60% answer before the 95% answer is sampled often enough; the reward ends near 0.64. Clip-higher raises it to 0.70–0.79 as εh\varepsilon_h goes from 0.4 to 1.0, the controller and the toy Clip-Cov to about 0.80–0.84, and a moderate entropy bonus (β≈0.02\beta\approx0.02–0.040.04) to about 0.90–0.91; a large bonus (β=0.15\beta=0.15) keeps entropy near 1.4 and the reward falls back to about 0.68. Entropy is a means, not a target: the right amount is the amount that keeps the useful alternatives alive.

Length: the regulariser in the reward

Length control is regularisation applied through the reward rather than the loss. The aggregation lesson showed an implicit one (sequence-mean favours long wrong answers); the explicit ones are:

MethodShapingNotes
DAPO overlong shaping00 up to Lmax⁡−LcacheL_{\max}-L_{\text{cache}}, linear down to −1-1 at Lmax⁡L_{\max}, −1-1 beyondalso: filter truncated samples
Kimi k1.5 length rewardλ=0.5−len−minmax−min\lambda=0.5-\frac{\text{len}-\text{min}}{\text{max}-\text{min}} within the group; λ\lambda if correct, min⁡(0,λ)\min(0,\lambda) if wrongswitched on after a warm-up; gives signal even in all-correct groups
Kimi K2 / K2.5 / K3 budgetsover-budget responses truncated and penalised (K2); budget = percentile of correct lengths, applied only to prompts with high accuracy (K2.5 Toggle); reward −1-1 above τ b0(x)\tau\,b_0(x) (K3 effort levels)effort levels as separate experts in K3
MAI-Thinking-1−wlen ρx ∣y∣/ℓmax⁡-w_{\text{len}}\,\rho_x\,\lvert y\rvert/\ell_{\max} with pass rate ρx\rho_x, wlen=0.25w_{\text{len}}=0.25 (0 at the 128K stage)penalises length more on easy prompts
MiMo-V2.6penalty only in groups whose pass rate exceeds a threshold, relative to a percentile of passing lengthsvalues undisclosed
DeepSeek-V3.2 / V4length penalty in the reward; reasoning-effort experts trained with different penalties and context windowsvalues undisclosed

Two design patterns recur. Length penalties are made conditional on success (k1.5’s wrong answers are never rewarded for length, MAI scales by pass rate, MiMo and K2.5 apply only to easy prompts), because a flat penalty on a hard prompt teaches the model to give up early. And penalties are switched on late or annealed (k1.5’s warm-up, K3’s annealed τ\tau), because early length growth is part of learning to reason. Olmo 3 reports the converse lesson for truncation: in its RL-Zero runs, not masking truncated sequences worked better than masking them, which made batch sizes fluctuate.

NumPy Length-shaping terms on one group
L = np.array([3000, 9000, 15000, 24000, 30000, 32768]); correct = np.array([1, 1, 1, 0, 1, 0])
L_max, L_cache = 32768, 4096
dapo = np.where(L <= L_max - L_cache, 0, np.where(L <= L_max, (L_max - L_cache - L) / L_cache, -1))   # DAPO
lam = 0.5 - (L - L.min()) / (L.max() - L.min())
k15 = np.where(correct == 1, lam, np.minimum(0, lam))                                                  # k1.5
mai = -0.25 * correct.mean() * L / L_max                                                                # MAI-style
budget = np.where(L > 1.5 * 12000, -1.0, correct)                                                       # K3-style τ·b0 = 18000
print("length   correct  DAPO-overlong  k1.5-length  MAI −w·pass·|y|/ℓ  budget(τb0=18k)")
for row in zip(L, correct, dapo, k15, mai, budget):
    print(f"{row[0]:6d} {row[1]:6d} {row[2]:12.3f} {row[3]:12.3f} {row[4]:14.3f} {row[5]:12.1f}")
lam_all = 0.5 - (L - L.min()) / (L.max() - L.min())
print("all-correct group: GRPO advantage", np.zeros(6), "→ with k1.5 length reward:", np.round(lam_all - lam_all.mean(), 2))
 

DAPO only touches the last 4K tokens; the k1.5 reward ranks every response in the group by length and gives an all-correct group, which carries no GRPO signal at all, advantages from +0.54 to −0.46; MAI’s term is mild and linear; a budget is a cliff. Which one fits depends on whether you want to stop runaway truncation (DAPO), compress reasoning (k1.5, budgets) or trade a little accuracy for tokens on easy prompts (MAI, MiMo).

Implementing it

PyTorch PyTorch: KL losses (k1/k2/k3/k3+/ρ·k3), entropy controller, Clip-Cov / KL-Cov, k1.5 loss 로컬에서 실행run locally (pip install torch)
import torch

def kl_loss(logp, ref_logp, old_logp, mask, kind="k3_is"):
    """Per-token KL(π_θ‖π_ref) loss, token-mean. logp has grad; ref_logp, old_logp do not."""
    log_r = ref_logp - logp                                   # log π_ref/π_θ
    k1, k2, k3 = -log_r, 0.5 * log_r ** 2, torch.exp(log_r) - 1 - log_r
    if kind == "k2":
        per = k2
    elif kind == "k3":
        per = k3                                              # gradient of KL(π_ref‖π_θ) on-policy
    elif kind == "k3+":                                       # value of k3, gradient of k2 (straight-through)
        per = k3.detach() + (k2 - k2.detach())
    elif kind == "k3_is":                                     # DeepSeek-V3.2: ρ·k3, exact off-policy
        per = torch.exp(logp - old_logp) * k3
    else:
        per = k1                                              # zero expected gradient on-policy
    m = mask.float()
    return (per * m).sum() / m.sum().clamp(min=1)

class EntropyClipController:
    """MAI-style integral controller on the clip upper bound: hi = 1/(1−ε) + κ."""
    def __init__(self, eps=0.6, target=0.3, delta=0.25, k_max=2.5):
        self.eps, self.target, self.delta, self.k_max, self.k = eps, target, delta, k_max, 0.0
    @torch.no_grad()
    def update(self, logp, old_logp, mask):
        m = mask.float()
        rho = torch.exp(logp - old_logp)
        h_hat = ((-logp * rho) * m).sum() / m.sum()          # Ĥ = mean(−log π · ρ)
        self.k = min(self.k_max, max(0.0, self.k + self.delta * float(torch.sign(self.target - h_hat))))
        return 1 - self.eps, 1 / (1 - self.eps) + self.k     # (low, high) ratio bounds

@torch.no_grad()
def cov_select(logp, adv, mask, mode="clip", frac=2e-4, lo=1.0, hi=5.0):
    """Clip-Cov / KL-Cov token selection by centred covariance (log π − mean)(A − mean)."""
    sel = mask.bool()
    lp, a = logp[sel], adv.expand_as(logp)[sel]
    cov = (lp - lp.mean()) * (a - a.mean())
    out = torch.zeros_like(lp, dtype=torch.bool)
    if mode == "clip":                                        # random frac of tokens with cov in [lo, hi]
        cand = torch.nonzero((cov >= lo) & (cov <= hi)).squeeze(-1)
        n = int(frac * lp.numel())
        if n > 0 and cand.numel() > 0:
            out[cand[torch.randperm(cand.numel())[:n]]] = True
    else:                                                     # KL-Cov: top-k fraction by covariance
        n = max(1, int(frac * lp.numel()))
        out[torch.topk(cov, n).indices] = True
    full = torch.zeros_like(mask, dtype=torch.bool)
    full[sel] = out
    return full          # Clip-Cov: detach these tokens' PG term; KL-Cov: add β·KL(π_old‖π_θ) on them

def k15_loss(seq_logp, seq_old_logp, rewards, group_size, tau=0.1):
    """Kimi k1.5: mean over k samples of (r − r̄ − τ log π_θ(y)/π_old(y))²; seq_logp: (N,) sums over tokens."""
    r = rewards.view(-1, group_size)
    r_bar = r.mean(1, keepdim=True)
    log_ratio = (seq_logp - seq_old_logp).view(-1, group_size)
    return ((r - r_bar - tau * log_ratio) ** 2).mean() / (2 * tau)
 

k3+ is written with detach so its value equals k3 (what you log) while its gradient equals k2’s. k15_loss divides by 2τ2\tau so that its gradient matches the template weight (r−rˉ−τlog⁡ρ)(r-\bar r-\tau\log\rho) rather than growing with τ\tau.

확인 문제Check yourself

Your GRPO run uses a k3 KL loss with 8 minibatch updates per rollout. Which change makes the expected KL gradient exactly ∇KL(π_θ‖π_ref) on every minibatch?

After the first minibatch the samples come from πold≠πθ\pi_{\text{old}}\ne\pi_\theta. k3+ uses the k2 gradient, which equals the reverse-KL gradient only under on-policy samples. ρ⋅k3\rho\cdot k_3 has expectation ∑yπθ(y)k3(y)=KL(πθ∥πref)\sum_y\pi_\theta(y)k_3(y)=\mathrm{KL}(\pi_\theta\|\pi_{\text{ref}}) as a function of θ whatever πold\pi_{\text{old}} is, so its gradient is exact; in the experiment it is the only estimator with zero error off-policy. k1 has zero expected gradient on-policy; lowering β only rescales.

확인 문제Check yourself

By the covariance formula, which update raises the policy's entropy?

ΔH≈−Cov⁡(log⁡π,Δz)\Delta H\approx-\operatorname{Cov}(\log\pi, \Delta z). A low-probability token has log⁡π\log\pi below the mean; raising it (Δz>0\Delta z>0) makes the covariance negative and ΔH\Delta H positive. The other two listed updates make the covariance positive and lower the entropy — which is why ordinary learning lowers entropy and why removing low-probability positive updates (PPO’s upper clip) accelerates the collapse.

Summary

  • A KL loss is defined by three choices: the estimator (k2 and k3+ give the reverse-KL gradient, k3 the forward one, k1 nothing on-policy), the sample distribution (only ρ·k3 is exact off-policy), and the placement (a per-token loss is a partial derivative; KL in the reward with a return is the full sequence gradient).
  • Kimi k1.5 fits the closed-form mirror-descent step π⋆∝πθier/τ\pi^\star\propto\pi_{\theta_i}e^{r/\tau} with a squared loss; in the template the weight is A^−τlog⁡ρ\hat A-\tau\log\rho, a soft quadratic trust region (DRO’s offline form). Replacing τlog⁡Z\tau\log Z by rˉ\bar r is exact only for large τ\tau.
  • Entropy changes by −Cov⁡(log⁡π,Δz)-\operatorname{Cov}(\log\pi, \Delta z); ordinary learning lowers it. Clip-higher restores the entropy-raising updates the upper clip removes, Clip-Cov/KL-Cov cap the highest-covariance tokens, bonuses push all states up, and controllers (MAI, MiMo-V2.6) steer the clip bounds toward a target.
  • Length is regularised through the reward: DAPO overlong shaping, k1.5’s group-relative length reward, budgets (K2–K3), pass-rate-scaled penalties (MAI, MiMo). Successful designs condition the penalty on success and switch it on late.

이 장난감에서 모든 방법이 엔트로피를 줄인다. 열두 답 가운데 열은 쓸모없고 사라져야 한다. 다른 것은 엔트로피가 어디에 내려앉느냐다. 대칭 clip에서는 95% 답이 충분히 자주 샘플되기 전에 대부분의 프롬프트가 60% 답에 자리 잡는다. 보상이 0.64 근처에서 끝난다. Clip-higher는 εh\varepsilon_h를 0.4에서 1.0으로 올리면 0.70–0.79로, controller와 장난감 Clip-Cov는 약 0.80–0.84로, 적당한 엔트로피 보너스(β≈0.02\beta\approx0.02–0.040.04)는 약 0.90–0.91로 올린다. 큰 보너스(β=0.15\beta=0.15)는 엔트로피를 1.4 근처에 두고 보상이 약 0.68로 다시 떨어진다. 엔트로피는 목표가 아니라 수단이다. 맞는 양은 쓸모 있는 대안을 살려 두는 양이다.

길이: 보상 안의 정규화

길이 제어는 손실이 아니라 보상을 통해 거는 정규화다. 집계 레슨이 숨은 것 하나(sequence-mean은 긴 오답을 선호한다)를 보였다. 드러난 것들은 다음과 같다.

방법Shaping메모
DAPO overlong shapingLmax⁡−LcacheL_{\max}-L_{\text{cache}}까지 00, Lmax⁡L_{\max}에서 −1-1까지 선형 감소, 그 너머 −1-1잘린 샘플 걸러내기도 함께
Kimi k1.5 길이 보상그룹 안에서 λ=0.5−len−minmax−min\lambda=0.5-\frac{\text{len}-\text{min}}{\text{max}-\text{min}}; 정답이면 λ\lambda, 오답이면 min⁡(0,λ)\min(0,\lambda)warm-up 뒤에 켬; 모두 정답인 그룹에도 신호를 줌
Kimi K2 / K2.5 / K3 budgetbudget 초과 응답을 자르고 벌함(K2); budget = 정답 길이의 백분위수, 정답률이 높은 프롬프트에만(K2.5 Toggle); τ b0(x)\tau\,b_0(x)를 넘으면 보상 −1-1(K3 effort 수준)K3에서는 effort 수준이 별도 expert
MAI-Thinking-1통과율 ρx\rho_x로 −wlen ρx ∣y∣/ℓmax⁡-w_{\text{len}}\,\rho_x\,\lvert y\rvert/\ell_{\max}, wlen=0.25w_{\text{len}}=0.25 (128K 단계에서는 0)쉬운 프롬프트에서 길이를 더 벌함
MiMo-V2.6통과율이 문턱을 넘는 그룹에서만, 통과한 길이의 백분위수에 상대적인 패널티값 비공개
DeepSeek-V3.2 / V4보상의 길이 패널티; 다른 패널티와 context window로 학습한 reasoning-effort expert값 비공개

두 설계 패턴이 되풀이된다. 길이 패널티는 성공에 조건부로 만든다(k1.5의 오답은 길이로 보상받지 않고, MAI는 통과율로 크기를 맞추며, MiMo와 K2.5는 쉬운 프롬프트에만 건다). 어려운 프롬프트에 평평한 패널티를 걸면 모델이 일찍 포기하는 법을 배우기 때문이다. 그리고 패널티는 늦게 켜거나 점차 조인다(k1.5의 warm-up, K3의 τ annealing). 초반의 길이 증가는 추론을 배우는 과정의 일부이기 때문이다. Olmo 3는 잘림에 관해 반대 교훈을 보고한다. RL-Zero 실험에서 잘린 시퀀스를 mask하지 않는 편이 mask하는 것보다 나았고, mask하면 배치 크기가 흔들렸다.

NumPy 그룹 하나에 건 길이 shaping 항들
L = np.array([3000, 9000, 15000, 24000, 30000, 32768]); correct = np.array([1, 1, 1, 0, 1, 0])
L_max, L_cache = 32768, 4096
dapo = np.where(L <= L_max - L_cache, 0, np.where(L <= L_max, (L_max - L_cache - L) / L_cache, -1))   # DAPO
lam = 0.5 - (L - L.min()) / (L.max() - L.min())
k15 = np.where(correct == 1, lam, np.minimum(0, lam))                                                  # k1.5
mai = -0.25 * correct.mean() * L / L_max                                                                # MAI식
budget = np.where(L > 1.5 * 12000, -1.0, correct)                                                       # K3식 τ·b0 = 18000
print("length   correct  DAPO-overlong  k1.5-length  MAI −w·pass·|y|/ℓ  budget(τb0=18k)")
for row in zip(L, correct, dapo, k15, mai, budget):
    print(f"{row[0]:6d} {row[1]:6d} {row[2]:12.3f} {row[3]:12.3f} {row[4]:14.3f} {row[5]:12.1f}")
lam_all = 0.5 - (L - L.min()) / (L.max() - L.min())
print("all-correct group: GRPO advantage", np.zeros(6), "→ with k1.5 length reward:", np.round(lam_all - lam_all.mean(), 2))
 

DAPO는 마지막 4K 토큰만 건드린다. k1.5 보상은 그룹의 모든 응답을 길이로 순위 매기고, GRPO 신호가 전혀 없는 모두 정답인 그룹에 +0.54에서 −0.46까지의 advantage를 준다. MAI의 항은 완만하고 선형이며, budget은 절벽이다. 어느 것이 맞는지는 폭주하는 잘림을 멈추고 싶은지(DAPO), 추론을 압축하고 싶은지(k1.5, budget), 쉬운 프롬프트에서 정확도를 조금 주고 토큰을 아끼고 싶은지(MAI, MiMo)에 달렸다.

구현

PyTorch PyTorch: KL 손실(k1/k2/k3/k3+/ρ·k3), 엔트로피 controller, Clip-Cov / KL-Cov, k1.5 손실 로컬에서 실행run locally (pip install torch)
import torch

def kl_loss(logp, ref_logp, old_logp, mask, kind="k3_is"):
    """토큰별 KL(π_θ‖π_ref) 손실, token-mean. logp는 grad가 있고 ref_logp, old_logp는 없다."""
    log_r = ref_logp - logp                                   # log π_ref/π_θ
    k1, k2, k3 = -log_r, 0.5 * log_r ** 2, torch.exp(log_r) - 1 - log_r
    if kind == "k2":
        per = k2
    elif kind == "k3":
        per = k3                                              # on-policy에서 KL(π_ref‖π_θ)의 gradient
    elif kind == "k3+":                                       # 값은 k3, gradient는 k2 (straight-through)
        per = k3.detach() + (k2 - k2.detach())
    elif kind == "k3_is":                                     # DeepSeek-V3.2: ρ·k3, off-policy에서도 정확
        per = torch.exp(logp - old_logp) * k3
    else:
        per = k1                                              # on-policy 기대 gradient 0
    m = mask.float()
    return (per * m).sum() / m.sum().clamp(min=1)

class EntropyClipController:
    """clip 상한에 거는 MAI식 적분 controller: hi = 1/(1−ε) + κ."""
    def __init__(self, eps=0.6, target=0.3, delta=0.25, k_max=2.5):
        self.eps, self.target, self.delta, self.k_max, self.k = eps, target, delta, k_max, 0.0
    @torch.no_grad()
    def update(self, logp, old_logp, mask):
        m = mask.float()
        rho = torch.exp(logp - old_logp)
        h_hat = ((-logp * rho) * m).sum() / m.sum()          # Ĥ = mean(−log π · ρ)
        self.k = min(self.k_max, max(0.0, self.k + self.delta * float(torch.sign(self.target - h_hat))))
        return 1 - self.eps, 1 / (1 - self.eps) + self.k     # (아래, 위) ratio 경계

@torch.no_grad()
def cov_select(logp, adv, mask, mode="clip", frac=2e-4, lo=1.0, hi=5.0):
    """중심화 공분산 (log π − mean)(A − mean)으로 고르는 Clip-Cov / KL-Cov 토큰."""
    sel = mask.bool()
    lp, a = logp[sel], adv.expand_as(logp)[sel]
    cov = (lp - lp.mean()) * (a - a.mean())
    out = torch.zeros_like(lp, dtype=torch.bool)
    if mode == "clip":                                        # cov가 [lo, hi]인 토큰 중 무작위 frac
        cand = torch.nonzero((cov >= lo) & (cov <= hi)).squeeze(-1)
        n = int(frac * lp.numel())
        if n > 0 and cand.numel() > 0:
            out[cand[torch.randperm(cand.numel())[:n]]] = True
    else:                                                     # KL-Cov: 공분산 상위 k 비율
        n = max(1, int(frac * lp.numel()))
        out[torch.topk(cov, n).indices] = True
    full = torch.zeros_like(mask, dtype=torch.bool)
    full[sel] = out
    return full          # Clip-Cov: 이 토큰의 PG 항을 detach; KL-Cov: 이 토큰에 β·KL(π_old‖π_θ)를 더함

def k15_loss(seq_logp, seq_old_logp, rewards, group_size, tau=0.1):
    """Kimi k1.5: 샘플 k개에 대한 (r − r̄ − τ log π_θ(y)/π_old(y))²의 평균; seq_logp: (N,) 토큰 합."""
    r = rewards.view(-1, group_size)
    r_bar = r.mean(1, keepdim=True)
    log_ratio = (seq_logp - seq_old_logp).view(-1, group_size)
    return ((r - r_bar - tau * log_ratio) ** 2).mean() / (2 * tau)
 

k3+는 detach로 써서 값은 k3(기록하는 것)와 같고 gradient는 k2와 같다. k15_loss는 2τ2\tau로 나눠 gradient가 τ\tau와 함께 커지지 않고 틀의 가중치 (r−rˉ−τlog⁡ρ)(r-\bar r-\tau\log\rho)와 맞게 했다.

확인 문제Check yourself

GRPO 실험이 rollout당 minibatch 업데이트 8번에 k3 KL 손실을 쓴다. 모든 minibatch에서 기대 KL gradient를 정확히 ∇KL(π_θ‖π_ref)로 만드는 변경은?

첫 minibatch 뒤의 샘플은 πold≠πθ\pi_{\text{old}}\ne\pi_\theta에서 온다. k3+는 on-policy 샘플에서만 reverse KL gradient와 같은 k2 gradient를 쓴다. ρ⋅k3\rho\cdot k_3는 πold\pi_{\text{old}}가 무엇이든 θ의 함수로서 기댓값이 ∑yπθ(y)k3(y)=KL(πθ∥πref)\sum_y\pi_\theta(y)k_3(y)=\mathrm{KL}(\pi_\theta\|\pi_{\text{ref}})이므로 gradient가 정확하다. 실험에서도 off-policy에서 오차가 0인 유일한 추정량이었다. k1은 on-policy 기대 gradient가 0이고, β를 낮추면 크기만 바뀐다.

확인 문제Check yourself

공분산 식에 따르면 정책의 엔트로피를 올리는 업데이트는?

ΔH≈−Cov⁡(log⁡π,Δz)\Delta H\approx-\operatorname{Cov}(\log\pi, \Delta z). 확률 낮은 토큰은 log⁡π\log\pi가 평균보다 낮다. 그것을 올리면(Δz>0\Delta z>0) 공분산이 음이 되고 ΔH\Delta H가 양이 된다. 나머지 두 업데이트는 공분산을 양으로 만들어 엔트로피를 내린다. 보통의 학습이 엔트로피를 내리는 이유이자, 확률 낮은 양의 업데이트를 지우는 것(PPO의 위쪽 clip)이 붕괴를 가속하는 이유다.

정리

  • KL 손실은 세 선택으로 정의된다. 추정량(k2와 k3+는 reverse KL gradient, k3는 forward, k1은 on-policy에서 0), 샘플 분포(off-policy에서 정확한 것은 ρ·k3뿐), 위치(토큰별 손실은 부분 미분, return과 함께 보상에 넣으면 시퀀스 전체 gradient).
  • Kimi k1.5는 닫힌 꼴 mirror descent step π⋆∝πθier/τ\pi^\star\propto\pi_{\theta_i}e^{r/\tau}를 제곱 손실로 맞춘다. 틀로 쓰면 가중치는 A^−τlog⁡ρ\hat A-\tau\log\rho, 부드러운 이차 trust region이다(DRO의 offline 꼴). τlog⁡Z\tau\log Z를 rˉ\bar r로 바꾸는 것은 τ\tau가 클 때만 정확하다.
  • 엔트로피는 −Cov⁡(log⁡π,Δz)-\operatorname{Cov}(\log\pi, \Delta z)만큼 변하고, 보통의 학습은 그것을 낮춘다. Clip-higher는 위쪽 clip이 지운 엔트로피 상승 업데이트를 돌려주고, Clip-Cov/KL-Cov는 공분산이 가장 큰 토큰을 누르며, 보너스는 모든 상태를 올리고, controller(MAI, MiMo-V2.6)는 clip 경계를 목표 쪽으로 조종한다.
  • 길이는 보상을 통해 정규화한다. DAPO overlong shaping, k1.5의 그룹 상대 길이 보상, budget(K2–K3), 통과율에 비례한 패널티(MAI, MiMo). 잘 된 설계는 패널티를 성공에 조건부로 걸고 늦게 켠다.

더 읽을거리Further reading