Skip to content

feat(megatron): handle zero-token no-signal steps in the shared trainer - #285

Merged
SigureMo merged 15 commits into
redai-studio:mainfrom
xcosmosbox:feat/zero-token-step
Oct 4, 2026
Merged

SigureMo merged 15 commits into
redai-studio:mainfrom
xcosmosbox:feat/zero-token-step

Conversation

@xcosmosbox

@xcosmosbox xcosmosbox commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

What

修复共享 Megatron 训练器对空 response 和全 mask batch 的处理:按真实有效 token 数归约;全局没有有效 token 时,各 rank 一致跳过 optimizer 和 LR scheduler 更新,避免 Adam 动量或 weight decay 在无训练信号时改变参数。

Why

此前 CP=1 会把空或全 mask response 至少计为一个 token,与 CP>1 的计数不一致;零梯度也不能保证 optimizer 不改变参数。修复适用于共享训练路径,不限于 RLOO。Relates to #205。

How

  • CP=1 与 CP>1 都按未 mask 的 token 计数;空 response 返回匹配的空 logits/token 切片。独立导出 num_tokens,使跳过判断不依赖 token-mean 或 sample-mean 指标分母,dummy microbatch 贡献零。
  • 末级 pipeline stage 在 DP+CP 组归约有效 token 数。PP>1 时所有 stage 参与广播,源为 mpu.get_pipeline_model_parallel_last_rank() 返回的全局 rank;PP=1 不广播。判断保留在设备侧,仅在 Python 分支前读取一次标量。
  • 零 token step 跳过 optimizer/scheduler,报告 grad_norm=0,并以 update_successful=False 通知 critic 检查。指标分母为零时仅接受全零分子;非零分子仍报错,避免掩盖归约错误。
  • OPD 两种 clip fraction 使用原始 loss mask 对应的 reducer,支持 token-mean、sample-mean 和 CP;TIS 改写 policy mask 时,OPD 诊断仍沿用原始 mask。
  • 中英文算法文档仅澄清 loss mask 与 reward baseline 的关系,保留必要的用户语义。

Testing

最近一次功能回归基于 af7cf7f(后续仅修改中英文文档):

CUDA_VISIBLE_DEVICES="" python -m pytest -q -rs \
  tests/backends/megatron/test_zero_token_step.py \
  tests/backends/megatron/test_rloo_policy_loss_dispatch.py

在具备 Megatron 依赖的环境中运行,结果为 58 passed、2 skipped;两项 CUDA host-sync 检查因隐藏 GPU 而跳过。覆盖包括:

  • 4 进程真实 Gloo 通信:TP=2/PP=2、DP=2/PP=2 拓扑下,全零及部分 rank 有有效 token 时,各 rank 的决策一致。PP>1 的覆盖使用真实进程组,不再依赖已删除的广播调用 mock 断言。
  • train_one_step 的 7 个场景:正常/零 token、不同归约模式、RM 指标,以及非末级 pipeline 经广播接收跳过决定;验证 optimizer/scheduler、critic 的 update_successful 标志和 capture 生命周期。
  • OPD 的 32 个 mask/TIS/clip/归约组合与 4 个 CP mask 切片及归约数值用例(隔离 OPD loss 归约);RLOO 独立 loss/梯度期望、全 mask batch 的零 loss/normalizer/指标/梯度,以及零分母非零分子的报错行为。

此前单节点 GPU 验证:f2fdcfb 完成 8-rank NCCL 的 7 种拓扑、28 个场景,以及 Qwen3-0.6B TP=2/PP=2 的正常→全 mask→正常训练,确认跳过步骤的参数、optimizer 和 scheduler 状态不变且后续恢复更新;d670f66 的 OPD 修复通过 60 个 CUDA loss 场景和 24 个 CUDA training-step 场景。本轮未重跑 GPU 端到端训练,未覆盖跨节点端到端训练。

  • pre-commit run --all-files 通过
  • 上述定向回归通过(未运行完整 pytest tests/)
  • 中英文文档同步更新
  • VitePress 文档构建通过,已核对中英文生成页面

Type of Change

  • Bug fix
  • Documentation update

@xcosmosbox
xcosmosbox marked this pull request as draft August 20, 2026 02:58
…ection

The original implementation unconditionally broadcast the zero-token
decision over the pipeline-model-parallel group, but that group does not
contain global rank 0 in PP=1 topologies, causing a collective mismatch
deadlock (rank 0 ValueError + other ranks stuck in optimizer all-reduce)
that tripped the global restart path. With PP=1 every rank is the last
pipeline stage and joins the same DP+CP all-reduce, so the local count is
already consistent and no broadcast is needed. Add regression tests for
PP=1 (no broadcast) and PP>1 (last stage broadcasts, non-last stages join).
@xcosmosbox
xcosmosbox marked this pull request as ready for review August 20, 2026 03:08
@xcosmosbox

Copy link
Copy Markdown
Contributor Author

All changes are ready, awaiting your review to merge @NINGBENZHE

@Yangruipis

Copy link
Copy Markdown
Collaborator

