mirror of
https://github.com/NVIDIA/Model-Optimizer.git
synced 2026-12-06 04:57:17 +08:00
Address CodeRabbit: non-raising scale check, per-mode cache, MTP scope
- Read a retained scale's FP4 / GGML weight quantizer directly instead of calling the format resolver, which raises on GGML before ranks agree. - Record whether the state caches hold the base or the draft build, so one read never returns the other's tensors or skips its check; a failed build is rebuilt. - Scope the lazy base build's scale check and EP trigger to what it writes, leaving out the live MTP (still checked by save_pretrained). 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
dc72967485
commit
a093f418f0
@@ -40,6 +40,7 @@ from modelopt.torch.quantization.nn.modules.tensor_quantizer import (
|
||||
GroupedQuantizer,
|
||||
TensorQuantizer,
|
||||
)
|
||||
from modelopt.torch.quantization.utils import representative_weight_quantizer
|
||||
from modelopt.torch.utils import import_plugin, warn_rank_0
|
||||
from modelopt.torch.utils.distributed import gather_state_dicts
|
||||
from modelopt.torch.utils.plugins.hf_checkpoint_utils import (
|
||||
@@ -68,7 +69,6 @@ from .quant_format import (
|
||||
QUANTIZATION_FP8_PB_WO,
|
||||
QUANTIZATION_NONE,
|
||||
QUANTIZATION_NVFP4,
|
||||
QUANTIZATION_NVFP4_AWQ,
|
||||
QUANTIZATION_W4A16_MXFP4,
|
||||
QUANTIZATION_W4A16_NVFP4,
|
||||
)
|
||||
@@ -184,6 +184,8 @@ class GPTModelExporter:
|
||||
|
||||
self._state_dict = OrderedDict()
|
||||
self._layer_state_dicts = OrderedDict()
|
||||
# Which build ("base" / "draft") the caches hold; None until one completes.
|
||||
self._state_dict_owner: str | None = None
|
||||
# Keys of the SequentialMLP experts held by this rank (all ranks' differ at EP>1).
|
||||
self._local_expert_keys: set[str] = set()
|
||||
self._hf_pretrained_model_name = pretrained_model_name_or_path
|
||||
@@ -308,7 +310,7 @@ class GPTModelExporter:
|
||||
save_directory: str | os.PathLike,
|
||||
):
|
||||
"""Save a EAGLE or Medusa checkpoints which can be deployed by vLLM and TensorRT-LLM."""
|
||||
if self._any_rank(self._has_pre_quant_scale(draft=True)):
|
||||
if self._any_rank(self._has_pre_quant_scale(self._export_roots(draft=True))):
|
||||
raise NotImplementedError(_PRE_QUANT_SCALE_UNSUPPORTED)
|
||||
# We use the last PP rank to write the config because
|
||||
# medusa_heads and eagle_module only exist in the last stage.
|
||||
@@ -390,7 +392,7 @@ class GPTModelExporter:
|
||||
"disable quantization of the MTP layer (e.g. '*mtp*')."
|
||||
)
|
||||
# Pipeline stages hold different layers, so agree before any rank raises.
|
||||
if self._any_rank(self._has_pre_quant_scale(draft=False)):
|
||||
if self._any_rank(self._has_pre_quant_scale(self._export_roots(draft=False))):
|
||||
raise NotImplementedError(_PRE_QUANT_SCALE_UNSUPPORTED)
|
||||
# One layer-shard writer per pipeline stage: other TP / DP / EP ranks hold the same layers
|
||||
# (EP>1 ranks hold no gathered experts at all), and writing them too would race on the same
|
||||
@@ -634,37 +636,52 @@ class GPTModelExporter:
|
||||
@property
|
||||
def state_dict(self):
|
||||
"""Return the real quantized state_dict of the base model."""
|
||||
if len(self._state_dict) == 0:
|
||||
self._get_state_dict()
|
||||
self._build_state_dicts("base")
|
||||
return self._state_dict
|
||||
|
||||
@property
|
||||
def layer_state_dicts(self):
|
||||
if len(self._layer_state_dicts) == 0:
|
||||
self._get_state_dict()
|
||||
self._build_state_dicts("base")
|
||||
return self._layer_state_dicts
|
||||
|
||||
@property
|
||||
def extra_state_dict(self):
|
||||
if len(self._state_dict) == 0:
|
||||
self._build_state_dicts("draft")
|
||||
return self._state_dict
|
||||
|
||||
def _build_state_dicts(self, owner: str):
|
||||
"""Fill the caches with the ``owner`` ("base" / "draft") export unless they already hold it.
|
||||
|
||||
Both builds write ``_state_dict``, so a cache holding the other one (or a failed build) is
|
||||
rebuilt rather than returned.
|
||||
"""
|
||||
if self._state_dict_owner == owner:
|
||||
return
|
||||
self._state_dict_owner = None
|
||||
self._state_dict, self._layer_state_dicts = OrderedDict(), OrderedDict()
|
||||
if owner == "base":
|
||||
self._get_state_dict()
|
||||
else:
|
||||
# Before caching anything. Drafts sit on the last stage and gather nothing.
|
||||
if self._has_pre_quant_scale(draft=True):
|
||||
if self._has_pre_quant_scale(self._export_roots(draft=True)):
|
||||
raise NotImplementedError(_PRE_QUANT_SCALE_UNSUPPORTED)
|
||||
self._get_medusa_heads_state_dict()
|
||||
self._get_eagle_module_state_dict()
|
||||
return self._state_dict
|
||||
self._state_dict_owner = owner
|
||||
|
||||
def _get_state_dict(self):
|
||||
model = self.model
|
||||
|
||||
# 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)
|
||||
# Before caching anything, over what this build writes (the live MTP is exported by
|
||||
# save_pretrained separately). Only grouped experts are gathered (over the EP group) here,
|
||||
# so agree there; every other layout builds rank-locally. EP peers hold the same layers,
|
||||
# so they take the same branch.
|
||||
roots = self._export_roots(draft=False, mtp=False)
|
||||
found = self._has_pre_quant_scale(roots)
|
||||
if (
|
||||
torch.distributed.is_initialized()
|
||||
and get_expert_model_parallel_world_size() > 1
|
||||
and any(hasattr(m, "num_gemms") for m in model.modules())
|
||||
and any(hasattr(m, "num_gemms") for root in roots for m in root.modules())
|
||||
):
|
||||
flag = torch.tensor([int(found)], device=torch.cuda.current_device())
|
||||
torch.distributed.all_reduce(
|
||||
@@ -1384,31 +1401,46 @@ class GPTModelExporter:
|
||||
|
||||
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 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.
|
||||
by resmoothing only counts on FP4 layers, which format resolution reads as AWQ (a format
|
||||
this exporter writes no quantization config for), and GGML ones, which it refuses. Read
|
||||
from the weight quantizer directly: the format resolver raises on the GGML case, which
|
||||
would skip the cross-rank agreement.
|
||||
"""
|
||||
|
||||
def retained_fp4_or_ggml(m):
|
||||
weight_quantizer = representative_weight_quantizer(m)
|
||||
return (
|
||||
hasattr(getattr(m, "input_quantizer", None), "_pre_quant_scale")
|
||||
and isinstance(weight_quantizer, TensorQuantizer)
|
||||
and weight_quantizer.is_enabled
|
||||
and (
|
||||
weight_quantizer.num_bits == (2, 1) or weight_quantizer.num_bits in GGML_FORMATS
|
||||
)
|
||||
)
|
||||
|
||||
# Every quantizer in the subtree, not just ``input_quantizer``: grouped and fused modules
|
||||
# name theirs differently.
|
||||
return any(
|
||||
(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
|
||||
)
|
||||
or retained_fp4_or_ggml(m)
|
||||
for m in module.modules()
|
||||
)
|
||||
|
||||
def _has_pre_quant_scale(self, draft: bool) -> bool:
|
||||
"""Whether this rank's modules that the export writes hold a pre_quant_scale.
|
||||
def _export_roots(self, draft: bool, mtp: bool = True) -> list[torch.nn.Module]:
|
||||
"""This rank's top-level modules that an export writes.
|
||||
|
||||
``draft`` selects the EAGLE / Medusa modules (``save_pretrained_extra_modules``) rather
|
||||
than the base model (``save_pretrained``); neither export writes the other.
|
||||
than the base model (``save_pretrained``); neither export writes the other. ``mtp=False``
|
||||
leaves out the live MTP, which only ``save_pretrained`` writes, not the lazy base build.
|
||||
"""
|
||||
return any(
|
||||
self._drops_pre_quant_scale(module)
|
||||
return [
|
||||
module
|
||||
for name, module in self.model.named_children()
|
||||
if (name in ("eagle_module", "medusa_heads")) == draft
|
||||
)
|
||||
if (name in ("eagle_module", "medusa_heads")) == draft and (mtp or name != "mtp")
|
||||
]
|
||||
|
||||
def _has_pre_quant_scale(self, roots: list[torch.nn.Module]) -> bool:
|
||||
return any(self._drops_pre_quant_scale(module) for module in roots)
|
||||
|
||||
def _any_rank_uses_iq_quantization(self) -> bool:
|
||||
"""Whether any rank's local stage holds a GGML layer.
|
||||
|
||||
@@ -515,8 +515,8 @@ def _test_export_rejects_weight_only_awq(model_dir, tmp_path, rank, size):
|
||||
model, [("eagle", {"eagle_architecture_config": deepcopy(default_eagle_config)})]
|
||||
)
|
||||
exporter = GPTModelExporter(model, model_dir, export_extra_modules=True)
|
||||
assert not exporter._has_pre_quant_scale(draft=True)
|
||||
assert exporter._has_pre_quant_scale(draft=False)
|
||||
assert not exporter._has_pre_quant_scale(exporter._export_roots(draft=True))
|
||||
assert exporter._has_pre_quant_scale(exporter._export_roots(draft=False))
|
||||
|
||||
|
||||
def test_export_rejects_weight_only_awq(dist_workers_size_1, tmp_path):
|
||||
@@ -551,26 +551,98 @@ 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,
|
||||
)
|
||||
)
|
||||
_GGML_QFORMAT = GGML_FORMAT_NAMES[0]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("weight_cfg", "refused"),
|
||||
[
|
||||
pytest.param(
|
||||
{"num_bits": (2, 1), "block_sizes": {-1: 16, "type": "dynamic", "scale_bits": (4, 3)}},
|
||||
True,
|
||||
id="fp4",
|
||||
),
|
||||
pytest.param({"num_bits": (4, 3)}, False, id="fp8"),
|
||||
pytest.param(
|
||||
{
|
||||
"num_bits": _GGML_QFORMAT,
|
||||
"block_sizes": {-1: getattr(ggml, f"{_GGML_QFORMAT.upper()}_BLOCK_SIZE")},
|
||||
"backend": "ggml",
|
||||
},
|
||||
True,
|
||||
id="ggml",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_retained_pre_quant_scale_refused_where_format_reads_it(weight_cfg, refused):
|
||||
"""Resmoothing keeps a disabled scale, which FP4 resolution reads as AWQ and GGML refuses.
|
||||
|
||||
The check must answer rather than raise as the GGML format resolver does, so that the ranks
|
||||
still agree before anyone raises.
|
||||
"""
|
||||
linear = torch.nn.Linear(256, 2, bias=False)
|
||||
linear.weight_quantizer = TensorQuantizer(QuantizerAttributeConfig(**weight_cfg))
|
||||
linear.input_quantizer = TensorQuantizer()
|
||||
linear.input_quantizer.disable()
|
||||
linear.input_quantizer.pre_quant_scale = torch.ones(32)
|
||||
linear.input_quantizer.pre_quant_scale = torch.ones(256)
|
||||
linear.input_quantizer._enable_pre_quant_scale = False
|
||||
exporter = object.__new__(GPTModelExporter)
|
||||
assert exporter._drops_pre_quant_scale(linear) is refused
|
||||
|
||||
|
||||
def test_base_and_draft_state_reads_keep_separate_caches():
|
||||
"""Both builds write one cache, so a read must rebuild rather than return the other's."""
|
||||
exporter = object.__new__(GPTModelExporter)
|
||||
exporter._state_dict, exporter._layer_state_dicts = {}, {}
|
||||
exporter._state_dict_owner = None
|
||||
exporter.model = torch.nn.Module() # no draft or base modules to check for scales
|
||||
|
||||
def build_base():
|
||||
exporter._state_dict["base.weight"] = torch.zeros(1)
|
||||
exporter._layer_state_dicts[1] = exporter._state_dict
|
||||
|
||||
def build_draft():
|
||||
exporter._state_dict["eagle_module.fc.weight"] = torch.zeros(1)
|
||||
|
||||
with (
|
||||
patch.object(exporter, "_get_state_dict", build_base),
|
||||
patch.object(exporter, "_get_eagle_module_state_dict", build_draft),
|
||||
patch.object(exporter, "_get_medusa_heads_state_dict", lambda: None),
|
||||
):
|
||||
assert list(exporter.extra_state_dict) == ["eagle_module.fc.weight"]
|
||||
assert list(exporter.state_dict) == ["base.weight"]
|
||||
assert list(exporter.extra_state_dict) == ["eagle_module.fc.weight"]
|
||||
assert list(exporter.layer_state_dicts[1]) == ["base.weight"]
|
||||
|
||||
|
||||
def _test_direct_state_ignores_mtp_only_pre_quant_scale(model_dir, tmp_path, rank, size):
|
||||
model = _get_tiny_llama_gpt(model_dir, tensor_model_parallel_size=size, mtp_num_layers=1)
|
||||
model = mtq.quantize(model, {**mtq.INT4_AWQ_CFG, "algorithm": "max"}, get_forward(model))
|
||||
mtp_linear = next(
|
||||
m
|
||||
for m in model.mtp.modules()
|
||||
if isinstance(getattr(m, "input_quantizer", None), TensorQuantizer)
|
||||
and getattr(m, "weight", None) is not None
|
||||
)
|
||||
mtp_linear.input_quantizer.pre_quant_scale = torch.ones(
|
||||
mtp_linear.weight.shape[1], device="cuda"
|
||||
)
|
||||
# The lazy base build doesn't write the live MTP, so the scale doesn't block it ...
|
||||
assert GPTModelExporter(model, model_dir).layer_state_dicts
|
||||
# ... but save_pretrained exports the MTP too, so it refuses.
|
||||
with pytest.raises(NotImplementedError, match="pre_quant_scale"):
|
||||
export_mcore_gpt_to_hf(
|
||||
model, model_dir, dtype=torch.bfloat16, export_dir=str(tmp_path / "export")
|
||||
)
|
||||
|
||||
|
||||
def test_direct_state_ignores_mtp_only_pre_quant_scale(dist_workers_size_1, tmp_path):
|
||||
model_dir = create_tiny_llama_dir(tmp_path, hidden_size=128, intermediate_size=256)
|
||||
dist_workers_size_1.run(
|
||||
partial(_test_direct_state_ignores_mtp_only_pre_quant_scale, model_dir, tmp_path)
|
||||
)
|
||||
|
||||
|
||||
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)
|
||||
|
||||
Reference in New Issue
Block a user