Track V · RL for LLMs & Agents · 08/10

Agent RL — 멀티턴, tool use, credit assignment, 환경Agent RL — multi-turn, tool use, credit assignment, environments

한 번 답하고 끝나는 bandit에서 모델 토큰과 환경 관측이 번갈아 나오는 멀티턴 trajectory로 넘어간다. 왜 tool 출력 토큰을 loss에서 빼야 하는지 유도하고, 긴 horizon의 credit assignment, 환경과 검증기 설계, 비동기 rollout과 staleness의 trade-off를 그림과 코드로 확인한다.From a bandit that answers once and stops, to multi-turn trajectories where model tokens and environment observations alternate. We derive why tool-output tokens must be left out of the loss, then look at credit assignment over long horizons, environment and verifier design, and the trade-off between asynchronous rollout and staleness, with figures and code.

The RLHF and RLVR we have seen so far were, in effect, bandits. Take a prompt, write a response once, receive a reward, done. An agent is different. It searches, reads the results, runs some code, looks at the error, fixes it, and only then answers. Tokens written by the environment are interleaved between its responses. This lesson looks at how that difference changes the loss function, credit assignment, and the training system.

Multi-turn trajectories

Written as an MDP, an agent episode looks like this. Starting from a prompt xx, the model writes an action a1a_1 (thinking and tool-call tokens), the environment returns an observation o1o_1 (the tool result), and this repeats.

τ=(x, a1, o1, a2, o2, …, aK),hk=(x,a1,o1,…,ok−1)\tau = (x,\ a_1,\ o_1,\ a_2,\ o_2,\ \dots,\ a_K),\qquad h_k = (x, a_1, o_1, \dots, o_{k-1})

hkh_k is the context just before the kk-th turn is written. The probability of a trajectory is a product of the policy and the environment.

Pθ(τ)=p(x)∏k=1K∏tπθ(ak,t∣hk,ak,<t)⏟tokens written by the model Penv(ok∣hk,ak)⏟environmentP_\theta(\tau)=p(x)\prod_{k=1}^{K}\underbrace{\prod_{t}\pi_\theta\big(a_{k,t}\mid h_k,a_{k,<t}\big)}_{\text{tokens written by the model}}\ \underbrace{P_{\text{env}}\big(o_k\mid h_k,a_k\big)}_{\text{environment}}

Take the log and differentiate with respect to θ\theta: the environment terms do not depend on θ\theta, so they vanish.

∇θlog⁡Pθ(τ)=∑k=1K∑t∇θlog⁡πθ(ak,t∣hk,ak,<t)\nabla_\theta\log P_\theta(\tau)=\sum_{k=1}^{K}\sum_{t}\nabla_\theta\log\pi_\theta\big(a_{k,t}\mid h_k,a_{k,<t}\big)

This is the justification for loss masking. The policy-gradient sum runs only over tokens the model generated. Tool-output tokens enter the next turn as context, but they are not training targets. Forget this and put the loss on the whole response, and you add a term ∇log⁡πθ(ok∣hk,ak)\nabla\log\pi_\theta(o_k\mid h_k,a_k) — which teaches the model to predict tool results, that is, to make up plausible results without running anything. On top of that, tool output is out-of-distribution text the model never wrote, so the log-probs of those tokens are very low and their gradients can spike. Search-R1 reported that training gets worse when search-result tokens are not masked.

지금까지의 RLHF와 RLVR은 사실상 bandit이었다. 프롬프트를 받고, 응답을 한 번 쓰고, 보상을 받으면 끝이다. agent는 다르다. 검색하고, 결과를 읽고, 코드를 돌려 보고, 에러를 보고 다시 고친 뒤에야 답을 낸다. 응답 사이사이에 환경이 쓴 토큰이 끼어든다. 이 레슨은 그 차이가 손실 함수, credit assignment, 그리고 학습 시스템을 어떻게 바꾸는지 본다.

멀티턴 trajectory

agent 에피소드를 MDP로 쓰면 이렇다. 프롬프트 xx에서 시작해 모델이 행동 a1a_1(생각과 tool 호출 토큰들)을 쓰고, 환경이 관측 o1o_1(tool 결과)을 돌려주고, 이것이 반복된다.

τ=(x, a1, o1, a2, o2, …, aK),hk=(x,a1,o1,…,ok−1)\tau = (x,\ a_1,\ o_1,\ a_2,\ o_2,\ \dots,\ a_K),\qquad h_k = (x, a_1, o_1, \dots, o_{k-1})

hkh_k는 kk번째 turn을 쓰기 직전까지의 문맥이다. trajectory의 확률은 정책과 환경의 곱이다.

Pθ(τ)=p(x)∏k=1K∏tπθ(ak,t∣hk,ak,<t)⏟모델이 쓴 토큰 Penv(ok∣hk,ak)⏟환경P_\theta(\tau)=p(x)\prod_{k=1}^{K}\underbrace{\prod_{t}\pi_\theta\big(a_{k,t}\mid h_k,a_{k,<t}\big)}_{\text{모델이 쓴 토큰}}\ \underbrace{P_{\text{env}}\big(o_k\mid h_k,a_k\big)}_{\text{환경}}

로그를 취해 θ\theta로 미분하면 환경 항은 θ\theta에 의존하지 않으니 사라진다.

∇θlog⁡Pθ(τ)=∑k=1K∑t∇θlog⁡πθ(ak,t∣hk,ak,<t)\nabla_\theta\log P_\theta(\tau)=\sum_{k=1}^{K}\sum_{t}\nabla_\theta\log\pi_\theta\big(a_{k,t}\mid h_k,a_{k,<t}\big)

이것이 loss masking의 근거다. policy gradient의 합은 모델이 생성한 토큰에 대해서만 돈다. tool 출력 토큰은 다음 turn의 문맥으로는 들어가지만 학습 대상은 아니다. 이것을 빼먹고 응답 전체에 손실을 걸면 ∇log⁡πθ(ok∣hk,ak)\nabla\log\pi_\theta(o_k\mid h_k,a_k) 항이 더해지는데, 이는 모델에게 tool 결과를 예측하도록, 즉 실행하지 않고도 그럴듯한 결과를 지어내도록 가르치는 것이다. 게다가 tool 출력은 모델이 직접 쓴 적 없는 분포 밖 텍스트라 그 토큰들의 log-prob이 매우 낮고 gradient가 크게 튈 수 있다. Search-R1은 검색 결과 토큰을 masking하지 않으면 학습이 나빠진다고 보고했다.

gradient 받는 모델 토큰model tokens receiving gradient – gradient 받는 환경 토큰environment tokens receiving gradient –
One episode: prompt → (think → tool call → tool result) × 3 → final answer. Each cell is one token; its colour is the advantage that token receives (blue +, red −), and hatching marks tokens excluded from the loss. Outlines: violet = tool call, green = final answer. Turn the tool-output mask off and even the tokens written by the environment are trained — the model learns to "predict", that is, make up, tool results. Switch to per-turn reward and click the rk cells on the right to change the rewards: even within the same failed episode, each turn receives a different signal. Lowering γ shrinks the share of the outcome reward for earlier turns. 한 에피소드: 프롬프트 → (생각 → tool 호출 → tool 결과) × 3 → 최종 답. 칸 하나가 토큰 하나이고, 색은 그 토큰이 받는 advantage(파랑 +, 빨강 −), 빗금은 loss에서 빠진 토큰이다. 테두리: 보라 = tool 호출, 초록 = 최종 답. tool 출력 mask를 끄면 환경이 쓴 토큰까지 학습된다. 모델이 tool 결과를 "예측"하도록, 즉 지어내도록 배우는 것이다. turn별 보상으로 바꾸고 오른쪽 rk 칸을 클릭해 보상을 바꿔 보면, 같은 실패 에피소드 안에서도 turn마다 다른 신호가 간다. γ를 낮추면 앞쪽 turn일수록 결과 보상의 몫이 줄어든다.
  1. In the default state (outcome reward only, γ=1) every model token gets the same advantage R−bR-b. That is exactly what GRPO does. Switch the outcome to failure and everything turns red. Even if the first turn’s search was a good choice, it is punished along with the rest.
  2. Turn the tool-output mask off and the tool rows get a red outline; more than a third of the trained tokens become tokens the model did not write.
  3. Switch to “per-turn reward” and T1 (successful search) and T2 (code error) receive different signals. Click the rkr_k cells on the right to change them.
  4. Lower γ to 0.7 and the outcome reward shrinks by γK−k\gamma^{K-k} as you move to earlier turns. The early part of a long episode carries less responsibility for the outcome.

Credit assignment: outcome reward vs turn reward

Broadcasting a single outcome reward to every token is simple and unbiased, but its variance grows with the horizon. When an episode with 30 tool calls fails, the gradient carries no information about which call was the problem. Only the average over many episodes sorts that out.

With turn-level rewards, the return and advantage of turn kk are

Gk=∑j≥kγ j−krj,A^k=Gk−bkG_k=\sum_{j\ge k}\gamma^{\,j-k}r_j,\qquad \hat A_k = G_k - b_k

and A^k\hat A_k is given to every model token of turn kk. There are roughly three options.

  • Outcome reward only + group baseline. Search-R1 and many SWE and coding agent RL setups do this. It is unbiased and leaves little room for hacking. Its sample efficiency is low.
  • Turn reward (process reward). Intermediate signals such as whether a tool call parses, how many more tests pass, or whether the search results contain the answer. Denser, but itself a new proxy and therefore a target of over-optimization — for example, meaningless calls that merely get the format right start to multiply.
  • Turn-level value. Like ArCHer, learn an utterance-level critic V(hk)V(h_k) and use A^k=rk+γV(hk+1)−V(hk)\hat A_k = r_k+\gamma V(h_{k+1})-V(h_k). It is the turn version of GAE. RLVR’s problem — critics are hard to train — comes right back. Another approach continues several times from the same intermediate state and uses the average as a baseline (GRPO’s group, pushed down to the turn level).

A discount γ\gamma applied per token makes an outcome thousands of tokens later almost zero, so token-level γ=1\gamma=1 is the norm in LLM RL. If you discount at all, do it per turn.

→ Go deeper: Long-horizon RL — credit assignment, context management and budgets when trajectories run to hundreds of turns.

Environments and verifiers

In agent RL the environment doubles as the dataset. A good environment is (1) graded automatically, (2) reproducible, and (3) hard for the policy to find loopholes in.

