Skip to content

[6/6] Prevent EP ranks from overwriting Megatron export shards - #2625

Closed
kinjalpatel27 wants to merge 30 commits into
mainfrom
kinjal/vllm-fq-ep-shard-writer
Closed

kinjalpatel27 wants to merge 30 commits into
mainfrom
kinjal/vllm-fq-ep-shard-writer

Conversation

@kinjalpatel27

@kinjalpatel27 kinjalpatel27 commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do?

Type of change: Bug fix

This is [6/6] of the vLLM fakequant export and reload series, stacked on kinjal/vllm-fq-source-config. The preceding five parts are open as draft PRs.

The shared Megatron exporter previously passed each EP rank's layer mapping to the safetensors writer. Ranks on the same pipeline stage could write the same shard filename concurrently. This change lets only TP0/EP0/DP0 of each pipeline stage pass layer shards. All ranks still enter the writer helper and its distributed barrier.

Usage

No API or CLI change. Existing regular unified and vLLM fakequant Megatron export calls use the corrected writer ownership.

Testing

  • python -m pytest -q tests/gpu_megatron/torch/export/test_vllm_fakequant_megatron_export.py -k grouped_ep_export in the prepared Megatron container: 2 passed (EP=2 with PP=1 and PP=2). Each test runs both regular and fakequant export, checks the per-rank shard mappings passed to the writer, and checks exported expert weights and shard indexes.
  • pre-commit run --files modelopt/torch/export/unified_export_megatron.py tests/gpu_megatron/torch/export/test_vllm_fakequant_megatron_export.py: passed.
  • git diff --check: passed.

Before your PR is "Ready for review"

  • Is this change backward compatible?: ✅
  • 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 (fix to the in-progress export series)
  • Did you get Claude approval on this PR?: N/A (draft; review not requested yet)

Additional Information

Base branch: kinjal/vllm-fq-source-config (5/6).

Stack

Merge in this order:

  1. 1/6 CLI wrapper and app entry point
  2. 2/6 Megatron quantizer sidecars
  3. 3/6 Grouped expert weight folding
  4. 4/6 Automatic fakequant reload
  5. 5/6 HF source config preservation
  6. 6/6 EP shard writer ownership

@copy-pr-bot

copy-pr-bot Bot commented Oct 1, 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 1, 2026 •

Copy link
Copy Markdown
Contributor

Important

Draft PR not reviewed

Draft PRs are not automatically reviewed by default.

  • Trigger a manual review

To automatically review draft PRs, update your CodeRabbit configuration:

reviews:
  auto_review:
    drafts: true
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

@kinjalpatel27
kinjalpatel27 force-pushed the kinjal/vllm-fq-source-config branch from f2a7098 to 5413ab9 Compare October 1, 2026 22:31
@kinjalpatel27
kinjalpatel27 force-pushed the kinjal/vllm-fq-ep-shard-writer branch from 80058bf to 8b602dc Compare October 1, 2026 22:31
@kinjalpatel27
kinjalpatel27 force-pushed the kinjal/vllm-fq-source-config branch from 5413ab9 to ee54eda Compare October 2, 2026 00:22
@kinjalpatel27
kinjalpatel27 force-pushed the kinjal/vllm-fq-ep-shard-writer branch from 8b602dc to 079e26d Compare October 2, 2026 00:22
@kinjalpatel27
kinjalpatel27 force-pushed the kinjal/vllm-fq-source-config branch from ee54eda to 1973903 Compare October 6, 2026 17:14
@kinjalpatel27
kinjalpatel27 force-pushed the kinjal/vllm-fq-ep-shard-writer branch from 079e26d to 7dec333 Compare October 6, 2026 17:22
kinjalpatel27 added a commit that referenced this pull request Oct 6, 2026
### What does this PR do?

Type of change: New feature

