Skip to content

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

refactor algorithm cli (#2140)

Heng Guo1fd913d9c102
diff --git a/README.md b/README.md
index 123abd1fc..1f75c07c9 100644
--- a/README.md
+++ b/README.md
@@ -248,6 +248,7 @@ ar.quantize_and_save(output_dir="./qmodel", format="auto_round")
##### 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)`.
- **`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.
diff --git a/README_CN.md b/README_CN.md
index c18fd88a6..73494030c 100644
--- a/README_CN.md
+++ b/README_CN.md
@@ -240,6 +240,7 @@ 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`)
diff --git a/auto_round/algorithms/composer.py b/auto_round/algorithms/composer.py
index b4e75f808..2267d94b4 100644
--- a/auto_round/algorithms/composer.py
+++ b/auto_round/algorithms/composer.py
@@ -88,9 +88,10 @@ class AlgorithmComposer:
"""An ordered composition of pre-processors + one block quantizer, built from
a list of algorithm config objects and an optional compressor.
- The ``preprocessors`` list is order-sensitive: algorithms are applied in
- the listed order (e.g. ``[Rotation, AWQ]``). There must be **exactly one**
- ``block_quantizer`` (the terminal weight-compression step).
+ The ``preprocessors`` list is order-sensitive: preprocessors are applied in
+ the listed order (e.g. ``[Rotation, AWQ]``). The block quantizer is always
+ the terminal weight-compression step, regardless of its position in the
+ input config list. There must be **exactly one** ``block_quantizer``.
Usage::
@@ -527,7 +528,12 @@ class AlgorithmComposer:
# ── Convenience act-calib helpers ────────────────────────────────────────
def members(self) -> list:
- """Return all algorithm members: preprocessors followed by the block quantizer."""
+ """Return the canonical execution order: preprocessors, then block quantizer.
+
+ Preprocessor order follows the input config list. The block quantizer
+ is always returned last, so its position in that input list has no
+ effect on pipeline execution.
+ """
return list(self.preprocessors) + [self.block_quantizer]
def dispatch_block(self, block: "torch.nn.Module", input_ids, input_others: dict):
diff --git a/auto_round/algorithms/config.py b/auto_round/algorithms/config.py
new file mode 100644
index 000000000..3202a79a5
--- /dev/null
+++ b/auto_round/algorithms/config.py
@@ -0,0 +1,100 @@
+# Copyright (c) 2026 Intel Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Algorithm configuration metadata used by generic front ends."""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from dataclasses import field as dataclass_field
+from typing import Any, ClassVar
+
+
+@dataclass(frozen=True)
+class AlgorithmParameter:
+ option_strings: tuple[str, ...]
+ field: str
+ argparse_kwargs: dict[str, Any]
+ mutex_group: int | None = None
+
+ @property
+ def dest(self) -> str:
+ return self.argparse_kwargs.get("dest", self.option_strings[0].lstrip("-").replace("-", "_"))
+
+
+class _MutuallyExclusiveParameterRegistry:
+ def __init__(self, registry: "AlgorithmParameterRegistry", group_id: int) -> None:
+ self._registry = registry
+ self._group_id = group_id
+
+ def add_argument(self, *option_strings: str, field: str, **kwargs) -> None:
+ self._registry._add_argument(*option_strings, field=field, mutex_group=self._group_id, **kwargs)
+
+
+class AlgorithmParameterRegistry:
+ """Collect algorithm parameter declarations without exposing argparse to configs."""
+
+ def __init__(self) -> None:
+ self.parameters: list[AlgorithmParameter] = []
+ self._fields: set[str] = set()
+ self._next_mutex_group = 0
+
+ def add_argument(self, *option_strings: str, field: str, **kwargs) -> None:
+ self._add_argument(*option_strings, field=field, mutex_group=None, **kwargs)
+
+ def _add_argument(self, *option_strings: str, field: str, mutex_group: int | None, **kwargs) -> None:
+ if not option_strings or any(not option.startswith("-") for option in option_strings):
+ raise ValueError("Algorithm arguments must define one or more option strings.")
+ if not field or not field.isidentifier():
+ raise ValueError(f"Invalid config field {field!r}.")
+ duplicate = next((parameter for parameter in self.parameters if parameter.field == field), None)
+ if duplicate is not None and not (
+ mutex_group is not None
+ and duplicate.mutex_group == mutex_group
+ and duplicate.dest == kwargs.get("dest", option_strings[0].lstrip("-").replace("-", "_"))
+ ):
+ raise ValueError(f"Config field {field!r} is already registered.")
+ self._fields.add(field)
+ self.parameters.append(AlgorithmParameter(tuple(option_strings), field, dict(kwargs), mutex_group))
+
+ def add_mutually_exclusive_group(self) -> _MutuallyExclusiveParameterRegistry:
+ group_id = self._next_mutex_group
+ self._next_mutex_group += 1
+ return _MutuallyExclusiveParameterRegistry(self, group_id)
+
+ def config_kwargs(self, args) -> dict[str, Any]:
+ values = {}
+ for parameter in self.parameters:
+ if not hasattr(args, parameter.dest):
+ continue
+ value = getattr(args, parameter.dest)
+ fallback = parameter.argparse_kwargs.get("fallback")
+ values[parameter.field] = fallback if value is None and fallback is not None else value
+ return values
+
+
+class AlgorithmConfig:
+ """Base mixin for config-owned command-line parameter declarations."""
+
+ cli_include_common_args: ClassVar[bool] = True
+
+ @classmethod
+ def register_args(cls, registry: AlgorithmParameterRegistry) -> None:
+ """Register algorithm-specific parameters. The default declares none."""
+
+ @classmethod
+ def get_registered_args(cls) -> AlgorithmParameterRegistry:
+ registry = AlgorithmParameterRegistry()
+ cls.register_args(registry)
+ return registry
diff --git a/auto_round/algorithms/quantization/config.py b/auto_round/algorithms/quantization/config.py
index 055525c9b..a570ec769 100644
--- a/auto_round/algorithms/quantization/config.py
+++ b/auto_round/algorithms/quantization/config.py
@@ -13,12 +13,13 @@
# limitations under the License.
from typing import ClassVar
+from auto_round.algorithms.config import AlgorithmConfig
from auto_round.export.export_to_gguf.config import GGUF_INNER_CONFIG
from auto_round.logger import logger
from auto_round.schemes import QuantizationScheme
-class QuantizationConfig:
+class QuantizationConfig(AlgorithmConfig):
"""Common quantization configuration shared by block quantizers.
Args:
diff --git a/auto_round/algorithms/quantization/rtn/config.py b/auto_round/algorithms/quantization/rtn/config.py
index 103eb30fa..b7b90ef39 100644
--- a/auto_round/algorithms/quantization/rtn/config.py
+++ b/auto_round/algorithms/quantization/rtn/config.py
@@ -12,17 +12,41 @@
# See the License for the specific language governing permissions and
# limitations under the License.
+from auto_round.algorithms.config import AlgorithmParameterRegistry
from auto_round.algorithms.quantization.config import QuantizationConfig
+from auto_round.algorithms.registry import register_algorithm
from auto_round.logger import logger
class RTNConfig(QuantizationConfig):
need_calib = False
+ @classmethod
+ def register_args(cls, registry: AlgorithmParameterRegistry) -> None:
+ mutex = registry.add_mutually_exclusive_group()
+ mutex.add_argument(
+ "--disable_opt_rtn",
+ field="disable_opt_rtn",
+ default=None,
+ dest="disable_opt_rtn",
+ action="store_const",
+ const=True,
+ help="Force plain RTN (disable optimized path).",
+ )
+ mutex.add_argument(
+ "--enable_opt_rtn",
+ field="disable_opt_rtn",
+ dest="disable_opt_rtn",
+ action="store_const",
+ const=False,
+ help="Force optimized RTN path.",
+ )
+
def __init__(
self,
*,
disable_opt_rtn: bool = None,
+ enable_opt_rtn: bool = None,
**kwargs,
) -> None:
"""Initialize an RTN configuration.
@@ -31,12 +55,11 @@ class RTNConfig(QuantizationConfig):
disable_opt_rtn: Whether to disable the optimized RTN path.
``None`` keeps the default heuristic, True forces plain
RTN, and False forces the optimized implementation.
+ enable_opt_rtn: Convenience alias for ``disable_opt_rtn=False``.
**kwargs: Common quantization arguments forwarded to
QuantizationConfig, such as bits, group_size, sym,
data_type, and activation quantization fields.
"""
- # pop before super().__init__ so it doesn't leak into QuantizationConfig as an unknown kwarg
- enable_opt_rtn = kwargs.pop("enable_opt_rtn", None)
super().__init__(**kwargs)
if enable_opt_rtn:
@@ -57,3 +80,11 @@ class RTNConfig(QuantizationConfig):
class OptimizedRTNConfig(RTNConfig):
need_calib = True
+
+
+register_algorithm(
+ "rtn",
+ aliases=("rtn",),
+ config_factory=RTNConfig,
+ summary="Round-To-Nearest quantization.",
+)
diff --git a/auto_round/algorithms/quantization/sign_round/config.py b/auto_round/algorithms/quantization/sign_round/config.py
index ba293857f..03de8728e 100644
--- a/auto_round/algorithms/quantization/sign_round/config.py
+++ b/auto_round/algorithms/quantization/sign_round/config.py
@@ -13,13 +13,114 @@
# limitations under the License.
from typing import Callable
+from auto_round.algorithms.config import AlgorithmParameterRegistry
from auto_round.algorithms.quantization.config import QuantizationConfig
+from auto_round.algorithms.registry import register_algorithm
from auto_round.logger import logger
class SignRoundConfig(QuantizationConfig):
"""Configuration for SignRound-style block quantization."""
+ @classmethod
+ def register_args(cls, registry: AlgorithmParameterRegistry) -> None:
+ registry.add_argument(
+ "--iters",
+ "--iter",
+ field="iters",
+ default=None,
+ type=int,
+ help="Number of optimization iterations per block.",
+ )
+ registry.add_argument(
+ "--lr", field="lr", default=None, type=float, help="Learning rate for rounding optimization."
+ )
+ registry.add_argument(
+ "--minmax_lr", field="minmax_lr", default=None, type=float, help="Learning rate for min-max tuning."
+ )
+ registry.add_argument(
+ "--momentum", field="momentum", default=0.0, type=float, help="Momentum factor for the optimizer."
+ )
+ registry.add_argument(
+ "--nblocks", field="nblocks", default=1, type=int, help="Number of blocks to optimize together."
+ )
+ minmax = registry.add_mutually_exclusive_group()
+ minmax.add_argument(
+ "--enable_minmax_tuning",
+ field="enable_minmax_tuning",
+ default=True,
+ dest="enable_minmax_tuning",
+ action="store_true",
+ help="Tune weight min/max ranges.",
+ )
+ minmax.add_argument(
+ "--no-enable_minmax_tuning",
+ "--disable_minmax_tuning",
+ field="enable_minmax_tuning",
+ dest="enable_minmax_tuning",
+ action="store_false",
+ help="Disable weight min/max tuning.",
+ )
+ registry.add_argument(
+ "--enable_norm_bias_tuning",
+ field="enable_norm_bias_tuning",
+ default=False,
+ action="boolean_optional",
+ help="Tune normalization and bias terms.",
+ )
+ registry.add_argument(
+ "--gradient_accumulate_steps",
+ field="gradient_accumulate_steps",
+ default=1,
+ type=int,
+ help="Gradient accumulation steps per update.",
+ )
+ registry.add_argument(
+ "--enable_alg_ext",
+ field="enable_alg_ext",
+ default=False,
+ action="boolean_optional",
+ help="Enable experimental SignRound extension.",
+ )
+ registry.add_argument(
+ "--not_use_best_mse",
+ field="not_use_best_mse",
+ default=False,
+ action="boolean_optional",
+ help="Skip restoring best-MSE checkpoint.",
+ )
+ quanted_input = registry.add_mutually_exclusive_group()
+ quanted_input.add_argument(
+ "--enable_quanted_input",
+ field="enable_quanted_input",
+ default=True,
+ dest="enable_quanted_input",
+ action="store_true",
+ help="Consume quantized output of previous blocks.",
+ )
+ quanted_input.add_argument(
+ "--no-enable_quanted_input",
+ "--disable_quanted_input",
+ field="enable_quanted_input",
+ dest="enable_quanted_input",
+ action="store_false",
+ help="Disable quantized-input propagation across blocks.",
+ )
+ registry.add_argument(
+ "--enable_adam",
+ field="enable_adam",
+ default=False,
+ action="boolean_optional",
+ help="Use the Adam-based SignRound variant.",
+ )
+ registry.add_argument(
+ "--enable_lfq",
+ field="enable_lfq",
+ default=False,
+ action="boolean_optional",
+ help="Enable last-block LM cross-entropy (LFQ) loss for the final transformer block (experimental).",
+ )
+
def __init__(
self,
*,
@@ -176,3 +277,11 @@ class AdamRoundConfig(SignRoundConfig):
class SignRoundV2Config(SignRoundConfig):
pass
+
+
+register_algorithm(
+ "auto_round",
+ aliases=("auto_round", "autoround", "sign_round", "signround"),
+ config_factory=SignRoundConfig,
+ summary="SignRound-style iterative block quantization.",
+)
diff --git a/auto_round/algorithms/registry.py b/auto_round/algorithms/registry.py
index 87b7e58e5..3dfffca67 100644
--- a/auto_round/algorithms/registry.py
+++ b/auto_round/algorithms/registry.py
@@ -17,7 +17,6 @@ class AlgRegistryEntry:
name: str
aliases: tuple[str, ...] = ()
config_factory: Callable[[], object] | None = None
- cli_handler: type | None = None
summary: str = ""
alias_factories: dict[str, Callable[[], object]] = field(default_factory=dict)
@@ -27,13 +26,25 @@ _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:
global _builtin_algorithms_registered
if _builtin_algorithms_registered:
return
- importlib.import_module("auto_round.cli.algorithms")
+ # Importing each config module triggers its own registration. Keeping the
+ # imports ordered preserves the help output and default algorithm order.
+ for module_name in (
+ "auto_round.algorithms.quantization.rtn.config",
+ "auto_round.algorithms.quantization.sign_round.config",
+ "auto_round.algorithms.transforms.awq.config",
+ "auto_round.algorithms.transforms.svdquant.config",
+ "auto_round.algorithms.transforms.hadamard.config",
+ "auto_round.algorithms.transforms.spinquant.preprocessor",
+ ):
+ importlib.import_module(module_name)
+
_builtin_algorithms_registered = True
@@ -58,7 +69,6 @@ def register_algorithm(
*,
aliases: tuple[str, ...] = (),
config_factory: Callable[[], object] | None = None,
- cli_handler: type | None = None,
summary: str = "",
alias_factories: dict[str, Callable[[], object]] | None = None,
) -> None:
@@ -73,8 +83,6 @@ def register_algorithm(
)
if config_factory is not None:
entry.config_factory = config_factory
- if cli_handler is not None:
- entry.cli_handler = cli_handler
if summary:
entry.summary = summary
if alias_factories:
@@ -136,7 +144,9 @@ def get_algorithm_entry(name: str) -> AlgRegistryEntry:
def iter_algorithm_entries() -> list[AlgRegistryEntry]:
_ensure_builtin_algorithms_registered()
- return list(_ALG_REGISTRY.values())
+ 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
def resolve_alg_config(alias: str) -> object:
diff --git a/auto_round/algorithms/transforms/awq/config.py b/auto_round/algorithms/transforms/awq/config.py
index dae4743c8..affc1bad0 100644
--- a/auto_round/algorithms/transforms/awq/config.py
+++ b/auto_round/algorithms/transforms/awq/config.py
@@ -12,7 +12,9 @@
# See the License for the specific language governing permissions and
# limitations under the License.
+from auto_round.algorithms.config import AlgorithmParameterRegistry
from auto_round.algorithms.quantization.config import QuantizationConfig
+from auto_round.algorithms.registry import register_algorithm
from auto_round.logger import logger
@@ -78,6 +80,73 @@ class AWQConfig(QuantizationConfig):
step come from the pipeline's ``block_quantizer`` config.
"""
+ @staticmethod
+ def _parse_duo_scaling(value: str) -> bool | str:
+ lowered = value.strip().lower()
+ if lowered == "true":
+ return True
+ if lowered == "false":
+ return False
+ if lowered == "both":
+ return "both"
+ raise ValueError("Expected one of: true, false, both")
+
+ @classmethod
+ def register_args(cls, registry: AlgorithmParameterRegistry) -> None:
+ registry.add_argument(
+ "--awq_duo_scaling",
+ "--awq-duo-scaling",
+ field="duo_scaling",
+ dest="duo_scaling",
+ default=True,
+ type=cls._parse_duo_scaling,
+ metavar="{true,false,both}",
+ help="Use activation+weight duo scaling (true/false/both).",
+ )
+ registry.add_argument(
+ "--awq_n_grid",
+ "--awq-n-grid",
+ field="n_grid",
+ dest="n_grid",
+ default=20,
+ type=int,
+ help="Number of grid-search points for AWQ scaling ratio.",
+ )
+ registry.add_argument(
+ "--awq_seqlen",
+ field="awq_seqlen",
+ default=None,
+ type=int,
+ help="Maximum sequence length used by AWQ calibration, distinct from global --seqlen.",
+ )
+ registry.add_argument(
+ "--awq_smooth_batch_size",
+ field="smooth_batch_size",
+ dest="awq_smooth_batch_size",
+ default=None,
+ type=int,
+ help="Microbatch size for AWQ parent replay during scale search; <=0 disables microbatching.",
+ )
+ registry.add_argument(
+ "--awq_apply_clip",
+ "--awq-apply-clip",
+ field="apply_clip",
+ dest="awq_apply_clip",
+ action="store_true",
+ help="Search and hard-clamp per-group AWQ weight clipping after smoothing.",
+ )
+ registry.add_argument(
+ "--awq_clip_as_init",
+ "--awq-clip-as-init",
+ field="clip_as_init",
+ dest="awq_clip_as_init",
+ action="store_true",
+ help=(
+ "Use the searched AWQ clip to initialize the block quantizer's weight range "
+ "instead of hard-clamping (requires --awq-apply-clip)."
+ ),
+ )
+
def __init__(
self,
*,
@@ -261,3 +330,11 @@ class AWQConfig(QuantizationConfig):
f"bits={self.bits}, group_size={self.group_size}, sym={self.sym}, "
f"mappings={'<explicit>' if self.mappings else 'auto'})"
)
+
+
+register_algorithm(
+ "awq",
+ aliases=("awq",),
+ config_factory=AWQConfig,
+ summary="Activation-Aware Weight Quantization (pre-processing).",
+)
diff --git a/auto_round/algorithms/transforms/hadamard/config.py b/auto_round/algorithms/transforms/hadamard/config.py
index 4947f1ff4..ed72ad1c4 100644
--- a/auto_round/algorithms/transforms/hadamard/config.py
+++ b/auto_round/algorithms/transforms/hadamard/config.py
@@ -34,10 +34,12 @@ Two implementation backends share this one schema (method B):
from __future__ import annotations
-from typing import Any, Optional
+from typing import Any, ClassVar, Optional
from pydantic import BaseModel, Field, field_validator
+from auto_round.algorithms.config import AlgorithmConfig, AlgorithmParameterRegistry
+from auto_round.algorithms.registry import register_algorithm
from auto_round.algorithms.transforms.base import BaseRotationConfig
from auto_round.compressors.utils import is_mx_fp, is_nv_fp
from auto_round.utils import logger
@@ -56,7 +58,7 @@ HADAMARD_TYPES: frozenset[str] = frozenset(
_SUPPORTED_BACKENDS: frozenset[str] = frozenset({"auto", "inplace", "transform"})
-class RotationConfig(BaseModel, BaseRotationConfig):
+class RotationConfig(AlgorithmConfig, BaseModel, BaseRotationConfig):
"""Unified configuration for Hadamard rotation/transform applied to a model.
See the module docstring for a description of the three backends.
@@ -83,6 +85,51 @@ class RotationConfig(BaseModel, BaseRotationConfig):
# for random hadamard (transform path)
random_seed: bool = Field(default=False, exclude=True)
+ cli_include_common_args: ClassVar[bool] = False
+
+ @classmethod
+ def register_args(cls, registry: AlgorithmParameterRegistry) -> None:
+ registry.add_argument(
+ "--rotation_type",
+ "--rotation-hadamard-type",
+ field="hadamard_type",
+ dest="rotation_hadamard_type",
+ default=None,
+ fallback="hadamard",
+ choices=["hadamard", "random_hadamard", "quarot_hadamard"],
+ help="Hadamard transform variant.",
+ )
+ registry.add_argument(
+ "--rotation_backend",
+ field="backend",
+ dest="rotation_backend",
+ default="auto",
+ choices=["auto", "inplace", "transform"],
+ help="Rotation backend to use.",
+ )
+ registry.add_argument(
+ "--rotation_block_size",
+ field="block_size",
+ dest="rotation_block_size",
+ default=None,
+ type=int,
+ help="Grouped Hadamard block size.",
+ )
+ registry.add_argument(
+ "--fuse_online_to_weight",
+ field="fuse_online_to_weight",
+ default=None,
+ action="boolean_optional",
+ help="Fuse online Hadamard rotation into weights.",
+ )
+ registry.add_argument(
+ "--allow_online_rotation",
+ field="allow_online_rotation",
+ default=True,
+ action="boolean_optional",
+ help="Allow online activation rotation.",
+ )
+
model_config = {"arbitrary_types_allowed": True}
def __init__(self, **data: Any) -> None:
@@ -211,3 +258,15 @@ def normalize_rotation_config(
return RotationConfig.model_validate(cfg_dict).model_dump()
except Exception as exc:
raise ValueError(f"Invalid RotationConfig: {exc}") from exc
+
+
+register_algorithm(
+ "hadamard",
+ aliases=("hadamard", "random_hadamard", "quarot_hadamard"),
+ config_factory=RotationConfig,
+ summary="Hadamard rotation/transform applied before quantization.",
+ alias_factories={
+ "random_hadamard": lambda: RotationConfig(hadamard_type="random_hadamard"),
+ "quarot_hadamard": lambda: RotationConfig(hadamard_type="quarot_hadamard"),
+ },
+)
diff --git a/auto_round/algorithms/transforms/spinquant/preprocessor.py b/auto_round/algorithms/transforms/spinquant/preprocessor.py
index b67b84073..f13df42be 100644
--- a/auto_round/algorithms/transforms/spinquant/preprocessor.py
+++ b/auto_round/algorithms/transforms/spinquant/preprocessor.py
@@ -28,6 +28,7 @@ from typing import Any, Optional
import torch
import torch.nn as nn
+from auto_round.algorithms.registry import register_algorithm
from auto_round.algorithms.transforms.base import BaseRotationConfig
# ---------------------------------------------------------------------------
@@ -144,6 +145,20 @@ class SpinQuantConfig(BaseRotationConfig):
)
+register_algorithm(
+ "quarot",
+ aliases=("quarot",),
+ config_factory=lambda: SpinQuantConfig(trainable_rotation=False, trainable_smooth=False),
+ summary="QuaRot fixed-Hadamard rotation (no training, no calibration data).",
+)
+register_algorithm(
+ "spinquant",
+ aliases=("spinquant",),
+ config_factory=lambda: SpinQuantConfig(trainable_rotation=True, trainable_smooth=True),
+ summary="SpinQuant trainable rotation (experimental).",
+)
+
+
class TrainableRMSNorm(nn.Module):
"""
RMSNorm wrapper with trainable ``smooth_values`` for joint
diff --git a/auto_round/algorithms/transforms/svdquant/config.py b/auto_round/algorithms/transforms/svdquant/config.py
index cb929cc08..6f67cd1ad 100644
--- a/auto_round/algorithms/transforms/svdquant/config.py
+++ b/auto_round/algorithms/transforms/svdquant/config.py
@@ -14,7 +14,9 @@
from __future__ import annotations
+from auto_round.algorithms.config import AlgorithmParameterRegistry
from auto_round.algorithms.quantization.config import QuantizationConfig
+from auto_round.algorithms.registry import register_algorithm
class SVDQuantConfig(QuantizationConfig):
@@ -35,6 +37,75 @@ class SVDQuantConfig(QuantizationConfig):
**kwargs: Shared :class:`QuantizationConfig` options.
"""
+ @classmethod
+ def register_args(cls, registry: AlgorithmParameterRegistry) -> None:
+ registry.add_argument("--svdquant-rank", field="rank", default=32, type=int, help="SVDQuant low-rank size.")
+ registry.add_argument(
+ "--enable-svdquant-smooth",
+ field="smooth_enabled",
+ dest="svdquant_smooth_enabled",
+ default=False,
+ action="store_true",
+ help="Enable SVDQuant activation-aware smoothing.",
+ )
+ registry.add_argument(
+ "--svdquant-smooth-num-grids",
+ field="smooth_num_grids",
+ default=20,
+ type=int,
+ help="Number of candidates per SVDQuant smooth search grid family.",
+ )
+ registry.add_argument(
+ "--svdquant-smooth-max-calibration-calls",
+ field="smooth_max_calibration_calls",
+ default=128,
+ type=int,
+ help="Maximum calibration calls retained per SVDQuant smooth group.",
+ )
+ registry.add_argument(
+ "--svdquant-residual-iters",
+ field="residual_iters",
+ default=1,
+ type=int,
+ help="Number of alternating low-rank and residual quantization iterations.",
+ )
+ registry.add_argument(
+ "--enable-svdquant-residual-early-stop",
+ field="residual_early_stop",
+ dest="svdquant_residual_early_stop",
+ default=False,
+ action="store_true",
+ help="Stop residual iteration when reconstruction error no longer improves.",
+ )
+ registry.add_argument(
+ "--svdquant-low-rank-dtype",
+ field="low_rank_dtype",
+ default="bf16",
+ choices=["bf16", "bfloat16", "fp16", "float16", "fp32", "float32"],
+ help="Data type for the SVDQuant low-rank branch.",
+ )
+ registry.add_argument(
+ "--svdquant-target-modules",
+ field="target_modules",
+ default=None,
+ type=str,
+ help="Comma-separated module-name substrings to transform.",
+ )
+ registry.add_argument(
+ "--svdquant-exclude-modules",
+ field="exclude_modules",
+ default=None,
+ type=str,
+ help="Comma-separated module-name substrings to exclude.",
+ )
+ registry.add_argument(
+ "--svdquant-model-adapter",
+ field="model_adapter",
+ default="auto",
+ choices=["auto", "identity", "flux"],
+ help="Architecture adapter used by SVDQuant export.",
+ )
+
def __init__(
self,
*,
@@ -113,3 +184,11 @@ def _normalize_patterns(value):
if isinstance(value, str):
return [item.strip() for item in value.split(",") if item.strip()]
return list(value)
+
+
+register_algorithm(
+ "svdquant",
+ aliases=("svdquant",),
+ config_factory=SVDQuantConfig,
+ summary="SVD low-rank decomposition before residual quantization.",
+)
diff --git a/auto_round/autoround.py b/auto_round/autoround.py
index 951e3e20d..c2464d9a4 100644
--- a/auto_round/autoround.py
+++ b/auto_round/autoround.py
@@ -14,6 +14,8 @@
from __future__ import annotations
+import functools
+import inspect
from typing import TYPE_CHECKING, Any, Optional, Union
import torch
@@ -348,51 +350,50 @@ _ENTRY_KWARG_OWNERS = {
}
_SCHEME_FIELDS = set(QuantizationScheme.get_attributes())
-_SIGNROUND_FIELDS = {
- "iters",
- "lr",
- "minmax_lr",
- "lr_scheduler",
- "momentum",
- "nblocks",
- "enable_minmax_tuning",
- "enable_norm_bias_tuning",
- "gradient_accumulate_steps",
- "enable_alg_ext",
- "not_use_best_mse",
- "dynamic_max_gap",
- "enable_quanted_input",
- "optimizer",
- "enable_adam",
- "enable_lfq",
-}
-_RTN_FIELDS = {"disable_opt_rtn", "enable_opt_rtn"}
-_AWQ_FIELDS = {
- "duo_scaling",
- "n_grid",
- "seqlen",
- "nsamples",
- "batch_size",
- "apply_smooth",
- "smooth_iters",
- "apply_clip",
- "clip_as_init",
- "clip_n_grid",
- "clip_max_shrink",
- "clip_n_sample_token",
- "awq_seqlen",
- "smooth_batch_size",
- "disable_opt_rtn",
- "enable_opt_rtn",
- "skip_moe",
- "mappings",
-}
-_ROTATION_FIELDS = {
- "hadamard_type",
- "block_size",
- "fuse_online_to_weight",
- "allow_online_rotation",
-}
+
+
+def _iter_registered_alg_configs() -> list[tuple[str, type]]:
+ """Return each registered algorithm's canonical name and config class."""
+ from auto_round.algorithms.registry import iter_algorithm_entries
+
+ result = []
+ seen = set()
+ for entry in iter_algorithm_entries():
+ factory = entry.config_factory
+ if factory is None:
+ continue
+ config_cls = factory if isinstance(factory, type) else type(factory())
+ if config_cls not in seen:
+ seen.add(config_cls)
+ result.append((entry.name, config_cls))
+ return result
+
+
[email protected]_cache(maxsize=None)
+def _discover_alg_config_fields(config_cls: type) -> frozenset:
+ """Discover accepted config fields without maintaining per-algorithm lists."""
+ from pydantic import BaseModel
+
+ if issubclass(config_cls, BaseModel):
+ return frozenset(config_cls.model_fields.keys())
+
+ from auto_round.algorithms.config import AlgorithmConfig
+ from auto_round.algorithms.quantization.config import QuantizationConfig
+
+ fields = set()
+ for klass in config_cls.__mro__:
+ if klass in (QuantizationConfig, AlgorithmConfig, object):
+ break
+ init = klass.__dict__.get("__init__")
+ if init is None:
+ continue
+ for name, parameter in inspect.signature(init).parameters.items():
+ if name != "self" and parameter.kind not in (
+ inspect.Parameter.VAR_POSITIONAL,
+ inspect.Parameter.VAR_KEYWORD,
+ ):
+ fields.add(name)
+ return frozenset(fields)
def _filter_supported_entry_kwargs(kwargs, *, context="AutoRound"):
@@ -415,17 +416,11 @@ def _split_entry_kwargs(kwargs, *, context="AutoRound"):
def _config_fields(config):
- fields = set(_SCHEME_FIELDS)
- name = type(config).__name__.lower()
- if "awq" in name:
- fields.update(_AWQ_FIELDS)
- elif "rtn" in name:
- fields.update(_RTN_FIELDS)
- elif "signround" in name or "adamround" in name:
- fields.update(_SIGNROUND_FIELDS)
- elif "rotation" in name:
- fields.update(_ROTATION_FIELDS)
- return fields
+ return set(_SCHEME_FIELDS) | set(_discover_alg_config_fields(type(config)))
+
+
+def _owning_algorithm_names(field_name: str) -> list[str]:
+ return [cls.__name__ for _, cls in _iter_registered_alg_configs() if field_name in _discover_alg_config_fields(cls)]
def _normalize_alg_configs(alg_configs, direct_kwargs=None):
@@ -569,7 +564,8 @@ def _normalize_alg_configs(alg_configs, direct_kwargs=None):
# ignored algorithm-specific error after selecting RTN.
if key == "iters" and any(isinstance(config, RTNConfig) for config in configs):
continue
- owner = "AWQ" if key in _AWQ_FIELDS else "the selected algorithm"
+ owners = _owning_algorithm_names(key)
+ owner = "/".join(owners) if owners else "the selected algorithm"
logger.error(
"%s-specific parameter '%s' was provided, but %s is not enabled by alg_configs. "
"The parameter is ignored.",
@@ -778,9 +774,34 @@ class _CompressorBuilder(object):
class AutoRound:
"""Unified AutoRound entry point.
- alg_configs accepts an algorithm alias, one QuantizationConfig, or a
- sequence of either. When omitted, SignRound is selected. AWQ-only
- pipelines receive an RTN block quantizer by default.
+ ``alg_configs`` accepts an algorithm alias, one config object, or a
+ sequence of aliases and config objects. A sequence may combine a
+ preprocessor with one block quantizer, for example
+ ``["auto_round", "quarot"]``. Preprocessors execute in their listed
+ order; the block quantizer is always the final quantization stage,
+ regardless of its position in the sequence. When omitted, SignRound is
+ selected. AWQ-only pipelines receive an RTN block quantizer by default.
+
+ Args:
+ model: A model name/path or an already-loaded ``torch.nn.Module``.
+ tokenizer: Optional tokenizer used for calibration data.
+ scheme: Quantization scheme such as ``"W4A16"`` or ``"MXFP4"``.
+ alg_configs: Algorithm alias, config instance, or sequence of either.
+ Use config instances to provide algorithm-specific options, such
+ as ``SignRoundConfig(iters=50)`` or ``AWQConfig(apply_clip=True)``.
+ layer_config: Optional per-layer quantization overrides.
+ dataset: Calibration dataset name, samples, or dataloader.
+ seqlen: Calibration sequence length.
+ nsamples: Number of calibration samples.
+ batch_size: Calibration batch size.
+ low_gpu_mem_usage: Enable lower-memory calibration at the cost of speed.
+ device_map: Device or device mapping used for quantization.
+ enable_torch_compile: Whether to use ``torch.compile`` where supported.
+ seed: Random seed used by calibration and tuning.
+ **kwargs: Additional compressor, model-type, evaluation, and legacy
+ compatibility options. Unsupported options are ignored with a
+ warning; algorithm-specific options should be placed in the
+ corresponding config object.
"""
SKIP_ARGS = ("local_args", "kwargs", "cls", "model_cls", "dynamic_compressor", "alg_configs")
diff --git a/auto_round/cli/algorithms.py b/auto_round/cli/algorithms.py
index b82a0754a..0136a2e44 100644
--- a/auto_round/cli/algorithms.py
+++ b/auto_round/cli/algorithms.py
@@ -1,583 +1,307 @@
-# # Copyright (C) 2026 Intel Corporation
-# # SPDX-License-Identifier: Apache-2.0
-
-"""Algorithm discovery, registration, listing, and config building for the CLI.
-
-To add a new algorithm:
-1. Write a class that extends AlgorithmHandler and set name/aliases/summary.
-2. Implement register(group) to declare argparse flags.
-3. Implement build(args, common_kwargs) to return a config object.
-
-No manual registry update needed — subclasses are auto-registered on definition.
-"""
+# Copyright (c) 2026 Intel Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Generic CLI adapter for algorithm-owned parameter declarations."""
from __future__ import annotations
import argparse
-import copy
-from abc import ABC, abstractmethod
-from typing import Any, ClassVar
+import inspect
+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.registry import (
get_algorithm_entry,
iter_algorithm_entries,
- register_algorithm,
resolve_algorithm_alias,
resolve_algorithm_names,
)
-# ============================================================================
-# Base class + registry
-# ============================================================================
-
-
-class AlgorithmHandler(ABC):
- """Bundles everything the CLI needs to know about one algorithm.
-
- Concrete subclasses are auto-registered in the class-level registry
- the moment their class body is processed.
- """
-
- name: str # canonical name used in --algorithm
- aliases: tuple[str, ...] = () # all accepted names, including canonical
- summary: str = "" # one-liner shown by `auto_round list alg`
- config_factory: ClassVar[type | None] = None
-
- def __init_subclass__(cls, **kwargs) -> None:
- super().__init_subclass__(**kwargs)
- # A class that overrides both register and build is considered a concrete
- # algorithm implementation and must also declare a `name` class attribute.
- if "register" in cls.__dict__ and "build" in cls.__dict__:
- if "name" not in cls.__dict__:
- raise TypeError(f"{cls.__name__} must define a 'name' class attribute " f"(e.g. name = 'my_algo').")
- register_algorithm(
- cls.name,
- aliases=cls.aliases,
- config_factory=cls.config_factory,
- cli_handler=cls,
- summary=cls.summary,
- )
- # ------------------------------------------------------------------
- # Abstract interface — implement in each subclass
- # ------------------------------------------------------------------
+def _parameter_registry(config_cls: type) -> AlgorithmParameterRegistry:
+ if _has_custom_register_args(config_cls):
+ return config_cls.get_registered_args()
+ return _fallback_parameter_registry(config_cls)
+
+
+def _has_custom_register_args(config_cls: type) -> bool:
+ if not issubclass(config_cls, AlgorithmConfig):
+ return False
+ for cls in config_cls.__mro__:
+ if cls is AlgorithmConfig:
+ break
+ if "register_args" in cls.__dict__:
+ return True
+ return False
+
+
+def _fallback_parameter_registry(config_cls: type) -> AlgorithmParameterRegistry:
+ """Derive simple CLI arguments from a config that has no custom registration."""
+ registry = AlgorithmParameterRegistry()
+ init = config_cls.__init__
+ try:
+ type_hints = get_type_hints(init)
+ except (NameError, TypeError):
+ type_hints = {}
+
+ for name, parameter in inspect.signature(init).parameters.items():
+ if name in {"self", "algorithm"} or parameter.kind in (
+ inspect.Parameter.VAR_POSITIONAL,
+ inspect.Parameter.VAR_KEYWORD,
+ ):
+ continue
+ annotation = type_hints.get(name, parameter.annotation)
+ default = parameter.default
+ if annotation is inspect.Parameter.empty:
+ annotation = type(default) if default is not inspect.Parameter.empty and default is not None else str
+ if annotation is bool or isinstance(default, bool):
+ action = argparse.BooleanOptionalAction
+ kwargs = {"action": action, "default": argparse.SUPPRESS}
+ else:
+ origin = get_origin(annotation)
+ 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}
+ registry.add_argument(f"--{name}", field=name, **kwargs)
+ return registry
+
+
+def _argument_compatibility_key(parameter) -> tuple:
+ kwargs = parameter.argparse_kwargs
+ return (
+ kwargs.get("action"),
+ kwargs.get("type"),
+ tuple(kwargs.get("choices", ())) if kwargs.get("choices") is not None else None,
+ kwargs.get("nargs"),
+ kwargs.get("const"),
+ kwargs.get("dest", parameter.dest),
+ )
+
+
+def _existing_action_compatibility_key(action) -> tuple:
+ return (
+ type(action),
+ action.type,
+ tuple(action.choices) if action.choices is not None else None,
+ action.nargs,
+ action.const,
+ action.dest,
+ )
+
+
+def _check_existing_parser_argument(parser, parameter, *, fallback: bool = False) -> bool:
+ """Reuse an existing common argument when its parsing semantics match."""
+ actions = [
+ parser._option_string_actions[option]
+ for option in parameter.option_strings
+ if option in parser._option_string_actions
+ ]
+ if not actions:
+ return False
+ action = actions[0]
+ parameter_key = _argument_compatibility_key(parameter)
+ action_key = _existing_action_compatibility_key(action)
+ if parameter_key[1:] != action_key[1:]:
+ if fallback:
+ return True
+ option = next(option for option in parameter.option_strings if option in parser._option_string_actions)
+ raise ValueError(f"incompatible shared CLI argument {option!r}")
+ return True
+
+
+def _merge_parameter(merged, parameter):
+ """Merge one shared CLI parameter or raise for incompatible definitions."""
+ overlapping_options = set(merged.option_strings) & set(parameter.option_strings)
+ if not overlapping_options and merged.dest != parameter.dest:
+ return None
+ if merged.dest != parameter.dest or _argument_compatibility_key(merged) != _argument_compatibility_key(parameter):
+ option = sorted(overlapping_options)[0] if overlapping_options else merged.dest
+ raise ValueError(f"incompatible shared CLI argument {option!r}")
+ kwargs = dict(merged.argparse_kwargs)
+ kwargs["default"] = argparse.SUPPRESS
+ return replace(
+ merged,
+ option_strings=tuple(dict.fromkeys(merged.option_strings + parameter.option_strings)),
+ argparse_kwargs=kwargs,
+ )
+
+
+def _add_parameter(group, parameter) -> None:
+ kwargs = dict(parameter.argparse_kwargs)
+ kwargs.pop("fallback", None)
+ if kwargs.get("action") == "boolean_optional":
+ kwargs["action"] = argparse.BooleanOptionalAction
+ group.add_argument(*parameter.option_strings, **kwargs)
+
- @abstractmethod
- def register(self, group) -> None:
- """Add argparse arguments to *group*."""
+def _add_registered_arguments(group, registry: AlgorithmParameterRegistry) -> None:
+ mutex_groups = {}
+ for parameter in registry.parameters:
+ target = group
+ if parameter.mutex_group is not None:
+ if parameter.mutex_group not in mutex_groups:
+ mutex_groups[parameter.mutex_group] = group.add_mutually_exclusive_group()
+ target = mutex_groups[parameter.mutex_group]
+ _add_parameter(target, parameter)
- @abstractmethod
- def build(self, args, common_kwargs: dict[str, Any]) -> Any:
- """Build and return an algorithm config from parsed *args*."""
- # ------------------------------------------------------------------
- # Registry operations — called on the class, not on instances
- # ------------------------------------------------------------------
+class AlgorithmHandler:
+ """Generic discovery, argparse adaptation, and config construction."""
@classmethod
- def get(cls, name: str) -> AlgorithmHandler:
- """Return the handler for a canonical algorithm name. Raises KeyError if unknown."""
+ def get(cls, name: str) -> type:
entry = get_algorithm_entry(name)
- if entry.cli_handler is None:
- raise KeyError(f"No handler registered for algorithm '{name}'.")
- return entry.cli_handler()
+ if entry.config_factory is None:
+ raise KeyError(f"No config class registered for algorithm '{name}'.")
+ return entry.config_factory if isinstance(entry.config_factory, type) else type(entry.config_factory())
@classmethod
def resolve_alias(cls, user_name: str) -> str | None:
- """Resolve a user-supplied algorithm name or alias to the canonical name.
-
- Returns None instead of raising so callers can silently skip unknowns.
- """
return resolve_algorithm_alias(user_name)
+ @classmethod
+ def add_group(cls, name: str, group) -> None:
+ _add_registered_arguments(group, _parameter_registry(cls.get(name)))
+
@classmethod
def add_groups(cls, parser) -> None:
- """Add an argparse argument group for every registered algorithm."""
+ merged_parameters = []
+ parameters_by_group = {}
+ locations = []
for entry in iter_algorithm_entries():
- if entry.cli_handler is None:
+ if entry.config_factory is None:
continue
- handler = entry.cli_handler()
- group = parser.add_argument_group(f"Algorithm: {handler.name}")
- handler.register(group)
+ config_cls = (
+ entry.config_factory if isinstance(entry.config_factory, type) else type(entry.config_factory())
+ )
+ registry = _parameter_registry(config_cls)
+ fallback = not _has_custom_register_args(config_cls)
+ if registry.parameters:
+ group_name = f"Algorithm: {entry.name}"
+ parameters_by_group.setdefault(group_name, [])
+ 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,
+ )
+ if existing_index is not None:
+ merged = _merge_parameter(merged_parameters[existing_index], parameter)
+ merged_parameters[existing_index] = merged
+ existing_group, existing_position = locations[existing_index]
+ parameters_by_group[existing_group][existing_position] = merged
+ continue
+ merged_parameters.append(parameter)
+ parameters_by_group[group_name].append(parameter)
+ locations.append((group_name, len(parameters_by_group[group_name]) - 1))
+
+ for group_name, parameters in parameters_by_group.items():
+ group = parser.add_argument_group(group_name)
+ registry = AlgorithmParameterRegistry()
+ registry.parameters = parameters
+ _add_registered_arguments(group, registry)
@classmethod
def build_configs(cls, args, common_kwargs: dict[str, Any]) -> list:
- """Build the ordered algorithm config list from parsed CLI args."""
raw = getattr(args, "algorithm", None) or ""
- names = [n.strip().lower() for n in raw.split(",") if n.strip()]
+ names = [name.strip().lower() for name in raw.split(",") if name.strip()]
- # Infer hadamard when --rotation_type is given
if getattr(args, "rotation_hadamard_type", None) and "hadamard" not in names:
names.append("hadamard")
- # Resolve aliases, drop unknowns, deduplicate preserving order.
- # Python API strings use this same resolver so their composition
- # semantics cannot drift apart again.
canonical = resolve_algorithm_names(names, ignore_unknown=True)
seen = set(canonical)
-
- # 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.
+ 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]
- 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 = []
+ built_configs = {}
+ if "awq" in canonical:
+ awq_entry = get_algorithm_entry("awq")
+ awq_cls = cls.get("awq")
+ awq_kwargs = _parameter_registry(awq_cls).config_kwargs(args)
+ if getattr(awq_cls, "cli_include_common_args", True):
+ awq_kwargs.update(common_kwargs)
+ if isinstance(awq_entry.config_factory, type):
+ awq_config = awq_entry.config_factory(**awq_kwargs)
+ elif awq_kwargs:
+ awq_config = awq_cls(**awq_kwargs)
+ else:
+ awq_config = awq_entry.config_factory()
+ explicit_opt_rtn = getattr(args, "disable_opt_rtn", None)
+ if explicit_opt_rtn is not None:
+ awq_config.disable_opt_rtn = explicit_opt_rtn
+ built_configs["awq"] = awq_config
+ awq_disable_opt_rtn = getattr(built_configs.get("awq"), "disable_opt_rtn", None)
for name in canonical:
- if name == "awq":
- configs.append(awq_config)
+ if name in built_configs:
+ configs.append(built_configs[name])
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))
+ entry = get_algorithm_entry(name)
+ config_cls = cls.get(name)
+ 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:
+ kwargs["disable_opt_rtn"] = awq_disable_opt_rtn
+ if isinstance(entry.config_factory, type):
+ config = entry.config_factory(**kwargs)
+ elif kwargs:
+ config = config_cls(**kwargs)
+ else:
+ config = entry.config_factory()
+ configs.append(config)
return configs
@classmethod
def format_listing(cls) -> str:
- """Render the short `list alg` output."""
lines = []
for entry in iter_algorithm_entries():
- if entry.cli_handler is None:
+ if entry.config_factory is None:
continue
- handler = entry.cli_handler()
- other = [a for a in handler.aliases if a != handler.name]
+ other = [alias for alias in entry.aliases if alias != entry.name]
alias_str = f" (aliases: {', '.join(other)})" if other else ""
- lines.append(f"- {handler.name}{alias_str}: {handler.summary}")
+ lines.append(f"- {entry.name}{alias_str}: {entry.summary}")
return "\n".join(lines)
@classmethod
def format_detail(cls, name: str) -> str:
- """Render detailed help text for one algorithm."""
- canon = cls.resolve_alias(name)
- if canon is None:
- supported = [entry.name for entry in iter_algorithm_entries() if entry.cli_handler is not None]
- raise ValueError(f"Unknown algorithm '{name}'. " f"Supported: {', '.join(supported)}.")
- handler = cls.get(canon)
- lines = [f"{handler.name}: {handler.summary}"]
- other = [a for a in handler.aliases if a != handler.name]
+ canonical = cls.resolve_alias(name)
+ if canonical is None:
+ supported = [entry.name for entry in iter_algorithm_entries() if entry.config_factory is not None]
+ raise ValueError(f"Unknown algorithm '{name}'. Supported: {', '.join(supported)}.")
+ entry = get_algorithm_entry(canonical)
+ lines = [f"{entry.name}: {entry.summary}"]
+ other = [alias for alias in entry.aliases if alias != entry.name]
if other:
lines.append(f"Aliases: {', '.join(other)}")
temp = argparse.ArgumentParser(add_help=False)
- group = temp.add_argument_group(f"Flags for {handler.name}")
- handler.register(group)
+ group = temp.add_argument_group(f"Flags for {entry.name}")
+ 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 ""
lines.append(f" {flags}: {action.help or ''}{default}")
return "\n".join(lines)
-
-
-# ============================================================================
-# Helpers
-# ============================================================================
-
-
-def _parse_bool_or_mode(value: str) -> bool | str:
- """Parse AWQ duo_scaling's tri-state: true / false / both."""
- lowered = value.strip().lower()
- if lowered == "true":
- return True
- if lowered == "false":
- return False
- if lowered == "both":
- return "both"
- raise argparse.ArgumentTypeError("Expected one of: true, false, both")
-
-
-# ============================================================================
-# Algorithm implementations (auto-registered via __init_subclass__)
-# ============================================================================
-
-
-class AWQ(AlgorithmHandler):
- name = "awq"
- aliases = ("awq",)
- summary = "Activation-Aware Weight Quantization (pre-processing)."
- config_factory = None
-
- def register(self, group) -> None:
- group.add_argument(
- "--awq_duo_scaling",
- dest="duo_scaling",
- default=True,
- type=_parse_bool_or_mode,
- metavar="{true,false,both}",
- help="Use activation+weight duo scaling (true/false/both).",
- )
- group.add_argument(
- "--awq_n_grid",
- dest="n_grid",
- default=20,
- type=int,
- help="Number of grid-search points for AWQ scaling ratio.",
- )
- group.add_argument(
- "--awq_seqlen",
- dest="awq_seqlen",
- default=None,
- type=int,
- help=(
- "Maximum sequence length used by AWQ calibration. "
- "This is distinct from the global calibration --seqlen."
- ),
- )
- group.add_argument(
- "--awq_smooth_batch_size",
- dest="awq_smooth_batch_size",
- default=None,
- type=int,
- help="Microbatch size for AWQ parent replay during scale search; <=0 disables microbatching.",
- )
- group.add_argument(
- "--awq_apply_clip",
- dest="awq_apply_clip",
- action="store_true",
- help="Search and hard-clamp per-group AWQ weight clipping after smoothing.",
- )
- group.add_argument(
- "--awq_clip_as_init",
- dest="awq_clip_as_init",
- action="store_true",
- help=(
- "Use the searched AWQ clip to initialize the block quantizer's "
- "weight range instead of hard-clamping (requires --awq_apply_clip)."
- ),
- )
-
- def build(self, args, common_kwargs: dict[str, Any]):
- from auto_round.algorithms.transforms.awq.config import AWQConfig
-
- awq_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),
- apply_clip=getattr(args, "awq_apply_clip", False),
- 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,
- )
-
-
-class SVDQuant(AlgorithmHandler):
- name = "svdquant"
- aliases = ("svdquant",)
- summary = "SVD low-rank decomposition before residual quantization."
- config_factory = None
-
- def register(self, group) -> None:
- group.add_argument("--svdquant-rank", default=32, type=int, help="SVDQuant low-rank size.")
- group.add_argument(
- "--enable-svdquant-smooth",
- dest="svdquant_smooth_enabled",
- default=False,
- action="store_true",
- help="Enable SVDQuant activation-aware smoothing.",
- )
- group.add_argument(
- "--svdquant-smooth-num-grids",
- default=20,
- type=int,
- help="Number of candidates per SVDQuant smooth search grid family.",
- )
- group.add_argument(
- "--svdquant-smooth-max-calibration-calls",
- default=128,
- type=int,
- help="Maximum calibration calls retained per SVDQuant smooth group.",
- )
- group.add_argument(
- "--svdquant-residual-iters",
- default=1,
- type=int,
- help="Number of alternating low-rank and residual quantization iterations.",
- )
- group.add_argument(
- "--enable-svdquant-residual-early-stop",
- dest="svdquant_residual_early_stop",
- default=False,
- action="store_true",
- help="Stop residual iteration when reconstruction error no longer improves.",
- )
- group.add_argument(
- "--svdquant-low-rank-dtype",
- default="bf16",
- choices=["bf16", "bfloat16", "fp16", "float16", "fp32", "float32"],
- help="Data type for the SVDQuant low-rank branch.",
- )
- group.add_argument(
- "--svdquant-target-modules",
- default=None,
- type=str,
- help="Comma-separated module-name substrings to transform.",
- )
- group.add_argument(
- "--svdquant-exclude-modules",
- default=None,
- type=str,
- help="Comma-separated module-name substrings to exclude.",
- )
- group.add_argument(
- "--svdquant-model-adapter",
- default="auto",
- choices=["auto", "identity", "flux"],
- help="Architecture adapter used by SVDQuant export.",
- )
-
- def build(self, args, common_kwargs: dict[str, Any]):
- from auto_round.algorithms.transforms.svdquant.config import SVDQuantConfig
-
- return SVDQuantConfig(
- rank=getattr(args, "svdquant_rank", 32),
- smooth_enabled=getattr(args, "svdquant_smooth_enabled", False),
- smooth_num_grids=getattr(args, "svdquant_smooth_num_grids", 20),
- smooth_max_calibration_calls=getattr(args, "svdquant_smooth_max_calibration_calls", 128),
- residual_iters=getattr(args, "svdquant_residual_iters", 1),
- residual_early_stop=getattr(args, "svdquant_residual_early_stop", False),
- low_rank_dtype=getattr(args, "svdquant_low_rank_dtype", "bf16"),
- target_modules=getattr(args, "svdquant_target_modules", None),
- exclude_modules=getattr(args, "svdquant_exclude_modules", None),
- model_adapter=getattr(args, "svdquant_model_adapter", "auto"),
- **common_kwargs,
- )
-
-
-class RTN(AlgorithmHandler):
- name = "rtn"
- aliases = ("rtn",)
- summary = "Round-To-Nearest quantization."
- config_factory = None
-
- def register(self, group) -> None:
- mutex = group.add_mutually_exclusive_group()
- mutex.add_argument(
- "--disable_opt_rtn",
- dest="disable_opt_rtn",
- default=None,
- action="store_const",
- const=True,
- help="Force plain RTN (disable optimized path).",
- )
- mutex.add_argument(
- "--enable_opt_rtn",
- dest="disable_opt_rtn",
- action="store_const",
- const=False,
- help="Force optimized RTN path.",
- )
-
- def build(self, args, common_kwargs: dict[str, Any]):
- from auto_round.algorithms.quantization.rtn.config import RTNConfig
-
- return RTNConfig(
- disable_opt_rtn=getattr(args, "disable_opt_rtn", None),
- **common_kwargs,
- )
-
-
-class AutoRound(AlgorithmHandler):
- name = "auto_round"
- aliases = ("auto_round", "autoround", "sign_round", "signround")
- summary = "SignRound-style iterative block quantization."
- config_factory = None
-
- def register(self, group) -> None:
- group.add_argument(
- "--iters", "--iter", default=None, type=int, help="Number of optimization iterations per block."
- )
- group.add_argument("--lr", default=None, type=float, help="Learning rate for rounding optimization.")
- group.add_argument("--minmax_lr", default=None, type=float, help="Learning rate for min-max tuning.")
- group.add_argument("--momentum", default=0.0, type=float, help="Momentum factor for the optimizer.")
- group.add_argument("--nblocks", default=1, type=int, help="Number of blocks to optimize together.")
- minmax_mutex = group.add_mutually_exclusive_group()
- minmax_mutex.add_argument(
- "--enable_minmax_tuning",
- default=True,
- dest="enable_minmax_tuning",
- action="store_true",
- help="Tune weight min/max ranges.",
- )
- minmax_mutex.add_argument(
- "--no-enable_minmax_tuning",
- "--disable_minmax_tuning",
- dest="enable_minmax_tuning",
- action="store_false",
- help="Disable weight min/max tuning.",
- )
- group.add_argument(
- "--enable_norm_bias_tuning",
- default=False,
- action=argparse.BooleanOptionalAction,
- help="Tune normalization and bias terms.",
- )
- group.add_argument(
- "--gradient_accumulate_steps", default=1, type=int, help="Gradient accumulation steps per update."
- )
- group.add_argument(
- "--enable_alg_ext",
- default=False,
- action=argparse.BooleanOptionalAction,
- help="Enable experimental SignRound extension.",
- )
- group.add_argument(
- "--not_use_best_mse",
- default=False,
- action=argparse.BooleanOptionalAction,
- help="Skip restoring best-MSE checkpoint.",
- )
- quanted_input_mutex = group.add_mutually_exclusive_group()
- quanted_input_mutex.add_argument(
- "--enable_quanted_input",
- default=True,
- dest="enable_quanted_input",
- action="store_true",
- help="Consume quantized output of previous blocks.",
- )
- quanted_input_mutex.add_argument(
- "--no-enable_quanted_input",
- "--disable_quanted_input",
- dest="enable_quanted_input",
- action="store_false",
- help="Disable quantized-input propagation across blocks.",
- )
- group.add_argument(
- "--enable_adam",
- default=False,
- action=argparse.BooleanOptionalAction,
- help="Use the Adam-based SignRound variant.",
- )
- group.add_argument(
- "--enable_lfq",
- default=False,
- action=argparse.BooleanOptionalAction,
- help="Enable last-block LM cross-entropy (LFQ) loss for the final transformer block (experimental).",
- )
-
- def build(self, args, common_kwargs: dict[str, Any]):
- from auto_round.algorithms.quantization.sign_round.config import SignRoundConfig
-
- return SignRoundConfig(
- iters=getattr(args, "iters", 200),
- lr=getattr(args, "lr", None),
- minmax_lr=getattr(args, "minmax_lr", None),
- momentum=getattr(args, "momentum", 0.0),
- nblocks=getattr(args, "nblocks", 1),
- enable_minmax_tuning=getattr(args, "enable_minmax_tuning", True),
- enable_norm_bias_tuning=getattr(args, "enable_norm_bias_tuning", False),
- gradient_accumulate_steps=getattr(args, "gradient_accumulate_steps", 1),
- enable_alg_ext=getattr(args, "enable_alg_ext", False),
- not_use_best_mse=getattr(args, "not_use_best_mse", False),
- enable_quanted_input=getattr(args, "enable_quanted_input", True),
- enable_adam=getattr(args, "enable_adam", False),
- enable_lfq=getattr(args, "enable_lfq", False),
- **common_kwargs,
- )
-
-
-class Hadamard(AlgorithmHandler):
- name = "hadamard"
- aliases = ("hadamard", "random_hadamard", "quarot_hadamard")
- summary = "Hadamard rotation/transform applied before quantization."
- config_factory = None
-
- def register(self, group) -> None:
- group.add_argument(
- "--rotation_type",
- "--rotation-hadamard-type",
- dest="rotation_hadamard_type",
- default=None,
- choices=["hadamard", "random_hadamard", "quarot_hadamard"],
- help="Hadamard transform variant.",
- )
- group.add_argument(
- "--rotation_backend",
- dest="rotation_backend",
- default="auto",
- choices=["auto", "inplace", "transform"],
- help="Rotation backend to use.",
- )
- group.add_argument(
- "--rotation_block_size",
- dest="rotation_block_size",
- default=None,
- type=int,
- help="Grouped Hadamard block size.",
- )
- group.add_argument(
- "--fuse_online_to_weight",
- default=None,
- action=argparse.BooleanOptionalAction,
- help="Fuse online Hadamard rotation into weights.",
- )
- group.add_argument(
- "--allow_online_rotation",
- default=True,
- action=argparse.BooleanOptionalAction,
- help="Allow online activation rotation.",
- )
-
- def build(self, args, common_kwargs: dict[str, Any]):
- from auto_round.algorithms.transforms.hadamard.config import RotationConfig
-
- hadamard_type = getattr(args, "rotation_hadamard_type", None) or "hadamard"
- return RotationConfig(
- hadamard_type=hadamard_type,
- backend=getattr(args, "rotation_backend", "auto"),
- block_size=getattr(args, "rotation_block_size", None),
- fuse_online_to_weight=getattr(args, "fuse_online_to_weight", None),
- allow_online_rotation=getattr(args, "allow_online_rotation", True),
- )
-
-
-def _register_builtin_algorithm_factories() -> None:
- from auto_round.algorithms.quantization.rtn.config import RTNConfig
- from auto_round.algorithms.quantization.sign_round.config import SignRoundConfig
- from auto_round.algorithms.transforms.awq.config import AWQConfig
- from auto_round.algorithms.transforms.hadamard.config import RotationConfig
- from auto_round.algorithms.transforms.svdquant.config import SVDQuantConfig
-
- register_algorithm("rtn", aliases=("rtn",), config_factory=RTNConfig, cli_handler=RTN, summary=RTN.summary)
- register_algorithm(
- "auto_round",
- aliases=("auto_round", "autoround", "sign_round", "signround"),
- config_factory=SignRoundConfig,
- cli_handler=AutoRound,
- summary=AutoRound.summary,
- )
- register_algorithm("awq", aliases=("awq",), config_factory=AWQConfig, cli_handler=AWQ, summary=AWQ.summary)
- register_algorithm(
- "svdquant",
- aliases=("svdquant",),
- config_factory=SVDQuantConfig,
- cli_handler=SVDQuant,
- summary=SVDQuant.summary,
- )
- register_algorithm(
- "hadamard",
- aliases=("hadamard", "random_hadamard", "quarot_hadamard"),
- config_factory=RotationConfig,
- cli_handler=Hadamard,
- summary=Hadamard.summary,
- alias_factories={
- "random_hadamard": lambda: RotationConfig(hadamard_type="random_hadamard"),
- "quarot_hadamard": lambda: RotationConfig(hadamard_type="quarot_hadamard"),
- },
- )
-
-
-_register_builtin_algorithm_factories()
diff --git a/auto_round/cli/main.py b/auto_round/cli/main.py
index 59ffc447f..0c6be246b 100644
--- a/auto_round/cli/main.py
+++ b/auto_round/cli/main.py
@@ -218,7 +218,7 @@ def _print_algorithm_help(argv: list[str]) -> bool:
add_common_quantization_arguments(quant_group)
for name in canonical_names:
alg_group = mini.add_argument_group(f"Algorithm: {name}")
- AlgorithmHandler.get(name).register(alg_group)
+ AlgorithmHandler.add_group(name, alg_group)
mini.print_help()
return True
diff --git a/docs/rotation_details.md b/docs/rotation_details.md
index da0311f1a..2b9f21819 100644
--- a/docs/rotation_details.md
+++ b/docs/rotation_details.md
@@ -16,11 +16,11 @@ This is most useful for aggressive low-bit schemes such as MXFP4, NVFP4 and W4A4
AutoRound provides two independent rotation implementations:
- **QuaRot / SpinQuant** — architecture-aware, full-model rotation applied at up to
- four positions (R1–R4). Selected via `rotation_config="quarot"`,
- `rotation_config="spinquant"`, or a `SpinQuantConfig` instance. **Recommended.**
+ four positions (R1–R4). Selected via `alg_configs=[..., "quarot"]`,
+ `alg_configs=[..., "spinquant"]`, or a `SpinQuantConfig` instance. **Recommended.**
- **Per-Linear Block Rotation** — an earlier, simpler implementation that applies a
block-diagonal Hadamard uniformly to every `nn.Linear`. Selected via
- `rotation_config="default"` / a string Hadamard type, or a `RotationConfig`
+ `alg_configs=[..., "hadamard"]` / a string Hadamard type, or a `RotationConfig`
instance. Also exposed through the `--algorithm hadamard` CLI.
---
@@ -92,13 +92,14 @@ Defined in `auto_round/algorithms/transforms/spinquant/preprocessor.py`.
### 1.3 String shortcuts
-| Value | Equivalent |
+Both are registered algorithm aliases usable directly in `alg_configs`:
+
+| Alias | Equivalent |
|-------|-----------|
| `"quarot"` | `SpinQuantConfig(trainable_rotation=False, trainable_smooth=False)` — deterministic Hadamard, no training, no calibration data. |
| `"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`.
+Both presets keep the default `r1=True, r2=True, r3=False, r4=False`.
> ⚠️ **SpinQuant trainable rotation** (`trainable_rotation=True`) enables learnable
> rotation matrices optimized via Cayley SGD. This feature is a research feature and not
@@ -113,14 +114,17 @@ from auto_round.algorithms.transforms.spinquant import SpinQuantConfig
model_name = "Qwen/Qwen3-0.6B"
-# QuaRot preset: R1+R2 deterministic Hadamard, no training
-ar = AutoRound(model_name, scheme="MXFP4", rotation_config="quarot")
+# QuaRot preset: R1+R2 deterministic Hadamard, no training. Rotation configs are
+# passed alongside a quantization algorithm through `alg_configs`.
+ar = AutoRound(model_name, scheme="MXFP4", alg_configs=["auto_round", "quarot"])
-# Choose how many positions to rotate:
-ar = AutoRound(model_name, scheme="MXFP4", rotation_config=SpinQuantConfig(r1=True)) # R1 only
-ar = AutoRound(model_name, scheme="MXFP4", rotation_config=SpinQuantConfig(r1=True, r2=True)) # R1+R2
+# Choose how many positions to rotate by passing a SpinQuantConfig instance instead:
+ar = AutoRound(model_name, scheme="MXFP4", alg_configs=["auto_round", SpinQuantConfig(r1=True)]) # R1 only
+ar = AutoRound(model_name, scheme="MXFP4", alg_configs=["auto_round", SpinQuantConfig(r1=True, r2=True)]) # R1+R2
ar = AutoRound(
- model_name, scheme="MXFP4", rotation_config=SpinQuantConfig(r1=True, r2=True, r3=True, r4=True)
+ model_name,
+ scheme="MXFP4",
+ alg_configs=["auto_round", SpinQuantConfig(r1=True, r2=True, r3=True, r4=True)],
) # all four
ar.quantize_and_save(output_dir="./Qwen3-0.6B-mxfp4-quarot", format="auto_round")
@@ -147,16 +151,19 @@ from `known_hadamard.py`, combining it with a Sylvester block.
ar = AutoRound(
model_name,
scheme="MXFP4",
- rotation_config=SpinQuantConfig(
- r1=True,
- r2=True,
- r3=True,
- r4=True,
- random_r1=True,
- random_r2=True,
- random_r3=True,
- random_r4=True,
- ),
+ alg_configs=[
+ "auto_round",
+ SpinQuantConfig(
+ r1=True,
+ r2=True,
+ r3=True,
+ r4=True,
+ random_r1=True,
+ random_r2=True,
+ random_r3=True,
+ random_r4=True,
+ ),
+ ],
)
```
@@ -249,8 +256,8 @@ from auto_round import AutoRound
model_name_or_path = "meta-llama/Llama-3.1-8B-Instruct"
-# rotation_config="default": block_size auto (32 for MXFP), hadamard_type="hadamard"
-ar = AutoRound(model_name_or_path, scheme="MXFP4", rotation_config="default")
+# "hadamard": block_size auto (32 for MXFP), hadamard_type="hadamard"
+ar = AutoRound(model_name_or_path, scheme="MXFP4", alg_configs=["auto_round", "hadamard"])
ar.quantize_and_save(output_dir="./Llama-3.1-8B-Instruct-mxfp4-ht", format="auto_round")
```
@@ -268,18 +275,21 @@ CLI flags: `--rotation_type {hadamard,random_hadamard,quarot_hadamard}`,
---
-## 3. How `rotation_config` is dispatched
+## 3. How rotation configs are dispatched
-`rotation_config` is accepted by `AutoRound` and normalized by the unified
-`apply_rotation()` entry point in
+A rotation config is passed alongside a quantization algorithm through `alg_configs`
+(e.g. `alg_configs=["auto_round", "hadamard"]` or
+`alg_configs=["auto_round", SpinQuantConfig(...)]`). It is not accepted as a separate
+top-level `AutoRound(...)` parameter. Once resolved, it is normalized and dispatched by
+the unified `apply_rotation()` entry point in
`auto_round/algorithms/transforms/__init__.py`:
- A `BaseRotationConfig` instance (`SpinQuantConfig` or `RotationConfig`) is used
directly.
-- The strings `"quarot"` / `"spinquant"` map to the `SpinQuantConfig` shortcuts above.
-- A dict with `algorithm="spinquant"` becomes a `SpinQuantConfig`.
-- Any other string (e.g. `"default"`, `"hadamard"`, `"random_hadamard"`) or dict maps to
- the per-linear `RotationConfig`.
+- The registered aliases `"quarot"` / `"spinquant"` resolve to the `SpinQuantConfig`
+ shortcuts above.
+- The registered aliases `"hadamard"`, `"random_hadamard"`, `"quarot_hadamard"` resolve
+ to the per-linear `RotationConfig` presets.
---
diff --git a/docs/step_by_step.md b/docs/step_by_step.md
index c8868dc34..f9ff4132e 100755
--- a/docs/step_by_step.md
+++ b/docs/step_by_step.md
@@ -958,7 +958,7 @@ autoround.save_quantized(format="auto_awq", output_dir="tmp_autoround")
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.
-AutoRound applies rotation through the `rotation_config` argument. The `"quarot"` preset — deterministic Hadamard rotation (QuaRot / SpinQuant), no training and no calibration data — is recommended for most use cases.
+AutoRound applies rotation through `alg_configs`, alongside a quantization algorithm. The `"quarot"` preset — deterministic Hadamard rotation (QuaRot / SpinQuant), no training and no calibration data — is recommended for most use cases.
#### API Usage
@@ -968,7 +968,7 @@ from auto_round import AutoRound
model_name = "Qwen/Qwen3-0.6B"
# QuaRot preset: deterministic Hadamard, no training
-ar = AutoRound(model_name, scheme="MXFP4", rotation_config="quarot")
+ar = AutoRound(model_name, scheme="MXFP4", alg_configs=["auto_round", "quarot"])
ar.quantize_and_save(output_dir="./Qwen3-0.6B-mxfp4-quarot", format="auto_round")
```
diff --git a/docs/step_by_step_CN.md b/docs/step_by_step_CN.md
index 89996b4bc..1aaf792ad 100755
--- a/docs/step_by_step_CN.md
+++ b/docs/step_by_step_CN.md
@@ -921,7 +921,7 @@ auto-round --model_name Qwen/Qwen3-0.6B --scheme "W4A16" --quant_lm_head --form
旋转在量化前对权重和激活中的离群点进行重分布,使分布更加均匀、对量化更友好。它对 MXFP4、NVFP4、W4A4 等激进的低比特方案最为有效。
-AutoRound 通过 `rotation_config` 参数应用旋转。推荐在大多数场景中使用 `"quarot"` 预设——确定性 Hadamard 旋转(QuaRot / SpinQuant),无需训练、无需校准数据。
+AutoRound 通过 `alg_configs`(与量化算法一起传入)应用旋转。推荐在大多数场景中使用 `"quarot"` 预设——确定性 Hadamard 旋转(QuaRot / SpinQuant),无需训练、无需校准数据。
#### API 用法
@@ -931,7 +931,7 @@ from auto_round import AutoRound
model_name = "Qwen/Qwen3-0.6B"
# QuaRot 预设:确定性 Hadamard,无需训练
-ar = AutoRound(model_name, scheme="MXFP4", rotation_config="quarot")
+ar = AutoRound(model_name, scheme="MXFP4", alg_configs=["auto_round", "quarot"])
ar.quantize_and_save(output_dir="./Qwen3-0.6B-mxfp4-quarot", format="auto_round")
```
diff --git a/test/unit/common/core/test_pipeline_fast.py b/test/unit/common/core/test_pipeline_fast.py
index 2fce2bf60..ae77014e1 100644
--- a/test/unit/common/core/test_pipeline_fast.py
+++ b/test/unit/common/core/test_pipeline_fast.py
@@ -68,6 +68,24 @@ def test_pipeline_multiple_block_quantizers_rejected():
AlgorithmComposer([RTNConfig(), SignRoundConfig()])
+ "configs",
+ [
+ [RTNConfig(disable_opt_rtn=True), RotationConfig()],
+ [RotationConfig(), RTNConfig(disable_opt_rtn=True)],
+ ],
+)
+def test_block_quantizer_is_terminal_regardless_of_config_order(configs):
+ """The config list position must not move the terminal block quantizer."""
+ pipeline = AlgorithmComposer(configs)
+
+ members = pipeline.members()
+
+ assert members[:-1] == pipeline.preprocessors
+ assert members[-1] is pipeline.block_quantizer
+ assert isinstance(members[-1], RTNQuantizer)
+
+
def test_hadamard_disables_only_block_forward_compile():
hadamard = AlgorithmComposer([SignRoundConfig()], _compile_orchestrator(rotation_configs=(RotationConfig(),)))
assert not hadamard.block_forward.enable_torch_compile
diff --git a/test/unit/common/models/test_audio_model.py b/test/unit/common/models/test_audio_model.py
index 68517b010..a70136963 100644
--- a/test/unit/common/models/test_audio_model.py
+++ b/test/unit/common/models/test_audio_model.py
@@ -229,7 +229,6 @@ class TestMiMoAudioQuantization:
seqlen=32,
device_map=device,
enable_torch_compile=True,
- disable_opt_rtn=True,
)
quantized_model, _ = autoround.quantize_and_save(output_dir=str(tmp_path / "saved"))
assert quantized_model is not None
diff --git a/test/unit/common/utils/test_cli_usage.py b/test/unit/common/utils/test_cli_usage.py
index 158aaa491..03a9ff39c 100644
--- a/test/unit/common/utils/test_cli_usage.py
+++ b/test/unit/common/utils/test_cli_usage.py
@@ -1,3 +1,5 @@
+import argparse
+import inspect
import shutil
import sys
from test.helpers import get_model_path
@@ -396,6 +398,151 @@ def test_svdquant_cli_rejects_underscore_option_aliases():
)
+def test_cli_fallback_derives_arguments_for_config_without_register_args(monkeypatch):
+ import auto_round.cli.algorithms as algorithm_cli
+ from auto_round.algorithms.config import AlgorithmConfig
+ from auto_round.algorithms.registry import AlgRegistryEntry
+ from auto_round.cli.algorithms import AlgorithmHandler
+ from auto_round.cli.parser import build_quantize_parser
+
+ class FallbackConfig(AlgorithmConfig):
+ def __init__(self, *, iters: int = 3, enabled: bool = False):
+ self.iters = iters
+ self.enabled = enabled
+
+ monkeypatch.setattr(
+ algorithm_cli,
+ "iter_algorithm_entries",
+ lambda: [AlgRegistryEntry(name="fallback", config_factory=FallbackConfig)],
+ )
+
+ parser = build_quantize_parser()
+ args = parser.parse_args(["--model", "dummy-model", "--algorithm", "fallback", "--iters", "7", "--enabled"])
+
+ assert args.iters == 7
+ assert args.enabled is True
+ assert algorithm_cli._parameter_registry(FallbackConfig).parameters
+
+
+def test_cli_explicit_registration_takes_precedence_over_constructor_fallback():
+ from auto_round.algorithms.config import AlgorithmConfig
+ from auto_round.cli.algorithms import _parameter_registry
+
+ class ExplicitConfig(AlgorithmConfig):
+ def __init__(self, *, internal_value: int = 1):
+ self.internal_value = internal_value
+
+ @classmethod
+ def register_args(cls, registry):
+ registry.add_argument("--public-value", field="internal_value", type=int)
+
+ parameters = _parameter_registry(ExplicitConfig).parameters
+
+ assert [parameter.option_strings for parameter in parameters] == [("--public-value",)]
+ assert [parameter.field for parameter in parameters] == ["internal_value"]
+
+
+def test_cli_shared_fallback_argument_is_routed_to_each_selected_config(monkeypatch):
+ import auto_round.cli.algorithms as algorithm_cli
+ from auto_round.algorithms.config import AlgorithmConfig
+ from auto_round.algorithms.registry import AlgRegistryEntry
+ from auto_round.cli.algorithms import AlgorithmHandler
+
+ class FirstConfig(AlgorithmConfig):
+ def __init__(self, *, iters: int = 3):
+ self.iters = iters
+
+ class SecondConfig(AlgorithmConfig):
+ def __init__(self, *, iters: int = 5):
+ self.iters = iters
+
+ monkeypatch.setattr(
+ algorithm_cli,
+ "iter_algorithm_entries",
+ lambda: [
+ AlgRegistryEntry(name="first", config_factory=FirstConfig),
+ AlgRegistryEntry(name="second", config_factory=SecondConfig),
+ ],
+ )
+
+ parser = argparse.ArgumentParser()
+ AlgorithmHandler.add_groups(parser)
+ args = parser.parse_args(["--iters", "11"])
+
+ assert algorithm_cli._parameter_registry(FirstConfig).config_kwargs(args) == {"iters": 11}
+ assert algorithm_cli._parameter_registry(SecondConfig).config_kwargs(args) == {"iters": 11}
+
+
+def test_build_configs_routes_shared_argument_to_selected_configs(monkeypatch):
+ import auto_round.cli.algorithms as algorithm_cli
+ from auto_round.algorithms.config import AlgorithmConfig
+ from auto_round.algorithms.quantization.sign_round.config import SignRoundConfig
+ from auto_round.algorithms.registry import AlgRegistryEntry
+ from auto_round.cli.algorithms import AlgorithmHandler
+
+ class SharedConfig(AlgorithmConfig):
+ def __init__(self, *, iters: int = 5):
+ self.iters = iters
+
+ entries = {
+ "auto_round": AlgRegistryEntry(name="auto_round", config_factory=SignRoundConfig),
+ "shared": AlgRegistryEntry(name="shared", config_factory=SharedConfig),
+ }
+ monkeypatch.setattr(algorithm_cli, "get_algorithm_entry", entries.__getitem__)
+ monkeypatch.setattr(algorithm_cli, "resolve_algorithm_names", lambda names, **_: list(names))
+
+ args = argparse.Namespace(algorithm="auto_round,shared", iters=11, rotation_hadamard_type=None)
+ configs = AlgorithmHandler.build_configs(args, {})
+
+ assert isinstance(configs[0], SignRoundConfig)
+ assert configs[0].iters == 11
+ assert isinstance(configs[1], SharedConfig)
+ assert configs[1].iters == 11
+
+
+def test_cli_rejects_incompatible_shared_fallback_argument(monkeypatch):
+ import auto_round.cli.algorithms as algorithm_cli
+ from auto_round.algorithms.config import AlgorithmConfig
+ from auto_round.algorithms.registry import AlgRegistryEntry
+ from auto_round.cli.algorithms import AlgorithmHandler
+
+ class IntegerConfig(AlgorithmConfig):
+ def __init__(self, *, value: int = 1):
+ self.value = value
+
+ class StringConfig(AlgorithmConfig):
+ def __init__(self, *, value: str = "value"):
+ self.value = value
+
+ monkeypatch.setattr(
+ algorithm_cli,
+ "iter_algorithm_entries",
+ lambda: [
+ AlgRegistryEntry(name="integer", config_factory=IntegerConfig),
+ AlgRegistryEntry(name="string", config_factory=StringConfig),
+ ],
+ )
+
+ with pytest.raises(ValueError, match="incompatible shared CLI argument.*--value"):
+ AlgorithmHandler.add_groups(argparse.ArgumentParser())
+
+
+def test_registered_cli_fields_are_accepted_by_config_constructors():
+ import auto_round.cli.algorithms as algorithm_cli
+ from auto_round.algorithms.registry import iter_algorithm_entries
+
+ for entry in iter_algorithm_entries():
+ if entry.config_factory is None:
+ continue
+ config_cls = entry.config_factory if isinstance(entry.config_factory, type) else type(entry.config_factory())
+ accepted = set(inspect.signature(config_cls.__init__).parameters)
+ accepted.discard("self")
+ accepted.update(getattr(config_cls, "model_fields", {}))
+ assert all(
+ parameter.field in accepted for parameter in algorithm_cli._parameter_registry(config_cls).parameters
+ )
+
+
def test_svdquant_cli_defaults_compose_before_signround():
from auto_round.algorithms.quantization.sign_round.config import SignRoundConfig
from auto_round.algorithms.transforms.svdquant.config import SVDQuantConfig
diff --git a/test/unit/test_cpu/core/test_entry_contract.py b/test/unit/test_cpu/core/test_entry_contract.py
index e63d12349..50e344fdb 100644
--- a/test/unit/test_cpu/core/test_entry_contract.py
+++ b/test/unit/test_cpu/core/test_entry_contract.py
@@ -71,13 +71,11 @@ def test_cli_awq_rtn_opt_policy():
def test_cli_rtn_inherits_built_awq_config_without_mutating_args(monkeypatch):
from argparse import Namespace
+ from auto_round.algorithms.registry import get_algorithm_entry
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)
+ from auto_round.cli.algorithms import AlgorithmHandler
- monkeypatch.setattr(AWQ, "build", build_awq_with_opt_rtn)
+ monkeypatch.setattr(get_algorithm_entry("awq"), "config_factory", lambda: AWQConfig(disable_opt_rtn=False))
args = Namespace(algorithm="rtn,awq", iters=200, disable_opt_rtn=None)
configs = AlgorithmHandler.build_configs(args, {})
diff --git a/test/unit/test_cuda/transform/test_mxfp4_transform.py b/test/unit/test_cuda/transform/test_mxfp4_transform.py
index 0996e2ffa..b3ee169aa 100644
--- a/test/unit/test_cuda/transform/test_mxfp4_transform.py
+++ b/test/unit/test_cuda/transform/test_mxfp4_transform.py
@@ -36,7 +36,7 @@ class TestAutoRound:
iters=0,
seqlen=2,
scheme=scheme,
- rotation_config="default",
+ alg_configs=["rtn", "hadamard"],
)
compressed_model, quantized_model_path = ar.quantize_and_save(output_dir=self.save_dir, format="auto_round")
@@ -56,7 +56,7 @@ class TestAutoRound:
iters=2,
seqlen=2,
scheme=scheme,
- rotation_config="default",
+ alg_configs=["auto_round", "hadamard"],
)
compressed_model, quantized_model_path = ar.quantize_and_save(output_dir=self.save_dir, format="auto_round")
@@ -76,7 +76,7 @@ class TestAutoRound:
iters=0,
seqlen=2,
scheme=scheme,
- rotation_config="random_hadamard",
+ alg_configs=["rtn", "random_hadamard"],
)
compressed_model, quantized_model_path = ar.quantize_and_save(output_dir=self.save_dir, format="auto_round")
diff --git a/test/unit/test_cuda/transform/test_spinquant.py b/test/unit/test_cuda/transform/test_spinquant.py
index 2e692c97c..570691046 100644
--- a/test/unit/test_cuda/transform/test_spinquant.py
+++ b/test/unit/test_cuda/transform/test_spinquant.py
@@ -5,7 +5,7 @@ Tests cover:
- normalize_rotation_config dispatcher (string, dict, object)
- BaseRotation registry integration
- Hook lifecycle (registration, tagging, selective removal)
- - Pipeline integration via AutoRound(rotation_config=...)
+ - Pipeline integration via AutoRound(alg_configs=[..., "quarot"/SpinQuantConfig(...)])
- Rotation correctness: R1, R1+R2, R1+R2+R3+R4 produce valid logits
"""
@@ -294,7 +294,7 @@ class TestRotationCorrectness:
class TestPipelineIntegration:
- """Test AutoRound(rotation_config=...) pipeline integration."""
+ """Test AutoRound(alg_configs=[..., rotation config]) pipeline integration."""
save_dir = "./saved_spinquant"
@@ -305,14 +305,14 @@ class TestPipelineIntegration:
@pytest.mark.timeout(180)
def test_pipeline_quarot_string(self):
- """AutoRound(rotation_config='quarot') should work end-to-end."""
+ """AutoRound(alg_configs=["rtn", "quarot"]) should work end-to-end."""
model_name = get_model_path("Qwen/Qwen3-0.6B")
ar = AutoRound(
model=model_name,
iters=0,
seqlen=2,
scheme="W4A16",
- rotation_config="quarot",
+ alg_configs=["rtn", "quarot"],
)
compressed_model, quantized_model_path = ar.quantize_and_save(output_dir=self.save_dir, format="auto_round")
@@ -322,7 +322,7 @@ class TestPipelineIntegration:
@pytest.mark.timeout(90)
def test_pipeline_spinquant_config(self):
- """AutoRound(rotation_config=SpinQuantConfig(...)) should work."""
+ """AutoRound(alg_configs=["rtn", SpinQuantConfig(...)]) should work."""
model_name = get_model_path("Qwen/Qwen3-0.6B")
cfg = SpinQuantConfig(
r1=True,
@@ -338,7 +338,7 @@ class TestPipelineIntegration:
iters=0,
seqlen=2,
scheme="W4A16",
- rotation_config=cfg,
+ alg_configs=["rtn", cfg],
)
compressed_model, quantized_model_path = ar.quantize_and_save(
output_dir=self.save_dir + "_cfg", format="auto_round"
@@ -346,23 +346,24 @@ class TestPipelineIntegration:
shutil.rmtree(self.save_dir + "_cfg", ignore_errors=True)
@pytest.mark.timeout(90)
- def test_pipeline_dict_config(self):
- """AutoRound(rotation_config={...}) should work."""
+ def test_pipeline_config_object(self):
+ """Building a SpinQuantConfig directly (instead of the dict shorthand) and passing
+ it via ``alg_configs`` should work."""
model_name = get_model_path("Qwen/Qwen3-0.6B")
+ cfg = SpinQuantConfig(
+ r1=True,
+ r2=True,
+ r3=False,
+ r4=False,
+ trainable_rotation=False,
+ trainable_smooth=False,
+ )
ar = AutoRound(
model=model_name,
iters=0,
seqlen=2,
scheme="W4A16",
- rotation_config={
- "algorithm": "spinquant",
- "r1": True,
- "r2": True,
- "r3": False,
- "r4": False,
- "trainable_rotation": False,
- "trainable_smooth": False,
- },
+ alg_configs=["rtn", cfg],
)
compressed_model, quantized_model_path = ar.quantize_and_save(
output_dir=self.save_dir + "_dict", format="auto_round"