EnvironmentActionsRewardWatch out for
Code execution / math + interpreter (ReTool)write and run codefinal-answer match, tests passingsandbox, time limits, hiding tests
SWE (SWE-bench-style, SWE-RL)explore the repo, edit files, run testshidden tests pass, patch similarityforbid editing test files, container cost
Search agent (Search-R1)search queries, reading documentsfinal-answer matchmasking search results, search API latency
Web browsing (WebArena-style)click, type, navigatejudged arrival at goal statestate reset, nondeterminism
Games and puzzles (RAGEN etc.)move, choosewin/loss, scorenarrow generalisation

A single SWE environment includes a Docker container, a repository, dependency installation and test execution. One rollout can take minutes, and most of that time is spent by the environment, not the GPU. That leads into the systems problem of the next section.

Rollout systems: synchronous vs asynchronous

Even in single-turn RLVR, the long tail of response lengths made waiting for the longest response in a batch a problem. For agents, tool latency (search APIs, tests inside containers, web page loads) is added and the tail becomes much heavier.

  1. 기본 상태(결과 보상만, γ=1)에서는 모든 모델 토큰이 같은 advantage R−bR-b를 받는다. GRPO가 하는 일과 같다. 결과를 실패로 바꾸면 전부 빨강이 된다. 첫 turn의 검색이 좋은 선택이었어도 같이 벌을 받는다.
  2. tool 출력 mask를 끄면 tool 행에 빨간 테두리가 생기고, 학습 토큰의 3분의 1 이상이 모델이 쓰지 않은 토큰이 된다.
  3. “turn별 보상”으로 바꾸면 T1(검색 성공)과 T2(코드 에러)가 서로 다른 신호를 받는다. 오른쪽 rkr_k 칸을 클릭해 바꿔 보자.
  4. γ를 0.7로 낮추면 결과 보상이 앞 turn으로 갈수록 γK−k\gamma^{K-k}로 줄어든다. 긴 에피소드의 앞부분은 결과에 대한 책임을 덜 진다.

credit assignment: 결과 보상 vs turn 보상

결과 보상 하나를 모든 토큰에 방송하는 방식은 단순하고 편향이 없지만, horizon이 길수록 분산이 커진다. 30번 tool을 호출한 에피소드가 실패했을 때, 그중 어느 호출이 문제였는지에 대한 정보가 gradient에 없다. 많은 에피소드의 평균으로만 그것을 가려낸다.

turn 단위 보상을 쓰면 turn kk의 return과 advantage는

Gk=∑j≥kγ j−krj,A^k=Gk−bkG_k=\sum_{j\ge k}\gamma^{\,j-k}r_j,\qquad \hat A_k = G_k - b_k

가 되고 A^k\hat A_k를 turn kk의 모델 토큰 전부에 준다. 선택지는 대략 세 가지다.

  • 결과 보상만 + 그룹 baseline. Search-R1, 많은 SWE·코딩 agent RL이 이 방식이다. 편향이 없고 해킹 여지가 적다. 표본 효율이 낮다.
  • turn 보상(process reward). tool 호출이 파싱되는지, 테스트가 몇 개 더 통과하는지, 검색 결과에 정답이 들어 있는지 같은 중간 신호. 밀도가 높지만 그 자체가 새 proxy라 과최적화의 대상이 된다. 형식만 맞춘 무의미한 호출이 늘어나는 식이다.
  • turn 단위 value. ArCHer처럼 발화 단위 critic V(hk)V(h_k)를 학습해 A^k=rk+γV(hk+1)−V(hk)\hat A_k = r_k+\gamma V(h_{k+1})-V(h_k)를 쓴다. GAE의 turn 버전이다. critic 학습이 어렵다는 RLVR의 문제가 그대로 돌아온다. 같은 중간 상태에서 여러 번 이어 써서 그 평균을 baseline으로 쓰는 방식(GRPO의 그룹을 turn 수준으로 내린 것)도 쓰인다.

할인율 γ\gamma를 토큰 단위로 걸면 수천 토큰 뒤의 결과가 거의 0이 되므로 LLM RL에서는 토큰 단위 γ=1\gamma=1이 보통이다. 할인을 쓴다면 turn 단위로 건다.

→ 더 깊이: Long-horizon RL — trajectory가 수백 turn으로 길어질 때의 credit assignment, 문맥 관리, 예산.

환경과 검증기

agent RL에서 환경은 데이터셋의 역할을 겸한다. 좋은 환경은 (1) 자동으로 채점되고, (2) 결과를 재현할 수 있고, (3) 정책이 허점을 찾기 어렵다.

환경행동보상주의할 점
코드 실행 / 수학+인터프리터 (ReTool)코드 작성·실행최종 답 일치, 테스트 통과샌드박스, 시간 제한, 테스트 숨기기
SWE (SWE-bench류, SWE-RL)저장소 탐색, 파일 편집, 테스트 실행숨겨진 테스트 통과, 패치 유사도테스트 파일 수정 금지, 컨테이너 비용
검색 agent (Search-R1)검색 질의, 문서 읽기최종 답 일치검색 결과 masking, 검색 API 지연
웹 브라우징 (WebArena류)클릭, 입력, 이동목표 상태 도달 판정상태 리셋, 비결정성
게임·퍼즐 (RAGEN 등)이동, 선택승패, 점수일반화가 좁다