Adds an installable `vllm` CLI shim for the fakequant serving example.
It accepts `--modelopt-*` options, carries them to the existing worker
through environment variables, chooses `FakeQuantWorker` only when
quantization or restore settings require it, and delegates other
commands to stock vLLM. It keeps the legacy direct script invocation and
recognizes the vLLM 0.30 `launch` command. The Docker default moves to
vLLM 0.30.0.

### Usage

```bash
pip install -e examples/vllm_serve
vllm serve <model_path> -tp 8 --modelopt-quant-cfg NVFP4_DEFAULT_CFG
```

### Testing

- Updated CLI and worker-selection coverage in
`tests/gpu/torch/quantization/test_vllm_dynamic_modules.py`.
- CLI delegation and `launch` argument handling were checked during
development against vLLM 0.30.0. CI is pending for this draft.

### Before your PR is "*Ready for review*"

- Is this change backward compatible?: ✅
- If you copied code from any other sources or added a new PIP
dependency, did you follow guidance in `CONTRIBUTING.md`?: N/A (no new
runtime dependency or copied code)
- Did you write any new necessary tests?: ✅
- Did you update Changelog?: ✅ (CLI feature entry in CHANGELOG.rst)
- Did you get Claude approval on this PR?: N/A (draft; review not
requested yet)

### Additional Information

Part of a six-PR stack. Merge in numeric order.

### Stack

Merge in this order:

