MojoLlama
Archived Mojo/MAX quantizer and serving research repository (read-only history)
Brought by drakestapleton
MojoLlama / src / mojollama / kernels / tests / test_quant_kernels.py
| 1 | #!/usr/bin/env python3 |
| 2 | """Test unified quant_kernels_omp.so against gguf Python dequantize reference. |
| 3 | Tests Q4_0, Q4_1, Q4_K, Q5_K, Q6_K, Q8_0 quantized matmul kernels. |
| 4 | """ |
| 5 | |
| 6 | import ctypes |
| 7 | import numpy as np |
| 8 | import struct |
| 9 | import os |
| 10 | import sys |
| 11 | |
| 12 | # ─── Load C kernel library ─────────────────────────────────────────────── |
| 13 | |
| 14 | KERNEL_DIR = os.path.dirname(os.path.abspath(__file__)) |
| 15 | lib = ctypes.CDLL(os.path.join(KERNEL_DIR, "quant_kernels_omp.so")) |
| 16 | |
| 17 | # Set up function signatures |
| 18 | def setup_lib(lib): |
| 19 | funcs = { |
| 20 | 'q4_0_matmul_omp': [ctypes.POINTER(ctypes.c_uint8), ctypes.POINTER(ctypes.c_float), |
| 21 | ctypes.POINTER(ctypes.c_float), ctypes.c_int, ctypes.c_int], |
| 22 | 'q4_1_matmul_omp': [ctypes.POINTER(ctypes.c_uint8), ctypes.POINTER(ctypes.c_float), |
| 23 | ctypes.POINTER(ctypes.c_float), ctypes.c_int, ctypes.c_int], |
| 24 | 'q4_k_matmul_omp': [ctypes.POINTER(ctypes.c_uint8), ctypes.POINTER(ctypes.c_float), |
| 25 | ctypes.POINTER(ctypes.c_float), ctypes.c_int, ctypes.c_int], |
| 26 | 'q5_k_matmul_omp': [ctypes.POINTER(ctypes.c_uint8), ctypes.POINTER(ctypes.c_float), |
| 27 | ctypes.POINTER(ctypes.c_float), ctypes.c_int, ctypes.c_int], |
| 28 | 'q6_k_matmul_omp': [ctypes.POINTER(ctypes.c_uint8), ctypes.POINTER(ctypes.c_float), |
| 29 | ctypes.POINTER(ctypes.c_float), ctypes.c_int, ctypes.c_int], |
| 30 | 'q8_0_matmul_omp': [ctypes.POINTER(ctypes.c_uint8), ctypes.POINTER(ctypes.c_float), |
| 31 | ctypes.POINTER(ctypes.c_float), ctypes.c_int, ctypes.c_int], |
| 32 | 'quant_matmul_omp': [ctypes.POINTER(ctypes.c_uint8), ctypes.POINTER(ctypes.c_float), |
| 33 | ctypes.POINTER(ctypes.c_float), ctypes.c_int, ctypes.c_int, ctypes.c_int], |
| 34 | 'q4_k_dequantize_row': [ctypes.POINTER(ctypes.c_uint8), ctypes.POINTER(ctypes.c_float), ctypes.c_int], |
| 35 | 'q5_k_dequantize_row': [ctypes.POINTER(ctypes.c_uint8), ctypes.POINTER(ctypes.c_float), ctypes.c_int], |
| 36 | 'q6_k_dequantize_row': [ctypes.POINTER(ctypes.c_uint8), ctypes.POINTER(ctypes.c_float), ctypes.c_int], |
| 37 | 'q8_0_dequantize_row': [ctypes.POINTER(ctypes.c_uint8), ctypes.POINTER(ctypes.c_float), ctypes.c_int], |
| 38 | 'f32_matmul_omp': [ctypes.POINTER(ctypes.c_float), ctypes.POINTER(ctypes.c_float), |
| 39 | ctypes.POINTER(ctypes.c_float), ctypes.c_int, ctypes.c_int], |
| 40 | } |
| 41 | for name, argtypes in funcs.items(): |
| 42 | fn = getattr(lib, name) |
| 43 | fn.argtypes = argtypes |
| 44 | fn.restype = None |
| 45 | lib.get_max_threads.argtypes = [] |
| 46 | lib.get_max_threads.restype = ctypes.c_int |
| 47 | lib.set_num_threads.argtypes = [ctypes.c_int] |
| 48 | lib.set_num_threads.restype = None |
| 49 | |
| 50 | setup_lib(lib) |
| 51 | |
| 52 | # Quant type constants (matching ggml) |
| 53 | GGML_TYPE_F32 = 0 |
| 54 | GGML_TYPE_Q4_0 = 2 |
| 55 | GGML_TYPE_Q4_1 = 3 |
| 56 | GGML_TYPE_Q4_K = 7 |
| 57 | GGML_TYPE_Q8_0 = 8 |
| 58 | GGML_TYPE_Q5_K = 9 |
| 59 | GGML_TYPE_Q6_K = 14 |
| 60 | |
| 61 | QK_K = 256 # values per super-block (K-quants) |
| 62 | QK8_0 = 32 # values per block (Q8_0) |
| 63 | |
| 64 | BLOCK_SIZES = { |
| 65 | GGML_TYPE_Q4_0: 18, |
| 66 | GGML_TYPE_Q4_1: 20, |
| 67 | GGML_TYPE_Q4_K: 144, |
| 68 | GGML_TYPE_Q5_K: 176, |
| 69 | GGML_TYPE_Q6_K: 210, |
| 70 | GGML_TYPE_Q8_0: 34, |
| 71 | } |
| 72 | |
| 73 | |
| 74 | def f16_to_f32(h): |
| 75 | """Convert fp16 (uint16) to float32.""" |
| 76 | return struct.unpack('<e', struct.pack('<H', h))[0] |
| 77 | |
| 78 | |
| 79 | # ─── GGUF Reader ───────────────────────────────────────────────────────── |
| 80 | |
| 81 | def read_gguf_tensor_data(filepath, tensor_name): |
| 82 | """Read tensor data from a GGUF file. Returns (numpy_array, quant_type).""" |
| 83 | from gguf import GGUFReader |
| 84 | reader = GGUFReader(filepath) |
| 85 | |
| 86 | for tensor in reader.tensors: |
| 87 | if tensor.name == tensor_name: |
| 88 | # Get quant type |
| 89 | qtype = tensor.tensor_type |
| 90 | data = bytes(tensor.data) # copy out |
| 91 | return np.frombuffer(data, dtype=np.uint8), qtype |
| 92 | |
| 93 | return None, None |
| 94 | |
| 95 | |
| 96 | def find_tensors_by_type(filepath, target_types): |
| 97 | """Find tensor names and their types in a GGUF file. |
| 98 | target_types: dict mapping ggml type id to type name.""" |
| 99 | from gguf import GGUFReader |
| 100 | reader = GGUFReader(filepath) |
| 101 | |
| 102 | results = [] |
| 103 | for tensor in reader.tensors: |
| 104 | qtype = tensor.tensor_type |
| 105 | if qtype in target_types: |
| 106 | results.append((tensor.name, qtype)) |
| 107 | return results |
| 108 | |
| 109 | |
| 110 | # ─── Python dequantize reference (from ggml spec) ──────────────────────── |
| 111 | |
| 112 | def get_scale_min_k4(j, scales): |
| 113 | """Unpack scale and min from the 12-byte scales array (Q4_K/Q5_K).""" |
| 114 | if j < 4: |
| 115 | d = scales[j] & 63 |
| 116 | m = scales[j + 4] & 63 |
| 117 | else: |
| 118 | d = (scales[j + 4] & 0xF) | ((scales[j - 4] >> 6) << 4) |
| 119 | m = (scales[j + 4] >> 4) | ((scales[j] >> 6) << 4) |
| 120 | return d, m |
| 121 | |
| 122 | |
| 123 | def dequantize_q4_k_row(data, n_values): |
| 124 | """Dequantize a Q4_K row to float32. |
| 125 | data: bytes of Q4_K blocks, n_values: number of output values.""" |
| 126 | nb = n_values // QK_K |
| 127 | out = np.zeros(n_values, dtype=np.float32) |
| 128 | idx = 0 |
| 129 | |
| 130 | for b in range(nb): |
| 131 | blk = data[b * 144 : (b + 1) * 144] |
| 132 | d = f16_to_f32(struct.unpack('<H', blk[0:2])[0]) |
| 133 | mn = f16_to_f32(struct.unpack('<H', blk[2:4])[0]) |
| 134 | scales = blk[4:16] |
| 135 | q = blk[16:144] # 128 bytes |
| 136 | |
| 137 | is_ = 0 |
| 138 | q_off = 0 |
| 139 | for j in range(0, QK_K, 64): |
| 140 | sc, m = get_scale_min_k4(is_ + 0, scales) |
| 141 | d1 = d * sc; m1 = mn * m |
| 142 | sc, m = get_scale_min_k4(is_ + 1, scales) |
| 143 | d2 = d * sc; m2 = mn * m |
| 144 | |
| 145 | for l in range(32): |
| 146 | out[idx + l] = d1 * (q[q_off + l] & 0xF) - m1 |
| 147 | for l in range(32): |
| 148 | out[idx + l + 32] = d2 * (q[q_off + l] >> 4) - m2 |
| 149 | |
| 150 | idx += 64 |
| 151 | q_off += 32 |
| 152 | is_ += 2 |
| 153 | |
| 154 | return out |
| 155 | |
| 156 | |
| 157 | def dequantize_q5_k_row(data, n_values): |
| 158 | """Dequantize a Q5_K row to float32.""" |
| 159 | nb = n_values // QK_K |
| 160 | out = np.zeros(n_values, dtype=np.float32) |
| 161 | idx = 0 |
| 162 | |
| 163 | for b in range(nb): |
| 164 | blk = data[b * 176 : (b + 1) * 176] |
| 165 | d = f16_to_f32(struct.unpack('<H', blk[0:2])[0]) |
| 166 | mn = f16_to_f32(struct.unpack('<H', blk[2:4])[0]) |
| 167 | scales = blk[4:16] |
| 168 | qh = blk[16:48] # 32 bytes |
| 169 | ql = blk[48:176] # 128 bytes |
| 170 | |
| 171 | is_ = 0 |
| 172 | ql_off = 0 |
| 173 | u1 = 1 |
| 174 | u2 = 2 |
| 175 | |
| 176 | for j in range(0, QK_K, 64): |
| 177 | sc, m = get_scale_min_k4(is_ + 0, scales) |
| 178 | d1 = d * sc; m1 = mn * m |
| 179 | sc, m = get_scale_min_k4(is_ + 1, scales) |
| 180 | d2 = d * sc; m2 = mn * m |
| 181 | |
| 182 | for l in range(32): |
| 183 | q5_lo = (ql[ql_off + l] & 0xF) + (16 if (qh[l] & u1) else 0) |
| 184 | out[idx + l] = d1 * q5_lo - m1 |
| 185 | for l in range(32): |
| 186 | q5_hi = (ql[ql_off + l] >> 4) + (16 if (qh[l] & u2) else 0) |
| 187 | out[idx + l + 32] = d2 * q5_hi - m2 |
| 188 | |
| 189 | idx += 64 |
| 190 | ql_off += 32 |
| 191 | is_ += 2 |
| 192 | u1 <<= 2 |
| 193 | u2 <<= 2 |
| 194 | |
| 195 | return out |
| 196 | |
| 197 | |
| 198 | def dequantize_q6_k_row(data, n_values): |
| 199 | """Dequantize a Q6_K row to float32.""" |
| 200 | nb = n_values // QK_K |
| 201 | out = np.zeros(n_values, dtype=np.float32) |
| 202 | idx = 0 |
| 203 | |
| 204 | for b in range(nb): |
| 205 | blk = data[b * 210 : (b + 1) * 210] |
| 206 | d = f16_to_f32(struct.unpack('<H', blk[208:210])[0]) |
| 207 | scales = blk[192:208] # int8_t[16] |
| 208 | ql = blk[0:128] |
| 209 | qh = blk[128:192] |
| 210 | |
| 211 | q_off = 0 |
| 212 | qh_off = 0 |
| 213 | sc_off = 0 |
| 214 | |
| 215 | for n in range(0, QK_K, 128): |
| 216 | for l in range(32): |
| 217 | is_ = l // 16 |
| 218 | q1 = ((ql[q_off + l] & 0xF) | (((qh[qh_off + l] >> 0) & 3) << 4)) - 32 |
| 219 | q2 = ((ql[q_off + l + 32] & 0xF) | (((qh[qh_off + l] >> 2) & 3) << 4)) - 32 |
| 220 | q3 = ((ql[q_off + l] >> 4) | (((qh[qh_off + l] >> 4) & 3) << 4)) - 32 |
| 221 | q4 = ((ql[q_off + l + 32] >> 4) | (((qh[qh_off + l] >> 6) & 3) << 4)) - 32 |
| 222 | |
| 223 | ds0 = d * np.int8(scales[sc_off + is_ + 0]) |
| 224 | ds2 = d * np.int8(scales[sc_off + is_ + 2]) |
| 225 | ds4 = d * np.int8(scales[sc_off + is_ + 4]) |
| 226 | ds6 = d * np.int8(scales[sc_off + is_ + 6]) |
| 227 | |
| 228 | out[idx + l + 0] = ds0 * q1 |
| 229 | out[idx + l + 32] = ds2 * q2 |
| 230 | out[idx + l + 64] = ds4 * q3 |
| 231 | out[idx + l + 96] = ds6 * q4 |
| 232 | |
| 233 | idx += 128 |
| 234 | q_off += 64 |
| 235 | qh_off += 32 |
| 236 | sc_off += 8 |
| 237 | |
| 238 | return out |
| 239 | |
| 240 | |
| 241 | def dequantize_q8_0_row(data, n_values): |
| 242 | """Dequantize a Q8_0 row to float32.""" |
| 243 | nb = n_values // QK8_0 |
| 244 | out = np.zeros(n_values, dtype=np.float32) |
| 245 | |
| 246 | for b in range(nb): |
| 247 | blk = data[b * 34 : (b + 1) * 34] |
| 248 | d = f16_to_f32(struct.unpack('<H', blk[0:2])[0]) |
| 249 | qs = blk[2:34] |
| 250 | for j in range(QK8_0): |
| 251 | out[b * QK8_0 + j] = np.int8(qs[j]) * d |
| 252 | |
| 253 | return out |
| 254 | |
| 255 | |
| 256 | def dequantize_q4_0_row(data, n_values): |
| 257 | """Dequantize a Q4_0 row to float32.""" |
| 258 | nb = n_values // 32 |
| 259 | out = np.zeros(n_values, dtype=np.float32) |
| 260 | |
| 261 | for b in range(nb): |
| 262 | blk = data[b * 18 : (b + 1) * 18] |
| 263 | d = f16_to_f32(struct.unpack('<H', blk[0:2])[0]) |
| 264 | for j in range(16): |
| 265 | lo = (blk[2 + j] & 0xF) - 8 |
| 266 | hi = (blk[2 + j] >> 4) - 8 |
| 267 | out[b * 32 + j] = d * lo |
| 268 | out[b * 32 + j + 16] = d * hi |
| 269 | |
| 270 | return out |
| 271 | |
| 272 | |
| 273 | def dequantize_q4_1_row(data, n_values): |
| 274 | """Dequantize a Q4_1 row to float32.""" |
| 275 | nb = n_values // 32 |
| 276 | out = np.zeros(n_values, dtype=np.float32) |
| 277 | |
| 278 | for b in range(nb): |
| 279 | blk = data[b * 20 : (b + 1) * 20] |
| 280 | d = f16_to_f32(struct.unpack('<H', blk[0:2])[0]) |
| 281 | m = f16_to_f32(struct.unpack('<H', blk[2:4])[0]) |
| 282 | for j in range(16): |
| 283 | lo = blk[4 + j] & 0xF |
| 284 | hi = blk[4 + j] >> 4 |
| 285 | out[b * 32 + j] = d * lo + m |
| 286 | out[b * 32 + j + 16] = d * hi + m |
| 287 | |
| 288 | return out |
| 289 | |
| 290 | |
| 291 | # ─── Dequantize reference using C kernels ──────────────────────────────── |
| 292 | |
| 293 | def c_dequantize_q4_k(data, n_values): |
| 294 | """Use C kernel to dequantize Q4_K data.""" |
| 295 | n_blocks = n_values // QK_K |
| 296 | data_arr = (ctypes.c_uint8 * len(data))(*data) |
| 297 | out_arr = (ctypes.c_float * n_values)() |
| 298 | lib.q4_k_dequantize_row(data_arr, out_arr, n_values) |
| 299 | return np.array(out_arr, dtype=np.float32) |
| 300 | |
| 301 | |
| 302 | def c_dequantize_q5_k(data, n_values): |
| 303 | """Use C kernel to dequantize Q5_K data.""" |
| 304 | data_arr = (ctypes.c_uint8 * len(data))(*data) |
| 305 | out_arr = (ctypes.c_float * n_values)() |
| 306 | lib.q5_k_dequantize_row(data_arr, out_arr, n_values) |
| 307 | return np.array(out_arr, dtype=np.float32) |
| 308 | |
| 309 | |
| 310 | def c_dequantize_q6_k(data, n_values): |
| 311 | """Use C kernel to dequantize Q6_K data.""" |
| 312 | data_arr = (ctypes.c_uint8 * len(data))(*data) |
| 313 | out_arr = (ctypes.c_float * n_values)() |
| 314 | lib.q6_k_dequantize_row(data_arr, out_arr, n_values) |
| 315 | return np.array(out_arr, dtype=np.float32) |
| 316 | |
| 317 | |
| 318 | def c_dequantize_q8_0(data, n_values): |
| 319 | """Use C kernel to dequantize Q8_0 data.""" |
| 320 | data_arr = (ctypes.c_uint8 * len(data))(*data) |
| 321 | out_arr = (ctypes.c_float * n_values)() |
| 322 | lib.q8_0_dequantize_row(data_arr, out_arr, n_values) |
| 323 | return np.array(out_arr, dtype=np.float32) |
| 324 | |
| 325 | |
| 326 | # ─── Test functions ─────────────────────────────────────────────────────── |
| 327 | |
| 328 | def test_dequantize(qtype_name, c_dequant_fn, py_dequant_fn, data, n_values): |
| 329 | """Compare C dequantize vs Python reference.""" |
| 330 | ref = py_dequant_fn(data, n_values) |
| 331 | c_result = c_dequant_fn(data, n_values) |
| 332 | |
| 333 | # Check correlation |
| 334 | if np.std(ref) < 1e-10: |
| 335 | corr = 1.0 # constant vector |
| 336 | else: |
| 337 | corr = np.corrcoef(ref, c_result)[0, 1] |
| 338 | |
| 339 | max_err = np.max(np.abs(ref - c_result)) |
| 340 | mean_err = np.mean(np.abs(ref - c_result)) |
| 341 | |
| 342 | print(f" {qtype_name}: correlation={corr:.10f}, max_err={max_err:.6e}, mean_err={mean_err:.6e}") |
| 343 | if corr < 0.99999: |
| 344 | print(f" WARNING: correlation below 0.99999!") |
| 345 | # Print first few values for debugging |
| 346 | for i in range(min(10, len(ref))): |
| 347 | print(f" [{i}] ref={ref[i]:.6f} c={c_result[i]:.6f} diff={ref[i]-c_result[i]:.6e}") |
| 348 | return corr |
| 349 | |
| 350 | |
| 351 | def test_matmul(qtype_name, matmul_fn, data, n_rows, n_cols, block_size): |
| 352 | """Test matmul by comparing C kernel result against: dequantize then dot product.""" |
| 353 | # Generate random input vector |
| 354 | np.random.seed(42) |
| 355 | x = np.random.randn(n_cols).astype(np.float32) |
| 356 | |
| 357 | # Use C dequantize reference to get expected result |
| 358 | # We'll compute: for each row, dot(dequant_row, x) |
| 359 | # Step 1: C dequantize the whole weight matrix |
| 360 | # Step 2: Compute reference via matrix-vector multiply |
| 361 | |
| 362 | # Use C matmul |
| 363 | data_arr = (ctypes.c_uint8 * len(data))(*data) |
| 364 | out = np.zeros(n_rows, dtype=np.float32) |
| 365 | x_ptr = x.ctypes.data_as(ctypes.POINTER(ctypes.c_float)) |
| 366 | out_ptr = out.ctypes.data_as(ctypes.POINTER(ctypes.c_float)) |
| 367 | |
| 368 | matmul_fn(data_arr, x_ptr, out_ptr, n_rows, n_cols) |
| 369 | |
| 370 | print(f" {qtype_name} matmul: out[0]={out[0]:.6f}, out[-1]={out[-1]:.6f}") |
| 371 | return out |
| 372 | |
| 373 | |
| 374 | def main(): |
| 375 | print("=" * 70) |
| 376 | print("Testing quant_kernels_omp.so against Python dequantize reference") |
| 377 | print("=" * 70) |
| 378 | |
| 379 | n_threads = min(os.cpu_count() or 4, 16) |
| 380 | lib.set_num_threads(n_threads) |
| 381 | print(f"Using {n_threads} threads") |
| 382 | print() |
| 383 | |
| 384 | # ─── Test 1: Llama-3.2-1B-Instruct-Q4_0.gguf ── |
| 385 | llama_path = "/onedev-workspace/work/Llama-3.2-1B-Instruct-Q4_0.gguf" |
| 386 | if os.path.exists(llama_path): |
| 387 | print("--- Llama-3.2-1B-Instruct-Q4_0.gguf ---") |
| 388 | from gguf import GGUFReader |
| 389 | |
| 390 | reader = GGUFReader(llama_path) |
| 391 | type_map = {} |
| 392 | for tensor in reader.tensors: |
| 393 | qtype = tensor.tensor_type |
| 394 | if qtype not in type_map and qtype in [GGML_TYPE_Q4_0, GGML_TYPE_Q4_1, GGML_TYPE_Q6_K, GGML_TYPE_Q8_0, GGML_TYPE_Q4_K, GGML_TYPE_Q5_K]: |
| 395 | type_map[qtype] = tensor.name |
| 396 | |
| 397 | type_names = { |
| 398 | GGML_TYPE_Q4_0: "Q4_0", |
| 399 | GGML_TYPE_Q4_1: "Q4_1", |
| 400 | GGML_TYPE_Q4_K: "Q4_K", |
| 401 | GGML_TYPE_Q5_K: "Q5_K", |
| 402 | GGML_TYPE_Q6_K: "Q6_K", |
| 403 | GGML_TYPE_Q8_0: "Q8_0", |
| 404 | } |
| 405 | |
| 406 | qlines = [] |
| 407 | for tensor in reader.tensors: |
| 408 | if tensor.tensor_type in type_names: |
| 409 | qlines.append(f" {tensor.name}: {type_names[tensor.tensor_type]}") |
| 410 | print("\n".join(qlines[:5]) + (" ..." if len(qlines) > 5 else "")) |
| 411 | |
| 412 | # Find a Q4_0 tensor and test |
| 413 | for tensor in reader.tensors: |
| 414 | qtype = tensor.tensor_type |
| 415 | data = bytes(tensor.data) |
| 416 | n_elements = tensor.shape[0] * (tensor.shape[1] if len(tensor.shape) > 1 else 1) |
| 417 | |
| 418 | if qtype == GGML_TYPE_Q4_0 and "blk.0" in tensor.name: |
| 419 | n_cols = tensor.shape[1] |
| 420 | n_rows = tensor.shape[0] |
| 421 | num_blocks_row = n_cols // 32 |
| 422 | data_row = data[:num_blocks_row * 18] # first row |
| 423 | |
| 424 | ref = dequantize_q4_0_row(data_row, n_cols) |
| 425 | deq = np.zeros(n_cols, dtype=np.float32) |
| 426 | in_arr = (ctypes.c_uint8 * len(data_row))(*data_row) |
| 427 | out_arr = (ctypes.c_float * n_cols)() |
| 428 | |
| 429 | # Test using the C dequantize via matmul approach |
| 430 | # For Q4_0 we don't have a separate dequantize function, use matmul with x=1 |
| 431 | # Instead, test matmul directly |
| 432 | x = np.random.randn(n_cols).astype(np.float32) |
| 433 | x_ptr = x.ctypes.data_as(ctypes.POINTER(ctypes.c_float)) |
| 434 | |
| 435 | # Compute reference: dequantize then dot |
| 436 | ref_full = dequantize_q4_0_row(data[:n_rows * num_blocks_row * 18], n_rows * n_cols) |
| 437 | ref_matrix = ref_full.reshape(n_rows, n_cols) |
| 438 | expected = ref_matrix @ x |
| 439 | |
| 440 | # C kernel |
| 441 | full_data = (ctypes.c_uint8 * len(data))(*data[:n_rows * num_blocks_row * 18]) |
| 442 | out = np.zeros(n_rows, dtype=np.float32) |
| 443 | out_ptr = out.ctypes.data_as(ctypes.POINTER(ctypes.c_float)) |
| 444 | lib.q4_0_matmul_omp(full_data, x_ptr, out_ptr, n_rows, n_cols) |
| 445 | |
| 446 | corr = np.corrcoef(expected, out)[0, 1] if np.std(expected) > 1e-10 else 1.0 |
| 447 | max_err = np.max(np.abs(expected - out)) |
| 448 | print(f" Q4_0 matmul test ({tensor.name}, {n_rows}x{n_cols}): corr={corr:.10f}, max_err={max_err:.6e}") |
| 449 | break |
| 450 | |
| 451 | # Test Q6_K if present |
| 452 | for tensor in reader.tensors: |
| 453 | qtype = tensor.tensor_type |
| 454 | data_raw = bytes(tensor.data) |
| 455 | |
| 456 | if qtype == GGML_TYPE_Q6_K and "blk.0" in tensor.name: |
| 457 | n_cols = tensor.shape[1] |
| 458 | n_rows = tensor.shape[0] |
| 459 | assert n_cols % QK_K == 0, f"n_cols={n_cols} not multiple of {QK_K}" |
| 460 | |
| 461 | # Test row-level dequantize |
| 462 | nb = n_cols // QK_K |
| 463 | row_data = data_raw[:nb * 210] |
| 464 | |
| 465 | # Python reference |
| 466 | ref = dequantize_q6_k_row(row_data, n_cols) |
| 467 | # C dequantize |
| 468 | in_arr = (ctypes.c_uint8 * len(row_data))(*row_data) |
| 469 | out_arr = (ctypes.c_float * n_cols)() |
| 470 | lib.q6_k_dequantize_row(in_arr, out_arr, n_cols) |
| 471 | c_result = np.array(out_arr, dtype=np.float32) |
| 472 | |
| 473 | corr_deq = np.corrcoef(ref, c_result)[0, 1] |
| 474 | max_err_deq = np.max(np.abs(ref - c_result)) |
| 475 | print(f" Q6_K dequant: corr={corr_deq:.10f}, max_err={max_err_deq:.6e}") |
| 476 | |
| 477 | # Test matmul |
| 478 | x = np.random.randn(n_cols).astype(np.float32) |
| 479 | x_ptr = x.ctypes.data_as(ctypes.POINTER(ctypes.c_float)) |
| 480 | |
| 481 | # Test with a few rows |
| 482 | test_rows = min(n_rows, 100) |
| 483 | full_data = (ctypes.c_uint8 * len(data_raw[:test_rows * nb * 210]))(*data_raw[:test_rows * nb * 210]) |
| 484 | |
| 485 | # Reference: dequantize then matmul |
| 486 | ref_matrix = np.zeros((test_rows, n_cols), dtype=np.float32) |
| 487 | for r in range(test_rows): |
| 488 | rd = data_raw[r * nb * 210 : (r + 1) * nb * 210] |
| 489 | ref_matrix[r] = dequantize_q6_k_row(rd, n_cols) |
| 490 | expected = ref_matrix @ x |
| 491 | |
| 492 | # C matmul |
| 493 | out = np.zeros(test_rows, dtype=np.float32) |
| 494 | out_ptr = out.ctypes.data_as(ctypes.POINTER(ctypes.c_float)) |
| 495 | lib.q6_k_matmul_omp(full_data, x_ptr, out_ptr, test_rows, n_cols) |
| 496 | |
| 497 | corr = np.corrcoef(expected, out)[0, 1] |
| 498 | max_err = np.max(np.abs(expected - out)) |
| 499 | mean_err = np.mean(np.abs(expected - out)) |
| 500 | print(f" Q6_K matmul ({test_rows}x{n_cols}): corr={corr:.10f}, max_err={max_err:.6e}, mean_err={mean_err:.6e}") |
| 501 | break |
| 502 | else: |
| 503 | print(f" File not found: {llama_path}") |
| 504 | |
| 505 | print() |
| 506 | |
| 507 | # ─── Test 2: Qwen3-30B-A3B-Q4_K_M.gguf ── |
| 508 | qwen_path = "/onedev-workspace/work/Qwen3-30B-A3B-Q4_K_M.gguf" |
| 509 | if os.path.exists(qwen_path): |
| 510 | print("--- Qwen3-30B-A3B-Q4_K_M.gguf ---") |
| 511 | from gguf import GGUFReader |
| 512 | |
| 513 | reader = GGUFReader(qwen_path) |
| 514 | type_names = { |
| 515 | GGML_TYPE_Q4_0: "Q4_0", |
| 516 | GGML_TYPE_Q4_1: "Q4_1", |
| 517 | GGML_TYPE_Q4_K: "Q4_K", |
| 518 | GGML_TYPE_Q5_K: "Q5_K", |
| 519 | GGML_TYPE_Q6_K: "Q6_K", |
| 520 | GGML_TYPE_Q8_0: "Q8_0", |
| 521 | } |
| 522 | |
| 523 | found_types = set() |
| 524 | for tensor in reader.tensors: |
| 525 | if tensor.tensor_type in type_names: |
| 526 | found_types.add(tensor.tensor_type) |
| 527 | print(f" Quant types found: {[type_names[t] for t in sorted(found_types)]}") |
| 528 | |
| 529 | # Test each quant type |
| 530 | for target_qtype, qname in [(GGML_TYPE_Q4_K, "Q4_K"), (GGML_TYPE_Q5_K, "Q5_K"), |
| 531 | (GGML_TYPE_Q6_K, "Q6_K"), (GGML_TYPE_Q8_0, "Q8_0")]: |
| 532 | for tensor in reader.tensors: |
| 533 | if tensor.tensor_type == target_qtype and "blk.0" in tensor.name: |
| 534 | data_raw = bytes(tensor.data) |
| 535 | n_cols = tensor.shape[1] |
| 536 | n_rows = tensor.shape[0] |
| 537 | |
| 538 | if target_qtype == GGML_TYPE_Q8_0: |
| 539 | assert n_cols % QK8_0 == 0, f"Q8_0: n_cols={n_cols} not multiple of {QK8_0}" |
| 540 | block_size = QK8_0 |
| 541 | bs = 34 |
| 542 | else: |
| 543 | assert n_cols % QK_K == 0, f"{qname}: n_cols={n_cols} not multiple of {QK_K}" |
| 544 | block_size = QK_K |
| 545 | bs = BLOCK_SIZES[target_qtype] |
| 546 | |
| 547 | nb = n_cols // block_size |
| 548 | test_rows = min(n_rows, 64) # test 64 rows |
| 549 | |
| 550 | print(f"\n Testing {qname} tensor: {tensor.name} ({n_rows}x{n_cols})") |
| 551 | |
| 552 | # Random input |
| 553 | np.random.seed(42) |
| 554 | x = np.random.randn(n_cols).astype(np.float32) |
| 555 | x_ptr = x.ctypes.data_as(ctypes.POINTER(ctypes.c_float)) |
| 556 | |
| 557 | # Python dequantize reference for test rows |
| 558 | py_dequant_fn = { |
| 559 | GGML_TYPE_Q4_K: dequantize_q4_k_row, |
| 560 | GGML_TYPE_Q5_K: dequantize_q5_k_row, |
| 561 | GGML_TYPE_Q6_K: dequantize_q6_k_row, |
| 562 | GGML_TYPE_Q8_0: dequantize_q8_0_row, |
| 563 | }[target_qtype] |
| 564 | |
| 565 | c_dequant_fn = { |
| 566 | GGML_TYPE_Q4_K: c_dequantize_q4_k, |
| 567 | GGML_TYPE_Q5_K: c_dequantize_q5_k, |
| 568 | GGML_TYPE_Q6_K: c_dequantize_q6_k, |
| 569 | GGML_TYPE_Q8_0: c_dequantize_q8_0, |
| 570 | }[target_qtype] |
| 571 | |
| 572 | # Test dequantize first |
| 573 | row_data = data_raw[:nb * bs] |
| 574 | ref_row = py_dequant_fn(row_data, n_cols) |
| 575 | c_row = c_dequant_fn(row_data, n_cols) |
| 576 | |
| 577 | deq_corr = np.corrcoef(ref_row, c_row)[0, 1] if np.std(ref_row) > 1e-10 else 1.0 |
| 578 | deq_max_err = np.max(np.abs(ref_row - c_row)) |
| 579 | deq_mean_err = np.mean(np.abs(ref_row - c_row)) |
| 580 | print(f" Dequantize: corr={deq_corr:.10f}, max_err={deq_max_err:.6e}, mean_err={deq_mean_err:.6e}") |
| 581 | |
| 582 | if deq_corr < 0.9999: |
| 583 | print(f" WARNING: Low correlation! First 5 diffs:") |
| 584 | for i in range(min(5, len(ref_row))): |
| 585 | print(f" [{i}] py={ref_row[i]:.6f} c={c_row[i]:.6f} diff={ref_row[i]-c_row[i]:.6e}") |
| 586 | |
| 587 | # Test matmul |
| 588 | test_data = data_raw[:test_rows * nb * bs] |
| 589 | test_arr = (ctypes.c_uint8 * len(test_data))(*test_data) |
| 590 | |
| 591 | # Reference: dequantize then matmul |
| 592 | ref_matrix = np.zeros((test_rows, n_cols), dtype=np.float32) |
| 593 | for r in range(test_rows): |
| 594 | rd = data_raw[r * nb * bs : (r + 1) * nb * bs] |
| 595 | ref_matrix[r] = py_dequant_fn(rd, n_cols) |
| 596 | expected = ref_matrix @ x |
| 597 | |
| 598 | # C matmul |
| 599 | out = np.zeros(test_rows, dtype=np.float32) |
| 600 | out_ptr = out.ctypes.data_as(ctypes.POINTER(ctypes.c_float)) |
| 601 | |
| 602 | matmul_fn = { |
| 603 | GGML_TYPE_Q4_K: lib.q4_k_matmul_omp, |
| 604 | GGML_TYPE_Q5_K: lib.q5_k_matmul_omp, |
| 605 | GGML_TYPE_Q6_K: lib.q6_k_matmul_omp, |
| 606 | GGML_TYPE_Q8_0: lib.q8_0_matmul_omp, |
| 607 | }[target_qtype] |
| 608 | |
| 609 | matmul_fn(test_arr, x_ptr, out_ptr, test_rows, n_cols) |
| 610 | |
| 611 | corr = np.corrcoef(expected, out)[0, 1] if np.std(expected) > 1e-10 else 1.0 |
| 612 | max_err = np.max(np.abs(expected - out)) |
| 613 | mean_err = np.mean(np.abs(expected - out)) |
| 614 | print(f" Matmul: corr={corr:.10f}, max_err={max_err:.6e}, mean_err={mean_err:.6e}") |
| 615 | |
| 616 | if corr < 0.9999: |
| 617 | print(f" WARNING: Low matmul correlation!") |
| 618 | for i in range(min(5, len(expected))): |
| 619 | print(f" [{i}] expected={expected[i]:.6f} got={out[i]:.6f} diff={expected[i]-out[i]:.6e}") |
| 620 | |
| 621 | # Also test via dispatch |
| 622 | out2 = np.zeros(test_rows, dtype=np.float32) |
| 623 | out2_ptr = out2.ctypes.data_as(ctypes.POINTER(ctypes.c_float)) |
| 624 | lib.quant_matmul_omp(test_arr, x_ptr, out2_ptr, test_rows, n_cols, target_qtype) |
| 625 | |
| 626 | dispatch_corr = np.corrcoef(expected, out2)[0, 1] if np.std(expected) > 1e-10 else 1.0 |
| 627 | print(f" Dispatch: corr={dispatch_corr:.10f}") |
| 628 | |
| 629 | break |
| 630 | else: |
| 631 | print(f" File not found: {qwen_path}") |
| 632 | |
| 633 | print() |
| 634 | print("=" * 70) |
| 635 | print("DONE") |
| 636 | |
| 637 | |
| 638 | if __name__ == "__main__": |
| 639 | main() |