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

Long-horizon RL — 긴 궤적의 credit, context 관리, 예산Long-horizon RL — credit, context management and budgets over long trajectories

수백 turn·수백만 토큰짜리 agent 궤적에서 무엇이 깨지는지 유도한다. 결과 보상의 turn당 SNR이 1/√K로 떨어지는 이유와 할인·process 보상·GiGPO·reverse curriculum이 각각 사는 것과 내주는 것, 정책이 관리된 context(접기·요약·discard-all·preserved thinking) 위에서 행동할 때 학습 샘플과 정규화가 어떻게 바뀌는지, 토큰·시간 예산과 끝나지 않은 궤적의 처리가 목적함수를 어떻게 바꾸는지를 그림과 코드로 확인한다.What breaks in agent trajectories of hundreds of turns and millions of tokens. Derive why the per-turn SNR of an outcome reward falls as 1/√K and what discounting, process rewards, GiGPO and reverse curricula buy and cost; how training samples and normalisation change when the policy acts on a managed context (folding, summaries, discard-all, preserved thinking); and how token and time budgets, and the handling of unfinished trajectories, change the objective — with figures and code.

The agent RL lesson set up the multi-turn trajectory, the loss mask over environment tokens and the outcome-vs-turn-reward choice on a three-turn example. Frontier agent RL in 2026 runs at a different scale. Kimi K3’s personal-assistant environment has rollouts with thousands of tool calls and millions of context tokens (K3 review); GLM-5.1 is described as sustaining “hundreds of rounds and thousands of tool calls” (GLM-5 review); QwenGyre trains on rollouts that last hours and reach about 1M tokens. At that scale three things that were harmless at K=3K=3 stop being harmless:

  1. Credit. One scalar at the end has to rank thousands of decisions. We derive how the gradient noise per decision grows with the horizon, and what each fix (turn rewards, discounting, step-level groups) buys and costs.
  2. Context. The trajectory no longer fits in the context window, so the policy acts on a managed context — folded, summarised or discarded. That changes what a training sample even is.
  3. Budgets and wall-clock. A rollout can outlive a training iteration and hit token, turn or time budgets. How you treat an unfinished trajectory quietly changes the objective.

The objective side (how tokens are weighted, clipped and regularised) is in the landscape, sequence vs token, clipping and IS and regularisation; the systems side of rollouts that span policy versions is in async and staleness. This lesson is about the horizon itself.

Credit over many turns

The noise of a broadcast outcome

Take an episode with KK turns. At turn kk the policy takes an action aka_k in context ckc_k; write sk=∇θlog⁡πθ(ak∣ck)s_k=\nabla_\theta\log\pi_\theta(a_k\mid c_k) for its score (summed over the tokens of the turn). With only an outcome reward RR and a baseline bb, GRPO-style training gives every turn the same advantage, so the gradient estimate for turn kk from one trajectory is

g^k=(R−b) sk,E[g^k]=E[R sk]=∇θkE[R]\hat g_k=(R-b)\,s_k,\qquad \mathbb E[\hat g_k]=\mathbb E[R\,s_k]=\nabla_{\theta_k}\mathbb E[R]

(the baseline drops out because E[sk]=0\mathbb E[s_k]=0). It is unbiased. Now suppose the outcome is built from KK roughly independent contributions, R=∑jcj(aj)+noiseR=\sum_j c_j(a_j)+\text{noise} with Var⁡cj=σc2\operatorname{Var}c_j=\sigma_c^2. Only ckc_k correlates with sks_k, so the mean is O(σc)O(\sigma_c) — it does not grow with KK. But the variance carries every other turn along:

Var⁡[g^k]≈E[(R−b)2] E[sk2]≈Kσc2 Ik⟹SNRk=∣Eg^k∣std⁡g^k ∝ 1K.\operatorname{Var}[\hat g_k]\approx\mathbb E\big[(R-b)^2\big]\,\mathbb E\big[s_k^2\big]\approx K\sigma_c^2\,I_k \quad\Longrightarrow\quad \text{SNR}_k=\frac{|\mathbb E\hat g_k|}{\operatorname{std}\hat g_k}\ \propto\ \frac{1}{\sqrt K}.

With a batch of NN trajectories the SNR is multiplied by N\sqrt N, so to keep the per-turn signal fixed, the number of trajectories must grow linearly with the number of turns. A binary success R=1[⋅]R=\mathbb 1[\cdot] gives the same law: Var⁡R≤14\operatorname{Var}R\le\tfrac14 is bounded, but each turn’s marginal effect on P(R=1)P(R=1) shrinks like 1/K1/\sqrt K. A 100-turn SWE episode broadcasting one bit is 100 times hungrier for samples, per decision, than a single-turn bandit.

Agent RL 레슨은 세 turn짜리 예로 멀티턴 trajectory, 환경 토큰의 loss mask, 결과 보상과 turn 보상 사이의 선택을 세웠다. 2026년의 frontier agent RL은 규모가 다르다. Kimi K3의 개인 비서 환경에는 tool 호출 수천 번, context 토큰 수백만 개짜리 rollout이 있고(K3 리뷰), GLM-5.1은 “수백 라운드, 수천 번의 tool 호출”을 버틴다고 소개된다(GLM-5 리뷰). QwenGyre는 몇 시간 동안 이어지고 약 1M 토큰에 이르는 rollout으로 학습한다. 이 규모에서는 K=3K=3일 때 무해했던 세 가지가 더는 무해하지 않다.

  1. Credit. 끝에 오는 스칼라 하나가 수천 개의 결정을 줄 세워야 한다. 결정 하나당 gradient 잡음이 horizon에 따라 어떻게 커지는지 유도하고, turn 보상·할인·step 단위 group 같은 처방이 각각 무엇을 얻고 무엇을 내주는지 본다.
  2. Context. trajectory가 context 창에 더는 들어가지 않으므로, 정책은 접히고 요약되고 버려진 관리된 context 위에서 행동한다. 학습 샘플이 무엇인지부터 달라진다.
  3. 예산과 wall-clock. rollout 하나가 학습 iteration보다 오래 살고, 토큰·turn·시간 예산에 걸린다. 끝나지 않은 trajectory를 어떻게 다루느냐가 목적함수를 조용히 바꾼다.

목적함수 쪽(토큰을 어떻게 가중하고 clip하고 정규화하는지)은 전체 지도, sequence vs token, clipping과 IS, 정규화에 있고, 여러 정책 버전에 걸친 rollout의 시스템 쪽은 비동기와 staleness에 있다. 이 레슨은 horizon 자체를 다룬다.

여러 turn에 걸친 credit

결과 보상을 뿌릴 때의 잡음

turn이 KK개인 에피소드를 보자. turn kk에서 정책은 context ckc_k에서 행동 aka_k를 고른다. 그 score를 sk=∇θlog⁡πθ(ak∣ck)s_k=\nabla_\theta\log\pi_\theta(a_k\mid c_k)로 쓴다(그 turn의 토큰에 대해 합한 값). 결과 보상 RR과 baseline bb만 있으면 GRPO식 학습은 모든 turn에 같은 advantage를 주므로, trajectory 하나에서 얻는 turn kk의 gradient 추정치는

g^k=(R−b) sk,E[g^k]=E[R sk]=∇θkE[R]\hat g_k=(R-b)\,s_k,\qquad \mathbb E[\hat g_k]=\mathbb E[R\,s_k]=\nabla_{\theta_k}\mathbb E[R]

이다(E[sk]=0\mathbb E[s_k]=0이므로 baseline은 빠진다). 불편(unbiased) 추정이다. 이제 결과가 서로 거의 독립인 KK개의 기여로 이루어진다고 하자. R=∑jcj(aj)+noiseR=\sum_j c_j(a_j)+\text{noise}, Var⁡cj=σc2\operatorname{Var}c_j=\sigma_c^2. sks_k와 상관이 있는 것은 ckc_k뿐이므로 평균은 O(σc)O(\sigma_c)이고 KK와 함께 커지지 않는다. 하지만 분산은 다른 모든 turn을 끌고 온다.

Var⁡[g^k]≈E[(R−b)2] E[sk2]≈Kσc2 Ik⟹SNRk=∣Eg^k∣std⁡g^k ∝ 1K.\operatorname{Var}[\hat g_k]\approx\mathbb E\big[(R-b)^2\big]\,\mathbb E\big[s_k^2\big]\approx K\sigma_c^2\,I_k \quad\Longrightarrow\quad \text{SNR}_k=\frac{|\mathbb E\hat g_k|}{\operatorname{std}\hat g_k}\ \propto\ \frac{1}{\sqrt K}.

trajectory NN개짜리 배치에서는 SNR에 N\sqrt N이 곱해진다. 따라서 turn당 신호를 일정하게 유지하려면 trajectory 수가 turn 수에 비례해 늘어야 한다. 이진 성공 보상 R=1[⋅]R=\mathbb 1[\cdot]도 같은 법칙을 따른다. Var⁡R≤14\operatorname{Var}R\le\tfrac14로 묶여 있지만, 각 turn이 P(R=1)P(R=1)에 주는 한계 효과가 1/K1/\sqrt K처럼 줄어든다. 비트 하나를 뿌리는 100 turn짜리 SWE 에피소드는 결정 하나당 single-turn bandit보다 샘플이 100배 더 필요하다.

turn 1 배치 SNRturn-1 batch SNR – 부호가 믿을 만한 turn (SNR>2)turns with a reliable sign (SNR>2) – "바쁜 행동"으로 샌 gradientgradient leaked into "busy" behaviour –
Left: for each turn k, the expected update on the decision that actually matters (blue bar, in units of the true outcome gradient of that turn) and the noise of one batch of N trajectories (whisker = ±1 standard error). Red bars are the update pushed into a behaviour the outcome does not care about. Right: batch SNR of turn 1 as the horizon grows, outcome-only (grey) vs the current setting (blue), with the 1/√K reference. Drag K up with ω = 0: the bars stay at 1 (unbiased) but the whiskers swallow them. Lower γ with ω = 0: early bars shrink but the whiskers shrink with them — the SNR does not move. Raise ω: dense rewards make every turn's sign reliable; then raise m and watch the red bars grow. 왼쪽: turn k마다, 실제로 결과를 바꾸는 결정에 들어가는 기대 업데이트(파란 막대, 그 turn의 참 outcome gradient를 1로 둔 단위)와 궤적 N개짜리 배치 한 번의 잡음(수염 = ±1 표준오차). 빨간 막대는 결과와 무관한 행동에 밀어 넣어지는 업데이트다. 오른쪽: horizon이 길어질 때 turn 1의 배치 SNR. 회색은 outcome만, 파랑은 현재 설정, 점선은 1/√K 기준선. ω = 0에서 K를 올리면 막대는 1(불편)에 그대로 있지만 수염이 막대를 삼킨다. ω = 0에서 γ를 낮추면 앞쪽 막대가 줄지만 수염도 같은 비율로 줄어 SNR은 그대로다. ω를 올리면 dense 보상 덕에 모든 turn의 부호가 믿을 만해지고, 이어서 m을 올리면 빨간 막대가 자란다.

Things to check in the figure.

  1. With ω = 0 (outcome only), drag K from 4 to 64. The blue bars stay at 1 — the estimate is unbiased at every turn — but the whiskers grow until the sign of most turns is a coin flip at N = 64. The right panel follows the dashed 1/K1/\sqrt K line.
  2. Raise N to 512: the whiskers shrink by 8\sqrt 8. That is the price of the horizon, paid in rollouts.
  3. Keep ω = 0 and lower γ to 0.7. Early bars become tiny, and so do their whiskers; the turn-1 SNR does not change. (Next section.)
  4. Raise ω to 0.5 with m = 0: every turn becomes reliable. Then raise m: the red bars — gradient pushed into a behaviour the outcome does not care about — grow, and at m ≈ 0.6 they are as large as the real signal.

What a turn discount does — and does not do

A discount looks like the textbook fix. With turn rewards rjr_j and a terminal RR, the reward-to-go of turn kk is

Gk=∑j≥kγ j−krj+γK−kR,g^k=(Gk−bk) sk.G_k=\sum_{j\ge k}\gamma^{\,j-k}r_j+\gamma^{K-k}R,\qquad \hat g_k=(G_k-b_k)\,s_k .