SWE 환경 하나는 Docker 컨테이너, 저장소, 의존성 설치, 테스트 실행을 포함한다. rollout 한 번이 수 분이 걸릴 수 있고, 그 시간의 대부분은 GPU가 아니라 환경이 쓴다. 이것이 다음 절의 시스템 문제로 이어진다.

rollout 시스템: 동기 vs 비동기

단일 턴 RLVR에서도 응답 길이의 긴 꼬리 때문에 배치의 가장 긴 응답을 기다리는 시간이 문제였다. agent에서는 tool 지연(검색 API, 컨테이너 안의 테스트, 웹 페이지 로딩)이 더해져 꼬리가 훨씬 무거워진다.

동기: 학습 stepsync: train steps – slot 유휴slot idle – 비동기: 학습 stepasync: train steps – staleness 평균staleness mean – / 최대max –
Each row is one rollout slot; the horizontal axis is time. Dark cells = model generation, orange = waiting for a tool, grey = idle, violet = training. The top (synchronous) waits for the slowest episode in the batch before training; the bottom (asynchronous) never lets a slot rest — it starts the next episode right away, and the trainer trains whenever N finished episodes have accumulated. The colour of the generation cells at the bottom shows how many versions stale that episode is when it is used for training (blue 0, teal 1, red 2, black 3 or more). Increase σ and the grey (idle) on the synchronous side grows, while the asynchronous side runs without idling but with more stale episodes. 각 행은 rollout slot 하나, 가로축은 시간이다. 진한 칸 = 모델 생성, 주황 = tool 대기, 회색 = 유휴, 보라 = 학습. 위(동기)는 배치의 가장 느린 에피소드를 기다린 뒤 학습하고, 아래(비동기)는 slot이 쉬지 않고 다음 에피소드를 시작하며 trainer가 끝난 에피소드 N개가 모일 때마다 학습한다. 아래쪽 생성 칸의 색은 그 에피소드가 학습에 쓰일 때 몇 버전 낡았는지(파랑 0, 청록 1, 빨강 2, 검정 3 이상)다. σ를 키우면 동기 쪽 회색(유휴)이 늘고, 비동기 쪽은 유휴 없이 돌지만 낡은 에피소드가 늘어난다.
  1. Lower σ to 0 and tool latency becomes constant, so synchronous idling is small. Raise σ towards 1.5 and in every batch everyone waits for one slow episode; the grey grows.
  2. On the asynchronous side the slots never rest, so there are more training steps in the same time. In exchange, teal, red and black mix in the generation cells. The longer the episode, the more updates fall between the policy at its start and the policy at training time.
  3. Increase N and, in the synchronous scheme, “the slowest one” gets slower (the maximum grows with the number of samples) and idling increases.

The synchronous scheme is strictly on-policy but slow; the asynchronous scheme is fast but off-policy by its staleness. Real systems pick somewhere in between.

  • colocated / hybrid engine (verl’s HybridFlow): the same GPUs alternate between generation and training. Synchronous and memory-efficient.
  • disaggregated + asynchronous (AReaL etc.): generation GPUs and training GPUs are separate, and generation never stops. Staleness is capped (samples that are too old are discarded, or generation pauses briefly) and a ratio correction goes into the loss.
  • partial rollout (Kimi k1.5): rollouts that are too long are cut off in this iteration and continued in the next. Several policy versions are mixed within one trajectory.

Either way, the samples used for training come not from the πθ\pi_\theta currently being trained but from a slightly earlier policy, and from a different engine (vLLM, SGLang). How to correct for that difference is the topic of the next lesson.

→ Go deeper: the agent RL framework landscape and verl today for how real systems are built; asynchronous RL systems compared and asynchronous RL and staleness for the staleness trade-off; agent loops and environments for tool latency, sandboxes and concurrency.

확인 문제Check yourself

You train a multi-turn search agent and put the loss on 'every token except the prompt'. Which problem is most likely to appear as training goes on?

∇log⁡Pθ(τ)\nabla\log P_\theta(\tau) has no environment term. Putting the loss on tool-result tokens amounts to adding ∇log⁡πθ(ok∣hk,ak)\nabla\log\pi_\theta(o_k\mid h_k,a_k), which teaches the model to “predict” — that is, make up — search results. And because tool output is text the model did not write, many of its tokens have very low log-prob, and both the gradient and the training–inference numerical mismatch at those positions grow. If a correct trajectory’s advantage is positive, this hallucination is even reinforced.

Implementing it

We unroll a multi-turn trajectory into a token-level array and build per-token advantages from an outcome reward and from turn rewards. · marks tokens excluded from the loss; +/- is the sign of the advantage.

NumPy Masks and per-token advantages in a multi-turn trajectory
import numpy as np

# Write one episode as (role, number of tokens, turn) pieces. tool = tokens written by the environment
segments = [("prompt", 14, -1),
            ("model", 14, 0), ("tool", 16, 0),
            ("model", 13, 1), ("tool",  9, 1),
            ("model", 14, 2), ("tool",  7, 2),
            ("model", 11, 3)]
