Skip to content

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

refine the code (#143)

wenhuach2159c640226e7a
diff --git a/README.md b/README.md
index 428e623b0..d9027c20d 100644
--- a/README.md
+++ b/README.md
@@ -40,10 +40,12 @@ image presents an overview of AutoRound.
### Build from Source
```bash
+pip install -vvv --no-build-isolation -e .
+or
pip install -r requirements.txt
python setup.py install
-or
-pip install -vvv --no-build-isolation -e .
+
+
```
### Install from pypi
diff --git a/auto_round/auto_quantizer.py b/auto_round/auto_quantizer.py
index cb7ebee01..a49fb2f33 100644
--- a/auto_round/auto_quantizer.py
+++ b/auto_round/auto_quantizer.py
@@ -80,6 +80,11 @@ _auto_round_available = _is_package_available("auto_round")
def is_auto_round_available():
+ try:
+ import auto_round
+ return True
+ except:
+ pass
if _auto_round_available:
version_autoround = version.parse(importlib_metadata.version("auto_round"))
if AUTOROUND_MINIMUM_VERSION < version_autoround:
diff --git a/auto_round/autoround.py b/auto_round/autoround.py
index 127ca52cb..5d135932e 100644
--- a/auto_round/autoround.py
+++ b/auto_round/autoround.py
@@ -22,6 +22,7 @@ import transformers
from torch import autocast
from .calib_dataset import get_dataloader
+from .quantizer import WrapperMultiblock, wrapper_block, unwrapper_block, WrapperLinear, unwrapper_layer
from .special_model_handler import check_hidden_state_dim, check_share_attention_mask
from .utils import (
CpuInfo,
@@ -34,324 +35,14 @@ from .utils import (
detect_device,
get_block_names,
get_module,
- get_scale_shape,
htcore,
is_optimum_habana_available,
logger,
- quant_weight,
sampling_inputs,
- set_module,
- to_device,
+ to_device, get_layer_names_in_block,
)
-class WrapperLinear(torch.nn.Module):
- def __init__(self, orig_layer, enable_minmax_tuning=True):
- """A wrapper module for linear layers that enables quantization and min-max tuning of weights.
-
- Args:
- - orig_layer (torch.nn.Module): The original linear layer to be wrapped.
- - enable_minmax_tuning (bool): Whether to enable min-max scaling tuning. Default is True.
-
- Attributes:
- - orig_layer (torch.nn.Module): The original linear layer being wrapped.
- - num_bits (int): The number of bits for quantization.
- - group_size (int): The size of the groups for quantization.
- - sym (bool): Whether the symmetric quantization is to be used.
- - value (torch.nn.Parameter): The learnable parameter for quantization.
- - enable_minmax_tuning (bool): Whether min-max scaling tuning is enabled.
- - min_scale (torch.nn.Parameter or torch.Tensor): The minimum scale for min-max tuning.
- - max_scale (torch.nn.Parameter or torch.Tensor): The maximum scale for min-max tuning.
- """
- super(WrapperLinear, self).__init__()
- self.orig_layer = orig_layer
- self.num_bits = self.orig_layer.bits
- self.group_size = self.orig_layer.group_size
- self.scale_dtype = self.orig_layer.scale_dtype
- self.sym = self.orig_layer.sym
- weight_dtype = self.orig_layer.weight.dtype
- weight_dtype = torch.float32
- self.value = torch.nn.Parameter(
- torch.zeros(self.orig_layer.weight.shape, device=self.orig_layer.weight.device, dtype=weight_dtype),
- requires_grad=True,
- )
- self.enable_minmax_tuning = enable_minmax_tuning
- shape = get_scale_shape(self.orig_layer.weight, self.group_size)
- if self.enable_minmax_tuning:
- self.min_scale = torch.nn.Parameter(
- torch.zeros(shape, device=self.orig_layer.weight.device, dtype=weight_dtype), requires_grad=True
- )
- self.max_scale = torch.nn.Parameter(
- torch.zeros(shape, device=self.orig_layer.weight.device, dtype=weight_dtype), requires_grad=True
- )
- else:
- self.min_scale = torch.tensor(0, device=self.orig_layer.weight.device, dtype=weight_dtype)
- self.max_scale = torch.tensor(0, device=self.orig_layer.weight.device, dtype=weight_dtype)
-
- def unwrapper(self, v, min_scale, max_scale):
- """Unwrapper the layer to the original layer.
-
- Args:
- - v (torch.Tensor): The rounding v parameter for quantization.
- - min_scale (torch.nn.Parameter or torch.Tensor): The minimum scale for min-max tuning.
- - max_scale (torch.nn.Parameter or torch.Tensor): The maximum scale for min-max tuning.
-
- Returns:
- - torch.nn.Module: The original linear layer with updated weights after quantization and dequantization.
- """
- min_scale.clamp_(-1, 0)
- max_scale.clamp_(-1, 0)
-
- q_dq_weight, scale, zp = quant_weight(
- self.orig_layer.weight,
- self.num_bits,
- self.group_size,
- self.sym,
- v,
- min_scale,
- max_scale,
- self.scale_dtype,
- )
- self.orig_layer.weight.data.copy_(q_dq_weight)
- self.orig_layer.weight.grad = None ##clear grad
- self.orig_layer.scale = scale.to("cpu")
- self.orig_layer.zp = zp.to("cpu") if zp is not None else None
- return self.orig_layer
-
- def forward(self, x):
- """Performs forward pass through the wrapped linear layer with quantized weights.
-
- Args:
- - x (torch.Tensor): The input tensor.
-
- Returns:
- - torch.Tensor: The output tensor after applying the linear transformation with quantized weights.
- """
- from torch.functional import F
-
- weight = self.orig_layer.weight
- self.min_scale.data.copy_(torch.clamp(self.min_scale.data, -1, 0))
- self.max_scale.data.copy_(torch.clamp(self.max_scale.data, -1, 0))
- weight_q, _, _ = quant_weight(
- weight,
- self.num_bits,
- self.group_size,
- self.sym,
- self.value,
- self.min_scale,
- self.max_scale,
- self.scale_dtype,
- )
- weight_q = weight_q.to(weight.dtype)
- # pylint: disable=not-callable
- return F.linear(x, weight_q, self.orig_layer.bias)
-
-
-class WrapperTransformerConv1d(torch.nn.Module):
- def __init__(self, orig_layer, enable_minmax_tuning=True):
- """A wrapper module for transformers 1D convolutional layers used in transformers,
- enabling quantization and min-max tuning of weights.
-
- Args:
- - orig_layer (torch.nn.Module): The original 1D convolutional layer to be wrapped.
- - num_bits (int): The number of bits for quantization.
- - group_size (int): The size of the groups for quantization.
- - sym (bool): Whether symmetric quantization is to be used.
- - enable_minmax_tuning (bool): Whether to enable min-max scaling tuning. Default is True.
-
- Attributes:
- - orig_layer (torch.nn.Module): The original 1D convolutional layer being wrapped.
- - num_bits (int): The number of bits for quantization.
- - group_size (int): The size of the groups for quantization.
- - sym (bool): Whether symmetric quantization is to be used.
- - weight_t (torch.Tensor): Transposed weight tensor of the original layer.
- - value (torch.nn.Parameter): The learnable parameter for quantization.
- - enable_minmax_tuning (bool): Whether min-max scaling tuning is enabled.
- - min_scale (torch.nn.Parameter or torch.Tensor): The minimum scale for min-max tuning.
- - max_scale (torch.nn.Parameter or torch.Tensor): The maximum scale for min-max tuning.
- """
- super(WrapperTransformerConv1d, self).__init__()
- self.orig_layer = orig_layer
- self.num_bits = self.orig_layer.bits
- self.group_size = self.orig_layer.group_size
- self.sym = self.orig_layer.sym
- self.scale_dtype = self.orig_layer.scale_dtype
- weight_dtype = self.orig_layer.weight.dtype
- weight_dtype = torch.float32
- device = self.orig_layer.weight.device
- self.weight_t = self.orig_layer.weight.t()
- self.value = torch.nn.Parameter(
- torch.zeros(self.weight_t.shape, device=device, dtype=weight_dtype), requires_grad=True
- )
- shape = get_scale_shape(self.weight_t, self.group_size)
-
- if enable_minmax_tuning:
- self.min_scale = torch.nn.Parameter(
- torch.zeros(shape, device=device, dtype=weight_dtype), requires_grad=True
- )
- self.max_scale = torch.nn.Parameter(
- torch.zeros(shape, device=device, dtype=weight_dtype), requires_grad=True
- )
- else:
- self.min_scale = torch.tensor(0, device=device, dtype=weight_dtype)
- self.max_scale = torch.tensor(0, device=device, dtype=weight_dtype)
-
- def unwrapper(self, v=0, min_scale=0, max_scale=0):
- """Unwrapper the layer to the original conv1d layer.
-
- Args:
- - v (torch.Tensor): The scaling parameter for quantization.
- - min_scale (torch.nn.Parameter or torch.Tensor): The minimum scale for min-max tuning.
- - max_scale (torch.nn.Parameter or torch.Tensor): The maximum scale for min-max tuning.
-
- Returns:
- - torch.nn.Module: The original 1D convolutional layer with updated weights after inverse quantization.
- """
- min_scale.clamp_(-1, 0)
- max_scale.clamp_(-1, 0)
- weight_q, scale, zp = quant_weight(
- self.weight_t, self.num_bits, self.group_size, self.sym, v, min_scale, max_scale, self.scale_dtype
- )
- self.orig_layer.weight.data.copy_(weight_q.t())
- self.orig_layer.weight.grad = None
- self.orig_layer.scale = scale.to("cpu")
- self.orig_layer.zp = zp.to("cpu")
- return self.orig_layer
-
- def forward(self, x):
- """Performs forward pass through the wrapped 1D convolutional layer with quantized weights.
-
- Args:
- x (torch.Tensor): The input tensor.
-
- Returns:
- torch.Tensor: The output tensor after applying the convolutional transformation with quantized weights.
- """
- with torch.no_grad():
- self.min_scale.clamp_(-1, 0)
- self.max_scale.clamp_(-1, 0)
- weight_q, _, _ = quant_weight(
- self.weight_t,
- self.num_bits,
- self.group_size,
- self.sym,
- self.value,
- self.min_scale,
- self.max_scale,
- self.scale_dtype,
- )
- weight_q = weight_q.to(self.weight_t.dtype)
- size_out = x.size()[:-1] + (self.orig_layer.nf,)
- x = torch.addmm(self.orig_layer.bias, x.view(-1, x.size(-1)), weight_q.t())
- x = x.view(*size_out)
- return x
-
-
-class WrapperMultiblock(torch.nn.Module):
- """A wrapper for a list of modules to be act as a single block.
-
- Args:
- module_list: The list of modules to wrap.
- """
-
- def __init__(self, module_list):
- super(WrapperMultiblock, self).__init__()
- self.layers = torch.nn.ModuleList(module_list)
-
- def forward(self, x, **kwargs):
- hidden_states = x
- for idx, decoder_layer in enumerate(self.layers):
- layer_outputs = decoder_layer(hidden_states, **kwargs)
- hidden_states = layer_outputs
- if isinstance(hidden_states, tuple) or isinstance(hidden_states, list):
- hidden_states = layer_outputs[0]
- return hidden_states
-
-
-def wrapper_block(block, enable_minmax_tuning):
- """Wraps the layers in the given block with a custom Wrapper module.
-
- Args:
- block: The input block containing linear and conv1d layers to be wrapped.
- enable_minmax_tuning: A boolean indicating whether min-max tuning is enabled.
-
- Returns:
- list: A list of names of the wrapped layers and unwrapped layers.
- """
- quantized_layers = []
- unquantized_layers = []
- for n, m in block.named_modules():
- if isinstance(m, torch.nn.Linear):
- if not check_to_quantized(m):
- unquantized_layers.append(n)
- continue
- new_m = WrapperLinear(m, enable_minmax_tuning=enable_minmax_tuning)
- set_module(block, n, new_m)
- quantized_layers.append(n)
-
- if isinstance(m, transformers.modeling_utils.Conv1D):
- if not check_to_quantized(m):
- unquantized_layers.append(n)
- continue
- new_m = WrapperTransformerConv1d(m, enable_minmax_tuning=enable_minmax_tuning)
- set_module(block, n, new_m)
- quantized_layers.append(n)
-
- return quantized_layers, unquantized_layers
-
-
-def unwrapper_layer(model, layer, layer_name, v=0, min_scale=0, max_scale=0):
- """Unwraps the WrapperLinear and WrapperTransformerConv1d modules in the given block.
-
- Args:
- block: The input block containing wrapped modules to be unwrapped.
- vs: A dictionary of scaling parameters for the wrapped modules.
- min_scales: A dictionary of minimum scaling values for the wrapped modules.
- max_scales: A dictionary of maximum scaling values for the wrapped modules.
- """
-
- if hasattr(layer, "orig_layer"):
-
- if isinstance(min_scale, torch.Tensor):
- min_scale = torch.clamp(min_scale, -1, 0)
- max_scale = torch.clamp(max_scale, -1, 0)
-
- else:
- min_scale = torch.tensor(0)
- max_scale = torch.tensor(0)
- orig_layer = layer.unwrapper(v, min_scale, max_scale)
- orig_layer = orig_layer.to("cpu")
- set_module(model, layer_name, orig_layer)
-
-
-def unwrapper_block(block, vs, min_scales, max_scales):
- """Unwraps the WrapperLinear and WrapperTransformerConv1d modules in the given block.
-
- Args:
- block: The input block containing wrapped modules to be unwrapped.
- vs: A dictionary of scaling parameters for the wrapped modules.
- min_scales: A dictionary of minimum scaling values for the wrapped modules.
- max_scales: A dictionary of maximum scaling values for the wrapped modules.
- """
- for n, m in block.named_modules():
- if hasattr(m, "orig_layer"):
- v = 0
- min_scale = torch.tensor(0)
- max_scale = torch.tensor(0)
- if isinstance(vs, dict):
- v = vs[n]
- if isinstance(min_scales, dict):
- min_scale = min_scales[n]
- min_scale = torch.clamp(min_scale, -1, 0)
- if isinstance(max_scales, dict):
- max_scale = max_scales[n]
- max_scale = torch.clamp(max_scale, -1, 0)
- orig_layer = m.unwrapper(v, min_scale, max_scale)
- set_module(block, n, orig_layer)
-
-
class AutoRound(object):
"""This is Signround+ which is an advanced version of Signround. For more information,
please refer to Cheng, Wenhua, et al. "Optimize weight rounding via signed gradient descent
@@ -404,36 +95,36 @@ class AutoRound(object):
"""
def __init__(
- self,
- model,
- tokenizer,
- bits: int = 4,
- group_size: int = 128,
- sym: bool = False,
- weight_config: dict = {},
- enable_full_range: bool = False, ##for symmetric, TODO support later
- batch_size: int = 8,
- amp: bool = True,
- device=None,
- lr_scheduler=None,
- dataset: Union[str, list, tuple, torch.utils.data.DataLoader] = "NeelNanda/pile-10k",
- enable_quanted_input: bool = True,
- enable_minmax_tuning: bool = True,
- lr: float = None,
- minmax_lr: float = None,
- low_gpu_mem_usage: bool = True,
- iters: int = 200,
- seqlen: int = 2048,
- n_samples: int = 512,
- sampler: str = "rand",
- seed: int = 42,
- n_blocks: int = 1,
- gradient_accumulate_steps: int = 1,
- not_use_best_mse: bool = False,
- dynamic_max_gap: int = -1,
- data_type: str = "int", ##only support int for now
- scale_dtype: str = "fp16",
- **kwargs,
+ self,
+ model,
+ tokenizer,
+ bits: int = 4,
+ group_size: int = 128,
+ sym: bool = False,
+ weight_config: dict = {},
+ enable_full_range: bool = False, ##for symmetric, TODO support later
+ batch_size: int = 8,
+ amp: bool = True,
+ device=None,
+ lr_scheduler=None,
+ dataset: Union[str, list, tuple, torch.utils.data.DataLoader] = "NeelNanda/pile-10k",
+ enable_quanted_input: bool = True,
+ enable_minmax_tuning: bool = True,
+ lr: float = None,
+ minmax_lr: float = None,
+ low_gpu_mem_usage: bool = True,
+ iters: int = 200,
+ seqlen: int = 2048,
+ n_samples: int = 512,
+ sampler: str = "rand",
+ seed: int = 42,
+ n_blocks: int = 1,
+ gradient_accumulate_steps: int = 1,
+ not_use_best_mse: bool = False,
+ dynamic_max_gap: int = -1,
+ data_type: str = "int", ##only support int for now
+ scale_dtype: str = "fp16",
+ **kwargs,
):
self.quantized = False
self.model_orig_dtype = model.dtype
@@ -679,7 +370,7 @@ class AutoRound(object):
Returns:
None
"""
- layers_in_blocks = self.get_layer_names_in_block()
+ layers_in_blocks = get_layer_names_in_block(self.model, self.supported_types)
for n, m in self.model.named_modules():
if not isinstance(m, tuple(self.supported_types)):
continue
@@ -1047,7 +738,7 @@ class AutoRound(object):
mse_loss = torch.nn.MSELoss().to(device)
scaler = self.get_scaler() # pylint: disable=assignment-from-none
init_loss = None
- best_v, best_min_scale, best_max_scale = torch.tensor(0), torch.tensor(0), torch.tensor(0)
+ best_v, best_min_scale, best_max_scale = torch.tensor(0), torch.tensor(1.0), torch.tensor(1.0)
gradient_accumulate_steps = self.train_bs ##Force to low gpu
train_bs = 1 ##Force to low gpu
pick_samples = train_bs * gradient_accumulate_steps
@@ -1060,7 +751,7 @@ class AutoRound(object):
whole_indices = torch.randperm(n_samples)[:pick_samples]
for tmp_step in range(gradient_accumulate_steps):
org_input = None
- indices = whole_indices[tmp_step * train_bs : (tmp_step + 1) * train_bs]
+ indices = whole_indices[tmp_step * train_bs: (tmp_step + 1) * train_bs]
if q_inputs is not None:
current_input = [q_inputs[i] for i in indices]
current_input = torch.cat(current_input, dim=0).to(device)
@@ -1092,14 +783,14 @@ class AutoRound(object):
best_loss = total_loss
if not self.not_use_best_mse:
best_v = copy.deepcopy(wrapper_linear.value.data)
- best_min_scale = copy.deepcopy(torch.clamp(wrapper_linear.min_scale.data, -1, 0))
- best_max_scale = copy.deepcopy(torch.clamp(wrapper_linear.max_scale.data, -1, 0))
+ best_min_scale = copy.deepcopy(torch.clamp(wrapper_linear.min_scale.data, 0, 1.0))
+ best_max_scale = copy.deepcopy(torch.clamp(wrapper_linear.max_scale.data, 0, 1.0))
last_best_iter = i
if self.not_use_best_mse and i == self.iters - 1:
best_v = copy.deepcopy(wrapper_linear.value.data)
- best_min_scale = copy.deepcopy(torch.clamp(wrapper_linear.min_scale.data, -1, 0))
- best_max_scale = copy.deepcopy(torch.clamp(wrapper_linear.max_scale.data, -1, 0))
+ best_min_scale = copy.deepcopy(torch.clamp(wrapper_linear.min_scale.data, 0, 1.0))
+ best_max_scale = copy.deepcopy(torch.clamp(wrapper_linear.max_scale.data, 0, 1.0))
if not self.not_use_best_mse:
if self.dynamic_max_gap > 0 and i - last_best_iter >= self.dynamic_max_gap:
@@ -1170,13 +861,13 @@ class AutoRound(object):
mse_loss = torch.nn.MSELoss().to(device)
scaler = self.get_scaler() # pylint: disable=assignment-from-none
init_loss = None
- best_v, best_min_scale, best_max_scale = torch.tensor(0), torch.tensor(0), torch.tensor(0)
+ best_v, best_min_scale, best_max_scale = torch.tensor(0), torch.tensor(1.0), torch.tensor(1.0)
for i in range(self.iters):
total_loss = 0
if self.sampler == "rand":
whole_indices = torch.randperm(n_samples)[:pick_samples]
for tmp_step in range(self.gradient_accumulate_steps):
- indices = whole_indices[tmp_step * self.train_bs : (tmp_step + 1) * self.train_bs]
+ indices = whole_indices[tmp_step * self.train_bs: (tmp_step + 1) * self.train_bs]
current_input_ids, current_input_others = sampling_inputs(
input_ids,
input_others,
@@ -1255,12 +946,12 @@ class AutoRound(object):
return None, output
def quant_blocks(
- self,
- model: torch.nn.Module,
- inputs,
- block_names,
- n_blocks=1,
- device=torch.device("cpu"),
+ self,
+ model: torch.nn.Module,
+ inputs,
+ block_names,
+ n_blocks=1,
+ device=torch.device("cpu"),
):
"""Quantize and dequantize the weights of the specified blocks in the model.
@@ -1291,7 +982,7 @@ class AutoRound(object):
for key in input_others.keys():
if isinstance(input_others[key], torch.Tensor) and (
- input_others[key].dtype == torch.float16 or input_others[key].dtype == torch.bfloat16
+ input_others[key].dtype == torch.float16 or input_others[key].dtype == torch.bfloat16
):
input_others[key] = input_others[key].to(tmp_dtype)
elif isinstance(input_others[key], list):
@@ -1304,7 +995,7 @@ class AutoRound(object):
logger.info(f"quantizing {i + 1}/{len(block_names)}, {n}")
m = get_module(model, n)
else:
- names = block_names[i : i + n_blocks]
+ names = block_names[i: i + n_blocks]
logger.info(names)
modules = [get_module(model, n) for n in names]
m = WrapperMultiblock(modules)
@@ -1371,28 +1062,6 @@ class AutoRound(object):
)
return compressed_model
- def get_layer_names_in_block(self): ##TODO consolidate with utils
- """Retrieves the names of layers within each block of the model.
-
- Returns:
- list: A list of strings, where each string is the name of a layer
- within a block of the model.
- """
- for n, m in self.model.named_modules():
- if isinstance(m, tuple(self.supported_types)):
- m.tmp_name = n
- layers_in_block = []
- block_names = get_block_names(self.model)
- for block_name in block_names:
- block = get_module(self.model, block_name)
- for n, m in block.named_modules():
- if hasattr(m, "tmp_name"):
- layers_in_block.append(m.tmp_name)
- for n, m in self.model.named_modules():
- if hasattr(m, "tmp_name"):
- delattr(m, "tmp_name")
- return layers_in_block
-
def get_quantized_layer_names_outside_blocks(self):
"""Gets the names of quantized layers outside blocks in the model.
@@ -1403,7 +1072,7 @@ class AutoRound(object):
return []
layer_names = []
- all_layers_in_block = self.get_layer_names_in_block()
+ all_layers_in_block = get_layer_names_in_block(self.model, self.supported_types)
for key in self.weight_config.keys():
if key in all_layers_in_block:
@@ -1529,37 +1198,37 @@ class AutoOPTRound(AutoRound):
"""
def __init__(
- self,
- model,
- tokenizer=None,
- bits: int = 4,
- group_size: int = 128,
- sym: bool = False,
- weight_config: dict = {},
- enable_full_range: bool = False,
- batch_size: int = 8,
- amp: bool = True,
- device="auto",
- lr_scheduler=None,
- dataset: Union[str, list, tuple, torch.utils.data.DataLoader] = "NeelNanda/pile-10k",
- enable_quanted_input: bool = True,
- enable_minmax_tuning: bool = True,
- lr: float = None,
- minmax_lr: float = None,
- low_gpu_mem_usage: bool = True,
- iters: int = 200,
- seqlen: int = 2048,
- n_samples: int = 512,
- sampler: str = "rand",
- seed: int = 42,
- n_blocks: int = 1,
- gradient_accumulate_steps: int = 1,
- not_use_best_mse: bool = False,
- dynamic_max_gap: int = -1,
- data_type: str = "int",
- scale_dtype: str = "fp16",
- optimizer="AdamW",
- **kwargs,
+ self,
+ model,
+ tokenizer=None,
+ bits: int = 4,
+ group_size: int = 128,
+ sym: bool = False,
+ weight_config: dict = {},
+ enable_full_range: bool = False,
+ batch_size: int = 8,
+ amp: bool = True,
+ device="auto",
+ lr_scheduler=None,
+ dataset: Union[str, list, tuple, torch.utils.data.DataLoader] = "NeelNanda/pile-10k",
+ enable_quanted_input: bool = True,
+ enable_minmax_tuning: bool = True,
+ lr: float = None,
+ minmax_lr: float = None,
+ low_gpu_mem_usage: bool = True,
+ iters: int = 200,
+ seqlen: int = 2048,
+ n_samples: int = 512,
+ sampler: str = "rand",
+ seed: int = 42,
+ n_blocks: int = 1,
+ gradient_accumulate_steps: int = 1,
+ not_use_best_mse: bool = False,
+ dynamic_max_gap: int = -1,
+ data_type: str = "int",
+ scale_dtype: str = "fp16",
+ optimizer="AdamW",
+ **kwargs,
):
super(AutoOPTRound, self).__init__(
model,
@@ -1677,37 +1346,37 @@ class AutoAdamRound(AutoOPTRound):
"""
def __init__(
- self,
- model,
- tokenizer=None,
- bits: int = 4,
- group_size: int = 128,
- sym: bool = False,
- weight_config: dict = {},
- enable_full_range: bool = False,
- batch_size: int = 8,
- amp: bool = True,
- device="auto",
- lr_scheduler=None,
- dataset: Union[str, list, tuple, torch.utils.data.DataLoader] = "NeelNanda/pile-10k",
- enable_quanted_input: bool = True,
- enable_minmax_tuning: bool = True,
- lr: float = None,
- minmax_lr: float = None,
- low_gpu_mem_usage: bool = True,
- iters: int = 200,
- seqlen: int = 2048,
- n_samples: int = 512,
- sampler: str = "rand",
- seed: int = 42,
- n_blocks: int = 1,
- gradient_accumulate_steps: int = 1,
- not_use_best_mse: bool = False,
- dynamic_max_gap: int = -1,
- data_type: str = "int",
- scale_dtype: str = "fp16",
- optimizer="AdamW",
- **kwargs,
+ self,
+ model,
+ tokenizer=None,
+ bits: int = 4,
+ group_size: int = 128,
+ sym: bool = False,
+ weight_config: dict = {},
+ enable_full_range: bool = False,
+ batch_size: int = 8,
+ amp: bool = True,
+ device="auto",
+ lr_scheduler=None,
+ dataset: Union[str, list, tuple, torch.utils.data.DataLoader] = "NeelNanda/pile-10k",
+ enable_quanted_input: bool = True,
+ enable_minmax_tuning: bool = True,
+ lr: float = None,
+ minmax_lr: float = None,
+ low_gpu_mem_usage: bool = True,
+ iters: int = 200,
+ seqlen: int = 2048,
+ n_samples: int = 512,
+ sampler: str = "rand",
+ seed: int = 42,
+ n_blocks: int = 1,
+ gradient_accumulate_steps: int = 1,
+ not_use_best_mse: bool = False,
+ dynamic_max_gap: int = -1,
+ data_type: str = "int",
+ scale_dtype: str = "fp16",
+ optimizer="AdamW",
+ **kwargs,
):
super(AutoAdamRound, self).__init__(
model,
@@ -1741,4 +1410,3 @@ class AutoAdamRound(AutoOPTRound):
optimizer,
**kwargs,
)
-
diff --git a/auto_round/export/export_to_autogptq.py b/auto_round/export/export_to_autogptq.py
index 4377719ec..e83324592 100644
--- a/auto_round/export/export_to_autogptq.py
+++ b/auto_round/export/export_to_autogptq.py
@@ -50,7 +50,7 @@ from ..utils import convert_dtype_torch2str_hf
@register_format("auto_gptq")
-def save_quantized_as_autogptq(output_dir, use_triton=True, inplace=True, **kwargs):
+def save_quantized_as_autogptq(output_dir, use_triton=True, inplace=True, **kwargs):##TODO align with autoround format
"""Export the model to autogptq format to easily leverage cuda kernel."""
try:
import auto_gptq
diff --git a/auto_round/export/export_to_itrex/export.py b/auto_round/export/export_to_itrex/export.py
index 54b1dcd83..d6d6fe679 100644
--- a/auto_round/export/export_to_itrex/export.py
+++ b/auto_round/export/export_to_itrex/export.py
@@ -15,20 +15,51 @@
import copy
import json
import os
-from os.path import isdir, isfile, join
from typing import Dict, List, Optional, Union
import torch
import transformers
-from safetensors.torch import save_file as safe_save
-
from auto_round.export.register import register_format
-from auto_round.utils import get_module, logger, quant_weight_w_scale, set_module
+from auto_round.utils import get_module, logger, set_module
from .config import QuantConfig
from .model_wrapper import WeightOnlyLinear
+
+def quant_weight_w_scale(weight, scale, zp, group_size=-1, device="cpu"):
+ """Quant and dequant tensor with group size.
+
+ Args:
+ weight: input weight
+ scale: scale
+ zp: zero point
+ group_size (int, optional): how many elements share one scale/zp. Defaults to -1.
+
+ Returns:
+ output: int weight.
+ """
+ scale = scale.to(device)
+ if zp is not None:
+ zp = zp.to(device)
+ if group_size == -1:
+ return torch.round(weight / scale) if zp is None else torch.round(weight / scale + zp)
+ int_weight = torch.zeros(weight.shape).to(device)
+ leng = weight.shape[1] // group_size
+ tail_flag = False if weight.shape[1] % group_size == 0 else True
+ for i in range(leng):
+ int_weight_tmp = weight[:, i * group_size: (i + 1) * group_size] / scale[:, i].unsqueeze(1)
+ if zp is not None:
+ int_weight_tmp += zp[:, i].unsqueeze(1)
+ int_weight[:, i * group_size: (i + 1) * group_size] = torch.round(int_weight_tmp)
+ if tail_flag:
+ int_weight_tmp = weight[:, leng * group_size:] / scale[:, -1].unsqueeze(1)
+ if zp is not None:
+ int_weight_tmp += zp[:, -1].unsqueeze(1)
+ int_weight[:, leng * group_size:] = torch.round(int_weight_tmp)
+ return int_weight
+
+
@register_format("itrex")
def save_quantized_as_itrex(output_dir, inplace=True, **kwargs):
"""Save configure file and weights for CPU backend inference."""
diff --git a/auto_round/quantizer.py b/auto_round/quantizer.py
new file mode 100644
index 000000000..5fce47d40
--- /dev/null
+++ b/auto_round/quantizer.py
@@ -0,0 +1,496 @@
+# 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.
+
+import torch
+import transformers
+
+from .utils import (
+ check_to_quantized,
+ get_scale_shape,
+ set_module
+)
+def round_ste(x: torch.Tensor):
+ """Straight-Through Estimator for rounding.
+ This function is adapted from omniquant.
+
+ Args:
+ x: torch.Tensor
+
+ Returns:
+ torch.Tensor
+ """
+ return (x.round() - x).detach() + x
+
+
+def quant_weight_asym(weight, num_bits=4, v=0, min_scale=1.0, max_scale=1.0, scale_dtype=torch.float16):
+ """Quantizes and dequantizes weight asymmetrically.
+
+ Args:
+ weight: Tensor containing the weight to be quantized
+ num_bits: Number of bits for quantization (e.g., 2, 3, 4, 8)
+ v: Rounding value perturbation
+ min_scale: Minimum scale coefficient for weight
+ max_scale: Maximum scale coefficient for weight
+
+ Returns:
+ Quantized and dequantized weight, scale, zero-point
+ """
+ maxq = torch.tensor(2 ** num_bits - 1)
+ if isinstance(min_scale, torch.Tensor):
+ wmin_tmp = torch.clamp(weight.min(1)[0], max=0)
+ wmax_tmp = torch.clamp(weight.max(1)[0], min=0)
+ wmin_tmp *= min_scale
+ wmax_tmp *= max_scale
+ wmax = torch.maximum(wmax_tmp, wmin_tmp)
+ wmin = torch.minimum(wmax_tmp, wmin_tmp)
+ else:
+ wmin = torch.clamp(weight.min(1)[0], max=0)
+ wmax = torch.clamp(weight.max(1)[0], min=0)
+
+ tmp = (wmin == 0) & (wmax == 0)
+ wmin[tmp] = -1
+ wmax[tmp] = +1
+ scale = ((wmax - wmin) / maxq).to(scale_dtype)
+ zp = round_ste(-wmin / scale)
+ scale = scale.unsqueeze(dim=-1)
+ zp = zp.unsqueeze(dim=-1)
+ int_w = round_ste(weight / scale + v)
+ q = torch.clamp(int_w + zp, 0, maxq)
+ return scale * (q - zp), scale, zp
+
+
+def quant_weight_sym(weight, num_bits=4, v=0, min_scale=1.0, max_scale=1.0, scale_dtype=torch.float16):
+ """Quantizes and dequantizes weight symmetrically.
+
+ Args:
+ weight: Tensor containing the weight to be quantized
+ num_bits: Number of bits for quantization (e.g., 2, 3, 4, 8)
+ v: Rounding value perturbation
+ min_scale: Minimum scale coefficient for weight
+ max_scale: Maximum scale coefficient for weight
+
+ Returns:
+ Quantized and dequantized weight, scale, zero-point
+ """
+ maxq = torch.tensor(2 ** num_bits - 1)
+ if isinstance(min_scale, torch.Tensor):
+ wmin_tmp = torch.clamp(weight.min(1,)[0], max=0)
+ wmax_tmp = torch.clamp(weight.max(1)[0], min=0)
+ wmin_tmp *= min_scale
+ wmax_tmp *= max_scale
+ wmax = torch.maximum(wmax_tmp, wmin_tmp)
+ wmin = torch.minimum(wmax_tmp, wmin_tmp)
+ else:
+ wmin = torch.clamp(weight.min(1)[0], max=0)
+ wmax = torch.clamp(weight.max(1)[0], min=0)
+ wmax_new = torch.max(wmin.abs(), wmax)
+ tmp = wmin < 0
+ wmin_new = wmin.clone() ##must clone, otherwise inplace backward will occur
+ if torch.any(tmp):
+ wmin_new[tmp] = -wmax_new[tmp]
+
+ tmp = (wmin_new == 0) & (wmax_new == 0)
+ wmin_new[tmp] = -1
+ wmax_new[tmp] = +1
+ scale = ((wmax_new - wmin_new) / maxq).to(scale_dtype)
+
+ scale = scale.unsqueeze(dim=-1)
+ zp = torch.full_like(scale, (maxq + 1) / 2)
+
+ int_w = round_ste(weight / scale + v)
+ q = torch.clamp(int_w + zp, 0, maxq)
+ return scale * (q - zp), scale, zp
+
+
+def quant_weight_actor(weight, num_bits, sym, v, min_scale, max_scale, scale_dtype=torch.float16):
+ """Quantizes and dequantizes weight symmetrically or asymmetrically .
+
+ Args:
+ weight: Tensor containing the weight to be quantized
+ num_bits: Number of bits for quantization (e.g., 2, 3, 4, 8)
+ sym: Sym or asym
+ v: Rounding value perturbation
+ min_scale: Minimum scale coefficient for weight
+ max_scale: Maximum scale coefficient for weight
+
+ Returns:
+ Quantized and dequantized weight, scale, zero-point
+ """
+ assert num_bits > 0, "num_bits should be larger than 0"
+ if sym:
+ return quant_weight_sym(weight, num_bits, v, min_scale, max_scale, scale_dtype)
+ else:
+ return quant_weight_asym(weight, num_bits, v, min_scale, max_scale, scale_dtype)
+
+
+def quant_weight(
+ weight, num_bits=4, group_size=-1, sym=False, v=0, min_scale=1.0, max_scale=1.0, scale_dtype=torch.float16
+):
+ """Quantizes and dequantizes weight, handing the group size issue .
+
+ Args:
+ weight: Tensor containing the weight to be quantized
+ num_bits: Number of bits for quantization (e.g., 2, 3, 4, 8)
+ group_size: The number of elements shares scale and zero point
+ sym: Sym or asym
+ v: Rounding value perturbation
+ min_scale: Minimum scale coefficient for weight
+ max_scale: Maximum scale coefficient for weight
+
+ Returns:
+ Quantized and dequantized weight, scale, zero-point
+ """
+ if group_size == -1 or weight.shape[1] < group_size:
+ return quant_weight_actor(
+ weight, num_bits, sym=sym, v=v, min_scale=min_scale, max_scale=max_scale, scale_dtype=scale_dtype
+ )
+ orig_shape = weight.shape
+ if weight.shape[1] % group_size == 0:
+ weight = weight.reshape(-1, group_size)
+ if isinstance(v, torch.Tensor):
+ v = v.reshape(-1, group_size)
+
+ weight, scale, zp = quant_weight_actor(
+ weight, num_bits, sym=sym, v=v, min_scale=min_scale, max_scale=max_scale, scale_dtype=scale_dtype
+ )
+ weight = weight.reshape(orig_shape)
+ scale = scale.reshape(weight.shape[0], -1) ##only for linear, conv1d
+ if zp is not None:
+ zp = zp.reshape(weight.shape[0], -1)
+ return weight, scale, zp
+
+ else:
+ pad_len = (weight.shape[1] + group_size - 1) // group_size * group_size - weight.shape[1]
+ weight_new = torch.nn.functional.pad(weight, (0, pad_len))
+ v = torch.nn.functional.pad(v, (0, pad_len))
+ weight_new = weight_new.reshape(-1, group_size)
+ if isinstance(v, torch.Tensor):
+ v = v.reshape(-1, group_size)
+ weight_new, scale, zp = quant_weight_actor(
+ weight_new, num_bits, sym=sym, v=v, min_scale=min_scale, max_scale=max_scale, scale_dtype=scale_dtype
+ )
+ weight_new = weight_new.reshape(orig_shape[0], -1)
+
+ weight_new = weight_new[:, :-pad_len]
+ scale = scale.reshape(weight_new.shape[0], -1) ##only for linear, conv1d
+ if zp is not None:
+ zp = zp.reshape(weight_new.shape[0], -1)
+ return weight_new, scale, zp
+
+
+class WrapperLinear(torch.nn.Module):
+ def __init__(self, orig_layer, enable_minmax_tuning=True):
+ """A wrapper module for linear layers that enables quantization and min-max tuning of weights.
+
+ Args:
+ - orig_layer (torch.nn.Module): The original linear layer to be wrapped.
+ - enable_minmax_tuning (bool): Whether to enable min-max scaling tuning. Default is True.
+
+ Attributes:
+ - orig_layer (torch.nn.Module): The original linear layer being wrapped.
+ - num_bits (int): The number of bits for quantization.
+ - group_size (int): The size of the groups for quantization.
+ - sym (bool): Whether the symmetric quantization is to be used.
+ - value (torch.nn.Parameter): The learnable parameter for quantization.
+ - enable_minmax_tuning (bool): Whether min-max scaling tuning is enabled.
+ - min_scale (torch.nn.Parameter or torch.Tensor): The minimum scale for min-max tuning.
+ - max_scale (torch.nn.Parameter or torch.Tensor): The maximum scale for min-max tuning.
+ """
+ super(WrapperLinear, self).__init__()
+ self.orig_layer = orig_layer
+ self.num_bits = self.orig_layer.bits
+ self.group_size = self.orig_layer.group_size
+ self.scale_dtype = self.orig_layer.scale_dtype
+ self.sym = self.orig_layer.sym
+ weight_dtype = self.orig_layer.weight.dtype
+ weight_dtype = torch.float32
+ self.value = torch.nn.Parameter(
+ torch.zeros(self.orig_layer.weight.shape, device=self.orig_layer.weight.device, dtype=weight_dtype),
+ requires_grad=True,
+ )
+ self.enable_minmax_tuning = enable_minmax_tuning
+ shape = get_scale_shape(self.orig_layer.weight, self.group_size)
+ if self.enable_minmax_tuning:
+ self.min_scale = torch.nn.Parameter(
+ torch.ones(shape, device=self.orig_layer.weight.device, dtype=weight_dtype), requires_grad=True
+ )
+ self.max_scale = torch.nn.Parameter(
+ torch.ones(shape, device=self.orig_layer.weight.device, dtype=weight_dtype), requires_grad=True
+ )
+ else:
+ self.min_scale = torch.tensor(1.0, device=self.orig_layer.weight.device, dtype=weight_dtype)
+ self.max_scale = torch.tensor(1.0, device=self.orig_layer.weight.device, dtype=weight_dtype)
+
+ def unwrapper(self, v, min_scale, max_scale):
+ """Unwrapper the layer to the original layer.
+
+ Args:
+ - v (torch.Tensor): The rounding v parameter for quantization.
+ - min_scale (torch.nn.Parameter or torch.Tensor): The minimum scale for min-max tuning.
+ - max_scale (torch.nn.Parameter or torch.Tensor): The maximum scale for min-max tuning.
+
+ Returns:
+ - torch.nn.Module: The original linear layer with updated weights after quantization and dequantization.
+ """
+ min_scale.clamp_(0, 1.0)
+ max_scale.clamp_(0, 1.0)
+
+ q_dq_weight, scale, zp = quant_weight(
+ self.orig_layer.weight,
+ self.num_bits,
+ self.group_size,
+ self.sym,
+ v,
+ min_scale,
+ max_scale,
+ self.scale_dtype,
+ )
+ self.orig_layer.weight.data.copy_(q_dq_weight)
+ self.orig_layer.weight.grad = None ##clear grad
+ self.orig_layer.scale = scale.to("cpu")
+ self.orig_layer.zp = zp.to("cpu") if zp is not None else None
+ return self.orig_layer
+
+ def forward(self, x):
+ """Performs forward pass through the wrapped linear layer with quantized weights.
+
+ Args:
+ - x (torch.Tensor): The input tensor.
+
+ Returns:
+ - torch.Tensor: The output tensor after applying the linear transformation with quantized weights.
+ """
+ from torch.functional import F
+
+ weight = self.orig_layer.weight
+ self.min_scale.data.copy_(torch.clamp(self.min_scale.data, 0, 1.0))
+ self.max_scale.data.copy_(torch.clamp(self.max_scale.data, 0, 1.0))
+ weight_q, _, _ = quant_weight(
+ weight,
+ self.num_bits,
+ self.group_size,
+ self.sym,
+ self.value,
+ self.min_scale,
+ self.max_scale,
+ self.scale_dtype,
+ )
+ weight_q = weight_q.to(weight.dtype)
+ # pylint: disable=not-callable
+ return F.linear(x, weight_q, self.orig_layer.bias)
+
+
+class WrapperTransformerConv1d(torch.nn.Module):
+ def __init__(self, orig_layer, enable_minmax_tuning=True):
+ """A wrapper module for transformers 1D convolutional layers used in transformers,
+ enabling quantization and min-max tuning of weights.
+
+ Args:
+ - orig_layer (torch.nn.Module): The original 1D convolutional layer to be wrapped.
+ - num_bits (int): The number of bits for quantization.
+ - group_size (int): The size of the groups for quantization.
+ - sym (bool): Whether symmetric quantization is to be used.
+ - enable_minmax_tuning (bool): Whether to enable min-max scaling tuning. Default is True.
+
+ Attributes:
+ - orig_layer (torch.nn.Module): The original 1D convolutional layer being wrapped.
+ - num_bits (int): The number of bits for quantization.
+ - group_size (int): The size of the groups for quantization.
+ - sym (bool): Whether symmetric quantization is to be used.
+ - weight_t (torch.Tensor): Transposed weight tensor of the original layer.
+ - value (torch.nn.Parameter): The learnable parameter for quantization.
+ - enable_minmax_tuning (bool): Whether min-max scaling tuning is enabled.
+ - min_scale (torch.nn.Parameter or torch.Tensor): The minimum scale for min-max tuning.
+ - max_scale (torch.nn.Parameter or torch.Tensor): The maximum scale for min-max tuning.
+ """
+ super(WrapperTransformerConv1d, self).__init__()
+ self.orig_layer = orig_layer
+ self.num_bits = self.orig_layer.bits
+ self.group_size = self.orig_layer.group_size
+ self.sym = self.orig_layer.sym
+ self.scale_dtype = self.orig_layer.scale_dtype
+ weight_dtype = self.orig_layer.weight.dtype
+ weight_dtype = torch.float32
+ device = self.orig_layer.weight.device
+ self.weight_t = self.orig_layer.weight.t()
+ self.value = torch.nn.Parameter(
+ torch.zeros(self.weight_t.shape, device=device, dtype=weight_dtype), requires_grad=True
+ )
+ shape = get_scale_shape(self.weight_t, self.group_size)
+
+ if enable_minmax_tuning:
+ self.min_scale = torch.nn.Parameter(
+ torch.ones(shape, device=device, dtype=weight_dtype), requires_grad=True
+ )
+ self.max_scale = torch.nn.Parameter(
+ torch.ones(shape, device=device, dtype=weight_dtype), requires_grad=True
+ )
+ else:
+ self.min_scale = torch.tensor(1.0, device=device, dtype=weight_dtype)
+ self.max_scale = torch.tensor(1.0, device=device, dtype=weight_dtype)
+
+ def unwrapper(self, v=0, min_scale=1.0, max_scale=1.0):
+ """Unwrapper the layer to the original conv1d layer.
+
+ Args:
+ - v (torch.Tensor): The scaling parameter for quantization.
+ - min_scale (torch.nn.Parameter or torch.Tensor): The minimum scale for min-max tuning.
+ - max_scale (torch.nn.Parameter or torch.Tensor): The maximum scale for min-max tuning.
+
+ Returns:
+ - torch.nn.Module: The original 1D convolutional layer with updated weights after inverse quantization.
+ """
+ min_scale.clamp_(0, 1.0)
+ max_scale.clamp_(0, 1.0)
+ weight_q, scale, zp = quant_weight(
+ self.weight_t, self.num_bits, self.group_size, self.sym, v, min_scale, max_scale, self.scale_dtype
+ )
+ self.orig_layer.weight.data.copy_(weight_q.t())
+ self.orig_layer.weight.grad = None
+ self.orig_layer.scale = scale.to("cpu")
+ self.orig_layer.zp = zp.to("cpu")
+ return self.orig_layer
+
+ def forward(self, x):
+ """Performs forward pass through the wrapped 1D convolutional layer with quantized weights.
+
+ Args:
+ x (torch.Tensor): The input tensor.
+
+ Returns:
+ torch.Tensor: The output tensor after applying the convolutional transformation with quantized weights.
+ """
+ with torch.no_grad():
+ self.min_scale.clamp_(0, 1.0)
+ self.max_scale.clamp_(0, 1.0)
+ weight_q, _, _ = quant_weight(
+ self.weight_t,
+ self.num_bits,
+ self.group_size,
+ self.sym,
+ self.value,
+ self.min_scale,
+ self.max_scale,
+ self.scale_dtype,
+ )
+ weight_q = weight_q.to(self.weight_t.dtype)
+ size_out = x.size()[:-1] + (self.orig_layer.nf,)
+ x = torch.addmm(self.orig_layer.bias, x.view(-1, x.size(-1)), weight_q.t())
+ x = x.view(*size_out)
+ return x
+
+
+class WrapperMultiblock(torch.nn.Module):
+ """A wrapper for a list of modules to be act as a single block.
+
+ Args:
+ module_list: The list of modules to wrap.
+ """
+
+ def __init__(self, module_list):
+ super(WrapperMultiblock, self).__init__()
+ self.layers = torch.nn.ModuleList(module_list)
+
+ def forward(self, x, **kwargs):
+ hidden_states = x
+ for idx, decoder_layer in enumerate(self.layers):
+ layer_outputs = decoder_layer(hidden_states, **kwargs)
+ hidden_states = layer_outputs
+ if isinstance(hidden_states, tuple) or isinstance(hidden_states, list):
+ hidden_states = layer_outputs[0]
+ return hidden_states
+
+
+def wrapper_block(block, enable_minmax_tuning):
+ """Wraps the layers in the given block with a custom Wrapper module.
+
+ Args:
+ block: The input block containing linear and conv1d layers to be wrapped.
+ enable_minmax_tuning: A boolean indicating whether min-max tuning is enabled.
+
+ Returns:
+ list: A list of names of the wrapped layers and unwrapped layers.
+ """
+ quantized_layers = []
+ unquantized_layers = []
+ for n, m in block.named_modules():
+ if isinstance(m, torch.nn.Linear):
+ if not check_to_quantized(m):
+ unquantized_layers.append(n)
+ continue
+ new_m = WrapperLinear(m, enable_minmax_tuning=enable_minmax_tuning)
+ set_module(block, n, new_m)
+ quantized_layers.append(n)
+
+ if isinstance(m, transformers.modeling_utils.Conv1D):
+ if not check_to_quantized(m):
+ unquantized_layers.append(n)
+ continue
+ new_m = WrapperTransformerConv1d(m, enable_minmax_tuning=enable_minmax_tuning)
+ set_module(block, n, new_m)
+ quantized_layers.append(n)
+
+ return quantized_layers, unquantized_layers
+
+
+def unwrapper_layer(model, layer, layer_name, v=0, min_scale=0, max_scale=0):
+ """Unwraps the WrapperLinear and WrapperTransformerConv1d modules in the given block.
+
+ Args:
+ block: The input block containing wrapped modules to be unwrapped.
+ vs: A dictionary of scaling parameters for the wrapped modules.
+ min_scales: A dictionary of minimum scaling values for the wrapped modules.
+ max_scales: A dictionary of maximum scaling values for the wrapped modules.
+ """
+
+ if hasattr(layer, "orig_layer"):
+
+ if isinstance(min_scale, torch.Tensor):
+ min_scale = torch.clamp(min_scale, 0, 1.0)
+ max_scale = torch.clamp(max_scale, 0, 1.0)
+
+ else:
+ min_scale = torch.tensor(1.0)
+ max_scale = torch.tensor(1.0)
+ orig_layer = layer.unwrapper(v, min_scale, max_scale)
+ orig_layer = orig_layer.to("cpu")
+ set_module(model, layer_name, orig_layer)
+
+
+def unwrapper_block(block, vs, min_scales, max_scales):
+ """Unwraps the WrapperLinear and WrapperTransformerConv1d modules in the given block.
+
+ Args:
+ block: The input block containing wrapped modules to be unwrapped.
+ vs: A dictionary of scaling parameters for the wrapped modules.
+ min_scales: A dictionary of minimum scaling values for the wrapped modules.
+ max_scales: A dictionary of maximum scaling values for the wrapped modules.
+ """
+ for n, m in block.named_modules():
+ if hasattr(m, "orig_layer"):
+ v = 0
+ min_scale = torch.tensor(1.0)
+ max_scale = torch.tensor(1.0)
+ if isinstance(vs, dict):
+ v = vs[n]
+ if isinstance(min_scales, dict):
+ min_scale = min_scales[n]
+ min_scale = torch.clamp(min_scale, 0, 1.0)
+ if isinstance(max_scales, dict):
+ max_scale = max_scales[n]
+ max_scale = torch.clamp(max_scale, 0, 1.0)
+ orig_layer = m.unwrapper(v, min_scale, max_scale)
+ set_module(block, n, orig_layer)
\ No newline at end of file
diff --git a/auto_round/utils.py b/auto_round/utils.py
index f661aeeab..a4a50a6ed 100644
--- a/auto_round/utils.py
+++ b/auto_round/utils.py
@@ -36,6 +36,7 @@ logger.addHandler(fh)
import importlib
import transformers
+
class LazyImport(object):
"""Lazy import python module till use."""
@@ -78,208 +79,6 @@ def is_optimum_habana_available():
return is_optimum_available() and importlib.util.find_spec("optimum.habana") is not None
-def round_ste(x: torch.Tensor):
- """Straight-Through Estimator for rounding.
- This function is adapted from omniquant.
-
- Args:
- x: torch.Tensor
-
- Returns:
- torch.Tensor
- """
- return (x.round() - x).detach() + x
-
-
-def quant_weight_asym(weight, num_bits=4, v=0, min_scale=0, max_scale=0, scale_dtype=torch.float16):
- """Quantizes and dequantizes weight asymmetrically.
-
- Args:
- weight: Tensor containing the weight to be quantized
- num_bits: Number of bits for quantization (e.g., 2, 3, 4, 8)
- v: Rounding value perturbation
- min_scale: Minimum scale coefficient for weight
- max_scale: Maximum scale coefficient for weight
-
- Returns:
- Quantized and dequantized weight, scale, zero-point
- """
- maxq = torch.tensor(2**num_bits - 1)
- if isinstance(min_scale, torch.Tensor):
- wmin_tmp = torch.clamp(weight.min(1)[0], max=0)
- wmax_tmp = torch.clamp(weight.max(1)[0], min=0)
- wmin_tmp *= min_scale + 1.0
- wmax_tmp *= max_scale + 1.0
- wmax = torch.maximum(wmax_tmp, wmin_tmp)
- wmin = torch.minimum(wmax_tmp, wmin_tmp)
- else:
- wmin = torch.clamp(weight.min(1)[0], max=0)
- wmax = torch.clamp(weight.max(1)[0], min=0)
-
- tmp = (wmin == 0) & (wmax == 0)
- wmin[tmp] = -1
- wmax[tmp] = +1
- scale = ((wmax - wmin) / maxq).to(scale_dtype)
- zp = round_ste(-wmin / scale)
- scale = scale.unsqueeze(dim=-1)
- zp = zp.unsqueeze(dim=-1)
- int_w = round_ste(weight / scale + v)
- q = torch.clamp(int_w + zp, 0, maxq)
- return scale * (q - zp), scale, zp
-
-
-def quant_weight_sym(weight, num_bits=4, v=0, min_scale=0, max_scale=0, scale_dtype=torch.float16):
- """Quantizes and dequantizes weight symmetrically.
-
- Args:
- weight: Tensor containing the weight to be quantized
- num_bits: Number of bits for quantization (e.g., 2, 3, 4, 8)
- v: Rounding value perturbation
- min_scale: Minimum scale coefficient for weight
- max_scale: Maximum scale coefficient for weight
-
- Returns:
- Quantized and dequantized weight, scale, zero-point
- """
- maxq = torch.tensor(2**num_bits - 1)
- if isinstance(min_scale, torch.Tensor):
- wmin_tmp = torch.clamp(weight.min(1)[0], max=0)
- wmax_tmp = torch.clamp(weight.max(1)[0], min=0)
- wmin_tmp *= min_scale + 1.0
- wmax_tmp *= max_scale + 1.0
- wmax = torch.maximum(wmax_tmp, wmin_tmp)
- wmin = torch.minimum(wmax_tmp, wmin_tmp)
- else:
- wmin = torch.clamp(weight.min(1)[0], max=0)
- wmax = torch.clamp(weight.max(1)[0], min=0)
- wmax_new = torch.max(wmin.abs(), wmax)
- tmp = wmin < 0
- wmin_new = wmin.clone() ##must clone, otherwise inplace backward will occur
- if torch.any(tmp):
- wmin_new[tmp] = -wmax_new[tmp]
-
- tmp = (wmin_new == 0) & (wmax_new == 0)
- wmin_new[tmp] = -1
- wmax_new[tmp] = +1
- scale = ((wmax_new - wmin_new) / maxq).to(scale_dtype)
-
- scale = scale.unsqueeze(dim=-1)
- zp = torch.full_like(scale, (maxq + 1) / 2)
-
- int_w = round_ste(weight / scale + v)
- q = torch.clamp(int_w + zp, 0, maxq)
- return scale * (q - zp), scale, zp
-
-
-def quant_weight_actor(weight, num_bits, sym, v, min_scale, max_scale, scale_dtype=torch.float16):
- """Quantizes and dequantizes weight symmetrically or asymmetrically .
-
- Args:
- weight: Tensor containing the weight to be quantized
- num_bits: Number of bits for quantization (e.g., 2, 3, 4, 8)
- sym: Sym or asym
- v: Rounding value perturbation
- min_scale: Minimum scale coefficient for weight
- max_scale: Maximum scale coefficient for weight
-
- Returns:
- Quantized and dequantized weight, scale, zero-point
- """
- assert num_bits > 0, "num_bits should be larger than 0"
- if sym:
- return quant_weight_sym(weight, num_bits, v, min_scale, max_scale, scale_dtype)
- else:
- return quant_weight_asym(weight, num_bits, v, min_scale, max_scale, scale_dtype)
-
-
-def quant_weight(
- weight, num_bits=4, group_size=-1, sym=False, v=0, min_scale=0, max_scale=0, scale_dtype=torch.float16
-):
- """Quantizes and dequantizes weight, handing the group size issue .
-
- Args:
- weight: Tensor containing the weight to be quantized
- num_bits: Number of bits for quantization (e.g., 2, 3, 4, 8)
- group_size: The number of elements shares scale and zero point
- sym: Sym or asym
- v: Rounding value perturbation
- min_scale: Minimum scale coefficient for weight
- max_scale: Maximum scale coefficient for weight
-
- Returns:
- Quantized and dequantized weight, scale, zero-point
- """
- if group_size == -1 or weight.shape[1] < group_size:
- return quant_weight_actor(
- weight, num_bits, sym=sym, v=v, min_scale=min_scale, max_scale=max_scale, scale_dtype=scale_dtype
- )
- orig_shape = weight.shape
- if weight.shape[1] % group_size == 0:
- weight = weight.reshape(-1, group_size)
- if isinstance(v, torch.Tensor):
- v = v.reshape(-1, group_size)
-
- weight, scale, zp = quant_weight_actor(
- weight, num_bits, sym=sym, v=v, min_scale=min_scale, max_scale=max_scale, scale_dtype=scale_dtype
- )
- weight = weight.reshape(orig_shape)
- scale = scale.reshape(weight.shape[0], -1) ##only for linear, conv1d
- if zp is not None:
- zp = zp.reshape(weight.shape[0], -1)
- return weight, scale, zp
-
- else:
- pad_len = (weight.shape[1] + group_size - 1) // group_size * group_size - weight.shape[1]
- weight_new = torch.nn.functional.pad(weight, (0, pad_len))
- v = torch.nn.functional.pad(v, (0, pad_len))
- weight_new = weight_new.reshape(-1, group_size)
- if isinstance(v, torch.Tensor):
- v = v.reshape(-1, group_size)
- weight_new, scale, zp = quant_weight_actor(
- weight_new, num_bits, sym=sym, v=v, min_scale=min_scale, max_scale=max_scale, scale_dtype=scale_dtype
- )
- weight_new = weight_new.reshape(orig_shape[0], -1)
-
- weight_new = weight_new[:, :-pad_len]
- scale = scale.reshape(weight_new.shape[0], -1) ##only for linear, conv1d
- if zp is not None:
- zp = zp.reshape(weight_new.shape[0], -1)
- return weight_new, scale, zp
-
-
-def quant_weight_w_scale(weight, scale, zp, group_size=-1, device="cpu"):
- """Quant and dequant tensor with group size.
-
- Args:
- weight: input weight
- scale: scale
- zp: zero point
- group_size (int, optional): how many elements share one scale/zp. Defaults to -1.
-
- Returns:
- output: int weight.
- """
- scale = scale.to(device)
- if zp is not None:
- zp = zp.to(device)
- if group_size == -1:
- return torch.round(weight / scale) if zp is None else torch.round(weight / scale + zp)
- int_weight = torch.zeros(weight.shape).to(device)
- leng = weight.shape[1] // group_size
- tail_flag = False if weight.shape[1] % group_size == 0 else True
- for i in range(leng):
- int_weight_tmp = weight[:, i * group_size : (i + 1) * group_size] / scale[:, i].unsqueeze(1)
- if zp is not None:
- int_weight_tmp += zp[:, i].unsqueeze(1)
- int_weight[:, i * group_size : (i + 1) * group_size] = torch.round(int_weight_tmp)
- if tail_flag:
- int_weight_tmp = weight[:, leng * group_size :] / scale[:, -1].unsqueeze(1)
- if zp is not None:
- int_weight_tmp += zp[:, -1].unsqueeze(1)
- int_weight[:, leng * group_size :] = torch.round(int_weight_tmp)
- return int_weight
-
-
def get_module(module, key):
"""Get module from model by key name.
@@ -421,8 +220,8 @@ def collect_minmax_scale(block):
max_scales = {}
for n, m in block.named_modules():
if hasattr(m, "orig_layer"):
- min_scales[n] = copy.deepcopy(torch.clamp(m.min_scale.data, -1, 0))
- max_scales[n] = copy.deepcopy(torch.clamp(m.max_scale.data, -1, 0))
+ min_scales[n] = copy.deepcopy(torch.clamp(m.min_scale.data, 0, 1.0))
+ max_scales[n] = copy.deepcopy(torch.clamp(m.max_scale.data, 0, 1.0))
return min_scales, max_scales
@@ -592,11 +391,11 @@ class CpuInfo(object):
cmd = "sysctl -n machdep.cpu.core_count"
with subprocess.Popen(
- args=cmd,
- shell=True,
- stdout=subprocess.PIPE,
- stderr=subprocess.STDOUT,
- universal_newlines=False,
+ args=cmd,
+ shell=True,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT,
+ universal_newlines=False,
) as proc:
proc.wait()
if proc.stdout:
diff --git a/examples/language-modeling/eval_042/evaluation.py b/examples/language-modeling/eval_042/evaluation.py
index 193ce9fca..ea19c8fae 100644
--- a/examples/language-modeling/eval_042/evaluation.py
+++ b/examples/language-modeling/eval_042/evaluation.py
@@ -105,6 +105,7 @@ def simple_evaluate(
:return
Dictionary of results
"""
+ from auto_round.auto_quantizer import AutoHfQuantizer
eval_logger.setLevel(getattr(logging, f"{verbosity}"))
start_date = time.time()
@@ -597,7 +598,7 @@ if __name__ == "__main__":
model_args = f"pretrained={args.model_name}"
if config.torch_dtype == torch.float32:
model_args += ",dtype=float16"
- model_args += ",dtype=float16"
+ # model_args += ",dtype=float16"
result = simple_evaluate(model="hf",
model_args=model_args,
tasks=test_tasks,
diff --git a/examples/language-modeling/main.py b/examples/language-modeling/main.py
index 4cfb98a03..841c9d2f0 100644
--- a/examples/language-modeling/main.py
+++ b/examples/language-modeling/main.py
@@ -152,8 +152,8 @@ if __name__ == '__main__':
return "Library not found"
- res = get_library_version("lm-eval")
- if res == "0.3.0":
+ lm_eval_version = get_library_version("lm-eval")
+ if lm_eval_version == "0.3.0":
use_eval_legacy = True
if isinstance(tasks, str):
@@ -178,7 +178,7 @@ if __name__ == '__main__':
if use_eval_legacy:
print("Using the legacy lm_eval(0.3.0)")
else:
- print(f"Using the latest {res}")
+ print(f"Using the latest {lm_eval_version}")
model_name = args.model_name
if model_name[-1] == "/":
@@ -340,10 +340,27 @@ if __name__ == '__main__':
model.save_pretrained(output_dir)
tokenizer.save_pretrained(output_dir)
- if not args.disable_eval and "fake" in deployment_device: ##support autogptq real eval later
+ if not args.disable_eval and "fake" in deployment_device and lm_eval_version != "0.4.2":
excel_name = f"{output_dir}_result.xlsx"
output_dir += "/"
print(excel_name, flush=True)
eval_model(model_path=output_dir, tasks=tasks, dtype=dtype, limit=None,
eval_bs=args.eval_bs, use_accelerate=not args.disable_low_gpu_mem_usage,
device=torch_device, excel_file=excel_name)
+
+ if not args.disable_eval and lm_eval_version == "0.4.2":
+ if "round" in deployment_device:
+ from auto_round.auto_quantizer import AutoHfQuantizer
+ from eval_042.evaluation import simple_evaluate
+
+ if 'gpu' in deployment_device or "auto_round" in gpu_format or "auto-round" in gpu_format:
+ model_args = f"pretrained={export_dir}-gpu"
+ else:
+ model_args = f"pretrained={output_dir}"
+
+ res = simple_evaluate(model="hf", model_args=model_args,
+ tasks=tasks,
+ batch_size=args.eval_bs)
+ from lm_eval.utils import make_table
+
+ print(make_table(res))
diff --git a/examples/language-modeling/requirements.txt b/examples/language-modeling/requirements.txt
index 9b0df5e0c..292166e4a 100644
--- a/examples/language-modeling/requirements.txt
+++ b/examples/language-modeling/requirements.txt
@@ -1,6 +1,8 @@
transformers
torch
-git+https://github.com/EleutherAI/lm-evaluation-harness.git@96d185fa6232a5ab685ba7c43e45d1dbb3bb906d
+lm-eval==0.4.2
+##for lm-eval 0.4.1 we usually used
+##git+https://github.com/EleutherAI/lm-evaluation-harness.git@96d185fa6232a5ab685ba7c43e45d1dbb3bb906d
# For the paper results use the old lm_eval (0.3.0)
# git+https://github.com/EleutherAI/lm-evaluation-harness.git@008fc2a23245c40384f2312718433eeb1e0f87a9
tiktoken
diff --git a/setup.py b/setup.py
index 67f58a278..c6b5c1e4d 100644
--- a/setup.py
+++ b/setup.py
@@ -72,7 +72,13 @@ if BUILD_CUDA_EXT:
print(
f"Building PyTorch CUDA extension requires PyTorch being installed, please install PyTorch first: {e}.\n NOTE: This issue may be raised due to pip build isolation system (ignoring local packages). Please use `--no-build-isolation` when installing with pip, and refer to https://github.com/AutoGPTQ/AutoGPTQ/pull/620 for more details.")
sys.exit(1)
+ if not torch.cuda.is_available():
+ print(
+ f"set BUILD_CUDA_EXT to False as no cuda device is available")
+ BUILD_CUDA_EXT = False
+
+if BUILD_CUDA_EXT:
CUDA_VERSION = None
ROCM_VERSION = os.environ.get('ROCM_VERSION', None)
if ROCM_VERSION and not torch.version.hip: