Skip to content

fix(mtp): 修复 CP 下 MTP 有效 token 归一化 - #488

Merged
NINGBENZHE merged 4 commits into
redai-studio:mainfrom
Yangruipis:fix/mtp-cp-normalization
Nov 2, 2026
Merged

NINGBENZHE merged 4 commits into
redai-studio:mainfrom
Yangruipis:fix/mtp-cp-normalization

Conversation

@Yangruipis

@Yangruipis Yangruipis commented Oct 26, 2026 •

Copy link
Copy Markdown
Collaborator

What

修复 Context Parallel(CP)下 MTP 辅助 loss 的有效 token 归一化,使 native 和 sequence-chunked 两条路径使用同一套 CP 组计数,避免各 rank 的有效监督数量不一致时,loss 和梯度随 CP 切分方式发生偏移。

同时调整 chunked 路径的 loss 日志口径,并在 CUDA 12、CUDA 13 两个镜像构建入口安装配套 MCore 补丁。

Why

CP 会将序列分到多个 rank,但各 rank 真正参与 MTP 监督的 token 数并不一定相同:

  • padding 和 loss mask 会排除部分位置;
  • packed sequence 的边界不能跨样本预测;
  • MTP 每增加一层预测深度,向后移动标签会进一步减少有效位置;
  • teacher input mask 可能使某个 rank 的当前层有效 token 数变成零。

原先使用本 rank 的有效 token 数作为分母,再经过 CP 梯度平均,相当于对“每个 rank 的均值”取平均,没有按有效 token 数正确加权。

例如,两张卡分别有 6 个、2 个有效 token,局部平均 loss 分别为 10、2:

局部均值再平均:(10 + 2) / 2 = 6
按全部有效 token 加权:(6 × 10 + 2 × 2) / 8 = 8

该问题也会影响 MTP 辅助梯度;当某个 rank 完全没有有效 token 时,简单 clamp 本地分母只能避免除零,不能恢复正确的全局权重。

How

1. 在 CP 组内统一计数

新增 MCore 配套补丁 docker/patch/megatron/mtp-cp-normalization.patch,提供共享计数函数:

  • 汇总当前 microbatch 在标签移动前的有效 token 数;
  • 汇总当前 MTP 深度、应用 teacher input mask 后的有效 token 数;
  • 通过显式 cp_group 执行 all-reduce;本地有效 token 数为零的 rank 同样参加 collective。

计数只在 CP 组内汇总,不将不同 DP 副本混成同一个 microbatch 的分母。

2. 按既有训练模式修正缩放

令 C 为 CP 大小,N_d 为当前预测深度的全 CP 有效 token 数,N_0 为移动前的全 CP 有效 token 数,α = mtp_loss_scaling_factor / mtp_num_layers。每个 rank 注入的辅助 loss 为:

模式 本 rank 的辅助 loss 缩放 原因
默认 microbatch 归一化 α × C × local_loss / max(N_d, 1) 使用统一分母,并补偿后续 CP 梯度平均
默认 per-token 归一化 α × local_loss × N_0 / max(N_d, 1) 保留现有最终主 loss token 归一化,使用一致的移动前后计数比
main_update_tokens α × local_loss 保持该模式原有的主 update token 分母语义

修复保留现有的 microbatch/update 归一化目标,不额外改变跨 microbatch 的训练加权方式。全局有效 token 数为零时,仅 clamp 分母,辅助 loss 和梯度仍为零。

3. 对齐 native、chunked 与日志路径

  • native 和 chunked 共用上述计数函数;保留已有静态 chunked dispatch、标签移动、selective logits 和参数 detach 行为。
  • 普通日志使用 CP 全局分母,并补偿 CP 平均;token-aware 日志仍保存本地 numerator/count,由既有 tracker 汇总后计算均值。
  • CP1 保留原有数值行为;chunked 在 CP>1 且缺少配套原生补丁时明确报错,避免静默使用错误分母。
  • 两个 Dockerfile 均在已有 model-operator 补丁之后应用新补丁。

Testing

  • 修复前,新增 CPU/Gloo 回归可以复现 CP2 参数梯度与未切分参考不一致。
  • 修复后,定向回归 31 项通过:
CUDA_VISIBLE_DEVICES="" OMP_NUM_THREADS=1 python -m pytest \
  tests/backends/megatron/test_mtp_cp_normalization.py \
  tests/backends/megatron/test_chunked_mtp_loss.py \
  tests/backends/megatron/test_mtp_tracker_reporting.py -q

新增双进程测试使用真实的 loss、cross-entropy、MTP 辅助梯度注入和 tracker;CPU roll adapter 交换序列分片并处理已知 packed 边界。它将 CP2 的参数梯度、hidden-state 梯度和日志 loss,与未切分参考逐项比较,覆盖:

  • rank 间有效 token 数不均;
  • 某个 rank 没有有效 token;
  • 全部 rank 的 mask 为零;
  • teacher input mask;
  • native/chunked、microbatch/per-token 及受支持的 main_update_tokens 模式。

还验证了固定 MCore 源码与现有补丁序列上,新补丁可用 patch --batch --forward --fuzz=0 应用,静态 chunked dispatch 保留,结果可通过 Python 编译。

本次未运行 GPU、多节点或端到端训练,也未完整重建镜像;验证范围为 CPU/Gloo 数值回归和原生补丁接入检查。

  • pre-commit run --all-files passes
  • Tests pass (pytest tests/)
  • New tests added (if applicable)
  • Documentation updated (if applicable)

Type of Change

  • Bug fix (non-breaking change that fixes an issue)
  • New feature (non-breaking change that adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)
  • Documentation update
  • Refactoring (no functional changes)
  • Performance improvement
  • CI/CD or build changes

Screenshots / Logs

修复前的 CP2 数值回归失败,修复后通过;零有效 token 场景保持有限值及零辅助梯度,原有 CP1 等价性和 tracker 日志回归通过。

@Yangruipis
Yangruipis requested a review from a team October 26, 2026 12:59
@rai-studio-bot

rai-studio-bot commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

Thanks for contributing to Relax, @Yangruipis! 感谢你为 Relax 做出贡献!

📚 Contribution guide / 贡献指南

Describe the problem, your changes, and how you validated them. Keep each PR focused and run pre-commit run --all-files before submitting.

请说明问题、改动和验证方式,保持 PR 聚焦,并在提交前运行 pre-commit run --all-files。

English contribution guide · 中文贡献指南

🛠️ CI commands / CI 指令
Command / 指令 Usage / 用途
/rerun Retry failed CI / 重跑失败的 CI
/rerun <target> Rerun a workflow or check / 重跑指定 workflow 或检查
/cancel <workflow> Cancel an entire workflow / 取消整个 workflow
/help Show commands and targets / 查看指令和 target
/review Request a code review / 请求代码 review

Put one command on the first line of a new PR comment. Rerun/cancel require PR authorship or repository write access.

在新 PR 评论的首行写一条指令。PR 作者或有仓库写权限的贡献者可以重跑、取消 CI。

CI usage and targets · CI 用法与 target

🔎 Merge requirements / 合入条件

GitHub:⏳ 合入条件未满足

Requirement / 条件 Status / 状态
审批人数 ⏳ 0/1 · 至少 1 位有仓库 write 或更高权限的人 Approve
团队审批(relax-block-reviewers) ⏳ 0/1 · 可联系:Aurelius84, yuanlehome, SigureMo, NINGBENZHE
CI ✅ 已通过

@rai-studio-bot

rai-studio-bot commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

Nyanpasu 审查看板

审查状态: ✅ 已通过

审查版本: 334db7f

目标分支: main

