Skip to content

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

20x for awq and 4x for gptq packing speedup (#459)

Wenhua Chengc803ce9bbaaa
diff --git a/auto_round/export/export_to_autogptq/export.py b/auto_round/export/export_to_autogptq/export.py
index 309595650..7fa62cf18 100644
--- a/auto_round/export/export_to_autogptq/export.py
+++ b/auto_round/export/export_to_autogptq/export.py
@@ -123,9 +123,7 @@ def save_quantized_as_autogptq(output_dir, inplace=True, backend="auto_gptq:exll
model = kwargs["model"]
supported_types = kwargs["supported_types"]
safe_serialization = True if 'safe_serialization' not in kwargs.keys() else kwargs["safe_serialization"]
- to_quant_block_names = kwargs["to_quant_block_names"]
quant_block_list = kwargs.get("quant_block_list", get_block_names(model))
- logger.info("Saving quantized model to autogptq format, this may take a while...")
tokenizer = kwargs.get("tokenizer", None)
processor = kwargs.get("processor", None)
if tokenizer is not None:
diff --git a/auto_round/export/export_to_autogptq/qlinear_triton.py b/auto_round/export/export_to_autogptq/qlinear_triton.py
index 8a10d06a5..c95129ed4 100644
--- a/auto_round/export/export_to_autogptq/qlinear_triton.py
+++ b/auto_round/export/export_to_autogptq/qlinear_triton.py
@@ -99,112 +99,39 @@ class QuantLinear(nn.Module, TritonModuleMixin):
def post_init(self):
pass
- def pack_cpu(self, linear, scales, zeros, g_idx=None):
- W = linear.weight.data.clone()
- if isinstance(linear, nn.Conv2d):
- W = W.flatten(1)
- if isinstance(linear, transformers.pytorch_utils.Conv1D):
- W = W.t()
-
+ def pack(self, linear, scales, zeros, g_idx=None):
+ scales_t = scales.t().contiguous()
self.g_idx = g_idx.clone() if g_idx is not None else self.g_idx
-
- scales = scales.t().contiguous()
- if isinstance(zeros, torch.Tensor):
- zeros = zeros.t().contiguous()
- scale_zeros = zeros * scales
- else:
- scale_zeros = scales * zeros
- self.scales = scales.clone().half()
if linear.bias is not None:
self.bias = linear.bias.clone().half()
-
- intweight = []
- for idx in range(self.infeatures):
- intweight.append(
- torch.round((W[:, idx] + scale_zeros[self.g_idx[idx]]) / self.scales[self.g_idx[idx]]).to(torch.int)[
- :, None
- ]
- )
- intweight = torch.cat(intweight, dim=1)
- intweight = intweight.t().contiguous()
- intweight = intweight.numpy().astype(np.uint32)
-
- i = 0
- row = 0
- qweight = np.zeros((intweight.shape[0] // 32 * self.bits, intweight.shape[1]), dtype=np.uint32)
- while row < qweight.shape[0]:
- for j in range(i, i + (32 // self.bits)):
- qweight[row] |= intweight[j] << (self.bits * (j - i))
- i += 32 // self.bits
- row += 1
-
- qweight = qweight.astype(np.int32)
- self.qweight = torch.from_numpy(qweight)
-
- if isinstance(zeros, torch.Tensor):
- zeros -= 1
- zeros = zeros.numpy().astype(np.uint32)
- qzeros = np.zeros((zeros.shape[0], zeros.shape[1] // 32 * self.bits), dtype=np.uint32)
- i = 0
- col = 0
- while col < qzeros.shape[1]:
- for j in range(i, i + (32 // self.bits)):
- qzeros[:, col] |= zeros[:, j] << (self.bits * (j - i))
- i += 32 // self.bits
- col += 1
-
- qzeros = qzeros.astype(np.int32)
- self.qzeros = torch.from_numpy(qzeros)
- else:
- zeros -= 1
- shape = scales.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)
-
- def pack(self, linear, scales, zeros, g_idx):
+ self.scales = scales_t.clone().half()
+ device = "cpu"
if torch.cuda.is_available():
- return self.pack_cuda(linear, scales, zeros, g_idx)
- else:
- return self.pack_cpu(linear, scales, zeros, g_idx)
+ device = "cuda:0"
- def pack_cuda(self, linear, scales, zeros, g_idx=None):
- W = linear.weight.data.clone()
+ W = linear.weight.data.to(device).clone()
if isinstance(linear, nn.Conv2d):
W = W.flatten(1)
if isinstance(linear, transformers.pytorch_utils.Conv1D):
W = W.t()
- scales_t = scales.t().contiguous()
- self.g_idx = g_idx.clone() if g_idx is not None else self.g_idx
- if linear.bias is not None:
- self.bias = linear.bias.clone().half()
- self.scales = scales_t.clone().half()
- repeat_scales = scales.to("cuda:0").repeat_interleave(self.group_size, 1)
+ repeat_scales = scales.to(device).repeat_interleave(self.group_size, 1)
if isinstance(zeros, torch.Tensor):
- repeat_zeros = zeros.to("cuda:0").repeat_interleave(self.group_size, 1)
+ repeat_zeros = zeros.to(device).repeat_interleave(self.group_size, 1)
else:
repeat_zeros = zeros
- intweight = torch.round(W.to("cuda:0") / repeat_scales + repeat_zeros).to(torch.int).t().contiguous().to("cpu")
- intweight = intweight.numpy().astype(np.uint32)
+ intweight = torch.round(W.to(device) / repeat_scales + repeat_zeros).to(
+ torch.int32)
+
del repeat_scales
+ intweight = intweight.reshape(-1, intweight.shape[1] // 32 * self.bits, 32 // self.bits)
+ order_map = torch.arange(0, 32 // self.bits, device=device) * self.bits
+ intweight = intweight << order_map
+ intweight = torch.sum(intweight, dim=-1)
- i = 0
- row = 0
- qweight = np.zeros((intweight.shape[0] // 32 * self.bits, intweight.shape[1]), dtype=np.uint32)
- # pack_array_with_numba_b4_c32(intweight, qweight)
- while row < qweight.shape[0]:
- for j in range(i, i + (32 // self.bits)):
- qweight[row] |= intweight[j] << (self.bits * (j - i))
- i += 32 // self.bits
- row += 1
-
- qweight = qweight.astype(np.int32)
- self.qweight = torch.from_numpy(qweight)
+ intweight = intweight.t().contiguous().to(torch.int32)
+ self.qweight = intweight.to("cpu")
if isinstance(zeros, torch.Tensor):
zeros = zeros.t().contiguous()
diff --git a/auto_round/export/export_to_awq/utils.py b/auto_round/export/export_to_awq/utils.py
index a8c0c63ae..f0ad7db78 100644
--- a/auto_round/export/export_to_awq/utils.py
+++ b/auto_round/export/export_to_awq/utils.py
@@ -213,75 +213,50 @@ class WQLinear_GEMM(nn.Module):
# need scales and zeros info for real quantization
assert scales is not None and zeros is not None
- scale_zeros = zeros * scales
awq_linear.scales = scales.clone().half()
if linear.bias is not None:
awq_linear.bias = linear.bias.clone().half()
pack_num = 32 // awq_linear.w_bit
-
+ device = "cpu"
if torch.cuda.is_available():
+ device = "cuda:0"
- repeat_scales = scales.to("cuda:0").t().repeat_interleave(group_size, 1)
- if isinstance(zeros, torch.Tensor):
- repeat_zeros = zeros.to("cuda:0").t().repeat_interleave(group_size, 1)
- else:
- repeat_zeros = zeros
- intweight = torch.round(linear.weight.to("cuda:0") / repeat_scales + repeat_zeros).to(
- torch.int).t().contiguous().to("cpu")
- intweight = intweight.to(dtype=torch.int32)
- del repeat_scales
+ repeat_scales = scales.to(device).t().repeat_interleave(group_size, 1)
+ if isinstance(zeros, torch.Tensor):
+ repeat_zeros = zeros.to(device).t().repeat_interleave(group_size, 1)
else:
- intweight = []
- for idx in range(awq_linear.in_features):
- intweight.append(
- torch.round(
- (linear.weight.data[:, idx] + scale_zeros[idx // group_size])
- / awq_linear.scales[idx // group_size]
- ).to(torch.int)[:, None]
- )
- intweight = torch.cat(intweight, dim=1)
- intweight = intweight.t().contiguous()
- intweight = intweight.to(dtype=torch.int32)
-
- qweight = torch.zeros(
- (intweight.shape[0], intweight.shape[1] // 32 * awq_linear.w_bit),
- dtype=torch.int32,
- device=intweight.device,
- )
+ repeat_zeros = zeros
+ intweight = torch.round(linear.weight.to(device) / repeat_scales + repeat_zeros).to(
+ torch.int).t().contiguous()
+ intweight = intweight.to(dtype=torch.int32)
+ del repeat_scales
- for col in range(intweight.shape[1] // pack_num):
- order_map = [0, 2, 4, 6, 1, 3, 5, 7]
- for i in range(pack_num):
- qweight_col = intweight[:, col * pack_num + order_map[i]]
- qweight[:, col] |= qweight_col << (i * awq_linear.w_bit)
- awq_linear.qweight = qweight
+ intweight = intweight.reshape(-1, intweight.shape[1] // pack_num, pack_num)
+
+ new_order_map = torch.tensor([0, 4, 1, 5, 2, 6, 3, 7], device=device) * awq_linear.w_bit
+ intweight = intweight << new_order_map
+ intweight = torch.sum(intweight, dim=-1).to(torch.int32)
+ awq_linear.qweight = intweight.to("cpu")
if isinstance(zeros, torch.Tensor):
- qzeros = torch.zeros(
- (scales.shape[0], scales.shape[1] // 32 * awq_linear.w_bit),
- dtype=torch.int32,
- device=zeros.device,
- )
- zeros = zeros.to(dtype=torch.int32, device="cpu")
+ zeros = zeros.to(dtype=torch.int32, device=device)
+ zeros = zeros.reshape(-1, zeros.shape[1] // pack_num, pack_num)
+ zeros = zeros << new_order_map
+ qzeros = torch.sum(zeros, dim=-1).to(torch.int32)
- for col in range(zeros.shape[1] // pack_num):
- order_map = [0, 2, 4, 6, 1, 3, 5, 7]
- for i in range(pack_num):
- qzero_col = zeros[:, col * pack_num + order_map[i]]
- qzeros[:, col] |= qzero_col << (i * awq_linear.w_bit)
else:
value = 0
for i in range(pack_num):
value |= zeros << (i * awq_linear.w_bit)
qzeros = torch.ones(
- (scales.shape[0], scales.shape[1] // 32 * awq_linear.w_bit),
+ (scales.shape[0], scales.shape[1] // pack_num),
dtype=torch.int32,
- device=qweight.device,
+ device=device,
) * value
- awq_linear.qzeros = qzeros
+ awq_linear.qzeros = qzeros.to("cpu")
return awq_linear