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 and , Schulman’s three estimators of are , and . Used as a loss, what matters is not the estimator’s value but its derivative with respect to , which is the weight it puts on :
With on-policy samples (), , so k1 contributes nothing in expectation; ‘s weight is exactly the score-function form of ; and ‘s weight gives , 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: , a value that is k3 and a derivative that is . 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 , not . V3.2 multiplies the estimator by (eq. 7 of the report):
Its expectation under is 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 is unbounded as (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 or 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 추정량이 아니다
샘플 토큰 와 에 대해 의 Schulman 추정량 셋은 , , 다. 손실로 쓸 때 중요한 것은 추정량의 값이 아니라 에 대한 미분, 즉 에 얹는 가중치다.
On-policy 샘플()이면 이라 k1은 기댓값에서 아무것도 기여하지 않는다. 의 가중치는 정확히 의 score-function 꼴이다. 의 가중치는 , 반대 방향을 준다(Tang & Munos 2025가 GRPO가 쓰는 “분산을 줄인” 추정량에 대해 이 점을 짚는다). 두 가지 수정이 쓰인다.
- k3+ (straight-through). 기록용 값은 k3로 두고 gradient는 k2의 것을 쓴다. , 값은 k3이고 미분은 인 손실이다. verl은 이것을
kl_loss_type: k3+로 제공한다(“KL 값 추정과 무관하게 straight-through로 k2를 써서 편향 없는 gradient를 추정”). REINFORCE++-baseline은 k2 손실을 바로 쓴다. - ρ·k3 (DeepSeek-V3.2). PPO식 step의 샘플은 가 아니라 에서 왔다. V3.2는 추정량에 를 곱한다(보고서 eq. 7).
아래 기댓값은 θ의 함수로서 이므로, on-policy든 off-policy든 값과 gradient가 모두 정확하다. 보고서 자신의 논증은 가중치에 관한 것이다. 보통 k3의 가중치 은 (정책보다 reference에서 훨씬 그럴듯한 토큰)에서 끝없이 커져, 그 확률을 올리는 데 “불균형하게 크고 유계가 아닌 가중치”를 준다.
두 수정의 차이는 샘플 분포다. k3+는 on-policy에서만 정확한 k2의 gradient를 쓴다. rollout당 minibatch 업데이트가 여러 번이거나 샘플러가 비동기면 샘플은 나 에서 오고 기댓값이 틀린 분포 아래에서 취해진다. V3.2의 추정량이 그에 강한 것은 importance ratio 덕분이다.
Where the KL goes: reward or loss
There is a second, independent issue. A KL “loss” summed per token, , is differentiated position by position as if the states were fixed. But 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,
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 , with .
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 , 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 rather than a fixed reference. Each iteration solves
whose solution is (derivation). Taking logs, satisfies for every response, including responses sampled from — so the condition can be fitted off-policy with a squared loss:
k1.5 replaces by the sample mean reward (which it equals as ). In the template the weight is the advantage minus a pull-back proportional to how far the response has already moved, : a soft quadratic trust region in place of a clip. Kimi K2 keeps this loss; K2.5 and K3 move it to tokens, , together with a log-ratio mask. The same squared form appears offline as Direct Reward Optimisation (Richemond et al. 2024), with and a learned value in place of .
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 the squared loss lands on to machine precision for every . With the fit is off by at and at . The Kimi review’s reading — “less mirror descent than mean-baseline REINFORCE plus an L2 penalty” at small — is what this shows.
Entropy: why it collapses
Write the policy at one state as a softmax over logits . Since , a small logit change changes the entropy by
For the policy gradient, the expected logit change is (natural gradient: ), so (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 : performance is bought with entropy, and the ceiling is reached at .
This one line explains every entropy-control method in use:
- Clip-higher. A low-probability token with positive advantage has a negative deviation and a positive , so it contributes positively to . 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 gives them back.
- Clip-Cov / KL-Cov (Cui et al.). Compute each token’s centred covariance ; Clip-Cov detaches the gradient of a random -fraction of tokens whose covariance lies in (, bounds 1 and 5); KL-Cov puts a KL penalty to the old policy on the top- fraction ( for 7B, for 32B, coefficient 1).
- Entropy bonus (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 and moves the clip upper bound : with , , ; 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.
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 “손실” 은 상태 가 고정된 것처럼 위치별로 미분된다. 그러나 는 이후 모든 상태의 분포, 따라서 이후 토큰의 KL도 바꾼다. Tang & Munos는 그래서 토큰 단위 KL 손실이 시퀀스 KL의 부분 미분일 뿐임을 보인다. 편향 없는 score-function 추정량은 누적형이다.
이것은 정확히 k1을 보상에 넣고 return으로 전파하는 방식(InstructGPT식 PPO, REINFORCE++)이 하는 일이다. GRPO는 편의상 KL을 손실로 옮겼다. reference 근처의 짧은 출력이면 차이가 작고, reference에서 먼 긴 추론 궤적이면 작지 않다. Ziegler et al.의 적응형 controller는 보상 안 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, 와 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 쪽으로 정규화한다. 매 iteration이 다음을 푼다.
해는 다(유도). log를 취하면 는 에서 샘플한 응답을 포함해 모든 응답에 대해 를 만족한다. 그래서 이 조건을 제곱 손실로 off-policy에서 맞출 수 있다.
k1.5는 를 샘플 평균 보상 로 바꾼다(에서 같아진다). 틀로 쓰면 가중치는 advantage에서 응답이 이미 움직인 만큼에 비례해 끌어당기는 항을 뺀 것, 다. clip 대신 부드러운 이차 trust region이다. Kimi K2는 이 손실을 유지하고, K2.5와 K3는 log-ratio mask와 함께 토큰 단위 로 옮긴다. 같은 제곱 꼴이 offline에서는 Direct Reward Optimisation(Richemond et al. 2024)으로 나타난다. 대신 학습한 가치 를 쓴 다.
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 를 쓰면 제곱 손실은 모든 에서 기계 정밀도로 에 내려앉는다. 을 쓰면 에서 , 에서 만큼 어긋난다. 작은 에서 “mirror descent라기보다 평균 baseline REINFORCE + L2 패널티”라는 Kimi 리뷰의 해석이 이것이다.
엔트로피: 왜 붕괴하나
한 상태의 정책을 logit 에 대한 softmax로 쓰자. 이므로 작은 logit 변화 가 엔트로피를 바꾸는 양은
Policy gradient에서 기대 logit 변화는 (natural gradient면 )이므로 다(Cui et al. 2025). 그럴듯한 토큰이 높은 advantage를, 드문 토큰이 낮은 advantage를 가질 때마다 엔트로피가 떨어진다. 보통의 학습이 바로 그렇다. Cui et al.은 RLVR 학습 내내 이 공분산이 대체로 양수로 머물러 엔트로피가 단조 감소함을 측정했고, 하류 성능을 로 맞췄다. 성능은 엔트로피를 주고 사며, 에서 천장에 닿는다.
이 한 줄이 쓰이고 있는 모든 엔트로피 제어를 설명한다.
- Clip-higher. 양의 advantage를 가진 확률 낮은 토큰은 편차가 음이고 가 양이라 에 양으로 기여한다. 바로 ratio가 가장 빨리 올라 PPO의 위쪽 clip에 먼저 걸리는 토큰이다(앞 레슨). 대칭 clip은 엔트로피를 올리는 업데이트를 골라서 지우고, 를 넓히면 돌려준다.
- Clip-Cov / KL-Cov(Cui et al.). 토큰마다 중심화한 공분산 를 계산한다. Clip-Cov는 공분산이 에 있는 토큰 중 무작위 비율의 gradient를 떼어 낸다(, 경계 1과 5). KL-Cov는 상위 비율에 old 정책으로의 KL 패널티를 건다(7B에서 , 32B에서 , 계수 1).
- 엔트로피 보너스 (A3C, PPO Eq. 9): 직접적이지만 쓸모없는 토큰을 포함해 모든 상태의 엔트로피를 똑같이 올린다. MAI는 엔트로피 보너스 손실이 자기 controller보다 나빴다고 보고한다.
- 엔트로피 controller. MAI-Thinking-1은 를 추정하고 clip 상한 를 로 움직인다(, , ). 보고서는 800 step 동안 엔트로피가 0.3 근처에 머문 것을 보인다. MiMo-V2.6은 양·음 advantage에 대한 별도 경계를 엔트로피로 조정한다(엔트로피가 낮으면 양의 band를 넓히고 음의 band를 좁힌다). GLM-4.5는 보상이 정체하면 샘플링 temperature를 올린다. 셋 다 추가 손실이 아니라 clip이나 샘플러를 쓴다.
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가 음수라서 그것을 내리면 엔트로피가 오른다. 부호를 뒤집으면 가장 큰 엔트로피 흡수원이 된다. 아래 그림이 전체 동역학을 돌린다.
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 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 (–) to about 0.90–0.91; a large bonus () 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:
| Method | Shaping | Notes |
|---|---|---|
| DAPO overlong shaping | up to , linear down to at , beyond | also: filter truncated samples |
| Kimi k1.5 length reward | within the group; if correct, if wrong | switched on after a warm-up; gives signal even in all-correct groups |
| Kimi K2 / K2.5 / K3 budgets | over-budget responses truncated and penalised (K2); budget = percentile of correct lengths, applied only to prompts with high accuracy (K2.5 Toggle); reward above (K3 effort levels) | effort levels as separate experts in K3 |
| MAI-Thinking-1 | with pass rate , (0 at the 128K stage) | penalises length more on easy prompts |
| MiMo-V2.6 | penalty only in groups whose pass rate exceeds a threshold, relative to a percentile of passing lengths | values undisclosed |
| DeepSeek-V3.2 / V4 | length penalty in the reward; reasoning-effort experts trained with different penalties and context windows | values 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 ), 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.
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
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 so that its gradient matches the template weight rather than growing with .
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 . k3+ uses the k2 gradient, which equals the reverse-KL gradient only under on-policy samples. has expectation as a function of θ whatever 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.
By the covariance formula, which update raises the policy's entropy?
. A low-probability token has below the mean; raising it () makes the covariance negative and 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 with a squared loss; in the template the weight is , a soft quadratic trust region (DRO’s offline form). Replacing by is exact only for large .
- Entropy changes by ; 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는 를 0.4에서 1.0으로 올리면 0.70–0.79로, controller와 장난감 Clip-Cov는 약 0.80–0.84로, 적당한 엔트로피 보너스(–)는 약 0.90–0.91로 올린다. 큰 보너스()는 엔트로피를 1.4 근처에 두고 보상이 약 0.68로 다시 떨어진다. 엔트로피는 목표가 아니라 수단이다. 맞는 양은 쓸모 있는 대안을 살려 두는 양이다.
길이: 보상 안의 정규화
길이 제어는 손실이 아니라 보상을 통해 거는 정규화다. 집계 레슨이 숨은 것 하나(sequence-mean은 긴 오답을 선호한다)를 보였다. 드러난 것들은 다음과 같다.
| 방법 | Shaping | 메모 |
|---|---|---|
| DAPO overlong shaping | 까지 , 에서 까지 선형 감소, 그 너머 | 잘린 샘플 걸러내기도 함께 |
| Kimi k1.5 길이 보상 | 그룹 안에서 ; 정답이면 , 오답이면 | warm-up 뒤에 켬; 모두 정답인 그룹에도 신호를 줌 |
| Kimi K2 / K2.5 / K3 budget | budget 초과 응답을 자르고 벌함(K2); budget = 정답 길이의 백분위수, 정답률이 높은 프롬프트에만(K2.5 Toggle); 를 넘으면 보상 (K3 effort 수준) | K3에서는 effort 수준이 별도 expert |
| MAI-Thinking-1 | 통과율 로 , (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하면 배치 크기가 흔들렸다.
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)에 달렸다.
구현
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는 로 나눠 gradient가 와 함께 커지지 않고 틀의 가중치 와 맞게 했다.
GRPO 실험이 rollout당 minibatch 업데이트 8번에 k3 KL 손실을 쓴다. 모든 minibatch에서 기대 KL gradient를 정확히 ∇KL(π_θ‖π_ref)로 만드는 변경은?
첫 minibatch 뒤의 샘플은 에서 온다. k3+는 on-policy 샘플에서만 reverse KL gradient와 같은 k2 gradient를 쓴다. 는 가 무엇이든 θ의 함수로서 기댓값이 이므로 gradient가 정확하다. 실험에서도 off-policy에서 오차가 0인 유일한 추정량이었다. k1은 on-policy 기대 gradient가 0이고, β를 낮추면 크기만 바뀐다.
공분산 식에 따르면 정책의 엔트로피를 올리는 업데이트는?
. 확률 낮은 토큰은 가 평균보다 낮다. 그것을 올리면() 공분산이 음이 되고 가 양이 된다. 나머지 두 업데이트는 공분산을 양으로 만들어 엔트로피를 내린다. 보통의 학습이 엔트로피를 내리는 이유이자, 확률 낮은 양의 업데이트를 지우는 것(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 를 제곱 손실로 맞춘다. 틀로 쓰면 가중치는 , 부드러운 이차 trust region이다(DRO의 offline 꼴). 를 로 바꾸는 것은 가 클 때만 정확하다.
- 엔트로피는 만큼 변하고, 보통의 학습은 그것을 낮춘다. 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
- Schulman, Approximating KL Divergence (blog, 2020) — k1·k2·k3 추정량의 원전.The original source of the k1, k2 and k3 estimators.
- Tang & Munos, On a few pitfalls in KL divergence gradient estimation for RL (2025) — KL 값 추정량을 손실로 미분하면 KL의 gradient가 아니다; 토큰 단위 KL 손실은 부분 미분일 뿐이다.Differentiating a KL value estimator is not the KL gradient; a token-level KL loss is only a partial derivative.
- DeepSeek-AI, DeepSeek-V3.2 (2025), §3.1 — ρ·k3, importance ratio로 보정한 편향 없는 KL 추정량.ρ·k3, the importance-corrected unbiased KL estimator.
- Kimi Team, Kimi k1.5: Scaling Reinforcement Learning with LLMs (2025), §2.3 — online mirror descent, 제곱 손실 surrogate, 길이 보상.Online mirror descent, the squared-loss surrogate, the length reward.
- Richemond et al., Offline Regularised Reinforcement Learning for Large Language Models Alignment (DRO, 2024) — ½(r − V − τ log π/π_ref)² 꼴의 제곱 손실을 쓰는 Direct Reward Optimisation.Direct Reward Optimisation, with a squared loss of the form ½(r − V − τ log π/π_ref)².
- Cui et al., The Entropy Mechanism of Reinforcement Learning for Reasoning Language Models (2025) — 엔트로피 변화 = −Cov(log π, logit 변화), R = −a·e^H + b, Clip-Cov와 KL-Cov.Entropy change = −Cov(log π, logit change), R = −a·e^H + b, Clip-Cov and KL-Cov.
- Ziegler et al., Fine-Tuning Language Models from Human Preferences (2019) — 목표 KL에 맞추는 적응형 β controller.The adaptive β controller that tracks a target KL.
- The Microsoft AI Team, MAI-Thinking-1: Building a Hill-Climbing Machine (2026) — clip 상한을 움직이는 엔트로피 controller(T1 Eq. 7–8)와 보상의 길이 항.An entropy controller that moves the clip upper bound (T1 Eqs. 7–8) and a length term in the reward.