mirror of
https://github.com/NVIDIA/Model-Optimizer.git
synced 2026-12-06 04:57:17 +08:00
Merge main into kmorabia/deprecate-mcore-gpt-export
Resolve the conflicts with #3651 in export_quantized_megatron_to_hf.py: keep its routing and --modelopt_megatron_exporter flag, and the deprecation-warning suppression around the ModelOpt-exporter fallback. --export_extra_modules exports EAGLE modules only (no Medusa or MTP). The deprecation docs now point at the example as the Megatron-Bridge export, and list bridges that post-process exported weights as still needing the old exporter. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Signed-off-by: Keval Morabia <28916987+kevalmorabia97@users.noreply.github.com>
This commit is contained in:
+3
-1
@@ -39,6 +39,8 @@ Changelog
|
||||
|
||||
*Megatron Framework (M-LM / M-Bridge)*
|
||||
|
||||
- ``examples/megatron_bridge/export_quantized_megatron_to_hf.py`` now exports through Megatron-Bridge (``AutoBridge.save_hf_pretrained_modelopt``) at any tensor, expert or pipeline parallelism when the installed Megatron-Bridge provides it and can export every enabled quantizer, writing the quantization config inline in ``config.json`` only (no ``hf_quant_config.json``). Otherwise, e.g. for KV-cache quantizers before Megatron-Bridge #7057, GGML / IQ formats, ``--export_extra_modules`` or a VLM's language-model-only QAD checkpoint, ModelOpt's Megatron exporter writes it at ``--tp_size 1`` (GGML / IQ also at ``--pp_size 1``); ``--modelopt_megatron_exporter`` selects it explicitly.
|
||||
|
||||
*Misc*
|
||||
|
||||
- Move agent skills to the repository-root ``skills/`` directory, with symlinks for agent discovery.
|
||||
@@ -50,7 +52,7 @@ Changelog
|
||||
|
||||
**Deprecations**
|
||||
|
||||
- ``modelopt.torch.export.export_mcore_gpt_to_hf`` is deprecated and planned for removal in 0.51.0; it now emits a ``DeprecationWarning``. Where it supports the checkpoint, export with Megatron-Bridge's ``AutoBridge.save_hf_pretrained_modelopt`` instead (set up as in `examples/megatron_bridge/README.md <https://github.com/NVIDIA/Model-Optimizer/tree/main/examples/megatron_bridge#pre-requisites>`_); the function's docstring lists what Megatron-Bridge doesn't export yet.
|
||||
- ``modelopt.torch.export.export_mcore_gpt_to_hf`` is deprecated and planned for removal in 0.51.0; it now emits a ``DeprecationWarning``. Where it supports the checkpoint, export with Megatron-Bridge's ``AutoBridge.save_hf_pretrained_modelopt`` instead, as ``examples/megatron_bridge/export_quantized_megatron_to_hf.py`` does (set up as in `examples/megatron_bridge/README.md <https://github.com/NVIDIA/Model-Optimizer/tree/main/examples/megatron_bridge#pre-requisites>`_); the function's docstring lists what Megatron-Bridge doesn't export yet.
|
||||
|
||||
**Bug Fixes**
|
||||
|
||||
|
||||
@@ -136,7 +136,7 @@ torchrun --nproc_per_node 2 export_quantized_megatron_to_hf.py \
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> The HuggingFace unified exporter can't split weights across GPUs with tensor parallelism. For large models, use `--pp_size` on `export_quantized_megatron_to_hf.py` to shard the export across GPUs with pipeline parallelism instead.
|
||||
> Megatron-Bridge writes the export at any `--tp_size` / `--ep_size` / `--pp_size`, with the quantization config inline in `config.json`, when it provides `AutoBridge.save_hf_pretrained_modelopt` (newer than the one in `nemo:26.10`) and can export every enabled quantizer: KV-cache quantizers (e.g. `--kv_cache_quant fp8` or a `*-kv_fp8*` recipe) need a Megatron-Bridge with #7057. Otherwise, and for GGML / IQ formats, `--export_extra_modules` or a VLM's language-model-only QAD checkpoint, ModelOpt's Megatron exporter writes it and `--tp_size` above 1 raises: use `--pp_size` (or `--ep_size`) to shard a large model across GPUs instead, except for GGML / IQ formats, which export at `--tp_size 1 --pp_size 1` only.
|
||||
|
||||
> [!TIP]
|
||||
> To recover the accuracy lost during quantization, fine-tune the quantized Megatron checkpoint (from step 1) with [Quantization Aware Distillation (QAD)](#quantization-aware-distillation-qad) before running the step 2 export.
|
||||
@@ -641,7 +641,7 @@ torchrun --nproc_per_node 2 prune_minitron.py \
|
||||
|
||||
## Sanity-Check Generation
|
||||
|
||||
[generate_vllm.py](generate_vllm.py) runs a quick generation check on an exported HuggingFace checkpoint using vLLM — a useful smoke test for a **quantized**, **pruned**, or **distilled** model to confirm it still produces coherent text. For quantized checkpoints, vLLM auto-detects the ModelOpt quantization from the exported `hf_quant_config.json`, so no extra flags are needed:
|
||||
[generate_vllm.py](generate_vllm.py) runs a quick generation check on an exported HuggingFace checkpoint using vLLM — a useful smoke test for a **quantized**, **pruned**, or **distilled** model to confirm it still produces coherent text. For quantized checkpoints, vLLM auto-detects the ModelOpt quantization from the `quantization_config` in the exported `config.json` (ModelOpt's Megatron exporter also writes `hf_quant_config.json`), so no extra flags are needed:
|
||||
|
||||
<!-- modelopt-snippet: bridge-generation -->
|
||||
```bash
|
||||
|
||||
@@ -18,12 +18,12 @@ checkpoint that can be deployed directly with TensorRT-LLM, vLLM, or SGLang.
|
||||
The process is as follows:
|
||||
1. Build the Megatron-Core model structure + tokenizer from the original HuggingFace model.
|
||||
2. Load the quantized Megatron checkpoint (ModelOpt state + weights are restored automatically).
|
||||
3. Export the model to a HuggingFace (unified) checkpoint via ModelOpt.
|
||||
|
||||
The HuggingFace unified exporter does not gather tensor-parallel-sharded weights, so this script
|
||||
always loads the checkpoint at tensor_model_parallel_size=1 (re-sharding from whatever TP was used
|
||||
during quantization). Use --pp_size and/or --ep_size to shard a large model across GPUs for
|
||||
export.
|
||||
3. Export the model to a HuggingFace (unified) checkpoint. Megatron-Bridge writes it at any
|
||||
TP / EP / PP when it provides ``AutoBridge.save_hf_pretrained_modelopt`` and can export every
|
||||
enabled quantizer (e.g. the KV-cache ones only since Megatron-Bridge #7057). Otherwise, and for
|
||||
what it doesn't cover (GGML / IQ formats, --export_extra_modules, a VLM's language-model-only
|
||||
QAD checkpoint), ModelOpt's Megatron exporter writes it at tensor_model_parallel_size=1: use
|
||||
--pp_size and/or --ep_size to shard a large model, except GGML / IQ formats (TP=1 and PP=1).
|
||||
|
||||
Example usage to export an FP8 checkpoint produced by quantize.py:
|
||||
|
||||
@@ -51,6 +51,7 @@ See `README.md` in this directory for more details.
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import re
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
|
||||
@@ -69,10 +70,16 @@ from mlflow_utils import (
|
||||
|
||||
import modelopt.torch.quantization as mtq
|
||||
import modelopt.torch.utils.distributed as dist
|
||||
from modelopt.torch.export import ensure_local_checkpoint, export_mcore_gpt_to_hf
|
||||
from modelopt.torch.export import (
|
||||
copy_non_model_files,
|
||||
ensure_local_checkpoint,
|
||||
export_mcore_gpt_to_hf,
|
||||
)
|
||||
from modelopt.torch.export.plugins.vllm_fakequant_megatron import (
|
||||
check_mcore_vllm_fakequant_quantizers,
|
||||
)
|
||||
from modelopt.torch.export.quant_utils import uses_iq_quantization
|
||||
from modelopt.torch.export.quantized_weight_export import get_quantized_weight_export_spec
|
||||
from modelopt.torch.utils import print_args, print_rank_0
|
||||
from modelopt.torch.utils.mlflow import Tool, masked_args
|
||||
from modelopt.torch.utils.plugins.mbridge import (
|
||||
@@ -140,14 +147,25 @@ def get_args() -> argparse.Namespace:
|
||||
parser.add_argument(
|
||||
"--export_extra_modules",
|
||||
action="store_true",
|
||||
help="Export extra modules such as EAGLE or MTP.",
|
||||
help=("Export EAGLE modules (ModelOpt's Megatron exporter only, at --tp_size 1)."),
|
||||
)
|
||||
parser.add_argument(
|
||||
"--modelopt_megatron_exporter",
|
||||
action="store_true",
|
||||
help=(
|
||||
"Export with ModelOpt's Megatron exporter (--tp_size 1 only) even where "
|
||||
"Megatron-Bridge's quantized export applies, e.g. to compare the two."
|
||||
),
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--tp_size",
|
||||
type=int,
|
||||
default=1,
|
||||
help="Tensor parallel size (--vllm_fakequant_export only; the unified exporter needs 1)",
|
||||
help=(
|
||||
"Tensor parallel size. Megatron-Bridge's exports support any; ModelOpt's Megatron "
|
||||
"exporter (GGML / IQ formats, --export_extra_modules) needs 1."
|
||||
),
|
||||
)
|
||||
parser.add_argument("--pp_size", type=int, default=1, help="Pipeline parallel size")
|
||||
parser.add_argument(
|
||||
@@ -208,6 +226,157 @@ def export_vllm_fakequant(bridge, model: list, export_dir: str) -> None:
|
||||
dist.barrier()
|
||||
|
||||
|
||||
def unexportable_weight(model: list) -> str | None:
|
||||
"""A quantized weight on this rank whose format Megatron-Bridge's writer can't pack, if any.
|
||||
|
||||
Megatron-Bridge packs each weight with ModelOpt's functional export, which supports fewer
|
||||
formats (e.g. not INT4 AWQ or INT8 weight-only) than ModelOpt's Megatron exporter; this runs
|
||||
its metadata-only check over every weight parameter, named as Megatron-Bridge names them (e.g.
|
||||
grouped experts' ``weight0``, ``weight1``, ...), before anything is written. Any error counts
|
||||
as unexportable, so no rank raises before the ranks agree.
|
||||
"""
|
||||
for chunk in model:
|
||||
for name, module in unwrap_model(chunk).named_modules():
|
||||
for weight_name, _ in module.named_parameters(recurse=False):
|
||||
if not re.fullmatch(r"weight\d*", weight_name):
|
||||
continue
|
||||
try:
|
||||
get_quantized_weight_export_spec(module, weight_name)
|
||||
except Exception as e:
|
||||
return f"{name}.{weight_name}: {e}"
|
||||
return None
|
||||
|
||||
|
||||
def bridge_rejected_by_quantized_export(bridge) -> str | None:
|
||||
"""The model bridge ``save_hf_pretrained_modelopt`` refuses up front, or None.
|
||||
|
||||
It refuses bridges without standalone HF export and bridges that post-process the exported
|
||||
weights (e.g. Nemotron 3.5 Super VL's), which a quantized export can't do yet.
|
||||
"""
|
||||
# TODO: drop the post-processing check once Megatron-Bridge supports quantization-safe export
|
||||
# post-processing (OMNIML-6311).
|
||||
try:
|
||||
model_bridge_type = type(bridge._model_bridge)
|
||||
except (AttributeError, ValueError, NotImplementedError): # no resolvable model bridge
|
||||
return None
|
||||
base = MegatronModelBridge.postprocess_hf_export_weights
|
||||
if (
|
||||
not getattr(model_bridge_type, "SUPPORTS_HF_PRETRAINED_EXPORT", True)
|
||||
or getattr(model_bridge_type, "postprocess_hf_export_weights", base) is not base
|
||||
):
|
||||
return model_bridge_type.__name__
|
||||
return None
|
||||
|
||||
|
||||
def bridge_export_unsupported(
|
||||
bridge, model: list, args: argparse.Namespace, language_model_only: bool
|
||||
) -> tuple[str | None, bool]:
|
||||
"""Why Megatron-Bridge's quantized export can't write this checkpoint, alike on every rank.
|
||||
|
||||
Returns the reason (None if it can) and whether the checkpoint has GGML / IQ formats, which
|
||||
ModelOpt's Megatron exporter writes at TP=1 and PP=1 only. Megatron-Bridge's export needs
|
||||
``AutoBridge.save_hf_pretrained_modelopt`` and doesn't cover GGML / IQ formats, extra modules
|
||||
(EAGLE), or a VLM's language-model-only checkpoint (it saves the in-memory
|
||||
vision tower, which that checkpoint doesn't hold; ModelOpt's exporter copies it from the HF
|
||||
source), or models whose bridge it rejects (see :func:`bridge_rejected_by_quantized_export`), and
|
||||
packs fewer weight formats (see :func:`unexportable_weight`). Older Megatron-Bridge versions
|
||||
also reject some quantizers (e.g. KV-cache ones).
|
||||
"""
|
||||
try:
|
||||
from megatron.bridge.models.conversion.modelopt_utils import check_exportable_quantizers
|
||||
except ImportError: # a Megatron-Bridge without the quantized export
|
||||
check_exportable_quantizers = None
|
||||
# Every rank's facts, agreed in one collective before any rank decides (pipeline stages hold
|
||||
# different layers, and ranks may differ in what they import).
|
||||
flags = torch.tensor(
|
||||
[
|
||||
int(
|
||||
check_exportable_quantizers is None
|
||||
or not hasattr(bridge, "save_hf_pretrained_modelopt")
|
||||
),
|
||||
int(language_model_only),
|
||||
int(any(uses_iq_quantization(unwrap_model(chunk)) for chunk in model)),
|
||||
# Not scanned when ModelOpt's exporter is forced.
|
||||
int(
|
||||
not args.modelopt_megatron_exporter
|
||||
and (weight := unexportable_weight(model)) is not None
|
||||
),
|
||||
],
|
||||
dtype=torch.int,
|
||||
# NCCL reduces CUDA tensors; gloo (e.g. a CPU test group) CPU ones.
|
||||
device="cuda"
|
||||
if torch.distributed.is_initialized() and torch.distributed.get_backend() == "nccl"
|
||||
else "cpu",
|
||||
)
|
||||
if torch.distributed.is_initialized():
|
||||
torch.distributed.all_reduce(flags, op=torch.distributed.ReduceOp.MAX)
|
||||
no_writer, language_model_only, ggml, unexportable = (bool(flag) for flag in flags.tolist())
|
||||
if args.modelopt_megatron_exporter:
|
||||
return "--modelopt_megatron_exporter", ggml
|
||||
if no_writer:
|
||||
return "this Megatron-Bridge has no save_hf_pretrained_modelopt", ggml
|
||||
if args.export_extra_modules:
|
||||
return "--export_extra_modules", ggml
|
||||
if language_model_only:
|
||||
return "a VLM's language-model-only checkpoint (e.g. from QAD)", ggml
|
||||
# The same model bridge on every rank.
|
||||
if (rejected := bridge_rejected_by_quantized_export(bridge)) is not None:
|
||||
return f"Megatron-Bridge's quantized export rejects {rejected}", ggml
|
||||
if ggml:
|
||||
return "the checkpoint has GGML / IQ formats", True
|
||||
if unexportable:
|
||||
detail = f": {weight}" if weight is not None else " on another rank"
|
||||
return f"Megatron-Bridge can't pack some quantized weights{detail}", False
|
||||
try:
|
||||
# Collective: raises on every rank if any rank holds a quantizer it can't export.
|
||||
check_exportable_quantizers(model)
|
||||
except RuntimeError as e:
|
||||
return f"Megatron-Bridge can't export some quantizers ({e})", False
|
||||
return None, False
|
||||
|
||||
|
||||
def use_bridge_export(
|
||||
bridge, model: list, args: argparse.Namespace, language_model_only: bool
|
||||
) -> bool:
|
||||
"""Whether Megatron-Bridge writes the unified export, else ModelOpt's Megatron exporter.
|
||||
|
||||
Decided alike on every rank, which all raise if the exporter it falls to can't run at this
|
||||
parallelism (also when --modelopt_megatron_exporter or --export_extra_modules selects it).
|
||||
"""
|
||||
unsupported, ggml = bridge_export_unsupported(bridge, model, args, language_model_only)
|
||||
if unsupported is None:
|
||||
return True
|
||||
if ggml and (args.tp_size != 1 or args.pp_size != 1):
|
||||
raise ValueError(
|
||||
f"Megatron-Bridge's quantized export doesn't apply ({unsupported}), and ModelOpt's "
|
||||
"Megatron exporter writes GGML / IQ formats at --tp_size 1 and --pp_size 1 only: "
|
||||
"export with --tp_size 1 --pp_size 1."
|
||||
)
|
||||
if args.tp_size != 1:
|
||||
raise ValueError(
|
||||
f"Megatron-Bridge's quantized export doesn't apply ({unsupported}), and ModelOpt's "
|
||||
"Megatron exporter needs --tp_size 1: export with --tp_size 1 (and --pp_size / "
|
||||
"--ep_size to shard the model)."
|
||||
)
|
||||
print_rank_0(f"Exporting with ModelOpt's Megatron exporter: {unsupported}.")
|
||||
return False
|
||||
|
||||
|
||||
def export_bridge_hf(bridge, model: list, args: argparse.Namespace) -> None:
|
||||
"""Export the quantized model to a unified HF checkpoint with Megatron-Bridge (any TP/EP/PP)."""
|
||||
print_rank_0(
|
||||
"Exporting to HuggingFace (unified) checkpoint with Megatron-Bridge at "
|
||||
f"{args.export_unified_hf_path}..."
|
||||
)
|
||||
bridge.save_hf_pretrained_modelopt(
|
||||
model, args.export_unified_hf_path, source_path=args.local_checkpoint_path
|
||||
)
|
||||
# Megatron-Bridge saves only the config, tokenizer and remote code; carry over the source's
|
||||
# other non-model files (README, chat templates, assets) as ModelOpt's exporter does.
|
||||
if dist.is_master():
|
||||
copy_non_model_files(args.local_checkpoint_path, args.export_unified_hf_path)
|
||||
|
||||
|
||||
def export_unified_hf(unwrapped_model, args: argparse.Namespace, trust_remote_code: bool) -> None:
|
||||
"""Export the quantized model to a unified HF checkpoint with ModelOpt's Megatron exporter."""
|
||||
# Extra modules (Medusa / EAGLE / MTP) only exist on the last pipeline stage. Use an all-reduce
|
||||
@@ -228,7 +397,8 @@ def export_unified_hf(unwrapped_model, args: argparse.Namespace, trust_remote_co
|
||||
f"Exporting to HuggingFace (unified) checkpoint at {args.export_unified_hf_path}..."
|
||||
)
|
||||
# TODO: Gemma3-VL is not in export_mcore_gpt_to_hf's per-arch mappings yet.
|
||||
# This script picks the exporter, so its users get no deprecation warning they can't act on.
|
||||
# This script falls back to this exporter only where Megatron-Bridge's can't export (or when
|
||||
# --modelopt_megatron_exporter asks for it), so it doesn't pass the deprecation warning on.
|
||||
with warnings.catch_warnings():
|
||||
warnings.filterwarnings(
|
||||
"ignore", "export_mcore_gpt_to_hf is deprecated", DeprecationWarning
|
||||
@@ -253,8 +423,11 @@ def main(args: argparse.Namespace):
|
||||
trust_remote_code = is_safe_repo(
|
||||
trust_remote_code=args.trust_remote_code, hf_path=args.local_checkpoint_path
|
||||
)
|
||||
if not args.vllm_fakequant_export and args.tp_size != 1:
|
||||
raise ValueError("--tp_size > 1 needs --vllm_fakequant_export.")
|
||||
if args.vllm_fakequant_export and args.modelopt_megatron_exporter:
|
||||
raise ValueError(
|
||||
"--modelopt_megatron_exporter selects the unified export's exporter; it doesn't apply "
|
||||
"to --vllm_fakequant_export."
|
||||
)
|
||||
if args.vllm_fakequant_export and args.export_extra_modules:
|
||||
raise ValueError("--export_extra_modules is not supported with --vllm_fakequant_export.")
|
||||
|
||||
@@ -287,13 +460,17 @@ def main(args: argparse.Namespace):
|
||||
# Load the quantized checkpoint (with the correct layer spec) rather than reconstructing it from the checkpoint
|
||||
# config, which avoids the non-serializable layer-spec issue for MoE / Mamba models.
|
||||
print_rank_0(f"Loading quantized Megatron checkpoint from {args.megatron_path}...")
|
||||
load_modelopt_megatron_checkpoint(model, args.megatron_path)
|
||||
loaded = load_modelopt_megatron_checkpoint(model, args.megatron_path)
|
||||
# Only a VLM's language-model-only checkpoint loads into other modules (``.language_model``).
|
||||
language_model_only = loaded is not model
|
||||
unwrapped_model = unwrap_model(model[0])
|
||||
mtq.merge_quant_lora(unwrapped_model)
|
||||
|
||||
if args.vllm_fakequant_export:
|
||||
print_rank_0(f"Exporting vLLM fake-quant checkpoint to {args.export_unified_hf_path}...")
|
||||
export_vllm_fakequant(bridge, model, args.export_unified_hf_path)
|
||||
elif use_bridge_export(bridge, model, args, language_model_only):
|
||||
export_bridge_hf(bridge, model, args)
|
||||
else:
|
||||
export_unified_hf(unwrapped_model, args, trust_remote_code)
|
||||
args.checkpoint_exported = True
|
||||
|
||||
@@ -14,7 +14,8 @@
|
||||
# limitations under the License.
|
||||
"""Sanity-check generation for a unified HF checkpoint, using vLLM.
|
||||
|
||||
vLLM auto-detects the ModelOpt quantization from the `hf_quant_config.json`, so no extra quant flags are needed.
|
||||
vLLM auto-detects the ModelOpt quantization from the `quantization_config` in `config.json` (ModelOpt's Megatron
|
||||
exporter also writes `hf_quant_config.json`), so no extra quant flags are needed.
|
||||
|
||||
Usage:
|
||||
python generate_vllm.py --model nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-FP8 --trust_remote_code
|
||||
|
||||
@@ -249,7 +249,7 @@ Non-default arguments:
|
||||
|
||||
### 4. Export
|
||||
|
||||
Convert the quantized Megatron checkpoint to a deployable unified HuggingFace checkpoint (**~7 min on 1 node, 0.5 GB200 GPU-hours**). The unified exporter loads at TP=1, so use pipeline parallelism to shard across GPUs.
|
||||
Convert the quantized Megatron checkpoint to a deployable unified HuggingFace checkpoint (**~7 min on 1 node, 0.5 GB200 GPU-hours**). The QAD checkpoint below holds only the language model (QAD distills the VLM's language model alone), so ModelOpt's exporter writes the export, copying the vision tower from the source model: it loads at TP=1, so use pipeline parallelism to shard across GPUs. Megatron-Bridge's export at any parallelism applies to full PTQ checkpoints only, and with this recipe's FP8 KV cache it needs Megatron-Bridge #7057 or newer (newer than the one in `nemo:26.10`).
|
||||
|
||||
<details>
|
||||
<summary>Export command (click to expand)</summary>
|
||||
|
||||
@@ -2442,9 +2442,10 @@ def export_mcore_gpt_to_hf(
|
||||
.. deprecated:: 0.50.0
|
||||
Planned for removal in 0.51.0. Where it supports the checkpoint, export with
|
||||
Megatron-Bridge's ``AutoBridge.save_hf_pretrained_modelopt`` instead, from the quantized
|
||||
model chunks and the local HF source checkpoint. It needs a Megatron-Bridge newer than the
|
||||
one in ``nemo:26.10``: ModelOpt tests it at the commit ``examples/megatron_bridge/README.md``
|
||||
names.
|
||||
model chunks and the local HF source checkpoint, as
|
||||
``examples/megatron_bridge/export_quantized_megatron_to_hf.py`` does. It needs a
|
||||
Megatron-Bridge newer than the one in ``nemo:26.10``: ModelOpt tests it at the commit
|
||||
``examples/megatron_bridge/README.md`` names.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
@@ -2452,8 +2453,9 @@ def export_mcore_gpt_to_hf(
|
||||
bridge.save_hf_pretrained_modelopt(model_chunks, export_dir, source_path=hf_path)
|
||||
|
||||
It doesn't export these yet, so keep using this function for them: GGML / IQ formats,
|
||||
EAGLE modules (``export_extra_modules=True``), and a VLM whose Megatron checkpoint holds
|
||||
only the language model.
|
||||
EAGLE modules (``export_extra_modules=True``), a VLM whose Megatron checkpoint holds only
|
||||
the language model, and models whose Megatron-Bridge bridge post-processes the exported
|
||||
weights (e.g. Nemotron 3.5 Super VL).
|
||||
|
||||
Neither path exports these:
|
||||
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
"""Which exporter export_quantized_megatron_to_hf.py picks, alike on every rank."""
|
||||
|
||||
import argparse
|
||||
from functools import partial
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
from _test_utils.examples.megatron_example_runner import _load_example_module
|
||||
from _test_utils.torch.distributed.utils import spawn_multiprocess_job
|
||||
|
||||
import modelopt.torch.quantization as mtq
|
||||
|
||||
|
||||
def _export_script():
|
||||
return _load_example_module("export_quantized_megatron_to_hf.py", "megatron_bridge")
|
||||
|
||||
|
||||
def _args(**kwargs):
|
||||
defaults = {"modelopt_megatron_exporter": False, "export_extra_modules": False}
|
||||
return argparse.Namespace(**{**defaults, "tp_size": 1, "pp_size": 1, **kwargs})
|
||||
|
||||
|
||||
class _Bridge:
|
||||
def save_hf_pretrained_modelopt(self, *args, **kwargs):
|
||||
raise AssertionError("not reached")
|
||||
|
||||
|
||||
def _int8_weight_only_linear():
|
||||
linear = torch.nn.Linear(16, 16)
|
||||
mtq.quantize(linear, mtq.INT8_WEIGHT_ONLY_CFG, lambda m: m(torch.randn(2, 16)))
|
||||
return linear
|
||||
|
||||
|
||||
def _rank_1_only(case, rank, size):
|
||||
export = _export_script()
|
||||
# Imported in the worker, so the pytest process never loads Megatron-Bridge.
|
||||
import megatron.bridge.models.conversion.modelopt_utils as modelopt_utils
|
||||
|
||||
bridge, model = _Bridge(), torch.nn.Linear(4, 4)
|
||||
if rank == 1 and case == "no_writer":
|
||||
bridge = SimpleNamespace()
|
||||
if case == "unexportable_weight":
|
||||
# On every rank: calibration syncs ranges across ranks. Only rank 1 then holds it.
|
||||
int8_weight_only = _int8_weight_only_linear() # a format Bridge's writer can't pack
|
||||
model = int8_weight_only if rank == 1 else model
|
||||
with patch.object(
|
||||
modelopt_utils,
|
||||
"check_exportable_quantizers",
|
||||
side_effect=AssertionError("entered Megatron-Bridge's preflight"),
|
||||
):
|
||||
assert not export.use_bridge_export(bridge, [model], _args(), False)
|
||||
|
||||
|
||||
@pytest.mark.timeout(120)
|
||||
@pytest.mark.parametrize("case", ["no_writer", "unexportable_weight"])
|
||||
def test_one_rank_without_bridge_support_sends_every_rank_to_modelopt(case):
|
||||
"""Rank 1 alone lacks Bridge support: every rank falls back before Bridge's preflight.
|
||||
|
||||
Rank 1 lacks Megatron-Bridge's writer, or holds a weight it can't pack (INT8 weight-only).
|
||||
"""
|
||||
spawn_multiprocess_job(2, partial(_rank_1_only, case))
|
||||
|
||||
|
||||
def test_a_forced_modelopt_export_of_an_iq_checkpoint_needs_tp_and_pp_1():
|
||||
export = _export_script()
|
||||
args = _args(modelopt_megatron_exporter=True, tp_size=2, pp_size=2)
|
||||
with (
|
||||
patch.object(export, "uses_iq_quantization", return_value=True),
|
||||
pytest.raises(ValueError, match="--tp_size 1 --pp_size 1"),
|
||||
):
|
||||
export.use_bridge_export(_Bridge(), [torch.nn.Linear(4, 4)], args, False)
|
||||
|
||||
|
||||
def test_a_bridge_that_post_processes_exported_weights_falls_back_to_modelopt():
|
||||
"""Megatron-Bridge rejects such bridges (e.g. Nemotron 3.5 Super VL's) only once exporting."""
|
||||
export = _export_script()
|
||||
|
||||
class _PostProcessing:
|
||||
def postprocess_hf_export_weights(self, path):
|
||||
pass
|
||||
|
||||
bridge = _Bridge()
|
||||
bridge._model_bridge = _PostProcessing()
|
||||
with patch.object(export, "unexportable_weight", return_value=None):
|
||||
assert not export.use_bridge_export(bridge, [torch.nn.Linear(4, 4)], _args(), False)
|
||||
@@ -125,9 +125,14 @@ def test_qad(tmp_path: Path, num_gpus, create_student, lora_rank, full_rank):
|
||||
["torchrun", f"--nproc_per_node={tp_size}", "quantize.py", "--skip_generate"]
|
||||
+ (["--output_qdq_weight"] if full_rank else []),
|
||||
hf_model_name_or_path=hf_model_path,
|
||||
recipe="general/ptq/nvfp4_default-kv_fp8"
|
||||
recipe=None
|
||||
if is_vlm
|
||||
else "general/ptq/nvfp4_default-kv_fp8"
|
||||
if lora_rank
|
||||
else "general/ptq/fp8_default-kv_fp8",
|
||||
# The VLM quantizes no KV cache, which Megatron-Bridge's export can carry, so only the
|
||||
# language-model-only routing keeps its export below on ModelOpt's exporter.
|
||||
quant_cfg="fp8" if is_vlm else None,
|
||||
lora_rank=lora_rank,
|
||||
tp_size=tp_size,
|
||||
pp_size=1,
|
||||
@@ -256,8 +261,8 @@ def test_qad(tmp_path: Path, num_gpus, create_student, lora_rank, full_rank):
|
||||
for name, value in resumed.items():
|
||||
torch.testing.assert_close(value, uninterrupted[name], rtol=0, atol=0)
|
||||
|
||||
# Step 3: export the distilled quantized checkpoint to a unified HF checkpoint. hf_quant_config.json
|
||||
# is only written for a quantized model, so its presence confirms the quantizers survived QAD.
|
||||
# Step 3: export the distilled quantized checkpoint to a unified HF checkpoint. config.json gets
|
||||
# a quantization_config only for a quantized model, which confirms the quantizers survived QAD.
|
||||
hf_export_path = tmp_path / "qad_hf"
|
||||
export_cmd = extend_cmd_parts(
|
||||
[
|
||||
@@ -271,14 +276,16 @@ def test_qad(tmp_path: Path, num_gpus, create_student, lora_rank, full_rank):
|
||||
pp_size=num_gpus,
|
||||
)
|
||||
run_example_command(export_cmd, example_path="megatron_bridge", setup_free_port=True)
|
||||
assert (hf_export_path / "config.json").exists()
|
||||
assert (hf_export_path / "hf_quant_config.json").exists()
|
||||
quant_config = json.loads((hf_export_path / "config.json").read_text())["quantization_config"]
|
||||
if is_vlm:
|
||||
# A VLM's language-model-only QAD checkpoint holds no vision tower, which only ModelOpt's
|
||||
# exporter copies from the HF source: the export must take that path (its sidecar shows it).
|
||||
assert (hf_export_path / "hf_quant_config.json").exists()
|
||||
if lora_rank:
|
||||
assert not (hf_export_path / "adapter_config.json").exists()
|
||||
index = json.loads((hf_export_path / "model.safetensors.index.json").read_text())
|
||||
assert not any("lora_" in key for key in index["weight_map"])
|
||||
quant_config = json.loads((hf_export_path / "hf_quant_config.json").read_text())
|
||||
assert quant_config["quantization"]["quant_algo"] == "NVFP4"
|
||||
assert quant_config["quant_algo"] == "NVFP4"
|
||||
# A quantized export writes routed experts one per expert while the BF16 reference packs
|
||||
# them, so both sides of that expansion differ from the reference.
|
||||
text_config = json.loads((hf_model_path / "config.json").read_text())
|
||||
@@ -324,5 +331,6 @@ def test_qad(tmp_path: Path, num_gpus, create_student, lora_rank, full_rank):
|
||||
)
|
||||
recipe = yaml.safe_load((fakequant_path / "quant_recipe.yaml").read_text())
|
||||
state = torch.load(fakequant_path / "quantizer_state.pth", weights_only=True)
|
||||
assert any(name.endswith("k_bmm_quantizer") for name in recipe["quantizers"])
|
||||
if not is_vlm: # the VLM quantizes no KV cache
|
||||
assert any(name.endswith("k_bmm_quantizer") for name in recipe["quantizers"])
|
||||
assert {key.rpartition(".")[0] for key in state} <= recipe["quantizers"].keys()
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
# limitations under the License.
|
||||
"""Tests for quantize.py and export_quantized_megatron_to_hf.py scripts."""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
@@ -93,23 +94,25 @@ def _command(script, num_gpus, options, *, snippet=None):
|
||||
"ep_size",
|
||||
),
|
||||
# Dense VLM: only the language model is quantized, vision is copied through. Keeps the
|
||||
# FP8 script-to-checkpoint coverage.
|
||||
# FP8 script-to-checkpoint coverage. No KV cache, so the full-VLM checkpoint exports through
|
||||
# Megatron-Bridge, which must still save the vision tower it restored.
|
||||
(
|
||||
create_tiny_qwen3vl_dir,
|
||||
{},
|
||||
{"recipe": "general/ptq/fp8_default-kv_fp8"},
|
||||
{"quant_cfg": "fp8"},
|
||||
False,
|
||||
"tp_size",
|
||||
"pp_size",
|
||||
"tp_size",
|
||||
),
|
||||
# Mamba hybrid + MoE with grouped-GEMM experts: exported with its experts sharded
|
||||
# across ranks (EP), resharded from the TP-quantized checkpoint.
|
||||
# across ranks (EP), resharded from the TP-quantized checkpoint. No KV cache, so the
|
||||
# grouped experts (weight0, weight1, ...) export through Megatron-Bridge.
|
||||
(
|
||||
create_tiny_nemotron_h_dir,
|
||||
# head_dim=64: FlashAttention-4 (used by TE on sm_120) cannot compile the default head_dim=8
|
||||
{"head_dim": 64},
|
||||
{"recipe": "general/ptq/nvfp4_default-kv_fp8"},
|
||||
{"quant_cfg": "nvfp4"},
|
||||
False,
|
||||
"tp_size",
|
||||
"ep_size",
|
||||
@@ -184,9 +187,25 @@ def test_quantize_and_export(
|
||||
snippet="bridge-export" if use_readme else None,
|
||||
)
|
||||
run_example_command(export_cmd, example_path="megatron_bridge", setup_free_port=True)
|
||||
assert (hf_export_path / "config.json").exists()
|
||||
assert (hf_export_path / "hf_quant_config.json").exists()
|
||||
assert_exported_checkpoint_matches(hf_export_path, hf_model_path)
|
||||
# Either exporter writes the quantization config inline (Megatron-Bridge's writes no
|
||||
# hf_quant_config.json).
|
||||
assert "quantization_config" in json.loads((hf_export_path / "config.json").read_text())
|
||||
is_vlm = "vision_config" in (hf_model_path / "config.json").read_text()
|
||||
if "kv" not in quantization_args.get("recipe", ""):
|
||||
# No KV cache: Megatron-Bridge must have written it, not ModelOpt's exporter as fallback.
|
||||
assert not (hf_export_path / "hf_quant_config.json").exists()
|
||||
if quantization_args.get("quant_cfg") == "nvfp4":
|
||||
# Routed experts (grouped in Megatron) come out NVFP4-packed, not unquantized.
|
||||
exported = load_safetensors_dir(hf_export_path)
|
||||
experts = [k for k in exported if ".experts." in k and k.endswith(".weight")]
|
||||
assert experts, "no routed expert weights exported"
|
||||
for name in experts:
|
||||
assert exported[name].dtype == torch.uint8, name
|
||||
assert {f"{name}_scale", f"{name}_scale_2"} <= exported.keys(), name
|
||||
# Vision tower and projector (model.visual.*) come through bit-exact.
|
||||
assert_exported_checkpoint_matches(
|
||||
hf_export_path, hf_model_path, bit_exact_prefixes=("model.visual.",) if is_vlm else ()
|
||||
)
|
||||
if fake_hub_checkpoint.active:
|
||||
assert (hf_export_path / fake_hub_checkpoint.marker).exists()
|
||||
|
||||
@@ -224,7 +243,6 @@ def test_quantize_and_export(
|
||||
**{fakequant_export_parallelism: num_gpus},
|
||||
)
|
||||
run_example_command(fakequant_cmd, example_path="megatron_bridge", setup_free_port=True)
|
||||
is_vlm = "vision_config" in (hf_model_path / "config.json").read_text()
|
||||
assert_exported_checkpoint_matches(
|
||||
fakequant_path,
|
||||
hf_model_path,
|
||||
@@ -235,5 +253,73 @@ def test_quantize_and_export(
|
||||
recipe = yaml.safe_load((fakequant_path / "quant_recipe.yaml").read_text())
|
||||
quantizers = recipe["quantizers"]
|
||||
state = torch.load(fakequant_path / "quantizer_state.pth", weights_only=True)
|
||||
assert any(name.endswith("k_bmm_quantizer") for name in quantizers)
|
||||
if "kv" in quantization_args.get("recipe", ""):
|
||||
assert any(name.endswith("k_bmm_quantizer") for name in quantizers)
|
||||
assert {key.rpartition(".")[0] for key in state} <= quantizers.keys()
|
||||
|
||||
|
||||
@pytest.mark.timeout(420)
|
||||
def test_bridge_export_matches_modelopt_exporter(tmp_path: Path, num_gpus):
|
||||
"""The CLI's Megatron-Bridge export at TP=num_gpus matches ModelOpt's exporter bit for bit."""
|
||||
hf_model_path = create_tiny_qwen3_dir(
|
||||
tmp_path, with_tokenizer=True, **dict(_DENSE_KWARGS, head_dim=64)
|
||||
)
|
||||
megatron_path = tmp_path / "quantized_megatron"
|
||||
quantize_cmd = _command(
|
||||
"quantize.py",
|
||||
num_gpus,
|
||||
{
|
||||
"hf_model_name_or_path": hf_model_path,
|
||||
# No KV-cache quantizers, which the pinned Megatron-Bridge rejects.
|
||||
"quant_cfg": "nvfp4",
|
||||
"tp_size": num_gpus,
|
||||
"calib_dataset_name": "cnn_dailymail",
|
||||
"calib_num_samples": 4,
|
||||
"calib_batch_size": 2,
|
||||
"seq_length": 16,
|
||||
"export_megatron_path": megatron_path,
|
||||
},
|
||||
)
|
||||
quantize_cmd.append("--skip_generate")
|
||||
run_example_command(quantize_cmd, example_path="megatron_bridge", setup_free_port=True)
|
||||
|
||||
exports = {}
|
||||
for name, options, flags in [
|
||||
("bridge", {"tp_size": num_gpus}, []),
|
||||
("modelopt", {"pp_size": num_gpus}, ["--modelopt_megatron_exporter"]),
|
||||
]:
|
||||
exports[name] = tmp_path / f"hf_{name}"
|
||||
export_cmd = _command(
|
||||
"export_quantized_megatron_to_hf.py",
|
||||
num_gpus,
|
||||
{
|
||||
"hf_model_name_or_path": hf_model_path,
|
||||
"megatron_path": megatron_path,
|
||||
"export_unified_hf_path": exports[name],
|
||||
**options,
|
||||
},
|
||||
)
|
||||
export_cmd.extend(flags)
|
||||
run_example_command(export_cmd, example_path="megatron_bridge", setup_free_port=True)
|
||||
# Only ModelOpt's exporter writes the sidecar: its absence shows the export reached Megatron-Bridge.
|
||||
assert not (exports["bridge"] / "hf_quant_config.json").exists()
|
||||
assert (exports["modelopt"] / "hf_quant_config.json").exists()
|
||||
|
||||
bridge, modelopt = (load_safetensors_dir(exports[name]) for name in ("bridge", "modelopt"))
|
||||
assert bridge.keys() == modelopt.keys()
|
||||
packed = [name for name in bridge if name.endswith(".weight_scale")]
|
||||
assert packed, "no NVFP4-packed weights exported"
|
||||
for name in packed:
|
||||
weight = name.removesuffix("_scale")
|
||||
assert bridge[weight].dtype == torch.uint8
|
||||
assert {f"{weight}_scale_2", name.replace("weight_scale", "input_scale")} <= bridge.keys()
|
||||
for name, tensor in bridge.items():
|
||||
expected = modelopt[name]
|
||||
assert tensor.dtype == expected.dtype and tensor.shape == expected.shape, name
|
||||
bits = (lambda t: t.view(torch.uint8)) if tensor.element_size() == 1 else (lambda t: t)
|
||||
assert torch.equal(bits(tensor), bits(expected)), name
|
||||
configs = [
|
||||
json.loads((exports[name] / "config.json").read_text())["quantization_config"]
|
||||
for name in ("bridge", "modelopt")
|
||||
]
|
||||
assert configs[0]["quant_algo"] == configs[1]["quant_algo"] == "NVFP4"
|
||||
|
||||
Reference in New Issue
Block a user