PTQ-Level Efficiency, QAT-Level Accuracy | 训练后量化的效率,量化感知训练的精度
fix: layer_config for lm_head takes effect in model-free mode (#2182)
Copilot1d0504631999
diff --git a/auto_round/compressors/model_free.py b/auto_round/compressors/model_free.pyindex 531f78556..db231de33 100644--- a/auto_round/compressors/model_free.py+++ b/auto_round/compressors/model_free.py@@ -120,6 +120,7 @@ from auto_round.utils.common import AUDIO_MM_KEYS, VISION_MM_KEYS, compress_layefrom auto_round.utils.device import clear_memory, memory_monitorfrom auto_round.utils.device_manager import default_enable_torch_compilefrom auto_round.utils.model_free_utils import (+ _LM_HEAD_PATTERNS,_apply_scheme_overrides,_build_cross_shard_pairs_from_weight_map,_build_quantization_config,@@ -609,9 +610,16 @@ class _ModelFreeCompressorCore:ignore_patterns = [p.strip() for p in self.ignore_layers_input.replace(" ", "").split(",") if p.strip()]ignore_patterns = [p + "." if re.search(r"\.\d+$", p) else p for p in ignore_patterns]- if not self.quant_lm_head and "lm_head" not in ignore_patterns:- ignore_patterns.append("lm_head")- ignore_patterns.append("head") # for deepseek v4+ if not self.quant_lm_head:+ layer_config_keys = set(self.layer_config or {})+ # Skip each known lm_head name variant unless the user has explicitly listed it in layer_config.+ # Each pattern is checked independently so a user-specified key takes priority over the default.+ for lm_head_pattern in _LM_HEAD_PATTERNS:+ pattern_in_config = any(+ key == lm_head_pattern or key.startswith(lm_head_pattern + ".") for key in layer_config_keys+ )+ if not pattern_in_config and lm_head_pattern not in ignore_patterns:+ ignore_patterns.append(lm_head_pattern)if not self.quant_nontext_module:for kw in _NONTEXT_KEYWORDS:diff --git a/auto_round/utils/model_free_utils.py b/auto_round/utils/model_free_utils.pyindex e489f0ca0..4ec86e902 100644--- a/auto_round/utils/model_free_utils.py+++ b/auto_round/utils/model_free_utils.py@@ -43,6 +43,12 @@ _NVFP4_E5M3_DATA_TYPE = "nvfp4_v2"_BLOCK_NAME_TO_IGNORE = ("shared_expert_gate.", ".gate.", "embed", "conv")_SUPPORTED_MXFP_BITS = (4, 8)_SUPPORTED_INT_BITS = (2, 4, 8)+# Known lm_head layer name variants across model families:+# "lm_head" – most models (LLaMA, Mistral, Qwen, …)+# "head" – DeepSeek v4+# "embed_out" – Pythia / Dolly+# "output" – some InternLM variants+_LM_HEAD_PATTERNS: tuple[str, ...] = ("lm_head", "head", "embed_out", "output")SUPPORTED_PRESET_SCHEMES = ("W2A16","W2A16G32",@@ -118,6 +124,10 @@ class _PatternMatcher:if cached is not None:return cachedlayer_name = tensor_name.rsplit(".", 1)[0] if "." in tensor_name else tensor_name+ # Explicit layer_config entries take priority: never ignore a layer the user has explicitly configured.+ if layer_name in self._layer_config:+ self._ignore_cache[tensor_name] = False+ return Falseresult = bool(self._ignore_re and self._ignore_re.search(layer_name))self._ignore_cache[tensor_name] = resultreturn result@@ -1709,11 +1719,12 @@ def _build_mxfp_autoround_quantization_config("act_data_type": "float",}- # lm_head: when explicitly quantized, record its full scheme in extra_config+ # lm_head variants: when explicitly quantized, record each variant's full scheme in extra_config# (mirrors the regular AutoRound MXFP export behavior).- if "lm_head" in quantized_set and "lm_head" not in extra_config:- lm_head_cfg = (layer_config or {}).get("lm_head", default_scheme)- extra_config["lm_head"] = {k: lm_head_cfg.get(k) for k in scheme_keys if lm_head_cfg.get(k) is not None}+ for lm_head_name in _LM_HEAD_PATTERNS:+ if lm_head_name in quantized_set and lm_head_name not in extra_config:+ lm_head_cfg = (layer_config or {}).get(lm_head_name, default_scheme)+ extra_config[lm_head_name] = {k: lm_head_cfg.get(k) for k in scheme_keys if lm_head_cfg.get(k) is not None}if extra_config:qconfig["extra_config"] = extra_config@@ -2045,9 +2056,10 @@ def _build_quantization_config(extra_config[layer_name].update({"act_bits": 16, "act_data_type": "float"})quantized_layer_set = set(quantized_layers)- if "lm_head" in quantized_layer_set and "lm_head" not in extra_config:- lm_head_cfg = layer_config.get("lm_head", default_scheme)- extra_config["lm_head"] = {k: lm_head_cfg.get(k) for k in scheme_keys if lm_head_cfg.get(k) is not None}+ for lm_head_name in _LM_HEAD_PATTERNS:+ if lm_head_name in quantized_layer_set and lm_head_name not in extra_config:+ lm_head_cfg = layer_config.get(lm_head_name, default_scheme)+ extra_config[lm_head_name] = {k: lm_head_cfg.get(k) for k in scheme_keys if lm_head_cfg.get(k) is not None}if extra_config:qconfig["extra_config"] = extra_configdiff --git a/test/unit/test_cpu/quantization/test_model_free.py b/test/unit/test_cpu/quantization/test_model_free.pyindex 4e0d8e6e9..2bbf071a0 100644--- a/test/unit/test_cpu/quantization/test_model_free.py+++ b/test/unit/test_cpu/quantization/test_model_free.py@@ -308,6 +308,73 @@ class TestParseLayerConfig:assert core.layer_config[".shared_expert."]["bits"] == 8+# ===========================================================================+# _build_ignore_patterns+# ===========================================================================+++class TestBuildIgnorePatterns:+ @staticmethod+ def _make_core(layer_config=None, quant_lm_head=False, scheme="W4A16"):+ core = _ModelFreeCompressorCore(+ model_name_or_path="dummy",+ output_dir="dummy_out",+ scheme=scheme,+ quant_lm_head=quant_lm_head,+ )+ core._parse_scheme()+ core._parse_layer_config()+ if layer_config:+ # Merge any explicit layer_config entries on top of the parsed defaults.+ for k, v in layer_config.items():+ core.layer_config[k] = v+ return core++ def test_lm_head_ignored_by_default(self):+ """Without quant_lm_head or an explicit layer_config entry, lm_head is skipped."""+ core = self._make_core()+ core._build_ignore_patterns()+ assert "lm_head" in core.ignore_patterns++ def test_lm_head_not_ignored_when_quant_lm_head_true(self):+ """quant_lm_head=True removes lm_head from ignore list."""+ core = self._make_core(quant_lm_head=True)+ core._build_ignore_patterns()+ assert "lm_head" not in core.ignore_patterns++ def test_lm_head_not_ignored_when_in_layer_config(self):+ """Explicit lm_head entry in layer_config removes it from the ignore list."""+ core = self._make_core(layer_config={"lm_head": {"bits": 4}})+ core._build_ignore_patterns()+ assert "lm_head" not in core.ignore_patterns++ def test_head_not_ignored_when_in_layer_config(self):+ """DeepSeek v4 uses 'head' as the lm_head layer name; explicit entry in layer_config removes it from ignore."""+ core = self._make_core(layer_config={"head": {"bits": 4}})+ core._build_ignore_patterns()+ assert "head" not in core.ignore_patterns++ def test_head_still_ignored_when_lm_head_in_layer_config_but_not_head(self):+ """Specifying 'lm_head' in layer_config should not unblock the separate 'head' pattern."""+ core = self._make_core(layer_config={"lm_head": {"bits": 4}})+ core._build_ignore_patterns()+ # 'lm_head' itself is unblocked, but 'head' (deepseek v4) remains ignored+ assert "lm_head" not in core.ignore_patterns+ assert "head" in core.ignore_patterns++ def test_embed_out_not_ignored_when_in_layer_config(self):+ """Pythia/Dolly models use 'embed_out' as the lm_head layer name."""+ core = self._make_core(layer_config={"embed_out": {"bits": 4}})+ core._build_ignore_patterns()+ assert "embed_out" not in core.ignore_patterns++ def test_output_not_ignored_when_in_layer_config(self):+ """Some InternLM variants use 'output' as the lm_head layer name."""+ core = self._make_core(layer_config={"output": {"bits": 4}})+ core._build_ignore_patterns()+ assert "output" not in core.ignore_patterns++# ===========================================================================# _process_shard# ===========================================================================@@ -650,6 +717,30 @@ class TestModelFreeQuantize:AutoRound(model=model_dir, scheme="W4A16", model_free=True, quant_lm_head=True).quantize_and_save(output_dir)assert "lm_head.qweight" in _read_output_keys(output_dir)+ def test_layer_config_lm_head_bits_takes_effect(self, tmp_path):+ """layer_config for lm_head should quantize lm_head even without quant_lm_head=True."""+ model_dir = _make_model_dir(tmp_path, _SIMPLE_CONFIG, _SIMPLE_TENSORS)+ output_dir = str(tmp_path / "output")+ AutoRound(+ model=model_dir,+ scheme="W2A16G64",+ model_free=True,+ layer_config={"lm_head": {"bits": 4}},+ ).quantize_and_save(output_dir)+ assert "lm_head.qweight" in _read_output_keys(output_dir)++ def test_layer_config_lm_head_scheme_takes_effect(self, tmp_path):+ """layer_config with scheme override for lm_head should quantize lm_head even without quant_lm_head=True."""+ model_dir = _make_model_dir(tmp_path, _SIMPLE_CONFIG, _SIMPLE_TENSORS)+ output_dir = str(tmp_path / "output")+ AutoRound(+ model=model_dir,+ scheme="W2A16G64",+ model_free=True,+ layer_config={"lm_head": {"scheme": "W4A16"}},+ ).quantize_and_save(output_dir)+ assert "lm_head.qweight" in _read_output_keys(output_dir)+def test_asym(self, tmp_path):model_dir = _make_model_dir(tmp_path, _LLAMA_CFG, {"layer.weight": torch.randn(64, 128)})output_dir = str(tmp_path / "output")