PTQ-Level Efficiency, QAT-Level Accuracy | 训练后量化的效率,量化感知训练的精度
Record AutoRound hyper-parameters in llm-compressor quantization_config (#2528)
Cross2pro4ae46af831e0
diff --git a/auto_round/compressors/base.py b/auto_round/compressors/base.pyindex 96cc46db8..b3aa923b4 100644--- a/auto_round/compressors/base.py+++ b/auto_round/compressors/base.py@@ -1975,8 +1975,13 @@ class BaseOrchestrator:)serialization_dict = asdict(SerializedCompressorConfig())+ calibration_context = getattr(self, "calibration_context", None)for key in serialization_dict:- serialization_dict[key] = getattr(self, key, serialization_dict[key])+ value = getattr(self, key, serialization_dict[key])+ # Calibration params (nsamples/seqlen/batch_size) live on the calibration context.+ if value is None and calibration_context is not None:+ value = getattr(calibration_context, key, None)+ serialization_dict[key] = valuefrom auto_round.version import __version__serialization_dict["autoround_version"] = __version__diff --git a/auto_round/export/export_to_llmcompressor/export.py b/auto_round/export/export_to_llmcompressor/export.pyindex 66a9ac20e..93f5a4f90 100644--- a/auto_round/export/export_to_llmcompressor/export.py+++ b/auto_round/export/export_to_llmcompressor/export.py@@ -20,6 +20,7 @@ from collections.abc import Callable, Mappingimport torchfrom auto_round.export.export_to_llmcompressor.utils import (+ add_autoround_config,add_routed_experts_if_moe,finalize_llmcompressor_config_names,)@@ -389,6 +390,8 @@ def save_quantized_as_llmcompressor([],[n for n, m in model.named_modules() if getattr(m, "quantization_scheme", None) is not None],)+ quantization_config_dict["provider"] = "auto-round"+ quantization_config_dict = add_autoround_config(quantization_config_dict, serialization_dict)model.config.quantization_config = quantization_config_dictif output_dir is None:diff --git a/auto_round/export/export_to_llmcompressor/export_to_fp.py b/auto_round/export/export_to_llmcompressor/export_to_fp.pyindex 137cd0ab1..f172556d0 100644--- a/auto_round/export/export_to_llmcompressor/export_to_fp.py+++ b/auto_round/export/export_to_llmcompressor/export_to_fp.py@@ -28,6 +28,7 @@ from auto_round.compressors.utils import is_mx_fp, is_nv_fpfrom auto_round.export.export_to_autoround.qlinear_fp import QuantLinearfrom auto_round.export.export_to_llmcompressor.config import initialize_quantizationfrom auto_round.export.export_to_llmcompressor.utils import (+ add_autoround_config,add_routed_experts_if_moe,finalize_llmcompressor_config_names,generate_ignore_regex_list,@@ -491,6 +492,7 @@ def save_quantized_as_fp([],[name for names in scheme_groups.values() for name in names],)+ quantization_config = add_autoround_config(quantization_config, serialization_dict)if hasattr(model, "config"):model.config.quantization_config = quantization_configif output_dir is None:diff --git a/auto_round/export/export_to_llmcompressor/export_to_static_fp.py b/auto_round/export/export_to_llmcompressor/export_to_static_fp.pyindex 6b1c4fc44..fce0b7e30 100644--- a/auto_round/export/export_to_llmcompressor/export_to_static_fp.py+++ b/auto_round/export/export_to_llmcompressor/export_to_static_fp.py@@ -26,7 +26,7 @@ from auto_round.data_type.utils import reshape_pad_tensor_by_group_size, revert_from auto_round.experimental.utils import NVFP4_KV_DTYPEfrom auto_round.export.export_to_autoround.export_to_fp8 import FP8QLinearfrom auto_round.export.export_to_llmcompressor.config import check_compressed_tensors_supported-from auto_round.export.export_to_llmcompressor.utils import finalize_llmcompressor_config_names+from auto_round.export.export_to_llmcompressor.utils import add_autoround_config, finalize_llmcompressor_config_namesfrom auto_round.export.utils import is_immediate_saving_mode, save_model, save_pretrained_artifactfrom auto_round.utils import (SUPPORTED_LAYER_TYPES,@@ -298,6 +298,7 @@ def save_quantized_as_static_fp(quantization_config = finalize_llmcompressor_config_names(quantization_config, model, [], [n for n in layer_config if check_to_quantized(layer_config[n])])+ quantization_config = add_autoround_config(quantization_config, serialization_dict)if hasattr(model, "config"):model.config.quantization_config = quantization_configdiff --git a/auto_round/export/export_to_llmcompressor/utils.py b/auto_round/export/export_to_llmcompressor/utils.pyindex eaa175f3b..d796b63c1 100644--- a/auto_round/export/export_to_llmcompressor/utils.py+++ b/auto_round/export/export_to_llmcompressor/utils.py@@ -17,6 +17,7 @@ import reimport torch+from auto_round.compressors.base import SERIALIZATION_KEYSfrom auto_round.utils import matches_any_regex, to_standard_regex_EXPERT_SEGMENTS = ("experts", "shared_experts")@@ -191,3 +192,56 @@ def generate_ignore_regex_list(regex_config: dict[str, dict], layer_config: dictignore_regex.append(key)return ignore_regex+++# Tuning hyper-parameters worth recording so a llm-compressor checkpoint can be+# traced back to (and re-created with) the AutoRound command that produced it.+AUTOROUND_CONFIG_KEY = "autoround_config"+# Prefer the shared compressor serialization allowlist so new hyper-parameters+# land here automatically. ``autoround_version`` is injected into+# ``serialization_dict`` at export time and is not a SerializedCompressorConfig field.+_AUTOROUND_CONFIG_FIELDS = ("autoround_version",) + tuple(SERIALIZATION_KEYS)+++def _to_json_value(value):+ import enum++ if isinstance(value, (bool, int, float, str)):+ return value+ if isinstance(value, torch.dtype):+ return str(value)+ if isinstance(value, torch.device):+ return str(value)+ if isinstance(value, enum.Enum):+ enum_value = value.value+ if isinstance(enum_value, (bool, int, float, str)):+ return enum_value+ return value.name+ if isinstance(value, type):+ return f"{value.__module__}.{value.__qualname__}"+ if isinstance(value, (list, tuple)):+ return [_to_json_value(v) for v in value]+ return str(value)+++def add_autoround_config(quantization_config: dict, serialization_dict: dict | None) -> dict:+ """Record AutoRound tuning hyper-parameters in an llm-compressor ``quantization_config``.++ The values are stored under a single nested ``"autoround_config"`` key so that the+ compressed-tensors / vLLM loaders, which only read the keys they know, are unaffected.+ Only runs when ``quantization_config["provider"] == "auto-round"``, so shared export+ helpers do not write AutoRound-branded metadata for other providers.+ """+ if not isinstance(quantization_config, dict) or not serialization_dict:+ return quantization_config+ if quantization_config.get("provider") != "auto-round":+ return quantization_config+ autoround_config = {}+ for key in _AUTOROUND_CONFIG_FIELDS:+ value = serialization_dict.get(key)+ if value is None:+ continue+ autoround_config[key] = _to_json_value(value)+ if autoround_config:+ quantization_config[AUTOROUND_CONFIG_KEY] = autoround_config+ return quantization_configdiff --git a/test/unit/common/export/test_llmc_autoround_config.py b/test/unit/common/export/test_llmc_autoround_config.pynew file mode 100644index 000000000..aeec6ad9b--- /dev/null+++ b/test/unit/common/export/test_llmc_autoround_config.py@@ -0,0 +1,154 @@+# Copyright (c) 2026 Intel Corporation+#+# 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.+"""AutoRound hyper-parameters are recorded in llm-compressor checkpoints (#2469)."""++import json++import pytest++from auto_round.export.export_to_llmcompressor.utils import AUTOROUND_CONFIG_KEY, add_autoround_config+++class TestAddAutoroundConfig:+ def test_records_tuning_args_and_version(self):+ qconfig = {"quant_method": "compressed-tensors", "provider": "auto-round"}+ serialization_dict = {+ "autoround_version": "0.17.0",+ "bits": 4,+ "group_size": 128,+ "sym": True,+ "iters": 200,+ "lr": 0.005,+ "nsamples": 128,+ "seqlen": 2048,+ "scale_dtype": "torch.float16",+ "act_bits": None,+ "regex_config": {"foo": {"bits": 8}},+ "supported_types": ["Linear"],+ }+ out = add_autoround_config(qconfig, serialization_dict)+ assert out is qconfig+ ar = qconfig[AUTOROUND_CONFIG_KEY]+ # SERIALIZATION_KEYS (maintainer request) includes compressor fields such as+ # regex_config / supported_types; dicts stringify via _to_json_value.+ assert ar == {+ "autoround_version": "0.17.0",+ "bits": 4,+ "group_size": 128,+ "sym": True,+ "iters": 200,+ "lr": 0.005,+ "nsamples": 128,+ "seqlen": 2048,+ "scale_dtype": "torch.float16",+ "regex_config": "{'foo': {'bits': 8}}",+ "supported_types": ["Linear"],+ }+ # untouched top-level keys+ assert qconfig["quant_method"] == "compressed-tensors"+ json.dumps(qconfig)++ def test_non_json_values_are_stringified(self):+ import enum++ import torch++ class SampleEnum(enum.Enum):+ A = "alpha"++ qconfig = {"provider": "auto-round"}+ add_autoround_config(+ qconfig,+ {+ "scale_dtype": torch.float16,+ "group_size": (128, 128),+ "static_kv_dtype": torch.device("cpu"),+ "static_attention_dtype": SampleEnum.A,+ },+ )+ assert qconfig[AUTOROUND_CONFIG_KEY] == {+ "scale_dtype": "torch.float16",+ "group_size": [128, 128],+ "static_kv_dtype": "cpu",+ "static_attention_dtype": "alpha",+ }++ @pytest.mark.parametrize("serialization_dict", [None, {}, {"iters": None}])+ def test_noop_without_values(self, serialization_dict):+ qconfig = {"provider": "auto-round"}+ add_autoround_config(qconfig, serialization_dict)+ assert AUTOROUND_CONFIG_KEY not in qconfig++ def test_noop_without_auto_round_provider(self):+ qconfig = {"provider": "other"}+ add_autoround_config(qconfig, {"iters": 200, "autoround_version": "0.17.0"})+ assert AUTOROUND_CONFIG_KEY not in qconfig+ qconfig_missing = {}+ add_autoround_config(qconfig_missing, {"iters": 200})+ assert AUTOROUND_CONFIG_KEY not in qconfig_missing++ def test_compressed_tensors_ignores_extra_key(self):+ ct = pytest.importorskip("compressed_tensors.quantization")+ qconfig = {+ "quant_method": "compressed-tensors",+ "format": "pack-quantized",+ "config_groups": {+ "group_0": {+ "targets": ["Linear"],+ "weights": {+ "num_bits": 4,+ "type": "int",+ "symmetric": True,+ "strategy": "group",+ "group_size": 128,+ },+ }+ },+ "ignore": ["lm_head"],+ "provider": "auto-round",+ }+ add_autoround_config(qconfig, {"iters": 200, "autoround_version": "0.17.0"})+ parsed = ct.QuantizationConfig.model_validate(qconfig)+ assert parsed.config_groups["group_0"].weights.num_bits == 4++[email protected]("scheme", ["W4A16", "MXFP4"])+def test_llmc_export_writes_autoround_config(tiny_opt_model_path, tmp_path, scheme):+ pytest.importorskip("compressed_tensors")+ from pathlib import Path++ from auto_round import AutoRound+ from auto_round.version import __version__++ ar = AutoRound(tiny_opt_model_path, scheme=scheme, iters=2, nsamples=2, seqlen=16, lr=0.01)+ _, export_dir = ar.quantize_and_save(output_dir=str(tmp_path), format="llm_compressor")+ config_path = Path(export_dir) / "config.json"+ assert config_path.is_file()+ with open(config_path) as f:+ qconfig = json.load(f)["quantization_config"]+ assert qconfig["quant_method"] == "compressed-tensors"+ ar_cfg = qconfig[AUTOROUND_CONFIG_KEY]+ assert ar_cfg["autoround_version"] == __version__+ assert ar_cfg["iters"] == 2+ assert ar_cfg["nsamples"] == 2+ assert ar_cfg["seqlen"] == 16+ assert ar_cfg["lr"] == 0.01+ assert ar_cfg["bits"] == 4++ from transformers import AutoConfig++ AutoConfig.from_pretrained(str(export_dir))+ from compressed_tensors.quantization import QuantizationConfig++ QuantizationConfig.model_validate(qconfig)