PTQ-Level Efficiency, QAT-Level Accuracy | 训练后量化的效率,量化感知训练的精度
support autoround hpu format (#182)
yintong-lu72f5ce8011f7
diff --git a/README.md b/README.mdindex 186825bf2..953e742cf 100644--- a/README.md+++ b/README.md@@ -168,6 +168,23 @@ inputs = tokenizer(text, return_tensors="pt").to(model.device)print(tokenizer.decode(model.generate(**inputs, max_new_tokens=50)[0]))```+### Intel Gaudi-2++```python+import torch+from transformers import AutoModelForCausalLM, AutoTokenizer+from auto_round.auto_quantizer import AutoHfQuantizer+import habana_frameworks.torch.core as htcore+import habana_frameworks.torch.hpu as hthpu+quantized_model_path = "./tmp_autoround"+model = AutoModelForCausalLM.from_pretrained(quantized_model_path, device_map="auto").to('hpu').to(torch.float32)+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]))+```++## Support List| Model | Supported |diff --git a/auto_round/auto_quantizer.py b/auto_round/auto_quantizer.pyindex 9b4993072..4bc89710b 100644--- a/auto_round/auto_quantizer.py+++ b/auto_round/auto_quantizer.py@@ -106,6 +106,16 @@ def is_autoround_exllamav2_available():res = Falsereturn res+def is_hpu_supported(): # pragma: no cover+ try:+ import subprocess+ import habana_frameworks.torch.core as htcore # pylint: disable=E0401+ hqt_version = subprocess.check_output(['pip', 'show', \+ 'habana_quantization_toolkit']).decode().split('\n')[1].split(': ')[1]+ assert(hqt_version >= "1.17")+ except ImportError as e:+ return False+ return Trueif is_auto_round_available():from auto_round_extension.cuda.post_init import autoround_post_init@@ -145,7 +155,7 @@ class AutoHfQuantizer:f"Unknown quantization type, got {quant_method} - supported types are:"f" {list(AUTO_QUANTIZER_MAPPING.keys())}")- if "auto-round" in quant_method:+ if "auto-round" in quant_method or is_hpu_supported(): # pragma: no covertarget_cls = AutoRoundQuantizerelse:target_cls = AUTO_QUANTIZER_MAPPING[quant_method]@@ -303,7 +313,8 @@ class AutoRoundQuantizer(HfQuantizer):quantization_config = model.config.quantization_configbits = quantization_config.bitsgroup_size = quantization_config.group_size- data_type = quantization_config.data_type+ data_type = quantization_config.data_type if hasattr(quantization_config, "data_type") \+ else "int" # pragma: no coversym = quantization_config.symextra_config = {}if hasattr(quantization_config, "extra_config"):@@ -323,7 +334,12 @@ class AutoRoundQuantizer(HfQuantizer):layer_configs[layer_name]["group_size"] = extra_config[layer_name].get("group_size", group_size)layer_configs[layer_name]["data_type"] = extra_config[layer_name].get("data_type", data_type)layer_configs[layer_name]["sym"] = extra_config[layer_name].get("sym", sym)- backend = quantization_config.backend+ if hasattr(quantization_config, "backend"): # pragma: no cover+ backend = quantization_config.backend+ elif 'gptq' in quantization_config.quant_method: # pragma: no cover+ backend = 'gptq'+ else: # pragma: no cover+ logger.error("Please specify quantization backend")self._replace_by_quant_layers(model, layer_configs, backend)return modeldiff --git a/auto_round/utils.py b/auto_round/utils.pyindex 43f1043b1..195c2586c 100644--- a/auto_round/utils.py+++ b/auto_round/utils.py@@ -381,7 +381,7 @@ def detect_device(device=None):if torch.cuda.is_available():device = torch.device("cuda")logger.info("Using GPU device")- elif is_optimum_habana_available():+ elif is_optimum_habana_available(): # pragma: no coverdevice = torch.device("hpu")logger.info("Using HPU device")# Use CPU as a fallback@@ -574,7 +574,7 @@ def check_memory_availability(device, inputs, weight, org_seqlen, org_bs):total_memory = torch.cuda.get_device_properties(current_gpu_index).total_memoryused_memory = torch.cuda.memory_allocated(current_gpu_index)free_space = total_memory - used_memory- elif "hpu" in device:+ elif "hpu" in device: # pragma: no covercurrent_hpu_index = torch.hpu.current_device()free_space = torch.hpu.memory_reserved(current_hpu_index)else:@@ -691,8 +691,7 @@ def dynamic_import_inference_linear(backend, bits, group_size, sym):"""exllama2_available = is_autoround_exllamav2_available()##TODO may have bug for marlin backend- if (- not torch.cuda.is_available()) or "qbits" in backend or "cpu" in backend:+ if (not torch.cuda.is_available() and not is_optimum_habana_available()) or "qbits" in backend or "cpu" in backend:try:from intel_extension_for_transformers import qbits # pylint: disable=E0401except Exception as e:@@ -701,11 +700,28 @@ def dynamic_import_inference_linear(backend, bits, group_size, sym):import auto_round_extension.qbits.qlinear_qbits as qlinear_qbitsreturn qlinear_qbits.QuantLinearif "gptq" in backend:+ if not is_optimum_habana_available():+ try:+ import auto_gptq # pylint: disable=E0401+ except Exception as e:+ raise ImportError("Please install auto-gptq via 'pip install auto-gptq' to support GPTQ backend ")+ return get_autogptq_infer_linear(backend, bits, group_size, sym)+ else: # pragma: no cover+ try:+ import habana_frameworks.torch.hpu # noqa: F401 # pylint: disable=E0401+ except Exception as e:+ pass+ else:+ from auto_round_extension.hpu.qlinear_hpu_gptq import QuantLinear+ return QuantLinear+ if bits == 4 and is_optimum_habana_available(): # pragma: no covertry:- import auto_gptq # pylint: disable=E0401+ import habana_frameworks.torch.hpu # noqa: F401 # pylint: disable=E0401except Exception as e:- raise ImportError("Please install auto-gptq via 'pip install auto-gptq' to support GPTQ backend ")- return get_autogptq_infer_linear(backend, bits, group_size, sym)+ pass+ else:+ from auto_round_extension.hpu.qlinear_hpu import QuantLinear+ return QuantLinearif bits == 4 and exllama2_available and "exllamav2" in backend:from auto_round_extension.cuda.qliner_exllamav2 import QuantLinearelif bits == 4 and "exllamav2" in backend:diff --git a/auto_round_extension/cuda/post_init.py b/auto_round_extension/cuda/post_init.pyindex 3de7e5ab9..4b74596a5 100644--- a/auto_round_extension/cuda/post_init.py+++ b/auto_round_extension/cuda/post_init.py@@ -129,11 +129,14 @@ def autoround_post_init(model):model_uses_exllamav2 = Falsefor _, submodule in model.named_modules():- if hasattr(submodule, "QUANT_TYPE") and submodule.QUANT_TYPE == "exllamav2":- model_uses_exllamav2 = True- device = submodule.qweight.device- scratch_fixed = submodule.scratch_space_fixed()- fixed_bytes[device] = max(scratch_fixed, fixed_bytes.get(device, 0))+ if hasattr(submodule, "QUANT_TYPE"):+ if submodule.QUANT_TYPE == "exllamav2":+ model_uses_exllamav2 = True+ device = submodule.qweight.device+ scratch_fixed = submodule.scratch_space_fixed()+ fixed_bytes[device] = max(scratch_fixed, fixed_bytes.get(device, 0))+ elif submodule.QUANT_TYPE == "hpu":+ submodule.post_init()if model_uses_exllamav2:from auto_round_extension.cuda.qliner_exllamav2 import ExLlamaV2DeviceTensorsdiff --git a/auto_round_extension/hpu/__init__.py b/auto_round_extension/hpu/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/auto_round_extension/hpu/qlinear_hpu.py b/auto_round_extension/hpu/qlinear_hpu.pynew file mode 100644index 000000000..9a6eb1490--- /dev/null+++ b/auto_round_extension/hpu/qlinear_hpu.py@@ -0,0 +1,197 @@+# 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.++# MIT License+#+# Copyright (c) 2023 潘其威(William)+#+# Permission is hereby granted, free of charge, to any person obtaining a copy+# of this software and associated documentation files (the "Software"), to deal+# in the Software without restriction, including without limitation the rights+# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+# copies of the Software, and to permit persons to whom the Software is+# furnished to do so, subject to the following conditions:+#+# The above copyright notice and this permission notice shall be included in all+# copies or substantial portions of the Software.+#+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+# SOFTWARE.+import math+from logging import getLogger++import numpy as np+import torch+import torch.nn as nn+import transformers+try:+ import habana_frameworks.torch.core as htcore+ convert_from_uint4 = torch.ops.hpu.convert_from_uint4+except Exception as e:+ hpu_import_exception = e++ def error_raiser_hpu(*args, **kwargs):+ raise ValueError(+ f"Trying to use HPU, but could not import the HPU framework with the following error: {hpu_import_exception}"+ )++ convert_from_uint4 = error_raiser_hpu+++logger = getLogger(__name__)++def pack_tensor(input, bits = 4):+ normal = input.to(torch.int32)+ q = torch.zeros((normal.shape[0], normal.shape[1] // 32 * bits), dtype=torch.int32)+ i = 0+ col = 0+ while col < q.shape[1]:+ for j in range(i, i + (32 // bits)):+ q[:, col] |= normal[:, j] << (bits * (j - i))+ i += 32 // bits+ col += 1+ q = q.to(torch.int32)+ return q++class QuantLinear(nn.Module):+ QUANT_TYPE = "hpu"++ def __init__(+ self,+ bits,+ group_size,+ infeatures,+ outfeatures,+ bias,+ use_cuda_fp16=True,+ kernel_switch_threshold=128,+ trainable=False,+ weight_dtype=torch.float16,+ ):+ logger.debug(f"qlinear_hpu QuantLinear::__init__ {bits=}, {group_size=}, {infeatures=}, {outfeatures=}, {bias=}, {use_cuda_fp16=}, {kernel_switch_threshold=}, {trainable=}, {weight_dtype=}")+ super().__init__()+ if bits != 4:+ raise NotImplementedError("Only 4 bits are supported.")++ self.infeatures = infeatures+ self.outfeatures = outfeatures+ self.bits = bits+ self.group_size = group_size if group_size != -1 else infeatures+ self.maxq = 2**self.bits - 1++ self.register_buffer(+ "qweight",+ torch.zeros((infeatures // 32 * self.bits, outfeatures), dtype=torch.int32),+ )+ self.register_buffer(+ "qzeros",+ torch.zeros(+ (+ math.ceil(infeatures / self.group_size),+ outfeatures // 32 * self.bits,+ ),+ dtype=torch.int32,+ ),+ )+ self.register_buffer(+ "scales",+ torch.zeros(+ (math.ceil(infeatures / self.group_size), outfeatures),+ dtype=weight_dtype,+ ),+ )+ self.register_buffer(+ "g_idx",+ torch.tensor([i // self.group_size for i in range(infeatures)], dtype=torch.int32),+ )++ if bias:+ self.register_buffer("bias", torch.zeros((outfeatures), dtype=weight_dtype))+ else:+ self.bias = None+ self.half_indim = self.infeatures // 2++ self.wf = torch.tensor(list(range(0, 32, self.bits)), dtype=torch.int32).unsqueeze(0)++ def _preprocessing(self):+ self.qweight = self.qweight.cpu()+ weight = self.unpack_weight_from_cuda_old_format()+ new_qweight = pack_tensor(weight)+ self.qweight = new_qweight.to('hpu')++ # TODO: Support group indexing and remove the check+ columns = self.qweight.shape[0]+ g_idx_trivial = [i // self.group_size for i in range(columns)]+ g_idx_trivial = torch.tensor(g_idx_trivial, dtype=torch.int32)+ assert torch.equal(self.g_idx, g_idx_trivial), "Non-trivial tensor g_idx is not supported"++ zeros = self.unpack_zeros_from_cuda_old_format().cpu()+ new_qzeros = pack_tensor(zeros)+ self.qzeros = new_qzeros.to('hpu')++ def post_init(self):+ self._preprocessing()++ def pack(self, linear, scales, zeros, g_idx):+ #TODO: implement+ raise NotImplementedError("QuantLinear HPU currently doesn't support packing")++ def set_packed(self, qlinear_cls):+ self.qweight = qlinear_cls.qweight+ self.qzeros = qlinear_cls.qzeros+ self.scales = qlinear_cls.scales+ self.bias = qlinear_cls.bias++ def forward(self, x):+ x_dtype = x.dtype+ out_shape = x.shape[:-1] + (self.outfeatures,)+ x = x.reshape(-1, x.shape[-1])+ scales = self.scales+ qweight = self.qweight+ zeros = self.qzeros+ weight = convert_from_uint4(qweight, scales, zeros, x_dtype)+ out = torch.matmul(x, weight)+ out = out.reshape(out_shape)+ out = out + self.bias if self.bias is not None else out+ return out++ def unpack_zeros_from_cuda_old_format(self):+ zeros = torch.bitwise_right_shift(+ torch.unsqueeze(self.qzeros, 2).expand(-1, -1, 32 // self.bits),+ self.wf.unsqueeze(0),+ ).to(torch.int16 if self.bits == 8 else torch.int8)++ # zeros = zeros + 1 # This line is commented for auto-round format export. \+ # It remains unchanged for gptq format in qlinear_hpu_gptq.py+ zeros = torch.bitwise_and(+ zeros, (2**self.bits) - 1+ ).to(self.scales.dtype) # NOTE: It appears that casting here after the `zeros = zeros + 1` is important.+ zeros = zeros.reshape(-1, zeros.shape[1] * zeros.shape[2])+ return zeros++ def unpack_weight_from_cuda_old_format(self):+ weight = torch.bitwise_right_shift(+ torch.unsqueeze(self.qweight, 1).expand(-1, 32 // self.bits, -1),+ self.wf.unsqueeze(-1),+ ).to(torch.int16 if self.bits == 8 else torch.int8)+ weight = torch.bitwise_and(weight, (2**self.bits) - 1)+ weight = weight.reshape((weight.shape[0]*weight.shape[1], weight.shape[2]))+ return weight++__all__ = ["QuantLinear"]diff --git a/auto_round_extension/hpu/qlinear_hpu_gptq.py b/auto_round_extension/hpu/qlinear_hpu_gptq.pynew file mode 100644index 000000000..c2f3a884e--- /dev/null+++ b/auto_round_extension/hpu/qlinear_hpu_gptq.py@@ -0,0 +1,196 @@+# 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.++# MIT License+#+# Copyright (c) 2023 潘其威(William)+#+# Permission is hereby granted, free of charge, to any person obtaining a copy+# of this software and associated documentation files (the "Software"), to deal+# in the Software without restriction, including without limitation the rights+# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+# copies of the Software, and to permit persons to whom the Software is+# furnished to do so, subject to the following conditions:+#+# The above copyright notice and this permission notice shall be included in all+# copies or substantial portions of the Software.+#+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+# SOFTWARE.+import math+from logging import getLogger++import numpy as np+import torch+import torch.nn as nn+import transformers+try:+ import habana_frameworks.torch.core as htcore+ convert_from_uint4 = torch.ops.hpu.convert_from_uint4+except Exception as e:+ hpu_import_exception = e++ def error_raiser_hpu(*args, **kwargs):+ raise ValueError(+ f"Trying to use HPU, but could not import the HPU framework with the following error: {hpu_import_exception}"+ )++ convert_from_uint4 = error_raiser_hpu+++logger = getLogger(__name__)++def pack_tensor(input, bits = 4):+ normal = input.to(torch.int32)+ q = torch.zeros((normal.shape[0], normal.shape[1] // 32 * bits), dtype=torch.int32)+ i = 0+ col = 0+ while col < q.shape[1]:+ for j in range(i, i + (32 // bits)):+ q[:, col] |= normal[:, j] << (bits * (j - i))+ i += 32 // bits+ col += 1+ q = q.to(torch.int32)+ return q++class QuantLinear(nn.Module):+ QUANT_TYPE = "hpu"++ def __init__(+ self,+ bits,+ group_size,+ infeatures,+ outfeatures,+ bias,+ use_cuda_fp16=True,+ kernel_switch_threshold=128,+ trainable=False,+ weight_dtype=torch.float16,+ ):+ logger.debug(f"qlinear_hpu QuantLinear::__init__ {bits=}, {group_size=}, {infeatures=}, {outfeatures=}, {bias=}, {use_cuda_fp16=}, {kernel_switch_threshold=}, {trainable=}, {weight_dtype=}")+ super().__init__()+ if bits != 4:+ raise NotImplementedError("Only 4 bits are supported.")++ self.infeatures = infeatures+ self.outfeatures = outfeatures+ self.bits = bits+ self.group_size = group_size if group_size != -1 else infeatures+ self.maxq = 2**self.bits - 1++ self.register_buffer(+ "qweight",+ torch.zeros((infeatures // 32 * self.bits, outfeatures), dtype=torch.int32),+ )+ self.register_buffer(+ "qzeros",+ torch.zeros(+ (+ math.ceil(infeatures / self.group_size),+ outfeatures // 32 * self.bits,+ ),+ dtype=torch.int32,+ ),+ )+ self.register_buffer(+ "scales",+ torch.zeros(+ (math.ceil(infeatures / self.group_size), outfeatures),+ dtype=weight_dtype,+ ),+ )+ self.register_buffer(+ "g_idx",+ torch.tensor([i // self.group_size for i in range(infeatures)], dtype=torch.int32),+ )++ if bias:+ self.register_buffer("bias", torch.zeros((outfeatures), dtype=weight_dtype))+ else:+ self.bias = None+ self.half_indim = self.infeatures // 2++ self.wf = torch.tensor(list(range(0, 32, self.bits)), dtype=torch.int32).unsqueeze(0)++ def _preprocessing(self):+ self.qweight = self.qweight.cpu()+ weight = self.unpack_weight_from_cuda_old_format()+ new_qweight = pack_tensor(weight)+ self.qweight = new_qweight.to('hpu')++ # TODO: Support group indexing and remove the check+ columns = self.qweight.shape[0]+ g_idx_trivial = [i // self.group_size for i in range(columns)]+ g_idx_trivial = torch.tensor(g_idx_trivial, dtype=torch.int32)+ assert torch.equal(self.g_idx, g_idx_trivial), "Non-trivial tensor g_idx is not supported"++ zeros = self.unpack_zeros_from_cuda_old_format().cpu()+ new_qzeros = pack_tensor(zeros)+ self.qzeros = new_qzeros.to('hpu')++ def post_init(self):+ self._preprocessing()++ def pack(self, linear, scales, zeros, g_idx):+ #TODO: implement+ raise NotImplementedError("QuantLinear HPU currently doesn't support packing")++ def set_packed(self, qlinear_cls):+ self.qweight = qlinear_cls.qweight+ self.qzeros = qlinear_cls.qzeros+ self.scales = qlinear_cls.scales+ self.bias = qlinear_cls.bias++ def forward(self, x):+ x_dtype = x.dtype+ out_shape = x.shape[:-1] + (self.outfeatures,)+ x = x.reshape(-1, x.shape[-1])+ scales = self.scales+ qweight = self.qweight+ zeros = self.qzeros+ weight = convert_from_uint4(qweight, scales, zeros, x_dtype)+ out = torch.matmul(x, weight)+ out = out.reshape(out_shape)+ out = out + self.bias if self.bias is not None else out+ return out++ def unpack_zeros_from_cuda_old_format(self):+ zeros = torch.bitwise_right_shift(+ torch.unsqueeze(self.qzeros, 2).expand(-1, -1, 32 // self.bits),+ self.wf.unsqueeze(0),+ ).to(torch.int16 if self.bits == 8 else torch.int8)++ zeros = zeros + 1+ zeros = torch.bitwise_and(+ zeros, (2**self.bits) - 1+ ).to(self.scales.dtype) # NOTE: It appears that casting here after the `zeros = zeros + 1` is important.+ zeros = zeros.reshape(-1, zeros.shape[1] * zeros.shape[2])+ return zeros++ def unpack_weight_from_cuda_old_format(self):+ weight = torch.bitwise_right_shift(+ torch.unsqueeze(self.qweight, 1).expand(-1, 32 // self.bits, -1),+ self.wf.unsqueeze(-1),+ ).to(torch.int16 if self.bits == 8 else torch.int8)+ weight = torch.bitwise_and(weight, (2**self.bits) - 1)+ weight = weight.reshape((weight.shape[0]*weight.shape[1], weight.shape[2]))+ return weight++__all__ = ["QuantLinear"]diff --git a/examples/language-modeling/README.md b/examples/language-modeling/README.mdindex 44e8bddae..bb28a0677 100644--- a/examples/language-modeling/README.md+++ b/examples/language-modeling/README.md@@ -123,6 +123,11 @@ CUDA_VISIBLE_DEVICES=0 python3 main.py --model_name facebook/opt-125m --amp --biCUDA_VISIBLE_DEVICES=1,2 python3 eval/evaluation.py --model_name /save_model_path/ --eval_bs 8 --tasks mmlu,lambada_openai,ptb --excel_path /result_excel/save_path/```+- User could also perform evaluation on Intel Gaudi-2 using the following script.+```bash+python3 eval_042/evaluation.py --model_name /saved_model_path/ --tasks mmlu --device hpu+```+You can also utilize the official lm_eval [link](https://github.com/EleutherAI/lm-evaluation-harness/tree/main?tab=readme-ov-file#basic-usage).## 4. Known Issuesdiff --git a/examples/language-modeling/eval_042/evaluation.py b/examples/language-modeling/eval_042/evaluation.pyindex bf628e9d5..278ff5a80 100644--- a/examples/language-modeling/eval_042/evaluation.py+++ b/examples/language-modeling/eval_042/evaluation.py@@ -580,6 +580,10 @@ if __name__ == "__main__":"--trust_remote_code", action='store_true',help="Whether to enable trust_remote_code")+ parser.add_argument(+ "--device", default="cuda:0",+ help="PyTorch device (e.g. cpu/cuda:0/hpu) for evaluation."+ )parser.add_argument("--tasks",default="lambada_openai,hellaswag,winogrande,piqa,mmlu,truthfulqa_mc1," \"openbookqa,boolq,rte,arc_easy,arc_challenge",@@ -595,6 +599,9 @@ if __name__ == "__main__":quantization_config = config.quantization_configif "quant_method" in quantization_config and "auto-round" in quantization_config["quant_method"]:from auto_round.auto_quantizer import AutoHfQuantizer+ elif "quant_method" in quantization_config and quantization_config["quant_method"] == "gptq":+ if args.device == "hpu":+ from auto_round.auto_quantizer import AutoHfQuantizertest_tasks = args.tasksif isinstance(test_tasks, str):@@ -609,6 +616,7 @@ if __name__ == "__main__":result = simple_evaluate(model="hf",model_args=model_args,tasks=test_tasks,+ device=args.device,batch_size=args.eval_bs)print(make_table(result))diff --git a/test/test_hpu.py b/test/test_hpu.pynew file mode 100644index 000000000..e7b355b28--- /dev/null+++ b/test/test_hpu.py@@ -0,0 +1,106 @@+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)++def is_hpu_supported():+ try:+ import habana_frameworks.torch.core as htcore # pylint: disable=E0401+ except ImportError as e:+ return False+ return True+++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_hpu_inference(self):+ if not is_hpu_supported():+ 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")+ from auto_round.auto_quantizer import AutoHfQuantizer+ import habana_frameworks.torch.core as htcore+ import habana_frameworks.torch.hpu as hthpu+ model = AutoModelForCausalLM.from_pretrained(quantized_model_path, device_map="auto", \+ trust_remote_code=True).to('hpu').to(torch.float32)+ 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_hpu_inference(self):+ if not is_hpu_supported():+ 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_round")++ from auto_round.auto_quantizer import AutoHfQuantizer+ import habana_frameworks.torch.core as htcore+ import habana_frameworks.torch.hpu as hthpu+ model = AutoModelForCausalLM.from_pretrained(quantized_model_path, \+ device_map="auto").to('hpu').to(torch.float32)+ 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)