Skip to content

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

step-1 support naive double quant in tuning (#442)

Wenhua Cheng66adfb1604c1
diff --git a/auto_round/autoround.py b/auto_round/autoround.py
index 95efc8d1b..ceab10a26 100644
--- a/auto_round/autoround.py
+++ b/auto_round/autoround.py
@@ -114,7 +114,7 @@ class AutoRound(object):
act_data_type (str): Specifies the data type for activations.
Defaults to None, in which case it inherits the weight data type.
act_dynamic (bool): Whether to use dynamic activation quantization. Default is True.
- to_quant_block_names (str|list): A string or list whose elements are list of
+ to_quant_block_names (str|list): A string or list whose elements are list of
block's layer names to be quantized.
enable_norm_bias_tuning (bool): Whether to enable fast norm/layer_bias tuning
enable_torch_compile (bool): Whether to enable torch compile to optimize quant_block/layer, torch>=2.6 True.
@@ -457,12 +457,7 @@ class AutoRound(object):
for n, m in self.model.named_modules():
if n not in self.layer_config.keys():
continue
- if hasattr(m, "scale"):
- self.layer_config[n]["scale"] = m.scale
- self.layer_config[n]["zp"] = m.zp
- delattr(m, "scale")
- delattr(m, "zp")
- else:
+ if not hasattr(m, "scale"):
self.layer_config[n]["data_type"] = "float"
if self.amp_dtype == torch.bfloat16:
self.layer_config[n]["data_type"] = "bfloat"
@@ -526,6 +521,11 @@ class AutoRound(object):
keys = ["data_type", "bits", "group_size", "sym", "scale_dtype", "act_bits", "act_group_size", "act_sym",
"act_dynamic", "act_data_type"]
for n, m in self.model.named_modules():
+ ##delete keys to avoid conflict with the previous tuning
+ for key in keys:
+ if hasattr(m, key):
+ delattr(m, key)
+
if not isinstance(m, tuple(self.supported_types)):
continue
##not set in layer config, so use the default values
@@ -1597,7 +1597,7 @@ class AutoRoundOPT(AutoRound):
act_data_type (str): Specifies the data type for activations.
Defaults to None, in which case it inherits the weight data type.
act_dynamic (bool): Whether to use dynamic activation quantization. Default is True.
- to_quant_block_names (str|list): A string or list whose elements are list of
+ to_quant_block_names (str|list): A string or list whose elements are list of
block's layer names to be quantized.
enable_norm_bias_tuning (bool): Whether to enable fast norm/layer_bias tuning
enable_torch_compile (bool): Whether to enable torch compile to optimize quant_block/layer function
@@ -1863,5 +1863,4 @@ class AutoRoundAdam(AutoRoundOPT):
device_map=device_map,
optimizer=optimizer,
**kwargs,
- )
-
+ )
\ No newline at end of file
diff --git a/auto_round/data_type/int.py b/auto_round/data_type/int.py
index 94c9f9d5a..26e5a4d7a 100644
--- a/auto_round/data_type/int.py
+++ b/auto_round/data_type/int.py
@@ -40,7 +40,7 @@ def quant_tensor_sym(tensor, bits=4, group_size=-1, v=0, min_scale=1.0, max_scal
"""
tensor, orig_shape, pad_len = reshape_pad_tensor_by_group_size(tensor, group_size)
- maxq = torch.tensor(2 ** (bits - 1))
+ maxq = 2 ** (bits - 1)
if tensor_min is None or tensor_max is None:
wmin_tmp = torch.clamp(tensor.min(-1)[0], max=0)
wmax_tmp = torch.clamp(tensor.max(-1)[0], min=0)
@@ -63,6 +63,74 @@ def quant_tensor_sym(tensor, bits=4, group_size=-1, v=0, min_scale=1.0, max_scal
return qdq_result, scale, zp
+## the values should be positive
+def double_quant_tensor(tensor, bits, q_scale_thresh):
+ maxq = 2 ** bits
+ wmax = torch.clamp(tensor.max(-1)[0], min=0)
+ scale = torch.clamp(wmax / maxq, q_scale_thresh)
+ scale = scale.view(-1, 1)
+ qdq_tensor = torch.clamp(round_ste(tensor / scale), max=maxq) * scale
+ return qdq_tensor, scale
+
+
+@register_dtype("int_asym_dq")
+def quant_tensor_asym_dq(tensor, bits=4, group_size=-1, v=0, min_scale=1.0, max_scale=1.0, scale_dtype=torch.float16,
+ tensor_min=None, tensor_max=None, q_scale_thresh=1e-5, super_group_size=32, super_bits=6,
+ **kwargs):
+ """Quantize and de-quantize tensor asymmetrically.
+
+ Args:
+ tensor: Tensor containing the tensor to be quantized
+ bits: Number of bits for quantization (e.g., 2, 3, 4, 8)
+ group_size: Number of elements to share scale for quantization
+ v: Rounding value perturbation
+ min_scale: Minimum scale coefficient for tensor
+ max_scale: Maximum scale coefficient for tensor
+ tensor_min (Tensor, optional): Minimum tensor value for quantization. Defaults to None.
+ tensor_max (Tensor, optional): Maximum tensor value for quantization. Defaults to None.
+ scale_dtype: dtype of the quantized scale,as most kernels only support FP16 or FP32, while this value is import
+ q_scale_thresh: clip the quantized scale's magnitude to this value to improve the numerical stability
+
+ Returns:
+ Quantized and de-quantized tensor, scale, zero-point
+ """
+ tensor, orig_shape, pad_len = reshape_pad_tensor_by_group_size(tensor, group_size)
+
+ maxq = 2 ** bits - 1
+ if tensor_min is None or tensor_max is None:
+ wmin_tmp = torch.clamp(tensor.min(-1)[0], max=0)
+ wmax_tmp = torch.clamp(tensor.max(-1)[0], min=0)
+ else:
+ wmin_tmp = tensor_min
+ wmax_tmp = tensor_max
+ if isinstance(min_scale, torch.Tensor):
+ wmin = wmin_tmp * min_scale
+ wmax = wmax_tmp * max_scale
+ else:
+ wmin = wmin_tmp
+ wmax = wmax_tmp
+ scale = ((wmax - wmin) / maxq).to(scale_dtype)
+ scale = torch.clamp(scale, min=q_scale_thresh)
+ scale = scale.view(-1, super_group_size)
+ wmin_m = -wmin # pylint: disable=E1130
+ wmin_m = wmin_m.view(-1, super_group_size)
+
+ ##conduct double quant
+ scale, d_scale = double_quant_tensor(scale, super_bits, q_scale_thresh)
+ wmin_m, d_wmin_m = double_quant_tensor(wmin_m, super_bits, q_scale_thresh)
+
+ scale = scale.view(-1, 1)
+ scale = torch.clamp(scale, q_scale_thresh)
+ wmin_m = wmin_m.view(-1, 1)
+
+ int_w = round_ste(tensor / scale + v)
+ q = torch.clamp(int_w + round_ste(wmin_m / scale), 0, maxq)
+ qdq_result = (scale * q - wmin_m).to(tensor.dtype)
+ qdq_result = revert_tensor_by_pad(qdq_result, orig_shape=orig_shape, pad_len=pad_len)
+ zp = round_ste(wmin_m / scale) # remove this later
+ return qdq_result, scale, zp
+
+
@register_dtype("int_asym")
def quant_tensor_asym(tensor, bits=4, group_size=-1, v=0, min_scale=1.0, max_scale=1.0, scale_dtype=torch.float16,
tensor_min=None, tensor_max=None, q_scale_thresh=1e-5, **kwargs):
@@ -84,7 +152,7 @@ def quant_tensor_asym(tensor, bits=4, group_size=-1, v=0, min_scale=1.0, max_sca
Quantized and de-quantized tensor, scale, zero-point
"""
tensor, orig_shape, pad_len = reshape_pad_tensor_by_group_size(tensor, group_size)
- maxq = torch.tensor(2 ** bits - 1)
+ maxq = 2 ** bits - 1
if tensor_min is None or tensor_max is None:
wmin_tmp = torch.clamp(tensor.min(-1)[0], max=0)
wmax_tmp = torch.clamp(tensor.max(-1)[0], min=0)
@@ -131,7 +199,7 @@ def quant_tensor_sym_gptq(tensor, bits=4, group_size=-1, v=0, min_scale=1.0, max
Quantized and de-quantized tensor, scale, zero-point
"""
tensor, orig_shape, pad_len = reshape_pad_tensor_by_group_size(tensor, group_size)
- maxq = torch.tensor(2 ** bits - 1)
+ maxq = 2 ** bits - 1
if tensor_min is None or tensor_max is None:
wmin_tmp = torch.clamp(tensor.min(-1)[0], max=0)
wmax_tmp = torch.clamp(tensor.max(-1)[0], min=0)
@@ -184,7 +252,7 @@ def quant_tensor_asym_wo_round(tensor, bits=4, group_size=-1, v=0, min_scale=1.0
Quantized and de-quantize tensor, scale, zero-point
"""
tensor, orig_shape, pad_len = reshape_pad_tensor_by_group_size(tensor, group_size)
- maxq = torch.tensor(2 ** bits - 1)
+ maxq = 2 ** bits - 1
if tensor_min is None or tensor_max is None:
wmin_tmp = torch.clamp(tensor.min(-1)[0], max=0)
wmax_tmp = torch.clamp(tensor.max(-1)[0], min=0)
diff --git a/auto_round/export/export_to_autogptq/export.py b/auto_round/export/export_to_autogptq/export.py
index b52192580..309595650 100644
--- a/auto_round/export/export_to_autogptq/export.py
+++ b/auto_round/export/export_to_autogptq/export.py
@@ -97,8 +97,8 @@ def pack_layer(name, model, layer_config, backend, pbar):
new_layer.device = device
set_module(model, name, new_layer)
qlayer = new_layer
- scale = layer_config[name]["scale"]
- zero = layer_config[name]["zp"]
+ scale = layer.scale
+ zero = layer.zp
# so far can only pack layer on CPU
qlayer.to("cpu")
##force to float32 to be compatible with torch 2.0
diff --git a/auto_round/export/export_to_autoround/export.py b/auto_round/export/export_to_autoround/export.py
index 5deb60c89..9505a07cd 100644
--- a/auto_round/export/export_to_autoround/export.py
+++ b/auto_round/export/export_to_autoround/export.py
@@ -97,6 +97,8 @@ def pack_layer(name, model, layer_config, backend, pbar):
layer = get_module(model, name)
device = layer.weight.device
+ scale = layer.scale
+ zp = layer.zp
QuantLinear = dynamic_import_quant_linear_for_packing(backend, bits, group_size, sym)
if isinstance(layer, nn.Linear):
@@ -117,21 +119,19 @@ def pack_layer(name, model, layer_config, backend, pbar):
new_layer.device = device
set_module(model, name, new_layer)
qlayer = new_layer
- scale = layer_config[name]["scale"]
- zero = layer_config[name]["zp"]
+
# so far can only pack layer on CPU
qlayer.to("cpu")
##force to float32 to be compatible with torch 2.0
- layer, scale, zero = layer.to("cpu"), scale.to("cpu"), zero.to("cpu").to(torch.float32)
sig = inspect.signature(qlayer.pack)
param_count = len(sig.parameters)
if param_count == 2:
qlayer.pack(layer, scale)
else:
- qlayer.pack(layer, scale, zero, None)
+ qlayer.pack(layer, scale, zp, None)
qlayer.to(device)
else:
- scale, zp = layer_config[name]["scale"].to(torch.float32), layer_config[name]["zp"].to(torch.float32)
+ scale, zp = scale.to(torch.float32),zp.to(torch.float32)
scale = scale.t().contiguous()
zp = zp.t().contiguous()
if bits != 4:
diff --git a/auto_round/export/export_to_awq/export.py b/auto_round/export/export_to_awq/export.py
index d3c345887..7f3a8d33f 100644
--- a/auto_round/export/export_to_awq/export.py
+++ b/auto_round/export/export_to_awq/export.py
@@ -46,13 +46,14 @@ def pack_layer(name, model, layer_config, backend, pbar):
if config["bits"] > 8:
pbar.update(1)
return
- scale, zp = config["scale"], config["zp"]
+ linear_layer = get_module(model, name)
+ scale, zp = linear_layer.scale, linear_layer.zp
scale = scale.t().contiguous()
zp = zp.t().contiguous()
config["zp"] = config["zp"].to(torch.float32)
bits = config["bits"]
group_size = config["group_size"]
- linear_layer = get_module(model, name)
+
if config["sym"]:
zp = 2 ** (config["bits"] - 1)
q_linear = WQLinear_GEMM.from_linear(
diff --git a/auto_round/export/export_to_gguf/convert.py b/auto_round/export/export_to_gguf/convert.py
index 41f00aad7..9024947de 100644
--- a/auto_round/export/export_to_gguf/convert.py
+++ b/auto_round/export/export_to_gguf/convert.py
@@ -1135,37 +1135,37 @@ class OriModel:
class Model(OriModel):
- def __init__(self,
- model,
- dir_model: Path,
- ftype: gguf.LlamaFileType,
- fname_out: Path,
- is_big_endian: bool = False,
- layer_config: dict = {},
- use_temp_file: bool = False,
- eager: bool = False,
- metadata_override: Path | None = None,
- model_name: str | None = None,
- split_max_tensors: int = 0,
- split_max_size: int = 0,
- dry_run: bool = False,
- small_first_shard: bool = False,
- hparams: dict[str, Any] | None = None):
+ def __init__(
+ self,
+ model,
+ dir_model: Path,
+ ftype: gguf.LlamaFileType,
+ fname_out: Path,
+ is_big_endian: bool = False,
+ use_temp_file: bool = False,
+ eager: bool = False,
+ metadata_override: Path | None = None,
+ model_name: str | None = None,
+ split_max_tensors: int = 0,
+ split_max_size: int = 0,
+ dry_run: bool = False,
+ small_first_shard: bool = False,
+ hparams: dict[str, Any] | None = None):
self.model = model
- self.layer_config = layer_config
- super().__init__(dir_model=dir_model,
- ftype=ftype,
- fname_out=fname_out,
- is_big_endian=is_big_endian,
- use_temp_file=use_temp_file,
- eager=eager,
- metadata_override=metadata_override,
- model_name=model_name,
- split_max_tensors=split_max_tensors,
- split_max_size=split_max_size,
- dry_run=dry_run,
- small_first_shard=small_first_shard,
- hparams=hparams)
+ super().__init__(
+ dir_model=dir_model,
+ ftype=ftype,
+ fname_out=fname_out,
+ is_big_endian=is_big_endian,
+ use_temp_file=use_temp_file,
+ eager=eager,
+ metadata_override=metadata_override,
+ model_name=model_name,
+ split_max_tensors=split_max_tensors,
+ split_max_size=split_max_size,
+ dry_run=dry_run,
+ small_first_shard=small_first_shard,
+ hparams=hparams)
@classmethod
def __init_subclass__(cls):
@@ -1276,14 +1276,16 @@ class Model(OriModel):
# Quant here
def _quant_data(data, data_qtype):
+ from auto_round.utils import get_module
suffix = '.weight'
- if suffix in name and name[:-len(suffix)] in self.layer_config:
+ if suffix in name:
layer_name = name[:-len(suffix)]
- if "scale" in self.layer_config[layer_name]:
- scale = self.layer_config[layer_name]['scale']
+ module = get_module(self.model, layer_name)
+ if hasattr(module, "scale"):
+ scale = module.scale
if isinstance(scale, torch.Tensor):
scale = scale.numpy()
- zp = self.layer_config[layer_name]['zp']
+ zp = module.zp
if isinstance(zp, torch.Tensor):
zp = zp.numpy()
data = ggml_quant(data, data_qtype.name.lower(), scale,
diff --git a/auto_round/export/export_to_gguf/export.py b/auto_round/export/export_to_gguf/export.py
index 742c96c04..211e1f00e 100644
--- a/auto_round/export/export_to_gguf/export.py
+++ b/auto_round/export/export_to_gguf/export.py
@@ -60,19 +60,25 @@ def save_quantized_as_gguf(output_dir, backend="gguf:q4_0", **kwargs):
model_name = model_name[-2]
else:
model_name = model_name[-1]
-
+
output_type = backend.split(":")[-1]
output_type = FTYPE_MAP.get(output_type.lower())
- layer_config = kwargs.get("layer_config")
- model_instance = model_class(model, dir_model=tmp_work_dir, ftype=output_type, fname_out=Path(output_dir),
- layer_config=layer_config, is_big_endian=False, model_name=model_name,
- split_max_tensors=False, split_max_size=0, dry_run=False,
- small_first_shard=False)
+ model_instance = model_class(
+ model,
+ dir_model=tmp_work_dir,
+ ftype=output_type,
+ fname_out=Path(output_dir),
+ is_big_endian=False,
+ model_name=model_name,
+ split_max_tensors=False,
+ split_max_size=0,
+ dry_run=False,
+ small_first_shard=False)
model_instance.write()
logger.info(f"Model successfully exported to {model_instance.fname_out}")
-
+
shutil.rmtree(tmp_work_dir, ignore_errors=True)
- return model
\ No newline at end of file
+ return model
diff --git a/auto_round/export/export_to_itrex/export.py b/auto_round/export/export_to_itrex/export.py
index d0bbb5618..ac6e2355d 100644
--- a/auto_round/export/export_to_itrex/export.py
+++ b/auto_round/export/export_to_itrex/export.py
@@ -213,7 +213,7 @@ def pack_model(
scale_dtype = v["scale_dtype"]
m = get_module(compressed_model, k)
fp_weight = m.weight.data
- scale, zp = v["scale"], v["zp"]
+ scale, zp = m.scale, m.zp
convert_dtype = scale_dtype
if not isinstance(scale, torch.Tensor):
scale = torch.tensor(scale, dtype=convert_dtype)
diff --git a/auto_round/quantizer.py b/auto_round/quantizer.py
index f44746086..297eb5db9 100644
--- a/auto_round/quantizer.py
+++ b/auto_round/quantizer.py
@@ -525,4 +525,4 @@ def unwrapper_block(block, best_params):
else:
best_param = None
orig_layer = m.unwrapper(best_param)
- set_module(block, n, orig_layer)
+ set_module(block, n, orig_layer)
\ No newline at end of file
diff --git a/auto_round/script/llm.py b/auto_round/script/llm.py
index 0b0498cd4..db9edba9c 100644
--- a/auto_round/script/llm.py
+++ b/auto_round/script/llm.py
@@ -291,6 +291,16 @@ def _gguf_args_check(args):
formats = args.format.lower().replace(' ', '').split(",")
for format in _GGUF_CONFIG:
if format in formats:
+ from pathlib import Path
+ from auto_round.export.export_to_gguf.convert import Model
+ hparams = Model.load_hparams(Path(args.model))
+ model_architecture = hparams["architectures"][0]
+ try:
+ model_class = Model.from_model_architecture(model_architecture)
+ except NotImplementedError:
+ logger.error(f"Model {model_architecture} is not supported to export GGUF format")
+ sys.exit(1)
+
unsupport_list, reset_list = [], []
gguf_config = _GGUF_CONFIG[format]
for k, v in gguf_config.items():