已完成 334db7f 的跟进审查,未发现需要修改的问题。新基线未改变 MTP 的 mask 坐标、CP 分组、空 rank 图连接或最终 token 归一化;前次 cp2 测试修复和已有回归证据保持适用。

审查阶段进度范围与结果
常规审查 ✅ 已完成 已核对 7 个变更文件及当前基线。MTP 补丁、分块实现和测试与上一已审版本一致;Docker 中的补丁顺序仍正确。H20 CI 历史回归通过;当前新 head CI 尚未完成。
深度审查 ✅ 已完成 固定 MCore 与当前 Relax 调用链核验显示,标签/掩码坐标、动态 CP 子组、空 rank 参与及 DDP/schedule/finalize 缩放未改变。未实测 GPU/NCCL、TP+CP、PP/VPP、多节点或完整镜像构建。

没有未解决的审查问题。

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

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

文件结论仓库维护必要性依据替代去向或方案
docker/Dockerfile
docker/Dockerfile.cu13
docker/patch/megatron/mtp-cp-normalization.patch
relax/models/common/chunked_mtp_loss.py
接收 原生和分块 MTP 的 CP 归一化与配套镜像补丁接入属于同一修复。 PR #488 What/How:CP 组共享有效目标计数,保留训练归一化模式。 维持既有后端补丁、分块算子和镜像入口位置。
tests/backends/megatron/test_chunked_mtp_loss.py
tests/backends/megatron/test_mtp_cp_normalization.py
tests/backends/megatron/test_selective_mtp_loss.py
接收 MTP 数值、兼容与 selective 门控持久回归,以及新增 collective 所需夹具调整。 PR #488 Testing 与已核实的 cp2 门控夹具失败修复。 保留 Megatron 测试目录,门控用例模拟通信,双进程回归保留真实计数 collective。
Powered by Nyanpasu with gpt-6.1-sol xhigh, please check the suggestions carefully.

- Sum valid MTP token counts across CP before normalizing native and chunked auxiliary losses.
- Preserve main-update-token normalization, static chunked dispatch and the current tracker reporting path.
- Correct CP loss reporting and apply the companion MCore patch in both CUDA image builds.

- Reproduce the unpatched CP2 gradient mismatch with CPU/Gloo.
- Pass 31 targeted regression tests, including unequal masks, empty ranks, all-zero masks and teacher masks.
- Verify the native patch against the pinned MCore patch sequence with zero fuzz.
- Pass all-files pre-commit. GPU and end-to-end training were not run.
@Yangruipis
Yangruipis force-pushed the fix/mtp-cp-normalization branch from 79ebc34 to 1a87434 Compare October 26, 2026 13:06
@Yangruipis Yangruipis changed the title fix(mtp): normalize auxiliary loss across CP fix(mtp): 修复 CP 下 MTP 有效 token 归一化 Oct 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.

审查通过

已完成 1a87434 的 6 文件审查,未发现需要修改的问题。CP 计数、后端梯度缩放及空 rank 参与路径符合固定 MCore 约定。本地未运行数值测试或 GPU/多节点 MTP;GPU 单测仍在运行。

审查看板

Powered by Nyanpasu with gpt-6.1-sol xhigh, please check the suggestions carefully.

@Yangruipis

Copy link
Copy Markdown
Collaborator Author

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

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 26, 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 ⚠️ Failed 2026-10-26T14:05:37.192089Z
We couldn’t complete this review. Comment @codex review to try again.
1a87434 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: Something went wrong. Try again later by commenting “@codex review”.

An unknown error occurred
ℹ️ 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".

Keep the native normalization helper active while simulating peer counts
for the fake CP group. Assert both MTP depths reduce on that group, and
skip the CP case on older MCore builds without the normalization patch.

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

审查通过

已复核 3ffe56a:新增 CP 计数归并 mock 修正了门控测试夹具,保留原有 selective/掩码断言和独立双进程回归;生产代码未变,未发现需要修改的问题。新一轮 CI 仍在运行,本地未新增数值或 GPU 验证。