Two separate things happen here. Causality — dropping rjr_j for j<kj<k — is free variance reduction, because E[rjsk]=0\mathbb E[r_j s_k]=0 for past rewards. Discounting with γ<1\gamma<1 trades bias for variance only when there are intermediate rewards to cut off: the noise of rewards more than ∼1/(1−γ)\sim1/(1-\gamma) turns ahead is suppressed, and so is their real credit.

With a terminal-only reward, Gk=γK−kRG_k=\gamma^{K-k}R is a constant multiple of RR. Then

g^k(γ)=γK−k g^k(1)⟹SNRk(γ)=SNRk(1).\hat g_k^{(\gamma)}=\gamma^{K-k}\,\hat g_k^{(1)}\quad\Longrightarrow\quad \text{SNR}_k^{(\gamma)}=\text{SNR}_k^{(1)} .

A turn discount on an outcome-only agent reduces no noise. It is a per-turn learning-rate schedule that says early turns should move less — a statement about trust, not about variance. Since token-level γ<1\gamma<1 makes an outcome thousands of tokens away vanish (agent RL), the frontier recipes reviewed on this site all broadcast the outcome undiscounted to every model token (GLM-4.5/5 agentic RL, MAI’s agentic climb, Nemotron’s SWE teacher) and put the extra structure somewhere else.

Denser signal, and where it leaks

The figure’s process reward is rk=(1−m) ak+m uk+σpεkr_k=(1-m)\,a_k+m\,u_k+\sigma_p\varepsilon_k: part of it scores the decision that matters (aka_k), part scores a behaviour the policy also controls but the outcome ignores (uku_k). In general write any intermediate reward as rk=qk+ekr_k=q_k+e_k, where qkq_k is the part whose expectation agrees with the outcome’s credit and eke_k is everything else the policy can influence. Mixing it in with weight ω,

E[g^]=∇E[R]+ω ∇E[∑kqk]+ω ∇E[∑kek].\mathbb E[\hat g]=\nabla\mathbb E[R]+\omega\,\nabla\mathbb E\Big[\sum_k q_k\Big]+\omega\,\nabla\mathbb E\Big[\sum_k e_k\Big].

The second term is the help (local, low-variance credit). The third term is a new objective: the policy is now trained to produce whatever eke_k pays for — well-formed but pointless tool calls, verbose “progress”, busywork the grader likes. That is over-optimisation at the level of turns. What frontier reports actually use as intermediate signal is telling — mostly penalties for things that are unambiguously wrong, where ek≈0e_k\approx0 by construction:

ReportIntermediate signalShape
GLM-4.5 agentic RL (review)malformed tool callrollout stops, reward 0 (process format penalty)
GLM-4.5 function-calling RLstep reward 1[FormatCorrect(at)∧Match(at,at∗)]\mathbb 1[\text{FormatCorrect}(a_t)\wedge\text{Match}(a_t,a_t^\ast)]exact match to a gold call, so ek=0e_k=0
MiniMax-M2 (review)rt=αrtprocess+βrtspeed+rtperfr_t=\alpha r^{\text{process}}_t+\beta r^{\text{speed}}_t+r^{\text{perf}}_t, A^i,t=∑p≥trp−Bi\hat A_{i,t}=\sum_{p\ge t}r_p-B_iprocess = language mixing and call-format errors; speed = h(Tcompletion/Tbaseline)h(T_{\text{completion}}/T_{\text{baseline}}) among equally correct trajectories
Nemotron 3 Ultra SWE teacher (review)broken reasoning / tool-call tokensnegative advantage on those tokens; unfinished trajectories excluded
MAI agentic climb (review)nonethe whole trajectory graded, every token of every step the same credit

The most aggressive version of “penalise the unambiguous” is to filter rather than penalise. Two masks are the baseline here. Tool-output tokens never receive gradient: Search-R1 and ReTool mask retrieved and interpreter tokens, as derived in agent RL. And SimpleTIR (Xue et al., 2025) adds a trajectory filter on top. In multi-turn tool-integrated reasoning, the authors trace training collapse to distribution drift from tool feedback. The drift makes the policy produce low-probability tokens, it compounds over turns, and it ends in “catastrophic gradient norm explosions”. Their fix is to drop from the policy update every trajectory that contains a void turn, a turn that yields “neither a code block nor a final answer”. On Qwen2.5-7B this took AIME24 from a text-only baseline of 22.1 to 50.5. A void turn is an eke_k-free signal of a broken trajectory, so removing such trajectories costs no bias towards a judged notion of progress. It only removes the samples whose gradients are dominated by off-distribution tokens. The stability playbook lists it next to the other remedies for gradient-norm spikes.

Kimi k1.5 gives the opposite argument for staying coarse (review): a perfect value function would assign negative advantage to a step that contains an error, yet a trajectory that makes the error, notices it and recovers is exactly what long-horizon training should reinforce. Fine-grained credit can punish exploration.

Step-level groups without a critic: GiGPO

If you cannot trust a dense reward and do not want a learned critic, you can still find natural comparisons inside the group. Group-in-Group Policy Optimization (GiGPO, Feng et al., NeurIPS 2025) notices that agent trajectories for the same task often pass through the same environment state — the same web page, the same room in ALFWorld. Actions taken from the same anchor state s~\tilde s can be compared directly. With Rt(i)=∑k≥tγk−trk(i)R^{(i)}_t=\sum_{k\ge t}\gamma^{k-t}r^{(i)}_k,

AE(τi)=R(τi)−mean⁡jR(τj)Fnorm,AS(at(i))=Rt(i)−mean⁡{Rt′(j):st′(j)=s~}Fnorm,A=AE+ωAS,A^E(\tau_i)=\frac{R(\tau_i)-\operatorname{mean}_jR(\tau_j)}{F_{\text{norm}}},\qquad A^S\big(a^{(i)}_t\big)=\frac{R^{(i)}_t-\operatorname{mean}\{R^{(j)}_{t'}:s^{(j)}_{t'}=\tilde s\}}{F_{\text{norm}}},\qquad A=A^E+\omega A^S,

with γ=0.95\gamma=0.95 and ω=1\omega=1 in the paper, and FnormF_{\text{norm}} either the std or 1. The anchor groups are built retroactively by hashing states, so there are no extra rollouts. Reported gains over GRPO (Table 1, 3 seeds, without std normalisation): ALFWorld 72.8 → 86.1 and WebShop success 56.8 → 67.4 at Qwen2.5-1.5B; 77.6 → 90.2 and 66.1 → 75.2 at 7B. It works where states recur (text games, web navigation, structured tools); in open-ended coding, exact states rarely repeat and the micro groups collapse to singletons, where AS=0A^S=0.

Shortening the horizon with a demonstration: reverse curriculum

If the 1/K1/\sqrt K law is the problem, the most direct fix is to make KK small at first. Suppose you have one correct demonstration (x,a1⋆,…,aK⋆)(x,a^\star_1,\dots,a^\star_K). Start each episode from the demonstration’s prefix up to turn K−jK-j and let the policy act only for the last jj turns. The outcome is still the only reward, but now it ranks jj decisions, not KK, so the per-decision SNR is ∝1/j\propto1/\sqrt j. When the policy succeeds reliably from that start, slide it earlier (j←j+Δj\leftarrow j+\Delta). The idea goes back to Salimans and Chen’s Montezuma’s Revenge agent, trained from a single demonstration (2018). R³ (Xi et al., 2024) applies it to LLM reasoning, sliding “the start state of reasoning from a demonstration’s end to its beginning”. They report +4.1 points on average over an RL baseline on eight reasoning tasks with Llama2-7B, and +4.2 on program-based GSM8K across three backbones. The cost is the demonstrations. The benefit is that outcome-only RL gets step-wise credit without a critic or a process reward. In agent RL a “demonstration prefix” is a replayable environment state, so the method needs environments that can be restored to the state after turn K−jK-j. Sandboxes with snapshots and replayable tool logs can, and live web pages often cannot.

NumPy Per-turn SNR vs horizon, the discount, and a leaky process reward
import numpy as np
from math import erf, sqrt, comb

SIG_E = 0.5

def true_grad(K):
    """Exact dE[R]/dθ_k at p = 1/2 for R = 1[Σ(2a_j−1) + σ_e√K z > 0]."""
    Phi = lambda x: 0.5 * (1 + erf(x / sqrt(2)))
    n, s = K - 1, SIG_E * sqrt(K)
    w = [comb(n, b) / 2**n for b in range(n + 1)]
    p1 = sum(wb * Phi((2*b - n + 1) / s) for b, wb in enumerate(w))
    p0 = sum(wb * Phi((2*b - n - 1) / s) for b, wb in enumerate(w))
    return 0.25 * (p1 - p0)

def per_turn_estimates(K, M=20000, omega=0.0, sp=0.5, m=0.0, gamma=1.0, seed=0):
    """Score-function estimates ĝ_k = (G_k − b_k)(a_k − ½) for M trajectories.
    a_k: decision that matters, u_k: 'busy' behaviour the outcome ignores."""
    rng = np.random.default_rng(seed)                            # same draws for every setting
    a = (rng.random((M, K)) < 0.5).astype(float)
    u = (rng.random((M, K)) < 0.5).astype(float)
    R = ((2*a - 1).sum(1) + SIG_E * np.sqrt(K) * rng.standard_normal(M) > 0).astype(float)
    r = (1 - m) * a + m * u + sp * rng.standard_normal((M, K))   # process reward
    G = np.zeros((M, K)); g = R.copy()
    for k in reversed(range(K)):                                 # reward-to-go
        g = omega * r[:, k] + (R if k == K - 1 else gamma * g)
        G[:, k] = g
    adv = G - G.mean(0)                                          # per-turn baseline
    return adv * (a - 0.5), adv * (u - 0.5)

N = 64   # trajectories per batch
print("outcome reward only: turn-1 estimate vs horizon K   (batch N = 64)")
print("   K   E[ĝ]/true   batch SNR   SNR·√K")
for K in [1, 2, 4, 8, 16, 32, 64]:
    gt, _ = per_turn_estimates(K)
    mean, std = gt[:, 0].mean(), gt[:, 0].std()
    snr = mean / (std / np.sqrt(N))
    print(f"{K:4d}   {mean/true_grad(K):8.3f}   {snr:9.2f}   {snr*np.sqrt(K):6.2f}")

K = 32
print(f"\nK={K}, terminal-only reward: does a per-turn discount γ reduce noise for turn 1?")
for gamma in [1.0, 0.9, 0.7]:
    gt, _ = per_turn_estimates(K, gamma=gamma)
    mean, std = gt[:, 0].mean(), gt[:, 0].std()
    print(f"  γ={gamma}:  E[ĝ_1] / (γ^(K-1)·true) = {mean/(gamma**(K-1)*true_grad(K)):.3f}"
          f"   batch SNR = {mean/(std/np.sqrt(N)):.3f}")

print(f"\nK={K}, add a dense process reward (ω = 0.5, σ_p = 0.5, γ = 0.9)")
for m in [0.0, 0.3, 0.6]:
    gt, gu = per_turn_estimates(K, omega=0.5, m=m, gamma=0.9)
    snr = np.abs(gt.mean(0)) / (gt.std(0) / np.sqrt(N))
    leak = np.abs(gu.mean(0)).sum() / np.abs(gt.mean(0)).sum()
    print(f"  m={m}:  median per-turn SNR {np.median(snr):5.2f}   turns with SNR>2: {int((snr > 2).sum())}/{K}"
          f"   leaked into 'busy' u: {leak:.0%}")
 

The first table is the 1/K1/\sqrt K law: SNR⋅K\text{SNR}\cdot\sqrt K is flat from K=2K=2 on (K=1K=1 is a bandit where the single decision nearly fixes the outcome). The second confirms that with the same random draws, a terminal-only discount rescales the estimate by exactly γK−1\gamma^{K-1} and leaves the SNR identical to three decimals. The third shows the trade: a moderately noisy process reward makes all 32 turns reliable at N=64N=64, but once 30% of it pays for the irrelevant behaviour, 39% as much gradient goes into that behaviour as into the real one.

