Field Log · Entry

Agent Trajectory Learning: Long-Horizon Credit Assignment (9/10)

긴 Agent episode를 상태 관찰 행동 보상 전이로 기록하고 outcome과 step reward를 각 결정에 배분해 offline imitation과 on-policy 학습 및 replay 평가로 연결하는 구조

오늘의 결론

  • Agent 학습 단위는 마지막 답 한 문장이 아니라 state → observation → action → environment transition이 반복되는 episode입니다.
  • 성공 trajectory만 behavior cloning하면 흔한 경로는 빨리 배우지만, 작은 실수가 누적된 뒤 처음 보는 state에서 복구하지 못합니다. 실패·수정 trajectory와 on-policy rollout이 필요합니다.
  • 최종 성공 보상만 주면 어떤 행동이 기여했는지 알기 어렵고, step reward만 강하게 주면 평가기를 만족하는 과정 흉내를 낼 수 있습니다. Outcome, process, cost, safety를 분리해 credit을 배분합니다.
  • Agent environment는 움직입니다. 검색 index, webpage, tool version, clock이 달라지면 같은 action의 결과가 달라집니다. Snapshot, replay, idempotency, fault injection 없이는 학습과 평가를 재현하기 어렵습니다.
  • Long-horizon 성능은 평균 답 정확도보다 task success, policy violation, loop, redundant action, recovery, cost, latency, checkpoint별 state coverage로 평가합니다.

앞 글에서는 개별 function call을 schema와 sandbox execution으로 학습했습니다. 이번에는 여러 tool call과 관찰이 이어지는 전체 Agent episode에서 어느 행동을 어떻게 학습할지 다룹니다.

initial state s0
  → action a0
  → observation o1 / state s1
  → action a1
  → ...
  → terminal state sT + outcome

trajectory store
  → offline imitation / preference / value targets
  → on-policy rollout in versioned environment
  → outcome + process + cost + safety rewards
  → credit assignment to decisions
  → replay evaluation and canary

이 글에서 답하는 질문

  1. Agent trajectory에 무엇을 저장해야 재현하고 학습할 수 있는가?
  2. Behavior cloning의 compounding error는 왜 생기는가?
  3. Offline 학습과 on-policy reinforcement learning은 언제 다른가?
  4. 최종 outcome을 여러 action에 어떻게 배분하는가?
  5. 실패 trajectory와 recovery를 어떤 target으로 바꾸는가?
  6. 움직이는 tool·검색 environment에서 어떻게 공정하게 평가하는가?

Agent episode의 state observation action reward transition을 durable trace로 저장하고 offline imitation과 on-policy rollout에서 outcome process cost safety 신호를 credit assignment한 뒤 replay evaluation으로 검증하는 파이프라인

1. Agent를 POMDP로 보면 빠진 정보가 보인다

Agent는 environment의 모든 상태를 직접 알지 못합니다. 검색 index 내부, 외부 API 상태, 사용자의 실제 의도는 부분적으로만 관찰됩니다. 이를 partially observable Markov decision process(POMDP) 관점으로 쓰면 다음 요소가 있습니다.

  • Hidden state $s_t$: 실제 environment와 업무 상태
  • Observation $o_t$: tool result, user message, error
  • Agent memory $m_t$: 지금까지의 압축된 history와 durable state
  • Action $a_t$: tool call, answer, ask, approve request, stop
  • Transition $P(s_{t+1}\mid s_t,a_t)$
  • Reward $r_t$와 terminal outcome $R_T$

Policy는 관찰 history 또는 memory를 조건으로 action을 고릅니다.

$$ a_t \sim \pi_\theta(a_t \mid o_{\le t}, a_{<t}, m_t) $$

따라서 학습 데이터에 action text만 있고 당시 observation·tool version·memory가 없으면 같은 결정을 재현할 수 없습니다.

2. Trajectory는 대화 로그보다 더 구조적이어야 한다

다음과 같은 episode record를 생각해 봅시다.

{
  "episode_id": "rag-agent-20260716-0184",
  "task_id": "maintenance-root-cause",
  "policy_version": "agent@sha256:...",
  "environment": {
    "document_snapshot": "docs@sha256:...",
    "tool_registry": "[email protected]",
    "simulator": "[email protected]",
    "clock": "2026-07-16T08:00:00+09:00",
    "random_seed": 8142
  },
  "initial_state": {
    "user_scope": ["fab-a:maintenance:read"],
    "budget": {"max_steps": 8, "max_tool_calls": 5}
  },
  "steps": [
    {
      "t": 0,
      "observation_ref": "blob:obs-000",
      "memory_hash": "sha256:...",
      "action": {"type": "tool", "name": "resolve_alias", "args": {"alias": "ETCH-7"}},
      "action_logprob": -0.42,
      "validator": "pass",
      "result_ref": "blob:result-000",
      "latency_ms": 32,
      "cost": 0.001
    }
  ],
  "terminal": {
    "status": "success",
    "task_score": 1.0,
    "policy_violations": 0,
    "total_cost": 0.017
  }
}

Raw observation에는 개인정보·secret이 들어갈 수 있으므로 접근 통제된 blob과 redacted trace를 분리합니다. 학습용 export는 policy에 따라 필요한 field만 materialize합니다.

반드시 versioning할 것

  • Model checkpoint, tokenizer, prompt, chat template
  • Tool registry와 executor
  • Retrieval corpus·index·embedding model
  • Memory summarizer와 context selector
  • Evaluator와 reward model
  • Clock, locale, random seed, fault schedule

Agent 성능 변화가 policy 때문인지 environment 변화 때문인지 분리하려면 이 정보가 필요합니다.

3. ReAct가 trajectory 표현에 남긴 것

ReAct는 reasoning trace와 environment action을 교차해 생성하는 패턴을 제안했습니다.

Thought: 필요한 장비 ID가 별칭으로 주어졌다.
Action: resolve_alias("ETCH-7")
Observation: {"equipment_id": "EQ-00914"}
Thought: 이제 해당 ID로 문서를 검색한다.
Action: search_documents(...)
Observation: ...

이 형식의 핵심은 긴 생각을 공개하는 데 있지 않습니다. 관찰이 다음 행동을 어떻게 바꾸는지를 trajectory로 표현했다는 데 있습니다. Production 학습에서는 자유로운 Thought를 다음처럼 검증 가능한 typed state로 바꿀 수 있습니다.

{
  "known": {"equipment_id": "EQ-00914"},
  "unknown": ["alarm_time_range"],
  "evidence": [],
  "next_action": "ask_user",
  "reason_code": "missing_required_time_range"
}

Internal chain-of-thought를 저장하지 않아도 decision state, evidence, action, result를 학습할 수 있습니다.

4. Behavior cloning: 가장 쉬운 출발점

Expert trajectory $\tau_E$에서 assistant action의 likelihood를 최대화합니다.

$$ \mathcal{L}\text{BC} = -\sum{\tau_E}\sum_t \log \pi_\theta(a_t^E \mid h_t^E) $$

WebGPT는 text browser environment에서 imitation learning과 human feedback을 결합하고, reference를 수집하도록 해 long-form answer의 사실 평가를 돕는 초기 사례입니다. FireAct는 여러 task와 prompting method에서 생성된 Agent trajectory로 fine-tuning하는 방향을 연구했습니다. AgentTuningAgent-FLAN도 agent 능력을 위한 data mixture와 fine-tuning 설계를 확장했습니다.

Behavior cloning의 장점은 안정적이고 구현이 단순하다는 것입니다. 그러나 expert가 방문한 state에서만 학습합니다.

5. Compounding error: 한 번의 작은 실수가 분포를 바꾼다

한 step의 오류 확률이 작아도 horizon $T$가 길면 episode 실패 확률이 커집니다. 모든 step이 독립이고 정확도가 $1-\epsilon$이라고 단순화하면 전체 성공 확률은 다음과 같습니다.

$$ P(\text{all correct}) = (1-\epsilon)^T $$

실제 Agent에서는 오류가 독립적이지 않습니다. 잘못된 tool call이 이후 observation을 바꾸고, 모델은 expert data에서 보지 못한 state로 이동합니다.

expert state distribution dE
      ↓ one wrong action
student-only state dπ
      ↓ no recovery examples
more errors → loop / unsafe fallback / premature answer

이것이 성공 demonstration만 늘리는 것으로 해결되지 않는 이유입니다.

대응

  • Student rollout에서 자주 방문하는 failure state 수집
  • Expert 또는 verifier가 해당 state에서 corrective action annotation
  • Failure → diagnosis → repair → stop trajectory 포함
  • 짧은 horizon에서 시작해 길이를 늘리는 curriculum
  • On-policy 또는 dataset aggregation
  • 안전한 fallback을 terminal success의 일부로 정의

6. 실패 trajectory를 학습 신호로 바꾸는 네 방식

6.1 Corrective SFT

잘못된 action 직후의 state에 올바른 recovery action을 target으로 붙입니다.

observation: search timeout
bad action: repeat 9 times
target: retry once with backoff, then fallback / ask

Bad action 자체에 SFT loss를 주는 것이 아니라, 그 상태에서 원하는 action을 가르칩니다.

6.2 Pairwise preference

같은 initial state에서 성공·실패 또는 효율·비효율 trajectory를 비교합니다. 전체 trajectory가 너무 길면 결정적으로 갈린 prefix pair를 잘라 비교합니다.

6.3 Step labels

각 action을 valid, useful, safe, redundant, irreversible 같은 축으로 label합니다. 53편의 process verifier가 여기에 연결됩니다.

6.4 Outcome replay

Terminal outcome을 보면서 어떤 early decision이 이후 선택지를 막았는지 counterfactual하게 분석합니다. 실제로 실행하지 않은 action의 결과는 관찰되지 않으므로 simulator 또는 logged bandit correction 없이는 인과 효과를 단정하지 않습니다.

7. Offline 학습과 on-policy 학습

Offline

고정 trajectory store에서 BC, preference optimization, value learning을 수행합니다.

장점:

  • 재현 가능하고 실제 tool 비용이 적다.
  • Human·production failure를 반복 사용할 수 있다.
  • 위험한 exploration이 없다.

한계:

  • Dataset policy가 방문하지 않은 state를 배우기 어렵다.
  • 다른 policy가 만든 action의 counterfactual outcome이 없다.
  • 오래된 tool·corpus 분포를 학습할 수 있다.

On-policy

현재 policy가 versioned environment에서 직접 episode를 만듭니다.

장점:

  • Student가 실제로 만드는 오류 state를 수집한다.
  • Exploration과 recovery를 학습할 수 있다.
  • 현재 tool·policy에 가까운 분포다.

한계:

  • Rollout 비용과 환경 orchestration이 크다.
  • Reward hacking과 unsafe exploration 위험이 있다.
  • Non-determinism이 gradient noise와 평가 오차를 만든다.
  • Environment throughput이 GPU 학습을 기다리게 할 수 있다.

실전에서는 verified offline warm start → simulator on-policy → read-only canary 순으로 위험을 줄입니다.

8. Long-horizon credit assignment

Terminal reward $R_T$만 있을 때 모든 action에 같은 성공·실패 label을 붙이면 기여도를 구분하지 못합니다. Discounted return은 다음처럼 미래 reward를 현재 action에 연결합니다.

$$ G_t = \sum_{k=t}^{T} \gamma^{k-t} r_k $$

Policy gradient는 advantage $A_t$를 이용해 예상보다 좋았던 action의 확률을 높입니다.

$$ \nabla_\theta J(\theta) \approx \mathbb{E}\left[\sum_t \nabla_\theta \log \pi_\theta(a_t\mid h_t) A_t\right] $$

문제는 Agent의 reward가 sparse하고 긴 delay를 가진다는 점입니다. 첫 검색 query가 마지막 답의 성공에 영향을 줘도 중간에는 신호가 없습니다.

Credit을 더 잘 나누는 신호

  • Schema·authorization 같은 deterministic step validity
  • Tool execution success와 error type
  • Retrieval evidence recall과 sufficiency
  • State progress: required slot·subgoal 충족
  • Process reward model 또는 value model
  • Final task outcome, user preference, factuality
  • Call cost, latency, loop, policy violation

Reward를 합치되 로그는 분리한다

$$ r_t = w_p r_t^\text{progress} +w_v r_t^\text{valid} -w_c c_t -w_s p_t^\text{safety} $$

Terminal에는 task success를 둡니다. 학습에 weighted sum을 사용하더라도 trace에는 각 component를 그대로 저장해 어떤 shortcut이 생겼는지 분석합니다.

9. Outcome reward와 process reward의 긴장

Outcome only

장점은 목표와 직접 연결된다는 점입니다. 단점은 sparse하고 운이 섞인다는 점입니다. 검색 API가 우연히 좋은 결과를 반환하면 나쁜 query도 보상을 받을 수 있습니다.

Process only

Step마다 조밀한 신호를 주지만 evaluator가 선호하는 형식만 학습할 수 있습니다. “계획을 5단계로 쓰기”가 실제 성공보다 높은 보상을 받는다면 불필요한 verbosity가 늘어납니다.

2025년 preprint Encouraging Good Processes Without the Need for Good Answers는 Agent planning에서 process-oriented reinforcement learning을 탐구합니다. 최신 아이디어를 적용할 때는 process metric이 실제 terminal success, cost, safety와 상관되는지 독립 holdout에서 확인해야 합니다.

좋은 기본 원칙은 다음과 같습니다.

  • Hard safety violation은 최종 성공으로 상쇄하지 않는다.
  • Deterministic validity는 step gate로 준다.
  • Progress reward는 terminal success와 calibration한다.
  • Final task outcome을 제거하지 않는다.
  • Reward component별 ablation을 한다.

10. Hierarchical credit: token보다 decision boundary를 본다

Agent action 하나는 수십 token의 JSON이나 query 문자열일 수 있습니다. 모든 token에 terminal reward를 동일하게 퍼뜨리면 어느 결정이 중요한지 해석하기 어렵습니다.

Trajectory를 계층화합니다.

episode
  ├─ subgoal: identify equipment
  │    └─ action: resolve_alias(args)
  ├─ subgoal: retrieve evidence
  │    ├─ action: search(query_1)
  │    └─ action: rerank(candidates)
  └─ subgoal: answer or abstain
       └─ action: grounded_answer(claims)

각 decision boundary에 action ID, pre-state, post-state, local reward를 둡니다. Tool call 내부 token loss와 episode-level decision reward를 분리할 수 있습니다.

2025년 preprint Agent Lightning은 Agent execution과 RL training을 분리하고 trajectory를 training transition으로 변환하며 hierarchical credit assignment를 다루는 방향을 제안합니다. 특정 framework를 채택하지 않더라도 Agent runtime trace를 학습 가능한 transition으로 변환하는 adapter layer라는 관점은 유용합니다.

11. Environment non-determinism을 통제한다

같은 query도 시점에 따라 검색 결과가 바뀝니다. 외부 API가 timeout이거나 A/B 응답을 줄 수 있습니다. 같은 policy를 두 번 실행해 점수가 다르면 학습 신호와 regression 판정이 흔들립니다.

세 가지 평가 mode

Mode목적구성
Replay정확한 회귀 테스트기록된 action→observation fixture
Snapshot simulator정책 탐색고정 corpus·tool state, fault injection
Live canary실제 drift 감지제한된 read-only traffic, 반복 측정

Replay는 새로운 action의 counterfactual 결과를 제공하지 못합니다. Simulator는 fidelity가 한계입니다. Live canary는 현실적이지만 비결정적이고 비용이 듭니다. 세 mode가 서로를 대체하지 않습니다.

통계적 평가

  • 같은 task를 여러 seed로 반복
  • Success rate의 confidence interval
  • Policy A/B를 같은 environment snapshot에서 paired comparison
  • Tool error rate와 task difficulty로 stratification
  • Index freshness와 observation drift report

12. Side effect와 exploration을 분리한다

On-policy RL에서 “새 행동을 시도해 보라”는 exploration은 실제 시스템에서 위험합니다.