role = np.concatenate([[r] * n for r, n, _ in segments])
turn = np.concatenate([[k] * n for _, n, k in segments])
loss_mask = (role == "model").astype(float)        # 1 only for tokens the policy generated

def turn_advantages(turn_rewards, R, gamma=1.0, baseline=0.0):
    """Return of turn k, G_k = Σ_{j≥k} γ^{j-k} r_j (outcome reward R on the last turn), minus a discounted baseline."""
    r = np.array(turn_rewards, float); r[-1] += R
    K = len(r); G = np.zeros(K); g = 0.0
    for k in reversed(range(K)):
        g = r[k] + gamma * g; G[k] = g
    return G - baseline * gamma ** (K - 1 - np.arange(K))

def to_tokens(A_turn):
    A_tok = np.where(turn >= 0, A_turn[np.maximum(turn, 0)], 0.0)
    return A_tok * loss_mask                          # environment tokens get zero gradient

def show(A_tok):
    return "".join("·" if m == 0 else ("+" if a > 0.05 else "-" if a < -0.05 else "0")
                   for a, m in zip(A_tok, loss_mask))

print("token roles:", "".join({"prompt": "p", "model": "M", "tool": "t"}[r] for r in role))
A_out = turn_advantages([0, 0, 0, 0], R=0.0, gamma=1.0, baseline=0.4)       # a failed episode
print("outcome only:", show(to_tokens(A_out)), "  A_k =", np.round(A_out, 2))
A_turn = turn_advantages([0.3, -0.3, 0.2, 0], R=0.0, gamma=0.9, baseline=0.1)  # search succeeded +, code error −
print("turn reward :", show(to_tokens(A_turn)), "  A_k =", np.round(A_turn, 2))
print(f"trained tokens {int(loss_mask.sum())} / total {len(role)}  ({int((1-loss_mask).sum())} prompt and tool-output tokens excluded)")

# --- 4 trajectories for the same question, as in GRPO: similar model-token counts, very different tool-output lengths
R = np.array([1.0, 0.0, 1.0, 0.0])
n_model = np.array([40, 52, 35, 60])               # tokens written by the model
n_tool  = np.array([20, 400, 30, 900])              # tokens inserted by the environment (long search results etc.)
A = (R - R.mean()) / (R.std() + 1e-6)
G = len(R)
w_ok  = A / (G * n_model)                           # seq-mean: average over model tokens
w_bug = A / (G * (n_model + n_tool))                # mistake: tool tokens included in the denominator
print("\nweight of one model token  (correct mask / tool in denominator)")
for i in range(G):
    print(f"  traj {i}: R={R[i]:.0f}  tool tokens {n_tool[i]:4d}  →  {w_ok[i]:+.5f} / {w_bug[i]:+.5f}"
          f"   (ratio {w_bug[i] / w_ok[i]:.2f})")
print("the longer a trajectory's tool output, the more its signal is diluted → a failed long search is barely punished")
 

The second part shows a subtle bug. Even if the mask is applied correctly to the numerator, putting tool tokens into the denominator (the count for the token average) dilutes the model tokens of trajectories with long tool outputs. A trajectory that received a 900-token search result and failed is barely punished. The numerator and the denominator of the loss must use the same mask.

Next, a small example of why “exactly the token ids” matters.

NumPy Off-policy introduced by decode → re-tokenise
VOCAB = ["Hello", "Hel", "lo", " world", " wor", "ld", "!", " "]

def encode(text):                      # a simple tokenizer that matches the longest token first
    out = []
    while text:
        tok = max((v for v in VOCAB if text.startswith(v)), key=len)
        out.append(tok); text = text[len(tok):]
    return out

sampled = ["Hel", "lo", " wor", "ld", "!"]    # tokens the rollout engine actually sampled
text = "".join(sampled)                      # stored after decoding to a string,
retok = encode(text)                         # then re-tokenized at training time
print("sampled tokens  :", sampled, len(sampled), "tokens")
print("re-tokenized    :", retok, len(retok), "tokens")
print("same string, different token sequence →", sampled != retok)
print("the trainer ends up computing log-probs of a sequence the policy never generated (off-policy, mask boundaries shift too)")
 

With real BPE tokenizers, too, several token sequences produce the same string. If the policy occasionally samples a “non-canonical” token sequence, the re-tokenized version is a sequence the policy never produced. The same happens when a tool-call JSON is parsed and re-serialised (whitespace, key order). The standard practice is to take token ids and log-probs straight from the rollout engine and pass them to the trainer.

Finally, the PyTorch form. Concatenate the pieces built with the chat template while building a per-role mask, and compute the loss minding the shift-by-one alignment (the logits at position tt predict token t+1t{+}1).

PyTorch PyTorch: multi-turn mask and PPO/GRPO loss 로컬에서 실행run locally (pip install torch)
import torch

def pack_episode(segments):
    """segments: [(token_ids, role, turn)] — token ids exactly as returned by the rollout engine.
    role ∈ {"prompt", "assistant", "tool"}. Concatenated in the same order."""
    ids = torch.cat([torch.as_tensor(t, dtype=torch.long) for t, _, _ in segments])
    asst = torch.cat([torch.full((len(t),), r == "assistant", dtype=torch.bool) for t, r, _ in segments])
    turn = torch.cat([torch.full((len(t),), k, dtype=torch.long) for t, _, k in segments])
    return ids, asst, turn