Next, GiGPO’s two-level advantage on a toy corridor where states recur.

NumPy GiGPO: episode advantage + anchor-state step advantage
import numpy as np
from collections import defaultdict

# Corridor: states 0..5, start 0, goal 5. Actions: +1 (forward) or -1 (back, floored at 0).
# Sparse outcome: R = 1 if the goal is reached within T_MAX steps, else 0. No step rewards.
T_MAX, GOAL, N, GAMMA, OMEGA = 12, 5, 16, 0.95, 1.0
rng = np.random.default_rng(2)

def rollout(p_fwd=0.65):
    s, steps = 0, []
    for _ in range(T_MAX):
        a = +1 if rng.random() < p_fwd else -1
        steps.append((s, a))
        s = min(GOAL, max(0, s + a))
        if s == GOAL:
            return steps, 1.0
    return steps, 0.0

trajs = [rollout() for _ in range(N)]
R = np.array([r for _, r in trajs])
A_E = (R - R.mean()) / (R.std() + 1e-8)          # episode-level (macro) advantage, GRPO-style

# step-level (micro): discounted return of each step, grouped by the anchor state it acted from
rows = []                                          # (traj i, step t, state, action, R_t)
for i, (steps, r) in enumerate(trajs):
    T = len(steps)
    for t, (s, a) in enumerate(steps):
        rows.append((i, t, s, a, GAMMA ** (T - 1 - t) * r))
groups = defaultdict(list)
for j, row in enumerate(rows):
    groups[row[2]].append(j)
A_S = np.zeros(len(rows))
for s, idx in groups.items():
    Rt = np.array([rows[j][4] for j in idx])
    A_S[idx] = (Rt - Rt.mean()) / (Rt.std() if Rt.std() > 1e-8 else 1.0)
    assert abs(A_S[idx].sum()) < 1e-9              # zero-mean inside every anchor group

print("successes:", int(R.sum()), "/", N, "  A^E =", np.round(np.unique(A_E), 2))
print("anchor groups {state: #steps}:", {s: len(v) for s, v in sorted(groups.items())})
print("check: micro advantages sum to 0 in every anchor group ✓\n")

A = np.array([A_E[i] for i, *_ in rows]) + OMEGA * A_S
act = np.array([a for *_, a, _ in rows]); ok = np.array([R[i] for i, *_ in rows]) == 1
print("mean advantage per step        forward(+1)   back(-1)")
for name, adv in [("A^E only (GRPO)", np.array([A_E[i] for i, *_ in rows])), ("A^S (anchor groups)", A_S), ("A^E + ω·A^S (GiGPO)", A)]:
    for sub, msk in [("failed eps", ~ok), ("successful eps", ok)]:
        print(f"  {name:20s} {sub:15s} {adv[msk & (act == 1)].mean():+8.3f}   {adv[msk & (act == -1)].mean():+8.3f}")
 

With a terminal-only reward, AEA^E cannot tell a forward step from a backward one inside the same episode. The anchor-state advantage can, through two channels only: different outcomes from the same state, and the discount (from the same state, the shorter path to success gets the larger γT−1−tR\gamma^{T-1-t}R). Here the separation is modest (+0.95 vs +0.78 in successful episodes) — an honest picture of how much a sparse reward can tell you even when you compare like with like.

확인 문제Check yourself

A 40-turn coding agent is trained with GRPO on a single pass/fail reward. A colleague proposes a per-turn discount γ = 0.9 'to reduce the variance for early turns'. What actually happens?

With a terminal-only reward the reward-to-go of turn kk is γK−kR\gamma^{K-k}R, a constant multiple of RR. Mean and standard deviation of g^k\hat g_k are both multiplied by γK−k\gamma^{K-k}, so the SNR is unchanged. The proposal is a per-turn learning-rate schedule. To actually reduce the noise you need information that separates turns: intermediate rewards (cut off by γ\gamma), step-level comparisons such as GiGPO’s anchor groups, or more trajectories.

The policy acts on a managed context

A context function, not a trajectory

Once a trajectory is longer than the window, the policy no longer conditions on the history hk=(x,a1,o1,…,ok−1)h_k=(x,a_1,o_1,\dots,o_{k-1}) but on a context produced by the harness:

ck=C(hk),Pθ(τ)=∏kπθ(ak∣ck) Penv(ok∣hk,ak),∇θlog⁡Pθ(τ)=∑k∇θlog⁡πθ(ak∣ck).c_k=\mathcal C(h_k),\qquad P_\theta(\tau)=\prod_k\pi_\theta(a_k\mid c_k)\,P_{\text{env}}(o_k\mid h_k,a_k),\qquad \nabla_\theta\log P_\theta(\tau)=\sum_k\nabla_\theta\log\pi_\theta(a_k\mid c_k).

The derivation of agent RL goes through unchanged as long as C\mathcal C does not depend on θ\theta: then C\mathcal C is just part of the environment’s transition. MiniMax-M2 states the same thing as its modelling choice: everything outside the LLM’s generation — context management, memory, sub-agent calls — lives in st+1=ftrans(st,at,ot)s_{t+1}=f_{\text{trans}}(s_t,a_t,o_t), and the training unit is each (st,at)(s_t,a_t) pair (review). Agent Lightning (Luo et al., 2025) builds a framework on the same idea. The trainer exposes “an OpenAI-like API” endpoint per task, and an unmodified agent (LangChain, OpenAI Agents SDK, AutoGen or custom code) calls it as its LLM. Each LLM call is recorded as a transition (the input the call actually saw, the output, a reward). Its LightningRL algorithm, in the current implementation, “simply assumes each action within the episode has the same value, equal to the final return”. Whatever the harness does to the context between calls is then, by construction, part of C\mathcal C. Three practical consequences follow.

  • Log-probs must be computed on ckc_k, the context the sampler actually saw — not on the original history. Training on hkh_k is learning a different conditional distribution.
  • If the policy writes the summary, the summary is an action. AutoCompact puts a compact() call into the action space; the summary tokens are trained like any other model tokens, and the decision when to compact is learned (SWE-bench Verified 30.4 → 39.6 for Qwen3-Coder-30B-A3B after SFT → GRPO, above a fixed 16K compaction at 28.8; most of the gain came from the RL stage).
  • A rewrite ends a training sequence. Each maximal append-only run of contexts is one sequence for the trainer. A trajectory with nn rewrites becomes n+1n+1 sequences that must share one advantage — AutoCompact splits at every point where the context is rewritten and gives all segments the same advantage, and QwenGyre normalises per run over its (at most five) leaf paths.

The last point has a sharp edge. If the loss is averaged over sequences, a trajectory split into nn segments gets nn times the weight of one that was never rewritten — and rewrites happen precisely in long trajectories. The NumPy block below shows the net push flipping sign from 0 to +0.56 in a balanced group.

Reasoning across turns

What happens to the model’s own reasoning between turns is a context policy too, and the labs have been moving in one direction.

ModelRule for earlier reasoning
DeepSeek-R1discarded whenever the next message arrives
DeepSeek-V3.2kept while only tool messages are appended; discarded at a new user message; tool calls and results always kept
DeepSeek-V4in conversations that call tools, kept even across user turns (interleaved thinking); still discarded in plain chat
GLM-5interleaved thinking, preserved thinking in coding-agent settings (all thinking blocks kept across turns), turn-level switch; GLM-5.3 makes clear_thinking=false the default

Whether to think at all is also part of the context. Qwen3’s thinking-mode fusion trains one model on both modes, switched by /think and /no_think flags in the prompt. Non-thinking samples keep an empty think block, so both modes share one template (Qwen3 review). GLM-5’s turn-level switch is the same idea applied per turn.

Two reasons drive this. Behaviourally, discarding reasoning at every tool call forces the model to rethink the problem from scratch at every call (V3.2’s argument). Computationally, a context that only grows keeps the previous call’s whole sequence as a prefix, so the KV cache is reusable (GLM-5). The flip side is a train–deploy coupling: V3.2 notes that frameworks emulating tool interaction with user messages (Terminus, Roo Code) discard reasoning every time and lose the benefit — its Terminal Bench 2.0 thinking score of 46.4 was measured under Claude Code, while under Terminus the report uses non-thinking mode (39.3). The context policy used in RL is part of the policy you ship. Kimi K3 goes further and swaps whole harnesses — tool interfaces, system prompts, context management, sub-agents — per task group so the policy does not overfit to one (review).

Observation policies

For tool outputs, the published policies are few and simple:

PolicyRuleReported effect
Summary (V3.2)at 80% of the window, summarise the overflowing trajectory and restartBrowseComp 51.4 → up to 60.2, stretching to ~364 steps on average
Discard-all (V3.2)at 80%, drop the entire tool-call historyBrowseComp → 67.6, matching parallel scaling with far fewer steps
Keep-recent-k (GLM-5)fold observations older than the last kk roundsk=5k=5: BrowseComp 55.3 → 62.0
Hierarchical (GLM-5 HCM)keep-recent-k, and discard-all once the context still exceeds T=32T=32Kup to 75.9 with a growing step budget
Learned (AutoCompact)the policy calls compact() and writes the statesee above

Nemotron 3 Ultra’s search teacher is trained with discard-all context management (review), and GLM-5 reports BrowseComp accuracy degrading beyond about 100K tokens — the simplest policies win partly because long contexts hurt. What the tables do not show is the cost structure, which differs a lot between policies and matters twice in RL: once at rollout (decode attention, prefill, KV reuse) and once at training (how many sequences, how many tokens forwarded).

그림에서 확인할 것.

  1. ω = 0(결과 보상만)에서 K를 4에서 64로 끌어 보자. 파란 막대는 1에 머문다. 모든 turn에서 추정이 불편이라는 뜻이다. 하지만 수염이 자라서 N = 64에서는 대부분 turn의 부호가 동전 던지기가 된다. 오른쪽 그림은 점선 1/K1/\sqrt K를 따라간다.
  2. N을 512로 올리면 수염이 8\sqrt 8배 줄어든다. horizon의 값을 rollout으로 치르는 셈이다.
  3. ω = 0인 채로 γ를 0.7로 내려 보자. 앞쪽 막대가 아주 작아지지만 수염도 같이 작아진다. turn 1의 SNR은 그대로다(다음 절).
  4. m = 0에서 ω를 0.5로 올리면 모든 turn이 믿을 만해진다. 이어서 m을 올리면, 결과와 무관한 행동에 밀어 넣어지는 gradient인 빨간 막대가 자라고, m ≈ 0.6에서 진짜 신호만큼 커진다.

turn 할인이 하는 일과 하지 않는 일

할인은 교과서적인 처방처럼 보인다. turn 보상 rjr_j와 끝 보상 RR이 있을 때 turn kk의 reward-to-go는

Gk=∑j≥kγ j−krj+γK−kR,g^k=(Gk−bk) skG_k=\sum_{j\ge k}\gamma^{\,j-k}r_j+\gamma^{K-k}R,\qquad \hat g_k=(G_k-b_k)\,s_k

이다. 여기서는 두 가지가 따로 일어난다. 인과성, 곧 j<kj<k인 rjr_j를 빼는 것은 공짜 분산 감소다. 과거 보상은 E[rjsk]=0\mathbb E[r_j s_k]=0이기 때문이다. γ<1\gamma<1인 할인은 잘라 낼 중간 보상이 있을 때만 bias와 분산을 맞바꾼다. 약 1/(1−γ)1/(1-\gamma) turn보다 먼 보상의 잡음이 억제되고, 그 보상의 진짜 credit도 함께 억제된다.

끝 보상만 있으면 Gk=γK−kRG_k=\gamma^{K-k}R은 RR의 상수배다. 그러면

g^k(γ)=γK−k g^k(1)⟹SNRk(γ)=SNRk(1)\hat g_k^{(\gamma)}=\gamma^{K-k}\,\hat g_k^{(1)}\quad\Longrightarrow\quad \text{SNR}_k^{(\gamma)}=\text{SNR}_k^{(1)}

