Repository navigation
【No.15】feat(agentic): weight version tracking and staleness audit for agentic async training - #669
nianliunian wants to merge 62 commits into
Conversation
…d_resp, build_sample
…eight version state tests
…ctory spans test Collapse the manually re-wrapped session_terminal comprehension back to the single line the formatter emits (CI pre-commit pins ruff format), and switch the second span to version=None so the unknown-version path is asserted to round-trip as JSON null through the trajectory stream.
… node The six-stream link test builds a SimpleNamespace lineage node; Task 4's trajectory serialization now reads node.weight_version_spans, so the fake needs the empty default to keep the trajectories stream emittable.
…ight version tracking
Add zh/en guide pages for the weight version staleness audit (metrics, CLI usage, detail-line format, fault tolerance), register them in the VitePress sidebar, cross-link the agentic-rollout audit sections, and record the completion summary for the weight version tracking work.
|
Thanks for contributing to Relax, @nianliunian! 感谢你为 Relax 做出贡献! 📚 Contribution guide / 贡献指南Describe the problem, your changes, and how you validated them. Keep each PR focused and run 请说明问题、改动和验证方式,保持 PR 聚焦,并在提交前运行 🛠️ CI commands / CI 指令
Put one command on the first line of a new PR comment. Rerun/cancel require PR authorship or repository write access. 在新 PR 评论的首行写一条指令。PR 作者或有仓库写权限的贡献者可以重跑、取消 CI。 🔎 Merge requirements / 合入条件GitHub:❌ 存在冲突
|
Nyanpasu 审查看板审查状态: 💬 已完成 · 有补充意见 审查版本: e304d94 目标分支: main 复审完成:F27 的 CP+OPSM 训练异常已修复。保留最终 PG 成员范围、完成边界和快照配额的非阻塞意见,并已发布三项轻量精简/测试说明建议;没有未解决的 P1。代码修复已在原线程确认,账户无权改变这些线程的 GitHub resolved 状态。
审查发现待处理
已解决或已取代改进建议(非阻塞)精简💡 生产代码 · 1 条建议删除仅供一个调用者使用的私有转发层,保留懒导入时机与门控语义。
💡 测试 · 1 条建议替换新增 CP replay 用例对累加器字段的断言,通过实际 bundle 检查所承诺的输出。
拆分💡 1 个拆分方案 建议保留 A→B:A 可独立交付权重版本审计与可信发布序号,B 在 A 的共用最终 PG mask 计算上为重放包增加可单独检查的 payload;CP 新回归加强了共同计算层的边界,但没有消除两个输出的独立价值。 箭头表示前置部分 → 后续部分;目标分支为 flowchart LR
target["目标分支"]
A["PR A"]
target --> A
B["PR B"]
A --> B
如何按依赖提交(stack)PR 作者 nianliunian 为 FIRST_TIME_CONTRIBUTOR,head 在 nianliunian/Relax、base 为 redai-studio/Relax;GitHub collaborator permission 返回 read,未证实上游写权限。 先按表重组混合提交,每部分携带对应测试和文档;逐层验证,并核对顶层最终树与原 PR 一致。独立部分各自向目标分支开普通 PR;只将有依赖的线性链组成 stack,分叉或多前置依赖按图分别安排提交。 Fork 贡献者: 分支保留在 fork,先将底层向上游目标分支提交;上层暂留本地,或在 fork 内以其前置分支为 base 开 draft PR。底层合入后,只将上层独有提交 rebase 到更新后的上游目标分支,再提交下一层;若底层被 squash,注意排除其旧提交。 Fork 内 PR 只用于增量审阅;上游 PR 的 base 不能指向 fork 独有分支。多个累计 PR 同时指向上游目标分支会包含重复差异。GitHub 原生 stack 要求所有分支位于同一仓库。 相关 PR💡 实现与合入建议部分重叠,无整体替代。e304d94 新增消费者/CP 门控,修复了原本在采集前的 CP 拆分触发;train/CLI 输出、PG-only 范围与独有 LoRA/adapter 行为未变,前轮整合建议仍适用。 https://github.com/redai-studio/Relax/pull/549 · https://github.com/redai-studio/Relax/pull/570 · https://github.com/redai-studio/Relax/pull/629 · https://github.com/redai-studio/Relax/pull/670 · 实现取舍: 目标成员的认证/未知分类可借用 #670:对 custom loss/reducer/TIS、CP 和 gated GSPO 等保守留 unknown。它的 effective mask 会并入有系数的 entropy/KL,不能直接替换 #669 的 PG-only 口径。#570 有更广 CP/MTP/loss 路径及作者报告的 GPU 证据;#549/#629 主要计量输入 mask。没有证据证明某个完整 PR 全面胜出。 当前 PR 调整: 保留 final_pg_loss 与 training_input 两块及各自缺失语义,补齐 ICEPOP、未知 reducer/TIS、GSPO 序列依赖的认证边界,复用现有 null 路径;保留 replay 和 train/CLI 两个消费者的独立回归。与 #570 合并时统一单一 engine 标签协议,避免两套 writer 覆盖同一标签。 合入顺序: 均为独立 main 分支,没有功能前置依赖。维护者若选择修正后的 #669 为报告基线,#670 rebase 后删除重复采集/report,保留未吸收的成员分类;反向也可行,#669 保留独有 CLI、managed/adapter 与 ordinal-map 行为。文件冲突和 PR 大小均不决定顺序,不建议自动关闭任一 PR。 依据与验证范围: 本轮 parent 复核相关 PR 的 live head/base/state、本地 merge-base 及更新时间,与前轮 pins 一致;三文件增量未改变 records/report 或标签协议。当前门控见 https://github.com/redai-studio/Relax/blob/e304d94adf758dd4b8f558d683a1dd04f111deb0/relax/backends/megatron/loss.py#L1266-L1287 。已核对四个相关 PR 的 live head/base/state 与本地 merge-base,均与 pins 一致。#670 的未知分类与目标合并见 https://github.com/redai-studio/Relax/blob/4cab9b2cf17d8b604f45f43e918ec58e1a826d85/relax/utils/agentic_obs/weight_loss.py#L13-L79 。#669 的新链路见 https://github.com/redai-studio/Relax/blob/ff1ba01a0c38a0f085b6d582aad95bc8f07025f0/relax/backends/megatron/loss.py#L1332-L1349 。比较未运行测试;其他 PR 的 CPU/GPU 数字是各自正文/讨论报告,范围和提交不同,不能作为本轮独立验证。
Powered by Nyanpasu with gpt-6.1-sol high, please check the suggestions carefully.
|
| continue | ||
| if args.group and trajectory.get("group_id") != args.group: | ||
| continue | ||
| rows.append(_detail_row(trajectory, consumed.get(export_id))) |
There was a problem hiding this comment.
这里遍历全部 trajectory,再用 consumed.get(export_id) 左连接,无法区分“没有 train 记录”和“已消费但版本未知”。Session 在 reward/filter 前就写 trajectory,评估导出也会写入同一流;因此被过滤、仅评估或消费证据缺失的导出都会进入 sample_count、生成跨度和三种缺失率。最小复现中,1 个 train 样本加 1 个未消费的未知版本 trajectory,得到 sample_count=2、缺失率 50%。
请以已记录的 train 输入界定训练统计总体,将没有消费证据的导出单独标为未确认;已存在 train 条目且消费版本为 null 的样本仍应保留为未知。Task 15 要求统计实际进入训练的样本。
There was a problem hiding this comment.
There was a problem hiding this comment.
这版已开始按各 DP rank 的 optimizer 结果筛选样本。还需用完整的更新与分片身份连接结果:merge_train_updates 按 (run_id, train_generation_id, update_id) 分组,但审计只用 update_id 保存并读取状态。我用两条同为 actor:3:2 的记录复现:旧代际提交成功,新代际失败,CLI 把两条样本都列为 optimizer-not-committed。请保留完整键,并只接纳与该 DP rank 成功边界 stage_id 匹配的输入。另一个输出边界是旧数据缺少 stage 流时,文本摘要会标出筛选未应用,--jsonl 却仍给这两条输出 confirmed: true。请让 JSONL 也明确表达 optimizer 结果未知。关联实现 · 记录契约 · 明细输出
There was a problem hiding this comment.
跨代际的三元键已修复,定向用例通过。stage_ids 仍按整个 update 收集,未绑定 DP rank。我给两卡成功更新的 DP1 输入填入 DP0 的 stage ID,实际 CLI 仍输出 confirmed: true, optimizer_status: committed。请按输入自己的 dp_rank 匹配 stage。缺失 stage 流的明细现在能看到 optimizer_status: unknown,但仍输出 confirmed: true,建议将未知的样本单列或用明确的兼容模式标识。 审计关联 · 基线的逐 rank 匹配
There was a problem hiding this comment.
跨 rank 的 stage 借用已被拒绝,旧格式也会逐行标记 optimizer_filter_applied: false。仍有一条可误计:若训练行同时缺少 dp_rank 与 stage_id,查表得到的 None 会与缺失的 stage_id 相等。实跑 CLI 把这样的输入标成 confirmed: true, optimizer_status: committed。请像基线的合并器一样,先要求有效的 stage ID 和对应 rank,再比较。实跑也确认匹配到失败阶段时,JSONL 仍丢掉已知的 failed,统一输出 unknown。审计关联 · 基线归属校验
| export_id = sample.get("sample_export_id") | ||
| if export_id is None: | ||
| continue | ||
| consumed[int(export_id)] = sample.get("consumed_weight_version") |
There was a problem hiding this comment.
这里只保留消费版本,丢掉了 train 样本已有的 loss_mask.ranges,后续 _detail_row 就会按所有生成 span 的完整长度计权。--rollout-sample-filter-path 可设置 remove_sample=True,标准转换会将该样本 mask 清零,但仍保留它参与 GRPO 组处理;训练记录也明确保留这类行。最小复现中,唯一 train 样本 effective_tokens=0、mask 为空,报告仍把其 4 个生成 token 计入滞后,得到 token_weighted_lag_mean=2。
请在 join 时保留训练 mask,将 response 坐标映射到各 lineage span 后,只按实际有效 token 计算 token 加权滞后及 token 缺失率,并单独呈现无有效 token 的样本;补充全零和部分 mask 的回归。Task 15 要求追踪实际参与训练的 token。
There was a problem hiding this comment.
a80efef5 已在 response 坐标内用输入 mask 对 span 求交。部分 mask 的 CPU 用例通过。仍有两处会高估实际训练 token。旧记录缺失 mask 时回退到整段长度。启用 OPSM 或 TIS 时,loss 还可能在输入快照之后屏蔽 token。建议把缺失 mask 的计数标为未知,并明确区分输入 mask 指标与最终训练目标指标。缺失 mask 回退 · 训练 loss
There was a problem hiding this comment.
两条建议都已在 a80efef 之后的提交中落实,逐条核对如下:
① 缺失 mask 标为未知,不回退整段长度 — relax/utils/agentic_obs/version_audit.py:effective_ranges is None(旧 schema 无 loss_mask)时 mask_known=False,所有 token
指标(effective_token_count、known_token_count、unknown_token_count、token_weighted_lag、token_missing_rate)均为 None,不进任何均值分子分母;样本级在汇总 mask_missing_sample_count 单独计数。空 mask 与缺失 mask 区分:空 mask 是“零有效 token”的证据(mask_known=True,计入
zero_effective_sample_count),不是缺失。版本级指标(oldest_lag/newest_lag/generation_span)不依赖 mask,仍然覆盖全部已知 span。回归:tests/cpu/utils/test_version_audit.py::TestSampleStats::test_missing_mask_is_unknown_not_full_length(断言五个 token 指标全 None 且
oldest_lag/generation_span 仍正常),空 mask 区分见同文件 test_zero_mask_is_zero_evidence_not_absence。
② 区分输入 mask 口径与最终训练目标口径 — 汇总 JSON 增加 mask_space: "training_input" 字段,数据中显式声明 token 指标描述的是“采集训练输入时快照的 mask”;启用 OPSM/TIS 后 loss 会在快照之后继续屏蔽 token,该口径在文档(docs/zh/guide/weight-version-audit.md 与英文版「mask
是输入 mask,不等于最终训练目标」要点)中说明:token 类指标可能高估实际训练到的 token 数,版本级指标不受影响。回归:tests/cpu/utils/test_version_audit.py::TestRunSummary::test_summary_names_the_mask_scope。
There was a problem hiding this comment.
已在 d5ba33f 核对你列出的两项改动。缺失 mask 会保留为未知,全零 mask 被识别为零有效 token。汇总也会明确输出 mask_space: "training_input"。这三个定向 CPU 用例均通过,之前要求的两项改动已经落实。
F2 仍标为部分解决,剩下的是 Task 15 中「实际参与训练的 token」这部分。当前实现能准确描述训练输入。若 OPSM 或自定义 TIS 在采集之后屏蔽 token,最终目标统计仍需 loss 侧的证据。文档已明确这个限制。Task 15 · 后续 loss 处理
There was a problem hiding this comment.
5259d01 新增了 replay bundle 的 final_loss_masks。现有 CLI 仍只读取训练输入的 loss_mask.ranges,因此新增 tensor 还没有进入 token 加权滞后和缺失率的统计。
还需区分各个 loss 分量的有效目标。新 mask 乘入 OPSM 后会把被拒绝序列置零,但 entropy、KL 等分量仍可使用原 reducer。定向 CPU 实验中,OPSM 使 pg_loss=0、记录的 mask 为 [0,0],开启 entropy 后总 loss 为 -0.5,两个 token 的梯度均为 1。实验执行了实际 policy loss 和采集,只替换前向及昂贵的通信边界。建议将可证明的最终目标信息接到消费记录和审计 reader,并让不支持的 loss/reducer 组合保留未知;文档需说明 tensor 所代表的目标范围。新增 mask · 后续目标分量
There was a problem hiding this comment.
ff1ba01 已将 loss 侧 mask 接到 train 流和 CLI 的 final_*,并单列 final_pg_loss 范围;此前“replay 字段尚未被 CLI 消费”的差异已消除。缺失与全零证据继续正确区分。
本项仍有 PG 范围内的缺口:ICEPOP 会把越界 token 的 PG 权重置零,却返回原 mask。新 hook 因此仍把这些 token 写成“确认训练过”。此外,GSPO 的序列比率在后续 TIS 门控之前由原 mask 求出,被后续 mask 排除的 log-prob 仍可能影响保留项的梯度;任意自定义 reducer 也没有成员保持契约。新采集入口目前只排除了 score-centering 与 dummy。
请仅对已证明的组合写出最终证据;其余沿用 final_loss_mask: null。这属于最终 PG 指标的适用范围问题,无需改变既有训练目标。已运行的 CLI 定向用例只验证字段传递,不能证明上述成员语义。
| if updater is not None: | ||
| return str(updater.weight_version) | ||
| if engine_client is not None: | ||
| version = getattr(engine_client.backend, "weight_version", None) |
There was a problem hiding this comment.
DCS 的 weight_version 是同步尝试计数:DeviceDirectBackend.update_weights_for_rollout() 在判断 actor_fwd_only 前就递增它。普通 Fully Async 模式下,rollout 握手短暂超时而 actor_fwd 健康时,train_async 仍会执行一次仅 actor_fwd 的同步,并继续后续训练。若上次 rollout 发布为 7,此时计数变成 8、rollout 仍使用 7,新的消费戳就会让审计报告年龄 1,虽然没有新 rollout 版本发布;后续成功发布变成 9,也会把一个实际发布差算成两个。
已通过真实 checkpoint client/backend 的有界 CPU 复现确认 7→8 且 rollout recipients 为空;传输与 collectives 被隔离,未做 GPU 验证。请将传输计数与成功发布序号分开,并在生成标签与消费戳两端统一映射。Task 15 要求按同一策略的已发布版本序号计算年龄。
There was a problem hiding this comment.
a80efef5 已修复原来的仅同步 actor_fwd 的场景,定向 CPU 回归通过。LoRA adapter 模式仍会错算。底座首次同步后不再推送,后续 adapter 更新的请求没有版本字段,delta-skip 时甚至不发请求,但 DCS 仍为这两种调用递增 weight_version。这样训练戳会变,生成端可能继续报告首次底座的标签。请按实际确认发布的策略版本打戳,或将该模式的年龄报告为未知。版本递增 · adapter 推送
There was a problem hiding this comment.
已核对 b77ad252。受管 LoRA 的消费端现在从已确认的发布器取值,capacity_skipped 当下会保留原标签。这修复了生成端与消费端读取不同计数器的问题。仍有一步需要处理:发布器用同步尝试号分配 version_id。成功发布 0、容量跳过 1、再成功发布 2 时,离线审计用 2 - 0 得到 2,实际只新增一次成功发布。定向 CPU 容量用例在此提交复现了这组发布 ID。请保留原 ID 供关联,并按同一策略的连续成功发布序号计算年龄。缺少映射时可将该年龄标为未知。传统 adapter 的标签问题也仍适用。发布器 · 容量回归 · 审计计算
There was a problem hiding this comment.
There was a problem hiding this comment.
已核对 e60a84f 的传统 DCS adapter-only 路径。真实 adapter 加载回执之后、恢复生成之前,现在会调用 /update_weight_version;delta-skip 会提前返回。两条定向 CPU 用例均通过,SGLang v0.5.21 源码的请求字段与该调用一致。真实 SGLang/NCCL 同步尚未运行。
这个修改覆盖传统 DCS adapter 标签滞后。此前 managed LoRA 的空映射回退仍适用,映射读取器本轮未变。标签调用 · 固定版本接口
| token_start=resp_train_token_count + span.token_start, | ||
| token_end=resp_train_token_count + span.token_end, |
There was a problem hiding this comment.
resp_train_token_count 跳过了中间 obs,但 Sample.response_length、loss_mask、rollout_log_probs 和 custom_advantage 的 continuation 坐标包含这些 token。现有两轮 fixture 经真实 build_sample 得到 response=abtoolcd、mask=[1,1,0,0,0,0,1,1],版本 3 的 span 却是 [2,4),指向工具文本 to;实际生成的 cd 在 [6,8)。这使新 Sample 字段无法与 response 或训练 mask 对齐;node 内的 trajectory span 不受影响。
这里已有 response_start,可以直接用它平移节点内区间:
| token_start=resp_train_token_count + span.token_start, | |
| token_end=resp_train_token_count + span.token_end, | |
| token_start=response_start + span.token_start, | |
| token_end=response_start + span.token_end, |
同时移除不再需要的计数器,并将现有 test_build_sample_flattens_spans_to_response_coordinates 改为检查 span 指向实际生成内容;目前该测试期望 [2,4),固定了错误偏移。
… kwarg ## 🐛 Bug Fix ### Fix 6 offline SFT CPU test failures from PR 669 CI - Update train.assert_called_once_with in test_mtp_only_training and test_resident_sft_param_sync to expect the new consumed_weight_version=None kwarg that actor.py now passes to train() - Bind _consumed_weight_version on the resident SFT AST fixture actor via the same _functions AST-extraction pattern used for the other helpers, so the megatron-free test path can execute train_actor up to the train call ## 🎨 Style ### docformatter and mdformat reflow - Reflow docstrings in version_audit.py and two weight version test files to wrap-79 per the repo docformatter hook ## ✅ Tests - Resident SFT file: 47 passed, 1 skipped (local, no megatron) - Weight version suites: 34 passed, 1 skipped; observability suites 201 passed - ruff check/format and docformatter checks green on all touched files
|
/rerun |
|
Head:
|
| @pytest.mark.parametrize( | ||
| ("content", "reason"), | ||
| [ | ||
| pytest.param(None, "file missing", id="missing_file"), | ||
| pytest.param("{bad", "corrupt JSON", id="corrupt_json"), | ||
| pytest.param("[1, 2]", "not a dict", id="not_a_dict"), | ||
| ], | ||
| ) | ||
| def test_unreadable_mapping_in_required_mode_reports_unknown_ages(self, tmp_path, content, reason): | ||
| # A user who passes --lora-artifact-dir says the run is managed LoRA, | ||
| # whose ids carry capacity-skip holes. When the mapping cannot be read | ||
| # ({reason}) the ages must be unknown, not differenced raw ids. |
There was a problem hiding this comment.
非阻塞精简建议。reason 仅出现在注释中,三个参数 ID 已标识失败分支。下面的 warning 用例也只读取 logger handler 中收集的记录,可去掉未读取的 capsys。这些改动保留现有输入、断言和诊断覆盖。
| @pytest.mark.parametrize( | |
| ("content", "reason"), | |
| [ | |
| pytest.param(None, "file missing", id="missing_file"), | |
| pytest.param("{bad", "corrupt JSON", id="corrupt_json"), | |
| pytest.param("[1, 2]", "not a dict", id="not_a_dict"), | |
| ], | |
| ) | |
| def test_unreadable_mapping_in_required_mode_reports_unknown_ages(self, tmp_path, content, reason): | |
| # A user who passes --lora-artifact-dir says the run is managed LoRA, | |
| # whose ids carry capacity-skip holes. When the mapping cannot be read | |
| # ({reason}) the ages must be unknown, not differenced raw ids. | |
| @pytest.mark.parametrize( | |
| "content", | |
| [ | |
| pytest.param(None, id="missing_file"), | |
| pytest.param("{bad", id="corrupt_json"), | |
| pytest.param("[1, 2]", id="not_a_dict"), | |
| ], | |
| ) | |
| def test_unreadable_mapping_in_required_mode_reports_unknown_ages(self, tmp_path, content): | |
| # Managed LoRA ids carry capacity-skip holes. If the mapping cannot | |
| # be read, report unknown ages. |
The LoRA adapter payload carries no version field, so after the first base sync the rollout engines keep labeling generation with that first ordinal while DeviceDirectBackend.weight_version advances on every publish — every consumption age in the staleness audit would read the publish count since the base sync too high, growing linearly with training. After the engines confirm an adapter load, rank 0 now stamps the published ordinal on all engines via the existing /update_weight_version endpoint (the same convention colocate routed-experts and fsdp_turbo already use) inside the pause window, the broadcast lock, and the try block, so a failure keeps the adapter push's fail-every-rank-while- paused contract. Delta-skipped pushes return before this point and stamp nothing.
| backend.lock.release.remote.return_value = True | ||
| # The fixture's ray.get returns None, which the lock-acquire spin loop reads | ||
| # as "not acquired"; pass values through so the acquired lock exits the loop. | ||
| monkeypatch.setattr(device_direct.ray, "get", lambda refs: refs) |
…tate The eager-session test harness builds AgenticSessionShard via object.__new__, so __init__ never runs and fields the fixture forgets to assign stay absent. _lora_runtime was one of them: _completion_weight_version read it with a bare attribute access, the AttributeError killed the finalize task inside finish_before_cancellation, and the session never reached a terminal state (surfacing as a timeout in test_leased_member_generates_before_siblings_first_request[train]). Fix it on both ends: the harness now assigns shard._lora_runtime = None alongside the other explicit field inits, and _completion_weight_version reads the runtime with getattr(self, "_lora_runtime", None) so a half-constructed shard cannot crash finalization — matching the defensive reads already used elsewhere on this class.
The completion boundary fed only managed LoRA Sessions: without a LoRA runtime, _completion_weight_version returned None unconditionally, so colocate/hybrid and traditional-DCS runs reported every post_generation_lag as unknown even though they carry segment and consumption versions. With observability on and no managed runtime, the finalize path now asks SGLangBackendAdapter for the engine-side default version: get_default_weight_version discovers workers through the router and GETs /get_weight_version on exactly one of them. It is a bypass observation, not a consistency read — no fan-out, single attempt, bounded by the existing _COMPLETION_VERSION_TIMEOUT_S, and any failure or timeout degrades to unknown with a warning instead of delaying or failing the export. The observability-off short circuit stays first, so a recorder-disabled shard still issues no query at all. The snapshot is only as good as the engine label: colocate/hybrid stamp the updater's version on every publish, while the traditional DCS adapter mode stamps the published ordinal only after each adapter publish — runs predating that stamping keep the label at the first base sync, and their completion snapshot inherits the staleness. The audit guide's post_generation_lag rows (zh/en) now state the per-mode completion sources and that scope.
VersionOrdinals.load returned cls(mapping) after filtering, so a mapping
file that parsed but yielded no usable entries — {} or a dict whose every
value is non-int — fell through to the raw-id mode of ordinal(): the
run was managed LoRA (the artifact dir was given), yet the audit
differenced the gapped attempt-counter ids as if every attempt had
published, reporting a newest_segment_lag of 4 for a source version 3
consumed at 7 instead of an unknown age.
Passing --lora-artifact-dir now decides the mode, not the mapping
content: no dir stays the traditional raw-id mode, a dir whose mapping
yields at least one usable entry stays the mapped mode, and a dir whose
mapping is missing, empty, corrupt, or unreadable makes every ordinal
unknown. The CLI warning wording and both language guides now cover the
empty case alongside missing/unreadable.
A train record missing both dp_rank and stage_id slipped through the per-rank boundary check: the lookup's None for the absent rank compared equal to the record's missing stage_id, and the CLI confirmed the sample with the update's committed verdict. Require a present stage_id before the comparison, as merge_train_updates requires a valid stage to pair an input with an attempt; such records now read unknown and land in optimizer-not-committed. The --jsonl branch also stamped every unconfirmed row with optimizer_status: unknown, discarding a failed verdict the join had actually reached. Record the verdict for both populations and print it per row, so a known failed stays distinguishable from an unjudged attempt; docs updated in both languages.
The CPU CI failed both parametrized variants of test_train_async_metrics_include_the_component_owned_tail with a TypeError: the real train() now receives consumed_weight_version=, but the clock-advancing side-effect lambda was positional-only. The mock only measures time, so it swallows all kwargs.
The publish test replaced ray.get with an identity function, so the assertions only saw the order requests were fired in: deleting the load-receipt wait (ray.get(futures)) or issuing /update_weight_version without awaiting its confirmation produced the same passing result, and the test called _push_lora_adapter_distributed directly, bypassing the pause/push/error-share/resume orchestration entirely. Enter through update_weights_for_rollout() now. The receipts are objects ray.get must unwrap for the lock spin loop, and the test interleaves every request with every receipt wait in one timeline, so the stamp is pinned between the engines' load confirmation and the resume, inside the lock. A second case fails the stamp receipt and asserts the fail-every- rank-while-paused contract: the push error surfaces as the shared RuntimeError, the lock is still released through the finally block, /continue_generation is never sent, adapter_loaded stays unset on the first sync, and no adapter snapshot is recorded.
The ordinary-path completion stamp was read from a finalize-time engine probe: the probe runs through router worker discovery, so a publication landing while discovery was in flight (i.e. after the Session had already finished generating) was reported as the completion boundary. With termination at v4, a v5 publish during the probe, and consumption at v5, the audit reported post_generation_lag 0 where the true wait was 1 — the post-termination release had folded itself into the boundary. The boundary now comes from the Session's own generation records: _apply_generate_result keeps the confirmed release of the latest backend attempt that reported one (None when the engine never did). That value is taken at the boundary itself and shares its source with the span labels, so it is comparable with the publication records the audit diffs against, and a later probe can no longer masquerade as the boundary. The late reads stay, but demoted to a separate observation: the managed runtime status and the one-worker engine probe now populate a distinct engine_default_weight_version trace event, and the audit reports current - engine_default as its own engine_default_lag column — an approximation that also swallows post-termination releases — while post_generation_lag is null rather than rescued by it when the Session never observed a release. The observability-off short circuit still precedes every query.
| stats["newest_lag"] = None | ||
| stats["newest_segment_lag"] = None | ||
| stats["post_generation_lag"] = None | ||
| stats["engine_default_lag"] = None |
There was a problem hiding this comment.
当所有片段都缺少版本标签时,代码在这里把独立的探针结果也清空了。用实际采集与审计函数复现:一个无标签片段、成功探测到引擎版本 4、训练消费版本 5,得到 engine_default_lag=null,但这两份观测已足够算出 1。现有近似指标用例传入了一个已知版本片段,因此没有覆盖该分支。
请在片段判断之外,按消费版本和探测版本各自的 ordinal 计算这一列。用例可传入 version=None,并同时断言最新片段年龄及精确等待均为 null,引擎默认滞后为 1。
| resumed, and the next sync re-pushes the adapter (``adapter_loaded`` stays | ||
| unset on the first sync). ``weight_version`` stays at the failed call's | ||
| ordinal: the counter advances per call (the attempt did happen), and the | ||
| retry that eventually succeeds publishes from that same ordinal. |
There was a problem hiding this comment.
这个用例从版本 3 开始,只调用一次同步。它能抓到打标回执失败后未释放锁或错误恢复生成。后面的私有字段断言无法验证「重试会用同一序号重新发布」:夹具把 should_skip 固定为假,而且同一后端若再次执行一次实际推送,会在打标前把本地序号从 4 增至 5。正常失败路径会抛错并保持暂停。计数与失败分支 · 发布前递增
建议保留回执、解锁和暂停断言,把说明收窄到本次失败。若需要保证同一后端重试,请让用例使用真实的跳过判定,再执行一次同步并断言引擎收到的 adapter 和版本标签。
| resumed, and the next sync re-pushes the adapter (``adapter_loaded`` stays | |
| unset on the first sync). ``weight_version`` stays at the failed call's | |
| ordinal: the counter advances per call (the attempt did happen), and the | |
| retry that eventually succeeds publishes from that same ordinal. | |
| resumed. This test covers the failed receipt and lock release. |
CI prek flagged the three weight-version test files: docformatter wraps summary lines at 72 chars, and the newly added docstrings exceeded it. Formatting only — no token or assertion changes.
The receipt-failure case claimed the retry that eventually succeeds publishes from the same ordinal, but the test only drives one sync and the fixture pins should_skip to never-skip. A real retry would bump weight_version again before stamping (the counter advances per non actor_fwd call), so the promised ordinal reuse contradicts production behavior. Narrow the docstring to what the case actually checks: the receipt failure, the lock release, the kept pause, and the one-step counter advance for the failed attempt.
The engine default lag is decided by the consumption stamp and the finalize-time probe alone, so it must stay computable when a sample's spans carry no known version. The column was previously nested inside the known-spans branch, which nulled it even though both observations were present. Move the computation out of the span-labeled branch.
The round-3 stamp (the Session's own last attempt meta_info) missed publications that land after the last attempt but before completion, e.g. a release published while the final tool call is still returning. The exact wait needs the confirmed publication ordinal in force at the completion event; output null when it cannot be obtained. On the managed LoRA path, read default_version from the LoRA version runtime status at the very start of finalize, next to the existing read point of _completion_weight_version: the publication ledger is the only source in the same version-id space as the span labels, and it advances only on confirmed commits. Timeout, exception, a status without a default, or observability off leave the stamp unknown — never falling back to the last attempt or the engine probe. Ordinary paths (colocate/hybrid/traditional DCS) expose no ledger at that event, so the completion stamp is always null there and the existing worker probe feeds only the separate engine_default observation. The managed path writes no second observation for the same read. Remove _SessionRecord.last_seen_weight_version and its recording block entirely: both prior sources were rejected, and the field existed only to be misused as the boundary. Wire the reviewer's v3 -> v4 -> v5 scenario from capture to stats: a test drives one attempt at v3, a ledger reporting v4 at finalize, and consumption at v5, asserting newest_segment_lag 2 and post_generation_lag 1 through compute_sample_stats.
| assert stats["post_generation_lag"] == 1 # 5 - 4: the true wait | ||
|
|
||
|
|
||
| async def test_completion_stamp_includes_a_release_published_during_the_tool_return(tmp_path): |
There was a problem hiding this comment.
这里与上一个用例的输入相同:生成片段为 v3,状态 RPC 立即返回 v4,两处都断言完成戳为 v4。保留上一个用例即可覆盖此断言,并继续验证探针为空、片段年龄为 2、等待为 1。可以删除本用例,或将它改为用事件控制状态 RPC 与发布的先后顺序,覆盖 F6 尚未验证的交错。
|
|
||
|
|
||
| async def test_completion_stamp_reads_the_release_ledger_at_the_event(tmp_path): | ||
| """The reviewer's v3 -> v4 -> v5 scenario, Session layer to stats layer. |
There was a problem hiding this comment.
The reviewer's 指向本轮审查记录。测试长期需要保留的契约是“工具返回期间发布的版本计入完成戳”,下文已用 v3、v4、v5 说明该行为。
| """The reviewer's v3 -> v4 -> v5 scenario, Session layer to stats layer. | |
| """Use the release published during the final tool call for the completion stamp. |
The round-4 stamp read the publication ledger's default_version through the runtime status RPC. That read is asynchronous: finalize submits the RPC, but the actor executes status() only later, so a commit landing between the submit and the actor-side read leaked into the completion stamp even though it postdates the completion event (the reviewer's v4-at-entry / v5-inside-the-window scenario: consumption at v5 would report a wait of 0 while a release actually crossed the boundary). Sample the boundary on one sortable edge instead: the ledger now records the wall clock of each commit (LoRAVersionManager.default_ committed_at, advanced only by commit), and status(as_of) reports the pair (default_version, default_committed_at) plus the verdict default_in_force_as_of — true only when the latest commit predates the caller's instant. _finalize_terminal_session passes its existing finalize_arrive_at (sampled locally before any await) as that instant, and _completion_weight_version accepts the stamp only when the verdict is true. A release landing inside the read window leaves the stamp None — the reviewer's second option: leave the unconfirmable exact wait empty rather than approximate it. Cross-process clock skew can only flip a verdict toward None, never let a newer commit pass as the boundary, so skew degrades in the safe direction. Ordinary callers of status() are unchanged: without as_of the reply keeps the same keys and the current default, and the two new fields are additive. The observability-off short circuit, the 2s bound on the read, and the never-fallback rule (no attempt echo, no engine probe, no unjudged default) all stay as they were. Merge the two Session-layer tests that shared the same inputs (the round-4 review flagged the duplicate) into the boundary-judgement pair: the tool-return release test now asserts the as_of call and the in-window race end to end through compute_sample_stats, with the stamp-unknown case asserting post_generation_lag None. Manager and runtime layer tests cover the committed-at stamp and the verdict. Reword the one docstring that referenced the review record.
| # RPC; the v5 commit (committed_at 11.5) lands in that window — after | ||
| # finalize entry (11.0), before the read. | ||
| submitted.set() | ||
| await asyncio.sleep(0) |
There was a problem hiding this comment.
这里的事件只表示测试替身已进入,sleep(0) 之后直接返回预写的 default_in_force_as_of=False。去掉事件和让出执行时间,断言仍会通过。若代码提前返回而未调用替身,后面的 submitted.wait() 还会一直等待。
如果只验证 Session 收到拒绝回执后把等待留空,直接使用该回执并断言 as_of 即可。如果要验证发布与读取的先后,用事件门控真实的本地 status(),在放行前调用实际的账本 commit,并给等待设置超时。
There was a problem hiding this comment.
There was a problem hiding this comment.
已核实 ff1ba01:状态读取协程先设置 entered 并等待 gate,测试带超时确认进入等待后才提交 v5、放开读取;读的是实际 runtime/manager 账本。定向用例 test_completion_stamp_carries_a_commit_that_races_the_marker 在 CPU 通过,本项测试交错意见已解决。此验证不包括真实 Ray actor mailbox。
The round-5 stamp judged the ledger's default against the finalize-entry wall clock. Both instants come from different processes with no trusted skew bound, so neither direction of the comparison is provable: with the runtime clock lagging, a commit that really postdates finalize entry carries an earlier timestamp and passes as the completion boundary, and the wait underreports (the reviewer's controlled-clock reproduction). The previous claim that skew only degrades the verdict to unknown was wrong and is retracted. The boundary now lives on the runtime itself: the finalize marker is one status RPC, and the reply is the ledger snapshot taken where that marker lands — the same single event loop the commits run on, so the stamp and every publication are totally ordered with no cross-process clock comparison. The edge sits at most one RPC transit after the Session's completion event; a release committing inside that transit is folded into the stamp, and the guide documents this bounded approximation explicitly. Failed, timed-out, or empty reads still leave the wait unknown. The wall-clock judgment and its committed-at bookkeeping are removed: nothing else consumed them, and keeping a comparison that no direction of can be proven would only invite reuse. The regression for the racing commit now drives the real runtime status over a real ledger with an event gate instead of a canned reply, so a stamp taken from anywhere other than the ledger read cannot pass.
…mation The round-6 stamp is sampled where the status RPC lands on the ledger, so every release committing between the Session's completion event and that read folds into the stamp — not just one. The reviewer's controlled run (v4 at finalize entry, v5 and v6 both committing before the read is served, consumption at v6) reads a wait of 0 where the finalize-entry boundary counts 2, so the earlier 'at most one release' phrasing in the guides, the Session docstring, and the audit docstring overstated the guarantee the code provides. The approximation is now stated without a per-release cap in both languages, and the exact wait is called out as still requiring evidence orderable against the completion event itself. The stamp-failure lifecycle test also drops its remaining re-push hint: the comment beside the adapter_loaded assertion still promised the next sync re-pushes the adapter, which that test never exercises.
| # Gate the actor-side read until the racing commit has landed, the | ||
| # same interleaving the reviewer produced with controlled clocks: | ||
| # finalize enters with the ledger at v4, v5 commits, then the read. |
There was a problem hiding this comment.
这里引用了早先的审查实验。长期需要保留的是读取门保证 v5 提交先于状态读取。
| # Gate the actor-side read until the racing commit has landed, the | |
| # same interleaving the reviewer produced with controlled clocks: | |
| # finalize enters with the ledger at v4, v5 commits, then the read. | |
| # Read the ledger only after the racing publication commits. |
There was a problem hiding this comment.
已核实 ff1ba01 删除对审查实验的引用,注释现直接说明 v5 提交先于状态读取的约束。本项已解决。
policy_loss_function now exports final_loss_masks — the input mask multiplied by every loss-side mask applied after the training-input snapshot (OPSM's whole-sequence zeroing, a rejection-sampling tis_func) — as an optional step-level payload for offline audits of the tokens the loss actually trained on. Absent when no downstream zeroing applies.
The replay bundle already carried final_loss_masks, but nothing read it: the staleness audit still token-weighted against the training-input mask, so OPSM or a rejection-sampling tis_func zeroing tokens downstream of that snapshot left the token-weighted lag and missing rate over-counting what the loss actually trained on. policy_loss_function now hands its final mask to the consumption record: record_final_loss_masks pairs positionally with the input snapshot of the same micro-batch and writes it as the per-sample final_loss_mask. Paths where that mask is not provable record nothing instead of guessing — score-centering excludes rows through its logit context rather than the mask, dummy micro-batches hold no input snapshot to pair with, and context parallelism zig-zags the response so a rank's shard cannot be reordered into response coordinates. The audit reads final_loss_mask into its own final_* block: the same token-weighted arithmetic restricted to the tokens the pg-loss term actually kept, reported alongside — never instead of — the input-mask block, scope-named final_pg_loss because entropy, KL and the OPD losses keep the input-mask reducer. Samples without that evidence are counted in final_mask_missing_sample_count and stay unknown rather than falling back to the input mask; an all-zero final mask stays zero evidence, not absence. The race test gates on an entered event so the interleaving proves the v5 commit lands after the status RPC started waiting, and its comment states the read-gate ordering directly. Guides name the final scope in both languages and show the missing-evidence summary fields.
| opsm_slices = opsm_mask.split(response_lengths, dim=0) | ||
| final_loss_masks = [mask * slice for mask, slice in zip(final_loss_masks, opsm_slices, strict=True)] |
There was a problem hiding this comment.
OPSM 的 mask 与本 rank 的 advantage、log-prob 对齐,CP>1 时长度小于完整 response_lengths。新增拆分使用全长,正常 OPSM+CP 训练因此在 loss 内直接抛错。该计算发生在 capture hook 的启用判断之前,关闭 replay 也会触发。
CP=2、一个 response 为 4 token、当前 rank 持有 2 token 的 CPU 复现走实际 loss:基线完成 backward,新版报 split_sizes=[4] 与本地长度 2 不符。只替换前向和通信边界,未执行真实 GPU CP。
请在正确的 token 坐标下生成审计 mask,并让不支持的采集范围保留未知。审计计算需受采集开关约束,同时保留 CP=2 且关闭 capture 的 loss/backward 回归。
There was a problem hiding this comment.
已核实 e304d94 修复本项:mask 构造现在受消费者和本 micro-batch 的有效 CP degree 门控,CP>1 时不再按完整 response 长度拆本地 OPSM mask,普通 PG 计算保持原样。
用同一 CPU 最小复现对照:ff1ba01 仍报 split_sizes=[4] 与本地长度 2 不符;新版完成 loss/backward,loss 为 -2.21034188885、两个梯度均为 -1.10517094442,与审计前相同。另定向运行 test_cp2_with_capture_writes_no_final_loss_mask_payload 通过,启用 replay 时不输出无法证明的最终 mask。
本项训练异常已解决。验证隔离了模型评分及 CP 通信,没有运行真实 GPU/CP;F2 的最终成员范围与 F28 的快照预算是另外两项,仍保持原状态。
| state = _CURRENT.get() | ||
| if state is None or not final_loss_masks or state.final_mask_ok is False: | ||
| return |
There was a problem hiding this comment.
四个张量更新尚未写完时,_begin_update 会令后续更新的 reserved=False;既有 _capture 因此只保留身份,不复制张量。新 hook 不检查这项准入,仍执行 torch.cat 和 CPU/pinned copy,将张量保留在 final_snapshots。随后 _submit_update 把整个 state 放到 metadata worker,却只按 group IDs 计费。这些最终快照没有对应输入,无法用于报告,却占用了本应受配额约束的内存。
即使输入已获准,新张量字节也未进入 state.size_bytes,更新与 worker 的字节上限同样漏算。请只为已接纳的输入快照采集最终 mask,并将新增保留张量计入现有预算;拒收时保留 metadata-only/最终证据未知的行为。此判断来自准入与队列调用链,未进行内存压力或 OOM 实测。
The final-objective mask derivation split the OPSM mask by the full response lengths, but under context parallelism that mask is CP-local — aligned with this rank's advantages and per-token pg-loss, exactly what the pg_loss product needs — so an OPSM+CP step crashed inside the loss (split_sizes=[4] against a local length of 2) even with every capture switch off, because the derivation ran unconditionally ahead of the hooks. The derivation is now gated on having a consumer — an active replay-capture step or an active agentic-obs update — and on the mask being provable in response coordinates. A zig-zag CP shard holds only this rank's half of each response and cannot be reordered back, so CP > 1 derives nothing: no replay payload, no record call, and the train record keeps those tokens unknown instead of a scrambled mask. Dynamic CP that shrinks a micro-batch back to CP=1 keeps full-response coordinates and derives as usual. The record hook now keys off the derivation itself rather than repeating its provability conditions, and a CP=2 regression covers the reviewer's crash shape with capture off, with an observation active, and with capture on (payload omitted, the rest of the stage intact).
| loss_module.mpu, "get_dynamic_data_context_parallel_groups", lambda group_size: None, raising=False | ||
| ) | ||
| monkeypatch.setattr(loss_module.mpu, "get_context_parallel_world_size", lambda: 2, raising=False) | ||
| monkeypatch.setattr(loss_module, "all_gather_with_cp", lambda tensor, *args, **kwargs: full_old) |
There was a problem hiding this comment.
这个替身对旧、新 log-prob 的 gather 都返回 full_old,所以实际 compute_opsm_mask 得到 seq_kl=0、全一 mask,与上方“整段被 OPSM 拒绝”的说明不同。首个用例的零梯度来自局部比率 exp(-3) 和负 advantage 触发的 PPO clipping;从该输入可推导,即使删去 OPSM 乘法,这个零梯度断言仍会通过。这里没有运行 mutation。
这些用例仍能保护 F27 的长度异常。若保留 OPSM 拒绝和梯度保持的验证主张,请区分两次 gather 的结果,并选取仍在 PPO clip 区间内、但高于 opsm_delta 的 KL;或者将说明与断言收窄到实际保护的“不抛异常/不写最终 mask”。调整现有 fixture 即可,无需再新增一组测试。
| ) | ||
|
|
||
|
|
||
| def _final_mask_observation_active() -> bool: |
There was a problem hiding this comment.
该私有函数只做一次局部导入,再原样返回零参数查询;没有缓存、装饰器或作为值的引用。唯一调用者可以直接完成这项操作,删除这层转发。为保持当前短路行为,只在 replay 未激活时导入和查询:
capture_active = capture_hooks.capture.current_step() is not None
if not capture_active:
from relax.utils.agentic_obs.train_hooks import final_mask_observation_active
capture_active = final_mask_observation_active()随后用 capture_active 进入其余 gate,即可保留同样的导入时机、结果和异常传播。
| assert step is not None | ||
| assert "final_loss_masks" not in step.tensors | ||
| # The rest of the loss.policy stage is captured normally. | ||
| assert step.loss_masks_tensor is not None | ||
| assert "pg_loss" in step.expected[StageId.LOSS_POLICY.value] |
There was a problem hiding this comment.
本用例承诺 bundle 不含无法证明的最终 mask,但这里只检查 CaptureRecord 的累加字段。把最终 mask 改存专用字段、到 writer 才生成同样的 payload,会保持用户看到的 bundle 不变,却使这些内部字段断言失效;writer 漏写其它已有字段也无法在此处被发现。
用例已执行 end_step() / disable(),可改用 BundleReader(tmp_path / "b-cp2").load() 检查最终张量缺席、样本输入 mask 保留,以及 expected 中仍有 pg_loss。仅替换此处新增断言,保留实际 loss/backward、CP gate 和消费者状态覆盖;不用运行不支持 CP 的 replay loss adapter。
|
|
||
| A 4-token response split across two ranks leaves this rank with two local | ||
| tokens whose log-probs drifted up (mean seq_kl 3 > opsm_delta), so the | ||
| whole local shard is OPSM-rejected. Reproduces the reviewer's crash shape: |
There was a problem hiding this comment.
Reproduces the reviewer's crash shape 解释了本次补丁的来源。长期需要保留的是本 rank 的本地长度为 2、完整 response 长度为 4,以及不能用完整长度拆本地 mask 的约束。请移除对 reviewer 的归因,直接描述该坐标契约;具体复现来源留在本行的 review 讨论即可。



What
Agentic 异步训练的权重版本追踪与滞后审计(任务 No.15)。观测流现在可以回答:每一段成功提交的生成内容,是由哪个权重版本生成的、被训练消费时滞后了多少。
WeightVersionSpan类型;在relax/agentic/session/service.py的生成 attempt 边界采集 spans,贯穿 IR /MsgNode/append_resp/build_sample,落到Sample.weight_version_spans。3.1.0);train 流在每个样本上打consumed_weight_version(schema3.2.0)。python -m relax.utils.agentic_obs.version_audit <run_dir>CLI,按sample_export_idjoin trajectories × train 两个数据流:支持 per-session/turn/segment 视角、未知版本率三口径(span/token/sample)、以及生成跨度 vs 消费滞后 vs 等待滞后三种指标区分;完成时刻的引擎默认版本作为独立近似指标engine_default_lag单列输出,绝不顶替等待滞后。docs/{zh,en}/guide/weight-version-audit.md;用户指南相应小节已更新。weight_version(详见 Why 节「DCS 版本计数」)。Why
Fully async 模式下,session 会跨越多次权重更新生成,还会因 abort 暂停恢复。没有按 segment 的版本关联,就无法审计数据新鲜度——无法区分"合法跨版本生成的 session"和"消费了严重陈旧数据的 session"。参考 miles PR #1891 与 #3334,并基于既有的 attempt 级字段
Sample.weight_versions扩展。关键设计决策:
version: null),绝不猜测为 0 或最新版本,且不进入滞后均值的分子分母。build_sample展平后在Sample上是整条 response 连续坐标——两套坐标系从不在同一流中混用。service.py既有异常护栏内,观测链路的其余改动均为加法式 kwarg 透传。除下文注明的 DCS 版本计数修正与 LoRA adapter 版本戳外,在 CPU 套件已验证的 colocate/hybrid 与 DCS 路径上 rollout/train 行为不变。loss_mask.ranges是"采集训练输入时"生效的 mask;OPSM/TIS 会在该快照之后继续屏蔽 token,因此 token 类指标描述输入口径(汇总以mask_space: "training_input"标明),最终训练目标口径需要 loss 内部信息,不在本审计的观测面内。缺失 mask 的旧记录按未知处理(token 指标为 null、计入mask_missing_sample_count),不回退到 span 全长。post_generation_lag)的完成戳在 Session 完成事件上取得:完成戳取同一策略在完成时刻的已确认发布序号——managed LoRA 路径在 finalize 起点读一次 LoRA runtime 的发布账本(status的default_version,该值只在发布 commit 时前进,与 span 标签同一 version_id 空间);这样,最后一段在 v3 生成、工具返回期间发布 v4、训练在 v5 消费时,等待滞后为 1 而不是 2(最后一次 attempt 的回显看不到工具等待期间落地的发布,不能作为完成戳)。无法取得已确认发布序号时(普通路径无发布账本、查询超时或异常、观测关闭),完成戳为null,等待滞后按未知输出——绝不用最新片段年龄或迟到的引擎探针顶替。finalize 时的引擎侧读取(普通路径对单个 worker 的一次get_weight_version)只作为独立的engine_default_weight_version观测,落到 CLI 的engine_default_lag近似列;managed 路径完成戳本身即来自账本,不重复写该观测。完成戳查询受观测开关门控:观测关闭时零额外 RPC;观测开启时受 2s 上限,超时/异常按未知完成导出,绝不阻塞正常 finalize。回归用例:tests/cpu/test_weight_version_service.py(v3→v4→v5 全链路、工具期间发布不漏、无账本/超时/异常/关闭各分支)、tests/cpu/test_weight_version_observability.py(观测关闭的会话正常走到终态)。既有行为的一处显式变化——DCS 版本计数:仅同步 actor_fwd、不向 rollout 发布的调用(如推理恢复期间仅为 ActorFwd 参考模型补权重)不再推进 DCS 的
DeviceDirectBackend.weight_version,rollout 继续服务上次发布的版本。以「一次 rollout 发布 → 一次仅 actor_fwd 刷新 → 再一次 rollout 发布」为例,weight_version计数现在为 1、1、2,此前为 1、2、3;每次调用的尝试计数weight_sync_attempts不受影响,仍逐次 +1。这是修复而非行为破坏:actor_fwd-only 同步只刷新参考模型,rollout 引擎没有收到新权重;若计数照增,下一次真实发布会跳过一个序号,生成侧标签与消费侧版本戳错位一个版本——一次实际发布会被差算成两个,跨过该点的消费滞后全部虚高 1。回归用例:tests/cpu/distributed/checkpoint_service/test_weight_sync_lifecycle.py::test_actor_fwd_only_sync_does_not_publish_a_new_weight_version;语义说明见docs/zh/guide/weight-version-audit.md。managed LoRA publication 使用自身已确认的发布序号,不受此变化影响。既有行为的一处显式变化——LoRA adapter 发布的版本戳:传统 LoRA adapter 模式(
--lora-adapter-mode,无 managed publication)下,/update_lora_from_distributed的 payload 本身不带版本字段,引擎的版本标签会永远停在首次底座同步,而 DCS 计数器每次 adapter 发布都在前进——消费年龄会虚高「自首次底座同步以来的 adapter 发布次数」,随训练线性增长。修复:adapter 推送确认后、恢复生成前,后端对全部 rollout 引擎调一次既有的/update_weight_version端点打上当前序号(与 colocate routed-experts、fsdp_turbo 两条既有发布路径的惯例一致)。调用位于 pause 窗口内、分布式锁的 try 块内,失败走既有的 push_error 全 rank 失败路径:锁仍释放、生成保持暂停、序号停在本次调用、下次同步重推 adapter。回归用例:tests/cpu/distributed/checkpoint_service/test_weight_sync_lifecycle.py::test_adapter_publish_stamps_the_engine_version与test_adapter_stamp_receipt_failure_keeps_generation_paused。How
relax/utils/types.py:WeightVersionSpan(version, token_start, token_end, attempt_seq)+Sample.weight_version_spans。relax/agentic/session/state.py/service.py:spans 按 generate attempt 累加,只经_terminal_response_locked → append_resp进入 forest;被丢弃的 IR(取消/abort)不会进入任何流。完成戳经_completion_weight_version在 finalize 起点采样(managed LoRA:发布账本default_version;普通路径:无账本,恒为未知),两条导出分支都写入agentic_trace.events.generation_complete_weight_version;引擎侧迟到读取写入独立的agentic_trace.events.engine_default_weight_version。relax/agentic/observability.py+relax/utils/agentic_obs/records.py:lineage 节点携带 spans(schema3.1.0)。relax/backends/megatron/actor.py+relax/utils/agentic_obs/train_hooks.py:按模式取consumed_weight_version——colocate/hybrid 走weight_updater.weight_version,DCS 传统路径走DeviceDirectBackend.weight_version(仅由 rollout 发布推进,见 Why 节说明;schema3.2.0)。relax/distributed/checkpoint_service/backends/device_direct.py:adapter 发布成功后对引擎打版本戳(见 Why 节「LoRA adapter 发布的版本戳」)。relax/utils/agentic_obs/version_audit.py(新增):流 join,容忍 JSONL 撕裂尾行与 overflow train 分片(overflow_step_*按数值序排列)。提供--lora-artifact-dir时以「是否提供目录」决定序号模式:目录给出但映射缺失、损坏、不可读或为空 → 全部年龄未知(CLI 有 warning),绝不回退到带空档的原始 id。engine_default_lag由消费版本与探测版本各自的 ordinal 决定,与片段标签无关——全部片段未知的样本仍能算出这一列。Testing
CPU 套件(本分支已 rebase 到当前
main):权重版本相关测试全绿:scenarios、session state/service、version_audit、types/train_hooks,以及扩展后的既有 observability 套件与 DCS 生命周期套件(含 actor_fwd-only 计数、adapter 版本戳与打标失败回归)。
全量回归 vs 合并前基线:
pytest tests/cpu→ 0 新增失败(既有环境性失败——缺 megatron/transformers/transfer_queue 依赖——与改动前完全一致)。触碰文件
ruff check与ruff format全部通过;docstring 按仓库 docformatter(--wrap-descriptions 79)排版。pre-commit run --all-filespassesTests pass (
pytest tests/cpu— 差异如上)New tests added (scenarios、service/state、observability round-trip、version_audit CLI、DCS lifecycle)
Documentation updated (
docs/{zh,en}/guide/weight-version-audit.md+ 用户指南小节)Type of Change
Screenshots / Logs
审计摘要示例(来自可复现的验收场景,数值经真实 CLI 逐字节核对):
{ "sample_count": 2, "lag_sample_count": 1, "oldest_lag_mean": 4.0, "oldest_lag_max": 4, "newest_lag_mean": 2.0, "token_weighted_lag_mean": 2.8, "generation_span_mean": 2.0, "span_missing_rate": 0.3333, "token_missing_rate": 0.2857, "sample_missing_rate": 0.5 }未知版本的样本(1002)不进入任何 lag 均值(
lag_sample_count=1),只通过三个缺失率出现。