Skip to content

fix(megatron): cast get_cp_local_num_tokens to torch.int for Megatron int32 token accumulator - #290

Merged
SigureMo merged 3 commits into
redai-studio:mainfrom
ZiyiTsang:fix/cp-num-tokens-int
Sep 26, 2026
Merged

SigureMo merged 3 commits into
redai-studio:mainfrom
ZiyiTsang:fix/cp-num-tokens-int

Conversation

@ZiyiTsang

Copy link
Copy Markdown
Contributor

Why

Megatron pipeline schedules accumulate the per-token loss normalizer on an int tensor:

  • megatron/core/pipeline_parallel/schedules.py — total_num_tokens = torch.zeros([], dtype=torch.int) (lines 256/652/1144/2363)
  • Relax own relax/backends/megatron/streaming_schedules.py:106,295 uses the same int accumulator

get_cp_local_num_tokens returned float32 (aggregated loss_mask.sum()), so every training run with --calculate-per-token-loss crashes at step 0 on the first total_num_tokens += num_tokens:

RuntimeError: result type Float can't be cast to the desired output type Int

17/30 example launchers enable --calculate-per-token-loss (all six sdpo launchers, most OPD/agentic recipes, rloo, mini_swe, nemo_gym).

How

Cast the three return paths of get_cp_local_num_tokens to torch.int so the value handed to forward_backward_* matches the accumulator dtype. Non-per-token-loss paths are unaffected (their normalizer is torch.tensor(1)), and mixing the int32 scalar into log_values still produces identical float32 metrics.

Testing

  • pytest tests/backends/megatron/test_rloo_policy_loss_dispatch.py tests/backends/megatron/test_rloo_cp_reduction.py passes on CPU.
  • test_rloo_policy_loss_dispatch now compares the normalizer dtype-safely and pins normalizer.dtype == torch.int as the regression contract (the dtype-strict torch.allclose would otherwise fail after this fix).

Relates to #285 (touches the same function cp_size == 1 branch).

Both branches (cp_size == 1 and cp_size > 1) returned float32
(loss_mask.sum()), crashing every --calculate-per-token-loss
training run at step 0: Megatron schedules.py accumulates
`total_num_tokens += num_tokens` on an int tensor, so a float
input raises "Result type Float can't be cast to the desired
output type Int". Match the accumulator dtype, and compare the
normalizer dtype-safely in the rloo dispatch test while pinning
the int contract.
Copilot AI lite review requested due to automatic review settings August 27, 2026 16:31

Copilot AI 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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@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-09T13:38:09.083997Z 4beb90e 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

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Hooray!

Reviewed commit: 4beb90e736

ℹ️ 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".

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

- Merge current main into the int32 token-count fix.
- Retain the shared CP mask-sum helper, SFT mask alignment, and CP=1
  clamping while casting the final count to Megatron's torch.int dtype.
- Validate with all-file pre-commit hooks, four focused CPU tests including
  two/four-process Gloo reductions, and ten isolated CP mask-alignment tests.
- 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 审查看板

审查状态: ✅ 已通过

审查版本: 9fdd83e

已完成目标提交 9fdd83e 审查,未发现需要修改的问题。本轮新提交仅为合并 main:两个改动文件与上轮已批准的 b71db72 逐字节一致,且已核实 main 侧变更(CP stage 3、repetition 诊断、megatron patch 扩充)不触及本修复的调用链与 int32 累加器契约。CPU eager 模式 4 项 RLOO 回归测试通过,GitHub CI(含 H20 4-GPU 单测与 Qwen3-4B/VL GPU、NPU 异步集成)全部通过。

审查阶段进度范围与结果
常规审查 ✅ 已完成 已核对合并后 diff、冲突解决结果与 main 侧交互:cp_utils.py、loss.py、streaming_schedules.py 及 get_cp_local_num_tokens 的全部消费方自上轮以来未被 main 修改;streaming_schedules.py:106/295 仍为 torch.int 累加器,pinned megatron patch 未改 schedules.py;本地 CPU eager 下 4 项 RLOO 回归测试通过(TorchInductor 后端为本地环境不兼容,非代码问题),GitHub CI 全绿。
深度审查 ✅ 已完成 父任务直接完成(改动仅 2 文件 +5/-2,未派发子任务):mutation 验证回归测试在未修复代码上于 dtype 断言处失败,且实证 torch.equal 会做 dtype 提升、既有测试无法发现 dtype 回退,新增断言检测力唯一;生产与测试必要性审计均完成,结论为保留现状,无有依据的精简项。

没有未解决的审查问题。

提交范围 · 接收 2 · 建议移出 0 · 待确认 0

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

