Skip to content

[OMNIML-6072] [2/21] Make amax synchronization correct under data-parallel calibration - #2744

Merged
shengliangxu merged 28 commits into
mainfrom
shengliangx/hfep-7-amax-sync
Oct 26, 2026
Merged

shengliangxu merged 28 commits into
mainfrom
shengliangx/hfep-7-amax-sync

Conversation

@shengliangxu

@shengliangxu shengliangxu commented Oct 12, 2026 •

Copy link
Copy Markdown
Collaborator

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 _amax then 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 axis and block_sizes, so a rank that never ran it reads a different layout than its calibrated peers.

  • One value: a per-tensor amax, or a dynamic-block quantizer's global scale (NVFP4 activations). A rank without one contributes zero, the identity for MAX over non-negative amax, and adopts the group's value.
    • If nobody calibrated the quantizer, it stays without an amax, so the usual amax is None handling still applies.
    • A calibrated amax of zero, from an all-zero weight, survives as on main.
  • A tensor: a static per-channel or per-block amax. A rank without one cannot know its shape, and NCCL hangs on mismatched ones, so the real reduce runs only when every rank holds one of the same shape and the same listed dtype. Otherwise every rank raises at once; raising only where the amax is missing would leave the other ranks blocked in a collective that never completes.
  • Dtype and device.
    • Every rank contributes float32: NCCL hangs rather than raising on a dtype mismatch. This was seen on Kimi-K3, NVFP4 EP64, with 8 ranks holding an amax and 56 not.
    • The collectives run on the device of the group's backend, read from the group's backend configuration: a group from a bare init_process_group() is named undefined but configured cpu:gloo,cuda:nccl.
    • Each rank then keeps its calibrator's dtype, so later bf16 writes (MSE calibration) round exactly as on main. A rank that never calibrated the quantizer adopts the group's dtype. A single value travels in float32, so a float64 one comes back rounded to float32 precision.
    • That rank puts the amax where it keeps its quantizer state: on a tensor the quantizer holds, else on the device of its module's weight-quantizer amax, which every rank calibrates from the weight before any sync, else on the collective's device. The module's parameters would mislead under CPU offload, where they rest off that device. In every one-GPU-per-rank layout this is the rank's GPU, as before.

