Skip to content

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

revert the gptq format code to fix the regression (#168)

wenhuach215947e9c06485
diff --git a/auto_round/export/export_to_autogptq.py b/auto_round/export/export_to_autogptq.py
index 67f7b6765..acff4fe4a 100644
--- a/auto_round/export/export_to_autogptq.py
+++ b/auto_round/export/export_to_autogptq.py
@@ -50,8 +50,7 @@ from ..utils import convert_dtype_torch2str_hf
@register_format("auto_gptq")
-def save_quantized_as_autogptq(output_dir, use_triton=True, inplace=True,
- **kwargs):
+def save_quantized_as_autogptq(output_dir, use_triton=True, inplace=True, **kwargs):##TODO align with autoround format
"""Export the model to autogptq format to easily leverage cuda kernel."""
try:
import auto_gptq
@@ -59,8 +58,15 @@ def save_quantized_as_autogptq(output_dir, use_triton=True, inplace=True,
raise ImportError("export to autogptq requires autogptq library. Please run 'pip install auto-gptq'")
model = kwargs["model"]
weight_config = kwargs["weight_config"]
+ sym = kwargs["sym"]
bits = kwargs["bits"]
group_size = kwargs["group_size"]
+ iters = kwargs["iters"]
+ lr = kwargs["lr"]
+ minmax_lr = kwargs["minmax_lr"]
+ enable_minmax_tuning = kwargs["enable_minmax_tuning"]
+ enable_quanted_input = kwargs["enable_quanted_input"]
+ scale_dtype = kwargs["scale_dtype"]
tokenizer = kwargs["tokenizer"]
supported_types = kwargs["supported_types"]
@@ -96,61 +102,172 @@ def save_quantized_as_autogptq(output_dir, use_triton=True, inplace=True,
from auto_gptq.modeling._utils import pack_model # pylint: disable=E0401
if bits == 3 or use_triton is False:
- use_triton = False
- quantizers = {}
- for key in weight_config:
- if key == "lm_head": ##TODO remove this after pr 87 is merged
- continue
- info = weight_config[key]
- if not check_to_quantized(info):
- continue
- quantizers[key] = (None, info["scale"], info["zp"].to(torch.float32), info["g_idx"])
- pack_model(
+ if bits == 3 and use_triton is True:
+ logger.warning("triton does not support 3 bits, reset it to False")
+ quantizers = {}
+ for key in weight_config:
+ if key == "lm_head": ##TODO remove this after pr 87 is merged
+ continue
+ info = weight_config[key]
+ if not check_to_quantized(info):
+ continue
+ ##force to float32 to be compatible with torch 2.0
+ quantizers[key] = (None, info["scale"], info["zp"].to(torch.float32), info["g_idx"])
+ pack_model(
+ compressed_model,
+ quantizers,
+ bits,
+ group_size,
+ use_cuda_fp16=True,
+ desc_act=False,
+ force_layer_back_to_cpu=True,
+ use_triton=False,
+ )
+ else:
+ quantizers = {}
+ for key in weight_config:
+ if key == "lm_head": ##TODO remove this after pr 87 is merged
+ continue
+ info = weight_config[key]
+ if not check_to_quantized(info):
+ continue
+ quantizers[key] = (None, info["scale"], info["zp"].to(torch.float32), info["g_idx"])
+ pack_model(
+ compressed_model,
+ quantizers,
+ bits,
+ group_size,
+ use_cuda_fp16=True,
+ desc_act=False,
+ force_layer_back_to_cpu=True,
+ use_triton=True,
+ )
+ if output_dir is None:
+ return compressed_model
+
+ _save_quantized_to_autogptq(
compressed_model,
- quantizers,
- bits,
- group_size,
- use_cuda_fp16=True,
+ output_dir,
+ bits=bits,
+ group_size=group_size,
+ sym=sym,
+ iters=iters,
+ lr=lr,
+ minmax_lr=minmax_lr,
+ enable_minmax_tuning=enable_minmax_tuning,
+ enable_quanted_input=enable_quanted_input,
+ scale_dtype=scale_dtype,
+ use_safetensors=True,
+ modules_in_block_to_quantize=modules_in_block_to_quantize,
+ )
+
+
+def _save_quantized_to_autogptq(
+ model,
+ save_dir: str,
+ bits=4,
+ group_size=128,
+ sym=False,
+ iters=200,
+ lr=5e-3,
+ minmax_lr=5e-3,
+ enable_minmax_tuning=True,
+ enable_quanted_input=True,
+ use_safetensors: bool = True,
+ scale_dtype=torch.float32,
+ safetensors_metadata: Optional[Dict[str, str]] = None,
+ modules_in_block_to_quantize=None,
+):
+ """Save quantized model and configs to local disk for cuda."""
+ os.makedirs(save_dir, exist_ok=True)
+ model.to("cpu")
+
+ model_base_name = "model"
+ if use_safetensors:
+ model_save_name = model_base_name + ".safetensors"
+ state_dict = model.state_dict()
+ state_dict = {k: v.clone().contiguous() for k, v in state_dict.items()}
+ if safetensors_metadata is None:
+ safetensors_metadata = {}
+ elif not isinstance(safetensors_metadata, dict):
+ raise TypeError("safetensors_metadata must be a dictionary.")
+ else:
+ logger.debug(f"Received safetensors_metadata: {safetensors_metadata}")
+ new_safetensors_metadata = {}
+ converted_keys = False
+ for key, value in safetensors_metadata.items():
+ if not isinstance(key, str) or not isinstance(value, str):
+ converted_keys = True
+ try:
+ new_key = str(key)
+ new_value = str(value)
+ except Exception as e:
+ raise TypeError(
+ "safetensors_metadata: both keys and values must be strings"
+ / f" and an error occurred when trying to convert them: {e}"
+ )
+ if new_key in new_safetensors_metadata:
+ logger.warning(
+ f"After converting safetensors_metadata keys to strings, the key '{new_key}' "
+ / "is duplicated. Ensure that all your metadata keys are strings to avoid overwriting."
+ )
+ new_safetensors_metadata[new_key] = new_value
+ safetensors_metadata = new_safetensors_metadata
+ if converted_keys:
+ logger.debug(
+ "One or more safetensors_metadata keys or values had to be converted to str()."
+ / f" Final safetensors_metadata: {safetensors_metadata}"
+ )
+
+ # Format is required to enable Accelerate to load the metadata
+ # otherwise it raises an OSError
+ safetensors_metadata["format"] = "pt"
+
+ # Store the quantization configuration as safetensors metadata
+ from auto_round import __version__
+
+ safetensors_metadata["autoround_version"] = str(__version__)
+ safetensors_metadata["bits"] = str(bits)
+ safetensors_metadata["group_size"] = str(group_size)
+ safetensors_metadata["iters"] = str(iters)
+ safetensors_metadata["lr"] = str(lr)
+ safetensors_metadata["minmax_lr"] = str(minmax_lr)
+ safetensors_metadata["enable_minmax_tuning"] = str(enable_minmax_tuning)
+ safetensors_metadata["enable_quanted_input"] = str(enable_quanted_input)
+ safetensors_metadata["scale_dtype"] = convert_dtype_torch2str_hf(scale_dtype)
+ safe_save(state_dict, join(save_dir, model_save_name), safetensors_metadata)
+ else:
+ model_save_name = model_base_name + ".bin"
+ torch.save(model.state_dict(), join(save_dir, model_save_name))
+
+ from auto_gptq.modeling._base import BaseQuantizeConfig # pylint: disable=E0401
+
+ quantization_config = BaseQuantizeConfig(
+ bits=bits,
+ group_size=group_size,
desc_act=False,
- force_layer_back_to_cpu=True,
- use_triton=use_triton
+ sym=sym,
+ true_sequential=False,
+ static_groups=False,
+ model_file_base_name=model_base_name,
)
- if output_dir is None:
- return compressed_model
- quantization_config = kwargs["serialization_dict"]
- quantization_config["quant_method"] = "gptq"
- quantization_config.pop("dataset", None) ## pile-10k is not supported in gptq
+ quantization_config.model_file_base_name = model_base_name
+
+ config_dict = quantization_config.to_dict()
+ config_dict["quant_method"] = "gptq"
+ config_dict["autoround_version"] = __version__
+ config_dict["iters"] = iters
+ config_dict["lr"] = lr
+ config_dict["minmax_lr"] = minmax_lr
+ config_dict["enable_minmax_tuning"] = enable_minmax_tuning
+ config_dict["enable_quanted_input"] = enable_quanted_input
+ config_dict["scale_dtype"] = convert_dtype_torch2str_hf(scale_dtype)
if modules_in_block_to_quantize is not None:
- quantization_config["modules_in_block_to_quantize"] = modules_in_block_to_quantize
- if hasattr(model, "config"):
- model.config.quantization_config = quantization_config
- save(compressed_model, output_dir)
-
-
-def save(model: torch.nn.Module, save_dir: str, max_shard_size: str = "5GB", safe_serialization: bool = True):
- """Save model state dict and configs.
-
- Args:
- model (`nn.Module`):
- Model to be saved. The model can be wrapped or unwrapped.
- save_dir (`str`):
- Directory to which to save. Will be created if it doesn't exist.
- max_shard_size (`str`, defaults to `"10GB"`):
- The maximum size for a checkpoint before being sharded. Checkpoints shard will then be each of size
- lower than this size. If expressed as a string, needs to be digits followed by a unit (like `"5MB"`).
- <Tip warning={true}>
-
- If a single weight of the model is bigger than `max_shard_size`, it will be in its own checkpoint shard
- which will be bigger than `max_shard_size`.
-
- </Tip>
- safe_serialization (`bool`, defaults to `True`):
- Whether to save the model using `safetensors` or the traditional PyTorch way (that uses `pickle`).
- """
- os.makedirs(save_dir, exist_ok=True)
- model.save_pretrained(save_dir, max_shard_size=max_shard_size, safe_serialization=safe_serialization)
- config_file = "quantization_config.json"
- if hasattr(model, "config") and hasattr(model.config, "quantization_config"):
- model.config.quantization_config["quant_method"] = "intel/auto-round"
- with open(os.path.join(save_dir, config_file), "w", encoding="utf-8") as f:
- json.dump(model.config.quantization_config, f, indent=2)
+ config_dict["modules_in_block_to_quantize"] = modules_in_block_to_quantize
+
+ with open(join(save_dir, "quantize_config.json"), "w", encoding="utf-8") as f:
+ json.dump(config_dict, f, indent=2)
+
+ config_dict["quant_method"] = "gptq" ##hf transformers could only recognize this value
+ model.config.quantization_config = config_dict
+ model.config.save_pretrained(save_dir)
\ No newline at end of file
diff --git a/auto_round/export/export_to_autoround/export.py b/auto_round/export/export_to_autoround/export.py
index ce7dc07cf..9d3ded310 100644
--- a/auto_round/export/export_to_autoround/export.py
+++ b/auto_round/export/export_to_autoround/export.py
@@ -51,7 +51,7 @@ def get_autogptq_backend_config(backend, bits=4):
use_triton = True
if backend == "gptq:marlin":
use_triton = False
- disable_marlin = True
+ disable_marlin = False
if backend == "gptq:exllamav2": ##need v1 code to export
use_triton = False
disable_marlin = True