Skip to content

PTQ-Level Efficiency, QAT-Level Accuracy | 训练后量化的效率,量化感知训练的精度

update cli and simplify --help (#2530)

Heng Guoaca358a1b741
diff --git a/README.md b/README.md
index 22f6829ff..239929fdf 100644
--- a/README.md
+++ b/README.md
@@ -66,11 +66,11 @@ It integrates with popular ecosystems including Transformers, vLLM, and SGLang,
* [2026/05] We provide **free** devices for quantization; please visit [Intel Low Bit Open LLM Leaderboard](https://huggingface.co/spaces/Intel/low_bit_open_llm_leaderboard) for more details.
-* [2025/12] The **SignRoundV2** paper is available. Turn on `enable_alg_ext` and use the **AutoScheme** API for mixed-precision quantization to reproduce the results: [*Paper*](http://arxiv.org/abs/2512.04746), [*Notes for evaluating LLaMA models*](./docs/alg_202508.md).
+* [2025/12] The **SignRoundV2** paper is available. Turn on the algorithm extension (`--algorithm auto_round_v2`, formerly `enable_alg_ext`) and use the **AutoScheme** API for mixed-precision quantization to reproduce the results: [*Paper*](http://arxiv.org/abs/2512.04746), [*Notes for evaluating LLaMA models*](./docs/alg_202508.md).
* [2025/10] AutoScheme is available to generate mixed-bit recipes in minutes: [*Usage*](https://github.com/intel/auto-round/blob/main/docs/step_by_step.md#autoscheme), [*Accuracy*](./docs/auto_scheme_acc.md).
-* [2025/08] An **improved INT2** algorithm is available via `--enable_alg_ext`: [*Accuracy*](./docs/alg_202508.md)
+* [2025/08] An **improved INT2** algorithm is available via the algorithm extension (`--algorithm auto_round_v2`, formerly `--enable_alg_ext`): [*Accuracy*](./docs/alg_202508.md)
* [2025/09] **MXFP4** and **NVFP4** dtypes is available: [*Accuracy*](./docs/mxnv_acc.md).
@@ -213,7 +213,7 @@ auto-round-fast \
</details>
-In conclusion, we recommend using **auto-round for W4A16 and auto-round-best with `enable_alg_ext` for W2A16**. However, you may adjust the
+In conclusion, we recommend using **auto-round for W4A16 and auto-round-best with `--algorithm auto_round_v2` for W2A16**. However, you may adjust the
configuration to suit your specific requirements and available resources.
> [!TIP]
@@ -252,10 +252,10 @@ ar.quantize_and_save(output_dir="./qmodel", format="auto_round")
- **`layer_config` (dict)**: Configuration for layer_wise scheme (default is `None`), mainly for customized mixed schemes.
##### Algorithm Settings
-- **`enable_alg_ext` (bool)**: [Experimental Feature] Only for `iters>0`. Enable algorithm variants for specific schemes (e.g., MXFP4/W2A16) that could bring notable improvements. Default is `False`.
-- **`alg_configs` (str|Config|list)**: Select one or more algorithms, such as `"awq"`, `"auto_round"`, or `['auto_round', 'quarot']`. Preprocessors run in list order and the block quantizer always runs last. Algorithm-specific options can be passed through their config objects, for example `SignRoundConfig(iters=50)`.
+- **`enable_alg_ext` (bool)**: [Deprecated] Use the `auto_round_v2` algorithm instead. [Experimental Feature] Only for `iters>0`. Enable algorithm variants for specific schemes (e.g., MXFP4/W2A16) that could bring notable improvements. Default is `False`.
+- **`alg_configs` (str|Config|list)**: Select one or more algorithms, such as `"awq"`, `"auto_round"`, `"auto_round_v2"`, `"rtn"`, `"opt-rtn"`, or `['auto_round', 'quarot']`. Preprocessors run in list order and the block quantizer always runs last. Algorithm-specific options can be passed through their config objects, for example `SignRoundConfig(iters=50)`.
-- **`disable_opt_rtn` (bool|None)**: Use pure RTN mode for specific schemes (e.g., GGUF and WOQ). Default is `None`. If None, it defaults to `False` in most cases to improve accuracy, but may be set to `True` due to known issues.
+- **`disable_opt_rtn` (bool|None)**: Use pure RTN mode for specific schemes (e.g., GGUF and WOQ). Default is `None`. If None, it defaults to `False` in most cases to improve accuracy, but may be set to `True` due to known issues. The algorithm name `rtn` selects pure RTN and `opt-rtn` selects the optimized path, on both the CLI (`--algorithm rtn`) and the Python API (`alg_configs="rtn"`); the name wins over the flag.
##### Tuning Process Parameters
- **`iters` (int)**: Number of tuning iterations (default is `200`). Common values: 0 (RTN mode), 50 (with lr=5e-3 recommended), 1000. Higher values increase accuracy but slow down tuning.
diff --git a/README_CN.md b/README_CN.md
index 4e11ea31e..c920887e1 100644
--- a/README_CN.md
+++ b/README_CN.md
@@ -75,11 +75,11 @@ AutoRound 旨在以合理的量化成本在低比特场景下实现出色的精
* [2026/03] 支持**MTP层量化**
-* [2025/12] 发布 **SignRoundV2** 论文。如果要复现论文成果,可启用 `enable_alg_ext`,并使用 **AutoScheme** API 对模型进行混合精度量化。相关链接:[*论文*](http://arxiv.org/abs/2512.04746),[*LLaMA 模型评估说明*](./docs/alg_202508.md)。
+* [2025/12] 发布 **SignRoundV2** 论文。如果要复现论文成果,可启用算法扩展(`--algorithm auto_round_v2`,原 `enable_alg_ext`),并使用 **AutoScheme** API 对模型进行混合精度量化。相关链接:[*论文*](http://arxiv.org/abs/2512.04746),[*LLaMA 模型评估说明*](./docs/alg_202508.md)。
* [2025/11] **LLM-Compressor** 已支持 AutoRound 算法。相关链接:[*使用方法*](https://github.com/vllm-project/llm-compressor/tree/main/examples/autoround/README.md),[*vLLM 博客*](https://blog.vllm.ai/2025/12/09/intel-autoround-llmc.html),[*RedHat 博客*](https://developers.redhat.com/articles/2025/12/09/advancing-low-bit-quantization-llms-autoround-x-llm-compressor),[*X 推文*](https://x.com/vllm_project/status/1998710451312771532),[*Intel 博客*](https://community.intel.com/t5/Blogs/Products-and-Solutions/HPC/Advancing-Low-Bit-Quantization-for-LLMs-AutoRound-x-LLM/post/1729336),[*LinkedIn*](https://www.linkedin.com/posts/vllm-project_advancing-lowbit-quantization-for-llms-activity-7404478053768441856-ru8f/?utm_source=share&utm_medium=member_desktop&rcm=ACoAAAapNW8BLnAdCAr57GOwSCJXjf76ZvOEOAg),[*微信*](https://mp.weixin.qq.com/s/l5WA-1_4ipffQN6GOH2Iqg),[*知乎*](https://zhuanlan.zhihu.com/p/1982167638315664412)。
-* [2025/11] 推出 **增强版 GGUF** 量化算法,启用 `--enable_alg_ext` 即可。相关链接:[*Accuracy*](./docs/gguf_alg_ext_acc.md)。
+* [2025/11] 推出 **增强版 GGUF** 量化算法,启用算法扩展(`--algorithm auto_round_v2`,原 `--enable_alg_ext`)即可。相关链接:[*Accuracy*](./docs/gguf_alg_ext_acc.md)。
* [2025/10] **SGLang** 已集成 AutoRound。相关链接:[*使用方法*](https://docs.sglang.io/advanced_features/quantization.html#using-auto-round),[*LMSYS 博客*](https://lmsys.org/blog/2025-11-13-AutoRound/),[*X 推文*](https://x.com/lmsysorg/status/1991977019220148650?s=20),[*Intel 博客*](https://community.intel.com/t5/Blogs/Tech-Innovation/Artificial-Intelligence-AI/AutoRound-Meets-SGLang-Enabling-Quantized-Model-Inference-with/post/1727196),[*LinkedIn*](https://www.linkedin.com/feed/update/urn:li:activity:7397742859354857472)。
@@ -87,7 +87,7 @@ AutoRound 旨在以合理的量化成本在低比特场景下实现出色的精
* [2025/09] 新增对 **MXFP4** 和 **NVFP4** 数据类型的支持。相关链接:[*Accuracy*](./docs/mxnv_acc.md)。
-* [2025/08] 提供 **改进版 INT2** 算法,启用 `--enable_alg_ext` 即可。相关链接:[*Accuracy*](./docs/alg_202508.md)。
+* [2025/08] 提供 **改进版 INT2** 算法,启用算法扩展(`--algorithm auto_round_v2`,原 `--enable_alg_ext`)即可。相关链接:[*Accuracy*](./docs/alg_202508.md)。
* [2025/07] 新增 **GGUF** 格式导出。相关链接:[*使用方法*](./docs/step_by_step.md#gguf-format)。
@@ -223,7 +223,7 @@ auto-round-fast \
</details>
-小结:对于 ​**W4A16 量化,我们建议使用默认的 auto-round;而 W2A16 量化我们则推荐启用 ​`enable_alg_ext`​ 参数的 auto-round-best​**。当然,您也可以根据自身需求和手头上的算力灵活调整配置。
+小结:对于 ​**W4A16 量化,我们建议使用默认的 auto-round;而 W2A16 量化我们则推荐启用 ​`--algorithm auto_round_v2`​ 的 auto-round-best​**。当然,您也可以根据自身需求和手头上的算力灵活调整配置。
> [!TIP]
> 对于 **INT2(W2A16)**,精度会随着调优成本的增加而稳步提升。增大 `--iters`(例如 1000 → 2000)、`--nsamples`、`--seqlen` 等参数,或改用带 `--enable_alg_ext` 的 `auto-round-best` 配方,都能以额外的调优时间换取持续更高的精度。随着校准数据量的增大(更大的 `--nsamples`/`--seqlen`),将学习率提高到 `4.0/iters`(例如 `--iters 1000` 时取 `4e-3`)通常会有帮助。详细结果请参阅 [W2A16 精度数据](./docs/alg_202508.md)。
@@ -264,9 +264,9 @@ ar.quantize_and_save(output_dir="./qmodel", format="auto_round")
##### 算法相关设置
-- ​**​`enable_alg_ext`​**​(bool):[实验性功能] 仅在 `iters > 0`​ 时生效。在特定 scheme(如 MXFP4 / W2A16)下启用算法扩展,可显著提升量化效果。默认值为 `False`。
-- **`alg_configs`**(str | Config | list):选择一个或多个算法,例如 `"awq"`、`"auto_round"` 或 `['auto_round', 'quarot']`。预处理算法按照列表顺序执行,block quantizer 始终最后执行。算法专用参数可以通过对应的 config 对象传入,例如 `SignRoundConfig(iters=50)`。
-- ​**​`disable_opt_rtn`​**​(bool | None):是否对特定方案(如 GGUF 与权重量化方案)禁用优化的 RTN 模式。优化的 RTN 模式需要标定数据和更多的算力来提升精度。默认值为 `None`:在大多数情况下,为提升精度,算法会自动采用优化的 RTN 模式(即 `False`);仅在已知存在兼容性问题时,才会自动禁用(即 `True`)
+- ​**​`enable_alg_ext`​**​(bool):[已弃用] 请改用 `auto_round_v2` 算法。[实验性功能] 仅在 `iters > 0`​ 时生效。在特定 scheme(如 MXFP4 / W2A16)下启用算法扩展,可显著提升量化效果。默认值为 `False`。
+- **`alg_configs`**(str | Config | list):选择一个或多个算法,例如 `"awq"`、`"auto_round"`、`"auto_round_v2"`、`"rtn"`、`"opt-rtn"` 或 `['auto_round', 'quarot']`。预处理算法按照列表顺序执行,block quantizer 始终最后执行。算法专用参数可以通过对应的 config 对象传入,例如 `SignRoundConfig(iters=50)`。
+- ​**​`disable_opt_rtn`​**​(bool | None):是否对特定方案(如 GGUF 与权重量化方案)禁用优化的 RTN 模式。优化的 RTN 模式需要标定数据和更多的算力来提升精度。默认值为 `None`:在大多数情况下,为提升精度,算法会自动采用优化的 RTN 模式(即 `False`);仅在已知存在兼容性问题时,才会自动禁用(即 `True`)。算法名 `rtn` 表示纯 RTN,`opt-rtn` 表示优化 RTN,命令行(`--algorithm rtn`)与 Python API(`alg_configs="rtn"`)一致;算法名优先于该开关。
diff --git a/auto_round/algorithms/config.py b/auto_round/algorithms/config.py
index d533b162e..ad9077e19 100644
--- a/auto_round/algorithms/config.py
+++ b/auto_round/algorithms/config.py
@@ -16,8 +16,10 @@
from __future__ import annotations
+from collections.abc import Mapping
from dataclasses import dataclass
from dataclasses import field as dataclass_field
+from types import MappingProxyType
from typing import Any, ClassVar
@@ -89,6 +91,12 @@ class AlgorithmConfig:
cli_include_common_args: ClassVar[bool] = True
+ #: Optional per-field help text for configs whose CLI arguments are derived
+ #: from their constructor signature instead of ``register_args`` (see the
+ #: CLI fallback registry). Keyed by constructor parameter name.
+ #: Subclasses should override this mapping rather than mutate the base default.
+ cli_field_help: ClassVar[Mapping[str, str]] = MappingProxyType({})
+
@classmethod
def register_args(cls, registry: AlgorithmParameterRegistry) -> None:
"""Register algorithm-specific parameters. The default declares none."""
diff --git a/auto_round/algorithms/quantization/rtn/config.py b/auto_round/algorithms/quantization/rtn/config.py
index ad0c2dc1d..201641bf6 100644
--- a/auto_round/algorithms/quantization/rtn/config.py
+++ b/auto_round/algorithms/quantization/rtn/config.py
@@ -31,7 +31,7 @@ class RTNConfig(QuantizationConfig):
dest="disable_opt_rtn",
action="store_const",
const=True,
- help="Force plain RTN (disable optimized path).",
+ help="Force plain RTN (disable optimized path). Equivalent to `--algorithm rtn`.",
)
mutex.add_argument(
"--enable_opt_rtn",
@@ -39,7 +39,7 @@ class RTNConfig(QuantizationConfig):
dest="disable_opt_rtn",
action="store_const",
const=False,
- help="Force optimized RTN path.",
+ help="Force optimized RTN path. Equivalent to `--algorithm opt-rtn`.",
)
registry.add_argument(
"--enable_neuqi",
@@ -112,9 +112,31 @@ class OptimizedRTNConfig(RTNConfig):
need_calib = True
+#: RTN variants selectable by algorithm name, mapped to the ``disable_opt_rtn``
+#: value the name forces. ``rtn`` means plain RTN and ``opt-rtn`` the optimized
+#: path; both the CLI and the entry API resolve the names through this mapping so
+#: the name means the same thing everywhere.
+RTN_VARIANT_DISABLE_OPT_RTN = {"rtn": True, "opt-rtn": False}
+
+
+def validate_rtn_variant_names(names) -> None:
+ """Reject conflicting canonical RTN variant names before constructing configs."""
+ variants = {name for name in names if isinstance(name, str) and name in RTN_VARIANT_DISABLE_OPT_RTN}
+ if len(variants) > 1:
+ raise ValueError("Cannot select both 'rtn' and 'opt-rtn'; choose one RTN variant.")
+
+
register_algorithm(
"rtn",
aliases=("rtn",),
config_factory=RTNConfig,
- summary="Round-To-Nearest quantization.",
+ summary="Round-To-Nearest quantization (plain, no optimized initialization).",
+)
+
+
+register_algorithm(
+ "opt-rtn",
+ aliases=("opt-rtn", "opt_rtn", "optimized_rtn", "optimized-rtn"),
+ config_factory=OptimizedRTNConfig,
+ summary="Round-To-Nearest quantization with the optimized initialization path.",
)
diff --git a/auto_round/algorithms/quantization/sign_round/config.py b/auto_round/algorithms/quantization/sign_round/config.py
index 32be62e94..e11f064a1 100644
--- a/auto_round/algorithms/quantization/sign_round/config.py
+++ b/auto_round/algorithms/quantization/sign_round/config.py
@@ -80,7 +80,8 @@ class SignRoundConfig(QuantizationConfig):
field="enable_alg_ext",
default=False,
action="boolean_optional",
- help="Enable experimental SignRound extension.",
+ help="(Deprecated) Enable the experimental SignRound algorithm extension. "
+ "Use `--algorithm auto_round_v2` instead.",
)
registry.add_argument(
"--not_use_best_mse",
@@ -171,8 +172,11 @@ class SignRoundConfig(QuantizationConfig):
bias terms.
gradient_accumulate_steps: Number of gradient accumulation
steps used per optimization update.
- enable_alg_ext: Whether to enable the experimental SignRound
- extension implementation.
+ enable_alg_ext: Deprecated. Whether to enable the experimental
+ SignRound extension implementation. Selecting the
+ ``auto_round_v2`` algorithm is the supported way to turn it on;
+ this switch is kept for backward compatibility and is
+ normalized to :class:`SignRoundV2Config`.
not_use_best_mse: Whether to skip restoring the best-MSE
checkpoint during tuning.
dynamic_max_gap: Maximum dynamic gap used by adaptive tuning
@@ -294,7 +298,33 @@ class AdamRoundConfig(SignRoundConfig):
class SignRoundV2Config(SignRoundConfig):
- pass
+ """SignRound with the algorithm extension (the former ``enable_alg_ext``) enabled.
+
+ The extension is intrinsic to this config, so ``enable_alg_ext`` reads as
+ ``True`` no matter how the config was built — including the ``__class__``
+ rewrite performed by :func:`normalize_algorithm_config` and direct attribute
+ assignment, both of which bypass ``__init__``. Select this config with
+ ``--algorithm auto_round_v2`` (CLI) or ``alg_configs="auto_round_v2"``
+ (Python API); the deprecated ``--enable_alg_ext`` switch is not redeclared
+ for it on the CLI.
+ """
+
+ @classmethod
+ def get_registered_args(cls) -> AlgorithmParameterRegistry:
+ """Declare the SignRound flags, minus the deprecated ``--enable_alg_ext`` switch."""
+ registry = super().get_registered_args()
+ registry.parameters = [parameter for parameter in registry.parameters if parameter.field != "enable_alg_ext"]
+ return registry
+
+ @property
+ def enable_alg_ext(self) -> bool:
+ """Always ``True``: the algorithm extension cannot be disabled for this config."""
+ return True
+
+ @enable_alg_ext.setter
+ def enable_alg_ext(self, value: bool) -> None:
+ # The extension is not optional here, so the assigned value is dropped.
+ pass
register_algorithm(
@@ -303,3 +333,11 @@ register_algorithm(
config_factory=SignRoundConfig,
summary="SignRound-style iterative block quantization.",
)
+
+
+register_algorithm(
+ "auto_round_v2",
+ aliases=("auto_round_v2", "auto_roundv2", "sign_round_v2", "signroundv2"),
+ config_factory=SignRoundV2Config,
+ summary="SignRound with the algorithm extension (the former `enable_alg_ext`) enabled.",
+)
diff --git a/auto_round/algorithms/registry.py b/auto_round/algorithms/registry.py
index 0e96bd1e4..c96b3db03 100644
--- a/auto_round/algorithms/registry.py
+++ b/auto_round/algorithms/registry.py
@@ -27,7 +27,6 @@ _ALIAS_TO_NAME: dict[str, str] = {}
_CONFIG_IMPL_REGISTRY: dict[type, type[BaseAlgorithm]] = {}
_builtin_algorithms_registered = False
_pipeline_members_registered = False
-_BUILTIN_ALGORITHM_ORDER = ("rtn", "auto_round", "awq", "svdquant", "hadamard", "quarot", "spinquant")
def _ensure_builtin_algorithms_registered() -> None:
@@ -100,7 +99,7 @@ def resolve_algorithm_alias(alias: str) -> str | None:
return _ALIAS_TO_NAME.get(alias.strip().lower())
-def resolve_algorithm_names(algorithms, *, ignore_unknown: bool = False) -> list[str]:
+def resolve_algorithm_names(algorithms) -> list[str]:
"""Resolve one algorithm string or sequence to ordered canonical names.
A comma-separated string and a sequence use exactly the same semantics.
@@ -121,11 +120,8 @@ def resolve_algorithm_names(algorithms, *, ignore_unknown: bool = False) -> list
continue
canonical = resolve_algorithm_alias(name)
if canonical is None:
- if ignore_unknown:
- continue
- supported_aliases = sorted(_ALIAS_TO_NAME.keys())
raise ValueError(
- f"Unknown algorithm alias '{name}'. Supported aliases: {supported_aliases}. "
+ f"Unknown algorithm alias '{name}'. Supported algorithms: {sorted(_ALG_REGISTRY)}. "
"If you are adding a new algorithm, register it via "
"auto_round.algorithms.registry.register_algorithm()."
)
@@ -145,9 +141,7 @@ def get_algorithm_entry(name: str) -> AlgRegistryEntry:
def iter_algorithm_entries() -> list[AlgRegistryEntry]:
_ensure_builtin_algorithms_registered()
- builtin = [_ALG_REGISTRY[name] for name in _BUILTIN_ALGORITHM_ORDER if name in _ALG_REGISTRY]
- custom = [entry for name, entry in _ALG_REGISTRY.items() if name not in _BUILTIN_ALGORITHM_ORDER]
- return builtin + custom
+ return list(_ALG_REGISTRY.values())
def resolve_alg_config(alias: str) -> object:
@@ -155,7 +149,7 @@ def resolve_alg_config(alias: str) -> object:
canonical = resolve_algorithm_alias(alias)
if canonical is None:
raise ValueError(
- f"Unknown algorithm alias '{alias}'. Supported aliases: {sorted(_ALIAS_TO_NAME.keys())}. "
+ f"Unknown algorithm alias '{alias}'. Supported algorithms: {sorted(_ALG_REGISTRY)}. "
"If you are adding a new algorithm, register it via auto_round.algorithms.registry.register_algorithm()."
)
diff --git a/auto_round/algorithms/transforms/spinquant/preprocessor.py b/auto_round/algorithms/transforms/spinquant/preprocessor.py
index 2cbec11ea..6d0d28dfb 100644
--- a/auto_round/algorithms/transforms/spinquant/preprocessor.py
+++ b/auto_round/algorithms/transforms/spinquant/preprocessor.py
@@ -132,6 +132,30 @@ class SpinQuantConfig(BaseRotationConfig):
dtype: torch.dtype = torch.float32
device: str | None = None
+ #: CLI descriptions for the flags derived from this dataclass's signature.
+ cli_field_help = {
+ "layerwise": "Rotate each decoder block in lock-step with block-wise quantization "
+ "instead of rotating the whole model up front.",
+ "r1": "Rotate the residual stream (R1).",
+ "r2": "Rotate the attention head dimension (R2).",
+ "r3": "Rotate the attention value path online (R3).",
+ "r4": "Rotate the MLP down-projection online (R4).",
+ "rotation_size": "Override the R1/R4 rotation dimension; must be a power of two. " "R2/R3 always use head_dim.",
+ "random_r1": "Use a random Hadamard matrix for R1 instead of the deterministic one.",
+ "random_r2": "Use a random Hadamard matrix for R2 instead of the deterministic one.",
+ "random_r3": "Use a random Hadamard matrix for R3 instead of the deterministic one.",
+ "random_r4": "Use a random Hadamard matrix for R4 instead of the deterministic one.",
+ "trainable_rotation": "Learn the rotation matrices (SpinQuant mode) instead of using fixed "
+ "Hadamard matrices (QuaRot mode).",
+ "trainable_smooth": "Learn the SmoothQuant smoothing scales jointly with the rotation.",
+ "online_r1_rotation": "Apply R1 through an online forward hook instead of fusing it into the weights.",
+ "smooth_lr": "Learning rate of the smoothing-scale optimizer.",
+ "loss_type": "Training loss: 'kl_top', 'kl_full' or 'mse'.",
+ "kl_top_k": "Number of top logits used by the 'kl_top' loss.",
+ "fuse_rmsnorm": "Fuse the RMSNorm scaling into the adjacent linear layers.",
+ "untie_embeddings": "Untie the input/output embeddings before rotating.",
+ }
+
def __post_init__(self):
if self.device is None:
self.device = "cuda" if torch.cuda.is_available() else "cpu"
diff --git a/auto_round/autoround.py b/auto_round/autoround.py
index 4c777606d..099c0e8ef 100644
--- a/auto_round/autoround.py
+++ b/auto_round/autoround.py
@@ -341,7 +341,11 @@ def _owning_algorithm_names(field_name: str) -> list[str]:
def _normalize_alg_configs(alg_configs, direct_kwargs=None, *, strict=False):
from auto_round.algorithms.config_resolver import split_quantization_configs
from auto_round.algorithms.quantization.config import QuantizationConfig
- from auto_round.algorithms.quantization.rtn.config import RTNConfig
+ from auto_round.algorithms.quantization.rtn.config import (
+ RTN_VARIANT_DISABLE_OPT_RTN,
+ RTNConfig,
+ validate_rtn_variant_names,
+ )
from auto_round.algorithms.registry import normalize_algorithm_config, resolve_alg_config, resolve_algorithm_names
from auto_round.algorithms.transforms import normalize_rotation_config
from auto_round.algorithms.transforms.awq.config import (
@@ -391,6 +395,18 @@ def _normalize_alg_configs(alg_configs, direct_kwargs=None, *, strict=False):
else:
raw_configs = [alg_configs]
+ validate_rtn_variant_names(raw_configs)
+
+ # An `rtn` / `opt-rtn` the caller actually named selects the RTN variant, the
+ # same way `--algorithm rtn` / `--algorithm opt-rtn` does on the CLI. When
+ # `alg_configs` is None the RTN config below is an implicit fallback, so it
+ # must keep the existing flag/heuristic behaviour.
+ named_rtn_variants = (
+ [name for name in raw_configs if isinstance(name, str) and name in RTN_VARIANT_DISABLE_OPT_RTN]
+ if alg_configs is not None
+ else []
+ )
+
configs = []
pending_rtn_indices = []
for raw_config in raw_configs:
@@ -508,6 +524,18 @@ def _normalize_alg_configs(alg_configs, direct_kwargs=None, *, strict=False):
recommended_config_name,
)
sync_rtn_opt_rtn_from_awq(configs)
+ if named_rtn_variants:
+ # Applied last, on RTN configs only (AWQ keeps its own policy), so the
+ # algorithm name is not overridden by the AWQ inheritance above or by a
+ # contradicting `disable_opt_rtn` argument. `orig_disable_opt_rtn` marks
+ # it as user policy, which is what stops the W8A16/W8A8 efficiency
+ # heuristic from silently switching the variant back.
+ forced_disable_opt_rtn = RTN_VARIANT_DISABLE_OPT_RTN[named_rtn_variants[0]]
+ for config in configs:
+ if isinstance(config, RTNConfig):
+ config.disable_opt_rtn = forced_disable_opt_rtn
+ if hasattr(config, "orig_disable_opt_rtn"):
+ config.orig_disable_opt_rtn = forced_disable_opt_rtn
return [normalize_algorithm_config(config) for config in configs]
diff --git a/auto_round/cli/algorithms.py b/auto_round/cli/algorithms.py
index 23f9dccb8..648c27838 100644
--- a/auto_round/cli/algorithms.py
+++ b/auto_round/cli/algorithms.py
@@ -22,6 +22,7 @@ from dataclasses import replace
from typing import Any, get_args, get_origin, get_type_hints
from auto_round.algorithms.config import AlgorithmConfig, AlgorithmParameterRegistry
+from auto_round.algorithms.quantization.rtn.config import RTN_VARIANT_DISABLE_OPT_RTN, validate_rtn_variant_names
from auto_round.algorithms.registry import (
get_algorithm_entry,
iter_algorithm_entries,
@@ -48,13 +49,19 @@ def _has_custom_register_args(config_cls: type) -> bool:
def _fallback_parameter_registry(config_cls: type) -> AlgorithmParameterRegistry:
- """Derive simple CLI arguments from a config that has no custom registration."""
+ """Derive simple CLI arguments from a config that has no custom registration.
+
+ A config may describe its derived flags through ``cli_field_help`` (a
+ ``{constructor parameter: help text}`` mapping); otherwise the flags show up
+ in ``--help`` without a description.
+ """
registry = AlgorithmParameterRegistry()
init = config_cls.__init__
try:
type_hints = get_type_hints(init)
except (NameError, TypeError):
type_hints = {}
+ field_help = getattr(config_cls, "cli_field_help", {})
for name, parameter in inspect.signature(init).parameters.items():
if name in {"self", "algorithm"} or parameter.kind in (
@@ -74,6 +81,8 @@ def _fallback_parameter_registry(config_cls: type) -> AlgorithmParameterRegistry
args = [arg for arg in get_args(annotation) if arg is not type(None)]
value_type = args[0] if origin is not None and args else annotation
kwargs = {"type": value_type, "default": argparse.SUPPRESS}
+ if field_help.get(name):
+ kwargs["help"] = field_help[name]
registry.add_argument(f"--{name}", field=name, **kwargs)
return registry
@@ -157,6 +166,46 @@ def _add_registered_arguments(group, registry: AlgorithmParameterRegistry) -> No
_add_parameter(target, parameter)
+# Algorithms that supply the block-quantization tuning step themselves. Selecting
+# any of them must not append the implicit `auto_round` fallback below.
+_BLOCK_QUANTIZER_ALGORITHMS = frozenset({"rtn", "opt-rtn", "auto_round", "auto_round_v2"})
+
+# `auto_round_v2` is a SignRound variant: with zero tuning iterations there is
+# nothing to tune, so it degrades to RTN exactly like `auto_round`.
+_ITERS_ZERO_ALGORITHMS = {"auto_round": "rtn", "auto_round_v2": "rtn"}
+
+# RTN variants selectable by name (`RTN_VARIANT_DISABLE_OPT_RTN` in the RTN config
+# module, shared with the entry API). The name is authoritative, so a contradicting
+# flag is ignored rather than silently winning. The mapping only applies when the
+# user spells the name out: the implicit `rtn` fallback (no `--algorithm`, the
+# `auto-round-rtn` / `auto-round-opt-rtn` recipes) keeps the existing flag- and
+# heuristic-driven behaviour.
+
+
+def _find_merge_target(merged_parameters, locations, group_name, parameter) -> int | None:
+ """Find an already-declared parameter that ``parameter`` should merge into.
+
+ Option strings are matched before the destination. A mutually exclusive pair
+ (e.g. ``--enable_minmax_tuning`` / ``--no-enable_minmax_tuning``) declares two
+ actions that share one ``dest``, so matching on ``dest`` alone would report a
+ conflict between the two halves of the same pair when a second algorithm
+ redeclares it. Parameters that share only a ``dest`` are merged when their
+ parsing semantics are identical, which keeps genuinely incompatible
+ re-declarations (same option string, different semantics) an error.
+ """
+ for index, item in enumerate(merged_parameters):
+ if locations[index][0] != group_name and set(item.option_strings) & set(parameter.option_strings):
+ return index
+ for index, item in enumerate(merged_parameters):
+ if (
+ locations[index][0] != group_name
+ and item.dest == parameter.dest
+ and _argument_compatibility_key(item) == _argument_compatibility_key(parameter)
+ ):
+ return index
+ return None
+
+
class AlgorithmHandler:
"""Generic discovery, argparse adaptation, and config construction."""
@@ -194,17 +243,7 @@ class AlgorithmHandler:
for parameter in registry.parameters:
if _check_existing_parser_argument(parser, parameter, fallback=fallback):
continue
- existing_index = next(
- (
- index
- for index, item in enumerate(merged_parameters)
- if locations[index][0] != group_name
- and (
- item.dest == parameter.dest or set(item.option_strings) & set(parameter.option_strings)
- )
- ),
- None,
- )
+ existing_index = _find_merge_target(merged_parameters, locations, group_name, parameter)
if existing_index is not None:
merged = _merge_parameter(merged_parameters[existing_index], parameter)
merged_parameters[existing_index] = merged
@@ -216,6 +255,12 @@ class AlgorithmHandler:
locations.append((group_name, len(parameters_by_group[group_name]) - 1))
for group_name, parameters in parameters_by_group.items():
+ if not parameters:
+ # Every flag of this algorithm is already declared by an earlier
+ # group with identical semantics (e.g. `auto_round_v2` reuses the
+ # SignRound switches), so an empty group would only add a blank
+ # header to `--help`.
+ continue
group = parser.add_argument_group(group_name)
registry = AlgorithmParameterRegistry()
registry.parameters = parameters
@@ -229,12 +274,17 @@ class AlgorithmHandler:
if getattr(args, "rotation_hadamard_type", None) and "hadamard" not in names:
names.append("hadamard")
- canonical = resolve_algorithm_names(names, ignore_unknown=True)
+ canonical = resolve_algorithm_names(names)
+ validate_rtn_variant_names(canonical)
+ # Names the user actually wrote. The implicit block-quantizer fallback
+ # appended below is deliberately excluded: only an explicit `rtn` /
+ # `opt-rtn` carries the plain-vs-optimized intent.
+ explicit_names = set(canonical)
seen = set(canonical)
- if not ({"rtn", "auto_round"} & seen):
+ if not (_BLOCK_QUANTIZER_ALGORITHMS & seen):
canonical.append("rtn" if "awq" in seen or getattr(args, "iters", 0) == 0 else "auto_round")
if getattr(args, "iters", None) == 0:
- canonical = ["rtn" if name == "auto_round" else name for name in canonical]
+ canonical = [_ITERS_ZERO_ALGORITHMS.get(name, name) for name in canonical]
configs = []
built_configs = {}
@@ -264,7 +314,11 @@ class AlgorithmHandler:
kwargs = _parameter_registry(config_cls).config_kwargs(args)
if getattr(config_cls, "cli_include_common_args", True):
kwargs.update(common_kwargs)
- if name == "rtn" and getattr(args, "disable_opt_rtn", None) is None and awq_disable_opt_rtn is not None:
+ if name in explicit_names and name in RTN_VARIANT_DISABLE_OPT_RTN:
+ # The algorithm name is authoritative: it selects the variant
+ # even when the opposite flag was passed as well.
+ kwargs["disable_opt_rtn"] = RTN_VARIANT_DISABLE_OPT_RTN[name]
+ elif name == "rtn" and getattr(args, "disable_opt_rtn", None) is None and awq_disable_opt_rtn is not None:
kwargs["disable_opt_rtn"] = awq_disable_opt_rtn
if isinstance(entry.config_factory, type):
config = entry.config_factory(**kwargs)
@@ -302,6 +356,9 @@ class AlgorithmHandler:
cls.add_group(canonical, group)
for action in group._group_actions:
flags = ", ".join(action.option_strings)
- default = f" (default: {action.default})" if action.default is not None else ""
+ if action.default is None or action.default is argparse.SUPPRESS:
+ default = ""
+ else:
+ default = f" (default: {action.default})"
lines.append(f" {flags}: {action.help or ''}{default}")
return "\n".join(lines)
diff --git a/auto_round/cli/main.py b/auto_round/cli/main.py
index 546e2df37..7984a58bd 100644
--- a/auto_round/cli/main.py
+++ b/auto_round/cli/main.py
@@ -27,6 +27,119 @@ from auto_round.cli.parser import (
from auto_round.compressors.config_resolution import ConfigResolutionError
from auto_round.logger import logger
+# Flags surfaced by `auto_round --help`. Entries are (dest, shown option strings):
+# the overview is a curated subset, so a few flags list only their primary name
+# instead of every alias. The full list stays behind `auto_round quantize --help`.
+_OVERVIEW_ARGUMENTS: tuple[tuple[str, tuple[str, ...]], ...] = (
+ ("model", ()),
+ ("model_name", ("--model",)),
+ ("scheme", ("--scheme",)),
+ ("algorithm", ("--algorithm",)),
+ ("bits", ("--bits",)),
+ ("group_size", ("--group_size",)),
+ ("iters", ("--iters",)),
+ ("nsamples", ("--nsamples",)),
+ ("seqlen", ("--seqlen",)),
+ ("batch_size", ("--batch_size",)),
+ ("device_map", ("--device_map",)),
+ ("format", ("--format",)),
+ ("output_dir", ("--output_dir",)),
+ ("asym", ("--asym",)),
+ ("ignore_layers", ("--ignore_layers",)),
+ ("tasks", ("--tasks",)),
+)
+
+_OVERVIEW_DESCRIPTION = """\
+AutoRound command line interface: quantize, evaluate and inspect models.
+
+commands:
+ quantize Quantize a model. This is the default command, so
+ `auto_round --model <path> ...` works without naming it.
+ list List the supported quantization schemes/formats or algorithms.
+ eval Evaluate a quantized or original model.
+ help [topic] Show this overview, or the help of `quantize`/`list`/`eval`.
+
+examples:
+ auto_round --model facebook/opt-125m --bits 4 --group_size 128
+ auto_round --model Qwen/Qwen3-0.6B --algorithm auto_round_v2 --iters 200
+ auto_round --model Qwen/Qwen3-0.6B --algorithm awq,auto_round_v2
+ auto_round --model <model> --schemes W2A16,W4A16 --bits 3 --ignore_scale_zp_bits
+ auto_round eval --model <quantized_model> --tasks lambada_openai
+ auto_round list alg
+
+This is only the commonly used subset of the quantize arguments.
+"""
+
+_OVERVIEW_EPILOG = """\
+see also:
+ auto_round quantize --help every quantize argument
+ auto_round --algorithm <name> --help the flags of one algorithm
+ auto_round list alg the supported algorithms
+ auto_round list format the supported output formats
+"""
+
+
+def _overview_parser(prog: str = "auto_round") -> argparse.ArgumentParser:
+ """Build the display-only parser behind the `auto_round --help` overview.
+
+ The curated flags are redeclared from the real quantize parser rather than
+ hard-coded, so the overview cannot drift from the actual help strings and
+ defaults. Only rendering matters here: this parser never parses anything.
+ """
+ full = build_quantize_parser(prog=prog)
+ by_dest: dict[str, argparse.Action] = {}
+ for action in full._actions:
+ if action.help is argparse.SUPPRESS:
+ # Hidden legacy aliases (e.g. --avg_bits, which also has dest="bits")
+ # must not shadow the documented flag they alias.
+ continue
+ by_dest.setdefault(action.dest, action)
+
+ parser = argparse.ArgumentParser(
+ prog=prog,
+ add_help=False,
+ usage="auto_round [<command>] [options]",
+ description=_OVERVIEW_DESCRIPTION,
+ epilog=_OVERVIEW_EPILOG,
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ )
+ group = parser.add_argument_group("common arguments")
+ for dest, shown_options in _OVERVIEW_ARGUMENTS:
+ action = by_dest.get(dest)
+ if action is None:
+ continue
+ if not action.option_strings:
+ group.add_argument(dest, nargs="?", help=action.help)
+ continue
+ options = list(shown_options or action.option_strings)
+ kwargs = {"help": action.help, "dest": action.dest}
+ if action.nargs == 0:
+ # A boolean switch: render it as one instead of as a value-taking flag.
+ if isinstance(action, argparse.BooleanOptionalAction):
+ group.add_argument(*options[:1], action=argparse.BooleanOptionalAction, **kwargs)
+ else:
+ group.add_argument(*options, action="store_true", default=argparse.SUPPRESS, **kwargs)
+ else:
+ kwargs["default"] = argparse.SUPPRESS
+ if action.metavar is not None:
+ kwargs["metavar"] = action.metavar
+ if action.nargs is not None:
+ kwargs["nargs"] = action.nargs
+ if action.choices is not None:
+ kwargs["choices"] = action.choices
+ group.add_argument(*options, **kwargs)
+ return parser
+
+
+def _print_overview_help() -> None:
+ """Print the concise top-level `auto_round --help` overview."""
+ _overview_parser().print_help()
+
+
+def _requests_overview_help(argv: list[str]) -> bool:
+ """True for a bare `auto_round --help`/`-h` that names no subcommand or topic."""
+ return bool(argv) and all(token in ("-h", "--help") for token in argv)
+
def _extract_common_quantization_kwargs(args) -> dict:
"""Map parsed CLI args back to QuantizationConfig constructor kwargs.
@@ -295,6 +408,12 @@ def tune(args):
"To disable it, use `--disable_low_cpu_mem_usage`."
)
+ if getattr(args, "enable_alg_ext", False):
+ logger.warning(
+ "`--enable_alg_ext` is deprecated; use `--algorithm auto_round_v2` instead. "
+ "Both select the same algorithm and remain equivalent."
+ )
+
if args.format is None:
args.format = "auto_round"
@@ -545,12 +664,15 @@ def _print_help(topic=None):
if topic == "eval":
build_eval_parser(prog="auto_round eval").print_help()
return
- build_root_parser().print_help()
+ _print_overview_help()
def run():
try:
argv = list(sys.argv[1:])
+ if _requests_overview_help(argv):
+ _print_overview_help()
+ return
command, command_argv = _normalize_cli_invocation(argv)
if command == "help":
diff --git a/auto_round/cli/parser.py b/auto_round/cli/parser.py
index 1997f5eee..60c29e799 100644
--- a/auto_round/cli/parser.py
+++ b/auto_round/cli/parser.py
@@ -172,7 +172,8 @@ def build_quantize_parser(*, prog: str = "auto_round quantize") -> argparse.Argu
"--alg_configs",
default=None,
type=str,
- help="Comma-separated algorithms such as 'awq' or 'awq,auto_round'.",
+ help="Comma-separated algorithms such as 'auto_round', 'auto_round_v2', 'rtn', 'opt-rtn' "
+ "or 'awq'. Run `auto_round list alg` for the full list.",
)
rt.add_argument("--output_dir", default="./tmp_autoround", type=str, help="Directory to save quantized artifacts.")
rt.add_argument(
diff --git a/auto_round/export/formats/backends/gguf.py b/auto_round/export/formats/backends/gguf.py
index 8a215930c..5286d9a69 100644
--- a/auto_round/export/formats/backends/gguf.py
+++ b/auto_round/export/formats/backends/gguf.py
@@ -129,7 +129,8 @@ class GGUFFormat(OutputFormat):
if ctx.iters != 0 and scheme.bits != 3 and not ctx.enable_alg_ext:
logger.warning_once(
"`iters=0` is recommended when exporting to current GGUF format"
- " or add `enable_alg_ext` for better accuracy with much more tuning cost."
+ " or use `--algorithm auto_round_v2` (the former `enable_alg_ext`) for better accuracy"
+ " with much more tuning cost."
" Please refer to https://github.com/intel/auto-round/tree/main/docs/gguf_alg_ext_acc.md"
" for the accuracy results."
)
diff --git a/docs/awq_details.md b/docs/awq_details.md
index 116f2e51c..ff9561509 100644
--- a/docs/awq_details.md
+++ b/docs/awq_details.md
@@ -31,7 +31,7 @@ auto-round --model <model> --scheme <scheme> --format fake \
--tasks "mmlu,gsm8k,piqa,hellaswag,winogrande"
auto-round --model <model> --scheme <scheme> --format fake \
- --enable_alg_ext --algorithm auto_round \
+ --algorithm auto_round_v2 \
--tasks "mmlu,gsm8k,piqa,hellaswag,winogrande"
# AWQ + RTN / AWQ + AutoRound / AWQ + AutoRound with algorithm extension
@@ -44,11 +44,11 @@ auto-round --model <model> --scheme <scheme> --format fake \
--tasks "mmlu,gsm8k,piqa,hellaswag,winogrande"
auto-round --model <model> --scheme <scheme> --format fake \
- --enable_alg_ext --algorithm awq,auto_round \
+ --algorithm awq,auto_round_v2 \
--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`. Accuracy columns are reported as percentages, so a raw score such as `0.7058` is shown as `70.58`.
+In the result tables, `AR2` denotes AutoRound with `--algorithm auto_round_v2` (formerly `--enable_alg_ext`), and `AWQ_AR2` denotes AWQ followed by AutoRound with the same algorithm extension. Accuracy columns are reported as percentages, so a raw score such as `0.7058` is shown as `70.58`.
The AWQ rows use the default AWQ smoothing flow. They do not include AWQ weight clipping unless `--awq_apply_clip` is explicitly enabled.
@@ -656,6 +656,6 @@ In the observation tables, `AVG Win Rate` counts how often the AWQ-composed meth
## 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 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 the algorithm extension (`--algorithm auto_round_v2`).
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.md
index d4ca852cb..77a2a93ef 100644
--- a/docs/awq_details_CN.md
+++ b/docs/awq_details_CN.md
@@ -31,7 +31,7 @@ auto-round --model <model> --scheme <scheme> --format fake \
--tasks "mmlu,gsm8k,piqa,hellaswag,winogrande"
auto-round --model <model> --scheme <scheme> --format fake \
- --enable_alg_ext --algorithm auto_round \
+ --algorithm auto_round_v2 \
--tasks "mmlu,gsm8k,piqa,hellaswag,winogrande"
# AWQ + RTN / AWQ + AutoRound / AWQ + 启用算法扩展的 AutoRound
@@ -44,11 +44,11 @@ auto-round --model <model> --scheme <scheme> --format fake \
--tasks "mmlu,gsm8k,piqa,hellaswag,winogrande"
auto-round --model <model> --scheme <scheme> --format fake \
- --enable_alg_ext --algorithm awq,auto_round \
+ --algorithm awq,auto_round_v2 \
--tasks "mmlu,gsm8k,piqa,hellaswag,winogrande"
```
-表中 `AR2` 表示启用 `--enable_alg_ext` 的 AutoRound,`AWQ_AR2` 表示 AWQ 后接启用 `--enable_alg_ext` 的 AutoRound。准确率列以百分制展示,例如原始值 `0.7058` 写作 `70.58`。
+表中 `AR2` 表示启用 `--algorithm auto_round_v2`(原 `--enable_alg_ext`)的 AutoRound,`AWQ_AR2` 表示 AWQ 后接启用同一算法扩展的 AutoRound。准确率列以百分制展示,例如原始值 `0.7058` 写作 `70.58`。
AWQ 相关行使用默认 AWQ smoothing 流程。除非显式设置 `--awq_apply_clip`,否则不包含 AWQ weight clipping。
@@ -260,6 +260,6 @@ AWQ 相关行使用默认 AWQ smoothing 流程。除非显式设置 `--awq_apply
## 总结
-AWQ 更适合量化误差对 activation-aware weight smoothing 敏感的 scheme,例如 MXFP4。它可以提升 scheme 准确率,尤其是与启用 `--enable_alg_ext` 的 AutoRound 组合时。
+AWQ 更适合量化误差对 activation-aware weight smoothing 敏感的 scheme,例如 MXFP4。它可以提升 scheme 准确率,尤其是与启用算法扩展(`--algorithm auto_round_v2`)的 AutoRound 组合时。
AWQ 不会给最终量化模型增加持续性内存开销,并且与终端量化算法正交,因此可以与 RTN、AutoRound 或 AutoRound2 组合,而不改变这些算法本身的核心量化逻辑。
diff --git a/docs/neuqi_acc.md b/docs/neuqi_acc.md
index 09b8d03d9..e8223b328 100644
--- a/docs/neuqi_acc.md
+++ b/docs/neuqi_acc.md
@@ -1,6 +1,6 @@
### NeUQI Accuracy Validation
-**NeUQI** ([arXiv 2505.17595](https://arxiv.org/abs/2505.17595)) is a calibration-free grid search for the optimized-RTN path, enabled with `--enable_neuqi`: asymmetric layers run a joint (scale, integer zero-point) search, symmetric layers a two-stage signed scale search; on the zero-shot path both are weighted by the activation imatrix (collected automatically), and with `iters > 0` the anchor uses the activation imatrix when the tuning path collects one (SignRoundV2's `enable_alg_ext`), running unweighted otherwise. With `iters > 0`, the search result anchors the SignRound tuning grid (frozen init).
+**NeUQI** ([arXiv 2505.17595](https://arxiv.org/abs/2505.17595)) is a calibration-free grid search for the optimized-RTN path, enabled with `--enable_neuqi`: asymmetric layers run a joint (scale, integer zero-point) search, symmetric layers a two-stage signed scale search; on the zero-shot path both are weighted by the activation imatrix (collected automatically), and with `iters > 0` the anchor uses the activation imatrix when the tuning path collects one (the `auto_round_v2` algorithm, formerly `enable_alg_ext`), running unweighted otherwise. With `iters > 0`, the search result anchors the SignRound tuning grid (frozen init).
#### Protocol
@@ -17,7 +17,7 @@ KL divergence between the BF16 base model and the dequantized W4A16 checkpoint o
- The symmetric two-stage search **strictly dominates the incumbent search**: −4.1% mean KL, −32% wall time, and better agreement at every quantile.
- There is no incumbent asymmetric search — `--enable_neuqi` adds the optimized-init capability for asymmetric layers; the quality ladder is flat from 64/32 to 256/64, so the [backend-aware default](./environments.md) narrows the eager sweep to 64/32 at no measured cost.
-#### Results — iters > 0 (SignRoundV2 tuning, `enable_alg_ext`)
+#### Results — iters > 0 (SignRoundV2 tuning, `--algorithm auto_round_v2`)
| recipe | mean | median | p90 | p99 | top1 | top5 | wall |
|:--|--:|--:|--:|--:|--:|--:|--:|
diff --git a/test/unit/common/core/test_entry_normalization.py b/test/unit/common/core/test_entry_normalization.py
index 08a232d96..e0e981bc9 100644
--- a/test/unit/common/core/test_entry_normalization.py
+++ b/test/unit/common/core/test_entry_normalization.py
@@ -228,7 +228,8 @@ def test_combined_awq_zero_iters_keeps_awq_and_selects_rtn():
@pytest.mark.parametrize(
("algorithm", "expected_types"),
[
- ("rtn", ["OptimizedRTNConfig"]),
+ ("rtn", ["RTNConfig"]),
+ ("opt-rtn", ["OptimizedRTNConfig"]),
("awq", ["AWQConfig", "RTNConfig"]),
("signround", ["SignRoundConfig"]),
("awq,signround", ["AWQConfig", "SignRoundConfig"]),
@@ -242,6 +243,70 @@ def test_legacy_algorithm_matches_alg_configs_aliases(algorithm, expected_types)
assert _types(unified_configs) == expected_types
+ ("alias", "expected_disable_opt_rtn"),
+ [
+ ("rtn", True),
+ ("opt-rtn", False),
+ ("opt_rtn", False),
+ ("optimized_rtn", False),
+ ("optimized-rtn", False),
+ ],
+)
+def test_named_rtn_variant_forces_the_disable_opt_rtn_policy(alias, expected_disable_opt_rtn):
+ """`rtn` selects plain RTN and `opt-rtn` the optimized path, as on the CLI."""
+ configs = _normalize_alg_configs(alias)
+
+ assert len(configs) == 1
+ assert configs[0].disable_opt_rtn is expected_disable_opt_rtn
+ # Marked as user policy, so the W8A16/W8A8 heuristic and the AWQ-inherited
+ # policy cannot switch the variant back.
+ assert configs[0].orig_disable_opt_rtn is expected_disable_opt_rtn
+
+
+ ("algorithm", "direct_kwargs", "expected_disable_opt_rtn"),
+ [
+ ("rtn", {"disable_opt_rtn": False}, True),
+ ("opt-rtn", {"disable_opt_rtn": True}, False),
+ ("rtn", {"enable_opt_rtn": True}, True),
+ ],
+)
+def test_named_rtn_variant_wins_over_a_contradicting_argument(algorithm, direct_kwargs, expected_disable_opt_rtn):
+ configs = _normalize_alg_configs(algorithm, direct_kwargs=dict(direct_kwargs))
+
+ assert len(configs) == 1
+ assert configs[0].disable_opt_rtn is expected_disable_opt_rtn
+ assert configs[0].orig_disable_opt_rtn is expected_disable_opt_rtn
+
+
+def test_implicit_rtn_fallback_keeps_the_heuristic_variant():
+ """`alg_configs=None` must not be treated as naming the `rtn` variant."""
+ heuristic = _normalize_alg_configs(None, direct_kwargs={"iters": 0})
+ forced = _normalize_alg_configs(None, direct_kwargs={"iters": 0, "disable_opt_rtn": True})
+
+ # No name was given, so the value stays unmarked (orig is None) and the
+ # engine picks the variant: W4A16 int is optimized by default.
+ assert heuristic[0].orig_disable_opt_rtn is None
+ assert heuristic[0].disable_opt_rtn is False
+ assert _types(heuristic) == ["OptimizedRTNConfig"]
+
+ # The explicit flag is still honoured, exactly as before.
+ assert forced[0].orig_disable_opt_rtn is True
+ assert forced[0].disable_opt_rtn is True
+ assert _types(forced) == ["RTNConfig"]
+
+
+def test_awq_keeps_its_own_policy_next_to_a_named_rtn_variant():
+ """Only RTN configs take the name's policy; AWQ keeps its own."""
+ configs = _normalize_alg_configs("awq,opt-rtn")
+
+ assert _types(configs) == ["AWQConfig", "OptimizedRTNConfig"]
+ assert configs[0].disable_opt_rtn is True
+ assert configs[1].disable_opt_rtn is False
+ assert configs[1].orig_disable_opt_rtn is False
+
+
def test_algorithm_and_alg_configs_are_mutually_exclusive():
with pytest.raises(ValueError, match="cannot be used together"):
_normalize_alg_configs("signround", direct_kwargs={"algorithm": "rtn"})
@@ -338,3 +403,15 @@ def test_awq_kwargs_without_awq_error_and_are_ignored(monkeypatch):
assert isinstance(configs[0], SignRoundConfig)
assert not hasattr(configs[0], "n_grid")
assert any("AWQ" in message for message in errors)
+
+
[email protected]("algorithms", ["rtn,opt-rtn", "opt_rtn,rtn", ["rtn", "optimized-rtn"]])
+def test_conflicting_rtn_variants_are_rejected(algorithms):
+ with pytest.raises(ValueError, match="Cannot select both.*rtn.*opt-rtn"):
+ _normalize_alg_configs(algorithms)
+
+
+def test_duplicate_optimized_rtn_aliases_are_deduplicated():
+ configs = _normalize_alg_configs(["opt_rtn", "optimized-rtn"])
+ assert len(configs) == 1
+ assert configs[0].disable_opt_rtn is False
diff --git a/test/unit/common/core/test_pipeline_fast.py b/test/unit/common/core/test_pipeline_fast.py
index d31ef8ef1..f680f8caa 100644
--- a/test/unit/common/core/test_pipeline_fast.py
+++ b/test/unit/common/core/test_pipeline_fast.py
@@ -138,6 +138,20 @@ def test_needs_calibration_data_when_layer_config_overrides_to_nvfp4():
assert compressor._needs_calibration_data() is True
[email protected]("resolver", ["resolve_algorithm_names", "resolve_alg_config"])
+def test_unknown_algorithm_error_lists_only_canonical_names(resolver):
+ from auto_round.algorithms import registry
+
+ with pytest.raises(ValueError) as error:
+ getattr(registry, resolver)("haha")
+
+ message = str(error.value)
+ supported = sorted(entry.name for entry in registry.iter_algorithm_entries())
+ assert f"Supported algorithms: {supported}." in message
+ assert "'autoround'" not in message
+ assert "'opt_rtn'" not in message
+
+
def test_registry_builtin_aliases_and_unknown():
assert isinstance(_r.resolve_alg_config("RTN"), RTNConfig)
assert isinstance(_r.resolve_alg_config("awq"), AWQConfig)
diff --git a/test/unit/common/utils/test_cli_usage.py b/test/unit/common/utils/test_cli_usage.py
index 5ae47a08b..01af975c2 100644
--- a/test/unit/common/utils/test_cli_usage.py
+++ b/test/unit/common/utils/test_cli_usage.py
@@ -371,6 +371,18 @@ def test_model_free_cli_disable_opt_rtn(monkeypatch):
assert compressor.disable_opt_rtn is True
[email protected]("flag", ["--algorithm", "--algorithms", "--alg", "--algs", "--alg_config", "--alg_configs"])
[email protected]("algorithms", ["haha", "rtn,haha", "haha,auto_round"])
+def test_unknown_algorithm_quantization_raises(flag, algorithms):
+ from auto_round.cli.algorithms import AlgorithmHandler
+ from auto_round.cli.parser import build_quantize_parser
+
+ args = build_quantize_parser().parse_args(["--model", "/models/opt-125m", flag, algorithms])
+
+ with pytest.raises(ValueError, match="Unknown algorithm alias 'haha'"):
+ AlgorithmHandler.build_configs(args, {})
+
+
def test_unknown_algorithm_help_exits_with_suggestion(monkeypatch):
from auto_round.cli import main as cli_main
@@ -709,3 +721,315 @@ def test_parse_max_shard_size():
parser = build_quantize_parser()
assert parser.parse_args([]).max_shard_size is None
assert parser.parse_args(["--max_shard_size", "1GB"]).max_shard_size == "1GB"
+
+
+# ---------------------------------------------------------------------------
+# `auto_round_v2` and the deprecated `--enable_alg_ext`
+# ---------------------------------------------------------------------------
+
+
+def _build_cli_configs(argv, **overrides):
+ """Build algorithm configs exactly like the quantize CLI does."""
+ from auto_round.cli.algorithms import AlgorithmHandler
+ from auto_round.cli.main import _extract_common_quantization_kwargs
+ from auto_round.cli.parser import build_quantize_parser
+
+ args = build_quantize_parser().parse_args(["--model", "dummy-model"] + list(argv))
+ if getattr(args, "iters", None) is None:
+ args.iters = 200
+ for key, value in overrides.items():
+ setattr(args, key, value)
+ return AlgorithmHandler.build_configs(args, _extract_common_quantization_kwargs(args))
+
+
+def test_cli_auto_round_v2_selects_a_single_signround_v2_config():
+ from auto_round.algorithms.quantization.sign_round.config import SignRoundV2Config
+
+ configs = _build_cli_configs(["--algorithm", "auto_round_v2"])
+
+ # auto_round_v2 must not drag in the implicit `auto_round` fallback, which
+ # would chain two block quantizers back to back.
+ assert [type(config).__name__ for config in configs] == ["SignRoundV2Config"]
+ assert isinstance(configs[0], SignRoundV2Config)
+ assert configs[0].enable_alg_ext is True
+
+
[email protected]("alias", ["auto_round_v2", "auto_roundv2", "sign_round_v2", "signroundv2"])
+def test_auto_round_v2_aliases_resolve_to_the_new_algorithm(alias):
+ from auto_round.cli.algorithms import AlgorithmHandler
+
+ assert AlgorithmHandler.resolve_alias(alias) == "auto_round_v2"
+
+
+def test_cli_auto_round_v2_composes_with_awq():
+ configs = _build_cli_configs(["--algorithm", "awq,auto_round_v2"])
+
+ assert [type(config).__name__ for config in configs] == ["AWQConfig", "SignRoundV2Config"]
+
+
+def test_cli_auto_round_v2_degrades_to_rtn_without_iters():
+ configs = _build_cli_configs(["--algorithm", "auto_round_v2", "--iters", "0"])
+
+ assert [type(config).__name__ for config in configs] == ["RTNConfig"]
+
+
+def test_deprecated_enable_alg_ext_still_selects_the_v2_algorithm():
+ from auto_round.algorithms.quantization.sign_round.config import SignRoundV2Config
+ from auto_round.algorithms.registry import normalize_algorithm_config
+
+ configs = _build_cli_configs(["--enable_alg_ext"])
+
+ assert [type(config).__name__ for config in configs] == ["SignRoundConfig"]
+ assert configs[0].enable_alg_ext is True
+ # The entry point rewrites SignRoundConfig + enable_alg_ext into the v2 config,
+ # which is what keeps the deprecated switch equivalent to the new spelling.
+ assert isinstance(normalize_algorithm_config(configs[0]), SignRoundV2Config)
+
+
+def test_v2_config_keeps_the_extension_enabled_however_it_is_built():
+ from auto_round.algorithms.quantization.sign_round.config import SignRoundConfig, SignRoundV2Config
+ from auto_round.algorithms.registry import normalize_algorithm_config
+
+ # normalize_algorithm_config rewrites __class__ without calling __init__.
+ coerced = normalize_algorithm_config(SignRoundConfig(iters=1, enable_alg_ext=True))
+ assert isinstance(coerced, SignRoundV2Config)
+ assert coerced.enable_alg_ext is True
+
+ # A direct assignment must not be able to switch the extension off either:
+ # the SignRoundV2 quantizer branches on this flag.
+ direct = SignRoundV2Config(iters=1)
+ direct.enable_alg_ext = False
+ assert direct.enable_alg_ext is True
+
+
+def test_enable_alg_ext_is_advertised_as_deprecated_in_help():
+ from auto_round.cli.algorithms import AlgorithmHandler
+
+ v1_help = AlgorithmHandler.format_detail("auto_round")
+ assert "--enable_alg_ext" in v1_help
+ assert "Deprecated" in v1_help
+ assert "auto_round_v2" in v1_help
+
+ # v2 always has the extension on, so the switch must not be offered again
+ # with a help text telling the user to select `--algorithm auto_round_v2`.
+ v2_help = AlgorithmHandler.format_detail("auto_round_v2")
+ assert "--enable_alg_ext" not in v2_help
+ assert "--iters" in v2_help
+
+
+def test_list_alg_includes_auto_round_v2():
+ from auto_round.cli.algorithms import AlgorithmHandler
+
+ assert "auto_round_v2" in AlgorithmHandler.format_listing()
+
+
+# ---------------------------------------------------------------------------
+# `rtn` / `opt-rtn` plain-vs-optimized RTN
+# ---------------------------------------------------------------------------
+
+
+def test_cli_rtn_algorithm_selects_plain_rtn():
+ from auto_round.algorithms.quantization.rtn.config import OptimizedRTNConfig, RTNConfig
+ from auto_round.algorithms.registry import normalize_algorithm_config
+
+ configs = _build_cli_configs(["--alg", "rtn"])
+
+ assert [type(config).__name__ for config in configs] == ["RTNConfig"]
+ assert configs[0].disable_opt_rtn is True
+ # An explicitly forced plain RTN must not be re-normalized into the optimized one.
+ assert type(normalize_algorithm_config(configs[0])) is RTNConfig
+ assert not isinstance(configs[0], OptimizedRTNConfig)
+
+
[email protected]("alias", ["opt-rtn", "opt_rtn", "optimized_rtn", "optimized-rtn"])
+def test_cli_opt_rtn_algorithm_selects_the_optimized_path(alias):
+ from auto_round.algorithms.quantization.rtn.config import OptimizedRTNConfig
+ from auto_round.algorithms.registry import normalize_algorithm_config
+
+ configs = _build_cli_configs(["--alg", alias])
+
+ # Exactly one block quantizer: opt-rtn must not append the implicit fallback.
+ assert [type(config).__name__ for config in configs] == ["OptimizedRTNConfig"]
+ assert isinstance(configs[0], OptimizedRTNConfig)
+ assert configs[0].disable_opt_rtn is False
+ assert configs[0].orig_disable_opt_rtn is False
+ assert isinstance(normalize_algorithm_config(configs[0]), OptimizedRTNConfig)
+
+
+ ("argv", "expected_disable_opt_rtn"),
+ [
+ (["--alg", "rtn", "--enable_opt_rtn"], True),
+ (["--alg", "opt-rtn", "--disable_opt_rtn"], False),
+ ],
+)
+def test_rtn_algorithm_name_wins_over_a_contradicting_flag(argv, expected_disable_opt_rtn):
+ configs = _build_cli_configs(argv)
+
+ assert len(configs) == 1
+ assert configs[0].disable_opt_rtn is expected_disable_opt_rtn
+ # `orig_disable_opt_rtn` marks the value as user policy, which is what stops
+ # the W8A16/W8A8 efficiency heuristic and the AWQ policy from overriding it.
+ assert configs[0].orig_disable_opt_rtn is expected_disable_opt_rtn
+
+
+def test_cli_opt_rtn_composes_with_awq_without_extra_configs():
+ from auto_round.algorithms.quantization.rtn.config import OptimizedRTNConfig
+
+ configs = _build_cli_configs(["--alg", "awq,opt-rtn"])
+
+ assert [type(config).__name__ for config in configs] == ["AWQConfig", "OptimizedRTNConfig"]
+ assert isinstance(configs[1], OptimizedRTNConfig)
+ assert configs[1].disable_opt_rtn is False
+
+
+ ("overrides", "expected_type"),
+ [
+ ({}, "RTNConfig"),
+ ({"disable_opt_rtn": True}, "RTNConfig"),
+ ({"disable_opt_rtn": False}, "RTNConfig"),
+ ],
+)
+def test_implicit_rtn_path_keeps_flag_and_heuristic_behaviour(overrides, expected_type):
+ """Without an explicit `--algorithm`, RTN must not be forced to plain.
+
+ This is what keeps `auto-round-rtn` / `auto-round-opt-rtn` and the plain
+ `--iters 0` path behaving exactly as before.
+ """
+ from auto_round.algorithms.registry import normalize_algorithm_config
+
+ configs = _build_cli_configs(["--iters", "0"], **overrides)
+
+ assert [type(config).__name__ for config in configs] == [expected_type]
+ if overrides:
+ # An explicit flag is user policy, exactly as before.
+ assert configs[0].disable_opt_rtn is overrides["disable_opt_rtn"]
+ assert configs[0].orig_disable_opt_rtn is overrides["disable_opt_rtn"]
+ else:
+ # No flag: `orig` stays None so the engine keeps owning the decision
+ # (heuristic default for a W4A16 int scheme is the optimized path).
+ assert configs[0].disable_opt_rtn is False
+ assert configs[0].orig_disable_opt_rtn is None
+ assert type(normalize_algorithm_config(configs[0])).__name__ == (
+ "OptimizedRTNConfig" if configs[0].disable_opt_rtn is False else "RTNConfig"
+ )
+
+
+def test_list_alg_includes_opt_rtn():
+ from auto_round.cli.algorithms import AlgorithmHandler
+
+ listing = AlgorithmHandler.format_listing()
+
+ assert "- rtn" in listing
+ assert "opt-rtn" in listing
+
+
+def test_opt_rtn_help_lists_the_rtn_switches():
+ from auto_round.cli.algorithms import AlgorithmHandler
+
+ help_text = AlgorithmHandler.format_detail("opt-rtn")
+
+ assert "--disable_opt_rtn" in help_text
+ assert "--enable_opt_rtn" in help_text
+
+
+# ---------------------------------------------------------------------------
+# `auto_round --help`
+# ---------------------------------------------------------------------------
+
+
+def test_bare_help_prints_the_concise_overview(capsys, monkeypatch):
+ from auto_round.cli import main as cli_main
+
+ monkeypatch.setattr(sys, "argv", ["auto_round", "--help"])
+ cli_main.run()
+ overview = capsys.readouterr().out
+
+ assert "common arguments" in overview
+ assert "auto_round quantize --help" in overview
+ assert "--algorithm auto_round_v2" in overview
+ # A curated subset, not the full quantize argument list.
+ assert len(overview.splitlines()) < 100
+ for noisy_flag in ("--svdquant-rank", "--kl_top_k", "--static_kv_dtype", "--target_bits"):
+ assert noisy_flag not in overview
+
+
[email protected]("argv", [["auto_round", "quantize", "--help"], ["auto_round", "help", "quantize"]])
+def test_explicit_quantize_help_still_prints_every_argument(capsys, monkeypatch, argv):
+ from auto_round.cli import main as cli_main
+
+ monkeypatch.setattr(sys, "argv", argv)
+ try:
+ cli_main.run()
+ except SystemExit as exc: # `quantize --help` exits through argparse with code 0
+ assert exc.code in (0, None)
+ help_text = capsys.readouterr().out
+
+ assert "auto_round quantize" in help_text
+ for flag in ("--svdquant-rank", "--kl_top_k", "--static_kv_dtype", "--enable_alg_ext"):
+ assert flag in help_text
+ assert "auto_round_v2" in help_text
+
+
+def test_algorithm_help_is_still_reported_for_the_new_algorithm(capsys, monkeypatch):
+ from auto_round.cli import main as cli_main
+
+ monkeypatch.setattr(sys, "argv", ["auto_round", "--algorithm", "auto_round_v2", "--help"])
+ cli_main.run()
+ help_text = capsys.readouterr().out
+
+ assert "algorithm(s): auto_round_v2" in help_text
+ assert "--iters" in help_text
+
+
+def test_overview_entries_all_resolve_to_documented_quantize_flags():
+ from auto_round.cli.main import _OVERVIEW_ARGUMENTS, _overview_parser
+
+ parser = _overview_parser()
+ rendered = {action.dest for action in parser._actions}
+ missing = [dest for dest, _ in _OVERVIEW_ARGUMENTS if dest not in rendered]
+
+ assert not missing, f"overview entries missing from the quantize parser: {missing}"
+ for action in parser._actions:
+ assert action.help not in (None, argparse.SUPPRESS), f"{action.dest} has no help text"
+
+
+def test_every_quantize_flag_has_help_text():
+ from auto_round.cli.parser import build_quantize_parser
+
+ undocumented = [action.option_strings for action in build_quantize_parser()._actions if not action.help]
+
+ assert undocumented == []
+
+
+def test_quantize_help_has_no_empty_algorithm_group():
+ import contextlib
+ import io
+
+ from auto_round.cli.parser import build_quantize_parser
+
+ help_text = io.StringIO()
+ with contextlib.redirect_stdout(help_text):
+ build_quantize_parser().print_help()
+ help_text = help_text.getvalue()
+
+ # `auto_round_v2` reuses the SignRound switches, so it must not add a bare header.
+ assert "Algorithm: auto_round:" in help_text
+ assert "Algorithm: auto_round_v2:" not in help_text
+
+
[email protected]("algorithms", ["rtn,opt-rtn", "opt_rtn,rtn", "rtn,optimized-rtn"])
+def test_cli_conflicting_rtn_variants_are_rejected(algorithms):
+ from auto_round.cli.algorithms import AlgorithmHandler
+
+ with pytest.raises(ValueError, match="Cannot select both.*rtn.*opt-rtn"):
+ AlgorithmHandler.build_configs(argparse.Namespace(algorithm=algorithms, iters=200), {})
+
+
+def test_overview_displays_primary_model_flag():
+ from auto_round.cli.main import _overview_parser
+
+ options = {option for action in _overview_parser()._actions for option in action.option_strings}
+ assert "--model" in options
+ assert "--model_name" not in options
diff --git a/test/unit/test_cpu/core/test_entry_contract.py b/test/unit/test_cpu/core/test_entry_contract.py
index 3e8a4e114..c508db5ea 100644
--- a/test/unit/test_cpu/core/test_entry_contract.py
+++ b/test/unit/test_cpu/core/test_entry_contract.py
@@ -108,7 +108,12 @@ def test_cli_awq_rtn_opt_policy():
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]),
+ (
+ Namespace(algorithm="awq", iters=200, disable_opt_rtn=False),
+ ["AWQConfig", "RTNConfig"],
+ [False, False],
+ ),
+ (Namespace(algorithm="awq,rtn", iters=200, disable_opt_rtn=False), ["AWQConfig", "RTNConfig"], [False, True]),
]
for args, expected_types, expected_disable_opt_rtn in cases:
@@ -118,7 +123,7 @@ def test_cli_awq_rtn_opt_policy():
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):
+def test_cli_named_rtn_selects_plain_path_without_mutating_args(monkeypatch):
from argparse import Namespace
from auto_round.algorithms.registry import get_algorithm_entry
@@ -131,6 +136,6 @@ def test_cli_rtn_inherits_built_awq_config_without_mutating_args(monkeypatch):
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[0].disable_opt_rtn is True
assert configs[1].disable_opt_rtn is False
assert args.disable_opt_rtn is None