이다. 결과 보상만 쓰는 agent에 turn 할인을 걸면 잡음은 하나도 줄지 않는다. “앞쪽 turn은 덜 움직여라”라는 turn별 학습률 스케줄일 뿐이다. 분산이 아니라 신뢰에 대한 진술이다. 토큰 단위 γ<1\gamma<1은 수천 토큰 뒤의 결과를 사라지게 만들기 때문에(agent RL), 이 사이트에서 리뷰한 frontier 레시피들은 모두 결과를 할인 없이 모든 모델 토큰에 뿌리고(GLM-4.5/5 agentic RL, MAI의 agentic climb, Nemotron의 SWE teacher) 추가 구조는 다른 곳에 넣는다.

더 dense한 신호, 그리고 새는 곳

그림의 process 보상은 rk=(1−m) ak+m uk+σpεkr_k=(1-m)\,a_k+m\,u_k+\sigma_p\varepsilon_k다. 일부는 결과를 바꾸는 결정(aka_k)을 채점하고, 일부는 정책이 마찬가지로 조절할 수 있지만 결과는 신경 쓰지 않는 행동(uku_k)을 채점한다. 일반적으로 중간 보상을 rk=qk+ekr_k=q_k+e_k로 쓰자. qkq_k는 기댓값이 결과의 credit과 일치하는 부분이고, eke_k는 정책이 영향을 줄 수 있는 나머지 전부다. 가중치 ω로 섞으면

E[g^]=∇E[R]+ω ∇E[∑kqk]+ω ∇E[∑kek]\mathbb E[\hat g]=\nabla\mathbb E[R]+\omega\,\nabla\mathbb E\Big[\sum_k q_k\Big]+\omega\,\nabla\mathbb E\Big[\sum_k e_k\Big]

이다. 둘째 항이 도움(국소적이고 분산이 낮은 credit)이다. 셋째 항은 새 목적함수다. 정책은 이제 eke_k가 돈을 주는 것은 무엇이든 만들도록 학습된다. 형식은 맞지만 쓸모없는 tool 호출, 장황한 “진행 상황”, 채점기가 좋아하는 바쁜 일. turn 수준의 과최적화다. frontier 보고서가 실제로 중간 신호로 쓰는 것을 보면 의미심장하다. 대부분 틀린 것이 명백한 것에 대한 벌점이고, 구성상 ek≈0e_k\approx0이다.

보고서중간 신호형태
GLM-4.5 agentic RL (리뷰)형식이 깨진 tool 호출rollout을 거기서 멈추고 보상 0 (process format penalty)
GLM-4.5 function-calling RLstep 보상 1[FormatCorrect(at)∧Match(at,at∗)]\mathbb 1[\text{FormatCorrect}(a_t)\wedge\text{Match}(a_t,a_t^\ast)]정답 호출과 정확히 일치해야 하므로 ek=0e_k=0
MiniMax-M2 (리뷰)rt=αrtprocess+βrtspeed+rtperfr_t=\alpha r^{\text{process}}_t+\beta r^{\text{speed}}_t+r^{\text{perf}}_t, A^i,t=∑p≥trp−Bi\hat A_{i,t}=\sum_{p\ge t}r_p-B_iprocess = 언어 섞임과 호출 형식 오류, speed = 똑같이 맞은 trajectory 사이에서 h(Tcompletion/Tbaseline)h(T_{\text{completion}}/T_{\text{baseline}})
Nemotron 3 Ultra SWE teacher (리뷰)깨진 추론·tool 호출 토큰그 토큰에 음의 advantage, 끝나지 않은 trajectory는 제외
MAI agentic climb (리뷰)없음trajectory 전체를 채점하고 모든 step의 모든 토큰에 같은 credit

“명백한 것만 벌한다”의 가장 공격적인 형태는 벌점 대신 걸러 내기다. 기본이 되는 mask는 두 가지다. 하나는 tool 출력 토큰이 결코 gradient를 받지 않게 하는 것이다(Search-R1과 ReTool은 검색 결과와 interpreter 토큰을 mask한다. 유도는 agent RL). 다른 하나로 SimpleTIR(Xue et al., 2025)는 그 위에 trajectory 필터를 더한다. 멀티턴 tool-integrated reasoning에서 저자들은 학습 붕괴의 원인을 tool 피드백이 만드는 분포 이동으로 짚는다. 이 이동 때문에 정책이 확률 낮은 토큰을 내고, 그것이 turn을 거치며 누적되어 “파국적인 gradient norm 폭발”로 끝난다. 처방은 void turn, 곧 “코드 블록도 최종 답도 내지 않는” turn을 포함한 trajectory를 모두 정책 업데이트에서 빼는 것이다. Qwen2.5-7B에서 AIME24가 텍스트 전용 기준선 22.1에서 50.5로 올랐다. void turn은 eke_k가 없는 “망가진 trajectory” 신호다. 그래서 이 trajectory들을 빼도 판정된 진척 쪽으로 편향이 생기지 않고, 분포 밖 토큰이 gradient를 지배하는 샘플만 사라진다. 안정성 플레이북에 gradient norm 스파이크의 다른 처방들과 함께 정리되어 있다.

Kimi k1.5는 반대로 거칠게 두는 쪽의 논거를 댄다(리뷰). 완벽한 가치함수라면 오류를 포함한 step에 음의 advantage를 줄 것이다. 그런데 오류를 저지르고, 알아채고, 회복하는 trajectory야말로 long-horizon 학습이 강화해야 할 것이다. 세밀한 credit이 탐색을 벌할 수 있다.

critic 없는 step 단위 group: GiGPO

dense 보상을 믿을 수 없고 학습된 critic도 원치 않는다면, group 안에서 자연스러운 비교 대상을 찾을 수 있다. Group-in-Group Policy Optimization(GiGPO, Feng et al., NeurIPS 2025)은 같은 과제의 agent trajectory들이 종종 같은 환경 상태(같은 웹 페이지, ALFWorld의 같은 방)를 지난다는 점에 주목한다. 같은 anchor 상태 s~\tilde s에서 내린 행동끼리는 직접 비교할 수 있다. Rt(i)=∑k≥tγk−trk(i)R^{(i)}_t=\sum_{k\ge t}\gamma^{k-t}r^{(i)}_k라 하면

AE(τi)=R(τi)−mean⁡jR(τj)Fnorm,AS(at(i))=Rt(i)−mean⁡{Rt′(j):st′(j)=s~}Fnorm,A=AE+ωASA^E(\tau_i)=\frac{R(\tau_i)-\operatorname{mean}_jR(\tau_j)}{F_{\text{norm}}},\qquad A^S\big(a^{(i)}_t\big)=\frac{R^{(i)}_t-\operatorname{mean}\{R^{(j)}_{t'}:s^{(j)}_{t'}=\tilde s\}}{F_{\text{norm}}},\qquad A=A^E+\omega A^S

이고, 논문은 γ=0.95\gamma=0.95, ω=1\omega=1을 쓰며 FnormF_{\text{norm}}은 std이거나 1이다. anchor group은 상태를 hash해서 사후에 만들므로 rollout이 추가로 들지 않는다. GRPO 대비 보고된 개선(Table 1, seed 3개, std 정규화 없음): Qwen2.5-1.5B에서 ALFWorld 72.8 → 86.1, WebShop 성공률 56.8 → 67.4, 7B에서 77.6 → 90.2, 66.1 → 75.2. 상태가 반복되는 곳(텍스트 게임, 웹 탐색, 구조화된 tool)에서 통한다. 열린 코딩 과제에서는 정확히 같은 상태가 거의 반복되지 않아 micro group이 원소 하나짜리가 되고, 그러면 AS=0A^S=0이다.

시연으로 horizon 줄이기: reverse curriculum

1/K1/\sqrt K 법칙이 문제라면 가장 직접적인 처방은 처음에 KK를 작게 만드는 것이다. 올바른 시연 (x,a1⋆,…,aK⋆)(x,a^\star_1,\dots,a^\star_K)이 하나 있다고 하자. 각 에피소드를 시연의 turn K−jK-j까지의 prefix에서 시작하고, 정책은 마지막 jj turn만 행동하게 한다. 보상은 여전히 결과뿐이지만, 이제 KK개가 아니라 jj개의 결정을 줄 세우므로 결정당 SNR은 ∝1/j\propto1/\sqrt j다. 그 시작점에서 정책이 안정적으로 성공하면 시작점을 앞으로 당긴다(j←j+Δj\leftarrow j+\Delta). 이 아이디어는 시연 하나로 Montezuma’s Revenge를 학습한 Salimans와 Chen(2018)으로 거슬러 올라간다. R³(Xi et al., 2024)는 이를 LLM 추론에 옮겨 “추론의 시작 상태를 시연의 끝에서 처음 쪽으로 밀어 간다”. Llama2-7B에서 추론 과제 8개 평균으로 RL 기준선보다 4.1점, 프로그램 기반 GSM8K에서 backbone 세 개에 걸쳐 4.2점 높다고 보고한다. 비용은 시연이고, 이득은 결과 보상만 쓰는 RL이 critic도 process 보상도 없이 step 단위 credit을 얻는다는 점이다. agent RL에서 “시연 prefix”는 다시 재생할 수 있는 환경 상태라서, turn K−jK-j 직후 상태로 되돌릴 수 있는 환경이 있어야 한다. snapshot을 갖춘 sandbox나 재생 가능한 tool 로그는 되고, 실시간 웹 페이지는 대개 안 된다.

NumPy horizon에 따른 turn별 SNR, 할인, 새는 process 보상
import numpy as np
from math import erf, sqrt, comb

SIG_E = 0.5

def true_grad(K):
    """R = 1[Σ(2a_j−1) + σ_e√K z > 0]일 때 p = 1/2에서의 정확한 dE[R]/dθ_k."""
    Phi = lambda x: 0.5 * (1 + erf(x / sqrt(2)))
    n, s = K - 1, SIG_E * sqrt(K)
    w = [comb(n, b) / 2**n for b in range(n + 1)]
    p1 = sum(wb * Phi((2*b - n + 1) / s) for b, wb in enumerate(w))
    p0 = sum(wb * Phi((2*b - n - 1) / s) for b, wb in enumerate(w))
    return 0.25 * (p1 - p0)

def per_turn_estimates(K, M=20000, omega=0.0, sp=0.5, m=0.0, gamma=1.0, seed=0):
    """trajectory M개에 대한 score-function 추정치 ĝ_k = (G_k − b_k)(a_k − ½).
    a_k: 결과를 바꾸는 결정, u_k: 결과와 무관한 '바쁜' 행동."""
    rng = np.random.default_rng(seed)                            # 모든 설정에서 같은 난수
    a = (rng.random((M, K)) < 0.5).astype(float)
    u = (rng.random((M, K)) < 0.5).astype(float)
    R = ((2*a - 1).sum(1) + SIG_E * np.sqrt(K) * rng.standard_normal(M) > 0).astype(float)
    r = (1 - m) * a + m * u + sp * rng.standard_normal((M, K))   # process 보상
    G = np.zeros((M, K)); g = R.copy()
    for k in reversed(range(K)):                                 # reward-to-go
        g = omega * r[:, k] + (R if k == K - 1 else gamma * g)
        G[:, k] = g
    adv = G - G.mean(0)                                          # turn별 baseline
    return adv * (a - 0.5), adv * (u - 0.5)

N = 64   # 배치당 trajectory 수
print("결과 보상만: horizon K에 따른 turn 1 추정치   (배치 N = 64)")
print("   K   E[ĝ]/참값   배치 SNR    SNR·√K")
for K in [1, 2, 4, 8, 16, 32, 64]:
    gt, _ = per_turn_estimates(K)
    mean, std = gt[:, 0].mean(), gt[:, 0].std()
    snr = mean / (std / np.sqrt(N))
    print(f"{K:4d}   {mean/true_grad(K):8.3f}   {snr:9.2f}   {snr*np.sqrt(K):6.2f}")

K = 32
print(f"\nK={K}, 끝 보상만 있을 때: turn 할인 γ가 turn 1의 잡음을 줄이는가?")
for gamma in [1.0, 0.9, 0.7]:
    gt, _ = per_turn_estimates(K, gamma=gamma)
    mean, std = gt[:, 0].mean(), gt[:, 0].std()
    print(f"  γ={gamma}:  E[ĝ_1] / (γ^(K-1)·참값) = {mean/(gamma**(K-1)*true_grad(K)):.3f}"
          f"   배치 SNR = {mean/(std/np.sqrt(N)):.3f}")