max_calibrate keeps main's sync structure (data-parallel always, expert-parallel filtered by _should_sync_amax_across_ep), so Megatron's numerics are unchanged. Three changes:

  • A rank joins the data-parallel sync even without an amax.
  • The tensor-parallel sync, of linears and of the KV-cache quantizers, likewise runs on every rank whether or not it calibrated the quantizer. It is gated on the quantizer being enabled, which the config makes the same on every rank, instead of on a local amax; on main a calibrated rank waited for a peer that skipped it. Block quantizers skip it on every rank. A rank that never ran the forward judges by their 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's type check 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.
  • HF fused experts (_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:

    • a rank that never calibrated still joins the sync;
    • a calibrated zero amax survives;
    • a rank that never calibrated puts a copy of the amax on a tensor the quantizer holds, else on the device calibration passes for the module, else on the collective's device; that device is the weight-quantizer amax's, for a linear and for fused experts, not the parameters';
    • every rank ends in the calibrator's dtype, and calibrated ranks take the group max, for an INT8 and an NVFP4 dynamic-block quantizer (the latter synced as per-tensor);
    • a quantizer no rank calibrated stays uncalibrated, per-tensor and per-channel;
    • uneven per-channel calibration fails on every rank: a rank without the amax, or ranks holding ones of different sizes, shapes or dtypes, or of dtypes outside the listed ones. Also when only the calibrated rank's layout reads per-channel (per-token block sizes, which the forward turns into a per-channel axis). This runs on a group with a 10 s timeout, so a rank left waiting fails rather than hangs. The jobs destroy the groups they create, so the session's pooled workers do not keep them;
    • a rank without an amax still joins the tensor-parallel sync, for a column-parallel linear and for the KV-cache quantizers, and skips it for block quantizers (static blocks, per-token block sizes, block sizes spanning every dimension) as its calibrated peers do. It joins again once such a quantizer is configured, or assigned, per-tensor, or configured with an axis the sync takes, and keeps skipping it after a config that leaves the block sizes in place;
    • a group initialized without a backend collects on CUDA (the CUDA side stubbed: CI's torch is a CPU build, which configures no NCCL);
    • only modules that opt in share expert input amax before the completeness check, while Megatron's raise as on main.

    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.py keeps 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/quantization at this PR and the full tests/unit at 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"

  • Is this change backward compatible?: ✅ Single-process calibration and Megatron's synchronization are unchanged.
  • If you copied code from any other sources or added a new PIP dependency, did you follow guidance in CONTRIBUTING.md: N/A
  • Did you write any new necessary tests?: ✅
  • Did you update Changelog?: N/A. Covered by the feature's entry in [21/21].
  • Did you get Claude approval on this PR?: ❌ Not yet.

Additional 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

  • Bug Fixes
    • Improved distributed quantization calibration so ranks can synchronize values even when some ranks have no local calibration data.
    • Calibration remains unset when no ranks have data, preserves calibrated zero values and data types, and flags inconsistent per-channel calibration across ranks.
    • Expert-parallel calibration shares input values before MoE completeness checks where configured.
    • Tensor-parallel and KV-cache synchronization now handles partially calibrated ranks correctly.
    • Distributed synchronization failures now raise a contextual error instead of being reduced to a warning.

@copy-pr-bot

copy-pr-bot Bot commented Oct 12, 2026

Copy link
Copy Markdown

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.

@coderabbitai

coderabbitai Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
Walkthrough

Distributed amax synchronization now includes ranks with missing local calibration values. Opted-in expert modules synchronize enabled input quantizers across expert-parallel groups before MoE completeness validation. Tests cover dtype, zero, missing, uneven, tensor-parallel, KV-cache, and expert-input cases.

Changes: Distributed Amax Calibration

Layer / File(s) Summary
Coordinate amax across ranks
modelopt/torch/quantization/nn/modules/tensor_quantizer.py, tests/gpu/torch/quantization/test_amax_sync_distributed.py, tests/unit/torch/quantization/test_dist.py
TensorQuantizer.sync_amax_across_distributed_group coordinates calibration presence, amax values, and dtype metadata across ranks. Static non-per-tensor quantizers raise on uneven calibration. Per-tensor and dynamic-block quantizers propagate calibrated values to uncalibrated ranks.
Synchronize opted-in expert inputs
modelopt/torch/quantization/model_calib.py, modelopt/torch/quantization/plugins/huggingface.py, tests/unit/torch/quantization/test_dist.py
max_calibrate synchronizes enabled input quantizers for opted-in QuantModules before MoE completeness validation. _QuantFusedExperts opts in. Tensor-parallel and KV-cache synchronization also includes enabled quantizers without local amax values.

Priority: Normal

Estimated code review effort: 4 (Complex) | ~45 minutes

Change: Bug fix

Sequence Diagram(s)

sequenceDiagram
  participant max_calibrate
  participant QuantModule
  participant TensorQuantizer
  participant EPGroup
  max_calibrate->>QuantModule: Check _share_input_amax_across_ep
  QuantModule-->>max_calibrate: Return sharing flag
  max_calibrate->>TensorQuantizer: Synchronize enabled input quantizers
  TensorQuantizer->>EPGroup: Reduce calibration state and amax
  EPGroup-->>TensorQuantizer: Return reduced state and amax
  max_calibrate->>max_calibrate: Check MoE calibration completeness
Loading

Suggested reviewers: kevalmorabia97

Merge Risk: Moderate · up to 13838

Distributed calibration now keeps ranks without local statistics in the synchronization step. However, for per-channel quantizers configured through block sizes, tensor-parallel ranks can disagree about whether to join the synchronization, which can hang the run. Make tensor-parallel participation depend on configuration rather than on state that changes during forward before merging. The earlier test-import concern is fixed.

Pre-merge checks: Passed 5 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 51.85% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 27 functions across 5 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 5 passed
Check name Status Explanation
Title check Passed The title clearly and concisely describes the main change: correcting amax synchronization for data-parallel calibration.
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Security Anti-Patterns Passed PASS. The reviewed range changes three ModelOpt Python modules and no examples or dependency files. Added code only implements distributed amax synchronization and an expert-sharing flag. The added di…
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Full details: Security Anti-Patterns

Explanation

PASS. The reviewed range changes three ModelOpt Python modules and no examples or dependency files. Added code only implements distributed amax synchronization and an expert-sharing flag. The added diff contains no torch.load(..., weights_only=False), numpy.load(..., allow_pickle=True), hardcoded trust_remote_code=True, external-input eval()/exec(), or # nosec. SECURITY.md states these rules apply to non-test code, and the dependency-file diff is empty.

✨ Finishing Touches: 💡 1
📝 Generate docstrings: 💡
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Comment @coderabbitai help to get the list of available commands.

@shengliangxu
shengliangxu added this pull request to stack #2755 October 12, 2026 00:57
@shengliangxu
shengliangxu force-pushed the shengliangx/hfep-7-amax-sync branch from 06a5f2d to 5f115f2 Compare October 12, 2026 02:35
@github-actions

github-actions Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor
PR Preview Action v1.8.1
Preview removed because the pull request was closed.
2026-10-26 23:59 UTC

@shengliangxu

Copy link
Copy Markdown
Collaborator Author

/ok to test 5f115f2

@codecov

codecov Bot commented Oct 12, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 92.98246% with 8 lines in your changes missing coverage. Please review.
✅ Project coverage is 79.17%. Comparing base (c6fa613) to head (b62b73c).
⚠️ Report is 13 commits behind head on main.

Files with missing lines Patch % Lines
modelopt/torch/quantization/model_calib.py 89.83% 6 Missing ⚠️
.../torch/quantization/nn/modules/tensor_quantizer.py 96.29% 2 Missing ⚠️
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     
Flag Coverage Δ
examples-diffusers 19.93% <33.69%> (+0.03%) ⬆️
examples-gpt-oss 13.45% <6.52%> (-0.01%) ⬇️
examples-hf_ptq 23.37% <34.78%> (-0.01%) ⬇️
examples-llm_distill 13.52% <6.52%> (-0.01%) ⬇️
examples-llm_eval 17.21% <33.69%> (+0.03%) ⬆️
examples-llm_qat 17.38% <33.69%> (+0.01%) ⬆️
examples-llm_sparsity 16.75% <6.52%> (+<0.01%) ⬆️
examples-megatron_bridge 26.51% <45.65%> (-0.19%) ⬇️
examples-specdec_bench 13.23% <6.52%> (-0.01%) ⬇️
examples-speculative_decoding 17.46% <33.69%> (-0.03%) ⬇️
examples-torch_onnx 21.25% <32.60%> (+<0.01%) ⬆️
examples-torch_trt 15.19% <33.69%> (+0.03%) ⬆️
examples-vllm_serve 17.42% <33.69%> (+0.03%) ⬆️
gpu 59.03% <47.82%> (+8.00%) ⬆️
regression 15.04% <6.52%> (-0.01%) ⬇️
unit 61.33% <94.73%> (+0.15%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@shengliangxu
shengliangxu force-pushed the shengliangx/hfep-7-amax-sync branch from 5f115f2 to d6a4b30 Compare October 12, 2026 08:39
@shengliangxu

Copy link
Copy Markdown
Collaborator Author

/ok to test d6a4b30

@shengliangxu shengliangxu changed the title [9/19] Make amax synchronization correct under data-parallel calibration [OMNIML-6072] [9/19] Make amax synchronization correct under data-parallel calibration Oct 12, 2026
@shengliangxu
shengliangxu force-pushed the shengliangx/hfep-7-amax-sync branch from d6a4b30 to e28bd09 Compare October 13, 2026 00:53
@shengliangxu
shengliangxu force-pushed the shengliangx/hfep-7-amax-sync branch from e28bd09 to 235ecbd Compare October 13, 2026 01:32
@shengliangxu

Copy link
Copy Markdown
Collaborator Author

/ok to test 235ecbd

@shengliangxu
shengliangxu removed this pull request from stack #2755 October 13, 2026 17:42
@shengliangxu
shengliangxu added this pull request to stack #2775 October 13, 2026 17:43
@shengliangxu shengliangxu changed the title [OMNIML-6072] [9/19] Make amax synchronization correct under data-parallel calibration [OMNIML-6072] [9/20] Make amax synchronization correct under data-parallel calibration Oct 13, 2026
@shengliangxu
shengliangxu force-pushed the shengliangx/hfep-7-amax-sync branch from 235ecbd to 9572dc5 Compare October 13, 2026 19:38
@shengliangxu
shengliangxu removed this pull request from stack #2775 October 13, 2026 19:38
@shengliangxu
shengliangxu added this pull request to stack #2781 October 13, 2026 19:40
@shengliangxu shengliangxu changed the title [OMNIML-6072] [9/20] Make amax synchronization correct under data-parallel calibration [OMNIML-6072] [10/21] Make amax synchronization correct under data-parallel calibration Oct 13, 2026
@shengliangxu

Copy link
Copy Markdown
Collaborator Author

/ok to test 9572dc5

@shengliangxu
shengliangxu removed this pull request from stack #2781 October 14, 2026 00:13
@shengliangxu
shengliangxu force-pushed the shengliangx/hfep-7-amax-sync branch from 9572dc5 to 6e7ca4f Compare October 14, 2026 00:14
@shengliangxu
shengliangxu added this pull request to stack #2786 October 14, 2026 00:14
@shengliangxu shengliangxu changed the title [OMNIML-6072] [10/21] Make amax synchronization correct under data-parallel calibration [OMNIML-6072] [11/22] Make amax synchronization correct under data-parallel calibration Oct 14, 2026
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]>
@shengliangxu

Copy link
Copy Markdown
Collaborator Author

/ok to test b957720

@shengliangxu

Copy link
Copy Markdown
Collaborator Author

Thanks for the summary. On the three items:

  • Per-quantizer probe cost. I'm measuring it now, at this PR's head against main, on 2 GPUs with all ranks holding the amax (the weight-quantizer case you describe). I'll post the numbers here. Whether to batch the probe per group in this PR or in a follow-up is the owner's call, and I'd like it to rest on that measurement.
  • Per-channel expert input amax. The EP share's comment now states the limit (b957720): it fills a single value, and a per-channel or static per-block expert input amax that some ranks lack raises on every rank. No shipped recipe calibrates an expert input per-channel.
  • test_amax_sync_distributed.py on 2 GPUs at this head. Running at b957720; I'll post the result here.

@shengliangxu

Copy link
Copy Markdown
Collaborator Author

/claude review

@shengliangxu

Copy link
Copy Markdown
Collaborator Author

tests/gpu/torch/quantization/test_amax_sync_distributed.py on 2 GPUs (NCCL) at b957720: 2 passed (test_per_tensor_amax_survives_uneven_calibration[rank_0_only] and [nobody]). The probe-cost numbers will follow in a separate comment.

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

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.py passing on 2 GPUs at b9577207d4f. 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_calibrate now 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_setter clearing 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.

@shengliangxu

Copy link
Copy Markdown
Collaborator Author

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 sync_amax_across_distributed_group call per quantizer over 10,000 per-tensor and 1,000 per-channel (4096, 1) quantizers, on NCCL.

GPUs per-tensor amax per-channel amax
main 2 22.9 µs 22.8 µs
this PR 2 98.4 µs 103.3 µs
main 4 24.8 µs 22.2 µs
this PR 4 96.4 µs 109.2 µs

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.

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

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

  1. [IMPORTANT Compatibility] — undeclared TP numerics change for static-block formats (model_calib.py:513). On main the skip condition is getattr(quantizer.block_sizes, "type", None) == "dynamic", and block_sizes is a plain dict, so that return is dead code: every block quantizer falls through, and a static-block one (axis is None, which is in axes_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 than main does. 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.

  2. [IMPORTANT Performance] — the probe all-reduce plus packed[1:].tolist() now runs for every enabled quantizer (tensor_quantizer.py:1459-1489). Two regressions against main: a fully dynamic quantizer (_dynamic=True) can never hold a static amax yet now pays a collective and a blocking host sync per group where main paid 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 where main did one and no sync, with .tolist() preventing any pipelining. An early if self._dynamic or dist.get_world_size(group) == 1: return removes both; each predicate is a config property so it stays rank-symmetric, and the single-rank guard is exactly equivalent to running the probe.

  3. [SUGGESTION] — _consumed_block_sizes sits 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 shared modelopt_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, and hash(tuple(shape)) is deterministic across processes (only str/bytes hashing 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 with main.
  • 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_device reading get_backend_config rather than get_backend is the right call for a bare init_process_group().
  • Weight calibration (weight_only_quantize) does run before the sync, so the premise of _quantizer_state_device holds; attention modules correctly fall back to the device of the collective for the KV quantizers.
  • _axis_setter clearing _block_sizes is safe: validate_block_sizes asserts axis is None when block_sizes is set, and axis is declared before block_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_enabled replacing quantizer.amax is not None also sidesteps the assert not self._dynamic in the amax getter that the TP condition on main could trip, and makes the pre-existing locally-guarded collective in apply_pre_quant_scale_and_smooth uniformly reachable.
  • AWQ-lite and SmoothQuant paths that assign .axis through 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_axis assert 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]>
@shengliangxu

Copy link
Copy Markdown
Collaborator Author

/ok to test b62b73c

@shengliangxu

Copy link
Copy Markdown
Collaborator Author

/claude review

@shengliangxu

Copy link
Copy Markdown
Collaborator Author

On the three items from the latest bot review:

  • Probe batching: as the owner, I accept deferring it. The measured cost is in the comment above: about 75 µs per quantizer per sync call, flat in GPU count. Batching the probe per group goes to a follow-up, which I'll link here.
  • 2 GPUs at the current head: tests/gpu/torch/quantization/test_amax_sync_distributed.py passes 2 of 2 on 2 GPUs (NCCL) at b62b73c, this PR's head. On 1 GPU both tests skip, as need_2_gpus intends.
  • Fridah-nv's single calibration-sync entry point: tracked as a follow-up too; I'll link it here.

@claude

claude Bot commented Oct 26, 2026

Copy link
Copy Markdown
Contributor

Claude review — PR 2744

Scope: full review; the trigger comment carried no scoping instructions. 5 changed files (+557/-29), all opened: model_calib.py, nn/modules/tensor_quantizer.py, plugins/huggingface.py, tests/unit/torch/quantization/test_dist.py, tests/gpu/torch/quantization/test_amax_sync_distributed.py. For composition context I also read enable_stats_collection / finish_stats_collection, _check_moe_calibration_complete / _should_sync_amax_across_ep / _has_expert_parallelism, the axis / block_sizes / amax properties, _block_sizes_to_axis / _setup_for_blockquant, get_modelopt_state / set_from_modelopt_state and _skip_properties_for_save_restore, reduce_amax / MaxCalibrator.collect, DistributedProcessGroup, QuantizerAttributeConfig's axis/block_sizes fields and their mutual-exclusion validator, and the one out-of-diff caller of sync_amax_across_distributed_group in apply_pre_quant_scale_and_smooth. No paths skipped.

This revision addresses all four suggestions from each of the two earlier Claude rounds (symmetric raise on uneven shape/dtype, _quantizer_state_device for the cold rank's placement, AnyQuantizer in the EP-share loop, .clone() on the adopted amax, and get_backend_config instead of the backend name).

Findings — CRITICAL: 0, IMPORTANT: 0, SUGGESTION: 5 (4 inline, 1 below).

What I checked hardest and found sound

  • Rank-invariance of the new is_enabled gate. This is the load-bearing claim, so I traced where _disabled can change during calibration. enable_stats_collection disables only on _calibrator is None, and both it and finish_stats_collection branch on _use_constant_amax / _constant_amax / _dynamic — all config-derived. Nothing disables a quantizer because its calibrator collected nothing, so is_enabled at sync time is identical on every rank. The old _amax is None gate was the genuine hazard.
  • The 7-element packing. [value, numel, -numel, shape_key, -shape_key, dtype_code, -dtype_code] under MAX recovers max and min of each field, so -neg_min_numel == max_numel and -neg_min_shape == max_shape really does mean "every rank holds one of the same shape", a cold rank's zeros can never pass it, and max_code == 0 catches an unlisted dtype held by all ranks. hash(tuple(amax.shape)) is deterministic across processes (int hashing is not seeded, unlike str), and % (1 << 24) keeps it exact in float32. Every branch after the reduce is decided from the reduced result alone, so collective sequences stay identical.
  • No shape divergence on the cold rank. I checked this specifically because a DDP buffer broadcast would break on it: reduce_amax returns torch.max(input) for axis=None and squeezes to 0-dim whenever numel == 1, so a calibrated per-tensor amax is 0-dim everywhere — matching the 0-dim packed[0].to(...).clone() the cold rank registers.
  • _collective_device on the group configuration. Reading get_backend_config rather than the group name is right, and deriving from the group rather than a local tensor is necessary (the cold rank has nothing to ask). It is also an improvement over main under multi-GPU-per-process offload, where main would all-reduce tensors sitting on different devices in the same group.
  • TP-sync equivalence for the calibrated rank. main's getattr(dict, "type", None) never fired, so block quantizers fell through to the axis check and were filtered by the tuple axis their forward sets; the rewrite returns at the top instead. I walked static blocks, INT4/W4A8, NVFP4 dynamic blocks (still synced, axis is None), and per-token blocks, and they land the same way. The one documented divergence (per-channel blocks spanning every dimension) is the layout the PR says it changes.
  • EP share placement and gating. It sits after the distributed_sync early return, before _check_moe_calibration_complete, matches "input_quantizer" in child_name (so *_proj_input_quantizer is covered) via AnyQuantizer + _iter_leaf_quantizers, and is opt-in only, so Megatron keeps main's check-then-sync and its error.
  • warn to raise. sync_amax_across_distributed_group has no caller outside model_calib.py, so the restore path the old warning hedged for does not exist.
  • Tests. They exercise the decisions rather than restating them, the multi-rank cases run on gloo via the session-scoped cpu_dist_workers so every PR hits them, short-timeout groups make a left-behind rank fail instead of hanging CI, and those groups are destroyed in finally. Nothing here needs a GPU except what stayed in the GPU file.

The fifth suggestion (out-of-diff, no good inline anchor)

apply_pre_quant_scale_and_smooth (model_calib.py:1385-1397) is the one sync_amax_across_distributed_group call site that was not converted to the new contract: its TP sync still sits inside if linear.input_quantizer.amax is not None:, so a rank without an amax skips a collective its peers join — precisely the shape of bug this PR removes everywhere else. It is safe today, because TP ranks see identical activations and max_calibrate has already made amax presence uniform across the DP group by the time SmoothQuant/AWQ run, and it also does not pass state_device. Still, the method's new docstring now documents an "every rank joins" contract that this caller alone does not honour, which will read as an oversight to the next person. Worth either converting it or noting why the local gate is safe there. (Related and still open from the first round: _amax_for_smoothing itself is never DP-synced.)

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 is_initialized(), world size 1 returns before any collective, Megatron's sync structure and numerics are held fixed, and the new failure modes raise on every rank together rather than hanging one. All five suggestions are polish or latent-consistency items; none blocks merge.

🤖 Generated with Claude Code

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

Claude review passed — no blocking issues found. LGTM

@shengliangxu

Copy link
Copy Markdown
Collaborator Author

On the latest review's fifth suggestion (the TP sync in apply_pre_quant_scale_and_smooth): same as the earlier answer in this conversation. smoothquant sets the input amax on every rank right before the call, and AWQ gates the call itself on awq_lite.is_enabled. Moving the sync out of the if would therefore not change participation on either path.

_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

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.

What would be the case when this is set to False?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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:

  1. max_calibrate skips the expert-parallel input-amax share for it.
  2. _check_moe_calibration_complete runs 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 raises MoE calibration incomplete: some experts received no tokens during calibration. Increase --calib-size ....
  3. 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_ep filters 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): raises MoE calibration incomplete.
  • [opted-in]: ends with input amax 1.0 on both ranks.

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

Looks great, only one general question

@shengliangxu

Copy link
Copy Markdown
Collaborator Author

Both follow-ups are now tracked:

  • OMNIML-6323: batch the amax-sync probe into one collective per process group. It covers the ~75 µs per quantizer per sync call measured above, plus the three items deferred from the last Claude review: is_mx_format in the early return, the _consumed_block_sizes note, and the get_backend stub.
  • OMNIML-6322: @Fridah-nv's single calibration-sync entry point with labeled, fail-together collectives. The probe batching can land inside it.

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