PTQ-Level Efficiency, QAT-Level Accuracy | 训练后量化的效率,量化感知训练的精度
clean and fix for new arch (#1761)
Heng Guo1c615f1c9f01
diff --git a/auto_round/compressors_new/base.py b/auto_round/compressors_new/base.pyindex 37f5726e8..025dfbd3f 100644--- a/auto_round/compressors_new/base.py+++ b/auto_round/compressors_new/base.py@@ -99,7 +99,7 @@ class SerializedCompressorConfig:super_bits: Optional[int] = Nonesuper_group_size: Optional[int] = Noneto_quant_block_names: Optional[list[str]] = None- transform_configs: Optional[list[dict[str, Any]]] = None+ rotation_configs: Optional[list[dict[str, Any]]] = Noneclass BaseCompressor(object):@@ -144,13 +144,13 @@ class BaseCompressor(object):**kwargs,):self.quantize_config = None- self.transform_configs: list[BaseRotationConfig] = []+ self.rotation_configs: list[BaseRotationConfig] = []_config_list = config if isinstance(config, list) else [config]for _cfg in _config_list:if isinstance(_cfg, QuantizationConfig):self.quantize_config = _cfgelif isinstance(_cfg, BaseRotationConfig):- self.transform_configs.append(_cfg)+ self.rotation_configs.append(_cfg)assert self.quantize_config is not None, "QuantizationConfig is required for Compressor"# Compressor-level calibration/layer params (do not live in QuantizationConfig).@@ -621,7 +621,7 @@ class BaseCompressor(object):def _get_calibration_dataset(self) -> str:"""Resolve calibration dataset: self.dataset > AutoScheme.dataset > default."""dataset = self.__dict__.get("dataset", None)- if dataset:+ if dataset is not None:return datasetfrom auto_round.auto_scheme.gen_auto_scheme import AutoScheme@@ -662,6 +662,7 @@ class BaseCompressor(object):self._resolve_formats()self._patch_model()self._build_layer_config()+ self._apply_rotations()# Reclaim temporaries from Phases 1-4 (scheme resolution, format# parsing, model patching, layer-config walk) before Phase 5@@ -728,7 +729,7 @@ class BaseCompressor(object):self.wrapper_block = wrapper_blockdef _resolve_formats(self) -> None:- """Phase 2 – Format resolution, GGUF attr sync, and rotation application.+ """Phase 2 – Format resolution and GGUF attr sync.Preconditions:- Phase 1 complete: ``self.quantizer`` is initialised and the scheme@@ -745,14 +746,12 @@ class BaseCompressor(object):have written onto ``self`` inside ``get_formats``, syncs them to``self.quantizer``, and rebuilds ``self.scheme`` accordingly.- Merges any GGUF-injected entries into ``self.layer_config``.- - **(2d)** Applies rotation transforms from ``self.transform_configs``.Postconditions:- ``self.formats`` is a list (or ``None``).- ``self.compress_context.formats`` mirrors ``self.formats``.- ``self.quantizer`` carries the GGUF-adjusted scheme attrs.- ``self.scheme`` is consistent with the final quantization attrs.- - All rotation transforms have been applied to ``self.model_context.model``."""# get_formats() inspects data_type / bits etc. that were just resolved.if isinstance(self.formats, str):@@ -843,15 +842,38 @@ class BaseCompressor(object):for _lname, _lval in _gguf_layer_cfg.items():self.layer_config.setdefault(_lname, _lval)- # ── 2d: apply rotation transforms ────────────────────────────────────- if self.transform_configs:- logger.info("Applying Hadamard transform to the model.")- for rotation_cfg in self.transform_configs:- self.model_context.model = apply_rotation(- self.model_context.model,- rotation_cfg,- data_type=self.quantize_config.data_type,- )+ def _apply_rotations(self) -> None:+ """Phase 4.5 – Apply Hadamard / rotation transforms to the model.++ Preconditions:+ - Phase 3 complete: model topology is final (``apply_patches`` has+ replaced / merged layers, e.g. MoE experts), so rotation operates+ on the same modules that quantization will later see.+ - Phase 4 complete: ``self.layer_config`` is built; rotation only+ transforms weights and does not change layer names, so this+ ordering matches the old arch where rotation ran after+ ``configure_layer_config``.+ - ``self.quantize_config.data_type`` is final (rotation backend+ dispatch depends on it).++ Work performed:+ - Iterates ``self.rotation_configs`` and calls+ :func:`~auto_round.algorithms.transforms.apply_rotation` on the+ model for each config.++ Postconditions:+ - ``self.model_context.model`` carries the rotated weights and any+ inserted online-Hadamard hooks.+ """+ if not self.rotation_configs:+ return+ logger.info("Applying Hadamard transform to the model.")+ for rotation_cfg in self.rotation_configs:+ self.model_context.model = apply_rotation(+ self.model_context.model,+ rotation_cfg,+ data_type=self.quantize_config.data_type,+ )def _patch_model(self) -> None:"""Phase 3 – Model structure patching.diff --git a/auto_round/export/utils.py b/auto_round/export/utils.pyindex c740791ef..837a9f073 100644--- a/auto_round/export/utils.py+++ b/auto_round/export/utils.py@@ -371,7 +371,7 @@ def filter_quantization_config(quantization_config):quantization_config.pop("act_sym", None)quantization_config.pop("act_group_size", None)- clean_list = ("supported_types", "quant_block_list", "transform_configs")+ clean_list = ("supported_types", "quant_block_list", "rotation_configs")for key in list(quantization_config.keys()):if callable(key):quantization_config.pop(key)diff --git a/auto_round/utils/common.py b/auto_round/utils/common.pyindex 865134b8b..3b9e1c234 100644--- a/auto_round/utils/common.py+++ b/auto_round/utils/common.py@@ -361,28 +361,28 @@ def _patch_mimo_attention_forward(model) -> None:"""Patch MiMo remote-code attention helpers for newer transformers call sites."""# Check if this is a MiMo model by class name (remote code models may not have model_type)model_class_name = model.__class__.__name__- logger.info(f"_patch_mimo_attention_forward called for {model_class_name}")+ logger.debug(f"_patch_mimo_attention_forward called for {model_class_name}")if "MiMo" not in model_class_name and "mimo" not in model_class_name.lower():- logger.info(f"Skipping patch: not a MiMo model (class name: {model_class_name})")+ logger.debug(f"Skipping patch: not a MiMo model (class name: {model_class_name})")returntry:module = importlib.import_module(model.__class__.__module__)- logger.info(f"Imported module: {model.__class__.__module__}")+ logger.debug(f"Imported module: {model.__class__.__module__}")except ImportError as e:logger.warning(f"Could not import module {model.__class__.__module__}: {e}")returneager_attention_forward = getattr(module, "eager_attention_forward", None)- logger.info(f"eager_attention_forward found: {eager_attention_forward is not None}")+ logger.debug(f"eager_attention_forward found: {eager_attention_forward is not None}")if eager_attention_forward is None:- logger.info("Skipping patch: eager_attention_forward not found in module")+ logger.debug("Skipping patch: eager_attention_forward not found in module")returnif getattr(eager_attention_forward, "_auto_round_mimo_patch", False):- logger.info("Skipping patch: already patched")+ logger.debug("Skipping patch: already patched")return@wraps(eager_attention_forward)@@ -402,7 +402,7 @@ def _patch_mimo_attention_forward(model) -> None:_patched_eager_attention_forward._auto_round_mimo_patch = Truemodule.eager_attention_forward = _patched_eager_attention_forward- logger.info(f"Successfully patched eager_attention_forward in {model.__class__.__module__}")+ logger.debug(f"Successfully patched eager_attention_forward in {model.__class__.__module__}")def _patch_qwen25_omni_talker(model) -> None: