|
| 1 | +# ----------------------------------------------------------------------------- |
| 2 | +# |
| 3 | +# Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. |
| 4 | +# SPDX-License-Identifier: BSD-3-Clause |
| 5 | +# |
| 6 | +# ----------------------------------------------------------------------------- |
| 7 | + |
| 8 | +import math |
| 9 | + |
| 10 | +import torch |
| 11 | +from torch import nn |
| 12 | + |
| 13 | + |
| 14 | +class QuantLinearTorchFunction(torch.autograd.Function): |
| 15 | + @staticmethod |
| 16 | + def symbolic(g, x, qself_qweight, qself_scales, qself_qzeros, g_idx, bits, groupsize, in_features, out_features): |
| 17 | + input_tuple = (x, qself_qweight, qself_scales, qself_qzeros) |
| 18 | + input_tuple += (g_idx,) if g_idx is not None else () |
| 19 | + return g.op( |
| 20 | + "com.microsoft::MatMulNBits", |
| 21 | + *input_tuple, |
| 22 | + outputs=1, |
| 23 | + K_i=in_features, |
| 24 | + N_i=out_features, |
| 25 | + bits_i=bits, |
| 26 | + block_size_i=groupsize, |
| 27 | + ) |
| 28 | + |
| 29 | + @staticmethod |
| 30 | + def forward(ctx, x, qself_qweight, qself_scales, qself_qzeros, g_idx, bits, groupsize, in_features, out_features): |
| 31 | + if torch.onnx.is_in_onnx_export(): |
| 32 | + return torch.zeros(x.shape[:-1] + (out_features,), dtype=x.dtype, device=x.device).float() |
| 33 | + fp_weight = dequantize_blockwise_bits( |
| 34 | + qself_qweight, qself_scales, qself_qzeros, bits, groupsize, g_idx, in_features, out_features |
| 35 | + )[0].float() |
| 36 | + |
| 37 | + return torch.matmul(x.float(), fp_weight.T.float()) |
| 38 | + |
| 39 | + |
| 40 | +def dequantize_blockwise_bits(quant_values, scale, zero_point, bits, groupsize, g_idx, rows, cols): |
| 41 | + if bits != 4: |
| 42 | + raise ValueError("Only bits=4 is supported for executing quantized model") |
| 43 | + if groupsize != 128: |
| 44 | + raise ValueError("Only groupsize=128 is supported for executing quantized model") |
| 45 | + expand_quant_value = ( |
| 46 | + quant_values.unsqueeze(-1) >> torch.tensor([[[[0, 4]]]], dtype=torch.int32, device=quant_values.device) |
| 47 | + ) & 0x0F |
| 48 | + expand_quant_value = expand_quant_value.reshape(*quant_values.shape[:-1], -1) |
| 49 | + aligned_scale = scale.reshape(*quant_values.shape[:-1], 1) |
| 50 | + if zero_point.dtype == scale.dtype: |
| 51 | + expand_zero_point = zero_point.reshape(*quant_values.shape[:-1], -1) |
| 52 | + else: |
| 53 | + expand_zero_point = ( |
| 54 | + zero_point.unsqueeze(-1) >> torch.tensor([[[[0, 4]]]], dtype=torch.int32, device=quant_values.device) |
| 55 | + ) & 0x0F |
| 56 | + try: |
| 57 | + expand_zero_point = expand_zero_point.reshape(*quant_values.shape[:-1], -1) |
| 58 | + # FIXME: remove try-except |
| 59 | + except RuntimeError: |
| 60 | + expand_zero_point = expand_zero_point.reshape(quant_values.shape[0], -1, 1) |
| 61 | + expand_zero_point = expand_zero_point[:, : quant_values.shape[1]] |
| 62 | + if g_idx is not None and g_idx[:32].sum().item() != 0: |
| 63 | + float_values = ( |
| 64 | + (expand_quant_value.reshape(expand_quant_value.shape[0], -1) - expand_zero_point[:, g_idx, 0]) |
| 65 | + * aligned_scale[:, g_idx, 0] |
| 66 | + ).to(scale.dtype) |
| 67 | + else: |
| 68 | + float_values = ((expand_quant_value - expand_zero_point) * aligned_scale).to(scale.dtype) |
| 69 | + float_values = float_values.reshape(cols, -1) |
| 70 | + if rows != float_values.shape[-1]: |
| 71 | + float_values = float_values[:, :rows] |
| 72 | + expand_zero_point = expand_zero_point[:, :rows] |
| 73 | + if expand_zero_point.ndim == 3: |
| 74 | + expand_zero_point = expand_zero_point.squeeze(-1) |
| 75 | + if aligned_scale.ndim == 3: |
| 76 | + aligned_scale = aligned_scale.squeeze(-1) |
| 77 | + |
| 78 | + return float_values, expand_zero_point, aligned_scale |
| 79 | + |
| 80 | + |
| 81 | +class QuantLinearORT(nn.Module): |
| 82 | + def __init__(self, bits, groupsize, in_features, out_features, bias): |
| 83 | + super().__init__() |
| 84 | + if bits not in [2, 3, 4, 5, 6, 7, 8]: |
| 85 | + raise NotImplementedError("Only 2,4,5,6,7,8 bits are supported.") |
| 86 | + self.in_features = in_features |
| 87 | + self.out_features = out_features |
| 88 | + self.bits = bits |
| 89 | + self.groupsize = groupsize if groupsize != -1 else in_features |
| 90 | + self.act_order = None |
| 91 | + |
| 92 | + q_rows = in_features // self.groupsize |
| 93 | + self.register_buffer( |
| 94 | + "qweight", |
| 95 | + torch.zeros((out_features, q_rows, self.groupsize // (8 // bits)), dtype=torch.uint8), |
| 96 | + ) |
| 97 | + self.register_buffer( |
| 98 | + "qzeros", |
| 99 | + torch.zeros((q_rows + (q_rows & 1)) * (out_features // 8 * self.bits), dtype=torch.uint8), |
| 100 | + ) |
| 101 | + self.register_buffer( |
| 102 | + "scales", torch.zeros((math.ceil(in_features / self.groupsize) * out_features), dtype=torch.float16) |
| 103 | + ) |
| 104 | + self.register_buffer( |
| 105 | + "g_idx", torch.tensor([i // self.groupsize for i in range(in_features)], dtype=torch.int32) |
| 106 | + ) |
| 107 | + if bias: |
| 108 | + self.register_buffer("bias", torch.zeros((out_features), dtype=torch.float16)) |
| 109 | + else: |
| 110 | + self.bias = None |
| 111 | + |
| 112 | + def quant_weight(self, weight, scales, zeros, g_idx): |
| 113 | + scale_zeros = zeros * scales |
| 114 | + scale_mat = scales[g_idx] |
| 115 | + scale_zeros_mat = scale_zeros[g_idx] |
| 116 | + int_weight_T = torch.round(((weight + scale_zeros_mat) / scale_mat).float()).to(torch.int) |
| 117 | + return int_weight_T |
| 118 | + |
| 119 | + def pack_on_device(self, int_weight, int_zeros): |
| 120 | + if self.bits != 4: |
| 121 | + raise ValueError("only 4bit is supported by ONNXRUNTIME for now.") |
| 122 | + |
| 123 | + # Order of groups |
| 124 | + self.act_order = self.g_idx[: self.groupsize // self.bits].sum().item() != 0 |
| 125 | + |
| 126 | + intzeros_pt = int_zeros.T if int_zeros.dtype == self.scales.dtype else int_zeros.T.byte() |
| 127 | + scales_pt = self.scales.T.to(int_weight.device) |
| 128 | + intweight_pt = int_weight.byte() |
| 129 | + |
| 130 | + block_size = self.groupsize |
| 131 | + rows, cols = intweight_pt.shape |
| 132 | + blob_size = block_size // 2 |
| 133 | + k_blocks = (rows + block_size - 1) // block_size |
| 134 | + padded_rows = k_blocks * block_size |
| 135 | + pad_len = padded_rows - rows |
| 136 | + if pad_len > 0: |
| 137 | + intweight_pt = torch.nn.functional.pad(intweight_pt, (0, 0, 0, pad_len), "constant", 0) |
| 138 | + intzeros_pt = torch.nn.functional.pad(intzeros_pt, (0, intzeros_pt.shape[-1] & 1, 0, 0), "constant", 0) |
| 139 | + |
| 140 | + # Pack zeros if they are not float |
| 141 | + if int_zeros.dtype != self.scales.dtype: |
| 142 | + intzeros_pt = (intzeros_pt[:, 0::2]) | (intzeros_pt[:, 1::2] << 4) |
| 143 | + intzeros_pt = intzeros_pt.reshape(-1) |
| 144 | + |
| 145 | + # Pack weights |
| 146 | + intweight_pt_T = int_weight.T |
| 147 | + intweight_pt_T = (intweight_pt_T[:, 0::2]) | (intweight_pt_T[:, 1::2] << 4) |
| 148 | + intweight_pt_T = intweight_pt_T.reshape(cols, k_blocks, blob_size) |
| 149 | + |
| 150 | + scales_pt = scales_pt.reshape(-1) |
| 151 | + |
| 152 | + # Validation checks |
| 153 | + if (self.qweight.shape != intweight_pt_T.shape) and ( |
| 154 | + self.qzeros.shape == intzeros_pt.shape or self.qzeros.dtype != intzeros_pt.dtype |
| 155 | + ): |
| 156 | + raise RuntimeError("Something went wrong while packing the weights in QuantLinearORT module") |
| 157 | + |
| 158 | + # Assign buffers |
| 159 | + self.scales = scales_pt.float() |
| 160 | + self.qweight = intweight_pt_T.byte() # Convert to uint8 |
| 161 | + if int_zeros.dtype != self.scales.dtype: |
| 162 | + self.qzeros = intzeros_pt.byte() # Convert to uint8 |
| 163 | + else: |
| 164 | + self.qzeros = intzeros_pt |
| 165 | + |
| 166 | + def pack(self, linear, scales, zeros, g_idx=None): |
| 167 | + layer_weight = linear.weight.data |
| 168 | + self.scales = scales.T |
| 169 | + self.g_idx = g_idx.clone() |
| 170 | + int_weight = self.quant_weight(layer_weight.T, scales.T, zeros.T, g_idx) |
| 171 | + return self.pack_on_device(int_weight, zeros.T) |
| 172 | + |
| 173 | + def forward(self, inputs): |
| 174 | + out = QuantLinearTorchFunction().apply( |
| 175 | + inputs, |
| 176 | + self.qweight, |
| 177 | + self.scales, |
| 178 | + self.qzeros, |
| 179 | + self.g_idx if self.act_order else None, |
| 180 | + self.bits, |
| 181 | + self.groupsize, |
| 182 | + self.in_features, |
| 183 | + self.out_features, |
| 184 | + ) |
| 185 | + out = out + self.bias if self.bias is not None else out |
| 186 | + return out |
0 commit comments