mirror of
https://github.com/NVIDIA/Model-Optimizer.git
synced 2026-12-06 04:57:17 +08:00
Keep resmoothed FP8 exportable and SequentialMLP direct access rank-local
- Refuse a disabled (resmoothed) pre_quant_scale only on FP4 layers, which format resolution still reads as nvfp4_awq; the functional export refuses active scales only, as FP4 already resolves to an unsupported format there. - Agree over the EP group before a lazy build only when it gathers grouped experts, so SequentialMLP direct access needs no peer. 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:
co-authored by
Claude Opus 5.5
parent
5493bf638b
commit
dc72967485
@@ -364,9 +364,9 @@ def _resolve_quantized_weight_export_inputs(
|
||||
f"Functional export does not support rotated quantizers for {weight_name!r}"
|
||||
)
|
||||
# AWQ / SmoothQuant fold its inverse into the weight; a disabled quantizer still applies it.
|
||||
# A disabled scale (after resmoothing) counts too, as format resolution does for FP4.
|
||||
# A scale disabled by resmoothing is fine here, except FP4 resolves it to unsupported AWQ.
|
||||
if any(
|
||||
isinstance(quantizer, TensorQuantizer) and hasattr(quantizer, "_pre_quant_scale")
|
||||
isinstance(quantizer, TensorQuantizer) and quantizer.pre_quant_scale is not None
|
||||
for quantizer in (weight_quantizer, input_quantizer)
|
||||
):
|
||||
raise _UnsupportedQuantizedWeightExportFormatError(
|
||||
|
||||
@@ -68,6 +68,7 @@ from .quant_format import (
|
||||
QUANTIZATION_FP8_PB_WO,
|
||||
QUANTIZATION_NONE,
|
||||
QUANTIZATION_NVFP4,
|
||||
QUANTIZATION_NVFP4_AWQ,
|
||||
QUANTIZATION_W4A16_MXFP4,
|
||||
QUANTIZATION_W4A16_NVFP4,
|
||||
)
|
||||
@@ -656,10 +657,15 @@ class GPTModelExporter:
|
||||
def _get_state_dict(self):
|
||||
model = self.model
|
||||
|
||||
# Before caching anything. Grouped experts are gathered over the EP group below, so agree
|
||||
# there; nothing else in this build is collective.
|
||||
# Before caching anything. Only grouped experts are gathered (over the EP group) in this
|
||||
# build, so agree there; every other layout builds rank-locally. EP peers hold the same
|
||||
# layers, so they take the same branch.
|
||||
found = self._has_pre_quant_scale(draft=False)
|
||||
if torch.distributed.is_initialized() and get_expert_model_parallel_world_size() > 1:
|
||||
if (
|
||||
torch.distributed.is_initialized()
|
||||
and get_expert_model_parallel_world_size() > 1
|
||||
and any(hasattr(m, "num_gemms") for m in model.modules())
|
||||
):
|
||||
flag = torch.tensor([int(found)], device=torch.cuda.current_device())
|
||||
torch.distributed.all_reduce(
|
||||
flag, op=torch.distributed.ReduceOp.MAX, group=get_expert_model_parallel_group()
|
||||
@@ -1377,13 +1383,18 @@ class GPTModelExporter:
|
||||
"""Whether ``module`` holds a pre_quant_scale, which the export would drop.
|
||||
|
||||
AWQ / SmoothQuant fold its inverse into the weight, and a disabled input quantizer still
|
||||
applies it, so even weight-only AWQ (W4A16) would export wrong weights. A disabled scale
|
||||
(after resmoothing) counts too: format resolution still reads its FP4 layers as AWQ.
|
||||
applies it, so even weight-only AWQ (W4A16) would export wrong weights. A scale disabled
|
||||
by resmoothing only counts on FP4 layers, which format resolution then reads as AWQ, a
|
||||
format this exporter writes no quantization config for.
|
||||
"""
|
||||
# Every quantizer in the subtree, not just ``input_quantizer``: grouped and fused modules
|
||||
# name theirs differently.
|
||||
return any(
|
||||
isinstance(m, TensorQuantizer) and hasattr(m, "_pre_quant_scale")
|
||||
(isinstance(m, TensorQuantizer) and m.pre_quant_scale is not None)
|
||||
or (
|
||||
hasattr(getattr(m, "input_quantizer", None), "_pre_quant_scale")
|
||||
and self._get_quantization_format(m) == QUANTIZATION_NVFP4_AWQ
|
||||
)
|
||||
for m in module.modules()
|
||||
)
|
||||
|
||||
|
||||
@@ -63,7 +63,6 @@ from modelopt.torch.export.quantized_weight_export import (
|
||||
)
|
||||
from modelopt.torch.export.unified_export_megatron import GPTModelExporter
|
||||
from modelopt.torch.quantization.config import QuantizerAttributeConfig
|
||||
from modelopt.torch.quantization.model_calib import disable_pre_quant_scale_and_resmooth
|
||||
from modelopt.torch.quantization.nn import TensorQuantizer
|
||||
from modelopt.torch.speculative.eagle.default_config import default_eagle_config
|
||||
from modelopt.torch.speculative.plugins.megatron_eagle import _DynamicEagleGPTModel
|
||||
@@ -422,6 +421,14 @@ def _test_sequential_experts_export_at_ep(model_dir, tmp_path, rank, size):
|
||||
export_mcore_gpt_to_hf(model, model_dir, dtype=torch.bfloat16, export_dir=str(export_dir))
|
||||
assert not stale.exists()
|
||||
|
||||
# Direct access to SequentialMLP experts stays rank-local: it needs no peer.
|
||||
exporter = GPTModelExporter(model, model_dir)
|
||||
if rank == 0:
|
||||
with patch.object(
|
||||
torch.distributed, "all_reduce", side_effect=AssertionError("waits for a peer")
|
||||
):
|
||||
assert exporter.layer_state_dicts
|
||||
|
||||
# Each rank's experts must land under their global ids, from whichever shard holds them.
|
||||
weight_map = json.loads((export_dir / "model.safetensors.index.json").read_text())["weight_map"]
|
||||
for layer_id, layer in enumerate(model.decoder.layers):
|
||||
@@ -502,15 +509,6 @@ def _test_export_rejects_weight_only_awq(model_dir, tmp_path, rank, size):
|
||||
with pytest.raises(NotImplementedError, match="pre_quant_scale"):
|
||||
exporter.layer_state_dicts
|
||||
|
||||
# Resmoothing keeps a disabled scale, which FP4 format resolution would still read as AWQ.
|
||||
for module in model.modules():
|
||||
if getattr(getattr(module, "input_quantizer", None), "pre_quant_scale", None) is not None:
|
||||
disable_pre_quant_scale_and_resmooth(module)
|
||||
with pytest.raises(NotImplementedError, match="pre_quant_scale"):
|
||||
export_mcore_gpt_to_hf(
|
||||
model, model_dir, dtype=torch.bfloat16, export_dir=str(tmp_path / "resmoothed")
|
||||
)
|
||||
|
||||
# A draft-only export writes none of the base's scaled weights, so a BF16 draft passes. Only
|
||||
# the check runs: the EAGLE draft export itself currently fails (EagleModule has no ``fc``).
|
||||
model = mtsp.convert(
|
||||
@@ -553,6 +551,26 @@ def test_export_pp2_rejects_pre_quant_scale_on_one_stage(dist_workers_size_2, tm
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("num_bits", "refused"), [((2, 1), True), ((4, 3), False)])
|
||||
def test_retained_pre_quant_scale_refused_only_for_fp4(num_bits, refused):
|
||||
"""Resmoothing keeps a disabled scale; FP4 format resolution still reads that layer as AWQ."""
|
||||
linear = torch.nn.Linear(32, 16, bias=False)
|
||||
linear.weight_quantizer = TensorQuantizer(
|
||||
QuantizerAttributeConfig(
|
||||
num_bits=num_bits,
|
||||
block_sizes={-1: 16, "type": "dynamic", "scale_bits": (4, 3)}
|
||||
if num_bits == (2, 1)
|
||||
else None,
|
||||
)
|
||||
)
|
||||
linear.input_quantizer = TensorQuantizer()
|
||||
linear.input_quantizer.disable()
|
||||
linear.input_quantizer.pre_quant_scale = torch.ones(32)
|
||||
linear.input_quantizer._enable_pre_quant_scale = False
|
||||
exporter = object.__new__(GPTModelExporter)
|
||||
assert exporter._drops_pre_quant_scale(linear) is refused
|
||||
|
||||
|
||||
def _test_direct_state_ep2_rejects_pre_quant_scale_on_one_rank(model_dir, rank, size):
|
||||
config = transformers.AutoConfig.from_pretrained(model_dir)
|
||||
initialize_for_megatron(expert_model_parallel_size=size)
|
||||
|
||||
@@ -37,6 +37,10 @@ from modelopt.torch.export.quantized_weight_export import (
|
||||
split_quantized_weight_export_state,
|
||||
)
|
||||
from modelopt.torch.quantization.config import QuantizerAttributeConfig
|
||||
from modelopt.torch.quantization.model_calib import (
|
||||
disable_pre_quant_scale_and_resmooth,
|
||||
max_calibrate,
|
||||
)
|
||||
from modelopt.torch.quantization.nn import (
|
||||
GroupedQuantizer,
|
||||
NVFP4StaticQuantizer,
|
||||
@@ -470,21 +474,39 @@ def test_export_allows_disabled_input_quantizer_that_rotates_back():
|
||||
assert get_quantized_weight_export_spec(module).quantization_format == "w4a16_mxfp4"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("enabled", [True, False])
|
||||
@pytest.mark.parametrize("quantization_format", ["fp8_pc_pt", "fp8_pb_wo"])
|
||||
def test_export_rejects_pre_quant_scale(quantization_format, enabled):
|
||||
"""FP8 formats don't otherwise check pre_quant_scale, with or without input quantization.
|
||||
|
||||
A scale disabled by resmoothing is refused too, as FP4 format resolution reads it as AWQ.
|
||||
"""
|
||||
def test_export_rejects_pre_quant_scale(quantization_format):
|
||||
"""FP8 formats don't otherwise check pre_quant_scale, with or without input quantization."""
|
||||
module = _capture_linear(quantization_format)
|
||||
module.input_quantizer.pre_quant_scale = torch.full((256,), 2.0)
|
||||
module.input_quantizer._enable_pre_quant_scale = enabled
|
||||
|
||||
with pytest.raises(NotImplementedError, match="pre_quant_scale"):
|
||||
get_quantized_weight_export_spec(module)
|
||||
|
||||
|
||||
def test_resmoothed_fp8_exports_as_if_never_smoothed():
|
||||
"""Resmoothing keeps a disabled pre_quant_scale, which an FP8 export may ignore."""
|
||||
cfg = copy.deepcopy(mtq.FP8_2D_BLOCKWISE_WEIGHT_ONLY_CFG)
|
||||
reference = mtq.quantize(nn.Linear(256, 128, bias=False), cfg)
|
||||
module = mtq.quantize(nn.Linear(256, 128, bias=False), cfg)
|
||||
with torch.no_grad():
|
||||
module.weight.copy_(reference.weight / 2) # what AWQ folds in for a scale of 2
|
||||
module.input_quantizer.pre_quant_scale = torch.full((256,), 2.0)
|
||||
disable_pre_quant_scale_and_resmooth(module)
|
||||
max_calibrate(reference, lambda m: m.weight_quantizer(m.weight))
|
||||
|
||||
assert get_quantized_weight_export_spec(module) == get_quantized_weight_export_spec(reference)
|
||||
exported = export_quantized_weight_tensors(
|
||||
module.weight, capture_quantized_weight_export_state(module), torch.bfloat16
|
||||
)
|
||||
expected = export_quantized_weight_tensors(
|
||||
reference.weight, capture_quantized_weight_export_state(reference), torch.bfloat16
|
||||
)
|
||||
assert exported.keys() == expected.keys()
|
||||
for name, tensor in expected.items():
|
||||
assert torch.equal(exported[name], tensor), name
|
||||
|
||||
|
||||
def test_export_rejects_sequential_input_quantizers():
|
||||
module = _capture_linear("w4a16_mxfp4")
|
||||
enabled = TensorQuantizer(QuantizerAttributeConfig(num_bits=(4, 3)))
|
||||
|
||||
Reference in New Issue
Block a user