PTQ-Level Efficiency, QAT-Level Accuracy | 训练后量化的效率,量化感知训练的精度
W4Afp8 export (#378)
Wenhua Cheng7f6e5d40e693
diff --git a/auto_round/autoround.py b/auto_round/autoround.pyindex dc9b4b3ff..1bfca8b89 100644--- a/auto_round/autoround.py+++ b/auto_round/autoround.py@@ -25,7 +25,7 @@ from torch import autocastfrom tqdm import tqdmimport acceleratefrom packaging import version-from .quantizer import WrapperMultiblock, wrapper_block, unwrapper_block, WrapperLinear, unwrapper_layer+from .wrapper import WrapperMultiblock, wrapper_block, unwrapper_block, WrapperLinear, unwrapper_layerfrom .special_model_handler import (shareable_keywords,init_cache_for_special_model,@@ -335,7 +335,7 @@ class AutoRound(object):# assert self.tokenizer != None or self.dataloader != Noneif self.act_bits <= 8:logger.warning(- "Activation quantization is an experimental feature with limited support and a complex API."+ "activation quantization is an experimental feature with limited support and a complex API. ""And please save the quantized model to fake format as real deployment is not supported currently")if "mx_fp" in self.data_type:@@ -348,7 +348,7 @@ class AutoRound(object):if self.nsamples < self.gradient_accumulate_steps * self.batch_size:if self.batch_size > self.nsamples:- logger.warning(f"reset batch_size to {self.nsamples} as n_sample({self.nsamples})"+ logger.warning(f"reset batch_size to {self.nsamples} as nsamples({self.nsamples})"f" is smaller than batch_size({self.batch_size})")self.batch_size = self.nsamplesif self.gradient_accumulate_steps > self.nsamples // self.batch_size:@@ -356,7 +356,7 @@ class AutoRound(object):logger.warning(f"reset gradient_accumulate_steps to {self.gradient_accumulate_steps}"f" as nsamples must equal or greater"- f" than gradient_accumulate_steps * batch_szie")+ f" than gradient_accumulate_steps * batch_size")def quantize(self):"""Quantize the model and return the quantized model along with layer configurations.@@ -401,7 +401,6 @@ class AutoRound(object):if "input_ids" in inputs.keys():total_samples = len(inputs["input_ids"])- self.n_samples = total_samplesif total_samples < self.batch_size:self.batch_size = total_sampleslogger.warning(f"force the train batch size to {total_samples}")@@ -445,7 +444,7 @@ class AutoRound(object):def dump_qinfo_to_layer_config(self):"""- dump quantization scale and zp to layer configuration+ dump quantization scale and zp to layer configuration, this function could be deleted laterArgs:Returns:@@ -457,6 +456,8 @@ class AutoRound(object):for n, m in self.model.named_modules():if n not in self.layer_config.keys():continue+ if hasattr(m, "orig_layer"):+ m = m.orig_layerif not hasattr(m, "scale"):self.layer_config[n]["data_type"] = "float"if self.amp_dtype == torch.bfloat16:@@ -464,6 +465,9 @@ class AutoRound(object):self.layer_config[n]["bits"] = 16self.layer_config[n]["group_size"] = Noneself.layer_config[n]["sym"] = None+ m.bits = 16+ m.group_size = None+ m.sym = Nonedef quant_layers(self, layer_names, layer_inputs):"""Quantizes specified layers based on inputs and configuration.@@ -1370,7 +1374,7 @@ class AutoRound(object):if not self.quantized:logger.warning("please run autoround.quantize first")return- if format == "fake" or format == "qdq" or self.act_bits <= 8: ##TODO fix act quantizaiton later+ if format == "fake" or format == "qdq": ##TODO fix act quantizaiton laterself.model = self.model.to("cpu")self.model.save_pretrained(output_dir)if self.tokenizer is not None:@@ -1379,6 +1383,10 @@ class AutoRound(object):if processor is not None:processor.save_pretrained(output_dir)return+ if self.act_bits <= 8 and format == "qdq":+ logger.warning(+ "Support for exporting activation quantization is limited. "+ "Please ensure that your configuration is supported.")if format in ["gguf:q4_0", "gguf:q4_1"]:if self.group_size != 32:logger.error(f"{format} need group_size=32, but it is {self.group_size}, cannot export.")@@ -1407,6 +1415,8 @@ class AutoRound(object):serialization_keys = ["bits",+ "act_bits",+"group_size","sym","data_type",@@ -1426,6 +1436,11 @@ class AutoRound(object):"to_quant_block_names","enable_norm_bias_tuning"]+ if self.act_bits <= 8:+ serialization_keys.extend(["act_bits",+ "act_group_size",+ "act_sym",+ "act_dynamic"])if isinstance(self.dataset, str):serialization_keys.append("dataset")serialization_dict = {}@@ -1863,4 +1878,4 @@ class AutoRoundAdam(AutoRoundOPT):device_map=device_map,optimizer=optimizer,**kwargs,- )\ No newline at end of file+ )diff --git a/auto_round/data_type/__init__.py b/auto_round/data_type/__init__.pyindex 4425414f7..c800fb9af 100644--- a/auto_round/data_type/__init__.py+++ b/auto_round/data_type/__init__.py@@ -16,4 +16,5 @@ import auto_round.data_type.intimport auto_round.data_type.mxfpimport auto_round.data_type.fp8from auto_round.data_type.register import QUANT_FUNC_WITH_DTYPE+import auto_round.data_type.w4fp8from auto_round.data_type.utils import get_quant_funcdiff --git a/auto_round/data_type/fp8.py b/auto_round/data_type/fp8.pyindex 76da5e5cc..d92c311ad 100644--- a/auto_round/data_type/fp8.py+++ b/auto_round/data_type/fp8.py@@ -13,27 +13,10 @@# limitations under the License.import torch-+from auto_round.data_type.utils import get_gaudi_fp8_ste_func, float8_e4m3fn_stefrom auto_round.data_type.register import register_dtype-def float8_e4m3fn_ste(x: torch.Tensor):- """Straight-Through Estimator (STE) for float8.-- Applies a quantization and dequantization step with float8 precision while maintaining- gradient flow using a straight-through estimator.-- Args:- x (torch.Tensor): Input tensor.-- Returns:- torch.Tensor: Quantized and dequantized tensor using float8 format.- """- fp8 = (x.to(torch.float8_e4m3fn).to(x.dtype) - x).detach() + x-- return fp8--@register_dtype("fp8_dynamic_per_token_sym")def fp8_dynamic_per_token_sym(tensor, max_scale=1.0, **kwargs):"""Dynamic per-token symmetric quantization using float8.@@ -96,16 +79,18 @@ def quant_fp8_sym(tensor, max_scale=1.0, tensor_max=None, **kwargs):info = torch.finfo(torch.float8_e4m3fn)orig_dtype = tensor.dtype- if tensor_max is None: ##dynamic per-te+ if tensor_max is None: ##dynamic per-tokentensor = tensor.reshape(-1, orig_shape[-1])max_tensor = torch.max(torch.abs(tensor), dim=-1)[0] * max_scale+ elif isinstance(tensor_max,torch.Tensor):+ max_tensor = tensor_max.clone().detach().to(tensor.device) * max_scaleelse:max_tensor = torch.tensor(tensor_max).to(tensor.device) * max_scalescale = max_tensor.to(torch.float32) / info.maxmin_scaling_factor = float(1.0 / (info.max * 512.0)) ##copy from vllmscale = torch.clip(scale, min=min_scaling_factor)- if tensor.dtype == torch.float16: ## Avoid NaN gradients with float16+ if tensor.dtype == torch.float16: ## Avoid NaN gradients with float16tensor = tensor.to(torch.bfloat16)scale = scale.unsqueeze(dim=-1)fp8_res = (tensor / scale)@@ -116,51 +101,46 @@ def quant_fp8_sym(tensor, max_scale=1.0, tensor_max=None, **kwargs):return qdq_res, scale, None-@register_dtype("fp8_to_int_sym")-def progressive_quant_fp8_int4(tensor, bits=4, group_size=-1, v=0, min_scale=1.0, max_scale=1.0, q_scale_thresh=1e-5,- weight_fp8_max_scale=1.0, **kwargs):- """Two-stage quantization: quantize tensor to fp8 by per tensor, then quantize fp8 to w4g128+@register_dtype("fp8_gaudi3_sym")+def quant_fp8_sym_gaudi3(tensor, max_scale=1.0, tensor_max=None, **kwargs):+ """Symmetric quantization using float8 format.- This method first quantizes the input tensor into float8 format and then performs- a secondary quantization to int4 with grouping.+ Allows both dynamic per-token scaling and tensor-wide quantization depending on input.Args:tensor (torch.Tensor): Input tensor to quantize.- bits (int, optional): Bit precision for secondary quantization. Defaults to 4.- group_size (int, optional): Group size for int4 quantization. Defaults to -1 (no grouping).- v (float, optional): Optional parameter for variance tuning. Defaults to 0.- min_scale (float, optional): Minimum scaling factor for int4 quantization. Defaults to 1.0.- max_scale (float, optional): Maximum scaling factor for int4 quantization. Defaults to 1.0.- q_scale_thresh (float, optional): Threshold for scaling. Defaults to 1e-5.- weight_fp8_max_scale (float, optional): Maximum scaling factor for float8 quantization. Defaults to 1.0.+ max_scale (float, optional): Maximum scaling factor. Defaults to 1.0.+ tensor_max (float, optional): Maximum tensor value for precomputed scale. Defaults to None.**kwargs: Additional arguments for compatibility.Returns:tuple:- Quantized and dequantized tensor (torch.Tensor).- - Combined scaling factor (torch.Tensor).+ - Scale tensor used for quantization (torch.Tensor).- Placeholder for zp (None)."""+ orig_shape = tensor.shape+ fp8_max = torch.finfo(torch.float8_e4m3fn).max+ orig_dtype = tensor.dtype- info = torch.finfo(torch.float8_e4m3fn)- tensor_max = torch.max(torch.abs(tensor)).to(torch.float32) * weight_fp8_max_scale ## better train a ratio- scale = tensor_max.to(torch.float32) / info.max- min_scaling_factor = 1.0 / (info.max * 512.0) ##copy from vllm- scale_bf16_to_fp8 = torch.clip(scale, min=min_scaling_factor)- fp8_res = tensor / scale_bf16_to_fp8- fp8_res = torch.clip(fp8_res, info.min, info.max)- fp8_res = float8_e4m3fn_ste(fp8_res)-- ##convert to bf16- fp8_res_using_16bit = fp8_res.to(tensor.dtype)- ##convert to int4- from auto_round.data_type.int import quant_tensor_sym- qdq_int4_tensor, scale_fp8_to_int4, zp_fp8_to_int4 = quant_tensor_sym(fp8_res_using_16bit, bits=bits,- group_size=group_size, v=v,- min_scale=min_scale,- max_scale=max_scale,- scale_dtype=torch.bfloat16,- q_scale_thresh=q_scale_thresh)- qdq_tensor = qdq_int4_tensor * scale_bf16_to_fp8-- return qdq_tensor, scale_fp8_to_int4 * scale_bf16_to_fp8, None,+ if tensor_max is None: ##dynamic per-te+ tensor = tensor.reshape(-1, orig_shape[-1])+ max_tensor = torch.max(torch.abs(tensor), dim=-1)[+ 0] * max_scale+ elif isinstance(tensor_max, torch.Tensor):+ max_tensor = tensor_max.clone().detach().to(tensor.device) * max_scale+ else:+ max_tensor = torch.tensor(tensor_max).to(tensor.device) * max_scale+ scale = max_tensor.to(torch.float32) / fp8_max+ min_scaling_factor = float(1.0 / (fp8_max * 512.0)) ##copy from vllm+ scale = torch.clip(scale, min=min_scaling_factor)+ if tensor.dtype == torch.float16: ## Avoid NaN gradients with float16+ tensor = tensor.to(torch.bfloat16)+ scale = scale.unsqueeze(dim=-1)+ fp8_res = (tensor / scale)+ fp8_res = torch.clip(fp8_res, -fp8_max, fp8_max)+ float8_e4m3fn_ste_gaudi = get_gaudi_fp8_ste_func()+ fp8_res = float8_e4m3fn_ste_gaudi(fp8_res)+ qdq_res = fp8_res * scale+ qdq_res = qdq_res.to(orig_dtype).reshape(orig_shape)+ return qdq_res, scale, Nonediff --git a/auto_round/data_type/utils.py b/auto_round/data_type/utils.pyindex 95538b7e7..8c8ee0c70 100644--- a/auto_round/data_type/utils.py+++ b/auto_round/data_type/utils.py@@ -14,7 +14,8 @@import torchfrom auto_round.data_type.register import QUANT_FUNC_WITH_DTYPE-+from functools import lru_cache+from auto_round.utils import loggerdef reshape_pad_tensor_by_group_size(data: torch.Tensor, group_size: int):"""Reshapes and pads the tensor to ensure that it can be quantized in groups of `group_size`.@@ -155,3 +156,53 @@ def floor_ste(x: torch.Tensor):"""return (x.floor() - x).detach() + x++def float8_e4m3fn_ste(x: torch.Tensor):+ """Straight-Through Estimator (STE) for float8.++ Applies a quantization and dequantization step with float8 precision while maintaining+ gradient flow using a straight-through estimator.++ Args:+ x (torch.Tensor): Input tensor.++ Returns:+ torch.Tensor: Quantized and dequantized tensor using float8 format.+ """+ fp8 = (x.to(torch.float8_e4m3fn).to(x.dtype) - x).detach() + x++ return fp8+++def float8_e4m3fn_hpu_ste(x: torch.Tensor):+ """Straight-Through Estimator (STE) for float8.++ Applies a quantization and dequantization step with float8 precision while maintaining+ gradient flow using a straight-through estimator.++ Args:+ x (torch.Tensor): Input tensor.++ Returns:+ torch.Tensor: Quantized and dequantized tensor using float8 format.+ """+ fp8 = ((torch.ops.hpu.cast_to_fp8_v2(x, 1.0, False, False, torch.float8_e4m3fn)[0]).to(x.dtype) - x).detach() + x++ return fp8+++@lru_cache(None)+def get_gaudi_fp8_ste_func():+ from auto_round.utils import is_hpu_supported++ if is_hpu_supported():+ fn = float8_e4m3fn_hpu_ste+ logger.warning_once("Using HPU STE for FP8")+ else:+ fn = float8_e4m3fn_ste+ logger.warning_once("Using CUDA/CPU STE for FP8")+ return fn++++diff --git a/auto_round/data_type/w4fp8.py b/auto_round/data_type/w4fp8.pynew file mode 100644index 000000000..9e65bed44--- /dev/null+++ b/auto_round/data_type/w4fp8.py@@ -0,0 +1,243 @@+# Copyright (c) 2025 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.++import torch++from auto_round.data_type.register import register_dtype+from auto_round.data_type.utils import get_gaudi_fp8_ste_func, float8_e4m3fn_ste+++# @register_dtype("fp8_gaudi3_to_int_sym")+# def progressive_quant_fp8_int4_gaudi3(+# tensor,+# bits=4,+# group_size=-1,+# v=0,+# min_scale=1.0,+# max_scale=1.0,+# q_scale_thresh=1e-5,+# weight_fp8_max_scale=1.0,+# **kwargs+# ):+# """Two-stage quantization: quantize tensor to fp8 by per tensor, then quantize fp8 to w4g128+#+# This method first quantizes the input tensor into float8 format and then performs+# a secondary quantization to int4 with grouping.+#+# Args:+# tensor (torch.Tensor): Input tensor to quantize.+# bits (int, optional): Bit precision for secondary quantization. Defaults to 4.+# group_size (int, optional): Group size for int4 quantization. Defaults to -1 (no grouping).+# v (float, optional): Optional parameter for variance tuning. Defaults to 0.+# min_scale (float, optional): Minimum scaling factor for int4 quantization. Defaults to 1.0.+# max_scale (float, optional): Maximum scaling factor for int4 quantization. Defaults to 1.0.+# q_scale_thresh (float, optional): Threshold for scaling. Defaults to 1e-5.+# weight_fp8_max_scale (float, optional): Maximum scaling factor for float8 quantization. Defaults to 1.0.+# **kwargs: Additional arguments for compatibility.+#+# Returns:+# tuple:+# - Quantized and dequantized tensor (torch.Tensor).+# - Combined scaling factor (torch.Tensor).+# - Placeholder for zp (None).+# """+# fp8_max = torch.finfo(torch.float8_e4m3fn).max+# tensor_max = (+# torch.max(torch.abs(tensor)).to(torch.float32) * weight_fp8_max_scale+# ) ## better train a ratio+# scale = tensor_max.to(torch.float32) / fp8_max+# min_scaling_factor = 1.0 / (fp8_max * 512.0) ##copy from vllm+# scale_bf16_to_fp8 = torch.clip(scale, min=min_scaling_factor)+# fp8_res = tensor / scale_bf16_to_fp8+# fp8_res = torch.clip(fp8_res, -fp8_max, fp8_max)+# float8_e4m3fn_ste_gaudi = get_gaudi_fp8_ste_func()+# fp8_res = float8_e4m3fn_ste_gaudi(fp8_res)+#+# # convert to bf16+# fp8_res_using_16bit = fp8_res.to(tensor.dtype)+# # convert to int4+# from auto_round.data_type.int import quant_tensor_sym+#+# qdq_int4_tensor, scale_fp8_to_int4, zp_fp8_to_int4 = quant_tensor_sym(+# fp8_res_using_16bit,+# bits=bits,+# group_size=group_size,+# v=v,+# min_scale=min_scale,+# max_scale=max_scale,+# scale_dtype=torch.bfloat16,+# q_scale_thresh=q_scale_thresh,+# )+# qdq_tensor = qdq_int4_tensor * scale_bf16_to_fp8+# scale_bf16_to_int4 = scale_fp8_to_int4 * scale_bf16_to_fp8+# return qdq_tensor, (scale_bf16_to_int4, scale_bf16_to_fp8), zp_fp8_to_int4+++# @register_dtype("fp8_gaudi3_to_int_sym_pc")+# def progressive_quant_fp8_int4_per_channel(+# tensor,+# bits=4,+# group_size=-1,+# v=0,+# min_scale=1.0,+# max_scale=1.0,+# q_scale_thresh=1e-5,+# weight_fp8_max_scale=1.0,+# **kwargs+# ):+# """The per-channel version of progressive quantization from float8 to int4."""+# # tensor: [out_feats, in_feats]+# # scale_bf16_to_fp8: [out_feats, 1]+# out_feats, in_feats = tensor.shape+# fp8_max = torch.finfo(torch.float8_e4m3fn).max+# dim = 1+# tensor_max = (+# torch.max(torch.abs(tensor), dim=dim, keepdim=True)[0].to(torch.float32)+# * weight_fp8_max_scale+# ) ## better train a ratio+# scale = tensor_max.to(torch.float32) / fp8_max+# min_scaling_factor = 1.0 / (fp8_max * 512.0) ##copy from vllm+# scale_bf16_to_fp8 = torch.clip(scale, min=min_scaling_factor)+# fp8_res = tensor / scale_bf16_to_fp8+# fp8_res = torch.clip(fp8_res, -fp8_max, fp8_max)+# float8_e4m3fn_ste_gaudi = get_gaudi_fp8_ste_func()+# fp8_res = float8_e4m3fn_ste_gaudi(fp8_res)+#+# ##convert to bf16+# fp8_res_using_16bit = fp8_res.to(tensor.dtype)+# ##convert to int4+# from auto_round.data_type.int import quant_tensor_sym+#+# qdq_int4_tensor, scale_fp8_to_int4, zp_fp8_to_int4 = quant_tensor_sym(+# fp8_res_using_16bit,+# bits=bits,+# group_size=group_size,+# v=v,+# min_scale=min_scale,+# max_scale=max_scale,+# scale_dtype=torch.bfloat16,+# q_scale_thresh=q_scale_thresh,+# )+# qdq_tensor = qdq_int4_tensor * scale_bf16_to_fp8+# scale_fp8_to_int4_with_group = scale_fp8_to_int4+# scale_fp8_to_int4_with_group_reshape_back = scale_fp8_to_int4_with_group.reshape(+# out_feats, -1+# )+# scale_bf16_to_int4 = scale_fp8_to_int4_with_group_reshape_back * scale_bf16_to_fp8+# scale_bf16_to_int4_with_group = scale_bf16_to_int4.reshape(-1, 1)+# return (+# qdq_tensor,+# (scale_bf16_to_int4_with_group, scale_bf16_to_fp8),+# zp_fp8_to_int4,+# )+++# @register_dtype("fp8_gaudi3_to_int_sym_v2")+# def progressive_quant_fp8_int4_v2(+# tensor,+# bits=4,+# group_size=-1,+# v=0,+# min_scale=1.0,+# max_scale=1.0,+# q_scale_thresh=1e-5,+# weight_fp8_max_scale=1.0,+# **kwargs+# ):+# """The variant of progressive quantization from float8 to int4.+#+# The variant quantizes the tensor to int4 first and then quantizes the qdq tensor to fp8.+# """+# # convert to int4 first+# from auto_round.data_type.int import quant_tensor_sym+#+# qdq_int4_tensor, scale_bf16_to_int4, zp_fp8_to_int4 = quant_tensor_sym(+# tensor,+# bits=bits,+# group_size=group_size,+# v=v,+# min_scale=min_scale,+# max_scale=max_scale,+# scale_dtype=torch.bfloat16,+# q_scale_thresh=q_scale_thresh,+# )+# # FIXME(Yi): some fuse error here+# torch._dynamo.graph_break()+# fp8_max = torch.finfo(torch.float8_e4m3fn).max+# tensor_max = (+# torch.max(torch.abs(qdq_int4_tensor)).to(torch.float32) * weight_fp8_max_scale+# ) ## better train a ratio+# scale = tensor_max.to(torch.float32) / fp8_max+# min_scaling_factor = 1.0 / (fp8_max * 512.0) ##copy from vllm+# scale_bf16_to_fp8 = torch.clip(scale, min=min_scaling_factor)+# fp8_res = qdq_int4_tensor / scale_bf16_to_fp8+# fp8_res = torch.clip(fp8_res, -fp8_max, fp8_max)+# float8_e4m3fn_ste_gaudi = get_gaudi_fp8_ste_func()+# fp8_res = float8_e4m3fn_ste_gaudi(fp8_res)+#+# # convert to bf16+# fp8_res_using_16bit = fp8_res.to(tensor.dtype)+#+# qdq_tensor = fp8_res_using_16bit * scale_bf16_to_fp8+#+# return qdq_tensor, (scale_bf16_to_int4, scale_bf16_to_fp8), zp_fp8_to_int4+++@register_dtype("fp8_to_int_sym")+def progressive_quant_fp8_int4(tensor, bits=4, group_size=-1, v=0, min_scale=1.0, max_scale=1.0,+ q_scale_thresh=1e-5, **kwargs):+ """Two-stage quantization: quantize tensor to fp8 by per tensor, then quantize fp8 to w4g128++ This method first quantizes the input tensor into float8 format and then performs+ a secondary quantization to int4 with grouping.++ Args:+ tensor (torch.Tensor): Input tensor to quantize.+ bits (int, optional): Bit precision for secondary quantization. Defaults to 4.+ group_size (int, optional): Group size for int4 quantization. Defaults to -1 (no grouping).+ v (float, optional): Optional parameter for variance tuning. Defaults to 0.+ min_scale (float, optional): Minimum scaling factor for int4 quantization. Defaults to 1.0.+ max_scale (float, optional): Maximum scaling factor for int4 quantization. Defaults to 1.0.+ q_scale_thresh (float, optional): Threshold for scaling. Defaults to 1e-5.+ **kwargs: Additional arguments for compatibility.++ Returns:+ tuple:+ - Quantized and dequantized tensor (torch.Tensor).+ - Combined scaling factor (torch.Tensor).+ - Placeholder for zp (None).+ """++ info = torch.finfo(torch.float8_e4m3fn)+ tensor_max = torch.max(torch.abs(tensor)).to(torch.float32)+ scale = tensor_max.to(torch.float32) / info.max+ min_scaling_factor = 1.0 / (info.max * 512.0) ##copy from vllm+ bf16_to_fp8_scale = torch.clip(scale, min=min_scaling_factor)+ fp8_res = tensor / bf16_to_fp8_scale+ fp8_res = torch.clip(fp8_res, info.min, info.max)+ fp8_res = float8_e4m3fn_ste(fp8_res)++ ##convert to bf16+ fp8_res_using_16bit = fp8_res.to(tensor.dtype)+ ##convert to int4+ from auto_round.data_type.int import quant_tensor_sym+ qdq_int4_tensor, scale_fp8_to_int4, zp_fp8_to_int4 = quant_tensor_sym(fp8_res_using_16bit, bits=bits,+ group_size=group_size, v=v,+ min_scale=min_scale,+ max_scale=max_scale,+ scale_dtype=torch.bfloat16,+ q_scale_thresh=q_scale_thresh)+ qdq_tensor = qdq_int4_tensor * bf16_to_fp8_scale++ return qdq_tensor, {"scale": scale_fp8_to_int4, "bf16_to_fp8_scale": bf16_to_fp8_scale}, zp_fp8_to_int4diff --git a/auto_round/export/export_to_autogptq/export.py b/auto_round/export/export_to_autogptq/export.pyindex 7fa62cf18..8746a63cf 100644--- a/auto_round/export/export_to_autogptq/export.py+++ b/auto_round/export/export_to_autogptq/export.py@@ -229,4 +229,4 @@ def save(model: torch.nn.Module, save_dir: str, max_shard_size: str = "5GB", safconfig_file = "quantize_config.json"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(model.config.quantization_config, f, indent=2)+ json.dump(model.config.quantization_config, f, indent=2)\ No newline at end of filediff --git a/auto_round/export/export_to_autogptq/qlinear_triton.py b/auto_round/export/export_to_autogptq/qlinear_triton.pyindex c95129ed4..0d5a67942 100644--- a/auto_round/export/export_to_autogptq/qlinear_triton.py+++ b/auto_round/export/export_to_autogptq/qlinear_triton.py@@ -159,4 +159,4 @@ class QuantLinear(nn.Module, TritonModuleMixin):self.qzeros = torch.from_numpy(qzeros)-__all__ = ["QuantLinear"]+__all__ = ["QuantLinear"]\ No newline at end of filediff --git a/auto_round/export/export_to_autoround/export.py b/auto_round/export/export_to_autoround/export.pyindex 9505a07cd..ff68dd754 100644--- a/auto_round/export/export_to_autoround/export.py+++ b/auto_round/export/export_to_autoround/export.py@@ -21,6 +21,7 @@ import torchimport torch.nn as nnimport transformers+import auto_round.export.export_to_autoround.qlinear_triton_actfrom auto_round.utils import get_layer_names_in_block, get_module, logger, set_moduleimport threadpoolctl as tctlimport inspect@@ -28,6 +29,7 @@ from tqdm import tqdmfrom concurrent.futures import ThreadPoolExecutorfrom auto_round.utils import get_autogptq_packing_qlinear+def check_neq_config(config, data_type, bits, group_size, sym):"""Checks if the provided configuration parameters are not equal to the values in the config dictionary.@@ -50,7 +52,7 @@ 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 dynamic_import_quant_linear_for_packing(backend, bits, group_size, sym):+def dynamic_import_quant_linear_for_packing(backend, bits, group_size, sym, act_bits=16):"""Dynamically imports and returns the appropriate QuantLinear class based on the specified backend and parameters.@@ -67,10 +69,13 @@ def dynamic_import_quant_linear_for_packing(backend, bits, group_size, sym):AssertionError: If the backend is not supported."""if "auto_round" in backend and "awq" not in backend and "gptq" not in backend:+ if act_bits <= 8: ##easily have bug for other configuration, need to refine code later+ return auto_round.export.export_to_autoround.qlinear_triton_act.QuantLinear##only support triton and exllamav2if not ("triton" in backend or "exllamav2" in backend):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 QuantLinearelif "awq" in backend:@@ -82,24 +87,78 @@ def dynamic_import_quant_linear_for_packing(backend, bits, group_size, sym):assert False, f"only support auto_gptq, auto_awq and auto_round backend"-def pack_layer(name, model, layer_config, backend, pbar):+def pack_qact_layer(name, model, layer_config, backend, pbar):with tctl.threadpool_limits(limits=1):pbar.set_description(f"packing {name}")- config = layer_config[name]- if config["bits"] > 8:+ layer = get_module(model, name)+ if hasattr(layer, "orig_layer"):+ layer = layer.orig_layer++ if layer.bits > 8:pbar.update(1)return- bits = config["bits"]- group_size = config["group_size"]- sym = config["sym"]+ device = layer.weight.device++ bits = layer.bits+ group_size = layer.group_size+ sym = layer.sym+ act_bits = layer.act_bits+ assert act_bits <= 8++ act_scale = layer.act_scale if hasattr(layer, "act_scale") else None+ w_bf16_to_fp8_scale = layer.w_bf16_to_fp8_scale if hasattr(layer, "w_bf16_to_fp8_scale") else None+ scale = layer.scale+ zp = layer.zp+ QuantLinear = auto_round.export.export_to_autoround.qlinear_triton_act.QuantLinear++ if isinstance(layer, nn.Linear):+ in_features = layer.in_features+ out_features = layer.out_features+ elif isinstance(layer, nn.Conv2d):+ in_features = layer.in_channels+ out_features = layer.out_channels+ elif isinstance(layer, transformers.pytorch_utils.Conv1D):+ in_features = layer.weight.shape[0]+ out_features = layer.weight.shape[1]+ bias = layer.bias is not None+ use_pc = False+ new_layer = QuantLinear( ##pylint: disable=E1123+ bits, group_size, in_features, out_features, bias, weight_dtype=layer.weight.dtype, use_pc=use_pc+ )+ new_layer.device = device+ set_module(model, name, new_layer)+ qlayer = new_layer++ qlayer.to("cpu")++ qlayer.pack(layer, scale, zp, act_scale, w_bf16_to_fp8_scale)+ qlayer.to(device)+ pbar.update(1)++def pack_layer(name, model, layer_config, backend, pbar):+ with tctl.threadpool_limits(limits=1):+ pbar.set_description(f"packing {name}")layer = get_module(model, name)+ if hasattr(layer, "orig_layer"):+ layer = layer.orig_layer+ if layer.act_bits <= 8:+ return pack_qact_layer(name, model, layer_config, backend, pbar)++ if layer.bits > 8:+ pbar.update(1)+ returndevice = layer.weight.device+ bits = layer.bits+ group_size = layer.group_size+ sym = layer.sym+ act_bits = layer.act_bits+scale = layer.scalezp = layer.zp- QuantLinear = dynamic_import_quant_linear_for_packing(backend, bits, group_size, sym)+ QuantLinear = dynamic_import_quant_linear_for_packing(backend, bits, group_size, sym, act_bits)if isinstance(layer, nn.Linear):in_features = layer.in_features@@ -120,7 +179,6 @@ def pack_layer(name, model, layer_config, backend, pbar):set_module(model, name, new_layer)qlayer = new_layer- # so far can only pack layer on CPUqlayer.to("cpu")##force to float32 to be compatible with torch 2.0sig = inspect.signature(qlayer.pack)@@ -131,7 +189,7 @@ def pack_layer(name, model, layer_config, backend, pbar):qlayer.pack(layer, scale, zp, None)qlayer.to(device)else:- scale, zp = scale.to(torch.float32),zp.to(torch.float32)+ scale, zp = scale.to(torch.float32), zp.to(torch.float32)scale = scale.t().contiguous()zp = zp.t().contiguous()if bits != 4:@@ -185,7 +243,6 @@ def save_quantized_as_autoround(output_dir, inplace=True, backend="auto_round:exbackend = backend.replace("auto_round", "auto_gptq")model = kwargs["model"]- to_quant_block_names = kwargs["to_quant_block_names"]quant_block_list = kwargs.get("quant_block_list", None)safe_serialization = True if 'safe_serialization' not in kwargs.keys() else kwargs["safe_serialization"]if not inplace:@@ -247,7 +304,10 @@ def save_quantized_as_autoround(output_dir, inplace=True, backend="auto_round:exif processor is not None:processor.save_pretrained(output_dir)- dtype = torch.float16 ##force dtype to fp16+ if quantization_config.get("act_bits", 16) <= 8:+ dtype = torch.bfloat16+ else:+ dtype = torch.float16 ##force dtype to fp16save(model, output_dir, safe_serialization=safe_serialization, dtype=dtype)return model@@ -286,4 +346,3 @@ def save(model: nn.Module, save_dir: str, max_shard_size: str = "5GB", safe_seriif 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/qlinear_triton_act.py b/auto_round/export/export_to_autoround/qlinear_triton_act.pynew file mode 100644index 000000000..f5afa2432--- /dev/null+++ b/auto_round/export/export_to_autoround/qlinear_triton_act.py@@ -0,0 +1,235 @@+# 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++logger = getLogger(__name__)+++class QuantLinear(nn.Module):+ QUANT_TYPE = "triton"++ def __init__(self, bits, group_size, infeatures, outfeatures, bias, trainable=False, **kwargs):+ super().__init__()+ if bits not in [2, 4, 8]:+ raise NotImplementedError("Only 2,4,8 bits are supported.")+ if infeatures % 32 != 0 or outfeatures % 32 != 0:+ raise NotImplementedError("in_feature and out_feature must be divisible by 32.")+ 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=torch.bfloat16,+ ),+ )+ use_pc = kwargs.pop("use_pc", False)+ w_bf16_to_fp8_scale_shape = (1, self.outfeatures) if use_pc else (1,)+ self.register_buffer(+ "w_bf16_to_fp8_scale",+ torch.zeros(+ w_bf16_to_fp8_scale_shape,+ dtype=torch.bfloat16,+ ),+ )+ self.register_buffer(+ "act_scales",+ torch.zeros(+ (1),+ dtype=torch.bfloat16,+ ),+ )++ 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=torch.float16))+ else:+ self.bias = None++ self.trainable = trainable++ def __repr__(self):+ return (+ f"{self.__class__.__name__}({self.infeatures}, {self.outfeatures}, "+ f"bits={self.bits}, group_size={self.group_size},"+ f"scales shape: {self.scales.shape}, "+ f"act_scales shape: {self.act_scales.shape}, w_bf16_to_fp8_scale shape: {self.w_bf16_to_fp8_scale.shape}"+ f")"+ )++ def post_init(self):+ pass++ def pack(self, linear, scales, zeros, act_scales, w_bf16_to_fp8_scale, g_idx=None):+ scales_t = scales.t().contiguous()+ self.g_idx = g_idx.clone() if g_idx is not None else self.g_idx+ self.act_scales.data.copy_(act_scales.squeeze().clone())+ self.w_bf16_to_fp8_scale.data.copy_(w_bf16_to_fp8_scale.squeeze().clone())+ if linear.bias is not None:+ self.bias = linear.bias.clone().half()+ self.scales = scales_t.clone().half()+ device = "cpu"+ if torch.cuda.is_available():+ device = "cuda:0"++ W = linear.weight.data.to(device).clone()+ if isinstance(linear, nn.Conv2d):+ W = W.flatten(1)+ if isinstance(linear, transformers.pytorch_utils.Conv1D):+ W = W.t()++ repeat_scales = scales.to(device).repeat_interleave(self.group_size, 1)+ if isinstance(zeros, torch.Tensor):+ repeat_zeros = zeros.to(device).repeat_interleave(self.group_size, 1)+ else:+ repeat_zeros = zeros++ intweight = torch.round(W.to(device) / repeat_scales + repeat_zeros).to(+ torch.int32)++ del repeat_scales+ intweight = intweight.reshape(-1, intweight.shape[1] // 32 * self.bits, 32 // self.bits)+ order_map = torch.arange(0, 32 // self.bits, device=device) * self.bits+ intweight = intweight << order_map+ intweight = torch.sum(intweight, dim=-1)++ intweight = intweight.t().contiguous().to(torch.int32)+ self.qweight = intweight.to("cpu")++ if isinstance(zeros, torch.Tensor):+ zeros = zeros.t().contiguous()+ zeros -= 1+ zeros = zeros.to(torch.float16).numpy().astype(np.uint32)+ qzeros = np.zeros((zeros.shape[0], zeros.shape[1] // 32 * self.bits), dtype=np.uint32)+ i = 0+ col = 0+ while col < qzeros.shape[1]:+ for j in range(i, i + (32 // self.bits)):+ qzeros[:, col] |= zeros[:, j] << (self.bits * (j - i))+ i += 32 // self.bits+ col += 1++ qzeros = qzeros.astype(np.int32)+ self.qzeros = torch.from_numpy(qzeros)+ else:+ zeros -= 1+ shape = scales_t.shape+ value = 0+ for j in range(0, (32 // self.bits)):+ value |= zeros << (self.bits * j)+ qzeros = np.ones((shape[0], shape[1] // 32 * self.bits), dtype=np.uint32) * value+ qzeros = qzeros.astype(np.int32)+ self.qzeros = torch.from_numpy(qzeros)++ @classmethod+ def warmup(cls, model, transpose=False, seqlen=2048):+ return+ # """+ # Pre-tunes the quantized kernel+ # """+ # from tqdm import tqdm+ #+ # kn_values = {}+ #+ # for _, m in model.named_modules():+ # if not isinstance(m, cls):+ # continue+ #+ # k = m.infeatures+ # n = m.outfeatures+ #+ # if (k, n) not in kn_values:+ # kn_values[(k, n)] = (+ # m.qweight,+ # m.scales,+ # m.qzeros,+ # m.g_idx,+ # m.bits,+ # m.maxq,+ # )+ #+ # logger.info(f"Found {len(kn_values)} unique KN Linear values.")+ # logger.info("Warming up autotune cache ...")+ # with torch.no_grad():+ # for m in tqdm(range(0, math.ceil(math.log2(seqlen)) + 1)):+ # m = 2 ** m+ # for (k, n), (+ # qweight,+ # scales,+ # qzeros,+ # g_idx,+ # bits,+ # maxq,+ # ) in kn_values.items():+ # if transpose:+ # a = torch.randn(m, k, dtype=torch.float16, device=model.device)+ # quant_matmul_248(a, qweight, scales, qzeros, g_idx, bits, maxq)+ # a = torch.randn(m, n, dtype=torch.float16, device=model.device)+ # transpose_quant_matmul_248(a, qweight, scales, qzeros, g_idx, bits, maxq)+ # else:+ # a = torch.randn(m, k, dtype=torch.float16, device=model.device)+ # quant_matmul_inference_only_248(a, qweight, scales, qzeros, g_idx, bits, maxq)+ # del kn_values+++__all__ = ["QuantLinear"]diff --git a/auto_round/script/llm.py b/auto_round/script/llm.pyindex 3bd53f3df..85c4ad735 100644--- a/auto_round/script/llm.py+++ b/auto_round/script/llm.py@@ -177,7 +177,7 @@ class BasicArgumentParser(argparse.ArgumentParser):self.add_argument("--enable_torch_compile", action='store_true',help="whether to enable torch compile")- self.add_argument("--act_data_type", default=None, type=str, help="activation data type")+ self.add_argument("--act_data_type","--act_dtype", default=None, type=str, help="activation data type")self.add_argument("--disable_act_dynamic", action='store_true', help="activation static quantization")@@ -414,12 +414,18 @@ def tune(args):torch_dtype=torch_dtype,trust_remote_code=not args.disable_trust_remote_code)else:- model = model_cls.from_pretrained(- model_name,- low_cpu_mem_usage=True,- torch_dtype=torch_dtype,- trust_remote_code=not args.disable_trust_remote_code,- device_map="auto" if use_auto_mapping else None)+ from auto_round.utils import _use_hpu_compile_mode+ if _use_hpu_compile_mode():+ model = model_cls.from_pretrained(+ model_name, low_cpu_mem_usage=True, torch_dtype=torch_dtype,+ attn_implementation="eager",+ trust_remote_code=not args.disable_trust_remote_code, device_map="auto" if use_auto_mapping else None+ )+ else:+ model = model_cls.from_pretrained(+ model_name, low_cpu_mem_usage=True, torch_dtype=torch_dtype,+ trust_remote_code=not args.disable_trust_remote_code, device_map="auto" if use_auto_mapping else None+ )from auto_round import AutoRound, AutoRoundAdamdiff --git a/auto_round/quantizer.py b/auto_round/wrapper.pysimilarity index 88%rename from auto_round/quantizer.pyrename to auto_round/wrapper.pyindex 297eb5db9..555618908 100644--- a/auto_round/quantizer.py+++ b/auto_round/wrapper.py@@ -58,7 +58,7 @@ class WrapperLinear(torch.nn.Module):device (str): Device on which to run computations (e.g., 'cpu' or 'cuda')."""- def __init__(self, orig_layer, enable_minmax_tuning=True, enable_norm_bias_tuning=False, device='cpu'):+ def __init__(self, orig_layer, enable_minmax_tuning=True, enable_norm_bias_tuning=False, device='cpu', **kwargs):"""Initializes the WrapperLinear module.Args:@@ -73,11 +73,25 @@ class WrapperLinear(torch.nn.Module):self.device = self.orig_layer.tuning_device if hasattr(self.orig_layer, "tuning_device") else deviceself.enable_minmax_tuning = enable_minmax_tuningself.enable_norm_bias_tuning = enable_norm_bias_tuning and (orig_layer.bias is not None)- self.enable_act_quant = self.orig_layer.act_bits <= 8+ self.enable_act_quant = self.orig_layer.act_bits <= 8 or self._check_act_quantization(+ self.orig_layer.act_data_type)self.q_scale_thresh = 1e-5self._init_tuning_params_and_quant_func()self.orig_forward = self.linear_forward if isinstance(self.orig_layer, torch.nn.Linear) else self.conv1d_forward+ @staticmethod+ def _check_act_quantization(data_type: str):+ support_dtypes = ["int", "mx_fp", "fp", "nv_fp"]+ for support_dtype in support_dtypes:+ if data_type.startswith(support_dtype) and len(data_type) > len(support_dtype):+ ##first check the following two bits+ suc_2str = data_type[len(support_dtype):len(support_dtype) + 2]+ if str.isdigit(suc_2str): ##>8+ return False+ if str.isdigit(data_type[len(support_dtype)]) and int(data_type[len(support_dtype)]) <= 8:+ return True+ return False+def _init_tuning_params_and_quant_func(self):"""Initializes tuning parameters and quantization functions.@@ -116,7 +130,7 @@ class WrapperLinear(torch.nn.Module):self.bias_quant_func = quant_tensor_asym_wo_roundself.params["bias_v"] = self.bias_v- def _init_params(self, name, dtype, shape, value, bool_condition):+ def _init_params(self, name, dtype, shape, value, tunable):"""Initializes a parameter for tuning or uses a constant if tuning is disabled.Args:@@ -124,9 +138,9 @@ class WrapperLinear(torch.nn.Module):dtype (torch.dtype): Data type of the parameter.shape (tuple): Shape of the parameter.value (float): Initial value for the parameter.- bool_condition (bool): Whether the parameter should be tunable.+ tunable (bool): Whether the parameter should be tunable."""- if bool_condition:+ if tunable:p = torch.nn.Parameter(torch.ones(shape, device=self.device, dtype=dtype) * value, requires_grad=True)self.params.update({name: p})else:@@ -153,12 +167,20 @@ class WrapperLinear(torch.nn.Module):if isinstance(self.orig_layer, transformers.modeling_utils.Conv1D):weight = weight.t()- weight_q, scale, zp = self.weight_quant_func(weight, bits=self.orig_layer.bits,- group_size=self.orig_layer.group_size, v=value,- min_scale=min_scale, max_scale=max_scale,- scale_dtype=self.orig_layer.scale_dtype,- tensor_min=self.weight_min, tensor_max=self.weight_max,- data_type=self.data_type, q_scale_thresh=self.q_scale_thresh)+ weight_q, scale, zp = self.weight_quant_func(+ weight,+ bits=self.orig_layer.bits,+ group_size=self.orig_layer.group_size,+ v=value,+ min_scale=min_scale,+ max_scale=max_scale,+ scale_dtype=self.orig_layer.scale_dtype,+ tensor_min=self.weight_min,+ tensor_max=self.weight_max,+ data_type=self.data_type,+ q_scale_thresh=self.q_scale_thresh,++ )weight_q = weight_q.to(weight.dtype)if isinstance(self.orig_layer, transformers.modeling_utils.Conv1D):weight_q = weight_q.t()@@ -221,11 +243,19 @@ class WrapperLinear(torch.nn.Module):shape = qdq_weight.shapeif isinstance(self.orig_layer, transformers.modeling_utils.Conv1D):shape = qdq_weight.t().shape- scale = scale.reshape(shape[0], -1)+if zp is not None:zp = zp.reshape(shape[0], -1)-- self.orig_layer.scale = scale.to("cpu")+ if isinstance(scale, dict):+ for key in scale.keys():+ if key == "scale":+ name = key+ self.orig_layer.scale = scale[key].reshape(shape[0], -1).to("cpu")+ else:+ name = "w_" + key+ setattr(self.orig_layer, name, scale[key].to("cpu"))+ else:+ self.orig_layer.scale = scale.reshape(shape[0], -1).to("cpu")self.orig_layer.zp = zp.to("cpu") if zp is not None else None##unwrapper bias@@ -244,11 +274,20 @@ class WrapperLinear(torch.nn.Module):##unwrapper actif self.enable_act_quant:- act_max_scale = best_params.get('act_max_scale', torch.tensor(1.0)).to(self.device)+ if not self.orig_layer.act_dynamic:+ act_max_scale = best_params.get('act_max_scale', torch.tensor(1.0)).to(self.device)+ act_max = self.orig_layer.act_max if hasattr(self.orig_layer, "act_max") else None+ tmp_shape = (1)+ if self.orig_layer.act_group_size > 1:+ tmp_shape = (1, self.orig_layer.act_group_size)+ _, act_scale, _ = self._qdq_act(torch.zeros(tmp_shape).to(self.device),+ act_max_scale=self.act_max_scale, act_max=act_max)+ self.orig_layer.act_max = torch.tensor(self.orig_layer.act_max * act_max_scale.item()).to("cpu")+ self.orig_layer.act_scale = act_scale.to("cpu")+self.orig_layer.q_scale_thresh = self.q_scale_threshself.orig_layer.data_type = self.data_type- if not self.orig_layer.act_dynamic:- self.orig_layer.act_max = self.orig_layer.act_max * act_max_scale.item()+self.orig_layer.act_data_type = self.act_data_typeself.orig_layer.act_quant_func = self.act_quant_funcwrapper_layer = WrapperWALayer(self.orig_layer)@@ -451,7 +490,7 @@ class WrapperMultiblock(torch.nn.Module):return hidden_states-def wrapper_block(block, enable_minmax_tuning, enable_norm_bias_tuning, device='cpu'):+def wrapper_block(block, enable_minmax_tuning, enable_norm_bias_tuning, device='cpu', **kwargs):"""Wraps the layers in the given block with a custom Wrapper module.Args:@@ -469,7 +508,9 @@ def wrapper_block(block, enable_minmax_tuning, enable_norm_bias_tuning, device='unquantized_layers.append(n)continuenew_m = WrapperLinear(m, enable_minmax_tuning=enable_minmax_tuning,- enable_norm_bias_tuning=enable_norm_bias_tuning, device=device)+ enable_norm_bias_tuning=enable_norm_bias_tuning, device=device,+ **kwargs,+ )set_module(block, n, new_m)quantized_layers.append(n)@@ -525,4 +566,4 @@ def unwrapper_block(block, best_params):else:best_param = Noneorig_layer = m.unwrapper(best_param)- set_module(block, n, orig_layer)\ No newline at end of file+ set_module(block, n, orig_layer)diff --git a/test/test_auto_round_hpu_only.py b/test/test_auto_round_hpu_only.pyindex 8942e40b1..ad75fd9ad 100644--- a/test/test_auto_round_hpu_only.py+++ b/test/test_auto_round_hpu_only.py@@ -44,3 +44,36 @@ def test_import():from auto_round import AutoRoundfrom auto_round.export.export_to_itrex.export import (WeightOnlyLinear, save_quantized_as_itrex)+++# @pytest.mark.parametrize(+# "data_type",+# ["fp8_to_int_sym"],+# )+# def test_w4a8(data_type):+# from auto_round import AutoRound+# from transformers import AutoModelForCausalLM, AutoTokenizer+#+# model_name = "facebook/opt-125m"+# model = AutoModelForCausalLM.from_pretrained(+# model_name,+# torch_dtype="auto",+# attn_implementation="eager",+# trust_remote_code=True,+# )+# tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)+#+# autoround = AutoRound(+# model,+# tokenizer,+# bits=4,+# group_size=128,+# iters=2,+# seqlen=2,+# data_type=data_type,+# act_data_type="fp8_gaudi3_sym",+# act_bits=8,+# act_dynamic=False,+# )+# q_model, qconfig = autoround.quantize()+# assert q_model is not None, f"Expected q_model to be not None"