@codex review following the repository AGENTS.md and skills/code-review/SKILL.md

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 9, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-09T18:10:56.130572Z 8cad9cb Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 8cad9cb47f

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread relax/backends/megatron/model.py Outdated
Comment on lines +972 to +975
torch.distributed.broadcast(
signal,
src=pp_size - 1,
group=mpu.get_pipeline_model_parallel_group(),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Use the pipeline group's global last rank as source

When PP is combined with TP or DP, pp_size - 1 is only the pipeline-local stage index and is generally not the global rank of the last member of each pipeline group; torch.distributed.broadcast(..., src=...) interprets src as a global rank. Consequently, most pipeline groups either reject this source as a non-member or wait for a rank that never participates, hanging every PP>1 training step. Resolve the group's last rank with dist.get_global_rank(pp_group, pp_size - 1) or Megatron's pipeline-last-rank helper.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

在 53ad8a4 上用当前 _is_global_zero_token_step() 和四进程 Gloo 复现了这个 P1:按仓库 tp-cp-ep-dp-pp 排列,TP=2、PP=2 的流水线组为 [0,2]、[1,3]。全局 token 数均为零时,rank 0/2 报 ValueError: Global rank 1 is not part of group;rank 1/3 则返回 False,因为作为首阶段的 rank 1 广播了初始零值,覆盖末阶段的跳过决定。

请把两个 broadcast 的源统一改为 mpu.get_pipeline_model_parallel_last_rank();Docker 固定的 Megatron 版本已提供该接口。当前回归测试 用 mock 强制断言 src == 1,无法验证真实组成员关系,需增加 PP 与 TP/DP 组合的进程组测试。

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

已在合并后的 8a0bc3d 复核此问题:本次 push 仅合入 main(GDN CP 等主线改动),_is_global_zero_token_step 与上一审查版本 53ad8a4 逐字节一致,上面的四进程 Gloo 复现结论对新 head 直接适用。

补充两点新信息:

  1. 新 head 的 CI 8/8 全绿(含 4×GPU / 4×NPU / 2×GPU 集成测试),但这些配置均为 PP=1,不会触达该广播路径,绿 CI 不能作为该路径正确的证据。
  2. 修复可循仓库既有模式解析组内全局 rank:dist.get_process_group_ranks(mpu.get_pipeline_model_parallel_group())(relax/backends/megatron/weight_update/lora_adapter_sync.py:160、hf_weight_iterator_direct.py:77 同 pattern),或直接使用 mpu.get_pipeline_model_parallel_last_rank()。同时请更新 tests/backends/megatron/test_zero_token_step.py:113、:137 的 mock 断言(当前断言 src == 1,与真实组成员关系无关)。

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

已在 f2fdcfb 确认修复:广播源改为 mpu.get_pipeline_model_parallel_last_rank()(model.py:992),且 PP>1 时所有 stage 进入同一广播(_is_global_zero_token_step 重构为 last-stage all-reduce + 单一共享广播)。新增 4 进程 Gloo 测试以真实 parallel_state 覆盖 TP=2/PP=2 与 DP=2/PP=2 拓扑(即本线程复现的配置),CI 中 test_is_global_zero_token_step_real_process_groups_agree[tp2-pp2]、[dp2-pp2] 均通过。

Comment thread relax/backends/megatron/model.py Outdated
Comment on lines +963 to +966
num_tokens_local = sum(x["values"][0] for x in losses_reduced) # type: ignore[index]
torch.distributed.all_reduce(
num_tokens_local,
group=mpu.get_data_parallel_group(with_context_parallel=True),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Detect zero tokens independently of metric reduction mode

When --calculate-per-token-loss is disabled, loss_function() stores num_samples rather than the token count in values[0]. A genuine fully masked batch therefore yields a positive value here, so this helper returns false and the optimizer and scheduler still advance with zero gradients—the exact parameter drift this change is intended to prevent. This affects the default response-mean mode used by many existing training scripts; pass an explicit effective-token count instead of reusing the metric denominator.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

此项已在 53ad8a4 修复:loss_function 单独导出 effective_num_tokens,检测器改为累加该字段,且 dummy microbatch 贡献零。隔离调用当前生产函数检查了 per-token 开/关与 dummy 开/关四种组合,计数均符合预期,不再依赖指标分母。

Comment thread relax/backends/megatron/model.py Outdated
num_tokens_local,
group=mpu.get_data_parallel_group(with_context_parallel=True),
)
signal[0] = 1 if num_tokens_local.item() == 0 else 0

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Remove per-step GPU-to-CPU token synchronization

This helper is called on every training step, and num_tokens_local.item() synchronizes the CUDA stream on every last-stage rank; signal.item() then introduces another host synchronization on every rank before returning. This adds a pipeline-wide stall to the hot training path even for ordinary nonempty batches. Keep the zero-test tensor-side and avoid redundant host materialization in accordance with the repository's hot-path rule.

AGENTS.md reference: AGENTS.md:L38-L40

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

已在 f2fdcfb 确认修复:signal.copy_((num_tokens_local == 0).reshape(1)) 把判定留在设备侧,冗余的 num_tokens_local.item() 已移除,仅保留 Python 分支必需的一次 signal.item()(docstring 已注明该约束)。新增 test_is_global_zero_token_step_single_host_sync 用 torch.cuda.set_sync_debug_mode("warn") 断言每次判定恰好一次主机同步,CI(H20 GPU)中 PP=1/PP=2 参数化均通过。

Comment thread relax/backends/megatron/model.py Outdated
"Training step %d has zero effective loss tokens globally; skipping optimizer and LR scheduler updates.",
step_id,
)
update_successful = True

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Mark skipped critic updates as unsuccessful

On a zero-token critic step no optimizer update occurs, but setting update_successful = True causes maybe_verify_critic_value_head_movement() to count it as an eligible successful update. After several consecutive zero-token critic batches, the runtime check emits a false value-head warning and marks itself verified, so it will not validate a later real update. Preserve a distinct skipped state or pass False to the movement checks for this branch.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

已在 f2fdcfb 确认修复:跳过分支改回报 update_successful = False(model.py:1271),assert_critic_value_head_updated(ci_utils.py:47)与 maybe_verify_critic_value_head_movement(ppo_utils.py:1678)均按未更新步早退,不再计入 eligible step,也不会触发误报警。test_train_one_step_preserves_logical_batch_and_capture 断言传给 critic 检查的值为 [not zero_tokens],CI 已通过。

@SigureMo SigureMo self-assigned this Sep 22, 2026
# 🔩 Chore

- Merge current main while preserving zero-token step handling and the
  shared CP mask-sum helper, including SFT predictor-mask alignment.
- Preserve logical step batch sizes for scheduler increments and sample-mean
  metrics, and close replay capture on both pipeline return paths.
- Carry effective token counts separately from metric denominators so
  main's sample-mean zero placeholder does not skip valid optimizer steps.

---

# ✅ Tests

- Adapt zero-token fixtures to the current trainer signature and add
  regressions for sample/token means, dummy batches, scheduler increments,
  and capture completion.
- All-file pre-commit hooks passed. Focused CPU suite: 25 passed, 2 skipped;
  isolated production-function/CP suite: 19 passed with Megatron boundaries
  stubbed. CPU tests ran eagerly due to the host's Triton mismatch.
- Multi-node GPU/Megatron integration was not run because this environment
  has CPU-only PyTorch and no Megatron installation.

Co-authored-by: Codex <[email protected]>
@rai-studio-bot

rai-studio-bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Nyanpasu 审查看板

审查状态: 💬 已完成 · 有补充意见

审查版本: 72bc6b7

目标分支: main

72bc6b7 已完成审查(一条 P3 非阻塞建议):get_responses CP=1 分支重构(-6/+2)经直接执行对照重构前分支语义验证逐项等价——(rl=0) 两情形 start==end 自然空切片,SFT 分支新增非空守卫对 (0,0) 必要(否则空 logits 配长度 1 tokens),显式 tokens 边界与负索引在 unconcat_tokens 恒为真实长度(data.py 于 CP 切分/填充前保存)下等价;本地 dispatch 11 + OPD 36 + sft_data 3 通过,本 head 全部必需 CI 检查(含 H20 GPU 单测)通过。其余 8 文件与 11d8be8 已批准版本逐字节一致。F1–F5 维持已解决;新增 F6(P3):描述 Testing 节「后续仅修改中英文文档」括号说明因本重构过期。

审查阶段进度范围与结果
常规审查 ✅ 已完成 已审查 72bc6b7 全部改动(loss.py -6/+2):重构以显式切片边界取代空 response 特判并以非空守卫限制 SFT 分支;6 组边界用例(含跨样本记账与 (0,0) 序列)经直接执行生产函数与重构前分支语义逐项比对一致;确认 unconcat_tokens 真实长度假设(data.py:367)与 bshd/thd 记账不变;本地三套件与全 head CI(含 H20)通过;发现 F6(P3,描述滞后)。
深度审查 ✅ 已完成 等价性验证构成本轮深度证据:直接执行 get_responses 对照独立复现的重构前分支语义(6 组用例全匹配);SFT 守卫缺失时的失效模式已推导((0,0) 会产出空 logits 配长度 1 的 tokens);此前轮次的定向变异证据对未触及范围沿用,并由本 head H20 GPU CI 全绿确认。

审查发现

待处理
编号 严重性 问题状态规则来源
F6 Low severity PR 描述 Testing 节「后续仅修改中英文文档」因 72bc6b76 代码重构过期 🚧 未解决 —
已解决或已取代
编号 严重性 问题状态规则来源
F1 High severity PP 广播使用 stage index 而非 global rank ✅ 已解决 —
F2 High severity 独立有效 token 计数不应依赖指标分母 ✅ 已解决 —
F3 Medium severity 末阶段零 token 判定重复进行标量同步 ✅ 已解决 热路径禁止 GPU-CPU 同步
F4 Medium severity 跳过的 critic step 被记为成功更新 ✅ 已解决 —
F5 Low severity PR 描述 Testing 节仍引用已删除的 mock 断言与 src=pp_size-1 语义 ✅ 已解决 —
提交范围 · 接收 9 · 建议移出 0 · 待确认 0

接收 9 个文件 · 建议移出 0 个文件 · 待确认 0 个文件。移出与待确认部分暂停深审,不代表审查通过。

文件结论仓库维护必要性依据替代去向或方案
relax/backends/megatron/cp_utils.py
relax/backends/megatron/loss.py
relax/backends/megatron/model.py
relax/utils/opd/opd_utils.py
接收 实现共享 Megatron 训练器的 zero-token no-signal step 语义与 OPD clip 指标归约;72bc6b76 在 11d8be8 之上仅将 get_responses 的空 response 特判重构为显式切片边界(-6/+2),行为等价性为本轮核对重点;其余职责与已批准轮一致。 PR #285 描述(What/How);调用方为 relax/backends/megatron/model.py train_one_step、loss.py policy_loss_function→compute_policy_opd_loss、get_log_probs_and_entropy→get_responses 外部实验脚本无法修复共享训练器与 OPD 诊断指标语义;这些行为必须随生产训练路径落库。
tests/backends/megatron/test_zero_token_step.py
tests/backends/megatron/test_rloo_cp_reduction.py
tests/backends/megatron/test_rloo_policy_loss_dispatch.py
接收 直接测试真实生产函数的回归测试;与 11d8be8 逐字节一致,检测等价性已经两组定向变异与本地执行验证,get_responses 空 response 用例在 dispatch 文件中本地可运行。 PR #285 描述 Testing 节;被测函数均在生产改动范围内 一次性外部验证无法提供长期回归保护;测试使用 monkeypatch 或本地 Gloo 进程组,无需多节点 GPU。
docs/en/examples/algorithms.md
docs/zh/examples/algorithms.md
接收 各一行中英文档更新,与已批准的 11d8be8 逐字节一致,本轮未触及。 PR #285 描述(Type of Change 勾选 Documentation update);docs/ 双语文档惯例 无更小机制;文档必须反映变更后的行为。
精简审查与验证依据
审查范围进度结论
生产代码 ✅ 已完成 生产改动必要且为最小实现:token 计数口径统一、指标归一化收敛为单一可测函数、optimizer/scheduler 跳过的跨 rank 一致判定、OPD clip 指标与 policy reducer 同基;72bc6b76 将 get_responses 空 response 处理并入通用显式切片路径(较 PR 中间版本更简且修复 base 的负索引边界缺陷,等价性已验证)。未发现可删除或合并的冗余实现。
测试 ✅ 已完成 本 head 的三个提交本身即测试精简,已按检测等价性审计:合并/删除后各失败模型仍有覆盖(真实 Gloo 进程组、真实 helper 跳过断言、TIS 有区分力组合),变异实验确认零检测损失;被删的 normalize 零路径单元测试为 megatron 门控覆盖的重复(以 GPU 套件为唯一覆盖是可接受的权衡)。无进一步可删除用例。

生产代码的必要性与替代方案

