Skip to content

[RFC] Replace #2297 with a single-loop complete-turn rollout core - #2312

Closed
jayhenry wants to merge 13 commits into
xs1997zju/agent-rl-stack-20261111/03-fit-cleanupfrom
refactor/async-agent-rl-publication
Closed

jayhenry wants to merge 13 commits into
xs1997zju/agent-rl-stack-20261111/03-fit-cleanupfrom
refactor/async-agent-rl-publication

Conversation

@jayhenry

@jayhenry jayhenry commented Nov 14, 2026 •

Copy link
Copy Markdown
Collaborator

定位

本 PR 是对 #2297(stack 第 4 层)的替代提案,不是新增层,也不改动现有 stack。

  • base 与 [Feature] Retain Agent tasks across complete-request weight updates #2297 相同:xs1997zju/agent-rl-stack-20261111/03-fit-cleanup
  • 已 rebase 到 base 最新 589fd88b(含 sampler resume、proxy retry 等上游修复)
  • 本 PR 相对 base 的 diff:40 files, +3929 / −792
  • 本分支现在直接基于 base 最新提交,不再携带旧 base 的两个重复修复提交。

#2297、#2298、#2299 保持 Draft/Open 不变;是否替换、以及替换后如何并入 stack,由 @xs1997zju 判断。

重构设计思路

目标是把第 4 层的职责收敛成 3 个有真实深度(Depth)的行为类,并让整个 fit 生命周期落在一个 asyncio loop 上。后续评审又补齐了真实取消边界与完整组交付生命周期。

flowchart TD
    A["fit(): 一次 asyncio.run"] --> B["_fit: 异步恢复与首次 I/O"]
    B --> C["初始化: pause → 恢复权重 → publish(0)"]
    C --> D["produce_batch: publish(step) → 完整组 Task 生产 → quiesce(保存点/末步) → seal/drain/pause"]
    D --> E["await_owned_operation(to_thread): 训练/保存/权重同步"]
    E --> D
    D --> F["末步: 不 reopen → close 取消并等待所有组 → 退出"]
    C --> G["RequestPublication"]
    G --> H["RequestGate"]
    H --> I["SessionServer → TraceStore"]
    D --> J["SessionAffinityRouter"]
    D --> K["_PendingTasks: 组 Task 唯一 owner"]
Loading
  1. Fit 生命周期(A3):fit() 只调用一次 asyncio.run(self._fit())。ReplayBuffer、sampler、Agent 客户端与 manager 仍在 __init__ 按原流程构造(只创建同步字段和惰性绑定的 Lock/Event/Semaphore,不启动 task、不发异步 I/O);异步恢复、首次权重 I/O 与初始发布、produce、save、close 在 fit loop 中 await。阻塞训练、DCP/HF 保存、权重/IPC 与资源切换通过 asyncio.to_thread 执行,并统一用 await_owned_operation 等待“真正结束”后再传播取消。

    约束边界:同一 loop 约束的是异步激活与使用,不是所有 Python 对象的构造;因此没有把 builder 搬进 _fit,构造阶段也不做异步 warmup 或 manager.resume。

  2. 请求发布(新增 RequestPublication):独占 freeze → 全部 seal → 全部 drain → 暂停后端 → 训练/保存/同步 → 全部 install → 全部 resume → reopen 全协议。Controller 只保留原 pause_generation / continue_generation(model_step) / assert_request_gates_healthy 入口。

  3. 请求门禁(保留 RequestGate):仅当 backend_ended AND terminal_recorded 才释放 lease;未知结局(断连/取消/未识别错误)保持 active 并毒化后续 drain。LMDeploy 已识别的预生成 context rejection 视为安全失败;SettlementReceipt 只保留 backend_ended/outcome。

  4. Affinity(合并为一个 SessionAffinityRouter):线程、loop、HTTP client、bindings、退休墓碑同一 owner;session 固定到具体 DP entrypoint,失活绑定 503 不改绑,退休 session 410,POST 不重放;probe 使用自有 session,发布后执行。

  5. 跨窗口 Agent 生命周期:_PendingTasks 仍是唯一 live task owner;策略以 retain_live_tasks 选择“跨窗口保留 + claim ready”或原 pause/drain;close 只 cancel 一次并等待原 Runner.finally 清理。

  6. 真实取消边界(F1/F2):新增 await_cancellable_tasks,持有原执行(本地 Task 或 Ray ObjectRef)。取消时本地 task.cancel()、远端 ray.cancel(force=False, recursive=False),等全部终态与 Runner finally 结束后再传播 CancelledError;普通异常同样等齐 sibling 再抛出。router 在远端终态后才释放 worker。

  7. 完整组交付(S2):BaseProduceContext.produce_group 拥有 sample → generate → 校验/入队或丢弃清理 → 统计,返回 bool;claim/pause/quiesce 只读终态,不再二次 put。非共卡用 _produce_pass 确认真实调度轮次退出,删除 _producer_idle/_group_admission/scheduling_paused;共卡用 manager 持有的稳定 ProduceProgress 跨窗口消费增量,并动态推进 consumer_step。Sync 保留原局部 pending/补组循环,仅在 finally 结清剩余组。

  8. Provenance:lease 显式传入 on_response;export_training_trace(expected_request_ids=..., require_routed_experts=...) 集中校验 prompt-only 首节点、完整后缀版本、路径/记录 ID 子集与跨分枝提交、专家齐全;response_model_steps 只表示连续后缀版本。

  9. 共享引用:TokenizedSegment / RolloutState 增加 routed_experts_shared;共享清理只 detach(Ray 引用计数保活),legacy 保留显式 free。

  10. 生成计数:generate_group 记录本窗口 suffix 增长 new_response_tokens;provenance 已版本化全部 token,不能再由版本数组长度推导生成量。

  11. Checkpoint 格式:两种 manager 的 manager_state 写入 group_task_lifecycle_version=1,恢复前先校验;旧格式直接拒绝,不补字段、不转换。

