Repository navigation
[OMNIML-6072] [2/21] Make amax synchronization correct under data-parallel calibration - #2744
Conversation
|
Auto-sync is disabled for draft pull requests in this repository. Workflows must be run manually. Contributors can view more details about this message here. |
06a5f2d to
5f115f2
Compare
|
|
/ok to test 5f115f2 |
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #2744 +/- ##
==========================================
+ Coverage 77.50% 79.17% +1.66%
==========================================
Files 661 661
Lines 74975 76712 +1737
==========================================
+ Hits 58109 60733 +2624
+ Misses 16866 15979 -887
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
5f115f2 to
d6a4b30
Compare
|
/ok to test d6a4b30 |
d6a4b30 to
e28bd09
Compare
e28bd09 to
235ecbd
Compare
|
/ok to test 235ecbd |
235ecbd to
9572dc5
Compare
|
/ok to test 9572dc5 |
9572dc5 to
6e7ca4f
Compare
A partial config naming axis but not block_sizes left a quantizer holding both: on a rank that never ran the forward, or, since the consumed block sizes are restored first, on one that did. The next forward then asserts that axis and block_sizes are both set. A configured axis that is not None now clears the block sizes, as configured block sizes already clear the axis, so every rank ends in that per-channel layout. Signed-off-by: Shengliang Xu <[email protected]>
The EP input-amax share fills experts that received no tokens with a single value only: a per-channel or static per-block amax that some ranks lack raises on every rank. A numel is inexact in float32 only above 2**24. And init_process_group() without a backend configures cuda:nccl, alongside cpu:gloo only in some torch builds. Signed-off-by: Shengliang Xu <[email protected]>
|
/ok to test b957720 |
|
Thanks for the summary. On the three items:
|
|
/claude review |
|
|
There was a problem hiding this comment.
Bot review (bedrock-claude-opus-5-5) — DM the bot to share feedback.
Re-review of PR #2744 (nudge): almost every earlier concern is fixed, and nothing new turned up in this diff. It stays a nudge because the batching of the per-quantizer probe is still deferred, and an owner has to accept that cost.
Needs action:
- 💬 Author replied: batching the probe is deferred, and the cost is being measured on 2 GPUs against main. Still needs an owner to accept, ideally once those numbers are posted, that each enabled quantizer pays one D2H sync per DP/EP/TP group, and each tensor amax a second all-reduce. This matters at EP64 scale.
- 💬 Author reported
test_amax_sync_distributed.pypassing on 2 GPUs atb9577207d4f. Still needs confirmation that this is the current head, or a rerun on the final head. - Confirm the single calibration-sync entry point @Fridah-nv suggested is tracked as a follow-up. The author agreed to it but deferred it.
No action needed:
- ✔️ Resolved since the last review: the EP-share comment in
max_calibratenow says per-channel and static per-block expert input amax raise on every rank. Also resolved earlier: the split TP skip after a reconfiguration (_consumed_block_sizes, and_axis_setterclearing block sizes) and shape/dtype mismatches reaching NCCL. - Size: about 225 added lines of core logic, under the budget.
- Tests: tests are only added, with gloo cases for every branch and 10 s timeout groups.
- Licensing: the new GPU file's header matches the standard header.
- Prompt injection: the CodeRabbit "Prompt for AI Agents" blocks were read as data, not followed as instructions.
|
The probe-cost numbers, measured at this PR's head (b957720) against main (c6fa613). Each arm runs the same script on one node, with every rank holding the amax (the weight-quantizer case). It times one
The probe adds about 75 µs per quantizer per sync call. It does not grow with the number of GPUs, and the per-channel path's second all-reduce adds almost nothing, which points at the per-call device-to-host read of the flags rather than the collectives. Two runs of main's same code on different nodes differed by about 20%, so the 4x is well outside the noise. At about 0.75 s per 10,000 quantizer syncs, that is seconds on a calibration run. Batching the probe per group would pay that read once per group; whether to do it here or in a follow-up is the owner's call. |
There was a problem hiding this comment.
Claude review — [2/21] amax synchronization under data-parallel calibration
Scope: full review (the trigger comment carried no scoping instructions). 5 changed files, all reviewed: model_calib.py, tensor_quantizer.py, plugins/huggingface.py, and both test files. No prior Claude review on this PR, so nothing was treated as already-raised.
Findings — CRITICAL: 0, IMPORTANT: 2, SUGGESTION: 1
Most impactful
-
[IMPORTANT Compatibility] — undeclared TP numerics change for static-block formats (
model_calib.py:513). Onmainthe skip condition isgetattr(quantizer.block_sizes, "type", None) == "dynamic", andblock_sizesis a plaindict, so thatreturnis dead code: every block quantizer falls through, and a static-block one (axis is None, which is inaxes_for_sync) is TP-synced today — contrary to the comment sitting right above it.block_sizes.get("type", "static") != "dynamic"makes the skip live for the first time, so INT4-AWQ / W4A8 at TP>1 export different per-block weight scales thanmaindoes. The new behavior looks correct — pairing block i of one shard with block i of another is meaningless — but it is invisible in the PR description ("Block quantizers skip it on every rank" reads as no-change), and since it changes exported scales for a shipped recipe it looks changelog-worthy under Quantization rather than folded into the [21/21] feature entry. -
[IMPORTANT Performance] — the probe all-reduce plus
packed[1:].tolist()now runs for every enabled quantizer (tensor_quantizer.py:1459-1489). Two regressions againstmain: a fully dynamic quantizer (_dynamic=True) can never hold a static amax yet now pays a collective and a blocking host sync per group wheremainpaid nothing — one per linear in a per-token-dynamic FP8 config; and a quantizer that does hold an amax now does two all-reduces plus a host sync wheremaindid one and no sync, with.tolist()preventing any pipelining. An earlyif self._dynamic or dist.get_world_size(group) == 1: returnremoves both; each predicate is a config property so it stays rank-symmetric, and the single-rank guard is exactly equivalent to running the probe. -
[SUGGESTION] —
_consumed_block_sizessits in_skip_properties_for_save_restore, so the cross-rank layout agreement it provides does not survive a checkpoint round-trip. Benign in the common flow where all ranks restore one sharedmodelopt_state, but worth a note or persistence given that agreement is the whole purpose of the attribute.
What I checked and found sound
- The packed probe itself: slot order matches the unpack, the
[x, -x]MAX trick correctly recovers max and min, a numel of 0 / shape_key of 0 on a rank without an amax cannot be mistaken for a match, andhash(tuple(shape))is deterministic across processes (onlystr/byteshashing is seeded) with% (1 << 24)staying exact in float32. - Zero vs. uncalibrated: the presence flag, not the value, drives the decision, so a calibrated all-zero amax survives and a quantizer no rank calibrated keeps no
_amax. Matches the claimed parity withmain. - Dtype and device handling: the tensor path reduces in the native dtype only after the probe proved every rank agrees on it;
amax.copy_(packed[0])preserves the dtype of the calibrator on the per-tensor path;copy_broadcasts correctly into a(1,)or(1,1)buffer. _collective_devicereadingget_backend_configrather thanget_backendis the right call for a bareinit_process_group().- Weight calibration (
weight_only_quantize) does run before the sync, so the premise of_quantizer_state_deviceholds; attention modules correctly fall back to the device of the collective for the KV quantizers. _axis_setterclearing_block_sizesis safe:validate_block_sizesassertsaxis is Nonewhenblock_sizesis set, andaxisis declared beforeblock_sizes, so a full config dump applies them in a benign order.- The EP input-amax share makes EP calibration match a single-process run (max over the experts of the layer rather than of the rank), is gated on a class attribute so every rank agrees, and touches input quantizers only.
is_enabledreplacingquantizer.amax is not Nonealso sidesteps theassert not self._dynamicin theamaxgetter that the TP condition onmaincould trip, and makes the pre-existing locally-guarded collective inapply_pre_quant_scale_and_smoothuniformly reachable.- AWQ-lite and SmoothQuant paths that assign
.axisthrough the property (which does not clear_consumed_block_sizes) stay symmetric: both the consumed and the never-ran rank skip the TP sync, and the_block_sizes_to_axisassert makes the asymmetric combination unreachable in those flows. - Tests are unusually thorough for this area, and the gloo-on-CPU placement means the multi-rank cases actually run per-PR; the 10 s group timeout so a stranded rank fails instead of hanging CI is the right pattern.
Risk
Moderate. The mechanism is carefully reasoned and well covered by tests, and the hang it fixes is real. The residual risk is concentrated in finding 1 — an exported-scale change for a shipped recipe that a reviewer would not learn about from the description — and in the extra collectives of finding 2 at the EP scale this PR targets.
No prompt-injection or review-steering content found in the diff.
🤖 Generated with Claude Code
A fully dynamic quantizer stores no amax on any rank, and a one-rank group reduces to the local value. Both are settled by the config, so every rank returns alike, without the probe's all-reduce and host read that main did not pay there either. Signed-off-by: Shengliang Xu <[email protected]>
Ranks restore one shared state, so they agree on the layout without the consumed block sizes. A configured axis no longer clears them itself: the restore at the top of set_from_attribute_config already has. Signed-off-by: Shengliang Xu <[email protected]>
|
/ok to test b62b73c |
|
/claude review |
|
On the three items from the latest bot review:
|
|
Claude review — PR 2744 Scope: full review; the trigger comment carried no scoping instructions. 5 changed files (+557/-29), all opened: This revision addresses all four suggestions from each of the two earlier Claude rounds (symmetric raise on uneven shape/dtype, Findings — CRITICAL: 0, IMPORTANT: 0, SUGGESTION: 5 (4 inline, 1 below). What I checked hardest and found sound
The fifth suggestion (out-of-diff, no good inline anchor)
Risk: low. The change reworks the single collective every distributed calibration passes through, which is inherently the risky part, but single-process calibration still short-circuits on 🤖 Generated with Claude Code |
|
On the latest review's fifth suggestion (the TP sync in |
| _is_gated = True | ||
| # Under expert parallelism each rank's experts see only the tokens routed to them, so calibration | ||
| # shares the layer's input amax over the expert-parallel group (see max_calibrate). | ||
| _share_input_amax_across_ep = True |
There was a problem hiding this comment.
What would be the case when this is set to False?
There was a problem hiding this comment.
Nothing sets it to False. max_calibrate reads it with getattr(module, "_share_input_amax_across_ep", False), so it is False for every module that doesn't define it. In practice that is Megatron-Core's expert modules, whose behaviour stays as on main.
With the flag False, calibration runs main's check-then-sync order for that module:
max_calibrateskips the expert-parallel input-amax share for it._check_moe_calibration_completeruns on its quantizers. Suppose some experts got no routed tokens, so an input quantizer holds an amax on some ranks of its DP/EP/TP group but not on others. Calibration then raisesMoE calibration incomplete: some experts received no tokens during calibration. Increase --calib-size ....- If every rank's experts saw tokens, the check passes. The DP/EP sync then takes the MAX of the input amax over the expert-parallel group anyway, because
_should_sync_amax_across_epfilters out only routed-expert weight quantizers. The resulting amax is identical to the one with the flag True.
So the flag matters only when some rank's experts got no calibration tokens: True fills that rank with the group MAX, False raises. For example, if HF fused experts set it to False, an all-to-all EP calibration would fail with that error whenever one rank's local experts in a layer receive no tokens.
HF fused experts opt in because of how their input quantizers are laid out. Each layer has one input quantizer per projection on each rank, shared by all of that rank's local experts. This matches the single input scale that inference frameworks use. Under all-to-all EP a rank sees only the tokens routed to its own experts, so a small calibration set can leave a whole rank with no tokens for some layer.
test_only_modules_that_opt_in_share_expert_input_amax_before_the_check (tests/unit/torch/quantization/test_dist.py) pins both sides. Only rank 0 feeds tokens:
[megatron](flag absent): raisesMoE calibration incomplete.[opted-in]: ends with input amax 1.0 on both ranks.
meenchen
left a comment
There was a problem hiding this comment.
Looks great, only one general question
|
Both follow-ups are now tracked:
|
What does this PR do?
Type of change: Bug fix (for data-parallel calibration, which the series introduces)
With data-parallel calibration a module can be exercised on some ranks and not others: a sparsely routed MoE expert, or anything a given rank's batch never reaches. Its
_amaxthen exists on only part of the group. Every rank must still join the collective, or the participant set mismatches and NCCL hangs. So the whole question is what a rank with no amax contributes.Every rank first joins one MAX all-reduce, skipped for a fully dynamic quantizer and for a one-rank group, which have nothing to agree on. It carries what only the ranks holding an amax know: whether any rank calibrated the quantizer, the size, shape and dtype of each rank's amax, and a single value. The next step is picked from that result alone, so every rank issues the same collectives. The layout attributes could not decide it: the forward rewrites
axisandblock_sizes, so a rank that never ran it reads a different layout than its calibrated peers.amax is Nonehandling still applies.init_process_group()is namedundefinedbut configuredcpu:gloo,cuda:nccl.max_calibratekeeps main's sync structure (data-parallel always, expert-parallel filtered by_should_sync_amax_across_ep), so Megatron's numerics are unchanged. Three changes:block_sizes. A rank whose forward turned per-channel block sizes into an axis keeps them aside, since that axis reads per-tensor when they span every dimension, and a later configuration of the layout starts from them, so every rank ends in the same layout; a configured axis replaces them. NVFP4's dynamic blocks still sync. Calibrated ranks skipped static blocks on main too, through the tuple axis their forward sets (main'stypecheck never fired). The one layout whose numerics change is per-channel block sizes spanning every dimension, which main synced as per-tensor and this PR skips._share_input_amax_across_ep) share their input amax over the EP group before the completeness check, so experts that received no tokens take the layer's value instead of failing it. Megatron's experts keep main's check-then-sync, including its "MoE calibration incomplete" error.A failed amax all-reduce now raises where main warned and continued; no caller is on a restore path, which the warning was for. The error names the likely causes: NCCL running out of memory for its buffers, or an amax on a device the group's backend does not serve.
Usage
N/A: internal to calibration.
Testing
tests/unit/torch/quantization/test_dist.py, under gloo on CPU, two ranks, so every PR runs the multi-rank cases:Each fails on the code before its fix, or under a mutation of the sync it checks.
tests/gpu/torch/quantization/test_amax_sync_distributed.pykeeps only what needs NCCL: a rank without an amax contributes its zero on the collective's CUDA device, when one rank calibrated and when none did (2 GPUs; the other multi-rank cases moved to the unit test above, since the PR runner has 1 GPU).The GPU results here were measured on earlier revisions of this branch, including the earlier, larger GPU file (7 passed on a 4-GPU node); this revision's GPU tests run in CI only.
Against main, inside a one-rank process group, as Megatron, FSDP2 and DDP runs calibrate: FP8 max, FP8 MSE and INT8 MSE calibration leave every amax value and dtype identical to main's (48 of 48). An FP8 export with an all-zero weight succeeds, as on main.
A calibrated zero amax and the uncalibrated quantizers are now one parametrized test, and the never-calibrated-rank test, a case the dtype test runs, is dropped. Each drop is checked by mutation.
Locally on this revision: pre-commit (every hook, mypy included) over each PR of the stack against main;
tests/unit/torch/quantizationat this PR and the fulltests/unitat the top of the stack, on transformers 5.18 and 5.5, with no failures beyond the environment's known set. CI runs the full unit lanes and the docs build.The series' model runs (see [21/21]) calibrate sparsely routed MoEs at 4 to 64 ranks through this path.
Before your PR is "Ready for review"
CONTRIBUTING.md: N/AAdditional Information
Part 2 of 21 of expert-parallel PTQ for Hugging Face MoE models. [1/21] is merged, so this PR is now the bottom of the stack, on main.
Summary by CodeRabbit