허용 가능한 exploration

  • Read-only search와 calculator
  • Simulator의 synthetic resource
  • Dry-run deploy·delete
  • Isolated coding sandbox
  • Fake email·payment endpoint

Production에서 금지할 exploration

  • 실제 결제·삭제·외부 메시지 발송
  • 권한 상승 시도
  • 임의 network egress
  • 실제 사용자의 private resource 탐색

Side-effect tool은 model policy가 아니라 trusted workflow가 approval token, idempotency key, compensating action을 관리합니다.

13. Durable execution이 학습 품질을 높인다

Episode가 중간에 worker 재시작으로 끊기면 실패를 policy 탓으로 잘못 기록할 수 있습니다. 27편의 원칙을 학습 environment에도 적용합니다.

  • 각 step 전에 state checkpoint
  • Tool call에 idempotency key
  • Retryable·terminal error 분리
  • 동일 episode 중복 실행 detection
  • Cancel과 timeout의 명시적 terminal status
  • Orchestrator failure와 model failure 분리
model_failure: invalid tool / wrong argument / bad stop
environment_failure: service down / fixture missing
orchestrator_failure: worker crash / duplicate delivery
evaluator_failure: parse bug / reward timeout

이 분류가 없으면 infrastructure 장애를 negative training example로 넣게 됩니다.

14. Curriculum: 짧고 검증 가능한 episode부터

긴 episode를 처음부터 학습하면 성공 신호가 희박하고 오류 공간이 큽니다.

  1. One-step no-call·tool selection
  2. Single tool + final answer
  3. Two-step dependency
  4. Missing slot clarification
  5. Recoverable failure 한 번
  6. Multi-hop retrieval과 evidence sufficiency
  7. 제한된 planning과 branching
  8. 긴 horizon + budget + safety constraint

난이도를 step 수만으로 정의하지 않습니다. Tool branching factor, observation ambiguity, reward delay, state irreversibility를 함께 기록합니다.

15. SWE-Gym이 보여 주는 환경의 중요성

Coding Agent는 repository를 읽고 수정하고 test를 실행하는 긴 episode를 가집니다. SWE-Gym은 software engineering Agent와 verifier 학습을 위한 executable environment 구축을 다룹니다. 이 영역에서 task text만 있고 정확한 repository commit, dependency, test command가 없으면 성공 여부를 재현할 수 없습니다.

RAG Agent도 같습니다.

  • Corpus snapshot과 ACL
  • Parser·chunker·embedding version
  • Search index와 reranker
  • Tool response fixture
  • Gold evidence·required claims

Environment가 dataset의 일부라는 관점이 필요합니다.

16. Episode 평가 설계

Outcome

  • Task success와 부분 완료
  • Required claim coverage와 citation correctness
  • Correct abstention·clarification
  • Human preference와 user correction

Process

  • Invalid action rate
  • Progress per step
  • Recovery success
  • Redundant tool calls와 loop
  • Premature stop
  • Evidence acquisition path

Efficiency

  • Steps, tool calls, model tokens
  • p50·p95 latency
  • External API·GPU cost
  • Parallelizable action을 직렬화한 비율

Safety

  • Unauthorized attempt
  • Prompt injection compliance
  • Secret exposure와 data egress
  • Irreversible side effect
  • Approval bypass

Robustness

  • Tool timeout·empty·malformed response
  • Schema drift
  • Corpus update
  • Long context와 memory truncation
  • 동일 task의 여러 paraphrase

17. RAG Agent의 credit attribution 예시

t0 ask_user(time_range)               +0.2 progress
t1 resolve_alias(ETCH-7)              +0.2 valid
t2 search(query, filter=equipment)    +0.3 evidence recall
t3 search(same query again)           -0.2 redundant cost
t4 answer(with unsupported claim)     -1.0 grounding hard fail
terminal task_success                 0.0

최종 실패를 모든 step에 동일하게 돌리면 t0–t2의 좋은 행동도 억제됩니다. 반대로 step progress만 합치면 unsupported final answer인데도 양의 보상을 받을 수 있습니다. Local credit와 terminal gate를 함께 두는 이유입니다.