1. [1/6 CLI wrapper and app entry
point](#2626)
2. [2/6 Megatron quantizer
sidecars](#2627)
3. [3/6 Grouped expert weight
folding](#2628)
4. [4/6 Automatic fakequant
reload](#2629)
5. [5/6 HF source config
preservation](#2630)
6. [6/6 EP shard writer
ownership](#2625)


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **New Features**
* Added ModelOpt options to the vLLM serving command for
fake-quantization settings, recipes, quantizer-state files, and
full-state checkpoint restoration.
* Commands without ModelOpt quantization settings use standard vLLM
behavior; non-serving commands pass through to vLLM, and invocations
without a command default to serving.
* Tracked `hf_ptq.py` runs now save and upload experiment metadata after
export.
* **Documentation**
* Updated serving instructions with CLI options, environment-variable
alternatives, Docker guidance, and tested vLLM releases.
* **Compatibility**
  * The fake-quantization vLLM CLI shim does not support vLLM 0.9.0.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Signed-off-by: Kinjal Patel <[email protected]>
@kinjalpatel27
kinjalpatel27 force-pushed the kinjal/vllm-fq-source-config branch from 1973903 to 812cfe3 Compare October 6, 2026 22:48
@kinjalpatel27
kinjalpatel27 force-pushed the kinjal/vllm-fq-ep-shard-writer branch from 7dec333 to db959f9 Compare October 6, 2026 22:54
@kinjalpatel27
kinjalpatel27 force-pushed the kinjal/vllm-fq-source-config branch 6 times, most recently from 01f6019 to d3207e3 Compare October 9, 2026 22:34
@kinjalpatel27
kinjalpatel27 force-pushed the kinjal/vllm-fq-source-config branch 2 times, most recently from 7f74f1b to fb9b374 Compare October 14, 2026 23:35
Base automatically changed from kinjal/vllm-fq-source-config to main October 15, 2026 13:49
kevalmorabia97 added a commit that referenced this pull request Oct 19, 2026
…d VLM models (#2873)

### What does this PR do?

Type of change: new feature, bug fix

Gaps found while running GGML IQ2 PTQ → QAD → vLLM evaluation of
GLM-5.3-Flash (321B MoE + vision tower) with `examples/megatron_bridge`
on GB300. None of it is GLM-specific; the GLM recipe itself is in #2539.

**Quantization**
- **GPTQ's chosen GGML codes survive a Megatron checkpoint.** GPTQ pins
the IQ/Q8_0 codes it picked to the weight quantizer (`_ggml_pinned_*`
buffers). The Megatron sharded state dict dropped them (with a warning),
so a PTQ checkpoint reloaded for QAD or export re-encoded every weight
from scratch. They are now saved and loaded with the weights, sharded
along the weight's tensor-parallel axis, and the restore no longer warns
that they are unsupported.
- **Layerwise calibration on Megatron VLMs.** Text calibration drives
the wrapper's `language_model` directly, so the early-stop patch on the
wrapper's `forward` never ran and calibration failed.
`get_mcore_layerwise_calibration_layers` now finds the decoder under
`language_model`, the early stop also patches the language model (only
the outermost patched forward swallows the stop), and
`megatron_prefill(skip_return_logits=True)` returns when the forward
stopped early.

**Export**
- **`--no_moe_grouped_gemm` (SequentialMLP) checkpoints export at
`--ep_size` > 1.** GGML export and GPTQ need per-expert linears, so
large MoEs could only export at EP=1, which ran out of GPU then host
memory for a 600 GB checkpoint. Experts are now written under their
global ids, and each EP rank other than 0 writes its own experts to
`model-XXXXX-of-YYYYY-epNNN.safetensors` shards that the index picks up.
Packed local-expert rules (Llama 4, GPT-OSS) still refuse EP > 1.
- **`export_quantized_megatron_to_hf.py --vllm_fakequant_export`**
exports with `export_mcore_gpt_to_hf_vllm_fq`, folding weight quantizers
into BF16 weights so formats vLLM has no kernels for (e.g. GGML IQ) can
be evaluated in a stock vLLM.
- **The fake-quant export drops the source's `quantization_config`.**
From a pre-quantized source (e.g. FP8 blockwise), `config.json` kept the
FP8 config and vLLM read the BF16 weights as FP8.

**`examples/megatron_bridge` flags**
- `distill.py --sft_in_batch_packing`: pack each micro-batch's
`--sft_hf_dataset` conversations into one THD sequence (`--mbs`
conversations per pack) instead of padding each to `--seq_length`;
Megatron-Bridge forces padding whenever EP > 1. Uses the per-micro-batch
dataloader and pads each conversation to a multiple of 2 x CP.
- `distill.py --moe_aux_loss_coeff`: override the MoE load-balancing
loss weight. The aux loss runs over every token, padding included; on
GLM's KDA/DSA layers it drove the pad-token embedding gradient to Inf at
32K.
- `distill.py` / `quantize.py --dsa_kernel_backend
{none,tilelang,cudnn}`: fused DeepSeek sparse-attention kernels. The
unfused fallback builds dense `[seq, seq]` scores per head and does not
fit at long sequence lengths.

### Usage

```bash
# Export a GGML (SequentialMLP) checkpoint at EP16 as a vLLM fake-quant BF16 checkpoint
torchrun --nproc_per_node 4 examples/megatron_bridge/export_quantized_megatron_to_hf.py \
    --hf_model_name_or_path <hf_model> --megatron_path <ptq_ckpt> --export_unified_hf_path <out> \
    --no_moe_grouped_gemm --ep_size 16 --vllm_fakequant_export

# QAD on chat data for an MoE at EP>1
torchrun ... examples/megatron_bridge/distill.py --sft --sft_hf_dataset <chat.jsonl> \
    --sft_in_batch_packing --mbs 2 --moe_aux_loss_coeff 0 --dsa_kernel_backend cudnn ...
```

### Testing

New or changed tests (each GPU test run in
`nvcr.io/nvidian/nemo:26.10.rc3`, 2x RTX 6000 Ada):
-
`test_unified_export_megatron.py::test_sequential_experts_export_at_ep`
(new, 2 ranks): a tiny Qwen3-MoE with SequentialMLP experts exported at
EP=2; every rank's experts are read back from the index under their
global ids and match bit for bit, and the checkpoint's names match the
HF reference. `test_megatron_export_rejects_packed_local_experts_at_ep`
replaces the old SequentialMLP refusal test.
- `test_vllm_fakequant_megatron_export.py::test_mcore_vllm_export`: the
source now carries an FP8 `quantization_config`, and the export's
`config.json` must not.
- `test_megatron.py::test_ggml_gptq_payload_sharded_state_dict` (new, 2
ranks, TP=2): GPTQ with the `general/ptq/iq2_xs` recipe, save and
reload, pinned payloads identical.
- `test_megatron.py::test_layerwise_calibrate_vlm_text_forward_loop`
(new): layerwise calibration of a wrapper without `decoder`, driven
through its `language_model` with `megatron_prefill`.
-
`tests/examples/megatron_bridge/test_distill.py::test_distill_llm_sft_hf_chat[packed]`
(new case): tiny Qwen3-MoE student, `--sft_in_batch_packing --mbs 2
--moe_aux_loss_coeff 0`.
- Each new test fails with the library changes reverted (the EP test,
the `quantization_config` check, the payload test with only the sharding
hunks reverted, the VLM test with only the layerwise/prefill hunks
reverted); the packed case fails on the unknown flags.
- Full files: `test_unified_export_megatron.py` 103 passed,
`test_vllm_fakequant_megatron_export.py` 7 passed, `test_megatron.py`
131 passed / 35 skipped / 3 failed. The 3
(`test_te_grouped_vs_sequential_default_loss[*]`,
`test_auto_quantize_moe_ep`) fail the same way on `main` in a full-file
run on this machine and pass when run alone, with or without this PR.
- CPU: `tests/unit/torch/quantization/test_ggml_*`,
`test_layerwise_calibrate.py`, `tests/unit/recipe`: 661 passed.
- Not run: `--dsa_kernel_backend` has no test (flag plumbing; needs a
DSA model, used in the GLM runs below).

**At scale** (oci-jhb GB300, every path above in use):
- GLM-5.3-Flash IQ2_S PTQ with layerwise GPTQ (EP16, 4 nodes, 256 x 32K
calibration with `--dsa_kernel_backend cudnn`); fake-quant export at
EP16 in ~6 min (all 354 tensors of the 4-layer mini model identical to
EP1 before the full run); QAD from that checkpoint at EP32 on 32 nodes
for 200 iterations with `--sft_in_batch_packing --moe_aux_loss_coeff 0`;
vLLM evaluation of the exports across 6 benchmarks.
- Qwen3.6-35B-A3B QAD on chat data with `--sft_in_batch_packing
--moe_aux_loss_coeff 0` (oci-hsg, 32 nodes).

### Before your PR is "*Ready for review*"

- Is this change backward compatible?: ✅ New flags default off. EP > 1
export of SequentialMLP checkpoints used to raise and now works.
- 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](https://github.com/NVIDIA/Model-Optimizer/blob/main/CHANGELOG.rst)?:
✅
- Did you get Claude approval on this PR?: ❌

### Additional Information

- #2539 (GLM-5.3-Flash support) adds the IQ2_S recipe that uses these
paths; the two PRs are independent and can merge in either order (both
add a 0.49 *Megatron Framework* CHANGELOG section).
- #2625 (draft) changes the same shard-writer block for grouped experts
at EP > 1; whichever merges second rebases.

🤖 Generated with [Claude Code](https://claude.com/claude-code)


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **New Features**
* Added options for SFT in-batch packing, MoE auxiliary-loss
coefficients, and DeepSeek sparse-attention kernel selection.
* Added BF16 fake-quant export, with activation quantizers saved
separately.
* Expanded expert-parallel export support for sequential experts,
including checkpoints not built with grouped GEMM.
* Added a Nemotron 3.5 Super VL AutoQuantize recipe, weighted imatrix
calibration for GGML formats, and external-draft speculative decoding.
* **Bug Fixes**
* Improved layerwise calibration for Megatron vision-language models and
preservation of GGML GPTQ data across parallel settings and exports.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Signed-off-by: Keval Morabia <[email protected]>
Co-authored-by: Claude Opus 5.5 <[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.

1 participant