Skip to content

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

unify target_bits/options into bits/schemes for AutoScheme (#2333)

Heng Guo2b5a3c5506a2
diff --git a/README.md b/README.md
index b53d8688a..5dd3c4535 100644
--- a/README.md
+++ b/README.md
@@ -276,15 +276,20 @@ ar.quantize_and_save(output_dir="./qmodel", format="auto_round")
AutoScheme provides an automatic algorithm to generate adaptive mixed bits/data-type quantization recipes.
Please refer to the [user guide](https://github.com/intel/auto-round/blob/main/docs/step_by_step.md#autoscheme) for more details on AutoScheme.
~~~python
-from auto_round import AutoRound, AutoScheme
+from auto_round import AutoRound
model_name = "Qwen/Qwen3-8B"
-avg_bits = 3.0
-scheme = AutoScheme(avg_bits=avg_bits, options=("GGUF:Q2_K_S", "GGUF:Q4_K_S"), ignore_scale_zp_bits=True)
layer_config = {"lm_head": "GGUF:Q6_K"}
# Change iters to 200 for non-GGUF schemes
-ar = AutoRound(model=model_name, scheme=scheme, layer_config=layer_config, iters=0)
+ar = AutoRound(
+ model=model_name,
+ schemes=("GGUF:Q2_K_S", "GGUF:Q4_K_S"),
+ bits=3.0,
+ ignore_scale_zp_bits=True,
+ layer_config=layer_config,
+ iters=0,
+)
ar.quantize_and_save()
~~~
@@ -294,8 +299,8 @@ ar.quantize_and_save()
##### AutoScheme Hyperparameters
-- **`avg_bits` (float)**: Target average bit-width for the entire model. Only quantized layers are included in the average bit calculation.
-- **`options` (str | list[str] | list[QuantizationScheme])**: Candidate quantization schemes to choose from. It can be a single comma-separated string (e.g., `"W4A16,W2A16"`), a list of strings (e.g., `["W4A16", "W2A16"]`), or a list of `QuantizationScheme` objects.
+- **`bits` (float)**: Target average bit-width for the entire model when `schemes` is provided. Only quantized layers are included in the average bit calculation. Without `schemes`, `bits` is the plain weight bit width and must be an integer.
+- **`schemes` (str | list[str] | list[QuantizationScheme])**: Candidate quantization schemes to choose from. It can be a single comma-separated string (e.g., `"W4A16,W2A16"`), a list of strings (e.g., `["W4A16", "W2A16"]`), or a list of `QuantizationScheme` objects. Providing schemes enables AutoScheme.
- **`ignore_scale_zp_bits` (bool)**: Only supported in API usage. Determines whether to exclude the bits of scale and zero-point from the average bit-width calculation (default: `False`).
- **`shared_layers` (Iterable[Iterable[str]], optional)**: Only supported in API usage. Defines groups of layers that share quantization settings.
- **`batch_size` (int, optional)**: Only supported in API usage. Can be set to `1` to reduce VRAM usage at the expense of longer tuning time.
diff --git a/README_CN.md b/README_CN.md
index 39858c7af..cf1863231 100644
--- a/README_CN.md
+++ b/README_CN.md
@@ -293,15 +293,20 @@ ar.quantize_and_save(output_dir="./qmodel", format="auto_round")
AutoScheme 提供了一种自动生成算法,用于生成 **自适应的混合精度/数据类型** 的量化方案(mixed bits/data type quantization recipes)。关于 AutoScheme 的更多细节可参考[用户指南](https://github.com/intel/auto-round/blob/main/docs/step_by_step.md#autoscheme)。
```python
-from auto_round import AutoRound, AutoScheme
+from auto_round import AutoRound
model_name = "Qwen/Qwen3-8B"
-avg_bits = 3.0
-scheme = AutoScheme(avg_bits=avg_bits, options=("GGUF:Q2_K_S", "GGUF:Q4_K_S"), ignore_scale_zp_bits=True)
layer_config = {"lm_head": "GGUF:Q6_K"}
# 对于非 GGUF 方案,将 iters 改为 200
-ar = AutoRound(model=model_name, scheme=scheme, layer_config=layer_config, iters=0)
+ar = AutoRound(
+ model=model_name,
+ schemes=("GGUF:Q2_K_S", "GGUF:Q4_K_S"),
+ bits=3.0,
+ ignore_scale_zp_bits=True,
+ layer_config=layer_config,
+ iters=0,
+)
ar.quantize_and_save()
```
@@ -310,8 +315,8 @@ ar.quantize_and_save()
##### AutoScheme 超参数
-- ​**​`avg_bits`​**​ **(float)** :整个模型的目标平均 bits(平均 bits 的计算仅包含被量化的层)。
-- ​**​`options`​**​ **(str | list[str] | list[QuantizationScheme])** ​:候选量化配置集合。支持以下表示形式:单个用逗号分隔的字符串(例如 `"W4A16,W2A16"`​)、字符串列表(例如 `["W4A16", "W2A16"]`​)和 `QuantizationScheme` 。
+- ​**​`bits`​**​ **(float)** :传入 `schemes` 时,为整个模型的目标平均 bits(平均 bits 的计算仅包含被量化的层)。未提供 `schemes` 时,`bits` 为普通权重量化位宽,必须为整数。
+- ​**​`schemes`​**​ **(str | list[str] | list[QuantizationScheme])** ​:候选量化配置集合。支持以下表示形式:单个用逗号分隔的字符串(例如 `"W4A16,W2A16"`​)、字符串列表(例如 `["W4A16", "W2A16"]`​)和 `QuantizationScheme` 。传入 `schemes` 即启用 AutoScheme。
- ​**​`ignore_scale_zp_bits`​**​ **(bool)** ​:仅支持 API 调用场景。用于决定在计算平均 bit 时,是否忽略 scale 与 zero-point 的位数(默认 `False`)。
- ​**​`shared_layers`​**​ **(Iterable[Iterable[str]], optional)** :仅支持 API 调用场景,用于定义多个层的分组,这些层将共享相同的量化配置。
- ​**​`batch_size`​**​ **(int, optional)** ​:仅支持 API 调用场景。设为 `1` 可以降低显存占用,但同时会增加训练时间。
diff --git a/auto_round/autoround.py b/auto_round/autoround.py
index 203966cb6..22baaf226 100644
--- a/auto_round/autoround.py
+++ b/auto_round/autoround.py
@@ -21,7 +21,15 @@ from typing import TYPE_CHECKING, Any, Optional, Union
import torch
from auto_round.logger import deprecated, logger
-from auto_round.schemes import QuantizationScheme, parse_scheme
+from auto_round.scheme_entry import (
+ collect_config_scheme_overrides,
+ eager_validate_scheme,
+ is_gguf_k_target,
+ is_weight_scheme,
+ preview_resolved_attrs,
+ resolve_entry_scheme,
+)
+from auto_round.schemes import QuantizationScheme
from auto_round.utils.device_manager import normalize_default_device_map
if TYPE_CHECKING:
@@ -31,90 +39,6 @@ if TYPE_CHECKING:
from auto_round.compressors.base import BaseOrchestrator as BaseCompressor
-def _collect_config_scheme_overrides(config) -> dict:
- """Return the config's explicitly-set scheme fields as a ``{field: value}`` dict.
-
- These are exactly the per-field overrides layered on top of ``scheme=`` — the
- single mechanism through which ``bits`` / ``act_bits`` / ``data_type`` etc.
- reach the resolved scheme. Fields left as ``None`` are omitted so the scheme's
- own value wins.
- """
- return {k: getattr(config, k) for k in config._scheme_fields if getattr(config, k, None) is not None}
-
-
-def _preview_resolved_attrs(config, scheme=None, format=None) -> dict:
- from auto_round.auto_scheme.gen_auto_scheme import AutoScheme
-
- """Resolve scheme attributes without mutating config, for routing decisions.
-
- Called in ``AutoRound.__new__`` before the concrete compressor class is
- chosen. ``SchemeMixin.resolve_scheme()`` will do the authoritative
- resolution later; this is just a lightweight preview so routing logic
- (``enable_imatrix``, ``needs_act_calib``, etc.) can use the correct values
- even when the user specified only ``scheme=`` without explicit bit/dtype args.
-
- This is the single source of resolved scheme fields for entry-level routing:
- callers read from the returned dict and never re-read raw ``config`` attrs.
- When the scheme cannot be previewed (``AutoScheme``, or a deferred parse
- error), the config's own explicitly-set scheme overrides are returned so the
- values still reflect what the user passed. ``format`` must match the
- authoritative parse so format-scoped policies (e.g. the 8-bit asym rule)
- resolve identically here and never turn a refusal into fabricated defaults.
-
- Returns:
- dict: resolved scheme attributes (config overrides when preview is skipped).
- """
- config_overrides = _collect_config_scheme_overrides(config)
- if isinstance(scheme, AutoScheme):
- # AutoScheme needs model info — cannot preview; fall back to raw config attrs.
- return config_overrides
- try:
- _, _, final_attrs = parse_scheme(scheme, config_overrides, format=format)
- return final_attrs
- except Exception as e:
- logger.warning_once(
- "Scheme preview failed (%s: %s); routing falls back to the config's explicit overrides.",
- type(e).__name__,
- e,
- )
- return config_overrides
-
-
-def _eager_validate_scheme(config, scheme=None, format=None) -> None:
- from auto_round.auto_scheme.gen_auto_scheme import AutoScheme
-
- """Eagerly validate scheme/config constraints at construction time.
-
- Mirrors the old-arch ``_check_configs()`` call in ``BaseCompressor.__init__``.
- Raises ``ValueError`` or ``NotImplementedError`` immediately if the scheme
- contains config-only invalid combinations (e.g. tuple group_size with non-fp8
- weight dtype) so that callers get a fast failure rather than a deferred error
- buried inside ``post_init()``.
-
- ``AutoScheme`` is skipped because it requires model information.
- """
- if isinstance(scheme, AutoScheme):
- return
-
- user_overrides = _collect_config_scheme_overrides(config)
- try:
- _, _, final_attrs = parse_scheme(scheme, user_overrides, format=format)
- except (ValueError, NotImplementedError):
- raise
- except Exception:
- return # Other parse errors are deferred to post_init
-
- import copy
-
- temp_config = copy.copy(config)
- if hasattr(config, "scheme"):
- temp_config.scheme = config.scheme.copy()
- temp_config._user_set_scheme_fields = set(getattr(config, "_user_set_scheme_fields", set()))
- for key, value in final_attrs.items():
- setattr(temp_config, key, value)
- temp_config.check_config() # raises ValueError / NotImplementedError if invalid
-
-
# ---------------------------------------------------------------------------
# Compressor-class registry
# ---------------------------------------------------------------------------
@@ -150,37 +74,6 @@ def _get_compressor_class(model_type: str, base_cls: type) -> type:
return combined
-def is_weight_scheme(scheme: Union[str, dict, object]) -> bool:
- if isinstance(scheme, str):
- return scheme.upper().startswith("W")
- if isinstance(scheme, dict):
- return all(isinstance(s, str) and s.upper().startswith("W") for s in scheme.values())
- from auto_round.auto_scheme.gen_auto_scheme import AutoScheme
-
- if isinstance(scheme, AutoScheme):
- opts = scheme.options
- if isinstance(opts, (list, tuple)):
- return all(isinstance(s, str) and s.upper().startswith("W") for s in opts)
- if isinstance(opts, str):
- return opts.upper().startswith("W")
- return False
-
-
-def is_gguf_k_target(value: Union[str, "AutoScheme", object]) -> bool:
- from auto_round.auto_scheme.gen_auto_scheme import AutoScheme
-
- if isinstance(value, str):
- normalized = value.strip().lower()
- return normalized.startswith("gguf:") and "_k" in normalized
- if isinstance(value, AutoScheme):
- opts = value.options
- if isinstance(opts, str):
- opts = [opts]
- if isinstance(opts, (list, tuple)):
- return any(isinstance(opt, str) and is_gguf_k_target(opt) for opt in opts)
- return False
-
-
def _resolve_quant_config_for_routing(alg_configs) -> tuple[list, list, "QuantizationConfig"]:
from auto_round.algorithms.config_resolver import split_quantization_configs
from auto_round.algorithms.quantization.config import QuantizationConfig
@@ -271,7 +164,7 @@ def _select_rtn_compressor_base_cls(quant_config: "RTNConfig", scheme, format, b
# resolution later; this preview only chooses the class). Computed once: neither
# `quant_config`'s scheme fields nor `scheme` itself change within this function,
# so the result is invariant across every use below — no need to recompute it.
- resolved_attrs = _preview_resolved_attrs(quant_config, scheme, format=format)
+ resolved_attrs = preview_resolved_attrs(quant_config, scheme, format=format)
# Auto-disable rtn optimization for W8A16/W8A8-equivalent resolved schemes,
# unless the user already set disable_opt_rtn explicitly.
@@ -714,14 +607,14 @@ class _CompressorBuilder(object):
route_scheme = (
scheme
if hasattr(scheme, "options") and hasattr(scheme, "avg_bits")
- else QuantizationScheme.from_dict(_preview_resolved_attrs(quant_config, scheme, format=format))
+ else QuantizationScheme.from_dict(preview_resolved_attrs(quant_config, scheme, format=format))
)
# Eagerly validate scheme constraints that do not require model info.
# This mirrors old-arch _check_configs() called at __init__ time so that
# callers get ValueError/NotImplementedError on construction, not deferred.
# Runs before the model-free early return so both routes enforce the
# same config-level constraints (e.g. the format-scoped 8-bit asym rule).
- _eager_validate_scheme(quant_config, scheme, format=format)
+ eager_validate_scheme(quant_config, scheme, format=format)
# NOTE: the W8-asym opt-in is the AR_ALLOW_W8_ASYM environment
# variable, read directly by parse_scheme and the generation-time
# gates; nothing is threaded through the compressor here.
@@ -800,6 +693,13 @@ class AutoRound:
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"``.
+ schemes: Optional candidate quantization schemes for AutoScheme
+ (adaptive mixed-bit selection), e.g. ``("W4A16", "W8A16")`` or
+ ``"W4A16,W8A16"``. Providing schemes enables AutoScheme; ``bits``
+ then sets the average target bits. Mutually exclusive with
+ ``scheme``.
+ bits: Weight quantization bit width. When ``schemes`` is provided it
+ is the average target bits for AutoScheme (e.g. ``4.2``).
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)``.
@@ -826,6 +726,8 @@ class AutoRound:
tokenizer=None,
platform: str = "hf",
scheme: Union[str, dict, QuantizationScheme, "AutoScheme"] = "W4A16",
+ schemes: Union[str, list, tuple, None] = None,
+ bits: Union[int, float, None] = None,
layer_config: dict[str, Union[str, dict, QuantizationScheme]] = None,
dataset: Optional[Union[str, list, tuple, torch.utils.data.DataLoader]] = None,
iters: int | None = None,
@@ -854,6 +756,9 @@ class AutoRound:
direct_kwargs["gradient_accumulate_steps"] = gradient_accumulate_steps
if algorithm is not None:
direct_kwargs["algorithm"] = algorithm
+ if bits is not None:
+ direct_kwargs["bits"] = bits
+ scheme, direct_kwargs = resolve_entry_scheme(scheme, schemes, direct_kwargs)
configs, runtime_kwargs = _prepare_entry_kwargs(alg_configs, direct_kwargs)
runtime_kwargs["batch_size"] = batch_size
diff --git a/auto_round/cli/main.py b/auto_round/cli/main.py
index de5f778b7..5d5d3524d 100644
--- a/auto_round/cli/main.py
+++ b/auto_round/cli/main.py
@@ -50,6 +50,18 @@ def _extract_common_quantization_kwargs(args) -> dict:
}
+def _normalize_scheme_list(raw) -> str | None:
+ """Normalize --schemes/--options into a comma-joined scheme list.
+
+ Accepts both space-separated (nargs="+" list) and comma-separated forms,
+ e.g. 'W4A16 W8A16' or 'W4A16,W8A16' -> 'W4A16,W8A16'.
+ """
+ if raw is None:
+ return None
+ flat = ",".join(raw) # handles list; each element may itself contain commas
+ return ",".join(p.strip() for p in flat.split(",") if p.strip())
+
+
def _build_entry_base_kwargs(args, *, low_cpu_mem_usage, enable_torch_compile, layer_config) -> dict:
return {
"platform": args.platform,
@@ -352,11 +364,16 @@ def tune(args):
from auto_round.auto_scheme import AutoScheme
- # Normalize --options: accepts both space-separated (nargs="+" list) and comma-separated string.
- # Examples: --options W4A16 W8A16 OR --options W4A16,W8A16
- if args.options is not None:
- flat = ",".join(args.options) # handles list; each element may itself contain commas
- args.options = ",".join(p.strip() for p in flat.split(",") if p.strip())
+ # Supplying multiple schemes enables AutoScheme: the schemes are the
+ # candidate options and --bits is the average target bits.
+ # --options/--avg_bits/--target_bits are deprecated aliases that argparse
+ # merges into --schemes/--bits (see _LegacyAliasAction in parser.py); they
+ # stay functional but are hidden from --help.
+ scheme_options = None
+ if args.schemes is not None:
+ if args.scheme.upper() != "W4A16":
+ raise ValueError("`--scheme` and `--schemes` cannot be used together, please use only `--schemes`")
+ scheme_options = _normalize_scheme_list(args.schemes)
# Normalize --shared_layers: supports three forms per invocation:
# - all bare tokens (no commas): treated as one group
@@ -384,17 +401,17 @@ def tune(args):
normalized_groups.append(group)
args.shared_layers = normalized_groups or None
- if args.avg_bits is not None:
- if args.options is None:
- raise ValueError("please set --options for auto scheme")
+ if scheme_options is not None:
+ if args.bits is None:
+ raise ValueError("please set --bits for auto scheme")
if enable_torch_compile is False:
logger.warning(
"`torch.compile` is disabled with AutoScheme. "
"Enabling it (the default) is strongly recommended to save VRAM."
)
scheme = AutoScheme(
- options=args.options,
- avg_bits=args.avg_bits,
+ options=scheme_options,
+ avg_bits=args.bits,
shared_layers=args.shared_layers,
ignore_scale_zp_bits=args.ignore_scale_zp_bits,
low_gpu_mem_usage=True,
@@ -402,6 +419,21 @@ def tune(args):
)
common_kwargs = _extract_common_quantization_kwargs(args)
+ if scheme_options is not None:
+ # `bits` is the AutoScheme average target, not a scheme override:
+ # the candidate options carry their own bit widths.
+ common_kwargs.pop("bits", None)
+ else:
+ # Without --schemes, `--bits` is a plain weight bit width and must be an integer.
+ bits = common_kwargs.get("bits")
+ if bits is not None:
+ if float(bits).is_integer():
+ common_kwargs["bits"] = int(bits)
+ else:
+ raise ValueError(
+ "`--bits` must be an integer for weight quantization; "
+ "use `--schemes` to set a fractional AutoScheme average target"
+ )
alg_configs = AlgorithmHandler.build_configs(args, common_kwargs)
from auto_round.utils import clear_memory
diff --git a/auto_round/cli/parser.py b/auto_round/cli/parser.py
index 68e360d19..77793f1b4 100644
--- a/auto_round/cli/parser.py
+++ b/auto_round/cli/parser.py
@@ -20,6 +20,30 @@ import argparse
from auto_round.cli.algorithms import AlgorithmHandler
from auto_round.eval.eval_cli import EvalArgumentParser
+from auto_round.logger import logger
+
+
+class _LegacyAliasAction(argparse.Action):
+ """Parse a deprecated flag into its canonical argument, hidden from --help.
+
+ e.g. ``--avg_bits``/``--target_bits`` store into ``bits`` and
+ ``--options``/``--option`` store into ``schemes``, so the legacy CLI usage
+ keeps working while the old names stay out of ``--help``.
+ """
+
+ _CANONICAL_FLAGS = {"bits": "--bits", "schemes": "--schemes"}
+
+ def __call__(self, parser, namespace, values, option_string=None):
+ logger.warning_once(
+ "`%s` is deprecated, please use `%s` instead", option_string, self._CANONICAL_FLAGS[self.dest]
+ )
+ current_value = getattr(namespace, self.dest, None)
+ if current_value is not None and current_value != values:
+ parser.error(
+ f"conflicting values for {self._CANONICAL_FLAGS[self.dest]}: "
+ f"{current_value!r} was already provided, but {option_string!r} set {values!r}"
+ )
+ setattr(namespace, self.dest, values)
def _parse_group_size(s: str):
@@ -36,7 +60,13 @@ def add_common_quantization_arguments(group) -> None:
_extract_common_quantization_kwargs() in main.py.
"""
group.add_argument("--scheme", default="W4A16", type=str, help="Quantization scheme preset, e.g. W4A16, W8A16.")
- group.add_argument("--bits", default=None, type=int, help="Weight quantization bit width.")
+ group.add_argument(
+ "--bits",
+ "--bit",
+ default=None,
+ type=float,
+ help="Weight quantization bit width. With --schemes, the average target bits for AutoScheme.",
+ )
group.add_argument(
"--group_size",
default=None,
@@ -145,13 +175,32 @@ def build_quantize_parser(*, prog: str = "auto_round quantize") -> argparse.Argu
help="Comma-separated algorithms such as 'awq' or 'awq,auto_round'.",
)
rt.add_argument("--output_dir", default="./tmp_autoround", type=str, help="Directory to save quantized artifacts.")
- rt.add_argument("--avg_bits", "--target_bits", default=None, type=float, help="Average target bits for AutoScheme.")
+ rt.add_argument(
+ "--schemes",
+ default=None,
+ type=str,
+ nargs="+",
+ help="Candidate quantization schemes for AutoScheme, e.g. 'W4A16,W8A16'. "
+ "Providing schemes enables AutoScheme; use --bits to set the average target bits.",
+ )
+ rt.add_argument(
+ "--avg_bits",
+ "--target_bits",
+ dest="bits",
+ default=None,
+ type=float,
+ help=argparse.SUPPRESS,
+ action=_LegacyAliasAction,
+ )
rt.add_argument(
"--options",
+ "--option",
+ dest="schemes",
default=None,
type=str,
nargs="+",
- help="AutoScheme options. Accepts comma-separated ('W4A16,W8A16') or space-separated (W4A16 W8A16).",
+ help=argparse.SUPPRESS,
+ action=_LegacyAliasAction,
)
rt.add_argument(
"--low_gpu_mem_usage", action="store_true", help="Enable memory-efficient mode by offloading features to CPU."
diff --git a/auto_round/scheme_entry.py b/auto_round/scheme_entry.py
new file mode 100644
index 000000000..3326454db
--- /dev/null
+++ b/auto_round/scheme_entry.py
@@ -0,0 +1,200 @@
+# 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.
+
+"""Entry-level scheme resolution layer.
+
+This module sits between the public entry points (``auto_round.AutoRound``,
+the CLI) and the core scheme parser (:func:`auto_round.schemes.parse_scheme`).
+It owns everything needed to turn user-facing scheme input — a single
+``scheme``, multiple ``schemes``, or the legacy ``options``/``avg_bits``
+kwargs — into the canonical scheme object the compressor pipeline consumes
+(``str`` / ``dict`` / ``QuantizationScheme`` / ``AutoScheme``), plus the
+routing preview/validation helpers the entry uses before a compressor exists.
+"""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Union
+
+from auto_round.logger import logger
+from auto_round.schemes import parse_scheme
+
+if TYPE_CHECKING:
+ from auto_round.auto_scheme.gen_auto_scheme import AutoScheme
+
+
+def collect_config_scheme_overrides(config) -> dict:
+ """Return the config's explicitly-set scheme fields as a ``{field: value}`` dict.
+
+ These are exactly the per-field overrides layered on top of ``scheme=`` — the
+ single mechanism through which ``bits`` / ``act_bits`` / ``data_type`` etc.
+ reach the resolved scheme. Fields left as ``None`` are omitted so the scheme's
+ own value wins.
+ """
+ return {k: getattr(config, k) for k in config._scheme_fields if getattr(config, k, None) is not None}
+
+
+def preview_resolved_attrs(config, scheme=None, format=None) -> dict:
+ """Resolve scheme attributes without mutating config, for routing decisions.
+
+ Called in ``AutoRound.__new__`` before the concrete compressor class is
+ chosen. ``SchemeMixin.resolve_scheme()`` will do the authoritative
+ resolution later; this is just a lightweight preview so routing logic
+ (``enable_imatrix``, ``needs_act_calib``, etc.) can use the correct values
+ even when the user specified only ``scheme=`` without explicit bit/dtype args.
+
+ This is the single source of resolved scheme fields for entry-level routing:
+ callers read from the returned dict and never re-read raw ``config`` attrs.
+ When the scheme cannot be previewed (``AutoScheme``, or a deferred parse
+ error), the config's own explicitly-set scheme overrides are returned so the
+ values still reflect what the user passed. ``format`` must match the
+ authoritative parse so format-scoped policies (e.g. the 8-bit asym rule)
+ resolve identically here and never turn a refusal into fabricated defaults.
+
+ Returns:
+ dict: resolved scheme attributes (config overrides when preview is skipped).
+ """
+ from auto_round.auto_scheme.gen_auto_scheme import AutoScheme
+
+ config_overrides = collect_config_scheme_overrides(config)
+ if isinstance(scheme, AutoScheme):
+ # AutoScheme needs model info — cannot preview; fall back to raw config attrs.
+ return config_overrides
+ try:
+ _, _, final_attrs = parse_scheme(scheme, config_overrides, format=format)
+ return final_attrs
+ except Exception as e:
+ logger.warning_once(
+ "Scheme preview failed (%s: %s); routing falls back to the config's explicit overrides.",
+ type(e).__name__,
+ e,
+ )
+ return config_overrides
+
+
+def eager_validate_scheme(config, scheme=None, format=None) -> None:
+ """Eagerly validate scheme/config constraints at construction time.
+
+ Mirrors the old-arch ``_check_configs()`` call in ``BaseCompressor.__init__``.
+ Raises ``ValueError`` or ``NotImplementedError`` immediately if the scheme
+ contains config-only invalid combinations (e.g. tuple group_size with non-fp8
+ weight dtype) so that callers get a fast failure rather than a deferred error
+ buried inside ``post_init()``.
+
+ ``AutoScheme`` is skipped because it requires model information.
+ """
+ from auto_round.auto_scheme.gen_auto_scheme import AutoScheme
+
+ if isinstance(scheme, AutoScheme):
+ return
+
+ user_overrides = collect_config_scheme_overrides(config)
+ try:
+ _, _, final_attrs = parse_scheme(scheme, user_overrides, format=format)
+ except (ValueError, NotImplementedError):
+ raise
+ except Exception:
+ return # Other parse errors are deferred to post_init
+
+ import copy
+
+ temp_config = copy.copy(config)
+ if hasattr(config, "scheme"):
+ temp_config.scheme = config.scheme.copy()
+ temp_config._user_set_scheme_fields = set(getattr(config, "_user_set_scheme_fields", set()))
+ for key, value in final_attrs.items():
+ setattr(temp_config, key, value)
+ temp_config.check_config() # raises ValueError / NotImplementedError if invalid
+
+
+def is_weight_scheme(scheme: Union[str, dict, object]) -> bool:
+ if isinstance(scheme, str):
+ return scheme.upper().startswith("W")
+ if isinstance(scheme, dict):
+ return all(isinstance(s, str) and s.upper().startswith("W") for s in scheme.values())
+ from auto_round.auto_scheme.gen_auto_scheme import AutoScheme
+
+ if isinstance(scheme, AutoScheme):
+ opts = scheme.options
+ if isinstance(opts, (list, tuple)):
+ return all(isinstance(s, str) and s.upper().startswith("W") for s in opts)
+ if isinstance(opts, str):
+ return opts.upper().startswith("W")
+ return False
+
+
+def is_gguf_k_target(value: Union[str, "AutoScheme", object]) -> bool:
+ from auto_round.auto_scheme.gen_auto_scheme import AutoScheme
+
+ if isinstance(value, str):
+ normalized = value.strip().lower()
+ return normalized.startswith("gguf:") and "_k" in normalized
+ if isinstance(value, AutoScheme):
+ opts = value.options
+ if isinstance(opts, str):
+ opts = [opts]
+ if isinstance(opts, (list, tuple)):
+ return any(isinstance(opt, str) and is_gguf_k_target(opt) for opt in opts)
+ return False
+
+
+def resolve_entry_scheme(scheme, schemes, direct_kwargs):
+ """Resolve the unified ``schemes``/``bits`` entry into an ``AutoScheme``.
+
+ ``AutoRound(model, schemes=("W4A16", "W8A16"), bits=4.2)`` is the
+ recommended AutoScheme entry: multiple schemes select the candidate
+ options and ``bits`` is the average target bits. The legacy ``options``
+ and ``avg_bits`` kwargs are still accepted for backward compatibility.
+
+ Returns ``(scheme, direct_kwargs)``; when ``schemes`` is given, ``scheme``
+ is replaced by an :class:`AutoScheme` and the consumed ``bits``/
+ ``shared_layers``/``ignore_scale_zp_bits`` are removed from
+ ``direct_kwargs`` so they no longer flow into the algorithm config.
+ """
+ legacy_options = direct_kwargs.pop("options", None)
+ legacy_avg_bits = direct_kwargs.pop("avg_bits", None)
+
+ if legacy_options is not None:
+ logger.warning_once("`options` is deprecated, please use `schemes` instead")
+ if schemes is not None:
+ raise ValueError("`schemes` and `options` cannot be used together, please use `schemes`")
+ schemes = legacy_options
+ if legacy_avg_bits is not None:
+ logger.warning_once("`avg_bits` is deprecated, please use `bits` instead")
+ if "bits" in direct_kwargs and direct_kwargs["bits"] is not None and direct_kwargs["bits"] != legacy_avg_bits:
+ raise ValueError("`bits` and `avg_bits` disagree, please use only `bits`")
+ direct_kwargs["bits"] = legacy_avg_bits
+
+ if schemes is None:
+ # Without schemes, `bits` is a plain weight bit width and must be an integer.
+ bits = direct_kwargs.get("bits")
+ if bits is not None and not float(bits).is_integer():
+ raise ValueError("`bits` must be an integer unless `schemes` is provided (AutoScheme average target bits)")
+ if bits is not None:
+ direct_kwargs["bits"] = int(bits)
+ return scheme, direct_kwargs
+
+ normalized_scheme = scheme.upper() if isinstance(scheme, str) else scheme
+ if normalized_scheme not in (None, "W4A16"):
+ raise ValueError("`scheme` and `schemes` are mutually exclusive, please pass only `schemes` for AutoScheme")
+ from auto_round.auto_scheme.gen_auto_scheme import AutoScheme
+
+ auto_scheme_kwargs = {}
+ bits = direct_kwargs.pop("bits", None)
+ if bits is not None:
+ auto_scheme_kwargs["avg_bits"] = bits
+ for key in ("shared_layers", "ignore_scale_zp_bits"):
+ if direct_kwargs.get(key) is not None:
+ auto_scheme_kwargs[key] = direct_kwargs.pop(key)
+ return AutoScheme(options=schemes, **auto_scheme_kwargs), direct_kwargs
diff --git a/docs/auto_scheme_acc.md b/docs/auto_scheme_acc.md
index 864de5c5e..bb5e46220 100644
--- a/docs/auto_scheme_acc.md
+++ b/docs/auto_scheme_acc.md
@@ -3,7 +3,7 @@
We tested with a fake model because the main branch currently has layer name mismatches between Transformers and GGUF.
~~~bash
-python3 -m auto_round Qwen/Qwen3-8B --options "gguf:q2_k_s,gguf:q4_k_s" --target_bits 3.5 --ignore_scale_zp_bits --iters 0 --format fake --output_dir "./test_gguf"
+python3 -m auto_round Qwen/Qwen3-8B --schemes "gguf:q2_k_s,gguf:q4_k_s" --bits 3.5 --ignore_scale_zp_bits --iters 0 --format fake --output_dir "./test_gguf"
~~~
diff --git a/docs/step_by_step.md b/docs/step_by_step.md
index d8221a92c..f2c62a93e 100755
--- a/docs/step_by_step.md
+++ b/docs/step_by_step.md
@@ -174,7 +174,7 @@ adopted within the community, **only 4-bits quantization is supported**. Please
**MLX Format**[Experimental Feature]: This format targets Apple Silicon (M1/M2/M3/...) and is loaded directly by [`mlx-lm`](https://github.com/ml-explore/mlx-lm) (text-only LLM) or [`mlx-vlm`](https://github.com/Blaizzy/mlx-vlm) (vision/audio + language).
- Supports **2, 3, 4, 5, 6, 8 bits** (5/6 bits are MLX-exclusive — GPTQ/AWQ have no standard packing for them).
-- Native **mixed-bit / mixed-group_size** via `layer_config` or AutoScheme (`--target_bits 3.5 --options "..."`);
+- Native **mixed-bit / mixed-group_size** via `layer_config` or AutoScheme (`--schemes "..." --bits 3.5`);
- Use `--format mlx` for a native MLX checkpoint; use `--format auto_round:mlx` if you want HuggingFace `transformers` + AutoRound to load it (post-init repacks each layer into MLX `QuantLinear` on Darwin).
- Limitation: embedding layer quantization has not supported
#### Format and scheme support matrix
@@ -489,11 +489,13 @@ We recommend exporting to the llm_compressor format for now, as it can be easily
- **`--iters 0`**: RTN. Fast (seconds to minutes).
- **`--iters 200`**: Tuning-aware scheme selection. More accurate but much slower.
+Providing multiple `--schemes` enables AutoScheme; `--bits` is then the average target bits.
+
~~~bash
auto_round \
--model_name $model_name \
- --avg_bits 6 \
- --options "mxfp4,mxfp8" \
+ --schemes "mxfp4,mxfp8" \
+ --bits 6 \
--ignore_scale_zp_bits \
--iters 0 \
--format fake
@@ -501,16 +503,14 @@ auto_round \
#### API Usage
~~~
-avg_bits= 3.0
-scheme = AutoScheme(avg_bits=avg_bits, options=("W2A16G64", "W4A16", "W8A16"))
-ar = AutoRound(model=model_name, scheme=scheme, iters=0, nsamples=1)
+ar = AutoRound(model=model_name, schemes=("W2A16G64", "W4A16", "W8A16"), bits=3.0, iters=0, nsamples=1)
ar.quantize_and_save()
~~~
#### Hyperparameters in AutoScheme
-`avg_bits(float)` Target average bits for the whole model; only layers to be quantized will be counted in the average bits calculation.
+`bits(float)` Target average bits for the whole model; only layers to be quantized will be counted in the average bits calculation. Without `schemes`, `bits` is the plain weight bit width and must be an integer.
-`options(Union[str, list[Union[QuantizationScheme, str]])` the options of quantization schemes to choose from. It could be a string like "W4A16", or a list of strings or QuantizationScheme objects.
+`schemes(Union[str, list[Union[QuantizationScheme, str]])` the candidate quantization schemes to choose from, e.g. a string like "W4A16,W8A16", or a list of strings or QuantizationScheme objects. Providing schemes enables AutoScheme.
`ignore_scale_zp_bits(bool)` Whether to ignore the bits of scale and zero point in average bits calculation. Default is False.
@@ -528,30 +528,33 @@ In some serving frameworks, certain layers (e.g., QKV or MoE) are fused to accel
```python
-from auto_round import AutoRound, AutoScheme
+from auto_round import AutoRound
shared_layers = [
["*.self_attn.k_proj", "v_proj", "q_proj", "out_proj"],
("model.decoder.layers.6.fc1", "model.decoder.layers.6.fc2"),
("fc1", "fc2"),
]
-target_bits = 5.0
model_name = "Qwen/Qwen3-0.6B"
-scheme = AutoScheme(avg_bits=target_bits, options=("W4A16", "MXFP8"), shared_layers=shared_layers)
-ar = AutoRound(model=model_name, scheme=scheme, iters=0, nsamples=1)
+ar = AutoRound(model=model_name, schemes=("W4A16", "MXFP8"), bits=5.0, shared_layers=shared_layers, iters=0, nsamples=1)
model, layer_config = ar.quantize()
```
Besides, if you want to fix the scheme for some layers, you could set it via `layer_config` in AutoRound API.
```python
-from auto_round import AutoRound, AutoScheme
+from auto_round import AutoRound
model_name = "Qwen/Qwen3-8B"
-avg_bits = 3.0
-scheme = AutoScheme(avg_bits=avg_bits, options=("GGUF:Q2_K_S", "GGUF:Q4_K_S"), ignore_scale_zp_bits=True)
layer_config = {"lm_head": "GGUF:Q6_K"}
-ar = AutoRound(model=model_name, scheme=scheme, layer_config=layer_config, iters=0)
+ar = AutoRound(
+ model=model_name,
+ schemes=("GGUF:Q2_K_S", "GGUF:Q4_K_S"),
+ bits=3.0,
+ ignore_scale_zp_bits=True,
+ layer_config=layer_config,
+ iters=0,
+)
ar.quantize_and_save()
```
diff --git a/docs/step_by_step_CN.md b/docs/step_by_step_CN.md
index 4dced5f01..df4e660e1 100755
--- a/docs/step_by_step_CN.md
+++ b/docs/step_by_step_CN.md
@@ -161,7 +161,7 @@ AutoRound 支持多种量化配置:
**MLX 格式(实验性功能)**:面向 Apple Silicon (M1/M2/M3/...),可直接被 [`mlx-lm`](https://github.com/ml-explore/mlx-lm)(纯文本 LLM)或 [`mlx-vlm`](https://github.com/Blaizzy/mlx-vlm)(多模态 VLM)加载推理。
- 支持 **2、3、4、5、6、8 bits**(其中 5/6 bits 是 MLX 独有,GPTQ/AWQ 没有标准打包格式)。
-- 原生支持 **混合 bit / 混合 group_size**:通过 `layer_config` 或 AutoScheme(如 `--target_bits 3.5 --options "..."`),按层覆盖会写入 `config.json["quantization"]`,
+- 原生支持 **混合 bit / 混合 group_size**:通过 `layer_config` 或 AutoScheme(如 `--schemes "..." --bits 3.5`),按层覆盖会写入 `config.json["quantization"]`,
- `--format mlx` 导出原生 MLX checkpoint;`--format auto_round:mlx` 则让 HuggingFace `transformers` + AutoRound 加载它(在 Darwin 上 post-init 会把每层重新打包成 MLX 的 `QuantLinear`)。
- 已经问题: 没有支持嵌入层的量化
@@ -481,11 +481,13 @@ AutoScheme 自动生成自适应的混合比特/混合数据类型量化方案
- **`--iters 0`**:基于 RTN 的 量化方案,速度快(秒到分钟级)。
- **`--iters 200`**:调优感知的量化方案,更精确但慢很多。
+传入多个 `--schemes` 即启用 AutoScheme;此时 `--bits` 为目标平均 bits。
+
~~~bash
auto_round \
--model_name $model_name \
- --avg_bits 6 \
- --options "mxfp4,mxfp8" \
+ --schemes "mxfp4,mxfp8" \
+ --bits 6 \
--ignore_scale_zp_bits \
--iters 0 \
--format fake
@@ -493,17 +495,15 @@ auto_round \
#### API 用法
~~~python
-avg_bits= 3.0
-scheme = AutoScheme(avg_bits=avg_bits, options=("W2A16G64", "W4A16","W8A16"))
-ar = AutoRound(model=model_name, scheme=scheme, iters=0, nsamples=1)
+ar = AutoRound(model=model_name, schemes=("W2A16G64", "W4A16","W8A16"), bits=3.0, iters=0, nsamples=1)
ar.quantize_and_save()
~~~
#### AutoScheme 超参数说明
-`avg_bits(float)`:模型整体的目标平均 bits;计算时仅计入待量化的层。
+`bits(float)`:模型整体的目标平均 bits;计算时仅计入待量化的层。未提供 `schemes` 时,`bits` 为普通权重量化位宽,必须为整数。
-`options(Union[str, list[Union[QuantizationScheme, str]]])`:候选量化配置集合。支持以下表示形式:单个用逗号分隔的字符串(例如 `"W4A16,W2A16"`​)、字符串列表(例如 `["W4A16", "W2A16"]`​)和 `QuantizationScheme` 。
+`schemes(Union[str, list[Union[QuantizationScheme, str]]])`:候选量化配置集合。支持以下表示形式:单个用逗号分隔的字符串(例如 `"W4A16,W2A16"`​)、字符串列表(例如 `["W4A16", "W2A16"]`​)和 `QuantizationScheme` 。传入 `schemes` 即启用 AutoScheme。
`ignore_scale_zp_bits(bool)`:仅支持 API 调用场景。用于决定在计算平均 bit 时,是否忽略 scale 与 zero-point 的位数(默认 `False`)。
@@ -521,30 +521,33 @@ ar.quantize_and_save()
示例代码如下:
```python
-from auto_round import AutoRound, AutoScheme
+from auto_round import AutoRound
shared_layers = [
["*.self_attn.k_proj", "v_proj", "q_proj", "out_proj"],
("model.decoder.layers.6.fc1", "model.decoder.layers.6.fc2"),
("fc1", "fc2"),
]
-target_bits = 5.0
model_name = "Qwen/Qwen3-0.6B"
-scheme = AutoScheme(avg_bits=target_bits, options=("W4A16", "MXFP8"), shared_layers=shared_layers)
-ar = AutoRound(model=model_name, scheme=scheme, iters=0, nsamples=1)
+ar = AutoRound(model=model_name, schemes=("W4A16", "MXFP8"), bits=5.0, shared_layers=shared_layers, iters=0, nsamples=1)
model, layer_config = ar.quantize()
```
此外,若需为特定的层固定量化方案,可使用 AutoRound API 中的`layer_config`参数,用法示例如下:
```python
-from auto_round import AutoRound, AutoScheme
+from auto_round import AutoRound
model_name = "Qwen/Qwen3-8B"
-avg_bits = 3.0
-scheme = AutoScheme(avg_bits=avg_bits, options=("GGUF:Q2_K_S", "GGUF:Q4_K_S"), ignore_scale_zp_bits=True)
layer_config = {"lm_head": "GGUF:Q6_K"}
-ar = AutoRound(model=model_name, scheme=scheme, layer_config=layer_config, iters=0)
+ar = AutoRound(
+ model=model_name,
+ schemes=("GGUF:Q2_K_S", "GGUF:Q4_K_S"),
+ bits=3.0,
+ ignore_scale_zp_bits=True,
+ layer_config=layer_config,
+ iters=0,
+)
ar.quantize_and_save()
```
diff --git a/test/unit/common/core/test_entry_scheme_unification.py b/test/unit/common/core/test_entry_scheme_unification.py
index 1fed25a84..e77de82e5 100644
--- a/test/unit/common/core/test_entry_scheme_unification.py
+++ b/test/unit/common/core/test_entry_scheme_unification.py
@@ -12,24 +12,105 @@
# See the License for the specific language governing permissions and
# limitations under the License.
"""Entry-layer scheme unification: routing decisions in ``entry.py`` read scheme
-fields from a single resolved-scheme source (``_preview_resolved_attrs``) rather
+fields from a single resolved-scheme source (``preview_resolved_attrs``) rather
than double-reading raw config attrs. These lock that the resolved values — and
the resulting compressor-class routing — are identical whether the user passes
``scheme=`` alone or the equivalent bit/dtype overrides on the alg config.
"""
+import pytest
+
from auto_round.algorithms.quantization.rtn.config import OptimizedRTNConfig, RTNConfig
-from auto_round.autoround import (
- _collect_config_scheme_overrides,
- _preview_resolved_attrs,
- _select_rtn_compressor_base_cls,
-)
+from auto_round.auto_scheme.gen_auto_scheme import AutoScheme
+from auto_round.autoround import _select_rtn_compressor_base_cls
from auto_round.compressors.orchestrator import CompressionOrchestrator
+from auto_round.scheme_entry import (
+ collect_config_scheme_overrides,
+ preview_resolved_attrs,
+ resolve_entry_scheme,
+)
+
+
+def test_schemes_and_bits_build_auto_scheme():
+ """schemes= + bits= select AutoScheme options and the average target bits."""
+ scheme, kwargs = resolve_entry_scheme("W4A16", ("W4A16", "W8A16"), {"bits": 4.2})
+ assert isinstance(scheme, AutoScheme)
+ assert scheme.options == ["W4A16", "W8A16"]
+ assert scheme.avg_bits == 4.2
+ assert "bits" not in kwargs # consumed as the AutoScheme target, not a scheme override
+
+
+def test_auto_scheme_threads_aux_kwargs():
+ """shared_layers/ignore_scale_zp_bits are consumed by the AutoScheme."""
+ scheme, kwargs = resolve_entry_scheme(
+ "W4A16", ("W4A16", "W8A16"), {"bits": 5.0, "shared_layers": [["a", "b"]], "ignore_scale_zp_bits": True}
+ )
+ assert scheme.shared_layers == [["a", "b"]]
+ assert scheme.ignore_scale_zp_bits is True
+ assert "shared_layers" not in kwargs and "ignore_scale_zp_bits" not in kwargs
+
+
+def test_schemes_mixed_string_and_scheme_object():
+ """schemes may mix preset names and QuantizationScheme instances."""
+ from auto_round.schemes import QuantizationScheme
+
+ obj = QuantizationScheme.from_dict({"bits": 4, "group_size": 64, "sym": True, "data_type": "int"})
+ scheme, kwargs = resolve_entry_scheme("W4A16", ("W4A16", obj), {"bits": 4.5})
+ assert isinstance(scheme, AutoScheme)
+ assert scheme.options == ["W4A16", obj]
+ assert scheme.avg_bits == 4.5
+ assert "bits" not in kwargs
+
+
+def test_group_size_override_applies_to_all_schemes():
+ """schemes= + group_size=32 overrides every candidate scheme's group_size."""
+ from auto_round.schemes import parse_scheme
+
+ scheme, kwargs = resolve_entry_scheme("W4A16", ("W4A16", "W8A16"), {"bits": 4.5, "group_size": 32})
+ # group_size stays a config override (it is not an AutoScheme field); the
+ # authoritative parse then applies it across every candidate option.
+ assert kwargs == {"group_size": 32}
+ overrides = collect_config_scheme_overrides(RTNConfig(group_size=32))
+ _, is_auto_scheme, _ = parse_scheme(scheme, overrides)
+ assert is_auto_scheme
+ for option in scheme.options:
+ assert option.group_size == 32
+
+
+def test_legacy_options_avg_bits_still_resolve():
+ """options=/avg_bits= remain accepted and map to schemes/bits."""
+ scheme, kwargs = resolve_entry_scheme("W4A16", None, {"options": ("W4A16", "W8A16"), "avg_bits": 4.0})
+ assert isinstance(scheme, AutoScheme)
+ assert scheme.options == ["W4A16", "W8A16"]
+ assert scheme.avg_bits == 4.0
+ assert "options" not in kwargs and "avg_bits" not in kwargs
+
+
+def test_bits_without_schemes_coerces_integral_float():
+ """bits=8.0 without schemes stays a plain integer weight bit override."""
+ scheme, kwargs = resolve_entry_scheme("W4A16", None, {"bits": 8.0, "group_size": 128})
+ assert scheme == "W4A16"
+ assert kwargs == {"bits": 8, "group_size": 128}
+
+
+def test_scheme_and_schemes_are_mutually_exclusive():
+ with pytest.raises(ValueError, match="mutually exclusive"):
+ resolve_entry_scheme("W8A16", ("W4A16", "W8A16"), {})
+
+
+def test_fractional_bits_requires_schemes():
+ with pytest.raises(ValueError, match="must be an integer"):
+ resolve_entry_scheme("W4A16", None, {"bits": 4.2})
+
+
+def test_schemes_and_options_conflict():
+ with pytest.raises(ValueError, match="cannot be used together"):
+ resolve_entry_scheme("W4A16", ("W4A16", "W8A16"), {"options": ("W4A16", "W8A16")})
def test_collect_config_scheme_overrides_omits_unset_fields():
cfg = RTNConfig(bits=8, data_type="int")
- overrides = _collect_config_scheme_overrides(cfg)
+ overrides = collect_config_scheme_overrides(cfg)
assert overrides["bits"] == 8
assert overrides["data_type"] == "int"
# Unset scheme fields must not appear (scheme's own value should win).
@@ -39,8 +120,8 @@ def test_collect_config_scheme_overrides_omits_unset_fields():
def test_preview_resolves_scheme_only_and_override_to_same_attrs():
# scheme="W8A16" vs bits=8 override on top of a W-generic scheme must resolve
# to the same bits/data_type for routing.
- from_scheme = _preview_resolved_attrs(RTNConfig(), "W8A16")
- from_override = _preview_resolved_attrs(RTNConfig(bits=8), "W8A16")
+ from_scheme = preview_resolved_attrs(RTNConfig(), "W8A16")
+ from_override = preview_resolved_attrs(RTNConfig(bits=8), "W8A16")
assert from_scheme.get("bits") == from_override.get("bits") == 8
@@ -53,7 +134,7 @@ def test_preview_threads_output_format_for_w8_asym(monkeypatch):
# whose defaults fabricate a W4/g128 scheme from a W8A16 request.
monkeypatch.delenv("AR_ALLOW_W8_ASYM", raising=False)
cfg = RTNConfig(sym=False)
- resolved = _preview_resolved_attrs(cfg, "W8A16", format="auto_round:llm_compressor")
+ resolved = preview_resolved_attrs(cfg, "W8A16", format="auto_round:llm_compressor")
assert resolved.get("bits") == 8
assert resolved.get("sym") is False
@@ -63,7 +144,7 @@ def test_route_scheme_not_fabricated_from_defaults_for_w8_asym_llmc(monkeypatch)
monkeypatch.delenv("AR_ALLOW_W8_ASYM", raising=False)
cfg = RTNConfig(sym=False)
- resolved = _preview_resolved_attrs(cfg, "W8A16", format="auto_round:llm_compressor")
+ resolved = preview_resolved_attrs(cfg, "W8A16", format="auto_round:llm_compressor")
scheme_obj = QuantizationScheme.from_dict(resolved)
assert scheme_obj.bits == 8
assert scheme_obj.sym is False
@@ -75,7 +156,7 @@ def test_preview_degrades_to_overrides_for_w8_asym_native_format(monkeypatch):
# see the format); it must never fabricate bits.
monkeypatch.delenv("AR_ALLOW_W8_ASYM", raising=False)
cfg = RTNConfig(sym=False)
- resolved = _preview_resolved_attrs(cfg, "W8A16", format="auto_round")
+ resolved = preview_resolved_attrs(cfg, "W8A16", format="auto_round")
assert resolved.get("bits") is None
assert resolved.get("sym") is False
@@ -84,13 +165,13 @@ def test_preview_falls_back_to_config_overrides_when_preview_skipped(monkeypatch
# An unknown scheme string makes parse_scheme raise; the resolver must then
# surface the config's explicit overrides (not an empty dict) so routing still
# sees the user's bits. The degradation must also be logged, never silent.
- import auto_round.autoround as entry_mod
+ import auto_round.scheme_entry as scheme_entry_mod
calls = []
- monkeypatch.setattr(entry_mod.logger, "warning_once", lambda *a, **k: calls.append(a))
+ monkeypatch.setattr(scheme_entry_mod.logger, "warning_once", lambda *a, **k: calls.append(a))
cfg = RTNConfig(bits=4, data_type="int")
- resolved = _preview_resolved_attrs(cfg, "definitely-not-a-real-scheme-xyz")
+ resolved = preview_resolved_attrs(cfg, "definitely-not-a-real-scheme-xyz")
assert resolved.get("bits") == 4
assert resolved.get("data_type") == "int"
assert len(calls) == 1
diff --git a/test/unit/common/utils/test_cli_usage.py b/test/unit/common/utils/test_cli_usage.py
index 39ab04796..4675d2bc8 100644
--- a/test/unit/common/utils/test_cli_usage.py
+++ b/test/unit/common/utils/test_cli_usage.py
@@ -584,13 +584,6 @@ def test_svdquant_cli_defaults_compose_before_signround():
assert isinstance(configs[1], SignRoundConfig)
-def _normalize_options(raw):
- if raw is None:
- return None
- flat = ",".join(raw)
- return ",".join(p.strip() for p in flat.split(",") if p.strip())
-
-
def _normalize_shared_layers(raw):
if raw is None:
return None
@@ -608,14 +601,45 @@ def _normalize_shared_layers(raw):
return normalized_groups or None
-def test_options_comma_space_separated():
- """--options accepts comma-separated and space-separated values."""
+def test_schemes_comma_space_separated():
+ """--schemes accepts comma-separated and space-separated values."""
+ from auto_round.cli.main import _normalize_scheme_list
+ from auto_round.cli.parser import build_quantize_parser
+
+ p = build_quantize_parser()
+ assert _normalize_scheme_list(p.parse_args(["--bits", "4", "--schemes", "W4A16,W8A16"]).schemes) == "W4A16,W8A16"
+ assert _normalize_scheme_list(p.parse_args(["--bits", "4", "--schemes", "W4A16", "W8A16"]).schemes) == "W4A16,W8A16"
+ assert p.parse_args(["--model", "dummy"]).schemes is None
+
+
+def test_legacy_auto_scheme_flags_alias_and_hidden():
+ """--options/--avg_bits/--target_bits alias --schemes/--bits but are hidden from --help."""
+ import io
+
+ from auto_round.cli.main import _normalize_scheme_list
from auto_round.cli.parser import build_quantize_parser
p = build_quantize_parser()
- assert _normalize_options(p.parse_args(["--avg_bits", "4", "--options", "W4A16,W8A16"]).options) == "W4A16,W8A16"
- assert _normalize_options(p.parse_args(["--avg_bits", "4", "--options", "W4A16", "W8A16"]).options) == "W4A16,W8A16"
- assert p.parse_args(["--model", "dummy"]).options is None
+ # legacy flags store into the canonical dests (bits / schemes)
+ args = p.parse_args(["--avg_bits", "4", "--options", "W4A16,W8A16"])
+ assert args.bits == 4.0
+ assert _normalize_scheme_list(args.schemes) == "W4A16,W8A16"
+ args = p.parse_args(["--target_bits", "3.5", "--option", "W2A16", "W4A16"])
+ assert args.bits == 3.5
+ assert _normalize_scheme_list(args.schemes) == "W2A16,W4A16"
+ # singular aliases
+ assert p.parse_args(["--bit", "8"]).bits == 8.0
+
+ help_text = io.StringIO()
+ import contextlib
+
+ with contextlib.redirect_stdout(help_text):
+ p.print_help()
+ help_text = help_text.getvalue()
+ for flag in ("--options", "--option", "--avg_bits", "--target_bits"):
+ assert flag not in help_text
+ for flag in ("--schemes", "--bits", "--bit"):
+ assert flag in help_text
def test_shared_layers_normalize():
diff --git a/test/unit/test_cuda/algorithms/test_alg_ext.py b/test/unit/test_cuda/algorithms/test_alg_ext.py
index 996d9f0df..936e1522d 100644
--- a/test/unit/test_cuda/algorithms/test_alg_ext.py
+++ b/test/unit/test_cuda/algorithms/test_alg_ext.py
@@ -142,13 +142,13 @@ class TestAlgExt:
python_path = sys.executable
res = os.system(
- f"PYTHONPATH='{AUTO_ROUND_PATH}:$PYTHONPATH' CUDA_VISIBLE_DEVICES=0 {python_path} -m auto_round --model {tiny_opt_model_path} --iters 1 --device auto --enable_alg_ext --disable_minmax_tuning --disable_quanted_input --avg_bits 2 --options=W2A16,W4A16 --ignore_scale_zp_bits --nsamples 1 --seqlen 32"
+ f"PYTHONPATH='{AUTO_ROUND_PATH}:$PYTHONPATH' CUDA_VISIBLE_DEVICES=0 {python_path} -m auto_round --model {tiny_opt_model_path} --iters 1 --device auto --enable_alg_ext --disable_minmax_tuning --disable_quanted_input --bits 2 --schemes=W2A16,W4A16 --ignore_scale_zp_bits --nsamples 1 --seqlen 32"
)
if res > 0 or res == -1:
assert False, "cmd line test fail, please have a check"
res = os.system(
- f"PYTHONPATH='{AUTO_ROUND_PATH}:$PYTHONPATH' CUDA_VISIBLE_DEVICES=0 {python_path} -m auto_round --model {tiny_opt_model_path} --iters 1 --device auto --enable_alg_ext --avg_bits 5.5 --options=mxfp4,mxfp8 --ignore_scale_zp_bits --enable_torch_compile --nsamples 1 --seqlen 32"
+ f"PYTHONPATH='{AUTO_ROUND_PATH}:$PYTHONPATH' CUDA_VISIBLE_DEVICES=0 {python_path} -m auto_round --model {tiny_opt_model_path} --iters 1 --device auto --enable_alg_ext --bits 5.5 --schemes=mxfp4,mxfp8 --ignore_scale_zp_bits --enable_torch_compile --nsamples 1 --seqlen 32"
)
if res > 0 or res == -1:
assert False, "cmd line test fail, please have a check"