Skip to content

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

fix saving hadamard rotation model without rotation config. (#1933)

lkk6a2e5ad3e4f1
diff --git a/auto_round/algorithms/transforms/__init__.py b/auto_round/algorithms/transforms/__init__.py
index 17a64d993..7a28b480a 100644
--- a/auto_round/algorithms/transforms/__init__.py
+++ b/auto_round/algorithms/transforms/__init__.py
@@ -81,6 +81,7 @@ __all__ = [
"save_rotation_config",
"preregister_rotation_buffers",
"rebuild_rotation_if_needed",
+ "apply_rotation_hooks_from_config",
]
@@ -388,3 +389,66 @@ def rebuild_rotation_if_needed(model: torch.nn.Module) -> None:
except Exception as e:
_dispatch_logger.warning(f"Failed to rebuild {name} rotations: {e}")
return # Only one rotation method expected per model
+
+
+def apply_rotation_hooks_from_config(
+ model: torch.nn.Module,
+ quantization_config,
+) -> torch.nn.Module:
+ """Apply rotation forward hooks at inference time based on saved config.
+
+ Unified entry point that handles both Hadamard rotation (via
+ ``rotation_config`` key) and SerializerMixin-based methods like
+ SpinQuant (via ``preregister_rotation_buffers``).
+
+ Called from ``convert_hf_model()`` before weight loading.
+
+ Args:
+ model: The model being loaded.
+ quantization_config: The quantization config (dict or object) read
+ from ``config.json``.
+
+ Returns:
+ The model with rotation hooks applied.
+ """
+ from auto_round.utils import logger
+
+ logger.warning_once(
+ "Rotation transform is still in experimental stage and uses forward hooks for inference, "
+ "the inference speed might be slow."
+ )
+
+ # --- Hadamard rotation (rotation_config key) ---
+ rotation_config = (
+ quantization_config.get("rotation_config", None)
+ if isinstance(quantization_config, dict)
+ else getattr(quantization_config, "rotation_config", None)
+ )
+ if rotation_config:
+ data_type = (
+ quantization_config.get("data_type", "mx_fp")
+ if isinstance(quantization_config, dict)
+ else getattr(quantization_config, "data_type", "mx_fp")
+ )
+ from auto_round.algorithms.transforms.quarot.apply import apply_rotation_transform
+ from auto_round.algorithms.transforms.quarot.config import RotationConfig as _RC
+
+ cfg = _RC(
+ block_size=rotation_config["block_size"],
+ hadamard_type=rotation_config["hadamard_type"],
+ )
+ model = apply_rotation_transform(
+ model,
+ cfg,
+ location="input",
+ desc="Register pre forward hook for hadamard transform",
+ data_type=data_type,
+ )
+
+ # --- SerializerMixin-based methods (SpinQuant / QuaRot / future) ---
+ try:
+ preregister_rotation_buffers(model, quantization_config)
+ except Exception as e:
+ _dispatch_logger.warning(f"Failed to pre-register rotation buffers: {e}")
+
+ return model
diff --git a/auto_round/algorithms/transforms/quarot/apply.py b/auto_round/algorithms/transforms/quarot/apply.py
index 9656002cc..41402cd8a 100644
--- a/auto_round/algorithms/transforms/quarot/apply.py
+++ b/auto_round/algorithms/transforms/quarot/apply.py
@@ -21,16 +21,20 @@ Public entry points
from __future__ import annotations
+import json
+import os
from typing import Any
import torch
+import torch.nn as nn
import tqdm
-from auto_round.algorithms.transforms.base import BaseRotation
+from auto_round.algorithms.transforms.base import BaseRotation, SerializerMixin
from auto_round.algorithms.transforms.quarot.config import RotationConfig, normalize_rotation_config
from auto_round.algorithms.transforms.quarot.transforms import build_hadamard_transform
from auto_round.compressors.utils import is_nv_fp
from auto_round.experimental.qmodules.base import QModuleBase
+from auto_round.utils import logger
__all__ = ["HadamardRotation", "apply_rotation_transform"]
@@ -54,12 +58,15 @@ def _triton_available(data_type: str = "mx_fp") -> bool:
@BaseRotation.register("hadamard")
-class HadamardRotation(BaseRotation):
+class HadamardRotation(BaseRotation, SerializerMixin):
"""Hadamard rotation algorithm.
Registered under ``"hadamard"`` in the
:class:`~auto_round.algorithms.transforms.base.BaseRotation` registry.
+ Implements :class:`SerializerMixin` for save/load support — the config
+ is persisted under ``"rotation_config"`` in ``config.json``.
+
Typical usage (via the top-level helper)::
from auto_round.algorithms.transforms import apply_rotation
@@ -102,7 +109,7 @@ class HadamardRotation(BaseRotation):
**kwargs: Reserved for future use.
Returns:
- The mutated *model* with ``model.rotation_config`` set to the
+ The mutated *model* with ``model._rotation_config`` set to the
normalised :class:`RotationConfig` dict.
"""
cfg = self.config
@@ -136,7 +143,7 @@ class HadamardRotation(BaseRotation):
fuse_online_to_weight=fuse_online_to_weight,
compute_device=compute_device,
)
- setattr(model, "rotation_config", cfg.model_dump())
+ setattr(model, "_rotation_config", cfg)
return model
# backend == "transform": original per-Linear triton-fused path.
@@ -152,9 +159,78 @@ class HadamardRotation(BaseRotation):
_apply_to_module(model, module, cfg, location, data_type)
# Store config on model for serialisation / downstream inspection.
- setattr(model, "rotation_config", cfg.model_dump())
+ setattr(model, "_rotation_config", cfg)
return model
+ # ------------------------------------------------------------------
+ # SerializerMixin — Save side
+ # ------------------------------------------------------------------
+
+ def inject_buffers_on_layer(
+ self,
+ layer_name: str,
+ qlayer: nn.Module,
+ model: nn.Module,
+ ) -> None:
+ """No-op — Hadamard rotation does not use per-module buffers."""
+
+ def inject_buffers_bulk(
+ self,
+ model: nn.Module,
+ quantization_config: dict,
+ ) -> None:
+ """Write rotation_config into quantization_config for persistence."""
+ config = getattr(model, "_rotation_config", None)
+ if config is not None:
+ cfg_dict = config.model_dump() if hasattr(config, "model_dump") else dict(config)
+ quantization_config[self.config_key()] = cfg_dict
+
+ def save_config(self, model: nn.Module, save_dir: str) -> None:
+ """Persist rotation_config into config.json after model.save_pretrained()."""
+ config = getattr(model, "_rotation_config", None)
+ if config is None:
+ return
+
+ cfg_dict = config.model_dump() if hasattr(config, "model_dump") else dict(config)
+
+ config_path = os.path.join(save_dir, "config.json")
+ if not os.path.exists(config_path):
+ logger.warning(f"[Hadamard] config.json not found at {save_dir}, cannot save rotation_config")
+ return
+
+ with open(config_path, "r") as f:
+ model_config = json.load(f)
+
+ if "quantization_config" in model_config:
+ model_config["quantization_config"][self.config_key()] = cfg_dict
+ else:
+ model_config[self.config_key()] = cfg_dict
+
+ with open(config_path, "w") as f:
+ json.dump(model_config, f, indent=2)
+
+ logger.info(f"[Hadamard] Saved rotation_config to {config_path}")
+
+ # ------------------------------------------------------------------
+ # SerializerMixin — Load side
+ # ------------------------------------------------------------------
+
+ def preregister_buffers(self, model: nn.Module, config_dict: dict) -> int:
+ """No-op — Hadamard rotation does not use per-module buffers."""
+ return 0
+
+ def rebuild_online(self, model: nn.Module) -> nn.Module:
+ """No-op — Hadamard hooks are rebuilt via apply_rotation_hooks_from_config."""
+ return model
+
+ def has_rotation_buffers(self, module: nn.Module) -> bool:
+ """Hadamard rotation does not inject buffers into modules."""
+ return False
+
+ @classmethod
+ def config_key(cls) -> str:
+ return "rotation_config"
+
# ---------------------------------------------------------------------------
# Module-level application helper
diff --git a/auto_round/algorithms/transforms/quarot/dispatcher.py b/auto_round/algorithms/transforms/quarot/dispatcher.py
index ae4d6c2e4..b5c1b090e 100644
--- a/auto_round/algorithms/transforms/quarot/dispatcher.py
+++ b/auto_round/algorithms/transforms/quarot/dispatcher.py
@@ -104,7 +104,7 @@ def apply_hadamard_rotation(
the transform backend.
Returns:
- The same model (for chaining); also stored on ``model.rotation_config``.
+ The same model (for chaining); also stored on ``model._rotation_config``.
"""
config = _to_config(rotation_config, data_type)
backend = resolve_hadamard_backend(config, data_type)
@@ -137,9 +137,8 @@ def apply_hadamard_rotation(
fuse_online_to_weight=fuse_online_to_weight,
compute_device=compute_device,
)
- # Stash for downstream (export / serialization). Plain dict so JSON
- # serialization (HF save_pretrained -> config.json) round-trips.
- setattr(model, "rotation_config", config.model_dump() if hasattr(config, "model_dump") else config)
+ # Stash config object for downstream (export / serialization).
+ setattr(model, "_rotation_config", config)
return model, hooks
elif backend == "transform":
diff --git a/auto_round/auto_scheme/delta_loss.py b/auto_round/auto_scheme/delta_loss.py
index b0fc7f60f..a19a40115 100644
--- a/auto_round/auto_scheme/delta_loss.py
+++ b/auto_round/auto_scheme/delta_loss.py
@@ -1311,7 +1311,7 @@ def _gen_layer_config(
# Rotation mutates weights in memory before AutoScheme starts. Clean-mode
# reloads from the original checkpoint and would silently discard those
# transformed weights during scoring and final restore.
- if getattr(model, "rotation_config", None):
+ if getattr(model, "_rotation_config", None):
offload_mode = "offload"
offload_kwargs = {"offload_dir_prefix": "autoscheme", "retain_saved_entries": True}
offload_context = OffloadManager(enabled=True, mode=offload_mode, cache_numel=True, **offload_kwargs)
diff --git a/auto_round/inference/convert_model.py b/auto_round/inference/convert_model.py
index b6de09d66..722cfd318 100644
--- a/auto_round/inference/convert_model.py
+++ b/auto_round/inference/convert_model.py
@@ -873,33 +873,14 @@ def convert_hf_model(model: nn.Module, target_device: str = "cpu") -> tuple[nn.M
layer_configs = get_layer_config(model, quantization_config)
used_backends = _replace_by_quant_layers(model, layer_configs, backend, target_device, packing_format)
- rotation_config = getattr(quantization_config, "rotation_config", None)
- if rotation_config is not None and rotation_config:
- from auto_round.algorithms.transforms.quarot.apply import apply_rotation_transform
- from auto_round.algorithms.transforms.quarot.config import RotationConfig
-
- # apply forward hook
- act_rotation_config = RotationConfig(
- block_size=rotation_config["block_size"],
- hadamard_type=rotation_config["hadamard_type"],
- ) # apply to activation
- model, _ = apply_rotation_transform(
- model,
- act_rotation_config,
- location="input",
- desc="Register pre forward hook for hadamard transform",
- data_type=quantization_config.data_type,
- )
-
- # Pre-register rotation buffers on QuantLinear modules so HuggingFace's
- # state_dict loader can populate them from safetensors.
- # Uses generic dispatch — supports SpinQuant and future rotation methods.
- try:
- from auto_round.algorithms.transforms import preregister_rotation_buffers
+ # Apply rotation hooks (hadamard, spinquant, quarot, etc.) via unified dispatch.
+ _has_rotation = getattr(quantization_config, "rotation_config", None) or getattr(
+ quantization_config, "spinquant_config", None
+ )
+ if _has_rotation:
+ from auto_round.algorithms.transforms import apply_rotation_hooks_from_config
- preregister_rotation_buffers(model, quantization_config)
- except Exception as e:
- logger.warning(f"Failed to pre-register rotation buffers: {e}")
+ model = apply_rotation_hooks_from_config(model, quantization_config)
# Suggest a better backend if available
if backend == "auto":
diff --git a/docs/step_by_step.md b/docs/step_by_step.md
index 228f778b2..ff757ac41 100644
--- a/docs/step_by_step.md
+++ b/docs/step_by_step.md
@@ -34,7 +34,7 @@ This document presents step-by-step instructions for auto-round llm quantization
+ [Device/Multi-GPU setting in Quantization](#devicemulti-gpu-setting-in-quantization)
- [Enable multiple gpus calibration in lm_head quantization](#enable-multiple-gpus-calibration-in-lm_head-quantization)
+ [Adjust Hyperparameters](#adjust-hyperparameters)
- + [Rotation](#rotation)
+ + [Rotation (Experimental)](#rotation-experimental)
- [QuaRot / SpinQuant](#quarot--spinquant)
- [Per-Linear Block Rotation (Experimental)](#per-linear-block-rotation-experimental)
* [4 Inference](#4-inference)
@@ -484,7 +484,6 @@ We will try to optimize the RAM usage in the future. The RAM usage is about 1.1-
#### Limitations
Embedding layer is not supported in AutoScheme, it will use the best scheme in options.
-
### AWQ Quantization Algorithm
AWQ (`algorithm="awq"`) is a pre-processing quantization algorithm that analyzes activation patterns and applies channel-wise scaling to protect salient weights. It runs BEFORE the actual quantization (RTN by default, or auto_round/SignRound).
@@ -520,7 +519,6 @@ ar.quantize_and_save(output_dir="./qmodel")
- `algorithm="awq"` + `format="auto_round"`: AWQ smoothing + AutoRound packing
- `algorithm="auto_round"` + `format="auto_awq"`: No AWQ smoothing + AutoAWQ packing
-
### OPT RTN Mode
AutoRound also supports Optimized RTN (Round-To-Nearest) mode for fast, calibration-free baseline quantization. Setting `iters=0` tp enable it and we recommend using `group_size=32` for better results. Check [accuracy comparison](./opt_rtn.md) between RTN and OPT RTN mode
@@ -859,7 +857,9 @@ autoround.save_quantized(format="auto_awq", output_dir="tmp_autoround")
Include the flag `--adam`. Note that AdamW is less effective than sign gradient descent in many scenarios we tested.
-### Rotation
+### Rotation (Experimental)
+
+> ⚠️ **Experimental feature**: Rotation transform is still in an experimental stage. Inference relies on forward hooks, which are currently only supported by the Hugging Face Transformers backend. As a result, inference may be slower compared to native (non-rotated) models.
AutoRound supports rotation-based transforms to improve quantization accuracy. Rotation redistributes outliers in weights and activations before quantization, making the distribution more uniform and quantization-friendly.
diff --git a/docs/step_by_step_CN.md b/docs/step_by_step_CN.md
index 248a6e9a5..c646ab672 100644
--- a/docs/step_by_step_CN.md
+++ b/docs/step_by_step_CN.md
@@ -35,7 +35,7 @@
- [lm_head 量化中开启多 GPU 标定](#lm_head-量化中开启多-gpu-标定)
- [手动配置设备映射](#手动配置设备映射)
+ [超参数调整](#超参数调整)
- + [旋转(Rotation)](#旋转rotation)
+ + [旋转(Rotation)(实验性)](#旋转rotation实验性)
- [QuaRot / SpinQuant](#quarot--spinquant)
- [逐线性层块旋转(实验性)](#逐线性层块旋转实验性)
* [4 推理部署](#4-推理部署)
@@ -482,7 +482,6 @@ ar.quantize_and_save()
#### 局限性
AutoScheme 目前还**不支持对嵌入层(Embedding layer)进行自动量化**。该层将直接采用候选方案中精度最高的配置。
-
### AWQ 量化算法
AWQ(`algorithm="awq"`)是一种预处理量化算法,通过分析激活分布并应用通道缩放(channel-wise scaling)来保护重要的权重。它在实际量化(默认为 RTN,或使用 auto_round/SignRound)之前运行。
@@ -518,9 +517,7 @@ ar.quantize_and_save(output_dir="./qmodel")
- `algorithm="awq"` + `format="auto_round"`:AWQ 平滑 + AutoRound 打包
- `algorithm="auto_round"` + `format="auto_awq"`:不使用 AWQ 平滑 + AutoAWQ 打包
-
### OPT-RTN 模式
-
AutoRound 还提供优化版 RTN(Round-To-Nearest,就近舍入)模式,无需标定数据即可实现快速基线量化。**启用方式为 `iters=0`**。同时为获得更好的效果,推荐搭配 `group_size=32` 。RTN 与 OPT RTN 模式的精度对比详见[《精度对比报告》](./opt_rtn.md)。
对于 GGUF 格式,我们参考 llamacpp 的思路,优化了 RTN 算法。若需使用原始(非优化)RTN 算法,开启 `--disable_opt_rtn` 即可。
@@ -828,7 +825,9 @@ auto-round --model_name Qwen/Qwen3-0.6B --scheme "W4A16" --quant_lm_head --form
#### 使用 AdamW 优化器
添加 `--adam` 参数即可启用;**注意**:在我们的多项测试场景中,AdamW 优化器的效果均不如符号梯度下降(sign gradient descent)。
-### 旋转(Rotation)
+### 旋转(Rotation)(实验性)
+
+> ⚠️ **实验性功能**:旋转变换仍处于实验阶段。推理依赖 forward hook 机制,目前仅支持 Hugging Face Transformers 后端,因此相比非旋转模型,推理速度可能较慢。
AutoRound 支持基于旋转的变换技术来提升量化精度。旋转在量化前对权重和激活中的离群点进行重分布,使分布更加均匀,从而对量化更友好。