PTQ-Level Efficiency, QAT-Level Accuracy | 训练后量化的效率,量化感知训练的精度
Prefetch next batch to CUDA for SignRound v1/v2 under low_gpu_mem_usage (#2549)
Wenhua Cheng3f86dea7b639
diff --git a/README.md b/README.mdindex bfbddc406..22f6829ff 100644--- a/README.md+++ b/README.md@@ -50,6 +50,8 @@ It integrates with popular ecosystems including Transformers, vLLM, and SGLang,## 🆕 What's New+* [2026/10] We now show that **W2A16** accuracy improves steadily as more tuning cost is invested. See the [W2A16 accuracy results](./docs/alg_202508.md).+* [2026/09] We improved MoE tuning speed by more than 3× and significantly reduced RAM usage. See the [doc](./docs/moe.md) for detailed results. Please note that this optimization may introduce some regressions or issues.* [2026/09] We now support 5/6/7-bit WOQ models in vLLM and Transformers on CUDA devices, thanks to Humming Kernel.@@ -214,6 +216,9 @@ auto-round-fast \In conclusion, we recommend using **auto-round for W4A16 and auto-round-best with `enable_alg_ext` for W2A16**. However, you may adjust theconfiguration to suit your specific requirements and available resources.+> [!TIP]+> For **INT2 (W2A16)**, accuracy improves steadily as you invest more tuning cost. Increasing knobs such as `--iters` (e.g. 1000 → 2000), `--nsamples`, and `--seqlen`, or switching to the `auto-round-best` recipe with `--enable_alg_ext`, trades additional tuning time for consistently higher accuracy. As you scale up the calibration data (larger `--nsamples`/`--seqlen`), raising the learning rate to `4.0/iters` (e.g. `4e-3` at `--iters 1000`) often helps. See the [W2A16 accuracy results](./docs/alg_202508.md) for details.+### API Usage```pythondiff --git a/README_CN.md b/README_CN.mdindex 881523c86..4e11ea31e 100644--- a/README_CN.md+++ b/README_CN.md@@ -49,6 +49,8 @@ AutoRound 旨在以合理的量化成本在低比特场景下实现出色的精## 🆕 最新进展+* [2026/10] 我们现在展示:**W2A16** 的精度会随着调优成本的增加而稳步提升。详细精度数据见 [W2A16 精度数据](./docs/alg_202508.md)。+* [2026/09] 我们将 MoE量化速度提升了 3 倍以上,并显著降低了 RAM 使用量。详细结果请参阅[文档](./docs/moe.md)。请注意,该优化可能会引入一些回归问题或其他问题。* [2026/09] 现在支持在 CUDA 设备上通过 vLLM 和 Transformers 使用 5/6/7-bit WOQ 模型,感谢 Humming Kernel 的支持。@@ -223,6 +225,9 @@ auto-round-fast \小结:对于 **W4A16 量化,我们建议使用默认的 auto-round;而 W2A16 量化我们则推荐启用 `enable_alg_ext` 参数的 auto-round-best**。当然,您也可以根据自身需求和手头上的算力灵活调整配置。+> [!TIP]+> 对于 **INT2(W2A16)**,精度会随着调优成本的增加而稳步提升。增大 `--iters`(例如 1000 → 2000)、`--nsamples`、`--seqlen` 等参数,或改用带 `--enable_alg_ext` 的 `auto-round-best` 配方,都能以额外的调优时间换取持续更高的精度。随着校准数据量的增大(更大的 `--nsamples`/`--seqlen`),将学习率提高到 `4.0/iters`(例如 `--iters 1000` 时取 `4e-3`)通常会有帮助。详细结果请参阅 [W2A16 精度数据](./docs/alg_202508.md)。+### API 用法```pythondiff --git a/auto_round/algorithms/composer.py b/auto_round/algorithms/composer.pyindex 46b3e28d3..79e7cd44e 100644--- a/auto_round/algorithms/composer.py+++ b/auto_round/algorithms/composer.py@@ -544,6 +544,10 @@ class AlgorithmComposer:input_ids=input_ids,)+ # Quantizer-agnostic block finalization (e.g. NVFP MoE act_max), kept+ # out of the per-algorithm tuning loop.+ self.block_quantizer.finalize_block(block, block_ctx)+# ── Step 5: post_quantize_block ─────────────────────────────────────────for pre in self.preprocessors:pre.post_quantize_block(block_ctx)diff --git a/auto_round/algorithms/quantization/base.py b/auto_round/algorithms/quantization/base.pyindex c5799ece4..ef6f58062 100644--- a/auto_round/algorithms/quantization/base.py+++ b/auto_round/algorithms/quantization/base.py@@ -356,6 +356,23 @@ class BaseQuantizer(BaseAlgorithm):block = block.to(device_manager.device)return block+ def finalize_block(self, block: "torch.nn.Module", block_ctx: "BlockContext | None" = None) -> None:+ """Post-tuning, quantizer-agnostic finalization for a compressed block.++ Invoked by the composer right after :meth:`quantize_block` returns, so+ format-specific post-processing stays out of the per-algorithm tuning+ loop. The default generates MoE experts' ``act_max`` automatically for+ NVFP static-activation schemes (``WrapperWALayer``); it is a no-op for+ schemes/blocks that do not need it. Subclasses may override to add their+ own finalization.+ """+ from auto_round.schemes import is_nvfp4_e5m3_gs+ from auto_round.utils import set_amax_for_all_moe_layers++ if self.config.is_act_nv_fp or is_nvfp4_e5m3_gs(self.config.act_data_type or ""):+ # enable moe experts act_max automatic generation for WrapperWALayer+ set_amax_for_all_moe_layers(block, attr_name="orig_layer.act_max")+# ── Lifecycle hooks ───────────────────────────────────────────────────────def prepare_run(self, composer: "AlgorithmComposer" = None) -> None:"""Model-level preparation (called once before block iteration starts)."""diff --git a/auto_round/algorithms/quantization/sign_round/quantizer.py b/auto_round/algorithms/quantization/sign_round/quantizer.pyindex ff95463ac..a04fc13c2 100644--- a/auto_round/algorithms/quantization/sign_round/quantizer.py+++ b/auto_round/algorithms/quantization/sign_round/quantizer.py@@ -31,7 +31,6 @@ from auto_round.compressors.utils import (snapshot_best_params,)from auto_round.logger import logger-from auto_round.schemes import is_nvfp4_e5m3_gsfrom auto_round.utils.perf_counters import _PerfCounters@@ -92,7 +91,6 @@ from auto_round.utils import (htcore,is_hpex_available,mv_module_from_gpu,- set_amax_for_all_moe_layers,)from auto_round.utils.device import clear_memory_if_reached_thresholdfrom auto_round.utils.device_manager import device_manager@@ -406,6 +404,59 @@ class SignRoundQuantizer(BaseQuantizer):# tensor nor an autograd graph through softmax.return soft_cross_entropy(q_logits, fp_logits, valid_mask)+ def _resolve_tuning_cache_plan(+ self,+ *,+ device,+ loss_device,+ active_inputs,+ block_fwd,+ lfq_last_block,+ ) -> tuple[type | None, Any]:+ """Decide the opt-in CUDA batch-prefetch staging for a tuning block.++ Returns ``(cache_cls, cache_budget)`` when the prefetch cache is+ eligible, or ``(None, 0)`` to keep the legacy synchronous gather. This+ is the single extension point for prefetch-cache variants: the tuning+ loop never branches on model type. The diffusion vs LLM/VLM class choice+ is delegated to+ :func:`auto_round.algorithms.tuning_cache.resolve_tuning_cache_cls`, and+ subclasses can override this method wholesale to plug in new variants+ without editing the algorithm.++ Under ``low_gpu_mem_usage`` the calibration pools are parked on the host,+ so every iteration copies its batch CPU->CUDA on the critical path. The+ cache double-buffers the batches onto CUDA on a background copy stream so+ the next transfer overlaps the current forward/backward.+ """+ from auto_round.algorithms.tuning_cache import resolve_tuning_cache_cls++ # Shared hardware eligibility: host-parked pools, a single CUDA device,+ # and a loss device that matches the compute device.+ if not (+ self.compress_context.low_gpu_mem_usage+ and str(device).startswith("cuda")+ and len(device_manager.device_list) == 1+ and (loss_device is None or torch.device(loss_device) == torch.device(device))+ ):+ return None, 0++ if getattr(self.model_context, "is_diffusion", False):+ # Diffusion prefetch is strictly opt-in via diffusion_tuning_cache_size.+ budget = getattr(self.model_context, "diffusion_tuning_cache_size", 0)+ if budget != "auto" and budget <= 0:+ return None, 0+ else:+ # LLM/VLM reconstruction needs a list input pool and a block forward.+ # The LFQ final-block logit loss concatenates token ids and runs a+ # different forward, so it keeps the legacy gather.+ if not (isinstance(active_inputs, list) and block_fwd is not None) or lfq_last_block:+ return None, 0+ # Auto-size the staging buffers after one warmup iteration.+ budget = "auto"++ return resolve_tuning_cache_cls(self.model_context), budget+def quantize_block(self,block,@@ -576,16 +627,24 @@ class SignRoundQuantizer(BaseQuantizer):)tuning_cache = None- # Only opt-in diffusion tuning can enter the CUDA staging path.- cache_budget = getattr(self.model_context, "diffusion_tuning_cache_size", 0)- use_tuning_cache = (- getattr(self.model_context, "is_diffusion", False)- and (cache_budget == "auto" or cache_budget > 0)- and self.compress_context.low_gpu_mem_usage- and str(device).startswith("cuda")- and len(device_manager.device_list) == 1- and (loss_device is None or torch.device(loss_device) == torch.device(device))+ # The LFQ final-block logit loss concatenates token ids and runs a+ # different forward, so it is excluded from the prefetch staging path.+ _lfq_last_block = (+ getattr(self, "enable_lfq", False)+ and input_ids is not None+ and block_ctx.block_index == block_ctx.block_cnt - 1+ and self._is_text_decoder_block(block_ctx.block_name))+ # Single, variant-free extension point: the plan hook owns all model-type+ # gating (diffusion vs LLM/VLM) and returns the cache class + budget.+ cache_cls, cache_budget = self._resolve_tuning_cache_plan(+ device=device,+ loss_device=loss_device,+ active_inputs=active_inputs,+ block_fwd=block_fwd,+ lfq_last_block=_lfq_last_block,+ )+ use_prefetch_cache = cache_cls is not None_perf.stop("prepare")_perf.start("loop")@@ -615,7 +674,7 @@ class SignRoundQuantizer(BaseQuantizer):# stages batches to the GPU itself via pinned slots); a bulk pull# onto the loss device would put the cached reference outputs on# cuda and the cache would decline every batch signature- if fp_outputs and loss_device is not None and not use_tuning_cache:+ if fp_outputs and loss_device is not None and not use_prefetch_cache:fp_outputs = self.pull_tuning_pool(fp_outputs,loss_device,@@ -629,10 +688,8 @@ class SignRoundQuantizer(BaseQuantizer):for i in range(self.iters):# Auto observes a complete forward/backward/optimizer iteration# on the legacy path before allocating any extra GPU buffers.- if use_tuning_cache and i == (1 if cache_budget == "auto" else 0):- from auto_round.compressors.diffusion.tuning_cache import DiffusionTuningCache-- tuning_cache = DiffusionTuningCache.create(+ if use_prefetch_cache and i == (1 if cache_budget == "auto" else 0):+ tuning_cache = cache_cls.create(block,block_fwd,active_inputs,@@ -770,10 +827,6 @@ class SignRoundQuantizer(BaseQuantizer):_perf.stop("tail")_log_tune_phases(_perf, self.iters)- if self.config.is_act_nv_fp or is_nvfp4_e5m3_gs(self.config.act_data_type or ""):- # enable moe experts act_max automatic generation for WrapperWALayer- set_amax_for_all_moe_layers(block, attr_name="orig_layer.act_max")-logger.infoclean(dump_info)return best_paramsdiff --git a/auto_round/algorithms/quantization/sign_roundv2/quantizer.py b/auto_round/algorithms/quantization/sign_roundv2/quantizer.pyindex 114f3c906..afffc8dd3 100644--- a/auto_round/algorithms/quantization/sign_roundv2/quantizer.py+++ b/auto_round/algorithms/quantization/sign_roundv2/quantizer.py@@ -41,6 +41,7 @@ from auto_round.data_type.utils import (reshape_imatrix_for_weight,reshape_pad_tensor_by_group_size,resolve_optimized_init_scale_fn,+ resolve_optimized_init_scale_zero_fn,revert_tensor_by_pad,round_ste,search_optimized_init_scale,@@ -113,6 +114,9 @@ class SignRoundOptimizedWrapperLinear(WrapperLinear):layer = self.orig_layerdata_type = layer.data_type+ # asym int threads an extra per-group integer zero point alongside the+ # searched scale (sym / mx / nv keep the scale-only contract)+ self._is_asym = "asym" in data_typeweight_reshape = self._prepare_init_scale_weight()# staged deferral keeps only the RAW column imatrix (or None): the# expanded full-size copy would be pinned per module for the whole@@ -122,14 +126,18 @@ class SignRoundOptimizedWrapperLinear(WrapperLinear):imatrix = None if defer_search else reshape_imatrix_for_weight(imatrix_raw, weight_reshape, layer.group_size)self.weight_quant_func = get_optimized_quant_func(data_type)- search_fn = resolve_optimized_init_scale_fn(data_type, self.q_scale_thresh)+ if self._is_asym:+ search_fn = resolve_optimized_init_scale_zero_fn(data_type, self.q_scale_thresh)+ else:+ search_fn = resolve_optimized_init_scale_fn(data_type, self.q_scale_thresh)if search_fn is None or self.weight_quant_func is None:raise ValueError(f"SignRound optimized path does not support data_type={data_type!r}; "- "expected a symmetric int / mx / nv type."+ "expected a symmetric int / mx / nv type or an asymmetric int type.")self.data_type = data_typeself.init_scale = None+ self.init_zp = Noneself._deferred_search_inputs = Noneif defer_search:# staged for run_batched_wrap_search: the exact callable the@@ -143,23 +151,40 @@ class SignRoundOptimizedWrapperLinear(WrapperLinear):search_fn,)else:- self.init_scale = search_fn(weight_reshape, layer.bits, imatrix)+ self._assign_search_result(search_fn(weight_reshape, layer.bits, imatrix))if hasattr(layer, "imatrix"):del layer.imatrixif self.enable_torch_compile:self.weight_quant_func = compile_func(self.weight_quant_func, self.device)+ def _assign_search_result(self, result) -> None:+ """Store an init-scale search result (asym also carries an integer zp)."""+ if getattr(self, "_is_asym", False):+ self.init_scale, self.init_zp = result+ else:+ self.init_scale = result++ def _extra_quant_kwargs(self) -> dict:+ """Thread the searched integer zero point into the asym quant func."""+ if getattr(self, "_is_asym", False) and getattr(self, "init_zp", None) is not None:+ return {"init_zp": self.init_zp}+ return {}+def _run_deferred_search_now(self) -> None:"""Run the staged search per-module (fallback when batching is off)."""weight, _data_type, bits, imatrix_raw, _thresh, search_fn = self._deferred_search_inputsimatrix = reshape_imatrix_for_weight(imatrix_raw, weight, self.orig_layer.group_size)- self.init_scale = search_fn(weight, bits, imatrix)+ self._assign_search_result(search_fn(weight, bits, imatrix))self._deferred_search_inputs = Nonedef finalize_batched_search(self, init_scale: "torch.Tensor | list[torch.Tensor]") -> None:- """Adopt a search result computed on a stacked same-shape batch."""- self.init_scale = init_scale+ """Adopt a search result computed on a stacked same-shape batch.++ For asym int the per-module (singleton) lane passes the ``(scale, zp)``+ tuple straight through; sym / mx / nv receive the single scale tensor.+ """+ self._assign_search_result(init_scale)self._deferred_search_inputs = Nonedef _prepare_init_scale_weight(self) -> torch.Tensor:@@ -370,20 +395,22 @@ class SignRoundV2Quantizer(SignRoundQuantizer):super().prepare_run(composer=composer)if (- self.scheme.sym- and self.scheme.super_group_size is None+ self.scheme.super_group_size is Noneand (self.scheme.data_type.startswith("int")or self.scheme.data_type.startswith("mx")or self.scheme.data_type.startswith("nv"))+ # mx / nv are inherently symmetric; int supports both sym and asym+ # through the optimized init-scale (+ zero-point) search.+ and (self.scheme.sym or self.scheme.data_type.startswith("int"))):if self.scheme.bits > 2 and not (self.scheme.data_type.startswith("mx") or self.scheme.data_type.startswith("nv")):logger.warning_once("algorithm extension has only undergone limited validation on "- "W2A16,INT4, MXFP4 and NVFP4; use with caution."+ "W2A16, INT4, MXFP4 and NVFP4; use with caution.")if self.scheme.act_bits <= 4 or self.scheme.bits < 4:self._use_outlier_suppressed_loss = True@@ -395,7 +422,10 @@ class SignRoundV2Quantizer(SignRoundQuantizer):self.wrapper_block = _named_wrapper_block(SignRoundDQWrapperLinear, "dq_wrapper_block")def can_compile_block_forward(self):- return False+ # torch.compile on the whole block forward is only reliable on torch >= 2.14+ from packaging.version import Version++ return Version(torch.__version__.split("+")[0]) >= Version("2.13")def _get_loss(self,diff --git a/auto_round/compressors/diffusion/tuning_cache.py b/auto_round/algorithms/tuning_cache.pysimilarity index 71%rename from auto_round/compressors/diffusion/tuning_cache.pyrename to auto_round/algorithms/tuning_cache.pyindex cd3fbccfd..26f098601 100644--- a/auto_round/compressors/diffusion/tuning_cache.py+++ b/auto_round/algorithms/tuning_cache.py@@ -12,7 +12,16 @@# See the License for the specific language governing permissions and# limitations under the License.-"""Opt-in, bounded CUDA staging for diffusion SignRound batches."""+"""Opt-in, bounded CUDA batch prefetch for SignRound block-reconstruction tuning.++Under ``low_gpu_mem_usage`` the calibration pools are parked on the host, so+every tuning iteration copies its batch CPU->CUDA on the critical path. This+module double-buffers the batches onto CUDA on a background copy stream so the+host->device transfer of the next batch overlaps the forward/backward of the+current one. :class:`BlockTuningPrefetchCache` is the generic (LLM/VLM) staging+cache; :class:`DiffusionTuningCache` specializes it for diffusion's+single-sample batches.+"""import queueimport random@@ -94,20 +103,39 @@ def _auto_budget_bytes(free_bytes):return max(0, min(free_bytes // 2, free_bytes - 2**30))-class DiffusionTuningCache:+class BlockTuningPrefetchCache:"""Two reusable host/device slots, with optional in-place best snapshots.+ Generic CUDA batch-prefetch staging cache for block-reconstruction tuning+ (LLM/VLM). Stages the multi-sample batches used by the block loop (the+ concatenated block inputs, the auxiliary ``input_others`` and the reference+ output) from the host calibration pools onto CUDA on a background copy+ stream.+The budget covers these persistent CUDA buffers only, not the trainingactivations/workspace. Pinned host memory is bounded by the two batch slots.The caller must close the cache after backward, including on early exit."""+ #: Human-readable prefix used in log messages (overridden by subclasses so+ #: the diffusion variant advertises itself as "Diffusion").+ LABEL = "Block tuning"+ #: The generic path stages multi-sample batches; the diffusion subclass sets+ #: this ``True`` to restrict itself to single-sample (``batch_size == 1``)+ #: batches.+ _require_batch_size_one = False+ #: The per-block budget / "prefetch enabled" summary is identical across+ #: blocks, so it is logged at INFO only for the first block that enables the+ #: cache (subsequent blocks log it at DEBUG). Tracked per class so the+ #: diffusion and generic variants each announce themselves once.+ _summary_logged = False+@classmethoddef create(cls, block, runner, inputs, others, outputs, sampler, iters, budget_gib, device):# Single-output blocks (e.g. Wan) pass a tensor list to the next block.if isinstance(inputs, list):inputs = {"hidden_states": inputs}- if runner.batch_size != 1 or not isinstance(inputs, dict) or iters <= 0:+ if (cls._require_batch_size_one and runner.batch_size != 1) or not isinstance(inputs, dict) or iters <= 0:return Nonecache = cls()cache.runner, cache.inputs, cache.others, cache.outputs = runner, inputs, others, outputs@@ -119,7 +147,8 @@ class DiffusionTuningCache:cache.signature = _signature(template)if cache.signature is None:logger.info(- "Diffusion tuning prefetch skipped: batch signature rejected (%s).",+ "%s prefetch skipped: batch signature rejected (%s).",+ cls.LABEL,_signature_decline_reason(template),)return None@@ -137,9 +166,10 @@ class DiffusionTuningCache:_auto_budget_bytes(free_bytes) if budget_gib == "auto" else int(min(budget_gib, free_bytes / 2**30) * 2**30))if budget_gib == "auto":- logger.info("Diffusion tuning auto cache budget after warmup: %.2f GiB.", budget / 2**30)+ _summary_log = logger.info if not cls._summary_logged else logger.debug+ _summary_log("%s auto cache budget after warmup: %.2f GiB.", cls.LABEL, budget / 2**30)if staging_bytes > budget:- logger.info("Diffusion tuning prefetch skipped: two batch buffers exceed the cache budget.")+ logger.info("%s prefetch skipped: two batch buffers exceed the cache budget.", cls.LABEL)return Nonecache.stop = threading.Event()cache.free, cache.ready = queue.Queue(), queue.Queue()@@ -165,18 +195,29 @@ class DiffusionTuningCache:cache.thread.start()except torch.OutOfMemoryError:cache.close()- logger.info("Diffusion tuning prefetch skipped: buffer allocation ran out of memory.")+ logger.info("%s prefetch skipped: buffer allocation ran out of memory.", cls.LABEL)return None- logger.info(- "Diffusion tuning prefetch enabled with %.2f GiB of GPU buffers; best parameters on %s.",+ _summary_log = logger.info if not cls._summary_logged else logger.debug+ _summary_log(+ "%s prefetch enabled with %.2f GiB of GPU buffers; best parameters on %s.",+ cls.LABEL,(staging_bytes + (best_bytes if cache.best is not None else 0)) / 2**30,"GPU" if cache.best is not None else "CPU",)+ cls._summary_logged = Truereturn cachedef _select(self, indices):inputs, others = self.runner.select_batch(self.inputs, self.others, torch.tensor(indices, dtype=torch.long))- return inputs, others, self.outputs[indices[0]]+ # Single-sample (diffusion) batches return the lone reference tensor+ # untouched; multi-sample (LLM/VLM block reconstruction) batches gather+ # the per-sample references and concatenate them along the batch dim so+ # the staged reference matches the concatenated block output.+ if len(indices) == 1:+ ref = self.outputs[indices[0]]+ else:+ ref = torch.cat([self.outputs[i] for i in indices], dim=self.runner.batch_dim)+ return inputs, others, refdef _produce(self, first):try:@@ -226,7 +267,7 @@ class DiffusionTuningCache:# keep up, release its buffers and let the caller use the legacy# synchronous path for the current batch.self.close()- logger.info("Diffusion tuning prefetch timed out; falling back to the legacy path.")+ logger.info("%s prefetch timed out; falling back to the legacy path.", self.LABEL)return Noneif isinstance(item, Exception):raise item@@ -234,7 +275,7 @@ class DiffusionTuningCache:# Dynamic shapes or a custom forward using Python RNG can invalidate# the forecast. Consume the actual sampler batch on the original path.self.close()- logger.info("Diffusion tuning prefetch stopped: batch structure or sample order changed.")+ logger.info("%s prefetch stopped: batch structure or sample order changed.", self.LABEL)return None_, self.current = itemslot = self.slots[self.current]@@ -271,3 +312,30 @@ class DiffusionTuningCache:torch.cuda.current_stream(self.device).synchronize()self.slots.clear()self.current = None+++class DiffusionTuningCache(BlockTuningPrefetchCache):+ """Diffusion specialization of :class:`BlockTuningPrefetchCache`.++ Diffusion SignRound tunes single-sample batches (``batch_size == 1``) with+ dict-shaped block inputs; everything else (the background copy-stream+ machinery, budgeting and best-parameter snapshots) is inherited unchanged.+ """++ LABEL = "Diffusion tuning"+ _require_batch_size_one = True+++def resolve_tuning_cache_cls(model_context) -> type[BlockTuningPrefetchCache]:+ """Return the prefetch-cache class for the active model type.++ This is the single place that knows about cache variants, so the SignRound+ tuning loop never branches on model type: it asks for a class and gets the+ diffusion specialization for diffusion pipelines, otherwise the generic+ LLM/VLM cache. New variants are added here (or by overriding the quantizer's+ ``_resolve_tuning_cache_plan`` hook) instead of threading ``if is_diffusion``+ checks through the algorithm.+ """+ if getattr(model_context, "is_diffusion", False):+ return DiffusionTuningCache+ return BlockTuningPrefetchCachediff --git a/auto_round/calib_dataset.py b/auto_round/calib_dataset.pyindex 767253a6e..b66d8857c 100644--- a/auto_round/calib_dataset.py+++ b/auto_round/calib_dataset.py@@ -370,6 +370,7 @@ def get_pile_dataset(seed=42,apply_chat_template=False,system_prompt=None,+ nsamples=512,):"""Returns a dataloader for the specified dataset and split.@@ -401,6 +402,12 @@ def get_pile_dataset(),)+ # Sample-level concat as a *fallback only*: samples already reaching seqlen+ # are preferred and kept as natural samples; short samples are packed+ # together only when there are fewer than `nsamples` full-length samples, so+ # calibration does not randomly pick packed sequences over natural ones.+ calib_dataset = _concat_samples_to_seqlen(calib_dataset, seqlen, nsamples)+return calib_dataset@@ -777,10 +784,11 @@ def get_competition_math_dataset(),)- # Sample-level concat by default: pack whole samples until each reaches- # seqlen, then reset, so short problem/solution pairs are not dropped by the- # downstream length filter.- calib_dataset = _concat_samples_to_seqlen(calib_dataset, seqlen)+ # Sample-level concat as a fallback: short problem/solution pairs are packed+ # into full-length sequences only when there are fewer than `nsamples`+ # natural full-length samples, so natural samples are preferred when+ # available and short pairs are not dropped by the downstream length filter.+ calib_dataset = _concat_samples_to_seqlen(calib_dataset, seqlen, nsamples)return calib_dataset@@ -1064,15 +1072,15 @@ def get_ultradata_agent_dataset(remove_columns=["text"],)- # Pack whole traces up to seqlen before returning. "Preferred" traces are- # chosen on their messages-only length (<= seqlen) and can remain shorter- # than seqlen even after rendering tools, so returning them unpacked would- # let _get_dataset_impl.filter_func drop them -- leaving calibration- # undersized despite available oversized fallback data. Sample-level packing- # concatenates short traces into full-length sequences, while oversized- # traces (already truncated to seqlen) each emit a single full-length- # sequence, so no usable data is lost.- calib_dataset = _concat_samples_to_seqlen(calib_dataset, seqlen)+ # Pack whole traces up to seqlen before returning, but only as a fallback.+ # "Preferred" traces are chosen on their messages-only length (<= seqlen) and+ # can remain shorter than seqlen even after rendering tools, so returning them+ # unpacked would let _get_dataset_impl.filter_func drop them -- leaving+ # calibration undersized despite available oversized fallback data. Packing+ # concatenates short traces into full-length sequences only when there are+ # fewer than `nsamples` natural full-length (oversized/truncated) traces, so+ # natural traces are preferred and no usable data is lost.+ calib_dataset = _concat_samples_to_seqlen(calib_dataset, seqlen, nsamples)return calib_dataset@@ -1381,8 +1389,21 @@ def get_local_dataset(return calib_dataset-def _concat_samples_to_seqlen(calib_dataset, seqlen):- """Pack whole samples together until each reaches ``seqlen`` tokens.+def _concat_samples_to_seqlen(calib_dataset, seqlen, nsamples=None):+ """Pack short samples into full-length sequences, as a fallback only.++ Samples that already reach ``seqlen`` are always kept as-is. Short samples+ (which the downstream length filter would otherwise drop) are packed together+ into additional ``seqlen``-length sequences.++ When ``nsamples`` is provided this packing happens **only when needed**: if+ there are already at least ``nsamples`` natural full-length samples, the short+ samples are left untouched (they will simply be dropped by the length filter),+ so calibration keeps using real, un-concatenated samples and the random+ selection never picks a packed sequence over a natural one. Packing kicks in+ only to make up a shortfall, and stops as soon as enough full-length+ sequences exist. When ``nsamples`` is ``None`` every short sample is packed+ (legacy behavior).Unlike the continuous packing in :func:`concat_dataset_element` (where asample's leftover tokens carry over into the next sequence, splitting@@ -1394,24 +1415,45 @@ def _concat_samples_to_seqlen(calib_dataset, seqlen):Args:calib_dataset: A tokenized ``Dataset`` with an ``input_ids`` column.seqlen: Target sequence length for each packed sample.+ nsamples: Desired number of calibration samples. When given, short+ samples are packed only if fewer than ``nsamples`` full-length+ samples already exist, and only until the shortfall is filled.Returns:- A new ``Dataset`` with packed ``input_ids`` / ``attention_mask`` columns.+ A new ``Dataset`` with packed ``input_ids`` / ``attention_mask`` columns,+ or the original dataset when packing is unnecessary / impossible."""- packed = []- buffer_ids = []+ # First pass: separate natural full-length samples from the short ones.+ long_samples, short_samples = [], []for example in calib_dataset:ids = example["input_ids"]if isinstance(ids, torch.Tensor):ids = ids.tolist()+ if len(ids) >= seqlen:+ long_samples.append(ids[:seqlen])+ else:+ short_samples.append(ids)++ # Enough natural full-length samples already: don't concat at all, so the+ # downstream shuffle/selection keeps picking real samples instead of packed+ # ones. (Short samples are left in place and dropped by the length filter.)+ if nsamples is not None and len(long_samples) >= nsamples:+ return calib_dataset++ # Not enough (or nsamples unknown): pack short samples to fill the gap.+ packed = []+ buffer_ids = []+ for ids in short_samples:buffer_ids.extend(ids)if len(buffer_ids) >= seqlen:- trimmed = buffer_ids[:seqlen]- packed.append({"input_ids": trimmed, "attention_mask": [1] * seqlen})+ packed.append(buffer_ids[:seqlen])# Reset: the next sample starts a fresh concatenation.buffer_ids = []+ # Stop once the total number of full-length sequences is enough.+ if nsamples is not None and len(long_samples) + len(packed) >= nsamples:+ break- if not packed:+ if not long_samples and not packed:logger.warning("Sample-level concat produced no full-length sequences (all samples ""shorter than seqlen=%d combined did not reach it). Returning the "@@ -1420,7 +1462,21 @@ def _concat_samples_to_seqlen(calib_dataset, seqlen):)return calib_dataset- return Dataset.from_list(packed)+ if packed:+ logger.info(+ "Sample-level concat: %d natural full-length samples were not enough "+ "(target nsamples=%s), packed short samples into %d additional "+ "seqlen=%d sequences.",+ len(long_samples),+ nsamples,+ len(packed),+ seqlen,+ )++ # Natural full-length samples first so they are preferred by the downstream+ # order-preserving selection; packed sequences only top up the shortfall.+ all_ids = long_samples + packed+ return Dataset.from_list([{"input_ids": ids, "attention_mask": [1] * seqlen} for ids in all_ids])def _normalize_split(split):@@ -1698,9 +1754,12 @@ def _get_generic_dataset(),)- # Pack short samples into full seqlen-length sequences when requested.+ # Pack short samples into full seqlen-length sequences when requested, as a+ # fallback only: short samples are packed just enough to make up a shortfall+ # when fewer than `nsamples` natural full-length samples exist (when+ # `nsamples` is None, every short sample is packed).if concat:- calib_dataset = _concat_samples_to_seqlen(calib_dataset, seqlen)+ calib_dataset = _concat_samples_to_seqlen(calib_dataset, seqlen, nsamples)return calib_dataset@@ -1993,11 +2052,16 @@ def _get_dataset_impl(system_prompt=system_prompt,)if get_dataset is get_fineweb_edu_dataset:+ # Scale the candidate pool with nsamples via AR_CALIB_DATA_MULTIPLIER+ # (same knob the other streaming datasets use), keeping the+ # _FINEWEB_EDU_MIN_CANDIDATES floor so small nsamples still get a+ # large enough pool after the downstream length filter.dataset_kwargs["max_samples"] = max(_FINEWEB_EDU_MIN_CANDIDATES,- data_lens.get(name, nsamples),+ data_lens.get(name, nsamples) * envs.AR_CALIB_DATA_MULTIPLIER,)elif get_dataset in (+ get_pile_dataset,get_cci3_hq_dataset,get_github_code_clean_dataset,get_opencode_instruct_dataset,diff --git a/auto_round/compressors/utils.py b/auto_round/compressors/utils.pyindex 251853590..d94a64d37 100644--- a/auto_round/compressors/utils.py+++ b/auto_round/compressors/utils.py@@ -154,11 +154,22 @@ def block_forward(input_others, input_tuple = prepare_special_model_block_inputs(block, input_ids, input_others, input_tuple)# Use the block's actual parameter name for the first positional argument.- import inspect as _inspect-- # For DDP-wrapped blocks, inspect the underlying module's signature+ # For DDP-wrapped blocks, inspect the underlying module's signature._actual_block = getattr(block, "module", block)- param_names = [p for p in _inspect.signature(_actual_block.forward).parameters.keys() if p != "self"]+ # ``inspect.signature`` is relatively expensive and the forward signature is+ # fixed for the lifetime of a block, yet this runs on *every* batch of every+ # reference/quantized-input/tuning pass (hundreds of thousands of calls for+ # large nsamples). Resolve the parameter names once and cache them on the+ # module so subsequent calls are a single attribute read.+ param_names = getattr(_actual_block, "_ar_forward_param_names", None)+ if param_names is None:+ import inspect as _inspect++ param_names = [p for p in _inspect.signature(_actual_block.forward).parameters.keys() if p != "self"]+ try:+ _actual_block._ar_forward_param_names = param_names+ except (AttributeError, RuntimeError): # pragma: no cover - exotic module types+ passblock_input_kwarg = param_names[0] if param_names else "hidden_states"if block_input_kwarg not in input_others:input_others[block_input_kwarg] = input_idsdiff --git a/auto_round/data_type/int.py b/auto_round/data_type/int.pyindex 857c83fb1..f65c39916 100644--- a/auto_round/data_type/int.py+++ b/auto_round/data_type/int.py@@ -249,6 +249,8 @@ def quant_tensor_asym(tensor_min=None,tensor_max=None,q_scale_thresh=1e-5,+ init_scale=None,+ init_zp=None,**kwargs):"""Quantize and de-quantize tensor asymmetrically.@@ -264,12 +266,34 @@ def quant_tensor_asym(tensor_max (Tensor, optional): Maximum tensor value for quantization. Defaults to None.scale_dtype: dtype of the quantized scale,as most kernels only support FP16 or FP32, while this value is importq_scale_thresh: clip the quantized scale's magnitude to this value to improve the numerical stability+ init_scale (Tensor, optional): Pre-searched per-group scale (SignRound optimized path). When set,+ ``max_scale`` tunes a coefficient on top of it and ``init_zp`` supplies the integer zero point,+ mirroring the symmetric ``quant_tensor_sym`` init branch.+ init_zp (Tensor, optional): Pre-searched per-group integer zero point paired with ``init_scale``.Returns:Quantized and de-quantized tensor, scale, zero-point"""tensor, orig_shape, pad_len = reshape_pad_tensor_by_group_size(tensor, group_size)maxq = int(2.0**bits) - 1++ if init_scale is not None:+ # SignRound optimized asym path: the (scale, integer zp) were searched+ # once at wrap time; ``max_scale`` is the per-group tuning coefficient+ # (Tensor) during tuning, or a plain scalar for a one-shot QDQ.+ if isinstance(max_scale, torch.Tensor):+ scale = init_scale * max_scale.unsqueeze(dim=-1)+ else:+ scale = init_scale * max_scale+ scale = scale.to(scale_dtype)+ scale = torch.clamp(scale, min=q_scale_thresh)+ zp = init_zp+ int_w = round_ste(tensor / scale + v)+ q = torch.clamp(int_w + zp, 0, maxq)+ qdq_result = (scale * (q - zp)).to(tensor.dtype)+ qdq_result = revert_tensor_by_pad(qdq_result, orig_shape=orig_shape, pad_len=pad_len)+ return qdq_result, scale, zp+if tensor_min is None or tensor_max is None:wmin_tmp = torch.clamp(tensor.min(-1)[0], max=0)wmax_tmp = torch.clamp(tensor.max(-1)[0], min=0)diff --git a/auto_round/data_type/utils.py b/auto_round/data_type/utils.pyindex e8eae2b94..7b68f008c 100644--- a/auto_round/data_type/utils.py+++ b/auto_round/data_type/utils.py@@ -233,10 +233,26 @@ def _resolve_optimized_dtype_funcs(data_type: str, q_scale_thresh: float = 1e-5)if dt.endswith("dq"):return None, Noneif dt.startswith("int"):- # The optimized int init-scale search is symmetric-only; asym int uses- # the standard tensor_min/tensor_max range instead.+ # The optimized int init-scale search is symmetric-only for the generic+ # single-tensor contract; asym int instead pairs the plain+ # ``quant_tensor_asym`` with a (scale, zero-point) search resolved via+ # ``resolve_optimized_init_scale_zero_fn`` (its tuple return can't travel+ # on the single-tensor search_fn path, so search_fn stays None here --+ # AWQ / ``search_optimized_init_scale`` are unaffected).if "asym" in dt:- return None, None+ # Only the exact ``int_asym`` type has an optimized path pairing the+ # plain ``quant_tensor_asym`` (rounded integer zero-point) with the+ # NeUQI (scale, integer zero-point) search. Other asymmetric int+ # variants deliberately use a different quantizer -- e.g.+ # ``int_asym_float_zp`` (GGUF q4_1/q5_1) keeps a *floating* zero point+ # via ``quant_tensor_asym_float_zp`` -- so they must NOT be silently+ # rerouted to rounded-zero-point quantization (which would write+ # incompatible metadata). They have no optimized path here.+ if dt != "int_asym":+ return None, None+ from auto_round.data_type.int import quant_tensor_asym++ return None, quant_tensor_asymfrom auto_round.data_type.int import quant_tensor_sym, search_scalesreturn _int_search_with_thresh(search_scales, q_scale_thresh), quant_tensor_sym@@ -266,6 +282,41 @@ def resolve_optimized_init_scale_fn(return search_fn+def resolve_optimized_init_scale_zero_fn(+ data_type: str, q_scale_thresh: float = 1e-5+) -> "Callable[..., tuple[torch.Tensor, torch.Tensor]] | None":+ """Resolve the asym-int joint ``(scale, integer zero-point)`` init search callable.++ Asymmetric sibling of :func:`resolve_optimized_init_scale_fn`. The symmetric+ optimized path threads a single ``init_scale`` tensor, but asym int also needs+ a per-group integer zero point, so this returns a callable+ ``(weight_reshape, bits, imatrix) -> (init_scale, init_zp)`` (NeUQI joint+ search) for asymmetric int data types, or ``None`` otherwise.++ The returned closure is intentionally per-call: the batched wrap-search+ dispatcher keys closures by ``repr`` (never merging lookalikes), so asym+ modules always take the per-module (singleton) lane -- its tuple result is+ incompatible with the stacked single-tensor write-back.+ """+ dt = str(data_type)+ # Only the exact ``int_asym`` type uses the NeUQI integer (scale, zero-point)+ # search. Other asymmetric int variants keep a different zero-point contract+ # (e.g. ``int_asym_float_zp`` uses a floating zero point), so they must not be+ # routed through this integer-zero-point search.+ if dt != "int_asym":+ return None+ from auto_round.data_type.neuqi import neuqi_search_scale_zero++ def _search_scale_zero(weight_reshape, bits, imatrix):+ qw = imatrix if isinstance(imatrix, torch.Tensor) else None+ scale, zp = neuqi_search_scale_zero(+ weight_reshape.to(torch.float32), bits, qw=qw, q_scale_thresh=q_scale_thresh+ )+ return scale.to(weight_reshape.dtype), zp.to(weight_reshape.dtype)++ return _search_scale_zero++def search_optimized_init_scale(weight_reshape: torch.Tensor,data_type: str,diff --git a/docs/alg_202508.md b/docs/alg_202508.mdindex 14828e230..3cf5bc4ff 100644--- a/docs/alg_202508.md+++ b/docs/alg_202508.md@@ -1,13 +1,18 @@- If you are evaluating LLaMA models with recent versions of Transformers, please-remove `@use_kernel_forward_from_hub("RMSNorm")` in [modeling_llama.py](https://github.com/huggingface/transformers/blob/main/src/transformers/models/llama/modeling_llama.py#L52C1-L52C40) and enable `add_bos_token`(this is set as default in AutoRound) in lm-eval to stabilize the accuracy. These adjustments affect the quantized model but not the BF16 model for the tasks evaluated in the AutoRoundv2 paper.+If you are evaluating LLaMA models with recent versions of Transformers, please+remove `@use_kernel_forward_from_hub("RMSNorm")`+in [modeling_llama.py](https://github.com/huggingface/transformers/blob/main/src/transformers/models/llama/modeling_llama.py#L52C1-L52C40)+and enable `add_bos_token`(this is set as default in AutoRound) in lm-eval to stabilize the accuracy. These adjustments+affect the quantized model but not the BF16 model for the tasks evaluated in the AutoRoundv2 paper.All other settings follow the default configurations of AutoRound and lm-eval.-| Qwen3-8B W2G64 | Avg. | arc_challenge | hellaswag | gsm8k | lambada_openai | mmlu | mmlupro | truthfulqa_mc1 | winogrande |-|:------------------------------|:------:|:-------------:|:---------:|:------:|:--------------:|:------:|:-------:|:--------------:|:----------:|-| AutoRound | 0.4373 | 0.4019 | 0.4437 | 0.4215 | 0.4826 | 0.5474 | 0.2630 | 0.3072 | 0.6314 |-| AutoRound+alg_ext | 0.4787 | 0.4275 | 0.4516 | 0.5944 | 0.5181 | 0.5773 | 0.2807 | 0.3305 | 0.6496 |-| AutoRoundBest+alg_ext lr 2e-3 | 0.4937 | 0.4505 | 0.474 | 0.5906 | 0.5556 | 0.6028 | 0.3127 | 0.3109 | 0.6527 |+| Qwen3-8B W2G64 | Avg. | arc_challenge | hellaswag | gsm8k | lambada_openai | mmlu | mmlupro | truthfulqa_mc1 | winogrande |+|:--------------------------------------------------------------------------|:------:|:-------------:|:---------:|:------:|:--------------:|:------:|:-------:|:--------------:|:----------:|+| AutoRound | 0.4373 | 0.4019 | 0.4437 | 0.4215 | 0.4826 | 0.5474 | 0.2630 | 0.3072 | 0.6314 |+| AutoRound+alg_ext | 0.4787 | 0.4275 | 0.4516 | 0.5944 | 0.5181 | 0.5773 | 0.2807 | 0.3305 | 0.6496 |+| AutoRoundBest+alg_ext lr 2e-3 | 0.4937 | 0.4505 | 0.474 | 0.5906 | 0.5556 | 0.6028 | 0.3127 | 0.3109 | 0.6527 |+| AutoRoundBest_alg_ext lr 4e-3 seqlen4096 nsamples 4096 dataset=finewebedu | 0.4977 | 0.4966 | 0.4906 | 0.5171 | 0.5397 | 0.6218 | 0.3381 | 0.3195 | 0.6582 |+| AutoRound+alg_ext iters 2000 nsamples 1024 lr 2e-3 | 0.5100 | 0.4548 | 0.4803 | 0.6505 | 0.5529 | 0.6161 | 0.3272 | 0.3256 | 0.6725 || Llama3.1-8B-Instruct W2G64 | Avg. | arc_challenge | hellaswag | gsm8k | lambada_openai | mmlu | mmlupro | truthfulqa_mc1 | winogrande ||:------------------------------|:------:|:-------------:|:---------:|:------:|:--------------:|:------:|:-------:|:--------------:|:----------:|diff --git a/test/unit/common/compressors/test_diffusion_tuning_cache.py b/test/unit/common/compressors/test_diffusion_tuning_cache.pyindex 4f4fd019b..d035a55b6 100644--- a/test/unit/common/compressors/test_diffusion_tuning_cache.py+++ b/test/unit/common/compressors/test_diffusion_tuning_cache.py@@ -18,7 +18,7 @@ import pytestimport torchfrom auto_round.algorithms.block_runner import BlockForwardRunner-from auto_round.compressors.diffusion.tuning_cache import DiffusionTuningCache, _batch_plan+from auto_round.algorithms.tuning_cache import DiffusionTuningCache, _batch_planfrom auto_round.compressors.utils import IndexSamplerdiff --git a/test/unit/test_cuda/models/test_diffusion.py b/test/unit/test_cuda/models/test_diffusion.pyindex ba0919ffe..41af3aa93 100644--- a/test/unit/test_cuda/models/test_diffusion.py+++ b/test/unit/test_cuda/models/test_diffusion.py@@ -65,7 +65,7 @@ class TestAutoRound:def test_diffusion_tune(self, tiny_flux_model_path, tmp_path, monkeypatch, low_gpu_mem_usage, cache_size):from diffusers import AutoPipelineForText2Image- from auto_round.compressors.diffusion.tuning_cache import DiffusionTuningCache+ from auto_round.algorithms.tuning_cache import DiffusionTuningCachecaches = []create_cache = DiffusionTuningCache.create