print(f"\nK={K}, dense process 보상 추가 (ω = 0.5, σ_p = 0.5, γ = 0.9)")
for m in [0.0, 0.3, 0.6]:
    gt, gu = per_turn_estimates(K, omega=0.5, m=m, gamma=0.9)
    snr = np.abs(gt.mean(0)) / (gt.std(0) / np.sqrt(N))
    leak = np.abs(gu.mean(0)).sum() / np.abs(gt.mean(0)).sum()
    print(f"  m={m}:  turn별 SNR 중앙값 {np.median(snr):5.2f}   SNR>2인 turn: {int((snr > 2).sum())}/{K}"
          f"   '바쁜' u로 샌 몫: {leak:.0%}")
 

첫 표가 1/K1/\sqrt K 법칙이다. K=2K=2부터 SNR⋅K\text{SNR}\cdot\sqrt K가 평평하다(K=1K=1은 결정 하나가 결과를 거의 정하는 bandit이다). 둘째 표는 같은 난수를 쓸 때 끝 보상에 건 할인이 추정치를 정확히 γK−1\gamma^{K-1}배 할 뿐이고 SNR은 소수점 셋째 자리까지 같음을 확인한다. 셋째 표는 맞바꿈을 보여 준다. 적당히 잡음 섞인 process 보상이 N=64에서 32개 turn을 모두 믿을 만하게 만들지만, 그 보상의 30%가 무관한 행동에 돈을 주는 순간 진짜 행동의 39%만큼의 gradient가 그 행동으로 들어간다.

다음은 상태가 반복되는 장난감 복도에서 GiGPO의 두 단계 advantage다.

NumPy GiGPO: 에피소드 advantage + anchor 상태 step advantage
import numpy as np
from collections import defaultdict

# 복도: 상태 0..5, 시작 0, 목표 5. 행동: +1(전진) 또는 -1(후진, 0 아래로는 못 감).
# 희소한 결과 보상: T_MAX step 안에 목표에 닿으면 R = 1, 아니면 0. step 보상은 없다.
T_MAX, GOAL, N, GAMMA, OMEGA = 12, 5, 16, 0.95, 1.0
rng = np.random.default_rng(2)

def rollout(p_fwd=0.65):
    s, steps = 0, []
    for _ in range(T_MAX):
        a = +1 if rng.random() < p_fwd else -1
        steps.append((s, a))
        s = min(GOAL, max(0, s + a))
        if s == GOAL:
            return steps, 1.0
    return steps, 0.0

trajs = [rollout() for _ in range(N)]
R = np.array([r for _, r in trajs])
A_E = (R - R.mean()) / (R.std() + 1e-8)          # 에피소드 단위(macro) advantage, GRPO식

# step 단위(micro): 각 step의 할인 return을, 그 step이 행동한 anchor 상태별로 묶는다
rows = []                                          # (traj i, step t, state, action, R_t)
for i, (steps, r) in enumerate(trajs):
    T = len(steps)
    for t, (s, a) in enumerate(steps):
        rows.append((i, t, s, a, GAMMA ** (T - 1 - t) * r))
groups = defaultdict(list)
for j, row in enumerate(rows):
    groups[row[2]].append(j)
A_S = np.zeros(len(rows))
for s, idx in groups.items():
    Rt = np.array([rows[j][4] for j in idx])
    A_S[idx] = (Rt - Rt.mean()) / (Rt.std() if Rt.std() > 1e-8 else 1.0)
    assert abs(A_S[idx].sum()) < 1e-9              # anchor group마다 평균 0

print("성공:", int(R.sum()), "/", N, "  A^E =", np.round(np.unique(A_E), 2))
print("anchor group {상태: step 수}:", {s: len(v) for s, v in sorted(groups.items())})
print("확인: 모든 anchor group에서 micro advantage의 합이 0 ✓\n")

A = np.array([A_E[i] for i, *_ in rows]) + OMEGA * A_S
act = np.array([a for *_, a, _ in rows]); ok = np.array([R[i] for i, *_ in rows]) == 1
print("step당 평균 advantage          전진(+1)      후진(-1)")
for name, adv in [("A^E만 (GRPO)", np.array([A_E[i] for i, *_ in rows])), ("A^S (anchor group)", A_S), ("A^E + ω·A^S (GiGPO)", A)]:
    for sub, msk in [("실패 에피소드", ~ok), ("성공 에피소드", ok)]:
        print(f"  {name:20s} {sub:15s} {adv[msk & (act == 1)].mean():+8.3f}   {adv[msk & (act == -1)].mean():+8.3f}")
 

끝 보상만 있으면 AEA^E는 같은 에피소드 안의 전진 step과 후진 step을 구별하지 못한다. anchor 상태 advantage는 구별할 수 있지만 경로는 두 가지뿐이다. 같은 상태에서 결과가 갈린 경우, 그리고 할인(같은 상태에서 성공까지 더 짧은 경로가 더 큰 γT−1−tR\gamma^{T-1-t}R를 받는다). 여기서는 구별 폭이 크지 않다(성공 에피소드에서 +0.95 대 +0.78). 같은 것끼리 비교해도 희소한 보상이 알려 줄 수 있는 양이 이 정도라는 정직한 그림이다.

확인 문제Check yourself

40 turn짜리 코딩 agent를 통과/실패 보상 하나로 GRPO 학습한다. 동료가 '앞쪽 turn의 분산을 줄이려고' turn 할인 γ = 0.9를 제안한다. 실제로 무슨 일이 일어나는가?

끝 보상만 있으면 turn kk의 reward-to-go는 γK−kR\gamma^{K-k}R, 곧 RR의 상수배다. g^k\hat g_k의 평균과 표준편차가 모두 γK−k\gamma^{K-k}배가 되므로 SNR은 변하지 않는다. 이 제안은 turn별 학습률 스케줄이다. 잡음을 실제로 줄이려면 turn을 구별하는 정보가 필요하다. (γ\gamma로 잘라 낼) 중간 보상, GiGPO의 anchor group 같은 step 단위 비교, 또는 더 많은 trajectory.

정책은 관리된 context 위에서 행동한다

trajectory가 아니라 context 함수

trajectory가 창보다 길어지면 정책은 더 이상 이력 hk=(x,a1,o1,…,ok−1)h_k=(x,a_1,o_1,\dots,o_{k-1})에 조건화하지 않고, harness가 만든 context에 조건화한다.

ck=C(hk),Pθ(τ)=∏kπθ(ak∣ck) Penv(ok∣hk,ak),∇θlog⁡Pθ(τ)=∑k∇θlog⁡πθ(ak∣ck).c_k=\mathcal C(h_k),\qquad P_\theta(\tau)=\prod_k\pi_\theta(a_k\mid c_k)\,P_{\text{env}}(o_k\mid h_k,a_k),\qquad \nabla_\theta\log P_\theta(\tau)=\sum_k\nabla_\theta\log\pi_\theta(a_k\mid c_k).

C\mathcal C가 θ\theta에 의존하지 않는 한 agent RL의 유도는 그대로 성립한다. 그러면 C\mathcal C는 환경 전이의 일부일 뿐이다. MiniMax-M2는 같은 것을 모델링 선택으로 명시한다. LLM 생성 바깥의 모든 것, 곧 context 관리·메모리·sub-agent 호출이 st+1=ftrans(st,at,ot)s_{t+1}=f_{\text{trans}}(s_t,a_t,o_t) 안에 살고, 학습 단위는 각 (st,at)(s_t,a_t) 쌍이다(리뷰). Agent Lightning(Luo et al., 2025)은 같은 생각 위에 프레임워크를 세운다. trainer가 과제마다 “OpenAI-like API” endpoint를 열고, 수정하지 않은 agent(LangChain, OpenAI Agents SDK, AutoGen, 직접 짠 코드)가 그 endpoint를 자기 LLM으로 호출한다. LLM 호출 하나하나가 (그 호출이 실제로 본 입력, 출력, 보상) transition으로 기록된다. 그 알고리즘 LightningRL은 현재 구현에서 “에피소드 안의 모든 행동이 최종 return과 같은 값을 갖는다고 단순히 가정”한다. 호출 사이에 harness가 context에 무슨 짓을 하든 구성상 C\mathcal C의 일부가 된다. 실무적 결과가 세 가지 따라 나온다.

  • log-prob은 ckc_k에서 계산해야 한다. sampler가 실제로 본 context다. 원래 이력이 아니다. hkh_k로 학습하면 다른 조건부 분포를 배우게 된다.
  • 요약을 정책이 쓰면 요약은 행동이다. AutoCompact는 compact() 호출을 행동 공간에 넣는다. 요약 토큰은 다른 모델 토큰처럼 학습되고, 언제 압축할지도 학습된다(Qwen3-Coder-30B-A3B, SFT → GRPO 후 SWE-bench Verified 30.4 → 39.6, 고정 16K 압축의 28.8보다 높고 개선의 대부분은 RL 단계에서 나왔다).
  • rewrite가 일어나면 학습 시퀀스가 끝난다. append만 일어나는 최대 구간 하나가 trainer의 시퀀스 하나다. rewrite가 nn번 일어난 trajectory는 advantage 하나를 나눠 가져야 하는 시퀀스 n+1n+1개가 된다. AutoCompact는 context가 다시 쓰이는 모든 지점에서 trajectory를 쪼개고 모든 구간에 같은 advantage를 주며, QwenGyre는 (최대 다섯 개의) leaf 경로에 대해 run 단위로 정규화한다.

마지막 항목에는 날이 서 있다. loss를 시퀀스에 대해 평균하면, 구간 nn개로 쪼개진 trajectory는 한 번도 다시 쓰이지 않은 trajectory보다 nn배 무게를 받는다. 그리고 rewrite는 바로 긴 trajectory에서 일어난다. 아래 NumPy 블록에서 균형 잡힌 group의 순 밀어올림이 0에서 +0.56으로 부호가 바뀌는 것을 볼 수 있다.

turn 사이의 추론

turn 사이에 모델 자신의 추론을 어떻게 하느냐도 context 정책이고, lab들은 한 방향으로 움직여 왔다.

모델이전 추론에 대한 규칙
DeepSeek-R1다음 메시지가 올 때마다 버린다
DeepSeek-V3.2tool 메시지만 붙는 동안은 유지하고, 새 user 메시지가 오면 버린다. tool 호출과 결과는 항상 남긴다
DeepSeek-V4tool을 호출하는 대화에서는 user turn을 넘어서도 유지한다(interleaved thinking). 일반 대화에서는 여전히 버린다
GLM-5interleaved thinking, 코딩 agent 설정에서의 preserved thinking(모든 thinking 블록을 turn을 넘어 유지), turn 단위 스위치. GLM-5.3은 clear_thinking=false를 기본값으로 한다

생각을 할지 말지도 context의 일부다. Qwen3의 thinking mode fusion은 프롬프트의 /think, /no_think 플래그로 전환되는 두 모드를 한 모델로 학습한다. non-thinking 샘플도 빈 think 블록을 남겨 두 모드가 같은 template을 공유한다(Qwen3 리뷰). GLM-5의 turn 단위 스위치는 같은 아이디어를 turn마다 적용한 것이다.

이유는 두 가지다. 행동 면에서, tool 호출마다 추론을 버리면 모델은 호출할 때마다 문제를 처음부터 다시 생각해야 한다(V3.2의 논거). 계산 면에서, 자라기만 하는 context는 직전 호출의 전체 시퀀스를 prefix로 유지하므로 KV cache를 재사용할 수 있다(GLM-5). 대가는 학습과 배포의 결합이다. V3.2는 tool 상호작용을 user 메시지로 흉내 내는 프레임워크(Terminus, Roo Code)가 매번 추론을 버려 이점을 잃는다고 적는다. Terminal Bench 2.0의 thinking 점수 46.4는 Claude Code에서 측정했고, Terminus에서는 보고서가 non-thinking 모드(39.3)를 쓴다. RL에서 쓴 context 정책은 출시하는 정책의 일부다. Kimi K3는 더 나아가 과제 group마다 tool 인터페이스·시스템 프롬프트·context 관리·sub-agent 같은 harness 전체를 바꿔 끼워, 정책이 harness 하나에 과적합하지 않게 한다(리뷰).

