PTQ-Level Efficiency, QAT-Level Accuracy | 训练后量化的效率,量化感知训练的精度
[Research Feature]add naive qat/qad (#2548)
Wenhua Cheng57b8648d52e2
diff --git a/auto_round/algorithms/composer.py b/auto_round/algorithms/composer.pyindex f6dc059dc..98f850100 100644--- a/auto_round/algorithms/composer.py+++ b/auto_round/algorithms/composer.py@@ -30,6 +30,7 @@ Design invariants (see AWQ_REFACTOR_PLAN.md §0.0 and §3.0):from __future__ import annotations+from contextlib import nullcontextfrom dataclasses import dataclassfrom typing import TYPE_CHECKING, Any@@ -45,6 +46,7 @@ from auto_round.algorithms.utils import _has_nvfp4_layerfrom auto_round.logger import loggerfrom auto_round.utils import clear_memoryfrom auto_round.utils.device_manager import device_manager+from auto_round.wrapper import preserve_original_weights, store_warm_start_params_and_unwrap, unwrapper_blockif TYPE_CHECKING: # avoid circular imports at runtimefrom auto_round.algorithms.quantization.base import BaseQuantizer@@ -79,6 +81,9 @@ class BlockContext:is_diffusion: bool = False # fail-fast gate for algorithms that don't support diffusionpbar: Any = Noneblock_cnt: int = 0 # total number of blocks being quantized in this run+ # Ordered names of every block in the current all_blocks group (used e.g. by the+ # LFQ loss to forward a non-final block's output through the remaining FP blocks).+ all_block_names: list[str] | None = None# ---------------------------------------------------------------------------@@ -105,13 +110,14 @@ def _release_pool_inplace(obj: Any) -> None:class AlgorithmComposer:- """An ordered composition of pre-processors + one block quantizer, built from+ """An ordered composition of preprocessors and quantizer stages, built froma list of algorithm config objects and an optional compressor.The ``preprocessors`` list is order-sensitive: preprocessors are applied inthe listed order (e.g. ``[Rotation, AWQ]``). The block quantizer is alwaysthe terminal weight-compression step, regardless of its position in the- input config list. There must be **exactly one** ``block_quantizer``.+ input config list. Quantizers execute in their relative config order;+ ``block_quantizer`` exposes the active stage (the terminal stage when idle).Usage::@@ -126,8 +132,8 @@ class AlgorithmComposer:1. If no ``QuantizationConfig`` with a ``BaseQuantizer`` is found in*configs*, a default :class:`RTNConfig` is appended automatically.2. ``BasePreprocessor`` instances go into ``preprocessors`` (in order).- 3. Exactly one ``BaseQuantizer`` becomes ``block_quantizer``.- 4. Multiple block-quantization configs raise ``ValueError``.+ 3. ``BaseQuantizer`` instances form an ordered stage sequence.+ 4. Every stage validates its capabilities before execution.5. If *compressor* is provided, every member is bound to it and``block_forward`` / quantization metadata are extracted from it.@@ -143,6 +149,7 @@ class AlgorithmComposer:from auto_round.algorithms.quantization.config import QuantizationConfigfrom auto_round.algorithms.transforms.base import BasePreprocessor, BaseRotationConfig+ self._orchestrator = orchestratorconfigs = list(configs)# Rotation configs travel in the same config list but are not block@@ -161,7 +168,9 @@ class AlgorithmComposer:configs = configs + [RTNConfig()]- configs = resolve_shared_config_values(configs)+ # Sequential quantizers own independent schedules/behavior, but operate+ # on the same quantization scheme. Do not reconcile their local settings.+ configs = resolve_shared_config_values(configs, reconcile_non_scheme=len(block_quantizer_configs) <= 1)preprocessors: list = []block_quantizers: list = []@@ -187,15 +196,21 @@ class AlgorithmComposer:f"Algorithm class {type(q).__name__} must inherit either " "BasePreprocessor or BaseQuantizer.")- if len(block_quantizers) > 1:- raise ValueError(- f"AlgorithmComposer allows exactly one block-quantization config, "- f"but got {len(block_quantizers)}: "- f"{[type(q).__name__ for q in block_quantizers]}. "- "Ensure only one of RTNConfig / SignRoundConfig / etc. is in the pipeline."- )if len(block_quantizers) == 0:raise ValueError("No block quantizer found in configs.")+ self.quantizers = tuple(block_quantizers)+ self._preserve_weights = False+ self._preserve_stage_weights = []+ needs_original_weights = False+ for quantizer in reversed(self.quantizers):+ self._preserve_stage_weights.append(needs_original_weights)+ if quantizer.config.nsamples is not None and not quantizer.whole_model_tuning:+ raise NotImplementedError(+ f"{type(quantizer.config).__name__}.nsamples overrides are only supported for whole-model tuning. "+ "Use the common calibration nsamples argument for this stage."+ )+ needs_original_weights = needs_original_weights or quantizer.requires_original_weights+ self._preserve_stage_weights.reverse()seen = set()for pre in preprocessors:@@ -209,17 +224,18 @@ class AlgorithmComposer:self.preprocessors = preprocessors- # TODO wenhuach support multi quantizerscan_compile_block_forward = False- self.block_quantizer = block_quantizers[0]+ self.block_quantizer = block_quantizers[-1]+ self.block_forward = Noneif orchestrator is not None:user_torch_compile = bool(getattr(getattr(orchestrator, "compress_context", None), "enable_torch_compile", False))rotation_configs = getattr(orchestrator, "rotation_configs", ())blockers = []- if not self.block_quantizer.can_compile_block_forward():- blockers.append(type(self.block_quantizer).__name__)+ for quantizer in self.quantizers:+ if not quantizer.can_compile_block_forward():+ blockers.append(type(quantizer).__name__)for component in [*self.preprocessors, *rotation_configs]:if not getattr(component, "can_compile_block_forward", lambda: True)():blockers.append(type(component).__name__)@@ -241,8 +257,8 @@ class AlgorithmComposer:else None)# A little tricky- if self.block_quantizer is not None:- self.block_quantizer.bind_block_forward_runner(self.block_forward)+ for quantizer in self.quantizers:+ quantizer.bind_block_forward_runner(self.block_forward)self.scheme = getattr(orchestrator, "scheme_context", None)# Rotation is modelled as ordinary pipeline members (see@@ -258,6 +274,81 @@ class AlgorithmComposer:# Guards the one-shot model-level rotation stage (apply_model_transforms).self._rotation_prepared: bool = False+ def compress_model(self, token_ids, run_blocks) -> bool:+ """Run ordered block/model tuning stages using the bound compressor.++ Returns True when the terminal stage handles the whole model (including+ outside-block layers). Preprocessors/rotations run only in the first+ block stage. The composer owns weight preservation and cleanup; algorithms+ only implement block/model tuning and optionally customize sampling.+ """+ orchestrator = self._orchestrator+ if orchestrator is None:+ raise RuntimeError("compress_model requires a bound compressor.")+ streaming_export = (+ orchestrator.compress_context.is_immediate_saving or orchestrator.compress_context.is_immediate_packing+ )+ if streaming_export and (len(self.quantizers) > 1 or self.block_quantizer.whole_model_tuning):+ raise NotImplementedError("Multi-stage/whole-model tuning does not support immediate saving/packing.")+ from auto_round import envs++ if envs.AR_RESUME_DIR and len(self.quantizers) > 1:+ raise NotImplementedError("Resuming a multi-stage quantization run is not supported.")+ if self.quantizers[0].whole_model_tuning and (self.preprocessors or self.has_layerwise_rotation):+ raise NotImplementedError("Block preprocessors/layer-wise rotation require a leading block-tuning stage.")+ terminal = self.block_quantizer+ preprocessors, rotations = self.preprocessors, self._rotation_members+ try:+ self.prepare_run()+ for index, (quantizer, preserve) in enumerate(zip(self.quantizers, self._preserve_stage_weights)):+ self.block_quantizer = quantizer+ self._preserve_weights = preserve+ if index:+ self.preprocessors, self._rotation_members = [], []+ logger.info(+ "Starting algorithm stage %d/%d: %s.", index + 1, len(self.quantizers), type(quantizer).__name__+ )+ if quantizer.whole_model_tuning:+ orchestrator._reload_model_for_tuning()+ runner = getattr(self, "block_forward", None)+ if runner is not None:+ runner.pool_placement = None+ stage_token_ids = quantizer.get_calibration_token_ids(token_ids, orchestrator.calibration)+ self._run_tuning(+ orchestrator.model_context.model,+ lambda: quantizer.quantize_model(+ orchestrator.model_context.model, stage_token_ids, device=device_manager.device+ ),+ )+ else:+ run_blocks(index > 0)+ return terminal.whole_model_tuning+ finally:+ self.block_quantizer = terminal+ self._preserve_weights = False+ self.preprocessors, self._rotation_members = preprocessors, rotations+ self.finalize_run()++ def _run_tuning(self, module, tune, collect_output=None):+ """Common block/model tuning finalization, including failure cleanup."""+ preserve = getattr(self, "_preserve_weights", False)+ with preserve_original_weights(module) if preserve else nullcontext():+ try:+ best_params = tune() or {}+ if preserve:+ store_warm_start_params_and_unwrap(module, best_params, before_unwrap=collect_output)+ else:+ unwrapper_block(module, best_params)+ except BaseException:+ # Do not bake partially tuned parameters when optimization or+ # output collection fails. Remove any remaining common wrappers.+ from auto_round.utils import set_module++ for name, wrapped in list(module.named_modules()):+ if hasattr(wrapped, "orig_layer"):+ set_module(module, name, wrapped.orig_layer)+ raise+# ── Internal hook helpers (act_max calibration) ───────────────────────────def _register_act_max_hooks(self, block: torch.nn.Module) -> list:@@ -265,61 +356,9 @@ class AlgorithmComposer:Returns a list of hook handles that the caller must remove when done."""- from auto_round.data_type.utils import reshape_pad_tensor_by_group_size- from auto_round.schemes import needs_nvfp_global_scale as is_nv_fp-- is_act_nv_fp = is_nv_fp(getattr(self.block_quantizer.config, "act_data_type", None) or "")-- def collect_act_max(module, input, output):- input = input[0] if isinstance(input, (tuple, list)) else input- if input.numel() == 0:- return- module_act_data_type = getattr(module, "act_data_type", None) or getattr(module, "data_type", None)- is_module_act_nv_fp = is_nv_fp(module_act_data_type) if module_act_data_type else is_act_nv_fp- input, _, _ = reshape_pad_tensor_by_group_size(input, module.act_group_size)- act_max = torch.max(torch.abs(input), dim=-1).values- if not hasattr(module, "act_max") or module.act_max.numel() == 0:- module.act_max = act_max- if is_module_act_nv_fp:- max_val = act_max.max()- module.act_max = max_val.unsqueeze(0) if max_val.dim() == 0 else max_val- return- act_max = act_max.to(module.act_max.device)- if is_module_act_nv_fp:- max_val = torch.max(act_max.max(), module.act_max.max())- module.act_max = max_val.unsqueeze(0) if max_val.dim() == 0 else max_val- else:- module.act_max = torch.max(act_max, module.act_max)-- def should_collect(name, module):- from auto_round.compressors.utils import check_need_act_calibration- from auto_round.utils import SUPPORTED_LAYER_TYPES, check_to_quantized+ from auto_round.data_type.utils import register_act_max_hooks- if isinstance(module, tuple(SUPPORTED_LAYER_TYPES)):- return (- hasattr(module, "act_dynamic")- and check_need_act_calibration(module.act_dynamic, module.act_data_type, module.act_bits)- and check_to_quantized(module)- )- if hasattr(module, "bits"):- act_dynamic = getattr(module, "act_dynamic", True)- act_data_type = getattr(module, "act_data_type", None)- act_bits = getattr(module, "act_bits", 16)- return (- module.bits <= 8- and check_need_act_calibration(act_dynamic, act_data_type, act_bits)- and check_to_quantized(module)- )- return False-- handles = []- if should_collect("", block):- handles.append(block.register_forward_hook(collect_act_max))- return handles- for name, module in block.named_modules():- if name and should_collect(name, module):- handles.append(module.register_forward_hook(collect_act_max))- return handles+ return register_act_max_hooks(block, getattr(self.block_quantizer.config, "act_data_type", None))def _get_fp_act_hooks(self, block: torch.nn.Module) -> list:"""Register FP-input act_max + quantizer forward hooks."""@@ -553,14 +592,20 @@ class AlgorithmComposer:# When quantized input is available from the previous block, use it;# otherwise fall back to the FP input.effective_input = q_inputs if q_inputs is not None else fp_inputs- self.block_quantizer.quantize_block(+ warm_start_outputs = []+ collect_warm_start_output = None+ if getattr(self, "_preserve_weights", False) and self.block_quantizer.enable_quanted_input:++ def collect_warm_start_output(wrapped_block):+ output = block_forward_fn(wrapped_block, effective_input, input_others)+ warm_start_outputs.append(getattr(block_forward_fn, "last_output_dict", None) or output)++ self._run_tuning(block,- effective_input,- input_others,- reference_output,- q_inputs,- block_ctx,- input_ids=input_ids,+ lambda: self.block_quantizer.quantize_block(+ block, effective_input, input_others, reference_output, q_inputs, block_ctx, input_ids=input_ids+ ),+ collect_warm_start_output,)# Quantizer-agnostic block finalization (e.g. NVFP MoE act_max), kept@@ -572,7 +617,11 @@ class AlgorithmComposer:pre.post_quantize_block(block_ctx)# ── Step 6: Collect quantized-block outputs for the next block ──────────- if self.block_quantizer.enable_quanted_input:+ if warm_start_outputs:+ # Warm-up has restored FP weights by now; use the output collected+ # while the wrappers still held the best quantization parameters.+ new_q_input = warm_start_outputs[0]+ elif self.block_quantizer.enable_quanted_input:with torch.no_grad():new_q_input = block_forward_fn(block, effective_input, input_others)new_q_input = getattr(block_forward_fn, "last_output_dict", None) or new_q_input@@ -630,31 +679,34 @@ class AlgorithmComposer:# ── Convenience act-calib helpers ────────────────────────────────────────def members(self) -> list:- """Return the canonical execution order: preprocessors, rotations, then block quantizer.+ """Return preprocessors, rotations, then all ordered quantizer stages.- Preprocessor order follows the input config list. The block quantizer- is always returned last, so its position in that input list has no- effect on pipeline execution. Rotation members sit between the- preprocessors and the block quantizer so ``prepare_run`` / ``finalize_run``- cover them like any other member.+ Run-level preparation and cleanup cover every member exactly once.+ Per-block work and dispatch use only the currently active quantizer."""- return list(self.preprocessors) + list(self._rotation_members) + [self.block_quantizer]+ return list(self.preprocessors) + list(self._rotation_members) + list(self.quantizers)def dispatch_block(self, block: torch.nn.Module, input_ids, input_others: dict):"""Dispatch block to device(s) via the pipeline's algorithms.- Iterates all members; if exactly one overrides the default dispatch_block,+ Iterates active members; if exactly one overrides the default dispatch_block,it is called. If multiple override, warns and uses the first one only.If none override, uses the block_quantizer's default (simple .to(device))."""from auto_round.algorithms.quantization.base import BaseQuantizeroverriders = []- for member in self.members():+ seen_ids = set()+ for member in [*self.preprocessors, *self._rotation_members, self.block_quantizer]:if not hasattr(member, "dispatch_block"):continue# Check if the member overrides the base defaultif type(member).dispatch_block is not BaseQuantizer.dispatch_block:+ # Custom pipelines may expose the same member through more than+ # one role; dispatch it only once.+ if id(member) in seen_ids:+ continue+ seen_ids.add(id(member))overriders.append(member)if len(overriders) > 1:diff --git a/auto_round/algorithms/config_resolver.py b/auto_round/algorithms/config_resolver.pyindex cccf8055b..34e253aa0 100644--- a/auto_round/algorithms/config_resolver.py+++ b/auto_round/algorithms/config_resolver.py@@ -67,7 +67,7 @@ def _public_config_attrs(config: Any) -> dict[str, Any]:return {key: valuefor key, value in vars(config).items()- if key != "scheme" and not key.startswith("_") and not callable(value)+ if key != "scheme" and key not in config.stage_local_fields and not key.startswith("_") and not callable(value)}@@ -106,16 +106,26 @@ def _resolve_shared_scheme_values(configs: list[Any]) -> None:setattr(config.scheme, attr_name, shared_value)-def resolve_shared_config_values(configs: list[Any]) -> list[Any]:+def resolve_shared_config_values(configs: list[Any], reconcile_non_scheme: bool = True) -> list[Any]:"""Merge shared public attrs across quantization configs without naming fields.A field is shared when at least two quantization configs define the samepublic attribute. ``None`` means "not set" and inherits from the singlenon-None value, while conflicting non-None values fail fast. Configs that do- not define a field do not participate in that field.+ not define a field do not participate in that field. Fields declared in+ ``stage_local_fields`` are never merged or propagated to another stage.++ When *reconcile_non_scheme* is ``False`` only the quantization *scheme*+ fields (bits / group_size / data_type …) are reconciled; the behavioral+ public attributes are left untouched. This is used when chaining two+ independent quantization stages (e.g. a block-wise warm-up feeding a+ whole-model quantizer) that legitimately differ on fields like+ ``enable_alg_ext`` while still sharing a single scheme."""quant_configs = _quantization_configs(configs)_resolve_shared_scheme_values(quant_configs)+ if not reconcile_non_scheme:+ return configsattrs_by_config = [(config, _public_config_attrs(config)) for config in quant_configs]field_to_configs: dict[str, list[Any]] = defaultdict(list)for config, attrs in attrs_by_config:diff --git a/auto_round/algorithms/quantization/adam_round/adam.py b/auto_round/algorithms/quantization/adam_round/adam.pyindex bb67e6c1b..2bfa576e4 100644--- a/auto_round/algorithms/quantization/adam_round/adam.py+++ b/auto_round/algorithms/quantization/adam_round/adam.py@@ -38,9 +38,10 @@ class AdamRoundQuantizer(SignRoundQuantizer):def _get_scaler(self):scaler = Noneif self.model_context.amp and not check_is_cpu(device_manager.device):- from torch.cuda.amp import GradScaler+ from torch.amp import GradScaler- scaler = GradScaler(init_scale=1024, growth_interval=100000)+ device_type = torch.device(device_manager.device).type+ scaler = GradScaler(device_type, init_scale=1024, growth_interval=100000)return scalerdef _scale_loss_and_backward(self, scaler, loss):diff --git a/auto_round/algorithms/quantization/base.py b/auto_round/algorithms/quantization/base.pyindex ef6f58062..7832cf2e5 100644--- a/auto_round/algorithms/quantization/base.py+++ b/auto_round/algorithms/quantization/base.py@@ -170,6 +170,9 @@ class BaseQuantizer(BaseAlgorithm):**kwargs: Reserved for future parameters.Returns:dict: Best quantization parameters found, or ``{}`` if not applicable.+ Leave common tuning wrappers installed: the composer loads these+ parameters, collects outputs and unwraps/restores FP weights.+ Algorithms that directly modify weights need no wrapper handling.Raises:NotImplementedError: Subclasses must override this method."""@@ -374,6 +377,61 @@ class BaseQuantizer(BaseAlgorithm):set_amax_for_all_moe_layers(block, attr_name="orig_layer.act_max")# ── Lifecycle hooks ───────────────────────────────────────────────────────+ #: Algorithms that tune the whole model jointly (a single forward to the LM+ #: head) instead of block-by-block set this to ``True``. The composer then+ #: calls :meth:`quantize_model` once and skips the per-block loop.+ whole_model_tuning: bool = False++ #: The composer preserves original FP weights across all preceding stages+ #: when a consumer needs them (e.g. to construct a full-precision teacher).+ #: Algorithms never manage preservation flags or stage cleanup themselves.+ requires_original_weights: bool = False++ def get_calibration_token_ids(self, token_ids, calibration):+ """Resolve this algorithm's sample count; override for custom sampling.++ Reuse the common cached samples when nsamples is unset, take a prefix+ when fewer are needed, or collect raw tokens without block forwards.+ """+ target = self.config.nsamples+ if token_ids is not None:+ if target is None or target == len(token_ids):+ return token_ids+ if target < len(token_ids):+ logger.info("Algorithm stage uses the first %d of %d calibration samples.", target, len(token_ids))+ return list(token_ids)[:target]+ if target is None:+ target = calibration.nsamples+ collect = getattr(calibration, "collect_token_ids", None)+ if callable(collect):+ logger.info("Collecting %d calibration samples for the algorithm stage.", target)+ collected = collect(target)+ if collected is not None and len(collected) > 0:+ return collected+ logger.warning("Cannot collect %d calibration token ids; falling back to the cached samples.", target)+ return token_ids++ def quantize_model(self, model, token_ids, device=None) -> dict:+ """Quantize the entire model jointly (whole-network tuning).++ Only invoked when :attr:`whole_model_tuning` is ``True``. The default+ implementation is intentionally absent; whole-model algorithms (e.g. QAD)+ override it to run their own full-model forward/optimize loop.++ Args:+ model: The model to quantize (all quantizable layers tuned jointly).+ token_ids: Per-sample calibration token-id tensors.+ device: Target compute device.++ Returns:+ Best tuning parameters, with common wrappers left installed for+ composer finalization, just like quantize_block. In-place algorithms+ may return an empty dict.+ """+ raise NotImplementedError(+ f"{type(self).__name__} sets whole_model_tuning=True but does not implement quantize_model()."+ )+def prepare_run(self, composer: "AlgorithmComposer" = None) -> None:"""Model-level preparation (called once before block iteration starts)."""returndiff --git a/auto_round/algorithms/quantization/config.py b/auto_round/algorithms/quantization/config.pyindex 14416b084..d18dca505 100644--- a/auto_round/algorithms/quantization/config.py+++ b/auto_round/algorithms/quantization/config.py@@ -36,13 +36,22 @@ class QuantizationConfig(AlgorithmConfig):act_dynamic: Whether activation quantization should be dynamic.super_bits: Bit width used for double quantization metadata.super_group_size: Group size used for double quantization metadata.+ nsamples: Optional algorithm-local calibration sample count. None reuses+ the common calibration samples. Currently only whole-model tuning+ supports this override; other stages reject it during composition.+ Algorithm CLI flags should map to this field, not a private name."""need_calib = True_scheme_fields: ClassVar[set[str]] = set(QuantizationScheme.get_attributes())+ # These fields belong to each stage, not the shared quantization setup.+ stage_local_fields: ClassVar[frozenset[str]] = frozenset({"nsamples"})- def __init__(self, *, scheme: QuantizationScheme = None, **kwargs) -> None:+ def __init__(self, *, scheme: QuantizationScheme = None, nsamples: int | None = None, **kwargs) -> None:+ if nsamples is not None and (isinstance(nsamples, bool) or not isinstance(nsamples, int) or nsamples <= 0):+ raise ValueError("`nsamples` must be a positive integer or None")+ self.nsamples = nsamplesobject.__setattr__(self, "scheme", scheme if scheme is not None else QuantizationScheme.empty())object.__setattr__(self, "_user_set_scheme_fields", set())diff --git a/auto_round/algorithms/quantization/qad/__init__.py b/auto_round/algorithms/quantization/qad/__init__.pynew file mode 100644index 000000000..2b8f8d9df--- /dev/null+++ b/auto_round/algorithms/quantization/qad/__init__.py@@ -0,0 +1,19 @@+# Copyright (c) 2026 Intel Corporation+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+"""QAD: quantization-aware distillation with an offline teacher Top-K cache."""++from auto_round.algorithms.quantization.qad.config import QADConfig+from auto_round.algorithms.quantization.qad.quantizer import QADQuantizer++__all__ = ["QADConfig", "QADQuantizer"]diff --git a/auto_round/algorithms/quantization/qad/config.py b/auto_round/algorithms/quantization/qad/config.pynew file mode 100644index 000000000..4398f8e9f--- /dev/null+++ b/auto_round/algorithms/quantization/qad/config.py@@ -0,0 +1,259 @@+# Copyright (c) 2026 Intel Corporation+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+"""QAD (quantization-aware distillation) algorithm config.++QAD fuses all text-decoder blocks into a single jointly-optimized group+(whole-network training) and tunes them against the full-precision teacher's+next-token distribution. To keep GPU/CPU memory low, the teacher is forwarded to+the LM head *once*, offline, and only the Top-K ``(index, prob)`` per token is+cached to disk; the student reads those compact tensors during tuning.+"""++from __future__ import annotations++from auto_round.algorithms.config import AlgorithmParameterRegistry+from auto_round.algorithms.quantization.sign_round.config import SignRoundConfig+from auto_round.algorithms.registry import register_algorithm+from auto_round.logger import logger+++class QADConfig(SignRoundConfig):+ """Configuration for the QAD (quantization-aware distillation) algorithm."""++ _warn_enable_qad = False++ @classmethod+ def register_args(cls, registry: AlgorithmParameterRegistry) -> None:+ super().register_args(registry)+ cls._register_qad_teacher_args(registry)+ cls._register_qad_tuning_args(registry)++ @classmethod+ def _register_qad_teacher_args(cls, registry: AlgorithmParameterRegistry) -> None:+ """Teacher-distillation-only args (not used by the pure-QAT variant)."""+ registry.add_argument(+ "--topk",+ field="topk",+ default=32,+ type=int,+ help=(+ "Number of top teacher logits cached per token for QAD distillation. "+ "Use -1 to store the full vocabulary distribution."+ ),+ )+ registry.add_argument(+ "--qad_kd_weight",+ field="qad_kd_weight",+ default=1.0,+ type=float,+ help=(+ "Weight of the teacher-distribution KD (soft) loss in the QAD objective: "+ "loss = qad_kd_weight * KL(p_T || p_S) + qad_ce_weight * CE(label, p_S). "+ "Set to 0 to drop distillation and train on hard labels only (pure QAT); "+ "when 0 the offline teacher cache is skipped entirely."+ ),+ )+ registry.add_argument(+ "--qad_ce_weight",+ field="qad_ce_weight",+ default=0.0,+ type=float,+ help=(+ "Weight of the hard-label next-token cross-entropy term added to the QAD loss. "+ "0 (default) keeps pure teacher distillation; a positive value mixes in the "+ "ground-truth label CE, turning QAD into quantization-aware training (QAT). "+ "Use together with --qad_kd_weight to interpolate KD<->QAT."+ ),+ )+ registry.add_argument(+ "--qad_workspace",+ field="qad_workspace",+ default=None,+ help=(+ "Directory where the offline teacher Top-K cache is written. "+ "Defaults to <AR_WORK_SPACE>/qad_teacher_cache when unset."+ ),+ )++ @classmethod+ def _register_qad_tuning_args(cls, registry: AlgorithmParameterRegistry) -> None:+ """Whole-model tuning knobs shared by QAD and the pure-QAT variant."""+ registry.add_argument(+ "--qad_lr",+ field="qad_lr",+ default=None,+ type=float,+ help=(+ "Learning rate for QAD tuning (rounding params). Lets QAD use a different "+ "lr from block-wise SignRound; falls back to --lr when unset."+ ),+ )+ registry.add_argument(+ "--qad_nsamples",+ field="nsamples",+ default=None,+ type=int,+ help=(+ "Number of calibration samples used by QAD tuning. Lets QAD use a different "+ "sample count from block-wise SignRound (e.g. '--algs sign_round,qad'); "+ "falls back to --nsamples when unset."+ ),+ )+ registry.add_argument(+ "--qad_optimizer",+ field="qad_optimizer",+ default="signround",+ choices=["signround", "adamw"],+ help="Optimizer used for QAD tuning: 'signround' (SignSGD) or 'adamw' (torch.optim.AdamW).",+ )+ registry.add_argument(+ "--tune_non_quant_params",+ field="tune_non_quant_params",+ default=False,+ action="boolean_optional",+ help=(+ "Also train the model's non-quantized FP parameters (e.g. lm_head, embeddings, "+ "norms, biases) jointly with the quantization params during QAD/QAT whole-model "+ "tuning, instead of freezing them. Useful for QAT where a kept-FP lm_head should "+ "adapt to the quantized backbone."+ ),+ )+ registry.add_argument(+ "--non_quant_params_lr",+ field="non_quant_params_lr",+ default=None,+ type=float,+ help=(+ "Learning rate for the non-quantized FP parameters when --tune_non_quant_params is "+ "set. Falls back to the QAD rounding lr when unset."+ ),+ )+ registry.add_argument(+ "--gradient_checkpointing",+ field="gradient_checkpointing",+ default=True,+ action="boolean_optional",+ help=(+ "Enable activation (gradient) checkpointing during QAD tuning (default: on): the "+ "whole-model backward recomputes block activations instead of "+ "storing them, trading compute for a large activation-memory saving. "+ "Use --no-gradient_checkpointing to disable."+ ),+ )++ def __init__(+ self,+ *,+ iters: int = 200,+ lr: float | None = None,+ qad_lr: float | None = None,+ nsamples: int | None = None,+ qad_nsamples: int | None = None,+ topk: int = 32,+ qad_optimizer: str | None = None,+ qad_workspace: str | None = None,+ gradient_checkpointing: bool = True,+ qad_kd_weight: float = 1.0,+ qad_ce_weight: float = 0.0,+ tune_non_quant_params: bool = False,+ non_quant_params_lr: float | None = None,+ **kwargs,+ ) -> None: # QAD implies whole-network joint distillation. `enable_qad` forces+ # `enable_lfq` and makes the orchestrator fuse all blocks into one group.+ kwargs.setdefault("enable_qad", True)+ # NOTE: QAD distills against the FP teacher's logits: the loss is the+ # forward KL(p_T || p_S) with p_T = softmax(teacher_logits/τ) (Top-K or+ # full vocab, see `_QADDistillLoss`); hard labels are only used as the+ # ignore mask. The inherited `lfq_loss` field is therefore NOT consumed on+ # the QAD path; it is kept in sync with the SignRound default only to+ # avoid a confusing mismatch.+ kwargs.setdefault("lfq_loss", "tk")+ # Tuning schedule: QAD defaults to more iterations than block-wise tuning+ # since the whole network is optimized jointly. `lr=None` keeps the base+ # heuristic (1/iters); pass an explicit value (e.g. 1e-4 for AdamW).+ # `qad_lr` (QAD-specific) takes precedence over the shared `lr`, so QAD+ # can use a different lr than SignRound when both run in one pipeline.+ kwargs.setdefault("iters", iters)+ kwargs.setdefault("lr", lr)+ self.qad_lr = qad_lr+ if qad_lr is not None:+ if qad_lr <= 0:+ raise ValueError("`qad_lr` must be positive")+ kwargs["lr"] = qad_lr+ # Keep the old Python keyword as an alias; storage and validation belong+ # to QuantizationConfig. The CLI maps --qad_nsamples directly to nsamples.+ if qad_nsamples is not None:+ if nsamples is not None and nsamples != qad_nsamples:+ raise ValueError("`nsamples` and legacy `qad_nsamples` must agree when both are supplied")+ nsamples = qad_nsamples+ kwargs["nsamples"] = nsamples+ # Normalize the optimizer choice before handing it to the base config+ # (SignRound keeps it on ``self.optimizer`` for the quantizer to resolve).+ # ``qad_optimizer`` is the QAD-specific name; a legacy ``optimizer=`` kwarg+ # is still accepted (pulled from ``kwargs``) for API backward compatibility.+ optimizer = (qad_optimizer or kwargs.pop("optimizer", None) or "signround").lower()+ if optimizer not in ("signround", "adamw"):+ raise ValueError(f"`qad_optimizer` must be 'signround' or 'adamw', got {optimizer!r}")+ self.qad_optimizer = optimizer+ kwargs["optimizer"] = optimizer+ super().__init__(**kwargs)+ # Force QAD semantics regardless of CLI arg defaults.+ self.enable_qad = True+ self.enable_lfq = True+ self.topk = topk+ if self.topk != -1 and self.topk <= 0:+ raise ValueError("`topk` must be positive, or -1 to store the full distribution")+ self.qad_workspace = qad_workspace+ self.gradient_checkpointing = bool(gradient_checkpointing)+ # Optionally fold the non-quantized FP params (lm_head, embeddings, norms,+ # biases) into the joint tuning instead of freezing them (QAT-style).+ self.tune_non_quant_params = bool(tune_non_quant_params)+ if non_quant_params_lr is not None and non_quant_params_lr <= 0:+ raise ValueError("`non_quant_params_lr` must be positive")+ self.non_quant_params_lr = non_quant_params_lr+ if self.tune_non_quant_params and self.qad_optimizer == "signround":+ logger.warning_once(+ "`tune_non_quant_params` trains full-precision params (lm_head/embeddings/norms) with "+ "SignSGD, whose coarse sign-only updates are ill-suited to FP fine-tuning; consider "+ "`--qad_optimizer adamw` (optionally with a small `--non_quant_params_lr`, e.g. 1e-5)."+ )+ # Loss mixing: total = kd_weight * KD(teacher) + ce_weight * CE(label).+ # Pure KD (default) keeps the historical behavior; a positive ce_weight+ # mixes in the hard-label objective (QAT), and kd_weight=0 drops the+ # teacher cache for a pure QAT run.+ self.qad_kd_weight = float(qad_kd_weight)+ self.qad_ce_weight = float(qad_ce_weight)+ if self.qad_kd_weight < 0 or self.qad_ce_weight < 0:+ raise ValueError("`qad_kd_weight` and `qad_ce_weight` must be non-negative")+ if self.qad_kd_weight == 0.0 and self.qad_ce_weight == 0.0:+ raise ValueError("`qad_kd_weight` and `qad_ce_weight` cannot both be 0 (no loss to optimize)")+ if self.qad_kd_weight == 0.0:+ # Pure hard-label objective: no teacher model/cache involved at all.+ logger.warning_once(+ "the `QAT` algorithm is experimental: all text-decoder blocks are tuned jointly "+ "against the ground-truth next-token cross-entropy (no teacher cache)."+ )+ else:+ logger.warning_once(+ "the `QAD` algorithm is experimental: the full-precision teacher Top-K is cached to disk "+ "and all text-decoder blocks are tuned jointly against it."+ )+++register_algorithm(+ "qad",+ aliases=("qad",),+ config_factory=QADConfig,+ summary="Quantization-aware distillation with an offline teacher Top-K cache.",+)diff --git a/auto_round/algorithms/quantization/qad/quantizer.py b/auto_round/algorithms/quantization/qad/quantizer.pynew file mode 100644index 000000000..2c5e7f2a7--- /dev/null+++ b/auto_round/algorithms/quantization/qad/quantizer.py@@ -0,0 +1,1090 @@+# Copyright (c) 2026 Intel Corporation+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+"""QAD quantizer: whole-network joint distillation from an offline teacher cache."""++from __future__ import annotations++import hashlib+import json+import math+import os++import torch++from auto_round import envs+from auto_round.algorithms.quantization.qad.config import QADConfig+from auto_round.algorithms.quantization.qad.teacher_cache import TeacherTopKCache+from auto_round.algorithms.quantization.sign_round.quantizer import SignRoundQuantizer+from auto_round.algorithms.quantization.sign_round.sign_sgd import SignSGD+from auto_round.algorithms.registry import register_pipeline_member+from auto_round.logger import logger+from auto_round.utils import check_is_cpu, clear_memory, htcore, is_hpex_available+from auto_round.utils.device_manager import device_manager++try: # CUDA-only fast path; falls back to the chunked PyTorch implementation.+ import triton+ import triton.language as tl++ _HAS_TRITON = True+except Exception: # pragma: no cover - triton is optional+ _HAS_TRITON = False+++def _streaming_logsumexp(s: torch.Tensor, tau: float, vocab_chunk: int) -> torch.Tensor:+ """Numerically-stable ``logsumexp(s/τ)`` over dim -1, streamed in vocab chunks.++ PyTorch fallback used when Triton / CUDA is unavailable. Keeps a running max+ and running sum so the largest temporary is ``[M, chunk]`` instead of the+ full ``[M, vocab]`` ``exp`` (the online-softmax trick that lets Unsloth's+ chunked kernel handle 256K-vocab models).+ """+ M, V = s.shape+ running_max = torch.full((M,), float("-inf"), device=s.device, dtype=torch.float32)+ running_sum = torch.zeros(M, device=s.device, dtype=torch.float32)+ for c0 in range(0, V, vocab_chunk):+ c1 = min(c0 + vocab_chunk, V)+ sc = s[:, c0:c1].float() / tau # [M, cw]+ chunk_max = sc.max(dim=-1).values # [M]+ new_max = torch.maximum(running_max, chunk_max)+ running_sum = running_sum * torch.exp(running_max - new_max) + torch.exp(sc - new_max.unsqueeze(1)).sum(dim=-1)+ running_max = new_max+ return running_max + torch.log(running_sum)+++_QAD_TRITON_BLOCK = 8192 # register-friendly vocab tile for the Triton kernels+++if _HAS_TRITON:++ @triton.jit+ def _qad_logsumexp_kernel(+ logits_ptr,+ logz_ptr,+ stride_b,+ stride_t,+ S1,+ VOCAB,+ INV_TAU,+ BLOCK: tl.constexpr,+ ):+ """One program per shifted row: online ``logsumexp(s/τ)`` over the vocab.++ Row ``r`` maps to token ``(b, t) = (r // S1, r % S1)`` so the kernel reads+ straight from the ``[B, seq, vocab]`` logits without a reshape/copy of the+ shifted slice. The ``exp`` tile is at most ``[BLOCK]`` wide.+ """+ row = tl.program_id(0)+ b = row // S1+ t = row % S1+ base = logits_ptr + b.to(tl.int64) * stride_b + t.to(tl.int64) * stride_t+ m = -float("inf")+ acc = 0.0+ for start in range(0, VOCAB, BLOCK):+ offs = start + tl.arange(0, BLOCK)+ msk = offs < VOCAB+ x = tl.load(base + offs, mask=msk, other=-float("inf")).to(tl.float32) * INV_TAU+ cmax = tl.max(x, 0)+ new_m = tl.maximum(m, cmax)+ acc = acc * tl.exp(m - new_m) + tl.sum(tl.exp(x - new_m), 0)+ m = new_m+ tl.store(logz_ptr + row, m + tl.log(acc))++ @triton.jit+ def _qad_softmax_kernel(+ logits_ptr,+ out_ptr,+ logz_ptr,+ prob_ptr,+ mask_ptr,+ scale_ptr,+ stride_b,+ stride_t,+ out_stride_b,+ out_stride_t,+ S1,+ VOCAB,+ INV_TAU,+ FULL: tl.constexpr,+ BLOCK: tl.constexpr,+ ):+ """Write ``softmax(s/τ)`` of one row/vocab-block straight into ``out``.++ ``out`` is the full ``[B, seq, vocab]`` gradient buffer; only the first+ ``S1`` positions per batch are written (the last predicts nothing), so the+ shifted-out position keeps its zero initialization. No full-vocab softmax+ is ever materialized outside this buffer.+ """+ row = tl.program_id(0)+ blk = tl.program_id(1)+ b = row // S1+ t = row % S1+ offs = blk * BLOCK + tl.arange(0, BLOCK)+ msk = offs < VOCAB+ x = (+ tl.load(+ logits_ptr + b.to(tl.int64) * stride_b + t.to(tl.int64) * stride_t + offs,+ mask=msk,+ other=-float("inf"),+ ).to(tl.float32)+ * INV_TAU+ )+ logz = tl.load(logz_ptr + row)+ y = tl.exp(x - logz)+ if FULL:+ target = tl.load(prob_ptr + row.to(tl.int64) * VOCAB + offs, mask=msk, other=0).to(tl.float32)+ y -= target+ valid = tl.load(mask_ptr + row)+ scale = tl.load(scale_ptr).to(tl.float32)+ y = tl.where(valid, y * scale, 0.0)+ tl.store(out_ptr + b.to(tl.int64) * out_stride_b + t.to(tl.int64) * out_stride_t + offs, y, mask=msk)+++def _triton_logsumexp(logits: torch.Tensor, tau: float) -> torch.Tensor:+ """Per-row ``logsumexp(s/τ)`` over the shifted logits via Triton -> ``[M]``."""+ B, S, V = logits.shape+ S1 = S - 1+ M = B * S1+ logz = torch.empty(M, device=logits.device, dtype=torch.float32)+ sb, st, _ = logits.stride()+ _qad_logsumexp_kernel[(M,)](logits, logz, sb, st, S1, V, 1.0 / tau, BLOCK=_QAD_TRITON_BLOCK, num_warps=8)+ return logz+++def _triton_softmax_into(out, logits, logz, tau, target, mask, scale, full_mode) -> None:+ """Store completed dense gradients, casting only after FP32 arithmetic."""+ B, S, V = logits.shape+ S1 = S - 1+ M = B * S1+ n_blk = triton.cdiv(V, _QAD_TRITON_BLOCK)+ sb, st, _ = logits.stride()+ osb, ost, _ = out.stride()+ _qad_softmax_kernel[(M, n_blk)](+ logits,+ out,+ logz,+ target,+ mask,+ scale,+ sb,+ st,+ osb,+ ost,+ S1,+ V,+ 1.0 / tau,+ FULL=full_mode,+ BLOCK=_QAD_TRITON_BLOCK,+ num_warps=8,+ )+++class _QADDistillLoss(torch.autograd.Function):+ """Memory-lean forward-KL distillation loss, à la Unsloth's fused cross-entropy.++ The target is the full-precision teacher's (temperature-scaled) distribution+ ``p_T = softmax(t/τ)`` -- *not* the hard next-token label. Per position:++ L = KL(p_T || p_S) = Σ_k p_T(k)·log p_T(k) − Σ_k p_T(k)·log p_S(k)+ = Σ_k p_T log p_T + logsumexp(s/τ) − Σ_k p_T(k)·(s_k/τ)++ using ``log p_S(k) = s_k/τ − logsumexp(s/τ)`` and ``Σ_k p_T(k) = 1``. The+ labels are only used as a validity mask (``-100`` = ignore). As in+ Unsloth's ``Fast_CrossEntropyLoss``:++ * the **forward** keeps only the per-row normalizer ``logsumexp`` (``[M]``),+ computed by a Triton kernel that streams over the vocabulary (CUDA) or by+ the chunked PyTorch fallback;+ * the **backward** recomputes ``softmax(s/τ)`` from the saved logits -- again+ via a Triton kernel on CUDA -- and writes the gradient+ ``(softmax(s/τ) − p_T)`` straight into the (sole) output buffer.++ The one-hot label of plain cross-entropy is simply replaced by the teacher+ distribution ``p_T`` (the teacher Top-K scattered back to vocab, or the full+ distribution when ``teacher_index is None``). No full-vocab log-softmax ever+ enters the autograd graph, so the retained memory is just the logits (the+ model output, unavoidable) plus the ``[M]`` normalizer.+ """++ @staticmethod+ def forward(ctx, logits, teacher_index, teacher_prob, labels, tau, eps, vocab_chunk):+ # logits: [B, seq, vocab]+ # teacher_prob: [B, seq, K] (Top-K) or [B, seq, vocab] (full)+ # teacher_index: [B, seq, K] (Top-K) or None (full)+ # labels: [B, seq] (-100 = ignore)+ B, S, V = logits.shape+ tau = float(tau)+ vocab_chunk = int(vocab_chunk) if vocab_chunk else V+ vocab_chunk = max(1, min(vocab_chunk, V))+ use_triton = _HAS_TRITON and logits.is_cuda++ # The kernels index rows via strides; only the last (vocab) dim must be+ # contiguous. Model LM-head logits already are, but be safe.+ if use_triton and logits.stride(-1) != 1:+ logits = logits.contiguous()++ S1 = S - 1+ M = B * S1+ mask = labels[:, 1:].reshape(M) != -100+ n_valid = int(mask.sum().item())++ ctx.shape = (B, S, V)+ ctx.tau = tau+ ctx.eps = float(eps)+ ctx.vocab_chunk = vocab_chunk+ ctx.n_valid = n_valid+ ctx.full_mode = teacher_index is None+ ctx.use_triton = use_triton++ if n_valid == 0:+ ctx.save_for_backward(logits)+ return logits.new_zeros(())++ # Per-row log-normalizer logsumexp(s/τ) -> [M], float32.+ if use_triton:+ logz = _triton_logsumexp(logits, tau)+ else:+ logz = _streaming_logsumexp(logits[:, :-1, :].reshape(M, V), tau, vocab_chunk)++ s3 = logits[:, :-1, :] # [B, S1, V] view+ logz3 = logz.view(B, S1)+ if teacher_index is None:+ # Full-distribution teacher (already sums to 1). The [B, S1, chunk]+ # product is transient; nothing full-vocab beyond the resident probs.+ p_full = teacher_prob[:, :-1, :].float() # [B, S1, V] (already resident)+ # FP16 storage does not preserve unit row mass. Both the KL formula+ # and its softmax-minus-target derivative require normalized targets.+ p_full = p_full / p_full.sum(dim=-1, keepdim=True).clamp_min(ctx.eps)+ cross = torch.zeros(B, S1, device=logits.device, dtype=torch.float32)+ neg_ent = torch.zeros(B, S1, device=logits.device, dtype=torch.float32)+ for c0 in range(0, V, vocab_chunk):+ c1 = min(c0 + vocab_chunk, V)+ pc = p_full[:, :, c0:c1]+ cross += (pc * (s3[:, :, c0:c1].float() / tau)).sum(dim=-1)+ neg_ent += torch.xlogy(pc, pc).sum(dim=-1)+ ti = logits.new_empty(0)+ pT = p_full+ else:+ K = teacher_prob.shape[-1]+ ti = teacher_index[:, :-1, :] # [B, S1, K]+ # Cache already holds softmax(topk(t)/τ) over the K set; the+ # renormalization is only a guard against storage round-off.+ pT = teacher_prob[:, :-1, :].float()+ pT = pT / pT.sum(dim=-1, keepdim=True).clamp_min(ctx.eps)+ s_sel = s3.gather(-1, ti).float() / tau # [B, S1, K]+ cross = (pT * s_sel).sum(dim=-1) # [B, S1]+ neg_ent = torch.xlogy(pT, pT).sum(dim=-1) # Σ p_T log p_T++ # KL(p_T || p_S) = Σ p_T log p_T − Σ p_T log p_S = neg_ent + logz − cross.+ # The teacher-entropy term is constant w.r.t. the student, so the gradient+ # is identical to soft-target CE; including it makes the logged loss a true+ # KL (0 at a perfect match) instead of KL + H(p_T).+ mask3 = mask.view(B, S1)+ loss_row = torch.where(mask3, logz3 - cross + neg_ent, torch.zeros_like(logz3))+ loss = (tau * tau) * loss_row.sum() / n_valid++ ctx.save_for_backward(logits, logz, pT, ti, mask)+ return loss++ @staticmethod+ def backward(ctx, grad_out):+ B, S, V = ctx.shape+ if ctx.n_valid == 0:+ (logits,) = ctx.saved_tensors+ return torch.zeros_like(logits), None, None, None, None, None, None++ logits, logz, pT, ti, mask = ctx.saved_tensors+ tau = ctx.tau+ vocab_chunk = ctx.vocab_chunk+ S1 = S - 1++ grad_logits = torch.zeros_like(logits)+ seg = grad_logits[:, :-1, :] # [B, S1, V] view -> in-place writes land in grad_logits+ scale = grad_out.float() * (tau / ctx.n_valid)+ mask3 = mask.view(B, S1, 1)+ logz3 = logz.view(B, S1, 1)+ s3 = logits[:, :-1, :]++ # Recompute softmax(s/τ) and write it straight into the gradient buffer+ # (no full-vocab softmax retained anywhere else).+ if ctx.use_triton:+ _triton_softmax_into(grad_logits, logits, logz, tau, pT.contiguous(), mask, scale, ctx.full_mode)+ else:+ for c0 in range(0, V, vocab_chunk):+ c1 = min(c0 + vocab_chunk, V)+ sc = s3[:, :, c0:c1].float() / tau+ grad = torch.exp(sc - logz3)+ if ctx.full_mode:+ grad -= pT[:, :, c0:c1]+ grad = torch.where(mask3, grad * scale, 0.0)+ seg[:, :, c0:c1] = grad.to(grad_logits.dtype)++ if not ctx.full_mode:+ # Overwrite the sparse target positions with their complete FP32+ # gradient. Subtracting from an already-cast dense gradient would+ # lose near-equal student/teacher probabilities in FP16/BF16.+ selected = torch.exp(s3.gather(-1, ti).float() / tau - logz3) - pT+ selected = torch.where(mask3, selected * scale, 0.0)+ seg.scatter_(2, ti, selected.to(grad_logits.dtype))++ return grad_logits, None, None, None, None, None, None+++@register_pipeline_member(QADConfig)+class QADQuantizer(SignRoundQuantizer):+ """Whole-model QAD: distill the FP teacher's cached Top-K into the student.++ Unlike block-by-block tuning, QAD optimizes the entire network jointly with a+ single full-model forward to the LM head (``whole_model_tuning``), so there is+ no nblocks fusing and no probing of the modules between the last block and the+ LM head:++ * The full-precision teacher is forwarded once (offline); only the Top-K+ ``(index, prob)`` per token is cached to disk.+ * All quantizable layers are wrapped and tuned jointly against a+ temperature-scaled soft-label cross-entropy over the teacher Top-K, so+ neither the teacher model nor full-vocab logits stay resident.+ """++ #: Run a single full-model forward instead of the per-block loop.+ whole_model_tuning = True+ requires_original_weights = True++ def __init__(self, config: QADConfig) -> None:+ super().__init__(config)+ self.qad_top_k = getattr(config, "topk", 32)+ self.qad_temperature = getattr(config, "lfq_temperature", 1.0)+ self.qad_workspace = getattr(config, "qad_workspace", None)+ # Loss mixing weights: total = kd_weight * KD(teacher) + ce_weight * CE(label).+ # kd_weight=0 => pure hard-label QAT (teacher cache is skipped);+ # ce_weight>0 => mix the ground-truth cross-entropy into the distillation.+ self.qad_kd_weight = float(getattr(config, "qad_kd_weight", 1.0))+ self.qad_ce_weight = float(getattr(config, "qad_ce_weight", 0.0))+ self._qad_use_teacher = self.qad_kd_weight > 0.0+ # Optionally train the non-quantized FP params (lm_head/embeddings/norms/+ # biases) jointly with the quantization params (QAT-style full tuning).+ self.tune_non_quant_params = bool(getattr(config, "tune_non_quant_params", False))+ self.non_quant_params_lr = getattr(config, "non_quant_params_lr", None)+ # Vocab chunk width for the streaming KD loss (caps the softmax temporary+ # at [N, chunk] in both forward and backward). 0/None = whole vocab.+ self.qad_loss_vocab_chunk = getattr(config, "qad_loss_vocab_chunk", 32768)+ # Recompute block activations in backward instead of storing them.+ self.gradient_checkpointing = getattr(config, "gradient_checkpointing", True)+ self._teacher_cache: TeacherTopKCache | None = None++ # ── optimizer selection (signround / adamw) ───────────────────────────────+ def _get_optimizer(self, optimizer):+ """Resolve the QAD optimizer: SignSGD ('signround') or AdamW ('adamw')."""+ opt = str(optimizer or "signround").lower()+ self._use_adamw = opt in ("adamw", "adam")+ if self._use_adamw:+ self.momentum = None # AdamW manages momentum internally+ return torch.optim.AdamW+ return SignSGD++ def _get_scaler(self):+ if not getattr(self, "_use_adamw", False):+ return super()._get_scaler()+ scaler = None+ if self.model_context.amp and not check_is_cpu(device_manager.device):+ from torch.amp import GradScaler++ device_type = torch.device(device_manager.device).type+ scaler = GradScaler(device_type, init_scale=1024, growth_interval=100000)+ return scaler++ def _scale_loss_and_backward(self, scaler, loss):+ if not getattr(self, "_use_adamw", False):+ return super()._scale_loss_and_backward(scaler, loss)+ if scaler is not None:+ loss = scaler.scale(loss)+ loss.backward()+ if is_hpex_available():+ htcore.mark_step()+ return loss++ def _step(self, scaler, optimizer, lr_schedule):+ if not getattr(self, "_use_adamw", False):+ return super()._step(scaler, optimizer, lr_schedule)+ if scaler is not None:+ scaler.step(optimizer)+ optimizer.zero_grad()+ lr_schedule.step()+ scaler.update()+ else:+ optimizer.step()+ optimizer.zero_grad()+ lr_schedule.step()+ if is_hpex_available():+ htcore.mark_step()++ # ── workspace / cache management ──────────────────────────────────────────+ def get_calibration_token_ids(self, token_ids, calibration):+ """Use original forward inputs, never the block reconstruction labels."""+ samples = getattr(calibration, "model_input_samples", None)+ if token_ids is not None and len(token_ids) and isinstance(token_ids[0], dict):+ samples = token_ids+ target = self.config.nsamples+ if target is None:+ target = len(token_ids) if token_ids is not None else self.calibration_context.nsamples+ if samples is not None and len(samples) >= target:+ return samples[:target]+ collect = getattr(calibration, "collect_token_ids", None)+ if callable(collect):+ return collect(target, include_model_inputs=True)+ # Custom calibrators may already provide raw tokens, but cannot recover+ # the context that a -100 label has destroyed.+ if token_ids is not None and any((self._as_batch_ids(ids, "cpu") < 0).any() for ids in token_ids):+ raise ValueError("QAD requires original input_ids and attention_mask, not loss-masked labels.")+ return list(token_ids)[:target] if token_ids is not None else None++ def _resolve_workspace(self) -> str:+ ws = self.qad_workspace+ # Treat None / NaN / empty as "unset" and fall back to AutoRound's workspace.+ unset = ws is None or (isinstance(ws, float) and math.isnan(ws)) or (isinstance(ws, str) and not ws.strip())+ if unset:+ ws = os.path.join(envs.AR_WORK_SPACE, "qad_teacher_cache")+ os.makedirs(ws, exist_ok=True)+ return ws++ @staticmethod+ def _as_batch_ids(ids, device) -> torch.Tensor:+ """Normalize one sample's token ids to a ``[1, seq]`` long tensor on *device*."""+ if isinstance(ids, dict):+ ids = ids.get("labels", ids["input_ids"])+ if not torch.is_tensor(ids):+ ids = torch.as_tensor(ids)+ ids = ids.to(device=device)+ if ids.dim() == 1:+ ids = ids.unsqueeze(0)+ return ids.long()++ @staticmethod+ def _strip_accelerate_hooks(model) -> None:+ """Remove accelerate dispatch hooks so a plain full-model forward works."""+ if hasattr(model, "hf_device_map") and len(getattr(model, "hf_device_map", {})) > 0:+ try:+ import accelerate++ accelerate.hooks.remove_hook_from_submodules(model)+ except Exception: # pragma: no cover - best effort+ pass++ @staticmethod+ def _safe_input_ids(ids: torch.Tensor, vocab_size: int | None) -> torch.Tensor:+ """Return a forward-safe copy of *ids* with out-of-range tokens replaced.++ Legacy tensor-only callers can carry the ``-100`` loss-ignore sentinel.+ Those are invalid embedding indices, so replace anything ``< 0`` or ``>=+ vocab_size`` with ``0``. The original ids are still used as loss labels so+ the masked positions are correctly ignored.+ """+ safe = ids.clone()+ invalid = safe < 0+ if vocab_size is not None:+ invalid = invalid | (safe >= vocab_size)+ if invalid.any():+ safe[invalid] = 0+ return safe++ # @torch.no_grad()+ def _forward_logits(self, model, batch_ids, vocab_size: int | None) -> torch.Tensor:+ """Forward original tokens and attention, independently of loss labels.++ Tensor-only callers retain the legacy sentinel handling. Calibration+ supplies dictionaries so even loss-ignored EOS tokens keep their context.+ """+ if isinstance(batch_ids, dict):+ input_ids = batch_ids["input_ids"]+ attention_mask = batch_ids.get("attention_mask", torch.ones_like(input_ids))+ else:+ input_ids = batch_ids+ attention_mask = (input_ids != -100).long()+ safe_ids = self._safe_input_ids(input_ids, vocab_size)+ return model(input_ids=safe_ids, attention_mask=attention_mask, use_cache=False).logits++ def _load_model_batch(self, sample_indices, token_ids, device):+ """Stack raw inputs/masks separately from the teacher's cached labels."""+ samples = [token_ids[int(i)] for i in sample_indices]+ if not isinstance(samples[0], dict):+ return self._load_ids_batch(sample_indices, token_ids, device)+ return {+ key: torch.cat([self._as_batch_ids(sample[key], device) for sample in samples], dim=0)+ for key in ("input_ids", "attention_mask")+ }++ @staticmethod+ def _enable_gradient_checkpointing(model) -> None:+ """Turn on HF activation checkpointing (``use_reentrant=False``).++ ``use_reentrant=False`` is required because QAD freezes every non-wrapper+ parameter, so the tensor entering the first decoder block+ (``inputs_embeds``) does not require grad; the reentrant implementation+ would then drop the gradient at the checkpoint boundary and starve the+ wrapper params. The saved-tensor-hooks implementation has no such+ restriction. No-op when the model does not support checkpointing.++ Because the base model is fully frozen, we also call+ ``enable_input_require_grads()`` (the PEFT/LoRA trick): it hooks the+ embedding output to ``requires_grad_(True)`` so the checkpointed region+ has a grad-requiring input and the autograd graph stays connected+ (otherwise ``loss`` ends up with no ``grad_fn``).+ """+ if not getattr(model, "supports_gradient_checkpointing", False):+ logger.warning("QAD: model does not support gradient checkpointing; ignoring the flag.")+ return+ try:+ model.gradient_checkpointing_enable(gradient_checkpointing_kwargs={"use_reentrant": False})+ except TypeError: # older transformers without the kwargs argument+ model.gradient_checkpointing_enable()+ # Keep the graph connected through the frozen embeddings.+ enable_input_grads = getattr(model, "enable_input_require_grads", None)+ if callable(enable_input_grads):+ enable_input_grads()++ @staticmethod+ def _disable_gradient_checkpointing(model) -> None:+ """Best-effort revert of :meth:`_enable_gradient_checkpointing`."""+ fn = getattr(model, "gradient_checkpointing_disable", None)+ if callable(fn):+ try:+ fn()+ except Exception: # pragma: no cover - best effort+ pass+ disable_input_grads = getattr(model, "disable_input_require_grads", None)+ if callable(disable_input_grads):+ try:+ disable_input_grads()+ except Exception: # pragma: no cover - best effort+ pass++ @staticmethod+ def _teacher_cache_signature(model, token_ids) -> dict:+ """Fingerprint of the run so a cache is never reused across models/data.++ Hash every parameter/buffer and all forward inputs. Config/path alone+ cannot distinguish fine-tuned or in-memory teachers. Transfer weight+ chunks to CPU so fingerprinting never duplicates a whole GPU model.+ """+ cfg = getattr(model, "config", None)+ weights = hashlib.sha256()++ def update_tensor(digest, name, tensor):+ tensor = tensor.detach()+ digest.update(f"{name}:{tensor.dtype}:{tuple(tensor.shape)}".encode())+ flat = tensor.reshape(-1)+ chunk_size = max(1, (16 * 1024 * 1024) // tensor.element_size())+ for start in range(0, flat.numel(), chunk_size):+ chunk = flat[start : start + chunk_size].cpu().contiguous().view(torch.uint8)+ digest.update(chunk.numpy().tobytes())++ for name, tensor in model.state_dict().items():+ update_tensor(weights, name, tensor)+ data_hash = hashlib.sha256()+ for index, sample in enumerate(token_ids if token_ids is not None else []):+ fields = sample if isinstance(sample, dict) else {"labels": sample}+ for key, tensor in sorted(fields.items()):+ update_tensor(data_hash, f"{index}:{key}", torch.as_tensor(tensor))+ seqlen = None+ if token_ids is not None and len(token_ids) > 0:+ first = token_ids[0]+ if isinstance(first, dict):+ first = first["input_ids"]+ if torch.is_tensor(first):+ seqlen = int(first.reshape(-1).shape[0])+ else:+ try:+ seqlen = len(first)+ except TypeError:+ seqlen = None+ return {+ "model_type": getattr(cfg, "model_type", None),+ "vocab_size": getattr(cfg, "vocab_size", None),+ "name_or_path": getattr(cfg, "_name_or_path", None),+ "model_class": f"{type(model).__module__}.{type(model).__qualname__}",+ "config": json.dumps(cfg.to_dict(), sort_keys=True, default=str) if hasattr(cfg, "to_dict") else str(cfg),+ "weights_sha256": weights.hexdigest(),+ "inputs_sha256": data_hash.hexdigest(),+ "nsamples": None if token_ids is None else len(token_ids),+ "seqlen": seqlen,+ }++ @torch.no_grad()+ def _build_teacher_cache_from_model(self, model, token_ids, device) -> None:+ """Forward the FP model to the LM head once per sample and cache the Top-K.++ Uses the real model forward (``model(input_ids).logits``), so no module+ between the last block and the LM head needs to be probed. Samples already+ on disk are skipped; each sample's logits are freed right after caching.+ """+ if self._teacher_cache is not None:+ self._teacher_cache.shutdown()+ self._teacher_cache = TeacherTopKCache(+ self._resolve_workspace(),+ self.qad_top_k,+ signature=self._teacher_cache_signature(model, token_ids),+ temperature=float(self.qad_temperature),+ )+ cache = self._teacher_cache+ vocab_size = getattr(getattr(model, "config", None), "vocab_size", None)+ was_training = model.training+ model.eval()+ n_built = 0+ for sample_idx, ids in enumerate(token_ids):+ batch_ids = self._as_batch_ids(ids, device)+ # Skip only when the cached file was produced by *this* sample; a+ # stale file from another model/dataset is rebuilt (overwritten).+ if cache.is_valid_for(sample_idx, batch_ids):+ continue+ inputs = self._load_model_batch([sample_idx], token_ids, device)+ logits = self._forward_logits(model, inputs, vocab_size) # [1, seq, vocab]+ # Store the original ids (with any -100) so they serve as loss labels.+ cache.build_sample(sample_idx, batch_ids, logits)+ del logits+ n_built += 1+ if was_training:+ model.train()+ if n_built:+ logger.info("QAD: cached teacher Top-%d for %d samples at %s", self.qad_top_k, n_built, cache.workspace)+ clear_memory()++ # ── whole-model tuning entry point ────────────────────────────────────────+ @torch.no_grad()+ def _calibrate_activations(self, model, token_ids, device) -> None:+ """Prepare activation ranges before wrapping, independently of the teacher cache."""+ from auto_round.data_type.utils import register_act_max_hooks, update_block_global_scale_if_needed+ from auto_round.utils import set_amax_for_all_moe_layers++ handles = register_act_max_hooks(model, self.config.act_data_type)+ was_training = model.training+ try:+ if handles:+ model.eval()+ vocab_size = getattr(getattr(model, "config", None), "vocab_size", None)+ for sample_idx in range(len(token_ids)):+ batch_ids = self._load_model_batch([sample_idx], token_ids, device)+ self._forward_logits(model, batch_ids, vocab_size)+ finally:+ for handle in handles:+ handle.remove()+ model.train(was_training)++ if handles:+ set_amax_for_all_moe_layers(model, attr_name="act_max")+ update_block_global_scale_if_needed(model, self.config.data_type or "int", self.config.group_size or -1)++ def quantize_model(self, model, token_ids, device=None) -> dict:+ """Tune jointly, releasing the teacher workspace even if setup fails."""+ try:+ return self._quantize_model(model, token_ids, device)+ finally:+ if self._teacher_cache is not None:+ self._teacher_cache.shutdown()++ def _quantize_model(self, model, token_ids, device=None) -> dict:+ """Tune the whole model jointly against the cached teacher distribution.++ Steps: (1) cache the FP teacher Top-K via a real full-model forward,+ (2) wrap every quantizable layer, (3) optimize all rounding/min-max+ params jointly with a full-model forward → KD loss → backward, and+ (4) return the best params for common composer finalization.+ """+ import copy++ from auto_round.compressors.utils import IndexSampler, collect_best_params++ device = device or device_manager.device+ if token_ids is None or len(token_ids) == 0:+ raise ValueError("QAD requires calibration token_ids but none were provided.")++ # Make the FP model resident on the compute device and hook-free.+ self._strip_accelerate_hooks(model)+ model.to(device)+ # A previous distributed block stage can leave placement hints on the+ # original modules. This pass is strictly single-device.+ for module in model.modules():+ if hasattr(module, "tuning_device"):+ del module.tuning_device+ # Freeze before creating wrapper parameters. Clear any gradients left+ # by a preceding stage; FP tuning is selectively re-enabled below.+ existing_tuning = {id(p) for module in model.modules() for p in getattr(module, "params", {}).values()}+ for parameter in model.parameters():+ if id(parameter) not in existing_tuning:+ parameter.requires_grad_(False)+ parameter.grad = None+ # Whole-model tuning bypasses the composer's per-block calibration.+ # Run this even when KD is disabled or all teacher samples are cached.+ self._calibrate_activations(model, token_ids, device)++ # 1) Offline teacher cache from a real full-model forward (no probing).+ # Skipped entirely for a pure hard-label QAT run (``--qad_kd_weight 0``).+ if self._qad_use_teacher:+ self._build_teacher_cache_from_model(model, token_ids, device)+ else:+ logger.info("QAD: KD weight is 0 -> hard-label QAT only; skipping the teacher cache.")++ # 2) Wrap every quantizable layer across the whole model.+ quantized_layers, unquantized_layers = self.wrapper_block(+ model,+ self.enable_minmax_tuning,+ self.enable_norm_bias_tuning,+ enable_torch_compile=self.compress_context.enable_torch_compile,+ device=device,+ enable_neuqi=getattr(self.config, "enable_neuqi", False),+ )+ logger.info("QAD: wrapped %d quantizable layers (%d kept FP).", len(quantized_layers), len(unquantized_layers))+ # The wrappers have now copied any warm-start params (e.g. from a prior+ # SignRound pass in ``--algs signround,qad``) into their tuning params.+ # Report how many layers were warm-started and drop the CPU stash.+ n_warm = 0+ for _n, m in model.named_modules():+ orig = getattr(m, "orig_layer", None)+ if orig is not None and getattr(orig, "_ar_warm_start", None):+ n_warm += 1+ del orig._ar_warm_start+ if hasattr(orig, "_ar_warm_start_wrapper_cls"):+ del orig._ar_warm_start_wrapper_cls+ if n_warm:+ logger.info("QAD: warm-started %d layers from the previous block-wise pass.", n_warm)+ else:+ logger.info("QAD: no warm-start params found; tuning starts from RTN init.")++ # 3) Collect trainable params and build the optimizer / lr schedule.+ round_params, minmax_params = [], []+ for _n, m in model.named_modules():+ if hasattr(m, "orig_layer"):+ for key in m.params.keys():+ (minmax_params if ("min" in key or "max" in key) else round_params).append(m.params[key])+ # Optionally add the non-quantized FP params (lm_head/embeddings/norms/+ # biases). Exclude the wrapper tuning params and the frozen original+ # quantized weights (everything under a wrapper's ``orig_layer``).+ fp_params = self._collect_non_quant_params(model) if self.tune_non_quant_params else []+ fp_optimizer_params, fp_master_pairs = self._prepare_fp_optimizer_params(fp_params)+ if not round_params and not minmax_params and not fp_params:+ logger.warning("QAD: no trainable quantization parameters found; nothing to tune.")+ if self._teacher_cache is not None:+ self._teacher_cache.shutdown()+ return {}++ base_lr = self.lr if self.lr is not None else (1.0 / self.iters if self.iters > 0 else 1e-3)+ minmax_lr = self.minmax_lr if self.minmax_lr is not None else base_lr+ extra_kwargs = {} if self.momentum is None else {"momentum": self.momentum}+ param_groups = [{"params": round_params, "lr": torch.tensor(float(base_lr))}]+ if self.enable_minmax_tuning and minmax_params:+ param_groups.append({"params": minmax_params, "lr": torch.tensor(float(minmax_lr))})+ if fp_params:+ fp_lr = self.non_quant_params_lr if self.non_quant_params_lr is not None else base_lr+ param_groups.append({"params": fp_optimizer_params, "lr": torch.tensor(float(fp_lr))})+ logger.info(+ "QAD: also tuning %d non-quantized FP parameter tensors (lm_head/embeddings/norms/biases) at lr=%.2e.",+ len(fp_params),+ float(fp_lr),+ )+ optimizer = self.optimizer(param_groups, lr=torch.tensor(float(base_lr)), weight_decay=0, **extra_kwargs)+ if self.lr_scheduler is None:+ lr_schedule = torch.optim.lr_scheduler.LinearLR(+ optimizer, start_factor=1.0, end_factor=0.0, total_iters=max(1, self.iters)+ )+ else:+ lr_schedule = copy.deepcopy(self.lr_scheduler)+ scaler = self._get_scaler()++ # 4) Joint tuning loop: full-model forward → KD loss → step.+ if self.gradient_checkpointing:+ # HF only runs the checkpointed path when the module is in training+ # mode, so switch to train(). LLM decoder dropout is 0 by default, so+ # the forward stays deterministic; the wrapper params still train via+ # STE. Recomputing activations in backward is the whole point here.+ self._enable_gradient_checkpointing(model)+ model.train()+ logger.info("QAD: gradient checkpointing enabled (activations recomputed in backward).")+ else:+ model.eval() # deterministic forward; wrapper params still train via STE+ vocab_size = getattr(getattr(model, "config", None), "vocab_size", None)+ nsamples = len(token_ids)+ batch_size = min(self.calibration_context.batch_size, nsamples)+ grad_accum = max(1, self.gradient_accumulate_steps)+ global_bs = min(nsamples, batch_size * grad_accum)+ sampler = IndexSampler(nsamples, global_bs)+ best_loss = float("inf")+ best_iter = -1+ best_params: dict = {}+ # The best-param snapshot covers every wrapped layer of the whole model+ # (``value`` alone is weight-sized), so always keep it on CPU instead of+ # duplicating it on the accelerator.+ best_cache_device = "cpu"+ # Non-quantized FP params are tuned in place on the model, so the best-loss+ # snapshot must cover them too (unwrapper only restores the wrapper params).+ best_fp_state: list | None = None+ from tqdm import tqdm++ # Whole-model tuning has no per-block loop, so progress is tracked over+ # the joint tuning iterations instead of over blocks.+ pbar = tqdm(range(self.iters), desc="QAD tuning")+ try:+ for it in pbar:+ global_indices = sampler.next_batch()+ if self._qad_use_teacher:+ self._teacher_cache.prefetch(global_indices)+ optimizer.zero_grad()+ total_loss = 0.0+ for start in range(0, len(global_indices), batch_size):+ idx = global_indices[start : start + batch_size]+ # Cached labels supervise the loss only. Forward the original+ # input tokens/masks, including any loss-ignored separators.+ if self._qad_use_teacher:+ batch_ids, t_index, t_prob = self._load_teacher_batch(idx, device)+ else:+ batch_ids, t_index, t_prob = self._load_ids_batch(idx, token_ids, device), None, None+ model_inputs = self._load_model_batch(idx, token_ids, device)+ logits = self._forward_logits(model, model_inputs, vocab_size)+ loss = self._qad_loss(logits, t_index, t_prob, batch_ids)+ self._scale_loss_and_backward(scaler, loss)+ total_loss += loss.item()+ # Drop the large per-microbatch logits/graph before the next+ # forward so the cached allocator can reuse the blocks.+ del logits, loss, batch_ids, model_inputs, t_index, t_prob+ # The loss was measured before the optimizer update: snapshot+ # that same state, including any jointly tuned FP parameters.+ if total_loss < best_loss:+ best_loss = total_loss+ best_iter = it+ if not self.not_use_best_mse:+ best_params = collect_best_params(model, best_cache_device)+ if fp_params:+ best_fp_state = self._snapshot_fp_params(fp_params, best_cache_device)+ self._copy_fp_grads_to_masters(fp_master_pairs)+ self._step(scaler, optimizer, lr_schedule)+ self._copy_fp_masters_to_model(fp_master_pairs)+ # Switch: with ``--not_use_best_mse`` keep the LAST iteration's+ # params instead of the best-loss ones. Collect them explicitly --+ # an empty dict would make ``unwrapper`` fall back to+ # value=0/scale=1 (plain RTN), not the tuned state.+ if self.not_use_best_mse and it == self.iters - 1:+ best_params = collect_best_params(model, best_cache_device)+ if fp_params:+ best_fp_state = self._snapshot_fp_params(fp_params, best_cache_device)+ pbar.set_postfix(loss=f"{total_loss:.3e}", best=f"{best_loss:.3e}@{best_iter}")+ logger.debug("QAD iter %d loss %.5e", it, total_loss)+ # # Periodically release cached blocks to curb fragmentation during+ # # the long whole-model tuning loop (cheap relative to a full step).+ # if self.iters <= 1 or (it % 10 == 0):+ # clear_memory()+ finally:+ # 5) Restore algorithm-specific FP params and release the prefetch pool.+ # Common wrapper finalization belongs to the composer.+ pbar.close()+ if best_iter >= 0:+ logger.info(+ "QAD: best loss %.4e at iter %d/%d%s.",+ best_loss,+ best_iter,+ self.iters,+ " (not used: --not_use_best_mse keeps the last iter)" if self.not_use_best_mse else "",+ )+ if self.gradient_checkpointing:+ self._disable_gradient_checkpointing(model)+ model.eval()+ # Restore the best-loss FP params (tuned in place on the model) before+ # baking the quantized weights.+ if best_fp_state is not None:+ self._restore_fp_params(fp_params, best_fp_state)+ if self._teacher_cache is not None:+ self._teacher_cache.shutdown()+ clear_memory()+ return best_params++ def _collect_non_quant_params(self, model) -> list:+ """Return the model's non-quantized FP params to train jointly (QAT-style).++ Excludes every parameter that belongs to a wrapper: both the tuning+ params (``value``/``min_scale``/``max_scale``) and the frozen original+ quantized weight/bias (everything under ``wrapper.orig_layer``). What+ remains are the parameters of modules kept at full precision -- e.g.+ ``lm_head``, embeddings, norms and biases -- which are enabled for grad+ and returned.+ """+ quant_param_ids: set[int] = set()+ for _n, m in model.named_modules():+ if hasattr(m, "orig_layer"):+ for p in m.params.values():+ quant_param_ids.add(id(p))+ for p in m.orig_layer.parameters(recurse=True):+ quant_param_ids.add(id(p))+ fp_params = []+ for p in model.parameters():+ if id(p) not in quant_param_ids:+ p.requires_grad_(True)+ fp_params.append(p)+ return fp_params++ @staticmethod+ def _prepare_fp_optimizer_params(fp_params):+ """Keep low-precision forward weights but optimize FP32 master copies."""+ optimizer_params, pairs = [], []+ for param in fp_params:+ if param.dtype in (torch.float16, torch.bfloat16):+ master = torch.nn.Parameter(param.detach().float().clone())+ optimizer_params.append(master)+ pairs.append((param, master))+ else:+ optimizer_params.append(param)+ return optimizer_params, pairs++ @staticmethod+ def _copy_fp_grads_to_masters(pairs):+ for param, master in pairs:+ master.grad = None if param.grad is None else param.grad.detach().float()+ param.grad = None++ @staticmethod+ @torch.no_grad()+ def _copy_fp_masters_to_model(pairs):+ for param, master in pairs:+ param.copy_(master)++ @staticmethod+ def _snapshot_fp_params(fp_params: list, device) -> list:+ """Detach-clone the FP params to *device* (CPU) as a best-loss snapshot."""+ return [p.detach().to(device, copy=True) for p in fp_params]++ @staticmethod+ def _restore_fp_params(fp_params: list, snapshot: list) -> None:+ """Copy a snapshot back into the live FP params (in place)."""+ for p, saved in zip(fp_params, snapshot):+ p.data.copy_(saved.to(p.device))++ def _load_ids_batch(self, sample_indices, token_ids, device) -> torch.Tensor:+ """Stack raw calibration ``input_ids`` for a batch (pure-QAT path).++ Used when the teacher cache is disabled (``--qad_kd_weight 0``): the+ hard-label CE only needs the token ids (with their ``-100`` ignore+ sentinels preserved as loss labels), so they are read straight from+ ``token_ids`` instead of from the on-disk teacher files.+ """+ ids_list = [self._as_batch_ids(token_ids[int(i)], device).squeeze(0) for i in sample_indices]+ return torch.stack(ids_list, dim=0)++ def _load_teacher_batch(self, sample_indices, device):+ """Load and stack cached ``(input_ids, index, prob)`` for a batch.++ Returns ``(input_ids, index, prob)`` where ``input_ids`` is ``[B, seq]``,+ ``index`` is ``[B, seq, K]`` (Top-K mode) or ``None`` (full-distribution+ mode), and ``prob`` is ``[B, seq, K]`` / ``[B, seq, vocab]``.+ """+ ids_list, idx_list, prob_list = [], [], []+ full_mode = False+ for i in sample_indices:+ input_ids, index, prob = self._teacher_cache.load(int(i), device)+ if index is None:+ full_mode = True+ ids_list.append(input_ids)+ idx_list.append(index)+ prob_list.append(prob)+ batch_ids = torch.stack(ids_list, dim=0)+ teacher_prob = torch.stack(prob_list, dim=0)+ teacher_index = None if full_mode else torch.stack(idx_list, dim=0)+ return batch_ids, teacher_index, teacher_prob++ def _qad_kd_loss(self, student_logits, teacher_index, teacher_prob, labels):+ """Temperature-scaled forward KL against the FP teacher's distribution.++ Per next-token position, the loss is ``KL(p_T || p_S)`` with+ ``p_T = softmax(t/τ)`` from the cached teacher logits and+ ``p_S = softmax(s/τ)``. When+ *teacher_index* is given, the sum is over the teacher's Top-K set (teacher+ probs renormalized within it); when it is ``None`` the teacher is the full+ vocabulary distribution. Positions with label ``-100`` are ignored.++ The heavy lifting is delegated to :class:`_QADDistillLoss`, a custom+ autograd Function that -- following Unsloth's fused cross-entropy -- keeps+ only the per-row ``logsumexp`` in the graph and recomputes ``softmax`` in+ the backward (Triton on CUDA, chunked PyTorch otherwise), so no full-vocab+ ``log_softmax`` tensor is ever retained.++ Args:+ student_logits: ``[B, seq, vocab]``.+ teacher_index: ``[B, seq, K]`` teacher Top-K token ids, or ``None``+ for a full-distribution teacher.+ teacher_prob: ``[B, seq, K]`` / ``[B, seq, vocab]`` teacher probs.+ labels: ``[B, seq]`` token ids (``-100`` = ignore).++ Returns:+ Scalar loss tensor (mean over valid next-token positions).+ """+ return _QADDistillLoss.apply(+ student_logits,+ teacher_index,+ teacher_prob,+ labels,+ float(self.qad_temperature),+ 1e-6,+ self.qad_loss_vocab_chunk,+ )++ def _qad_ce_loss(self, student_logits, labels):+ """Hard-label next-token cross-entropy over the student logits.++ This is the standard causal-LM objective: at position ``t`` the target is+ the ground-truth token ``labels[t+1]`` (``-100`` positions are ignored).+ It is expressed as a one-hot special case of :class:`_QADDistillLoss`+ (teacher mass 1.0 on the label, temperature 1.0), so it reuses the same+ memory-lean streaming/Triton path as the KD loss and shares the exact+ next-token shift and ignore mask -- no extra full-vocab log-softmax is+ materialized.++ Args:+ student_logits: ``[B, seq, vocab]``.+ labels: ``[B, seq]`` token ids (``-100`` = ignore).++ Returns:+ Scalar cross-entropy loss (mean over valid next-token positions).+ """+ # Target for student position ``t`` is the token at ``t+1``; align a+ # one-hot teacher index to the same ``[:, :-1]`` slice _QADDistillLoss+ # consumes. Invalid (-100) targets are set to 0 for the gather and are+ # dropped anyway by the shared ``labels[:, 1:] != -100`` mask.+ next_labels = torch.full_like(labels, -100)+ next_labels[:, :-1] = labels[:, 1:]+ ce_index = next_labels.clamp_min(0).unsqueeze(-1) # [B, seq, 1]+ ce_prob = torch.ones_like(ce_index, dtype=torch.float32) # one-hot mass+ return _QADDistillLoss.apply(+ student_logits,+ ce_index,+ ce_prob,+ labels,+ 1.0, # hard-label CE uses no temperature smoothing+ 1e-6,+ self.qad_loss_vocab_chunk,+ )++ def _qad_loss(self, student_logits, teacher_index, teacher_prob, labels):+ """Combined QAD objective: ``kd_weight * KD + ce_weight * CE``.++ * ``kd_weight > 0`` adds the teacher-distribution distillation term+ (:meth:`_qad_kd_loss`); *teacher_index*/*teacher_prob* come from the+ offline cache and may be ``None`` when distillation is disabled.+ * ``ce_weight > 0`` adds the hard-label cross-entropy (:meth:`_qad_ce_loss`),+ turning QAD into quantization-aware training (QAT).++ At least one weight is positive (validated by the config).+ """+ loss = None+ if self.qad_kd_weight > 0.0 and teacher_prob is not None:+ loss = self.qad_kd_weight * self._qad_kd_loss(student_logits, teacher_index, teacher_prob, labels)+ if self.qad_ce_weight > 0.0:+ ce = self.qad_ce_weight * self._qad_ce_loss(student_logits, labels)+ loss = ce if loss is None else loss + ce+ if loss is None: # defensive: config guarantees at least one active term+ raise RuntimeError("QAD loss has no active term; set --qad_kd_weight or --qad_ce_weight > 0.")+ return lossdiff --git a/auto_round/algorithms/quantization/qad/teacher_cache.py b/auto_round/algorithms/quantization/qad/teacher_cache.pynew file mode 100644index 000000000..0b386506a--- /dev/null+++ b/auto_round/algorithms/quantization/qad/teacher_cache.py@@ -0,0 +1,274 @@+# Copyright (c) 2026 Intel Corporation+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+"""Offline teacher Top-K cache for QAD (quantization-aware distillation).++The full-precision teacher is forwarded through to the LM head once, and only+the Top-K ``(index, prob)`` pairs per token are written to disk together with+the sample's own ``input_ids``. During tuning the student loads these compact+tensors per batch, so neither the teacher model nor the full-vocab logits need+to stay resident -- keeping GPU/CPU memory low.++Storing the ``input_ids`` alongside the teacher makes each file self-describing:+the cache is the single source of truth for both the student forward and the+distillation target (no separate token-id copy), and it can be matched to the+original data by content. The large first-block hidden states are never stored.++On-disk layout (one file per calibration sample)::++ <workspace>/teacher_<sample_idx>.pt -> {+ "input_ids": int32[seq], # the tokens that produced the teacher+ "index": int32[seq, K] | None, # teacher Top-K token ids (None = full vocab)+ "prob": float32[seq, K] | float16[seq, vocab],+ # Top-K: softmax(topk(logits)/τ) re-normalized over K+ # full: softmax(logits/τ)+ }+"""++from __future__ import annotations++import hashlib+import json+import os+from concurrent.futures import Future, ThreadPoolExecutor++import torch+from filelock import FileLock++from auto_round.logger import logger+++class TeacherTopKCache:+ """Disk-backed store of per-token teacher Top-K ``(index, prob)`` tensors.++ When ``top_k == -1`` the full vocabulary distribution is stored instead (the+ ``index`` field is omitted and the student compares against every logit).++ A small thread pool provides optional read-ahead: :meth:`prefetch` submits+ background disk reads for a set of sample indices so that a later+ :meth:`load` returns an already-loaded tensor instead of blocking on IO.++ The cache is **self-invalidating**: a ``manifest.json`` records the signature+ of the run that produced the files (model fingerprint, vocab size, Top-K, …).+ When a new run opens the workspace with a different signature the stale+ teacher files are cleared, so a cache written for one model/config is never+ silently reused by another (which would, e.g., feed out-of-range token ids+ from a larger vocabulary into a smaller model's ``gather``).+ """++ _MANIFEST = "manifest.json"++ def __init__(+ self,+ workspace: str,+ top_k: int,+ num_workers: int = 4,+ signature: dict | None = None,+ temperature: float = 1.0,+ ) -> None:+ self.top_k = int(top_k)+ # Distillation temperature τ: the cached teacher target is softmax(t/τ),+ # matching the student's softmax(s/τ) in the KD loss.+ self.temperature = float(temperature)+ if self.temperature <= 0:+ raise ValueError("`temperature` must be positive")+ self.store_full = self.top_k == -1+ # Different teachers never invalidate each other's files. Identical+ # signatures share a namespace for reuse, with one active owner at a+ # time so neither rebuilding nor prefetching can race another process.+ if signature is not None:+ namespace = json.dumps(+ {**signature, "top_k": self.top_k, "temperature": self.temperature}, sort_keys=True+ ).encode()+ workspace = os.path.join(workspace, hashlib.sha256(namespace).hexdigest())+ self.workspace = workspace+ os.makedirs(self.workspace, exist_ok=True)+ self._workspace_lock = FileLock(os.path.join(self.workspace, ".cache.lock"), timeout=0, thread_local=False)+ self._workspace_lock.acquire()+ self._num_workers = max(1, int(num_workers))+ self._executor: ThreadPoolExecutor | None = None+ self._pending: dict[int, Future] = {}+ try:+ self._reconcile_signature(signature)+ except BaseException:+ self._workspace_lock.release()+ raise++ # ── signature / invalidation ──────────────────────────────────────────────+ def _manifest_path(self) -> str:+ return os.path.join(self.workspace, self._MANIFEST)++ def _reconcile_signature(self, signature: dict | None) -> None:+ """Drop stale teacher files when the workspace signature changed.++ The Top-K width is always part of the effective signature (a cache built+ with a different ``top_k`` cannot be reused), so it is merged in here.+ """+ if signature is None:+ return+ # `target` versions the stored semantics (Top-K logits re-softmaxed) so+ # caches written by older code are rebuilt.+ sig = {**signature, "top_k": self.top_k, "temperature": self.temperature, "target": "topk_logit_softmax"}+ existing = None+ path = self._manifest_path()+ if os.path.exists(path):+ try:+ with open(path, encoding="utf-8") as fh:+ existing = json.load(fh)+ except (OSError, json.JSONDecodeError):+ existing = None+ if existing != sig:+ if existing is not None:+ logger.warning(+ "QAD: teacher cache at %s was built for a different run "+ "(signature mismatch); clearing stale files.",+ self.workspace,+ )+ self.clear()+ try:+ with open(path, "w", encoding="utf-8") as fh:+ json.dump(sig, fh)+ except OSError: # pragma: no cover - best effort+ pass++ def _path(self, sample_idx: int) -> str:+ return os.path.join(self.workspace, f"teacher_{int(sample_idx)}.pt")++ def exists(self, sample_idx: int) -> bool:+ return os.path.exists(self._path(sample_idx))++ def is_valid_for(self, sample_idx: int, input_ids: torch.Tensor) -> bool:+ """Return True only when the cached sample was produced by *input_ids*.++ Guards against reusing a file whose tokens differ from the current+ calibration sample (different dataset, order, or sequence length), and+ drops files that are unreadable or whose Top-K width no longer matches+ the configured ``top_k``.+ """+ if not self.exists(sample_idx):+ return False+ try:+ data = torch.load(self._path(sample_idx), map_location="cpu")+ except Exception: # pragma: no cover - corrupt file -> rebuild+ return False+ cached_ids = data.get("input_ids")+ ids = input_ids.reshape(-1).to(torch.int32).cpu()+ if cached_ids is None or tuple(cached_ids.shape) != tuple(ids.shape) or not torch.equal(cached_ids, ids):+ return False+ index = data.get("index")+ if self.store_full:+ return index is None+ if index is None:+ return False+ # A rebuilt file with a different top_k width cannot be stacked with+ # peers, so force a rebuild when the stored width diverges.+ return index.size(-1) == self.top_k++ @torch.no_grad()+ def build_sample(self, sample_idx: int, input_ids: torch.Tensor, logits: torch.Tensor) -> None:+ """Extract and persist the teacher distribution (and its input) for one sample.++ Args:+ sample_idx: Calibration-sample index (the key).+ input_ids: The token ids that produced *logits*, shape ``[1, seq]`` or ``[seq]``.+ logits: Teacher logits of shape ``[1, seq, vocab]`` or ``[seq, vocab]``.+ """+ if logits.dim() == 3:+ logits = logits[0]+ ids = input_ids.reshape(-1).to(torch.int32).cpu()+ logits = logits.float()+ if self.store_full or self.top_k >= logits.size(-1):+ # Store the full distribution softmax(t/τ); indices are implicit (0..vocab-1).+ probs = torch.softmax(logits / self.temperature, dim=-1)+ torch.save(+ {"input_ids": ids, "index": None, "prob": probs.to(torch.float16).cpu()},+ self._path(sample_idx),+ )+ return+ # Top-K mode: take the teacher's Top-K *logits*, then re-softmax over just+ # those K entries -> p_T = softmax(topk(t)/τ), which sums to 1 over the K set.+ top_logits, indices = logits.topk(self.top_k, dim=-1) # [seq, K]+ probs = torch.softmax(top_logits / self.temperature, dim=-1)+ torch.save(+ {+ "input_ids": ids,+ "index": indices.to(torch.int32).cpu(),+ # K is small, keep fp32 so the renormalized target is stored exactly.+ "prob": probs.cpu(),+ },+ self._path(sample_idx),+ )++ # Read-ahead prefetching+ def _pool(self) -> ThreadPoolExecutor:+ if self._executor is None:+ self._executor = ThreadPoolExecutor(max_workers=self._num_workers, thread_name_prefix="qad_teacher")+ return self._executor++ def _read_cpu(self, sample_idx: int):+ """Blocking disk read of one sample → ``(input_ids, index_or_None, prob)`` on CPU."""+ data = torch.load(self._path(sample_idx), map_location="cpu")+ return data["input_ids"], data["index"], data["prob"]++ def prefetch(self, sample_indices) -> None:+ """Submit background disk reads for *sample_indices* (non-blocking)."""+ for i in sample_indices:+ i = int(i)+ if i not in self._pending:+ self._pending[i] = self._pool().submit(self._read_cpu, i)++ def load(self, sample_idx: int, device: torch.device) -> tuple[torch.Tensor, torch.Tensor | None, torch.Tensor]:+ """Load one sample's ``(input_ids, index, prob)`` onto *device*.++ Uses a pending prefetch future when available; otherwise reads from disk+ synchronously.++ Returns:+ ``(input_ids, index, prob)`` where ``input_ids`` is ``[seq]`` long,+ ``index`` is ``[seq, K]`` long (or ``None`` for a full-distribution+ cache) and ``prob`` is ``[seq, K]`` / ``[seq, vocab]`` float.+ """+ sample_idx = int(sample_idx)+ future = self._pending.pop(sample_idx, None)+ if future is not None:+ input_ids, index, prob = future.result()+ else:+ input_ids, index, prob = self._read_cpu(sample_idx)+ input_ids = input_ids.to(device=device, dtype=torch.long)+ if index is not None:+ index = index.to(device=device, dtype=torch.long)+ prob = prob.to(device=device, dtype=torch.float32)+ return input_ids, index, prob++ def shutdown(self) -> None:+ """Stop the prefetch thread pool and drop any pending futures."""+ self._pending.clear()+ if self._executor is not None:+ self._executor.shutdown(wait=True, cancel_futures=True)+ self._executor = None+ self._workspace_lock.release()++ def clear(self) -> None:+ """Remove all cached teacher files from the workspace."""+ if not os.path.isdir(self.workspace):+ return+ removed = 0+ for name in os.listdir(self.workspace):+ if name.startswith("teacher_") and name.endswith(".pt"):+ try:+ os.remove(os.path.join(self.workspace, name))+ removed += 1+ except OSError:+ pass+ if removed:+ logger.debug("QAD: cleared %d cached teacher files from %s", removed, self.workspace)diff --git a/auto_round/algorithms/quantization/qat/__init__.py b/auto_round/algorithms/quantization/qat/__init__.pynew file mode 100644index 000000000..2b4435f61--- /dev/null+++ b/auto_round/algorithms/quantization/qat/__init__.py@@ -0,0 +1,24 @@+# Copyright (c) 2026 Intel Corporation+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+"""QAT (quantization-aware training) algorithm package.++QAT tunes the whole network jointly against the ground-truth next-token+cross-entropy -- i.e. the pure hard-label special case of QAD with no teacher+model and no offline teacher cache. It reuses QAD's whole-model tuning loop via+a thin subclass.+"""++from auto_round.algorithms.quantization.qat.config import QATConfig++__all__ = ["QATConfig"]diff --git a/auto_round/algorithms/quantization/qat/config.py b/auto_round/algorithms/quantization/qat/config.pynew file mode 100644index 000000000..2bb897820--- /dev/null+++ b/auto_round/algorithms/quantization/qat/config.py@@ -0,0 +1,65 @@+# Copyright (c) 2026 Intel Corporation+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+"""QAT (quantization-aware training) algorithm config.++QAT is the pure hard-label special case of QAD: all text-decoder blocks are+tuned jointly against the ground-truth next-token cross-entropy, so the+expensive offline teacher Top-K cache is never built. The config reuses QAD's+whole-model tuning machinery and only drops the distillation-specific knobs+(``--topk``, ``--qad_workspace`` and the KD/CE loss weights).+"""++from __future__ import annotations++from auto_round.algorithms.config import AlgorithmParameterRegistry+from auto_round.algorithms.quantization.qad.config import QADConfig+from auto_round.algorithms.quantization.sign_round.config import SignRoundConfig+from auto_round.algorithms.registry import register_algorithm+++class QATConfig(QADConfig):+ """Configuration for the QAT (quantization-aware training) algorithm.++ Equivalent to ``QADConfig(qad_kd_weight=0, qad_ce_weight=1)`` but exposed as a+ first-class algorithm: it forces the pure hard-label objective and never+ constructs the teacher cache. It inherits every whole-model tuning behavior+ from :class:`QADConfig` and resolves to+ :class:`~auto_round.algorithms.quantization.qat.quantizer.QATQuantizer`.+ """++ @classmethod+ def register_args(cls, registry: AlgorithmParameterRegistry) -> None:+ # Skip QAD's teacher-distillation args (topk / workspace / KD-CE weights);+ # QAT only exposes the shared whole-model tuning knobs (lr, nsamples,+ # optimizer, gradient checkpointing) on top of the SignRound base args.+ SignRoundConfig.register_args(registry)+ cls._register_qad_tuning_args(registry)++ def __init__(self, *, qad_ce_weight: float = 1.0, **kwargs) -> None:+ # Pure hard-label training: no KD term -> no teacher model, no cache.+ kwargs["qad_kd_weight"] = 0.0+ if float(qad_ce_weight) <= 0:+ raise ValueError("`qad_ce_weight` must be > 0 for QAT")+ # Drop any teacher-only kwargs that might arrive from a shared config so+ # they never reach the base initializer with surprising values.+ kwargs.pop("topk", None)+ super().__init__(qad_ce_weight=float(qad_ce_weight), **kwargs)+++register_algorithm(+ "qat",+ aliases=("qat",),+ config_factory=QATConfig,+ summary="Quantization-aware training on ground-truth labels (no teacher cache).",+)diff --git a/auto_round/algorithms/quantization/qat/quantizer.py b/auto_round/algorithms/quantization/qat/quantizer.pynew file mode 100644index 000000000..541d01e8e--- /dev/null+++ b/auto_round/algorithms/quantization/qat/quantizer.py@@ -0,0 +1,33 @@+# Copyright (c) 2026 Intel Corporation+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+"""QAT quantizer: whole-network hard-label training (no teacher cache)."""++from __future__ import annotations++from auto_round.algorithms.quantization.qad.quantizer import QADQuantizer+from auto_round.algorithms.quantization.qat.config import QATConfig+from auto_round.algorithms.registry import register_pipeline_member+++@register_pipeline_member(QATConfig)+class QATQuantizer(QADQuantizer):+ """Pure quantization-aware training on ground-truth labels.++ QAT is QAD with ``qad_kd_weight == 0``: the whole model is tuned jointly+ against the hard-label next-token cross-entropy, so the offline teacher+ Top-K cache is skipped entirely (``_qad_use_teacher`` is ``False``). All the+ heavy lifting -- wrapping layers, the whole-model forward, the AdamW/SignSGD+ optimizer selection and the best-param bookkeeping -- is inherited unchanged+ from :class:`QADQuantizer`.+ """diff --git a/auto_round/algorithms/quantization/search_dispatch.py b/auto_round/algorithms/quantization/search_dispatch.pyindex e8fd4b090..3aa9c2013 100644--- a/auto_round/algorithms/quantization/search_dispatch.py+++ b/auto_round/algorithms/quantization/search_dispatch.py@@ -466,6 +466,11 @@ def run_batched_wrap_search(deferred_wrappers: list[WrapperLinear], max_batch: ifor w in deferred_wrappers:inputs = w._deferred_search_inputsif inputs is None:+ # Warm-started wrappers (e.g. QAD chaining `signround,qad`) resolve+ # ``init_scale`` directly and stage no search; skip them. A wrapper+ # with neither staged inputs nor a resolved init_scale is a real bug.+ if getattr(w, "init_scale", None) is not None:+ continueraise RuntimeError(f"{type(w).__name__} was queued for batched wrap search without staged inputs; ""the defer_search flag never reached its search init"diff --git a/auto_round/algorithms/quantization/sign_round/config.py b/auto_round/algorithms/quantization/sign_round/config.pyindex e11f064a1..fef318f29 100644--- a/auto_round/algorithms/quantization/sign_round/config.py+++ b/auto_round/algorithms/quantization/sign_round/config.py@@ -22,6 +22,10 @@ from auto_round.logger import loggerclass SignRoundConfig(QuantizationConfig):"""Configuration for SignRound-style block quantization."""+ # Whether to emit the generic `enable_qad` experimental warning (subclasses+ # with their own warning, e.g. QADConfig, disable it).+ _warn_enable_qad = True+@classmethoddef register_args(cls, registry: AlgorithmParameterRegistry) -> None:registry.add_argument(@@ -121,6 +125,70 @@ class SignRoundConfig(QuantizationConfig):action="boolean_optional",help="Enable last-block LM cross-entropy (LFQ) loss for the final transformer block (experimental).",)+ registry.add_argument(+ "--lfq_loss",+ field="lfq_loss",+ default="tk",+ choices=["ce", "dtk", "rkl", "tk"],+ help=(+ "LFQ loss type for the final transformer block. 'ce' uses next-token cross-entropy "+ "against the ground-truth labels; 'dtk' uses the Decoupled Tempered Top-K forward-KL "+ "knowledge distillation loss (KL(p_T || p_S)); 'rkl' uses the same decoupled Top-K "+ "objective with the reverse KL (KL(p_S || p_T)); 'tk' only aligns the Top-K-normalized "+ "conditional distributions (tempered conditional KL within the teacher Top-K, without "+ "the binary mass term). 'dtk'/'rkl'/'tk' distill the FP (teacher) block output into the "+ "quantized (student) block output (experimental)."+ ),+ )+ registry.add_argument(+ "--lfq_top_k",+ field="lfq_top_k",+ default=32,+ type=int,+ help="Number of top teacher logits used by the 'dtk' LFQ loss.",+ )+ registry.add_argument(+ "--lfq_temperature",+ field="lfq_temperature",+ default=1.0,+ type=float,+ help="Temperature applied to the within-Top-K conditional KL term of the 'dtk' LFQ loss.",+ )+ registry.add_argument(+ "--lfq_num_blocks",+ field="lfq_num_blocks",+ default=1,+ type=int,+ help=(+ "Number of final text-decoder blocks the LFQ loss is applied to (default 1 = last "+ "block only). Increase to propagate the logit-aware signal to deeper blocks."+ ),+ )+ registry.add_argument(+ "--lfq_mse_weight",+ field="lfq_mse_weight",+ default=0.0,+ type=float,+ help=(+ "Weight of the MSE block-reconstruction term added to the LFQ (KD) loss: "+ "loss = kd_loss + lfq_mse_weight * mse_loss. 0.0 (default) replaces the MSE loss "+ "entirely with the KD loss (original behavior); >0 combines both so the block keeps "+ "its reconstruction fidelity while adding logit alignment."+ ),+ )+ registry.add_argument(+ "--enable_qad",+ field="enable_qad",+ default=False,+ action="boolean_optional",+ help=(+ "Enable QAD (quantization-aware distillation): fuse all text-decoder blocks into a "+ "single jointly-optimized group (whole-network training, not block-by-block) and tune "+ "them against the final-output LM loss (`--lfq_loss`, default 'ce'). No intermediate "+ "block MSE is used. Implies --enable_lfq. Set --nblocks N to train in joint chunks of "+ "N blocks instead of the whole network at once (experimental)."+ ),+ )registry.add_argument("--enable_neuqi",field="enable_neuqi",@@ -151,6 +219,12 @@ class SignRoundConfig(QuantizationConfig):optimizer: str | None = None, # TODO later wenhuach delete thisenable_adam: bool = False, # TODO later wenhuach delete thisenable_lfq: bool = False,+ lfq_loss: str = "tk",+ lfq_top_k: int = 32,+ lfq_temperature: float = 1.0,+ lfq_num_blocks: int = 1,+ lfq_mse_weight: float = 0.0,+ enable_qad: bool = False,enable_neuqi: bool = False,**kwargs,) -> None:@@ -185,6 +259,30 @@ class SignRoundConfig(QuantizationConfig):quantized output of previous blocks during calibration.optimizer: Optional optimizer name override.enable_adam: Whether to use the Adam-based SignRound variant.+ enable_lfq: Enable the last-block LM loss (LFQ) for the final+ transformer block (experimental).+ lfq_loss: LFQ loss type, ``"ce"`` (next-token cross-entropy),+ ``"dtk"`` (Decoupled Tempered Top-K forward-KL distillation,+ ``KL(p_T || p_S)``), ``"rkl"`` (same decoupled Top-K objective+ with the reverse KL ``KL(p_S || p_T)``) or ``"tk"`` (only align+ the Top-K-normalized conditional distributions, without the+ binary mass term). ``"dtk"``/``"rkl"``/``"tk"`` distill the FP+ teacher block output into the quantized student.+ lfq_top_k: Number of top teacher logits used by the ``"dtk"`` LFQ loss.+ lfq_temperature: Temperature applied to the within-Top-K conditional+ KL term of the ``"dtk"`` LFQ loss.+ lfq_num_blocks: Number of final text-decoder blocks the LFQ loss is+ applied to (default 1 = last block only).+ lfq_mse_weight: Weight of the MSE block-reconstruction term added to+ the KD loss (``loss = kd_loss + lfq_mse_weight * mse_loss``). 0.0+ replaces MSE with the KD loss (original behavior); >0 combines+ both.+ enable_qad: Enable QAD (quantization-aware distillation): fuse all+ text-decoder blocks into a single jointly-optimized group and+ tune them against the final-output LM loss (``lfq_loss``, default+ ``"ce"``), with no intermediate block MSE. Implies+ ``enable_lfq``. ``nblocks`` > 1 trains in joint chunks instead of+ the whole network at once.enable_neuqi: Opt into the NeUQI grid search (arXiv 2505.17595):the joint (scale, integer zero-point) search runs once atlayer init and anchors the tuning grid to the winner, frozen@@ -228,7 +326,33 @@ class SignRoundConfig(QuantizationConfig):self.enable_adam = enable_adamself.enable_lfq = enable_lfqif self.enable_lfq:- logger.warning("the `enable_lfq` feature is experimental and currently has limited model support.")+ logger.warning_once("the `enable_lfq` feature is experimental and currently has limited model support.")+ self.lfq_loss = lfq_loss+ if self.lfq_loss not in ("ce", "dtk", "rkl", "tk"):+ raise ValueError(f"`lfq_loss` must be one of 'ce', 'dtk', 'rkl' or 'tk', got {self.lfq_loss!r}")+ self.lfq_top_k = lfq_top_k+ if self.lfq_top_k <= 0:+ raise ValueError("`lfq_top_k` must be positive")+ self.lfq_temperature = lfq_temperature+ if self.lfq_temperature <= 0:+ raise ValueError("`lfq_temperature` must be positive")+ self.lfq_num_blocks = lfq_num_blocks+ if self.lfq_num_blocks <= 0:+ raise ValueError("`lfq_num_blocks` must be positive")+ self.lfq_mse_weight = lfq_mse_weight+ if self.lfq_mse_weight < 0:+ raise ValueError("`lfq_mse_weight` must be non-negative")+ # Legacy QAD flag: configuration normalization routes this to QADConfig+ # and its whole-model quantizer, independently of block-wise nblocks.+ self.enable_qad = enable_qad+ if self.enable_qad:+ self.enable_lfq = True+ # QADConfig emits its own (more specific) warning, so skip the generic one there.+ if self.enable_qad and self._warn_enable_qad:+ logger.warning_once(+ "the `enable_qad` (quantization-aware distillation) mode is experimental: all "+ "text-decoder blocks are tuned jointly with a whole-model forward."+ )def _lr_for_bits(self, bits: int | None) -> float | None:"""Return the auto lr heuristic for a given bit-width.diff --git a/auto_round/algorithms/quantization/sign_round/lfq.py b/auto_round/algorithms/quantization/sign_round/lfq.pynew file mode 100644index 000000000..0e359127a--- /dev/null+++ b/auto_round/algorithms/quantization/sign_round/lfq.py@@ -0,0 +1,595 @@+# Copyright (c) 2024-2025 Intel Corporation+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.++"""LFQ model helpers and losses, including memory-efficient soft cross-entropy.++The LFQ objective (Eq. 3 of the paper) minimizes the cross-entropy between the+FP model's token distribution ``σ(X·W_FP·W_Head)`` and the quantized model's+distribution ``σ(X·W_q·W_Head)``. A naive implementation materializes two full+``[batch*seq, vocab]`` float32 tensors (softmax and log_softmax) plus the+autograd graph that produces them -- prohibitive for large-vocab models.++This module reproduces the essence of Unsloth's fused cross-entropy trick, but+for a *soft* target distribution instead of hard integer labels:++* logsumexp reformulation so ``log_softmax`` is never materialized::++ softCE_i = logsumexp(q_i) - Σ_j softmax(fp_i)_j · q_{i,j} (Σ_j p=1)++* analytic gradient (no autograd graph through softmax)::++ dL/dq_{i,j} = softmax(q_i)_j - softmax(fp_i)_j++* row chunking: only ``chunk_rows × vocab`` float32 elements are live at a time;+ softmax is recomputed in the backward pass (compute-for-memory tradeoff).++Unlike Unsloth's Triton kernel this is pure PyTorch, so it runs on CPU / CUDA /+HPU without a Triton dependency.+"""++from __future__ import annotations++from typing import TYPE_CHECKING, Any++import torch++from auto_round.logger import logger++if TYPE_CHECKING:+ from auto_round.algorithms.block_runner import BlockForwardRunner+ from auto_round.context.model import ModelContext++__all__ = ["DEFAULT_SOFT_CE_CHUNK_ELEMS", "LFQMixin", "soft_cross_entropy"]++# Target number of (rows × vocab) float32 elements processed per chunk.+# 2**23 ≈ 8.4M elems ≈ 32 MB per temporary fp32 tensor.+DEFAULT_SOFT_CE_CHUNK_ELEMS = 1 << 23+++def _rows_per_chunk(vocab_size: int, chunk_elems: int) -> int:+ return max(1, chunk_elems // max(1, vocab_size))+++class _SoftCrossEntropy(torch.autograd.Function):+ """Chunked soft cross-entropy with an analytic, memory-light backward."""++ @staticmethod+ def forward(ctx, q_logits, fp_logits, valid_mask, chunk_elems):+ # q_logits / fp_logits: [N, V]; valid_mask: [N] (float, 1.0 keep / 0.0 drop)+ n_rows, vocab_size = q_logits.shape+ rows = _rows_per_chunk(vocab_size, chunk_elems)++ denom = valid_mask.sum().clamp_min(1.0)+ total = q_logits.new_zeros((), dtype=torch.float32)++ for start in range(0, n_rows, rows):+ end = min(start + rows, n_rows)+ m = valid_mask[start:end]+ # No host-side ``if m.sum() == 0`` skip here: it would force a+ # device-to-host sync on every chunk (dozens per forward for large+ # vocabs). Invalid rows are already zeroed by multiplying with ``m``,+ # and ``denom`` guards the all-invalid case, so the math stays correct.+ q_c = q_logits[start:end].float()+ lse_q = torch.logsumexp(q_c, dim=-1)+ p_fp = torch.softmax(fp_logits[start:end].float(), dim=-1)+ dot = (p_fp * q_c).sum(dim=-1)+ ce = (lse_q - dot) * m+ total = total + ce.sum()++ loss = total / denom++ ctx.save_for_backward(q_logits, fp_logits, valid_mask, denom)+ ctx.chunk_elems = chunk_elems+ return loss++ @staticmethod+ def backward(ctx, grad_output):+ q_logits, fp_logits, valid_mask, denom = ctx.saved_tensors+ n_rows, vocab_size = q_logits.shape+ rows = _rows_per_chunk(vocab_size, ctx.chunk_elems)++ # scale = dLoss / denom, broadcast per valid row.+ scale = (grad_output / denom).to(torch.float32)+ dq = torch.empty_like(q_logits)++ for start in range(0, n_rows, rows):+ end = min(start + rows, n_rows)+ m = valid_mask[start:end].unsqueeze(-1)+ # dL/dq = softmax(q) - softmax(fp), recomputed to avoid storing it.+ grad = torch.softmax(q_logits[start:end].float(), dim=-1)+ grad -= torch.softmax(fp_logits[start:end].float(), dim=-1)+ grad *= m * scale+ dq[start:end] = grad.to(dq.dtype)++ return dq, None, None, None+++def soft_cross_entropy(+ q_logits: torch.Tensor,+ fp_logits: torch.Tensor,+ valid_mask: torch.Tensor = None,+ chunk_elems: int = DEFAULT_SOFT_CE_CHUNK_ELEMS,+) -> torch.Tensor:+ """Mean soft cross-entropy ``-Σ_j σ(fp)_j log σ(q)_j`` over valid positions.++ Gradients flow only through ``q_logits``; ``fp_logits`` is treated as a+ detached soft target.++ Args:+ q_logits: Quantized logits, shape ``[..., vocab]``.+ fp_logits: FP logits (soft target), same shape as ``q_logits``.+ valid_mask: Optional boolean/0-1 mask over positions (all leading dims+ except vocab). Positions with 0 are excluded from the loss.+ chunk_elems: Target ``rows × vocab`` float32 elements per chunk.++ Returns:+ Scalar loss tensor.+ """+ vocab_size = q_logits.shape[-1]+ q2d = q_logits.reshape(-1, vocab_size)+ fp2d = fp_logits.reshape(-1, vocab_size).detach()++ if valid_mask is None:+ mask = q2d.new_ones(q2d.shape[0], dtype=torch.float32)+ else:+ mask = valid_mask.reshape(-1).to(device=q2d.device, dtype=torch.float32)++ return _SoftCrossEntropy.apply(q2d, fp2d, mask, chunk_elems)+++class LFQMixin:+ """Please refer to https://arxiv.org/html/2605.29756v1. LFQ capabilities shared by quantizers without a separate lifecycle.++ The host initializes the LFQ configuration attributes and provides ``model``,+ ``model_context`` and ``block_forward``. It also clears the cached+ ``_lm_head`` and ``_post_block_modules`` when finalizing a run.+ """++ # Supplied by the host; annotations do not shadow its context properties.+ model: Any+ model_context: ModelContext+ block_forward: BlockForwardRunner+ enable_lfq: bool+ enable_qad: bool+ lfq_loss_type: str+ lfq_top_k: int+ lfq_temperature: float+ lfq_num_blocks: int++ def _init_lm_components(self) -> None:+ """Lazily locate and cache ``_post_block_modules`` and ``_lm_head`` for LFQ loss.++ ``_post_block_modules`` is an ordered list of modules that must be applied+ between the last transformer-block output and the lm_head projection.+ Most architectures have a single final norm; OPT additionally has an+ optional ``project_out`` projection.++ Supported without manual configuration:+ LLaMA / Qwen / Gemma / Mistral / InternLM / Phi-3 — ``model.model.norm``+ OPT — ``model.model.decoder.{final_layer_norm, project_out}`` (both optional)+ GPT-2 / Falcon / Bloom — ``model.transformer.ln_f``+ GPT-NeoX / Pythia — ``model.gpt_neox.final_layer_norm``+ Phi / Phi-2 — ``model.model.final_layernorm``+ MPT — ``model.transformer.norm_f``+ ChatGLM — ``model.transformer.encoder.final_layernorm``+ RWKV — ``model.rwkv.ln_out``++ Raises ``AttributeError`` if no lm_head equivalent can be found.+ """+ if hasattr(self, "_lm_head"):+ return++ model = self.model++ # ── lm_head ──────────────────────────────────────────────────────────+ for name in ("lm_head", "embed_out", "output", "head"):+ if hasattr(model, name):+ self._lm_head = getattr(model, name)+ break+ else:+ raise AttributeError(+ f"Cannot locate lm_head in {type(model).__name__}. " "Checked: lm_head, embed_out, output, head."+ )++ # ── post-block processing (ordered list applied before lm_head) ───────+ # OPT: decoder has both an optional final_layer_norm *and* an optional+ # project_out that maps ffn_dim → word_embed_proj_dim. Detect by probing+ # for the characteristic project_out attribute (may be None).+ try:+ decoder = model.model.decoder+ _ = decoder.project_out # raises AttributeError if not an OPT decoder+ self._post_block_modules = [m for m in (decoder.final_layer_norm, decoder.project_out) if m is not None]+ return+ except AttributeError:+ pass++ # All other architectures: single optional final norm.+ norm_getters = [+ lambda: model.model.norm, # LLaMA / Qwen / Gemma / Mistral / InternLM / Phi-3+ lambda: model.transformer.ln_f, # GPT-2 / Falcon / Bloom+ lambda: model.gpt_neox.final_layer_norm, # GPT-NeoX / Pythia+ lambda: model.model.final_layernorm, # Phi / Phi-2+ lambda: model.transformer.norm_f, # MPT+ lambda: model.transformer.encoder.final_layernorm, # ChatGLM+ lambda: model.rwkv.ln_out, # RWKV+ ]+ self._post_block_modules = []+ for getter in norm_getters:+ try:+ norm = getter()+ if norm is not None:+ self._post_block_modules = [norm]+ break+ except AttributeError:+ continue++ # Keywords that identify non-text (visual / audio / multimodal) blocks.+ # LFQ loss is only meaningful for pure language-model decoder blocks.+ _NON_TEXT_BLOCK_KEYWORDS = frozenset(+ {+ "vis",+ "vision",+ "visual",+ "image",+ "img",+ "audio",+ "video",+ "patch",+ "pixel",+ "clip",+ "vit",+ "perceiver",+ "resampler",+ "connector",+ "projector",+ }+ )++ def _is_text_decoder_block(self, block_name: str) -> bool:+ """Return ``True`` if *block_name* refers to a text-decoder block.++ Blocks whose names contain any of the non-text keywords (vision, audio,+ image, …) are considered multimodal and excluded from LFQ loss.+ """+ name_lower = block_name.lower()+ return not any(kw in name_lower for kw in self._NON_TEXT_BLOCK_KEYWORDS)++ def _lfq_is_kd_block(self, block_ctx) -> bool:+ """Return ``True`` if the KD (LFQ logit-lens) loss applies to this block.++ * QAD off (default): the last ``lfq_num_blocks`` text-decoder blocks.+ * QAD on: every fused group (chunk) is tuned against the final-output+ LM loss.++ Requires LFQ enabled, token IDs available (checked by the caller) and a+ pure text-decoder block.+ """+ if not self.enable_lfq or not self._is_text_decoder_block(block_ctx.block_name):+ return False+ # QAD: every fused group (chunk) is tuned against the final-output LM loss.+ if self.enable_qad:+ return True+ all_names = getattr(block_ctx, "all_block_names", None)+ group_names = getattr(block_ctx, "block_names", None) or []+ if all_names and group_names and group_names[-1] in all_names:+ text_names = [name for name in all_names if self._is_text_decoder_block(name)]+ endpoint = group_names[-1]+ return endpoint in text_names and text_names.index(endpoint) >= len(text_names) - self.lfq_num_blocks+ return block_ctx.block_index >= block_ctx.block_cnt - self.lfq_num_blocks++ def _get_lfq_downstream_blocks(self, block_ctx, device) -> list:+ """Return the (FP, not-yet-quantized) blocks that follow the current one.++ Only used in the default (non-QAD) LFQ mode with ``lfq_num_blocks`` > 1:+ a non-final KD block's output must go through the remaining decoder+ blocks before the final norm / lm_head, otherwise the loss would be a+ logit-lens on an intermediate hidden state. The returned blocks are+ moved to *device*; the caller is responsible for moving them back.++ Returns an empty list when the current block is the last one, when the+ block order is unknown, or when a downstream block is not materialized+ (e.g. offloaded / meta), in which case it falls back to the logit-lens.+ """+ if self.enable_qad:+ return []+ all_names = getattr(block_ctx, "all_block_names", None)+ cur_names = getattr(block_ctx, "block_names", None) or []+ if not all_names or not cur_names or cur_names[-1] not in all_names:+ if block_ctx.block_index < block_ctx.block_cnt - 1:+ logger.warning_once(+ "LFQ: block order unavailable, non-final KD blocks fall back to the logit-lens loss "+ "(block output fed directly to the final norm/lm_head)."+ )+ return []+ downstream_names = all_names[all_names.index(cur_names[-1]) + 1 :]+ if not downstream_names:+ return []++ from auto_round.utils import convert_module_to_hp_if_necessary, get_module++ model = getattr(block_ctx, "model", None) or self.model+ blocks = []+ for name in downstream_names:+ m = get_module(model, name)+ if m is None or any(p.device.type == "meta" or p.numel() == 0 for p in m.parameters()):+ logger.warning_once(+ f"LFQ: downstream block {name} is not materialized (offloaded/meta); non-final KD blocks fall "+ "back to the logit-lens loss. Disable low_cpu_mem_usage/disk streaming to propagate "+ "through the remaining blocks."+ )+ return []+ blocks.append(m)+ for m in blocks:+ convert_module_to_hp_if_necessary(m, self.model_context.amp_dtype, device)+ m.to(device)+ logger.info(+ f"LFQ: propagating {block_ctx.block_name} output through {len(blocks)} downstream FP block(s) "+ "before lm_head"+ )+ return blocks++ def _forward_lfq_downstream(+ self,+ hidden_state: torch.Tensor,+ downstream_blocks: list,+ inputs,+ input_others: dict,+ indices,+ device,+ ) -> torch.Tensor:+ """Forward *hidden_state* through *downstream_blocks* (frozen FP blocks).++ Gradients flow through the activations back to the current block; the+ downstream block parameters themselves are frozen (``requires_grad=False``).+ """+ if not downstream_blocks:+ return hidden_state+ from auto_round.utils import to_device++ block_fwd = self.block_forward+ out_device = hidden_state.device+ if not isinstance(indices, torch.Tensor):+ indices = torch.tensor(indices, dtype=torch.long)+ _, batch_others = block_fwd.select_batch(inputs, input_others, indices)+ batch_others = to_device(batch_others, device)+ h = hidden_state.to(device)+ for m in downstream_blocks:+ # block_forward mutates the kwargs dict (pops positional_inputs, injects the+ # hidden-state kwarg), so hand each block a fresh shallow copy.+ raw = block_fwd._forward_one_batch(m, h, dict(batch_others))+ h = block_fwd._normalize_output(raw, m)+ return h.to(out_device)++ def _lfq_logits(self, hidden_state: torch.Tensor) -> torch.Tensor:+ """Project a block hidden state to vocabulary logits.++ Applies every post-block module (final norm, optional projection, …) in+ order, then runs lm_head.++ Args:+ hidden_state: Block output, shape ``[batch, seq_len, hidden]``.++ Returns:+ Logits tensor of shape ``[batch, seq_len, vocab_size]``.+ """+ self._init_lm_components()+ device = hidden_state.device++ for module in self._post_block_modules:+ module.to(device)+ hidden_state = module(hidden_state)++ self._lm_head.to(device)+ return self._lm_head(hidden_state)++ def lfq_loss(+ self,+ hidden_state: torch.Tensor,+ input_ids: torch.Tensor,+ teacher_hidden_state: torch.Tensor | None = None,+ sample_indices: list | None = None,+ ) -> torch.Tensor:+ """Compute the LFQ loss from the last block's hidden states.++ Two loss types are supported, selected by ``self.lfq_loss_type``:++ * ``"ce"`` (default): next-token cross-entropy against ground-truth+ labels. Positions marked with ``-100`` in *input_ids* are excluded.+ * ``"dtk"``: Decoupled Tempered Top-K forward-KL knowledge distillation+ (``KL(p_T || p_S)``). The FP block output (*teacher_hidden_state*) is+ the teacher and the quantized block output (*hidden_state*) is the+ student. Requires *teacher_hidden_state*; falls back to ``"ce"`` when+ it is ``None``.+ * ``"rkl"``: same decoupled Top-K objective but using the reverse KL+ ``KL(p_S || p_T)`` (mode-seeking). Also requires *teacher_hidden_state*.+ * ``"tk"``: only aligns the Top-K-normalized conditional distributions+ (tempered conditional KL within the teacher Top-K, dropping the binary+ mass term). Also requires *teacher_hidden_state*.++ Args:+ hidden_state: Last (quantized/student) block output,+ shape ``[batch, seq_len, hidden]``.+ input_ids: Token-ID labels with ``-100`` for ignored positions,+ shape ``[batch, seq_len]``.+ teacher_hidden_state: FP (teacher) block output used by the ``"dtk"``,+ ``"rkl"`` and ``"tk"`` losses, same shape as *hidden_state*.+ sample_indices: Calibration-sample indices for this batch. Unused by+ the base implementation; QAD subclasses use it to load the+ offline teacher Top-K cache from disk.++ Returns:+ Scalar loss tensor.+ """+ device = hidden_state.device+ logits = self._lfq_logits(hidden_state)++ if self.lfq_loss_type in ("dtk", "rkl", "tk") and teacher_hidden_state is not None:+ with torch.no_grad():+ teacher_logits = self._lfq_logits(teacher_hidden_state.to(device))+ return self._decoupled_topk_kd_loss(+ logits,+ teacher_logits,+ input_ids.to(device),+ reverse=(self.lfq_loss_type == "rkl"),+ conditional_only=(self.lfq_loss_type == "tk"),+ )++ if not (input_ids[..., 1:] != -100).any():+ return logits.float().sum() * 0.0++ if hasattr(self.model, "loss_function"):+ loss = self.model.loss_function(+ logits=logits,+ labels=input_ids.to(device),+ vocab_size=self.model.config.vocab_size,+ )+ else:+ import torch.nn.functional as F++ # Standard causal-LM shift: predict token t+1 from hidden state t.+ shift_logits = logits[..., :-1, :].contiguous()+ shift_labels = input_ids[..., 1:].contiguous().to(device)+ loss = F.cross_entropy(+ shift_logits.view(-1, shift_logits.size(-1)),+ shift_labels.view(-1),+ ignore_index=-100,+ )+ return loss++ def _decoupled_topk_kd_loss(+ self,+ student_logits: torch.Tensor,+ teacher_logits: torch.Tensor,+ labels: torch.Tensor,+ reverse: bool = False,+ conditional_only: bool = False,+ ) -> torch.Tensor:+ """Decoupled Tempered Top-K knowledge-distillation loss (per-token mean).++ Decomposes the KL divergence between the teacher and student next-token+ distributions via the chain rule into:++ * ``L_B``: a binary (Bernoulli) term matching the total probability mass+ the teacher/student assign to the teacher's Top-K set, and+ * ``L_T``: the temperature-scaled conditional KL *within* the Top-K set,+ weighted by the expectation distribution's Top-K mass.++ This "decoupled, tempered Top-K" objective avoids support mismatch while+ preserving the benefits of temperature-scaled distillation.++ The Top-K set is always the teacher's. ``reverse`` selects the KL+ direction:++ * ``reverse=False`` (forward KL): the expectation is over the teacher,+ i.e. ``KL(p_T || p_S)`` — mode-covering, the standard distillation+ objective.+ * ``reverse=True`` (reverse KL): the expectation is over the student,+ i.e. ``KL(p_S || p_T)`` — mode-seeking.++ When ``conditional_only`` is ``True`` the binary mass term ``L_B`` and the+ Top-K mass weighting are dropped, so the loss only aligns the two+ distributions *renormalized within the Top-K set* (the tempered+ conditional KL alone).++ Gradients flow only through the student; the teacher is detached.++ Args:+ student_logits: Student logits, shape ``[batch, seq_len, vocab]``.+ teacher_logits: Teacher logits, shape ``[batch, seq_len, vocab]``.+ labels: Token-ID labels with ``-100`` for ignored positions,+ shape ``[batch, seq_len]``. Only used to mask out+ padding / ignored next-token positions.+ reverse: When ``True`` compute the reverse KL ``KL(p_S || p_T)``+ instead of the forward KL ``KL(p_T || p_S)``.+ conditional_only: When ``True`` only align the Top-K-normalized+ conditional distributions (drop ``L_B`` and the mass+ weighting).++ Returns:+ Scalar loss tensor (mean over valid next-token positions).+ """+ import torch.nn.functional as F++ top_k = int(self.lfq_top_k)+ tau = float(self.lfq_temperature)+ eps = 1e-6++ # Causal-LM shift: position t predicts token t+1.+ s = student_logits[..., :-1, :].contiguous()+ t = teacher_logits[..., :-1, :].contiguous()+ shift_labels = labels[..., 1:].contiguous()++ vocab = s.size(-1)+ s = s.reshape(-1, vocab).float()+ t = t.reshape(-1, vocab).float()+ mask = shift_labels.reshape(-1) != -100++ if mask.sum() == 0:+ # Keep the graph connected so backward() is a no-op but valid.+ return student_logits.float().sum() * 0.0++ s = s[mask]+ t = t[mask]+ top_k = min(top_k, vocab)++ log_pS = F.log_softmax(s, dim=-1)+ log_pT = F.log_softmax(t, dim=-1)++ # Teacher Top-K set per token (used for both forward and reverse KL).+ topk_idx = t.topk(top_k, dim=-1).indices # [N, k]+ log_pS_topk = log_pS.gather(-1, topk_idx) # [N, k]+ log_pT_topk = log_pT.gather(-1, topk_idx) # [N, k]++ # Total mass on the Top-K set (in log space for stability).+ log_PT_T = torch.logsumexp(log_pT_topk, dim=-1) # [N]+ log_PS_T = torch.logsumexp(log_pS_topk, dim=-1) # [N]++ # Select the expectation (E) and the "other" (O) distribution per KL+ # direction. Forward KL(p_T || p_S): E=teacher, O=student.+ # Reverse KL(p_S || p_T): E=student, O=teacher.+ if reverse:+ log_PE_T, log_PO_T = log_PS_T, log_PT_T+ log_pE_topk, log_pO_topk = log_pS_topk, log_pT_topk+ else:+ log_PE_T, log_PO_T = log_PT_T, log_PS_T+ log_pE_topk, log_pO_topk = log_pT_topk, log_pS_topk++ PE_T = log_PE_T.exp().clamp(min=eps, max=1.0 - eps)++ # Conditional distributions within the Top-K: log p(x|T) = log p(x) - log P(T).+ log_cE = log_pE_topk - log_PE_T.unsqueeze(-1) # [N, k]+ log_cO = log_pO_topk - log_PO_T.unsqueeze(-1) # [N, k]++ # Apply temperature tau: p^(tau)(x) = p(x)^(1/tau) / Z, computed in log space.+ log_cE_tau = log_cE / tau+ log_cE_tau = log_cE_tau - torch.logsumexp(log_cE_tau, dim=-1, keepdim=True)+ log_cO_tau = log_cO / tau+ log_cO_tau = log_cO_tau - torch.logsumexp(log_cO_tau, dim=-1, keepdim=True)++ # Tempered KL: D^(tau)_KL = tau^2 * KL( pE^(tau) || pO^(tau) ).+ kl_tau = (log_cE_tau.exp() * (log_cE_tau - log_cO_tau)).sum(dim=-1) # [N]++ if conditional_only:+ # Only align the Top-K-normalized conditional distributions; drop the+ # binary mass term L_B and the Top-K mass weighting.+ return ((tau * tau) * kl_tau).mean()++ # L_B: KL( Bern(P_E(T)) || Bern(P_O(T)) ).+ log_one_minus_PE = torch.log1p(-PE_T)+ log_one_minus_PO = torch.log1p(-log_PO_T.exp().clamp(min=eps, max=1.0 - eps))+ l_b = PE_T * (log_PE_T - log_PO_T) + (1.0 - PE_T) * (log_one_minus_PE - log_one_minus_PO)++ l_t = PE_T * (tau * tau) * kl_tau++ return (l_b + l_t).mean()diff --git a/auto_round/algorithms/quantization/sign_round/lfq_loss.py b/auto_round/algorithms/quantization/sign_round/lfq_loss.pydeleted file mode 100644index 3290f63c3..000000000--- a/auto_round/algorithms/quantization/sign_round/lfq_loss.py+++ /dev/null@@ -1,140 +0,0 @@-# Copyright (c) 2024-2025 Intel Corporation-#-# Licensed under the Apache License, Version 2.0 (the "License");-# you may not use this file except in compliance with the License.-# You may obtain a copy of the License at-#-# http://www.apache.org/licenses/LICENSE-2.0-#-# Unless required by applicable law or agreed to in writing, software-# distributed under the License is distributed on an "AS IS" BASIS,-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-# See the License for the specific language governing permissions and-# limitations under the License.--"""Memory-efficient soft cross-entropy for the LFQ (last-block) loss.--The LFQ objective (Eq. 3 of the paper) minimizes the cross-entropy between the-FP model's token distribution ``σ(X·W_FP·W_Head)`` and the quantized model's-distribution ``σ(X·W_q·W_Head)``. A naive implementation materializes two full-``[batch*seq, vocab]`` float32 tensors (softmax and log_softmax) plus the-autograd graph that produces them -- prohibitive for large-vocab models.--This module reproduces the essence of Unsloth's fused cross-entropy trick, but-for a *soft* target distribution instead of hard integer labels:--* logsumexp reformulation so ``log_softmax`` is never materialized::-- softCE_i = logsumexp(q_i) - Σ_j softmax(fp_i)_j · q_{i,j} (Σ_j p=1)--* analytic gradient (no autograd graph through softmax)::-- dL/dq_{i,j} = softmax(q_i)_j - softmax(fp_i)_j--* row chunking: only ``chunk_rows × vocab`` float32 elements are live at a time;- softmax is recomputed in the backward pass (compute-for-memory tradeoff).--Unlike Unsloth's Triton kernel this is pure PyTorch, so it runs on CPU / CUDA /-HPU without a Triton dependency.-"""--from __future__ import annotations--import torch--__all__ = ["DEFAULT_SOFT_CE_CHUNK_ELEMS", "soft_cross_entropy"]--# Target number of (rows × vocab) float32 elements processed per chunk.-# 2**23 ≈ 8.4M elems ≈ 32 MB per temporary fp32 tensor.-DEFAULT_SOFT_CE_CHUNK_ELEMS = 1 << 23---def _rows_per_chunk(vocab_size: int, chunk_elems: int) -> int:- return max(1, chunk_elems // max(1, vocab_size))---class _SoftCrossEntropy(torch.autograd.Function):- """Chunked soft cross-entropy with an analytic, memory-light backward."""-- @staticmethod- def forward(ctx, q_logits, fp_logits, valid_mask, chunk_elems):- # q_logits / fp_logits: [N, V]; valid_mask: [N] (float, 1.0 keep / 0.0 drop)- n_rows, vocab_size = q_logits.shape- rows = _rows_per_chunk(vocab_size, chunk_elems)-- denom = valid_mask.sum().clamp_min(1.0)- total = q_logits.new_zeros((), dtype=torch.float32)-- for start in range(0, n_rows, rows):- end = min(start + rows, n_rows)- m = valid_mask[start:end]- # No host-side ``if m.sum() == 0`` skip here: it would force a- # device-to-host sync on every chunk (dozens per forward for large- # vocabs). Invalid rows are already zeroed by multiplying with ``m``,- # and ``denom`` guards the all-invalid case, so the math stays correct.- q_c = q_logits[start:end].float()- lse_q = torch.logsumexp(q_c, dim=-1)- p_fp = torch.softmax(fp_logits[start:end].float(), dim=-1)- dot = (p_fp * q_c).sum(dim=-1)- ce = (lse_q - dot) * m- total = total + ce.sum()-- loss = total / denom-- ctx.save_for_backward(q_logits, fp_logits, valid_mask, denom)- ctx.chunk_elems = chunk_elems- return loss-- @staticmethod- def backward(ctx, grad_output):- q_logits, fp_logits, valid_mask, denom = ctx.saved_tensors- n_rows, vocab_size = q_logits.shape- rows = _rows_per_chunk(vocab_size, ctx.chunk_elems)-- # scale = dLoss / denom, broadcast per valid row.- scale = (grad_output / denom).to(torch.float32)- dq = torch.empty_like(q_logits)-- for start in range(0, n_rows, rows):- end = min(start + rows, n_rows)- m = valid_mask[start:end].unsqueeze(-1)- # dL/dq = softmax(q) - softmax(fp), recomputed to avoid storing it.- grad = torch.softmax(q_logits[start:end].float(), dim=-1)- grad -= torch.softmax(fp_logits[start:end].float(), dim=-1)- grad *= m * scale- dq[start:end] = grad.to(dq.dtype)-- return dq, None, None, None---def soft_cross_entropy(- q_logits: torch.Tensor,- fp_logits: torch.Tensor,- valid_mask: torch.Tensor = None,- chunk_elems: int = DEFAULT_SOFT_CE_CHUNK_ELEMS,-) -> torch.Tensor:- """Mean soft cross-entropy ``-Σ_j σ(fp)_j log σ(q)_j`` over valid positions.-- Gradients flow only through ``q_logits``; ``fp_logits`` is treated as a- detached soft target.-- Args:- q_logits: Quantized logits, shape ``[..., vocab]``.- fp_logits: FP logits (soft target), same shape as ``q_logits``.- valid_mask: Optional boolean/0-1 mask over positions (all leading dims- except vocab). Positions with 0 are excluded from the loss.- chunk_elems: Target ``rows × vocab`` float32 elements per chunk.-- Returns:- Scalar loss tensor.- """- vocab_size = q_logits.shape[-1]- q2d = q_logits.reshape(-1, vocab_size)- fp2d = fp_logits.reshape(-1, vocab_size).detach()-- if valid_mask is None:- mask = q2d.new_ones(q2d.shape[0], dtype=torch.float32)- else:- mask = valid_mask.reshape(-1).to(device=q2d.device, dtype=torch.float32)-- return _SoftCrossEntropy.apply(q2d, fp2d, mask, chunk_elems)diff --git a/auto_round/algorithms/quantization/sign_round/quantizer.py b/auto_round/algorithms/quantization/sign_round/quantizer.pyindex a04fc13c2..d2a3a8070 100644--- a/auto_round/algorithms/quantization/sign_round/quantizer.py+++ b/auto_round/algorithms/quantization/sign_round/quantizer.py@@ -23,6 +23,7 @@ from torch import autocastfrom auto_round.algorithms.block_runner import BlockForwardRunnerfrom auto_round.algorithms.quantization.base import BaseQuantizerfrom auto_round.algorithms.quantization.sign_round.config import SignRoundConfig+from auto_round.algorithms.quantization.sign_round.lfq import LFQMixinfrom auto_round.algorithms.quantization.sign_round.sign_sgd import SignSGDfrom auto_round.algorithms.registry import register_pipeline_memberfrom auto_round.compressors.utils import (@@ -95,14 +96,15 @@ from auto_round.utils import (from auto_round.utils.device import clear_memory_if_reached_thresholdfrom auto_round.utils.device_manager import device_managerfrom auto_round.utils.distributed import setup_ddp_if_needed_-from auto_round.wrapper import WrapperLinear, unwrapper_block, unwrapper_layer, wrapper_block--if TYPE_CHECKING:- from auto_round.algorithms.composer import BlockContext+from auto_round.wrapper import (+ WrapperLinear,+ unwrapper_layer,+ wrapper_block,+)@register_pipeline_member(SignRoundConfig)-class SignRoundQuantizer(BaseQuantizer):+class SignRoundQuantizer(LFQMixin, BaseQuantizer):def __init__(self, config: SignRoundConfig) -> None:super().__init__(config)@@ -120,6 +122,12 @@ class SignRoundQuantizer(BaseQuantizer):self.enable_quanted_input = config.enable_quanted_inputself.dynamic_max_gap = config.dynamic_max_gapself.enable_lfq = config.enable_lfq+ self.lfq_loss_type = getattr(config, "lfq_loss", "ce")+ self.lfq_top_k = getattr(config, "lfq_top_k", 32)+ self.lfq_temperature = getattr(config, "lfq_temperature", 1.0)+ self.lfq_num_blocks = getattr(config, "lfq_num_blocks", 1)+ self.lfq_mse_weight = getattr(config, "lfq_mse_weight", 0.0)+ self.enable_qad = getattr(config, "enable_qad", False)self.optimizer = self._get_optimizer(optimizer=config.optimizer)self.wrapper_block = wrapper_block@@ -230,180 +238,6 @@ class SignRoundQuantizer(BaseQuantizer):else:return inputs.shape[self.calibration_context.batch_dim]- def _init_lm_components(self) -> None:- """Lazily locate and cache ``_post_block_modules`` and ``_lm_head`` for LFQ loss.-- ``_post_block_modules`` is an ordered list of modules that must be applied- between the last transformer-block output and the lm_head projection.- Most architectures have a single final norm; OPT additionally has an- optional ``project_out`` projection.-- Supported without manual configuration:- LLaMA / Qwen / Gemma / Mistral / InternLM / Phi-3 — ``model.model.norm``- OPT — ``model.model.decoder.{final_layer_norm, project_out}`` (both optional)- GPT-2 / Falcon / Bloom — ``model.transformer.ln_f``- GPT-NeoX / Pythia — ``model.gpt_neox.final_layer_norm``- Phi / Phi-2 — ``model.model.final_layernorm``- MPT — ``model.transformer.norm_f``- ChatGLM — ``model.transformer.encoder.final_layernorm``- RWKV — ``model.rwkv.ln_out``-- Raises ``AttributeError`` if no lm_head equivalent can be found.- """- if hasattr(self, "_lm_head"):- return-- model = self.model-- # ── lm_head ──────────────────────────────────────────────────────────- for name in ("lm_head", "embed_out", "output", "head"):- if hasattr(model, name):- self._lm_head = getattr(model, name)- break- else:- raise AttributeError(- f"Cannot locate lm_head in {type(model).__name__}. " "Checked: lm_head, embed_out, output, head."- )-- # ── post-block processing (ordered list applied before lm_head) ───────- # OPT: decoder has both an optional final_layer_norm *and* an optional- # project_out that maps ffn_dim → word_embed_proj_dim. Detect by probing- # for the characteristic project_out attribute (may be None).- try:- decoder = model.model.decoder- _ = decoder.project_out # raises AttributeError if not an OPT decoder- self._post_block_modules = [m for m in (decoder.final_layer_norm, decoder.project_out) if m is not None]- return- except AttributeError:- pass-- # All other architectures: single optional final norm.- norm_getters = [- lambda: model.model.norm, # LLaMA / Qwen / Gemma / Mistral / InternLM / Phi-3- lambda: model.transformer.ln_f, # GPT-2 / Falcon / Bloom- lambda: model.gpt_neox.final_layer_norm, # GPT-NeoX / Pythia- lambda: model.model.final_layernorm, # Phi / Phi-2- lambda: model.transformer.norm_f, # MPT- lambda: model.transformer.encoder.final_layernorm, # ChatGLM- lambda: model.rwkv.ln_out, # RWKV- ]- self._post_block_modules = []- for getter in norm_getters:- try:- norm = getter()- if norm is not None:- self._post_block_modules = [norm]- break- except AttributeError:- continue-- # Keywords that identify non-text (visual / audio / multimodal) blocks.- # LFQ loss is only meaningful for pure language-model decoder blocks.- _NON_TEXT_BLOCK_KEYWORDS = frozenset(- {- "vis",- "vision",- "visual",- "image",- "img",- "audio",- "video",- "patch",- "pixel",- "clip",- "vit",- "perceiver",- "resampler",- "connector",- "projector",- }- )-- def _is_text_decoder_block(self, block_name: str) -> bool:- """Return ``True`` if *block_name* refers to a text-decoder block.-- Blocks whose names contain any of the non-text keywords (vision, audio,- image, …) are considered multimodal and excluded from LFQ loss.- """- name_lower = block_name.lower()- return not any(kw in name_lower for kw in self._NON_TEXT_BLOCK_KEYWORDS)-- def lfq_loss(- self,- q_hidden_state: torch.Tensor,- fp_hidden_state: torch.Tensor,- input_ids: torch.Tensor = None,- ) -> torch.Tensor:- """Compute the LFQ loss between the FP and quantized token distributions.-- Implements Eq. 3 of the LFQ paper: the cross-entropy between the FP- model's logit distribution and the quantized model's logit distribution,-- L_CE = -(1/L) Σ_{i,j} σ(X·W_FP·W_Head)_{i,j} · log σ(X·W_q·W_Head)_{i,j}-- where ``σ`` is the softmax over the vocabulary dimension. Both logits are- obtained by applying every post-block module (final norm, optional- projection, …) in order followed by ``lm_head``. The FP distribution is- the (detached) soft target; gradients flow only through the quantized- branch. This is a distribution-matching objective, *not* a hard-label- next-token cross-entropy.-- Args:- q_hidden_state: Quantized last-block output ``X·W_q``, shape- ``[batch, seq_len, hidden]``.- fp_hidden_state: FP last-block output ``X·W_FP`` used to build the- soft target distribution, same shape as above.- input_ids: Optional token-ID labels with ``-100`` for ignored- (e.g. padding) positions, shape ``[batch, seq_len]``.- When provided, those positions are excluded from the- loss; token values themselves are not used as targets.-- Returns:- Scalar LFQ loss tensor.- """- from .lfq_loss import soft_cross_entropy-- self._init_lm_components()- device = q_hidden_state.device-- for module in self._post_block_modules:- module.to(device)- self._lm_head.to(device)-- def _to_logits(hidden: torch.Tensor) -> torch.Tensor:- for module in self._post_block_modules:- hidden = module(hidden)- return self._lm_head(hidden)-- # FP logits form the (detached) soft target distribution σ(X·W_FP·W_Head).- with torch.no_grad():- fp_logits = _to_logits(fp_hidden_state.to(device))-- # Quantized logits: gradients flow through this branch only.- q_logits = _to_logits(q_hidden_state)-- # Position mask for the soft-CE objective.- #- # IMPORTANT: this is a *deliberate same-position* mask — no next-token- # shift is applied. LFQ (Eq. 3) matches the FP and quantized output- # distributions σ(X·W_FP·W_Head) vs σ(X·W_q·W_Head) at each position; it- # is a per-position distillation objective, not next-token prediction,- # so logits and the target distribution are aligned position-for-position- # (unlike the legacy hard-label CE path that used shift_logits/labels).- #- # ``input_ids`` already carries the calibrator's -100 ignore markers- # (pad tokens, trailing repeated tokens, and the last position of each- # sample). Those positions are simply dropped here; the token *values*- # are never used as targets.- valid_mask = None- if input_ids is not None:- valid_mask = input_ids.to(device) != -100-- # Memory-efficient soft cross-entropy (Unsloth-style logsumexp + analytic- # gradient + row chunking): never materializes a full float32 log_softmax- # tensor nor an autograd graph through softmax.- return soft_cross_entropy(q_logits, fp_logits, valid_mask)-def _resolve_tuning_cache_plan(self,*,@@ -493,7 +327,8 @@ class SignRoundQuantizer(BaseQuantizer):Returns:dict: Best quantization parameters found during optimization, or an- empty dict if no trainable parameters were found.+ empty dict if no trainable parameters were found. Wrappers stay+ installed for the composer to finalize and collect outputs."""device = device_manager.device# None coalesces to the primary: an explicit None from the placement pass@@ -565,7 +400,6 @@ class SignRoundQuantizer(BaseQuantizer):f"layers in the block")logger.info(dump_info)- unwrapper_block(block, {})return {}# Build optimizer param groups with a per-layer lr for the rounding@@ -646,6 +480,29 @@ class SignRoundQuantizer(BaseQuantizer):)use_prefetch_cache = cache_cls is not None+ # LFQ with lfq_num_blocks > 1: a non-final KD block's output must pass+ # through the remaining (FP) blocks before reaching the final norm/lm_head.+ lfq_downstream_blocks = []+ lfq_teacher_final = None+ if (+ input_ids is not None+ and isinstance(fp_outputs, list)+ and isinstance(active_inputs, list)+ and self._lfq_is_kd_block(block_ctx)+ ):+ lfq_downstream_blocks = self._get_lfq_downstream_blocks(block_ctx, device)+ if lfq_downstream_blocks and self.lfq_loss_type in ("dtk", "rkl", "tk"):+ # The teacher path is fixed across iterations: precompute it once.+ lfq_teacher_final = []+ with torch.no_grad():+ for s in range(0, nsamples, batch_size):+ idx = list(range(s, min(s + batch_size, nsamples)))+ ref = torch.cat([fp_outputs[j] for j in idx], dim=0)+ out = self._forward_lfq_downstream(+ ref, lfq_downstream_blocks, active_inputs, input_others, idx, device+ )+ lfq_teacher_final.extend(o.to(fp_outputs[0].device) for o in torch.split(out, 1, dim=0))+_perf.stop("prepare")_perf.start("loop")# iters>0 hot-pool strategy (loop-amortized; the iters=0 lane streams@@ -710,6 +567,19 @@ class SignRoundQuantizer(BaseQuantizer):num_elm = self._get_non_zero_cnt(valid_token_mask, global_indices)_perf.stop("sampler")+ # Per-block loss schedule (constant across batches/iters):+ # lfq_kd_block -> apply the KD logit-lens loss on this block+ # lfq_mse_block -> add the MSE reconstruction loss on this block+ # QAD: every fused group is tuned against the final-output LM loss only+ # (no MSE); with the whole network fused this is the true final logits.+ # Non-QAD: KD on the last `lfq_num_blocks`, MSE elsewhere (and on KD+ # blocks only when `lfq_mse_weight` > 0).+ lfq_kd_block = input_ids is not None and self._lfq_is_kd_block(block_ctx)+ if self.enable_qad:+ lfq_mse_block = False+ else:+ lfq_mse_block = (not lfq_kd_block) or self.lfq_mse_weight > 0+for batch_start in range(0, len(global_indices), batch_size):indices = global_indices[batch_start : batch_start + batch_size]_perf.start("s_fwd")@@ -733,17 +603,34 @@ class SignRoundQuantizer(BaseQuantizer):pred_output = pred_output.to(loss_device)_perf.stop("s_fwd")_perf.start("s_loss")- if (- block_ctx.block_index == block_ctx.block_cnt - 1- and self.enable_lfq- and input_ids is not None- and self._is_text_decoder_block(block_ctx.block_name)- ):+ if lfq_kd_block:+ # For KD losses ("dtk"/"rkl"/"tk"), ref_output (FP block output) is the teacher.+ teacher_output = ref_output if self.lfq_loss_type in ("dtk", "rkl", "tk") else None+ lfq_student = pred_output+ if lfq_downstream_blocks:+ lfq_student = self._forward_lfq_downstream(+ pred_output, lfq_downstream_blocks, active_inputs, input_others, indices, device+ )+ if lfq_teacher_final is not None:+ teacher_output = torch.cat([lfq_teacher_final[j] for j in indices], dim=0).to(+ lfq_student.device+ )loss = self.lfq_loss(- pred_output,- ref_output,+ lfq_student,torch.cat([input_ids[i] for i in indices], dim=0),+ teacher_hidden_state=teacher_output,+ sample_indices=indices,)+ # Optionally combine with the MSE block-reconstruction loss so the+ # block keeps its reconstruction fidelity while adding logit alignment.+ if lfq_mse_block:+ mse_term = self._get_loss(+ pred_output, ref_output, indices, mse_loss, device, valid_token_mask+ )+ # In QAD a scheduled MSE checkpoint defaults to weight 1.0; outside+ # QAD the explicit `lfq_mse_weight` controls the combination.+ mse_w = self.lfq_mse_weight if self.lfq_mse_weight > 0 else 1.0+ loss = loss + mse_w * mse_termelse:# the mask must land on the same device pred/ref were staged# on (loss_device, which card-0-risk relocation may move off@@ -799,6 +686,10 @@ class SignRoundQuantizer(BaseQuantizer):finally:if tuning_cache is not None:tuning_cache.close()+ for m in lfq_downstream_blocks:+ mv_module_from_gpu(m)+ del lfq_teacher_final+_perf.stop("loop")_perf.start("tail")@@ -821,8 +712,6 @@ class SignRoundQuantizer(BaseQuantizer):self.compress_context.clear_memory() # clear cached memory during trainingif len(unquantized_layer_names) != 0:logger.info(f"Unquantized layers: {unquantized_layer_names}")- with torch.no_grad():- unwrapper_block(block, best_params)_perf.stop("tail")_log_tune_phases(_perf, self.iters)diff --git a/auto_round/algorithms/quantization/sign_roundv2/quantizer.py b/auto_round/algorithms/quantization/sign_roundv2/quantizer.pyindex afffc8dd3..c833a6542 100644--- a/auto_round/algorithms/quantization/sign_roundv2/quantizer.py+++ b/auto_round/algorithms/quantization/sign_roundv2/quantizer.py@@ -12,6 +12,7 @@# See the License for the specific language governing permissions and# limitations under the License.+import mathfrom collections.abc import Callablefrom contextlib import nullcontextfrom functools import partial@@ -27,6 +28,7 @@ from auto_round.algorithms.quantization.sign_round.quantizer import SignRoundQuaif TYPE_CHECKING:from auto_round.algorithms.composer import AlgorithmComposer+from auto_round import envsfrom auto_round.algorithms.registry import register_pipeline_memberfrom auto_round.data_type.gguf import (double_quant_tensor_sym_rtn,@@ -41,7 +43,6 @@ 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,@@ -103,7 +104,7 @@ def _dq_asym_group_size(bits: int) -> int:class SignRoundOptimizedWrapperLinear(WrapperLinear):- minmax_scale_bound = (0.0, 2.0)+ minmax_scale_bound = (0.1, 10.0) # TODO widened from 2.0 for low-bit QAD; verify correctness# Opt-in protocol for wrapper_block: the init-scale search is weight-local# and row-independent, so same-shape modules can be searched as one stacked# batch (bit-identical per module, far fewer python/launch round-trips).@@ -112,11 +113,44 @@ class SignRoundOptimizedWrapperLinear(WrapperLinear):def _init_tuning_params_and_quant_func(self, defer_search: bool = False) -> None:super()._init_tuning_params_and_quant_func(defer_search=defer_search)+ # Log/geometric min-max tuning (opt-in): re-anchor the tunable min/max+ # scale coefficients to log space so each SignSGD step is a symmetric+ # multiplicative move. Only engages when the coefficients are actually+ # trainable (``nn.Parameter``); constant/frozen coefficients keep the+ # plain linear path (a constant 1.0 must not be passed through exp()).+ self._use_log_minmax = False+ _min_tunable = isinstance(getattr(self, "min_scale", None), torch.nn.Parameter)+ _max_tunable = isinstance(getattr(self, "max_scale", None), torch.nn.Parameter)+ if envs.AR_ENABLE_LOG_MINMAX and _min_tunable and _max_tunable:+ self._use_log_minmax = True+ warm_start = getattr(self.orig_layer, "_ar_warm_start", None) or {}+ saved_log = warm_start.get("minmax_parameterization") == "log"+ with torch.no_grad():+ for key in ("min_scale", "max_scale"):+ param = getattr(self, key)+ if not isinstance(param, torch.nn.Parameter):+ continue+ saved = warm_start.get(key)+ compatible = saved is not None and saved.shape == param.shape+ if self._use_log_minmax:+ if not compatible:+ # theta = 0 <-> coeff = exp(0) = 1.0+ param.zero_()+ elif not saved_log:+ param.clamp_min_(torch.finfo(param.dtype).tiny).log_()+ elif compatible and saved_log:+ param.exp_()+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_type++ # Warm-start reuse: a prior pass (SignRound -> QAD chaining) may have+ # stashed the searched ``init_scale`` on this layer. Reuse it verbatim so+ # the second pass tunes on the exact same scale grid (re-searching here+ # would differ because the imatrix was consumed/deleted in the first pass).+ warm_start = getattr(layer, "_ar_warm_start", None)+ warm_init_scale = warm_start.get("init_scale") if warm_start else None+weight_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@@ -126,20 +160,19 @@ 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)- 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)+ 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 or an asymmetric int type."+ "expected a symmetric int / mx / nv type.")self.data_type = data_typeself.init_scale = None- self.init_zp = Noneself._deferred_search_inputs = None- if defer_search:+ if warm_init_scale is not None:+ # Warm-started from a prior pass: reuse the exact scale, skip any search.+ self.init_scale = warm_init_scale.to(self.device)+ elif defer_search:# staged for run_batched_wrap_search: the exact callable the# per-module path would invoke travels with the moduleself._deferred_search_inputs = (@@ -151,40 +184,52 @@ class SignRoundOptimizedWrapperLinear(WrapperLinear):search_fn,)else:- self._assign_search_result(search_fn(weight_reshape, layer.bits, imatrix))+ self.init_scale = 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 _prepare_minmax_scale(self, min_scale, max_scale):+ """Return the multiplicative coefficients the quant func consumes.- 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 {}+ In log mode the stored parameters are ``theta`` (SignSGD tunes them with+ symmetric fixed steps); clamp them to the symmetric log bound and return+ ``exp(theta)`` so the quant function still receives plain multiplicative+ coefficients, while ``+lr``/``-lr`` steps become ``xe^lr``/``/e^lr``.+ Gradients flow back through ``exp`` to the ``theta`` parameters.+ """+ if not getattr(self, "_use_log_minmax", False):+ return super()._prepare_minmax_scale(min_scale, max_scale)+ # The shared ``minmax_scale_bound`` is defined in Euclidean (coefficient)+ # space; convert it to the log/theta clamp range here so both the linear+ # and log paths read from one bound. ``log`` is undefined at <= 0, so when+ # the linear bound starts at 0 fall back to a multiplicatively symmetric+ # lower end (the reciprocal of the upper coefficient), keeping shrink/expand+ # equidistant from the identity.+ coeff_low, coeff_high = self.minmax_scale_bound+ if coeff_low <= 0.0:+ coeff_low = 1.0 / coeff_high+ low, high = math.log(coeff_low), math.log(coeff_high)+ min_scale.data.clamp_(low, high)+ max_scale.data.clamp_(low, high)+ return torch.exp(min_scale), torch.exp(max_scale)def _run_deferred_search_now(self) -> None:"""Run the staged search per-module (fallback when batching is off)."""+ # Warm-started wrappers (QAD chaining) resolve ``init_scale`` directly and+ # stage no search inputs; there is nothing to run for them.+ if self._deferred_search_inputs is None:+ returnweight, _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._assign_search_result(search_fn(weight, bits, imatrix))+ self.init_scale = 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.-- 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)+ """Adopt a search result computed on a stacked same-shape batch."""+ self.init_scale = init_scaleself._deferred_search_inputs = Nonedef _prepare_init_scale_weight(self) -> torch.Tensor:@@ -222,6 +267,66 @@ class SignRoundOptimizedWrapperLinear(WrapperLinear):return weight_reshape+class SignRoundOptimizedAsymWrapperLinear(SignRoundOptimizedWrapperLinear):+ """Algorithm-extension wrapper for asymmetric INT weights.++ The plain asym path seeds the grid from the raw per-group min/max+ (``scale=(max-min)/maxq``, ``zp=round(-min/scale)``), which at low bit-widths+ is a poor init: the step is too coarse for bell-shaped groups and the integer+ zero-point rounding clips one side. This wrapper instead anchors the grid to an+ imatrix-weighted joint ``(scale, zp)`` search (NeUQI), expressed as per-group+ ``(tensor_min, tensor_max)`` margins that ``quant_tensor_asym`` reproduces+ exactly, and -- unlike ``--enable_neuqi`` on the plain path -- keeps+ ``min_scale``/``max_scale`` tunable around that anchor (both shrink and expand).+ """++ minmax_scale_bound = (0.5, 1.5)+ # The asymmetric anchor search runs inline and does not stage init-scale inputs.+ supports_batched_search = False++ def _init_tuning_params_and_quant_func(self, defer_search: bool = False):+ layer = self.orig_layer+ # Let the anchor below own the NeUQI search: disable the base wrapper's+ # frozen-margin NeUQI branch so margins stay tunable and the search runs once.+ enable_neuqi = self.enable_neuqi+ self.enable_neuqi = False+ try:+ WrapperLinear._init_tuning_params_and_quant_func(self, defer_search=defer_search)+ finally:+ self.enable_neuqi = enable_neuqi+ self.init_scale = None+ self._asym_anchor = False++ if self.weight_min is None or layer.bits >= 16 or isinstance(layer.group_size, tuple):+ return++ warm_start = getattr(layer, "_ar_warm_start", None)+ if warm_start and warm_start.get("anchor_min") is not None and warm_start.get("anchor_max") is not None:+ wmin = warm_start["anchor_min"].to(self.device, torch.float32)+ wmax = warm_start["anchor_max"].to(self.device, torch.float32)+ else:+ from auto_round.data_type.neuqi import neuqi_anchor_margins++ weight_reshape = self._prepare_init_scale_weight()+ wmin, wmax = neuqi_anchor_margins(+ weight_reshape,+ layer.bits,+ layer.group_size,+ getattr(layer, "imatrix", None),+ self.device,+ sym=False,+ )+ if wmin.numel() != self.weight_min.numel() or wmax.numel() != self.weight_max.numel():+ logger.warning_once("SignRoundV2 asym: anchor shape mismatch, falling back to min/max init.")+ return+ # Keep the anchor in fp32 so quant_tensor_asym re-derives the searched zp exactly.+ self.weight_min = wmin.reshape(self.weight_min.shape).to(self.device, torch.float32)+ self.weight_max = wmax.reshape(self.weight_max.shape).to(self.device, torch.float32)+ self._asym_anchor = True+ if hasattr(layer, "imatrix"):+ del layer.imatrix++class SignRoundDQWrapperLinear(WrapperLinear):minmax_scale_bound = (0.5, 1.5)@@ -395,34 +500,42 @@ class SignRoundV2Quantizer(SignRoundQuantizer):super().prepare_run(composer=composer)if (- self.scheme.super_group_size is None+ self.scheme.sym+ and 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 = Trueelse:self._use_outlier_suppressed_loss = Falseself.wrapper_block = _named_wrapper_block(SignRoundOptimizedWrapperLinear, "wrapper_block")+ elif (+ not self.scheme.sym+ and self.scheme.super_group_size is None+ and self.scheme.data_type == "int"+ and self.scheme.bits < 16+ ):+ # Asym INT: searched (scale, zp) anchor + tunable margins, and the same+ # outlier-suppressed block loss the sym path uses at low bits.+ self._use_outlier_suppressed_loss = self.scheme.act_bits <= 4 or self.scheme.bits < 4+ self.wrapper_block = _named_wrapper_block(SignRoundOptimizedAsymWrapperLinear, "wrapper_block")if self.scheme.data_type.endswith("dq"):self.wrapper_block = _named_wrapper_block(SignRoundDQWrapperLinear, "dq_wrapper_block")def can_compile_block_forward(self):- # torch.compile on the whole block forward is only reliable on torch >= 2.14+ # torch.compile on the whole block forward is only reliable on torch >= 2.13from packaging.version import Versionreturn Version(torch.__version__.split("+")[0]) >= Version("2.13")diff --git a/auto_round/algorithms/registry.py b/auto_round/algorithms/registry.pyindex c96b3db03..2e39a3f4b 100644--- a/auto_round/algorithms/registry.py+++ b/auto_round/algorithms/registry.py@@ -5,6 +5,8 @@ from __future__ import annotationsimport copyimport importlib+import importlib.util+import pkgutilfrom collections.abc import Callablefrom dataclasses import dataclass, fieldfrom typing import TYPE_CHECKING@@ -38,6 +40,8 @@ def _ensure_builtin_algorithms_registered() -> None:for module_name in ("auto_round.algorithms.quantization.rtn.config","auto_round.algorithms.quantization.sign_round.config",+ "auto_round.algorithms.quantization.qad.config",+ "auto_round.algorithms.quantization.qat.config","auto_round.algorithms.transforms.awq.config","auto_round.algorithms.transforms.svdquant.config","auto_round.algorithms.transforms.hadamard.config",@@ -45,6 +49,15 @@ def _ensure_builtin_algorithms_registered() -> None:):importlib.import_module(module_name)+ # Optional quantizers own their registration and CLI parameters. Removing+ # an experimental package must not require changes to the shared registry.+ package = importlib.import_module("auto_round.algorithms.quantization")+ for module in pkgutil.iter_modules(package.__path__, package.__name__ + "."):+ if module.ispkg:+ config_module = module.name + ".config"+ if importlib.util.find_spec(config_module) is not None:+ importlib.import_module(config_module)+_builtin_algorithms_registered = True@@ -56,6 +69,8 @@ def _ensure_pipeline_members_registered() -> None:"auto_round.algorithms.quantization.rtn.quantizer","auto_round.algorithms.quantization.sign_round.quantizer","auto_round.algorithms.quantization.sign_roundv2.quantizer",+ "auto_round.algorithms.quantization.qad.quantizer",+ "auto_round.algorithms.quantization.qat.quantizer","auto_round.algorithms.quantization.adam_round.adam","auto_round.algorithms.transforms.awq.base","auto_round.algorithms.transforms.svdquant.apply",@@ -183,6 +198,21 @@ def resolve_pipeline_member(config: object) -> type[BaseAlgorithm]:raise ValueError(f"Unknown algorithm config type {config_cls.__name__!r}.")+def pipeline_member_for_config_class(config_cls: type):+ """Return the pipeline member class for a config *class* (or ``None``).++ Class-level counterpart of :func:`resolve_pipeline_member` (which needs an+ instance). Used by the CLI to tell whether an algorithm is a terminal block+ quantizer without constructing its config.+ """+ _ensure_pipeline_members_registered()+ for cls in config_cls.__mro__:+ member_cls = _CONFIG_IMPL_REGISTRY.get(cls)+ if member_cls is not None:+ return member_cls+ return None++def coerce_config_class(config: object, target_cls: type) -> object:if type(config) is target_cls:return config@@ -196,9 +226,21 @@ def coerce_config_class(config: object, target_cls: type) -> object:def normalize_algorithm_config(config: object) -> object:+ from auto_round.algorithms.quantization.qad.config import QADConfigfrom auto_round.algorithms.quantization.rtn.config import OptimizedRTNConfig, RTNConfigfrom auto_round.algorithms.quantization.sign_round.config import AdamRoundConfig, SignRoundConfig, SignRoundV2Config+ if type(config) in (SignRoundConfig, SignRoundV2Config, AdamRoundConfig) and getattr(config, "enable_qad", False):+ defaults = QADConfig(+ topk=getattr(config, "lfq_top_k", 32),+ qad_optimizer="adamw" if getattr(config, "enable_adam", False) else getattr(config, "optimizer", None),+ )+ normalized = coerce_config_class(config, QADConfig)+ for key, value in vars(defaults).items():+ if not hasattr(normalized, key):+ setattr(normalized, key, value)+ normalized.optimizer = defaults.optimizer+ return normalizedif type(config) is OptimizedRTNConfig and getattr(config, "disable_opt_rtn", False):return coerce_config_class(config, RTNConfig)if type(config) is RTNConfig and not getattr(config, "disable_opt_rtn", False):diff --git a/auto_round/autoround.py b/auto_round/autoround.pyindex 099c0e8ef..457e16453 100644--- a/auto_round/autoround.py+++ b/auto_round/autoround.py@@ -85,13 +85,10 @@ def _resolve_quant_config_for_routing(alg_configs) -> tuple[list, list, Quantizafrom auto_round.algorithms.quantization.rtn.config import RTNConfig as _RTNConfigreturn preprocessor_configs, block_quant_configs, _RTNConfig()- if len(block_quant_configs) > 1:- raise ValueError(- f"Only one block-quantization config is allowed, but got {len(block_quant_configs)}: "- f"{[type(c).__name__ for c in block_quant_configs]}"- )- if len(block_quant_configs) == 1:- return preprocessor_configs, block_quant_configs, block_quant_configs[0]+ if block_quant_configs:+ # Stage ordering belongs to the composer. The last quantizer drives+ # public scheme/format resolution, independently of algorithm identity.+ return preprocessor_configs, block_quant_configs, block_quant_configs[-1]raise ValueError("At least one quantization algorithm config is required. ""Pass a block quantizer such as RTNConfig or SignRoundConfig, "@@ -620,7 +617,7 @@ class _CompressorBuilder:else:alg_configs = normalize_algorithm_config(alg_configs)configs_for_routing = alg_configs if isinstance(alg_configs, list) else [alg_configs]- preprocessor_configs, _, quant_config = _resolve_quant_config_for_routing(configs_for_routing)+ preprocessor_configs, quantizer_configs, quant_config = _resolve_quant_config_for_routing(configs_for_routing)is_svdquant = any(type(config).__name__ == "SVDQuantConfig" for config in preprocessor_configs)if is_svdquant and "svdquant_omni" not in {name.strip().lower() for name in (format or "").split(",")}:format = "svdquant_nunchaku"@@ -647,6 +644,10 @@ class _CompressorBuilder:# route predicate; otherwise the fast path silently drops them and# cannot emit the required export metadata.route_decision_kwargs = dict(base_kwargs, **route_kwargs, format=format)+ if len(quantizer_configs) > 1:+ if route_kwargs.get("model_free", False):+ raise ValueError("model_free=True is not supported with multiple quantizer stages.")+ route_decision_kwargs["disable_model_free"] = Trueis_svdquant_rtn = type(quant_config) is RTNConfig and is_svdquantif is_svdquant_rtn and not route_kwargs.get("model_free", False):# SVDQuant must run before plain RTN on the regular blockwise path.@@ -723,7 +724,7 @@ class _CompressorBuilder:# block_forward_hooks -> pre_quantize_block -> post_quantize_block)# actually runs; the pipeline auto-appends RTN when no block_quantizer# is supplied. SignRound is itself data-driven and shares the same host.- if preprocessor_configs or isinstance(quant_config, SignRoundConfig):+ if preprocessor_configs or len(quantizer_configs) > 1 or not isinstance(quant_config, RTNConfig):return _get_compressor_class(model_type, Compressor)(alg_configs, **local_args, **ctor_kwargs)elif isinstance(quant_config, RTNConfig):base_cls = _select_rtn_compressor_base_cls(quant_config, scheme, format, base_kwargs)diff --git a/auto_round/calibration/llm.py b/auto_round/calibration/llm.pyindex 41ed11322..4e9c60b6e 100644--- a/auto_round/calibration/llm.py+++ b/auto_round/calibration/llm.py@@ -281,6 +281,119 @@ class LLMCalibrator(Calibrator):hook_handle.remove()self.hook_handles = []+ def _mask_ids_for_loss(self, input_ids: torch.Tensor, attention_mask=None) -> torch.Tensor:+ """Return a copy of ``input_ids`` with loss-ignored positions set to ``-100``.++ Only padding is ignored. Causal losses shift these labels themselves,+ so the final non-padding token must remain a supervision target.+ """+ ids_to_cache = input_ids.clone()+ if ids_to_cache.dim() == 1:+ ids_to_cache = ids_to_cache.unsqueeze(0)+ if attention_mask is not None:+ ids_to_cache.masked_fill_(attention_mask.to(ids_to_cache.device) == 0, -100)+ elif self.tokenizer is not None and getattr(self.tokenizer, "pad_token_id", None) is not None:+ # With a shared PAD/EOS id only an explicit mask can distinguish+ # padding from real separators or the final EOS target.+ if self.tokenizer.pad_token_id != getattr(self.tokenizer, "eos_token_id", None):+ ids_to_cache[ids_to_cache == self.tokenizer.pad_token_id] = -100+ else:+ # Heuristic: trailing repeated tokens are treated as padding.+ for b in range(ids_to_cache.shape[0]):+ last_token = ids_to_cache[b, -1].item()+ j = ids_to_cache.shape[1] - 2+ while j >= 0 and input_ids.reshape(ids_to_cache.shape)[b, j] == last_token:+ ids_to_cache[b, j + 1] = -100+ j -= 1+ return ids_to_cache++ def _model_input_samples(self, input_ids, attention_mask=None):+ """Keep forward inputs separate from labels, including internal EOS tokens."""+ input_ids = input_ids.detach().to("cpu", copy=True)+ if input_ids.dim() == 1:+ input_ids = input_ids.unsqueeze(0)+ if attention_mask is None:+ attention_mask = torch.ones_like(input_ids)+ pad = getattr(self.tokenizer, "pad_token_id", None)+ eos = getattr(self.tokenizer, "eos_token_id", None)+ if pad is not None and pad != eos:+ attention_mask = (input_ids != pad).long()+ else:+ attention_mask = attention_mask.detach().to("cpu", copy=True).reshape(input_ids.shape)+ labels = self._mask_ids_for_loss(input_ids, attention_mask)+ return [+ {"input_ids": ids, "attention_mask": mask, "labels": target}+ for ids, mask, target in zip(input_ids.split(1), attention_mask.split(1), labels.split(1))+ ]++ @torch.no_grad()+ def collect_token_ids(self, nsamples: int, *, include_model_inputs=False) -> list:+ """Collect ``nsamples`` raw calibration token-id samples WITHOUT running the model.++ Used by whole-model algorithms (e.g. QAD) that only need token ids and+ may want a different sample count than the block-wise calibration+ (e.g. ``sign_round,qad`` with ``qad_nsamples != nsamples``). The ids are+ masked with ``-100`` exactly like the ``input_ids`` cached by :meth:`calib`.+ With ``include_model_inputs=True``, return original ``input_ids``,+ ``attention_mask`` and separate ``labels`` for whole-model forwards.+ """+ from auto_round.calib_dataset import get_dataloader+ from auto_round.utils.dataset_utils import strip_dataset_spec_whitespace++ if isinstance(self.dataset, str):+ dataloader = get_dataloader(+ self.tokenizer,+ self.seqlen,+ strip_dataset_spec_whitespace(self.dataset),+ self.seed,+ self.batch_size,+ nsamples,+ trust_remote_code=self.trust_remote_code,+ )+ else:+ dataloader = self.dataset+ if dataloader.__class__.__name__ == "BatchEncoding":+ dataloader = [dataloader.data]++ token_ids: list = []+ for data in dataloader:+ if data.__class__.__name__ == "BatchEncoding":+ data = data.data+ if data is None:+ continue+ attention_mask = None+ if isinstance(data, torch.Tensor):+ input_ids = data+ elif isinstance(data, str):+ if self.tokenizer is None:+ raise ValueError("please provide tokenizer for string input")+ encoded = self.tokenizer(data, truncation=True, max_length=self.seqlen, return_tensors="pt")+ input_ids = encoded["input_ids"]+ attention_mask = encoded.get("attention_mask")+ elif isinstance(data, (tuple, list)):+ input_ids = data[0]+ else:+ input_ids = data["input_ids"]+ attention_mask = data.get("attention_mask")+ if input_ids.dim() == 1:+ input_ids = input_ids.unsqueeze(0)+ if input_ids.shape[-1] < self.seqlen:+ continue+ if include_model_inputs:+ token_ids.extend(self._model_input_samples(input_ids, attention_mask))+ else:+ ids = self._mask_ids_for_loss(input_ids.to("cpu"), attention_mask)+ token_ids.extend(list(torch.split(ids, 1, dim=0)))+ if len(token_ids) >= nsamples:+ break+ token_ids = token_ids[:nsamples]+ if len(token_ids) < nsamples:+ logger.warning_once(+ f"An insufficient number of samples likely reduces the accuracy of the quantized model. "+ f"Target samples count is {nsamples}, while valid samples count is {len(token_ids)}"+ )+ return token_ids+@torch.no_grad()def calib(self, nsamples: int, bs: int) -> None:"""Drive the model with text data so block hooks fire.@@ -310,6 +423,7 @@ class LLMCalibrator(Calibrator):else:self.dataloader = self.datasettotal_cnt = 0+ self.model_input_samples = []if self.dataloader.__class__.__name__ == "BatchEncoding":self.dataloader = [self.dataloader.data]@@ -342,27 +456,13 @@ class LLMCalibrator(Calibrator):input_ids = data_new["input_ids"]if input_ids.shape[-1] < self.seqlen:continue- # Cache raw token IDs for quantize_block. Positions that should be- # excluded from the loss are marked with -100 (PyTorch's standard- # ignore index):- # • actual pad tokens (matched via pad_token_id when available, or- # detected as trailing repeated tokens otherwise)- # • the last token of every sample (no next-token target)+ # Block losses use masked labels; whole-model forwards need the+ # original tokens and attention mask, not reconstructed labels.+ attention_mask = data_new.get("attention_mask") if isinstance(data_new, dict) else None+ self.model_input_samples.extend(self._model_input_samples(input_ids, attention_mask))if "input_ids" not in self.inputs:self.inputs["input_ids"] = []- ids_to_cache = input_ids.clone()- if self.tokenizer is not None and getattr(self.tokenizer, "pad_token_id", None) is not None:- ids_to_cache[ids_to_cache == self.tokenizer.pad_token_id] = -100- else:- # Heuristic: trailing repeated tokens are treated as padding.- for b in range(ids_to_cache.shape[0]):- last_token = ids_to_cache[b, -1]- j = ids_to_cache.shape[1] - 2- while j >= 0 and ids_to_cache[b, j] == last_token:- ids_to_cache[b, j] = -100- j -= 1- # Always exclude the last position (no supervision target).- ids_to_cache[:, -1] = -100+ ids_to_cache = self._mask_ids_for_loss(input_ids, attention_mask)self.inputs["input_ids"].extend(list(torch.split(ids_to_cache.to("cpu"), 1, dim=0)))if need_attention_mask:if (@@ -370,7 +470,8 @@ class LLMCalibrator(Calibrator):and "attention_mask" in data_newand data_new["attention_mask"] is not None):- new_attention_mask = data_new["attention_mask"]+ new_attention_mask = data_new["attention_mask"].clone()+ data_new["attention_mask"] = new_attention_maskelif (self.tokenizer is not Noneand hasattr(self.tokenizer, "pad_token")diff --git a/auto_round/cli/algorithms.py b/auto_round/cli/algorithms.pyindex 648c27838..e6e27dc74 100644--- a/auto_round/cli/algorithms.py+++ b/auto_round/cli/algorithms.py@@ -166,10 +166,6 @@ def _add_registered_arguments(group, registry: AlgorithmParameterRegistry) -> No_add_parameter(target, parameter)-# Algorithms that supply the block-quantization tuning step themselves. Selecting-# any of them must not append the implicit `auto_round` fallback below.-_BLOCK_QUANTIZER_ALGORITHMS = frozenset({"rtn", "opt-rtn", "auto_round", "auto_round_v2"})-# `auto_round_v2` is a SignRound variant: with zero tuning iterations there is# nothing to tune, so it degrades to RTN exactly like `auto_round`._ITERS_ZERO_ALGORITHMS = {"auto_round": "rtn", "auto_round_v2": "rtn"}@@ -266,6 +262,27 @@ class AlgorithmHandler:registry.parameters = parameters_add_registered_arguments(group, registry)+ @classmethod+ def _has_block_quantizer(cls, names) -> bool:+ """Whether any algorithm in *names* is a terminal block quantizer.++ Block-quantization algorithms (rtn, auto_round, qad, …) already provide a+ block quantizer, so the CLI must not append a default one. Preprocessors+ (awq, hadamard, svdquant, …) do not count.+ """+ from auto_round.algorithms.quantization.base import BaseQuantizer+ from auto_round.algorithms.registry import pipeline_member_for_config_class++ for name in names:+ try:+ config_cls = cls.get(name)+ except KeyError:+ continue+ member = pipeline_member_for_config_class(config_cls)+ if member is not None and issubclass(member, BaseQuantizer):+ return True+ return False+@classmethoddef build_configs(cls, args, common_kwargs: dict[str, Any]) -> list:raw = getattr(args, "algorithm", None) or ""@@ -281,7 +298,7 @@ class AlgorithmHandler:# `opt-rtn` carries the plain-vs-optimized intent.explicit_names = set(canonical)seen = set(canonical)- if not (_BLOCK_QUANTIZER_ALGORITHMS & seen):+ if not cls._has_block_quantizer(canonical):canonical.append("rtn" if "awq" in seen or getattr(args, "iters", 0) == 0 else "auto_round")if getattr(args, "iters", None) == 0:canonical = [_ITERS_ZERO_ALGORITHMS.get(name, name) for name in canonical]diff --git a/auto_round/compressors/base.py b/auto_round/compressors/base.pyindex da5238d4a..96cc46db8 100644--- a/auto_round/compressors/base.py+++ b/auto_round/compressors/base.py@@ -285,13 +285,10 @@ class BaseOrchestrator:from auto_round.algorithms.config_resolver import split_quantization_configs_preprocessor_configs, _block_quantizer_configs = split_quantization_configs(self._alg_configs)- if len(_block_quantizer_configs) > 1:- raise ValueError(- f"Only one block-quantization config is allowed, but got {len(_block_quantizer_configs)}: "- f"{[type(c).__name__ for c in _block_quantizer_configs]}"- )if _block_quantizer_configs:- self.quantize_config = _block_quantizer_configs[0]+ # The terminal stage drives public scheme/format resolution. Stage+ # ordering and compatibility are exclusively the composer's job.+ self.quantize_config = _block_quantizer_configs[-1]elif _preprocessor_configs:from auto_round.algorithms.quantization.rtn.config import RTNConfig as _RTNConfig@@ -1512,14 +1509,15 @@ class BaseOrchestrator:plan = getattr(self, "compression_plan", None)if plan is not None:block_quantizer = self._alg_composer.block_quantizer- block_quantizer.layer_config = {name: dict(config) for name, config in plan.layer_config.items()}- block_quantizer.has_qlayer_outside_block = plan.has_qlayer_outside_block- block_quantizer.regex_config = {name: dict(config) for name, config in plan.regex_config.items()}- block_quantizer.quant_block_list = (- [list(group) for group in plan.quant_block_list] if plan.quant_block_list is not None else None- )- block_quantizer.to_quant_block_names = self.to_quant_block_names- block_quantizer.ignore_layers = self.ignore_layers+ for quantizer in self._alg_composer.quantizers:+ quantizer.layer_config = {name: dict(config) for name, config in plan.layer_config.items()}+ quantizer.has_qlayer_outside_block = plan.has_qlayer_outside_block+ quantizer.regex_config = {name: dict(config) for name, config in plan.regex_config.items()}+ quantizer.quant_block_list = (+ [list(group) for group in plan.quant_block_list] if plan.quant_block_list is not None else None+ )+ quantizer.to_quant_block_names = self.to_quant_block_names+ quantizer.ignore_layers = self.ignore_layersfrom auto_round.algorithms.config_resolver import sync_shared_config_from@@ -1819,6 +1817,21 @@ class BaseOrchestrator:if self.formats is None:return+ # Whole-model quantizers (e.g. QAD) tune the entire network in one pass and+ # never run the per-block loop that packs/writes shards incrementally, so+ # immediate packing/saving would leave the output dir without model files.+ # Fall back to packing and saving the whole model after quantization.+ from auto_round.algorithms.config_resolver import get_algorithm_class, split_quantization_configs++ _qcls = get_algorithm_class(self.quantize_config) if self.quantize_config is not None else None+ _, quantizer_configs = split_quantization_configs(self._alg_configs)+ if len(quantizer_configs) > 1 or (_qcls is not None and getattr(_qcls, "whole_model_tuning", False)):+ if self.compress_context.is_immediate_packing or self.compress_context.is_immediate_saving:+ logger.info("Staged/whole-model tuning: disabling immediate packing/saving; saving at the end.")+ self.compress_context.is_immediate_packing = False+ self.compress_context.is_immediate_saving = False+ return+formats = getattr(self, "formats", [])if any(not format.is_supported_immediate_packing() for format in formats):self.compress_context.is_immediate_packing = Falsediff --git a/auto_round/compressors/orchestrator.py b/auto_round/compressors/orchestrator.pyindex e34c31ced..c87ddb34e 100644--- a/auto_round/compressors/orchestrator.py+++ b/auto_round/compressors/orchestrator.py@@ -445,6 +445,7 @@ class CompressionOrchestrator(BaseOrchestrator):is_diffusion=self.model_context.is_diffusion,pbar=pbar,block_cnt=(len(block_names) + nblocks - 1) // nblocks,+ all_block_names=list(block_names),)# ── Infrastructure: calibration-data placement (--calibration_data_device)@@ -654,6 +655,8 @@ class CompressionOrchestrator(BaseOrchestrator):self.post_init()if not self.need_calib:+ if len(self.alg_composer.quantizers) > 1:+ raise NotImplementedError("Multiple zero-shot quantizer stages are not supported yet.")return self._quantize_zero_shot()return self._quantize_data_driven()@@ -810,6 +813,20 @@ class CompressionOrchestrator(BaseOrchestrator):self._check_compatibility()+ if all(quantizer.whole_model_tuning for quantizer in self.alg_composer.quantizers):+ # Whole-model algorithms collect their own raw model inputs. Building+ # first-block activation pools here wastes gigabytes and no block+ # stage exists to consume/release those pools.+ self.inputs = {}+ self.calibration.inputs = {}++ def no_block_stage(replay=False):+ raise RuntimeError("A whole-model-only pipeline must not schedule block tuning.")++ self.alg_composer.compress_model(None, no_block_stage)+ self.model_context.quantized = True+ return self.model_context.model, self.layer_config+if bool(self.quant_block_list):all_blocks = self.quant_block_listelse:@@ -909,115 +926,33 @@ class CompressionOrchestrator(BaseOrchestrator):start_time = time.time()- self.alg_composer.prepare_run()-- # Build one ResumeState per block group (almost always just one group- # for text-only dense models) when AR_RESUME_DIR is set, so a- # crash/kill mid-tuning can resume from the first not-yet-quantized- # block instead of restarting from block 0. See auto_round/utils/resume.py.resume_states = None- if envs.AR_RESUME_DIR:- if not self.compress_context.is_immediate_saving and not self.compress_context.low_cpu_mem_usage:- logger.warning(- "AR_RESUME_DIR is set but neither immediate saving nor "- "low_cpu_mem_usage is active. Without low_cpu_mem_usage, "- "already-quantized blocks are never offloaded anywhere a "- "resumed process could find them (see OffloadManager's "- "deterministic resume directory in offload.py), so a "- "resumed run's in-memory model will have meta/empty "- "weights for blocks completed in a PRIOR process. Pass "- "low_cpu_mem_usage=True (or a format= to quantize_and_save) "- "for resumability to be meaningful here."- )- from auto_round.utils.resume import ResumeState, compute_run_signature, layer_config_fingerprint- model_dir = getattr(self.model_context, "disk_stream_model_dir", None) or getattr(- getattr(self.model_context.model, "config", None), "_name_or_path", None- )- dataset_desc = str(getattr(self, "dataset", None))- # str(self.scheme) alone is bits-blind for AutoScheme runs: two runs- # with different avg_bits share it, so include the resolved- # per-layer allocation (see layer_config_fingerprint docstring).- scheme_desc = (- str(self.scheme)- + "|"- + layer_config_fingerprint(getattr(getattr(self, "quantizer", None), "layer_config", None))- )- resume_states = []- for group_idx, block_names in enumerate(all_blocks):- sig = compute_run_signature(- model_dir,- scheme_desc,- dataset_desc,+ def run_blocks(replay=False):+ nonlocal all_inputs, all_q_inputs, input_ids_cache, resume_states+ if replay:+ self._reload_model_for_tuning()+ all_inputs = self.cache_data(+ to_cache_block_names,self.calibration_context.nsamples,- self.calibration_context.seqlen,- block_names,- )- resume_states.append(- ResumeState(os.path.join(envs.AR_RESUME_DIR, f"group_{group_idx}"), sig, block_names)+ to_cache_layer_names,+ last_cache_name=_last_cache_name,)+ input_ids_cache = all_inputs.pop("input_ids", None)+ self.inputs = all_inputs+ all_q_inputs = None+ self.model_context.model = mv_module_from_gpu(self.model_context.model)+ pbar.reset()+ resume_states = self._run_cached_block_stage(all_blocks, all_inputs, all_q_inputs, input_ids_cache, pbar)- for group_idx, block_names in enumerate(all_blocks):- inputs = all_inputs[block_names[0]]- all_inputs.pop(block_names[0])- q_inputs = None- if all_q_inputs is not None:- q_inputs = all_q_inputs[block_names[0]]- all_q_inputs.pop(block_names[0])-- inputs, q_inputs = _update_inputs(inputs, q_inputs)-- clear_memory(self.inputs)-- resume_state = resume_states[group_idx] if resume_states is not None else None- resume_input_ids = None- if resume_state is not None and resume_state.resume_index > 0:- if self.nblocks != 1:- logger.warning(- "AR_RESUME_DIR is set but nblocks != 1; resuming mid-group is only "- "supported for nblocks=1 -- restarting this group from block 0."- )- resume_state = None- else:- resume_name = block_names[resume_state.resume_index]- # Only used here for `input_others` (position/mask info,- # which is legitimately re-sourced from this same cache- # every iteration regardless of resuming); the actual- # chained `input_ids` comes from `resume_input_ids`- # below, not this cache -- see- # auto_round/utils/resume.py's module docstring for why- # the two aren't interchangeable.- if resume_name in all_inputs:- inputs = all_inputs.pop(resume_name)- q_inputs = resume_state.load_q_input()- resume_input_ids = resume_state.load_input_ids()- if resume_input_ids is None:- logger.warning(- "AR_RESUME_DIR manifest is missing its cached input_ids tensor; "- "restarting this group from block 0 instead of resuming with a "- "possibly-inconsistent chain value."- )- resume_state = None- else:- pbar.update(resume_state.resume_index)+ try:+ handles_whole_model = self.alg_composer.compress_model(input_ids_cache, run_blocks)+ finally:+ pbar.close()+ if handles_whole_model:+ self.model_context.quantized = True+ return self.model_context.model, self.layer_config- self._quantize_blocks(- self.model_context.model,- inputs,- block_names,- q_input=q_inputs if q_inputs is not None else None,- nblocks=self.nblocks,- pbar=pbar,- input_others_extra_blocks=all_inputs,- token_ids=input_ids_cache,- resume_state=resume_state,- resume_input_ids=resume_input_ids,- )- if self.compress_context.is_immediate_packing and len(self.formats) != 1:- raise ValueError(- f"Expected exactly one packing format when 'immediate_packing' is True, "- f"but got {len(self.formats)} formats."- )if resume_states is not None:if self.compress_context.is_immediate_saving:# Don't clear resume state yet when exporting to shards --@@ -1033,10 +968,6 @@ class CompressionOrchestrator(BaseOrchestrator):for rs in resume_states:rs.clear()- # ── Pipeline lifecycle: model-level teardown (also finalizes any- # layer-wise rotation). Symmetric with ``prepare_run`` above. ──────- self.alg_composer.finalize_run()-pbar.set_description("Quantizing done")pbar.close()# Pool placement is per-block: clear it so later forwards (outside-block@@ -1100,6 +1031,101 @@ class CompressionOrchestrator(BaseOrchestrator):self.model_context.quantized = Truereturn self.model_context.model, self.layer_config+ def _reload_model_for_tuning(self):+ """Materialize offloaded/streamed blocks for another model-level pass."""+ if (+ self.compress_context.low_cpu_mem_usage+ or getattr(self.model_context, "_disk_stream_index", None) is not None+ ):+ blocks = self.quant_block_list or get_block_names(self.model_context.model)+ self._offloader.reload(self.model_context.model, flatten_list(blocks))++ def _run_cached_block_stage(self, all_blocks, all_inputs, all_q_inputs, token_ids, pbar):+ """Execute cached block groups with device/offload/resume infrastructure.++ Algorithm selection and stage state belong to the composer. This service+ always runs its active block pipeline, including for non-terminal stages.+ """+ resume_states = None+ if envs.AR_RESUME_DIR:+ if not self.compress_context.is_immediate_saving and not self.compress_context.low_cpu_mem_usage:+ logger.warning(+ "AR_RESUME_DIR is set but neither immediate saving nor low_cpu_mem_usage is active. "+ "Pass low_cpu_mem_usage=True (or a format= to quantize_and_save) for resumability."+ )+ from auto_round.utils.resume import ResumeState, compute_run_signature, layer_config_fingerprint++ model_dir = getattr(self.model_context, "disk_stream_model_dir", None) or getattr(+ getattr(self.model_context.model, "config", None), "_name_or_path", None+ )+ dataset_desc = str(getattr(self, "dataset", None))+ # Include resolved per-layer bits: str(self.scheme) is bits-blind+ # for AutoScheme runs with different allocations.+ scheme_desc = (+ str(self.scheme)+ + "|"+ + layer_config_fingerprint(getattr(getattr(self, "quantizer", None), "layer_config", None))+ )+ resume_states = []+ for group_idx, block_names in enumerate(all_blocks):+ sig = compute_run_signature(+ model_dir,+ scheme_desc,+ dataset_desc,+ self.calibration_context.nsamples,+ self.calibration_context.seqlen,+ block_names,+ )+ resume_states.append(+ ResumeState(os.path.join(envs.AR_RESUME_DIR, f"group_{group_idx}"), sig, block_names)+ )++ for group_idx, block_names in enumerate(all_blocks):+ inputs = all_inputs.pop(block_names[0])+ q_inputs = all_q_inputs.pop(block_names[0], None) if all_q_inputs is not None else None+ inputs, q_inputs = _update_inputs(inputs, q_inputs)+ clear_memory(self.inputs)+ resume_state = resume_states[group_idx] if resume_states is not None else None+ resume_input_ids = None+ if resume_state is not None and resume_state.resume_index > 0:+ if self.nblocks != 1:+ logger.warning("AR_RESUME_DIR is set but nblocks != 1; restarting this group from block 0.")+ resume_state = None+ else:+ resume_name = block_names[resume_state.resume_index]+ # Re-source position/mask metadata, but load the exact chained+ # hidden states rather than deriving them from this cache.+ if resume_name in all_inputs:+ inputs = all_inputs.pop(resume_name)+ q_inputs = resume_state.load_q_input()+ resume_input_ids = resume_state.load_input_ids()+ if resume_input_ids is None:+ logger.warning(+ "AR_RESUME_DIR manifest is missing its cached input_ids tensor; "+ "restarting this group from block 0."+ )+ resume_state = None+ else:+ pbar.update(resume_state.resume_index)+ self._quantize_blocks(+ self.model_context.model,+ inputs,+ block_names,+ q_input=q_inputs,+ nblocks=self.nblocks,+ pbar=pbar,+ input_others_extra_blocks=all_inputs,+ token_ids=token_ids,+ resume_state=resume_state,+ resume_input_ids=resume_input_ids,+ )+ if self.compress_context.is_immediate_packing and len(self.formats) != 1:+ raise ValueError(+ f"Expected exactly one packing format when 'immediate_packing' is True, "+ f"but got {len(self.formats)} formats."+ )+ return resume_states+def _quantize_layers_outside_blocks(self,layer_names: list,diff --git a/auto_round/data_type/utils.py b/auto_round/data_type/utils.pyindex 7b68f008c..1b6744be0 100644--- a/auto_round/data_type/utils.py+++ b/auto_round/data_type/utils.py@@ -524,6 +524,61 @@ def get_gaudi_fp8_ste_func():return fn+def register_act_max_hooks(block: Module, act_data_type=None) -> list:+ """Collect static activation maxima, including NVFP's per-tensor global maximum.++ The caller owns the returned handles and must remove them after calibration.+ """+ from auto_round.compressors.utils import check_need_act_calibration+ from auto_round.utils import SUPPORTED_LAYER_TYPES++ @torch.no_grad()+ def collect_act_max(module, inputs, output):+ inputs = inputs[0] if isinstance(inputs, (tuple, list)) else inputs+ if inputs.numel() == 0:+ return+ module_dtype = getattr(module, "act_data_type", None) or getattr(module, "data_type", None) or act_data_type+ is_nvfp = needs_nvfp_global_scale(module_dtype or "")+ inputs, _, _ = reshape_pad_tensor_by_group_size(inputs, module.act_group_size)+ act_max = inputs.abs().amax(dim=-1)+ if is_nvfp:+ act_max = act_max.amax().reshape(1)+ previous = getattr(module, "act_max", None)+ if previous is not None and previous.numel():+ act_max = act_max.to(previous.device)+ if is_nvfp:+ previous = previous.amax().reshape(1)+ act_max = torch.maximum(act_max, previous)+ module.act_max = act_max++ def should_collect(module):+ if isinstance(module, tuple(SUPPORTED_LAYER_TYPES)):+ return (+ hasattr(module, "act_dynamic")+ and check_need_act_calibration(module.act_dynamic, module.act_data_type, module.act_bits)+ and check_to_quantized(module)+ )+ if hasattr(module, "bits"):+ return (+ module.bits <= 8+ and check_need_act_calibration(+ getattr(module, "act_dynamic", True),+ getattr(module, "act_data_type", None),+ getattr(module, "act_bits", 16),+ )+ and check_to_quantized(module)+ )+ return False++ if should_collect(block):+ return [block.register_forward_hook(collect_act_max)]+ return [+ module.register_forward_hook(collect_act_max)+ for name, module in block.named_modules()+ if name and should_collect(module)+ ]++# please refer from https://github.com/vllm-project/llm-compressor/blob/# 29f4d5644b48e9c8ebb7e36d5be9f7c92747ceb7/src/llmcompressor/modifiers/utils/helpers.py#L11def update_fused_layer_global_scales(diff --git a/auto_round/envs.py b/auto_round/envs.pyindex 843320573..595b17d1a 100644--- a/auto_round/envs.py+++ b/auto_round/envs.py@@ -44,6 +44,7 @@ if TYPE_CHECKING:AR_PERF_COUNTERS: bool = FalseAR_SEARCH_BATCH_GB: float | None = NoneAR_DISABLE_CROSS_DEVICE_SEARCH: bool = False+ AR_ENABLE_LOG_MINMAX: bool = Falsedef _get_optional_positive_int_env(name: str) -> int | None:@@ -98,6 +99,13 @@ environment_variables: dict[str, Callable[[], Any]] = {"AR_ACT_SCALE": lambda: float(os.getenv("AR_ACT_SCALE", "1.0")),"AR_ENABLE_ACT_MINMAX_TUNING": lambda: os.getenv("AR_ENABLE_ACT_MINMAX_TUNING", "0").lower()in ("1", "true", "yes"),+ # Tune the SignRound optimized-path min/max scale coefficients in log+ # (geometric) space: the stored parameter is ``theta`` with ``coeff =+ # exp(theta)``, so each symmetric SignSGD step is a multiplicative move+ # (``+lr -> x e^lr``, ``-lr -> / e^lr``). This makes shrinking and expanding+ # the quant range equidistant (e.g. reaching 0.5x and 2x costs the same+ # number of steps) instead of the linear-coefficient asymmetry. Default off.+ "AR_ENABLE_LOG_MINMAX": lambda: os.getenv("AR_ENABLE_LOG_MINMAX", "0").lower() in ("1", "true", "yes"),"AR_FUSE_ONLINE_ROTATION": lambda: os.getenv("AR_FUSE_ONLINE_ROTATION", "0").lower() in ("1", "true", "yes"),# Controls the search range ratio for symmetric int scale search in# `auto_round.data_type.int.search_scales`. The search bound isdiff --git a/auto_round/eval/eval_cli.py b/auto_round/eval/eval_cli.pyindex b40c552a3..b18aeea64 100644--- a/auto_round/eval/eval_cli.py+++ b/auto_round/eval/eval_cli.py@@ -31,6 +31,46 @@ from auto_round.utils import ()+def _has_eval_model_artifacts(model_dir: str) -> bool:+ if not os.path.isdir(model_dir):+ return False+ artifact_names = {"config.json", "model_index.json", "modular_model_index.json"}+ for name in artifact_names:+ if os.path.isfile(os.path.join(model_dir, name)):+ return True+ return any(name.endswith(".gguf") for name in os.listdir(model_dir))+++def _resolve_exported_model_path(model_path):+ """Resolve wrapper output directories to the actual exported model folder.++ Some helper scripts pass a parent output directory (for example+ ``outputs/aware_topk_tune_shared``) while the export itself lives in a+ single nested subdirectory derived from model name and quantization scheme.+ When there is exactly one child directory containing loadable model+ artifacts, prefer that child automatically.+ """+ from auto_round.utils import logger++ if not isinstance(model_path, str) or not os.path.isdir(model_path):+ return model_path++ if _has_eval_model_artifacts(model_path):+ return model_path++ candidate_dirs = []+ for entry in os.listdir(model_path):+ candidate = os.path.join(model_path, entry)+ if os.path.isdir(candidate) and _has_eval_model_artifacts(candidate):+ candidate_dirs.append(candidate)++ if len(candidate_dirs) == 1:+ resolved = candidate_dirs[0]+ logger.info("Resolved evaluation model path '%s' to exported artifact '%s'.", model_path, resolved)+ return resolved+ return model_path++class EvalArgumentParser(argparse.ArgumentParser):def __init__(self, *args, **kwargs):@@ -201,6 +241,8 @@ def eval(args):"lm_eval>=0.4.2", "lm-eval is required for evaluation, please install it with `pip install 'lm-eval>=0.4.2'`")+ args.model_name = _resolve_exported_model_path(args.model_name)+if is_diffusion_model(args.model_name):from auto_round.eval.evaluation import evaluate_diffusion_modelfrom auto_round.utils import diffusion_load_modeldiff --git a/auto_round/wrapper.py b/auto_round/wrapper.pyindex af0d4c7f2..331d84b1a 100644--- a/auto_round/wrapper.py+++ b/auto_round/wrapper.py@@ -13,6 +13,7 @@# limitations under the License.import math+from contextlib import contextmanagerfrom math import ceilimport torch@@ -59,6 +60,14 @@ def get_scale_shape(weight, group_size):return shape+def _restore_warm_start_param(orig_layer, name, param):+ """Restore a compatible parameter without replacing its optimizer identity."""+ saved = getattr(orig_layer, "_ar_warm_start", {}).get(name)+ if saved is not None and saved.shape == param.shape:+ with torch.no_grad():+ param.copy_(saved.to(device=param.device, dtype=param.dtype))++class WrapperLinear(torch.nn.Module):"""A wrapper for linear/conv1d layers to enable quantization and tuning.@@ -108,6 +117,7 @@ class WrapperLinear(torch.nn.Module):self.enable_norm_bias_tuning = enable_norm_bias_tuning and (orig_layer.bias is not None)self.enable_act_quant = self.orig_layer.act_bits <= 8self.weight_global_scale = getattr(self.orig_layer, "weight_global_scale", None)+ self.input_global_scale = getattr(self.orig_layer, "input_global_scale", None)if needs_nvfp_global_scale(self.orig_layer.data_type) and self.weight_global_scale is None:from auto_round.data_type.nvfp import calculate_gparam_by_dtype@@ -244,6 +254,52 @@ class WrapperLinear(torch.nn.Module):self._init_params("min_scale", p_dtype, shape, 1.0, _margins_tunable)self._init_params("max_scale", p_dtype, shape, 1.0, _margins_tunable)+ # Midrise int (v1 path): the absmax-derived scale (absmax / (maxq-0.5)) is far from the+ # MSE optimum (~0.5x at W2) and the default [0, 1] max_scale bound with SignSGD can barely+ # shrink that far. Seed ``init_scale`` with the same imatrix-weighted search used by the v2+ # path and let ``max_scale`` tune a coefficient around it in both directions.+ # (SignRoundOptimizedWrapperLinear re-runs the search and keeps its own bound.)+ if (+ str(self.orig_layer.data_type).startswith("int_midrise")+ and type(self).minmax_scale_bound == WrapperLinear.minmax_scale_bound # plain v1 wrapper only+ and self.enable_round_tuning+ and self.orig_layer.bits < 16+ and not isinstance(orig_layer.group_size, tuple)+ ):+ from auto_round.data_type.utils import reshape_imatrix_for_weight, search_optimized_init_scale++ warm_start = getattr(orig_layer, "_ar_warm_start", None)+ if warm_start and warm_start.get("init_scale") is not None:+ self.init_scale = warm_start["init_scale"].to(self.device)+ else:+ w_r = weight_reshape.to(self.device, torch.float32)+ imatrix = reshape_imatrix_for_weight(getattr(orig_layer, "imatrix", None), w_r, orig_layer.group_size)+ self.init_scale = search_optimized_init_scale(+ w_r, orig_layer.data_type, orig_layer.bits, imatrix.to(w_r.device), self.q_scale_thresh+ )+ self.minmax_scale_bound = (0.5, 1.5)++ # Warm-start: when a prior block-wise pass (e.g. the SignRound -> QAD+ # chaining) stashed its tuned ``value``/``min_scale``/``max_scale`` on+ # this layer via ``store_warm_start_params_and_unwrap``, seed the freshly+ # created tuning parameters with them so this pass continues from that+ # state instead of starting from RTN (value=0, scale coeff=1).+ warm_start = getattr(orig_layer, "_ar_warm_start", None)+ if warm_start:+ for _key in ("value", "min_scale", "max_scale"):+ saved = warm_start.get(_key)+ param = self.params.get(_key)+ if saved is None or param is None:+ continue+ saved = saved.to(device=param.device, dtype=param.dtype)+ if saved.shape == param.shape:+ param.data.copy_(saved)+ else:+ logger.warning_once(+ f"warm-start param '{_key}' shape {tuple(saved.shape)} does not match "+ f"{tuple(param.shape)}; keeping the default initialization."+ )+self.weight_quant_func, self.data_type = get_quant_func(orig_layer.data_type,orig_layer.bits,@@ -270,10 +326,17 @@ class WrapperLinear(torch.nn.Module):"act_max_scale", p_dtype, (1), 1.0, envs.AR_ENABLE_ACT_MINMAX_TUNING or (not orig_layer.act_dynamic))self._init_params("act_min_scale", p_dtype, (1), 1.0, envs.AR_ENABLE_ACT_MINMAX_TUNING)+ if warm_start:+ for key in ("act_min_scale", "act_max_scale"):+ saved = warm_start.get(key)+ param = self.params.get(key)+ if saved is not None and param is not None and saved.shape == param.shape:+ param.data.copy_(saved.to(device=param.device, dtype=param.dtype))# Bias tuningif self.enable_norm_bias_tuning:self._init_params("bias_v", p_dtype, self.orig_layer.bias.shape, 0, True)+ _restore_warm_start_param(self.orig_layer, "bias_v", self.bias_v)from auto_round.data_type.int import quant_tensor_asym_wo_roundself.bias_quant_func = quant_tensor_asym_wo_round@@ -423,17 +486,22 @@ class WrapperLinear(torch.nn.Module):**quant_kwargs,}- def _qdq_weight(self, value, min_scale, max_scale):- """Quantizes and dequantizes weights with tuning parameters.-- Args:- value (torch.Tensor): Value added for rounding for tuning.- min_scale (torch.Tensor): Minimum scale for the min value of quantization.- max_scale (torch.Tensor): Maximum scale for the max value of quantization.+ def _prepare_minmax_scale(self, min_scale, max_scale):+ """Clamp the min/max scale coefficients and return what the quant func sees.- Returns:- tuple: Quantized weight, scale, and zero point.+ Default (linear) behavior: the stored parameters *are* the multiplicative+ coefficients, clamped in place to ``minmax_scale_bound`` and passed+ through unchanged. Subclasses may override this to tune the coefficients+ in a different geometry (e.g. log/geometric space) while keeping the+ quant functions -- which always receive plain multiplicative+ coefficients -- untouched."""+ min_bound, max_bound = self.minmax_scale_bound+ min_scale.data.clamp_(min_bound, max_bound)+ max_scale.data.clamp_(min_bound, max_bound)+ return min_scale, max_scale++ def _qdq_weight(self, value, min_scale, max_scale):presolved = getattr(self, "_presolved_qdq", None)if presolved is not None:# Batched-search write-back: the search already ran on a stacked@@ -445,9 +513,7 @@ class WrapperLinear(torch.nn.Module):return presolvedif self.orig_layer.bits >= 16:return self.orig_layer.weight, None, None- min_bound, max_bound = self.minmax_scale_bound- min_scale.data.clamp_(min_bound, max_bound)- max_scale.data.clamp_(min_bound, max_bound)+ min_scale, max_scale = self._prepare_minmax_scale(min_scale, max_scale)weight = self.orig_layer.weightif weight.device.type == "meta":weight = self.orig_layer.get_weight().to(self.device)@@ -571,8 +637,11 @@ class WrapperLinear(torch.nn.Module):# Unwrapper actif self.enable_act_quant:+ act_min_scale = best_params.get("act_min_scale", torch.tensor(1.0)).detach().to(self.device).clone()+ act_max_scale = best_params.get("act_max_scale", torch.tensor(1.0)).detach().to(self.device).clone()+ act_min_scale.clamp_(0, 1.0)+ act_max_scale.clamp_(0, 1.0)if not self.orig_layer.act_dynamic:- act_max_scale = best_params.get("act_max_scale", torch.tensor(1.0)).to(self.device)act_max = self.orig_layer.act_max if hasattr(self.orig_layer, "act_max") else Noneif act_max is not None:tmp_shape = 1@@ -582,11 +651,11 @@ class WrapperLinear(torch.nn.Module):tmp_shape = (act_max.shape[0], 1)_, act_scale, _ = self._qdq_act(torch.zeros(tmp_shape).to(self.device),- act_min_scale=self.act_min_scale,- act_max_scale=self.act_max_scale,+ act_min_scale=act_min_scale,+ act_max_scale=act_max_scale,act_max=act_max,)- self.orig_layer.act_max = self.orig_layer.act_max * act_max_scale.item()+ # Keep calibration statistics separate from the tuned coefficients.self.orig_layer.act_max = self.orig_layer.act_max.to("cpu")else:act_scale = torch.ones(1, dtype=self.orig_layer.scale_dtype)@@ -594,8 +663,8 @@ class WrapperLinear(torch.nn.Module):self.orig_layer.q_scale_thresh = self.q_scale_threshself.orig_layer.data_type = self.data_type- self.orig_layer.act_min_scale = self.act_min_scale- self.orig_layer.act_max_scale = self.act_max_scale+ self.orig_layer.act_min_scale = act_min_scale+ self.orig_layer.act_max_scale = act_max_scaleself.orig_layer.act_data_type = self.act_data_typeself.orig_layer.act_quant_func = self.act_quant_func@@ -754,29 +823,18 @@ class WrapperWALayer(torch.nn.Module):quant_kwargs = {}if hasattr(self.orig_layer, "input_global_scale"):quant_kwargs["global_scale"] = self.orig_layer.input_global_scale- if act_max is None:- x, _, _ = self.orig_layer.act_quant_func(- x,- bits=self.orig_layer.act_bits,- group_size=self.orig_layer.act_group_size,- scale_dtype=self.orig_layer.scale_dtype,- q_scale_thresh=self.orig_layer.q_scale_thresh,- data_type=self.orig_layer.act_data_type,- min_scale=min_scale,- max_scale=max_scale,- **quant_kwargs,- )- else:- x, _, _ = self.orig_layer.act_quant_func(- x,- bits=self.orig_layer.act_bits,- group_size=self.orig_layer.act_group_size,- scale_dtype=self.orig_layer.scale_dtype,- q_scale_thresh=self.orig_layer.q_scale_thresh,- data_type=self.orig_layer.act_data_type,- act_max=act_max,- **quant_kwargs,- )+ x, _, _ = self.orig_layer.act_quant_func(+ x,+ bits=self.orig_layer.act_bits,+ group_size=self.orig_layer.act_group_size,+ scale_dtype=self.orig_layer.scale_dtype,+ q_scale_thresh=self.orig_layer.q_scale_thresh,+ data_type=self.orig_layer.act_data_type,+ tensor_max=act_max,+ min_scale=min_scale,+ max_scale=max_scale,+ **quant_kwargs,+ )# 3) Linear computation via orig_layer (pre_hooks already removed, no double execution)return self.orig_layer.forward(x)@@ -808,6 +866,7 @@ class WrapperLayerNorm(torch.nn.Module):requires_grad=True,)self.params = {"v": self.v}+ _restore_warm_start_param(self.orig_layer, "v", self.v)from auto_round.data_type.int import quant_tensor_asym_wo_roundself.quant_func = quant_tensor_asym_wo_round@@ -859,6 +918,7 @@ class WrapperLlamaNorm(torch.nn.Module):requires_grad=True,)self.params = {"v": self.v}+ _restore_warm_start_param(self.orig_layer, "v", self.v)from auto_round.data_type.int import quant_tensor_asym_wo_roundself.quant_func = quant_tensor_asym_wo_round@@ -977,8 +1037,10 @@ def wrapper_block(return Noneif kind == "skip":return "u"- extra = {"defer_search": True} if _defer_batch else {}- new_m = wrapper_cls(+ layer_wrapper_cls = getattr(m, "_ar_warm_start_wrapper_cls", wrapper_cls)+ defer_search = _defer_batch and getattr(layer_wrapper_cls, "supports_batched_search", False)+ extra = {"defer_search": True} if defer_search else {}+ new_m = layer_wrapper_cls(m,enable_minmax_tuning=enable_minmax_tuning,enable_norm_bias_tuning=enable_norm_bias_tuning,@@ -988,7 +1050,7 @@ def wrapper_block(**extra,)set_module(block, n, new_m)- if _defer_batch:+ if defer_search:deferred_wrappers.append(new_m)return "q"@@ -1022,7 +1084,8 @@ def unwrapper_layer(model, layer, layer_name, best_params):max_scales: A dictionary of maximum scaling values for the wrapped modules."""- if hasattr(layer, "orig_layer"):+ # WrapperWALayer retains activation QDQ and is not a tuning wrapper.+ if hasattr(layer, "orig_layer") and callable(getattr(layer, "unwrapper", None)):orig_layer = layer.unwrapper(best_params)act_max = getattr(orig_layer, "act_max", None)act_scale = getattr(orig_layer, "act_scale", None)@@ -1052,10 +1115,111 @@ def unwrapper_block(block, best_params):max_scales: A dictionary of maximum scaling values for the wrapped modules."""for n, m in block.named_modules():- if hasattr(m, "orig_layer"):+ # Keep persistent activation wrappers, which do not implement unwrapper.+ if hasattr(m, "orig_layer") and callable(getattr(m, "unwrapper", None)):if n in best_params.keys():best_param = best_params[n]else:best_param = Noneorig_layer = m.unwrapper(best_param)set_module(block, n, orig_layer)+++@contextmanager+def preserve_original_weights(block):+ """Keep a host snapshot for a composer-owned stage that must not bake weights.++ This also covers algorithms that modify parameters in place instead of using+ common wrappers. Only the current block is copied on block-tuning paths;+ ordinary/final stages do not pay this cost. Restore the original module graph+ and parameter dtype/values on success or failure, leaving warm-start metadata+ on the original layers available to subsequent stages.+ """+ modules = list(block.named_modules())+ parameters = [(p, p.detach().to("cpu", copy=True), p.requires_grad) for p in block.parameters()]+ quantization_types = [+ (module, key, getattr(module, key))+ for _, module in modules+ for key in ("data_type", "act_data_type")+ if hasattr(module, key)+ ]+ try:+ yield+ finally:+ with torch.no_grad():+ for name, module in modules:+ if name:+ set_module(block, name, module)+ for parameter, saved, requires_grad in parameters:+ parameter.data = saved.to(parameter.device)+ parameter.requires_grad_(requires_grad)+ # RTN writes resolved one-shot dtype names during finalization.+ # Subsequent training stages need the original differentiable types.+ for module, key, value in quantization_types:+ setattr(module, key, value)++[email protected]_grad()+def store_warm_start_params_and_unwrap(block, best_params, *, before_unwrap=None):+ """Warm-start variant of :func:`unwrapper_block`: keep the original FP weight.++ Instead of baking the tuned ``value``/``min_scale``/``max_scale`` into the+ (quantized) weight like :func:`unwrapper_block` does, this stashes them on+ each ``orig_layer`` under ``_ar_warm_start`` and restores the untouched+ full-precision layer. A later pass (e.g. QAD whole-model tuning) can then+ re-wrap the same layers and seed its tuning parameters from the stash via the+ warm-start branch in :meth:`WrapperLinear._init_tuning_params_and_quant_func`.++ The optimized SignRound wrapper also exposes a searched ``init_scale`` (not a+ trainable parameter); it is stashed too so the second pass reuses the exact+ same scale grid instead of re-searching it.++ Args:+ block: The block (or single wrapped layer) whose wrappers to collect.+ best_params: Result of ``collect_best_params`` -- either a flat+ ``{param_name: tensor}`` dict (single-wrapper block) or+ ``{submodule_name: {param_name: tensor}}``.+ before_unwrap: Optional callback receiving the still-wrapped block with+ its best parameters loaded. Used to collect quantized outputs before+ restoring FP layers; restoration also happens if the callback raises.+ """+ best_params = best_params or {}+ wrapped_layers = [+ (n, m)+ for n, m in block.named_modules()+ if hasattr(m, "orig_layer") and hasattr(m, "params") and callable(getattr(m, "unwrapper", None))+ ]+ try:+ for n, m in wrapped_layers:+ if n in best_params:+ layer_params = best_params[n]+ elif any(key in best_params for key in m.params):+ # Flat dict: the block itself is the wrapped layer.+ layer_params = best_params+ else:+ layer_params = {}+ store = {}+ for key in m.params:+ if key in layer_params and layer_params[key] is not None:+ store[key] = layer_params[key].detach().to("cpu", copy=True)+ store["minmax_parameterization"] = "log" if getattr(m, "_use_log_minmax", False) else "linear"+ init_scale = getattr(m, "init_scale", None)+ if init_scale is not None:+ store["init_scale"] = init_scale.detach().to("cpu")+ # Asym optimized wrapper: preserve the searched grid anchor too.+ if getattr(m, "_asym_anchor", False):+ store["anchor_min"] = m.weight_min.detach().to("cpu")+ store["anchor_max"] = m.weight_max.detach().to("cpu")+ m.orig_layer._ar_warm_start = store+ if isinstance(m, WrapperLinear):+ m.orig_layer._ar_warm_start_wrapper_cls = type(m)+ if before_unwrap is not None:+ for key, saved in layer_params.items():+ param = m.params.get(key)+ if param is not None and saved is not None:+ param.copy_(saved.to(device=param.device, dtype=param.dtype))+ if before_unwrap is not None:+ before_unwrap(block)+ finally:+ for n, m in wrapped_layers:+ set_module(block, n, m.orig_layer)diff --git a/requirements-hpu.txt b/requirements-hpu.txtindex 0fbe967a4..2ababbfcf 100644--- a/requirements-hpu.txt+++ b/requirements-hpu.txt@@ -1,5 +1,6 @@accelerate>=1.10.0datasets+filelockpy-cpuinfosentencepiecenumpydiff --git a/requirements.txt b/requirements.txtindex bdec150de..eddd51af7 100644--- a/requirements.txt+++ b/requirements.txt@@ -1,6 +1,7 @@# 1.5.1<accelerate<1.10.0 may cause potentially high RAM usage; versions 1.10.0 or above are recommended.acceleratedatasets+filelocknumpypy-cpuinfotorchdiff --git a/test/unit/common/core/test_pipeline_fast.py b/test/unit/common/core/test_pipeline_fast.pyindex f680f8caa..17de8326c 100644--- a/test/unit/common/core/test_pipeline_fast.py+++ b/test/unit/common/core/test_pipeline_fast.py@@ -63,9 +63,12 @@ def test_pipeline_duplicate_preprocessor_rejected():AlgorithmComposer([AWQConfig(), AWQConfig()])-def test_pipeline_multiple_block_quantizers_rejected():- with pytest.raises(ValueError, match="exactly one block-quantization config"):- AlgorithmComposer([RTNConfig(), SignRoundConfig()])+def test_pipeline_multiple_block_quantizers_keep_config_order():+ pipeline = AlgorithmComposer([RTNConfig(), SignRoundConfig()])+ assert len(pipeline.quantizers) == 2+ assert isinstance(pipeline.quantizers[0], RTNQuantizer)+ assert pipeline.block_quantizer is pipeline.quantizers[-1]+ assert isinstance(pipeline.block_quantizer.config, SignRoundConfig)@pytest.mark.parametrize(diff --git a/test/unit/common/core/test_wrapper_utils.py b/test/unit/common/core/test_wrapper_utils.pyindex a603d0da0..7e7b02fd4 100644--- a/test/unit/common/core/test_wrapper_utils.py+++ b/test/unit/common/core/test_wrapper_utils.py@@ -274,6 +274,42 @@ class TestWrapperBlock:assert isinstance(quantized, list)+class TestUnwrapperActivationLayer:+ """Activation QDQ wrappers must survive tuning-wrapper cleanup."""++ @pytest.mark.parametrize("unwrap_single_layer", [False, True])+ def test_preserves_activation_quantization(self, unwrap_single_layer):+ from auto_round.wrapper import WrapperLayerNorm, WrapperWALayer, unwrapper_block, unwrapper_layer++ layer = torch.nn.Linear(4, 4, bias=False)+ layer.act_quant_func = MagicMock(side_effect=lambda x, **kwargs: (torch.zeros_like(x), None, None))+ layer.act_bits = 8+ layer.act_group_size = -1+ layer.scale_dtype = torch.float32+ layer.q_scale_thresh = 1e-5+ layer.act_data_type = "int"+ layer.act_min_scale = 1.0+ layer.act_max_scale = 1.0+ activation_wrapper = WrapperWALayer(layer, enable_torch_compile=False)+ norm = torch.nn.LayerNorm(4)+ block = torch.nn.Sequential(activation_wrapper, WrapperLayerNorm(norm))++ # Repeated cleanup must not remove activation QDQ or call its missing unwrapper.+ for _ in range(2):+ if unwrap_single_layer:+ unwrapper_layer(block, block[0], "0", None)+ unwrapper_layer(block, block[1], "1", None)+ else:+ unwrapper_block(block, {})++ assert block[0] is activation_wrapper+ assert block[0].orig_layer is layer+ assert block[1] is norm+ output = block[0](torch.ones(2, 4))+ torch.testing.assert_close(output, torch.zeros_like(output))+ layer.act_quant_func.assert_called_once()++class TestWrapperLinearQdqBias:"""Tests for WrapperLinear._qdq_bias method."""diff --git a/test/unit/common/eval/test_eval_cli.py b/test/unit/common/eval/test_eval_cli.pyindex 54e3dfa70..d599b3851 100644--- a/test/unit/common/eval/test_eval_cli.py+++ b/test/unit/common/eval/test_eval_cli.py@@ -703,6 +703,29 @@ class TestEvaluateTasksWithRetry:class TestLoadGgufModelIfNeeded:"""CPU-only tests for GGUF detection using temporary files/directories."""+ def test_parent_export_dir_resolves_to_single_nested_artifact_dir(self, tmp_path):+ export_root = tmp_path / "aware_topk_tune_shared"+ nested_model_dir = export_root / "Qwen3-30B-A3B-w4g128"+ nested_model_dir.mkdir(parents=True)+ (nested_model_dir / "config.json").write_text('{"model_type": "qwen3_moe"}', encoding="utf-8")++ resolved = eval_cli._resolve_exported_model_path(str(export_root))++ assert resolved == str(nested_model_dir)++ def test_parent_export_dir_stays_unchanged_when_multiple_nested_artifacts_exist(self, tmp_path):+ export_root = tmp_path / "aware_topk_tune_shared"+ first_nested = export_root / "first-export"+ second_nested = export_root / "second-export"+ first_nested.mkdir(parents=True)+ second_nested.mkdir(parents=True)+ (first_nested / "config.json").write_text('{"model_type": "llama"}', encoding="utf-8")+ (second_nested / "config.json").write_text('{"model_type": "llama"}', encoding="utf-8")++ resolved = eval_cli._resolve_exported_model_path(str(export_root))++ assert resolved == str(export_root)+def test_gguf_file_detected_at_file_path(self, monkeypatch, tmp_path):gguf_path = tmp_path / "model.gguf"# GGUF readers validate the four-byte magic even though the modeldiff --git a/test/unit/common/export/test_svdquant_nunchaku_format.py b/test/unit/common/export/test_svdquant_nunchaku_format.pyindex b66aec6d4..1695d647b 100644--- a/test/unit/common/export/test_svdquant_nunchaku_format.py+++ b/test/unit/common/export/test_svdquant_nunchaku_format.py@@ -151,6 +151,7 @@ def test_full_model_format_disables_immediate_packing_and_saving():is_immediate_saving=True,),quantize_config=SimpleNamespace(data_type="mx_fp"),+ _alg_configs=[],output_dir="unused",_ensure_shard_writer=lambda: pytest.fail("full-model export must not create a shard writer"),)diff --git a/test/unit/common/utils/test_alg_ext.py b/test/unit/common/utils/test_alg_ext.pyindex a9fb4c9e5..436d99fd8 100644--- a/test/unit/common/utils/test_alg_ext.py+++ b/test/unit/common/utils/test_alg_ext.py@@ -1,6 +1,7 @@import jsonimport pytest+import torchfrom auto_round import AutoRound@@ -11,6 +12,60 @@ def _local_calibration_dataset(tmp_path):return str(dataset_path)+def _asym_linear():+ layer = torch.nn.Linear(8, 4, bias=False)+ layer.bits = 2+ layer.group_size = 4+ layer.sym = False+ layer.data_type = "int"+ layer.act_bits = 16+ layer.scale_dtype = torch.float32+ return layer++[email protected]("defer_search", [False, True])+def test_asym_alg_ext_wrapper_accepts_defer_search(defer_search):+ from auto_round.algorithms.quantization.sign_roundv2.quantizer import SignRoundOptimizedAsymWrapperLinear++ wrapper = SignRoundOptimizedAsymWrapperLinear(+ _asym_linear(),+ enable_minmax_tuning=True,+ enable_norm_bias_tuning=False,+ enable_torch_compile=False,+ device="cpu",+ defer_search=defer_search,+ )++ assert wrapper._asym_anchor+ assert isinstance(wrapper.min_scale, torch.nn.Parameter)+ assert isinstance(wrapper.max_scale, torch.nn.Parameter)+ assert torch.isfinite(wrapper.weight_min).all()+ assert torch.isfinite(wrapper.weight_max).all()++[email protected]("batching_disabled", [False, True])+def test_asym_alg_ext_wrapper_keeps_search_inline(monkeypatch, batching_disabled):+ from auto_round.algorithms.quantization import search_dispatch+ from auto_round.algorithms.quantization.sign_roundv2.quantizer import SignRoundOptimizedAsymWrapperLinear+ from auto_round.wrapper import wrapper_block++ monkeypatch.setattr(search_dispatch, "batched_search_disabled", lambda: batching_disabled)+ block = torch.nn.Sequential(_asym_linear(), _asym_linear())+ quantized, unquantized = wrapper_block(+ block,+ enable_minmax_tuning=True,+ enable_norm_bias_tuning=False,+ enable_torch_compile=False,+ device="cpu",+ wrapper_cls=SignRoundOptimizedAsymWrapperLinear,+ )++ assert quantized == ["0", "1"]+ assert unquantized == []+ assert not SignRoundOptimizedAsymWrapperLinear.supports_batched_search+ assert all(layer._asym_anchor for layer in block)++class TestAlgExt:def test_gguf_q4_alg_ext(self, tiny_qwen_model_path, tmp_path):"""Exercise the GGUF algorithm-extension path not covered by CUDA matrix tests."""@@ -27,6 +82,24 @@ class TestAlgExt:def test_alg_ext_import(self):from auto_round.algorithms.quantization.sign_roundv2 import SignRoundV2Quantizer+ def test_w2_asym_alg_ext(self, tiny_opt_model_path, tmp_path):+ """Asyme INT now uses the searched (scale, zp) anchor wrapper on the alg-ext path."""+ ar = AutoRound(+ tiny_opt_model_path,+ scheme="W2A16G64",+ sym=False,+ iters=2,+ nsamples=1,+ seqlen=32,+ dataset=_local_calibration_dataset(tmp_path),+ enable_alg_ext=True,+ )+ model, _ = ar.quantize()+ zps = [m.zp for m in model.modules() if hasattr(m, "zp") and isinstance(m.zp, __import__("torch").Tensor)]+ assert zps, "expected asym zero points on quantized layers"+ for zp in zps:+ assert zp.min() >= 0 and zp.max() <= 3+def test_nvfp4_alg_ext(self, tiny_opt_model_path, tmp_path):"""Keep NVFP4 as the representative format not exercised by the CUDA matrix."""AutoRound(diff --git a/test/unit/common/utils/test_cli_usage.py b/test/unit/common/utils/test_cli_usage.pyindex 01af975c2..5bd5f9467 100644--- a/test/unit/common/utils/test_cli_usage.py+++ b/test/unit/common/utils/test_cli_usage.py@@ -605,12 +605,38 @@ def test_registered_cli_fields_are_accepted_by_config_constructors():if entry.config_factory is None:continueconfig_cls = entry.config_factory if isinstance(entry.config_factory, type) else type(entry.config_factory())- accepted = set(inspect.signature(config_cls.__init__).parameters)- accepted.discard("self")+ accepted = set()+ for cls in config_cls.__mro__:+ parameters = inspect.signature(cls.__init__).parameters.values()+ accepted.update(+ parameter.name+ for parameter in parameters+ if parameter.name != "self"+ and parameter.kind in (inspect.Parameter.POSITIONAL_OR_KEYWORD, inspect.Parameter.KEYWORD_ONLY)+ )+ if not any(parameter.kind == inspect.Parameter.VAR_KEYWORD for parameter in parameters):+ breakaccepted.update(getattr(config_cls, "model_fields", {}))- assert all(- parameter.field in accepted for parameter in algorithm_cli._parameter_registry(config_cls).parameters- )+ registered = {parameter.field for parameter in algorithm_cli._parameter_registry(config_cls).parameters}+ assert (+ not registered - accepted+ ), f"{config_cls.__name__}: unsupported CLI fields {sorted(registered - accepted)}"++[email protected]("algorithm", ["qad", "qat"])+def test_inherited_cli_fields_are_forwarded_to_config_constructors(algorithm):+ import auto_round.cli.algorithms as algorithm_cli+ from auto_round.algorithms.quantization.qad.config import QADConfig+ from auto_round.algorithms.quantization.qat.config import QATConfig++ config_cls = {"qad": QADConfig, "qat": QATConfig}[algorithm]+ args = argparse.Namespace(momentum=0.25, lfq_num_blocks=2, qad_lr=0.01)+ config = config_cls(**algorithm_cli._parameter_registry(config_cls).config_kwargs(args))++ assert config.momentum == 0.25+ assert config.lfq_num_blocks == 2+ assert config.qad_lr == 0.01+ assert config.lr == 0.01def test_svdquant_cli_defaults_compose_before_signround():diff --git a/test/unit/test_cpu/algorithms/test_algorithm_nsamples.py b/test/unit/test_cpu/algorithms/test_algorithm_nsamples.pynew file mode 100644index 000000000..6321d88de--- /dev/null+++ b/test/unit/test_cpu/algorithms/test_algorithm_nsamples.py@@ -0,0 +1,133 @@+# Copyright (c) 2026 Intel Corporation+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.++import argparse+from types import SimpleNamespace+from unittest.mock import Mock++import pytest++from auto_round.algorithms.composer import AlgorithmComposer+from auto_round.algorithms.config_resolver import resolve_shared_config_values, sync_shared_config_from+from auto_round.algorithms.quantization.base import BaseQuantizer+from auto_round.algorithms.quantization.config import QuantizationConfig+from auto_round.algorithms.quantization.qad.config import QADConfig+from auto_round.algorithms.quantization.qat.config import QATConfig+from auto_round.algorithms.quantization.sign_round.config import SignRoundConfig+from auto_round.cli.algorithms import AlgorithmHandler++[email protected]("config_cls", [QuantizationConfig, SignRoundConfig, QADConfig, QATConfig])+def test_inherited_nsamples(config_cls):+ assert config_cls().nsamples is None+ assert config_cls(nsamples=16).nsamples == 16++[email protected]("config_cls", [QuantizationConfig, SignRoundConfig, QADConfig, QATConfig])[email protected]("value", [0, -1, True, 1.5, "16"])+def test_invalid_nsamples(config_cls, value):+ with pytest.raises(ValueError, match="nsamples.*positive integer"):+ config_cls(nsamples=value)+++def test_legacy_qad_nsamples_keyword():+ config = QADConfig(qad_nsamples=16)+ assert config.nsamples == 16+ assert "qad_nsamples" not in vars(config)+ assert QADConfig(nsamples=16, qad_nsamples=16).nsamples == 16+ with pytest.raises(ValueError, match="must agree"):+ QADConfig(nsamples=8, qad_nsamples=16)+ with pytest.raises(ValueError, match="nsamples.*positive integer"):+ QADConfig(qad_nsamples=0)++[email protected]("algorithm", ["qad", "qat", "sign_round,qad"])[email protected]("target", [None, 32])+def test_qad_cli_maps_to_algorithm_nsamples(algorithm, target):+ parser = argparse.ArgumentParser()+ parser.add_argument("--nsamples", type=int, default=128)+ AlgorithmHandler.add_groups(parser)+ argv = ["--nsamples", "8"]+ if target is not None:+ argv.extend(["--qad_nsamples", str(target)])+ args = parser.parse_args(argv)+ args.algorithm = algorithm+ configs = AlgorithmHandler.build_configs(args, {})+ config = configs[-1]+ assert isinstance(config, QADConfig)+ assert config.nsamples == target+ assert args.nsamples == 8+ if len(configs) == 2:+ assert configs[0].nsamples is None+ registry = type(config).get_registered_args()+ parameter = next(p for p in registry.parameters if "--qad_nsamples" in p.option_strings)+ assert parameter.field == "nsamples"+++def test_nsamples_is_not_shared_or_synced():+ first, second = QADConfig(nsamples=8), QADConfig(nsamples=16)+ resolve_shared_config_values([first, second])+ assert (first.nsamples, second.nsamples) == (8, 16)+ unset = QADConfig()+ resolve_shared_config_values([first, unset])+ sync_shared_config_from(first, [unset, second])+ assert unset.nsamples is None+ assert second.nsamples == 16+++def test_warmup_keeps_common_sampling():+ composer = AlgorithmComposer([SignRoundConfig(), QADConfig(nsamples=16)])+ assert composer.quantizers[0].config.nsamples is None+ assert composer.block_quantizer.config.nsamples == 16+++def test_unsupported_block_sampling_fails_explicitly():+ with pytest.raises(NotImplementedError, match="only supported for whole-model tuning"):+ AlgorithmComposer([SignRoundConfig(nsamples=16)])+++def _resolve(target, cached, calibration):+ # This helper only needs the calibrator, not a loaded model or GPU state.+ quantizer = BaseQuantizer(QuantizationConfig(nsamples=target))+ return quantizer.get_calibration_token_ids(cached, calibration)++[email protected]("target", [None, 3])+def test_whole_model_reuses_cache(target):+ cached = [1, 2, 3]+ collect = Mock()+ assert _resolve(target, cached, SimpleNamespace(collect_token_ids=collect)) is cached+ collect.assert_not_called()+++def test_whole_model_slices_cache():+ cached = [1, 2, 3]+ collect = Mock()+ assert _resolve(2, cached, SimpleNamespace(collect_token_ids=collect)) == [1, 2]+ assert cached == [1, 2, 3]+ collect.assert_not_called()++[email protected]("cached", [None, [1]])+def test_whole_model_collects_tokens(cached):+ tokens = [1, 2, 3]+ collect = Mock(return_value=tokens)+ assert _resolve(3, cached, SimpleNamespace(collect_token_ids=collect)) is tokens+ collect.assert_called_once_with(3)++[email protected]("calibration", [SimpleNamespace(), SimpleNamespace(collect_token_ids=lambda n: [])])+def test_whole_model_collection_falls_back(calibration):+ cached = [1]+ assert _resolve(3, cached, calibration) is cacheddiff --git a/test/unit/test_cpu/algorithms/test_composer_stages.py b/test/unit/test_cpu/algorithms/test_composer_stages.pynew file mode 100644index 000000000..a005a61a7--- /dev/null+++ b/test/unit/test_cpu/algorithms/test_composer_stages.py@@ -0,0 +1,211 @@+# Copyright (c) 2026 Intel Corporation+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.++from types import SimpleNamespace+from unittest.mock import Mock++import pytest+import torch++from auto_round.algorithms.composer import AlgorithmComposer+from auto_round.algorithms.quantization.qad.config import QADConfig+from auto_round.algorithms.quantization.sign_round.config import SignRoundConfig+from auto_round.wrapper import preserve_original_weights+++def _pipeline(configs, monkeypatch):+ monkeypatch.delenv("AR_RESUME_DIR", raising=False)+ composer = AlgorithmComposer(configs)+ model = torch.nn.Sequential(torch.nn.Linear(2, 2, bias=False, dtype=torch.bfloat16))+ model.requires_grad_(False)+ composer._orchestrator = SimpleNamespace(+ model_context=SimpleNamespace(model=model),+ compress_context=SimpleNamespace(is_immediate_saving=False, is_immediate_packing=False),+ calibration=SimpleNamespace(nsamples=3),+ _reload_model_for_tuning=Mock(),+ )+ return composer, model+++def test_three_stages_preserve_original_bf16_without_algorithm_hooks(monkeypatch):+ composer, model = _pipeline([SignRoundConfig(), SignRoundConfig(), QADConfig(nsamples=2)], monkeypatch)+ original = model[0].weight.detach().clone()+ block_calls, output_values = [], []++ def run_blocks(replay):+ block_calls.append((composer.block_quantizer, replay))+ torch.testing.assert_close(model[0].weight, original)++ def tune():+ with torch.no_grad():+ model[0].weight.fill_(3)+ return {}++ composer._run_tuning(model, tune, lambda module: output_values.append(module[0].weight.clone()))+ torch.testing.assert_close(model[0].weight, original)++ def tune_model(module, tokens, device=None):+ torch.testing.assert_close(module[0].weight, original)+ assert tokens == [1, 2]+ with torch.no_grad():+ module[0].weight.fill_(7)+ return {}++ composer.quantizers[-1].quantize_model = Mock(side_effect=tune_model)+ assert composer.compress_model([1, 2, 3], run_blocks) is True+ assert [q for q, _ in block_calls] == list(composer.quantizers[:2])+ assert [replay for _, replay in block_calls] == [False, True]+ assert len(output_values) == 2+ assert all(torch.all(value == 3) for value in output_values)+ assert torch.all(model[0].weight == 7)+ assert model[0].weight.dtype == torch.bfloat16+ assert composer._preserve_weights is False+ composer._orchestrator._reload_model_for_tuning.assert_called_once()+ for quantizer in composer.quantizers:+ assert not hasattr(quantizer, "begin_stage")+ assert not hasattr(quantizer, "end_stage")+ assert not hasattr(quantizer, "warm_start_collect")+++def test_block_stages_consume_previous_weights_when_originals_not_required(monkeypatch):+ composer, model = _pipeline([SignRoundConfig(), SignRoundConfig()], monkeypatch)+ original = model[0].weight.detach().clone()+ seen = []++ def run_blocks(replay):+ seen.append((replay, model[0].weight.detach().clone()))++ def tune():+ with torch.no_grad():+ model[0].weight.add_(1)+ return {}++ composer._run_tuning(model, tune)++ assert composer.compress_model([1], run_blocks) is False+ torch.testing.assert_close(seen[0][1], original)+ torch.testing.assert_close(seen[1][1], original + 1)+ torch.testing.assert_close(model[0].weight, original + 2)+++def test_stage_failure_restores_weights_and_composer(monkeypatch):+ composer, model = _pipeline([SignRoundConfig(), QADConfig()], monkeypatch)+ terminal = composer.block_quantizer+ original_layer = model[0]+ original = original_layer.weight.detach().clone()+ for quantizer in composer.quantizers:+ quantizer.finalize_run = Mock()++ def run_blocks(replay):+ def tune():+ with torch.no_grad():+ original_layer.weight.fill_(5)+ model[0] = torch.nn.Identity()+ raise RuntimeError("tuning failed")++ composer._run_tuning(model, tune)++ with pytest.raises(RuntimeError, match="tuning failed"):+ composer.compress_model([1], run_blocks)+ assert model[0] is original_layer+ torch.testing.assert_close(model[0].weight, original)+ assert composer.block_quantizer is terminal+ assert composer._preserve_weights is False+ for quantizer in composer.quantizers:+ quantizer.finalize_run.assert_called_once()+++def test_weight_preservation_restores_dtype_and_requires_grad():+ model = torch.nn.Linear(2, 2, dtype=torch.bfloat16)+ original = model.weight.detach().clone()+ with preserve_original_weights(model):+ model.weight.data = torch.zeros_like(model.weight, dtype=torch.float32)+ model.weight.requires_grad_(False)+ torch.testing.assert_close(model.weight, original)+ assert model.weight.dtype == torch.bfloat16+ assert model.weight.requires_grad++[email protected]("option", ["is_immediate_saving", "is_immediate_packing"])+def test_multi_stage_streaming_rejected_before_tuning(monkeypatch, option):+ composer, _ = _pipeline([SignRoundConfig(), QADConfig()], monkeypatch)+ setattr(composer._orchestrator.compress_context, option, True)+ run_blocks = Mock()+ with pytest.raises(NotImplementedError, match="immediate saving/packing"):+ composer.compress_model([1], run_blocks)+ run_blocks.assert_not_called()+++def test_multi_stage_resume_rejected_before_tuning(monkeypatch):+ composer, _ = _pipeline([SignRoundConfig(), QADConfig()], monkeypatch)+ monkeypatch.setenv("AR_RESUME_DIR", "unused-resume-dir")+ run_blocks = Mock()+ with pytest.raises(NotImplementedError, match="Resuming a multi-stage"):+ composer.compress_model([1], run_blocks)+ run_blocks.assert_not_called()++[email protected]("block_stages", [1, 2])+def test_tiny_model_block_to_model_tuning_without_downloads(monkeypatch, block_stages):+ from tokenizers import Tokenizer, models+ from transformers import LlamaConfig, LlamaForCausalLM, PreTrainedTokenizerFast++ from auto_round import AutoRound+ from auto_round.algorithms.quantization.qat.config import QATConfig++ monkeypatch.delenv("AR_RESUME_DIR", raising=False)+ torch.manual_seed(42)+ config = LlamaConfig(+ vocab_size=32,+ hidden_size=32,+ intermediate_size=64,+ num_hidden_layers=1,+ num_attention_heads=2,+ num_key_value_heads=2,+ max_position_embeddings=16,+ )+ config._attn_implementation = "eager"+ model = LlamaForCausalLM(config).to(torch.bfloat16).eval()+ original_weight = model.model.layers[0].self_attn.q_proj.weight.detach().clone()+ vocab = {"<pad>": 0, "<s>": 1, "</s>": 2, "<unk>": 3, **{str(i): i for i in range(4, 32)}}+ tokenizer = PreTrainedTokenizerFast(+ tokenizer_object=Tokenizer(models.WordLevel(vocab, unk_token="<unk>")),+ pad_token="<pad>",+ bos_token="<s>",+ eos_token="</s>",+ unk_token="<unk>",+ )+ tokens = torch.randint(3, 32, (3, 8))+ dataset = torch.utils.data.DataLoader(tokens, batch_size=1)+ algorithms = [SignRoundConfig(iters=1, bits=4, group_size=8) for _ in range(block_stages)]+ algorithms.append(QATConfig(iters=1, bits=4, group_size=8, nsamples=3, gradient_checkpointing=False))+ compressor = AutoRound(+ model,+ tokenizer=tokenizer,+ alg_configs=algorithms,+ dataset=dataset,+ nsamples=2,+ seqlen=8,+ batch_size=1,+ device_map="cpu",+ low_cpu_mem_usage=False,+ enable_torch_compile=False,+ )+ quantized, layer_config = compressor.quantize()+ assert quantized is model+ assert layer_config+ assert not torch.equal(model.model.layers[0].self_attn.q_proj.weight, original_weight)+ assert all(not hasattr(module, "orig_layer") for module in model.modules())+ with torch.no_grad():+ assert torch.isfinite(model(input_ids=tokens[:1]).logits).all()diff --git a/test/unit/test_cpu/algorithms/test_lfq_loss.py b/test/unit/test_cpu/algorithms/test_lfq.pysimilarity index 50%rename from test/unit/test_cpu/algorithms/test_lfq_loss.pyrename to test/unit/test_cpu/algorithms/test_lfq.pyindex a61b77470..14f88e5c3 100644--- a/test/unit/test_cpu/algorithms/test_lfq_loss.py+++ b/test/unit/test_cpu/algorithms/test_lfq.py@@ -12,7 +12,7 @@# See the License for the specific language governing permissions and# limitations under the License.-"""CPU tests for the LFQ memory-efficient soft cross-entropy.+"""CPU tests for the LFQ mixin and memory-efficient soft cross-entropy.The custom ``torch.autograd.Function`` behind ``soft_cross_entropy`` relies onan analytic backward, row chunking, and valid-row normalization, so these tests@@ -25,10 +25,13 @@ implementation across the tricky cases:* 3-D ``[batch, seq, vocab]`` inputs that get flattened internally."""+from types import SimpleNamespace+import pytestimport torch-from auto_round.algorithms.quantization.sign_round.lfq_loss import soft_cross_entropy+from auto_round.algorithms.quantization.sign_round.lfq import LFQMixin, soft_cross_entropy+from auto_round.algorithms.quantization.sign_round.quantizer import SignRoundQuantizerdef _reference_soft_ce(q_logits, fp_logits, valid_mask=None):@@ -136,3 +139,131 @@ def test_soft_ce_matches_hard_onehot_reference():loss = soft_cross_entropy(q, fp, None, chunk_elems=1 << 23)ref = torch.nn.functional.cross_entropy(q.double(), labels, reduction="mean")assert torch.allclose(loss.double(), ref.double(), atol=1e-5, rtol=1e-4)+++def lfq():+ """Tiny standalone LFQ host, without model downloads or quantizer setup."""+ torch.manual_seed(6)+ host = LFQMixin()+ host.model = SimpleNamespace(+ model=SimpleNamespace(norm=torch.nn.LayerNorm(4)),+ lm_head=torch.nn.Linear(4, 8, bias=False),+ )+ for module in (host.model.model.norm, host.model.lm_head):+ module.requires_grad_(False)+ host.enable_lfq = True+ host.enable_qad = False+ host.lfq_loss_type = "ce"+ host.lfq_top_k = 3+ host.lfq_temperature = 1.5+ host.lfq_num_blocks = 2+ return host+++def test_quantizer_inherits_lfq_methods():+ assert issubclass(SignRoundQuantizer, LFQMixin)+ for name in (+ "_init_lm_components",+ "_is_text_decoder_block",+ "_lfq_is_kd_block",+ "_get_lfq_downstream_blocks",+ "_forward_lfq_downstream",+ "_lfq_logits",+ "lfq_loss",+ "_decoupled_topk_kd_loss",+ ):+ assert name not in SignRoundQuantizer.__dict__+ assert getattr(SignRoundQuantizer, name) is getattr(LFQMixin, name)+++def test_lfq_logits_and_component_cache(lfq):+ hidden = torch.randn(2, 4, 4)+ expected = lfq.model.lm_head(lfq.model.model.norm(hidden))+ torch.testing.assert_close(lfq._lfq_logits(hidden), expected)+ assert lfq._post_block_modules == [lfq.model.model.norm]+ head = lfq._lm_head+ lfq.model.lm_head = torch.nn.Identity()+ lfq._init_lm_components()+ assert lfq._lm_head is head+++def test_lfq_opt_post_block_order(lfq):+ norm = torch.nn.LayerNorm(4)+ projection = torch.nn.Linear(4, 6, bias=False)+ head = torch.nn.Linear(6, 8, bias=False)+ lfq.model = SimpleNamespace(+ model=SimpleNamespace(decoder=SimpleNamespace(final_layer_norm=norm, project_out=projection)),+ lm_head=head,+ )+ hidden = torch.randn(2, 3, 4)+ torch.testing.assert_close(lfq._lfq_logits(hidden), head(projection(norm(hidden))))+ assert lfq._post_block_modules == [norm, projection]++[email protected]("loss_type", ["ce", "dtk", "rkl", "tk"])+def test_lfq_ce_and_missing_teacher_fallback(lfq, loss_type):+ lfq.lfq_loss_type = loss_type+ hidden = torch.randn(2, 4, 4, requires_grad=True)+ labels = torch.tensor([[1, 2, -100, 4], [3, 4, 5, 6]])+ logits = lfq._lfq_logits(hidden)+ expected = torch.nn.functional.cross_entropy(logits[:, :-1].reshape(-1, 8), labels[:, 1:].reshape(-1))+ loss = lfq.lfq_loss(hidden, labels)+ torch.testing.assert_close(loss, expected)+ loss.backward()+ assert hidden.grad is not None+ assert torch.isfinite(hidden.grad).all()++[email protected]("loss_type", ["dtk", "rkl", "tk"])[email protected]("all_masked", [False, True])+def test_lfq_kd_gradient_and_mask(lfq, loss_type, all_masked):+ lfq.lfq_loss_type = loss_type+ student = torch.randn(2, 4, 4, requires_grad=True)+ teacher = torch.randn(2, 4, 4, requires_grad=True)+ labels = torch.full((2, 4), -100) if all_masked else torch.tensor([[1, 2, -100, 4], [3, 4, 5, 6]])+ loss = lfq.lfq_loss(student, labels, teacher_hidden_state=teacher, sample_indices=[0, 1])+ assert torch.isfinite(loss)+ loss.backward()+ assert student.grad is not None+ assert torch.isfinite(student.grad).all()+ assert teacher.grad is None+ if all_masked:+ assert loss.item() == 0.0+ assert torch.count_nonzero(student.grad) == 0+ else:+ assert torch.count_nonzero(student.grad) > 0+++ "enabled,qad,name,index,expected",+ [+ (False, False, "model.layers.3", 3, False),+ (True, False, "model.layers.1", 1, False),+ (True, False, "model.layers.2", 2, True),+ (True, False, "model.layers.3", 3, True),+ (True, False, "vision.layers.3", 3, False),+ (True, True, "model.layers.0", 0, True),+ (True, True, "audio.layers.3", 3, False),+ ],+)+def test_lfq_block_selection(lfq, enabled, qad, name, index, expected):+ lfq.enable_lfq = enabled+ lfq.enable_qad = qad+ block_ctx = SimpleNamespace(block_name=name, block_index=index, block_cnt=4)+ assert lfq._lfq_is_kd_block(block_ctx) is expected+++def test_lfq_downstream_empty_passthrough(lfq):+ hidden = torch.randn(1, 3, 4, requires_grad=True)+ assert lfq._forward_lfq_downstream(hidden, [], None, {}, [0], "cpu") is hidden+++def test_quantizer_finalize_clears_lfq_cache():+ quantizer = SignRoundQuantizer.__new__(SignRoundQuantizer)+ for name in ("_cached_valid_token_mask", "_lm_head", "_post_block_modules"):+ setattr(quantizer, name, object())+ quantizer.finalize_run()+ for name in ("_cached_valid_token_mask", "_lm_head", "_post_block_modules"):+ assert not hasattr(quantizer, name)+ quantizer.finalize_run()diff --git a/test/unit/test_cpu/algorithms/test_qad_act_quant.py b/test/unit/test_cpu/algorithms/test_qad_act_quant.pynew file mode 100644index 000000000..febc6308f--- /dev/null+++ b/test/unit/test_cpu/algorithms/test_qad_act_quant.py@@ -0,0 +1,237 @@+# Copyright (c) 2026 Intel Corporation+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.++"""Offline CPU regressions for QAD with activation quantization."""++from types import SimpleNamespace++import pytest+import torch++from auto_round import envs+from auto_round.algorithms.composer import AlgorithmComposer+from auto_round.algorithms.quantization.qad.config import QADConfig+from auto_round.algorithms.quantization.qad.quantizer import QADQuantizer+from auto_round.algorithms.quantization.sign_roundv2.quantizer import SignRoundOptimizedWrapperLinear+from auto_round.schemes import PRESET_SCHEMES+from auto_round.wrapper import WrapperLinear, WrapperWALayer, store_warm_start_params_and_unwrap+++def _linear(scheme):+ layer = torch.nn.Linear(32, 32, bias=False)+ for key, value in PRESET_SCHEMES[scheme].to_dict().items():+ if value is not None:+ setattr(layer, key, value)+ layer.scale_dtype = torch.float32+ layer.requires_grad_(False)+ return layer+++def _wrap(layer, cls=WrapperLinear):+ return cls(layer, enable_torch_compile=False, device="cpu")++[email protected]("scheme", ["MXFP4", "FP8_STATIC"])[email protected]("env_scale", [1.0, 0.75])+def test_finalize_restores_best_activation_scales(monkeypatch, scheme, env_scale):+ monkeypatch.setattr(envs, "AR_ENABLE_ACT_MINMAX_TUNING", True)+ monkeypatch.setattr(envs, "AR_ACT_SCALE", env_scale)+ torch.manual_seed(42)+ layer = _linear(scheme)+ if scheme == "FP8_STATIC":+ layer.act_max = torch.tensor([10.0])+ wrapper = _wrap(layer)+ inputs = torch.randn(2, 32)+ with torch.no_grad():+ wrapper.act_min_scale.fill_(0.6)+ wrapper.act_max_scale.fill_(0.5)+ best = {key: value.detach().clone() for key, value in wrapper.params.items()}+ expected = wrapper(inputs).clone()+ _, expected_scale, _ = wrapper._qdq_act(+ inputs, wrapper.act_min_scale, wrapper.act_max_scale, getattr(layer, "act_max", None)+ )+ wrapper.act_min_scale.fill_(1.0)+ wrapper.act_max_scale.fill_(1.0)+ finalized = wrapper.unwrapper(best)++ torch.testing.assert_close(finalized(inputs), expected)+ assert finalized.orig_layer.act_min_scale.item() == pytest.approx(0.6)+ assert finalized.orig_layer.act_max_scale.item() == pytest.approx(0.5)+ assert not finalized.orig_layer.act_max_scale.requires_grad+ if scheme == "FP8_STATIC":+ torch.testing.assert_close(layer.act_scale, expected_scale)+ torch.testing.assert_close(layer.act_max, torch.tensor([10.0]))++[email protected]("scheme", ["NVFP4", "NVFP4_E5M3_GS"])[email protected]("fixed_global_scale", [False, True])+def test_nvfp_finalized_qdq_matches_training(scheme, fixed_global_scale):+ torch.manual_seed(42)+ layer = _linear(scheme)+ layer.act_max = torch.tensor([100.0])+ if fixed_global_scale:+ layer.input_global_scale = torch.tensor([26.88])+ wrapper = _wrap(layer)+ inputs = torch.randn(2, 32)+ with torch.no_grad():+ expected = wrapper(inputs).clone()+ finalized = wrapper.unwrapper({})+ torch.testing.assert_close(finalized(inputs), expected)++[email protected]("wrapper_cls", [WrapperLinear, SignRoundOptimizedWrapperLinear])[email protected]("scheme", ["MXFP4", "NVFP4"])+def test_activation_warm_start(monkeypatch, wrapper_cls, scheme):+ monkeypatch.setattr(envs, "AR_ENABLE_ACT_MINMAX_TUNING", True)+ torch.manual_seed(42)+ layer = _linear(scheme)+ layer.act_max = torch.tensor([100.0])+ layer.input_global_scale = torch.tensor([26.88])+ wrapper = _wrap(layer, wrapper_cls)+ best = {key: value.detach().clone() for key, value in wrapper.params.items()}+ best["act_min_scale"].fill_(0.6)+ best["act_max_scale"].fill_(0.5)+ block = torch.nn.Sequential(wrapper)+ store_warm_start_params_and_unwrap(block, {"0": best})+ resumed = _wrap(block[0], wrapper_cls)+ torch.testing.assert_close(resumed.act_min_scale, best["act_min_scale"])+ torch.testing.assert_close(resumed.act_max_scale, best["act_max_scale"])+ torch.testing.assert_close(layer.act_max, torch.tensor([100.0]))+ torch.testing.assert_close(resumed.input_global_scale, layer.input_global_scale)+++class _TinyLM(torch.nn.Module):+ def __init__(self, scheme):+ super().__init__()+ self.config = SimpleNamespace(vocab_size=32)+ self.embedding = torch.nn.Embedding(32, 32)+ self.first = _linear(scheme)+ self.second = _linear(scheme)+ self.requires_grad_(False)++ def forward(self, input_ids, **kwargs):+ hidden = self.first(self.embedding(input_ids))+ return SimpleNamespace(logits=self.second(hidden))+++def _quantizer(tmp_path, use_teacher=False):+ quantizer = QADQuantizer(+ QADConfig(+ iters=2,+ lr=0.01,+ topk=8,+ qad_workspace=str(tmp_path),+ qad_kd_weight=1 if use_teacher else 0,+ qad_ce_weight=0 if use_teacher else 1,+ gradient_checkpointing=False,+ )+ )+ quantizer.bind(+ SimpleNamespace(+ model_context=SimpleNamespace(amp=False),+ compress_context=SimpleNamespace(enable_torch_compile=False),+ calibration_context=SimpleNamespace(batch_size=1),+ )+ )+ quantizer._get_scaler = lambda: None+ return quantizer++[email protected]("scheme", ["MXFP4", "NVFP4", "NVFP4_E5M3_GS", "FP8_STATIC"])[email protected]("teacher_cache", ["disabled", "cold", "warm"])+def test_whole_model_activation_calibration(tmp_path, scheme, teacher_cache):+ torch.manual_seed(42)+ model = _TinyLM(scheme)+ quantizer = _quantizer(tmp_path, teacher_cache != "disabled")+ token_ids = [torch.tensor([1, 2, 3, 4]), torch.tensor([4, 3, 2, -100])]+ if teacher_cache == "warm":+ # All samples are already cached: calibration must not depend on cache misses.+ quantizer._build_teacher_cache_from_model(model, token_ids, "cpu")+ gradients = []++ def backward(scaler, loss):+ loss.backward()+ gradients.append([model.first.value.grad.abs().sum().item(), model.second.value.grad.abs().sum().item()])++ quantizer._scale_loss_and_backward = backward+ composer = object.__new__(AlgorithmComposer)+ composer._run_tuning(model, lambda: quantizer.quantize_model(model, token_ids, device="cpu"))+ assert gradients and all(first > 0 and second > 0 for first, second in gradients)+ for layer in (model.first, model.second):+ assert isinstance(layer, WrapperWALayer)+ assert not layer.orig_layer._forward_hooks+ if scheme == "MXFP4":+ assert not hasattr(layer.orig_layer, "act_max")+ else:+ assert torch.isfinite(layer.orig_layer.act_max).all()+ assert layer.orig_layer.act_max.numel() == 1+ assert layer.orig_layer.act_max.item() > 0+ if scheme.startswith("NVFP4"):+ from auto_round.data_type.nvfp import calculate_gparam_by_dtype++ # The NVFP exporter can now derive its required static input scale.+ original = layer.orig_layer+ scale = calculate_gparam_by_dtype(original.act_max, original.act_data_type, original.act_group_size)+ assert torch.isfinite(scale).all() and (scale > 0).all()++ if scheme.startswith("NVFP4"):+ from auto_round.export.export_to_autoround.export_to_nvfp_mx import pack_layer++ for name in ("first", "second"):+ original = getattr(model, name).orig_layer+ expected_scale = calculate_gparam_by_dtype(+ original.act_max, original.act_data_type, original.act_group_size+ )+ pack_layer(name, model, backend=None, device="cpu")+ torch.testing.assert_close(getattr(model, name).input_global_scale.reshape(-1), expected_scale.reshape(-1))+++def test_calibration_prepares_fused_nvfp_scales(tmp_path, monkeypatch):+ monkeypatch.setattr(envs, "AR_NVFP4_FUSED_LAYER_GLOBAL_SCALE", True)+ model = torch.nn.Module()+ for name in ("q_proj", "k_proj", "v_proj"):+ setattr(model, name, _linear("NVFP4"))+ with torch.no_grad():+ model.q_proj.weight.fill_(0.1)+ model.k_proj.weight.fill_(0.2)+ model.v_proj.weight.fill_(0.4)+ quantizer = _quantizer(tmp_path)++ def forward(module, *args):+ inputs = torch.ones(1, 32)+ for name in ("q_proj", "k_proj", "v_proj"):+ getattr(module, name)(inputs)++ monkeypatch.setattr(quantizer, "_forward_logits", forward)+ quantizer._calibrate_activations(model, [torch.tensor([1, 2])], "cpu")+ for projection in (model.q_proj, model.k_proj, model.v_proj):+ torch.testing.assert_close(projection.weight_global_scale, model.v_proj.weight_global_scale)+ torch.testing.assert_close(projection.act_max, torch.ones(1))+++def test_calibration_removes_hooks_on_failure(tmp_path, monkeypatch):+ model = _TinyLM("NVFP4")+ model.train()+ quantizer = _quantizer(tmp_path)++ def fail_forward(*args):+ assert model.first._forward_hooks+ raise RuntimeError("calibration failed")++ monkeypatch.setattr(quantizer, "_forward_logits", fail_forward)+ with pytest.raises(RuntimeError, match="calibration failed"):+ quantizer._calibrate_activations(model, [torch.tensor([1, 2])], "cpu")+ assert model.training+ assert not model.first._forward_hooks+ assert not model.second._forward_hooksdiff --git a/test/unit/test_cpu/algorithms/test_qad_numerics_and_lifecycle.py b/test/unit/test_cpu/algorithms/test_qad_numerics_and_lifecycle.pynew file mode 100644index 000000000..5cb7a17d8--- /dev/null+++ b/test/unit/test_cpu/algorithms/test_qad_numerics_and_lifecycle.py@@ -0,0 +1,240 @@+# Copyright (c) 2026 Intel Corporation+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.++"""Offline QAD numerical stability and cache/wrapper lifecycle regressions."""++from concurrent.futures import ThreadPoolExecutor+from types import SimpleNamespace+from unittest.mock import Mock++import pytest+import torch+import torch.nn.functional as F+from filelock import Timeout++from auto_round.algorithms.quantization.qad.config import QADConfig+from auto_round.algorithms.quantization.qad.quantizer import QADQuantizer, _QADDistillLoss+from auto_round.algorithms.quantization.qad.teacher_cache import TeacherTopKCache+from auto_round.algorithms.quantization.sign_round.lfq import LFQMixin+from auto_round.wrapper import WrapperLinear, WrapperWALayer, store_warm_start_params_and_unwrap+++def test_full_vocabulary_fp16_targets_are_shift_invariant():+ target = torch.full((1, 2, 3), 1 / 3, dtype=torch.float16)+ assert target.float().sum(-1)[0, 0] != 1+ labels = torch.tensor([[1, 2]])+ losses, gradients = [], []+ for offset in (0.0, 16.0):+ logits = torch.full((1, 2, 3), offset, requires_grad=True)+ loss = _QADDistillLoss.apply(logits, None, target, labels, 1.0, 1e-6, 2)+ loss.backward()+ losses.append(loss.detach())+ gradients.append(logits.grad)+ torch.testing.assert_close(losses[0], losses[1], atol=1e-5, rtol=0)+ torch.testing.assert_close(losses[0], torch.tensor(0.0), atol=1e-6, rtol=0)+ torch.testing.assert_close(gradients[0], gradients[1], atol=2e-6, rtol=0)+ torch.testing.assert_close(gradients[0].sum(-1), torch.zeros(1, 2), atol=1e-6, rtol=0)++[email protected]("dtype", [torch.float16, torch.bfloat16])[email protected]("full_mode", [False, True])+def test_low_precision_gradient_is_cast_after_subtraction_and_scaling(dtype, full_mode):+ logits = torch.zeros(2, 2, 2, dtype=dtype, requires_grad=True)+ target = torch.tensor([0.5001, 0.4999]).expand(2, 2, 2).clone()+ indices = None if full_mode else torch.tensor([0, 1]).expand(2, 2, 2)+ labels = torch.tensor([[0, 1], [-100, -100]])+ loss = _QADDistillLoss.apply(logits, indices, target, labels, 1.0, 1e-6, 1)+ (loss * 1024).backward()+ reference = logits.detach().float().requires_grad_()+ expected_loss = F.kl_div(F.log_softmax(reference[0, 0], -1), target[0, 0], reduction="sum")+ (expected_loss * 1024).backward()+ torch.testing.assert_close(logits.grad, reference.grad.to(dtype), atol=1e-5, rtol=0.01)+ assert logits.grad[0, 0].abs().min() > 0+ assert torch.count_nonzero(logits.grad[1]) == 0+ assert torch.count_nonzero(logits.grad[:, 1]) == 0++[email protected]("dtype", [torch.float16, torch.bfloat16, torch.float32])+def test_fp_optimizer_masters_work_with_grad_scaler(dtype):+ param = torch.nn.Parameter(torch.tensor([1.0, -1.0], dtype=dtype))+ original = param.detach().clone()+ optimizer_params, pairs = QADQuantizer._prepare_fp_optimizer_params([param])+ assert optimizer_params[0].dtype == torch.float32+ optimizer = torch.optim.AdamW(optimizer_params, lr=0.01, weight_decay=0)+ scaler = torch.amp.GradScaler("cpu", init_scale=16)+ for _ in range(2):+ scaler.scale(param.float().square().sum()).backward()+ QADQuantizer._copy_fp_grads_to_masters(pairs)+ assert optimizer_params[0].grad.dtype == torch.float32+ scaler.step(optimizer)+ scaler.update()+ optimizer.zero_grad()+ QADQuantizer._copy_fp_masters_to_model(pairs)+ assert param.dtype == dtype+ assert not torch.equal(param, original)+ assert param.abs().max() < original.abs().max()+ if pairs:+ assert param.grad is None++[email protected]("hf_loss", [False, True])[email protected]("seqlen", [1, 3])+def test_all_ignored_ce_is_graph_connected_zero(hf_loss, seqlen):+ model = SimpleNamespace()+ if hf_loss:+ model.loss_function = Mock(side_effect=AssertionError("CE must not be called with no valid labels"))+ hidden = torch.randn(2, seqlen, 4, requires_grad=True)+ labels = torch.full((2, seqlen), -100)+ # Bind the lightweight loss harness without relying on a downloaded model.+ harness = SimpleNamespace(lfq_loss_type="ce", _lfq_logits=lambda hidden: hidden, model=model)+ loss = LFQMixin.lfq_loss(harness, hidden, labels)+ assert loss.item() == 0 and torch.isfinite(loss)+ loss.backward()+ torch.testing.assert_close(hidden.grad, torch.zeros_like(hidden))+ if hf_loss:+ model.loss_function.assert_not_called()+++def test_different_cache_signatures_do_not_invalidate_active_readers(tmp_path):+ cache = TeacherTopKCache(str(tmp_path), 2, signature={"teacher": "one"})+ ids = torch.tensor([1, 2])+ logits = torch.tensor([[3.0, 2.0, 1.0], [1.0, 2.0, 3.0]])+ try:+ cache.build_sample(0, ids, logits)+ cache.prefetch([0])+ with ThreadPoolExecutor(1) as executor:+ other = executor.submit(TeacherTopKCache, str(tmp_path), 2, signature={"teacher": "two"}).result()+ try:+ other.build_sample(0, ids, -logits)+ assert cache.workspace != other.workspace+ loaded_ids, index, probs = cache.load(0, "cpu")+ torch.testing.assert_close(loaded_ids, ids)+ torch.testing.assert_close(index, logits.topk(2).indices)+ torch.testing.assert_close(probs, logits.topk(2).values.softmax(-1))+ finally:+ other.shutdown()+ finally:+ cache.shutdown()+++def test_same_cache_signature_has_exclusive_lifecycle_lock(tmp_path):+ signature = {"teacher": "same"}+ cache = TeacherTopKCache(str(tmp_path), 2, signature=signature)+ try:+ with pytest.raises(Timeout):+ TeacherTopKCache(str(tmp_path), 2, signature=signature)+ cache.build_sample(0, torch.tensor([1, 2]), torch.randn(2, 3))+ cache.prefetch([0])+ finally:+ cache.shutdown()+ reopened = TeacherTopKCache(str(tmp_path), 2, signature=signature)+ try:+ assert reopened.exists(0)+ finally:+ reopened.shutdown()+++def test_cache_lock_released_when_qad_setup_fails(tmp_path, monkeypatch):+ quantizer = QADQuantizer(QADConfig(qad_workspace=str(tmp_path)))+ cache = TeacherTopKCache(str(tmp_path), 2, signature={"teacher": "one"})+ quantizer._teacher_cache = cache++ def fail(*args):+ raise RuntimeError("wrapper setup failed")++ monkeypatch.setattr(quantizer, "_quantize_model", fail)+ with pytest.raises(RuntimeError, match="wrapper setup failed"):+ quantizer.quantize_model(torch.nn.Linear(2, 2), [torch.tensor([1, 2])])+ reopened = TeacherTopKCache(str(tmp_path), 2, signature={"teacher": "one"})+ reopened.shutdown()+++def test_warm_start_skips_persistent_activation_wrapper():+ linear = torch.nn.Linear(4, 4).requires_grad_(False)+ for key, value in dict(bits=4, group_size=4, sym=True, data_type="int", act_bits=16).items():+ setattr(linear, key, value)+ linear.scale_dtype = torch.float32+ tuned = WrapperLinear(linear, enable_torch_compile=False)+ # A persistent QDQ wrapper has orig_layer, but no tuning params/unwrapper.+ persistent = object.__new__(WrapperWALayer)+ torch.nn.Module.__init__(persistent)+ persistent.orig_layer = torch.nn.Linear(4, 4)+ block = torch.nn.ModuleList([persistent, tuned])+ best = {"1": {key: value.detach().clone() for key, value in tuned.params.items()}}+ store_warm_start_params_and_unwrap(block, best)+ assert block[0] is persistent+ assert block[1] is linear+ assert "value" in linear._ar_warm_start++[email protected]("algorithm", ["qad", "qat", "rtn_qad"])+def test_whole_model_and_rtn_qad_without_downloads(tmp_path, monkeypatch, algorithm):+ from tokenizers import Tokenizer, models+ from transformers import LlamaConfig, LlamaForCausalLM, PreTrainedTokenizerFast++ from auto_round import AutoRound+ from auto_round.algorithms.quantization.qat.config import QATConfig+ from auto_round.algorithms.quantization.rtn.config import RTNConfig++ torch.manual_seed(42)+ config = LlamaConfig(+ vocab_size=32,+ hidden_size=32,+ intermediate_size=64,+ num_hidden_layers=1,+ num_attention_heads=2,+ num_key_value_heads=2,+ max_position_embeddings=16,+ )+ config._attn_implementation = "eager"+ model = LlamaForCausalLM(config).eval()+ original = model.model.layers[0].self_attn.q_proj.weight.detach().clone()+ vocab = {"<pad>": 0, "<s>": 1, "</s>": 2, "<unk>": 3, **{str(i): i for i in range(4, 32)}}+ tokenizer = PreTrainedTokenizerFast(+ tokenizer_object=Tokenizer(models.WordLevel(vocab, unk_token="<unk>")),+ pad_token="<pad>",+ bos_token="<s>",+ eos_token="</s>",+ unk_token="<unk>",+ )+ kwargs = dict(iters=2, bits=4, group_size=8, nsamples=2, gradient_checkpointing=False)+ configs = [QATConfig(**kwargs)] if algorithm == "qat" else [QADConfig(qad_workspace=str(tmp_path), **kwargs)]+ if algorithm == "rtn_qad":+ configs.insert(0, RTNConfig(bits=4, group_size=8, act_bits=8, act_data_type="int", act_dynamic=True))+ configs[-1].act_bits = 8+ configs[-1].act_data_type = "int"+ configs[-1].act_dynamic = True+ tokens = torch.randint(3, 32, (2, 4))+ compressor = AutoRound(+ model,+ tokenizer=tokenizer,+ alg_configs=configs,+ dataset=torch.utils.data.DataLoader(tokens, batch_size=1),+ nsamples=2,+ seqlen=4,+ batch_size=1,+ device_map="cpu",+ low_cpu_mem_usage=False,+ enable_torch_compile=False,+ )+ if algorithm != "rtn_qad":+ monkeypatch.setattr(compressor, "cache_data", Mock(side_effect=AssertionError("unused activation cache")))+ quantized, _ = compressor.quantize()+ assert quantized is model+ projection = model.model.layers[0].self_attn.q_proj+ assert not torch.equal(projection.weight, original)+ if algorithm != "rtn_qad":+ assert not compressor.inputs+ assert not compressor.calibration.inputs+ assert torch.isfinite(model(input_ids=tokens).logits).all()diff --git a/test/unit/test_cpu/algorithms/test_qad_review_regressions.py b/test/unit/test_cpu/algorithms/test_qad_review_regressions.pynew file mode 100644index 000000000..089ca6034--- /dev/null+++ b/test/unit/test_cpu/algorithms/test_qad_review_regressions.py@@ -0,0 +1,341 @@+# Copyright (c) 2026 Intel Corporation+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.++"""Offline regressions for QAD review findings and chained tuning state."""++import copy+from types import SimpleNamespace++import pytest+import torch+import torch.nn.functional as F+from transformers.models.llama.modeling_llama import LlamaRMSNorm++from auto_round import envs+from auto_round.algorithms.composer import AlgorithmComposer, BlockContext+from auto_round.algorithms.quantization.qad.config import QADConfig+from auto_round.algorithms.quantization.qad.quantizer import QADQuantizer+from auto_round.algorithms.quantization.sign_round.config import AdamRoundConfig, SignRoundConfig, SignRoundV2Config+from auto_round.algorithms.quantization.sign_round.quantizer import SignRoundQuantizer+from auto_round.algorithms.quantization.sign_roundv2.quantizer import SignRoundOptimizedWrapperLinear+from auto_round.calibration.llm import LLMCalibrator+from auto_round.wrapper import (+ preserve_original_weights,+ store_warm_start_params_and_unwrap,+ wrapper_block,+)++[email protected](autouse=True)+def _seed():+ torch.manual_seed(42)+++def _linear():+ layer = torch.nn.Linear(8, 8)+ for key, value in dict(bits=4, group_size=8, sym=True, data_type="int", act_bits=16).items():+ setattr(layer, key, value)+ layer.scale_dtype = torch.float32+ return layer+++class _TinyLM(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.config = SimpleNamespace(model_type="tiny", vocab_size=8, _name_or_path="same-checkpoint")+ self.embedding = torch.nn.Embedding(8, 8)+ self.proj = _linear()+ self.calls = []++ def forward(self, input_ids, attention_mask, **kwargs):+ self.calls.append((input_ids.detach().clone(), attention_mask.detach().clone()))+ # Context-dependent outputs expose corrupted internal EOS tokens.+ hidden = (self.embedding(input_ids) * attention_mask.unsqueeze(-1)).cumsum(dim=1)+ return SimpleNamespace(logits=self.proj(hidden))+++def _quantizer(tmp_path, **kwargs):+ config = QADConfig(iters=2, lr=0.01, gradient_checkpointing=False, qad_workspace=str(tmp_path), topk=3, **kwargs)+ quantizer = QADQuantizer(config)+ quantizer.bind(+ SimpleNamespace(+ model_context=SimpleNamespace(amp=False),+ compress_context=SimpleNamespace(enable_torch_compile=False),+ calibration_context=SimpleNamespace(batch_size=2, nsamples=2),+ )+ )+ quantizer._get_scaler = lambda: None+ return quantizer+++def _calibrator():+ calibrator = object.__new__(LLMCalibrator)+ calibrator.tokenizer = SimpleNamespace(pad_token_id=2, eos_token_id=2)+ return calibrator++[email protected]("last_padded", [False, True])+def test_original_context_is_independent_of_labels(tmp_path, last_padded):+ calibrator = _calibrator()+ ids = torch.tensor([[1, 2, 3, 2]])+ mask = torch.tensor([[1, 1, 1, 0 if last_padded else 1]])+ sample = calibrator._model_input_samples(ids, mask)[0]+ assert sample["labels"][0, 1] == 2 # Internal EOS is not padding.+ sample["labels"][0, 1] = -100 # Loss exclusion must not change context.+ quantizer = _quantizer(tmp_path)+ model = _TinyLM()+ expected = model(input_ids=ids, attention_mask=mask).logits+ inputs = quantizer._load_model_batch([0], [sample], "cpu")+ torch.testing.assert_close(quantizer._forward_logits(model, inputs, 8), expected)+ quantizer._build_teacher_cache_from_model(model, [sample], "cpu")+ labels, _, _ = quantizer._load_teacher_batch([0], "cpu")+ assert labels[0, 1] == -100+ torch.testing.assert_close(model.calls[-1][0], ids)+ torch.testing.assert_close(model.calls[-1][1], mask)+ quantizer._teacher_cache.shutdown()+++def test_collect_and_reuse_original_calibration_inputs(tmp_path):+ calibrator = _calibrator()+ ids = torch.tensor([[1, 2, 3, 2], [4, 2, 5, 2]])+ mask = torch.tensor([[1, 1, 1, 0], [1, 1, 1, 1]])+ calibrator.dataset = [{"input_ids": ids, "attention_mask": mask}]+ calibrator.seqlen = 4+ samples = calibrator.collect_token_ids(2, include_model_inputs=True)+ torch.testing.assert_close(torch.cat([sample["input_ids"] for sample in samples]), ids)+ torch.testing.assert_close(samples[0]["labels"], torch.tensor([[1, 2, 3, -100]]))+ calibrator.model_input_samples = samples+ quantizer = _quantizer(tmp_path)+ selected = quantizer.get_calibration_token_ids([sample["labels"] for sample in samples], calibrator)+ assert selected[0] is samples[0]+ # More samples than the common pool must use the same raw-input collection.+ calibrator.model_input_samples = samples[:1]+ quantizer.config.nsamples = 2+ selected = quantizer.get_calibration_token_ids([samples[0]["labels"]], calibrator)+ torch.testing.assert_close(selected[1]["attention_mask"], mask[1:])+++def test_block_calibration_does_not_mutate_whole_model_attention(tmp_path):+ calibrator = _calibrator()+ ids = torch.tensor([[1, 2, 3], [4, 2, 5]])+ original_mask = torch.ones_like(ids)+ data = {"input_ids": ids.clone(), "attention_mask": original_mask.clone()}+ calibrator.dataset = [data]+ calibrator.model = _TinyLM()+ calibrator.model.device = "cpu"+ calibrator.inputs = {}+ calibrator.batch_size = 2+ calibrator.seqlen = 3+ calibrator.calib(nsamples=1, bs=2)+ # Block caching forces a nontrivial final attention position; the dataset+ # and whole-model snapshot must retain the user's unmodified attention.+ assert calibrator.model.calls[-1][1][0, -1] == 0+ torch.testing.assert_close(data["attention_mask"], original_mask)+ torch.testing.assert_close(calibrator.model_input_samples[0]["attention_mask"], original_mask[:1])+ quantizer = _quantizer(tmp_path)+ quantizer.config.nsamples = 1+ selected = quantizer.get_calibration_token_ids(calibrator.inputs["input_ids"], calibrator)+ assert len(selected) == 1+ torch.testing.assert_close(selected[0]["labels"], ids[:1])+++def test_last_token_remains_a_next_token_target(tmp_path):+ calibrator = _calibrator()+ ids = torch.tensor([[1, 3]])+ labels = calibrator._mask_ids_for_loss(ids)+ torch.testing.assert_close(labels, ids)+ eos_ids = torch.tensor([[1, 2]])+ torch.testing.assert_close(calibrator._mask_ids_for_loss(eos_ids), eos_ids)+ logits = torch.randn(1, 2, 8, requires_grad=True)+ quantizer = _quantizer(tmp_path)+ loss = quantizer._qad_ce_loss(logits, labels)+ torch.testing.assert_close(loss, F.cross_entropy(logits[:, 0], ids[:, 1]))+ loss.backward()+ assert logits.grad[:, 0].abs().sum() > 0+ assert logits.grad[:, 1].abs().sum() == 0+ no_tokenizer = object.__new__(LLMCalibrator)+ no_tokenizer.tokenizer = None+ torch.testing.assert_close(no_tokenizer._mask_ids_for_loss(ids), ids)+ torch.testing.assert_close(+ no_tokenizer._mask_ids_for_loss(torch.tensor([[1, 3, 3, 3]])), torch.tensor([[1, 3, -100, -100]])+ )+++def test_custom_calibrator_requires_recoverable_inputs(tmp_path):+ quantizer = _quantizer(tmp_path)+ raw_ids = [torch.tensor([1, 2])]+ selected = quantizer.get_calibration_token_ids(raw_ids, SimpleNamespace())+ assert selected[0] is raw_ids[0]+ with pytest.raises(ValueError, match="original input_ids"):+ quantizer.get_calibration_token_ids([torch.tensor([1, -100])], SimpleNamespace())+ sample = _calibrator()._model_input_samples(torch.tensor([[1, 2]]))[0]+ assert quantizer.get_calibration_token_ids([sample], SimpleNamespace())[0] is sample+++def test_teacher_signature_includes_bfloat16_weights_and_scalar_buffers():+ model = _TinyLM().to(torch.bfloat16)+ model.register_buffer("counter", torch.tensor(0))+ ids = [torch.tensor([1, 2])]+ original = QADQuantizer._teacher_cache_signature(model, ids)+ model.counter.add_(1)+ assert original != QADQuantizer._teacher_cache_signature(model, ids)+++def test_teacher_cache_checks_actual_weights_and_masks(tmp_path):+ model = _TinyLM()+ sample = _calibrator()._model_input_samples(torch.tensor([[1, 2, 3]]))[0]+ quantizer = _quantizer(tmp_path)+ quantizer._build_teacher_cache_from_model(model, [sample], "cpu")+ assert len(model.calls) == 1+ quantizer._build_teacher_cache_from_model(model, [sample], "cpu")+ assert len(model.calls) == 1 # Identical weights/data safely reuse the cache.+ other = copy.deepcopy(model)+ other.calls = []+ with torch.no_grad():+ other.proj.weight.add_(0.25)+ quantizer._build_teacher_cache_from_model(other, [sample], "cpu")+ assert len(other.calls) == 1 # Same config/path, different in-memory teacher.+ with torch.no_grad():+ other.embedding.weight.add_(0.1)+ quantizer._build_teacher_cache_from_model(other, [sample], "cpu")+ assert len(other.calls) == 2 # Also revalidate a reused quantizer instance.+ sample["attention_mask"][0, 1] = 0+ quantizer._build_teacher_cache_from_model(other, [sample], "cpu")+ assert len(other.calls) == 3+ quantizer._teacher_cache.shutdown()++[email protected]("use_teacher", [False, True])[email protected]("tune_fp", [False, True])+def test_whole_model_freezes_base_and_clears_placement(tmp_path, use_teacher, tune_fp):+ model = _TinyLM()+ original_params = list(model.parameters())+ for module in model.modules():+ module.tuning_device = "cuda:7" # CPU test catches accidental use of stale metadata.+ for parameter in original_params:+ parameter.grad = torch.ones_like(parameter)+ quantizer = _quantizer(tmp_path, qad_kd_weight=int(use_teacher), qad_ce_weight=1, tune_non_quant_params=tune_fp)+ samples = _calibrator()._model_input_samples(torch.tensor([[1, 2, 3], [4, 2, 5]]))+ gradients = []++ def backward(scaler, loss):+ loss.backward()+ assert model.proj.value.grad is not None+ assert model.proj.orig_layer.weight.grad is None+ assert model.proj.orig_layer.bias.grad is None+ assert (model.embedding.weight.grad is not None) == tune_fp+ assert not any(hasattr(module, "tuning_device") for module in model.modules())+ gradients.append(model.proj.value.grad.abs().sum().item())++ quantizer._scale_loss_and_backward = backward+ composer = object.__new__(AlgorithmComposer)+ composer._run_tuning(model, lambda: quantizer.quantize_model(model, samples, device="cpu"))+ assert len(gradients) == 2 and all(value > 0 for value in gradients)+ assert not model.proj.weight.requires_grad+ assert model.embedding.weight.requires_grad == tune_fp+ assert all(2 in ids for ids, _ in model.calls)++[email protected]("config_cls", [SignRoundConfig, SignRoundV2Config, AdamRoundConfig])+def test_enable_qad_routes_to_whole_model(config_cls):+ composer = AlgorithmComposer([config_cls(enable_qad=True, iters=2, nblocks=1, lfq_top_k=5)])+ quantizer = composer.block_quantizer+ assert isinstance(quantizer, QADQuantizer)+ assert quantizer.whole_model_tuning+ assert quantizer.requires_original_weights+ assert quantizer.iters == 2+ assert quantizer.qad_top_k == 5++[email protected]("nblocks", [1, 2, 3])[email protected]("last_blocks", [1, 2, 3])+def test_lfq_uses_physical_group_endpoint(nblocks, last_blocks):+ quantizer = SignRoundQuantizer(SignRoundConfig(enable_lfq=True, lfq_num_blocks=last_blocks))+ names = [f"model.layers.{index}" for index in range(8)]+ starts = list(range(0, 8, nblocks))+ for start in starts:+ group = names[start : start + nblocks]+ ctx = BlockContext(+ model=torch.nn.Module(),+ block_names=group,+ block_name=group[0],+ block_index=start,+ block_cnt=len(starts),+ all_block_names=names,+ )+ assert quantizer._lfq_is_kd_block(ctx) == (min(start + nblocks, 8) > 8 - last_blocks)++[email protected]("topk", [-10, -2, 0])+def test_invalid_topk_rejected_immediately(topk):+ with pytest.raises(ValueError, match="topk"):+ QADConfig(topk=topk)++[email protected]("topk", [-1, 1, 32])+def test_valid_topk_accepted(topk):+ assert QADConfig(topk=topk).topk == topk++[email protected]("source_log,target_log", [(True, True), (False, True), (True, False)])+def test_log_minmax_warm_start_preserves_coefficients(monkeypatch, source_log, target_log):+ monkeypatch.setattr(envs, "AR_ENABLE_LOG_MINMAX", source_log)+ layer = _linear().requires_grad_(False)+ wrapped = SignRoundOptimizedWrapperLinear(layer, enable_torch_compile=False)+ best = {key: value.detach().clone() for key, value in wrapped.params.items()}+ best["min_scale"].fill_(-0.2 if source_log else 0.8)+ best["max_scale"].fill_(0.3 if source_log else 1.2)+ block = torch.nn.Sequential(wrapped)+ store_warm_start_params_and_unwrap(block, {"0": best})+ monkeypatch.setattr(envs, "AR_ENABLE_LOG_MINMAX", target_log)+ resumed = SignRoundOptimizedWrapperLinear(layer, enable_torch_compile=False)+ min_coeff, max_coeff = resumed._prepare_minmax_scale(resumed.min_scale, resumed.max_scale)+ for coefficient, key in [(min_coeff, "min_scale"), (max_coeff, "max_scale")]:+ expected = best[key].exp() if source_log else best[key]+ torch.testing.assert_close(coefficient, expected)+ torch.testing.assert_close(resumed.init_scale, wrapped.init_scale)++[email protected]("norm_cls", [torch.nn.LayerNorm, LlamaRMSNorm])+def test_bias_and_norm_warm_start_matches_previous_best_output(norm_cls):+ block = torch.nn.Sequential(_linear(), norm_cls(8)).requires_grad_(False)+ original = {key: value.clone() for key, value in block.state_dict().items()}+ inputs = torch.randn(2, 8)+ with preserve_original_weights(block):+ wrapper_block(block, True, True, enable_torch_compile=False)+ best = {}+ for name, wrapped in block.named_children():+ best[name] = {key: value.detach().clone() for key, value in wrapped.params.items()}+ for key, param in wrapped.params.items():+ if key in ("bias_v", "v"):+ best[name][key].fill_(0.2)+ with torch.no_grad():+ param.copy_(best[name][key])+ expected = block(inputs).detach()+ store_warm_start_params_and_unwrap(block, best)+ for key, value in block.state_dict().items():+ torch.testing.assert_close(value, original[key])+ wrapper_block(block, True, True, enable_torch_compile=False)+ torch.testing.assert_close(block[0].bias_v, best["0"]["bias_v"])+ torch.testing.assert_close(block[1].v, best["1"]["v"])+ torch.testing.assert_close(block(inputs), expected)+++def test_log_minmax_incompatible_warm_start_uses_identity(monkeypatch):+ monkeypatch.setattr(envs, "AR_ENABLE_LOG_MINMAX", True)+ layer = _linear().requires_grad_(False)+ layer._ar_warm_start = {"min_scale": torch.ones(3), "max_scale": torch.ones(3), "minmax_parameterization": "log"}+ resumed = SignRoundOptimizedWrapperLinear(layer, enable_torch_compile=False)+ torch.testing.assert_close(resumed.min_scale, torch.zeros_like(resumed.min_scale))+ torch.testing.assert_close(resumed.max_scale, torch.zeros_like(resumed.max_scale))diff --git a/test/unit/test_cpu/algorithms/test_qad_warm_start.py b/test/unit/test_cpu/algorithms/test_qad_warm_start.pynew file mode 100644index 000000000..18bc46ead--- /dev/null+++ b/test/unit/test_cpu/algorithms/test_qad_warm_start.py@@ -0,0 +1,212 @@+# Copyright (c) 2026 Intel Corporation+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.++"""CPU regressions for SignRound -> QAD state and output hand-off."""++from types import SimpleNamespace+from unittest.mock import Mock++import pytest+import torch++from auto_round.algorithms.composer import AlgorithmComposer, BlockContext+from auto_round.algorithms.quantization.qad.config import QADConfig+from auto_round.algorithms.quantization.qad.quantizer import QADQuantizer+from auto_round.algorithms.quantization.sign_roundv2.quantizer import SignRoundOptimizedWrapperLinear+from auto_round.wrapper import WrapperLinear, store_warm_start_params_and_unwrap, wrapper_block+++class _SnapshotLayer(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.orig_layer = torch.nn.Linear(1, 1, bias=False)+ self.orig_layer.requires_grad_(False)+ self.value = torch.nn.Parameter(torch.zeros(()))+ self.params = {"value": self.value}+++class _SnapshotModel(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.layer = _SnapshotLayer()+ self.fp = torch.nn.Parameter(torch.zeros(()))+ self.config = SimpleNamespace(vocab_size=2)++[email protected]("use_last", [False, True])[email protected]("tune_fp", [False, True])+def test_qad_snapshot_matches_measured_loss(monkeypatch, use_last, tune_fp):+ """Best loss is at the initial state; deliberately make each update worse."""+ model = _SnapshotModel()+ model.fp.requires_grad_(tune_fp)+ quantizer = QADQuantizer(+ QADConfig(+ iters=2,+ lr=0.1,+ qad_kd_weight=0,+ qad_ce_weight=1,+ gradient_checkpointing=False,+ tune_non_quant_params=tune_fp,+ not_use_best_mse=use_last,+ )+ )+ quantizer.bind(+ SimpleNamespace(+ model_context=SimpleNamespace(amp=False),+ compress_context=SimpleNamespace(enable_torch_compile=False),+ calibration_context=SimpleNamespace(batch_size=1),+ )+ )+ quantizer.wrapper_block = lambda *args, **kwargs: (["layer"], [])+ quantizer._forward_logits = lambda *args: model.layer.value + model.fp+ quantizer._qad_loss = lambda logits, *args: logits.square()+ quantizer._get_scaler = lambda: None+ quantizer._scale_loss_and_backward = lambda scaler, loss: loss.backward()+ snapshots = []++ def worsen_state(scaler, optimizer, schedule):+ with torch.no_grad():+ model.layer.value.add_(1)+ if tune_fp:+ model.fp.add_(1)++ def capture_unwrap(block, params):+ snapshots.append(params["layer"]["value"].clone())++ quantizer._step = worsen_state+ monkeypatch.setattr("auto_round.algorithms.composer.unwrapper_block", capture_unwrap)+ monkeypatch.setattr("auto_round.algorithms.quantization.qad.quantizer.clear_memory", lambda: None)+ composer = object.__new__(AlgorithmComposer)+ composer._run_tuning(+ model, lambda: quantizer.quantize_model(model, [torch.ones(2, dtype=torch.long)] * 2, device="cpu")+ )++ expected = 2.0 if use_last else 0.0+ assert model.layer.value.item() == 2.0 # Both optimizer steps actually ran.+ torch.testing.assert_close(snapshots[0], torch.tensor(expected))+ torch.testing.assert_close(model.fp, torch.tensor(expected if tune_fp else 0.0))+++def _make_linear():+ layer = torch.nn.Linear(64, 2, bias=False)+ with torch.no_grad():+ layer.weight.copy_(torch.linspace(-0.9, 1.0, 128).reshape(2, 64))+ layer.requires_grad_(False)+ layer.bits = 2+ layer.group_size = 64+ layer.sym = True+ layer.data_type = "int"+ layer.act_bits = 16+ layer.scale_dtype = torch.float32+ return layer+++def _wrap(layer, wrapper_cls):+ return wrapper_cls(layer, device="cpu", enable_torch_compile=False)++[email protected]("wrapper_cls", [WrapperLinear, SignRoundOptimizedWrapperLinear])[email protected]("output_dict", [False, True])+def test_warmup_propagates_best_quantized_output(monkeypatch, wrapper_cls, output_dict):+ """Propagate QDQ output, preserve FP reference/weights and the QAD init grid."""+ layer = _make_linear()+ block = torch.nn.Sequential(layer)+ fp_weight = layer.weight.detach().clone()+ inputs = [torch.linspace(-1, 2, 64).reshape(1, 64)]+ fp_output = layer(inputs[0]).detach()+ expected_outputs = []+ calls = []++ def forward(module, samples, others):+ calls.append(module[0])+ result = [module(sample) for sample in samples]+ forward.last_output_dict = {"hidden_states": result} if output_dict else None+ return result++ forward.last_output_dict = None++ def tune(module, *args, **kwargs):+ wrapped = _wrap(module[0], wrapper_cls)+ module[0] = wrapped+ best = {key: value.detach().clone() for key, value in wrapped.params.items()}+ best["value"].fill_(0.4)+ best["min_scale"].fill_(0.8)+ best["max_scale"].fill_(0.8)+ with torch.no_grad():+ for key, value in best.items():+ wrapped.params[key].copy_(value)+ expected_outputs.append(module(inputs[0]).detach())+ wrapped.value.fill_(-0.4) # Final iterate is deliberately not the best.+ return {"0": best}++ composer = object.__new__(AlgorithmComposer)+ composer._preserve_weights = True+ composer.block_forward = forward+ composer.block_quantizer = SimpleNamespace(+ enable_quanted_input=True,+ quantize_block=tune,+ finalize_block=Mock(),+ register_fp_input_forward_hooks=lambda block: [],+ register_qinput_forward_hooks=lambda block: [],+ )+ composer.preprocessors = []+ composer._rotation_members = []+ composer.scheme = None+ composer._get_fp_act_hooks = lambda block: []+ composer._get_q_act_hooks = lambda block: []+ monkeypatch.setattr("auto_round.algorithms.composer.clear_memory", lambda: None)+ ctx = BlockContext(model=block, block_names=["0"], block_name="0", block_index=0)+ quantized, reference = composer.compress_block(block, inputs, {}, ctx)++ q_result = quantized["hidden_states"] if output_dict else quantized+ fp_result = reference["hidden_states"] if output_dict else reference+ torch.testing.assert_close(q_result[0], expected_outputs[0])+ torch.testing.assert_close(fp_result[0], fp_output)+ assert not torch.allclose(q_result[0], fp_output)+ assert len(calls) == 2 # FP reference, then the still-wrapped best QDQ forward.+ assert isinstance(calls[1], wrapper_cls)+ assert block[0] is layer+ torch.testing.assert_close(layer.weight, fp_weight)+ torch.testing.assert_close(layer._ar_warm_start["value"], torch.full((2, 64), 0.4))++ # QAD re-wraps exactly these FP layers with the transferred best parameters.+ wrapper_block(block, True, False, enable_torch_compile=False, device="cpu")+ resumed = block[0]+ assert isinstance(resumed, wrapper_cls)+ with torch.no_grad():+ torch.testing.assert_close(resumed(inputs[0]), q_result[0])+ if wrapper_cls is SignRoundOptimizedWrapperLinear:+ torch.testing.assert_close(resumed.init_scale, layer._ar_warm_start["init_scale"])+++def test_warmup_restores_all_fp_layers_when_forward_raises():+ layers = [_make_linear(), _make_linear()]+ weights = [layer.weight.detach().clone() for layer in layers]+ block = torch.nn.ModuleList([_wrap(layer, WrapperLinear) for layer in layers])+ best = {+ name: {key: value.detach().clone() for key, value in module.params.items()}+ for name, module in block.named_children()+ }++ def fail_forward(module):+ assert all(isinstance(layer, WrapperLinear) for layer in module)+ raise RuntimeError("forward failed")++ with pytest.raises(RuntimeError, match="forward failed"):+ store_warm_start_params_and_unwrap(block, best, before_unwrap=fail_forward)++ for index, layer in enumerate(layers):+ assert block[index] is layer+ torch.testing.assert_close(layer.weight, weights[index])+ assert "value" in layer._ar_warm_startdiff --git a/test/unit/test_cuda/algorithms/test_qad_numerics.py b/test/unit/test_cuda/algorithms/test_qad_numerics.pynew file mode 100644index 000000000..ca7904846--- /dev/null+++ b/test/unit/test_cuda/algorithms/test_qad_numerics.py@@ -0,0 +1,98 @@+# Copyright (c) 2026 Intel Corporation+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.++"""CUDA regressions for QAD low-precision gradients and AMP master weights."""++from types import SimpleNamespace++import pytest+import torch+import torch.nn.functional as F++from auto_round.algorithms.composer import AlgorithmComposer+from auto_round.algorithms.quantization.qad import quantizer as qad_module+from auto_round.algorithms.quantization.qad.config import QADConfig++pytestmark = pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA required")++[email protected]("use_triton", [False, True])[email protected]("dtype", [torch.float16, torch.bfloat16])[email protected]("full_mode", [False, True])+def test_cuda_low_precision_gradient_matches_fp32(monkeypatch, use_triton, dtype, full_mode):+ if use_triton and not qad_module._HAS_TRITON:+ pytest.skip("Triton unavailable")+ if dtype == torch.bfloat16 and not torch.cuda.is_bf16_supported():+ pytest.skip("BF16 unavailable")+ monkeypatch.setattr(qad_module, "_HAS_TRITON", use_triton)+ logits = torch.zeros(2, 2, 2, dtype=dtype, device="cuda", requires_grad=True)+ target = torch.tensor([0.5001, 0.4999], device="cuda").expand(2, 2, 2).clone()+ indices = None if full_mode else torch.tensor([0, 1], device="cuda").expand(2, 2, 2)+ labels = torch.tensor([[0, 1], [-100, -100]], device="cuda")+ loss = qad_module._QADDistillLoss.apply(logits, indices, target, labels, 1.0, 1e-6, 1)+ (loss * 1024).backward()+ reference = logits.detach().float().requires_grad_()+ loss_ref = F.kl_div(F.log_softmax(reference[0, 0], -1), target[0, 0], reduction="sum")+ (loss_ref * 1024).backward()+ torch.testing.assert_close(logits.grad, reference.grad.to(dtype), atol=1e-5, rtol=0.01)+ assert logits.grad[0, 0].abs().min() > 0+++class _HalfLM(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.config = SimpleNamespace(vocab_size=8)+ self.embedding = torch.nn.Embedding(8, 8)+ self.proj = torch.nn.Linear(8, 8, bias=False)+ for key, value in dict(bits=4, group_size=8, sym=True, data_type="int", act_bits=16).items():+ setattr(self.proj, key, value)+ self.proj.scale_dtype = torch.float32++ def forward(self, input_ids, **kwargs):+ return SimpleNamespace(logits=self.proj(self.embedding(input_ids)))++[email protected]("use_teacher", [False, True])+def test_fp16_adamw_amp_whole_model_tuning(tmp_path, monkeypatch, use_teacher):+ torch.manual_seed(42)+ monkeypatch.setattr(qad_module, "device_manager", SimpleNamespace(device="cuda"))+ model = _HalfLM().to(device="cuda", dtype=torch.float16)+ original = model.embedding.weight.detach().clone()+ quantizer = qad_module.QADQuantizer(+ QADConfig(+ iters=2,+ lr=0.01,+ qad_optimizer="adamw",+ tune_non_quant_params=True,+ qad_kd_weight=int(use_teacher),+ qad_ce_weight=1,+ qad_workspace=str(tmp_path),+ topk=3,+ gradient_checkpointing=False,+ not_use_best_mse=True,+ )+ )+ quantizer.bind(+ SimpleNamespace(+ model_context=SimpleNamespace(amp=True),+ compress_context=SimpleNamespace(enable_torch_compile=False),+ calibration_context=SimpleNamespace(batch_size=1),+ )+ )+ samples = [torch.tensor([1, 2, 3]), torch.tensor([3, 2, 1])]+ composer = object.__new__(AlgorithmComposer)+ composer._run_tuning(model, lambda: quantizer.quantize_model(model, samples, device="cuda"))+ assert model.embedding.weight.dtype == torch.float16+ assert not torch.equal(model.embedding.weight, original)+ assert torch.isfinite(model.embedding.weight).all()