PTQ-Level Efficiency, QAT-Level Accuracy | 训练后量化的效率,量化感知训练的精度
avoid potential bug for auto-gptq 0.8 (#250)
wenhuach215dd16fc34a97
diff --git a/README.md b/README.mdindex 8a4170e74..31364a528 100644--- a/README.md+++ b/README.md@@ -51,7 +51,7 @@ pip install auto-round## Model Quantization-### API Usage+### API Usage (Gaudi2/CPU/GPU)```pythonfrom transformers import AutoModelForCausalLM, AutoTokenizer@@ -129,8 +129,8 @@ autoround.save_quantized(output_dir, format='auto_round', inplace=True)</details>-### Basic Usage (auto-round version > 0.3.0)-AutoRound support Gaudi2, CPU and GPU. A user guide detailing the full list of supported arguments is provided by calling ```auto_round -h``` on the terminal. Alternatively, you can use ```auto-round``` instead of ```auto_round```.+### Basic Usage (version > 0.3.0)+A user guide detailing the full list of supported arguments is provided by calling ```auto_round -h``` on the terminal. Alternatively, you can use ```auto-round``` instead of ```auto_round```.```bashdiff --git a/auto_round/export/export_to_autogptq/export.py b/auto_round/export/export_to_autogptq/export.pyindex 836fa4e50..f051304aa 100644--- a/auto_round/export/export_to_autogptq/export.py+++ b/auto_round/export/export_to_autogptq/export.py@@ -36,8 +36,8 @@# SOFTWARE.import torch-from auto_round.utils import check_to_quantized, get_block_names,\- get_module, logger, get_layer_names_in_block, set_module+from auto_round.utils import check_to_quantized, get_block_names, \+ get_module, logger, get_layer_names_in_block, set_moduleimport copyimport jsonimport os@@ -50,54 +50,7 @@ import threadpoolctl as tctlimport inspectfrom tqdm import tqdmfrom concurrent.futures import ThreadPoolExecutor--def get_autogptq_packing_qlinear(backend, bits=4, group_size=128, sym=False):- """- Configures and returns a QuantLinear class based on the specified backend and parameters.-- Args:- backend (str): The backend to be used for quantization. Supported values include "qigen", "triton", "marlin",- "exllama", and "cuda".- bits (int, optional): The number of bits for quantization. Default is 4.- group_size (int, optional): The group size for quantization. Default is 128.- sym (bool, optional): Flag indicating whether to use symmetric quantization. Default is False.-- Returns:- class: The dynamically imported QuantLinear class configured according to the specified parameters.- """- use_triton = True- disable_exllamav2 = True- disable_exllamav1 = False- disable_marlin = True- use_qigen = False- if "qigen" in backend:- use_triton = False- use_qigen = True- elif "marlin" in backend and sym:- use_triton = False- disable_marlin = False- else:- ##we all use triton for others, ##TODO may have bugs for some backends- from auto_round.export.export_to_autogptq.qlinear_triton import QuantLinear- return QuantLinear- try:- import auto_gptq # pylint: disable=E0401- except:- logger.warning_once(f"please install auto_gptq via 'pip install auto-gptq' to support exporting to {backend}")- exit()-- from auto_gptq.utils.import_utils import dynamically_import_QuantLinear # pylint: disable=E0401- QuantLinear = dynamically_import_QuantLinear(- use_triton=use_triton,- desc_act=False,- group_size=group_size,- bits=bits,- disable_exllama=disable_exllamav1,- disable_exllamav2=disable_exllamav2,- use_qigen=use_qigen,- disable_marlin=disable_marlin,- )- return QuantLinear+from auto_round.utils import get_autogptq_packing_qlineardef pack_layer(name, model, layer_config, backend, pbar):@@ -152,8 +105,8 @@ def pack_layer(name, model, layer_config, backend, pbar):qlayer.pack(layer, scale, zero, None)qlayer.to(device)pbar.update(1)--++@register_format("auto_gptq")def save_quantized_as_autogptq(output_dir, inplace=True, backend="auto_gptq:exllamav2",**kwargs):@@ -162,7 +115,7 @@ def save_quantized_as_autogptq(output_dir, inplace=True, backend="auto_gptq:exllmodel = kwargs["model"]tokenizer = kwargs["tokenizer"]supported_types = kwargs["supported_types"]- safe_serialization = True if 'safe_serialization' not in kwargs.keys() else kwargs["safe_serialization"]+ safe_serialization = True if 'safe_serialization' not in kwargs.keys() else kwargs["safe_serialization"]quant_block_list = kwargs["quant_block_list"]logger.info("Saving quantized model to autogptq format, this may take a while...")if tokenizer is not None:@@ -220,7 +173,6 @@ def save_quantized_as_autogptq(output_dir, inplace=True, backend="auto_gptq:exllreturn model-def save(model: torch.nn.Module, save_dir: str, max_shard_size: str = "5GB", safe_serialization: bool = True):"""Save model state dict and configs.@@ -248,7 +200,3 @@ def save(model: torch.nn.Module, save_dir: str, max_shard_size: str = "5GB", safif hasattr(model, "config") and hasattr(model.config, "quantization_config"):with open(os.path.join(save_dir, config_file), "w", encoding="utf-8") as f:json.dump(model.config.quantization_config, f, indent=2)----diff --git a/auto_round/export/export_to_autoround/export.py b/auto_round/export/export_to_autoround/export.pyindex f5fc540a7..b8ca27d26 100644--- a/auto_round/export/export_to_autoround/export.py+++ b/auto_round/export/export_to_autoround/export.py@@ -27,6 +27,7 @@ import threadpoolctl as tctlimport inspectfrom tqdm import tqdmfrom concurrent.futures import ThreadPoolExecutor+from auto_round.utils import get_autogptq_packing_qlineardef check_neq_config(config, data_type, bits, group_size, sym):@@ -51,62 +52,12 @@ def check_neq_config(config, data_type, bits, group_size, sym):return [key for key, expected_value in expected_config.items() if config.get(key) != expected_value]-def get_autogptq_packing_qlinear(backend, bits=4, group_size=128, sym=False):- """- Configures and returns a QuantLinear class based on the specified backend and parameters.-- Args:- backend (str): The backend to be used for quantization. Supported values include "qigen", "triton", "marlin",- "exllama", and "cuda".- bits (int, optional): The number of bits for quantization. Default is 4.- group_size (int, optional): The group size for quantization. Default is 128.- sym (bool, optional): Flag indicating whether to use symmetric quantization. Default is False.-- Returns:- class: The dynamically imported QuantLinear class configured according to the specified parameters.- """- use_triton = True- disable_exllamav2 = True- disable_exllamav1 = False- disable_marlin = True- use_qigen = False- if "qigen" in backend:- use_triton = False- use_qigen = True- elif "triton" in backend:- use_triton = True- elif "marlin" in backend and sym:- use_triton = False- disable_marlin = False- elif "exllama" in backend: ##need v1 code to export- use_triton = True ##same with triton- disable_marlin = True- elif "cuda" in backend:- use_triton = False- disable_marlin = True- disable_exllamav2 = True- disable_exllamav1 = True-- from auto_gptq.utils.import_utils import dynamically_import_QuantLinear # pylint: disable=E0401- QuantLinear = dynamically_import_QuantLinear(- use_triton=use_triton,- desc_act=False,- group_size=group_size,- bits=bits,- disable_exllama=disable_exllamav1,- disable_exllamav2=disable_exllamav2,- use_qigen=use_qigen,- disable_marlin=disable_marlin,- )- return QuantLinear--def dynamic_import_quantLinear_for_packing(backend, bits, group_size, sym):"""Dynamically imports and returns the appropriate QuantLinear class based on the specified backend and parameters.Args:- backend (str): The backend to be used for quantization. Supported values include "auto_round" and "gptq".+ backend (str): The backend to be used for quantization. Supported values include "auto_round" "awq" and "gptq".bits (int): The number of bits for quantization.group_size (int): The group size for quantization.sym (bool): Flag indicating whether to use symmetric quantization.@@ -117,10 +68,10 @@ def dynamic_import_quantLinear_for_packing(backend, bits, group_size, sym):Raises:AssertionError: If the backend is not supported."""- if "auto_round" in backend and "awq" not in backend:+ if "auto_round" in backend and "awq" not in backend and "gptq" not in backend:##only support triton and exllamav2if not ("triton" in backend or "exllamav2" in backend):- logger.warning_once(f"autoround format does not support {backend}, try to pack with autogptq")+ logger.warning_once(f"auto_round format does not support {backend}, try to pack each layer with auto_gptq")return get_autogptq_packing_qlinear(backend, bits, group_size, sym)from auto_round_extension.cuda.qlinear_triton import QuantLinearreturn QuantLinear@@ -130,7 +81,7 @@ def dynamic_import_quantLinear_for_packing(backend, bits, group_size, sym):elif "gptq" in backend:return get_autogptq_packing_qlinear(backend, bits, group_size, sym)else:- assert False, f"only support gptq and autoround backend"+ assert False, f"only support auto_gptq, auto_awq and auto_round backend"def pack_layer(name, model, layer_config, backend, pbar):@@ -226,11 +177,11 @@ def save_quantized_as_autoround(output_dir, inplace=True, backend="auto_round:exAssertionError: If the backend is not supported."""if ":" not in backend:- backend = "autoround:exllamav2"+ backend = "auto_round:exllamav2"backend = backend.replace("autoround", "auto_round")backend = backend.replace("auto-round", "auto_round")- if not ("triton" in backend or "exllamav2" in backend or "awq" in backend):- logger.info(f"autoround format does not support {backend}, try to pack with autogptq")+ if not ("triton" in backend or "exllamav2" in backend or "awq" in backend or "gptq" in backend):+ logger.info(f"auto_round format does not support {backend}, try to pack each layer with autogptq")backend = backend.replace("auto_round", "auto_gptq")model = kwargs["model"]@@ -359,4 +310,3 @@ def save_awq(if hasattr(model, "config") and hasattr(model.config, "quantization_config"):with open(os.path.join(save_dir, config_file), "w", encoding="utf-8") as f:json.dump(quantization_config, f, indent=2)-diff --git a/auto_round/utils.py b/auto_round/utils.pyindex 038e14045..6eeb81c8a 100644--- a/auto_round/utils.py+++ b/auto_round/utils.py@@ -339,9 +339,10 @@ def collect_best_params(block):if hasattr(m, "orig_layer"):params[n] = {}for key in m.params.keys():- params[n][key]=copy.deepcopy(m.params[key].data)+ params[n][key] = copy.deepcopy(m.params[key].data)return params+@torch.no_grad()def sampling_inputs(input_ids, input_others, indices, seqlen,share_attention_mask_flag=False, not_share_position_ids_flag=False, input_dim=0):@@ -710,10 +711,14 @@ def get_autogptq_infer_linear(backend, bits=4, group_size=128, sym=False):disable_exllamav1 = Falsedisable_marlin = Trueuse_qigen = False+ use_tritonv2 = Falseif "qigen" in backend:use_qigen = Trueelif "triton" in backend:use_triton = True+ elif "tritonv2" in backend:+ use_triton = False+ use_tritonv2 = Trueelif "marlin" in backend:use_triton = Falsedisable_marlin = False@@ -730,16 +735,31 @@ def get_autogptq_infer_linear(backend, bits=4, group_size=128, sym=False):disable_exllamav2 = Truedisable_exllamav1 = Truefrom auto_gptq.utils.import_utils import dynamically_import_QuantLinear # pylint: disable=E0401- QuantLinear = dynamically_import_QuantLinear(- use_triton=use_triton,- desc_act=False,- group_size=group_size,- bits=bits,- disable_exllama=disable_exllamav1,- disable_exllamav2=disable_exllamav2,- use_qigen=use_qigen,- disable_marlin=disable_marlin,- )+ version = get_library_version("auto_gptq")+ from packaging.version import Version+ if Version(version) <= Version("0.7.1"):+ QuantLinear = dynamically_import_QuantLinear(+ use_triton=use_triton,+ desc_act=False,+ group_size=group_size,+ bits=bits,+ disable_exllama=disable_exllamav1,+ disable_exllamav2=disable_exllamav2,+ use_qigen=use_qigen,+ disable_marlin=disable_marlin+ )+ else:+ QuantLinear = dynamically_import_QuantLinear(+ use_triton=use_triton,+ desc_act=False,+ group_size=group_size,+ bits=bits,+ disable_exllama=disable_exllamav1,+ disable_exllamav2=disable_exllamav2,+ use_qigen=use_qigen,+ use_marlin=not disable_marlin,+ use_tritonv2=use_tritonv2+ )return QuantLinear@@ -806,3 +826,83 @@ def dynamic_import_inference_linear(backend, bits, group_size, sym):from auto_round_extension.cuda.qlinear_tritonv2 import QuantLinearreturn QuantLinear++def get_library_version(library_name):+ import pkg_resources+ try:+ version = pkg_resources.get_distribution(library_name).version+ return version+ except pkg_resources.DistributionNotFound:+ return f"{library_name} is not installed"+++def get_autogptq_packing_qlinear(backend, bits=4, group_size=128, sym=False):+ """+ Configures and returns a QuantLinear class based on the specified backend and parameters.++ Args:+ backend (str): The backend to be used for quantization. Supported values include "qigen", "triton", "marlin",+ "exllama", and "cuda".+ bits (int, optional): The number of bits for quantization. Default is 4.+ group_size (int, optional): The group size for quantization. Default is 128.+ sym (bool, optional): Flag indicating whether to use symmetric quantization. Default is False.++ Returns:+ class: The dynamically imported QuantLinear class configured according to the specified parameters.+ """+ use_triton = True+ disable_exllamav2 = True+ disable_exllamav1 = False+ disable_marlin = True+ use_qigen = False+ if "qigen" in backend:+ use_triton = False+ use_qigen = True+ elif "triton" in backend:+ use_triton = True+ elif "marlin" in backend and sym:+ use_triton = False+ disable_marlin = False+ elif "exllama" in backend: ##need v1 code to export+ use_triton = True ##same with triton+ disable_marlin = True+ elif "cuda" in backend:+ use_triton = False+ disable_marlin = True+ disable_exllamav2 = True+ disable_exllamav1 = True+ if use_triton:+ from auto_round.export.export_to_autogptq.qlinear_triton import QuantLinear+ return QuantLinear+ try:+ import auto_gptq # pylint: disable=E0401+ except:+ logger.error(f"please install auto_gptq via 'pip install auto-gptq' to support exporting to {backend}")+ exit()++ from auto_gptq.utils.import_utils import dynamically_import_QuantLinear # pylint: disable=E0401+ version = get_library_version("auto_gptq")+ from packaging.version import Version+ if Version(version) <= Version("0.7.1"):+ QuantLinear = dynamically_import_QuantLinear(+ use_triton=use_triton,+ desc_act=False,+ group_size=group_size,+ bits=bits,+ disable_exllama=disable_exllamav1,+ disable_exllamav2=disable_exllamav2,+ use_qigen=use_qigen,+ disable_marlin=disable_marlin,+ )+ else:+ QuantLinear = dynamically_import_QuantLinear(+ use_triton=use_triton,+ desc_act=False,+ group_size=group_size,+ bits=bits,+ disable_exllama=disable_exllamav1,+ disable_exllamav2=disable_exllamav2,+ use_qigen=use_qigen,+ use_marlin=not disable_marlin,+ )+ return QuantLineardiff --git a/examples/language-modeling/README.md b/examples/language-modeling/README.mdindex f9fb00598..da9184289 100644--- a/examples/language-modeling/README.md+++ b/examples/language-modeling/README.md@@ -85,11 +85,13 @@ CUDA_VISIBLE_DEVICES=0 python3 main.py --model_name facebook/opt-125m --bits 4- **Enable marlin kernel:**+please install auto-gptq from source+```bash-CUDA_VISIBLE_DEVICES=0 python3 main.py --model_name facebook/opt-125m --sym --bits 4 --group_size 128 --deployment_device "auto_round:marlin"+CUDA_VISIBLE_DEVICES=0 python3 main.py --model_name facebook/opt-125m --sym --bits 4 --group_size 128 --format "auto_round:gptq:marlin"```-for AutoGPTQ format, enable `--sym` in the quantization and set the deployment_device to "gpu" and then follow the API in AutoGPTQ+for AutoGPTQ format, enable `--sym` in the quantization and set the format to "auto_gptq" and then follow the API in AutoGPTQ- **Utilize the AdamW Optimizer:**diff --git a/requirements.txt b/requirements.txtindex 31b70312a..987d26b6d 100644--- a/requirements.txt+++ b/requirements.txt@@ -9,4 +9,5 @@ numpy < 2.0threadpoolctllm-eval==0.4.4intel-extension-for-transformers-tqdm\ No newline at end of file+tqdm+packaging\ No newline at end of file