관측 정책

tool 출력에 대해 공개된 정책은 몇 개 안 되고 단순하다.

정책규칙보고된 효과
요약 (V3.2)창의 80%에서 넘친 trajectory를 요약하고 다시 시작BrowseComp 51.4 → 최대 60.2, 평균 약 364 step까지 늘어남
Discard-all (V3.2)80%에서 tool 호출 이력 전체를 버림BrowseComp → 67.6, 훨씬 적은 step으로 parallel scaling과 같은 수준
Keep-recent-k (GLM-5)최근 kk 라운드보다 오래된 관측을 접음k=5k=5: BrowseComp 55.3 → 62.0
계층형 (GLM-5 HCM)keep-recent-k, 그래도 context가 T=32T=32K를 넘으면 discard-allstep 예산을 늘리며 최대 75.9
학습형 (AutoCompact)정책이 compact()를 호출하고 상태를 씀위 참고

Nemotron 3 Ultra의 search teacher는 discard-all context 관리로 학습된다(리뷰). GLM-5는 BrowseComp 정확도가 약 100K 토큰을 넘으면 떨어진다고 보고한다. 가장 단순한 정책이 이기는 이유의 일부는 긴 context 자체가 해롭기 때문이다. 표가 보여 주지 않는 것은 비용 구조다. 정책마다 크게 다르고, RL에서는 두 번 문제가 된다. 한 번은 rollout 때(decode attention, prefill, KV 재사용), 한 번은 학습 때(시퀀스가 몇 개이고 forward하는 토큰이 몇 개인지).

최대 contextpeak context – 학습 시퀀스training sequences – 끝에 남은 원본 관측raw observations visible at the end –
Each turn the model writes a = 600 tokens (reasoning + call) and the environment returns o tokens; the prompt is 3K. Left: context length per turn for all five policies (current one bold; grey line = window W, dashed = 80%). Right: four costs per policy, each scaled to the largest policy: decode attention (Σ context × generated tokens), prefill (new tokens + tokens re-prefilled because a rewrite invalidated the KV cache), tokens forwarded in training (one sequence per append-only segment, no prefix sharing), and the share of raw observations still visible at the end. Switch between policies: "none" overflows; keep-recent-k never overflows here but still grows (it folds observations, not reasoning) and rewrites the context every turn, so it re-prefills ~k turns and produces one training sequence per turn. Discard-all rewrites rarely and cheaply but forgets everything; hierarchical has the cheapest decode. turn마다 모델이 a = 600 토큰(추론 + 호출)을 쓰고 환경이 o 토큰을 돌려준다. 프롬프트는 3K다. 왼쪽: 다섯 정책의 turn별 context 길이(현재 정책은 굵게, 회색 선 = 창 W, 점선 = 80%). 오른쪽: 정책별 비용 네 가지, 각각 가장 큰 정책을 1로 맞췄다. decode attention(Σ context × 생성 토큰), prefill(새 토큰 + rewrite가 KV cache를 무효화해 다시 prefill한 토큰), 학습 때 forward하는 토큰(append만 일어나는 구간마다 시퀀스 하나, prefix 공유 없음), 끝까지 원본으로 남은 관측의 비율. 정책을 바꿔 보면 "관리 없음"은 창을 넘친다. keep-recent-k는 여기서 넘치지는 않지만 여전히 자라고(관측은 접어도 추론은 접지 않는다) 매 turn context를 다시 쓰므로, 약 k turn 분량을 다시 prefill하고 학습 시퀀스가 turn마다 하나 생긴다. discard-all은 드물고 싸게 다시 쓰지만 모든 것을 잊고, decode가 가장 싼 것은 계층형이다.

What to look for (defaults: 150 turns, 2K-token observations, 128K window).

  1. None overflows around turn 51: 3K+51×2.6K≈128K3\text{K}+51\times2.6\text{K}\approx128\text{K}.
  2. Keep-recent-k never overflows here, but notice its trace still climbs: folding observations does not fold the model’s own 600-token turns, and 150×600=90150\times600=90K of reasoning and calls accumulates. Its prefill bar is high because each fold changes a block kk rounds back, invalidating the KV cache from there: every turn re-prefills k(a+o)+stub≈13k(a+o)+\text{stub}\approx13K tokens. And it produces one training sequence per turn.
  3. Discard-all rewrites four times, re-prefills nothing, and trains on four short sequences — but at the end only ~19% of observations are visible.
  4. Hierarchical caps the context at 32K (cheapest decode attention) at the price of keep-recent-k’s per-turn rewrites.
  5. Set o to 10K: keep-recent-k with k=20k=20 overflows again — a fixed kk is a token budget only if observations have bounded size.

None of these is “best”; they choose which cost to pay. The re-prefill and training-sequence counts are our arithmetic, not numbers from the reports — but they are why trajectory-tree and prefix-merging training (MiniMax Forge reports up to 40× faster training from merging shared prefixes; QwenGyre computes shared prefixes once and caps leaf paths at 5, at 74.8% of the uncapped fwd–bwd time with about the same score) matters so much for long-horizon RL.

NumPy Context policies: token arithmetic and loss weighting
import numpy as np

X0, A, STUB, SUMM, T_HCM = 3000, 600, 30, 3000, 32768   # prompt, tokens per action, folded stub, summary, HCM threshold

def run(policy, K=150, o=2000, W=131072, k=5):
    """Token arithmetic of one K-turn episode under a context policy (same rules as the figure)."""
    blocks = [["p", X0]]
    length = lambda: sum(n for _, n in blocks)
    c = dict(decode=0.0, prefill=X0, train=0, seg=1, peak=X0, fail=0)
    seg_len = 0
    def rewrite(first):                      # KV cache is invalid from block `first` on
        nonlocal seg_len
        c["prefill"] += sum(n for _, n in blocks[first:])
        c["train"] += seg_len                # close the append-only segment = one training sequence
        c["seg"] += 1
    for j in range(1, K + 1):
        L = length()
        if L + A > W:
            c["fail"] = j; break
        c["decode"] += A * L + A * A / 2     # attention work ∝ context length per generated token
        blocks.append(["a", A]); seg_len = L + A
        c["peak"] = max(c["peak"], seg_len)
        if j == K: break
        blocks.append(["o", o]); c["prefill"] += o
        if policy in ("keep-recent-k", "hierarchical"):
            raw = [i for i, b in enumerate(blocks) if b[0] == "o"]
            if len(raw) > k:
                for i in raw[:len(raw) - k]:
                    blocks[i] = ["stub", STUB]
                rewrite(raw[0])
        if policy in ("summarise", "discard-all") and length() > 0.8 * W:
            if policy == "summarise":
                c["decode"] += SUMM * length() + SUMM ** 2 / 2   # the policy writes the summary
                blocks = [blocks[0], ["s", SUMM]]
            else:
                blocks = [blocks[0]]
            rewrite(1)
        if policy == "hierarchical" and length() > min(T_HCM, 0.8 * W):
            blocks = [blocks[0]]; rewrite(1)
    c["train"] += seg_len
    n_obs = (c["fail"] - 1) if c["fail"] else K - 1
    c["visible"] = sum(b[0] == "o" for b in blocks) / max(1, n_obs)
    return c

pols = ["none", "keep-recent-k", "summarise", "discard-all", "hierarchical"]
res = {p: run(p) for p in pols}
print("K=150 turns, o=2000-token observations, W=128K, k=5")
print(f"{'policy':14s} {'status':>10s} {'peak':>7s} {'decode att.':>12s} {'prefill':>9s} {'train tok':>10s} {'seqs':>5s} {'visible':>8s}")
for p in pols:
    c = res[p]
    st = f"✗ t={c['fail']}" if c["fail"] else "ok"
    print(f"{p:14s} {st:>10s} {c['peak']/1024:6.0f}K {c['decode']:12.2e} {c['prefill']/1e6:8.2f}M "
          f"{c['train']/1e6:9.2f}M {c['seg']:5d} {c['visible']:8.0%}")

kr = res["keep-recent-k"]
print(f"\nkeep-recent-k re-prefills {(kr['prefill'] - X0 - 149*2000)/1e6:.3f}M tokens: ≈ (K−k−1)·(k·(a+o) + stub)"
      f" = {(150-5-1)*(5*(600+2000) + 30)/1e6:.3f}M")

# --- loss normalisation when one trajectory becomes many sequences
# 4 trajectories of one group, advantages from the outcome; trajectory 2 was split into 6 segments.
adv = np.array([+1.0, -1.0, +1.0, -1.0])
n_seg = np.array([1, 1, 6, 1])
w_per_seq = n_seg / n_seg.sum()            # mean over sequences: each segment counts once
w_per_traj = np.ones(4) / 4                # QwenGyre-style per-run normalisation
print("\nweight of each trajectory in the loss   per-sequence mean   per-trajectory mean")
for i in range(4):
    print(f"  traj {i}  A={adv[i]:+.0f}  segments={n_seg[i]}          {w_per_seq[i]:.3f}               {w_per_traj[i]:.3f}")
print(f"net push (Σ w·A): per-sequence {np.dot(w_per_seq, adv):+.3f}, per-trajectory {np.dot(w_per_traj, adv):+.3f}"
      "  ← many-segment trajectories should not count more")
 

The table reproduces the figure at its defaults, and the re-prefill count matches the closed form (K−k−1) (k(a+o)+stub)(K-k-1)\,(k(a+o)+\text{stub}) exactly. The second part is the normalisation trap: per-sequence averaging turns a balanced group (two successes, two failures) into a net positive push, because the successful trajectory that happened to be rewritten six times counts six times.

확인 문제Check yourself

You switch a search agent from discard-all to keep-recent-k (k = 5) at rollout time. Training uses one sequence per append-only segment and averages the loss over sequences. What changes in training?

Keep-recent-k rewrites the context every turn (one more observation gets folded), so every turn after the kk-th starts a new append-only segment. The trainer must forward each segment with its own context, roughly ∑k∣ck∣\sum_k|c_k| tokens instead of ∣cK∣|c_K|, and a sequence-averaged loss gives a trajectory weight proportional to its number of segments. Share one advantage across the segments of a trajectory and normalise per trajectory (AutoCompact, QwenGyre), and merge shared prefixes where you can.

Budgets: tokens, turns and wall-clock

Long horizons need budgets, and frontier reports put them directly into the reward:

  • Kimi K3 (reasoning effort). Each problem gets an initial budget b0(x)b_0(x) from the cold-start model, and the reward is overwritten with −1-1 when the total tokens T(y)>τ b0(x)T(y)>\tau\,b_0(x); for agentic tasks T(y)T(y) counts cumulative output tokens including reasoning and tool-call arguments. A max-effort expert is trained first with a large τ\tau, then τ\tau is annealed for the high and low experts.
  • Kimi K2. Responses over a per-task-type token budget are truncated and penalised.
  • Kimi K2.5 (Toggle). Training alternates every mm iterations between a budget phase and a standard phase. In the budget phase, a correct response’s reward is multiplied by zero if it exceeds the problem’s budget, which is the ρ\rho-th percentile of correct-response lengths, estimated once at the start. This applies only to problems whose mean accuracy exceeds λ\lambda, so hard problems keep their room to explore. The standard phase uses the raw reward up to the maximum length, which avoids the “length-overfitting” of models trained under rigid budgets. The report gives 25–30% fewer output tokens on average with negligible impact on performance, but does not state ρ\rho or λ\lambda in the text.
  • DeepSeek-V4. Different modes are trained with different length penalties and context windows (Think High at 128K, Think Max at 384K).
  • Nemotron 3 Ultra. About 2.5% of RLVR prompts are in medium-effort mode with a length-based adjustment; medium uses about 2.5× fewer tokens at about 7% lower accuracy.
  • MiniMax-M2. A completion-time reward among equally correct trajectories, which pays for parallel tool calls and good use of sub-agents — a wall-clock budget, not a token budget.

The length-penalty families themselves (k1.5’s group-relative length reward and its descendants) are derived in regularisation.

What to do with a trajectory that hits the budget

When a rollout reaches the budget BB unfinished, there are three choices, and they optimise different things. Let LL be the length the trajectory would have had.

  1. Score it as a failure (R=0R=0). The objective becomes P(success∧L≤B)P(\text{success}\wedge L\le B): there is a gradient towards finishing within budget. This is what you want when the budget is part of the task.
  2. Drop it from the loss (Nemotron’s SWE teacher excludes unfinished trajectories). The gradient is now an estimate of ∇E[R∣L≤B]\nabla\mathbb E[R\mid L\le B] under the policy’s own length distribution: no pressure to finish, and the group baseline is computed over a length-filtered subset. If long attempts are systematically harder, the filter also removes them from the denominator of the success rate.
  3. Resume it later (partial rollout). No length filter, but the continuation is sampled from newer weights.

A related trap appears when rollouts are interrupted (preemption, node failure). If each in-flight token is interrupted with a small hazard hh, a trajectory of length LL survives with probability e−hLe^{-hL}; regenerating interrupted requests from scratch therefore trains on the tilted length distribution

ptrained(L) ∝ p(L) e−hL,p_{\text{trained}}(L)\ \propto\ p(L)\,e^{-hL},

which systematically favours short responses. DeepSeek-V4 states this as the reason its rollout service resumes from a token-level write-ahead log and the saved KV cache instead of regenerating (§5.2.3, review).

When the horizon outlives an iteration

Kimi k1.5 introduced partial rollout: a fixed output-token budget per iteration, unfinished trajectories saved to a replay buffer and continued in the next iteration, so a few very long generations do not stall the batch (review). K3 extends it — generation pauses once a fraction λ\lambda of responses has finished, and paused rollouts resume first in the next iteration together with their sandbox state. MiMo-V2 uses asynchronous partial rollout with staleness 4 and staleness-aware truncated IS. The price in every case is a trajectory whose segments were sampled by different policy versions. How to bound and correct that — staleness limits, decoupled objectives, masking — is the subject of async and staleness, and the numerical side of “which policy sampled this token” is mismatch engineering.

In PyTorch

Turning one managed-context trajectory into training sequences: each append-only segment is a sequence with its own context, all segments share the trajectory’s advantage, model tokens are masked exactly as in agent RL, and the loss is normalised per trajectory.

PyTorch PyTorch: segments of a managed-context trajectory, shared advantage, per-trajectory normalisation 로컬에서 실행run locally (pip install torch)
import torch
import torch.nn.functional as F

def segments_to_batch(trajectories, pad_id=0):
    """trajectories: list of dicts with
         'segments': list of (token_ids LongTensor (T,), is_model BoolTensor (T,), rollout_logp FloatTensor (T,))
                     — one entry per append-only context, exactly as the sampler saw it
         'adv':      scalar advantage of the whole trajectory (e.g. group-normalised outcome)
    Returns padded (S, T) tensors plus, per sequence, its advantage and its trajectory's segment count."""
    ids, mask, old, adv, nseg = [], [], [], [], []
    for tr in trajectories:
        n = len(tr["segments"])
        for tok, is_model, logp in tr["segments"]:
            ids.append(tok); mask.append(is_model); old.append(logp)
            adv.append(tr["adv"]); nseg.append(n)
    pad = lambda xs, v: torch.nn.utils.rnn.pad_sequence(xs, batch_first=True, padding_value=v)
    return (pad(ids, pad_id), pad(mask, False), pad(old, 0.0),
            torch.tensor(adv, dtype=torch.float32), torch.tensor(nseg, dtype=torch.float32))

def long_horizon_pg_loss(model, ids, mask, old_logp, adv, nseg, n_traj, eps=0.2):
    """PPO-style token loss where every segment of a trajectory shares that trajectory's advantage,
    and each trajectory has total weight 1/n_traj however many segments it was split into."""
    logits = model(ids).logits[:, :-1].float()                    # position t predicts token t+1
    logp = torch.log_softmax(logits, -1).gather(-1, ids[:, 1:].unsqueeze(-1)).squeeze(-1)
    m = mask[:, 1:].float()                                       # only tokens the policy sampled
    ratio = torch.exp(logp - old_logp[:, 1:])
    A = adv[:, None]
    surr = torch.minimum(ratio * A, ratio.clamp(1 - eps, 1 + eps) * A)
    tok_per_seq = m.sum(1).clamp(min=1)
    per_seq = (surr * m).sum(1) / tok_per_seq                     # token mean inside a segment
    # per-trajectory normalisation: a trajectory split into n segments contributes 1/n per segment
    return -(per_seq / nseg).sum() / n_traj
 

Summary

  • A broadcast outcome is unbiased per turn, but its SNR falls like 1/K1/\sqrt K: per-decision sample cost grows linearly with the number of turns.
  • A per-turn discount reduces variance only when there are intermediate rewards to cut off; on a terminal-only reward it is just a per-turn step size. Process rewards help exactly as much as their error term eke_k is zero — reports mostly use unambiguous penalties and filters (format, broken calls, SimpleTIR’s void turns) and step-level comparisons (GiGPO) instead of judged progress. A reverse curriculum from demonstrations shortens the effective horizon instead.
  • The policy acts on ck=C(hk)c_k=\mathcal C(h_k). Compute log-probs on ckc_k, treat policy-written summaries as actions, split at rewrites, share the advantage across segments and normalise per trajectory.
  • Reasoning retention moved from “discard every turn” (R1) to “keep within tool use” (V3.2) to “keep across turns” (V4, GLM-5 preserved thinking); the context policy in RL must match deployment.
  • Simple observation policies (discard-all, keep-recent-k, hierarchical) win on BrowseComp but pay different costs: rewrites invalidate KV caches and multiply training sequences.
  • Budgets go into the reward (K3’s τb0(x)\tau b_0(x) rule, completion-time rewards); dropping, zeroing or resuming unfinished trajectories optimises different objectives, and regenerating interrupted rollouts biases towards short ones.

볼 것(기본값: 150 turn, 관측 2K 토큰, 창 128K).

  1. 관리 없음은 51번째 turn쯤 넘친다. 3K+51×2.6K≈128K3\text{K}+51\times2.6\text{K}\approx128\text{K}.
  2. Keep-recent-k는 여기서 넘치지 않지만 곡선이 여전히 올라가는 것을 보자. 관측을 접어도 모델 자신의 600 토큰짜리 turn은 접히지 않아서, 추론과 호출 150×600=90150\times600=90K가 쌓인다. prefill 막대가 높은 이유는 접기가 kk 라운드 전의 블록을 바꾸어 그 지점부터 KV cache를 무효화하기 때문이다. 매 turn k(a+o)+stub≈13k(a+o)+\text{stub}\approx13K 토큰을 다시 prefill한다. 그리고 학습 시퀀스가 turn마다 하나 생긴다.
  3. Discard-all은 네 번 다시 쓰고, 다시 prefill하는 것이 없고, 짧은 시퀀스 네 개로 학습한다. 하지만 끝에는 관측의 약 19%만 보인다.
  4. 계층형은 context를 32K로 묶어(decode attention이 가장 싸다) keep-recent-k의 turn별 rewrite를 대가로 치른다.
  5. o를 10K로 올려 보자. k=20k=20인 keep-recent-k가 다시 넘친다. 고정된 kk는 관측 크기가 유한할 때만 토큰 예산이 된다.

어느 것도 “최선”이 아니다. 어떤 비용을 낼지 고르는 것이다. 재-prefill과 학습 시퀀스 수는 보고서의 숫자가 아니라 우리의 산수다. 그래도 이것이 trajectory tree와 prefix 병합 학습이 long-horizon RL에서 그토록 중요한 이유다(MiniMax Forge는 공유 prefix 병합으로 학습이 최대 40배 빨라졌다고 보고하고, QwenGyre는 공유 prefix를 한 번만 계산하고 leaf 경로를 5개로 제한해 점수는 거의 같게, fwd–bwd 시간은 제한 없을 때의 74.8%로 줄였다).

NumPy context 정책: 토큰 산수와 loss 가중치
import numpy as np

X0, A, STUB, SUMM, T_HCM = 3000, 600, 30, 3000, 32768   # 프롬프트, 행동당 토큰, 접힌 stub, 요약, HCM 임계값

def run(policy, K=150, o=2000, W=131072, k=5):
    """context 정책 하나 아래 K turn 에피소드의 토큰 산수 (그림과 같은 규칙)."""
    blocks = [["p", X0]]
    length = lambda: sum(n for _, n in blocks)
    c = dict(decode=0.0, prefill=X0, train=0, seg=1, peak=X0, fail=0)
    seg_len = 0
    def rewrite(first):                      # 블록 `first`부터 KV cache가 무효
        nonlocal seg_len
        c["prefill"] += sum(n for _, n in blocks[first:])
        c["train"] += seg_len                # append만 일어난 구간을 닫는다 = 학습 시퀀스 하나
        c["seg"] += 1
    for j in range(1, K + 1):
        L = length()
        if L + A > W:
            c["fail"] = j; break
        c["decode"] += A * L + A * A / 2     # 생성 토큰당 attention 작업 ∝ context 길이
        blocks.append(["a", A]); seg_len = L + A
        c["peak"] = max(c["peak"], seg_len)
        if j == K: break
        blocks.append(["o", o]); c["prefill"] += o
        if policy in ("keep-recent-k", "hierarchical"):
            raw = [i for i, b in enumerate(blocks) if b[0] == "o"]
            if len(raw) > k:
                for i in raw[:len(raw) - k]:
                    blocks[i] = ["stub", STUB]
                rewrite(raw[0])
        if policy in ("summarise", "discard-all") and length() > 0.8 * W:
            if policy == "summarise":
                c["decode"] += SUMM * length() + SUMM ** 2 / 2   # 요약은 정책이 쓴다
                blocks = [blocks[0], ["s", SUMM]]
            else:
                blocks = [blocks[0]]
            rewrite(1)
        if policy == "hierarchical" and length() > min(T_HCM, 0.8 * W):
            blocks = [blocks[0]]; rewrite(1)
    c["train"] += seg_len
    n_obs = (c["fail"] - 1) if c["fail"] else K - 1
    c["visible"] = sum(b[0] == "o" for b in blocks) / max(1, n_obs)
    return c

pols = ["none", "keep-recent-k", "summarise", "discard-all", "hierarchical"]
res = {p: run(p) for p in pols}
print("K=150 turn, 관측 2000 토큰, W=128K, k=5")
print(f"{'정책':14s} {'상태':>10s} {'최대':>7s} {'decode att.':>12s} {'prefill':>9s} {'학습 토큰':>10s} {'시퀀스':>5s} {'보이는 관측':>8s}")
for p in pols:
    c = res[p]
    st = f"✗ t={c['fail']}" if c["fail"] else "ok"
    print(f"{p:14s} {st:>10s} {c['peak']/1024:6.0f}K {c['decode']:12.2e} {c['prefill']/1e6:8.2f}M "
          f"{c['train']/1e6:9.2f}M {c['seg']:5d} {c['visible']:8.0%}")

kr = res["keep-recent-k"]
print(f"\nkeep-recent-k 다시 prefill하는 토큰 {(kr['prefill'] - X0 - 149*2000)/1e6:.3f}M: ≈ (K−k−1)·(k·(a+o) + stub)"
      f" = {(150-5-1)*(5*(600+2000) + 30)/1e6:.3f}M")

# --- trajectory 하나가 시퀀스 여러 개가 될 때의 loss 정규화
# 한 group의 trajectory 4개, advantage는 결과에서. trajectory 2는 구간 6개로 쪼개졌다.
adv = np.array([+1.0, -1.0, +1.0, -1.0])
n_seg = np.array([1, 1, 6, 1])
w_per_seq = n_seg / n_seg.sum()            # 시퀀스 평균: 구간마다 한 번씩 센다
w_per_traj = np.ones(4) / 4                # QwenGyre식 run 단위 정규화
print("\nloss에서 각 trajectory의 가중치        시퀀스 평균          trajectory 평균")
for i in range(4):
    print(f"  traj {i}  A={adv[i]:+.0f}  구간={n_seg[i]}          {w_per_seq[i]:.3f}               {w_per_traj[i]:.3f}")
