PTQ-Level Efficiency, QAT-Level Accuracy | 训练后量化的效率,量化感知训练的精度
Fix autoround format accuracy issue (#179)
wenhuach210126180f3352
diff --git a/README.md b/README.mdindex ea6b26e8c..f9b834fa0 100644--- a/README.md+++ b/README.md@@ -61,18 +61,17 @@ quantization in some scenarios, especially at lower bits,like 2. Please save qua```pythonfrom transformers import AutoModelForCausalLM, AutoTokenizer-model_name = "meta-llama/Llama-2-7b-hf"-model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto", trust_remote_code=True)-tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)+model_name = "facebook/opt-125m"+model = AutoModelForCausalLM.from_pretrained(model_name, device_map="auto")+tokenizer = AutoTokenizer.from_pretrained(model_name)from auto_round import AutoRoundbits, group_size, sym = 4, 128, False-##device:Optional["auto", None, "hpu", "cpu", "cuda"]-autoround = AutoRound(model, tokenizer, bits=bits, group_size=group_size, sym=sym, device=None)+autoround = AutoRound(model, tokenizer, bits=bits, group_size=group_size, sym=sym)autoround.quantize()output_dir = "./tmp_autoround"-autoround.save_quantized(output_dir) ##save_quantized(output_dir,format=="auto_round")+autoround.save_quantized(output_dir) ##save_quantized(output_dir,format="auto_round")```<details>@@ -157,6 +156,7 @@ print(tokenizer.decode(model.generate(**inputs, max_new_tokens=50)[0]))### GPU```python+##pip install auto-gptqfrom transformers import AutoModelForCausalLM, AutoTokenizer##from auto_round.auto_quantizer import AutoHfQuantizer ## uncomment it for models with auto_round formatdiff --git a/auto_round/auto_quantizer.py b/auto_round/auto_quantizer.pyindex 2ddd1f1f0..9b4993072 100644--- a/auto_round/auto_quantizer.py+++ b/auto_round/auto_quantizer.py@@ -223,7 +223,7 @@ class AutoRoundConfig(QuantizationConfigMixin):dataset: str = None,group_size: int = 128,sym: bool = False,- backend="autoround:exllamav2",+ backend="auto_round:exllamav2",layer_config: dict = None,**kwargs,):@@ -273,9 +273,15 @@ class AutoRoundQuantizer(HfQuantizer):if not is_auto_round_available():raise ImportError("Loading a AutoRound quantized model requires auto-round library (`pip install ""auto-round`)")- elif version.parse(importlib.metadata.version("auto_round")) < version.parse("0.2.0"):- raise ImportError("You need a version of auto_round > 0.2.0 to use AutoRound: `pip install --upgrade "- "auto-round`")+ else:+ try:+ import auto_round+ autoround_version = version.parse(auto_round.__version__)+ except:+ autoround_version = version.parse(importlib.metadata.version("auto_round"))+ if autoround_version < version.parse("0.2.0"):+ raise ImportError("You need a version of auto_round > 0.2.0 to use AutoRound: `pip install --upgrade "+ "auto-round` or install from source")def update_torch_dtype(self, torch_dtype: "torch.dtype") -> "torch.dtype":if torch_dtype is None:diff --git a/auto_round/autoround.py b/auto_round/autoround.pyindex 85421f2ec..359af0b85 100644--- a/auto_round/autoround.py+++ b/auto_round/autoround.py@@ -320,7 +320,7 @@ class AutoRound(object):self.layer_config[n]["data_type"] = "float"if self.amp_dtype == torch.bfloat16:self.layer_config[n]["data_type"] = "bfloat"- self.layer_config[n]["bits"] = 16+ self.layer_config[n]["bits"] = 32self.layer_config[n]["group_size"] = Noneself.layer_config[n]["sym"] = None@@ -389,7 +389,7 @@ class AutoRound(object):for key in keys:setattr(m, key, layer_config[n][key])- tmp=1+@torch.no_grad()def get_block_outputs(self, block, input_ids, input_others, bs, device, cache_device):diff --git a/auto_round/export/__init__.py b/auto_round/export/__init__.pyindex 4f4265bba..6b0fd04be 100644--- a/auto_round/export/__init__.py+++ b/auto_round/export/__init__.py@@ -13,7 +13,7 @@# limitations under the License.from .register import EXPORT_FORMAT-from .export_to_autogptq import save_quantized_as_autogptq+from auto_round.export.export_to_autogptq.export import save_quantized_as_autogptqfrom .export_to_itrex import save_quantized_as_itrex, QuantConfigfrom .export_to_autoround.export import save_quantized_as_autorounddiff --git a/auto_round/export/export_to_autogptq/__init__.py b/auto_round/export/export_to_autogptq/__init__.pynew file mode 100644index 000000000..2045808ac--- /dev/null+++ b/auto_round/export/export_to_autogptq/__init__.py@@ -0,0 +1,14 @@+# Copyright (c) 2024 Intel Corporation+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+diff --git a/auto_round/export/export_to_autogptq.py b/auto_round/export/export_to_autogptq/export.pysimilarity index 88%rename from auto_round/export/export_to_autogptq.pyrename to auto_round/export/export_to_autogptq/export.pyindex a80015823..9231b6e63 100644--- a/auto_round/export/export_to_autogptq.py+++ b/auto_round/export/export_to_autogptq/export.py@@ -44,13 +44,12 @@ import torchfrom safetensors.torch import save_file as safe_savefrom auto_round.export.register import register_format-from auto_round.utils import check_to_quantized, get_block_names, get_module, logger--from ..utils import convert_dtype_torch2str_hf+from auto_round.utils import check_to_quantized, get_block_names, get_module, logger, convert_dtype_torch2str_hf+import threadpoolctl as tctl@register_format("auto_gptq")-def save_quantized_as_autogptq(output_dir, use_triton=True, inplace=True, **kwargs):##TODO align with autoround format+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@@ -104,34 +103,17 @@ def save_quantized_as_autogptq(output_dir, use_triton=True, inplace=True, **kwarif bits == 3 or use_triton is False:if bits == 3 and use_triton is True:logger.warning("triton does not support 3 bits, reset it to False")- quantizers = {}- for key in layer_config:- if key == "lm_head": ##TODO remove this after pr 87 is merged- continue- info = layer_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 layer_config:- if key == "lm_head": ##TODO remove this after pr 87 is merged- continue- info = layer_config[key]- if not check_to_quantized(info):- continue- quantizers[key] = (None, info["scale"], info["zp"].to(torch.float32), info["g_idx"])+ use_triton = False+ quantizers = {}+ for key in layer_config:+ if key == "lm_head": ##TODO remove this after pr 87 is merged+ continue+ info = layer_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"])+ with tctl.threadpool_limits(limits=1):pack_model(compressed_model,quantizers,@@ -140,7 +122,7 @@ def save_quantized_as_autogptq(output_dir, use_triton=True, inplace=True, **kwaruse_cuda_fp16=True,desc_act=False,force_layer_back_to_cpu=True,- use_triton=True,+ use_triton=use_triton,)if output_dir is None:return compressed_model@@ -270,4 +252,4 @@ def _save_quantized_to_autogptq(config_dict["quant_method"] = "gptq" ##hf transformers could only recognize this valuemodel.config.quantization_config = config_dict- model.config.save_pretrained(save_dir)\ No newline at end of file+ model.config.save_pretrained(save_dir)diff --git a/auto_round/export/export_to_autoround/export.py b/auto_round/export/export_to_autoround/export.pyindex f7c5e535d..cbb21e6da 100644--- a/auto_round/export/export_to_autoround/export.py+++ b/auto_round/export/export_to_autoround/export.py@@ -73,7 +73,7 @@ def get_autogptq_packing_qlinear(backend, bits=4, group_size=128, sym=False):disable_exllamav1 = Falsedisable_marlin = Trueuse_qigen = False- if "qigen" in "backend":+ if "qigen" in backend:use_triton = Falseuse_qigen = Trueelif "triton" in backend:@@ -104,7 +104,7 @@ def get_autogptq_packing_qlinear(backend, bits=4, group_size=128, sym=False):return QuantLinear-def dynamic_import_quantLienar_for_packing(backend, bits, group_size, sym):+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.@@ -123,7 +123,7 @@ def dynamic_import_quantLienar_for_packing(backend, bits, group_size, sym):if "auto_round" 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 packing with autogptq")+ logger.warning_once(f"autoround format does not support {backend}, try to pack with autogptq")return get_autogptq_packing_qlinear(backend, bits, group_size, sym)from auto_round_extension.cuda.qliner_triton import QuantLinearreturn QuantLinear@@ -135,7 +135,7 @@ def dynamic_import_quantLienar_for_packing(backend, bits, group_size, sym):@register_format("auto_round")-def save_quantized_as_autoround(output_dir, inplace=True, backend="autoround:exllamav2", **kwargs):+def save_quantized_as_autoround(output_dir, inplace=True, backend="auto_round:exllamav2", **kwargs):"""Saves a quantized model in the auto-round format.@@ -159,12 +159,12 @@ def save_quantized_as_autoround(output_dir, inplace=True, backend="autoround:exl"""if ":" not in backend:backend = "autoround:exllamav2"- if not ("triton" in backend or "exllamav2" in backend):- logger.info(f"autoround format does not support {backend}, try to packing with autogptq")-backend = backend.replace("autoround", "auto_round")backend = backend.replace("auto-round", "auto_round")- backend = backend.replace("auto_round", "auto_gptq")+ if not ("triton" in backend or "exllamav2" in backend):+ logger.info(f"autoround format does not support {backend}, try to pack with autogptq")+ backend = backend.replace("auto_round", "auto_gptq")+model = kwargs["model"]model = model.to(torch.float16) ##force to fp16if not inplace:@@ -177,7 +177,7 @@ def save_quantized_as_autoround(output_dir, inplace=True, backend="autoround:exlfor name in layer_config.keys():config = kwargs["layer_config"][name]- if config["data_type"] != "int" and config["bits"] >= 16:+ if config["bits"] > 8:continuelogger.info(f"packing {name}")@@ -188,7 +188,7 @@ def save_quantized_as_autoround(output_dir, inplace=True, backend="autoround:exllayer = get_module(model, name)device = layer.weight.device- QuantLinear = dynamic_import_quantLienar_for_packing(backend, bits, group_size, sym)+ QuantLinear = dynamic_import_quantLinear_for_packing(backend, bits, group_size, sym)if isinstance(layer, nn.Linear):in_features = layer.in_features@@ -226,7 +226,7 @@ def save_quantized_as_autoround(output_dir, inplace=True, backend="autoround:exlquantization_config["backend"] = backendextra_config = {}for layer_name in layer_config:- if layer_config[layer_name]["bits"] >= 16:+ if layer_config[layer_name]["bits"] > 8:continueif layer_name not in layer_names_in_block:extra_config[layer_name] = {}diff --git a/examples/language-modeling/eval_042/evaluation.py b/examples/language-modeling/eval_042/evaluation.pyindex fa1a6f4f0..bf628e9d5 100644--- a/examples/language-modeling/eval_042/evaluation.py+++ b/examples/language-modeling/eval_042/evaluation.py@@ -603,9 +603,7 @@ if __name__ == "__main__":from lm_eval.utils import make_tablemodel_args = f"pretrained={args.model_name}"- if config.torch_dtype == torch.float32:- model_args += ",dtype=float16"- # model_args += ",dtype=float16"+ model_args += ",dtype=float16"if args.trust_remote_code:model_args += f",trust_remote_code=True"result = simple_evaluate(model="hf",diff --git a/examples/language-modeling/main.py b/examples/language-modeling/main.pyindex 5ec9dcb23..b21e28dda 100644--- a/examples/language-modeling/main.py+++ b/examples/language-modeling/main.py@@ -142,7 +142,7 @@ if __name__ == '__main__':tasks = args.tasksuse_eval_legacy = False- if "marlin" in args.deployment_device and args.sym == False:+ if "marlin" in args.deployment_device and args.sym is False:assert False, "marlin backend only supports sym quantization, please set --sym"if args.act_bits <= 8 and args.deployment_device != "fake":@@ -349,8 +349,6 @@ if __name__ == '__main__':device=torch_device, excel_file=excel_name)if not args.disable_eval and lm_eval_version == "0.4.2":- if "round" in eval_folder:- from auto_round.auto_quantizer import AutoHfQuantizerfrom eval_042.evaluation import simple_evaluateif 'gpu' in deployment_device or len(gpu_formats) > 0:diff --git a/requirements.txt b/requirements.txtindex 83ec1fe4e..66cbf2523 100644--- a/requirements.txt+++ b/requirements.txt@@ -6,4 +6,5 @@ torchtransformerstritonnumpy < 2.0-threadpoolctl\ No newline at end of file+threadpoolctl+auto-gptq\ No newline at end of filediff --git a/test/test_autoround.py b/test/test_autoround.pyindex 279f5dee9..8b8e9a8e2 100644--- a/test/test_autoround.py+++ b/test/test_autoround.py@@ -69,9 +69,14 @@ class TestAutoRound(unittest.TestCase):dataset=self.llm_dataloader,)autoround.quantize()++ autoround.save_quantized(output_dir="./saved", inplace=False, format="itrex")+ try:+ import auto_gptq+ except:+ returnif torch.cuda.is_available():autoround.save_quantized(output_dir="./saved", inplace=False)- autoround.save_quantized(output_dir="./saved", inplace=False, format="itrex")def test_sym(self):bits, group_size, sym = 4, 128, Truediff --git a/test/test_autoround_export.py b/test/test_autoround_export_to_itrex.pysimilarity index 100%rename from test/test_autoround_export.pyrename to test/test_autoround_export_to_itrex.pydiff --git a/test/test_conv1d.py b/test/test_conv1d.pyindex b2e51a24e..0d010051d 100644--- a/test/test_conv1d.py+++ b/test/test_conv1d.py@@ -30,7 +30,7 @@ class TestQuantizationConv1d(unittest.TestCase):shutil.rmtree("runs", ignore_errors=True)- def test_wa_quant(self):+ def test_quant(self):self.model = AutoModelForCausalLM.from_pretrained(self.model_name, torch_dtype="auto", trust_remote_code=True)bits, group_size, sym = 4, 128, Falseautoround = AutoRound(@@ -44,7 +44,12 @@ class TestQuantizationConv1d(unittest.TestCase):dataset=self.llm_dataloader,)+autoround.quantize()+ try:+ import auto_gptq+ except:+ returnautoround.save_quantized("./saved")diff --git a/test/test_export.py b/test/test_export.pynew file mode 100644index 000000000..7a747837b--- /dev/null+++ b/test/test_export.py@@ -0,0 +1,154 @@+import copy+import shutil+import sys+import unittest++sys.path.insert(0, "..")+import torch+import transformers+from transformers import AutoModelForCausalLM, AutoTokenizer++from auto_round import AutoRound+++class LLMDataLoader:+ def __init__(self):+ self.batch_size = 1++ def __iter__(self):+ for i in range(2):+ yield torch.ones([1, 10], dtype=torch.long)+++class TestAutoRound(unittest.TestCase):+ @classmethod+ def setUpClass(self):+ model_name = "facebook/opt-125m"+ self.model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto", trust_remote_code=True)+ self.tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)+ self.llm_dataloader = LLMDataLoader()++ @classmethod+ def tearDownClass(self):+ shutil.rmtree("./saved", ignore_errors=True)+ shutil.rmtree("runs", ignore_errors=True)++ def test_autogptq_format(self):+ if not torch.cuda.is_available():+ return+ try:+ import auto_gptq+ except:+ return+ bits, group_size, sym = 4, 128, False+ autoround = AutoRound(+ self.model,+ self.tokenizer,+ bits=bits,+ group_size=group_size,+ sym=sym,+ iters=2,+ seqlen=2,+ dataset=self.llm_dataloader,+ )+ autoround.quantize()+ quantized_model_path = "./saved"++ autoround.save_quantized(output_dir=quantized_model_path, inplace=False, format="auto_gptq")+ model = AutoModelForCausalLM.from_pretrained(quantized_model_path, device_map="auto", trust_remote_code=True)+ tokenizer = AutoTokenizer.from_pretrained(quantized_model_path)+ 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]))+ shutil.rmtree("./saved", ignore_errors=True)++ # def test_autogptq_marlin_format(self):+ #+ # if not torch.cuda.is_available():+ # return+ # try:+ # import auto_gptq+ # except:+ # return+ # bits, group_size, sym = 4, 128, True+ # autoround = AutoRound(+ # self.model,+ # self.tokenizer,+ # bits=bits,+ # group_size=group_size,+ # sym=sym,+ # iters=2,+ # seqlen=2,+ # dataset=self.llm_dataloader,+ # )+ # autoround.quantize()+ # quantized_model_path = "./saved"+ #+ # autoround.save_quantized(output_dir=quantized_model_path, inplace=False, format="auto_gptq")+ #+ # from auto_gptq import AutoGPTQForCausalLM+ # model = AutoGPTQForCausalLM.from_quantized(quantized_model_path, device_map="auto", use_safetensors=True,+ # use_marlin=True)+ # tokenizer = AutoTokenizer.from_pretrained(quantized_model_path)+ # 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]))+ # shutil.rmtree("./saved", ignore_errors=True)++ def test_autoround_format(self):+ bits, group_size, sym = 4, 128, False+ autoround = AutoRound(+ self.model,+ self.tokenizer,+ bits=bits,+ group_size=group_size,+ sym=sym,+ iters=2,+ seqlen=2,+ dataset=self.llm_dataloader,+ )+ autoround.quantize()+ quantized_model_path = "./saved"++ autoround.save_quantized(output_dir=quantized_model_path, inplace=False, format="auto_round")++ from auto_round.auto_quantizer import AutoHfQuantizer+ model = AutoModelForCausalLM.from_pretrained(quantized_model_path, device_map="auto")+ tokenizer = AutoTokenizer.from_pretrained(quantized_model_path)+ 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]))+ shutil.rmtree("./saved", ignore_errors=True)++ # def test_autoround_marlin_format(self):+ # if not torch.cuda.is_available():+ # return+ # try:+ # import auto_gptq+ # except:+ # return+ # bits, group_size, sym = 4, 128, True+ # autoround = AutoRound(+ # self.model,+ # self.tokenizer,+ # bits=bits,+ # group_size=group_size,+ # sym=sym,+ # iters=2,+ # seqlen=2,+ # dataset=self.llm_dataloader,+ # )+ # autoround.quantize()+ # quantized_model_path = "./saved"+ #+ # autoround.save_quantized(output_dir=quantized_model_path, inplace=False, format="auto_round:marlin")+ #+ # from auto_round.auto_quantizer import AutoHfQuantizer+ # model = AutoModelForCausalLM.from_pretrained(quantized_model_path, device_map="auto")+ # tokenizer = AutoTokenizer.from_pretrained(quantized_model_path)+ # 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]))+ # shutil.rmtree("./saved", ignore_errors=True)+ #+