|
| 1 | +# Adapted from https://github.com/AutoGPTQ/AutoGPTQ/blob/main/auto_gptq/nn_modules/qlinear/qlinear_marlin.py |
| 2 | + |
| 3 | +import numpy as np |
| 4 | +import torch |
| 5 | +import torch.nn as nn |
| 6 | + |
| 7 | +try: |
| 8 | + import autogptq_marlin_cuda |
| 9 | +except ImportError as e: |
| 10 | + marlin_import_exception = e |
| 11 | + |
| 12 | + def error_raiser_marlin(*args, **kwargs): |
| 13 | + raise ValueError( |
| 14 | + f"Trying to use the marlin backend, but could not import the C++/CUDA dependencies with the following error: {marlin_import_exception}" |
| 15 | + ) |
| 16 | + |
| 17 | + autogptq_marlin_cuda = error_raiser_marlin |
| 18 | + |
| 19 | + |
| 20 | +def mul(A, B, C, s, workspace, thread_k=-1, thread_n=-1, sms=-1, max_par=16): |
| 21 | + """Marlin FP16xINT4 multiply; can be used within `torch.compile`. |
| 22 | + @A: `torch.half` input matrix of shape `(m, k)` in standard row-major layout |
| 23 | + @B: `torch.int` weight matrix of original shape `(k, n)` in Marlin format; see `Layer.pack()` |
| 24 | + @C: `torch.half` out matrix of shape `(m, n)` in standard row-major layout |
| 25 | + @s: `torch.half` scales of shape `(m / group_size, n)` |
| 26 | + @workspace: `torch.int` tensor with at least `n / 128 * max_par` entries that are all zero |
| 27 | + @thread_k: `k` size of a thread_tile in `B` (can usually be left as auto -1) |
| 28 | + @thread_n: `n` size of a thread_tile in `B` (can usually be left as auto -1) |
| 29 | + @sms: number of SMs to use for the kernel (can usually be left as auto -1) |
| 30 | + @max_par: maximum number of batch 64 problems to solve in parallel for large input sizes |
| 31 | + """ |
| 32 | + autogptq_marlin_cuda.mul(A, B, C, s, workspace, thread_k, thread_n, sms, max_par) |
| 33 | + |
| 34 | + |
| 35 | +# Precompute permutations for Marlin weight and scale shuffling |
| 36 | + |
| 37 | + |
| 38 | +def _get_perms(): |
| 39 | + perm = [] |
| 40 | + for i in range(32): |
| 41 | + perm1 = [] |
| 42 | + col = i // 4 |
| 43 | + for block in [0, 1]: |
| 44 | + for row in [ |
| 45 | + 2 * (i % 4), |
| 46 | + 2 * (i % 4) + 1, |
| 47 | + 2 * (i % 4 + 4), |
| 48 | + 2 * (i % 4 + 4) + 1, |
| 49 | + ]: |
| 50 | + perm1.append(16 * row + col + 8 * block) |
| 51 | + for j in range(4): |
| 52 | + perm.extend([p + 256 * j for p in perm1]) |
| 53 | + |
| 54 | + perm = np.array(perm) |
| 55 | + interleave = np.array([0, 2, 4, 6, 1, 3, 5, 7]) |
| 56 | + perm = perm.reshape((-1, 8))[:, interleave].ravel() |
| 57 | + perm = torch.from_numpy(perm) |
| 58 | + scale_perm = [] |
| 59 | + for i in range(8): |
| 60 | + scale_perm.extend([i + 8 * j for j in range(8)]) |
| 61 | + scale_perm_single = [] |
| 62 | + for i in range(4): |
| 63 | + scale_perm_single.extend([2 * i + j for j in [0, 1, 8, 9, 16, 17, 24, 25]]) |
| 64 | + return perm, scale_perm, scale_perm_single |
| 65 | + |
| 66 | +# _perm, _scale_perm, _scale_perm_single = _get_perms() |
| 67 | + |
| 68 | +# def unpack_qzeros(qzeros): |
| 69 | +# unpacked_zeros = torch.zeros( |
| 70 | +# (qzeros.shape[0], qzeros.shape[1] * 8), |
| 71 | +# dtype=torch.int8, |
| 72 | +# device=qzeros.device, |
| 73 | +# requires_grad=False, |
| 74 | +# ) |
| 75 | + |
| 76 | +# for col in range(unpacked_zeros.shape[1]): |
| 77 | +# i = col % 8 |
| 78 | +# unpacked_zeros[:, col] = (qzeros[:, col // 8] >> (4 * i)) & 0xF |
| 79 | + |
| 80 | +# return unpacked_zeros + 1 |
| 81 | + |
| 82 | +def pack(x, nbits=4): |
| 83 | + pack_size = 32 // nbits |
| 84 | + out = torch.zeros((x.shape[0]//pack_size, x.shape[1]), dtype=x.dtype, device=x.device) |
| 85 | + bitmask = 2**nbits - 1 |
| 86 | + for i in range(pack_size): |
| 87 | + out |= (x[i::pack_size] & bitmask) << (nbits*i) |
| 88 | + return out |
| 89 | + |
| 90 | +def unpack(x, nbits=4, axis=0): |
| 91 | + assert nbits == 4 |
| 92 | + bitmask = 2**nbits - 1 |
| 93 | + pack_size = 32 // nbits |
| 94 | + dim0_size = x.shape[0] * pack_size if axis == 0 else x.shape[0] |
| 95 | + dim1_size = x.shape[1] * pack_size if axis == 1 else x.shape[1] |
| 96 | + output = torch.empty((dim0_size, dim1_size), dtype=x.dtype, layout=x.layout, device=x.device) |
| 97 | + |
| 98 | + if axis == 0: |
| 99 | + for i in range(pack_size): |
| 100 | + output[i::pack_size, :] = (x >> (i*nbits)) & bitmask |
| 101 | + elif axis == 1: |
| 102 | + for i in range(pack_size): |
| 103 | + output[:, i::pack_size] = (x >> (i*nbits)) & bitmask |
| 104 | + else: |
| 105 | + assert False, "invalid unpack axis" |
| 106 | + return output |
| 107 | + |
| 108 | + |
| 109 | +class MarlinQuantLinear(nn.Module): |
| 110 | + QUANT_TYPE = "marlin" |
| 111 | + |
| 112 | + def __init__(self, qweight, qzeros, scales, g_idx, bias, bits, group_size): |
| 113 | + super().__init__() |
| 114 | + |
| 115 | + pack_size = 32 // bits |
| 116 | + infeatures = qweight.shape[0] * pack_size |
| 117 | + outfeatures = qweight.shape[1] |
| 118 | + |
| 119 | + device_capability = torch.cuda.get_device_capability() |
| 120 | + if not device_capability[0] >= 8: |
| 121 | + raise ValueError(f'Can not use Marlin int4*fp16 kernel with a device of compute capability {device_capability}.') |
| 122 | + if infeatures % 128 != 0 or outfeatures % 256 != 0: |
| 123 | + raise ValueError("`infeatures` must be divisible by 128 and `outfeatures` by 256.") |
| 124 | + if bits not in [4]: |
| 125 | + raise NotImplementedError("Only 4 bits are supported.") |
| 126 | + if group_size not in [-1, 128] and group_size != infeatures: |
| 127 | + raise ValueError("Only group_size -1 and 128 are supported.") |
| 128 | + if infeatures % group_size != 0: |
| 129 | + raise ValueError("`infeatures` must be divisible by `group_size`.") |
| 130 | + |
| 131 | + self.infeatures = infeatures |
| 132 | + self.outfeatures = outfeatures |
| 133 | + self.group_size = group_size if group_size != -1 else infeatures |
| 134 | + |
| 135 | + self.desc_act = not ( g_idx is None |
| 136 | + or torch.equal(g_idx, torch.arange(infeatures, device=qweight.device) // group_size) ) |
| 137 | + |
| 138 | + if self.desc_act: |
| 139 | + # shuffle weight rows |
| 140 | + self.perm = torch.argsort(g_idx) |
| 141 | + # unpack --> shuffle --> pack |
| 142 | + qweight = pack(unpack(qweight)[self.perm]) |
| 143 | + |
| 144 | + # Repack into marlin format |
| 145 | + self.B = autogptq_marlin_cuda.gptq_repack(qweight) |
| 146 | + |
| 147 | + # # Check symmetric quantization, very slow, skipping for now |
| 148 | + # dequantized_qzeros = unpack_qzeros(qzeros) |
| 149 | + # if not torch.all(dequantized_qzeros == 8): |
| 150 | + # raise ValueError( |
| 151 | + # "Marlin kernel is compatible only with checkpoints using symetric quantization. " |
| 152 | + # "Found non-symmetric quantization for the weight {name}." |
| 153 | + # ) |
| 154 | + |
| 155 | + # Process scales |
| 156 | + _, _scale_perm, _scale_perm_single = _get_perms() |
| 157 | + s = scales.data.clone() |
| 158 | + if group_size != infeatures: |
| 159 | + s = s.reshape((1, -1)) |
| 160 | + s = s.reshape((-1, len(_scale_perm)))[:, _scale_perm] |
| 161 | + else: |
| 162 | + s = s.reshape((-1, len(_scale_perm_single)))[:, _scale_perm_single] |
| 163 | + s = s.reshape((-1, outfeatures)).contiguous() |
| 164 | + self.s = s |
| 165 | + |
| 166 | + # TODO: Can the workspace be shared among all marlin invocations? |
| 167 | + self.workspace = torch.zeros(self.outfeatures // 128 * 16, dtype=torch.int, device=qweight.device) |
| 168 | + self.bias = bias if bias is not None else None |
| 169 | + |
| 170 | + def post_init(self): |
| 171 | + pass |
| 172 | + |
| 173 | + def forward(self, A): |
| 174 | + A = A.half() |
| 175 | + #Support activation reordering |
| 176 | + if self.desc_act: |
| 177 | + A = A[:, self.perm] |
| 178 | + C = torch.empty(A.shape[:-1] + (self.s.shape[1],), dtype=A.dtype, device=A.device) |
| 179 | + mul( |
| 180 | + A.view((-1, A.shape[-1])), |
| 181 | + self.B, |
| 182 | + C.view((-1, C.shape[-1])), |
| 183 | + self.s, |
| 184 | + self.workspace, |
| 185 | + ) |
| 186 | + C = C + self.bias if self.bias is not None else C |
| 187 | + return C |
0 commit comments