18. 최소 구현 순서

  1. Read-only 2–4 step task 100개와 고정 environment snapshot을 만듭니다.
  2. State·observation·action·result·version을 구조화해 저장합니다.
  3. Human 또는 strong policy의 성공 trajectory로 behavior cloning합니다.
  4. Student rollout에서 failure state와 recovery target을 수집합니다.
  5. Outcome, validity, progress, cost, safety reward를 분리합니다.
  6. Replay와 snapshot simulator에서 paired evaluation합니다.
  7. Short horizon에서 long horizon으로 curriculum을 늘립니다.
  8. Simulator on-policy를 적용하고 reward hacking을 audit합니다.
  9. Environment·orchestrator·evaluator failure를 model failure와 분리합니다.
  10. 제한된 read-only canary에서 live drift를 확인합니다.

19. 실전 체크리스트

  • Episode에 model·prompt·tool·corpus·evaluator version이 있다.
  • State, observation, action, result가 typed record로 분리됐다.
  • Sensitive raw trace와 redacted training export를 분리한다.
  • Success demonstration 외에 corrective recovery data가 있다.
  • Offline dataset coverage와 on-policy visited state를 비교한다.
  • Outcome·process·cost·safety reward component를 따로 기록한다.
  • Hard safety failure가 평균 reward로 상쇄되지 않는다.
  • Decision boundary와 subgoal 단위 credit을 추적한다.
  • Replay, snapshot simulator, live canary의 목적이 구분됐다.
  • Idempotency와 durable checkpoint가 있다.
  • Infrastructure failure를 model failure로 학습하지 않는다.
  • Short-to-long horizon curriculum이 있다.
  • Loop, premature stop, redundant action을 측정한다.
  • Confidence interval과 paired evaluation을 사용한다.

스스로 확인하기

Q1. 성공한 Agent 대화만 많이 모으면 충분한가?

아닙니다. Student가 작은 오류 후 방문하는 state와 recovery를 보지 못해 compounding error가 생깁니다.

Q2. 최종 성공 reward를 모든 action에 주면 왜 문제인가?

좋은 행동과 나쁜 행동의 기여를 구분하지 못하고, environment 운에 따른 결과까지 모든 step에 전파합니다.

Q3. Process reward가 촘촘하면 outcome reward를 없애도 되는가?

권장하지 않습니다. Process evaluator의 shortcut을 학습할 수 있으므로 최종 task success와 독립 holdout 상관을 유지해야 합니다.

Q4. Replay environment만 있으면 on-policy 학습이 가능한가?

기록되지 않은 새로운 action의 observation을 제공하지 못합니다. Branching simulator 또는 실제 read-only environment가 필요합니다.

Q5. Side-effect tool에서도 exploration하면 더 빨리 배우지 않는가?

실제 사용자·자원에 피해를 줄 수 있습니다. Simulator·dry-run·synthetic resource에서만 탐색하고 production은 trusted approval gate를 둡니다.

마무리

Agent trajectory learning은 긴 대화 log를 SFT 파일로 바꾸는 작업이 아닙니다. 당시 state와 environment를 재현하고, 관찰이 행동을 어떻게 바꿨으며, 어떤 결정이 결과와 비용·안전에 기여했는지를 학습 가능한 transition으로 만드는 일입니다.

Offline imitation으로 안정적인 출발점을 만들고, student가 실제로 방문하는 실패 state를 on-policy 환경에서 수집하며, local progress와 terminal outcome을 함께 사용해야 합니다. 여기에 snapshot, replay, idempotency가 더해져야 성능 개선과 환경 운을 구분할 수 있습니다.

다음 글에서는 모든 요청을 하나의 모델에 보내지 않고 router와 cascade로 모델·tool·compute를 배분하는 Compound AI System을 설계하고, 품질·비용·지연의 Pareto frontier를 평가합니다.

참고문헌

검증 메모 — 문헌 링크와 서지 정보는 2026년 7월 16일 확인했습니다. 2025년의 마지막 두 자료는 preprint으로 구분했으며, framework의 성능 주장을 일반 법칙으로 사용하지 않고 학습 시스템 설계 관점만 반영했습니다.