def token_advantages(turn, asst, turn_adv):
    """Broadcast turn-level advantages (K,) to that turn's assistant tokens."""
    adv = turn_adv[turn.clamp(min=0)]
    return torch.where(asst, adv, torch.zeros_like(adv))

def agent_pg_loss(model, ids, asst, adv, old_logp, eps=0.2):
    """ids/asst/adv/old_logp: (B, T). old_logp is the rollout engine's log-prob of the sampled tokens (same position alignment)."""
    logits = model(ids).logits[:, :-1].float()          # position t → predicts token t+1
    tgt = ids[:, 1:]
    logp = torch.log_softmax(logits, -1).gather(-1, tgt.unsqueeze(-1)).squeeze(-1)
    m = asst[:, 1:].float()                             # only positions whose target is a model token
    A = adv[:, 1:]
    ratio = torch.exp(logp - old_logp[:, 1:])
    surr = torch.minimum(ratio * A, ratio.clamp(1 - eps, 1 + eps) * A)
    return -(surr * m).sum() / m.sum().clamp(min=1)     # same mask in numerator and denominator
 
확인 문제Check yourself

Switching to asynchronous rollout doubled training throughput, but training became unstable on long episodes. What should you suspect first?

As seen in the figure, in the asynchronous scheme the longer an episode takes, the more policy updates fall between its generation and its training. Long episodes are also the stalest samples. Using them as if they were on-policy biases the gradient; the PPO ratio leaves the clip range often and the signal is thrown away, or, used without correction, the variance grows. Capping staleness, importance-sampling correction, and measuring the training–inference engine mismatch are the next steps — and that is the next lesson.

Summary

  • An agent trajectory alternates model tokens and environment observations. ∇log⁡Pθ(τ)\nabla\log P_\theta(\tau) has no environment term, so the loss goes only on tokens the model sampled (in both numerator and denominator).
  • Broadcasting only the outcome reward is unbiased but has high variance over long horizons. Turn rewards add density but become a new proxy, and turn-level critics are hard to train.
  • The environment is both dataset and reward. Automatic grading, reproducibility and closing loopholes (hidden tests, sandboxes) are at the heart of its design.
  • The tool format is fixed in the chat template, and the rollout’s token ids must be used for training as they are. Re-tokenization creates silent off-policy data.
  • Because of the long tail of tool latency, synchronous rollout idles a lot and asynchronous rollout creates staleness. The trade-off between them is central to agent RL system design.
  1. σ를 0으로 내리면 tool 지연이 일정해 동기 방식의 유휴가 작다. σ를 1.5 쪽으로 올리면 배치마다 느린 에피소드 하나를 모두가 기다리며 회색이 늘어난다.
  2. 비동기 쪽은 slot이 쉬지 않아 같은 시간에 학습 step이 더 많다. 대신 생성 칸에 청록·빨강·검정이 섞인다. 긴 에피소드일수록 시작할 때의 정책과 학습할 때의 정책 사이에 여러 번의 업데이트가 끼어 있다.
  3. N을 키우면 동기 방식에서는 “가장 느린 것”이 더 느려지고(최댓값은 표본 수에 따라 커진다) 유휴가 늘어난다.

동기 방식은 엄밀하게 on-policy지만 느리고, 비동기 방식은 빠르지만 staleness만큼 off-policy다. 실제 시스템은 그 사이 어딘가를 고른다.

  • colocated / hybrid engine (verl의 HybridFlow): 같은 GPU가 생성과 학습을 번갈아 한다. 동기적이고 메모리 효율이 좋다.
  • disaggregated + 비동기 (AReaL 등): 생성 GPU와 학습 GPU를 나누고, 생성은 멈추지 않는다. staleness에 상한을 두고(너무 낡은 샘플은 버리거나 생성을 잠시 멈춤) ratio 보정을 손실에 넣는다.
  • partial rollout (Kimi k1.5): 너무 긴 rollout은 이번 iteration에서 끊어 두고 다음 iteration에서 이어 쓴다. 한 trajectory 안에 여러 정책 버전이 섞인다.

어느 쪽이든 학습에 쓰는 샘플은 지금 학습 중인 πθ\pi_\theta가 아니라 조금 전의 정책, 그리고 다른 엔진(vLLM, SGLang)이 만든 것이다. 그 차이를 어떻게 보정하는지가 다음 레슨의 주제다.

→ 더 깊이: 실제 시스템의 구조는 Agent RL 프레임워크 지형도와 verl 오늘, staleness 트레이드오프는 비동기 RL 시스템 비교와 비동기 RL과 staleness, tool 지연·sandbox·동시성은 Agent loop과 환경.

확인 문제Check yourself

멀티턴 검색 agent를 학습하는데, 손실을 '프롬프트를 제외한 모든 토큰'에 걸었다. 학습이 진행될수록 생길 가능성이 가장 큰 문제는?