范围必须保留的契约更简单的方案结论依据与限制
relax/backends/megatron/cp_utils.py 移除 CP=1 的 clamp_min(loss_mask.sum(), 1) get_cp_local_num_tokens 返回真实未 mask token 数(int32,与 main #290 一致);唯一生产调用方为 loss_function(relax/backends/megatron/loss.py:1469)。 保留 clamp_min 并在 loss_function 内对空 response 特判。 保留 保留 clamp_min 会维持 CP=1 与 CP>1 双口径(本 PR 要修复的问题);调用方唯一、改动最小,正常非空路径数值不变。
relax/backends/megatron/loss.py:normalize_reduced_loss_metrics、get_responses 空 response 语义(72bc6b76 重构为显式切片边界+SFT 非空守卫)、num_tokens 独立导出 train_one_step 消费归一化指标;num_tokens 供 _is_global_zero_token_step 独立计数;get_responses 对空/全空序列返回匹配的空 chunk、SFT 分支产出 next-token 对齐切片。 保留重构前的空 response 特判分支与负索引切片(PR 中间版本),或维持 base 的无守卫结构(存在 tokens[-0:] 边界缺陷)。 保留 72bc6b7 比其中间版本更简(4 行特判并入通用切片路径,仅留 2 行守卫/边界改动),且修掉了 base 的 tokens[-0:] 缺陷;等价性经直接执行 6 组边界用例对照重构前语义逐项验证,本 head H20 GPU CI 全绿。限制:本地无法执行 megatron 门控的 SFT 路径测试,依赖 CI 确认。
relax/backends/megatron/model.py:_is_global_zero_token_step(f2fdcfb 重构)与 train_one_step 跳过分支(update_successful=False) 全局零 token 时所有 rank 一致跳过 optimizer 与 scheduler 更新,critic 检查不计入 eligible step。 修复前的条件广播(src=stage index)+ 本地 .item() 判定 + update_successful=True。 保留 单一共享广播(src=get_pipeline_model_parallel_last_rank())+ 设备侧判定(一次必需主机读取)比修复前更简单且正确;真实进程组测试与 sync-debug 测试在 CI 通过。d670f66 未触及该区域。
d670f66:policy_loss_function 入口捕获 opd_metric_reducer(TIS 重建前、原始掩码基),compute_policy_opd_loss 新增 metric_reducer 参数,两处 clip_frac 改为 mask 感知归约 OPD clip 指标 numerator 与归一化分母同基(per-token 为掩码内 token 和、sample-mean 为逐样本掩码均值和);全 mask batch 下为零以配合 no-signal fail-fast;TIS 替换 policy 掩码时 OPD 诊断保持原始掩码(与 OPD loss 自身的 reduce_opd_loss 基一致)。 维持 .mean()(掩码盲、跨 microbatch/rank 不可加,全 mask batch 产生非零分子会触发 normalize_reduced_loss_metrics 的 fail-fast 误报)。 保留 改动最小:两处指标行 + 一个参数 + 一处 reducer 捕获;opd_utils 中无其他掩码盲 .mean();44 个参数化测试在 H20 CI 通过,期望值算术与生产公式核验一致(partial-mask token 2/3、sample 0.75 等)。

测试的必要性与替代方案

范围必须保留的契约更简单的方案结论依据与限制
tests/backends/megatron/test_zero_token_step.py(9219871b 后经 3 个提交合并/精简:train_one_step 7 场景、真实 Gloo 进程组、OPD 32 组合) 锁定 _is_global_zero_token_step 分布式契约(真实 TP=2/PP=2、DP=2/PP=2 进程组全 rank 一致 + 每次判定一次主机同步)与 train_one_step 跳过行为(含 non-last-stage 经广播接收决策);OPD clip 指标在 2 clip × 2 均值 × 8 掩码/TIS 组合下按有效 token 归约、TIS 保持原始掩码基、全 mask 零指标零梯度,CP 无有效 token rank 贡献零。 保留被删除的 2 个 mock PP2 广播测试与 8 个无区分力的 TIS 组合、独立跳过测试与 normalize 零路径单元测试。 保留 删除项检测等价性由两组定向变异验证:OPD 改用 TIS reducer 恰好 12 个保留 TIS 用例失败(被删组合在该变异下本就通过);clamp_min 重引入由保留用例捕获。真实 Gloo 测试以真实组成员覆盖 src 契约(mock 断言的更强替代)。合并后的跳过断言强于原独立测试(执行真实 helper 而非 stub)。本地 36 用例 + CI 通过。
tests/backends/megatron/test_rloo_policy_loss_dispatch.py(af7cf7f6 折叠 fully-masked-batch 用例并删除两个零 token 单元测试) loss_function 的 token denominator/numerator oracle(含全 batch 全 mask:零 loss、零 normalizer、全零 logging、零梯度)与 normalize_reduced_loss_metrics 非零分子 fail-fast;normalizer dtype 与 main #290 的 int32 一致。 保留独立的 test_all_zero_token_loss_returns_zero_normalizer_and_numerator 与 test_zero_token_metrics_are_reported_as_zero_without_division。 保留 折叠用例以更强断言覆盖被删测试(count_nonzero 覆盖整个 values 张量并新增零梯度断言);clamp_min 重引入变异由该用例捕获(3 失败之一)。normalize 零返回路径仍由 megatron 门控测试覆盖(train_one_step token-mean-zero 与 OPD 全 mask per_token),fail-fast 分支保留本地单元测试;代价是零路径失去 CPU 级快速覆盖(H20 必跑,可接受)。本地 11 用例通过。
tests/backends/megatron/test_rloo_cp_reduction.py(第三样本改为 0 长度 response) get_cp_local_num_tokens 与 CP 切分在含空 response 时的 ownership 一致性。 维持原有非空 response 用例。 保留 0 长度样本使部分 CP rank 本地切片为空,同时验证空 cat 分支与 ownership 计数。
9219871 合并提交:test_train_one_step_preserves_logical_batch_and_capture 新增 reward-model-pair-mean 参数化变体(+28 行) RM pair-sum 指标(rm/score_* 与 _score_*_second_moment)经 normalize_reduced_loss_metrics 按 logical GBS 归一化后,再由 main #258 的 popping 计算 rm/score_*_std;零 token 步跳过 optimizer 且 RM 指标全零。来源:main #258 的 model.py popping 代码与本 PR 归一化的合并交互。 不新增变体,仅依赖 main 侧 RM loss 单元测试(其不经 train_one_step,无法覆盖该交互)。 保留 独立算术 oracle:GBS=2 与 token_count=4 分离,pair sums 6/3/20/5 除以 GBS 得 3/1.5/10/2.5,std=sqrt(10-9)=1.0、sqrt(2.5-2.25)=0.5,已手工核验并通过对生产 normalize_reduced_loss_metrics 源码的隔离执行复现;若合并把 popping 移到归一化之前或丢失任一侧,断言失败。复用既有 mock harness(PP=1 无广播断言、critic update_successful 捕获),无重复实现;本地缺 megatron.core 无法执行,由 CI(H20)覆盖。
Powered by Nyanpasu with glm-5.3[1m] xhigh, please check the suggestions carefully.

@rai-studio-bot rai-studio-bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

需要修改:PP 与 TP/DP 组合仍存在阻塞训练或错误更新的广播源问题,四进程复现证据已补充到原讨论。独立有效 token 计数的修复已确认。

已审查本次全部 8 个变更文件及相关调用路径,18 项隔离生产函数检查通过。完整 pytest 因本地环境问题未完成;未运行 GPU/多节点集成测试,相关 CI 仍在运行。

Powered by Nyanpasu with gpt-6-astra medium, please check the suggestions carefully.

@rai-studio-bot rai-studio-bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

复核结论:仍需修改(P1 未解决)

已在合并 main 后的 8a0bc3d 完成复核:本次合并不改变本 PR 的生产代码与测试(cp_utils.py、loss.py、model.py 相关函数与上一审查版本逐字节一致),前次验证结论(含四进程 Gloo 复现)直接适用;CI 8/8 全部通过,补上了前次审查时仍在运行的验证项,但集成配置均为 PP=1,未覆盖 F1 的 PP>1 广播路径。阻塞项 F1(PP 广播源使用 stage index 而非全局 rank)仍未解决,最新复核证据已补充到原讨论;F2 已确认解决,F3、F4(P2)维持开放。

看板:#285 (comment)

Powered by Nyanpasu with glm-5.3[1m] xhigh, please check the suggestions carefully.

# 🔩 Chore

## Resolve conflict with redai-studio#290

- Keep exact CP=1 token counting without the per-sample `clamp_min(., 1)`
- Keep the `torch.int` cast of `get_cp_local_num_tokens` required by the
  Megatron int32 token accumulator
# 🐛 Bug Fix

## Broadcast the skip decision from the global last rank

- Use `mpu.get_pipeline_model_parallel_last_rank()` as the pipeline
  broadcast source; `pp_size - 1` is a stage index and breaks PP with TP/DP
- Enter one shared broadcast from every pipeline stage when PP>1

## Do not count skipped steps as successful updates

- Report `update_successful=False` on zero-token steps so critic value-head
  movement checks ignore steps without a parameter update

---

# ⚡ Performance

## Remove the redundant host synchronization

- Keep the zero-token test on device and read the decision once

---

# ✅ Tests

## Cover real process groups and the skip contract

- Add 4-process Gloo tests for TP=2/PP=2 and DP=2/PP=2 topologies
- Assert the mocked broadcast source is the global last rank
- Assert a single CUDA host synchronization per decision
- Assert skipped steps pass `update_successful=False` to critic checks

@rai-studio-bot rai-studio-bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

复核结论:通过

f2fdcfb 的修复提交已逐项确认:F1 广播源改为 get_pipeline_model_parallel_last_rank() 且所有 pipeline stage 进入同一广播,并以 4 进程 Gloo 真实进程组测试(TP=2/PP=2、DP=2/PP=2)在 CI 通过;F3 判定保留在设备侧,仅剩 Python 分支必需的一次主机读取并由 CUDA sync-debug 测试锁定;F4 跳过步不再计入 critic value-head 检查。与 main 的合并(#290 的 int32 cast、#83)解决干净,测试已适配。CI 12/12 全绿,四个历史发现全部解决,未发现新问题。

看板:#285 (comment)

Powered by Nyanpasu with glm-5.3[1m] xhigh, please check the suggestions carefully.

@xcosmosbox

Copy link
Copy Markdown
Contributor Author

@SigureMo 感谢 SigureMo 老师您之前解决的冲突及对 F2 53ad8a4 的修复。我在 8a0bc3d 之后接着把剩下由 RAI bot 所建议的部分推进了一下,新增以下两个提交:

1. 6af3f68:合入 main(99a0b6a)

2. f2fdcfb:处理审查看板剩余的问题

  • F1:pipeline 广播的 src 改为 mpu.get_pipeline_model_parallel_last_rank()(全局 rank);PP>1 时所有 stage 都进入同一次 broadcast。mock 断言改为检查全局 rank,并新增 4 进程 Gloo 真实进程组测试(TP=2/PP=2、DP=2/PP=2),修复前可复现 Global rank 1 is not part of group。
  • F3:零 token 判定留在 device 上,每个 step 只在最后做一次 .item()(原先有 3 次 host 同步),并加了 CUDA sync-debug 测试防止回退。
  • F4:跳过分支改为 update_successful=False,critic value-head 检查不会再把跳过的 step 当成成功更新,已补断言。

验证(单机 2×A100)

  • pre-commit run --all-files 通过。
  • PR 相关的 3 个测试文件:27 passed。
  • tests/backends/megatron:370 passed、6 skipped;另有 2 项失败,在未改动的 main 上同样复现(test_chunked_mtp_loss.py::test_is_training_logging_matches;test_gdn_cp_gpu.py 缺少 megatron.core.context_parallel_layout)。
  • torchrun + NCCL 下,PP=2 和 DP=2 两种拓扑的判定结果正确且各 rank 一致。

还没覆盖:多节点 PP>1 端到端训练,我这边没有对应硬件。

F1–F4 应该都已经处理完了,PR 描述里 How/Testing 的细节以这条为准。麻烦帮忙触发一次复审;如果你那边有 PP>1 环境,也辛苦帮忙跑一下验证。

# 🐛 Bug Fix

- Reduce OPD clip indicators with the original mask-aware policy reducer.
- Preserve additive token/sample numerators and zero-token metric validation.
- Keep OPD diagnostics on the original masks when TIS replaces policy masks.

---

# ✅ Tests

- Cover both clipping modes, token/sample means, partial and empty masks,
  TIS rejection, and CP ranks without valid tokens.
- Validate 76 related tests and production CUDA loss/backward on QS.

Co-authored-by: Codex <[email protected]>
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

@rai-studio-bot rai-studio-bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

复核结论:通过

d670f66 已复核:OPD clip 指标(opd_per_token_clip_frac / opd_is_clip_frac)从掩码盲的 .mean() 改为与 policy reducer 一致的 mask 感知归约,numerator 与归一化分母同基(per-token 为有效 token 和、sample-mean 为逐样本均值和),全 mask batch 下为零以配合本 PR 的 no-signal 校验;TIS 替换 policy 掩码时 OPD 诊断保持原始掩码基。前次四项发现所在代码未被本提交触及,修复保持有效。CI 12/12 全绿,44 个新增参数化测试(clip 模式 × 均值模式 × TIS × 5 种掩码场景 + CP 无有效 token rank)在 H20 全部通过。

看板:#285 (comment)

Powered by Nyanpasu with glm-5.3[1m] xhigh, please check the suggestions carefully.

SigureMo and others added 2 commits October 4, 2026 21:43
# 🔩 Chore

- Merge main through 823941b, including DPO and reward-model training support.
- Preserve strict zero-token metric normalization before reward-model score
  standard deviations are derived from normalized moments.
- Keep optimizer and scheduler skipping and mask-aware OPD diagnostics intact.

---

# ✅ Tests

- Cover normal and zero-token reward-model metrics with logical pair batch
  size distinct from the effective token count.
- Validate the merged tree with all pre-commit hooks and focused CPU regressions
  for zero-token handling, policy loss, DPO, reward modeling, and classification.

Co-authored-by: Codex <[email protected]>
# ✅ Tests

- Remove two mocked PP2 collective tests duplicated by real Gloo coverage.
- Retain four-process TP2/PP2 and DP2/PP2 decision agreement tests.

Co-authored-by: Codex <[email protected]>

@rai-studio-bot rai-studio-bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

复核结论:通过

9219871b(将 main 合入分支)已复核:相对新 merge-base 的有效增量仍为原 9 个文件,生产 hunks 与已批准的 d670f667 轮逐项一致(仅上下文因 main 侧 DPO/RM 改动偏移),合并未引入对 main 侧文件的任何隐藏改动。合并交互逐项验证:normalize_reduced_loss_metrics 与 main #258 新增的 RM second-moment popping 语义一致(已隔离执行生产函数复现新测试 oracle);dpo/rm/seq_cls 路径均经共享 loss_function 外层导出 num_tokens,RM 生产批次分支长度为正、不会误触发零 token 跳过。合并提交新增的 reward-model-pair-mean 测试变体(+28 行)oracle 独立、可锁定错误合并顺序。F1–F4 维持已解决,CI 无失败(部分检查仍在运行),未发现新问题。

看板:#285 (comment)

Powered by Nyanpasu with glm-5.3[1m] xhigh, please check the suggestions carefully.

SigureMo and others added 2 commits October 4, 2026 22:18
# ✅ Tests

- Fold the standalone optimizer and scheduler skip test into the existing
  train-one-step parameterization without expanding its seven scenarios.
- Preserve non-last pipeline stage coverage by injecting the received skip
  decision through broadcast and exercising the real zero-token helper.
- Retain update, metric, gradient-norm, critic-status, and capture assertions.

Co-authored-by: Codex <[email protected]>
# ✅ Tests

- Reduce the OPD clipping matrix from 40 to 32 cases by omitting TIS
  combinations whose original masks already contain no valid tokens.
- Fold the fully masked RLOO batch into the scalar and gradient tests,
  retaining zero loss, normalizer, logging, and gradient assertions.
- Remove duplicate all-zero metric normalization coverage while retaining
  rejection of nonzero numerators with a zero denominator.

Co-authored-by: Codex <[email protected]>
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

@rai-studio-bot rai-studio-bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

复核结论:已完成 · 一条非阻塞建议

af7cf7f6 的三个仅测试提交已逐项审计(生产代码未触及,有效增量与已批准的 9219871 轮逐字节一致):c4165c56 删除的 PP2 mock 断言由保留的真实 Gloo 进程组测试覆盖(错误 src 会直接抛错/挂起,即 F1 的原始复现路径);5570841c 合并后的 train_one_step 参数化测试保有原独立跳过测试的全部断言,并改为实际执行真实 _is_global_zero_token_step(新增 non-last-stage 场景);af7cf7f6 裁剪后的 OPD 矩阵对「原始掩码基」失败模型保有完整检测。已通过两组定向变异验证检测等价性:重引入 clamp_min 使 3 个用例失败(含新合并的 fully-masked-batch);将 OPD 指标改为 TIS 掩码 reducer 恰好使 12 个保留 TIS 用例失败。本地 dispatch 测试 11 passed、OPD 测试 36 passed;本 head 的 Python 3.10/3.12 与两项集成检查全绿(日志确认含新合并用例),H20 单测仍在运行。未发现功能性问题,一条 P3 文档建议:

  • Low severity P3 · PR 描述 Testing 节仍引用已删除的 mock 断言与 src=pp_size-1 语义
    非行级:PR 描述问题,无法挂到变更 diff 行。
    Testing 节仍写「PP>1 断言 last stage 广播(src=pp_size-1)、非 last stage 加入广播」:这两个 mock 断言已在 c4165c5 删除,由 4 进程真实 Gloo 进程组测试(TP=2/PP=2、DP=2/PP=2)取代;且 src=pp_size-1 是 F1 修复前的语义,当前代码使用 mpu.get_pipeline_model_parallel_last_rank()。建议将该条目更新为当前实际覆盖,避免后续读者按描述误解 PP 广播契约(该语义曾是 P1 死锁缺陷)。

看板:#285 (comment)

Powered by Nyanpasu with glm-5.3[1m] xhigh, please check the suggestions carefully.

# 📝 Documentation

- Explain in both languages that masking policy-loss tokens does not remove
  a sample's reward from the group baseline calculation.
- Remove backend zero-token handling details from the algorithm overview.

Co-authored-by: Codex <[email protected]>
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

@rai-studio-bot rai-studio-bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

复核结论:通过

11d8be81 已复核:本轮唯一改动为两行中英文档改写,已验证其表述与实现一致——「loss mask 只控制 token 是否参与策略损失、不将样本 reward 排除出组内 baseline 计算」对应 normalize_group_leave_one_out 按位置分组且不按掩码过滤 reward 的实现;移除后端 zero-token 细节属算法概览的编辑取舍,N_eff 公式与 rollout/rloo/no_signal_frac 指标仍保留可观测语义。其余 8 个文件与 af7cf7f 已审版本逐字节一致;af7cf7f6 的 H20 单测已全绿,确认合并/精简后的测试套件在 GPU CI 通过。上轮 F5(PR 描述滞后)已通过描述更新解决:src=pp_size-1 条目已移除,How 节现正确记录全局 rank 广播源,Testing 节与当前套件逐项吻合(58 passed + 2 CUDA 跳过 = 49 个 zero-token 用例 + 11 个 dispatch 用例),未覆盖项(GPU 端到端、跨节点)已如实披露。F1–F5 全部解决,未发现新问题;本 head CI 无失败(仍在运行)。

看板:#285 (comment)

Powered by Nyanpasu with glm-5.3[1m] xhigh, please check the suggestions carefully.

# ♻️ Refactor

- Use explicit token slice bounds so empty responses naturally yield empty chunks.
- Restrict the SFT branch to nonempty responses to preserve fully empty sequence handling.

Co-authored-by: Codex <[email protected]>
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

@rai-studio-bot rai-studio-bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

复核结论:已完成 · 一条非阻塞建议

72bc6b76(get_responses 重构)已复核:CP=1 分支的显式切片边界在全部边界组合下与原语义逐项等价——(rl=0) 两种情形 start==end 自然产出空切片;(rl=tl>0) SFT 分支不变(新增的非空守卫是必要的:否则 (0,0) 样本进入 SFT 分支会得到空 logits 配长度 1 的 tokens);tokens[total_length-response_length:total_length] 与 tokens[-response_length:] 等价,因 unconcat_tokens 在 data.py 中于 CP 切分/填充前保存、恒为真实长度。已通过直接执行生产函数对照重构前分支语义(6 组用例含跨样本记账)、本地 dispatch 11 + OPD 36 + sft_data 3 全部通过,且本 head 全部必需 CI 检查(含 H20 GPU 单测)通过。其余 8 个文件与 11d8be8 已批准版本逐字节一致。功能性问题未发现;一条 P3:

  • Low severity P3 · PR 描述 Testing 节的「后续仅修改中英文文档」已过期
    非行级:PR 描述问题,无法挂到变更 diff 行。
    描述第 19 行仍写「最近一次功能回归基于 af7cf7f(后续仅修改中英文文档)」:72bc6b76 是 af7cf7f 之后的代码重构,括号说明已不成立。建议更新为提及该重构(行为等价已验证、本 head CI 全部必需检查通过)或将回归基准改挂当前 head,避免合并时读者误以为 af7cf7f 后代码未变。

看板:#285 (comment)

Powered by Nyanpasu with glm-5.3[1m] xhigh, please check the suggestions carefully.

@SigureMo SigureMo left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTMeow 🐾

@SigureMo
SigureMo merged commit 05590bc into redai-studio:main Oct 4, 2026
12 checks passed
Mukayi added a commit to Mukayi/Relax that referenced this pull request Oct 12, 2026
…er-profiler

Brings in upstream/main 653c43c..dce533b (redai-studio#257, redai-studio#258, redai-studio#285, redai-studio#323, redai-studio#330,
redai-studio#335, redai-studio#408, redai-studio#409, redai-studio#412, redai-studio#414, redai-studio#416, redai-studio#417, redai-studio#419-redai-studio#421, redai-studio#424, redai-studio#426, redai-studio#427,
redai-studio#430, and 42 commits synced on 10-12 without PR numbers).

The only conflict is relax/utils/env.py: cc4b052 adds the DeepSeek-V4
MXFP4 QAT variables at the same spot where this branch adds the straggler
profiler variables. Resolved by keeping both blocks, straggler first.
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.

4 participants