print(f"순 밀어올림 (Σ w·A): 시퀀스 평균 {np.dot(w_per_seq, adv):+.3f}, trajectory 평균 {np.dot(w_per_traj, adv):+.3f}"
      "  ← 구간이 많은 trajectory가 더 세게 세어지면 안 된다")
 

표는 그림의 기본값을 재현하고, 재-prefill 토큰 수는 닫힌 식 (K−k−1) (k(a+o)+stub)(K-k-1)\,(k(a+o)+\text{stub})와 정확히 일치한다. 둘째 부분은 정규화의 함정이다. 시퀀스 평균은 균형 잡힌 group(성공 둘, 실패 둘)을 순 양의 밀어올림으로 바꾼다. 우연히 여섯 번 다시 쓰인 성공 trajectory가 여섯 번 세어지기 때문이다.

확인 문제Check yourself

search agent의 rollout context 정책을 discard-all에서 keep-recent-k(k = 5)로 바꾼다. 학습은 append만 일어나는 구간마다 시퀀스 하나를 쓰고 loss를 시퀀스에 대해 평균한다. 학습에서 무엇이 바뀌는가?

keep-recent-k는 매 turn context를 다시 쓰므로(관측 하나가 더 접힌다), kk번째 이후 turn마다 append만 일어나는 새 구간이 시작된다. trainer는 각 구간을 자기 context와 함께 forward해야 하므로 ∣cK∣|c_K| 대신 대략 ∑k∣ck∣\sum_k|c_k| 토큰을 처리하고, 시퀀스 평균 loss는 trajectory에 구간 수에 비례하는 무게를 준다. 한 trajectory의 구간들이 advantage 하나를 공유하게 하고 trajectory 단위로 정규화하며(AutoCompact, QwenGyre), 가능하면 공유 prefix를 병합한다.

예산: 토큰, turn, wall-clock

긴 horizon에는 예산이 필요하고, frontier 보고서들은 예산을 보상에 직접 넣는다.

  • Kimi K3 (reasoning effort). 문제마다 cold-start 모델로 초기 예산 b0(x)b_0(x)를 정하고, 총 토큰이 T(y)>τ b0(x)T(y)>\tau\,b_0(x)이면 보상을 −1-1로 덮어쓴다. agentic 과제에서 T(y)T(y)는 추론과 tool 호출 인자를 포함한 누적 출력 토큰이다. 큰 τ\tau로 max-effort expert를 먼저 학습하고, 이어 τ\tau를 줄여 가며 high·low expert를 만든다.
  • Kimi K2. 과제 유형별 토큰 예산을 넘는 응답은 잘리고 벌점을 받는다.
  • Kimi K2.5 (Toggle). mm iteration마다 예산 단계와 일반 단계를 번갈아 학습한다. 예산 단계에서는 맞은 응답이라도 문제별 예산을 넘으면 보상에 0을 곱한다. 예산은 맞은 응답 길이의 ρ\rho번째 백분위수이고, 학습 시작 때 한 번 추정한다. 이 규칙은 평균 정확도가 λ\lambda를 넘는 문제에만 적용되므로, 어려운 문제는 탐색할 여지를 그대로 갖는다. 일반 단계는 최대 길이까지 원래 보상을 쓴다. 엄격한 예산으로만 학습한 모델이 보이는 “길이 과적합”을 피하려는 것이다. 보고서는 평균 25–30% 적은 출력 토큰에 성능 영향은 무시할 만하다고 하지만, 본문에 ρ\rho와 λ\lambda의 값은 없다.
  • DeepSeek-V4. 모드마다 다른 길이 벌점과 context 창으로 학습한다(Think High는 128K, Think Max는 384K).
  • Nemotron 3 Ultra. RLVR 프롬프트의 약 2.5%가 길이 기반 조정을 받는 medium-effort 모드다. medium은 토큰을 약 2.5배 덜 쓰고 정확도는 약 7% 낮다.
  • MiniMax-M2. 똑같이 맞은 trajectory 사이에서 완료 시간 보상을 주어 병렬 tool 호출과 sub-agent 활용에 값을 매긴다. 토큰 예산이 아니라 wall-clock 예산이다.

길이 벌점 계열 자체(k1.5의 group 상대 길이 보상과 그 후손)는 정규화에서 유도한다.

예산에 걸린 trajectory를 어떻게 할까

rollout이 끝나지 않은 채 예산 BB에 닿으면 선택지가 셋 있고, 각각 다른 것을 최적화한다. LL을 그 trajectory가 원래 가졌을 길이라 하자.

  1. 실패로 채점한다(R=0R=0). 목적함수가 P(success∧L≤B)P(\text{success}\wedge L\le B)가 되어, 예산 안에 끝내는 쪽으로 gradient가 생긴다. 예산이 과제의 일부일 때 원하는 것이다.
  2. loss에서 뺀다(Nemotron의 SWE teacher는 끝나지 않은 trajectory를 제외한다). gradient는 이제 정책 자신의 길이 분포 아래 ∇E[R∣L≤B]\nabla\mathbb E[R\mid L\le B]의 추정치다. 끝내라는 압력이 없고, group baseline은 길이로 걸러진 부분집합에서 계산된다. 긴 시도가 체계적으로 더 어렵다면, 이 필터는 그것들을 성공률의 분모에서도 지운다.
  3. 나중에 이어 쓴다(partial rollout). 길이 필터는 없지만, 이어지는 부분은 더 새 가중치에서 샘플된다.

rollout이 중단될 때(선점, 노드 장애) 비슷한 함정이 있다. 진행 중인 토큰마다 작은 위험률 hh로 중단된다면, 길이 LL인 trajectory가 살아남을 확률은 e−hLe^{-hL}이다. 중단된 요청을 처음부터 다시 생성하면 학습은 기울어진 길이 분포

ptrained(L) ∝ p(L) e−hLp_{\text{trained}}(L)\ \propto\ p(L)\,e^{-hL}

위에서 이루어지고, 짧은 응답이 체계적으로 유리해진다. DeepSeek-V4는 이것을 rollout 서비스가 다시 생성하지 않고 토큰 단위 write-ahead log와 저장된 KV cache에서 이어 가는 이유로 명시한다(§5.2.3, 리뷰).

horizon이 iteration보다 길 때

Kimi k1.5는 partial rollout을 도입했다. iteration마다 출력 토큰 예산을 고정하고, 끝나지 않은 trajectory는 replay buffer에 저장했다가 다음 iteration에서 이어 써서, 아주 긴 생성 몇 개가 배치를 멈추지 않게 한다(리뷰). K3는 이를 확장해, 응답 중 비율 λ\lambda가 끝나면 생성을 멈추고, 멈춘 rollout은 다음 iteration에서 sandbox 상태와 함께 먼저 재개한다. MiMo-V2는 staleness 4의 비동기 partial rollout과 staleness를 고려한 truncated IS를 쓴다. 어느 경우든 대가는 구간마다 다른 정책 버전이 샘플한 trajectory다. 그것을 어떻게 묶고 보정하는지(staleness 한도, decoupled 목적함수, masking)는 비동기와 staleness의 주제이고, “이 토큰을 어느 정책이 샘플했나”의 수치적 측면은 불일치 엔지니어링에 있다.

PyTorch로

관리된 context의 trajectory 하나를 학습 시퀀스로 바꾸는 코드다. append만 일어나는 구간 하나가 자기 context를 가진 시퀀스 하나이고, 모든 구간이 trajectory의 advantage를 공유하며, 모델 토큰은 agent RL과 똑같이 mask하고, loss는 trajectory 단위로 정규화한다.

PyTorch PyTorch: 관리된 context trajectory의 구간, 공유 advantage, trajectory 단위 정규화 로컬에서 실행run locally (pip install torch)
import torch
import torch.nn.functional as F

def segments_to_batch(trajectories, pad_id=0):
    """trajectories: 다음 키를 가진 dict의 리스트
         'segments': (token_ids LongTensor (T,), is_model BoolTensor (T,), rollout_logp FloatTensor (T,))의 리스트
                     — append만 일어난 context 하나당 하나, sampler가 본 그대로
         'adv':      trajectory 전체의 스칼라 advantage (예: group 정규화한 결과 보상)
    패딩한 (S, T) 텐서와, 시퀀스마다 그 advantage와 소속 trajectory의 구간 수를 돌려준다."""
    ids, mask, old, adv, nseg = [], [], [], [], []
    for tr in trajectories:
        n = len(tr["segments"])
        for tok, is_model, logp in tr["segments"]:
            ids.append(tok); mask.append(is_model); old.append(logp)
            adv.append(tr["adv"]); nseg.append(n)
    pad = lambda xs, v: torch.nn.utils.rnn.pad_sequence(xs, batch_first=True, padding_value=v)
    return (pad(ids, pad_id), pad(mask, False), pad(old, 0.0),
            torch.tensor(adv, dtype=torch.float32), torch.tensor(nseg, dtype=torch.float32))

def long_horizon_pg_loss(model, ids, mask, old_logp, adv, nseg, n_traj, eps=0.2):
    """한 trajectory의 모든 구간이 그 trajectory의 advantage를 공유하고,
    trajectory 하나는 몇 개로 쪼개졌든 전체 가중치 1/n_traj를 갖는 PPO식 토큰 loss."""
    logits = model(ids).logits[:, :-1].float()                    # 위치 t가 토큰 t+1을 예측
    logp = torch.log_softmax(logits, -1).gather(-1, ids[:, 1:].unsqueeze(-1)).squeeze(-1)
    m = mask[:, 1:].float()                                       # 정책이 샘플한 토큰만
    ratio = torch.exp(logp - old_logp[:, 1:])
    A = adv[:, None]
    surr = torch.minimum(ratio * A, ratio.clamp(1 - eps, 1 + eps) * A)
    tok_per_seq = m.sum(1).clamp(min=1)
    per_seq = (surr * m).sum(1) / tok_per_seq                     # 구간 안에서는 토큰 평균
    # trajectory 단위 정규화: 구간 n개로 쪼개진 trajectory는 구간마다 1/n씩 기여
    return -(per_seq / nseg).sum() / n_traj
 

정리

  • 뿌려진 결과 보상은 turn마다 불편이지만 SNR이 1/K1/\sqrt K로 떨어진다. 결정당 샘플 비용이 turn 수에 비례해 늘어난다.
  • turn 할인은 잘라 낼 중간 보상이 있을 때만 분산을 줄인다. 끝 보상만 있으면 turn별 보폭일 뿐이다. process 보상은 오차 항 eke_k가 0인 만큼만 돕는다. 보고서들은 판정된 진척 대신 명백한 벌점과 필터(형식, 깨진 호출, SimpleTIR의 void turn)와 step 단위 비교(GiGPO)를 주로 쓴다. 시연에서 출발하는 reverse curriculum은 실효 horizon 자체를 줄인다.
  • 정책은 ck=C(hk)c_k=\mathcal C(h_k) 위에서 행동한다. log-prob은 ckc_k에서 계산하고, 정책이 쓴 요약은 행동으로 다루며, rewrite에서 쪼개고, 구간들이 advantage를 공유하게 하고, trajectory 단위로 정규화한다.
  • 추론 유지는 “매 turn 버림”(R1)에서 “tool 사용 중 유지”(V3.2), “turn을 넘어 유지”(V4, GLM-5 preserved thinking)로 옮겨 왔다. RL의 context 정책은 배포와 같아야 한다.
  • 단순한 관측 정책(discard-all, keep-recent-k, 계층형)이 BrowseComp에서 이기지만 치르는 비용이 다르다. rewrite는 KV cache를 무효화하고 학습 시퀀스를 늘린다.
  • 예산은 보상에 들어간다(K3의 τb0(x)\tau b_0(x) 규칙, 완료 시간 보상). 끝나지 않은 trajectory를 빼느냐, 0으로 두느냐, 이어 쓰느냐는 서로 다른 목적함수를 최적화하고, 중단된 rollout을 다시 생성하면 짧은 쪽으로 편향된다.

더 읽을거리Further reading