∇log⁡Pθ(τ)\nabla\log P_\theta(\tau)에는 환경 항이 없다. tool 결과 토큰에 손실을 걸면 ∇log⁡πθ(ok∣hk,ak)\nabla\log\pi_\theta(o_k\mid h_k,a_k)를 더하는 셈이고, 이는 모델이 검색 결과를 “예측”하도록, 즉 지어내도록 가르친다. 또 tool 출력은 모델이 쓰지 않은 텍스트라 log-prob이 매우 낮은 토큰이 많고, 그 위치의 gradient와 학습–추론 수치 불일치가 커진다. 정답 trajectory의 advantage가 양수이면 이 환각이 강화되기까지 한다.

직접 구현하기

멀티턴 trajectory를 토큰 단위 배열로 펼치고, 결과 보상과 turn 보상에서 토큰별 advantage를 만든다. ·는 loss에서 빠진 토큰, +/-는 advantage의 부호다.

NumPy 멀티턴 trajectory의 마스크와 토큰별 advantage
import numpy as np

# 한 에피소드를 (역할, 토큰 수, turn) 조각으로 적는다. tool = 환경이 쓴 토큰
segments = [("prompt", 14, -1),
            ("model", 14, 0), ("tool", 16, 0),
            ("model", 13, 1), ("tool",  9, 1),
            ("model", 14, 2), ("tool",  7, 2),
            ("model", 11, 3)]
role = np.concatenate([[r] * n for r, n, _ in segments])
turn = np.concatenate([[k] * n for _, n, k in segments])
loss_mask = (role == "model").astype(float)        # 정책이 생성한 토큰만 1

def turn_advantages(turn_rewards, R, gamma=1.0, baseline=0.0):
    """turn k의 return G_k = Σ_{j≥k} γ^{j-k} r_j (마지막 turn에 결과 보상 R) − 할인된 baseline."""
    r = np.array(turn_rewards, float); r[-1] += R
    K = len(r); G = np.zeros(K); g = 0.0
    for k in reversed(range(K)):
        g = r[k] + gamma * g; G[k] = g
    return G - baseline * gamma ** (K - 1 - np.arange(K))

def to_tokens(A_turn):
    A_tok = np.where(turn >= 0, A_turn[np.maximum(turn, 0)], 0.0)
    return A_tok * loss_mask                          # 환경 토큰은 gradient 0

def show(A_tok):
    return "".join("·" if m == 0 else ("+" if a > 0.05 else "-" if a < -0.05 else "0")
                   for a, m in zip(A_tok, loss_mask))

print("토큰 역할:", "".join({"prompt": "p", "model": "M", "tool": "t"}[r] for r in role))
A_out = turn_advantages([0, 0, 0, 0], R=0.0, gamma=1.0, baseline=0.4)       # 실패한 에피소드
print("결과 보상만 :", show(to_tokens(A_out)), "  A_k =", np.round(A_out, 2))
A_turn = turn_advantages([0.3, -0.3, 0.2, 0], R=0.0, gamma=0.9, baseline=0.1)  # 검색 성공 +, 코드 에러 −
print("turn 보상   :", show(to_tokens(A_turn)), "  A_k =", np.round(A_turn, 2))
print(f"학습되는 토큰 {int(loss_mask.sum())} / 전체 {len(role)}  (프롬프트·tool 출력 {int((1-loss_mask).sum())}개 제외)")

# --- GRPO처럼 같은 질문의 trajectory 4개: 모델 토큰 수는 비슷하고 tool 출력 길이는 크게 다르다
R = np.array([1.0, 0.0, 1.0, 0.0])
n_model = np.array([40, 52, 35, 60])               # 모델이 쓴 토큰 수
n_tool  = np.array([20, 400, 30, 900])              # 환경이 넣은 토큰 수 (긴 검색 결과 등)
A = (R - R.mean()) / (R.std() + 1e-6)
G = len(R)
w_ok  = A / (G * n_model)                           # seq-mean: 모델 토큰 수로 평균
w_bug = A / (G * (n_model + n_tool))                # 실수: tool 토큰까지 분모에 넣음
print("\n모델 토큰 하나의 가중치  (올바른 mask / 분모에 tool 포함)")
for i in range(G):
    print(f"  traj {i}: R={R[i]:.0f}  tool 토큰 {n_tool[i]:4d}  →  {w_ok[i]:+.5f} / {w_bug[i]:+.5f}"
          f"   (비 {w_bug[i] / w_ok[i]:.2f})")
print("tool 출력이 길었던 trajectory일수록 신호가 희석된다 → 실패한 긴 검색이 거의 벌을 받지 않는다")
 

두 번째 부분은 미묘한 버그를 보여 준다. 마스크를 분자에는 제대로 걸었어도 분모(토큰 평균의 개수)에 tool 토큰을 넣으면, tool 출력이 긴 trajectory의 모델 토큰이 희석된다. 900토큰짜리 검색 결과를 받고 실패한 trajectory가 거의 벌을 받지 않는다. 손실의 분자와 분모 모두 같은 마스크를 써야 한다.

다음은 “토큰 id 그대로”가 왜 중요한지 보여 주는 작은 예다.

NumPy 디코드 → 재토큰화가 만드는 off-policy
VOCAB = ["Hello", "Hel", "lo", " world", " wor", "ld", "!", " "]

def encode(text):                      # 가장 긴 토큰부터 맞추는 단순 tokenizer
    out = []
    while text:
        tok = max((v for v in VOCAB if text.startswith(v)), key=len)
        out.append(tok); text = text[len(tok):]
    return out

