Hzfinfdu commited on
Commit
8df4f69
1 Parent(s): d3ca341

Upload quantization.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. quantization.py +397 -0
quantization.py ADDED
@@ -0,0 +1,397 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import torch
3
+ import torch.nn as nn
4
+ from torch.cuda.amp import custom_bwd, custom_fwd
5
+ import math
6
+
7
+
8
+ def find_layers(module, layers=[nn.Conv2d, nn.Linear], name=''):
9
+ if type(module) in layers:
10
+ return {name: module}
11
+ res = {}
12
+ for name1, child in module.named_children():
13
+ res.update(find_layers(
14
+ child, layers=layers, name=name + '.' + name1 if name != '' else name1
15
+ ))
16
+ return res
17
+
18
+
19
+ try:
20
+ import triton
21
+ import triton.language as tl
22
+ from .custom_autotune import *
23
+ except:
24
+ print('triton not installed. Run `pip install triton` to load quantized version of MOSS.')
25
+
26
+ # code based https://github.com/fpgaminer/GPTQ-triton
27
+ @autotune(
28
+ configs=[
29
+ triton.Config({'BLOCK_SIZE_M': 256, 'BLOCK_SIZE_N': 64, 'BLOCK_SIZE_K': 32, 'GROUP_SIZE_M': 8},
30
+ num_stages=4, num_warps=4),
31
+ triton.Config({'BLOCK_SIZE_M': 64, 'BLOCK_SIZE_N': 256, 'BLOCK_SIZE_K': 32, 'GROUP_SIZE_M': 8},
32
+ num_stages=4, num_warps=4),
33
+ triton.Config({'BLOCK_SIZE_M': 128, 'BLOCK_SIZE_N': 128, 'BLOCK_SIZE_K': 32, 'GROUP_SIZE_M': 8},
34
+ num_stages=4, num_warps=4),
35
+ triton.Config({'BLOCK_SIZE_M': 128, 'BLOCK_SIZE_N': 64, 'BLOCK_SIZE_K': 32, 'GROUP_SIZE_M': 8},
36
+ num_stages=4, num_warps=4),
37
+ triton.Config({'BLOCK_SIZE_M': 64, 'BLOCK_SIZE_N': 128, 'BLOCK_SIZE_K': 32, 'GROUP_SIZE_M': 8},
38
+ num_stages=4, num_warps=4),
39
+ triton.Config({'BLOCK_SIZE_M': 128, 'BLOCK_SIZE_N': 32, 'BLOCK_SIZE_K': 32, 'GROUP_SIZE_M': 8},
40
+ num_stages=4, num_warps=4),
41
+ # These provided a benefit on a 3090
42
+ triton.Config({'BLOCK_SIZE_M': 64, 'BLOCK_SIZE_N': 64, 'BLOCK_SIZE_K': 32, 'GROUP_SIZE_M': 8}, num_stages=4,
43
+ num_warps=4),
44
+ triton.Config({'BLOCK_SIZE_M': 32, 'BLOCK_SIZE_N': 64, 'BLOCK_SIZE_K': 32, 'GROUP_SIZE_M': 8}, num_stages=4,
45
+ num_warps=4),
46
+ triton.Config({'BLOCK_SIZE_M': 64, 'BLOCK_SIZE_N': 32, 'BLOCK_SIZE_K': 32, 'GROUP_SIZE_M': 8}, num_stages=4,
47
+ num_warps=4),
48
+ triton.Config({'BLOCK_SIZE_M': 32, 'BLOCK_SIZE_N': 64, 'BLOCK_SIZE_K': 64, 'GROUP_SIZE_M': 8}, num_stages=4,
49
+ num_warps=4),
50
+ triton.Config({'BLOCK_SIZE_M': 64, 'BLOCK_SIZE_N': 64, 'BLOCK_SIZE_K': 64, 'GROUP_SIZE_M': 8}, num_stages=4,
51
+ num_warps=4),
52
+ triton.Config({'BLOCK_SIZE_M': 64, 'BLOCK_SIZE_N': 32, 'BLOCK_SIZE_K': 64, 'GROUP_SIZE_M': 8}, num_stages=4,
53
+ num_warps=4),
54
+ triton.Config({'BLOCK_SIZE_M': 32, 'BLOCK_SIZE_N': 64, 'BLOCK_SIZE_K': 128, 'GROUP_SIZE_M': 8},
55
+ num_stages=4, num_warps=4),
56
+ ],
57
+ key=['M', 'N'],
58
+ nearest_power_of_two=True,
59
+ )
60
+ @triton.jit
61
+ def matmul_248_kernel(a_ptr, b_ptr, c_ptr,
62
+ scales_ptr, zeros_ptr, g_ptr,
63
+ M, N, K, bits, maxq,
64
+ stride_am, stride_ak,
65
+ stride_bk, stride_bn,
66
+ stride_cm, stride_cn,
67
+ stride_scales, stride_zeros,
68
+ BLOCK_SIZE_M: tl.constexpr, BLOCK_SIZE_N: tl.constexpr, BLOCK_SIZE_K: tl.constexpr,
69
+ GROUP_SIZE_M: tl.constexpr):
70
+ """
71
+ Compute the matrix multiplication C = A x B.
72
+ A is of shape (M, K) float16
73
+ B is of shape (K//8, N) int32
74
+ C is of shape (M, N) float16
75
+ scales is of shape (G, N) float16
76
+ zeros is of shape (G, N) float16
77
+ g_ptr is of shape (K) int32
78
+ """
79
+ infearure_per_bits = 32 // bits
80
+
81
+ pid = tl.program_id(axis=0)
82
+ num_pid_m = tl.cdiv(M, BLOCK_SIZE_M)
83
+ num_pid_n = tl.cdiv(N, BLOCK_SIZE_N)
84
+ num_pid_k = tl.cdiv(K, BLOCK_SIZE_K)
85
+ num_pid_in_group = GROUP_SIZE_M * num_pid_n
86
+ group_id = pid // num_pid_in_group
87
+ first_pid_m = group_id * GROUP_SIZE_M
88
+ group_size_m = min(num_pid_m - first_pid_m, GROUP_SIZE_M)
89
+ pid_m = first_pid_m + (pid % group_size_m)
90
+ pid_n = (pid % num_pid_in_group) // group_size_m
91
+
92
+ offs_am = pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)
93
+ offs_bn = pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)
94
+ offs_k = tl.arange(0, BLOCK_SIZE_K)
95
+ a_ptrs = a_ptr + (offs_am[:, None] * stride_am + offs_k[None, :] * stride_ak) # (BLOCK_SIZE_M, BLOCK_SIZE_K)
96
+ a_mask = (offs_am[:, None] < M)
97
+ # b_ptrs is set up such that it repeats elements along the K axis 8 times
98
+ b_ptrs = b_ptr + ((offs_k[:, None] // infearure_per_bits) * stride_bk + offs_bn[None,
99
+ :] * stride_bn) # (BLOCK_SIZE_K, BLOCK_SIZE_N)
100
+ g_ptrs = g_ptr + offs_k
101
+ # shifter is used to extract the N bits of each element in the 32-bit word from B
102
+ scales_ptrs = scales_ptr + offs_bn[None, :]
103
+ zeros_ptrs = zeros_ptr + (offs_bn[None, :] // infearure_per_bits)
104
+
105
+ shifter = (offs_k % infearure_per_bits) * bits
106
+ zeros_shifter = (offs_bn % infearure_per_bits) * bits
107
+ accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32)
108
+
109
+ for k in range(0, num_pid_k):
110
+ g_idx = tl.load(g_ptrs)
111
+
112
+ # Fetch scales and zeros; these are per-outfeature and thus reused in the inner loop
113
+ scales = tl.load(scales_ptrs + g_idx[:, None] * stride_scales) # (BLOCK_SIZE_K, BLOCK_SIZE_N,)
114
+ zeros = tl.load(zeros_ptrs + g_idx[:, None] * stride_zeros) # (BLOCK_SIZE_K, BLOCK_SIZE_N,)
115
+
116
+ zeros = (zeros >> zeros_shifter[None, :]) & maxq
117
+ zeros = (zeros + 1)
118
+
119
+ a = tl.load(a_ptrs, mask=a_mask, other=0.) # (BLOCK_SIZE_M, BLOCK_SIZE_K)
120
+ b = tl.load(b_ptrs) # (BLOCK_SIZE_K, BLOCK_SIZE_N), but repeated
121
+
122
+ # Now we need to unpack b (which is N-bit values) into 32-bit values
123
+ b = (b >> shifter[:, None]) & maxq # Extract the N-bit values
124
+ b = (b - zeros) * scales # Scale and shift
125
+
126
+ accumulator += tl.dot(a, b)
127
+ a_ptrs += BLOCK_SIZE_K
128
+ b_ptrs += (BLOCK_SIZE_K // infearure_per_bits) * stride_bk
129
+ g_ptrs += BLOCK_SIZE_K
130
+
131
+ c = accumulator.to(tl.float16)
132
+ c_ptrs = c_ptr + stride_cm * offs_am[:, None] + stride_cn * offs_bn[None, :]
133
+ c_mask = (offs_am[:, None] < M) & (offs_bn[None, :] < N)
134
+ tl.store(c_ptrs, accumulator, mask=c_mask)
135
+
136
+
137
+ # code based https://github.com/fpgaminer/GPTQ-triton
138
+ @autotune(
139
+ configs=[
140
+ triton.Config({'BLOCK_SIZE_M': 256, 'BLOCK_SIZE_K': 64, 'BLOCK_SIZE_N': 32, 'GROUP_SIZE_M': 8},
141
+ num_stages=4, num_warps=4),
142
+ triton.Config({'BLOCK_SIZE_M': 64, 'BLOCK_SIZE_K': 256, 'BLOCK_SIZE_N': 32, 'GROUP_SIZE_M': 8},
143
+ num_stages=4, num_warps=4),
144
+ triton.Config({'BLOCK_SIZE_M': 128, 'BLOCK_SIZE_K': 128, 'BLOCK_SIZE_N': 32, 'GROUP_SIZE_M': 8},
145
+ num_stages=4, num_warps=4),
146
+ triton.Config({'BLOCK_SIZE_M': 128, 'BLOCK_SIZE_K': 64, 'BLOCK_SIZE_N': 32, 'GROUP_SIZE_M': 8},
147
+ num_stages=4, num_warps=4),
148
+ triton.Config({'BLOCK_SIZE_M': 64, 'BLOCK_SIZE_K': 128, 'BLOCK_SIZE_N': 32, 'GROUP_SIZE_M': 8},
149
+ num_stages=4, num_warps=4),
150
+ triton.Config({'BLOCK_SIZE_M': 128, 'BLOCK_SIZE_K': 32, 'BLOCK_SIZE_N': 32, 'GROUP_SIZE_M': 8},
151
+ num_stages=4, num_warps=4),
152
+ # These provided a benefit on a 3090
153
+ triton.Config({'BLOCK_SIZE_M': 64, 'BLOCK_SIZE_K': 64, 'BLOCK_SIZE_N': 32, 'GROUP_SIZE_M': 8}, num_stages=4,
154
+ num_warps=4),
155
+ triton.Config({'BLOCK_SIZE_M': 32, 'BLOCK_SIZE_K': 64, 'BLOCK_SIZE_N': 32, 'GROUP_SIZE_M': 8}, num_stages=4,
156
+ num_warps=4),
157
+ triton.Config({'BLOCK_SIZE_M': 64, 'BLOCK_SIZE_K': 32, 'BLOCK_SIZE_N': 32, 'GROUP_SIZE_M': 8}, num_stages=4,
158
+ num_warps=4),
159
+ triton.Config({'BLOCK_SIZE_M': 32, 'BLOCK_SIZE_K': 64, 'BLOCK_SIZE_N': 64, 'GROUP_SIZE_M': 8}, num_stages=4,
160
+ num_warps=4),
161
+ triton.Config({'BLOCK_SIZE_M': 64, 'BLOCK_SIZE_K': 64, 'BLOCK_SIZE_N': 64, 'GROUP_SIZE_M': 8}, num_stages=4,
162
+ num_warps=4),
163
+ triton.Config({'BLOCK_SIZE_M': 64, 'BLOCK_SIZE_K': 32, 'BLOCK_SIZE_N': 64, 'GROUP_SIZE_M': 8}, num_stages=4,
164
+ num_warps=4),
165
+ triton.Config({'BLOCK_SIZE_M': 32, 'BLOCK_SIZE_K': 64, 'BLOCK_SIZE_N': 128, 'GROUP_SIZE_M': 8},
166
+ num_stages=4, num_warps=4),
167
+ ],
168
+ key=['M', 'K'],
169
+ nearest_power_of_two=True,
170
+ )
171
+ @triton.jit
172
+ def trans_matmul_248_kernel(a_ptr, b_ptr, c_ptr,
173
+ scales_ptr, zeros_ptr, g_ptr,
174
+ M, N, K, bits, maxq,
175
+ stride_am, stride_ak,
176
+ stride_bk, stride_bn,
177
+ stride_cm, stride_cn,
178
+ stride_scales, stride_zeros,
179
+ BLOCK_SIZE_M: tl.constexpr, BLOCK_SIZE_N: tl.constexpr, BLOCK_SIZE_K: tl.constexpr,
180
+ GROUP_SIZE_M: tl.constexpr):
181
+ """
182
+ Compute the matrix multiplication C = A x B.
183
+ A is of shape (M, N) float16
184
+ B is of shape (K//8, N) int32
185
+ C is of shape (M, K) float16
186
+ scales is of shape (G, N) float16
187
+ zeros is of shape (G, N) float16
188
+ g_ptr is of shape (K) int32
189
+ """
190
+ infearure_per_bits = 32 // bits
191
+
192
+ pid = tl.program_id(axis=0)
193
+ num_pid_m = tl.cdiv(M, BLOCK_SIZE_M)
194
+ num_pid_k = tl.cdiv(K, BLOCK_SIZE_K)
195
+ num_pid_n = tl.cdiv(N, BLOCK_SIZE_N)
196
+ num_pid_in_group = GROUP_SIZE_M * num_pid_k
197
+ group_id = pid // num_pid_in_group
198
+ first_pid_m = group_id * GROUP_SIZE_M
199
+ group_size_m = min(num_pid_m - first_pid_m, GROUP_SIZE_M)
200
+ pid_m = first_pid_m + (pid % group_size_m)
201
+ pid_k = (pid % num_pid_in_group) // group_size_m
202
+
203
+ offs_am = pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)
204
+ offs_bk = pid_k * BLOCK_SIZE_K + tl.arange(0, BLOCK_SIZE_K)
205
+ offs_n = tl.arange(0, BLOCK_SIZE_N)
206
+ a_ptrs = a_ptr + (offs_am[:, None] * stride_am + offs_n[None, :] * stride_ak) # (BLOCK_SIZE_M, BLOCK_SIZE_N)
207
+ a_mask = (offs_am[:, None] < M)
208
+ # b_ptrs is set up such that it repeats elements along the K axis 8 times
209
+ b_ptrs = b_ptr + ((offs_bk[:, None] // infearure_per_bits) * stride_bk + offs_n[None,
210
+ :] * stride_bn) # (BLOCK_SIZE_K, BLOCK_SIZE_N)
211
+ g_ptrs = g_ptr + offs_bk
212
+ g_idx = tl.load(g_ptrs)
213
+
214
+ # shifter is used to extract the N bits of each element in the 32-bit word from B
215
+ scales_ptrs = scales_ptr + offs_n[None, :] + g_idx[:, None] * stride_scales
216
+ zeros_ptrs = zeros_ptr + (offs_n[None, :] // infearure_per_bits) + g_idx[:, None] * stride_zeros
217
+
218
+ shifter = (offs_bk % infearure_per_bits) * bits
219
+ zeros_shifter = (offs_n % infearure_per_bits) * bits
220
+ accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_K), dtype=tl.float32)
221
+
222
+ for k in range(0, num_pid_n):
223
+ # Fetch scales and zeros; these are per-outfeature and thus reused in the inner loop
224
+ scales = tl.load(scales_ptrs) # (BLOCK_SIZE_K, BLOCK_SIZE_N,)
225
+ zeros = tl.load(zeros_ptrs) # (BLOCK_SIZE_K, BLOCK_SIZE_N,)
226
+
227
+ zeros = (zeros >> zeros_shifter[None, :]) & maxq
228
+ zeros = (zeros + 1)
229
+
230
+ a = tl.load(a_ptrs, mask=a_mask, other=0.) # (BLOCK_SIZE_M, BLOCK_SIZE_N)
231
+ b = tl.load(b_ptrs) # (BLOCK_SIZE_K, BLOCK_SIZE_N), but repeated
232
+
233
+ # Now we need to unpack b (which is N-bit values) into 32-bit values
234
+ b = (b >> shifter[:, None]) & maxq # Extract the N-bit values
235
+ b = (b - zeros) * scales # Scale and shift
236
+ b = tl.trans(b)
237
+
238
+ accumulator += tl.dot(a, b)
239
+ a_ptrs += BLOCK_SIZE_N
240
+ b_ptrs += BLOCK_SIZE_N
241
+ scales_ptrs += BLOCK_SIZE_N
242
+ zeros_ptrs += (BLOCK_SIZE_N // infearure_per_bits)
243
+
244
+ c = accumulator.to(tl.float16)
245
+ c_ptrs = c_ptr + stride_cm * offs_am[:, None] + stride_cn * offs_bk[None, :]
246
+ c_mask = (offs_am[:, None] < M) & (offs_bk[None, :] < K)
247
+ tl.store(c_ptrs, accumulator, mask=c_mask)
248
+
249
+
250
+ def matmul248(input, qweight, scales, qzeros, g_idx, bits, maxq):
251
+ output = torch.empty((input.shape[0], qweight.shape[1]), device='cuda', dtype=torch.float16)
252
+ grid = lambda META: (
253
+ triton.cdiv(input.shape[0], META['BLOCK_SIZE_M']) * triton.cdiv(qweight.shape[1], META['BLOCK_SIZE_N']),)
254
+ matmul_248_kernel[grid](input, qweight, output,
255
+ scales, qzeros, g_idx,
256
+ input.shape[0], qweight.shape[1], input.shape[1], bits, maxq,
257
+ input.stride(0), input.stride(1),
258
+ qweight.stride(0), qweight.stride(1),
259
+ output.stride(0), output.stride(1),
260
+ scales.stride(0), qzeros.stride(0))
261
+ return output
262
+
263
+
264
+ def transpose_matmul248(input, qweight, scales, qzeros, g_idx, bits, maxq):
265
+ output_dim = (qweight.shape[0] * 32) // bits
266
+ output = torch.empty((input.shape[0], output_dim), device='cuda', dtype=torch.float16)
267
+ grid = lambda META: (
268
+ triton.cdiv(input.shape[0], META['BLOCK_SIZE_M']) * triton.cdiv(output_dim, META['BLOCK_SIZE_K']),)
269
+ transpose_matmul_248_kernel[grid](input, qweight, output,
270
+ scales, qzeros, g_idx,
271
+ input.shape[0], qweight.shape[1], output_dim, bits, maxq,
272
+ input.stride(0), input.stride(1),
273
+ qweight.stride(0), qweight.stride(1),
274
+ output.stride(0), output.stride(1),
275
+ scales.stride(0), qzeros.stride(0))
276
+ return output
277
+
278
+
279
+ class QuantLinearFunction(torch.autograd.Function):
280
+ @staticmethod
281
+ @custom_fwd(cast_inputs=torch.float16)
282
+ def forward(ctx, input, qweight, scales, qzeros, g_idx, bits, maxq):
283
+ output = matmul248(input, qweight, scales, qzeros, g_idx, bits, maxq)
284
+ ctx.save_for_backward(qweight, scales, qzeros, g_idx)
285
+ ctx.bits, ctx.maxq = bits, maxq
286
+ return output
287
+
288
+ @staticmethod
289
+ @custom_bwd
290
+ def backward(ctx, grad_output):
291
+ qweight, scales, qzeros, g_idx = ctx.saved_tensors
292
+ bits, maxq = ctx.bits, ctx.maxq
293
+ grad_input = None
294
+
295
+ if ctx.needs_input_grad[0]:
296
+ grad_input = transpose_matmul248(grad_output, qweight, scales, qzeros, g_idx, bits, maxq)
297
+ return grad_input, None, None, None, None, None, None
298
+
299
+ class QuantLinear(nn.Module):
300
+ def __init__(self, bits, groupsize, infeatures, outfeatures, bias):
301
+ super().__init__()
302
+ if bits not in [2, 4, 8]:
303
+ raise NotImplementedError("Only 2,4,8 bits are supported.")
304
+ self.infeatures = infeatures
305
+ self.outfeatures = outfeatures
306
+ self.bits = bits
307
+ self.maxq = 2 ** self.bits - 1
308
+ self.groupsize = groupsize if groupsize != -1 else infeatures
309
+
310
+ self.register_buffer('qweight', torch.zeros((infeatures // 32 * self.bits, outfeatures), dtype=torch.int32))
311
+ self.register_buffer('qzeros', torch.zeros((math.ceil(infeatures / self.groupsize), outfeatures // 32 * self.bits), dtype=torch.int32))
312
+ self.register_buffer('scales', torch.zeros((math.ceil(infeatures / self.groupsize), outfeatures), dtype=torch.float16))
313
+ self.register_buffer('g_idx', torch.tensor([i // self.groupsize for i in range(infeatures)], dtype=torch.int32))
314
+ if bias:
315
+ self.register_buffer('bias', torch.zeros((outfeatures), dtype=torch.float16))
316
+ else:
317
+ self.bias = None
318
+
319
+ def pack(self, linear, scales, zeros, g_idx=None):
320
+ self.g_idx = g_idx.clone() if g_idx is not None else self.g_idx
321
+
322
+ scales = scales.t().contiguous()
323
+ zeros = zeros.t().contiguous()
324
+ scale_zeros = zeros * scales
325
+ self.scales = scales.clone().half()
326
+ if linear.bias is not None:
327
+ self.bias = linear.bias.clone().half()
328
+
329
+ intweight = []
330
+ for idx in range(self.infeatures):
331
+ intweight.append(torch.round(
332
+ (linear.weight.data[:, idx] + scale_zeros[self.g_idx[idx]]) / self.scales[self.g_idx[idx]]).to(
333
+ torch.int)[:, None])
334
+ intweight = torch.cat(intweight, dim=1)
335
+ intweight = intweight.t().contiguous()
336
+ intweight = intweight.numpy().astype(np.uint32)
337
+ qweight = np.zeros((intweight.shape[0] // 32 * self.bits, intweight.shape[1]), dtype=np.uint32)
338
+ i = 0
339
+ row = 0
340
+ while row < qweight.shape[0]:
341
+ if self.bits in [2, 4, 8]:
342
+ for j in range(i, i + (32 // self.bits)):
343
+ qweight[row] |= intweight[j] << (self.bits * (j - i))
344
+ i += 32 // self.bits
345
+ row += 1
346
+ else:
347
+ raise NotImplementedError("Only 2,4,8 bits are supported.")
348
+
349
+ qweight = qweight.astype(np.int32)
350
+ self.qweight = torch.from_numpy(qweight)
351
+
352
+ zeros -= 1
353
+ zeros = zeros.numpy().astype(np.uint32)
354
+ qzeros = np.zeros((zeros.shape[0], zeros.shape[1] // 32 * self.bits), dtype=np.uint32)
355
+ i = 0
356
+ col = 0
357
+ while col < qzeros.shape[1]:
358
+ if self.bits in [2, 4, 8]:
359
+ for j in range(i, i + (32 // self.bits)):
360
+ qzeros[:, col] |= zeros[:, j] << (self.bits * (j - i))
361
+ i += 32 // self.bits
362
+ col += 1
363
+ else:
364
+ raise NotImplementedError("Only 2,4,8 bits are supported.")
365
+
366
+ qzeros = qzeros.astype(np.int32)
367
+ self.qzeros = torch.from_numpy(qzeros)
368
+
369
+ def forward(self, x):
370
+ out_shape = x.shape[:-1] + (self.outfeatures,)
371
+ out = QuantLinearFunction.apply(x.reshape(-1, x.shape[-1]), self.qweight, self.scales,
372
+ self.qzeros, self.g_idx, self.bits, self.maxq)
373
+ out = out + self.bias if self.bias is not None else out
374
+ return out.reshape(out_shape)
375
+
376
+ def make_quant(module, names, bits, groupsize, name=''):
377
+ if isinstance(module, QuantLinear):
378
+ return
379
+ for attr in dir(module):
380
+ tmp = getattr(module, attr)
381
+ name1 = name + '.' + attr if name != '' else attr
382
+ if name1 in names:
383
+ delattr(module, attr)
384
+ setattr(module, attr, QuantLinear(bits, groupsize, tmp.in_features, tmp.out_features, tmp.bias is not None))
385
+ for name1, child in module.named_children():
386
+ make_quant(child, names, bits, groupsize, name + '.' + name1 if name != '' else name1)
387
+
388
+
389
+ def quantize_with_gptq(model, wbits, groupsize):
390
+ model = model.eval()
391
+ layers = find_layers(model)
392
+ for name in ['lm_head']:
393
+ if name in layers:
394
+ del layers[name]
395
+ make_quant(model, layers, wbits, groupsize)
396
+ # model.load_state_dict(torch.load(checkpoint))
397
+ return model