审查看板

Powered by Nyanpasu with gpt-6.1-sol xhigh, please check the suggestions carefully.

NINGBENZHE
NINGBENZHE previously approved these changes Oct 30, 2026

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

lgtm

Keep both MTP CP normalization and DP-reshardable checkpoint patches in
the CUDA 13 image, including main branch checksum checks and cleanup.

Validation: full pre-commit checks pass; replayed both affected Megatron
files from the pinned revision with zero fuzz and verified optimizer hashes.

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

审查通过

已复核 9a379ba 合并 main 后的补丁接入及 MTP 调用链,未发现需要修改的问题。归一化实现和测试未变,新基线未改变相关计数、CP 分组和缩放约定。当前 CI 尚未完成;本轮未做 GPU/多节点训练或完整镜像构建。

审查看板

Powered by Nyanpasu with gpt-6.1-sol 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.

审查通过

已复核 334db7f,未发现需要修改的问题。新基线未改变 MTP 的 mask 坐标、CP 分组、空 rank 图连接或最终 token 归一化;前次 cp2 测试修复及回归证据保持适用。当前 CI 尚未完成,本轮未做 GPU、多节点训练或完整镜像构建。

审查看板

Powered by Nyanpasu with gpt-6.1-terra xhigh, please check the suggestions carefully.

@NINGBENZHE
NINGBENZHE enabled auto-merge (squash) November 2, 2026 04:29
@NINGBENZHE
NINGBENZHE merged commit 3673d7e into redai-studio:main Nov 2, 2026
14 of 15 checks passed
SigureMo added a commit that referenced this pull request Nov 4, 2026
## What

The ROCm image (gfx950/gfx942), the en/zh ROCm guide plus the
docker/README.md section, and the cuda_ipc fix for a ROCm regression on
main since #495.

## How

- Image: how it matches Dockerfile.cu13 (SGLang patch, Rust tree core,
router, Megatron patches including #488's), plus the prebuilt wheels,
the requirements handling and the runtime environment variables.
- SGLang patch: the one remaining fix, linked to
sgl-project/sglang#44266, with a note that it can be dropped once Relax
upgrades past that.
 - Transport fix: how the cuda_ipc default is skipped on ROCm.

## Testing

- End-to-end colocated GRPO on 8× MI350X (`gfx950` image):

  | Task | Rollouts | Result | `mismatch_kl` |
  | --- | --- | --- | --- |
| Qwen3-4B DAPO-Math (`run-qwen3-4B-8xgpu.sh`) | 3 | Succeeded; weight
update 3.9 s, step ≈ 159 s | 6.2e-4 – 1.0e-3 |
| Qwen3-VL-4B Open-R1 (`run-qwen3-vl-4B-8xgpu.sh`) | 3 | Succeeded;
reward 0.36 → 0.52, weight update 4.3 s | 6.7e-4 – 7.2e-4 |
| Qwen3-Omni-30B-A3B AVQA (16-GPU recipe on one node, EP 4) | 450 |
Held-out AVQA accuracy 0.750 → 0.884; reward 0.81 → 0.95 (first/last 50
rollouts) | 3.0e-3 – 6.2e-3 |


- [x] `pre-commit run --all-files` passes
- [ ] Tests pass (`pytest tests/`)
- [x] New tests added (if applicable)
- [x] Documentation updated (if applicable)

## Type of Change

- [ ] Bug fix (non-breaking change that fixes an issue)
- [x] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [x] Documentation update
- [ ] Refactoring (no functional changes)
- [ ] Performance improvement
- [ ] CI/CD or build changes

## Screenshots / Logs

<!-- If applicable, add screenshots or log output to help explain the
changes. -->

---------

Co-authored-by: Nyakku Shigure <[email protected]>
Co-authored-by: Codex <[email protected]>
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.

3 participants