文件结论仓库维护必要性依据替代去向或方案
relax/backends/megatron/cp_utils.py
接收 修复生产运行时崩溃:get_cp_local_num_tokens 原返回 float32,而 Megatron forward_backward_* 调度器与 relax/backends/megatron/streaming_schedules.py:106,295 的 total_num_tokens 均为 torch.int 累加器,--calculate-per-token-loss 下第一步即抛 RuntimeError。该仓库必须维护此行为。 PR #290 描述(Why 节引用 megatron/core/pipeline_parallel/schedules.py int 累加器);唯一生产调用方 relax/backends/megatron/loss.py:1437(loss_function 每 token 归一化器)。 外部工件无法修复生产崩溃;在 loss.py 调用点单独 cast 虽可行,但会给后续调用方留下 float 返回的隐患——该函数契约即 token 计数,天然应为整数,函数内收敛更简单。
tests/backends/megatron/test_rloo_policy_loss_dispatch.py
接收 在 loss_function 真实分发路径上钉住 normalizer.dtype == torch.int 回归契约;既有 test_rloo_cp_reduction 的 torch.equal 会做 dtype 提升比较,无法发现 dtype 回退,该断言是本修复的最小回归防线。 PR #290 描述 Testing 节;被测入口 relax/backends/megatron/loss.py loss_function(经 CPU stub mpu 分发)。 仅保留数值比较不足以防止 dtype 回退(torch.equal(int, float) 为 True);增加独立的 dtype 单测不如在既有 oracle 测试中一并钉住,维护面最小。
精简审查与验证依据
审查范围进度结论
生产代码 ✅ 已完成 单点 cast 已是最小实现;考察了调用点 cast、torch.long、改累加器三种替代方案均劣于现状,保留。
测试 ✅ 已完成 dtype 断言为该修复唯一可检测 dtype 回退的防线,且复用既有 oracle 测试、维护面最小,保留。

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

范围必须保留的契约更简单的方案结论依据与限制
relax/backends/megatron/cp_utils.py get_cp_local_num_tokens 返回值 .to(torch.int) 返回值作为 per-token 归一化器传入 Megatron forward_backward_* 与 relax/backends/megatron/streaming_schedules.py:106,295 的 torch.int 累加器;唯一生产调用方 relax/backends/megatron/loss.py:1437,--calculate-per-token-loss 下 float 返回在 step-0 即抛 RuntimeError。 在 loss.py:1437 调用点单独 cast(可行但给其余调用方留下 float 陷阱);cast 为 torch.long(与 int32 累加器 += 同样抛类型错误);修改累加器为 float(改动 Megatron 上游契约,风险大)。 保留 两文件与上轮已批准的 b71db72 逐字节一致;本地 CPU eager 4 项 RLOO 回归测试通过;GitHub CI 全绿(含 H20 4-GPU 单测、Qwen3-4B/VL GPU 与 NPU 异步集成);mutation 验证未修复代码上回归测试失败。限制:未本地执行 GPU 多节点 Megatron 集成(由 CI GPU 集成测试覆盖)。

测试的必要性与替代方案

范围必须保留的契约更简单的方案结论依据与限制
tests/backends/megatron/test_rloo_policy_loss_dispatch.py:170-171 的 dtype 断言与 dtype-safe allclose 在真实 loss_function 分发路径上钉住 normalizer.dtype == torch.int,防止 dtype 回退重新引入 step-0 崩溃;同时保留既有数值 oracle。 仅保留数值比较(torch.allclose 与 dtype 无关,检测不到回退);依赖既有 test_rloo_cp_reduction 的 torch.equal(实测对 int/float 做类型提升后比较,同样检测不到);另建独立 dtype 单测(重复维护、无额外检测力)。 保留 mutation 实证:checkout 未修复的 cp_utils.py 后该测试在 :170 断言处失败;torch.equal(int, float)==True 已实测确认。测试改动仅 2 行,无多余断言。
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.

已审查目标提交 b71db72,未发现需要修改的问题,同意合入。已核对 CP token 计数、损失归一化及标准/streaming 调度器的整数累加契约。

两组 RLOO 回归测试在 CPU eager 模式下共 4 项通过;因本地 Triton 不兼容,验证时关闭了 TorchDynamo。未执行 GPU/多节点集成测试,本地缺少相应运行环境;GitHub CI 仍在运行。

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

@SigureMo SigureMo changed the title fix(megatron): cast get_cp_local_num_tokens to torch.int for Megatron int32 token accumulator fix(megatron): cast get_cp_local_num_tokens to torch.int for Megatron int32 token accumulator Sep 26, 2026

@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.

结论:同意合入

已审查目标提交 9fdd83e(本轮新提交仅为合并 main)。两个改动文件与上轮已批准的 b71db72 逐字节一致;已核实 main 侧新变更(CP stage 3、repetition 诊断、megatron patch 扩充)不触及本修复的调用链与 int32 累加器契约:get_cp_local_num_tokens 的全部消费方、relax/backends/megatron/loss.py 与 streaming_schedules.py(torch.int 累加器)自上轮以来未被 main 修改,pinned megatron patch 也未改动 schedules.py。

本地 CPU eager 模式下 4 项 RLOO 回归测试通过(TorchInductor 后端为本地环境不兼容,非本次改动问题);GitHub CI 在该提交全部通过(含 H20 4-GPU 单测与 Qwen3-4B/VL GPU、NPU 异步集成)。

审查详情与范围记录:#290 (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 204ef28 into redai-studio:main Sep 26, 2026
8 checks passed
xcosmosbox added a commit to xcosmosbox/Relax that referenced this pull request Oct 2, 2026
# 🔩 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
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.

5 participants