sampled = ["Hel", "lo", " wor", "ld", "!"]    # rollout 엔진이 실제로 샘플한 토큰
text = "".join(sampled)                      # 문자열로 디코드해 저장했다가
retok = encode(text)                         # 학습 때 다시 토큰화하면
print("샘플된 토큰  :", sampled, len(sampled), "개")
print("재토큰화 결과:", retok, len(retok), "개")
print("같은 문자열, 다른 토큰열 →", sampled != retok)
print("학습기는 정책이 생성하지 않은 시퀀스의 log-prob을 계산하게 된다 (off-policy, mask 경계도 어긋남)")
 

실제 BPE tokenizer에서도 같은 문자열을 만드는 토큰열은 여러 개다. 정책이 드물게 “비정규” 토큰열을 샘플하면, 재토큰화된 버전은 정책이 낸 적 없는 시퀀스다. tool 호출 JSON을 파싱했다가 다시 직렬화하는 과정(공백, 키 순서)에서도 같은 일이 생긴다. rollout 엔진에서 토큰 id와 log-prob을 그대로 받아 학습기로 넘기는 것이 정석이다.

마지막으로 PyTorch에서의 형태다. chat template으로 만든 조각들을 이어 붙이며 역할별 마스크를 만들고, 한 칸 밀린 정렬(위치 tt의 logits가 토큰 t+1t{+}1을 예측)에 주의해 손실을 계산한다.

PyTorch PyTorch: 멀티턴 마스크와 PPO/GRPO 손실 로컬에서 실행run locally (pip install torch)
import torch

def pack_episode(segments):
    """segments: [(token_ids, role, turn)] — rollout 엔진이 돌려준 토큰 id 그대로.
    role ∈ {"prompt", "assistant", "tool"}. 같은 순서로 이어 붙인다."""
    ids = torch.cat([torch.as_tensor(t, dtype=torch.long) for t, _, _ in segments])
    asst = torch.cat([torch.full((len(t),), r == "assistant", dtype=torch.bool) for t, r, _ in segments])
    turn = torch.cat([torch.full((len(t),), k, dtype=torch.long) for t, _, k in segments])
    return ids, asst, turn

def token_advantages(turn, asst, turn_adv):
    """turn 단위 advantage (K,)를 그 turn의 assistant 토큰에 방송."""
    adv = turn_adv[turn.clamp(min=0)]
    return torch.where(asst, adv, torch.zeros_like(adv))

def agent_pg_loss(model, ids, asst, adv, old_logp, eps=0.2):
    """ids/asst/adv/old_logp: (B, T). old_logp는 rollout 엔진이 준 샘플 토큰의 log-prob(위치 정렬 동일)."""
    logits = model(ids).logits[:, :-1].float()          # 위치 t → 토큰 t+1 예측
    tgt = ids[:, 1:]
    logp = torch.log_softmax(logits, -1).gather(-1, tgt.unsqueeze(-1)).squeeze(-1)
    m = asst[:, 1:].float()                             # 예측 대상이 모델 토큰인 위치만
    A = adv[:, 1:]
    ratio = torch.exp(logp - old_logp[:, 1:])
    surr = torch.minimum(ratio * A, ratio.clamp(1 - eps, 1 + eps) * A)
    return -(surr * m).sum() / m.sum().clamp(min=1)     # 분자·분모 모두 같은 마스크
 
확인 문제Check yourself

비동기 rollout으로 바꾸자 학습 처리량이 두 배가 되었지만, 길이가 긴 에피소드에서 학습이 불안정해졌다. 가장 먼저 의심할 것은?

그림에서 본 것처럼 비동기 방식에서는 오래 걸리는 에피소드일수록 생성과 학습 사이에 더 많은 정책 업데이트가 끼어든다. 긴 에피소드는 가장 낡은 샘플이기도 하다. 그 샘플을 on-policy처럼 쓰면 gradient가 편향되고, PPO ratio가 clip 밖으로 많이 나가 신호가 버려지거나, 보정 없이 쓰면 분산이 커진다. staleness 상한, importance sampling 보정, 학습–추론 엔진 차이의 측정이 다음 단계이고, 그것이 다음 레슨이다.

정리

  • agent trajectory는 모델 토큰과 환경 관측이 번갈아 나온다. ∇log⁡Pθ(τ)\nabla\log P_\theta(\tau)에는 환경 항이 없으므로 손실은 모델이 샘플한 토큰에만 건다(분자와 분모 모두).
  • 결과 보상만 방송하면 편향은 없지만 긴 horizon에서 분산이 크다. turn 보상은 밀도를 주지만 새 proxy가 되고, turn 단위 critic은 학습이 어렵다.
  • 환경은 데이터셋이자 보상이다. 자동 채점, 재현성, 허점 차단(테스트 숨기기, 샌드박스)이 설계의 핵심이다.
  • tool 형식은 chat template에 고정되고, rollout의 토큰 id를 그대로 학습에 써야 한다. 재토큰화는 조용한 off-policy를 만든다.
  • tool 지연의 긴 꼬리 때문에 동기 rollout은 유휴가 크고, 비동기 rollout은 staleness를 만든다. 둘 사이의 trade-off가 agent RL 시스템 설계의 중심이다.

더 읽을거리Further reading