perf(megatron): skip zero-advantage backward - #253
Open
xiaoh1024 wants to merge 1 commit into
Open
Conversation
There was a problem hiding this comment.
Pull request overview
This PR introduces an opt-in Megatron training optimization to skip building/traversing the backward graph for microbatches whose effective advantages are all zero, while preserving forward/loss/metrics semantics and adding fail-fast validation for supported configurations.
Changes:
- Add
--skip-zero-advantage-backward(default off) plus strict configuration validation in Megatron args. - Detect zero-effective-advantage microbatches in the Megatron forward step and avoid autograd graph construction; enforce a runtime “complete loss is finite and zero” guard when skipping.
- Track skipped-backward token stats and adjust FLOPs/MFU reporting accordingly; add unit tests for skip logic, validation, and perf metrics.
Reviewed changes
Copilot reviewed 8 out of 8 changed files in this pull request and generated 3 comments.
Show a summary per file
| File | Description |
|---|---|
relax/backends/megatron/model.py |
Detect all-zero effective advantages and run model forward under no_grad for those microbatches; record skipped seq lens. |
relax/backends/megatron/loss.py |
Add skip marker key, log skip metric weight, and replace skipped loss with a detached differentiable scalar after validating it’s finite zero. |
relax/backends/megatron/arguments.py |
Add fail-fast validation restricting the feature to a known-safe Megatron configuration subset. |
relax/backends/megatron/actor.py |
Gather and aggregate per-rank skipped seq lens for downstream perf logging. |
relax/utils/training/train_metric_utils.py |
Subtract skipped-backward FLOPs from actor-train TFLOPs/MFU and log skipped token counts/fraction. |
relax/utils/arguments.py |
Add CLI flag --skip-zero-advantage-backward (default disabled). |
tests/backends/megatron/test_zero_advantage_backward.py |
New tests covering zero-advantage detection, validation constraints, and loss/grad behavior for skipped vs non-skipped paths. |
tests/utils/test_train_metric_utils.py |
Add test ensuring FLOPs/MFU excludes skipped-backward work and logs skipped token metrics. |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
Comment on lines
+1399
to
+1404
| skip_zero_advantage_backward = bool(batch.get(_SKIP_ZERO_ADVANTAGE_BACKWARD_KEY, False)) | ||
| if getattr(args, "skip_zero_advantage_backward", False): | ||
| metric_weight = num_tokens if args.calculate_per_token_loss else loss.new_tensor(num_samples) | ||
| log["zero_advantage_backward_fraction"] = metric_weight * float(skip_zero_advantage_backward) | ||
| if skip_zero_advantage_backward: | ||
| detached_loss = loss.detach() |
Comment on lines
+67
to
+70
| if advantage.shape != loss_mask.shape: | ||
| return False | ||
| effective_advantages.append(advantage.masked_select(loss_mask.bool())) | ||
| return torch.count_nonzero(torch.cat(effective_advantages)).item() == 0 |
Comment on lines
1
to
4
| import math | ||
| from argparse import Namespace | ||
| from collections.abc import Callable, Iterator | ||
| from functools import partial |
Contributor
|
✅ 验收通过,但是不合入。 还有几个问题,希望修下:
|
xiaoh1024
force-pushed
the
perf/task23-zero-advantage-backward
branch
from
August 21, 2026 04:11
b27c70d to
4889767
Compare
Contributor
Author
感谢 review,几个问题已经修复:
|
xiaoh1024
force-pushed
the
perf/task23-zero-advantage-backward
branch
from
August 30, 2026 14:35
e40f17a to
9572fc7
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Changes
relax/backends/megatron/model.pyno_grad执行该 microbatch 的模型 forward。relax/backends/megatron/loss.pyrelax/backends/megatron/arguments.py、relax/utils/arguments.py--skip-zero-advantage-backward。relax/backends/megatron/actor.py、relax/utils/training/train_metric_utils.pytests/backends/megatron/test_zero_advantage_backward.py、tests/utils/test_train_metric_utils.pyVerification
环境、硬件、commit:
5b2301110db97f38234402dc90e70ae6fb063cde39ddc2d2b661df9e083556161ba7208e406e0514ghcr.io/redai-infra/relaxrl:dev-20260715-8325919e@sha256:3fa8ce578acda6c829b83016bde42c38fa892681e4f36ca330f545616fe578e2Qwen/Qwen3-4B@1cfa9a7208912126459214e8b04321603b3df60czhuzilin/dapo-math-17k@2e65612930298bde4c5d58fd97b3f23a483aaff9zhuzilin/aime-2024@1c625e328db94ec7ef7ff169016b097c468d60b9可复制命令:
单元测试:
端到端结果:每次运行统计 rollout 1–19;rollout 0 含启动开销,rollout 20 含评测,均不计入主指标。
两次独立运行的吞吐均值标准差为 baseline 11.84 tokens/s、candidate 7.78 tokens/s(CV 0.12% / 0.07%)。GPU 利用率下降是减少 backward 计算后的预期结果:rollout 与角色切换等未改变阶段在更短的 step 中占比上升。模型、样本和有效 token 口径不变;仅省略经校验不会产生参数梯度的 backward。峰值显存按两次运行各自峰值的均值报告,基本不变。
正确性/质量护栏:
rollout/raw_rewardrollout/response_lengthstrain/losstrain/grad_normAIME 仅作为未退化护栏;不把两次随机评测的均值差异解释为本优化带来的质量收益。四次运行均完成 21/21 rollouts、240-sample AIME eval 和 iteration-20 checkpoint。
Risk & Rollback
--skip-zero-advantage-backward即恢复原有路径。Checklist