Skip to content

PTQ-Level Efficiency, QAT-Level Accuracy | 训练后量化的效率,量化感知训练的精度

support packing immediately in new quantization api to save ram usage (#466)

Wenhua Cheng8033dd0d881f
diff --git a/auto_round/auto_quantizer.py b/auto_round/auto_quantizer.py
index 5b6ebc93b..da78e5698 100644
--- a/auto_round/auto_quantizer.py
+++ b/auto_round/auto_quantizer.py
@@ -178,6 +178,10 @@ class AutoHfQuantizer:
if isinstance(quantization_config_from_args, (AutoRoundConfig)):
logger.info(f"Loading quantized model in auto_round format.")
tmp_backend = quantization_config["quant_method"]
+ if "auto-round" not in tmp_backend and "gptq" not in tmp_backend and "awq" not in tmp_backend:
+ logger.error("could not convert to auto_round format, currently only supports `gptq`,`awq` or "
+ "`auto-round` format")
+ exit(-1)
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"]
@@ -470,6 +474,22 @@ class AutoRoundQuantizer(HfQuantizer):
extra_config = {}
if hasattr(quantization_config, "extra_config"):
extra_config = quantization_config.extra_config
+ if hasattr(quantization_config, "modules_in_block_to_quantize"):##gptq format
+ modules_in_block_to_quantize_tmp = quantization_config.modules_in_block_to_quantize
+ modules_in_block_to_quantize = [item for sublist in modules_in_block_to_quantize_tmp for item in sublist]
+ for layer_name in layer_names:
+ quantized = False
+ for qname in modules_in_block_to_quantize:
+ if qname in layer_name:
+ quantized=True
+ break
+ if not quantized:
+ extra_config[layer_name]={"bits":16}
+ if hasattr(quantization_config, "modules_to_not_convert"):
+ for layer_name in quantization_config.modules_to_not_convert:
+ extra_config[layer_name]={"bits":16}
+
+
layer_names += extra_config.keys()
layer_names = list(set(layer_names))
diff --git a/auto_round/autoround.py b/auto_round/autoround.py
index abd7750aa..3f444c964 100644
--- a/auto_round/autoround.py
+++ b/auto_round/autoround.py
@@ -16,15 +16,13 @@ import os
import re
import torch
-import transformers
import copy
import time
-from typing import Optional, Union
+from typing import Optional, Union, List
from transformers import set_seed
from torch import autocast
from tqdm import tqdm
import accelerate
-from packaging import version
from .wrapper import WrapperMultiblock, wrapper_block, unwrapper_block, WrapperLinear, unwrapper_layer
from .special_model_handler import (
shareable_keywords,
@@ -53,7 +51,8 @@ from .utils import (
unsupport_meta_device, clear_memory,
compile_func,
find_matching_blocks, is_debug_mode,
- TORCH_VERSION_AT_LEAST_2_6
+ TORCH_VERSION_AT_LEAST_2_6,
+ supported_layer_types
)
from .low_cpu_mem.utils import get_layers_before_block
@@ -172,7 +171,7 @@ class AutoRound(object):
set_seed(self.seed)
assert not unsupport_meta_device(model), (
"AutoRound does not support for params on meta device."
- " Please use more gpus vis set `--device 0,1,2,3` or just use one gpu")
+ " Please use more gpus by setting `--device 0,1,2,3` or just use one gpu")
## important tuning hype-parameters
self.amp = amp
@@ -198,7 +197,7 @@ class AutoRound(object):
self.minmax_lr = minmax_lr or self.lr
self.data_type = data_type
- self.supported_types = [torch.nn.Linear, transformers.modeling_utils.Conv1D]
+ self.supported_types = supported_layer_types
self.model = model.eval()
self.tokenizer = tokenizer
self.device = detect_device(device)
@@ -267,7 +266,38 @@ class AutoRound(object):
self.set_device_map_in_blocks(self.device_map)
- self.set_layerwise_config(self.layer_config) ##better place in the end
+ self.is_packing_immediate = False ## whether to pack the layer immediately after tuning
+
+ self.serialization_keys = [
+ "bits",
+ "group_size",
+ "sym",
+ "data_type",
+ "enable_quanted_input",
+ "enable_minmax_tuning",
+ "data_type",
+ "seqlen",
+ "batch_size",
+ "scale_dtype",
+ "lr",
+ "minmax_lr",
+ "gradient_accumulate_steps",
+ "iters",
+ "amp",
+ "nsamples",
+ "low_gpu_mem_usage",
+ "to_quant_block_names",
+ "enable_norm_bias_tuning",
+ "act_bits",
+ "act_group_size",
+ "act_sym",
+ "act_dynamic",
+ "act_data_type",
+ "super_bits",
+ "super_group_size"
+ ]
+
+ self.has_qlayer_outside_block = self.set_layerwise_config(self.layer_config) ##better place in the end
def set_device_map_in_blocks(self, device_map):
"""Sets the device map for specific blocks in the model.
@@ -363,6 +393,89 @@ class AutoRound(object):
f" as nsamples must equal or greater"
f" than gradient_accumulate_steps * batch_size")
+ # def _check_format_compatibility(self, format): ##TODO
+ # ##check lm_head, mixed_bits, bits, each layer supporting, etc
+ # pass
+
+ def quantize_and_save(self, output_dir: str = "tmp_autoround", format: str = "auto_round", inplace=True, **kwargs):
+ """Quantizes the model and saves it in the specified format(s).
+
+ This function checks the validity of the requested format(s), quantizes
+ the model accordingly, and saves it to the specified output directory.
+ If multiple formats are provided, the model is saved separately for each format.
+
+ Args:
+ output_dir (str, optional): The directory where the quantized model
+ will be saved. Defaults to "tmp_autoround".
+ format (str, optional): The quantization format(s) to use, separated
+ by commas if multiple. Defaults to "auto_round".
+ inplace (bool, optional): Whether to modify the model in place if only
+ one format is used. Defaults to True.
+ **kwargs: Additional arguments for the quantization and saving process.
+
+ Returns:
+ model: A qdq model or packed model based on the configurations
+ folders: The folder paths where the quantized models are saved.
+
+ Raises:
+ ValueError: If an unsupported format is specified.
+ """
+ # Validate and process the specified formats
+ formats = format.replace(' ', '').split(',')
+ from auto_round.utils import supported_formats
+ for format_ in formats:
+ if format_ not in supported_formats:
+ logger.error(f"Unsupported format {format_}, please choose from {supported_formats}")
+ exit(-1)
+
+ # If multiple formats are specified, enforce inplace=False
+ if len(format) > 1:
+ inplace = False
+ inplace = kwargs.get("inplace", inplace)
+ kwargs.pop("inplace", None)
+
+ # Determine if immediate packing is required
+ if (len(formats) == 1 and
+ ("awq" in formats[0] or "gptq" in formats[0] or "auto_round" in formats[0]) and
+ not self.has_qlayer_outside_block and inplace): # TODO: Support more formats
+ self.is_packing_immediate = True
+
+ # Adjust format settings based on compatibility
+ for index in range(len(formats)):
+ format = formats[index]
+ if "auto_round" in format:
+ if self.sym and ("gptq" not in format and "awq" not in format):
+ format = format.replace('auto_round', 'auto_round:gptq')
+ formats[index] = format
+
+ if not any(f in format for f in ["triton", "exllamav2", "awq", "gptq"]):
+ logger.info(f"AutoRound format does not support {format}, attempting to use AutoGPTQ")
+ format = format.replace("auto_round", "auto_gptq")
+ formats[index] = format
+
+ # Remove duplicates from formats list
+ def remove_duplicates(lst):
+ seen = set()
+ return [x for x in lst if not (x in seen or seen.add(x))]
+
+ formats = remove_duplicates(formats)
+ self.formats = formats
+
+ # # Check format compatibility
+ # self._check_format_compatibility(formats)
+
+ # Perform model quantization
+ model, _ = self.quantize()
+
+ # Save the quantized model in the specified formats
+ folders = []
+ for format in formats:
+ save_format_ = format.replace(":", "-").replace("_", "-")
+ save_folder = os.path.join(output_dir, save_format_) if len(formats) > 1 else output_dir
+ self.save_quantized(save_folder, format=format, inplace=inplace, **kwargs)
+ folders.append(save_folder)
+
+ return model, folders
def quantize(self):
"""Quantize the model and return the quantized model along with layer configurations.
the entry of AutoRound.
@@ -393,6 +506,7 @@ class AutoRound(object):
self.model = mv_module_from_gpu(self.model, self.low_cpu_mem_usage)
logger.info("caching done")
pbar = tqdm(range(0, sum([len(i) for i in all_blocks]), self.nblocks))
+
for block_names in all_blocks:
inputs = all_inputs[block_names[0]]
all_inputs.pop(block_names[0])
@@ -418,10 +532,10 @@ class AutoRound(object):
device=self.device,
pbar=pbar
)
+ if self.is_packing_immediate:
+ assert len(self.formats) == 1
- self.quant_layers(layer_names, all_inputs)
-
- self.dump_qinfo_to_layer_config()
+ self.quant_layers(layer_names, all_inputs) ##TODO pack layer immediately
end_time = time.time()
cost_time = end_time - self.start_time
@@ -444,36 +558,8 @@ class AutoRound(object):
logger.info(summary_info)
self.quantized = True
- ##self.model = self.model.to(self.model_orig_dtype)##keep it as amp dtype
return self.model, self.layer_config
- def dump_qinfo_to_layer_config(self):
- """
- dump quantization scale and zp to layer configuration, this function could be deleted later
- Args:
-
- Returns:
- None
- """
- # load scale and zp if use low_cpu_memory
- self.model = self.model.to('cpu')
-
- 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_layer
- if not hasattr(m, "scale"):
- self.layer_config[n]["data_type"] = "float"
- if self.amp_dtype == torch.bfloat16:
- self.layer_config[n]["data_type"] = "bfloat"
- self.layer_config[n]["bits"] = 16
- self.layer_config[n]["group_size"] = None
- self.layer_config[n]["sym"] = None
- m.bits = 16
- m.group_size = None
- m.sym = None
-
def quant_layers(self, layer_names, layer_inputs):
"""Quantizes specified layers based on inputs and configuration.
@@ -502,7 +588,6 @@ class AutoRound(object):
self.model = mv_module_from_gpu(self.model, self.low_cpu_mem_usage)
clear_memory()
- device = next(self.model.parameters()).device
if self.enable_torch_compile:
quant_layer = compile_func(self.quant_layer, self.device)
else:
@@ -517,45 +602,72 @@ class AutoRound(object):
clear_memory(q_layer_input)
def set_layerwise_config(self, layer_config):
- """Sets the layer-wise configuration based on the provided layer_config.
- By default, only quantize layers in blocks.
+ """
+ Sets the layer-wise configuration based on the provided `layer_config`.
+ By default, only quantize layers in blocks.
Args:
- layer_config: The layer configuration.
+ layer_config (dict): The configuration dictionary for each layer containing various configuration options.
Returns:
- None
+ bool: Returns True if there are quantized layers outside the blocks (e.g., lm-head),
+ otherwise returns False.
"""
+ # Get the names of layers in quantization blocks
layers_in_blocks = get_layer_names_in_block(self.model, self.supported_types, self.quant_block_list)
- keys = ["data_type", "bits", "group_size", "sym", "scale_dtype", "act_bits", "act_group_size", "act_sym",
- "act_dynamic", "act_data_type", "super_bits", "super_group_size"]
+
+ # List of configuration keys
+ keys = self.serialization_keys
+
+ has_qlayer_outside_block = False # Flag to track if there are quantized layers outside blocks (e.g., lm-head)
+
+ # Iterate through all modules in the model
for n, m in self.model.named_modules():
- ##delete keys to avoid conflict with the previous tuning
+
+ # Delete previous configuration to avoid conflicts with prior tuning
for key in keys:
if hasattr(m, key):
delattr(m, key)
+ # Skip unsupported types
if not isinstance(m, tuple(self.supported_types)):
continue
- ##not set in layer config, so use the default values
+
+ # If the layer is not in the config and is part of a quantization block, use default configuration
if n not in layer_config.keys() and n in layers_in_blocks:
layer_config[n] = {}
for key in keys:
layer_config[n][key] = getattr(self, key)
- elif n in layer_config.keys(): ## partly set
+ # If the layer is partially configured, fill in missing values
+ elif n in layer_config.keys():
for key in keys:
if key not in layer_config[n].keys():
layer_config[n][key] = getattr(self, key)
- else: ##not in layer_config and layers in block,
+ # If the layer is not in the config and not part of a quantization block,
+ # use default configuration and set specific values
+ else:
layer_config[n] = {}
for key in keys:
layer_config[n][key] = getattr(self, key)
layer_config[n]["bits"] = 16
layer_config[n]["act_bits"] = 16
+ if n in layers_in_blocks:
+ layer_config[n]["in_blocks"] = True
+ else:
+ layer_config[n]["in_blocks"] = False
+
+ # If the layer is outside a block and requires quantization, mark it as a quantized layer outside the block
+ if n not in layers_in_blocks and check_to_quantized(layer_config[n]):
+ has_qlayer_outside_block = True
+
+ # Apply the configuration to the corresponding layer in the model
for key in keys:
setattr(m, key, layer_config[n][key])
+ # Return whether there are quantized layers outside the blocks
+ return has_qlayer_outside_block
+
@torch.no_grad()
def get_block_outputs(self, block, input_ids, input_others, bs, device, cache_device, save_output=True):
"""Compute the output of a given block of the model for a given input.
@@ -1283,7 +1395,7 @@ class AutoRound(object):
inputs,
block_names,
nblocks=1,
- device=torch.device("cpu"),
+ device="cpu",
pbar=None
):
"""Quantize and dequantize the weights of the specified blocks in the model.
@@ -1329,7 +1441,13 @@ class AutoRound(object):
if pbar is None:
pbar = tqdm(range(0, len(block_names), nblocks))
+ for n, m in self.model.named_modules():
+ if isinstance(m, tuple(self.supported_types)):
+ m.name = n
+
for i in range(0, len(block_names), nblocks):
+ if i!=0:
+ pbar.update(1)
if nblocks == 1:
n = block_names[i]
pbar.set_description(f"Quantizing {n}")
@@ -1350,9 +1468,20 @@ class AutoRound(object):
q_input=q_input,
device=device,
)
- pbar.update(1)
+ if self.is_packing_immediate:
+ from auto_round.export import PACKING_LAYER_WITH_FORMAT
+ for _, tmp_m in m.named_modules():
+ if hasattr(tmp_m, "bits") and check_to_quantized(tmp_m):
+ target_backend = self.formats[0].split(":")[0] if ":" in self.formats[0] else self.formats[0]
+ PACKING_LAYER_WITH_FORMAT[target_backend](tmp_m.name, self.model, self.formats[0])
+ pbar.set_description(f"Quantizing done")
+ pbar.update(1)
+ pbar.close()
self.model = mv_module_from_gpu(self.model, self.low_cpu_mem_usage)
+ for n, m in self.model.named_modules():
+ if hasattr(m, "name"):
+ delattr(m, "name")
del q_input
del input_ids
@@ -1418,38 +1547,10 @@ class AutoRound(object):
if "awq" in format and not self.bits == 4:
raise ValueError("The AWQ format only supports W4 quantization ")
- serialization_keys = [
- "bits",
- "act_bits",
-
- "group_size",
- "sym",
- "data_type",
- "enable_quanted_input",
- "enable_minmax_tuning",
- "data_type",
- "seqlen",
- "batch_size",
- "scale_dtype",
- "lr",
- "minmax_lr",
- "gradient_accumulate_steps",
- "iters",
- "amp",
- "nsamples",
- "low_gpu_mem_usage",
- "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")
+ self.serialization_keys.append("dataset")
serialization_dict = {}
- for key in serialization_keys:
+ for key in self.serialization_keys:
serialization_dict[key] = getattr(self, key)
from .version import __version__
diff --git a/auto_round/export/__init__.py b/auto_round/export/__init__.py
index 05e825065..845544017 100644
--- a/auto_round/export/__init__.py
+++ b/auto_round/export/__init__.py
@@ -12,7 +12,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-from auto_round.export.register import EXPORT_FORMAT, register_format
+from auto_round.export.register import EXPORT_FORMAT,PACKING_LAYER_WITH_FORMAT, register_format,register_layer_packing
@register_format("auto_gptq")
@@ -52,4 +52,28 @@ def _save_quantized_as_autoawq(*args, **kwargs):
@register_format("gguf")
def _save_quantized_as_autoawq(*args, **kwargs):
from auto_round.export.export_to_gguf.export import save_quantized_as_gguf
- return save_quantized_as_gguf(*args, **kwargs)
\ No newline at end of file
+ return save_quantized_as_gguf(*args, **kwargs)
+
+
+@register_layer_packing("auto_round")
+def _packing_layer_with_autoround(*args, **kwargs):
+ from auto_round.export.export_to_autoround.export import pack_layer
+
+ return pack_layer(*args, **kwargs)
+
+
+@register_layer_packing("auto_gptq")
+def _packing_layer_with_autogptq(*args, **kwargs):
+ from auto_round.export.export_to_autogptq.export import pack_layer
+
+ return pack_layer(*args, **kwargs)
+
+
+@register_layer_packing("auto_awq")
+def _packing_layer_with_autoawq(*args, **kwargs):
+ from auto_round.export.export_to_awq.export import pack_layer
+
+ return pack_layer(*args, **kwargs)
+
+
+
diff --git a/auto_round/export/export_to_autogptq/export.py b/auto_round/export/export_to_autogptq/export.py
index 8746a63cf..7a1d81424 100644
--- a/auto_round/export/export_to_autogptq/export.py
+++ b/auto_round/export/export_to_autogptq/export.py
@@ -37,7 +37,7 @@ import torch
import auto_round.export.export_to_autogptq.qlinear_triton
from auto_round.utils import check_to_quantized, get_block_names, \
- get_module, logger, set_module
+ get_module, logger, set_module, supported_layer_types
import copy
import json
import os
@@ -59,69 +59,69 @@ BLOCK_PATTERNS = [ ## copy from transformers optimum
]
-def pack_layer(name, model, layer_config, backend, pbar):
- with tctl.threadpool_limits(limits=1):
- pbar.set_description(f"packing {name}")
- if name == "lm_head": ##dese not support lm-head
- pbar.update(1)
- return
- config = layer_config[name]
- if config["bits"] > 8:
- pbar.update(1)
- return
- bits = config["bits"]
- group_size = config["group_size"]
- sym = config["sym"]
-
- layer = get_module(model, name)
- device = layer.weight.device
-
- QuantLinear = get_autogptq_packing_qlinear(backend, bits, group_size, sym)
-
- 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
- ##bias = True ## if using the above, llama3 lambada RTN will be NAN , TODO why?
- new_layer = QuantLinear( ##pylint: disable=E1123
- bits, group_size, in_features, out_features, bias, weight_dtype=layer.weight.dtype
- )
-
- new_layer.device = device
- set_module(model, name, new_layer)
- qlayer = new_layer
- scale = layer.scale
- zero = layer.zp
- # so far can only pack layer on CPU
- qlayer.to("cpu")
- ##force to float32 to be compatible with torch 2.0
- if sym and isinstance(new_layer, auto_round.export.export_to_autogptq.qlinear_triton.QuantLinear):
- layer, scale = layer.to("cpu"), scale.to("cpu")
- zero = 2 ** (bits - 1)
- else:
- layer, scale, zero = layer.to("cpu"), scale.to("cpu"), zero.to("cpu").to(torch.float32)
- sig = inspect.signature(qlayer.pack)
- param_count = len(sig.parameters)
- if param_count == 2:
- qlayer.pack(layer, scale)
- else:
- qlayer.pack(layer, scale, zero, None)
- qlayer.to(device)
- pbar.update(1)
+def pack_layer(name, model, backend):
+
+ if name == "lm_head": ##dese not support lm-head
+ return
+ layer = get_module(model, name)
+
+ if not isinstance(layer, supported_layer_types): ##already packed
+ return
+
+ bits = layer.bits
+ if bits > 8:
+ return
+
+ group_size = layer.group_size
+ sym = layer.sym
+
+ device = layer.weight.device
+
+ QuantLinear = get_autogptq_packing_qlinear(backend, bits, group_size, sym)
+
+ 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
+ ##bias = True ## if using the above, llama3 lambada RTN will be NAN , TODO why?
+ new_layer = QuantLinear( ##pylint: disable=E1123
+ bits, group_size, in_features, out_features, bias, weight_dtype=layer.weight.dtype
+ )
+
+ new_layer.device = device
+ set_module(model, name, new_layer)
+ qlayer = new_layer
+ scale = layer.scale
+ zero = layer.zp
+ # so far can only pack layer on CPU
+ qlayer.to("cpu")
+ ##force to float32 to be compatible with torch 2.0
+ if sym and isinstance(new_layer, auto_round.export.export_to_autogptq.qlinear_triton.QuantLinear):
+ layer, scale = layer.to("cpu"), scale.to("cpu")
+ zero = 2 ** (bits - 1)
+ else:
+ layer, scale, zero = layer.to("cpu"), scale.to("cpu"), zero.to("cpu").to(torch.float32)
+ sig = inspect.signature(qlayer.pack)
+ param_count = len(sig.parameters)
+ if param_count == 2:
+ qlayer.pack(layer, scale)
+ else:
+ qlayer.pack(layer, scale, zero, None)
+ qlayer.to(device)
+
def save_quantized_as_autogptq(output_dir, inplace=True, backend="auto_gptq:exllamav2",
**kwargs):
"""Export the model to autogptq format to easily leverage cuda kernel."""
model = kwargs["model"]
- supported_types = kwargs["supported_types"]
safe_serialization = True if 'safe_serialization' not in kwargs.keys() else kwargs["safe_serialization"]
quant_block_list = kwargs.get("quant_block_list", get_block_names(model))
tokenizer = kwargs.get("tokenizer", None)
@@ -140,19 +140,19 @@ def save_quantized_as_autogptq(output_dir, inplace=True, backend="auto_gptq:exll
quantization_config['block_name_to_quantize'] = common_prefix
quantization_config.pop("to_quant_block_names", None)
+ ## as layers maybe already packed, we need to check in layer_config
+ layer_config = kwargs["layer_config"]
+ for n,m in model.named_modules():
+ m.tmp_name=n
+
all_to_quantized = True
modules_in_block_to_quantize = []
for block_names in all_blocks:
first_block = get_module(model, block_names[0])
for n, m in first_block.named_modules():
- is_supported_type = False
- for supported_type in supported_types:
- if isinstance(m, supported_type):
- is_supported_type = True
- break
- if not is_supported_type:
+ if m.tmp_name not in layer_config.keys():
continue
- if not check_to_quantized(m):
+ if not check_to_quantized(layer_config[m.tmp_name]):
all_to_quantized = False
else:
modules_in_block_to_quantize.append(n)
@@ -160,6 +160,9 @@ def save_quantized_as_autogptq(output_dir, inplace=True, backend="auto_gptq:exll
if all_to_quantized:
modules_in_block_to_quantize = None
+ for n, m in model.named_modules():
+ delattr(m,"tmp_name")
+
if not inplace:
model = copy.deepcopy(model.to("cpu"))
@@ -172,7 +175,10 @@ def save_quantized_as_autogptq(output_dir, inplace=True, backend="auto_gptq:exll
with ThreadPoolExecutor(max_workers=max_workers) as executor:
with tqdm(total=len(names), leave=True) as pbar:
def wrapper(name):
- pack_layer(name, model, layer_config, backend, pbar)
+ pbar.set_description(f"packing {name}")
+ with tctl.threadpool_limits(limits=1):
+ pack_layer(name, model, backend)
+ pbar.update(1)
for _ in executor.map(wrapper, names):
pass
@@ -229,4 +235,4 @@ def save(model: torch.nn.Module, save_dir: str, max_shard_size: str = "5GB", saf
config_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)
\ No newline at end of file
+ json.dump(model.config.quantization_config, f, indent=2)
diff --git a/auto_round/export/export_to_autoround/export.py b/auto_round/export/export_to_autoround/export.py
index ff68dd754..f0743eec8 100644
--- a/auto_round/export/export_to_autoround/export.py
+++ b/auto_round/export/export_to_autoround/export.py
@@ -22,7 +22,7 @@ import torch.nn as nn
import transformers
import auto_round.export.export_to_autoround.qlinear_triton_act
-from auto_round.utils import get_layer_names_in_block, get_module, logger, set_module
+from auto_round.utils import get_layer_names_in_block, get_module, logger, set_module, supported_layer_types
import threadpoolctl as tctl
import inspect
from tqdm import tqdm
@@ -87,125 +87,133 @@ def dynamic_import_quant_linear_for_packing(backend, bits, group_size, sym, act_
assert False, f"only support auto_gptq, auto_awq and auto_round backend"
-def pack_qact_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.bits > 8:
- pbar.update(1)
- return
-
- 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
+def pack_qact_layer(name, model):
+ layer = get_module(model, name)
+ if hasattr(layer, "orig_layer"):
+ layer = layer.orig_layer
+
+ if layer.bits > 8:
+ return
+
+ device = layer.weight.device
+ bits = layer.bits
+ group_size = layer.group_size
+ act_bits = layer.act_bits
+
+ 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)
+
+
+def pack_layer(layer_name, model, backend):
+ """
+ Packs a model layer for quantization based on its type and configuration.
+
+ This function retrieves the specified layer from the model, checks its
+ compatibility for quantization, and replaces it with a quantized version
+ if applicable. The quantization process depends on the layer's bit-width,
+ group size, symmetry, and activation bits.
+
+ Args:
+ layer_name (str): The name of the layer to be packed.
+ model (torch.nn.Module): The model containing the layer.
+ backend (str): The backend framework to be used for quantization.
+
+ Returns:
+ None: The function modifies the model in place.
+ """
+ layer = get_module(model, layer_name)
+ if hasattr(layer, "orig_layer"):
+ layer = layer.orig_layer
+
+ if not isinstance(layer, supported_layer_types): ##already packed
+ return
+
+ if int(layer.act_bits) <= 8:
+ return pack_qact_layer(layer_name, model)
+
+ if int(layer.bits) > 8:
+ return
+
+ device = layer.weight.device
+ bits = layer.bits
+ group_size = layer.group_size
+ sym = layer.sym
+ act_bits = layer.act_bits
+
+ scale = layer.scale
+ zp = layer.zp
+ QuantLinear = dynamic_import_quant_linear_for_packing(backend, bits, group_size, sym, act_bits)
+
+ 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
+
+ if "awq" not in backend:
new_layer = QuantLinear( ##pylint: disable=E1123
- bits, group_size, in_features, out_features, bias, weight_dtype=layer.weight.dtype, use_pc=use_pc
+ bits, group_size, in_features, out_features, bias, weight_dtype=layer.weight.dtype
)
new_layer.device = device
- set_module(model, name, new_layer)
+ set_module(model, layer_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)
- return
- device = layer.weight.device
-
- bits = layer.bits
- group_size = layer.group_size
- sym = layer.sym
- act_bits = layer.act_bits
-
- scale = layer.scale
- zp = layer.zp
- QuantLinear = dynamic_import_quant_linear_for_packing(backend, bits, group_size, sym, act_bits)
-
- 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
-
- if "awq" not in backend:
- new_layer = QuantLinear( ##pylint: disable=E1123
- bits, group_size, in_features, out_features, bias, weight_dtype=layer.weight.dtype
- )
- new_layer.device = device
- set_module(model, name, new_layer)
- qlayer = new_layer
-
- qlayer.to("cpu")
- ##force to float32 to be compatible with torch 2.0
- sig = inspect.signature(qlayer.pack)
- param_count = len(sig.parameters)
- if param_count == 2:
- qlayer.pack(layer, scale)
- else:
- qlayer.pack(layer, scale, zp, None)
- qlayer.to(device)
+ ##force to float32 to be compatible with torch 2.0
+ sig = inspect.signature(qlayer.pack)
+ param_count = len(sig.parameters)
+ if param_count == 2:
+ qlayer.pack(layer, scale)
else:
- scale, zp = scale.to(torch.float32), zp.to(torch.float32)
- scale = scale.t().contiguous()
- zp = zp.t().contiguous()
- if bits != 4:
- logger.error("AutoAWQ format only supports 4-bits quantization.")
- qlayer = QuantLinear.from_linear(
- linear=layer,
- w_bit=bits,
- group_size=group_size,
- init_only=False,
- scales=scale,
- zeros=zp,
- )
- qlayer.to(device)
- set_module(model, name, qlayer)
-
- pbar.update(1)
+ qlayer.pack(layer, scale, zp, None)
+ qlayer.to(device)
+ else:
+ scale, zp = scale.to(torch.float32), zp.to(torch.float32)
+ scale = scale.t().contiguous()
+ zp = zp.t().contiguous()
+ if bits != 4:
+ logger.error("AutoAWQ format only supports 4-bits quantization.")
+ qlayer = QuantLinear.from_linear(
+ linear=layer,
+ w_bit=bits,
+ group_size=group_size,
+ init_only=False,
+ scales=scale,
+ zeros=zp,
+ )
+ qlayer.to(device)
+ set_module(model, layer_name, qlayer)
def save_quantized_as_autoround(output_dir, inplace=True, backend="auto_round:exllamav2", **kwargs):
@@ -230,10 +238,7 @@ def save_quantized_as_autoround(output_dir, inplace=True, backend="auto_round:ex
Raises:
AssertionError: If the backend is not supported.
"""
- if ":" not in backend:
- backend = "auto_round:exllamav2"
- backend = backend.replace("autoround", "auto_round")
- backend = backend.replace("auto-round", "auto_round")
+
##if using sym, we change to gptq sym kernel to avoid compiling from auto_round source
if (kwargs.get("sym") is None or kwargs.get("sym") == True) and ("gptq" not in backend and "awq" not in backend):
backend = backend.replace('auto_round', 'auto_round:gptq')
@@ -243,11 +248,9 @@ def save_quantized_as_autoround(output_dir, inplace=True, backend="auto_round:ex
backend = backend.replace("auto_round", "auto_gptq")
model = kwargs["model"]
- 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:
model = copy.deepcopy(model.to("cpu"))
- layer_names_in_block = get_layer_names_in_block(model, quant_block_list=quant_block_list)
layer_config = kwargs["layer_config"]
quantization_config = kwargs["serialization_dict"]
@@ -258,13 +261,14 @@ def save_quantized_as_autoround(output_dir, inplace=True, backend="auto_round:ex
processor = kwargs.get("processor", None)
extra_config = {}
for layer_name in layer_config:
- if layer_name not in layer_names_in_block and layer_config[layer_name]["bits"] <= 8: ##lm head
+ if not layer_config[layer_name]["in_blocks"] and layer_config[layer_name][
+ "bits"] <= 8: ##lm head ##TODO fix act and so on
extra_config[layer_name] = {}
extra_config[layer_name]["bits"] = layer_config[layer_name]["bits"]
extra_config[layer_name]["data_type"] = layer_config[layer_name]["data_type"]
extra_config[layer_name]["group_size"] = layer_config[layer_name]["group_size"]
extra_config[layer_name]["sym"] = layer_config[layer_name]["sym"]
- elif layer_name in layer_names_in_block:
+ elif layer_config[layer_name]["in_blocks"]:
neq_keys = check_neq_config(
layer_config[layer_name],
data_type=quantization_config["data_type"],
@@ -286,7 +290,10 @@ def save_quantized_as_autoround(output_dir, inplace=True, backend="auto_round:ex
with ThreadPoolExecutor(max_workers=max_workers) as executor:
with tqdm(total=len(names), leave=True) as pbar:
def wrapper(name):
- pack_layer(name, model, layer_config, backend, pbar)
+ pbar.set_description(f"packing {name}")
+ with tctl.threadpool_limits(limits=1):
+ pack_layer(name, model, backend)
+ pbar.update(1)
for _ in executor.map(wrapper, names):
pass
diff --git a/auto_round/export/export_to_awq/export.py b/auto_round/export/export_to_awq/export.py
index 637a67e81..08b8d7817 100644
--- a/auto_round/export/export_to_awq/export.py
+++ b/auto_round/export/export_to_awq/export.py
@@ -28,7 +28,7 @@ from auto_round.utils import (logger, get_module,
set_module,
check_to_quantized,
get_multimodal_block_names,
- extract_block_names_to_str)
+ extract_block_names_to_str, supported_layer_types)
import copy
import json
from .utils import WQLinear_GEMM
@@ -36,35 +36,37 @@ from concurrent.futures import ThreadPoolExecutor
import threadpoolctl as tctl
from tqdm import tqdm
-def pack_layer(name, model, layer_config, backend, pbar):
- with tctl.threadpool_limits(limits=1):
- pbar.set_description(f"packing {name}")
- if name == "lm_head": ##dese not support lm-head
- pbar.update(1)
- return
- config = layer_config[name]
- if config["bits"] > 8:
- pbar.update(1)
- return
- linear_layer = get_module(model, name)
- scale, zp = linear_layer.scale, linear_layer.zp
- scale = scale.t().contiguous()
- zp = zp.t().contiguous().to(torch.float32)
- bits = config["bits"]
- group_size = config["group_size"]
-
- if config["sym"]:
- zp = 2 ** (config["bits"] - 1)
- q_linear = WQLinear_GEMM.from_linear(
- linear=linear_layer,
- w_bit=bits,
- group_size=group_size,
- init_only=False,
- scales=scale,
- zeros=zp,
- )
- set_module(model, name, q_linear)
- pbar.update(1)
+
+def pack_layer(name, model, backend):
+ if name == "lm_head": ##dese not support lm-head
+ return
+ layer = get_module(model, name)
+
+ if not isinstance(layer, supported_layer_types): ##already packed
+ return
+
+ bits = layer.bits
+
+ if bits > 8:
+ return
+
+ group_size = layer.group_size
+ sym = layer.sym
+ linear_layer = get_module(model, name)
+ scale, zp = linear_layer.scale, linear_layer.zp
+ scale = scale.t().contiguous()
+ zp = zp.t().contiguous().to(torch.float32)
+ if sym:
+ zp = 2 ** (bits - 1)
+ q_linear = WQLinear_GEMM.from_linear(
+ linear=linear_layer,
+ w_bit=bits,
+ group_size=group_size,
+ init_only=False,
+ scales=scale,
+ zeros=zp,
+ )
+ set_module(model, name, q_linear)
def save_quantized_as_autoawq(output_dir, inplace=True, **kwargs):
@@ -102,7 +104,10 @@ def save_quantized_as_autoawq(output_dir, inplace=True, **kwargs):
with ThreadPoolExecutor(max_workers=max_workers) as executor:
with tqdm(total=len(names), leave=True) as pbar:
def wrapper(name):
- pack_layer(name, compressed_model, layer_config, backend, pbar)
+ pbar.set_description(f"packing {name}")
+ with tctl.threadpool_limits(limits=1):
+ pack_layer(name, compressed_model, backend)
+ pbar.update(1)
for _ in executor.map(wrapper, names):
pass
diff --git a/auto_round/export/export_to_itrex/export.py b/auto_round/export/export_to_itrex/export.py
index ac6e2355d..b5c508677 100644
--- a/auto_round/export/export_to_itrex/export.py
+++ b/auto_round/export/export_to_itrex/export.py
@@ -20,7 +20,7 @@ from typing import Dict, List, Optional, Union
import torch
import transformers
from auto_round.export.register import register_format
-from auto_round.utils import get_module, logger, set_module, detect_device
+from auto_round.utils import get_module, logger, set_module, detect_device, check_to_quantized
from .config import QuantConfig
from .model_wrapper import WeightOnlyLinear
@@ -203,7 +203,7 @@ def pack_model(
q_config = layer_config
for k, v in q_config.items():
- if "float" in v["data_type"]:
+ if check_to_quantized(v) is False:
continue
logger.info(f"Packing {k}")
dtype = v["data_type"]
diff --git a/auto_round/export/register.py b/auto_round/export/register.py
index 3947130c9..62a518558 100644
--- a/auto_round/export/register.py
+++ b/auto_round/export/register.py
@@ -34,3 +34,26 @@ def register_format(name):
return format
return register
+
+
+
+PACKING_LAYER_WITH_FORMAT = {}
+
+def register_layer_packing(name):
+ """Class decorator to register a EXPORT subclass to the registry.
+
+ Decorator function used before a Pattern subclass.
+
+ Args:
+ cls (class): The subclass of register.
+ name: A string. Define the export type.
+
+ Returns:
+ cls: The class of register.
+ """
+
+ def register(format):
+ PACKING_LAYER_WITH_FORMAT[name] = format
+ return format
+
+ return register
diff --git a/auto_round/script/llm.py b/auto_round/script/llm.py
index 2efe4d499..ef653ef64 100644
--- a/auto_round/script/llm.py
+++ b/auto_round/script/llm.py
@@ -30,11 +30,9 @@ import re
import argparse
import sys
-
from auto_round.utils import (
get_fp_layer_names,
clear_memory,
- is_debug_mode,
get_device_and_parallelism,
set_cuda_visible_devices)
@@ -177,7 +175,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","--act_dtype", 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")
@@ -205,15 +203,15 @@ class EvalArgumentParser(argparse.ArgumentParser):
default="0",
type=str,
help="the device to be used for tuning. "
- "Currently, device settings support CPU, GPU, and HPU."
- "The default is set to cuda:0,"
- "allowing for automatic detection and switch to HPU or CPU."
- "set --device 0,1,2 to use multiple cards.")
+ "Currently, device settings support CPU, GPU, and HPU."
+ "The default is set to cuda:0,"
+ "allowing for automatic detection and switch to HPU or CPU."
+ "set --device 0,1,2 to use multiple cards.")
self.add_argument(
"--tasks",
"--task",
default="lambada_openai,hellaswag,winogrande,piqa,mmlu,wikitext,truthfulqa_mc1,"
- "openbookqa,boolq,arc_easy,arc_challenge",
+ "openbookqa,boolq,arc_easy,arc_challenge",
help="lm-eval tasks")
self.add_argument(
"--disable_trust_remote_code", action='store_true', help="whether to disable trust_remote_code")
@@ -221,7 +219,6 @@ class EvalArgumentParser(argparse.ArgumentParser):
self.add_argument("--eval_task_by_task", action='store_true', help="whether to eval task by task.")
-
def setup_parser():
parser = BasicArgumentParser()
@@ -325,7 +322,7 @@ def _gguf_args_check(args):
logger.error(f"Model {model_architecture} is not supported to export GGUF format")
sys.exit(1)
- if format.endswith("_k") and ("hidden_size" in hparams and hparams["hidden_size"] % 256 !=0):
+ if format.endswith("_k") and ("hidden_size" in hparams and hparams["hidden_size"] % 256 != 0):
model_name = args.model.split('/')
model_name = model_name[-1] if model_name[-1] else model_name[-2]
hidden_size = hparams["hidden_size"]
@@ -359,23 +356,17 @@ def _gguf_args_check(args):
def tune(args):
import transformers
- from transformers import AutoModelForCausalLM, AutoTokenizer, AutoModel, AutoConfig, AutoProcessor
+ from transformers import AutoModelForCausalLM, AutoTokenizer, AutoModel, AutoConfig
- from auto_round import AutoRoundConfig
- from auto_round.utils import detect_device, get_library_version, detect_device_count
+ from auto_round.utils import detect_device, get_library_version
from auto_round.utils import logger
- from auto_round.export.export_to_gguf.config import GGUF_CONFIG
tasks = args.tasks
if args.format is None:
args.format = "auto_round"
- supported_formats = [
- "auto_round", "auto_gptq", "auto_awq", "auto_round:auto_gptq", "auto_round:auto_awq", "auto_gptq:marlin",
- "itrex", "itrex_xpu", "fake"
- ]
- supported_formats.extend(list(GGUF_CONFIG.keys()))
formats = args.format.lower().replace(' ', '').split(",")
+ from auto_round.utils import supported_formats
for format in formats:
if format not in supported_formats:
raise ValueError(f"{format} is not supported, we only support {supported_formats}")
@@ -571,9 +562,16 @@ def tune(args):
device_map=args.device_map,
super_group_size=args.super_group_size,
super_bits=args.super_bits,
- )
- model, _ = autoround.quantize()
+ )
+
model_name = args.model.rstrip("/")
+ if model_name.split('/')[-1].strip('.') == "":
+ export_dir = os.path.join(args.output_dir, f"w{args.bits}g{args.group_size}")
+ else:
+ export_dir = os.path.join(args.output_dir, model_name.split('/')[-1] + f"-w{args.bits}g{args.group_size}")
+
+ model, folders = autoround.quantize_and_save(export_dir, format=args.format)
+
if args.low_cpu_mem_mode == 1 or args.low_cpu_mem_mode == 2:
import shutil
shutil.rmtree(args.low_cpu_mem_tmp_dir, ignore_errors=True)
@@ -581,50 +579,35 @@ def tune(args):
model.eval()
clear_memory()
- if model_name.split('/')[-1].strip('.') == "":
- export_dir = os.path.join(args.output_dir, f"w{args.bits}g{args.group_size}")
- else:
- export_dir = os.path.join(args.output_dir, model_name.split('/')[-1] + f"-w{args.bits}g{args.group_size}")
-
- format_list = args.format.replace(' ', '').split(',')
- inplace = False if len(format_list) > 1 else True
- eval_folder = None
-
- eval_gguf_model = False
- for format_ in format_list:
- save_format_ = format_.replace(":", "-")
- save_format_ = save_format_.replace("_", "-")
- save_folder = f'{export_dir}-{save_format_}'
- autoround.save_quantized(save_folder, format=format_, inplace=inplace)
- if 'gguf' in format_:
- if not any([file.endswith(".gguf") for file in os.listdir(save_folder)]):
- logger.error(f"fail to export {format_}")
- eval_gguf_model = True
- eval_folder = save_folder
-
lm_eval_version = get_library_version("lm-eval")
if isinstance(tasks, str):
tasks = tasks.split(',')
-
+ eval_folder = folders[-1]
if not args.disable_eval and eval_folder is not None:
from lm_eval.utils import make_table # pylint: disable=E0401
logger.info(f"Using lm-eval version {lm_eval_version}")
+ eval_gguf_model = False
+ for file in os.listdir(eval_folder):
+ if file.endswith("guff"):
+ eval_gguf_model = True
+ break
if args.act_bits <= 8 or eval_gguf_model:
if eval_gguf_model:
for file in os.listdir(eval_folder):
gguf_file = file
- user_model = AutoModelForCausalLM.from_pretrained(save_folder, gguf_file=gguf_file, device_map="auto")
- if hasattr(model, "hf_device_map") and len(model.hf_device_map) > 1:
- from accelerate.big_modeling import dispatch_model
-
- dispatch_model(model, model.hf_device_map)
- user_model = model
+ user_model = AutoModelForCausalLM.from_pretrained(eval_folder, gguf_file=gguf_file, device_map="auto")
else:
- device_str = detect_device(device_str)
- user_model = model.to(device_str)
+ if hasattr(model, "hf_device_map") and len(model.hf_device_map) > 1:
+ from accelerate.big_modeling import dispatch_model
+
+ dispatch_model(model, model.hf_device_map)
+ user_model = model
+ else:
+ device_str = detect_device(device_str)
+ user_model = model.to(device_str)
if args.eval_task_by_task:
eval_task_by_task(user_model, device=device_str, tasks=args.tasks, batch_size=args.eval_bs)
@@ -651,7 +634,7 @@ def tune(args):
def _eval_init(tasks, model_path, device, disable_trust_remote_code=False):
set_cuda_visible_devices(device)
device_str, parallelism = get_device_and_parallelism(device)
- model_args = f'pretrained={model_path},trust_remote_code={not disable_trust_remote_code}' #,add_bos_token={True}
+ model_args = f'pretrained={model_path},trust_remote_code={not disable_trust_remote_code}' # ,add_bos_token={True}
if parallelism:
model_args += ",parallelize=True"
if isinstance(tasks, str):
@@ -740,4 +723,3 @@ def eval_task_by_task(model, device, tasks, tokenizer=None, batch_size=None, max
for key in res_keys:
res_all[key].update(res[key])
print(make_table(res_all))
-
diff --git a/auto_round/utils.py b/auto_round/utils.py
index e1f92e18c..da9082cb9 100644
--- a/auto_round/utils.py
+++ b/auto_round/utils.py
@@ -18,11 +18,8 @@ import os
import sys
import subprocess
from collections import UserDict
-from typing import Union, Optional
import re
-# for cpu usage
import cpuinfo
-import numpy as np
import psutil
import torch
from torch.amp import autocast
@@ -31,6 +28,18 @@ from functools import lru_cache
from packaging import version
import gc
from .special_model_handler import shareable_keywords, SPECIAL_MULTIMODAL_BLOCK
+import transformers
+from auto_round.export.export_to_gguf.config import GGUF_CONFIG
+
+supported_formats = (
+ "auto_round", "auto_gptq", "auto_awq", "auto_round:auto_gptq", "auto_round:auto_awq", "auto_gptq:marlin",
+ "itrex", "itrex_xpu", "fake"
+)
+
+
+supported_formats = supported_formats + tuple(GGUF_CONFIG.keys())
+
+supported_layer_types = (torch.nn.Linear, transformers.modeling_utils.Conv1D)
@lru_cache(None)
@@ -515,11 +524,11 @@ def check_to_quantized(config):
"""
if isinstance(config, dict):
- if int(config["bits"]) > 8:
+ if int(config["bits"]) > 8 and int(config["act_bits"] > 8):
return False
return True
else:
- if int(config.bits) > 8:
+ if int(config.bits) > 8 and int(config.act_bits) > 8:
return False
return True
@@ -796,8 +805,8 @@ def check_memory_availability(device, inputs, weight, org_seqlen, org_bs):
return False, seqlen, bs
-def get_layer_names_in_block(model, supported_types=[torch.nn.Linear,
- transformers.modeling_utils.Conv1D], quant_block_list=None):
+def get_layer_names_in_block(model, supported_types=(torch.nn.Linear,
+ transformers.modeling_utils.Conv1D), quant_block_list=None):
"""Retrieves the names of layers within each block of the model.
Returns:
@@ -805,7 +814,7 @@ def get_layer_names_in_block(model, supported_types=[torch.nn.Linear,
within a block of the model.
"""
for n, m in model.named_modules():
- if isinstance(m, tuple(supported_types)):
+ if isinstance(m, supported_types):
m.tmp_name = n
layers_in_block = []
if bool(quant_block_list):
@@ -1146,6 +1155,7 @@ def check_awq_gemm_compatibility(model, bits, group_size, sym, layer_configs=Non
return True, ""
+
def get_device_and_parallelism(device):
from auto_round.utils import detect_device
devices = device.replace(" ", "").split(',')
@@ -1160,6 +1170,7 @@ def get_device_and_parallelism(device):
parallelism = False
return device, parallelism
+
def set_cuda_visible_devices(device):
devices = device.replace(" ", "").split(',')
if all(s.isdigit() for s in devices):
diff --git a/auto_round/version.py b/auto_round/version.py
index 100d95bd4..7f9d2e651 100644
--- a/auto_round/version.py
+++ b/auto_round/version.py
@@ -14,4 +14,4 @@
"""Intel® auto-round: An open-source Python library
supporting popular model weight only compression based on signround."""
-__version__ = "0.4.6"
+__version__ = "0.5.0"
diff --git a/test/test_autoround.py b/test/test_autoround.py
index b2c796cdd..74d4b7505 100644
--- a/test/test_autoround.py
+++ b/test/test_autoround.py
@@ -237,7 +237,7 @@ class TestAutoRound(unittest.TestCase):
dataset=self.llm_dataloader,
)
autoround.quantize()
-
+ #
def test_signround(self):
bits, group_size, sym = 4, -1, False
autoround = AutoRound(
@@ -271,6 +271,7 @@ class TestAutoRound(unittest.TestCase):
layer_config=layer_config,
)
autoround.quantize()
+
def test_wa_quant(self):
bits, group_size, sym, act_bits = 4, 128, False, 4
autoround = AutoRound(
@@ -285,7 +286,7 @@ class TestAutoRound(unittest.TestCase):
act_bits=4,
)
autoround.quantize()
-
+
def test_auto_device_map(self):
bits, group_size, sym = 4, 128, False
model_name = "facebook/opt-125m"
@@ -301,7 +302,7 @@ class TestAutoRound(unittest.TestCase):
dataset=self.llm_dataloader,
)
autoround.quantize()
-
+
def test_fp32(self):
bits, group_size, sym = 4, 128, False
model_name = "facebook/opt-125m"
@@ -325,8 +326,8 @@ class TestAutoRound(unittest.TestCase):
model_name = "facebook/opt-125m"
model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.float32, trust_remote_code=True,
device_map='auto')
- layer_config = {"model.decoder.layers.0.self_attn.q_proj": {"bits": "16"},
- "model.decoder.layers.1.self_attn.k_proj": {"bits": "16"}}
+ layer_config = {"model.decoder.layers.0.self_attn.q_proj": {"bits": 16},
+ "model.decoder.layers.1.self_attn.k_proj": {"bits": 16}}
autoround = AutoRound(
model,
self.tokenizer,
diff --git a/test/test_autoround_export_to_itrex.py b/test/test_autoround_export_to_itrex.py
index 7d6ee77cf..195b9ffbb 100644
--- a/test/test_autoround_export_to_itrex.py
+++ b/test/test_autoround_export_to_itrex.py
@@ -90,7 +90,7 @@ class TestAutoroundExport(unittest.TestCase):
self.assertEqual(config.desc_act, loaded_config.desc_act)
self.assertEqual(config.bits, loaded_config.bits)
self.assertEqual(config.sym, loaded_config.sym)
-
+
def test_xpu_export(self):
model = copy.deepcopy(self.gptj)
out1 = model(self.lm_input)
diff --git a/test/test_basic_usage.py b/test/test_basic_usage.py
index af93af4bf..1337ac517 100644
--- a/test/test_basic_usage.py
+++ b/test/test_basic_usage.py
@@ -31,8 +31,10 @@ class TestAutoRoundCmd(unittest.TestCase):
assert False, "cmd line test fail, please have a check"
res = os.system(
- f"cd .. && {python_path} -m auto_round --model './saved' --eval_task_by_task --tasks piqa,openbookqa --bs 32"
+ f"cd .. && {python_path} -m auto_round --model 'facebook/opt-125m' --eval_task_by_task --tasks piqa,openbookqa --bs 32"
)
+ if res > 0 or res == -1:
+ assert False, "cmd line test fail, please have a check"
# test mllm script
@@ -47,7 +49,7 @@ class TestAutoRoundCmd(unittest.TestCase):
f"cd .. && {python_path} -m auto_round --mllm --eval -h")
if res > 0 or res == -1:
assert False, "cmd line test fail, please have a check"
-
+
# test auto_round_mllm --lmms help
res = os.system(
f"cd .. && {python_path} -m auto_round --mllm --lmms -h")
diff --git a/test_cuda/test_export.py b/test_cuda/test_export.py
new file mode 100644
index 000000000..74c0cafab
--- /dev/null
+++ b/test_cuda/test_export.py
@@ -0,0 +1,244 @@
+import copy
+import shutil
+import sys
+import unittest
+
+sys.path.insert(0, "..")
+import torch
+import transformers
+from transformers import AutoModelForCausalLM, AutoTokenizer
+
+from auto_round import AutoRound
+
+
+class LLMDataLoader:
+ def __init__(self):
+ self.batch_size = 1
+
+ def __iter__(self):
+ for i in range(2):
+ yield torch.ones([1, 10], dtype=torch.long)
+
+
+class TestAutoRound(unittest.TestCase):
+ @classmethod
+ def setUpClass(self):
+ self.model_name = "facebook/opt-125m"
+
+ self.llm_dataloader = LLMDataLoader()
+
+ @classmethod
+ def tearDownClass(self):
+ shutil.rmtree("./saved", ignore_errors=True)
+ shutil.rmtree("runs", ignore_errors=True)
+
+ def test_autogptq_format(self):
+ model = AutoModelForCausalLM.from_pretrained(self.model_name, torch_dtype="auto", trust_remote_code=True)
+ tokenizer = AutoTokenizer.from_pretrained(self.model_name, trust_remote_code=True)
+ bits, group_size, sym = 4, 128, False
+ autoround = AutoRound(
+ model,
+ tokenizer,
+ bits=bits,
+ group_size=group_size,
+ sym=sym,
+ iters=2,
+ seqlen=2,
+ dataset=self.llm_dataloader,
+ )
+ autoround.quantize()
+ quantized_model_path = "./saved"
+
+ autoround.save_quantized(output_dir=quantized_model_path, inplace=False, format="auto_gptq")
+ model = AutoModelForCausalLM.from_pretrained(quantized_model_path, device_map="auto", trust_remote_code=True)
+ tokenizer = AutoTokenizer.from_pretrained(quantized_model_path)
+ text = "There is a girl who likes adventure,"
+ inputs = tokenizer(text, return_tensors="pt").to(model.device)
+ res = tokenizer.decode(model.generate(**inputs, max_new_tokens=50)[0])
+ assert (res == "</s>There is a girl who likes adventure, she is a good friend of mine, she is a good friend of"
+ " mine, she is a good friend of mine, she is a good friend of mine, she is a good friend of mine, "
+ "she is a good friend of mine, she is")
+ shutil.rmtree("./saved", ignore_errors=True)
+
+ def test_autogptq_format_fp_layers(self):
+ model = AutoModelForCausalLM.from_pretrained(self.model_name, torch_dtype="auto", trust_remote_code=True)
+ tokenizer = AutoTokenizer.from_pretrained(self.model_name, trust_remote_code=True)
+ layer_config = {}
+ for n, m in model.named_modules():
+ if "q_proj" in n:
+ layer_config[n] = {"bits": 16}
+
+ bits, group_size, sym = 4, 128, False
+ autoround = AutoRound(
+ model,
+ tokenizer,
+ bits=bits,
+ group_size=group_size,
+ sym=sym,
+ iters=1,
+ seqlen=2,
+ dataset=self.llm_dataloader,
+ layer_config=layer_config
+ )
+ autoround.quantize()
+ quantized_model_path = "./saved"
+ autoround.save_quantized(output_dir=quantized_model_path, inplace=False, format="auto_gptq")
+
+ model = AutoModelForCausalLM.from_pretrained(quantized_model_path, device_map="auto", trust_remote_code=True)
+ tokenizer = AutoTokenizer.from_pretrained(quantized_model_path)
+ text = "There is a girl who likes adventure,"
+ inputs = tokenizer(text, return_tensors="pt").to(model.device)
+ res = tokenizer.decode(model.generate(**inputs, max_new_tokens=50)[0])
+ assert res == ("</s>There is a girl who likes adventure, she is a great artist, she is a great artist, "
+ "she is a great artist, she is a great artist, she is a great artist,"
+ " she is a great artist, she is a great artist, she is a great artist, she is")
+ shutil.rmtree("./saved", ignore_errors=True)
+
+ def test_autogptq_format_qsave_fp_layers(self):
+ model = AutoModelForCausalLM.from_pretrained(self.model_name, torch_dtype="auto", trust_remote_code=True)
+ tokenizer = AutoTokenizer.from_pretrained(self.model_name, trust_remote_code=True)
+ layer_config = {}
+ for n, m in model.named_modules():
+ if "q_proj" in n:
+ layer_config[n] = {"bits": 16}
+
+ bits, group_size, sym = 4, 128, False
+ autoround = AutoRound(
+ model,
+ tokenizer,
+ bits=bits,
+ group_size=group_size,
+ sym=sym,
+ iters=1,
+ seqlen=2,
+ dataset=self.llm_dataloader,
+ layer_config=layer_config
+ )
+ quantized_model_path = "./saved"
+ autoround.quantize_and_save(output_dir=quantized_model_path, format="auto_gptq")
+
+ model = AutoModelForCausalLM.from_pretrained(quantized_model_path, device_map="auto", trust_remote_code=True)
+ tokenizer = AutoTokenizer.from_pretrained(quantized_model_path)
+ text = "There is a girl who likes adventure,"
+ inputs = tokenizer(text, return_tensors="pt").to(model.device)
+ res = tokenizer.decode(model.generate(**inputs, max_new_tokens=50)[0])
+ assert (
+ res == "</s>There is a girl who likes adventure, she is a great artist, she is a great artist,"
+ " she is a great artist, she is a great artist, she is a great artist, "
+ "she is a great artist, she is a great artist, she is a great artist, she is")
+ from auto_round import AutoRoundConfig
+
+ model = AutoModelForCausalLM.from_pretrained(quantized_model_path, device_map="auto", trust_remote_code=True,
+ quantization_config=AutoRoundConfig())
+ tokenizer = AutoTokenizer.from_pretrained(quantized_model_path)
+ text = "There is a girl who likes adventure,"
+ inputs = tokenizer(text, return_tensors="pt").to(model.device)
+ g_tokens = model.generate(**inputs, max_new_tokens=50)[0]
+ res = tokenizer.decode(g_tokens)
+ assert (
+ res == "</s>There is a girl who likes adventure, she is a great artist, she is a great artist,"
+ " she is a great artist, she is a great artist, she is a great artist, she is a great "
+ "artist, she is a great artist, she is a great artist, she is")
+ ##print(res)
+ shutil.rmtree("./saved", ignore_errors=True)
+
+ def test_autoround_format(self):
+ model = AutoModelForCausalLM.from_pretrained(self.model_name, torch_dtype="auto", trust_remote_code=True)
+ tokenizer = AutoTokenizer.from_pretrained(self.model_name, trust_remote_code=True)
+ bits, group_size, sym = 4, 128, False
+ autoround = AutoRound(
+ model,
+ tokenizer,
+ bits=bits,
+ group_size=group_size,
+ sym=sym,
+ iters=1,
+ 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")
+
+ model = AutoModelForCausalLM.from_pretrained(quantized_model_path, device_map="auto")
+ tokenizer = AutoTokenizer.from_pretrained(quantized_model_path)
+ text = "There is a girl who likes adventure,"
+ inputs = tokenizer(text, return_tensors="pt").to(model.device)
+ res = tokenizer.decode(model.generate(**inputs, max_new_tokens=50)[0])
+ print(res)
+ assert res == ("</s>There is a girl who likes adventure, she is a great artist, she is a great artist,"
+ " she is a great artist, she is a great artist, she is a great artist, "
+ "she is a great artist, she is a great artist, she is a great artist, she is")
+ shutil.rmtree("./saved", ignore_errors=True)
+
+
+ #
+ def test_autoawq_format(self):
+ model = AutoModelForCausalLM.from_pretrained(self.model_name, torch_dtype="auto", trust_remote_code=True)
+ tokenizer = AutoTokenizer.from_pretrained(self.model_name, trust_remote_code=True)
+ bits, group_size, sym = 4, 128, False
+ autoround = AutoRound(
+ model,
+ tokenizer,
+ bits=bits,
+ group_size=group_size,
+ sym=sym,
+ iters=1,
+ seqlen=2,
+ dataset=self.llm_dataloader,
+ )
+ autoround.quantize()
+ quantized_model_path = "./saved"
+
+ autoround.save_quantized(output_dir=quantized_model_path, inplace=False, \
+ format="auto_awq")
+
+ model = AutoModelForCausalLM.from_pretrained(quantized_model_path, device_map="auto")
+ tokenizer = AutoTokenizer.from_pretrained(quantized_model_path)
+ text = "There is a girl who likes adventure,"
+ inputs = tokenizer(text, return_tensors="pt").to(model.device)
+ res = tokenizer.decode(model.generate(**inputs, max_new_tokens=50)[0])
+ assert res == ("</s>There is a girl who likes adventure, but she's not a very good one.\nI don't"
+ " know why you're getting downvoted. I think you're just being a dick.\nI'm not a dick, "
+ "I just think it's funny that people are downvoting")
+ shutil.rmtree("./saved", ignore_errors=True)
+
+ def test_autoawq_format_fp_qsave_layers(self):
+ model = AutoModelForCausalLM.from_pretrained(self.model_name, torch_dtype="auto", trust_remote_code=True)
+ layer_config = {"model.decoder.layers.0.self_attn.k_proj": {"bits": 16},
+ "model.decoder.layers.9.self_attn.v_proj": {"bits": 16}, }
+ tokenizer = AutoTokenizer.from_pretrained(self.model_name, trust_remote_code=True)
+ bits, group_size, sym = 4, 128, False
+ autoround = AutoRound(
+ model,
+ tokenizer,
+ bits=bits,
+ group_size=group_size,
+ sym=sym,
+ iters=1,
+ seqlen=2,
+ dataset=self.llm_dataloader,
+ layer_config=layer_config
+ )
+ quantized_model_path = "/data5/wenhuach/test_export"
+ autoround.qsave(output_dir=quantized_model_path,
+ format="auto_awq")
+ from auto_round import AutoRoundConfig
+ model = AutoModelForCausalLM.from_pretrained(quantized_model_path, device_map="auto",
+ quantization_config=AutoRoundConfig())
+ 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)
+
+ model = AutoModelForCausalLM.from_pretrained(quantized_model_path, device_map="auto")
+ tokenizer = AutoTokenizer.from_pretrained(quantized_model_path)
+ text = "There is a girl who likes adventure,"
+ inputs = tokenizer(text, return_tensors="pt").to(model.device)
+ res = tokenizer.decode(model.generate(**inputs, max_new_tokens=50)[0])
+ print(res)
+
+ shutil.rmtree("./saved", ignore_errors=True)