diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 78c396dcb7d..7e12d3ce83b 100755 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -30,6 +30,7 @@ Changelog *Quantization - Export & Deployment* - ``examples/hf_ptq/convert_ggml_to_int8.py`` now also converts GGML exports that hold other formats (FP8, NVFP4, KV cache quantization): their GGML layers become ModelOpt ``INT8_PB_WO`` layers beside the rest of the export, which vLLM newer than 0.34.0 serves. Exports with only GGML layers still become compressed-tensors, and fused MoE experts now convert in both. +- ``register_quant_backend`` takes an optional ``export_converter``: a function that converts, in place, the quantizers of a custom quantization backend into ones that the export writes, such as static NVFP4 weight quantizers holding the backend's scales. The Hugging Face checkpoint exports of a transformers model (``export_hf_checkpoint``, ``examples/llm_qat/export.py`` and ``export_speculative_decoding``) run it before they build the quantization config and pack the weights, so such a model exports without a conversion step of its own. A sharded (FSDP2 or expert-parallel), offloaded or layerwise export refuses such a model. *Quantization - Recipes* diff --git a/modelopt/torch/export/layerwise_export.py b/modelopt/torch/export/layerwise_export.py index 2ff3abe966f..0f49cabc713 100644 --- a/modelopt/torch/export/layerwise_export.py +++ b/modelopt/torch/export/layerwise_export.py @@ -48,6 +48,7 @@ from .quant_utils import ( ) from .registry import ExportContext, PrepareMoEInputsRegistry from .unified_export_hf import ( + _backends_to_convert, _dispatch_export_handler, _fuse_shared_input_modules, _prepare_moe_inputs, @@ -138,6 +139,12 @@ def assert_formats_supported(module: nn.Module, scope: str) -> None: def assert_layerwise_export_supported(model: nn.Module) -> None: """Raise unless per-layer export is valid for this model.""" + if backends := _backends_to_convert(model): + raise NotImplementedError( + f"layerwise export does not run the export converters that the quantizers of the " + f"backends {sorted(backends)} need. Export the model with export_hf_checkpoint() " + "after a calibration without layerwise export." + ) assert_formats_supported(model, "before calibration") tied = _tied_quantized_modules(model) diff --git a/modelopt/torch/export/unified_export_hf.py b/modelopt/torch/export/unified_export_hf.py index 070415e1945..2ab6999bd43 100644 --- a/modelopt/torch/export/unified_export_hf.py +++ b/modelopt/torch/export/unified_export_hf.py @@ -91,6 +91,7 @@ from modelopt.torch.quantization.algorithms import ( ) from modelopt.torch.quantization.ggml import GGML_FORMAT_REGISTRY from modelopt.torch.quantization.nn import SequentialQuantizer, TensorQuantizer +from modelopt.torch.quantization.nn.modules.tensor_quantizer import _QUANT_BACKEND_EXPORT_CONVERTERS from modelopt.torch.quantization.qtensor import MXFP8QTensor, NVFP4QTensor from modelopt.torch.quantization.qtensor.base_qtensor import QTensorWrapper from modelopt.torch.quantization.qtensor.nvfp4_tensor import ( @@ -1037,12 +1038,56 @@ def _process_quantized_modules( _dispatch_export_handler(name, sub_module, ctx) +def _backends_to_convert(model: nn.Module) -> set[str]: + """The backends with an export converter that an enabled quantizer of ``model`` uses.""" + return { + module.backend + for module in model.modules() + if isinstance(module, TensorQuantizer) + and module.is_enabled + and getattr(module, "backend", None) in _QUANT_BACKEND_EXPORT_CONVERTERS + } + + +def _convert_custom_backends(model: nn.Module) -> None: + """Run the export converter of each custom backend that the quantizers of ``model`` use. + + See ``export_converter`` of :func:`~modelopt.torch.quantization.nn.register_quant_backend`. + Each converter runs once, and only while an enabled quantizer still uses its backend, so a + converter that also converts another backend's quantizers leaves nothing for that backend's + converter. + + A sharded or offloaded model is refused before any converter runs. Under FSDP2 every rank + holds the same quantizers, so every rank refuses; the expert-parallel export runs this inside + :func:`_process_together`, which raises on every rank if any rank fails. + """ + if not _QUANT_BACKEND_EXPORT_CONVERTERS or not (backends := _backends_to_convert(model)): + return + if any(_hf_shard_flags(model)) or has_accelerate_offload(model): + raise NotImplementedError( + f"The quantizers of the backends {sorted(backends)} need their export converters, " + "which the export does not run on a sharded (FSDP2 or expert-parallel) or offloaded " + "model. Export the model from a single process, without offload." + ) + converted: set[str] = set() + while pending := sorted(_backends_to_convert(model) - converted): + converted.add(pending[0]) + _QUANT_BACKEND_EXPORT_CONVERTERS[pending[0]](model) + if left := _backends_to_convert(model): + raise RuntimeError( + f"Enabled quantizers of the backends {sorted(left)} are left after their export " + "converters ran. A converter must convert or disable every enabled quantizer of its " + "backend." + ) + + def _prepare_model_for_export(model, dtype, is_modelopt_qlora): """Run the shared export setup. Packing the weights is a separate step. Both export paths call this so they cannot drift. Returns the dtype, the tied-weight map and the quant config. """ + _convert_custom_backends(model) dtype = _resolve_export_dtype(model, dtype) # One tied-weight map for the whole export (amax sync + final dedup in postprocess_state_dict). # Sourced from HF's name-based all_tied_weights_keys, so it is correct even under FSDP/offload. @@ -1180,7 +1225,10 @@ def _export_transformers_checkpoint( quant_config: config information to export hf_quant_cfg.json Raises: - NotImplementedError: if the model has accelerate offload hooks. + NotImplementedError: if the model has accelerate offload hooks, or is sharded or offloaded + and an enabled quantizer uses a custom backend with an export converter. + RuntimeError: if an enabled quantizer of a backend with an export converter is left after + the converters run. """ dtype, tied_map, quant_config = _prepare_model_for_export(model, dtype, is_modelopt_qlora) diff --git a/modelopt/torch/export/unified_export_hf_streaming.py b/modelopt/torch/export/unified_export_hf_streaming.py index 69cdc53117f..a0caed847b2 100644 --- a/modelopt/torch/export/unified_export_hf_streaming.py +++ b/modelopt/torch/export/unified_export_hf_streaming.py @@ -52,6 +52,7 @@ from .quant_utils import ( ) from .registry import ExportContext from .unified_export_hf import ( + _convert_custom_backends, _dispatch_export_handler, _prepare_model_for_export, _prepare_moe_inputs, @@ -343,13 +344,19 @@ def _export_transformers_checkpoint_streaming( ``quantization_config`` into ``config.json``. Raises: - NotImplementedError: if the model's conversion mapping regroups tensors. + NotImplementedError: if the model's conversion mapping regroups tensors, or if an enabled + quantizer uses a custom backend with an export converter, which this export does not + run (see ``register_quant_backend``). RuntimeError: if decoder layers cannot be discovered for layer-wise materialization. """ # Deferred: modelopt.torch.quantization imports modelopt.torch.export, so importing the # per-model PTQ module at module scope here would risk an import cycle. from modelopt.torch.models.step3p5.modeling_ptq import _reconstruct_fused_moe_linear + # Refuses a model that needs an export converter, since it is offloaded, before anything is + # written. + _convert_custom_backends(model) + export_dir = Path(export_dir) # Materialization dispatch walks the module tree from the root; without these maps each # call re-derives them, which is O(N^2) over a MoE model's expert modules. diff --git a/modelopt/torch/quantization/nn/modules/tensor_quantizer.py b/modelopt/torch/quantization/nn/modules/tensor_quantizer.py index 9159e7f0885..8b2c378435a 100644 --- a/modelopt/torch/quantization/nn/modules/tensor_quantizer.py +++ b/modelopt/torch/quantization/nn/modules/tensor_quantizer.py @@ -76,11 +76,17 @@ __all__ = [ QuantBackendEntrypoint = Callable[[torch.Tensor, "TensorQuantizer"], torch.Tensor] +QuantBackendExportConverter = Callable[[nn.Module], None] _QUANT_FUNCTIONAL_BACKENDS: dict[str, QuantBackendEntrypoint] = {} +_QUANT_BACKEND_EXPORT_CONVERTERS: dict[str, QuantBackendExportConverter] = {} -def register_quant_backend(name: str, entrypoint: QuantBackendEntrypoint) -> None: +def register_quant_backend( + name: str, + entrypoint: QuantBackendEntrypoint, + export_converter: QuantBackendExportConverter | None = None, +) -> None: """Register a custom quantization backend. Args: @@ -90,14 +96,38 @@ def register_quant_backend(name: str, entrypoint: QuantBackendEntrypoint) -> Non See :class:`modelopt.torch.quantization.config.QuantizerAttributeConfig` for details on choosing from the registered backends via the ``backend`` and ``backend_extra_args`` fields. + export_converter: Optional. A callable that takes a model and, in place, converts every + enabled quantizer of this backend into a built-in one that the export writes (such as + a static NVFP4 weight quantizer holding the backend's scales) or disables it, since the + export does not know the backend's format. The Hugging Face checkpoint exports of a + transformers model call it as they prepare a model with an enabled quantizer of this + backend, before they build the quantization config and pack the weights: + ``export_hf_checkpoint``, ``examples/llm_qat/export.py`` and + ``export_speculative_decoding``, which exports the whole model before it keeps the + draft model's weights. A sharded (FSDP2 or expert-parallel), offloaded or layerwise + export refuses such a model instead, before any converter runs, and the export raises + if an enabled quantizer of a backend with a converter is left after the converters + run. Like the rest of the export, the converter changes the model in place, and it + returns nothing, since the caller of the export keeps the same model. The + converted quantizers are then exported as any built-in ones: for example, NVFP4 layers + that take the same input, such as q/k/v or gate/up, get the largest of their global + scales so that serving can fuse them, and the block scales of the others are + requantized to it, so a converter that needs exact scales should give those layers + one global amax. """ if not isinstance(name, str) or not name: raise ValueError("Backend name must be a non-empty string.") if not callable(entrypoint): raise TypeError("Entrypoint must be callable.") + if export_converter is not None and not callable(export_converter): + raise TypeError("Export converter must be callable.") if name in _QUANT_FUNCTIONAL_BACKENDS: warnings.warn(f"Overwriting existing backend: {name}") _QUANT_FUNCTIONAL_BACKENDS[name] = entrypoint + if export_converter is None: + _QUANT_BACKEND_EXPORT_CONVERTERS.pop(name, None) + else: + _QUANT_BACKEND_EXPORT_CONVERTERS[name] = export_converter def unregister_quant_backend(name: str) -> None: @@ -109,6 +139,7 @@ def unregister_quant_backend(name: str) -> None: if not isinstance(name, str) or not name: raise ValueError("Backend name must be a non-empty string.") _QUANT_FUNCTIONAL_BACKENDS.pop(name, None) + _QUANT_BACKEND_EXPORT_CONVERTERS.pop(name, None) def is_registered_quant_backend(name: str) -> bool: diff --git a/tests/unit/torch/export/test_custom_backend_export.py b/tests/unit/torch/export/test_custom_backend_export.py new file mode 100644 index 00000000000..093e9960123 --- /dev/null +++ b/tests/unit/torch/export/test_custom_backend_export.py @@ -0,0 +1,274 @@ +# 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. + +"""Tests for the export converter of a custom quantization backend.""" + +import faulthandler +import json +from unittest import mock + +import pytest +import torch +from _test_utils.torch.distributed.utils import bounded_collectives +from _test_utils.torch.transformers_models import get_tiny_llama +from torch.distributed.device_mesh import init_device_mesh +from torch.distributed.fsdp import fully_shard + +import modelopt.torch.quantization as mtq +from modelopt.torch.export import export_hf_checkpoint +from modelopt.torch.export.layerwise_export import assert_layerwise_export_supported +from modelopt.torch.export.unified_export_hf import _export_transformers_checkpoint +from modelopt.torch.quantization.config import QuantizerAttributeConfig +from modelopt.torch.quantization.nn import ( + TensorQuantizer, + register_quant_backend, + unregister_quant_backend, +) +from modelopt.torch.quantization.nn.modules.tensor_quantizer import _QUANT_BACKEND_EXPORT_CONVERTERS +from modelopt.torch.utils.distributed import DistributionPlan, set_distribution_plan + +# Converters run in the order of their backend names: BACKEND's first. +BACKEND = "toy_backend" +OTHER_BACKEND = "toy_backend_2" +TOY_CFG = {"num_bits": 8, "axis": None, "backend": BACKEND} +# Patched to make the export see a model as sharded; it returns (FSDP2, expert parallel). +SHARD_FLAGS = "modelopt.torch.export.unified_export_hf._hf_shard_flags" +FP8_CFG = next( + entry["cfg"] + for entry in mtq.FP8_DEFAULT_CFG["quant_cfg"] + if entry["quantizer_name"] == "*weight_quantizer" +) + + +def _toy_fake_quant(inputs: torch.Tensor, quantizer) -> torch.Tensor: + """The toy backends' fake quantization: round to a multiple of 1/64.""" + return torch.round(inputs * 64) / 64 + + +def _quantize(model, cfg=TOY_CFG, algorithm=None): + """Quantize the MLP weights of ``model`` with the quantizer attributes ``cfg``.""" + quant_cfg = [ + {"quantizer_name": "*", "enable": False}, + {"quantizer_name": "*mlp*weight_quantizer", "cfg": cfg}, + ] + + def forward_loop(model): + model(torch.randint(model.config.vocab_size, (2, 8))) + + return mtq.quantize( + model, {"quant_cfg": quant_cfg, "algorithm": algorithm}, forward_loop if algorithm else None + ) + + +def _convert_to_fp8(model, backends=(BACKEND,)): + """Replace each weight quantizer of ``backends`` with a built-in per-tensor FP8 one.""" + for module in model.modules(): + quantizer = getattr(module, "weight_quantizer", None) + if isinstance(quantizer, TensorQuantizer) and quantizer.backend in backends: + fp8 = TensorQuantizer(QuantizerAttributeConfig(**FP8_CFG)) + fp8.amax = module.weight.detach().abs().amax().float() + module.weight_quantizer = fp8 + + +@pytest.fixture +def converter(): + """Register the toy backends, the first with a converter to FP8; unregister them after.""" + converter = mock.Mock(side_effect=_convert_to_fp8) + register_quant_backend(BACKEND, _toy_fake_quant, export_converter=converter) + register_quant_backend(OTHER_BACKEND, _toy_fake_quant) + yield converter + unregister_quant_backend(BACKEND) + unregister_quant_backend(OTHER_BACKEND) + + +def test_the_export_writes_the_quantizers_that_the_converter_makes(converter): + model = _quantize(get_tiny_llama()) + # The same model, converted by hand: a model with built-in FP8 weight quantizers. + by_hand = _quantize(get_tiny_llama()) + _convert_to_fp8(by_hand) + + state_dict, quant_config = _export_transformers_checkpoint(model) + expected_state_dict, expected_quant_config = _export_transformers_checkpoint(by_hand) + + converter.assert_called_once_with(model) + assert quant_config == expected_quant_config + assert quant_config["quantization"]["quant_algo"] == "FP8" + assert state_dict.keys() == expected_state_dict.keys() + for key, tensor in expected_state_dict.items(): + assert torch.equal(state_dict[key], tensor), key + + +def test_export_hf_checkpoint_converts_the_quantizers(converter, tmp_path): + model = _quantize(get_tiny_llama()) + + export_hf_checkpoint(model, export_dir=tmp_path) + + converter.assert_called_once_with(model) + config = json.loads((tmp_path / "config.json").read_text())["quantization_config"] + assert config["quant_algo"] == "FP8" + + +def test_no_converter_runs_for_a_model_whose_quantizers_do_not_use_its_backend( + converter, monkeypatch +): + other = mock.Mock() + register_quant_backend(OTHER_BACKEND, _toy_fake_quant, export_converter=other) + model = _quantize(get_tiny_llama(), FP8_CFG, algorithm="max") + # A disabled quantizer of the backend does not count. + disabled = model.model.layers[0].mlp.up_proj.weight_quantizer + disabled.backend = BACKEND + disabled.disable() + # Nor is such a model refused when it is sharded. + monkeypatch.setattr(SHARD_FLAGS, lambda model: (True, True)) + + _export_transformers_checkpoint(model) + + converter.assert_not_called() + other.assert_not_called() + + +@pytest.mark.parametrize("shard_flags", [(True, False), (False, True)], ids=["fsdp2", "ep"]) +def test_a_sharded_model_is_refused_before_any_converter_runs(converter, monkeypatch, shard_flags): + monkeypatch.setattr(SHARD_FLAGS, lambda model: shard_flags) + model = _quantize(get_tiny_llama()) + + with pytest.raises(NotImplementedError, match="sharded"): + _export_transformers_checkpoint(model) + + converter.assert_not_called() + + +def _refuse_a_sharded_model_on_two_ranks(rank, size, export_dir): + # A rank left waiting in a collective exits with its stack instead of hanging the run. The + # workers are reused, so the timer and the backend are undone in ``finally``. + faulthandler.dump_traceback_later(45, exit=True) + converter = mock.Mock(side_effect=_convert_to_fp8) + register_quant_backend(BACKEND, _toy_fake_quant, export_converter=converter) + try: + model = get_tiny_llama(dtype=torch.float32) + mesh = init_device_mesh("cpu", (size,)) + for layer in model.model.layers: + fully_shard(layer, mesh=mesh) + fully_shard(model, mesh=mesh) + model = _quantize(model) + set_distribution_plan(model, DistributionPlan(size, dense="fsdp")) + + # Each rank raises its own refusal, or the other rank's, which the export passes on. + with ( + bounded_collectives(), + pytest.raises((NotImplementedError, RuntimeError), match="sharded"), + ): + export_hf_checkpoint(model, export_dir=export_dir) + converter.assert_not_called() + finally: + unregister_quant_backend(BACKEND) + faulthandler.cancel_dump_traceback_later() + + +def test_a_sharded_model_is_refused_on_every_rank(tmp_path, cpu_dist_workers): + """Both ranks of an FSDP2 export refuse the model, and neither waits on the other.""" + cpu_dist_workers.run(_refuse_a_sharded_model_on_two_ranks, export_dir=str(tmp_path)) + + +def test_an_offloaded_model_is_refused_before_any_converter_runs(converter, monkeypatch, tmp_path): + # A model with offload hooks; export_hf_checkpoint takes the offloaded export for it. + monkeypatch.setattr( + "modelopt.torch.export.unified_export_hf.has_accelerate_offload", lambda model: True + ) + model = _quantize(get_tiny_llama()) + + with pytest.raises(NotImplementedError, match="offloaded"): + _export_transformers_checkpoint(model) + with ( + pytest.warns(UserWarning, match="Cannot export model"), + pytest.raises(NotImplementedError, match="offloaded"), + ): + export_hf_checkpoint(model, export_dir=tmp_path) + + converter.assert_not_called() + assert not any(tmp_path.iterdir()) + + +def test_the_layerwise_export_refuses_a_model_that_needs_a_converter(converter): + model = _quantize(get_tiny_llama()) + + with pytest.raises(NotImplementedError, match="layerwise export does not run"): + assert_layerwise_export_supported(model) + + converter.assert_not_called() + + +def test_the_export_raises_if_a_converter_leaves_a_quantizer_of_its_backend(converter): + model = _quantize(get_tiny_llama()) + up_proj = model.model.layers[0].mlp.up_proj + left = up_proj.weight_quantizer + + def convert_all_but_one(model): + _convert_to_fp8(model) + up_proj.weight_quantizer = left + + converter.side_effect = convert_all_but_one + + with pytest.raises(RuntimeError, match=rf"backends \['{BACKEND}'\] are left"): + _export_transformers_checkpoint(model) + + converter.assert_called_once_with(model) + + +def test_the_export_raises_if_a_later_converter_brings_back_a_converted_backend(converter): + model = _quantize(get_tiny_llama()) + quantizer = model.model.layers[0].mlp.up_proj.weight_quantizer + quantizer.backend = OTHER_BACKEND + # The converter of OTHER_BACKEND, which runs after BACKEND's, gives the quantizer BACKEND. + other = mock.Mock(side_effect=lambda model: setattr(quantizer, "backend", BACKEND)) + register_quant_backend(OTHER_BACKEND, _toy_fake_quant, export_converter=other) + + with pytest.raises(RuntimeError, match=rf"backends \['{BACKEND}'\] are left"): + _export_transformers_checkpoint(model) + + converter.assert_called_once_with(model) + other.assert_called_once_with(model) + + +def test_a_converter_that_also_converts_another_backend_leaves_nothing_for_its_converter( + converter, +): + other = mock.Mock() + register_quant_backend(OTHER_BACKEND, _toy_fake_quant, export_converter=other) + converter.side_effect = lambda model: _convert_to_fp8(model, (BACKEND, OTHER_BACKEND)) + model = _quantize(get_tiny_llama(), {**TOY_CFG, "backend": OTHER_BACKEND}) + model.model.layers[0].mlp.up_proj.weight_quantizer.backend = BACKEND + + _export_transformers_checkpoint(model) + + converter.assert_called_once_with(model) + other.assert_not_called() + + +def test_registering_a_backend_again_or_unregistering_it_drops_its_converter(converter): + with pytest.warns(UserWarning, match="Overwriting existing backend"): + register_quant_backend(BACKEND, _toy_fake_quant) + assert BACKEND not in _QUANT_BACKEND_EXPORT_CONVERTERS + + with pytest.warns(UserWarning, match="Overwriting existing backend"): + register_quant_backend(BACKEND, _toy_fake_quant, export_converter=converter) + unregister_quant_backend(BACKEND) + assert BACKEND not in _QUANT_BACKEND_EXPORT_CONVERTERS + + +def test_an_export_converter_must_be_callable(): + with pytest.raises(TypeError, match="Export converter must be callable"): + register_quant_backend(BACKEND, _toy_fake_quant, export_converter="not callable") + assert BACKEND not in _QUANT_BACKEND_EXPORT_CONVERTERS