PTQ-Level Efficiency, QAT-Level Accuracy | 训练后量化的效率,量化感知训练的精度
support llm dynamic wint8aint8 export (#1376)
Wang, Mengnic9f6155b5343
diff --git a/auto_round/compressors/base.py b/auto_round/compressors/base.pyindex 22149ddbc..5c454e099 100644--- a/auto_round/compressors/base.py+++ b/auto_round/compressors/base.py@@ -43,6 +43,7 @@ from auto_round.compressors.utils import (get_shared_keys,infer_bits_by_data_type,init_cache,+ is_dynamic_wint8aint8,is_mx_fp,is_nv_fp,is_static_wfp8afp8,@@ -435,12 +436,12 @@ class BaseCompressor(object):disable_opt_rtn = Trueif (self.bits >= 8- and self.act_bits >= 16+ and self.act_bits >= 8and self.iters == 0and self.data_type == "int"and disable_opt_rtn is None):- logger.warning("`disable_opt_rtn` is turned on for W8A16 quantization to improve efficiency.")+ logger.warning("`disable_opt_rtn` is turned on for W8A16/W8A8 quantization to improve efficiency.")disable_opt_rtn = Trueif disable_opt_rtn is None and self.iters == 0:logger.info(@@ -828,6 +829,7 @@ class BaseCompressor(object):self.act_bits <= 8and (not is_nv_fp(self.act_data_type) or "static_gs" not in self.act_data_type)and not is_mx_fp(self.act_data_type)+ and not is_dynamic_wint8aint8(self)and not is_static_wfp8afp8(self.act_data_type)):logger.warning(@@ -1668,6 +1670,9 @@ class BaseCompressor(object):logger.warning("immediate_saving is only supported for int quantization, set to False")self.is_immediate_saving = False+ if self.orig_output_dir is None:+ self.is_immediate_saving = False+def quantize(self) -> tuple[torch.nn.Module, dict[str, Any]]:"""Quantize the model and return the quantized model along with layer configurations.The entry of AutoRound.Returns:diff --git a/auto_round/compressors/utils.py b/auto_round/compressors/utils.pyindex 8d890df8f..b0a83b1d5 100644--- a/auto_round/compressors/utils.py+++ b/auto_round/compressors/utils.py@@ -68,6 +68,15 @@ def is_wfp8afp8(ar):return False+def is_wint8aint8(ar):+ if ("int8" in ar.act_data_type or ("int" in ar.act_data_type and ar.act_bits == 8)) and (+ "int8" in ar.data_type or ("int" in ar.data_type and ar.bits == 8)+ ):+ return True+ else:+ return False++def is_static_wfp8afp8(ar_or_format: Union[str, Callable]) -> bool:if isinstance(ar_or_format, str):return "fp8_static" in ar_or_format.lower()@@ -78,6 +87,16 @@ def is_static_wfp8afp8(ar_or_format: Union[str, Callable]) -> bool:return False+def is_dynamic_wint8aint8(ar_or_format: Union[str, Callable]) -> bool:+ if isinstance(ar_or_format, str):+ return "int8_w8a8" in ar_or_format.lower()+ if not ar_or_format.act_dynamic:+ return False+ if is_wint8aint8(ar_or_format):+ return True+ return False++def block_forward(block: torch.nn.Module,input_ids: torch.Tensor,diff --git a/auto_round/export/export_to_llmcompressor/config.py b/auto_round/export/export_to_llmcompressor/config.pyindex 1bd58fd6b..6d6513d80 100644--- a/auto_round/export/export_to_llmcompressor/config.py+++ b/auto_round/export/export_to_llmcompressor/config.py@@ -11,48 +11,6 @@# 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.---quantization_config = {- "config_groups": {- "group_0": {- "input_activations": {- "actorder": None,- "block_structure": None,- "dynamic": True,- "group_size": None,- "num_bits": 8,- "observer": None,- "observer_kwargs": {},- "strategy": "token",- "symmetric": True,- "type": "int",- },- "output_activations": None,- "targets": ["Linear"],- "weights": {- "actorder": None,- "block_structure": None,- "dynamic": False,- "group_size": None,- "num_bits": 8,- "observer": "minmax",- "observer_kwargs": {},- "strategy": "channel",- "symmetric": True,- "type": "int",- },- }- },- "format": "int-quantized",- "global_compression_ratio": 1.5, # not exactly correct, but a placeholder- "ignore": [],- "kv_cache_scheme": None,- "quant_method": "compressed-tensors",- "quantization_status": "compressed",- "provider": "auto-round", # This is the key to indicate the model provider-}-# Copyright (c) 2023 Intel Corporation## Licensed under the Apache License, Version 2.0 (the "License");diff --git a/auto_round/export/export_to_llmcompressor/export.py b/auto_round/export/export_to_llmcompressor/export.pyindex ab7eae5d2..3c39d06e4 100644--- a/auto_round/export/export_to_llmcompressor/export.py+++ b/auto_round/export/export_to_llmcompressor/export.py@@ -18,33 +18,89 @@ from typing import Callable, Unionimport torch-from auto_round.compressors.utils import is_mx_fp, is_nv_fp, is_standard_fp, is_static_wfp8afp8-from auto_round.export.export_to_llmcompressor.config import quantization_config-from auto_round.export.export_to_llmcompressor.export_to_fp import save_quantized_as_fp-from auto_round.export.export_to_llmcompressor.export_to_static_fp import save_quantized_as_static_fp+from auto_round.export.utils import save_modelfrom auto_round.logger import loggerfrom auto_round.utils import (+ SUPPORTED_LAYER_TYPES,+ check_to_quantized,copy_python_files_from_model_cache,detect_device,get_module,set_module,+ unsupported_meta_device,)from auto_round.wrapper import WrapperWALayer[email protected]_grad()-def recover_qweight(qdq_weight, scale):- """- Recover the quantized weight to its original floating-point representation.-- Args:- qdq_weight (torch.Tensor): The quantized weight tensor.- scale (float): The scale factor used for quantization.-- Returns:- torch.Tensor: The recovered floating-point weight tensor.- """- return (qdq_weight / scale).to(torch.int8)+def construct_ct_scheme(layer):+ from compressed_tensors.quantization import QuantizationArgs, QuantizationScheme # pylint: disable=E0401++ weights_args = QuantizationArgs(+ num_bits=layer.bits,+ type=layer.data_type.split("_")[-2], # int_sym, rtn_int_sym+ symmetric=layer.sym,+ dynamic=False,+ group_size=None,+ strategy="tensor" if layer.act_group_size == 0 else "channel" if layer.act_group_size == -1 else None,+ )+ activations_args = QuantizationArgs(+ num_bits=layer.act_bits,+ type=layer.act_data_type.split("_")[-2], # int_sym, rtn_int_sym+ symmetric=layer.act_sym,+ dynamic=layer.act_dynamic,+ group_size=None,+ strategy="tensor" if layer.act_group_size == 0 else "token" if layer.act_group_size == -1 else None,+ )+ scheme = QuantizationScheme(+ targets=[layer.__class__.__name__],+ weights=weights_args,+ input_activations=activations_args,+ )+ return scheme+++def pack_layer(name, model, device=None):+ from compressed_tensors.compressors import IntQuantizationCompressor # pylint: disable=E0401+ from compressed_tensors.quantization import QuantizationStatus # pylint: disable=E0401+ from compressed_tensors.utils import delete_offload_parameter, register_offload_parameter # pylint: disable=E0401++ layer = get_module(model, name)+ if type(layer) not in SUPPORTED_LAYER_TYPES and not isinstance(layer, WrapperWALayer): ##already packed+ return++ if not check_to_quantized(layer):+ return++ if hasattr(layer, "quantization_status") and layer.quantization_status == QuantizationStatus.COMPRESSED:+ return++ scheme = construct_ct_scheme(layer)+ setattr(layer, "quantization_scheme", scheme)+ setattr(layer, "weight_scale", torch.nn.Parameter(layer.scale.to(device)))+ if not isinstance(layer.zp, torch.Tensor):+ if layer.sym:+ zp = torch.full_like(layer.weight_scale, 0).to(torch.int8)+ else:+ zp = torch.full_like(layer.weight_scale, layer.zp).to(torch.int8)+ else:+ zp = layer.zp++ setattr(layer, "weight_zero_point", torch.nn.Parameter(zp.to(device), requires_grad=False))+ delattr(layer, "scale")++ compressor = IntQuantizationCompressor()+ q_state_dict = compressor.compress(layer.state_dict(), names_to_scheme={"": scheme}, show_progress=False)++ # remove any existing parameters+ for name, _ in list(layer.named_parameters(recurse=False)):+ delete_offload_parameter(layer, name)++ # replace with compressed parameters+ for name, value in q_state_dict.items():+ param = torch.nn.Parameter(value, requires_grad=False)+ register_offload_parameter(layer, name, param, device)++ layer.quantization_status = QuantizationStatus.COMPRESSED@torch.no_grad()@@ -81,6 +137,7 @@ def save_quantized_as_llmcompressor(Returns:torch.nn.Module: The quantized model that was saved."""+ from compressed_tensors.quantization import QuantizationConfig # pylint: disable=E0401safe_serialization = kwargs.get("safe_serialization", True)processor = kwargs.get("processor", None)@@ -97,31 +154,24 @@ def save_quantized_as_llmcompressor(# generate q_weightdevice = detect_device(device)- for n, m in model.named_modules():- if isinstance(m, WrapperWALayer):- m = m.orig_layer- q_weight = recover_qweight(m.weight.to(device), m.scale.to(device)).to("cpu")- delattr(m, "weight")- setattr(m, "weight", torch.nn.Buffer(q_weight))- setattr(m, "weight_scale", torch.nn.Buffer(m.scale))-- # replace WrapperWALayer with orig_layer- candidates = []- for n, m in model.named_modules():- if isinstance(m, WrapperWALayer):- candidates.append(n)- for n in candidates:- set_module(model, n, get_module(model, n).orig_layer)+ if not unsupported_meta_device(model):+ for n, m in model.named_modules():+ pack_layer(n, model, device)+ if output_dir is None:+ return model++ quantization_config = QuantizationConfig.from_pretrained(model)# save model.config, model.state_dict()- model.config.quantization_config = quantization_config+ model.config.quantization_config = quantization_config.to_dict()model.config.save_pretrained(output_dir)+try:- model.save_pretrained(output_dir, safe_serialization=safe_serialization)+ save_model(model, output_dir, safe_serialization=safe_serialization)except ValueError as e:if hasattr(model, "generation_config"):setattr(model.generation_config, "do_sample", True)- model.save_pretrained(output_dir, safe_serialization=safe_serialization)+ save_model(model, output_dir, safe_serialization=safe_serialization)try:copy_python_files_from_model_cache(model, output_dir)diff --git a/auto_round/formats.py b/auto_round/formats.pyindex 0f440d87d..6fe957c61 100644--- a/auto_round/formats.py+++ b/auto_round/formats.py@@ -27,6 +27,7 @@ import torchimport transformersfrom auto_round.compressors.utils import (+ is_dynamic_wint8aint8,is_mx_fp,is_nv_fp,is_standard_fp,@@ -47,6 +48,7 @@ from auto_round.utils import (get_block_names,get_module,logger,+ unsupported_meta_device,)@@ -62,6 +64,7 @@ class AutoRoundExportFormat(str, Enum):NV_FP = "nv_fp"MX_FP_RCEIL = "mx_fp_rceil"NV_FP4_WITH_STATIC_GS = "nv_fp4_with_static_gs"+ INT8_W8A8 = "int8_w8a8"if TYPE_CHECKING:@@ -305,8 +308,12 @@ class FakeFormat(OutputFormat):serialization_dict: dict = None,**kwargs,):- model = model.to("cpu")- model.save_pretrained(output_dir)+ if not unsupported_meta_device(model):+ model = model.to("cpu")+ model.save_pretrained(output_dir)+ elif hasattr(model, "config") and model.config is not None:+ model.config.save_pretrained(output_dir)+if tokenizer is not None and hasattr(tokenizer, "save_pretrained"):tokenizer.save_pretrained(output_dir)processor = kwargs.get("processor", None)@@ -321,7 +328,7 @@ class FakeFormat(OutputFormat):@OutputFormat.register("llm_compressor")class LLMCompressorFormat(OutputFormat):- support_schemes = ["MXFP4", "MXFP8", "NVFP4", "FPW8A16", "FP8_STATIC"]+ support_schemes = ["MXFP4", "MXFP8", "NVFP4", "FPW8A16", "FP8_STATIC", "INT8_W8A8"]format_name = "llm_compressor"def __init__(self, format, ar):@@ -353,6 +360,11 @@ class LLMCompressorFormat(OutputFormat):f"please note that group_size={ar.group_size}"" may not be supported for llm_compressor format, and cannot be loaded in llm_compressor")+ elif is_dynamic_wint8aint8(ar):+ from auto_round.export.export_to_llmcompressor import check_compressed_tensors_supported++ check_compressed_tensors_supported()+ self.backend = LLMCompressorFormat(AutoRoundExportFormat.INT8_W8A8.value, ar)else:if format.upper() not in list(AutoRoundExportFormat.__members__.keys()):raise KeyError(f"Unsupported backend format llm_compressor:{format}, please check")@@ -364,9 +376,9 @@ class LLMCompressorFormat(OutputFormat):error_logs = []if scheme.bits not in [4, 8, 16]:error_logs.append(f"bits={scheme.bits}")- if not re.search("mxfp|fp|nvfp", scheme.data_type):+ if not re.search("mxfp|fp|nvfp|int", scheme.data_type):error_logs.append(f"data_type={scheme.data_type}")- if scheme.data_type == "fp" and scheme.bits != 8:+ if scheme.data_type in ["fp", "int"] and scheme.bits != 8:error_logs.append(f"data_type={scheme.data_type}, bits={scheme.bits}")if scheme.super_bits:error_logs.append(f"super_bits={scheme.super_bits}")@@ -415,7 +427,10 @@ class LLMCompressorFormat(OutputFormat):from auto_round.export.export_to_llmcompressor.export_to_static_fp import pack_layerreturn pack_layer(layer_name, model, self.get_backend_name(), device=device)+ elif re.search(f"{AutoRoundExportFormat.INT8_W8A8.value}", self.output_format):+ from auto_round.export.export_to_llmcompressor.export import pack_layer+ return pack_layer(layer_name, model, device=device)## passed as no other llm_compressor format is supported yetlogger.warning("No other llm_compressor packing format(except NVFP&MXFP) is supported yet, skip packing")returndiff --git a/auto_round/schemes.py b/auto_round/schemes.pyindex e9026450d..9ac3a4a9d 100644--- a/auto_round/schemes.py+++ b/auto_round/schemes.py@@ -266,6 +266,21 @@ FP8_STATIC = QuantizationScheme.from_dict(})+INT8_W8A8 = QuantizationScheme.from_dict(+ {+ "bits": 8,+ "group_size": -1,+ "data_type": "int",+ "sym": True,+ "act_bits": 8,+ "act_group_size": -1,+ "act_data_type": "int",+ "act_dynamic": True,+ "act_sym": True,+ }+)++# For AutoScheme 16 bits optionsBF16 = QuantizationScheme.from_dict({@@ -293,6 +308,7 @@ PRESET_SCHEMES = {"FP8_STATIC": FP8_STATIC,"BF16": BF16,"W4A16_MIXED": W4A16,+ "INT8_W8A8": INT8_W8A8,}from auto_round.export.export_to_gguf.config import GGUF_CONFIGdiff --git a/test/test_cpu/export/test_export.py b/test/test_cpu/export/test_export.pyindex dfe339590..93cfdaac5 100644--- a/test/test_cpu/export/test_export.py+++ b/test/test_cpu/export/test_export.py@@ -416,6 +416,16 @@ class TestAutoRound:assert format_list[1].output_format == "auto_gptq"assert format_list[1].get_backend_name() == "auto_gptq"+ autoround = AutoRound(+ model=self.model_name,+ scheme="INT8_W8A8",+ )+ format_list = get_formats("llm_compressor, auto_round:llm_compressor", autoround)+ assert format_list[0].output_format == "llm_compressor"+ assert format_list[0].get_backend_name() == "llm_compressor:int8_w8a8"+ assert format_list[1].output_format == "auto_round"+ assert format_list[1].get_backend_name() == "auto_round:llm_compressor:int8_w8a8"+def test_export_format_with_scheme(self, tiny_qwen_model_path):from auto_round.formats import get_formats@@ -450,3 +460,20 @@ class TestAutoRound:sym=True,)get_formats("auto_round:auto_awq", ar)++ def test_llmc_dynamic_wint8aint8_export(self):+ from safetensors import safe_open++ autoround = AutoRound(+ self.model_name,+ iters=0,+ nsamples=2,+ seqlen=2,+ scheme="INT8_W8A8",+ )+ quantized_model_path = "./saved"+ autoround.quantize_and_save(output_dir=quantized_model_path, format="llm_compressor")+ f = safe_open(os.path.join(quantized_model_path, "model.safetensors"), framework="pt")+ assert "model.decoder.layers.8.self_attn.k_proj.weight_scale" in f.keys()+ assert f.get_tensor("model.decoder.layers.5.self_attn.v_proj.weight").dtype == torch.int8+ shutil.rmtree(quantized_model_path, ignore_errors=True)