PTQ-Level Efficiency, QAT-Level Accuracy | 训练后量化的效率,量化感知训练的精度
support for recipes such as ar-best ar-light (#2547)
Heng Guo8869842f9741
diff --git a/README.md b/README.mdindex cc8b6f04e..c728c45cb 100644--- a/README.md+++ b/README.md@@ -108,6 +108,8 @@ Out-of-the-box quantization for 10+ vision-language models [example models](http✅ **Multiple Recipes**Choose from `auto-round-best`, `auto-round`, `auto-round-light`, `auto-round-opt-rtn` (optimized RTN) and `auto-round-rtn` (pure RTN, fastest baseline) to suit your needs. Details are shown in [quantization recipes](https://github.com/intel/auto-round/blob/main/docs/step_by_step.md#recipe-recommendation)+Use the same plans in Python with `AutoRound(..., recipe="auto-round-best")` or in the CLI with `--recipe auto-round-best`. Omitting the recipe selects `auto-round`; legacy commands remain shortcuts. See [built-in recipes and overrides](./docs/recipes.md).+✅ Advanced UtilitiesIncludes [multiple gpus quantization](https://github.com/intel/auto-round/blob/main/docs/step_by_step.md#devicemulti-gpu-setting-in-quantization), [multiple calibration datasets](https://github.com/intel/auto-round/blob/main/docs/step_by_step.md#default-dataset) and support for [10+ runtime backends](https://github.com/intel/auto-round/blob/main/docs/step_by_step.md#specify-inference-backend).diff --git a/README_CN.md b/README_CN.mdindex 83a940623..d303e0d13 100644--- a/README_CN.md+++ b/README_CN.md@@ -119,6 +119,8 @@ AutoRound 旨在以合理的量化成本在低比特场景下实现出色的精✅ **多种量化方案可选** 提供 `auto-round-best`、`auto-round`、`auto-round-light`、`auto-round-opt-rtn`(优化版 RTN)以及 `auto-round-rtn`(原始 RTN,最快基线)等多种预设方案,能够满足多样化需求。详见:[量化方案](https://github.com/intel/auto-round/blob/main/docs/step_by_step.md#recipe-recommendation)+Python 可通过 `AutoRound(..., recipe="auto-round-best")` 使用同一方案,CLI 可使用 `--recipe auto-round-best`。不传 recipe 默认选择 `auto-round`,已有命令保留为快捷入口。详见[内置 Recipe 与覆盖规则](./docs/recipes_CN.md)。+✅ **实用额外特性** 支持[多 GPU 量化](https://github.com/intel/auto-round/blob/main/docs/step_by_step.md#devicemulti-gpu-setting-in-quantization)和[多标定数据集](https://github.com/intel/auto-round/blob/main/docs/step_by_step.md#default-dataset),并兼容[十余种推理后端](https://github.com/intel/auto-round/blob/main/docs/step_by_step.md#specify-inference-backend)。✅ **不局限于权重量化** 我们正积极扩展对 **MXFP、NVFP、W8A8** 等更多数据类型的支持。diff --git a/auto_round/autoround.py b/auto_round/autoround.pyindex 457e16453..6442f9fc5 100644--- a/auto_round/autoround.py+++ b/auto_round/autoround.py@@ -21,6 +21,9 @@ from typing import TYPE_CHECKING, Any, Optional, Unionimport torchfrom auto_round.logger import deprecated, logger+from auto_round.recipes import Recipe, get_recipe, resolve_recipe+from auto_round.recipes.recipe import UNSET+from auto_round.recipes.resolver import merge_layer_defaultsfrom auto_round.scheme_entry import (collect_config_scheme_overrides,eager_validate_scheme,@@ -756,6 +759,8 @@ class AutoRound:alg_configs: Algorithm alias, config instance, or sequence of either.Use config instances to provide algorithm-specific options, suchas ``SignRoundConfig(iters=50)`` or ``AWQConfig(apply_clip=True)``.+ recipe: Recommended quantization plan, defaulting to ``"auto-round"``.+ Explicit alg_configs replaces its pipeline while inheriting calibration defaults.layer_config: Optional per-layer quantization overrides.dataset: Calibration dataset name, samples, dataloader, or a:class:`~auto_round.utils.dataset_utils.CalibDataset` object.@@ -788,11 +793,11 @@ class AutoRound:schemes: str | list | tuple | None = None,bits: float | None = None,layer_config: dict[str, str | dict | QuantizationScheme] | None = None,- dataset: str | list | tuple | torch.utils.data.DataLoader | None = None,+ dataset: str | list | tuple | torch.utils.data.DataLoader | None = UNSET,iters: int | None = None,- seqlen: int = 2048,- nsamples: int = 128,- batch_size: int = 8,+ seqlen: int = UNSET,+ nsamples: int = UNSET,+ batch_size: int = UNSET,gradient_accumulate_steps: int | None = None,low_gpu_mem_usage: bool = False,calibration_data_device: str = "auto",@@ -802,6 +807,7 @@ class AutoRound:low_cpu_mem_usage: bool = True,alg_configs=None,algorithm: str | None = None,+ recipe: str | Recipe = "auto-round",**kwargs,) -> BaseCompressor:direct_kwargs = dict(kwargs)@@ -821,10 +827,27 @@ class AutoRound:direct_kwargs["bits"] = bitsscheme, direct_kwargs = resolve_entry_scheme(scheme, schemes, direct_kwargs)+ definition = get_recipe(recipe) if isinstance(recipe, str) else recipe+ plan = resolve_recipe(+ definition,+ scheme=scheme,+ model=model,+ trust_remote_code=direct_kwargs.get("trust_remote_code", True),+ )+ if alg_configs is None and algorithm is None:+ alg_configs = plan.build_configs()+ calibration = plan.calibration+ dataset = calibration.get("dataset") if dataset is UNSET else dataset+ seqlen = calibration["seqlen"] if seqlen is UNSET else seqlen+ nsamples = calibration["nsamples"] if nsamples is UNSET else nsamples+ batch_size = calibration["batch_size"] if batch_size is UNSET else batch_size+ if plan.layer_config:+ layer_config = merge_layer_defaults(plan.layer_config, layer_config)+configs, runtime_kwargs = _prepare_entry_kwargs(alg_configs, direct_kwargs, strict=strict_model_free)runtime_kwargs["batch_size"] = batch_size- return _CompressorBuilder(+ compressor = _CompressorBuilder(model,scheme,configs,@@ -844,6 +867,8 @@ class AutoRound:seqlen=seqlen,**runtime_kwargs,)+ compressor.resolved_recipe = plan+ return compressor# Keep legacy entry points available for downstream integrations such asdiff --git a/auto_round/cli/algorithms.py b/auto_round/cli/algorithms.pyindex e6e27dc74..8fb3392ba 100644--- a/auto_round/cli/algorithms.py+++ b/auto_round/cli/algorithms.py@@ -285,6 +285,39 @@ class AlgorithmHandler:@classmethoddef build_configs(cls, args, common_kwargs: dict[str, Any]) -> list:+ plan = getattr(args, "_recipe_plan", None)+ if plan is not None and getattr(args, "algorithm", None) is None:+ from auto_round.autoround import _normalize_alg_configs++ configs = []+ explicit = args._explicit_fields+ for stage, default_config in zip(plan.pipeline, plan.build_configs()):+ registry = _parameter_registry(type(default_config))+ overrides = {+ parameter.field: getattr(args, parameter.dest)+ for parameter in registry.parameters+ if parameter.dest in explicit and hasattr(args, parameter.dest)+ }+ if getattr(type(default_config), "cli_include_common_args", True):+ overrides.update({key: value for key, value in common_kwargs.items() if value is not None})+ configs.append(stage.build_config(overrides))+ direct = {"iters": args.iters} if "iters" in explicit else {}+ if direct.get("iters") == 0:+ rtn_cls = cls.get("rtn")+ direct.update(+ {+ parameter.field: getattr(args, parameter.dest)+ for parameter in _parameter_registry(rtn_cls).parameters+ if parameter.dest in explicit and hasattr(args, parameter.dest)+ }+ )+ if "disable_opt_rtn" in explicit:+ direct["disable_opt_rtn"] = args.disable_opt_rtn+ if getattr(args, "rotation_hadamard_type", None):+ rotation_cls = cls.get("hadamard")+ configs.append(rotation_cls(**_parameter_registry(rotation_cls).config_kwargs(args)))+ return _normalize_alg_configs(configs, direct)+raw = getattr(args, "algorithm", None) or ""names = [name.strip().lower() for name in raw.split(",") if name.strip()]diff --git a/auto_round/cli/main.py b/auto_round/cli/main.pyindex 96fdc9011..1e8b1678a 100644--- a/auto_round/cli/main.py+++ b/auto_round/cli/main.py@@ -1,7 +1,7 @@# # Copyright (C) 2026 Intel Corporation# # SPDX-License-Identifier: Apache-2.0-"""CLI entry points: command routing, RECIPES, tune, eval, list.+"""CLI entry points: command routing, recipes, tune, eval, list.This module is the single place that wires together:parser.py - argparse construction (all flag declarations here)@@ -26,6 +26,7 @@ from auto_round.cli.parser import ()from auto_round.compressors.config_resolution import ConfigResolutionErrorfrom auto_round.logger import logger+from auto_round.recipes import get_recipe, list_recipes, resolve_recipe# Flags surfaced by `auto_round --help`. Entries are (dest, shown option strings):# the overview is a curated subset, so a few flags list only their primary name@@ -243,32 +244,6 @@ def _to_autoround_kwargs(args, *, low_cpu_mem_usage, enable_torch_compile, layerreturn kwargs-RECIPES = {- "default": {- "batch_size": 8,- "iters": 200,- "seqlen": 2048,- "nsamples": 128,- "lr": None,- },- "best": {- "batch_size": 8,- "iters": 1000,- "seqlen": 2048,- "nsamples": 512,- "lr": None,- },- "light": {- "batch_size": 8,- "iters": 50,- "seqlen": 2048,- "nsamples": 128,- "lr": 5e-3,- },- "rtn": {"batch_size": 8, "iters": 0, "seqlen": 2048, "nsamples": 1, "lr": None, "disable_opt_rtn": True},- "opt_rtn": {"batch_size": 8, "iters": 0, "seqlen": 2048, "nsamples": 128, "lr": None, "disable_opt_rtn": False},-}-# ============================================================================# list subcommand# ============================================================================@@ -288,6 +263,14 @@ def list_item(argv=None):print("AutoRound supported algorithms:")print(AlgorithmHandler.format_listing())print("\nUse `auto_round list alg <name>` or `auto_round --algorithm <name> --help` for details.")+ elif args.item in {"recipe", "recipes"}:+ for name in [args.name] if args.name else list_recipes():+ definition = get_recipe(name)+ print(f"{definition.name}: {definition.description}")+ if args.name:+ plan = resolve_recipe(definition)+ print("Pipeline: " + " -> ".join(f"{stage.algorithm}({stage.params})" for stage in plan.pipeline))+ print(f"Calibration: {plan.calibration}")else:raise ValueError(f"Unsupported list target: {args.item}")@@ -351,11 +334,10 @@ def _print_algorithm_help(argv: list[str]) -> bool:return True-def start(recipe="default", argv=None):+def start(recipe="auto-round", argv=None):from auto_round.utils.oom import install_oom_census_hookinstall_oom_census_hook() # last-resort tensor census for uncaught CUDA OOMs- recipe_defaults = RECIPES[recipe]argv = list(sys.argv[1:] if argv is None else argv)format_was_explicit = any(arg in {"--format", "--formats"} or arg.startswith(("--format=", "--formats=")) for arg in argv@@ -367,18 +349,46 @@ def start(recipe="default", argv=None):parser = build_quantize_parser(prog="auto_round quantize")args = parser.parse_args(argv)args._api_format = args.format if format_was_explicit or args.model_free else None+ _apply_recipe_defaults(args, recipe)+ tune(args)+++def _apply_recipe_defaults(args, recipe="auto-round"):+ """Normalize recommendations for both command entry points and direct tune calls."""+ if getattr(args, "_recipe_plan", None) is not None:+ return+ if not hasattr(args, "_explicit_fields"):+ # Namespaces built outside the quantize parser: treat every set value as explicit.+ args._explicit_fields = {key for key, value in vars(args).items() if value is not None}+ args.recipe = get_recipe(args.recipe or recipe).name+ definition = get_recipe(args.recipe)+ args._recipe_plan = resolve_recipe(+ definition,+ model=args.model or args.model_name,+ scheme=args.scheme,+ trust_remote_code=not args.disable_trust_remote_code,+ )- # Apply recipe defaults for fields the user didn't set- for key, value in recipe_defaults.items():+ for key, value in args._recipe_plan.calibration.items():if getattr(args, key, None) is None:setattr(args, key, value)+ # Keep effective legacy attributes available to integrations inspecting tune(args).+ if args.algorithm is None:+ configs = args._recipe_plan.build_configs()+ for config in configs:+ for key in ("iters", "lr", "disable_opt_rtn"):+ if key not in args._explicit_fields and hasattr(config, key):+ setattr(args, key, getattr(config, key))+ if all(not hasattr(config, "iters") for config in configs):+ if "iters" not in args._explicit_fields:+ args.iters = 0if args.model_free:args.iters = 0-- tune(args)+ args._explicit_fields.add("iters")def tune(args):+ _apply_recipe_defaults(args)assert args.model or args.model_name, "[model] or --model MODEL_NAME should be set."if args.model is None:args.model = args.model_name@@ -605,6 +615,7 @@ def tune(args):autoround: BaseCompressor = AutoRound(model_name,scheme=scheme,+ recipe=args._recipe_plan,alg_configs=alg_configs if len(alg_configs) > 1 else alg_configs[0],**_to_autoround_kwargs(args,diff --git a/auto_round/cli/parser.py b/auto_round/cli/parser.pyindex e8ae636f9..0149efef1 100644--- a/auto_round/cli/parser.py+++ b/auto_round/cli/parser.py@@ -53,6 +53,35 @@ def _parse_group_size(s: str):return tuple(int(x.strip()) for x in s.split(","))+class _QuantizeArgumentParser(argparse.ArgumentParser):+ """Retain explicit options even when parsed args are passed directly to tune()."""++ def parse_known_args(self, args=None, namespace=None):+ import sys++ argv = list(sys.argv[1:] if args is None else args)+ parsed, extras = super().parse_known_args(argv, namespace)+ parsed._explicit_fields = self._explicit_dests(argv)+ return parsed, extras++ def _explicit_dests(self, argv) -> set[str]:+ """Return destinations set on the command line, including abbreviated options."""+ defaults = [(action, action.default) for action in self._actions]+ parser_defaults = dict(self._defaults)+ try:+ for action, _ in defaults:+ action.default = argparse.SUPPRESS+ self._defaults.clear()+ seen, _ = super().parse_known_args(argv, argparse.Namespace())+ except SystemExit:+ return set()+ finally:+ for action, default in defaults:+ action.default = default+ self._defaults.update(parser_defaults)+ return {dest for dest in vars(seen) if dest != "model"}++def add_common_quantization_arguments(group) -> None:"""Add common quantization flags to an argparse group.@@ -123,10 +152,11 @@ def add_common_quantization_arguments(group) -> None:def build_quantize_parser(*, prog: str = "auto_round quantize") -> argparse.ArgumentParser:"""Build the quantize parser with all argument groups."""- parser = argparse.ArgumentParser(prog=prog)+ parser = _QuantizeArgumentParser(prog=prog)# ---- Model / Runtime ----rt = parser.add_argument_group("Runtime Arguments")+ rt.add_argument("--recipe", default=None, help="Recommended quantization plan (default: auto-round).")rt.add_argument("model", default=None, nargs="?", help="Path to the pre-trained model or Hugging Face model id.")rt.add_argument("--model_name",@@ -408,8 +438,8 @@ def build_quantize_parser(*, prog: str = "auto_round quantize") -> argparse.Argudef build_list_parser(*, prog: str = "auto_round list") -> argparse.ArgumentParser:parser = argparse.ArgumentParser(prog=prog)- parser.add_argument("item", type=str, help="item to list, e.g., format, alg")- parser.add_argument("name", nargs="?", default=None, help="optional specific format/algorithm name")+ parser.add_argument("item", type=str, help="item to list, e.g., format, alg, recipe")+ parser.add_argument("name", nargs="?", default=None, help="optional specific format/algorithm/recipe name")return parserdiff --git a/auto_round/compressors/layer_config_resolver.py b/auto_round/compressors/layer_config_resolver.pyindex 490f64c59..5df562824 100644--- a/auto_round/compressors/layer_config_resolver.py+++ b/auto_round/compressors/layer_config_resolver.py@@ -354,8 +354,9 @@ def _traverse_and_expand_layer_config(# (e.g. MTP layers that transformers does not instantiate).safetensor_only_names = _get_safetensor_layer_names_not_in_model(model, all_module_names)- # 6. expand regex configs+ # 6. expand regex configs; exact layer names always take precedence over patterns.regex_config = {}+ exact_names = {name for name in layer_config if name in all_supported_layer_names}for name in list(layer_config.keys()):if name in all_supported_layer_names:continue@@ -387,7 +388,8 @@ def _traverse_and_expand_layer_config(val = layer_config.pop(name)regex_config[name] = val # keep regex configfor match in matched:- layer_config[match] = val+ if match not in exact_names:+ layer_config[match] = valreturn layer_config, regex_config, embedding_layer_names, supported_typesdiff --git a/auto_round/recipes/__init__.py b/auto_round/recipes/__init__.pynew file mode 100644index 000000000..a278b4496--- /dev/null+++ b/auto_round/recipes/__init__.py@@ -0,0 +1,16 @@+# Copyright (c) 2026 Intel Corporation+# SPDX-License-Identifier: Apache-2.0+"""Built-in and context-aware recommended quantization plans."""++from auto_round.recipes.recipe import AlgorithmSpec, Recipe+from auto_round.recipes.registry import get_recipe, list_recipes, register_recipe+from auto_round.recipes.resolver import resolve_recipe++__all__ = [+ "AlgorithmSpec",+ "Recipe",+ "get_recipe",+ "list_recipes",+ "register_recipe",+ "resolve_recipe",+]diff --git a/auto_round/recipes/recipe.py b/auto_round/recipes/recipe.pynew file mode 100644index 000000000..8974be334--- /dev/null+++ b/auto_round/recipes/recipe.py@@ -0,0 +1,130 @@+# Copyright (c) 2026 Intel Corporation+# SPDX-License-Identifier: Apache-2.0+"""Recipe definitions and built-in recommendations."""++from __future__ import annotations++from collections.abc import Callable+from dataclasses import dataclass, field+from typing import Any+++class _Unset:+ def __repr__(self):+ return "UNSET"+++UNSET = _Unset()+++def calibration_defaults() -> dict[str, Any]:+ return {"batch_size": 8, "seqlen": 2048, "nsamples": 128}+++@dataclass(frozen=True)+class AlgorithmSpec:+ """A stable stage name, registered algorithm name, and constructor parameters."""++ name: str+ algorithm: str+ params: dict[str, Any] = field(default_factory=dict)++ def build_config(self, overrides: dict[str, Any] | None = None):+ """Apply constructor overrides while preserving callable-factory defaults."""+ import copy+ import inspect++ from auto_round.algorithms.registry import get_algorithm_entry, resolve_alg_config++ entry = get_algorithm_entry(self.algorithm)+ factory = entry.alias_factories.get(self.algorithm.strip().lower(), entry.config_factory)+ params = copy.deepcopy({**self.params, **(overrides or {})})+ if isinstance(factory, type):+ return factory(**params)+ config = resolve_alg_config(self.algorithm)+ if not params:+ return config+ fields = set(getattr(type(config), "model_fields", {}))+ for cls in type(config).__mro__:+ init = cls.__dict__.get("__init__")+ if init is None:+ continue+ fields.update(+ name+ for name, parameter in inspect.signature(init).parameters.items()+ if name != "self"+ and parameter.kind in (inspect.Parameter.POSITIONAL_OR_KEYWORD, inspect.Parameter.KEYWORD_ONLY)+ )+ defaults = {name: copy.deepcopy(getattr(config, name)) for name in fields if hasattr(config, name)}+ result = type(config)(**{**defaults, **params})+ if hasattr(config, "_user_set_scheme_fields"):+ result._user_set_scheme_fields.update(config._user_set_scheme_fields)+ return result+++@dataclass+class Recipe:+ """Defaults with an optional process(recipe, *, scheme, model_config) function.++ The function edits an isolated copy using ordinary Python conditionals.+ It may replace the pipeline or modify calibration and layer defaults.+ """++ name: str+ pipeline: tuple[AlgorithmSpec, ...]+ calibration: dict[str, Any] = field(default_factory=dict)+ layer_config: dict[str, Any] = field(default_factory=dict)+ description: str = ""+ aliases: tuple[str, ...] = ()+ process: Callable[..., None] | None = None++ def build_configs(self) -> list:+ """Construct fresh configs using the existing algorithm registry."""+ return [stage.build_config() for stage in self.pipeline]+++def builtin_recipes() -> tuple[Recipe, ...]:+ """Return built-in recommendations; numerical schemes remain in schemes.py."""+ calibration = calibration_defaults()+ return (+ Recipe(+ "auto-round",+ (AlgorithmSpec("quantizer", "auto_round", {"iters": 200}),),+ dict(calibration),+ description="Balanced quantization cost and accuracy.",+ aliases=("auto_round", "ar", "default"),+ ),+ Recipe(+ "auto-round-light",+ (AlgorithmSpec("quantizer", "auto_round", {"iters": 50, "lr": 5e-3}),),+ dict(calibration),+ description="Lower-cost iterative quantization.",+ aliases=("auto_round_light", "ar-light", "ar_light", "light"),+ ),+ Recipe(+ "auto-round-best",+ (AlgorithmSpec("quantizer", "auto_round", {"iters": 1000}),),+ {**calibration, "nsamples": 512},+ description="Accuracy-oriented iterative quantization.",+ aliases=("auto_round_best", "ar-best", "ar_best", "best"),+ ),+ Recipe(+ "rtn",+ (AlgorithmSpec("quantizer", "rtn", {"disable_opt_rtn": True}),),+ {**calibration, "nsamples": 1},+ description="Plain round-to-nearest quantization.",+ ),+ Recipe(+ "opt-rtn",+ (AlgorithmSpec("quantizer", "rtn", {"disable_opt_rtn": False}),),+ dict(calibration),+ description="Optimized round-to-nearest quantization.",+ aliases=("opt_rtn",),+ ),+ Recipe(+ "awq",+ (AlgorithmSpec("smooth", "awq"), AlgorithmSpec("quantizer", "rtn", {"disable_opt_rtn": True})),+ dict(calibration),+ description="AWQ smoothing followed by plain RTN.",+ ),+ )diff --git a/auto_round/recipes/registry.py b/auto_round/recipes/registry.pynew file mode 100644index 000000000..8570d771b--- /dev/null+++ b/auto_round/recipes/registry.py@@ -0,0 +1,41 @@+# Copyright (c) 2026 Intel Corporation+# SPDX-License-Identifier: Apache-2.0+"""Discovery with isolated recipe definitions and unambiguous aliases."""++import copy++from auto_round.recipes.recipe import Recipe, builtin_recipes++_RECIPES: dict[str, Recipe] = {}+_ALIASES: dict[str, str] = {}+++def register_recipe(recipe: Recipe) -> None:+ """Register an isolated definition; reject colliding names and aliases."""+ names = (recipe.name, *recipe.aliases)+ keys = [name.strip().lower() for name in names]+ if any(not key for key in keys) or len(set(keys)) != len(keys):+ raise ValueError("Recipe names and aliases must be nonempty and unique.")+ conflicts = set(keys) & _ALIASES.keys()+ if conflicts:+ raise ValueError(f"Recipe names/aliases already registered: {sorted(conflicts)}")+ canonical = keys[0]+ _RECIPES[canonical] = copy.deepcopy(recipe)+ _ALIASES.update({key: canonical for key in keys})+++def get_recipe(name: str) -> Recipe:+ """Return an independent definition using a case-insensitive name or alias."""+ canonical = _ALIASES.get(name.strip().lower())+ if canonical is None:+ raise ValueError(f"Unknown recipe {name!r}. Available recipes: {', '.join(list_recipes())}")+ return copy.deepcopy(_RECIPES[canonical])+++def list_recipes() -> list[str]:+ """List canonical recipe names in registration order."""+ return list(_RECIPES)+++for _recipe in builtin_recipes():+ register_recipe(_recipe)diff --git a/auto_round/recipes/resolver.py b/auto_round/recipes/resolver.pynew file mode 100644index 000000000..53133b04b--- /dev/null+++ b/auto_round/recipes/resolver.py@@ -0,0 +1,58 @@+# Copyright (c) 2026 Intel Corporation+# SPDX-License-Identifier: Apache-2.0+"""Pure recommendation resolution, independent of model loading and execution."""++import copy++from auto_round.recipes.recipe import Recipe, calibration_defaults+from auto_round.recipes.registry import get_recipe+++def merge_layer_defaults(defaults: dict, overrides: dict | None) -> dict:+ """Merge per-pattern fields; scalar scheme entries replace the whole entry."""+ result = copy.deepcopy(defaults)+ for name, value in (overrides or {}).items():+ if isinstance(value, dict) and isinstance(result.get(name), dict):+ result[name].update(copy.deepcopy(value))+ else:+ result[name] = copy.deepcopy(value)+ return result+++def resolve_recipe(+ recipe: str | Recipe = "auto-round", *, scheme="W4A16", model=None, model_config=None, trust_remote_code=True+) -> Recipe:+ """Apply a recipe's processing function to an isolated copy of its defaults."""+ definition = get_recipe(recipe) if isinstance(recipe, str) else copy.deepcopy(recipe)+ if not isinstance(definition, Recipe):+ raise TypeError("recipe must be a registered name or Recipe instance.")+ definition.calibration = {**calibration_defaults(), **definition.calibration}+ if definition.process is not None:+ if model_config is None:+ model_config = getattr(model, "config", None)+ if model_config is None and isinstance(model, str):+ from transformers import AutoConfig++ from auto_round.logger import logger++ try:+ model_config = AutoConfig.from_pretrained(model, trust_remote_code=trust_remote_code)+ except (OSError, ValueError) as error:+ logger.debug("Could not load recipe model metadata for %s: %s", model, error)+ definition.process(+ definition,+ scheme=scheme.upper() if isinstance(scheme, str) else scheme,+ model_config=copy.deepcopy(model_config),+ )+ # The returned plan is already processed; resolving it again must not rerun the callback.+ definition.process = None+ pipeline = definition.pipeline+ calibration = definition.calibration+ if not pipeline or len({stage.name for stage in pipeline}) != len(pipeline):+ raise ValueError("Recipe pipeline must have nonempty, unique stage names and at least one stage.")+ if any(not stage.name for stage in pipeline):+ raise ValueError("Recipe stage names must be nonempty.")+ invalid_calibration = set(calibration) - {"dataset", "seqlen", "nsamples", "batch_size"}+ if invalid_calibration:+ raise ValueError(f"Unsupported recipe calibration fields: {sorted(invalid_calibration)}")+ return definitiondiff --git a/docs/recipes.md b/docs/recipes.mdnew file mode 100644index 000000000..1f58e0c1e--- /dev/null+++ b/docs/recipes.md@@ -0,0 +1,125 @@+# Quantization recipes++Recipes are the shared recommendation source for the Python API and CLI.+Omitting `recipe` selects `auto-round`. A recipe chooses a complete algorithm pipeline,+calibration defaults, and optional per-layer recommendations. Scheme definitions+and algorithm implementations remain independent of recipes.++## Built-in plans++| Recipe | Initial pipeline | Iterations | Samples |+| --- | --- | --- | --- |+| `auto-round` | SignRound | 200 | 128 |+| `auto-round-light` | SignRound, learning rate 0.005 | 50 | 128 |+| `auto-round-best` | SignRound | 1000 | 512 |+| `rtn` | Plain RTN | — | 1 |+| `opt-rtn` | Optimized RTN | — | 128 |+| `awq` | AWQ smoothing → plain RTN | — | 128 |++All initial plans use sequence length 2048 and batch size 8. Names are case-insensitive+and accept the following aliases in both Python and the CLI:++| Canonical name | Aliases |+| --- | --- |+| `auto-round` | `auto_round`, `ar`, `default` |+| `auto-round-light` | `auto_round_light`, `ar-light`, `ar_light`, `light` |+| `auto-round-best` | `auto_round_best`, `ar-best`, `ar_best`, `best` |+| `opt-rtn` | `opt_rtn` |++Listings and resolved recipe names use the canonical names, matching the existing CLI naming.+The three `auto-round` tiers express cost/accuracy goals: their pipelines may gain+validated scheme-specific recommendations in future releases. They do not+guarantee an accuracy ordering on every model. Core calibration requirements+still apply, including static activation calibration for RTN when required.++## Usage and overrides++```python+from auto_round import AutoRound, SignRoundConfig++compressor = AutoRound("Qwen/Qwen3-0.6B", scheme="MXFP4", recipe="auto-round-best")++# Explicit values win even when equal to an older API default.+compressor = AutoRound("Qwen/Qwen3-0.6B", recipe="auto-round-best", nsamples=128)++# Replace the entire algorithm pipeline, retaining auto-round-best calibration defaults.+compressor = AutoRound("Qwen/Qwen3-0.6B", recipe="auto-round-best", alg_configs=SignRoundConfig(iters=20))+```++```bash+auto_round Qwen/Qwen3-0.6B --scheme MXFP4 --recipe auto-round-best+auto_round Qwen/Qwen3-0.6B --recipe auto-round-best --nsamples 128 --iters 20+auto_round Qwen/Qwen3-0.6B --recipe auto-round-best --algorithm awq+auto_round list recipes+auto_round list recipe awq+```++Explicit algorithm configs replace the recipe pipeline, rather than appending to+it. Their algorithm parameters are not overwritten by recipe stage parameters.+The deprecated `algorithm=` Python argument and CLI `--algorithm` retain their+existing algorithm-selection semantics. Explicit `iters=0` still selects RTN.+Explicit layer entries override recipe entries per pattern and per field; a+scalar scheme entry replaces the entire entry. Capability checks still reject+unsupported combinations regardless of recipe overrides.++`auto_round_best`, `auto_round_light`, `auto_round_rtn`, and `auto_round_opt_rtn`+select the corresponding recipe. Their hyphenated spellings work identically.+An explicit `--recipe` overrides the shortcut's default selection.++## Inspecting and extending recipes++```python+from auto_round.recipes import get_recipe, list_recipes, resolve_recipe++print(list_recipes())+definition = get_recipe("auto-round-best")+plan = resolve_recipe(definition)+print(plan.pipeline, plan.calibration)+configs = plan.build_configs()+```++`resolve_recipe()` returns an independent, processed `Recipe` copy. Each `build_configs()`+call creates fresh algorithm configs. A constructed compressor exposes its+recommendation as `compressor.resolved_recipe`; this is the selected recommendation,+not a replacement for the effective config after explicit overrides and validation.++For custom recipes, use `Recipe` and `AlgorithmSpec`. A recipe can provide an+ordinary Python function to adjust its defaults:++```python+from auto_round.recipes import AlgorithmSpec, Recipe, resolve_recipe+++def configure(recipe, *, scheme, model_config):+ if scheme == "MXFP4":+ recipe.calibration["nsamples"] = 256+ if getattr(model_config, "model_type", None) == "some_model":+ recipe.layer_config["lm_head"] = "BF16"+++custom = Recipe(+ "custom",+ pipeline=(AlgorithmSpec("quantizer", "auto_round", {"iters": 50}),),+ process=configure,+)+plan = resolve_recipe(custom, scheme="MXFP4")+```++This example illustrates the API, not a benchmarked recommendation. The function+edits an independent copy of the recipe and returns nothing. It can replace+`recipe.pipeline` directly or modify algorithm parameters, calibration, and layer+defaults using ordinary Python. There is no conditional patch language or merge+order to learn. Calibration keys are `dataset`, `seqlen`, `nsamples`, and `batch_size`.++Pass a `Recipe` directly to `AutoRound` or register it with `register_recipe` to+use its name in Python and an in-process CLI. Registration rejects duplicate names+and aliases. The resolver accepts `scheme` and `model_config` directly. Entry+points provide the model; configuration metadata is looked up for string inputs+only when a processing function exists. If lookup is unavailable, `model_config`+is `None`. No model weights are loaded during recipe processing.+Existing mixed-scheme handling remains in `auto_round/schemes.py`, and model layer+defaults remain in `auto_round/special_model_handler.py`. They run after model+loading for both Python and CLI. Shape restrictions and model compatibility+patches also remain outside recipes.++AutoScheme remains the independent mixed-bit scheme-selection feature.diff --git a/docs/recipes_CN.md b/docs/recipes_CN.mdnew file mode 100644index 000000000..89f8f9a80--- /dev/null+++ b/docs/recipes_CN.md@@ -0,0 +1,115 @@+# 量化 Recipe++Recipe 是 Python API 与 CLI 共用的推荐配置来源。不传 `recipe` 等价于选择 `auto-round`。+Recipe 提供完整算法组合、校准默认值和可选的逐层推荐配置。+Scheme 定义和算法实现保持独立。++## 内置方案++| Recipe | 初始算法组合 | 迭代次数 | 样本数 |+| --- | --- | --- | --- |+| `auto-round` | SignRound | 200 | 128 |+| `auto-round-light` | SignRound,学习率 0.005 | 50 | 128 |+| `auto-round-best` | SignRound | 1000 | 512 |+| `rtn` | 普通 RTN | — | 1 |+| `opt-rtn` | 优化 RTN | — | 128 |+| `awq` | AWQ 平滑 → 普通 RTN | — | 128 |++所有初始方案的序列长度为 2048,batch size 为 8。名称不区分大小写,+Python 和 CLI 均支持以下别名:++| 正式名称 | 别名 |+| --- | --- |+| `auto-round` | `auto_round`、`ar`、`default` |+| `auto-round-light` | `auto_round_light`、`ar-light`、`ar_light`、`light` |+| `auto-round-best` | `auto_round_best`、`ar-best`、`ar_best`、`best` |+| `opt-rtn` | `opt_rtn` |++列表和解析后的 recipe 名称统一使用正式名称,与现有 CLI 命名保持一致。+三个 `auto-round` 档位表达成本与效果目标,未来可增加经过验证的 scheme 专属推荐组合,+但不保证每个模型上的精度严格按档位排序。核心校准要求仍然适用,例如 RTN+在需要时仍要进行静态激活校准。++## 使用与覆盖++```python+from auto_round import AutoRound, SignRoundConfig++compressor = AutoRound("Qwen/Qwen3-0.6B", scheme="MXFP4", recipe="auto-round-best")++# 显式值优先,即使它等于旧 API 默认值。+compressor = AutoRound("Qwen/Qwen3-0.6B", recipe="auto-round-best", nsamples=128)++# 整体替换算法组合,同时继承 auto-round-best 的校准默认值。+compressor = AutoRound("Qwen/Qwen3-0.6B", recipe="auto-round-best", alg_configs=SignRoundConfig(iters=20))+```++```bash+auto_round Qwen/Qwen3-0.6B --scheme MXFP4 --recipe auto-round-best+auto_round Qwen/Qwen3-0.6B --recipe auto-round-best --nsamples 128 --iters 20+auto_round Qwen/Qwen3-0.6B --recipe auto-round-best --algorithm awq+auto_round list recipes+auto_round list recipe awq+```++显式算法配置整体替换 recipe pipeline,不自动追加。其算法参数不会被 recipe+阶段参数覆盖。旧 Python `algorithm=` 和 CLI `--algorithm` 保留已有算法选择语义。+显式 `iters=0` 仍选择 RTN。显式逐层配置按模式、按字段覆盖 recipe 配置;+字符串 scheme 值整体替换对应条目。无论如何覆盖,能力校验仍会拒绝不支持的组合。++`auto_round_best`、`auto_round_light`、`auto_round_rtn`、`auto_round_opt_rtn`+选择对应 recipe;连字符形式行为一致。显式 `--recipe` 优先于快捷命令的默认选择。++## 检查与扩展++```python+from auto_round.recipes import get_recipe, list_recipes, resolve_recipe++print(list_recipes())+definition = get_recipe("auto-round-best")+plan = resolve_recipe(definition)+print(plan.pipeline, plan.calibration)+configs = plan.build_configs()+```++`resolve_recipe()` 返回处理后的独立 `Recipe` 副本。每次 `build_configs()` 都构造新的算法配置。+构造后的 compressor 通过 `compressor.resolved_recipe` 暴露所选推荐配置;+它不替代显式覆盖和核心校验后的最终有效配置。++自定义 recipe 使用 `Recipe`、`AlgorithmSpec`,需要根据 model/scheme 调整时,+提供普通 Python 函数即可:++```python+from auto_round.recipes import AlgorithmSpec, Recipe, resolve_recipe+++def configure(recipe, *, scheme, model_config):+ if scheme == "MXFP4":+ recipe.calibration["nsamples"] = 256+ if getattr(model_config, "model_type", None) == "some_model":+ recipe.layer_config["lm_head"] = "BF16"+++custom = Recipe(+ "custom",+ pipeline=(AlgorithmSpec("quantizer", "auto_round", {"iters": 50}),),+ process=configure,+)+plan = resolve_recipe(custom, scheme="MXFP4")+```++该示例展示接口,不代表经过精度验证的推荐值。函数修改 recipe 的独立副本,+不需要返回值。可以直接替换 `recipe.pipeline`,或者通过普通 Python 修改+算法参数、校准和逐层默认值,无需学习条件补丁语法或合并顺序。+校准字段为 `dataset`、`seqlen`、`nsamples`、`batch_size`。++可以直接把 `Recipe` 传给 `AutoRound`,也可以通过 `register_recipe` 注册后在+Python 和同进程 CLI 中按名称使用。注册拒绝重复名称和别名。+Resolver 直接接收 `scheme`、`model_config`。入口提供 model;仅存在处理函数时,+才为字符串模型输入查询配置元信息。配置查询不可用时,`model_config` 为 `None`。+Recipe 处理不会加载模型权重。已有 mixed scheme 处理保留在+`auto_round/schemes.py`,模型逐层默认配置保留在 `auto_round/special_model_handler.py`。+这些处理仍在加载模型后执行,Python 和 CLI 均适用。+Shape 限制和模型兼容补丁也不归 recipe 管理。++AutoScheme 仍是独立的混合位宽选择功能。diff --git a/test/unit/common/core/test_init.py b/test/unit/common/core/test_init.pyindex 72e13d4fb..0a6f96766 100644--- a/test/unit/common/core/test_init.py+++ b/test/unit/common/core/test_init.py@@ -9,6 +9,7 @@ from auto_round.cli.main import _to_autoround_kwargsfrom auto_round.cli.parser import build_quantize_parserfrom auto_round.compressors.base import MIN_ITERS_FOR_TORCH_COMPILE, BaseOrchestratorfrom auto_round.logger import logger+from auto_round.recipes.recipe import UNSETfrom auto_round.utils.device_manager import default_enable_torch_compile@@ -18,7 +19,7 @@ def test_torch_compile_platform_default_is_deferred():def test_dataset_default_is_deferred():- assert inspect.signature(AutoRound.__new__).parameters["dataset"].default is None+ assert inspect.signature(AutoRound.__new__).parameters["dataset"].default is UNSETassert inspect.signature(BaseOrchestrator.__init__).parameters["dataset"].default is Nonediff --git a/test/unit/common/core/test_recipes.py b/test/unit/common/core/test_recipes.pynew file mode 100644index 000000000..36eec2fe9--- /dev/null+++ b/test/unit/common/core/test_recipes.py@@ -0,0 +1,519 @@+from types import SimpleNamespace++import pytest++from auto_round import AutoRound+from auto_round.algorithms.quantization.rtn.config import RTNConfig+from auto_round.algorithms.quantization.sign_round.config import SignRoundConfig+++def test_builtin_recipes():+ from auto_round.recipes import list_recipes, resolve_recipe++ assert list_recipes() == ["auto-round", "auto-round-light", "auto-round-best", "rtn", "opt-rtn", "awq"]+ for name, iters, nsamples in [+ ("auto-round", 200, 128),+ ("auto-round-light", 50, 128),+ ("auto-round-best", 1000, 512),+ ]:+ plan = resolve_recipe(name)+ assert plan.build_configs()[0].iters == iters+ assert plan.calibration["nsamples"] == nsamples+ assert resolve_recipe("light").build_configs()[0].lr == 0.005+ assert resolve_recipe("rtn").build_configs()[0].disable_opt_rtn is True+ assert resolve_recipe("opt_rtn").build_configs()[0].disable_opt_rtn is False+ assert [type(config).__name__ for config in resolve_recipe("awq").build_configs()] == ["AWQConfig", "RTNConfig"]+++def test_recipe_results_are_isolated():+ from auto_round.recipes import get_recipe, resolve_recipe++ definition = get_recipe("ar-best")+ definition.calibration["nsamples"] = 1+ plan = resolve_recipe("ar-best")+ plan.calibration["nsamples"] = 2+ plan.pipeline[0].params["iters"] = 3+ assert resolve_recipe("ar-best").calibration["nsamples"] == 512+ assert resolve_recipe("ar-best").build_configs()[0].iters == 1000+++def test_recipe_function_selects_pipeline_and_parameters():+ from auto_round.recipes import AlgorithmSpec, Recipe, resolve_recipe++ def process(recipe, *, scheme, model_config):+ if scheme == "MXFP4":+ recipe.pipeline = (AlgorithmSpec("smooth", "awq"), AlgorithmSpec("quantizer", "auto_round", {"iters": 50}))+ if getattr(model_config, "model_type", None) == "tiny":+ recipe.pipeline[-1].params["iters"] = 7+ recipe.calibration["nsamples"] = 16+ recipe.layer_config["lm_head"] = "BF16"++ recipe = Recipe(+ name="contextual",+ pipeline=(AlgorithmSpec("quantizer", "auto_round", {"iters": 200}),),+ process=process,+ )+ plan = resolve_recipe(recipe, scheme="MXFP4", model_config=SimpleNamespace(model_type="tiny"))+ assert [stage.algorithm for stage in plan.pipeline] == ["awq", "auto_round"]+ assert plan.build_configs()[1].iters == 7+ assert plan.calibration["nsamples"] == 16+ assert plan.layer_config == {"lm_head": "BF16"}+ assert len(resolve_recipe(recipe).pipeline) == 1+++def test_recipe_validation():+ from auto_round.recipes import Recipe, resolve_recipe++ with pytest.raises(ValueError, match="Unknown recipe"):+ resolve_recipe("ar-bset")+ recipe = Recipe("broken", ())+ with pytest.raises(ValueError, match="at least one stage"):+ resolve_recipe(recipe)+++def capture_entry(monkeypatch):+ from auto_round import autoround++ def capture(model, scheme, configs, **kwargs):+ return SimpleNamespace(model=model, scheme=scheme, configs=configs, **kwargs)++ monkeypatch.setattr(autoround, "_CompressorBuilder", capture)+++def test_default_entry_is_ar(capture_entry):+ default = AutoRound("dummy")+ explicit = AutoRound("dummy", recipe="ar")+ assert default.configs[0].iters == explicit.configs[0].iters == 200+ assert default.nsamples == explicit.nsamples == 128+++def test_entry_recipe_and_explicit_calibration(capture_entry):+ entry = AutoRound("dummy", recipe="ar-best", nsamples=128, batch_size=1, seqlen=32)+ assert entry.configs[0].iters == 1000+ assert (entry.nsamples, entry.batch_size, entry.seqlen) == (128, 1, 32)+ assert AutoRound("dummy", recipe="ar-best").nsamples == 512+++def test_explicit_pipeline_replaces_recipe_but_inherits_calibration(capture_entry):+ config = SignRoundConfig(iters=3, lr=0.25)+ entry = AutoRound("dummy", recipe="ar-best", alg_configs=config)+ assert entry.configs[0].iters == 3+ assert entry.configs[0].lr == 0.25+ assert config.iters == 3+ assert entry.nsamples == 512+ rtn = AutoRound("dummy", recipe="ar-best", alg_configs=RTNConfig(disable_opt_rtn=True))+ assert len(rtn.configs) == 1+ assert isinstance(rtn.configs[0], RTNConfig)+ assert not hasattr(rtn.configs[0], "iters")+++def test_legacy_entry_selectors_override_recipe(capture_entry):+ assert isinstance(AutoRound("dummy", iters=0).configs[0], RTNConfig)+ awq = AutoRound("dummy", recipe="ar-best", algorithm="awq")+ assert [type(config).__name__ for config in awq.configs] == ["AWQConfig", "RTNConfig"]+ assert awq.nsamples == 512+++def test_entry_applies_recipe_function_and_layer_overrides(capture_entry):+ from auto_round.recipes import AlgorithmSpec, Recipe++ def process(recipe, *, scheme, model_config):+ if model_config.model_type == "tiny":+ recipe.layer_config["proj"] = {"bits": 8}++ recipe = Recipe(+ "custom",+ (AlgorithmSpec("quantizer", "auto_round"),),+ process=process,+ )+ model = SimpleNamespace(config=SimpleNamespace(model_type="tiny"))+ entry = AutoRound(model, recipe=recipe, layer_config={"proj": {"bits": 4}})+ assert entry.layer_config["proj"]["bits"] == 4+++ "recipe,canonical",+ [+ ("auto-round", "auto-round"),+ ("auto_round", "auto-round"),+ ("ar", "auto-round"),+ ("default", "auto-round"),+ ("auto-round-light", "auto-round-light"),+ ("auto_round_light", "auto-round-light"),+ ("ar-light", "auto-round-light"),+ ("ar_light", "auto-round-light"),+ ("light", "auto-round-light"),+ ("auto-round-best", "auto-round-best"),+ ("auto_round_best", "auto-round-best"),+ ("ar-best", "auto-round-best"),+ ("ar_best", "auto-round-best"),+ ("best", "auto-round-best"),+ (" AR_LIGHT ", "auto-round-light"),+ ("awq", "awq"),+ ("rtn", "rtn"),+ ("opt-rtn", "opt-rtn"),+ ("opt_rtn", "opt-rtn"),+ ],+)+def test_cli_python_recipe_parity(recipe, canonical, capture_entry, monkeypatch):+ from auto_round.cli import main+ from auto_round.cli.algorithms import AlgorithmHandler++ captured = {}+ monkeypatch.setattr(main, "tune", lambda args: captured.setdefault("args", args))+ main.start(argv=["dummy", "--recipe", recipe])+ args = captured["args"]+ configs = AlgorithmHandler.build_configs(args, main._extract_common_quantization_kwargs(args))+ entry = AutoRound("dummy", recipe=recipe)+ assert args.recipe == entry.resolved_recipe.name == canonical+ assert [type(config) for config in configs] == [type(config) for config in entry.configs]+ assert args.nsamples == entry.nsamples+ for cli_config, api_config in zip(configs, entry.configs):+ for field in ("iters", "lr", "disable_opt_rtn"):+ assert getattr(cli_config, field, None) == getattr(api_config, field, None)+++def test_cli_explicit_pipeline_and_shortcut_override(monkeypatch):+ from auto_round.cli import main+ from auto_round.cli.algorithms import AlgorithmHandler++ captured = {}+ monkeypatch.setattr(main, "tune", lambda args: captured.setdefault("args", args))+ main.start("best", argv=["dummy", "--recipe", "ar-light", "--algorithm", "awq", "--nsamples", "512"])+ args = captured["args"]+ configs = AlgorithmHandler.build_configs(args, {})+ assert args.recipe == "auto-round-light"+ assert args.nsamples == 512+ assert [type(config).__name__ for config in configs] == ["AWQConfig", "RTNConfig"]+++def test_cli_explicit_values_override_recipe_stage_parameters(monkeypatch):+ from auto_round.cli import main+ from auto_round.cli.algorithms import AlgorithmHandler++ captured = {}+ monkeypatch.setattr(main, "tune", lambda args: captured.setdefault("args", args))+ main.start(argv=["dummy", "--recipe", "ar-best", "--iters", "50", "--disable_minmax_tuning"])+ config = AlgorithmHandler.build_configs(captured["args"], {})[0]+ assert config.iters == 50+ assert config.enable_minmax_tuning is False+++def test_cli_recipe_listing(capsys):+ from auto_round.cli.main import list_item++ list_item(["recipes"])+ output = capsys.readouterr().out+ assert "auto-round-best" in output+ assert "ar-best" not in output+ list_item(["recipe", "awq"])+ output = capsys.readouterr().out+ assert "awq" in output and "rtn" in output+++def test_cli_context_recipe_preserves_stage_defaults_and_layers(monkeypatch, capture_entry):+ from auto_round.cli import main+ from auto_round.cli.algorithms import AlgorithmHandler+ from auto_round.recipes import AlgorithmSpec, Recipe, register_recipe, registry++ def process(recipe, *, scheme, model_config):+ if scheme == "MXFP4":+ recipe.pipeline[0].params.update(enable_minmax_tuning=False, iters=7)+ recipe.layer_config["proj"] = "BF16"++ monkeypatch.setattr(registry, "_RECIPES", dict(registry._RECIPES))+ monkeypatch.setattr(registry, "_ALIASES", dict(registry._ALIASES))+ register_recipe(+ Recipe(+ "test-context",+ (AlgorithmSpec("quantizer", "auto_round"),),+ calibration={"nsamples": 32},+ process=process,+ )+ )+ captured = {}+ monkeypatch.setattr(main, "tune", lambda args: captured.setdefault("args", args))+ main.start(argv=["dummy", "--recipe", "test-context", "--scheme", "MXFP4"])+ config = AlgorithmHandler.build_configs(captured["args"], {})[0]+ assert config.enable_minmax_tuning is False+ assert config.iters == 7+ entry = AutoRound("dummy", recipe="test-context", scheme="MXFP4")+ assert entry.layer_config == {"proj": "BF16"}+++def test_entry_keeps_recipe_resolution_for_inspection(capture_entry):+ entry = AutoRound("dummy", recipe="best")+ assert entry.resolved_recipe.name == "auto-round-best"+++def test_cli_zero_iters_retains_rtn_search_options(monkeypatch):+ from auto_round.cli import main+ from auto_round.cli.algorithms import AlgorithmHandler++ captured = {}+ monkeypatch.setattr(main, "tune", lambda args: captured.setdefault("args", args))+ main.start(argv=["dummy", "--iters", "0", "--enable_neuqi", "--enable_opt_rtn"])+ config = AlgorithmHandler.build_configs(captured["args"], {})[0]+ assert isinstance(config, RTNConfig)+ assert config.enable_neuqi is True+++def test_cli_explicit_signround_uses_config_defaults(monkeypatch):+ from auto_round.cli import main+ from auto_round.cli.algorithms import AlgorithmHandler++ captured = {}+ monkeypatch.setattr(main, "tune", lambda args: captured.setdefault("args", args))+ main.start(argv=["dummy", "--recipe", "ar-best", "--algorithm", "auto_round"])+ configs = AlgorithmHandler.build_configs(captured["args"], {})+ assert configs[0].iters == 200+ assert captured["args"].nsamples == 512+++def test_recipe_function_looks_up_metadata_only_when_needed(monkeypatch, capture_entry):+ from transformers import AutoConfig++ from auto_round.recipes import AlgorithmSpec, Recipe++ calls = []++ def load_config(name, **kwargs):+ calls.append(name)+ return SimpleNamespace(model_type="tiny")++ monkeypatch.setattr(AutoConfig, "from_pretrained", load_config)+ AutoRound("dummy")+ assert calls == []++ def process(recipe, *, scheme, model_config):+ if model_config.model_type == "tiny":+ recipe.pipeline[0].params["iters"] = 7++ recipe = Recipe(+ "model-aware",+ (AlgorithmSpec("quantizer", "auto_round"),),+ process=process,+ )+ assert AutoRound("dummy", recipe=recipe).configs[0].iters == 7+ assert calls == ["dummy"]+++def test_custom_recipe_inherits_shared_calibration_defaults():+ from auto_round.recipes import AlgorithmSpec, Recipe, resolve_recipe++ plan = resolve_recipe(Recipe("custom", (AlgorithmSpec("quantizer", "rtn"),)))+ assert plan.calibration == {"batch_size": 8, "seqlen": 2048, "nsamples": 128}+++def test_entry_rejects_invalid_recipe_type(capture_entry):+ with pytest.raises(TypeError, match="recipe must"):+ AutoRound("dummy", recipe=None)++[email protected]("entry_name,recipe_name", [("run_best", "auto-round-best"), ("run_light", "auto-round-light")])+def test_legacy_shortcuts_select_named_recipe(monkeypatch, entry_name, recipe_name):+ import sys++ from auto_round.cli import main++ captured = {}+ monkeypatch.setattr(main, "tune", lambda args: captured.setdefault("args", args))+ monkeypatch.setattr(sys, "argv", ["auto_round_shortcut", "dummy"])+ getattr(main, entry_name)()+ assert captured["args"].recipe == recipe_name+++def test_callable_factory_defaults_survive_recipe_parameters(monkeypatch):+ from auto_round.algorithms.registry import get_algorithm_entry+ from auto_round.recipes import AlgorithmSpec, Recipe, resolve_recipe++ monkeypatch.setattr(+ get_algorithm_entry("auto_round"), "config_factory", lambda: SignRoundConfig(iters=17, momentum=0.25)+ )+ recipe = Recipe("factory", (AlgorithmSpec("quantizer", "auto_round", {"lr": 0.1}),))+ config = resolve_recipe(recipe).build_configs()[0]+ assert config.iters == 17+ assert config.momentum == 0.25+ assert config.lr == 0.1+++def test_alias_factory_defaults_survive_recipe_and_cli_overrides(monkeypatch):+ from auto_round.cli import main+ from auto_round.cli.algorithms import AlgorithmHandler+ from auto_round.recipes import AlgorithmSpec, Recipe, register_recipe, registry, resolve_recipe++ monkeypatch.setattr(registry, "_RECIPES", dict(registry._RECIPES))+ monkeypatch.setattr(registry, "_ALIASES", dict(registry._ALIASES))+ recipe = Recipe(+ "random-rotation",+ (+ AlgorithmSpec("rotation", "random_hadamard", {"block_size": 32}),+ AlgorithmSpec("quantizer", "auto_round"),+ ),+ )+ register_recipe(recipe)+ assert resolve_recipe(recipe).build_configs()[0].hadamard_type == "random_hadamard"+ captured = {}+ monkeypatch.setattr(main, "tune", lambda args: captured.setdefault("args", args))+ main.start(argv=["dummy", "--recipe", recipe.name, "--rotation_block_size", "64", "--bits", "4"])+ configs = AlgorithmHandler.build_configs(captured["args"], {"bits": 4})+ assert configs[0].hadamard_type == "random_hadamard"+ assert configs[0].block_size == 64+ assert configs[1].bits == 4+++def test_cli_recipe_respects_stage_common_argument_opt_out(monkeypatch):+ import auto_round.algorithms.registry as algorithms+ from auto_round.algorithms.config import AlgorithmConfig+ from auto_round.algorithms.registry import register_algorithm+ from auto_round.algorithms.transforms.base import BaseRotationConfig+ from auto_round.cli import main+ from auto_round.cli.algorithms import AlgorithmHandler+ from auto_round.recipes import AlgorithmSpec, Recipe, register_recipe, registry++ class StrictRotationConfig(AlgorithmConfig, BaseRotationConfig):+ cli_include_common_args = False++ def __init__(self):+ pass++ monkeypatch.setattr(registry, "_RECIPES", dict(registry._RECIPES))+ monkeypatch.setattr(registry, "_ALIASES", dict(registry._ALIASES))+ monkeypatch.setattr(algorithms, "_ALG_REGISTRY", dict(algorithms._ALG_REGISTRY))+ monkeypatch.setattr(algorithms, "_ALIAS_TO_NAME", dict(algorithms._ALIAS_TO_NAME))+ register_algorithm("strict-rotation", config_factory=StrictRotationConfig)+ register_recipe(+ Recipe(+ "strict-pipeline",+ (AlgorithmSpec("rotation", "strict-rotation"), AlgorithmSpec("quantizer", "auto_round")),+ )+ )+ captured = {}+ monkeypatch.setattr(main, "tune", lambda args: captured.setdefault("args", args))+ main.start(argv=["dummy", "--recipe", "strict-pipeline", "--bits", "4", "--group_size", "32"])+ configs = AlgorithmHandler.build_configs(captured["args"], {"bits": 4, "group_size": 32})+ assert isinstance(configs[0], StrictRotationConfig)+ assert configs[1].bits == 4+ assert configs[1].group_size == 32+++def test_direct_tune_applies_recipe_before_building_configs(monkeypatch):+ from auto_round.cli import main+ from auto_round.cli.algorithms import AlgorithmHandler+ from auto_round.cli.parser import build_quantize_parser++ args = build_quantize_parser().parse_args(["dummy", "--recipe", "ar-best", "--nsamples", "128"])++ def check_configs(args, common_kwargs):+ assert args.recipe == "auto-round-best"+ assert args.nsamples == 128+ assert args.batch_size == 8+ assert args.seqlen == 2048+ assert args._recipe_plan.build_configs()[0].iters == 1000+ raise StopIteration("configuration inspected")++ monkeypatch.setattr(AlgorithmHandler, "build_configs", check_configs)+ with pytest.raises(StopIteration, match="configuration inspected"):+ main.tune(args)+++def test_dataset_omission_inherits_recipe_but_explicit_none_is_deferred(capture_entry):+ from auto_round.recipes import AlgorithmSpec, Recipe++ recipe = Recipe(+ "dataset", (AlgorithmSpec("quantizer", "auto_round"),), calibration={"dataset": "custom-calibration"}+ )+ assert AutoRound("dummy", recipe=recipe).dataset == "custom-calibration"+ assert AutoRound("dummy", recipe=recipe, dataset=None).dataset is None+ assert AutoRound("dummy").dataset is None+++def test_callable_factory_recipe_still_validates_overrides(monkeypatch):+ from auto_round.algorithms.registry import get_algorithm_entry+ from auto_round.recipes import AlgorithmSpec++ entry = get_algorithm_entry("hadamard")+ monkeypatch.setattr(entry, "config_factory", lambda: entry.alias_factories["random_hadamard"]())+ with pytest.raises(ValueError):+ AlgorithmSpec("rotation", "hadamard", {"backend": "invalid"}).build_config()+++def test_exact_user_layer_wins_over_recipe_regex():+ import torch.nn as nn++ from auto_round.compressors.config_resolution import ResolvedScheme+ from auto_round.compressors.layer_config_resolver import resolve_layer_config+ from auto_round.recipes.resolver import merge_layer_defaults+ from auto_round.schemes import QuantizationScheme++ model = nn.Module()+ model.a_proj = nn.Linear(32, 32)+ model.b_proj = nn.Linear(32, 32)+ layer_config = merge_layer_defaults({r".*proj$": {"bits": 8}}, {"a_proj": {"bits": 16}})+ resolved = resolve_layer_config(+ model=model,+ scheme=ResolvedScheme.from_scheme(QuantizationScheme(act_bits=16, act_data_type="float")),+ layer_config=layer_config,+ supported_types=(nn.Linear,),+ inner_supported_types=(),+ )+ assert resolved["a_proj"]["bits"] == 16+ assert resolved["b_proj"]["bits"] == 8+++def test_cli_resolves_contextual_recipe_once(monkeypatch, capture_entry):+ from auto_round.cli import main+ from auto_round.recipes import AlgorithmSpec, Recipe, register_recipe, registry++ calls = []++ def process(recipe, *, scheme, model_config):+ calls.append(scheme)+ recipe.calibration["nsamples"] = 16 + len(calls)++ monkeypatch.setattr(registry, "_RECIPES", dict(registry._RECIPES))+ monkeypatch.setattr(registry, "_ALIASES", dict(registry._ALIASES))+ register_recipe(Recipe("test-once", (AlgorithmSpec("quantizer", "auto_round"),), process=process))+ import auto_round++ seen = {}++ def fake_entry(*args, **kwargs):+ entry = AutoRound(*args, **kwargs)+ seen["entry"] = entry+ raise StopIteration++ monkeypatch.setattr(auto_round, "AutoRound", fake_entry)+ with pytest.raises(StopIteration):+ main.start(argv=["dummy", "--recipe", "test-once"])+ assert calls == ["W4A16"]+ assert seen["entry"].nsamples == 17++[email protected]("option", ["--iter", "--iters", "--iters="])+def test_cli_option_spellings_override_recipe(monkeypatch, option):+ from auto_round.cli import main+ from auto_round.cli.algorithms import AlgorithmHandler++ captured = {}+ monkeypatch.setattr(main, "tune", lambda args: captured.setdefault("args", args))+ argv = ["dummy", "--recipe", "ar-best", "--disable_minmax"]+ argv += [option + "5"] if option.endswith("=") else [option, "5"]+ main.start(argv=argv)+ config = AlgorithmHandler.build_configs(captured["args"], {})[0]+ assert config.iters == 5+ assert config.enable_minmax_tuning is False+++def test_tune_accepts_namespace_without_explicit_fields():+ import argparse++ from auto_round.cli import main+ from auto_round.cli.parser import build_quantize_parser++ args = argparse.Namespace(**vars(build_quantize_parser().parse_args(["dummy", "--iters", "5"])))+ del args._explicit_fields+ main._apply_recipe_defaults(args)+ assert args.iters == 5+ assert args._recipe_plan.name == "auto-round"