PTQ-Level Efficiency, QAT-Level Accuracy | 训练后量化的效率,量化感知训练的精度
Optimize pack zeros for int sym (#743)
Weiwei8888dda75ae3
diff --git a/auto_round/autoround.py b/auto_round/autoround.pyindex 319be6d70..2c30b704f 100644--- a/auto_round/autoround.py+++ b/auto_round/autoround.py@@ -848,8 +848,10 @@ class AutoRound(object):if isinstance(value, dict):for k, v in value.items():setattr(module, k if k == "scale" else f"w_{k}", v.cpu())- else:+ elif isinstance(value, torch.Tensor):setattr(module, param_name, value.cpu())+ else:+ setattr(module, param_name, value)# Update configself.layer_config.setdefault(name, {}).update(config)diff --git a/auto_round/data_type/int.py b/auto_round/data_type/int.pyindex 3a50b870f..5b151fdfe 100644--- a/auto_round/data_type/int.py+++ b/auto_round/data_type/int.py@@ -64,14 +64,12 @@ def quant_tensor_sym(max_v = (2 * (wmax_abs < wmin_abs).int() - 1) * torch.max(wmax_abs, wmin_abs)scale = (max_v / maxq).to(scale_dtype)scale = torch.where(scale < 0, torch.clamp(scale, max=-q_scale_thresh), torch.clamp(scale, min=q_scale_thresh))- zp = torch.full_like(scale, maxq) # pylint: disable=E1130scale = scale.unsqueeze(dim=-1)- zp = zp.unsqueeze(dim=-1)int_w = round_ste(tensor / scale + v)- q = torch.clamp(int_w + zp, 0, 2**bits - 1)- qdq_result = (scale * (q - zp)).to(tensor.dtype)+ q = torch.clamp(int_w, -maxq, maxq - 1)+ qdq_result = (scale * q).to(tensor.dtype)qdq_result = revert_tensor_by_pad(qdq_result, orig_shape=orig_shape, pad_len=pad_len)- return qdq_result, scale, zp+ return qdq_result, scale, maxq@register_dtype("int_asym")diff --git a/auto_round/export/export_to_autogptq/export.py b/auto_round/export/export_to_autogptq/export.pyindex cd49637a8..b4e210408 100644--- a/auto_round/export/export_to_autogptq/export.py+++ b/auto_round/export/export_to_autogptq/export.py@@ -109,11 +109,12 @@ def pack_layer(name, model, backend):# so far can only pack layer on CPUqlayer.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 = int(zero.flatten()[0])+ if sym and isinstance(zero, torch.Tensor):+ layer, scale, zero = layer.to("cpu"), scale.to("cpu"), zero.to("cpu")+ if isinstance(new_layer, auto_round.export.export_to_autogptq.qlinear_triton.QuantLinear):+ zero = int(zero.flatten()[0])else:- layer, scale, zero = layer.to("cpu"), scale.to("cpu"), zero.to("cpu").to(torch.float32)+ layer, scale, zero = layer.to("cpu"), scale.to("cpu"), zerosig = inspect.signature(qlayer.pack)param_count = len(sig.parameters)if param_count == 2:diff --git a/auto_round/export/export_to_autoround/export.py b/auto_round/export/export_to_autoround/export.pyindex 22ffe967d..1640528b6 100644--- a/auto_round/export/export_to_autoround/export.py+++ b/auto_round/export/export_to_autoround/export.py@@ -200,7 +200,11 @@ def pack_layer(layer_name, model, backend):qlayer = new_layerimport auto_round_extension.torch.qlinear_torch- if sym and isinstance(QuantLinear, (auto_round_extension.torch.qlinear_torch.QuantLinear)):+ if (+ sym+ and isinstance(zp, torch.Tensor)+ and isinstance(QuantLinear, (auto_round_extension.torch.qlinear_torch.QuantLinear))+ ):zp = int(zp.flatten()[0])qlayer.to("cpu")@@ -213,11 +217,11 @@ def pack_layer(layer_name, model, backend):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 sym:- zp = int(zp.flatten()[0])+ scale = scale.to(torch.float32).t().contiguous()+ if isinstance(zp, torch.Tensor):+ zp = zp.to(torch.float32).t().contiguous()+ if sym:+ zp = int(zp.flatten()[0])if bits != 4:logger.error("AutoAWQ format only supports 4-bits quantization.")diff --git a/auto_round/export/export_to_autoround/export_to_fp8_woq.py b/auto_round/export/export_to_autoround/export_to_fp8_woq.pyindex b543c4390..cca0626f8 100644--- a/auto_round/export/export_to_autoround/export_to_fp8_woq.py+++ b/auto_round/export/export_to_autoround/export_to_fp8_woq.py@@ -110,7 +110,11 @@ def pack_layer(layer_name, model, data_type, packing_device=None):torch_dtype = torch.float8_e5m2info = torch.finfo(torch_dtype)if zp is not None:- q_weight = weight.to(packing_device) / scale.to(packing_device) + zp.to(packing_device)+ q_weight = (+ weight.to(packing_device) / scale.to(packing_device) + zp.to(packing_device)+ if isinstance(zp, torch.Tensor)+ else zp+ )else:q_weight = weight.to(packing_device) / scale.to(packing_device)q_weight = torch.clamp(q_weight, info.min, info.max)diff --git a/auto_round/export/export_to_awq/export.py b/auto_round/export/export_to_awq/export.pyindex 760a7205e..9d50a2a4e 100644--- a/auto_round/export/export_to_awq/export.py+++ b/auto_round/export/export_to_awq/export.py@@ -61,9 +61,10 @@ def pack_layer(name, model, backend):linear_layer = get_module(model, name)scale, zp = linear_layer.scale, linear_layer.zpscale = scale.t().contiguous()- zp = zp.t().contiguous().to(torch.float32)- if sym:- zp = int(zp.flatten()[0])+ if isinstance(zp, torch.Tensor):+ zp = zp.t().contiguous().to(torch.float32)+ if sym:+ zp = int(zp.flatten()[0])q_linear = WQLinear_GEMM.from_linear(linear=linear_layer,w_bit=bits,diff --git a/auto_round/export/export_to_gguf/packing.py b/auto_round/export/export_to_gguf/packing.pyindex a867ffae9..f831c6939 100644--- a/auto_round/export/export_to_gguf/packing.py+++ b/auto_round/export/export_to_gguf/packing.py@@ -45,7 +45,7 @@ def ggml_quant(data = data.to(torch.float32).to(device)scale = scale.to(device) if scale is not None else scale- zp = zp.to(device) if zp is not None else zp+ zp = zp.to(device) if zp is not None and isinstance(zp, torch.Tensor) else zpwmin = wmin.to(device) if wmin is not None else wmind_scale = d_scale.to(device) if d_scale is not None else d_scaled_wmin = d_wmin.to(device) if d_wmin is not None else d_wmin@@ -62,7 +62,7 @@ def ggml_quant(device = "cpu"blocks = blocks.to(device)scale = scale.to(device) if scale is not None else scale- zp = zp.to(device) if zp is not None else zp+ zp = zp.to(device) if zp is not None and isinstance(zp, torch.Tensor) else zpwmin = wmin.to(device) if wmin is not None else wmind_scale = d_scale.to(device) if d_scale is not None else d_scaled_wmin = d_wmin.to(device) if d_wmin is not None else d_wmindiff --git a/auto_round/export/export_to_itrex/export.py b/auto_round/export/export_to_itrex/export.pyindex 731c93d2f..ef64af77b 100644--- a/auto_round/export/export_to_itrex/export.py+++ b/auto_round/export/export_to_itrex/export.py@@ -40,7 +40,7 @@ def quant_weight_w_scale(weight, scale, zp, group_size=-1, device="cpu"):output: int weight."""scale = scale.to(device)- if zp is not None:+ if zp is not None and isinstance(zp, torch.Tensor):zp = zp.to(device)if group_size == -1:return torch.round(weight / scale) if zp is None else torch.round(weight / scale + zp)@@ -220,10 +220,10 @@ def pack_model(else:if not inplace:scale = scale.clone()- zp = zp.clone()+ zp = zp.clone() if isinstance(zp, torch.Tensor) else zpelse:scale = scale.to(dtype=convert_dtype)- zp = zp.to(dtype=torch.int32)+ zp = zp.to(dtype=torch.int32) if isinstance(zp, torch.Tensor) else zpif isinstance(m, transformers.pytorch_utils.Conv1D):fp_weight = fp_weight.t_().contiguous()int_weight = quant_weight_w_scale(fp_weight, scale, zp, group_size, fp_weight.device)diff --git a/auto_round/export/export_to_itrex/model_wrapper.py b/auto_round/export/export_to_itrex/model_wrapper.pyindex 202770df0..0d736b0b1 100644--- a/auto_round/export/export_to_itrex/model_wrapper.py+++ b/auto_round/export/export_to_itrex/model_wrapper.py@@ -248,7 +248,7 @@ class WeightOnlyLinear(torch.nn.Module):self.qweight = self.qweight.t_().contiguous()if zp is not None:- zp = zp.to(self.device)+ zp = zp.to(self.device) if isinstance(zp, torch.Tensor) else zpif self.use_optimum_format:zp -= 1if self.use_optimum_format or self.compression_dim == 0:diff --git a/auto_round/wrapper.py b/auto_round/wrapper.pyindex 591e5c567..c3dfc0765 100644--- a/auto_round/wrapper.py+++ b/auto_round/wrapper.py@@ -294,11 +294,14 @@ class WrapperLinear(torch.nn.Module):if zp is not None:if isinstance(zp, dict):_set_dict_attr(zp, "zp")- elif zp.numel() > 1:- zp = zp.reshape(shape[0], -1)- self.orig_layer.zp = zp.to("cpu")+ elif isinstance(zp, torch.Tensor):+ if zp.numel() > 1:+ zp = zp.reshape(shape[0], -1)+ self.orig_layer.zp = zp.to("cpu")+ else:+ self.orig_layer.zp = zp.view(-1).to("cpu")else:- self.orig_layer.zp = zp.view(-1).to("cpu")+ self.orig_layer.zp = zpelse:self.orig_layer.zp = Nonediff --git a/auto_round_extension/torch/qlinear_torch.py b/auto_round_extension/torch/qlinear_torch.pyindex c45e183df..1a1e0c8aa 100644--- a/auto_round_extension/torch/qlinear_torch.py+++ b/auto_round_extension/torch/qlinear_torch.py@@ -200,13 +200,34 @@ class QuantLinear(nn.Module):self.qzeros = qzeros.cpu()else:- shape = scales_t.shape- value = 0- for j in range(0, (32 // self.bits)):- value |= zeros << (self.bits * j)- qzeros = np.ones((shape[0], shape[1] // 32 * self.bits), dtype=np.uint32) * value- qzeros = qzeros.astype(np.int32)- self.qzeros = torch.from_numpy(qzeros)+ if self.bits in [2, 4, 8]:+ shape = scales_t.shape+ value = 0+ for j in range(0, (32 // self.bits)):+ value |= zeros << (self.bits * j)+ qzeros = np.ones((shape[0], shape[1] // 32 * self.bits), dtype=np.uint32) * value+ qzeros = qzeros.astype(np.int32)+ self.qzeros = torch.from_numpy(qzeros)+ else: ## bits == 3+ shape = scales_t.shape[0], scales_t.shape[1] // 32 * self.bits+ qzeros = torch.zeros(shape, dtype=torch.int32)+ zero_val = zeros+ total_cols = shape[1]+ # Precompute shifts for 3-bit packing+ shifts0 = torch.arange(0, 10, dtype=torch.int32) * self.bits+ shifts1 = shifts0 + 1+ shifts2 = shifts0 + 2+ # Compute packed pattern parts+ part0 = (zero_val << shifts0).sum().to(torch.int32) | (zero_val << 30)+ part1 = (zero_val << shifts1).sum().to(torch.int32) | (zero_val << 31) | ((zero_val >> 2) & 1)+ part2 = (zero_val << shifts2).sum().to(torch.int32) | ((zero_val >> 1) & 0x3)+ pattern = torch.tensor([part0, part1, part2], dtype=torch.int32)+ # Tile pattern across all columns+ repeats = (total_cols + 2) // 3+ full_row = pattern.repeat(repeats)[:total_cols]+ # Broadcast across rows+ qzeros[:] = full_row.unsqueeze(0)+ self.qzeros = qzeros.cpu()def forward(self, x):out_shape = x.shape[:-1] + (self.outfeatures,)diff --git a/auto_round_extension/torch/qlinear_torch_zp.py b/auto_round_extension/torch/qlinear_torch_zp.pyindex 2958d249c..74485f93a 100644--- a/auto_round_extension/torch/qlinear_torch_zp.py+++ b/auto_round_extension/torch/qlinear_torch_zp.py@@ -72,7 +72,7 @@ class QuantLinear(nn.Module):# is performed by unpacking the weights and using torch.matmulif self.bits in [2, 4, 8]:self.wf = torch.tensor(list(range(0, 32, self.bits)), dtype=torch.int32).unsqueeze(0)- elif self.bits == 3:+ else: ## bits == 3self.wf = torch.tensor([[0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 0],@@ -125,7 +125,7 @@ class QuantLinear(nn.Module):intweight = intweight.t().contiguous().to(torch.int32)self.qweight = intweight.to("cpu")- elif self.bits == 3:+ else: ## bits == 3intweight = intweight.t().contiguous()intweight = intweight.cpu().numpy().astype(np.uint32)i = 0@@ -159,46 +159,77 @@ class QuantLinear(nn.Module):self.qweight = qweight.cpu()- zeros = zeros.t().contiguous()- zeros -= 1- zeros = zeros.numpy().astype(np.uint32)- qzeros = torch.zeros((zeros.shape[0], zeros.shape[1] // 32 * self.bits), dtype=torch.int32)- i = 0- col = 0- while col < qzeros.shape[1]:+ if isinstance(zeros, torch.Tensor):+ zeros = zeros.t().contiguous()+ zeros -= 1+ zeros = zeros.numpy().astype(np.uint32)+ qzeros = torch.zeros((zeros.shape[0], zeros.shape[1] // 32 * self.bits), dtype=torch.int32)+ i = 0+ col = 0+ while col < qzeros.shape[1]:+ if self.bits in [2, 4, 8]:+ packed_zeros = torch.tensor(zeros[:, i : i + (32 // self.bits)]).to(dtype=torch.int32)+ shifts = torch.arange(0, (32 // self.bits)) * self.bits+ shifted = packed_zeros << shifts+ qzeros[:, col] |= shifted.sum(dim=-1)+ i += 32 // self.bits+ col += 1+ else: ## bits == 3+ packed_zeros = torch.tensor(zeros[:, i : i + 10]).to(dtype=torch.int32)+ shifts = torch.arange(0, 10) * self.bits+ shifted = packed_zeros << shifts+ qzeros[:, col] = shifted.sum(dim=-1)+ i += 10+ qzeros[:, col] |= zeros[:, i] << 30+ col += 1+ qzeros[:, col] |= (zeros[:, i] >> 2) & 1+ i += 1+ packed_zeros = torch.tensor(zeros[:, i : i + 10]).to(dtype=torch.int32)+ shifts = torch.arange(0, 10) * self.bits + 1+ shifted = packed_zeros << shifts+ qzeros[:, col] |= shifted.sum(dim=-1)+ i += 10+ qzeros[:, col] |= zeros[:, i] << 31+ col += 1+ qzeros[:, col] |= (zeros[:, i] >> 1) & 0x3+ i += 1+ packed_zeros = torch.tensor(zeros[:, i : i + 10]).to(dtype=torch.int32)+ shifts = torch.arange(0, 10) * self.bits + 2+ shifted = packed_zeros << shifts+ qzeros[:, col] |= shifted.sum(dim=-1)+ i += 10+ col += 1+ self.qzeros = qzeros.cpu()+ else:+ zeros -= 1if self.bits in [2, 4, 8]:- packed_zeros = torch.tensor(zeros[:, i : i + (32 // self.bits)]).to(dtype=torch.int32)- shifts = torch.arange(0, (32 // self.bits)) * self.bits- shifted = packed_zeros << shifts- qzeros[:, col] |= shifted.sum(dim=-1)- i += 32 // self.bits- col += 1- elif self.bits == 3:- packed_zeros = torch.tensor(zeros[:, i : i + 10]).to(dtype=torch.int32)- shifts = torch.arange(0, 10) * self.bits- shifted = packed_zeros << shifts- qzeros[:, col] = shifted.sum(dim=-1)- i += 10- qzeros[:, col] |= zeros[:, i] << 30- col += 1- qzeros[:, col] |= (zeros[:, i] >> 2) & 1- i += 1- packed_zeros = torch.tensor(zeros[:, i : i + 10]).to(dtype=torch.int32)- shifts = torch.arange(0, 10) * self.bits + 1- shifted = packed_zeros << shifts- qzeros[:, col] |= shifted.sum(dim=-1)- i += 10- qzeros[:, col] |= zeros[:, i] << 31- col += 1- qzeros[:, col] |= (zeros[:, i] >> 1) & 0x3- i += 1- packed_zeros = torch.tensor(zeros[:, i : i + 10]).to(dtype=torch.int32)- shifts = torch.arange(0, 10) * self.bits + 2- shifted = packed_zeros << shifts- qzeros[:, col] |= shifted.sum(dim=-1)- i += 10- col += 1- self.qzeros = qzeros.cpu()+ shape = scales_t.shape+ value = 0+ for j in range(0, (32 // self.bits)):+ value |= zeros << (self.bits * j)+ qzeros = np.ones((shape[0], shape[1] // 32 * self.bits), dtype=np.uint32) * value+ qzeros = qzeros.astype(np.int32)+ self.qzeros = torch.from_numpy(qzeros)+ else: ## bits == 3+ shape = scales_t.shape[0], scales_t.shape[1] // 32 * self.bits+ qzeros = torch.zeros(shape, dtype=torch.int32)+ zero_val = zeros+ total_cols = shape[1]+ # Precompute shifts for 3-bit packing+ shifts0 = torch.arange(0, 10, dtype=torch.int32) * self.bits+ shifts1 = shifts0 + 1+ shifts2 = shifts0 + 2+ # Compute packed pattern parts+ part0 = (zero_val << shifts0).sum().to(torch.int32) | (zero_val << 30)+ part1 = (zero_val << shifts1).sum().to(torch.int32) | (zero_val << 31) | ((zero_val >> 2) & 1)+ part2 = (zero_val << shifts2).sum().to(torch.int32) | ((zero_val >> 1) & 0x3)+ pattern = torch.tensor([part0, part1, part2], dtype=torch.int32)+ # Tile pattern across all columns+ repeats = (total_cols + 2) // 3+ full_row = pattern.repeat(repeats)[:total_cols]+ # Broadcast across rows+ qzeros[:] = full_row.unsqueeze(0)+ self.qzeros = qzeros.cpu()def forward(self, x):out_shape = x.shape[:-1] + (self.outfeatures,)diff --git a/test/test_cpu/test_woq_linear.py b/test/test_cpu/test_woq_linear.pyindex f12400777..fcdfeb27f 100644--- a/test/test_cpu/test_woq_linear.py+++ b/test/test_cpu/test_woq_linear.py@@ -37,7 +37,8 @@ class TestWeightOnlyLinear:qdq, scale, zp = quant_tensor_sym(weight, -1)int_weight = qdq.div(scale).add(zp).clamp(0, 2 ** (bits) - 1).to(torch.int32).reshape(origin_shape)scale = scale.reshape(origin_shape[0], -1)- zp = zp.reshape(origin_shape[0], -1).to(torch.int32).clamp(0, 2 ** (bits) - 1)+ if isinstance(zp, torch.Tensor):+ zp = zp.reshape(origin_shape[0], -1).to(torch.int32).clamp(0, 2 ** (bits) - 1)module_with_legacy_pack = WeightOnlyLinear(in_features=m.in_features,out_features=m.out_features,@@ -50,7 +51,9 @@ class TestWeightOnlyLinear:compression_dtype=compression_dtype,use_legacy_pack=True,)- module_with_legacy_pack.pack(int_weight.clone(), scale.clone(), zp.clone(), m.bias)+ module_with_legacy_pack.pack(+ int_weight.clone(), scale.clone(), zp.clone() if isinstance(zp, torch.Tensor) else zp, m.bias+ )module_with_new_pack = WeightOnlyLinear(in_features=m.in_features,out_features=m.out_features,@@ -63,7 +66,9 @@ class TestWeightOnlyLinear:compression_dtype=compression_dtype,use_legacy_pack=False,)- module_with_new_pack.pack(int_weight.clone(), scale.clone(), zp.clone(), m.bias)+ module_with_new_pack.pack(+ int_weight.clone(), scale.clone(), zp.clone() if isinstance(zp, torch.Tensor) else zp, m.bias+ )assert torch.equal(module_with_new_pack.qweight, module_with_legacy_pack.qweight)diff --git a/test/test_cuda/test_2_3bits.py b/test/test_cuda/test_2_3bits.pyindex 51982854a..8bb23f6aa 100644--- a/test/test_cuda/test_2_3bits.py+++ b/test/test_cuda/test_2_3bits.py@@ -10,8 +10,8 @@ import transformersfrom lm_eval.utils import make_table # pylint: disable=E0401from transformers import AutoModelForCausalLM, AutoTokenizer-from auto_round import AutoRound-from auto_round.eval.evaluation import simple_evaluate+from auto_round import AutoRound, AutoRoundConfig+from auto_round.eval.evaluation import simple_evaluate, simple_evaluate_user_modelfrom auto_round.testing_utils import require_autogptq, require_greater_than_050, require_greater_than_051@@ -36,26 +36,51 @@ class TestAutoRound(unittest.TestCase):shutil.rmtree("./saved", ignore_errors=True)shutil.rmtree("runs", ignore_errors=True)+ def model_infer(self, model, tokenizer):+ prompts = [+ "Hello,my name is",+ # "The president of the United States is",+ # "The capital of France is",+ # "The future of AI is",+ ]++ inputs = tokenizer(prompts, return_tensors="pt", padding=False, truncation=True)++ outputs = model.generate(+ input_ids=inputs["input_ids"].to(model.device),+ attention_mask=inputs["attention_mask"].to(model.device),+ do_sample=False, ## change this to follow official usage+ max_new_tokens=5,+ )+ generated_ids = [output_ids[len(input_ids) :] for input_ids, output_ids in zip(inputs["input_ids"], outputs)]++ decoded_outputs = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)++ for i, prompt in enumerate(prompts):+ print(f"Prompt: {prompt}")+ print(f"Generated: {decoded_outputs[i]}")+ print("-" * 50)+ return decoded_outputs[0]+@require_greater_than_051def test_3bits_autoround(self):model_name = "/models/opt-125m"model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.float16, device_map="auto")tokenizer = AutoTokenizer.from_pretrained(model_name)autoround = AutoRound(model, tokenizer, bits=3)- autoround.quantize_and_save(self.save_dir, format="auto_round", inplace=False)- model_args = f"pretrained={self.save_dir}"- res = simple_evaluate(- model="hf",- model_args=model_args,- # tasks="arc_easy",- tasks=self.tasks,- batch_size="auto",+ quantized_model_path = self.save_dir+ autoround.quantize_and_save(output_dir=quantized_model_path, format="auto_round") ##will convert to gptq model++ quantization_config = AutoRoundConfig(backend="torch")+ model = AutoModelForCausalLM.from_pretrained(+ quantized_model_path, torch_dtype=torch.float16, device_map="auto", quantization_config=quantization_config)- ## 0.3130- accuracy = res["results"]["lambada_openai"]["acc,none"]- assert accuracy > 0.3- shutil.rmtree("./saved", ignore_errors=True)+ tokenizer = AutoTokenizer.from_pretrained(self.save_dir)+ self.model_infer(model, tokenizer)+ result = simple_evaluate_user_model(model, tokenizer, batch_size=16, tasks="lambada_openai")+ print(result["results"]["lambada_openai"]["acc,none"])+ self.assertGreater(result["results"]["lambada_openai"]["acc,none"], 0.3) ## 0.3130@require_greater_than_051def test_3bits_asym_autoround(self):