PTQ-Level Efficiency, QAT-Level Accuracy | 训练后量化的效率,量化感知训练的精度
Support force loading into autoround Format (#453)
WeiweiZhang1a79d1a360f5c
diff --git a/auto_round/auto_quantizer.py b/auto_round/auto_quantizer.pyindex 305f64ab3..5b6ebc93b 100644--- a/auto_round/auto_quantizer.py+++ b/auto_round/auto_quantizer.py@@ -126,7 +126,7 @@ class AutoHfQuantizer:else:quantization_config = AutoQuantizationConfig.from_dict(quantization_config) # pylint: disable=E1101quant_method = quantization_config.quant_method-+# Again, we need a special care for bnb as we have a single quantization config# class for both 4-bit and 8-bit quantizationif quant_method == QuantizationMethod.BITS_AND_BYTES:@@ -169,16 +169,30 @@ class AutoHfQuantizer:else:warning_msg = ""+ loading_attr_dict = quantization_config_from_args.get_loading_attributes() \+ if quantization_config_from_args is not None else Noneif isinstance(quantization_config, dict):if "auto-round" in quantization_config["quant_method"]:quantization_config = AutoRoundConfig.from_dict(quantization_config)else:- quantization_config = AutoQuantizationConfig.from_dict(quantization_config) # pylint: disable=E1101+ if isinstance(quantization_config_from_args, (AutoRoundConfig)):+ logger.info(f"Loading quantized model in auto_round format.")+ tmp_backend = quantization_config["quant_method"]+ target_backend = quantization_config["backend"] if "backend" in quantization_config else "auto"+ if loading_attr_dict is not None and "backend" in loading_attr_dict:+ target_backend = loading_attr_dict["backend"]+ loading_attr_dict.pop("backend")+ if "auto_round" not in target_backend:+ target_backend = f"auto_round:{tmp_backend}" #+ quantization_config = AutoRoundConfig.from_dict(quantization_config)+ setattr(quantization_config, "backend", target_backend)+ else:+ quantization_config = AutoQuantizationConfig.from_dict(quantization_config) # pylint: disable=E1101if isinstance(quantization_config,(GPTQConfig, AwqConfig, AutoRoundConfig)) and quantization_config_from_args is not None:# special case for GPTQ / AWQ config collision- loading_attr_dict = quantization_config_from_args.get_loading_attributes()+for attr, val in loading_attr_dict.items():setattr(quantization_config, attr, val)warning_msg += (@@ -270,7 +284,7 @@ class AutoRoundConfig(QuantizationConfigMixin):def get_loading_attributes(self):# attributes_dict = copy.deepcopy(self.__dict__)- loading_attibutes_dict = {"target_backend": self.backend}+ loading_attibutes_dict = {"backend": self.backend}# loading_attributes = ["backend"]# loading_attibutes_dict = {i: j for i, j in attributes_dict.items() if i in loading_attributes}return loading_attibutes_dict@@ -419,6 +433,7 @@ class AutoRoundQuantizer(HfQuantizer):quantization_config.target_backend = quantization_config.backendtarget_device = self.detect_device(quantization_config.target_backend, quantization_config.backend)+ target_device = self.detect_device(None, quantization_config.backend)self.target_device = target_device@@ -782,3 +797,4 @@ if version.parse(transformers.__version__) < version.parse("4.38.0"):transformers.quantizers.auto.AutoHfQuantizer = AutoHfQuantizertransformers.modeling_utils.AutoHfQuantizer = AutoHfQuantizer+diff --git a/auto_round/export/export_to_awq/export.py b/auto_round/export/export_to_awq/export.pyindex 0a6146bea..637a67e81 100644--- a/auto_round/export/export_to_awq/export.py+++ b/auto_round/export/export_to_awq/export.py@@ -49,8 +49,7 @@ def pack_layer(name, model, layer_config, backend, pbar):linear_layer = get_module(model, name)scale, zp = linear_layer.scale, linear_layer.zpscale = scale.t().contiguous()- zp = zp.t().contiguous()- # config["zp"] = config["zp"].to(torch.float32)+ zp = zp.t().contiguous().to(torch.float32)bits = config["bits"]group_size = config["group_size"]diff --git a/auto_round_extension/ipex/qlinear_ipex_awq.py b/auto_round_extension/ipex/qlinear_ipex_awq.pyindex c90e9861b..46a42d898 100644--- a/auto_round_extension/ipex/qlinear_ipex_awq.py+++ b/auto_round_extension/ipex/qlinear_ipex_awq.py@@ -50,10 +50,18 @@ class QuantLinear(nn.Module):def post_init(self):assert self.qweight.device.type == "cpu"+ from packaging import version+ from auto_round.auto_quantizer import importlib_metadatafrom intel_extension_for_pytorch.nn.modules.weight_only_quantization import WeightOnlyQuantizedLinear- self.ipex_linear = WeightOnlyQuantizedLinear.from_weight(self.qweight, self.scales, self.qzeros, \- self.in_features, self.out_features, None, self.bias, \- self.group_size, None, 0, 1)+ version_ipex = version.parse(importlib_metadata.version("intel_extension_for_pytorch"))+ if version_ipex < version.parse("2.6.0"):+ self.ipex_linear = WeightOnlyQuantizedLinear.from_weight(self.qweight, self.scales, self.qzeros, \+ self.in_features, self.out_features, None, self.bias, \+ self.group_size, None, 0, 1)+ else:+ self.ipex_linear = WeightOnlyQuantizedLinear.from_weight(self.qweight, self.scales, self.qzeros, \+ self.in_features, self.out_features, None, self.bias, \+ self.group_size, None, 1, 0)@classmethoddef from_linear(cls, linear, w_bit, group_size, init_only=False, scales=None):@@ -85,3 +93,4 @@ class QuantLinear(nn.Module):self.w_bit,self.group_size,))+diff --git a/test/test_export.py b/test/test_export.pyindex aa19c89b1..238f41158 100644--- a/test/test_export.py+++ b/test/test_export.py@@ -36,10 +36,6 @@ class TestAutoRound(unittest.TestCase):def test_autogptq_format(self):if not torch.cuda.is_available():return- try:- import auto_gptq- except:- returnbits, group_size, sym = 4, 128, Falseautoround = AutoRound(self.model,@@ -131,10 +127,6 @@ class TestAutoRound(unittest.TestCase):def test_autoround_awq_format(self):- try:- import awq- except:- returnbits, group_size, sym = 4, 128, Falseautoround = AutoRound(self.model,@@ -150,8 +142,11 @@ class TestAutoRound(unittest.TestCase):quantized_model_path = "./saved"autoround.save_quantized(output_dir=quantized_model_path, inplace=False, format="auto_round:awq")-- from auto_round.auto_quantizer import AutoHfQuantizer+ try:+ import awq+ except:+ return+ from auto_round import AutoRoundConfigmodel = AutoModelForCausalLM.from_pretrained(quantized_model_path, device_map="auto")tokenizer = AutoTokenizer.from_pretrained(quantized_model_path)text = "There is a girl who likes adventure,"@@ -160,10 +155,6 @@ class TestAutoRound(unittest.TestCase):shutil.rmtree("./saved", ignore_errors=True)def test_autoawq_format(self):- try:- import awq- except:- returnbits, group_size, sym = 4, 128, Falseautoround = AutoRound(self.model,@@ -180,8 +171,10 @@ class TestAutoRound(unittest.TestCase):autoround.save_quantized(output_dir=quantized_model_path, inplace=False, \format="auto_awq", model_path="facebook/opt-125m")-- from auto_round.auto_quantizer import AutoHfQuantizer+ try:+ import awq+ except:+ returnmodel = AutoModelForCausalLM.from_pretrained(quantized_model_path, device_map="auto")tokenizer = AutoTokenizer.from_pretrained(quantized_model_path)text = "There is a girl who likes adventure,"@@ -219,4 +212,4 @@ class TestAutoRound(unittest.TestCase):# 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)- #\ No newline at end of file+ #diff --git a/test/test_generation.py b/test/test_generation.pyindex c2f2a333e..8772d41b4 100644--- a/test/test_generation.py+++ b/test/test_generation.py@@ -98,6 +98,7 @@ class TestAutoRoundFormatGeneration(unittest.TestCase):res = tokenizer.decode(model.generate(**inputs, max_new_tokens=50)[0])print(res)assert ("!!!" not in res)+def test_llm_generation_asym_qbits(self):try:import intel_extension_for_transformers@@ -133,7 +134,35 @@ class TestAutoRoundFormatGeneration(unittest.TestCase):res = tokenizer.decode(model.generate(**inputs, max_new_tokens=50)[0])print(res)assert ("!!!" not in res)----++ def test_force_to_autoround_format(self):+ bits = 4+ group_size = 128+ autoround = AutoRound(+ self.model,+ self.tokenizer,+ bits=bits,+ group_size=group_size,+ sym=True,+ iters=1,+ seqlen=2,+ dataset=self.llm_dataloader,+ )+ autoround.quantize()+ quantized_model_path = "./saved"+ autoround.save_quantized(output_dir=quantized_model_path, format="auto_awq", inplace=False)+ device = "auto" ##cpu, hpu, cuda, auto+ from auto_round import AutoRoundConfig+ quantization_config = AutoRoundConfig(+ # backend="auto_round:ipex_awq",+ backend="auto"+ )+ model = AutoModelForCausalLM.from_pretrained(quantized_model_path, device_map=device,+ quantization_config=quantization_config)+ tokenizer = AutoTokenizer.from_pretrained(quantized_model_path)+ text = "There is a girl who likes adventure,"+ inputs = tokenizer(text, return_tensors="pt").to(model.device)+ res = tokenizer.decode(model.generate(**inputs, max_new_tokens=50)[0])+ print(res)+ assert ("!!!" not in res)+