删除/未引入:LoopThread、ColocateKeepaliveManager、AgentTurnPausePolicy、DrainPendingPausePolicy、SessionAffinityService、_producer_idle、_group_admission、scheduling_paused。

行为与配置变化

  • 配置收敛到一处:RolloutConfig.cross_weight_update_rollout = CrossWeightUpdateRolloutConfig(wait/freeze/drain/quiesce_timeout) 与 RolloutConfig.session_affinity;删除 manager 的 turn_keepalive* 与 disagg 的 cross_weight_update_rollout_*;turn 模式下 SessionServer 构造即关闭准入。
  • turn 模式仍然拒绝在线评测(沿用 [Feature] Retain Agent tasks across complete-request weight updates #2297 的策略),构建时一次性校验固定拓扑、provenance、禁用 token partial rollout、恢复需 optimizer states。
  • _xt_request_id / _xt_model_step 不再作为控制通道;客户端传入的这些字段会被剥离,lease 由 SessionServer 显式传递。
  • RolloutController.continue_generation 在 turn 模式下必须携带真实 model_step。
  • AgentInSandboxLoopConfig 新增 require_turn_provenance / retire_route_on_completion。
  • turn 模式 checkpoint 必须包含 replay buffer;完整组 checkpoint 使用新格式标识,旧存档直接报错。

提交与阅读顺序

commit 内容
49aec162 feat(rollout): gate and publish complete-turn rollout versions 门禁、发布、affinity、trace 数据模型与 provenance 导出、共享引用
d08214c4 feat(rl): retain live agents across production windows 策略 retain/quiesce/close、manager admission/idle、生成 token 计数
757016d0 feat(rl): drive the whole fit on one asyncio loop trainer 单 loop 编排、配置统一与校验、trainer 单测更新
42c02bcc refactor(rl): construct loop-owned components in init 构造位置对齐原流程:__init__ 统一构造组件,_fit 只保留异步恢复/首次 I/O/生产/保存/关闭
8ca6381e fix(rl): cancel real Agent execution and wait for all cleanup F1/F2:await_cancellable_tasks、组内 sample 全量清理、Ray ObjectRef 取消与 router 释放
9897fa22 refactor(rl): fix the strategy mode at build time and delegate pause S1/A1:retain_live_tasks 构建期确定、manager 委托 pause_produce
ce5f38dd refactor(rollout): centralize the complete-turn decision and split guards S3/S4:_is_complete_turn、两字段结算收据、长条件分阶段
345953c5 refactor(rl): stop disagg production through status and update_event S2 过渡:删除 _group_admission/scheduling_paused,复用 status/update_event,保留 _producer_idle
0856ef0f feat(rl): deliver complete groups once and settle disagg rounds by Task S2 完整:完整组 Task 一次交付、_produce_pass、共卡稳定账本、Sync 局部收尾、checkpoint 版本 1
b6a398b0 refactor: clarify the colocated progress ledger as next_consumer_step 6.1:ProduceProgress.consumer_step → next_consumer_step;ProduceContext.consumer_step 公开属性保留
3e6dc7d4 refactor: rename turn_resume to cross_weight_update_rollout 6.4:CrossWeightUpdateRolloutConfig → CrossWeightUpdateRolloutConfig,RolloutConfig/manager 成员同名替换;测试文件同步改名
8051f574 refactor: drop rollout quiesce and allow non-exact checkpoint state 6.3:删除 strategy/manager/trainer 的 quiesce 与 quiesce_timeout;turn 模式 pending 存档改为 warning,明确非严格数据恢复契约
091591db refactor: make model_step mandatory and move request barriers into the controller 6.2:continue_generation(model_step) 必填;RequestPublication 并入 controller 的 RolloutRequestState 私有协议

API 简化(2026-11-19 review 6.1–6.4)

  • 6.1:共卡账本字段改为 next_consumer_step,与“取走第 n 步 batch 后应为 n+1”语义一致;context 对 strategy 仍暴露 consumer_step。
  • 6.2:continue_generation 必填真实 rollout model_step,manager 不再区分有无参调用;请求门禁的暂停/发布状态移入 RolloutController,删除独立 RequestPublication 类。
  • 6.3:删除 quiesce:checkpoint/final 不再等待全部 live Agent;仍保留 gate drain 的 LLM 请求安全屏障。turn 模式允许保存带未完成组 Task 的 checkpoint,但明确 live Agent/工具状态不落盘,冷恢复不保证样本序列和统计严格一致。
  • 6.4:配置与同义成员统一为 cross_weight_update_rollout / CrossWeightUpdateRolloutConfig,表达“rollout 跨权重更新继续执行”;request_publication.py 相应改名为 cross_weight_update_rollout.py,控制器屏障测试改名为 test_rollout_request_barrier.py。

端到端实验(简要)

环境:8×GPU 共卡(RLColocateTrainer),3 步,GLOBAL_BATCH_SIZE=8,PROMPT_REPEAT_K=8,开启 cross_weight_update_rollout + session_affinity + require_turn_provenance + retire_route_on_completion,关闭 DCP/HF/eval。代码版本 0856ef0f(rebase 到 589fd88b),运行 20261117_140024。

以下 e2e 在 API 简化前完成;随后 4 个 6.1–6.4 提交为行为等价重构,由单测覆盖,未重跑 e2e。

  • 结果:3/3 step 完成,进程 exit 0;权重分别在 step 1/2 后同步并发布版本 1/2,末步不再 onload。
  • 逐步 rewards/mean:0.2333 / 0.2807 / 0.2075;raw_rewards/mean 0.2179 / 0.2400 / 0.2059;advantages/mean −0.0069 / −0.0030 / +0.0037;invalid_train_groups=0。
  • batch:78 / 75 / 75 样本;response_len mean 14.3k / 14.8k / 10.8k。
  • 窗口耗时:produce 780s / 498s / 1025s;training 183s / 147s / 128s;sync_weight 22.9s / 17.0s;save 15.5s / 9.2s / 8.8s;step 合计 1003s / 674s / 1167s。
  • 门禁与发布故障:Request publication deadline / Backend resume failed / Backend pause failed / Unsettled requests 均为 0。
  • 沙箱 attempt:194 completed / 38 failed(约 16.4%),错误为 agent_chat/entry_exception、rc_missing、rule_grader/judger 等,均由 producer 标记 FAILED 并补采;末步 buffer 余 4 个已完成组(超发余量,未消费)。
  • 与历史 run 对照(同一配置):rebase 前 553dce3e 为 0.4194 / 0.1000 / 0.2000;592cabd0 为 0.3871 / 0.1020 / 0.2679,均处于同一量级。
  • 单测:API 简化后 tests/rl 全量 588 passed / 19 skipped;15 个失败均因本机环境(缺 QWEN3_4B_PATH/QWEN3_5_MOE_PATH、GPU/Ray 启动、缺 pytest-asyncio 插件),其中 4 个在未合入本分支的 base 上同样失败。仓库 pre-commit(ruff/docformatter/codespell/mypy 435 files/pydantic-extra-check)通过。

已知未覆盖:非共卡 RLDisaggregatedTrainer 未跑端到端(启动、pause/quiesce、发布与 close 由单测覆盖);本基线不含 frozen MTP 等 preview 后续能力;本次未产出评估集指标(turn 模式禁用在线评测)。

已知 TODO:超时语义(来自 #2297 review)

本次不改变行为,仅在代码中留下 TODO(timeout-reconciliation):

  • drain_timeout:RequestGate.drain 到期会写入永久 barrier failure 并抛错,即使已准入请求随后结算完成,install/reopen 仍失败并终止训练。后续应保持 gate 关闭、拓扑冻结,在同一 barrier 内继续等待/核对;只有确认未结算请求或后端故障才失败。
  • freeze_timeout:同时约束 health recovery、SessionServer 获取、seal,以及 install→resume→reopen 的共享预算;任一超时都会终止训练。ray.get 超时不会取消远端 RPC,seal/reopen 可能只完成部分入口。后续应区分等待预算耗尽与真实故障,保留 barrier/阶段/未完成 RPC,按入口核对状态后再推进,不能盲目继续或重跑 pause。
  • wait_timeout:只限制已准入请求在 gate 关闭期间的等待,到期只让该 Agent 请求失败,不会终止训练;后续可结合 agent/model 请求预算再校准。

已知 TODO:协议与流式(来自 #2297 review)

  • Anthropic 格式:SessionServer 当前只接受 OpenAI chat completions,Anthropic /v1/messages 被拒绝。已加 TODO(anthropic-format):扩展 gate 准入、请求归一化与 trace 组装以支持 Anthropic 格式。
  • Stream 模式:当前要求非流式 traced generation;已加 TODO(stream-support):支持流式响应,同时在释放 lease 前完成“backend ended + trace committed”的完整轮次结算。

请作者判断

  1. 是否接受用本分支替换 [Feature] Retain Agent tasks across complete-request weight updates #2297 的第 4 层实现?
  2. 若接受,集成方式偏好哪一种:

Admission barriers, one owned version publication path, session affinity and
request-exact traces now live in the rollout control plane:

- RequestGate admits one traced OpenAI generation per session and only
  releases a lease after the backend ended and the trace committed; unknown
  exits poison the barrier instead of allowing a weight update.
- RequestPublication freezes topology, seals/drains every SessionServer,
  pauses backends, installs the next version, then reopens admission. The
  controller only routes its existing pause/continue/health entrypoints.
- SessionAffinityRouter owns its thread, loop and HTTP client; sessions stay
  bound across updates, dead bindings fail closed with 503, and retired
  sessions get 410 without replaying a POST.
- Trace nodes carry their request identity and model step, and shared
  routed-expert references survive trace release through Ray reference
  counting while legacy refs keep the explicit free contract.

SessionServer no longer accepts client-forged _xt_* identity; the lease is
passed explicitly to the trace write path.
The production strategies now own the lifecycle of retained Agent tasks so a
turn can span weight updates:

- AsyncProduceStrategy and DisaggAsyncProduceStrategy keep their existing
  _PendingTasks as the single live-task owner; retain_live_tasks claims done
  groups instead of cancelling them, while legacy mode still drains per
  window.
- _PendingTasks.close cancels each task once, waits for the real Runner
  finally cleanup and reports non-cancellation errors.
- AgentLoopManager.produce_batch accepts quiesce and only opens the quiesce
  wait in turn mode; DisaggAgentLoopManager stops group admission, waits for
  the current producer put to finish, then quiesces and pauses.
- Produced tokens are counted from suffix growth recorded at generation time;
  provenance already versions every response token, so version-array length
  can no longer derive the generation count.

Cancellation still reaches the original Runner.finally and Pool cleanup; the
manager does not reach into another owner's pending set.
The synchronous fit now runs one ``asyncio.run`` for the complete training
lifetime, so Agent tasks and local clients keep the same loop while blocking
training, export and weight work move to threads:

- ReplayBuffer, samplers and Agent managers are built inside ``_fit``; resume,
  produce, save and close are awaited there instead of being wrapped in
  repeated ``asyncio_run`` windows.
- ``await_owned_operation`` is the single cancellation protocol: it waits for
  the owned thread/cleanup to really finish, reports its error, then
  propagates cancellation. It is reused by the ReplayBuffer path.
- Colocate startup publishes the restored version before any group, and the
  final window neither reopens admission nor onloads rollout weights.
- Disaggregated startup stops admission, prepares real weights and KV, then
  publishes version zero through the ordinary continue path; producer
  shutdown waits for its own task and the retained Agent cleanup.
- Turn-resume configuration lives only in ``RolloutConfig.turn_resume``; the
  trainer validates fixed topology, disabled evaluation, provenance and
  partial-rollout constraints once.

The trainer tests now assert the same public batch/save/report behavior
through the async entrypoint, and the debug replay paths wait for their
threaded file I/O.
The single-loop constraint constrains asynchronous activation and use, not
Python object construction. ReplayBuffer, samplers, Agent clients and the
manager are created only from synchronous fields and lazily bound asyncio
primitives, so they return to the original __init__ call sites:

- Both trainers rebuild the base construction order: debug-rollout branch,
  colocate normal path and disaggregated path build the ReplayBuffer and call
  _build_agent_loop_components (including total_epochs derivation) during
  initialization.
- The disaggregated should_continue_fn check moves back next to construction.
- _fit now only performs async manager resume, first weight I/O and initial
  publication, produce, save and close on the fit loop.

Trainer tests drop the fake _cfg/_build_agent_loop_components scaffold that
existed only because construction had been moved into the loop.
close() previously only waited for group-level Tasks: a group gather could
propagate cancellation before slow samples finished their Runner cleanup
(F1), and cancelling a local await on a Ray ObjectRef never stopped the
remote Agent (F2).

- Add await_cancellable_tasks: hold the original executions, send one local
  task.cancel or ray.cancel(..., recursive=False) per pending execution, wait
  for every terminal state, then propagate cancellation. Ordinary errors also
  wait for all siblings before propagating.
- AgentInSandboxLoop.generate_group merges its sample children with this
  helper, so every sample's Runner.finally completes before the group ends.
- BaseProduceContext.generate_group and RouterAgentLoop.generate_group keep
  the original worker ObjectRef and wait for its terminal state; the router
  releases the worker only afterwards.
- Widen await_owned_operation to Awaitable so the helper can protect the
  gathered Future.

Tests cover local cleanup ordering, error-after-siblings, a real CPU Ray
actor cancelled before the awaiting owner returns, router worker release
after remote cleanup, and the sandbox group waiting for every sample. The
blocking-training trainer test now drives the real _train_one_batch with a
thread-blocking train controller instead of an async stand-in.
The manager previously wrote strategy.retain_live_tasks after construction
and then repeated the strategy's retain/legacy branch when pausing. Both
places now use the existing interfaces:

- AsyncProduceStrategyConfig.build and DisaggAsyncProduceStrategyConfig.build
  accept retain_live_tasks; each strategy stores it as internal state. The two
  managers pass turn_resume is not None at build time and no longer mutate the
  strategy afterwards. SyncProduceStrategyConfig accepts the uniform argument
  and keeps its per-window ownership.
- AgentLoopManager.produce_batch always delegates to
  strategy.pause_produce(context): legacy drains its window, turn mode claims
  the groups that completed during gate drain, so live Agent results are not
  skipped. It also always passes model_step to continue_generation; the legacy
  controller accepts and ignores it.
- Disaggregated continue_produce uses the same single call shape.

Add a retain-mode behavior test: build(retain_live_tasks=True) pauses without
draining a live group, and the next quiesce delivers it once.
…ards

Lease settlement repeated the same terminal rules in several places, and a
receipt field was always true.

- SettlementReceipt now carries backend_ended and outcome only. The receipt is
  assigned after the success/failure terminal has been handled, so its
  presence already means "terminal recorded"; RequestGate releases a lease
  when a receipt exists and backend_ended is true. Remove terminal_recorded
  and safe_for_weight_update.
- Add _is_complete_turn and use it both in on_response and in the forwarding
  settlement. The lease branch no longer repeats checks already guaranteed by
  the entry path (non-stream, successful HTTP response, non-error payload);
  the response data guarantee is documented next to the decision.
- Split _is_lmdeploy_context_rejection into structure, protocol fields,
  message and length checks.
- Split install_version/reopen guards by barrier identity, installed version
  and unsettled state; split the cold-resume configuration checks into one
  named resuming fact.
This is the smaller transitional step from the review: keep the producer-idle
confirmation, but remove the duplicated admission flag and strategy pause flag.

- Delete _group_admission. pause_produce sets UPDATE_WEIGHT_AND_ABORT and
  _update_event before waiting for _producer_idle: the status stops the next
  scheduling round, and the event stops the running strategy from scheduling
  more groups. The idle event still confirms that the current produce call,
  including its result puts, has exited.
- produce_loop checks the status directly instead of waiting on an admission
  event; only a normal round that was not paused advances
  producer_future_step.
- Delete DisaggAsyncProduceStrategy.scheduling_paused; ctx.should_abort()
  (the shared update event) is the single pause signal.
- continue_produce, shutdown and resume no longer create or flip admission or
  scheduling flags.

Add a behavior test: pause waits for the in-flight round, no new round starts
while paused, and continue_produce resumes scheduling.
Implement the complete group Task design from
design_2312_disagg_group_task_lifecycle.md. Both layouts now share one group
lifetime; the disaggregated manager waits for an actual scheduling-round Task
instead of idle/admission flags.

- BaseProduceContext.produce_group owns sample -> generate -> validate/put or
  discard/cleanup -> statistics. A cancelled generation releases only the
  undelivered states after F1/F2 cleanup; a started delivery is awaited to
  completion. Strategies spawn this Task before any business await, so
  registration cannot miss a group.
- Both async strategies and SyncProduceStrategy keep complete group Tasks in
  _PendingTasks. Claim/quiesce/pause/close only read terminal states (via
  await_cancellable_tasks); they never put a result a second time. Sync keeps
  its original sampler path and gains the same registry ownership for pause
  and exception close.
- _PendingTasks.cancel_all reuses the strict close protocol; pause_pending_tasks
  takes no put callback for complete groups and keeps the legacy callback for
  any not-yet-migrated strategy.
- DisaggAgentLoopManager records _produce_pass: the actual round Task performs
  target planning, strategy scheduling, produce_time and future_step updates.
  pause_produce waits that Task; close waits it and then closes every
  strategy; resume resets it. Delete _producer_idle; the status/update_event
  pair already stops the next round.
- AgentLoopManager keeps one stable ProduceProgress ledger for its lifetime:
  windows re-target samples and move consumer_step, so a group delivered after
  a window returned contributes its increment exactly once to a later report.
  close now covers legacy too, and cold resume rebuilds the ledger with
  consumer_step = saved step + 1.

Tests cover complete-group delivery once, retain-mode pauses, the transitional
disagg round wait, and the cross-window ledger.
@jayhenry
jayhenry force-pushed the refactor/async-agent-rl-publication branch from 553dce3 to 0856ef0 Compare November 17, 2026 14:52
@jayhenry
jayhenry marked this pull request as ready for review November 17, 2026 17:17
@jayhenry
jayhenry force-pushed the refactor/async-agent-rl-publication branch 2 times, most recently from 2947c83 to ae51674 Compare November 20, 2026 06:19
@jayhenry
jayhenry force-pushed the refactor/async-agent-rl-publication branch from ae51674 to 091591d Compare November 20, 2026 06:26
@jayhenry

Copy link
Copy Markdown
Collaborator Author

Replacement implementation has been moved into #2297: 04-agent-core now points at this branch's commits, and #2298/#2299 are rebased onto the new stack. Closing this duplicate proposal; original #2297 implementation is backed up at backup/agent-rl-stack-04-agent-core-20261120 (6b6439f0).

@jayhenry jayhenry closed this Nov 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant