PTQ-Level Efficiency, QAT-Level Accuracy | 训练后量化的效率,量化感知训练的精度
fix inplace rotation issue (#1903)
Wenhua Cheng9d5edd56086b
diff --git a/auto_round/__main__.py b/auto_round/__main__.pyindex 859e07e9b..70992f5df 100644--- a/auto_round/__main__.py+++ b/auto_round/__main__.py@@ -425,9 +425,15 @@ class BasicArgumentParser(argparse.ArgumentParser):"--rotation_type",default=None,type=str,- choices=["hadamard", "random_hadamard"],+ choices=["hadamard", "random_hadamard", "inplace_quarot_hadamard", "inplace_hadamard", "inplace_random"],help="Research feature: applies a rotation (e.g., Hadamard) to reduce activation/weight outliers",)+ scheme.add_argument(+ "--rotation_block_size",+ default=None,+ type=int,+ help="Research feature rotation_block_size",+ )gguf = self.add_argument_group("Double Quant Arguments")gguf.add_argument("--super_group_size", default=None, type=int, help="Super group size for double quantization."@@ -763,7 +769,7 @@ def tune(args):if args.rotation_type:from auto_round.algorithms.transforms.rotation.config import RotationConfig- rot_config = RotationConfig(hadamard_type=args.rotation_type)+ rot_config = RotationConfig(hadamard_type=args.rotation_type, block_size=args.rotation_block_size)autoround: BaseCompressor = AutoRound(model=model_name,diff --git a/auto_round/algorithms/transforms/rotation/config.py b/auto_round/algorithms/transforms/rotation/config.pyindex 629714557..8143e95d1 100644--- a/auto_round/algorithms/transforms/rotation/config.py+++ b/auto_round/algorithms/transforms/rotation/config.py@@ -50,7 +50,9 @@ __all__ = []# Supported Hadamard transform types (also used by HadamardTransform registry).-HADAMARD_TYPES: frozenset[str] = frozenset({"hadamard", "random_hadamard", "quarot_hadamard"})+HADAMARD_TYPES: frozenset[str] = frozenset(+ {"hadamard", "random_hadamard", "inplace_quarot_hadamard", "inplace_hadamard", "inplace_random"}+)_SUPPORTED_BACKENDS: frozenset[str] = frozenset({"auto", "inplace", "transform"})diff --git a/auto_round/algorithms/transforms/rotation/dispatcher.py b/auto_round/algorithms/transforms/rotation/dispatcher.pyindex ef47c2e56..5aebd9443 100644--- a/auto_round/algorithms/transforms/rotation/dispatcher.py+++ b/auto_round/algorithms/transforms/rotation/dispatcher.py@@ -57,7 +57,8 @@ def resolve_hadamard_backend(config: RotationConfig, data_type: str) -> str:fuse_requested = bool(config.fuse_online_to_weight)allow_online_rotation: bool = config.allow_online_rotation- if requested == "inplace":+ if requested == "inplace" or "inplace" in config.hadamard_type:+ config.hadamard_type = config.hadamard_type[len("inplace_") :]return "inplace"transform_backend_name = "transform"diff --git a/auto_round/algorithms/transforms/rotation/inplace/apply.py b/auto_round/algorithms/transforms/rotation/inplace/apply.pyindex 3177d6fa9..6590798da 100644--- a/auto_round/algorithms/transforms/rotation/inplace/apply.py+++ b/auto_round/algorithms/transforms/rotation/inplace/apply.py@@ -41,6 +41,25 @@ from auto_round.algorithms.transforms.rotation.inplace.model_config import (# ---------------------------------------------------------------------------+def _resolve_head_dim(mapping, config, hidden_size, num_heads):+ """Resolve the per-head attention dimension.++ Resolution order:+ 1. ``mapping.attn_head_dim`` (explicit override on the RotationMapping).+ 2. ``config.head_dim`` if present (Qwen-3 and other models declare an+ explicit ``head_dim`` that does not necessarily equal+ ``hidden_size // num_heads``; e.g. Qwen3-32B has hidden=5120,+ heads=64, head_dim=128 → o_proj.in_features = 8192, not 5120).+ 3. ``hidden_size // num_heads`` as a last-resort default.+ """+ if mapping.attn_head_dim:+ return mapping.attn_head_dim+ cfg_head_dim = getattr(config, "head_dim", None)+ if isinstance(cfg_head_dim, int) and cfg_head_dim > 0:+ return cfg_head_dim+ return hidden_size // num_heads++def _fuse_ln_linear(layernorm: torch.nn.Module,linear_layers: typing.Iterable[torch.nn.Linear],@@ -69,32 +88,79 @@ def _reset_ln_params(layernorm: torch.nn.Module) -> None:layernorm.bias.data.fill_(0.0)+def _rotate_weight_chunked(+ weight: torch.Tensor,+ Q: torch.Tensor,+ side: str,+ compute_device,+ chunk: int = 4096,+) -> torch.Tensor:+ """Compute the rotated weight without ever materialising the full fp64 copy.++ * ``side == 'input'`` → returns ``W @ Q`` (chunked over rows of ``W``).+ * ``side == 'output'`` → returns ``Q^T @ W`` (chunked over columns of ``W``).++ The output is pre-allocated in the **original** dtype on the **original**+ device of ``weight``. At any moment only a single chunk lives in fp64 on+ ``compute_device``, so peak transient memory is roughly+ ``chunk * other_dim * 8`` bytes instead of ``W.numel() * 8``.++ Embedding/lm_head on Qwen3-14B (151936 × 5120) drops from ~12 GB to a few+ hundred MB transient.+ """+ dtype = weight.dtype+ dev = weight.device+ out = torch.empty_like(weight)+ Q_ = Q.to(device=compute_device, dtype=torch.float64)+ try:+ if side == "input":+ # (R, C) @ (C, C) → (R, C); chunk over R.+ R = weight.shape[0]+ for i in range(0, R, chunk):+ j = min(i + chunk, R)+ blk = weight.data[i:j].to(device=compute_device, dtype=torch.float64)+ rotated = (blk @ Q_).to(device=dev, dtype=dtype)+ out[i:j].copy_(rotated)+ del blk, rotated+ elif side == "output":+ # Q^T @ (R, C) → (R, C); chunk over C so each block is (R, chunk).+ C = weight.shape[1]+ Q_T = Q_.T.contiguous()+ for i in range(0, C, chunk):+ j = min(i + chunk, C)+ blk = weight.data[:, i:j].to(device=compute_device, dtype=torch.float64)+ rotated = (Q_T @ blk).to(device=dev, dtype=dtype)+ out[:, i:j].copy_(rotated)+ del blk, rotated+ del Q_T+ else:+ raise ValueError(f"side must be 'input' or 'output', got {side!r}")+ finally:+ del Q_+ return out++def _rotate_linear_by_Q(module: torch.nn.Linear, Q: torch.Tensor, side: str, compute_device=None) -> None:"""Apply rotation *Q* to a Linear layer's weight (and bias if present).+ Memory-efficient: never materialises the full fp64 weight at once.+Args:side: ``'input'`` → W = W @ Q (rotate input side)``'output'`` → W = Q^T @ W (rotate output side)compute_device: Device to run computation on. If None, auto-detects GPU."""- dtype = module.weight.data.dtype- dev = module.weight.data.devicecdev = _resolve_compute_device(compute_device)- W_ = module.weight.data.to(device=cdev, dtype=torch.float64)- Q_ = Q.to(device=cdev)- if side == "input":- new_W = torch.matmul(W_, Q_).to(device=dev, dtype=dtype)- else:- new_W = torch.matmul(Q_.T, W_).to(device=dev, dtype=dtype)- # Release fp64 copy before assigning back so peak memory ≈ 1× weight + 1× rotated.- del W_- module.weight.data = new_W+ module.weight.data = _rotate_weight_chunked(module.weight.data, Q, side, cdev)if side == "output" and module.bias is not None:+ dtype = module.bias.data.dtype+ dev = module.bias.data.device+ # Bias is a 1-D vector → small; safe to do in one shot.b = module.bias.data.to(device=cdev, dtype=torch.float64)+ Q_ = Q.to(device=cdev, dtype=torch.float64)new_b = torch.matmul(Q_.T, b).to(device=dev, dtype=dtype)- del b+ del b, Q_module.bias.data = new_b- del Q_def _untie_word_embeddings(model, mapping: RotationMapping) -> None:@@ -255,7 +321,7 @@ def _rotate_weights(hidden_size = getattr(config, mapping.hidden_size_attr)intermediate_size = getattr(config, mapping.intermediate_size_attr)num_heads = getattr(config, mapping.num_heads_attr)- head_dim = mapping.attn_head_dim or (hidden_size // num_heads)+ head_dim = _resolve_head_dim(mapping, config, hidden_size, num_heads)is_grouped = group_size is not None and group_size > 0desc = f"Rotating (group_size={group_size})" if is_grouped else "Rotating"@@ -308,13 +374,11 @@ def _rotate_weights(embedding, group_size, use_fast_had=fused_fast, compute_device=compute_device, had_matrix=had_matrix)else:- dtype = embedding.weight.data.dtype- dev = embedding.weight.data.device- cdev = compute_device- W_ = embedding.weight.data.to(device=cdev, dtype=torch.float64)- new_W = torch.matmul(W_, Q.to(cdev)).to(device=dev, dtype=dtype)- del W_- embedding.weight.data = new_W+ # Chunked: avoids a full fp64 copy of the (vocab, hidden) embedding,+ # which on Qwen3-14B is ~6 GB on its own.+ embedding.weight.data = _rotate_weight_chunked(+ embedding.weight.data, Q, side="input", compute_device=compute_device+ )if mapping.positional_embedding is not None:pos_emb = _resolve(model, mapping.positional_embedding)@@ -323,13 +387,9 @@ def _rotate_weights(pos_emb, group_size, use_fast_had=fused_fast, compute_device=compute_device, had_matrix=had_matrix)else:- pos_dtype = pos_emb.weight.data.dtype- pos_dev = pos_emb.weight.data.device- cdev = compute_device- P_ = pos_emb.weight.data.to(device=cdev, dtype=torch.float64)- new_P = torch.matmul(P_, Q.to(cdev)).to(device=pos_dev, dtype=pos_dtype)- del P_- pos_emb.weight.data = new_P+ pos_emb.weight.data = _rotate_weight_chunked(+ pos_emb.weight.data, Q, side="input", compute_device=compute_device+ )# ---- Top-level: lm_head ----lm_head = _resolve(model, mapping.lm_head)@@ -432,11 +492,34 @@ def _rotate_weights(had_matrix=_online_had(intermediate_size),)- # OV projection: v_proj per-head output + o_proj full/cross-head input+ # OV projection: v_proj per-head output + o_proj decomposed input+ #+ # The online hook on o_proj applies (H_cross ⊗ I_head)⁻¹ at+ # runtime, so the weight-side rotation must equal exactly+ # (H_cross ⊗ I_head)(I_heads ⊗ H_head) = H_cross ⊗ H_head.+ #+ # IMPORTANT: we must NOT use a single full-dimension Hadamard+ # (``had_dim=-1``) on o_proj, because the butterfly construction+ # ``matmul_hadU(hidden_size)`` does NOT satisfy the Kronecker+ # decomposition ``H_hidden = H_num_heads ⊗ H_head_dim`` when+ # ``num_heads`` is not a power of 2 (e.g. Qwen3-14B, num_heads=40).+ # Instead we always apply per-head + cross-head separately.v_proj = _resolve(layer, mapping.attn_v)o_proj = _resolve(layer, mapping.attn_o)if is_grouped:- pass+ # In grouped mode, apply input-side grouped Had to o_proj+ # (with corresponding online hook) to smooth the attention+ # output that flows into o_proj. Analogous to down_proj+ # which gets both output+input rotation, and matches the+ # transform backend which rotates every linear's input.+ _rotate_linear_grouped(+ o_proj,+ group_size,+ side="input",+ use_fast_had=online_fast,+ compute_device=compute_device,+ had_matrix=online_had_matrix,+ )else:online_head_had = _online_had(head_dim)apply_exact_had_to_linear(@@ -447,31 +530,22 @@ def _rotate_weights(compute_device=compute_device,had_matrix=online_head_had,)- if preset == "random_hadamard":- apply_exact_had_to_linear(- o_proj,- had_dim=head_dim,- output=False,- use_fast_had=online_fast,- compute_device=compute_device,- had_matrix=online_head_had,- )- apply_cross_head_had_to_linear(- o_proj,- num_heads,- head_dim,- use_fast_had=online_fast,- compute_device=compute_device,- had_matrix=_online_had(num_heads),- )- else:- apply_exact_had_to_linear(- o_proj,- had_dim=-1,- output=False,- use_fast_had=online_fast,- compute_device=compute_device,- )+ apply_exact_had_to_linear(+ o_proj,+ had_dim=head_dim,+ output=False,+ use_fast_had=online_fast,+ compute_device=compute_device,+ had_matrix=online_head_had,+ )+ apply_cross_head_had_to_linear(+ o_proj,+ num_heads,+ head_dim,+ use_fast_had=online_fast,+ compute_device=compute_device,+ had_matrix=_online_had(num_heads),+ )else:# ---- unfused mode: no residual rotation, only input-side Had ----@@ -608,7 +682,7 @@ def _register_online_hooks(num_heads = getattr(config, mapping.num_heads_attr)hidden_size = getattr(config, mapping.hidden_size_attr)intermediate_size = getattr(config, mapping.intermediate_size_attr)- head_dim = mapping.attn_head_dim or (hidden_size // num_heads)+ head_dim = _resolve_head_dim(mapping, config, hidden_size, num_heads)is_grouped = group_size is not None and group_size > 0@@ -704,8 +778,9 @@ def _register_online_hooks(# o_proj: cross-head Had on input (fused mode, full only)h = module.register_forward_pre_hook(_make_o_proj_hook())handles.append(h)- elif not fuse_online_to_weight:- # o_proj: full Had on hidden_size input (unfused mode, matches weight rotation)+ else:+ # o_proj: grouped Had (fused+grouped) or full Had (unfused)+ # on hidden_size input — compensates the input-side weight rotation.h = module.register_forward_pre_hook(_make_hidden_had_hook())handles.append(h)elif suffix in attn_qkv_suffixes:@@ -788,19 +863,26 @@ def apply_rotation_transform(mapping = infer_mapping_from_model(model)- _untie_word_embeddings(model, mapping)+ # LayerNorm fusion, mean subtraction, and embedding untying are only+ # needed for fused (QuaRot-style) residual-stream rotation. In unfused+ # mode the per-linear rotation + online hook pair is self-contained and+ # does not require modifying norms or the residual stream. Skipping+ # fusion in unfused mode avoids changing the weight distribution+ # (γ absorbed into W), which hurts quantisation quality.+ if fuse_online_to_weight:+ _untie_word_embeddings(model, mapping)- if _uses_layernorm_with_mean(model, mapping):- _subtract_embedding_mean(model, mapping)+ if _uses_layernorm_with_mean(model, mapping):+ _subtract_embedding_mean(model, mapping)- _fuse_layer_norms(model, mapping)+ _fuse_layer_norms(model, mapping)- if _uses_layernorm_with_mean(model, mapping):- layers = _resolve(model, mapping.layers_attr)- for layer in layers:- _bake_mean_into_linear(_resolve(layer, mapping.attn_o))- _bake_mean_into_linear(_resolve(layer, mapping.mlp_out))- _replace_layernorms_with_rmsnorm(model)+ if _uses_layernorm_with_mean(model, mapping):+ layers = _resolve(model, mapping.layers_attr)+ for layer in layers:+ _bake_mean_into_linear(_resolve(layer, mapping.attn_o))+ _bake_mean_into_linear(_resolve(layer, mapping.mlp_out))+ _replace_layernorms_with_rmsnorm(model)_rotate_weights(model,@@ -836,9 +918,54 @@ def apply_rotation_transform(if __name__ == "__main__":from transformers import AutoModelForCausalLM, AutoTokenizer- model_name = "/models/opt-125m"+ # model_name = "/models/opt-125m"+ # tokenizer = AutoTokenizer.from_pretrained(model_name)+ # model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.float16, device_map="auto")+ # model.to("cuda")+ # text = "There is a girl who likes adventure,"+ # inputs = tokenizer(text, return_tensors="pt").to(model.device)+ # print(tokenizer.decode(model.generate(**inputs, max_new_tokens=50)[0]))+ #+ # model_name = "/models/Qwen3-14B"+ # tokenizer = AutoTokenizer.from_pretrained(model_name)+ # model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto", device_map="auto")+ # apply_rotation_transform(model, group_size=-1, allow_online_rotation=True, fuse_online_to_weight=True)+ # model.to("cuda")+ # text = "There is a girl who likes adventure,"+ # inputs = tokenizer(text, return_tensors="pt").to(model.device)+ # print(tokenizer.decode(model.generate(**inputs, max_new_tokens=50)[0]))+ #+ # model_name = "/models/Qwen3-14B"+ # tokenizer = AutoTokenizer.from_pretrained(model_name)+ # model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto", device_map="auto")+ # apply_rotation_transform(model, group_size=32, allow_online_rotation=True, fuse_online_to_weight=True)+ # model.to("cuda")+ # text = "There is a girl who likes adventure,"+ # inputs = tokenizer(text, return_tensors="pt").to(model.device)+ # print(tokenizer.decode(model.generate(**inputs, max_new_tokens=50)[0]))+ #+ # model_name = "/models/Qwen3-14B"+ # tokenizer = AutoTokenizer.from_pretrained(model_name)+ # model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto", device_map="auto")+ # apply_rotation_transform(model, group_size=32, allow_online_rotation=True, fuse_online_to_weight=False)+ # model.to("cuda")+ # text = "There is a girl who likes adventure,"+ # inputs = tokenizer(text, return_tensors="pt").to(model.device)+ # print(tokenizer.decode(model.generate(**inputs, max_new_tokens=50)[0]))++ model_name = "/models/Qwen3-32B"tokenizer = AutoTokenizer.from_pretrained(model_name)- model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.float16, device_map="auto")+ model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto", device_map="auto")+ apply_rotation_transform(model, group_size=32, allow_online_rotation=True, fuse_online_to_weight=True)+ model.to("cuda")+ text = "There is a girl who likes adventure,"+ inputs = tokenizer(text, return_tensors="pt").to(model.device)+ print(tokenizer.decode(model.generate(**inputs, max_new_tokens=50)[0]))++ model_name = "/models/Qwen3-32B"+ tokenizer = AutoTokenizer.from_pretrained(model_name)+ model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto", device_map="auto")+ apply_rotation_transform(model, group_size=32, allow_online_rotation=True, fuse_online_to_weight=False)model.to("cuda")text = "There is a girl who likes adventure,"inputs = tokenizer(text, return_tensors="pt").to(model.device)@@ -854,7 +981,7 @@ if __name__ == "__main__":model_name = "/models/Qwen3-8B"tokenizer = AutoTokenizer.from_pretrained(model_name)- model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.float16, device_map="auto")+ model = AutoModelForCausalLM.from_pretrained(model_name, device_map="auto")apply_rotation_transform(model, group_size=-1, allow_online_rotation=True, fuse_online_to_weight=True)model.to("cuda")text = "There is a girl who likes adventure,"@@ -863,7 +990,7 @@ if __name__ == "__main__":from transformers import AutoModelForCausalLM, AutoTokenizer- model_name = "/models/Meta-Llama-3.1-8B-Instruct"+ model_name = "/models/Llama-3.1-8B-Instruct"tokenizer = AutoTokenizer.from_pretrained(model_name)model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.float16, device_map="auto")apply_rotation_transform(model, fuse_online_to_weight=True, group_size=32)diff --git a/auto_round/compressors/base.py b/auto_round/compressors/base.pyindex 08c8772c4..4ad5babfd 100644--- a/auto_round/compressors/base.py+++ b/auto_round/compressors/base.py@@ -36,8 +36,8 @@ from auto_round.logger import loggerfrom auto_round.schemes import (QuantizationScheme,_handle_special_schemes,- _parse_scheme,get_gguf_scheme,+ parse_scheme,preset_name_to_scheme,)from auto_round.special_model_handler import get_predefined_fixed_attr, get_predefined_ignore_layers, update_module@@ -192,6 +192,12 @@ class BaseCompressor(object):if isinstance(_cfg, QuantizationConfig):self.quantize_config = _cfgelif isinstance(_cfg, BaseRotationConfig):+ if hasattr(_cfg, "block_size") and _cfg.block_size is None:+ if "group_size" in kwargs:+ block_size = kwargs["group_size"]+ else:+ block_size = parse_scheme(scheme, {})[2]["group_size"]+ _cfg.block_size = block_size # TODO not robustself.rotation_configs.append(_cfg)assert self.quantize_config is not None, "QuantizationConfig is required for Compressor"@@ -372,7 +378,7 @@ class BaseCompressor(object):for k in scheme_fieldsif getattr(self.quantize_config, k, None) is not None}- default_scheme, self.is_auto_scheme, final_attrs = _parse_scheme(self.scheme, user_scheme_overrides)+ default_scheme, self.is_auto_scheme, final_attrs = parse_scheme(self.scheme, user_scheme_overrides)for key, value in final_attrs.items():setattr(self.quantize_config, key, value)diff --git a/auto_round/compressors/entry.py b/auto_round/compressors/entry.pyindex d001aaf72..94b03d1bf 100644--- a/auto_round/compressors/entry.py+++ b/auto_round/compressors/entry.py@@ -18,7 +18,7 @@ from auto_round.compressors.data_driven import CalibratedRTNCompressor, DataDrivfrom auto_round.compressors.utils import check_need_act_calibrationfrom auto_round.compressors.zero_shot import ZeroShotCompressorfrom auto_round.logger import logger-from auto_round.schemes import QuantizationScheme, _parse_scheme+from auto_round.schemes import QuantizationScheme, parse_schemedef _preview_resolved_attrs(config, scheme=None) -> dict:@@ -39,7 +39,7 @@ def _preview_resolved_attrs(config, scheme=None) -> dict:scheme_attr_names = QuantizationScheme.get_attributes()user_overrides = {k: getattr(config, k) for k in scheme_attr_names if getattr(config, k, None) is not None}try:- _, _, final_attrs = _parse_scheme(scheme, user_overrides)+ _, _, final_attrs = parse_scheme(scheme, user_overrides)return final_attrsexcept Exception:return {}@@ -62,7 +62,7 @@ def _eager_validate_scheme(config, scheme=None) -> None:scheme_attr_names = QuantizationScheme.get_attributes()user_overrides = {k: getattr(config, k) for k in scheme_attr_names if getattr(config, k, None) is not None}try:- _, _, final_attrs = _parse_scheme(scheme, user_overrides)+ _, _, final_attrs = parse_scheme(scheme, user_overrides)except (ValueError, NotImplementedError):raiseexcept Exception:diff --git a/auto_round/schemes.py b/auto_round/schemes.pyindex d351a3f07..1f202a2ca 100644--- a/auto_round/schemes.py+++ b/auto_round/schemes.py@@ -237,9 +237,9 @@ def _override_scheme_with_user_specify(return QuantizationScheme.from_dict(scheme_dict)-def _parse_scheme(+def parse_scheme(scheme: Union[str, dict, QuantizationScheme, "AutoScheme"], user_scheme_overrides: dict[str, Any]-) -> tuple[Union[str, QuantizationScheme], bool]:+) -> tuple[Union[str, QuantizationScheme], bool, dict[str, Any]]:"""Parses the final scheme."""