PTQ-Level Efficiency, QAT-Level Accuracy | 训练后量化的效率,量化感知训练的精度
support AWQ sample control and optimize AWQ+ARV2 for INT WOQ (#2484)
Weiwei98ad5bbc3e9b
diff --git a/auto_round/algorithms/block_runner.py b/auto_round/algorithms/block_runner.pyindex 56121c8ea..358303600 100644--- a/auto_round/algorithms/block_runner.py+++ b/auto_round/algorithms/block_runner.py@@ -293,6 +293,10 @@ class BlockForwardRunner:"""Slice inputs and others by sample indices (public for custom loops)."""return self._select_batch(inputs, input_others, indices)+ def count_samples(self, inputs: Any) -> int:+ """Return the number of cached calibration samples in ``inputs``."""+ return self._count_samples(inputs)+# ── Helpers ──────────────────────────────────────────────────────────────def split_outputs(self, output: torch.Tensor) -> list[torch.Tensor]:diff --git a/auto_round/algorithms/composer.py b/auto_round/algorithms/composer.pyindex 79e7cd44e..f6dc059dc 100644--- a/auto_round/algorithms/composer.py+++ b/auto_round/algorithms/composer.py@@ -455,7 +455,16 @@ class AlgorithmComposer:with torch.no_grad():pre_hooks = []for pre in self.preprocessors:- pre_hooks.extend(pre.register_fp_input_forward_hooks(block))+ hooks = pre.register_fp_input_forward_hooks(block)+ if not hooks:+ continue+ pre_inputs, pre_others = pre.select_calibration_samples(fp_inputs, input_others)+ if pre_inputs is fp_inputs and pre_others is input_others:+ pre_hooks.extend(hooks)+ continue+ block_forward_fn(block, pre_inputs, pre_others)+ for h in hooks:+ h.remove()if pre_hooks:block_forward_fn(block, fp_inputs, input_others)for h in pre_hooks:@@ -479,14 +488,24 @@ class AlgorithmComposer:group_size = self.scheme.group_size if self.scheme else -1act_data_type = self.scheme.act_data_type if self.scheme else data_type+ # A reference supplied by an external caller may have been collected+ # before a weight-changing preprocessor (for example AWQ smoothing or+ # hard clipping). Such a reference is stale and must not be used as the+ # quantizer target or propagated as the next block's FP input.+ reference_invalidated = any(pre.invalidates_reference_output(block_ctx) for pre in self.preprocessors)+reference_next_input = None# ── Step 3: Quantizer calibration (act_max, imatrix, etc.) ─────────────if fp_inputs is not None:with torch.no_grad():quant_hooks = self._get_fp_act_hooks(block)- if reference_output is None:+ if reference_output is None or reference_invalidated:reference_output = block_forward_fn(block, fp_inputs, input_others)- reference_next_input = getattr(block_forward_fn, "last_output_dict", None) or reference_output+ reference_next_input = getattr(block_forward_fn, "last_output_dict", None) or reference_output+ else:+ # No forward happened in this step, so last_output_dict may+ # belong to an earlier AWQ subset/calibration replay.+ reference_next_input = reference_outputfor h in quant_hooks:h.remove()diff --git a/auto_round/algorithms/transforms/awq/base.py b/auto_round/algorithms/transforms/awq/base.pyindex 310b375e2..20d1f19bd 100644--- a/auto_round/algorithms/transforms/awq/base.py+++ b/auto_round/algorithms/transforms/awq/base.py@@ -182,6 +182,7 @@ class AWQTransform(BasePreprocessor):self.duo_scaling: bool | str = config.duo_scalingself.n_grid: int = config.n_gridself.smooth_iters: int = getattr(config, "smooth_iters", 1)+ self._awq_nsamples: int = config.awq_nsamples# AWQ weight-clip options (search + hard-clamp after smoothing).self.apply_clip: bool = getattr(config, "apply_clip", False)@@ -223,6 +224,9 @@ class AWQTransform(BasePreprocessor):self._clip_input_feat: dict[str, torch.Tensor] = {}self._finalized: bool = False+ self._sample_indices: torch.Tensor | None = None+ self._sample_population: int | None = None+ self._modified_block_name: str | None = None# ── Algorithm Fusion: lifecycle hook implementations ──────────────────────@@ -284,6 +288,10 @@ class AWQTransform(BasePreprocessor):if composer is not None:self._qdq_tool.configure(composer, awq_config=self.config)+ self._sample_indices = None+ self._sample_population = None+ self._modified_block_name = None+logger.info("AWQ: resolved %d mappings across %d blocks.",len(self._resolved_mappings),@@ -304,15 +312,37 @@ class AWQTransform(BasePreprocessor):return self._register_awq_hooks(self.model_context.model, block, block_name)return []+ def select_calibration_samples(self, fp_inputs, input_others):+ """Select one deterministic random AWQ subset shared by every block.++ The global calibration cache remains unchanged for the downstream+ quantizer. Only AWQ's activation statistics, smoothing replay, and clip+ features use this subset.+ """+ if self.block_forward is None:+ return fp_inputs, input_others+ num_samples = self.block_forward.count_samples(fp_inputs)+ if num_samples <= self._awq_nsamples:+ return fp_inputs, input_others+ if self._sample_indices is None or self._sample_population != num_samples:+ generator = torch.Generator(device="cpu")+ generator.manual_seed(42)+ self._sample_indices = torch.randperm(num_samples, generator=generator)[: self._awq_nsamples]+ self._sample_indices, _ = torch.sort(self._sample_indices)+ self._sample_population = num_samples+ logger.info("AWQ: randomly selected %d/%d calibration samples.", self._awq_nsamples, num_samples)+ return self.block_forward.select_batch(fp_inputs, input_others, self._sample_indices)+def pre_quantize_block(self, ctx: BlockContext) -> None:"""Apply AWQ smoothing for this block and mark modified params.- Called after the reference forward (activation stats collected) and- before the block quantizer runs.+ Called after activation-stat collection and before the authoritative+ reference forward and block quantizer run."""if len(ctx.block_names) != 1:raise ValueError(f"AWQ requires nblocks=1, got {len(ctx.block_names)} blocks: {ctx.block_names}.")block_name = ctx.block_names[0]+ self._modified_block_name = Noneblock_mappings = self._block_mappings.get(block_name, [])if not block_mappings:logger.debug("AWQ: no mappings for block '%s', skipping.", block_name)@@ -331,14 +361,29 @@ class AWQTransform(BasePreprocessor):)if not active_mappings:return- self._smooth_block(block_name, active_mappings)+ if self.config.apply_smooth:+ self._smooth_block(block_name, active_mappings)if self.apply_clip:self._clip_block(block_name, active_mappings)+ if self.config.apply_smooth or (self.apply_clip and not self.clip_as_init):+ self._modified_block_name = block_namemodified = []for mapping in active_mappings:modified.extend(mapping.balance_names)modified.append(mapping.smooth_name)+ def invalidates_reference_output(self, ctx: BlockContext) -> bool:+ """Return whether AWQ changes this block before reference collection.++ Smoothing mutates weights even though its inverse scale folding should+ preserve the FP function. Hard clipping intentionally changes the FP+ function. In both cases the authoritative reference and next-block FP+ input must be produced by a new forward through the transformed block.+ ``clip_as_init`` only records bounds and therefore does not invalidate+ an otherwise current reference.+ """+ return self._modified_block_name == ctx.block_name+def post_quantize_block(self, ctx: BlockContext) -> None:"""Release per-block AWQ caches to free memory."""block_mappings = self._block_mappings.get(ctx.block_name, [])@@ -368,6 +413,9 @@ class AWQTransform(BasePreprocessor):self._activation_stats.clear()self._parent_args_cache.clear()self._clip_input_feat.clear()+ self._sample_indices = None+ self._sample_population = None+ self._modified_block_name = Noneself._finalized = Truelogger.debug("AWQ: finalize_quantization complete.")diff --git a/auto_round/algorithms/transforms/awq/config.py b/auto_round/algorithms/transforms/awq/config.pyindex 92018236d..22e541a00 100644--- a/auto_round/algorithms/transforms/awq/config.py+++ b/auto_round/algorithms/transforms/awq/config.py@@ -112,6 +112,18 @@ class AWQConfig(QuantizationConfig):type=int,help="Number of grid-search points for AWQ scaling ratio.",)+ registry.add_argument(+ "--awq-v2-scale-search",+ field="v2_scale_search",+ default="auto",+ choices=("auto", "full", "off", "reuse"),+ help=(+ "Scale-search policy used by AWQ's internal QDQ when the terminal quantizer is AutoRoundV2: "+ "auto uses plain RTN for INT schemes and full search otherwise, full searches every AWQ "+ "candidate, off uses plain RTN for AWQ loss only, and reuse searches once per balance layer "+ "and reuses that scale."+ ),+ )registry.add_argument("--awq_seqlen",field="awq_seqlen",@@ -119,6 +131,19 @@ class AWQConfig(QuantizationConfig):type=int,help="Maximum sequence length used by AWQ calibration, distinct from global --seqlen.",)+ registry.add_argument(+ "--awq_nsamples",+ "--awq-nsamples",+ "--awq-samples",+ field="awq_nsamples",+ dest="awq_nsamples",+ default=128,+ type=int,+ help=(+ "Maximum number of randomly selected calibration samples used by AWQ smoothing and clipping, "+ "independent of global --nsamples."+ ),+ )registry.add_argument("--awq_smooth_batch_size",field="smooth_batch_size",@@ -154,6 +179,7 @@ class AWQConfig(QuantizationConfig):n_grid: int = 20,seqlen: int = 2048,nsamples: int = 128,+ awq_nsamples: int = 128,batch_size: int = 8,apply_smooth: bool = True,smooth_iters: int = 1,@@ -164,6 +190,7 @@ class AWQConfig(QuantizationConfig):clip_n_sample_token: int = 512,awq_seqlen: int | None = None,smooth_batch_size: int | None = None,+ v2_scale_search: str = "auto",disable_opt_rtn: bool | None = True,skip_moe: bool = True,mappings: list[dict] | None = None,@@ -180,8 +207,13 @@ class AWQConfig(QuantizationConfig):AWQ scaling ratio.seqlen: Calibration sequence length retained for compatibilitywith standalone AWQ entry points.- nsamples: Number of calibration samples retained for compatibility- with standalone AWQ entry points.+ nsamples: Global calibration sample count retained for compatibility+ with standalone AWQ entry points. In composed pipelines, the+ downstream quantizer owns this value.+ awq_nsamples: Maximum number of randomly selected calibration samples+ used by AWQ activation statistics, smoothing, and clipping.+ Defaults to 128 and is independent of the downstream block+ quantizer's global calibration sample count.batch_size: Batch size retained for compatibility with standaloneAWQ entry points.apply_smooth: Whether to apply AWQ smoothing before the downstream@@ -236,6 +268,14 @@ class AWQConfig(QuantizationConfig):peak VRAM while preserving the AWQ parent-output loss, at thecost of more parent forward calls. ``None`` or ``<= 0`` replaysthe cached calibration batch as-is.+ v2_scale_search: AutoRoundV2 scale-search policy for AWQ's internal+ grid-loss QDQ. ``"auto"`` (the default) uses ``"off"`` for INT+ schemes and ``"full"`` for MX/NV schemes. ``"full"`` preserves+ the exact terminal quantizer initialization for every AWQ+ candidate. ``"off"`` uses plain RTN for AWQ loss while leaving+ the terminal AutoRoundV2 search unchanged. ``"reuse"`` searches+ once for each balance layer before the AWQ grid and reuses that+ scale.disable_opt_rtn: Whether AWQ's internal weight QDQ should use theplain RTN path. Defaults to True because AWQ calibration has notshown accuracy or cost benefits from optimized RTN in benchmarks.@@ -261,6 +301,8 @@ class AWQConfig(QuantizationConfig):disable_opt_rtn = Falsesuper().__init__(**kwargs)+ if awq_seqlen is not None and (isinstance(awq_seqlen, bool) or not isinstance(awq_seqlen, int)):+ raise ValueError(f"`awq_seqlen` must be an integer or None, got {awq_seqlen!r}")if awq_seqlen is None:awq_seqlen = 512@@ -270,6 +312,9 @@ class AWQConfig(QuantizationConfig):self.n_grid = n_gridself.seqlen = seqlenself.nsamples = nsamples+ if isinstance(awq_nsamples, bool) or not isinstance(awq_nsamples, int) or awq_nsamples < 1:+ raise ValueError(f"`awq_nsamples` must be a positive integer, got {awq_nsamples!r}")+ self.awq_nsamples = awq_nsamplesself.batch_size = batch_sizeself.apply_smooth = apply_smoothif smooth_iters is None or smooth_iters < 1:@@ -285,14 +330,21 @@ class AWQConfig(QuantizationConfig):raise ValueError(f"`clip_max_shrink` must be in (0, 1), got {clip_max_shrink!r}")if clip_n_sample_token is None or clip_n_sample_token < 1:raise ValueError(f"`clip_n_sample_token` must be a positive integer, got {clip_n_sample_token!r}")- if smooth_batch_size is not None and smooth_batch_size < 0:+ if smooth_batch_size is not None and (+ isinstance(smooth_batch_size, bool) or not isinstance(smooth_batch_size, int) or smooth_batch_size < 0+ ):raise ValueError(f"`smooth_batch_size` must be a non-negative integer or None, got {smooth_batch_size!r}")+ if v2_scale_search not in {"auto", "full", "off", "reuse"}:+ raise ValueError(+ "`v2_scale_search` must be one of 'auto', 'full', 'off', or 'reuse', " f"got {v2_scale_search!r}"+ )self._disable_opt_rtn = disable_opt_rtnself.clip_n_grid = clip_n_gridself.clip_max_shrink = clip_max_shrinkself.clip_n_sample_token = clip_n_sample_tokenself.awq_seqlen = awq_seqlenself.smooth_batch_size = smooth_batch_size+ self.v2_scale_search = v2_scale_searchself.skip_moe = skip_moeself.mappings = mappingsself.infer_bs_coeff = 1@@ -324,7 +376,9 @@ class AWQConfig(QuantizationConfig):f"AWQConfig(duo_scaling={self.duo_scaling!r}, n_grid={self.n_grid}, "f"smooth_iters={self.smooth_iters}, "f"apply_clip={self.apply_clip}, clip_as_init={self.clip_as_init}, "- f"awq_seqlen={self.awq_seqlen}, smooth_batch_size={self.smooth_batch_size}, "+ f"awq_nsamples={self.awq_nsamples}, awq_seqlen={self.awq_seqlen}, "+ f"smooth_batch_size={self.smooth_batch_size}, "+ f"v2_scale_search={self.v2_scale_search!r}, "f"disable_opt_rtn={self.disable_opt_rtn}, "f"skip_moe={self.skip_moe}, "f"bits={self.bits}, group_size={self.group_size}, sym={self.sym}, "diff --git a/auto_round/algorithms/transforms/awq/qdq.py b/auto_round/algorithms/transforms/awq/qdq.pyindex 2a51956a2..9154970f3 100644--- a/auto_round/algorithms/transforms/awq/qdq.py+++ b/auto_round/algorithms/transforms/awq/qdq.py@@ -61,6 +61,7 @@ class QDQTool:self.layer_config: dict | None = Noneself.disable_opt_rtn: bool | None = Noneself.use_v2_scale_search: bool = False+ self.v2_scale_search: str = "auto"# ── runtime wiring ────────────────────────────────────────────────────────@staticmethod@@ -80,6 +81,7 @@ class QDQTool:awq_disable_opt_rtn = getattr(block_config, "disable_opt_rtn", False)self.disable_opt_rtn = bool(awq_disable_opt_rtn)self.use_v2_scale_search = self._block_quantizer_is_signroundv2(composer)+ self.v2_scale_search = getattr(awq_config, "v2_scale_search", "auto")@staticmethoddef _block_quantizer_is_signroundv2(block_quantizer_or_composer) -> bool:@@ -129,10 +131,24 @@ class QDQTool:iters=0,)opt_quant_func = None- if self.use_v2_scale_search and params["sym"]:+ policy = self._resolve_v2_scale_search(self.v2_scale_search, params["data_type"])+ if self.use_v2_scale_search and policy != "off" and params["sym"]:opt_quant_func = get_optimized_quant_func(params["data_type"])return quant_func, opt_quant_func+ @staticmethod+ def _resolve_v2_scale_search(policy: str, data_type: str) -> str:+ """Resolve ``auto`` to ``off`` for INT and ``full`` for MX/NV schemes.++ The optimized V2 init-scale search is costly inside AWQ's candidate+ loop and does not repay that cost for INT weight QDQ, while the final+ SignRoundV2 quantizer still runs its own scale search. Floating-point+ schemes keep the exact terminal initialization by default.+ """+ if policy != "auto":+ return policy+ return "off" if str(data_type).lower().startswith("int") else "full"+# ── the unified QDQ for AWQ search ──────────────────────@torch.no_grad()def qdq(@@ -143,6 +159,7 @@ class QDQTool:quant_func=None,opt_quant_func=None,imatrix: torch.Tensor | None = None,+ init_scale: torch.Tensor | None = None,) -> torch.Tensor:"""Quantize-dequantize ``weight`` under the resolved ``params``.@@ -151,7 +168,8 @@ class QDQTool:the dispatched ``quant_func``; a non-``None`` ``opt_quant_func`` enablesthe SignRoundV2 optimized init-scale path for this weight. Used forboth the scale grid-search and the clip-search -- reference/loss only,- it never mutates stored weights.+ it never mutates stored weights. ``init_scale`` lets the ``reuse``+ policy supply a scale computed once before the AWQ smoothing loop."""if quant_func is None:quant_func, opt_quant_func = self.resolve_quant_funcs(params)@@ -175,9 +193,10 @@ class QDQTool:active_quant_func = quant_funcif opt_quant_func is not None:- init_scale = compute_optimized_init_scale(- weight, params["data_type"], params["bits"], params["group_size"], imatrix=imatrix- )+ if init_scale is None:+ init_scale = compute_optimized_init_scale(+ weight, params["data_type"], params["bits"], params["group_size"], imatrix=imatrix+ )if init_scale is not None:quant_kwargs["init_scale"] = init_scalequant_kwargs["imatrix"] = imatrix if isinstance(imatrix, torch.Tensor) else torch.ones_like(weight)diff --git a/auto_round/algorithms/transforms/awq/smooth.py b/auto_round/algorithms/transforms/awq/smooth.pyindex 68e2d61c8..91419e276 100644--- a/auto_round/algorithms/transforms/awq/smooth.py+++ b/auto_round/algorithms/transforms/awq/smooth.py@@ -20,7 +20,11 @@ from typing import TYPE_CHECKINGimport torchfrom auto_round.algorithms.transforms.smoothing.groups import SmoothGroup-from auto_round.data_type.utils import reshape_pad_tensor_by_group_size, revert_tensor_by_pad+from auto_round.data_type.utils import (+ compute_optimized_init_scale,+ reshape_pad_tensor_by_group_size,+ revert_tensor_by_pad,+)if TYPE_CHECKING:from auto_round.algorithms.transforms.awq.base import AWQTransform@@ -128,6 +132,24 @@ class AWQSmoothStrategy:# coupling to the first layer and makes direct calls robust.bl_quant_funcs = {bl: owner._qdq_tool.resolve_quant_funcs(bl_params[bl]) for bl in mapping.balance_layers}+ reused_init_scales = {}+ if owner._qdq_tool.v2_scale_search == "reuse":+ for bl in mapping.balance_layers:+ _, opt_quant_func = bl_quant_funcs[bl]+ if opt_quant_func is None:+ continue+ # Reuse the scale found for the original balance-layer weight.+ # This deliberately avoids rerunning the optimized search for+ # every AWQ smoothing candidate; the final V2 quantizer still+ # performs its normal scale search on the transformed weight.+ reused_init_scales[bl] = compute_optimized_init_scale(+ orig_state[bl],+ bl_params[bl]["data_type"],+ bl_params[bl]["bits"],+ bl_params[bl]["group_size"],+ imatrix=getattr(bl, "imatrix", None),+ )+def candidates():for ratio, use_duo in owner._get_grid_search_params():if use_duo:@@ -154,6 +176,7 @@ class AWQSmoothStrategy:quant_func=quant_func,opt_quant_func=opt_quant_func,imatrix=getattr(bl, "imatrix", None),+ init_scale=reused_init_scales.get(bl),)bl.weight.data = (w_qdq / scales_view).to(bl.weight.dtype)@@ -171,6 +194,7 @@ class AWQSmoothStrategy:quant_func=quant_func,opt_quant_func=opt_quant_func,imatrix=getattr(bl, "imatrix", None),+ init_scale=reused_init_scales.get(bl),)total_loss += (w_orig - w_qdq / scales_view).pow(2).sum().item()diff --git a/auto_round/algorithms/transforms/base.py b/auto_round/algorithms/transforms/base.pyindex d904584ae..2c0444820 100644--- a/auto_round/algorithms/transforms/base.py+++ b/auto_round/algorithms/transforms/base.py@@ -39,9 +39,28 @@ class BasePreprocessor(BaseAlgorithm):"""def pre_quantize_block(self, ctx) -> None:- """Called after the reference forward, before block quantization."""+ """Apply this transform before reference collection and block quantization."""return+ def invalidates_reference_output(self, ctx) -> bool:+ """Whether this block's pre-computed reference must be collected again.++ Preprocessors that mutate the floating-point block during+ :meth:`pre_quantize_block` must override this method. This prevents a+ caller-provided reference, collected before the transform, from being+ used as the quantizer target or propagated to the next block.+ """+ return False++ def select_calibration_samples(self, fp_inputs, input_others):+ """Return the calibration inputs this preprocessor should observe.++ The default keeps the full shared cache. Algorithms with an independent+ calibration budget, such as AWQ, may return a sample subset without+ changing the terminal quantizer's inputs.+ """+ return fp_inputs, input_others+def post_quantize_block(self, ctx) -> None:"""Called after the block quantizer completes."""returndiff --git a/docs/awq_details.md b/docs/awq_details.mdindex ff9561509..ebe80b9d9 100644--- a/docs/awq_details.md+++ b/docs/awq_details.md@@ -48,6 +48,60 @@ auto-round --model <model> --scheme <scheme> --format fake \--tasks "mmlu,gsm8k,piqa,hellaswag,winogrande"```+## Calibration Controls++AWQ has its own calibration budget for activation statistics and for the smoothing and clipping searches. These controls affect AWQ preprocessing only; the downstream RTN or AutoRound quantizer retains the global calibration cache and performs its own final scale search.++| CLI option | `AWQConfig` field | Default | Purpose |+| --- | --- | --- | --- |+| `--awq-nsamples` | `awq_nsamples` | `128` | Maximum number of calibration samples used by AWQ activation statistics, smoothing, and clipping. |+| `--awq_seqlen` | `awq_seqlen` | `512` | Maximum sequence length used by AWQ calibration; `<= 0` disables truncation. |+| `--awq_smooth_batch_size` | `smooth_batch_size` | `None` | Micro-batch size for replaying the parent module during the AWQ scale search; lower positive values reduce peak VRAM, while `<= 0` disables micro-batching. |+| `--awq-v2-scale-search` | `v2_scale_search` | `auto` | Scale-search policy for AWQ's internal QDQ when the terminal quantizer is AutoRoundV2. |++`--awq-nsamples` is independent of the global `--nsamples`. AWQ selects a deterministic random subset (seed 42) from the cached calibration inputs and reuses the same subset for every block. The global cache is not modified, so the downstream RTN/AutoRound quantizer and the FP reference forward still use all cached samples. Set `--awq-nsamples` greater than or equal to `--nsamples` to use all of them.++`--awq-v2-scale-search` takes effect only when the terminal quantizer is AutoRoundV2, which is enabled with `--enable_alg_ext` and `--algorithm auto_round` (or `awq,auto_round`). With an RTN terminal quantizer, the option is ignored. The policy changes only the QDQ used to score AWQ candidates; the terminal AutoRoundV2 quantizer always performs its own initialization search.++- `auto` (default): use `off` for INT schemes and `full` for non-INT schemes such as MXFP and NVFP.+- `off`: use plain RTN for AWQ's candidate loss. This is the fastest option and the recommended default for INT.+- `full`: reproduce the terminal V2 optimized init-scale search for every AWQ candidate. This is the slowest and most faithful option.+- `reuse`: run the optimized init-scale search once per balance layer and reuse it for every AWQ candidate. This is a middle ground between `off` and `full`.++When smoothing or hard clipping changes a block, AWQ requests a fresh FP reference forward before quantization, so a stale reference is never used as the quantizer target or passed to the next block.++```bash+# INT: auto resolves to off; AWQ uses at most 128 samples while the quantizer uses 256.+auto-round --model <model> --scheme W4A16 --format fake \+ --algorithm awq,auto_round --enable_alg_ext \+ --nsamples 256 --awq-nsamples 128++# MXFP4: auto resolves to full; use reuse to cut AWQ calibration time.+auto-round --model <model> --scheme MXFP4 --format fake \+ --algorithm awq,auto_round --enable_alg_ext \+ --awq-v2-scale-search reuse++# INT with an explicit full optimized search for every AWQ candidate.+auto-round --model <model> --scheme W4A16 --format fake \+ --algorithm awq,auto_round --enable_alg_ext \+ --awq-v2-scale-search full+```++The same settings are available through `AWQConfig`:++```python+from auto_round import AutoRound, AWQConfig, SignRoundV2Config++ar = AutoRound(+ model="<model>",+ scheme="W4A16",+ alg_configs=[+ AWQConfig(awq_nsamples=128, awq_seqlen=512, v2_scale_search="auto"),+ SignRoundV2Config(iters=200),+ ],+)+```+In the result tables, `AR2` denotes AutoRound with `--algorithm auto_round_v2` (formerly `--enable_alg_ext`), and `AWQ_AR2` denotes AWQ followed by AutoRound with the same algorithm extension. Accuracy columns are reported as percentages, so a raw score such as `0.7058` is shown as `70.58`.The AWQ rows use the default AWQ smoothing flow. They do not include AWQ weight clipping unless `--awq_apply_clip` is explicitly enabled.diff --git a/docs/awq_details_CN.md b/docs/awq_details_CN.mdindex 77a2a93ef..ef804c7c2 100644--- a/docs/awq_details_CN.md+++ b/docs/awq_details_CN.md@@ -48,6 +48,60 @@ auto-round --model <model> --scheme <scheme> --format fake \--tasks "mmlu,gsm8k,piqa,hellaswag,winogrande"```+## 标定数据选择++AWQ 为激活统计以及 smoothing、clipping 搜索维护独立的校准预算。这些设置只影响 AWQ 的预处理;下游 RTN 或 AutoRound 量化算法仍使用完整的全局校准缓存,并自行执行最终的 scale 搜索。++| CLI 选项 | `AWQConfig` 字段 | 默认值 | 作用 |+| --- | --- | --- | --- |+| `--awq-nsamples` | `awq_nsamples` | `128` | AWQ 激活统计、smoothing 和 clipping 使用的最大校准样本数。 |+| `--awq_seqlen` | `awq_seqlen` | `512` | AWQ 校准使用的最大序列长度;`<= 0` 表示关闭截断。 |+| `--awq_smooth_batch_size` | `smooth_batch_size` | `None` | AWQ scale 搜索中重放 parent 模块的 micro-batch 大小;较小的正数可降低峰值显存,`<= 0` 表示关闭 micro-batching。 |+| `--awq-v2-scale-search` | `v2_scale_search` | `auto` | 终端量化算法为 AutoRoundV2 时,AWQ 内部 QDQ 使用的 scale 搜索策略。 |++`--awq-nsamples` 独立于全局 `--nsamples`。AWQ 会从已缓存的校准输入中确定性地随机抽取一个子集(随机种子固定为 42),并在所有 block 中复用同一子集。全局缓存不会被修改,因此下游 RTN/AutoRound 量化算法和 FP reference forward 仍使用全部已缓存样本。将 `--awq-nsamples` 设置为大于等于 `--nsamples` 即可使用全部样本。++`--awq-v2-scale-search` 仅在终端量化算法为 AutoRoundV2 时生效,即同时启用 `--enable_alg_ext` 和 `--algorithm auto_round`(或 `awq,auto_round`)。终端量化算法为 RTN 时,该选项会被忽略。此策略只改变用于给 AWQ 候选打分的 QDQ;终端 AutoRoundV2 量化算法始终会执行自己的初始化搜索。++- `auto`(默认):INT scheme 使用 `off`,MXFP、NVFP 等非 INT scheme 使用 `full`。+- `off`:AWQ 候选损失使用普通 RTN。速度最快,也是 INT 的推荐默认值。+- `full`:对每个 AWQ 候选都复现终端 V2 的优化 init-scale 搜索。速度最慢,但最贴近终端量化。+- `reuse`:每个 balance layer 只做一次优化 init-scale 搜索,并在所有 AWQ 候选中复用。速度介于 `off` 和 `full` 之间。++当 smoothing 或 hard clipping 修改了某个 block 时,AWQ 会在量化前重新执行一次 FP reference forward,避免使用过期的 reference 作为量化目标或传递给下一个 block。++```bash+# INT:auto 解析为 off;AWQ 最多使用 128 个样本,终端量化使用 256 个。+auto-round --model <model> --scheme W4A16 --format fake \+ --algorithm awq,auto_round --enable_alg_ext \+ --nsamples 256 --awq-nsamples 128++# MXFP4:auto 解析为 full;使用 reuse 可缩短 AWQ 校准时间。+auto-round --model <model> --scheme MXFP4 --format fake \+ --algorithm awq,auto_round --enable_alg_ext \+ --awq-v2-scale-search reuse++# INT:显式对每个 AWQ 候选执行完整的优化搜索。+auto-round --model <model> --scheme W4A16 --format fake \+ --algorithm awq,auto_round --enable_alg_ext \+ --awq-v2-scale-search full+```++这些参数也可以通过 `AWQConfig` 设置:++```python+from auto_round import AutoRound, AWQConfig, SignRoundV2Config++ar = AutoRound(+ model="<model>",+ scheme="W4A16",+ alg_configs=[+ AWQConfig(awq_nsamples=128, awq_seqlen=512, v2_scale_search="auto"),+ SignRoundV2Config(iters=200),+ ],+)+```+表中 `AR2` 表示启用 `--algorithm auto_round_v2`(原 `--enable_alg_ext`)的 AutoRound,`AWQ_AR2` 表示 AWQ 后接启用同一算法扩展的 AutoRound。准确率列以百分制展示,例如原始值 `0.7058` 写作 `70.58`。AWQ 相关行使用默认 AWQ smoothing 流程。除非显式设置 `--awq_apply_clip`,否则不包含 AWQ weight clipping。diff --git a/test/unit/common/compressors/test_reference_output.py b/test/unit/common/compressors/test_reference_output.pyindex 68f3273f8..b55630aa9 100644--- a/test/unit/common/compressors/test_reference_output.py+++ b/test/unit/common/compressors/test_reference_output.py@@ -14,6 +14,7 @@ import torchfrom auto_round import RTNConfigfrom auto_round.algorithms.composer import AlgorithmComposer, BlockContext+from auto_round.algorithms.transforms.base import BasePreprocessordef _make_ctx():@@ -93,3 +94,71 @@ class TestCompressBlockReferenceOutputSkip:)assert ref_next is pre_computed+++class _WeightChangingPreprocessor(BasePreprocessor):+ """Minimal transform used to exercise reference invalidation."""++ def register_fp_input_forward_hooks(self, block):+ return []++ def pre_quantize_block(self, ctx):+ ctx.model.weight.data.mul_(2)++ def invalidates_reference_output(self, ctx):+ return True+++def test_weight_changing_preprocessor_recomputes_seeded_reference():+ """A pre-transform reference must not survive a weight-changing preprocessor."""+ from auto_round.algorithms.block_runner import BlockForwardRunner++ composer = AlgorithmComposer([RTNConfig()])+ block = torch.nn.Linear(1, 1, bias=False)+ block.weight.data.fill_(1)+ fp_inputs = [torch.tensor([[3.0]])]+ stale_reference = [torch.tensor([[3.0]])]+ ctx = BlockContext(+ model=block,+ block_names=["block"],+ block_name="block",+ block_index=0,+ )+ composer.block_forward = BlockForwardRunner(batch_size=1, amp=False, enable_torch_compile=False)+ composer.block_quantizer.quantize_block = MagicMock()+ composer.block_quantizer.enable_quanted_input = False+ composer._get_fp_act_hooks = MagicMock(return_value=[])+ composer._get_q_act_hooks = MagicMock(return_value=[])+ composer.preprocessors = [_WeightChangingPreprocessor()]++ _, reference_next_input = composer.compress_block(+ block,+ fp_inputs,+ {},+ block_ctx=ctx,+ reference_output=stale_reference,+ )++ expected = torch.tensor([[6.0]])+ assert torch.equal(reference_next_input[0], expected)+ quantizer_reference = composer.block_quantizer.quantize_block.call_args.args[3]+ assert torch.equal(quantizer_reference[0], expected)+++def test_reference_propagation_ignores_stale_last_output_dict():+ """A skipped reference forward cannot reuse metadata from preprocessor calibration."""+ composer = AlgorithmComposer([RTNConfig()])+ fp_inputs = [torch.zeros(1, 4)]+ pre_computed = [torch.ones(1, 4)]+ mock_forward = _patch_composer(composer, fp_inputs)+ mock_forward.last_output_dict = {"hidden_states": [torch.full((1, 4), 9.0)]}++ _, reference_next_input = composer.compress_block(+ torch.nn.Linear(4, 4),+ fp_inputs,+ {},+ block_ctx=_make_ctx(),+ reference_output=pre_computed,+ )++ assert reference_next_input is pre_computeddiff --git a/test/unit/test_cpu/algorithms/test_awq.py b/test/unit/test_cpu/algorithms/test_awq.pyindex 380d76661..c70bd3df4 100644--- a/test/unit/test_cpu/algorithms/test_awq.py+++ b/test/unit/test_cpu/algorithms/test_awq.py@@ -525,7 +525,7 @@ class TestAWQMoE:def fake_resolve_quant_funcs(params):return f"{params['data_type']}_{params['bits']}", None- def fake_qdq(weight, params, *, quant_func=None, opt_quant_func=None, imatrix=None):+ def fake_qdq(weight, params, *, quant_func=None, opt_quant_func=None, imatrix=None, init_scale=None):records.append((params["data_type"], params["bits"], quant_func))return weight@@ -986,6 +986,277 @@ class TestAWQUseV2ScaleSearch:compressor = self._make_compressor(block)assert q._qdq_tool._block_quantizer_is_signroundv2(compressor) is False+ def test_v2_scale_search_policy(self):+ """AWQ policy changes internal QDQ without disabling the intrinsic terminal V2 extension."""+ from auto_round.algorithms.quantization.sign_round.config import SignRoundV2Config+ from auto_round.algorithms.transforms.awq.base import AWQTransform+ from auto_round.algorithms.transforms.awq.config import AWQConfig++ block = SignRoundV2Config(iters=1)+ compressor = self._make_compressor(block)++ off = AWQTransform(AWQConfig(v2_scale_search="off"))+ off._qdq_tool.configure(compressor, off.config)+ assert (+ off._qdq_tool.resolve_quant_funcs(+ {"data_type": "int", "bits": 3, "sym": True, "group_size": 128, "disable_opt_rtn": True}+ )[1]+ is None+ )++ reuse = AWQTransform(AWQConfig(v2_scale_search="reuse"))+ reuse._qdq_tool.configure(compressor, reuse.config)+ assert (+ reuse._qdq_tool.resolve_quant_funcs(+ {"data_type": "int", "bits": 2, "sym": True, "group_size": 64, "disable_opt_rtn": True}+ )[1]+ is not None+ )+ assert block.enable_alg_ext is True++ def test_v2_scale_search_defaults_off_for_int(self):+ """The default policy uses plain RTN for INT and full search for MX/NV."""+ from auto_round.algorithms.quantization.sign_round.config import SignRoundV2Config+ from auto_round.algorithms.transforms.awq.base import AWQTransform+ from auto_round.algorithms.transforms.awq.config import AWQConfig++ block = SignRoundV2Config(iters=1)+ compressor = self._make_compressor(block)+ auto = AWQTransform(AWQConfig())+ auto._qdq_tool.configure(compressor, auto.config)++ assert auto.config.v2_scale_search == "auto"+ assert (+ auto._qdq_tool.resolve_quant_funcs(+ {"data_type": "int", "bits": 4, "sym": True, "group_size": 128, "disable_opt_rtn": True}+ )[1]+ is None+ )+ assert (+ auto._qdq_tool.resolve_quant_funcs(+ {"data_type": "mx_fp4", "bits": 4, "sym": True, "group_size": 32, "disable_opt_rtn": True}+ )[1]+ is not None+ )++ def test_reuse_computes_v2_scale_once_per_balance_layer(self, monkeypatch):+ """Reuse avoids repeating the optimized scale search for each AWQ candidate."""+ import torch.nn as nn++ import auto_round.algorithms.transforms.awq.smooth as awq_smooth+ from auto_round.algorithms.transforms.awq.base import AWQTransform+ from auto_round.algorithms.transforms.awq.config import AWQConfig+ from auto_round.algorithms.transforms.awq.mappings import ResolvedMapping++ smooth = nn.Linear(4, 4, bias=False)+ balance = nn.Linear(4, 4, bias=False)+ balance.global_name = "block.balance"+ mapping = ResolvedMapping(+ smooth_name="block.smooth",+ smooth_layer=smooth,+ balance_names=[balance.global_name],+ balance_layers=[balance],+ parent_name="block",+ parent=nn.Module(),+ )+ transform = AWQTransform(AWQConfig(v2_scale_search="reuse", n_grid=2))+ transform._qdq_tool.v2_scale_search = "reuse"+ transform._qdq_tool.layer_config = {+ balance.global_name: {+ "bits": 4,+ "group_size": 4,+ "sym": True,+ "data_type": "int_sym",+ "disable_opt_rtn": True,+ }+ }+ transform._qdq_tool.use_v2_scale_search = True+ transform._get_grid_search_params = lambda: [(0.0, False), (1.0, False)]++ calls = []++ def fake_scale(weight, *_args, **_kwargs):+ calls.append(weight)+ return torch.ones(weight.shape[0], 1)++ monkeypatch.setattr(awq_smooth, "compute_optimized_init_scale", fake_scale)+ result = transform._grid_search_scales(mapping, torch.ones(4))++ assert result is not None+ assert len(calls) == 1++ def test_v2_scale_search_config_validation(self):+ """Reject misspelled scale-search policies."""+ import pytest++ from auto_round.algorithms.transforms.awq.config import AWQConfig++ with pytest.raises(ValueError, match="v2_scale_search"):+ AWQConfig(v2_scale_search="fast")++ def test_v2_scale_search_cli_registration(self):+ """Expose the low-bit scale-search policy through the generic CLI registry."""+ from auto_round.algorithms.transforms.awq.config import AWQConfig++ parameters = {parameter.field: parameter for parameter in AWQConfig.get_registered_args().parameters}+ assert parameters["v2_scale_search"].argparse_kwargs["default"] == "auto"+ assert parameters["v2_scale_search"].argparse_kwargs["choices"] == ("auto", "full", "off", "reuse")++ def test_awq_nsamples_cli_and_validation(self):+ """AWQ sample cap is independent, user-facing, and strictly positive."""+ import pytest++ from auto_round.algorithms.transforms.awq.config import AWQConfig++ parameters = {parameter.field: parameter for parameter in AWQConfig.get_registered_args().parameters}+ assert parameters["awq_nsamples"].argparse_kwargs["dest"] == "awq_nsamples"+ assert parameters["awq_nsamples"].argparse_kwargs["default"] == 128+ config = AWQConfig(nsamples=256, awq_nsamples=17)+ assert config.nsamples == 256+ assert config.awq_nsamples == 17+ with pytest.raises(ValueError, match="positive integer"):+ AWQConfig(awq_nsamples=0)+ with pytest.raises(ValueError, match="positive integer"):+ AWQConfig(awq_nsamples=1.5)+ with pytest.raises(ValueError, match="positive integer"):+ AWQConfig(awq_nsamples=True)++ def test_awq_integer_option_validation(self):+ """AWQ integer controls reject floats and booleans at construction time."""+ import pytest++ from auto_round.algorithms.transforms.awq.config import AWQConfig++ with pytest.raises(ValueError, match="awq_seqlen"):+ AWQConfig(awq_seqlen=1.5)+ with pytest.raises(ValueError, match="awq_seqlen"):+ AWQConfig(awq_seqlen=True)+ with pytest.raises(ValueError, match="smooth_batch_size"):+ AWQConfig(smooth_batch_size=1.5)+ with pytest.raises(ValueError, match="smooth_batch_size"):+ AWQConfig(smooth_batch_size=True)++ def test_awq_nsamples_random_subset_is_deterministic(self):+ """AWQ uses a stable random subset without changing quantizer inputs."""+ from auto_round.algorithms.block_runner import BlockForwardRunner+ from auto_round.algorithms.transforms.awq.base import AWQTransform+ from auto_round.algorithms.transforms.awq.config import AWQConfig++ transform = AWQTransform(AWQConfig(awq_nsamples=3))+ runner = BlockForwardRunner(batch_size=2, enable_torch_compile=False)+ transform.bind_block_forward_runner(runner)+ inputs = [torch.full((1, 2, 4), idx, dtype=torch.float32) for idx in range(8)]+ others = {"position_ids": [torch.full((1, 2), idx) for idx in range(8)]}++ selected_inputs, selected_others = transform.select_calibration_samples(inputs, others)+ expected = torch.randperm(8, generator=torch.Generator().manual_seed(42))[:3].sort().values+ assert selected_inputs[:, 0, 0].to(torch.long).tolist() == expected.tolist()+ assert selected_others["position_ids"][:, 0].tolist() == expected.tolist()+ assert len(inputs) == 8++ repeated_inputs, _ = transform.select_calibration_samples(inputs, others)+ assert torch.equal(selected_inputs, repeated_inputs)++ def test_awq_smoothing_preserves_fp_function(self):+ """Inverse folding keeps the smooth-to-balance FP path unchanged."""+ import torch.nn as nn++ from auto_round.algorithms.transforms.awq.base import AWQTransform+ from auto_round.algorithms.transforms.awq.config import AWQConfig+ from auto_round.algorithms.transforms.awq.mappings import ResolvedMapping++ torch.manual_seed(0)+ smooth = nn.Linear(4, 6, bias=True)+ balance = nn.Linear(6, 3, bias=False)+ mapping = ResolvedMapping(+ smooth_name="block.smooth",+ smooth_layer=smooth,+ balance_names=["block.balance"],+ balance_layers=[balance],+ parent_name="block",+ parent=nn.Sequential(smooth, balance),+ )+ inputs = torch.randn(2, 5, 4)+ expected = balance(smooth(inputs))+ scales = torch.tensor([0.5, 0.75, 1.25, 1.5, 2.0, 0.8])++ AWQTransform(AWQConfig())._apply_scales(mapping, scales)++ assert torch.allclose(balance(smooth(inputs)), expected, atol=1e-6, rtol=1e-5)++ def test_awq_clip_as_init_does_not_modify_weight(self, monkeypatch):+ """clip_as_init records bounds without hard-clamping the FP block."""+ import torch.nn as nn++ from auto_round.algorithms.transforms.awq.base import AWQTransform+ from auto_round.algorithms.transforms.awq.config import AWQConfig+ from auto_round.algorithms.transforms.awq.mappings import ResolvedMapping++ layer = nn.Linear(4, 2, bias=False)+ layer.global_name = "block.balance"+ smooth = nn.Linear(4, 4, bias=False)+ mapping = ResolvedMapping(+ smooth_name="block.smooth",+ smooth_layer=smooth,+ balance_names=[layer.global_name],+ balance_layers=[layer],+ parent_name="block",+ parent=nn.Module(),+ )+ transform = AWQTransform(AWQConfig(apply_clip=True, clip_as_init=True))+ transform._clip_input_feat[mapping.smooth_name] = torch.randn(3, 4)+ clip_min = torch.full((2, 1, 1), -0.5)+ clip_max = torch.full((2, 1, 1), 0.5)+ monkeypatch.setattr(transform, "_compute_best_clip", lambda *_args: (clip_min, clip_max))+ original_weight = layer.weight.detach().clone()++ transform._clip_block("block", [mapping])++ assert torch.equal(layer.weight, original_weight)+ assert torch.equal(layer.awq_clip_min, clip_min)+ assert torch.equal(layer.awq_clip_max, clip_max)++ def test_awq_reference_invalidation_requires_an_applied_transform(self):+ """Skipped mappings and clip-as-init alone keep a supplied reference valid."""+ import torch.nn as nn++ from auto_round.algorithms.composer import BlockContext+ from auto_round.algorithms.transforms.awq.base import AWQTransform+ from auto_round.algorithms.transforms.awq.config import AWQConfig+ from auto_round.algorithms.transforms.awq.mappings import ResolvedMapping++ block_name = "block"+ ctx = BlockContext(model=None, block_names=[block_name], block_name=block_name, block_index=0)+ smooth = nn.Linear(4, 4, bias=False)+ balance = nn.Linear(4, 4, bias=False)+ mapping = ResolvedMapping(+ smooth_name="block.smooth",+ smooth_layer=smooth,+ balance_names=["block.balance"],+ balance_layers=[balance],+ parent_name=block_name,+ parent=nn.Module(),+ )++ clip_init = AWQTransform(AWQConfig(apply_smooth=False, apply_clip=True, clip_as_init=True))+ clip_init._block_mappings = {block_name: [mapping]}+ clip_init._activation_stats[mapping.smooth_name] = [torch.ones(4), 1]+ clip_init._clip_input_feat[mapping.smooth_name] = torch.randn(2, 4)+ clip_init._qdq_tool.layer_config = {}+ clip_init._compute_best_clip = lambda *_args: (+ torch.full((4, 1, 1), -0.5),+ torch.full((4, 1, 1), 0.5),+ )+ clip_init.pre_quantize_block(ctx)+ assert clip_init.invalidates_reference_output(ctx) is False++ skipped = AWQTransform(AWQConfig(apply_smooth=True))+ skipped._block_mappings = {block_name: [mapping]}+ skipped._activation_stats[mapping.smooth_name] = [torch.ones(4), 1]+ skipped._mapping_is_smoothable = lambda _mapping: False+ skipped.pre_quantize_block(ctx)+ assert skipped.invalidates_reference_output(ctx) is False+def test_qdq_configure_resolves_opt_rtn_policy_and_legacy_shapes(self):"""QDQ wiring covers AWQ-owned policy plus legacy compressor-shaped callers."""from auto_round.algorithms.composer import AlgorithmComposerdiff --git a/test/unit/test_cuda/algorithms/test_awq.py b/test/unit/test_cuda/algorithms/test_awq.pyindex da1459920..7ef1ede6f 100644--- a/test/unit/test_cuda/algorithms/test_awq.py+++ b/test/unit/test_cuda/algorithms/test_awq.py@@ -531,7 +531,7 @@ class TestAWQMoE:def fake_resolve_quant_funcs(params):return f"{params['data_type']}_{params['bits']}", None- def fake_qdq(weight, params, *, quant_func=None, opt_quant_func=None, imatrix=None):+ def fake_qdq(weight, params, *, quant_func=None, opt_quant_func=None, imatrix=None, init_scale=None):records.append((params["data_type"], params["bits"], quant_func))return weightdiff --git a/test/unit/test_xpu/algorithms/test_awq.py b/test/unit/test_xpu/algorithms/test_awq.pyindex 9bbb8cb1a..e4f9dc1e0 100644--- a/test/unit/test_xpu/algorithms/test_awq.py+++ b/test/unit/test_xpu/algorithms/test_awq.py@@ -527,7 +527,7 @@ class TestAWQMoE:def fake_resolve_quant_funcs(params):return f"{params['data_type']}_{params['bits']}", None- def fake_qdq(weight, params, *, quant_func=None, opt_quant_func=None, imatrix=None):+ def fake_qdq(weight, params, *, quant_func=None, opt_quant_func=None, imatrix=None, init_scale=None):records.append((params["data_type"], params["bits"], quant_func))return weight