PTQ-Level Efficiency, QAT-Level Accuracy | 训练后量化的效率,量化感知训练的精度
add awq torch_compile fix, disable_opt_rtn by default for awq (#2208)
Weiwei611d44028193
diff --git a/README.md b/README.mdindex 6f7e399d3..0831747ce 100644--- a/README.md+++ b/README.md@@ -36,6 +36,8 @@ See our papers [SignRoundV1](https://arxiv.org/pdf/2309.05516) and [SignRoundV2]## 🆕 What's New+* [2026/08] We experimentally support **algorithm composition**, e.g., `--algs awq,signround`[./docs/awq_details.md](./docs/awq_details.md) and `--algs hadamard,awq,signround`[./docs/rotation_details.md](./docs/rotation_details.md), to improve accuracy, especially in scenarios with activation quantization.+* [2026/08] AutoScheme WOQ deployment on vLLM is experimentally restored, thanks to Humming Kernel: [*vLLM PR*](https://github.com/vllm-project/vllm/pull/52890), [*Example Model*](https://huggingface.co/Intel/Qwen3.8-27B-bpw2.8-AutoRound). Note: shared layers must be configured per vLLM's fusion patterns.* [2026/07] `torch.compile` is enabled by default except on Windows to accelerate quantization. Minor numerical differences compared with the non-compiled path are expected due to compiler optimizations. To disable it, pass `enable_torch_compile=False` to the Python API or use `--disable_torch_compile` on the CLI.@@ -418,4 +420,3 @@ Special thanks to open-source low precision libraries such as AutoGPTQ, AutoAWQ,## 🌟 Support UsIf you find AutoRound helpful, please ⭐ star the repo and share it with your community!-diff --git a/README_CN.md b/README_CN.mdindex 05ceff704..e8a9664f0 100644--- a/README_CN.md+++ b/README_CN.md@@ -35,6 +35,8 @@ AutoRound 是专为大语言模型(LLMs)和视觉-语言模型(VLMs)设## 🆕 最新进展+* [2026/08] 我们实验性地支持**算法组合**,例如 AWQ + SignRound(`--algorithm awq,signround`,[./docs/awq_details.md](./docs/awq_details.md))以及 Hadamard(research 特性)+ AWQ + SignRound(`--algorithm hadamard,awq,signround`,[./docs/rotation_details.md](./docs/rotation_details.md)),以提升精度,尤其是在带有激活量化的场景中。+* [2026/08] 感谢 Humming Kernel,AutoScheme WOQ 在 vLLM 上的部署已实验性恢复:[*vLLM PR*](https://github.com/vllm-project/vllm/pull/52890),[*示例模型*](https://huggingface.co/Intel/Qwen3.8-27B-bpw2.8-AutoRound)。注意:共享层需按 vLLM 的融合模式进行配置。* [2026/07] 除 Windows 外默认启用 `torch.compile`,以加速量化。由于编译器优化,与未编译路径相比可能会出现细微的数值差异,这是符合预期的。如需关闭,可在 Python API 中传入 `enable_torch_compile=False`,或在命令行中使用 `--disable_torch_compile`。diff --git a/auto_round/algorithms/composer.py b/auto_round/algorithms/composer.pyindex a32e8dc03..b4e75f808 100644--- a/auto_round/algorithms/composer.py+++ b/auto_round/algorithms/composer.py@@ -84,13 +84,6 @@ class BlockContext:# ---------------------------------------------------------------------------# AlgorithmComposer# ----------------------------------------------------------------------------def _can_compile_block_forward(block_quantizer, rotation_configs, user_enabled: bool) -> bool:- """Return whether every component participating in block replay supports compilation."""- if not user_enabled or not block_quantizer.can_compile_block_forward():- return False- return all(getattr(config, "can_compile_block_forward", lambda: True)() for config in rotation_configs)--class AlgorithmComposer:"""An ordered composition of pre-processors + one block quantizer, built froma list of algorithm config objects and an optional compressor.@@ -193,15 +186,18 @@ class AlgorithmComposer:getattr(getattr(orchestrator, "compress_context", None), "enable_torch_compile", False))rotation_configs = getattr(orchestrator, "rotation_configs", ())- can_compile_block_forward = _can_compile_block_forward(- self.block_quantizer, rotation_configs, user_torch_compile- )- if (- user_torch_compile- and not can_compile_block_forward- and any(not getattr(config, "can_compile_block_forward", lambda: True)() for config in rotation_configs)- ):- logger.info("Block-forward torch.compile is disabled because an enabled rotation is incompatible.")+ blockers = []+ if not self.block_quantizer.can_compile_block_forward():+ blockers.append(type(self.block_quantizer).__name__)+ for component in [*self.preprocessors, *rotation_configs]:+ if not getattr(component, "can_compile_block_forward", lambda: True)():+ blockers.append(type(component).__name__)+ can_compile_block_forward = user_torch_compile and not blockers+ if user_torch_compile and blockers:+ logger.info(+ "Block-forward torch.compile is disabled because %s is incompatible.",+ ", ".join(blockers),+ )if _has_nvfp4_layer(orchestrator):can_compile_block_forward = Falsediff --git a/auto_round/algorithms/registry.py b/auto_round/algorithms/registry.pyindex b79647e7a..87b7e58e5 100644--- a/auto_round/algorithms/registry.py+++ b/auto_round/algorithms/registry.py@@ -194,6 +194,8 @@ def normalize_algorithm_config(config: object) -> object:from auto_round.algorithms.quantization.rtn.config import OptimizedRTNConfig, RTNConfigfrom auto_round.algorithms.quantization.sign_round.config import AdamRoundConfig, SignRoundConfig, SignRoundV2Config+ if type(config) is OptimizedRTNConfig and getattr(config, "disable_opt_rtn", False):+ return coerce_config_class(config, RTNConfig)if type(config) is RTNConfig and not getattr(config, "disable_opt_rtn", False):return coerce_config_class(config, OptimizedRTNConfig)if type(config) is SignRoundConfig:diff --git a/auto_round/algorithms/transforms/awq/base.py b/auto_round/algorithms/transforms/awq/base.pyindex 3f62ca205..2c8332e5e 100644--- a/auto_round/algorithms/transforms/awq/base.py+++ b/auto_round/algorithms/transforms/awq/base.py@@ -280,6 +280,10 @@ class AWQTransform(BasePreprocessor):)exit(-1)+ def can_compile_block_forward(self) -> bool:+ """AWQ installs per-block calibration hooks that trigger Dynamo recompiles."""+ return False+def prepare_run(self, composer: "AlgorithmComposer" = None) -> None:"""Resolve model-wide mappings and group them by transformer block."""model = self.model@@ -321,7 +325,7 @@ class AWQTransform(BasePreprocessor):self._block_mappings.setdefault(key, []).append(m)if composer is not None:- self._qdq_tool.configure(composer)+ self._qdq_tool.configure(composer, awq_config=self.config)logger.info("AWQ: resolved %d mappings across %d blocks.",diff --git a/auto_round/algorithms/transforms/awq/config.py b/auto_round/algorithms/transforms/awq/config.pyindex 520846011..dae4743c8 100644--- a/auto_round/algorithms/transforms/awq/config.py+++ b/auto_round/algorithms/transforms/awq/config.py@@ -16,6 +16,52 @@ from auto_round.algorithms.quantization.config import QuantizationConfigfrom auto_round.logger import logger+def _unique_opt_rtn_value(values) -> bool | None:+ values = [value for value in values if value is not None]+ unique_values = []+ for value in values:+ if not any(value == existing for existing in unique_values):+ unique_values.append(value)+ if len(unique_values) > 1:+ raise ValueError("Conflicting AWQ disable_opt_rtn values. Use one AWQ config or the same opt-RTN policy.")+ return unique_values[0] if unique_values else None+++def awq_disable_opt_rtn(configs) -> bool | None:+ """Return AWQ's resolved opt-RTN policy from normalized config objects."""+ return _unique_opt_rtn_value(config.disable_opt_rtn for config in configs if isinstance(config, AWQConfig))+++def direct_opt_rtn_kwargs(config_kwargs) -> dict:+ """Return explicit opt-RTN kwargs from direct entry/CLI arguments."""+ if config_kwargs.get("enable_opt_rtn"):+ return {"enable_opt_rtn": True}+ if config_kwargs.get("disable_opt_rtn") is not None:+ return {"disable_opt_rtn": config_kwargs["disable_opt_rtn"]}+ return {}+++def rtn_inherited_opt_kwargs(config_kwargs, awq_disable_opt_rtn_value) -> dict:+ """Return RTN kwargs where explicit user policy wins over AWQ inheritance."""+ opt_kwargs = direct_opt_rtn_kwargs(config_kwargs)+ if not opt_kwargs and awq_disable_opt_rtn_value is not None:+ opt_kwargs["disable_opt_rtn"] = awq_disable_opt_rtn_value+ return opt_kwargs+++def sync_rtn_opt_rtn_from_awq(configs) -> None:+ """Apply AWQ's opt-RTN policy to RTN configs that did not set one explicitly."""+ from auto_round.algorithms.quantization.rtn.config import RTNConfig++ awq_value = awq_disable_opt_rtn(configs)+ if awq_value is None:+ return+ for config in configs:+ if isinstance(config, RTNConfig) and getattr(config, "orig_disable_opt_rtn", None) is None:+ config.disable_opt_rtn = awq_value+ config.orig_disable_opt_rtn = awq_value++class AWQConfig(QuantizationConfig):"""Configuration for AWQ (Activation-Aware Weight Quantization).@@ -49,6 +95,7 @@ class AWQConfig(QuantizationConfig):clip_n_sample_token: int = 512,awq_seqlen: int | None = None,smooth_batch_size: int | None = None,+ disable_opt_rtn: bool | None = True,skip_moe: bool = True,mappings: list[dict] | None = None,**kwargs,@@ -120,6 +167,11 @@ class AWQConfig(QuantizationConfig):peak VRAM while preserving the AWQ parent-output loss, at thecost of more parent forward calls. ``None`` or ``<= 0`` replaysthe cached calibration batch as-is.+ disable_opt_rtn: Whether AWQ's internal weight QDQ should use the+ plain RTN path. Defaults to True because AWQ calibration has not+ shown accuracy or cost benefits from optimized RTN in benchmarks.+ ``enable_opt_rtn=True`` may also be passed to force the+ optimized path.skip_moe: Whether to exclude routed MoE experts from AWQ smoothing.When True, balance layers belonging to routed experts (modulenames matching ``.experts.<N>.``) are dropped from the resolved@@ -135,6 +187,9 @@ class AWQConfig(QuantizationConfig):QuantizationConfig, such as bits, group_size, sym,data_type, and activation quantization fields."""+ enable_opt_rtn = kwargs.pop("enable_opt_rtn", None)+ if enable_opt_rtn:+ disable_opt_rtn = Falsesuper().__init__(**kwargs)if awq_seqlen is None:@@ -163,6 +218,7 @@ class AWQConfig(QuantizationConfig):raise ValueError(f"`clip_n_sample_token` must be a positive integer, got {clip_n_sample_token!r}")if smooth_batch_size is not None and smooth_batch_size < 0:raise ValueError(f"`smooth_batch_size` must be a non-negative integer or None, got {smooth_batch_size!r}")+ self._disable_opt_rtn = disable_opt_rtnself.clip_n_grid = clip_n_gridself.clip_max_shrink = clip_max_shrinkself.clip_n_sample_token = clip_n_sample_token@@ -173,6 +229,15 @@ class AWQConfig(QuantizationConfig):self.infer_bs_coeff = 1self.batch_dim = None+ @property+ def disable_opt_rtn(self) -> bool | None:+ """Whether AWQ's internal QDQ uses plain RTN instead of optimized RTN."""+ return self._disable_opt_rtn++ @disable_opt_rtn.setter+ def disable_opt_rtn(self, value: bool | None) -> None:+ self._disable_opt_rtn = value+def finalize_scheme(self) -> None:"""Adjust AWQ state that depends on the resolved run scheme."""data_type = self.data_type@@ -191,6 +256,7 @@ class AWQConfig(QuantizationConfig):f"smooth_iters={self.smooth_iters}, "f"apply_clip={self.apply_clip}, clip_as_init={self.clip_as_init}, "f"awq_seqlen={self.awq_seqlen}, smooth_batch_size={self.smooth_batch_size}, "+ f"disable_opt_rtn={self.disable_opt_rtn}, "f"skip_moe={self.skip_moe}, "f"bits={self.bits}, group_size={self.group_size}, sym={self.sym}, "f"mappings={'<explicit>' if self.mappings else 'auto'})"diff --git a/auto_round/algorithms/transforms/awq/qdq.py b/auto_round/algorithms/transforms/awq/qdq.pyindex 4c98acdbb..2a51956a2 100644--- a/auto_round/algorithms/transforms/awq/qdq.py+++ b/auto_round/algorithms/transforms/awq/qdq.py@@ -62,16 +62,32 @@ class QDQTool:self.disable_opt_rtn: bool | None = Noneself.use_v2_scale_search: bool = False- # # ── runtime wiring ────────────────────────────────────────────────────────- def configure(self, composer) -> None:+ # ── runtime wiring ────────────────────────────────────────────────────────+ @staticmethod+ def _block_quantizer_config(block_quantizer_or_composer):+ """Return the terminal block-quantizer config from new or legacy hosts."""+ block_quantizer = getattr(block_quantizer_or_composer, "block_quantizer", block_quantizer_or_composer)+ config = getattr(block_quantizer, "config", None)+ if config is not None:+ return config+ return getattr(block_quantizer_or_composer, "quantize_config", None)++ def configure(self, composer, awq_config=None) -> None:"""Derive QDQ behaviour from the run's block quantizer."""- self.disable_opt_rtn = bool(getattr(composer.block_quantizer, "disable_opt_rtn", False))- self.use_v2_scale_search = self._block_quantizer_is_signroundv2(composer.block_quantizer)+ block_config = self._block_quantizer_config(composer)+ awq_disable_opt_rtn = getattr(awq_config, "disable_opt_rtn", None)+ if awq_disable_opt_rtn is None:+ awq_disable_opt_rtn = getattr(block_config, "disable_opt_rtn", False)+ self.disable_opt_rtn = bool(awq_disable_opt_rtn)+ self.use_v2_scale_search = self._block_quantizer_is_signroundv2(composer)@staticmethod- def _block_quantizer_is_signroundv2(quantizer) -> bool:+ def _block_quantizer_is_signroundv2(block_quantizer_or_composer) -> bool:"""Return ``True`` if the terminal block quantizer is SignRoundV2."""- return quantizer.__class__.__name__ == "SignRoundV2Quantizer"+ from auto_round.algorithms.quantization.sign_round.config import SignRoundV2Config++ config = QDQTool._block_quantizer_config(block_quantizer_or_composer)+ return isinstance(config, SignRoundV2Config)# ── per-layer scheme resolution + dispatch ────────────────────────────────def _layer_config_for(self, layer: torch.nn.Module) -> dict:diff --git a/auto_round/autoround.py b/auto_round/autoround.pyindex f3dfe570f..9370a5268 100644--- a/auto_round/autoround.py+++ b/auto_round/autoround.py@@ -383,6 +383,8 @@ _AWQ_FIELDS = {"clip_n_sample_token","awq_seqlen","smooth_batch_size",+ "disable_opt_rtn",+ "enable_opt_rtn","skip_moe","mappings",}@@ -433,6 +435,11 @@ def _normalize_alg_configs(alg_configs, direct_kwargs=None):from auto_round.algorithms.quantization.rtn.config import RTNConfigfrom auto_round.algorithms.registry import normalize_algorithm_config, resolve_alg_config, resolve_algorithm_namesfrom auto_round.algorithms.transforms import normalize_rotation_config+ from auto_round.algorithms.transforms.awq.config import (+ awq_disable_opt_rtn,+ rtn_inherited_opt_kwargs,+ sync_rtn_opt_rtn_from_awq,+ )from auto_round.algorithms.transforms.base import BaseRotationConfigdirect_kwargs = dict(direct_kwargs or {})@@ -476,8 +483,14 @@ def _normalize_alg_configs(alg_configs, direct_kwargs=None):raw_configs = [alg_configs]configs = []+ pending_rtn_indices = []for raw_config in raw_configs:- config = resolve_alg_config(raw_config) if isinstance(raw_config, str) else raw_config+ if isinstance(raw_config, str) and raw_config == "rtn":+ pending_rtn_indices.append(len(configs))+ configs.append(None)+ continue+ else:+ config = resolve_alg_config(raw_config) if isinstance(raw_config, str) else raw_configif not isinstance(config, (QuantizationConfig, BaseRotationConfig)):raise TypeError(f"alg_configs entries must be algorithm or QuantizationConfig instances, "@@ -485,6 +498,11 @@ def _normalize_alg_configs(alg_configs, direct_kwargs=None):)configs.append(normalize_algorithm_config(config))+ awq_opt_rtn_policy = awq_disable_opt_rtn(configs)+ for index in pending_rtn_indices:+ config = RTNConfig(**rtn_inherited_opt_kwargs(config_kwargs, awq_opt_rtn_policy))+ configs[index] = normalize_algorithm_config(config)+# ``iters=0`` has always selected RTN in the public entry and CLI. Apply# that rule after every input form has become a config so aliases, config# objects, and the deprecated ``algorithm`` argument cannot choose@@ -495,7 +513,8 @@ def _normalize_alg_configs(alg_configs, direct_kwargs=None):for index, config in enumerate(configs):effective_iters = direct_iters if direct_iters is not None else getattr(config, "iters", None)if isinstance(config, SignRoundConfig) and effective_iters == 0:- rtn_config = RTNConfig(scheme=config.scheme.copy())+ rtn_kwargs = rtn_inherited_opt_kwargs(config_kwargs, awq_disable_opt_rtn(configs))+ rtn_config = RTNConfig(scheme=config.scheme.copy(), **rtn_kwargs)rtn_config._user_set_scheme_fields = set(getattr(config, "_user_set_scheme_fields", set()))configs[index] = normalize_algorithm_config(rtn_config)@@ -512,12 +531,35 @@ def _normalize_alg_configs(alg_configs, direct_kwargs=None):preprocessors, block_configs = split_quantization_configs(configs)if preprocessors and not block_configs:- configs.append(normalize_algorithm_config(RTNConfig()))+ fallback_rtn_kwargs = rtn_inherited_opt_kwargs(config_kwargs, awq_disable_opt_rtn(configs))+ configs.append(normalize_algorithm_config(RTNConfig(**fallback_rtn_kwargs)))_, block_configs = split_quantization_configs(configs)for key, value in config_kwargs.items():if value is None:continue+ if key in ("disable_opt_rtn", "enable_opt_rtn"):+ if key == "enable_opt_rtn" and not value:+ continue+ opt_rtn_value = False if key == "enable_opt_rtn" else value+ targets = [config for config in configs if "disable_opt_rtn" in _config_fields(config)]+ if not targets:+ logger.warning_once(+ "RTN-specific parameter '%s' was provided, but RTN/AWQ is not enabled by alg_configs. "+ "The parameter is ignored.",+ key,+ )+ continue+ for target in targets:+ target.disable_opt_rtn = opt_rtn_value+ if hasattr(target, "orig_disable_opt_rtn"):+ target.orig_disable_opt_rtn = opt_rtn_value+ logger.warning(+ "Passing '%s' directly to AutoRound is supported, but the recommended usage is "+ "'alg_configs=\"awq\"' or 'alg_configs=\"rtn\"'.",+ key,+ )+ continueif key in _SCHEME_FIELDS:targets = block_configselse:@@ -545,18 +587,15 @@ def _normalize_alg_configs(alg_configs, direct_kwargs=None):)continuetarget = targets[0]- if key in ("disable_opt_rtn", "enable_opt_rtn"):- if key == "disable_opt_rtn" or value:- target.disable_opt_rtn = False if key == "enable_opt_rtn" else value- target.orig_disable_opt_rtn = target.disable_opt_rtn- else:- setattr(target, key, value)+ setattr(target, key, value)+ recommended_config_name = type(target).__name__.replace("Config", "")logger.warning("Passing '%s' directly to AutoRound is supported, but the recommended usage is ""'alg_configs=%sConfig(...)'.",key,- type(targets[0]).__name__.replace("Config", ""),+ recommended_config_name,)+ sync_rtn_opt_rtn_from_awq(configs)return [normalize_algorithm_config(config) for config in configs]@@ -638,6 +677,20 @@ class _CompressorBuilder(object):if is_svdquant:format = "svdquant_nunchaku"+ # Any preprocessor that requires calibration data (e.g. AWQ, SVDQuant+ # smoothing) must run on the regular model-loaded path; model-free RTN+ # cannot replay their calibration.+ calibration_preprocessors = [+ type(config).__name__ for config in preprocessor_configs if getattr(config, "need_calib", False)+ ]+ has_calibration_preprocessor = bool(calibration_preprocessors)+ if has_calibration_preprocessor and route_kwargs.get("model_free", False):+ raise ValueError(+ "model_free=True is not supported with calibration-based preprocessor algorithms "+ f"({', '.join(calibration_preprocessors)}). "+ "Use the regular flow so the model can be loaded for calibration."+ )+# Model-free routing is now supported directly by the new entry path.model_free_iters = 0 if isinstance(quant_config, RTNConfig) else getattr(quant_config, "iters", None)model_free_disable_opt_rtn = getattr(quant_config, "disable_opt_rtn", None)@@ -650,6 +703,10 @@ class _CompressorBuilder(object):if is_svdquant_rtn and not route_kwargs.get("model_free", False):# SVDQuant must run before plain RTN on the regular blockwise path.route_decision_kwargs["disable_model_free"] = True+ if has_calibration_preprocessor:+ # Calibration-based preprocessors need the model loaded for+ # calibration; model-free RTN cannot apply their transforms.+ route_decision_kwargs["disable_model_free"] = Trueroute_scheme = (schemeif hasattr(scheme, "options") and hasattr(scheme, "avg_bits")diff --git a/auto_round/cli/algorithms.py b/auto_round/cli/algorithms.pyindex fb07b5263..b82a0754a 100644--- a/auto_round/cli/algorithms.py+++ b/auto_round/cli/algorithms.py@@ -14,6 +14,7 @@ No manual registry update needed — subclasses are auto-registered on definitiofrom __future__ import annotationsimport argparse+import copyfrom abc import ABC, abstractmethodfrom typing import Any, ClassVar@@ -115,16 +116,34 @@ class AlgorithmHandler(ABC):canonical = resolve_algorithm_names(names, ignore_unknown=True)seen = set(canonical)- # Default quantization algorithm if none was specified- if not ({"awq", "rtn", "auto_round"} & seen):- canonical.append("rtn" if getattr(args, "iters", 0) == 0 else "auto_round")+ # Default terminal quantizer if none was specified. AWQ is a+ # calibration preprocessor; AWQ-only pipelines intentionally default to+ # RTN so RTN CLI flags such as --disable_opt_rtn are applied before the+ # lower-level composer has to append a fallback quantizer.+ if not ({"rtn", "auto_round"} & seen):+ default_quantizer = "rtn" if "awq" in seen or getattr(args, "iters", 0) == 0 else "auto_round"+ canonical.append(default_quantizer)# Keep the legacy API rule even when the user explicitly spells out# ``--algorithm auto_round``: zero iterations select RTN.if getattr(args, "iters", None) == 0:canonical = ["rtn" if name == "auto_round" else name for name in canonical]- return [cls.get(name).build(args, common_kwargs) for name in canonical]+ explicit_opt_rtn = getattr(args, "disable_opt_rtn", None) is not None+ awq_config = cls.get("awq").build(args, common_kwargs) if "awq" in canonical else None+ awq_disable_opt_rtn = getattr(awq_config, "disable_opt_rtn", None)++ configs = []+ for name in canonical:+ if name == "awq":+ configs.append(awq_config)+ continue+ build_args = args+ if name == "rtn" and not explicit_opt_rtn and awq_disable_opt_rtn is not None:+ build_args = copy.copy(args)+ setattr(build_args, "disable_opt_rtn", awq_disable_opt_rtn)+ configs.append(cls.get(name).build(build_args, common_kwargs))+ return configs@classmethoddef format_listing(cls) -> str:@@ -242,6 +261,7 @@ class AWQ(AlgorithmHandler):from auto_round.algorithms.transforms.awq.config import AWQConfigawq_seqlen = getattr(args, "awq_seqlen", None)+ disable_opt_rtn = getattr(args, "disable_opt_rtn", None)return AWQConfig(duo_scaling=getattr(args, "duo_scaling", True),n_grid=getattr(args, "n_grid", 20),@@ -249,6 +269,7 @@ class AWQ(AlgorithmHandler):clip_as_init=getattr(args, "awq_clip_as_init", False),awq_seqlen=512 if awq_seqlen is None else awq_seqlen,smooth_batch_size=getattr(args, "awq_smooth_batch_size", None),+ disable_opt_rtn=True if disable_opt_rtn is None else disable_opt_rtn,**common_kwargs,)diff --git a/auto_round/cli/parser.py b/auto_round/cli/parser.pyindex 7175a1f8c..570fe52b8 100644--- a/auto_round/cli/parser.py+++ b/auto_round/cli/parser.py@@ -126,6 +126,8 @@ def build_quantize_parser(*, prog: str = "auto_round quantize") -> argparse.Argu"--algorithms","--alg","--algs",+ "--alg_config",+ "--alg_configs",default=None,type=str,help="Comma-separated algorithms such as 'awq' or 'awq,auto_round'.",diff --git a/docs/awq_details.md b/docs/awq_details.mdnew file mode 100644index 000000000..a519e71d9--- /dev/null+++ b/docs/awq_details.md@@ -0,0 +1,689 @@+# AWQ Algorithm Results++This document summarizes an experimental comparison between native AutoRound flows and AWQ-composed flows. The goal is to evaluate whether applying AWQ smoothing before RTN or AutoRound improves accuracy for `W4A16`, `MXFP4`, and `INT8` (`W8A8`) schemes.++All results were measured with `--format fake` and evaluated on `mmlu,gsm8k,piqa,hellaswag,winogrande`. These five widely used LLM benchmarks cover complementary error modes: MMLU for factual knowledge and broad understanding, GSM8K for mathematical reasoning, PIQA for physical commonsense, HellaSwag for commonsense sentence completion, and Winogrande for pronoun and coreference resolution. Reporting the average score across this task set reduces sensitivity to single-task variance and provides a more stable view of quantization-induced accuracy changes. Unless noted otherwise, the remaining quantization settings follow the AutoRound defaults.++## AWQ Algorithm Characteristics++AWQ is an activation-aware weight smoothing method. It searches for per-channel scaling factors from calibration activations, applies the scaling to reduce quantization-sensitive weight channels, and then hands the transformed model to the terminal quantization algorithm.++AWQ changes the pre-quantization weight distribution, while RTN, AutoRound, and AutoRound2 decide how the final quantized values are produced. In this design, AWQ can be composed with different quantizers without changing their core optimization logic.++From the resource perspective, AWQ does not introduce a persistent RAM or VRAM burden in the quantized model. During calibration, `AWQ_RTN` stays around the same host RAM level as the other flows and uses much less VRAM than iterative AutoRound flows. When AWQ is followed by AutoRound or AutoRound2, the peak VRAM is mainly determined by the downstream AutoRound optimization rather than by AWQ itself.++The main added cost is timecost and the increase is acceptable when AWQ provides measurable accuracy gains, especially for MXFP4 and selected W4A16 cases.++The configurations in the tables map to the following CLI usage:++```bash+# Pure RTN baseline+auto-round-rtn --model <model> --scheme <scheme> --format fake \+ --tasks "mmlu,gsm8k,piqa,hellaswag,winogrande"++# Optimized RTN baseline+auto-round-opt-rtn --model <model> --scheme <scheme> --format fake \+ --tasks "mmlu,gsm8k,piqa,hellaswag,winogrande"++# Native AutoRound / AutoRound with algorithm extension+auto-round --model <model> --scheme <scheme> --format fake \+ --algorithm auto_round \+ --tasks "mmlu,gsm8k,piqa,hellaswag,winogrande"++auto-round --model <model> --scheme <scheme> --format fake \+ --enable_alg_ext --algorithm auto_round \+ --tasks "mmlu,gsm8k,piqa,hellaswag,winogrande"++# AWQ + RTN / AWQ + AutoRound / AWQ + AutoRound with algorithm extension+auto-round --model <model> --scheme <scheme> --format fake \+ --algorithm awq \+ --tasks "mmlu,gsm8k,piqa,hellaswag,winogrande"++auto-round --model <model> --scheme <scheme> --format fake \+ --algorithm awq,auto_round \+ --tasks "mmlu,gsm8k,piqa,hellaswag,winogrande"++auto-round --model <model> --scheme <scheme> --format fake \+ --enable_alg_ext --algorithm awq,auto_round \+ --tasks "mmlu,gsm8k,piqa,hellaswag,winogrande"+```++In the result tables, `AR2` denotes AutoRound with `--enable_alg_ext`, and `AWQ_AR2` denotes AWQ followed by AutoRound with `--enable_alg_ext`.++In the observation tables, `AVG Win Rate` counts how often the AWQ-composed method improves model-level AVG accuracy for that scheme, `Max AVG Delta Gain` is the largest absolute AVG improvement in percentage points, and `Max AVG Rel. Gain` is the largest relative AVG improvement. For `AWQ_RTN`, the comparison includes both `RTN` and `opt_rtn` when both baselines are available.++## MXFP4++**Note: For Llama-3.1-Instruct, we recommend removing `@use_kernel_forward_from_hub("RMSNorm")` in [modeling_llama.py](https://github.com/huggingface/transformers/blob/main/src/transformers/models/llama/modeling_llama.py#L52C1-L52C40); the tests below did not remove it, which can make the accuracy results inaccurate.**++<table border="1">+ <tr>+ <td>Model</td>+ <td>Config</td>+ <td>GSM8K (%)</td>+ <td>HellaSwag (%)</td>+ <td>MMLU (%)</td>+ <td>PIQA (%)</td>+ <td>WinoGrande (%)</td>+ <td>AVG (%)</td>+ <td>Timecost</td>+ <td>RAM</td>+ <td>VRAM</td>+ </tr>+ <tr>+ <td rowspan="8">Llama-3.1-8B-I</td>+ <td>BF16</td>+ <td>70.51</td>+ <td>59.71</td>+ <td>68.37</td>+ <td>80.09</td>+ <td>73.40</td>+ <td>70.42</td>+ <td>-</td>+ <td>-</td>+ <td>-</td>+ </tr>+ <tr>+ <td>RTN</td>+ <td>59.06</td>+ <td>58.88</td>+ <td>64.63</td>+ <td>78.94</td>+ <td>72.77</td>+ <td>66.86</td>+ <td>72.30</td>+ <td>25.52GB</td>+ <td>0.83GB</td>+ </tr>+ <tr>+ <td>opt_rtn</td>+ <td>65.20</td>+ <td>58.91</td>+ <td>65.04</td>+ <td>79.05</td>+ <td>73.48</td>+ <td>68.34</td>+ <td>62.00</td>+ <td>25.65GB</td>+ <td>1.65GB</td>+ </tr>+ <!-- TODO: MXFP4 Llama-3.1 AR data is anomalous (GSM8K=0.00, AVG=43.13); treat as preliminary and revisit for now. -->+ <tr>+ <td>AR</td>+ <td>0.00</td>+ <td>31.20</td>+ <td>48.50</td>+ <td>75.24</td>+ <td>60.69</td>+ <td>43.13</td>+ <td>959.21</td>+ <td>25.39GB</td>+ <td>16.30GB</td>+ </tr>+ <tr>+ <td>AR2</td>+ <td>67.32</td>+ <td>57.94</td>+ <td>64.11</td>+ <td>80.25</td>+ <td>73.80</td>+ <td>68.68</td>+ <td>1104.91</td>+ <td>24.38GB</td>+ <td>17.78GB</td>+ </tr>+ <tr>+ <td>AWQ_RTN</td>+ <td>66.26</td>+ <td>58.36</td>+ <td>66.12</td>+ <td>79.00</td>+ <td>73.95</td>+ <td>68.74</td>+ <td>1132.04</td>+ <td>24.36GB</td>+ <td>7.60GB</td>+ </tr>+ <tr>+ <td>AWQ_AR</td>+ <td>69.75</td>+ <td>57.74</td>+ <td>65.71</td>+ <td>79.27</td>+ <td>72.69</td>+ <td>69.03</td>+ <td>2136.06</td>+ <td>24.47GB</td>+ <td>19.24GB</td>+ </tr>+ <tr>+ <td><b>AWQ_AR2</b></td>+ <td><b>71.27</b></td>+ <td><b>58.29</b></td>+ <td><b>66.07</b></td>+ <td><b>80.25</b></td>+ <td><b>73.88</b></td>+ <td><b>69.95</b></td>+ <td><b>2274.64</b></td>+ <td><b>24.40GB</b></td>+ <td><b>18.12GB</b></td>+ </tr>+ <tr>+ <td rowspan="8">Qwen3-8B</td>+ <td>BF16</td>+ <td>87.41</td>+ <td>57.16</td>+ <td>72.92</td>+ <td>76.71</td>+ <td>67.72</td>+ <td>72.38</td>+ <td>-</td>+ <td>-</td>+ <td>-</td>+ </tr>+ <tr>+ <td>RTN</td>+ <td>86.05</td>+ <td>55.07</td>+ <td>70.30</td>+ <td>75.41</td>+ <td>66.93</td>+ <td>70.75</td>+ <td>61.00</td>+ <td>23.23GB</td>+ <td>0.74GB</td>+ </tr>+ <tr>+ <td>opt_rtn</td>+ <td>86.50</td>+ <td>55.53</td>+ <td>70.64</td>+ <td>75.79</td>+ <td>66.77</td>+ <td>71.05</td>+ <td>66.00</td>+ <td>23.55GB</td>+ <td>1.40GB</td>+ </tr>+ <tr>+ <td>AR</td>+ <td>86.73</td>+ <td>54.90</td>+ <td>71.56</td>+ <td>76.44</td>+ <td>70.09</td>+ <td>71.94</td>+ <td>968.45</td>+ <td>22.32GB</td>+ <td>15.68GB</td>+ </tr>+ <tr>+ <td>AR2</td>+ <td>86.58</td>+ <td>55.07</td>+ <td>71.86</td>+ <td>76.61</td>+ <td>69.77</td>+ <td>71.98</td>+ <td>1195.57</td>+ <td>22.35GB</td>+ <td>16.00GB</td>+ </tr>+ <tr>+ <td>AWQ_RTN</td>+ <td>85.90</td>+ <td>55.79</td>+ <td>71.54</td>+ <td>76.93</td>+ <td>67.80</td>+ <td>71.59</td>+ <td>1088.34</td>+ <td>22.34GB</td>+ <td>6.93GB</td>+ </tr>+ <tr>+ <td>AWQ_AR</td>+ <td>85.37</td>+ <td>54.41</td>+ <td>71.47</td>+ <td>76.55</td>+ <td>70.32</td>+ <td>71.62</td>+ <td>2346.84</td>+ <td>22.45GB</td>+ <td>16.75GB</td>+ </tr>+ <tr>+ <td><b>AWQ_AR2</b></td>+ <td><b>86.66</b></td>+ <td><b>55.19</b></td>+ <td><b>71.99</b></td>+ <td><b>77.37</b></td>+ <td><b>70.80</b></td>+ <td><b>72.40</b></td>+ <td><b>2266.50</b></td>+ <td><b>22.37GB</b></td>+ <td><b>16.16GB</b></td>+ </tr>+</table>++### MXFP4 Observations++| Comparison | AVG Win Rate | Max AVG Delta Gain | Max AVG Rel. Gain |+| --- | ---: | ---: | ---: |+| `AWQ_RTN` vs `RTN` / `opt_rtn` | 4/4 (100%) | +1.88 pts | +2.81% |+| `AWQ_AR` vs `AR` | 1/2 (50%) | +25.90 pts | +60.05%* |+| `AWQ_AR2` vs `AR2` | 2/2 (100%) | +1.27 pts | +1.85% |++*The Llama `AWQ_AR` vs `AR` result is inflated by the unstable native `AR` baseline (`GSM8K=0.00`, `AVG=43.13`).++- MXFP4 is the strongest case for AWQ composition. `AWQ_RTN` improves over both `RTN` and `opt_rtn` on both models, and `AWQ_AR2` improves over `AR2` on both models.+- `AWQ_AR2` gives the most consistent MXFP4 profile: AVG improves on both models, with up to +1.27 points and +1.85% relative AVG gain.+- `AWQ_AR` is not uniformly reliable. The large Llama gain is driven by an unstable native `AR` baseline, while Qwen `AWQ_AR` is below native `AR` on AVG.+- The tradeoff remains runtime and VRAM. `AWQ_RTN` costs around 18x the `RTN` runtime, while `AWQ_AR` / `AWQ_AR2` cost about 2x native `AR` / `AR2` on MXFP4.++## W4A16++<table border="1">+ <tr>+ <td>Model</td>+ <td>Config</td>+ <td>GSM8K (%)</td>+ <td>HellaSwag (%)</td>+ <td>MMLU (%)</td>+ <td>PIQA (%)</td>+ <td>WinoGrande (%)</td>+ <td>AVG (%)</td>+ <td>Timecost</td>+ <td>RAM</td>+ <td>VRAM</td>+ </tr>+ <tr>+ <td rowspan="8">Llama-3.1-8B-I</td>+ <td>BF16</td>+ <td>70.51</td>+ <td>59.71</td>+ <td>68.37</td>+ <td>80.09</td>+ <td>73.40</td>+ <td>70.42</td>+ <td>-</td>+ <td>-</td>+ <td>-</td>+ </tr>+ <tr>+ <td>RTN</td>+ <td>71.80</td>+ <td>59.14</td>+ <td>65.46</td>+ <td>79.43</td>+ <td>72.77</td>+ <td>69.72</td>+ <td>60.00</td>+ <td>25.08GB</td>+ <td>0.56GB</td>+ </tr>+ <tr>+ <td>opt_rtn</td>+ <td>67.63</td>+ <td>58.99</td>+ <td>65.67</td>+ <td>78.94</td>+ <td>73.95</td>+ <td>69.04</td>+ <td>162.30</td>+ <td>28.31GB</td>+ <td>7.90GB</td>+ </tr>+ <tr>+ <td>AR</td>+ <td>67.40</td>+ <td>58.93</td>+ <td>66.81</td>+ <td>79.87</td>+ <td>73.72</td>+ <td>69.35</td>+ <td>769.27</td>+ <td>24.29GB</td>+ <td>12.32GB</td>+ </tr>+ <tr>+ <td>AR2</td>+ <td>69.60</td>+ <td>59.13</td>+ <td>66.81</td>+ <td>79.87</td>+ <td>73.09</td>+ <td>69.70</td>+ <td>918.59</td>+ <td>24.04GB</td>+ <td>13.26GB</td>+ </tr>+ <tr>+ <td>AWQ_RTN</td>+ <td>70.58</td>+ <td>59.09</td>+ <td>65.89</td>+ <td>79.87</td>+ <td>72.85</td>+ <td>69.66</td>+ <td>1075.44</td>+ <td>24.07GB</td>+ <td>7.68GB</td>+ </tr>+ <tr>+ <td><b>AWQ_AR</b></td>+ <td><b>73.24</b></td>+ <td><b>59.11</b></td>+ <td><b>66.97</b></td>+ <td><b>80.14</b></td>+ <td><b>72.93</b></td>+ <td><b>70.48</b></td>+ <td><b>1813.51</b></td>+ <td><b>24.07GB</b></td>+ <td><b>13.32GB</b></td>+ </tr>+ <tr>+ <td>AWQ_AR2</td>+ <td>70.13</td>+ <td>59.09</td>+ <td>67.11</td>+ <td>79.87</td>+ <td>73.56</td>+ <td>69.95</td>+ <td>3533.26</td>+ <td>24.07GB</td>+ <td>13.17GB</td>+ </tr>+ <tr>+ <td rowspan="8">Qwen3-8B</td>+ <td>BF16</td>+ <td>87.41</td>+ <td>57.16</td>+ <td>72.92</td>+ <td>76.71</td>+ <td>67.72</td>+ <td>72.38</td>+ <td>-</td>+ <td>-</td>+ <td>-</td>+ </tr>+ <tr>+ <td>RTN</td>+ <td>86.43</td>+ <td>56.18</td>+ <td>70.84</td>+ <td>75.52</td>+ <td>67.17</td>+ <td>71.23</td>+ <td>97.00</td>+ <td>23.10GB</td>+ <td>0.50GB</td>+ </tr>+ <tr>+ <td>opt_rtn</td>+ <td>87.26</td>+ <td>55.96</td>+ <td>71.58</td>+ <td>76.33</td>+ <td>68.43</td>+ <td>71.91</td>+ <td>180.17</td>+ <td>27.17GB</td>+ <td>7.38GB</td>+ </tr>+ <tr>+ <td>AR</td>+ <td>88.02</td>+ <td>56.03</td>+ <td>72.13</td>+ <td>76.22</td>+ <td>67.72</td>+ <td>72.02</td>+ <td>779.03</td>+ <td>21.73GB</td>+ <td>11.41GB</td>+ </tr>+ <tr>+ <td>AR2</td>+ <td>86.96</td>+ <td>55.95</td>+ <td>72.38</td>+ <td>76.71</td>+ <td>68.27</td>+ <td>72.05</td>+ <td>1028.79</td>+ <td>22.00GB</td>+ <td>12.48GB</td>+ </tr>+ <tr>+ <td>AWQ_RTN</td>+ <td>86.13</td>+ <td>56.04</td>+ <td>71.91</td>+ <td>75.63</td>+ <td>67.56</td>+ <td>71.45</td>+ <td>1108.32</td>+ <td>22.02GB</td>+ <td>6.93GB</td>+ </tr>+ <tr>+ <td>AWQ_AR</td>+ <td>86.73</td>+ <td>56.13</td>+ <td>71.51</td>+ <td>76.22</td>+ <td>69.06</td>+ <td>71.93</td>+ <td>1957.19</td>+ <td>21.94GB</td>+ <td>12.07GB</td>+ </tr>+ <tr>+ <td><b>AWQ_AR2</b></td>+ <td><b>86.50</b></td>+ <td><b>56.07</b></td>+ <td><b>72.23</b></td>+ <td><b>76.55</b></td>+ <td><b>69.14</b></td>+ <td><b>72.10</b></td>+ <td><b>3673.00</b></td>+ <td><b>22.03GB</b></td>+ <td><b>12.79GB</b></td>+ </tr>+</table>++### W4A16 Observations++| Comparison | AVG Win Rate | Max AVG Delta Gain | Max AVG Rel. Gain |+| --- | ---: | ---: | ---: |+| `AWQ_RTN` vs `RTN` / `opt_rtn` | 2/4 (50%) | +0.62 pts | +0.90% |+| `AWQ_AR` vs `AR` | 1/2 (50%) | +1.13 pts | +1.63% |+| `AWQ_AR2` vs `AR2` | 2/2 (100%) | +0.25 pts | +0.36% |++- W4A16 shows model-dependent behavior. The clearest gain is Llama `AWQ_AR` over `AR`, with +1.13 average points and +1.63% relative AVG gain.+- `AWQ_RTN` is not a strong W4A16 default. It wins 2/4 AVG comparisons against `RTN` and `opt_rtn`.+- `AWQ_AR2` improves AVG on both models, but the gain is small compared with the added runtime.++## INT8 / W8A8++<table border="1">+ <tr>+ <td>Model</td>+ <td>Config</td>+ <td>GSM8K (%)</td>+ <td>HellaSwag (%)</td>+ <td>MMLU (%)</td>+ <td>PIQA (%)</td>+ <td>WinoGrande (%)</td>+ <td>AVG (%)</td>+ <td>Timecost</td>+ <td>RAM</td>+ <td>VRAM</td>+ </tr>+ <tr>+ <td rowspan="6">Llama-3.1-8B-I</td>+ <td>BF16</td>+ <td>70.51</td>+ <td>59.71</td>+ <td>68.37</td>+ <td>80.09</td>+ <td>73.40</td>+ <td>70.42</td>+ <td>-</td>+ <td>-</td>+ <td>-</td>+ </tr>+ <tr>+ <td>RTN</td>+ <td>71.49</td>+ <td>59.64</td>+ <td>68.37</td>+ <td>80.30</td>+ <td>74.27</td>+ <td>70.81</td>+ <td>58.00</td>+ <td>25.00GB</td>+ <td>0.56GB</td>+ </tr>+ <tr>+ <td>AR</td>+ <td>69.90</td>+ <td>59.62</td>+ <td>68.36</td>+ <td>80.36</td>+ <td>73.64</td>+ <td>70.38</td>+ <td>836.48</td>+ <td>24.90GB</td>+ <td>13.63GB</td>+ </tr>+ <tr>+ <td>AWQ_RTN</td>+ <td>73.24</td>+ <td>59.66</td>+ <td>68.30</td>+ <td>80.09</td>+ <td>73.32</td>+ <td>70.92</td>+ <td>1052.19</td>+ <td>23.98GB</td>+ <td>7.67GB</td>+ </tr>+ <tr>+ <td>AWQ_AR</td>+ <td>68.99</td>+ <td>59.77</td>+ <td>68.12</td>+ <td>80.30</td>+ <td>73.09</td>+ <td>70.05</td>+ <td>1228.53</td>+ <td>24.10GB</td>+ <td>14.29GB</td>+ </tr>+ <tr>+ <td><b>RTN_smooth2048_clip</b></td>+ <td><b>72.93</b></td>+ <td><b>59.89</b></td>+ <td><b>68.27</b></td>+ <td><b>80.14</b></td>+ <td><b>73.95</b></td>+ <td><b>71.04</b></td>+ <td><b>1668.43</b></td>+ <td><b>24.50GB</b></td>+ <td><b>18.46GB</b></td>+ </tr>+ <tr>+ <td rowspan="6">Qwen3-8B</td>+ <td>BF16</td>+ <td>87.41</td>+ <td>57.16</td>+ <td>72.92</td>+ <td>76.71</td>+ <td>67.72</td>+ <td>72.38</td>+ <td>-</td>+ <td>-</td>+ <td>-</td>+ </tr>+ <tr>+ <td>RTN</td>+ <td>87.79</td>+ <td>57.09</td>+ <td>72.90</td>+ <td>76.77</td>+ <td>67.80</td>+ <td>72.47</td>+ <td>84.00</td>+ <td>23.09GB</td>+ <td>0.50GB</td>+ </tr>+ <tr>+ <td>AR</td>+ <td>86.96</td>+ <td>56.57</td>+ <td>72.58</td>+ <td>77.20</td>+ <td>68.11</td>+ <td>72.28</td>+ <td>881.10</td>+ <td>23.66GB</td>+ <td>12.58GB</td>+ </tr>+ <tr>+ <td>AWQ_RTN</td>+ <td>86.96</td>+ <td>57.22</td>+ <td>72.85</td>+ <td>76.39</td>+ <td>68.27</td>+ <td>72.34</td>+ <td>1143.95</td>+ <td>21.93GB</td>+ <td>6.93GB</td>+ </tr>+ <tr>+ <td>AWQ_AR</td>+ <td>87.41</td>+ <td>56.80</td>+ <td>72.65</td>+ <td>76.71</td>+ <td>67.64</td>+ <td>72.24</td>+ <td>1324.51</td>+ <td>22.85GB</td>+ <td>13.40GB</td>+ </tr>+ <tr>+ <td><b>RTN_smooth2048_clip</b></td>+ <td><b>87.87</b></td>+ <td><b>57.14</b></td>+ <td><b>72.90</b></td>+ <td><b>76.66</b></td>+ <td><b>67.96</b></td>+ <td><b>72.51</b></td>+ <td><b>1796.55</b></td>+ <td><b>22.47GB</b></td>+ <td><b>15.77GB</b></td>+ </tr>+</table>++### INT8 Observations++| Comparison | AVG Win Rate | Max AVG Delta Gain | Max AVG Rel. Gain |+| --- | ---: | ---: | ---: |+| `AWQ_RTN` vs `RTN` | 1/2 (50%) | +0.11 pts | +0.16% |+| `AWQ_AR` vs `AR` | 0/2 (0%) | -0.04 pts | -0.06% |++- INT8/W8A8 is already a high-accuracy setting in these experiments. Most INT8 recipes are close to the BF16 reference, and some recipes slightly exceed BF16 AVG.+- The experimental `RTN_smooth2048_clip` rows give the best INT8 AVG for both models in this table: 71.04 on Llama and 72.51 on Qwen.+- In `RTN_smooth2048_clip`, `smooth2048` denotes AWQ calibration with sequence length 2048 (`awq_seqlen=2048`), and `clip` denotes AWQ weight clipping (`apply_clip=True`) enabled during the AWQ search.+- For AWQ-composed INT8, the AVG movement is small. Llama `AWQ_RTN` improves over `RTN` by +0.11 points (+0.16% relative), while the other AWQ-composed comparisons are slightly below their native counterparts.+- Given the strong INT8 baseline, AWQ is better positioned as an optional exploration path for INT8/W8A8 rather than a primary default.++## Summary++AWQ is most useful for schemes where quantization is sensitive to activation-aware weight smoothing, such as MXFP4. It can improve scheme accuracy, especially when combined with AutoRound plus `--enable_alg_ext`.+AWQ does not add persistent memory overhead to the quantized model and is orthogonal to terminal quantization algorithms, so it can be composed with RTN, AutoRound, or AutoRound2 without changing their core quantization logic.diff --git a/docs/awq_details_CN.md b/docs/awq_details_CN.mdnew file mode 100644index 000000000..ea8207bbc--- /dev/null+++ b/docs/awq_details_CN.md@@ -0,0 +1,292 @@+# AWQ 算法结果++本文总结了原生 AutoRound 流程与 AWQ 组合流程的实验对比。目标是评估在 `W4A16`、`MXFP4` 和 `INT8`(`W8A8`)方案下,在 RTN 或 AutoRound 之前加入 AWQ smoothing 是否能够提升准确率。++所有结果均使用 `--format fake` 测得,并在 `mmlu,gsm8k,piqa,hellaswag,winogrande` 上评估。这五个常用 LLM 基准覆盖互补的误差类型:MMLU 侧重事实知识与综合理解,GSM8K 侧重数学推理,PIQA 侧重物理常识,HellaSwag 侧重常识句子补全,Winogrande 侧重代词与指代消解。报告该任务集合的平均分,可以降低单个任务波动对结论的影响,并更稳定地反映量化引入的精度变化。除非特别说明,其余量化参数均采用 AutoRound 默认设置。++## AWQ 算法特点++AWQ 是一种 activation-aware 的权重平滑方法。它根据校准激活搜索逐通道 scaling factor,通过缩放降低对量化更敏感的权重通道,然后再把变换后的模型交给最终量化算法处理。++因此,AWQ 与 RTN、AutoRound 是正交关系:AWQ 改变的是量化前的权重分布,而 RTN、AutoRound、AutoRound2 决定最终量化值如何生成。这样的设计允许 AWQ 与不同终端量化算法组合,而不需要改变这些算法本身的核心优化逻辑。++从资源角度看,AWQ 不会给最终量化模型引入持续性的 RAM 或 VRAM 负担。在校准阶段,`AWQ_RTN` 的主机 RAM 与其他流程基本处于同一水平,VRAM 明显低于迭代式 AutoRound 流程。AWQ 后接 AutoRound 或 AutoRound2 时,峰值 VRAM 主要由后续 AutoRound 优化决定,而不是 AWQ 本身带来的固定开销。++AWQ 的主要额外成本是校准时间。对于 PTQ 来说,这属于一次性的离线成本;当 AWQ 带来明确准确率收益时,尤其是在 MXFP4 和部分 W4A16 场景中,这个时间增加是可以接受的。++表中的配置对应以下 CLI 用法:++```bash+# 原始 RTN 基线+auto-round-rtn --model <model> --scheme <scheme> --format fake \+ --tasks "mmlu,gsm8k,piqa,hellaswag,winogrande"++# 优化版 RTN 基线+auto-round-opt-rtn --model <model> --scheme <scheme> --format fake \+ --tasks "mmlu,gsm8k,piqa,hellaswag,winogrande"++# 原生 AutoRound / 启用算法扩展的 AutoRound+auto-round --model <model> --scheme <scheme> --format fake \+ --algorithm auto_round \+ --tasks "mmlu,gsm8k,piqa,hellaswag,winogrande"++auto-round --model <model> --scheme <scheme> --format fake \+ --enable_alg_ext --algorithm auto_round \+ --tasks "mmlu,gsm8k,piqa,hellaswag,winogrande"++# AWQ + RTN / AWQ + AutoRound / AWQ + 启用算法扩展的 AutoRound+auto-round --model <model> --scheme <scheme> --format fake \+ --algorithm awq \+ --tasks "mmlu,gsm8k,piqa,hellaswag,winogrande"++auto-round --model <model> --scheme <scheme> --format fake \+ --algorithm awq,auto_round \+ --tasks "mmlu,gsm8k,piqa,hellaswag,winogrande"++auto-round --model <model> --scheme <scheme> --format fake \+ --enable_alg_ext --algorithm awq,auto_round \+ --tasks "mmlu,gsm8k,piqa,hellaswag,winogrande"+```++表中 `AR2` 表示启用 `--enable_alg_ext` 的 AutoRound,`AWQ_AR2` 表示 AWQ 后接启用 `--enable_alg_ext` 的 AutoRound。准确率列以百分制展示,例如原始值 `0.7058` 写作 `70.58`。BF16 作为参考基线放在每个模型分组的第一行。每个模型在每个 scheme 下平均分最高的量化行使用粗体标出。原始表格中有一行 Llama MXFP4 标为 `WQ_AR2`,本文将其视为 `AWQ_AR2`。++观察表中,`AVG Win Rate` 表示在当前 scheme 下所有可比较模型中,AWQ 组合方法 AVG 更高的比例;`Max AVG Delta Gain` 表示最大的 AVG 绝对提升(百分点);`Max AVG Rel. Gain` 表示最大的 AVG 相对提升。对于 `AWQ_RTN`,当 `RTN` 和 `opt_rtn` 都存在时,会同时纳入这两个基线进行比较。++## MXFP4++**注意:对于 Llama-3.1-Instruct,我们建议移除 [modeling_llama.py](https://github.com/huggingface/transformers/blob/main/src/transformers/models/llama/modeling_llama.py#L52C1-L52C40) 中的 `@use_kernel_forward_from_hub("RMSNorm")`;下方的测试并未移除该装饰器,会导致精度测试结果不准确。**++<table border="1">+ <tr>+ <td>Model</td>+ <td>Config</td>+ <td>GSM8K (%)</td>+ <td>HellaSwag (%)</td>+ <td>MMLU (%)</td>+ <td>PIQA (%)</td>+ <td>WinoGrande (%)</td>+ <td>AVG (%)</td>+ <td>Timecost</td>+ <td>RAM</td>+ <td>VRAM</td>+ </tr>+ <tr>+ <td rowspan="8">Llama-3.1-8B-I</td>+ <td>BF16</td>+ <td>70.51</td>+ <td>59.71</td>+ <td>68.37</td>+ <td>80.09</td>+ <td>73.40</td>+ <td>70.42</td>+ <td>-</td>+ <td>-</td>+ <td>-</td>+ </tr>+ <tr><td>RTN</td><td>59.06</td><td>58.88</td><td>64.63</td><td>78.94</td><td>72.77</td><td>66.86</td><td>72.30</td><td>25.52GB</td><td>0.83GB</td></tr>+ <tr><td>opt_rtn</td><td>65.20</td><td>58.91</td><td>65.04</td><td>79.05</td><td>73.48</td><td>68.34</td><td>62.00</td><td>25.65GB</td><td>1.65GB</td></tr>+ <!-- TODO: MXFP4 Llama-3.1 的 AR 数据异常(GSM8K=0.00,AVG=43.13),暂时视为初步结果,后续复核。 -->+ <tr><td>AR</td><td>0.00</td><td>31.20</td><td>48.50</td><td>75.24</td><td>60.69</td><td>43.13</td><td>959.21</td><td>25.39GB</td><td>16.30GB</td></tr>+ <tr><td>AR2</td><td>67.32</td><td>57.94</td><td>64.11</td><td>80.25</td><td>73.80</td><td>68.68</td><td>1104.91</td><td>24.38GB</td><td>17.78GB</td></tr>+ <tr><td>AWQ_RTN</td><td>66.26</td><td>58.36</td><td>66.12</td><td>79.00</td><td>73.95</td><td>68.74</td><td>1132.04</td><td>24.36GB</td><td>7.60GB</td></tr>+ <tr><td>AWQ_AR</td><td>69.75</td><td>57.74</td><td>65.71</td><td>79.27</td><td>72.69</td><td>69.03</td><td>2136.06</td><td>24.47GB</td><td>19.24GB</td></tr>+ <tr><td><b>AWQ_AR2</b></td><td><b>71.27</b></td><td><b>58.29</b></td><td><b>66.07</b></td><td><b>80.25</b></td><td><b>73.88</b></td><td><b>69.95</b></td><td><b>2274.64</b></td><td><b>24.40GB</b></td><td><b>18.12GB</b></td></tr>+ <tr>+ <td rowspan="8">Qwen3-8B</td>+ <td>BF16</td>+ <td>87.41</td>+ <td>57.16</td>+ <td>72.92</td>+ <td>76.71</td>+ <td>67.72</td>+ <td>72.38</td>+ <td>-</td>+ <td>-</td>+ <td>-</td>+ </tr>+ <tr><td>RTN</td><td>86.05</td><td>55.07</td><td>70.30</td><td>75.41</td><td>66.93</td><td>70.75</td><td>61.00</td><td>23.23GB</td><td>0.74GB</td></tr>+ <tr><td>opt_rtn</td><td>86.50</td><td>55.53</td><td>70.64</td><td>75.79</td><td>66.77</td><td>71.05</td><td>66.00</td><td>23.55GB</td><td>1.40GB</td></tr>+ <tr><td>AR</td><td>86.73</td><td>54.90</td><td>71.56</td><td>76.44</td><td>70.09</td><td>71.94</td><td>968.45</td><td>22.32GB</td><td>15.68GB</td></tr>+ <tr><td>AR2</td><td>86.58</td><td>55.07</td><td>71.86</td><td>76.61</td><td>69.77</td><td>71.98</td><td>1195.57</td><td>22.35GB</td><td>16.00GB</td></tr>+ <tr><td>AWQ_RTN</td><td>85.90</td><td>55.79</td><td>71.54</td><td>76.93</td><td>67.80</td><td>71.59</td><td>1088.34</td><td>22.34GB</td><td>6.93GB</td></tr>+ <tr><td>AWQ_AR</td><td>85.37</td><td>54.41</td><td>71.47</td><td>76.55</td><td>70.32</td><td>71.62</td><td>2346.84</td><td>22.45GB</td><td>16.75GB</td></tr>+ <tr><td><b>AWQ_AR2</b></td><td><b>86.66</b></td><td><b>55.19</b></td><td><b>71.99</b></td><td><b>77.37</b></td><td><b>70.80</b></td><td><b>72.40</b></td><td><b>2266.50</b></td><td><b>22.37GB</b></td><td><b>16.16GB</b></td></tr>+</table>++### MXFP4 观察++| Comparison | AVG Win Rate | Max AVG Delta Gain | Max AVG Rel. Gain |+| --- | ---: | ---: | ---: |+| `AWQ_RTN` vs `RTN` / `opt_rtn` | 4/4 (100%) | +1.88 pts | +2.81% |+| `AWQ_AR` vs `AR` | 1/2 (50%) | +25.90 pts | +60.05%* |+| `AWQ_AR2` vs `AR2` | 2/2 (100%) | +1.27 pts | +1.85% |++*Llama 的 `AWQ_AR` vs `AR` 结果受到原生 `AR` 基线异常影响(`GSM8K=0.00`,`AVG=43.13`),因此相对提升偏高。++- MXFP4 是 AWQ 组合收益最清晰的场景。`AWQ_RTN` 在两个模型上都高于 `RTN` 和 `opt_rtn`,`AWQ_AR2` 在两个模型上都高于 `AR2`。+- `AWQ_AR2` 是 MXFP4 中更稳定的组合:两个模型 AVG 均提升,最高带来 +1.27 分、+1.85% 的 AVG 相对提升。+- `AWQ_AR` 并不稳定。Llama 的大幅收益主要来自原生 `AR` 基线异常,而 Qwen 上 `AWQ_AR` 的 AVG 低于原生 `AR`。+- 代价仍然是耗时和显存。`AWQ_RTN` 约为 `RTN` 耗时的 18 倍;在 MXFP4 上,`AWQ_AR` / `AWQ_AR2` 约为原生 `AR` / `AR2` 的 2 倍。++## W4A16++<table border="1">+ <tr>+ <td>Model</td>+ <td>Config</td>+ <td>GSM8K (%)</td>+ <td>HellaSwag (%)</td>+ <td>MMLU (%)</td>+ <td>PIQA (%)</td>+ <td>WinoGrande (%)</td>+ <td>AVG (%)</td>+ <td>Timecost</td>+ <td>RAM</td>+ <td>VRAM</td>+ </tr>+ <tr>+ <td rowspan="8">Llama-3.1-8B-I</td>+ <td>BF16</td>+ <td>70.51</td>+ <td>59.71</td>+ <td>68.37</td>+ <td>80.09</td>+ <td>73.40</td>+ <td>70.42</td>+ <td>-</td>+ <td>-</td>+ <td>-</td>+ </tr>+ <tr><td>RTN</td><td>71.80</td><td>59.14</td><td>65.46</td><td>79.43</td><td>72.77</td><td>69.72</td><td>60.00</td><td>25.08GB</td><td>0.56GB</td></tr>+ <tr><td>opt_rtn</td><td>67.63</td><td>58.99</td><td>65.67</td><td>78.94</td><td>73.95</td><td>69.04</td><td>162.30</td><td>28.31GB</td><td>7.90GB</td></tr>+ <tr><td>AR</td><td>67.40</td><td>58.93</td><td>66.81</td><td>79.87</td><td>73.72</td><td>69.35</td><td>769.27</td><td>24.29GB</td><td>12.32GB</td></tr>+ <tr><td>AR2</td><td>69.60</td><td>59.13</td><td>66.81</td><td>79.87</td><td>73.09</td><td>69.70</td><td>918.59</td><td>24.04GB</td><td>13.26GB</td></tr>+ <tr><td>AWQ_RTN</td><td>70.58</td><td>59.09</td><td>65.89</td><td>79.87</td><td>72.85</td><td>69.66</td><td>1075.44</td><td>24.07GB</td><td>7.68GB</td></tr>+ <tr><td><b>AWQ_AR</b></td><td><b>73.24</b></td><td><b>59.11</b></td><td><b>66.97</b></td><td><b>80.14</b></td><td><b>72.93</b></td><td><b>70.48</b></td><td><b>1813.51</b></td><td><b>24.07GB</b></td><td><b>13.32GB</b></td></tr>+ <tr><td>AWQ_AR2</td><td>70.13</td><td>59.09</td><td>67.11</td><td>79.87</td><td>73.56</td><td>69.95</td><td>3533.26</td><td>24.07GB</td><td>13.17GB</td></tr>+ <tr>+ <td rowspan="8">Qwen3-8B</td>+ <td>BF16</td>+ <td>87.41</td>+ <td>57.16</td>+ <td>72.92</td>+ <td>76.71</td>+ <td>67.72</td>+ <td>72.38</td>+ <td>-</td>+ <td>-</td>+ <td>-</td>+ </tr>+ <tr><td>RTN</td><td>86.43</td><td>56.18</td><td>70.84</td><td>75.52</td><td>67.17</td><td>71.23</td><td>97.00</td><td>23.10GB</td><td>0.50GB</td></tr>+ <tr><td>opt_rtn</td><td>87.26</td><td>55.96</td><td>71.58</td><td>76.33</td><td>68.43</td><td>71.91</td><td>180.17</td><td>27.17GB</td><td>7.38GB</td></tr>+ <tr><td>AR</td><td>88.02</td><td>56.03</td><td>72.13</td><td>76.22</td><td>67.72</td><td>72.02</td><td>779.03</td><td>21.73GB</td><td>11.41GB</td></tr>+ <tr><td>AR2</td><td>86.96</td><td>55.95</td><td>72.38</td><td>76.71</td><td>68.27</td><td>72.05</td><td>1028.79</td><td>22.00GB</td><td>12.48GB</td></tr>+ <tr><td>AWQ_RTN</td><td>86.13</td><td>56.04</td><td>71.91</td><td>75.63</td><td>67.56</td><td>71.45</td><td>1108.32</td><td>22.02GB</td><td>6.93GB</td></tr>+ <tr><td>AWQ_AR</td><td>86.73</td><td>56.13</td><td>71.51</td><td>76.22</td><td>69.06</td><td>71.93</td><td>1957.19</td><td>21.94GB</td><td>12.07GB</td></tr>+ <tr><td><b>AWQ_AR2</b></td><td><b>86.50</b></td><td><b>56.07</b></td><td><b>72.23</b></td><td><b>76.55</b></td><td><b>69.14</b></td><td><b>72.10</b></td><td><b>3673.00</b></td><td><b>22.03GB</b></td><td><b>12.79GB</b></td></tr>+</table>++### W4A16 观察++| Comparison | AVG Win Rate | Max AVG Delta Gain | Max AVG Rel. Gain |+| --- | ---: | ---: | ---: |+| `AWQ_RTN` vs `RTN` / `opt_rtn` | 2/4 (50%) | +0.62 pts | +0.90% |+| `AWQ_AR` vs `AR` | 1/2 (50%) | +1.13 pts | +1.63% |+| `AWQ_AR2` vs `AR2` | 2/2 (100%) | +0.25 pts | +0.36% |++- W4A16 的 AWQ 收益依赖模型和后续量化方法。最明确的收益是 Llama 上 `AWQ_AR` 相比 `AR` 提升 +1.13 平均分,AVG 相对提升 +1.63%。+- `AWQ_RTN` 不适合作为 W4A16 的强默认项。它相对 `RTN` 和 `opt_rtn` 的 AVG 胜率为 2/4,但收益较小且不稳定。+- `AWQ_AR2` 在两个模型上都提升 AVG,但增益较小(+0.25 分和 +0.05 分),需要结合额外耗时判断是否值得启用。++## INT8 / W8A8++<table border="1">+ <tr>+ <td>Model</td>+ <td>Config</td>+ <td>GSM8K (%)</td>+ <td>HellaSwag (%)</td>+ <td>MMLU (%)</td>+ <td>PIQA (%)</td>+ <td>WinoGrande (%)</td>+ <td>AVG (%)</td>+ <td>Timecost</td>+ <td>RAM</td>+ <td>VRAM</td>+ </tr>+ <tr>+ <td rowspan="6">Llama-3.1-8B-I</td>+ <td>BF16</td>+ <td>70.51</td>+ <td>59.71</td>+ <td>68.37</td>+ <td>80.09</td>+ <td>73.40</td>+ <td>70.42</td>+ <td>-</td>+ <td>-</td>+ <td>-</td>+ </tr>+ <tr><td>RTN</td><td>71.49</td><td>59.64</td><td>68.37</td><td>80.30</td><td>74.27</td><td>70.81</td><td>58.00</td><td>25.00GB</td><td>0.56GB</td></tr>+ <tr><td>AR</td><td>69.90</td><td>59.62</td><td>68.36</td><td>80.36</td><td>73.64</td><td>70.38</td><td>836.48</td><td>24.90GB</td><td>13.63GB</td></tr>+ <tr><td>AWQ_RTN</td><td>73.24</td><td>59.66</td><td>68.30</td><td>80.09</td><td>73.32</td><td>70.92</td><td>1052.19</td><td>23.98GB</td><td>7.67GB</td></tr>+ <tr><td>AWQ_AR</td><td>68.99</td><td>59.77</td><td>68.12</td><td>80.30</td><td>73.09</td><td>70.05</td><td>1228.53</td><td>24.10GB</td><td>14.29GB</td></tr>+ <tr><td><b>RTN_smooth2048_clip</b></td><td><b>72.93</b></td><td><b>59.89</b></td><td><b>68.27</b></td><td><b>80.14</b></td><td><b>73.95</b></td><td><b>71.04</b></td><td><b>1668.43</b></td><td><b>24.50GB</b></td><td><b>18.46GB</b></td></tr>+ <tr>+ <td rowspan="6">Qwen3-8B</td>+ <td>BF16</td>+ <td>87.41</td>+ <td>57.16</td>+ <td>72.92</td>+ <td>76.71</td>+ <td>67.72</td>+ <td>72.38</td>+ <td>-</td>+ <td>-</td>+ <td>-</td>+ </tr>+ <tr><td>RTN</td><td>87.79</td><td>57.09</td><td>72.90</td><td>76.77</td><td>67.80</td><td>72.47</td><td>84.00</td><td>23.09GB</td><td>0.50GB</td></tr>+ <tr><td>AR</td><td>86.96</td><td>56.57</td><td>72.58</td><td>77.20</td><td>68.11</td><td>72.28</td><td>881.10</td><td>23.66GB</td><td>12.58GB</td></tr>+ <tr><td>AWQ_RTN</td><td>86.96</td><td>57.22</td><td>72.85</td><td>76.39</td><td>68.27</td><td>72.34</td><td>1143.95</td><td>21.93GB</td><td>6.93GB</td></tr>+ <tr><td>AWQ_AR</td><td>87.41</td><td>56.80</td><td>72.65</td><td>76.71</td><td>67.64</td><td>72.24</td><td>1324.51</td><td>22.85GB</td><td>13.40GB</td></tr>+ <tr><td><b>RTN_smooth2048_clip</b></td><td><b>87.87</b></td><td><b>57.14</b></td><td><b>72.90</b></td><td><b>76.66</b></td><td><b>67.96</b></td><td><b>72.51</b></td><td><b>1796.55</b></td><td><b>22.47GB</b></td><td><b>15.77GB</b></td></tr>+</table>++### INT8 观察++| Comparison | AVG Win Rate | Max AVG Delta Gain | Max AVG Rel. Gain |+| --- | ---: | ---: | ---: |+| `AWQ_RTN` vs `RTN` | 1/2 (50%) | +0.11 pts | +0.16% |+| `AWQ_AR` vs `AR` | 0/2 (0%) | -0.04 pts | -0.06% |++- INT8/W8A8 在这些实验中本身已经是高精度设置。大多数 INT8 recipe 的结果接近 BF16 参考水平,部分 recipe 的 AVG 还略高于 BF16。+- 实验性的 `RTN_smooth2048_clip` 行在两个模型的 INT8 表中都取得最高 AVG:Llama 为 71.04,Qwen 为 72.51。+- 在 `RTN_smooth2048_clip` 中,`smooth2048` 表示 AWQ 校准使用序列长度 2048(`awq_seqlen=2048`),`clip` 表示在 AWQ 搜索中启用权重裁剪(`apply_clip=True`)。+- 对 AWQ 组合的 INT8 路径而言,AVG 变化幅度较小。Llama `AWQ_RTN` 相比 `RTN` 提升 +0.11 分(AVG 相对提升 +0.16%),其他 AWQ 组合结果则略低于对应的原生量化路径。+- 考虑到 INT8 的原生基线已经较强,AWQ 更适合作为 INT8/W8A8 的可选探索路径,而不是首选默认路径。++## 总结++### 优势++- AWQ 可以提升 MXFP4 准确率,尤其是与启用 `--enable_alg_ext` 的 AutoRound 组合时。+- 在本次 Llama W4A16 实验中,AWQ 有明显收益:`AWQ_AR` 平均分达到 70.48,略高于 BF16 参考结果。+- AWQ 不会给最终量化模型增加持续性内存开销。在校准阶段,`AWQ_RTN` 的 RAM 与其他流程接近,VRAM 明显低于迭代式 AutoRound 流程。+- AWQ 与终端量化算法正交,可以与 RTN、AutoRound 或 AutoRound2 组合,而不改变这些算法本身的核心量化逻辑。+- AWQ 更适合量化误差对 activation-aware weight smoothing 敏感的 scheme,例如 MXFP4。++### 劣势++- AWQ 会增加一次性的校准时间。即使是 `AWQ_RTN`,这些 8B 模型也需要约 18 分钟,而原始 `RTN` 约 1 分钟;当准确率收益明确时,这个离线时间成本是可以接受的。+- AWQ 对 W4A16 的提升不稳定;Qwen W4A16 的收益很小或接近中性。+- 对 INT8/W8A8,AWQ 带来的额外 AVG 收益有限,因为原生 INT8 基线已经接近 BF16。+- `AWQ_AR` 与 `AWQ_AR2` 会继承迭代式 AutoRound 优化的 GPU 内存特征。这些行里的较高 VRAM 应理解为后续优化器的成本,而不是 AWQ 给最终模型增加的持续性内存开销。+- AWQ 的收益依赖模型和 scheme,因此更适合作为可选组合,而不是通用默认配置。++## 使用建议++- 当目标是 MXFP4,或某个 W4A16 模型已验证存在收益时,可以将 AWQ 作为可选预处理算法使用。+- 当目标 scheme 显示出明确准确率收益时,可以把 AWQ 的额外校准时间视为可接受的离线成本。+- AWQ 内部 QDQ 默认使用原始 RTN 是合理的。这些结果没有显示出在 AWQ 校准期间使用优化版 RTN 有明确的准确率/成本收益。+- 对不含 AWQ 的终端 RTN,仍应保留优化版 RTN,尤其是 MXFP4,因为它能以较低成本提升准确率。+- 对 INT8/W8A8,除非具体模型显示出明确收益,否则优先使用原生 RTN。diff --git a/docs/rotation_details.md b/docs/rotation_details.mdindex 5a9aa8ffc..da0311f1a 100644--- a/docs/rotation_details.md+++ b/docs/rotation_details.md@@ -1,6 +1,6 @@-# Rotation Transform — Details (Experimental)+# Rotation Transform — Details (Research)-> ⚠️ **Experimental feature.** Rotation transform is still in an experimental stage. Inference relies on forward hooks, which are currently only supported by the Hugging Face Transformers backend. As a result, inference may be slower compared to native (non-rotated) models.+> ⚠️ **Research feature.** Rotation transform is still in a research stage. Inference relies on forward hooks, which are currently only supported by the Hugging Face Transformers backend. As a result, inference may be slower compared to native (non-rotated) models.This document is the in-depth reference for AutoRound's rotation transforms. For aconcise getting-started guide, see the *Rotation* section in@@ -77,8 +77,8 @@ Defined in `auto_round/algorithms/transforms/spinquant/preprocessor.py`.| `rotation_size` | `None` (auto) | Overrides the R1/R4 block size (R1 uses it instead of `hidden_size`, R4 instead of `intermediate_size`). R2 always uses `head_dim`; R3 has no custom size. Must be a positive power of 2. || `random_r1` / `random_r2` / `random_r3` / `random_r4` | `False` | Use random Hadamard (`H × diag(±1)`) instead of the deterministic matrix at that position. Only relevant in QuaRot mode. || `online_r1_rotation` | `True` | Apply R1 online via hook (`True`) or fuse it fully into weights (`False`). |-| `trainable_rotation` | `False` | Learn the rotation matrices via Cayley SGD (SpinQuant mode). **Experimental**, requires a dataloader. |-| `trainable_smooth` | `False` | Learn SmoothQuant-style `smooth_values` jointly via Adam. **Experimental**, requires a dataloader. |+| `trainable_rotation` | `False` | Learn the rotation matrices via Cayley SGD (SpinQuant mode). **Research**, requires a dataloader. |+| `trainable_smooth` | `False` | Learn SmoothQuant-style `smooth_values` jointly via Adam. **Research**, requires a dataloader. || `iters` | `200` | Training iterations (trainable modes only). || `lr` | `1e-4` | SGDG (Cayley) learning rate for rotation matrices. || `smooth_lr` | `1e-3` | Adam learning rate for smooth values. |@@ -95,13 +95,13 @@ Defined in `auto_round/algorithms/transforms/spinquant/preprocessor.py`.| Value | Equivalent ||-------|-----------|| `"quarot"` | `SpinQuantConfig(trainable_rotation=False, trainable_smooth=False)` — deterministic Hadamard, no training, no calibration data. |-| `"spinquant"` | `SpinQuantConfig(trainable_rotation=True, trainable_smooth=True)` — **experimental**, requires a dataloader. |+| `"spinquant"` | `SpinQuantConfig(trainable_rotation=True, trainable_smooth=True)` — **research**, requires a dataloader. |Both presets keep the default `r1=True, r2=True, r3=False, r4=False`. A dict with`algorithm="spinquant"` is also parsed into a `SpinQuantConfig`.> ⚠️ **SpinQuant trainable rotation** (`trainable_rotation=True`) enables learnable-> rotation matrices optimized via Cayley SGD. This feature is experimental and not+> rotation matrices optimized via Cayley SGD. This feature is a research feature and not> fully validated on real models. Use `"quarot"` (fixed Hadamard) for production> workloads.@@ -205,7 +205,7 @@ with a `*_type` code: `0` = deterministic, `1` = random, `2` = trained):## 2. Per-Linear Block Rotation-> ⚠️ This is an earlier experimental implementation that applies block-diagonal+> ⚠️ This is an earlier research implementation that applies block-diagonal> Hadamard rotation **per linear layer** by patching every `nn.Linear` module in the> model. For most use cases the QuaRot / SpinQuant approach above is preferred — it> provides architecture-aware rotation at specific positions (R1–R4) with betterdiff --git a/docs/step_by_step.md b/docs/step_by_step.mdindex be535ef99..c8868dc34 100755--- a/docs/step_by_step.md+++ b/docs/step_by_step.md@@ -35,7 +35,7 @@ This document presents step-by-step instructions for auto-round llm quantization+ [Device/Multi-GPU setting in Quantization](#devicemulti-gpu-setting-in-quantization)- [Enable multiple gpus calibration in lm_head quantization](#enable-multiple-gpus-calibration-in-lm_head-quantization)+ [Adjust Hyperparameters](#adjust-hyperparameters)- + [Rotation (Experimental)](#rotation-experimental)+ + [Rotation (Research)](#rotation-research)* [4 Inference](#4-inference)+ [CPU](#cpu)+ [Intel GPU](#intel-gpu)@@ -350,6 +350,8 @@ AWQ (Activation-Aware Weight Quantization) is available as an alternative quantiThe canonical AWQ deployment path is **W4A16** served by vLLM's AWQ/Marlin CUDA kernels. **INT8** is AutoRound's W8A8 scheme and can use AWQ smoothing before RTN quantization for vLLM's compressed_tensors backend (cutlass INT8 GEMM).+AWQ can also be composed with AutoRound optimization (`--algorithm awq,auto_round`). See [AWQ algorithm results](./awq_details.md) for accuracy and cost comparisons across W4A16, MXFP4, and INT8.+#### CLI Usage```bash@@ -950,9 +952,9 @@ autoround.save_quantized(format="auto_awq", output_dir="tmp_autoround")Include the flag `--adam`. Note that AdamW is less effective than sign gradient descent in many scenarios we tested.-### Rotation (Experimental)+### Rotation (Research)-> ⚠️ **Experimental feature**: Rotation transform is still experimental. Inference relies on forward hooks, which are currently only supported by the Hugging Face Transformers backend, so rotated models may run slower than native (non-rotated) models.+> ⚠️ **Research feature**: Rotation transform is still a research feature. Inference relies on forward hooks, which are currently only supported by the Hugging Face Transformers backend, so rotated models may run slower than native (non-rotated) models.Rotation redistributes outliers in weights and activations before quantization, making the distribution more uniform and quantization-friendly. It is most useful for aggressive low-bit schemes such as MXFP4, NVFP4 and W4A4.diff --git a/docs/step_by_step_CN.md b/docs/step_by_step_CN.mdindex d099d66b5..89996b4bc 100755--- a/docs/step_by_step_CN.md+++ b/docs/step_by_step_CN.md@@ -36,7 +36,7 @@- [lm_head 量化中开启多 GPU 标定](#lm_head-量化中开启多-gpu-标定)- [手动配置设备映射](#手动配置设备映射)+ [超参数调整](#超参数调整)- + [旋转(Rotation)(实验性)](#旋转rotation实验性)+ + [旋转(Rotation)(研究性)](#旋转rotation研究性)* [4 推理部署](#4-推理部署)+ [CPU](#cpu)+ [英特尔 GPU](#英特尔-gpu)@@ -346,6 +346,8 @@ AWQ(Activation-Aware Weight Quantization,激活感知权重量化)是一AWQ 的标准部署路径是 **W4A16**,通过 vLLM 的 AWQ/Marlin CUDA 内核提供服务。**INT8** 是 AutoRound 的 W8A8 scheme,可在 RTN 量化前使用 AWQ 平滑化,并通过 vLLM 的 compressed_tensors 后端(cutlass INT8 GEMM)提供服务。+AWQ 也可以与 AutoRound 优化组合使用(`--algorithm awq,auto_round`)。W4A16、MXFP4 和 INT8 的准确率与成本对比请参考 [AWQ 算法结果](./awq_details_CN.md)。+#### 命令行用法```bash@@ -913,9 +915,9 @@ auto-round --model_name Qwen/Qwen3-0.6B --scheme "W4A16" --quant_lm_head --form#### 使用 AdamW 优化器添加 `--adam` 参数即可启用;**注意**:在我们的多项测试场景中,AdamW 优化器的效果均不如符号梯度下降(sign gradient descent)。-### 旋转(Rotation)(实验性)+### 旋转(Rotation)(研究性)-> ⚠️ **实验性功能**:旋转变换仍处于实验阶段。推理依赖 forward hook 机制,目前仅支持 Hugging Face Transformers 后端,因此相比非旋转模型,旋转后的模型推理速度可能较慢。+> ⚠️ **研究性功能**:旋转变换仍处于研究阶段。推理依赖 forward hook 机制,目前仅支持 Hugging Face Transformers 后端,因此相比非旋转模型,旋转后的模型推理速度可能较慢。旋转在量化前对权重和激活中的离群点进行重分布,使分布更加均匀、对量化更友好。它对 MXFP4、NVFP4、W4A4 等激进的低比特方案最为有效。diff --git a/test/unit/test_cpu/algorithms/test_awq.py b/test/unit/test_cpu/algorithms/test_awq.pyindex a9f933c07..31fadb61e 100644--- a/test/unit/test_cpu/algorithms/test_awq.py+++ b/test/unit/test_cpu/algorithms/test_awq.py@@ -940,6 +940,34 @@ class TestAWQUseV2ScaleSearch:compressor = self._make_compressor(block)assert q._qdq_tool._block_quantizer_is_signroundv2(compressor) is False+ def test_qdq_configure_resolves_opt_rtn_policy_and_legacy_shapes(self):+ """QDQ wiring covers AWQ-owned policy plus legacy compressor-shaped callers."""+ from auto_round.algorithms.composer import AlgorithmComposer+ from auto_round.algorithms.quantization.rtn.config import RTNConfig+ from auto_round.algorithms.transforms.awq.config import AWQConfig++ composer = AlgorithmComposer([AWQConfig(n_grid=1), RTNConfig(disable_opt_rtn=True)])+ awq = composer.preprocessors[0]+ awq._qdq_tool.configure(composer)++ assert awq._qdq_tool.disable_opt_rtn is True++ composer = AlgorithmComposer([AWQConfig(n_grid=1, enable_opt_rtn=True), RTNConfig(disable_opt_rtn=True)])+ awq = composer.preprocessors[0]+ awq._qdq_tool.configure(composer, awq_config=awq.config)++ assert awq._qdq_tool.disable_opt_rtn is False++ q = self._awq_transform()+ compressor = self._make_compressor(RTNConfig(disable_opt_rtn=True))+ q._qdq_tool.configure(compressor)++ assert q._qdq_tool.disable_opt_rtn is True++ compressor = self._make_compressor(self._signroundv2_config(data_type="mx_fp"))++ assert q._qdq_tool._block_quantizer_is_signroundv2(compressor) is True+def test_init_scale_dispatch_by_data_type(self):"""``search_optimized_init_scale`` injects only for sym int/mx/nv."""import torchdiff --git a/test/unit/test_cpu/core/test_autoround_entry.py b/test/unit/test_cpu/core/test_autoround_entry.pyindex 0b4d8c0ea..990872266 100644--- a/test/unit/test_cpu/core/test_autoround_entry.py+++ b/test/unit/test_cpu/core/test_autoround_entry.py@@ -54,6 +54,41 @@ def test_awq_and_signround_does_not_append_rtn():assert _types(configs) == ["AWQConfig", "SignRoundConfig"]+def test_awq_rtn_uses_regular_model_loaded_route(monkeypatch):+ from auto_round import AutoRound++ created = {}++ class FakeCompressor:+ def __init__(self, config, **kwargs):+ created["config"] = config+ created["kwargs"] = kwargs++ def fail_model_free(*args, **kwargs):+ raise AssertionError("AWQ pipelines must not auto-route to model-free quantization.")++ monkeypatch.setattr("auto_round.autoround._build_model_free_compressor", fail_model_free)+ monkeypatch.setattr("auto_round.autoround._build_model_type_ctor_kwargs", lambda *args, **kwargs: ("llm", {}))+ monkeypatch.setattr("auto_round.autoround._get_compressor_class", lambda model_type, base_cls: FakeCompressor)++ ar = AutoRound(+ "dummy-model",+ scheme="W4A16",+ alg_configs=[AWQConfig(n_grid=1), RTNConfig(disable_opt_rtn=True)],+ )++ assert isinstance(ar, FakeCompressor)+ assert _types(created["config"]) == ["AWQConfig", "RTNConfig"]++ with pytest.raises(ValueError, match="model_free=True.*AWQConfig"):+ AutoRound(+ "dummy-model",+ scheme="W4A16",+ alg_configs=[AWQConfig(n_grid=1), RTNConfig(disable_opt_rtn=True)],+ model_free=True,+ )++def test_direct_signround_kwargs_warn_and_apply(monkeypatch):warnings = []monkeypatch.setattr("auto_round.autoround.logger.warning", lambda message, *args: warnings.append(message % args))@@ -74,6 +109,31 @@ def test_zero_iters_selects_rtn_and_forwards_disable_opt_rtn():assert configs[0].disable_opt_rtn is True+def test_awq_rtn_opt_policy_defaults_and_explicit_overrides():+ cases = [+ (_normalize_alg_configs("awq"), ["AWQConfig", "RTNConfig"], [True, True]),+ (+ _normalize_alg_configs(None, direct_kwargs={"algorithm": "awq,rtn", "disable_opt_rtn": True}),+ ["AWQConfig", "RTNConfig"],+ [True, True],+ ),+ (+ _normalize_alg_configs([AWQConfig(enable_opt_rtn=True), RTNConfig()]),+ ["AWQConfig", "OptimizedRTNConfig"],+ [False, False],+ ),+ (+ _normalize_alg_configs([AWQConfig(), RTNConfig(enable_opt_rtn=True)]),+ ["AWQConfig", "OptimizedRTNConfig"],+ [True, False],+ ),+ ]++ for configs, expected_types, expected_disable_opt_rtn in cases:+ assert _types(configs) == expected_types+ assert [config.disable_opt_rtn for config in configs] == expected_disable_opt_rtn++@pytest.mark.parametrize("algorithm", ["signround", "auto_round", "autoround"])def test_legacy_signround_alias_with_zero_iters_selects_rtn(algorithm):legacy_configs = _normalize_alg_configs(None, direct_kwargs={"algorithm": algorithm, "iters": 0})@@ -94,14 +154,14 @@ def test_explicit_zero_iter_signround_config_selects_rtn():def test_combined_awq_zero_iters_keeps_awq_and_selects_rtn():configs = _normalize_alg_configs(None, direct_kwargs={"algorithm": "awq,signround", "iters": 0})- assert _types(configs) == ["AWQConfig", "OptimizedRTNConfig"]+ assert _types(configs) == ["AWQConfig", "RTNConfig"]@pytest.mark.parametrize(("algorithm", "expected_types"),[("rtn", ["OptimizedRTNConfig"]),- ("awq", ["AWQConfig", "OptimizedRTNConfig"]),+ ("awq", ["AWQConfig", "RTNConfig"]),("signround", ["SignRoundConfig"]),("awq,signround", ["AWQConfig", "SignRoundConfig"]),],diff --git a/test/unit/test_cpu/core/test_entry_contract.py b/test/unit/test_cpu/core/test_entry_contract.pyindex 0ebda2063..e63d12349 100644--- a/test/unit/test_cpu/core/test_entry_contract.py+++ b/test/unit/test_cpu/core/test_entry_contract.py@@ -48,3 +48,41 @@ def test_cli_explicit_auto_round_with_zero_iters_selects_rtn():configs = AlgorithmHandler.build_configs(args, {})assert type(configs[0]).__name__ == "RTNConfig"+++def test_cli_awq_rtn_opt_policy():+ from argparse import Namespace++ from auto_round.cli.algorithms import AlgorithmHandler++ cases = [+ (Namespace(algorithm="awq", iters=200, disable_opt_rtn=True), ["AWQConfig", "RTNConfig"], [True, True]),+ (Namespace(algorithm="awq", iters=200, disable_opt_rtn=None), ["AWQConfig", "RTNConfig"], [True, True]),+ (Namespace(algorithm="awq,rtn", iters=200, disable_opt_rtn=False), ["AWQConfig", "RTNConfig"], [False, False]),+ ]++ for args, expected_types, expected_disable_opt_rtn in cases:+ configs = AlgorithmHandler.build_configs(args, {})++ assert [type(config).__name__ for config in configs] == expected_types+ assert [config.disable_opt_rtn for config in configs] == expected_disable_opt_rtn+++def test_cli_rtn_inherits_built_awq_config_without_mutating_args(monkeypatch):+ from argparse import Namespace++ from auto_round.algorithms.transforms.awq.config import AWQConfig+ from auto_round.cli.algorithms import AWQ, AlgorithmHandler++ def build_awq_with_opt_rtn(self, args, common_kwargs):+ return AWQConfig(disable_opt_rtn=False)++ monkeypatch.setattr(AWQ, "build", build_awq_with_opt_rtn)++ args = Namespace(algorithm="rtn,awq", iters=200, disable_opt_rtn=None)+ configs = AlgorithmHandler.build_configs(args, {})++ assert [type(config).__name__ for config in configs] == ["RTNConfig", "AWQConfig"]+ assert configs[0].disable_opt_rtn is False+ assert configs[1].disable_opt_rtn is False+ assert args.disable_opt_rtn is Nonediff --git a/test/unit/test_cpu/core/test_pipeline_fail_fast.py b/test/unit/test_cpu/core/test_pipeline_fail_fast.pyindex f49fef09a..2fce2bf60 100644--- a/test/unit/test_cpu/core/test_pipeline_fail_fast.py+++ b/test/unit/test_cpu/core/test_pipeline_fail_fast.py@@ -6,7 +6,7 @@ import pytestfrom auto_round import AutoRound as NewAutoRoundfrom auto_round import AWQConfig, OptimizedRTNConfig, RotationConfig, RTNConfig, SignRoundConfig, SpinQuantConfig-from auto_round.algorithms.composer import AlgorithmComposer, _can_compile_block_forward, _has_nvfp4_layer+from auto_round.algorithms.composer import AlgorithmComposer, _has_nvfp4_layerfrom auto_round.algorithms.config_resolver import (get_algorithm_class,resolve_shared_config_values,@@ -36,9 +36,14 @@ class CompileCompatibleRotation:return True-class CompileCompatibleQuantizer:- def can_compile_block_forward(self):- return True+def _compile_orchestrator(enable_torch_compile=True, rotation_configs=()):+ return SimpleNamespace(+ model_context=None,+ compress_context=SimpleNamespace(enable_torch_compile=enable_torch_compile),+ rotation_configs=rotation_configs,+ data_type="int",+ layer_config={},+ )def test_split_awq_plus_rtn():@@ -64,12 +69,22 @@ def test_pipeline_multiple_block_quantizers_rejected():def test_hadamard_disables_only_block_forward_compile():- quantizer = CompileCompatibleQuantizer()- hadamard = RotationConfig()+ hadamard = AlgorithmComposer([SignRoundConfig()], _compile_orchestrator(rotation_configs=(RotationConfig(),)))+ assert not hadamard.block_forward.enable_torch_compile++ compatible = AlgorithmComposer(+ [SignRoundConfig()], _compile_orchestrator(rotation_configs=(CompileCompatibleRotation(),))+ )+ assert compatible.block_forward.enable_torch_compile++ disabled = AlgorithmComposer([SignRoundConfig()], _compile_orchestrator(enable_torch_compile=False))+ assert not disabled.block_forward.enable_torch_compile+++def test_awq_disables_block_forward_compile():+ pipeline = AlgorithmComposer([AWQConfig(), SignRoundConfig()], _compile_orchestrator())- assert not _can_compile_block_forward(quantizer, [hadamard], user_enabled=True)- assert _can_compile_block_forward(quantizer, [CompileCompatibleRotation()], user_enabled=True)- assert not _can_compile_block_forward(quantizer, [], user_enabled=False)+ assert not pipeline.block_forward.enable_torch_compiledef test_detect_nvfp4_from_layer_config_scheme_override():diff --git a/test/unit/test_cpu/utils/test_model_scope.py b/test/unit/test_cpu/utils/test_model_scope.pyindex 5d15a1247..45368afe6 100644--- a/test/unit/test_cpu/utils/test_model_scope.py+++ b/test/unit/test_cpu/utils/test_model_scope.py@@ -1,7 +1,7 @@import copyimport osimport shutil-from test.helpers import get_model_path+from test.helpers import get_model_path, save_tiny_modelimport pytestimport torch@@ -13,8 +13,10 @@ class TestModelScope:@pytest.fixture(autouse=True)def setup_saved_path(self, tmp_path):self.saved_path = str(tmp_path / "saved")+ self.tiny_model_path = str(tmp_path / "tiny")yieldshutil.rmtree(self.saved_path, ignore_errors=True)+ shutil.rmtree(self.tiny_model_path, ignore_errors=True)@classmethoddef setup_class(self):@@ -32,13 +34,15 @@ class TestModelScope:@pytest.mark.timeout(120)def test_llm(self, dataloader):- model_name = get_model_path("Qwen/Qwen2.5-0.5B-Instruct")+ model_name = save_tiny_model(get_model_path("Qwen/Qwen2.5-0.5B-Instruct"), self.tiny_model_path, num_layers=2)autoround = AutoRound(model_name, platform="model_scope", scheme="w4a16", iters=0, seqlen=2, dataset=dataloader)- autoround.quantize_and_save()+ autoround.quantize_and_save(self.saved_path)@pytest.mark.timeout(480)def test_mllm(self, dataloader):- model_name = get_model_path("Qwen/Qwen2-VL-2B-Instruct")+ model_name = save_tiny_model(+ get_model_path("Qwen/Qwen2-VL-2B-Instruct"), self.tiny_model_path, num_layers=2, is_mllm=True+ )autoround = AutoRound(model_name, platform="model_scope", scheme="w4a16", iters=0, seqlen=2, dataset=dataloader, batch_size=2)diff --git a/test/unit/test_cuda/algorithms/test_awq.py b/test/unit/test_cuda/algorithms/test_awq.pyindex 15b7f3038..c072c7761 100644--- a/test/unit/test_cuda/algorithms/test_awq.py+++ b/test/unit/test_cuda/algorithms/test_awq.py@@ -123,7 +123,6 @@ class TestAWQMoE:yieldshutil.rmtree(self.save_dir, ignore_errors=True)- @pytest.mark.timeout(120)def test_awq_moe_dynamic_smoothing(self, tiny_qwen_moe_model_path):"""AWQ mapping resolution works on MoE model."""from auto_round.algorithms.transforms.awq.mappings import resolve_mappingsdiff --git a/test/unit/test_cuda/backends/test_exllamav2_backend.py b/test/unit/test_cuda/backends/test_exllamav2_backend.pyindex 7ca321b20..7ff82b9da 100644--- a/test/unit/test_cuda/backends/test_exllamav2_backend.py+++ b/test/unit/test_cuda/backends/test_exllamav2_backend.py@@ -128,7 +128,6 @@ class TestAutoRoundexllamaBackend:torch.cuda.empty_cache()@require_gptqmodel- @pytest.mark.timeout(90)def test_gptqmodel_awq_exllamav2_4bits_asym(self, dataloader):"""Test AWQ quantization with gptqmodel:awq_exllamav2 backend (bfloat16 inference)."""model_path = get_model_path("facebook/opt-125m")diff --git a/test/unit/test_cuda/backends/test_torch_backend.py b/test/unit/test_cuda/backends/test_torch_backend.pyindex dd03cd87b..f4127fb2c 100644--- a/test/unit/test_cuda/backends/test_torch_backend.py+++ b/test/unit/test_cuda/backends/test_torch_backend.py@@ -33,7 +33,6 @@ class TestAutoRoundTorchBackend:# Keep one CI test for torch backend and skip others to save time.# @pytest.mark.skip_ci(reason="Only tiny model is suggested")# @pytest.mark.skip_ci(reason="Time-consuming; Accuracy evaluation")- @pytest.mark.timeout(90)def test_torch_4bits_asym(self, dataloader):model_path = get_model_path("facebook/opt-125m")model = AutoModelForCausalLM.from_pretrained(model_path, torch_dtype="auto", trust_remote_code=True)diff --git a/test/unit/test_cuda/export/test_auto_round_format.py b/test/unit/test_cuda/export/test_auto_round_format.pyindex cbb185801..be463fde6 100644--- a/test/unit/test_cuda/export/test_auto_round_format.py+++ b/test/unit/test_cuda/export/test_auto_round_format.py@@ -174,8 +174,10 @@ class TestAutoRound:assert list(tmp_layer.weight_scale_inv.shape) == [16, 8]assert compressed_model.config.quantization_config["quant_method"] == "auto-round"assert compressed_model.config.quantization_config["weight_block_size"] == (128, 128)- if is_cuda_support_fp8():- eval_generated_prompt(quantized_model_path, device="cuda:0")+ # TODO: open below test after this issue is fixed.+ # https://github.com/huggingface/transformers/issues/46209+ # if is_cuda_support_fp8():+ # eval_generated_prompt(quantized_model_path, device="cuda:0")def test_fp8_block_autoround_format(self):model_name = "Qwen/Qwen3-0.6B"