PTQ-Level Efficiency, QAT-Level Accuracy | 训练后量化的效率,量化感知训练的精度
fix lm-head quant issue at disable_quanted_input (#117)
wenhuach21b51cfa98c814
diff --git a/README.md b/README.mdindex 9e67cbbc7..e2f693656 100644--- a/README.md+++ b/README.md@@ -25,6 +25,8 @@ image presents an overview of AutoRound.<div align="left">## What's New+* [2024/05] Check out our updated paper on [arxiv](https://arxiv.org/pdf/2309.05516v4)+* [2024/05] AutoRound supports lm-head quantization, saving 0.7G for LLaMA3-8B at W4G128.* [2024/05] AutoRound performs well in [low_bit_open_llm_leaderboard](https://huggingface.co/spaces/Intel/low_bit_open_llm_leaderboard)## Prerequisites@@ -203,7 +205,7 @@ If you find SignRound useful for your research, please cite our paper:```bash@article{cheng2023optimize,title={Optimize Weight Rounding via Signed Gradient Descent for the Quantization of LLMs},- author={Cheng, Wenhua and Zhang, Weiwei and Shen, Haihao and Cai, Yiyang and He, Xin and Lv, Kaokao},+ author={Cheng, Wenhua and Zhang, Weiwei and Shen, Haihao and Cai, Yiyang and He, Xin and Lv, Kaokao and Liu, Yi},journal={arXiv preprint arXiv:2309.05516},year={2023}}diff --git a/auto_round/autoround.py b/auto_round/autoround.pyindex dcb08bfbb..4da651074 100644--- a/auto_round/autoround.py+++ b/auto_round/autoround.py@@ -503,6 +503,7 @@ class AutoRound(object):"gradient_accumulate_steps","iters","amp",+ "low_gpu_mem_usage",]if isinstance(dataset, str):serialization_keys.append("dataset")@@ -665,7 +666,8 @@ class AutoRound(object):self.quant_layer(layer_name, layer_inputs[layer_name], q_layer_input, device=self.device)for i in range(len(layer_inputs)):layer_input[i] = None- q_layer_input[i] = None+ if q_layer_input is not None:+ q_layer_input[i] = Nonetorch.cuda.empty_cache()def set_layerwise_config(self, weight_config):@@ -1035,14 +1037,13 @@ class AutoRound(object):)else:optimizer = self.optimizer(round_params, lr=self.lr, weight_decay=0)+if self.lr_scheduler is None:lr_schedule = torch.optim.lr_scheduler.LinearLR(optimizer, start_factor=1.0, end_factor=0.0, total_iters=self.iters, verbose=False)else:lr_schedule = copy.deepcopy(self.lr_scheduler)-- train_bs = self.train_bsn_samples = len(inputs)last_best_iter = 0best_loss = torch.finfo(torch.float).max@@ -1050,25 +1051,26 @@ class AutoRound(object):scaler = self.get_scaler() # pylint: disable=assignment-from-noneinit_loss = Nonebest_v, best_min_scale, best_max_scale = torch.tensor(0), torch.tensor(0), torch.tensor(0)- gradient_accumulate_steps = self.gradient_accumulate_stepsgradient_accumulate_steps = self.train_bs ##Force to low gputrain_bs = 1 ##Force to low gpu- pick_samples = train_bs+ pick_samples = train_bs * gradient_accumulate_steps+if self.sampler != "rand":- indices = torch.randperm(n_samples)[:pick_samples]+ whole_indices = torch.randperm(n_samples)[:pick_samples]for i in range(self.iters):total_loss = 0- for _ in range(gradient_accumulate_steps):+ if self.sampler == "rand":+ whole_indices = torch.randperm(n_samples)[:pick_samples]+ for tmp_step in range(gradient_accumulate_steps):org_input = None- if self.sampler == "rand":- indices = torch.randperm(n_samples)[:pick_samples]+ 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)org_input = [inputs[i] for i in indices]org_input = torch.cat(org_input, dim=0).to(device)else:- current_input = [q_inputs[i] for i in indices]+ current_input = [inputs[i] for i in indices]current_input = torch.cat(current_input, dim=0).to(device)org_input = current_inputwith torch.no_grad():@@ -1084,10 +1086,10 @@ class AutoRound(object):output_q.to(torch.float32), current_output.to(torch.float32))total_loss += loss.item() / gradient_accumulate_steps- if i == 0:- init_loss = total_lossself.scale_loss_and_backward(scaler, loss)+ if i == 0:+ init_loss = total_lossif total_loss < best_loss:best_loss = total_loss@@ -1136,9 +1138,8 @@ class AutoRound(object):if q_input is not None:for i in range(len(input_ids)):input_ids[i] = None- torch.cuda.empty_cache()input_ids = q_input-+ torch.cuda.empty_cache()quantized_layer_names, unquantized_layer_names = wrapper_block(block, self.enable_minmax_tuning)round_params = []@@ -1163,10 +1164,10 @@ class AutoRound(object):else:lr_schedule = copy.deepcopy(self.lr_scheduler)- pick_samples = self.train_bs+ pick_samples = self.train_bs * self.gradient_accumulate_stepsn_samples = len(input_ids)if self.sampler != "rand":- indices = torch.randperm(n_samples)[:pick_samples]+ whole_indices = torch.randperm(n_samples)[:pick_samples]last_best_iter = 0best_loss = torch.finfo(torch.float).maxmse_loss = torch.nn.MSELoss().to(device)@@ -1175,9 +1176,10 @@ class AutoRound(object):best_v, best_min_scale, best_max_scale = torch.tensor(0), torch.tensor(0), torch.tensor(0)for i in range(self.iters):total_loss = 0- for _ in range(self.gradient_accumulate_steps):- if self.sampler == "rand":- indices = torch.randperm(n_samples)[:pick_samples]+ 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]current_input_ids, current_input_others = sampling_inputs(input_ids,input_others,@@ -1204,10 +1206,9 @@ class AutoRound(object):)total_loss += loss.item() / self.gradient_accumulate_steps- if i == 0:- init_loss = total_loss-self.scale_loss_and_backward(scaler, loss)+ if i == 0:+ init_loss = total_lossif total_loss < best_loss:best_loss = total_loss@@ -1448,9 +1449,9 @@ class AutoRound(object):Returns:The specified optimizer."""- from auto_round.sign_sgd import SGD+ from auto_round.sign_sgd import SignSGD- return SGD+ return SignSGDdef get_scaler(self):"""Returns scaler, in SignRound, no need to use scaler."""diff --git a/auto_round/export/export_to_autoround/autoround_quantizer.py b/auto_round/export/export_to_autoround/autoround_quantizer.pyindex 9a2651042..9b75b9dd4 100644--- a/auto_round/export/export_to_autoround/autoround_quantizer.py+++ b/auto_round/export/export_to_autoround/autoround_quantizer.py@@ -177,7 +177,7 @@ class AutoHfQuantizer:@dataclassclass AutoRoundConfig(QuantizationConfigMixin):"""This is a wrapper class about all possible attributes and features that you can play with a model that has been- loaded using `optimum` api for gptq quantization relying on auto_gptq backend.+ loaded AutoRound quantization.Args:bits (`int`):@@ -250,10 +250,7 @@ class AutoRoundConfig(QuantizationConfigMixin):class AutoRoundQuantizer(HfQuantizer):- """- Quantizer of the GPTQ method - for GPTQ the quantizer support calibration of the model through- `auto_gptq` package. Quantization is done under the hood for users if they load a non-prequantized model.- """+ """Quantizer of the Autoround method, currently only gptq backend has been supported."""requires_calibration = Falserequired_packages = ["auto_gptq"]diff --git a/auto_round/sign_sgd.py b/auto_round/sign_sgd.pyindex 851378a7b..e4b948107 100644--- a/auto_round/sign_sgd.py+++ b/auto_round/sign_sgd.py@@ -99,7 +99,7 @@ import torchfrom torch import Tensorfrom torch.optim.optimizer import Optimizer-__all__ = ["SGD", "sgd"]+__all__ = ["SignSGD", "sgd"]class _RequiredParameter(object):@@ -125,7 +125,7 @@ def _use_grad_for_differentiable(func):return _use_grad-class SGD(Optimizer):+class SignSGD(Optimizer):r"""Implements stochastic gradient descent (optionally with momentum)... math::@@ -242,7 +242,7 @@ class SGD(Optimizer):)if nesterov and (momentum <= 0 or dampening != 0):raise ValueError("Nesterov momentum requires a momentum and zero dampening")- super(SGD, self).__init__(params, defaults)+ super(SignSGD, self).__init__(params, defaults)def __setstate__(self, state):super().__setstate__(state)