Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/MojoLlama/blob/main/src/mojollama/model/cq4_matmul.py # MojoLlama Archived Mojo/MAX quantizer and serving research repository (read-only history) Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `MojoLlama / src / mojollama / model / cq4_matmul.py` 281 lines · 10416 bytes Raw Blame History 1 """ 2 C-backed Q4_0 quantized matmul for GGUF models — AVX2+FMA+OpenMP. 3 4 Uses the optimized q4_kernel_omp.so with: 5 - Full AVX2 SIMD dequant pipeline (15-instruction nibble unpack) 6 - FMA chain for dot products (1 MUL + 3 FMAs per block) 7 - Row-outer accumulation (1 write per row, not per block) 8 - 4-row register blocking variant 9 - OpenMP multi-threading on Threadripper 3970X (32 physical cores) 10 - Vectorized RMS norm, SiLU, softmax 11 - Thread control (get/set OMP threads) 12 """ 13 import ctypes 14 import numpy as np 15 import os 16 from pathlib import Path 17 18 _kernel_dir = Path(__file__).parent.parent / "kernels" 19 _lib_omp = None 20 _lib_batch = None 21 22 23 def _get_omp_lib(): 24 global _lib_omp 25 if _lib_omp is None: 26 lib_path = _kernel_dir / "q4_kernel_omp.so" 27 _lib_omp = ctypes.CDLL(str(lib_path)) 28 # Matmul: (w, x, out, n_rows, n_cols, type_size) 29 _lib_omp.q4_matmul_omp.argtypes = [ 30 ctypes.POINTER(ctypes.c_uint8), ctypes.POINTER(ctypes.c_float), 31 ctypes.POINTER(ctypes.c_float), ctypes.c_int, ctypes.c_int, ctypes.c_int, 32 ] 33 _lib_omp.q4_matmul_omp.restype = None 34 # Blocked variant 35 _lib_omp.q4_matmul_omp_blocked.argtypes = [ 36 ctypes.POINTER(ctypes.c_uint8), ctypes.POINTER(ctypes.c_float), 37 ctypes.POINTER(ctypes.c_float), ctypes.c_int, ctypes.c_int, ctypes.c_int, 38 ] 39 _lib_omp.q4_matmul_omp_blocked.restype = None 40 # AVX2 single-threaded (start, end rows) 41 _lib_omp.q4_matmul_avx2.argtypes = [ 42 ctypes.POINTER(ctypes.c_uint8), ctypes.POINTER(ctypes.c_float), 43 ctypes.POINTER(ctypes.c_float), ctypes.c_int, ctypes.c_int, 44 ctypes.c_int, ctypes.c_int, ctypes.c_int, 45 ] 46 _lib_omp.q4_matmul_avx2.restype = None 47 # Norm, activation, softmax 48 _lib_omp.q4_rms_norm.argtypes = [ 49 ctypes.POINTER(ctypes.c_float), ctypes.POINTER(ctypes.c_float), 50 ctypes.POINTER(ctypes.c_float), ctypes.c_int, 51 ] 52 _lib_omp.q4_rms_norm.restype = None 53 _lib_omp.q4_silu.argtypes = [ctypes.POINTER(ctypes.c_float), ctypes.c_int] 54 _lib_omp.q4_silu.restype = None 55 _lib_omp.q4_softmax.argtypes = [ctypes.POINTER(ctypes.c_float), ctypes.c_int] 56 _lib_omp.q4_softmax.restype = None 57 # Thread control 58 _lib_omp.q4_get_max_threads.argtypes = [] 59 _lib_omp.q4_get_max_threads.restype = ctypes.c_int 60 _lib_omp.q4_set_num_threads.argtypes = [ctypes.c_int] 61 _lib_omp.q4_set_num_threads.restype = None 62 # Auto-detect: physical cores only (no SMT) 63 n_phys = _detect_physical_cores() 64 _lib_omp.q4_set_num_threads(n_phys) 65 return _lib_omp 66 67 68 def _get_batch_lib(): 69 global _lib_batch 70 if _lib_batch is None: 71 lib_path = _kernel_dir / "q4_kernel_batch.so" 72 _lib_batch = ctypes.CDLL(str(lib_path)) 73 MAX_PROJ = 7 74 _PP = ctypes.POINTER(ctypes.c_uint8) * MAX_PROJ 75 _PF = ctypes.POINTER(ctypes.c_float) * MAX_PROJ 76 _PI = ctypes.c_int * MAX_PROJ 77 _lib_batch.batch_matmul.argtypes = [ 78 _PP, ctypes.POINTER(ctypes.c_float), _PF, _PI, _PI, _PI, ctypes.c_int, 79 ] 80 _lib_batch.batch_matmul.restype = None 81 return _lib_batch 82 83 84 def _detect_physical_cores(): 85 """Detect physical cores, excluding SMT. On Threadripper 3970X: 32.""" 86 try: 87 cores = set() 88 import glob 89 for p in glob.glob("/sys/devices/system/cpu/cpu*/topology/core_id"): 90 try: 91 with open(p) as f: 92 cores.add(int(f.read().strip())) 93 except (ValueError, OSError): 94 pass 95 if cores: 96 return len(cores) 97 except (FileNotFoundError, OSError): 98 pass 99 return max(1, (os.cpu_count() or 2) // 2) 100 101 102 def _canonical_q4_bytes(tensor) -> bytes: 103 """Convert a GGUF Q4_0 tensor to canonical Q4_0 bytes for C kernel.""" 104 from gguf.quants import Q4_0 105 import gguf 106 arr = gguf.dequantize(tensor.data, tensor.tensor_type) 107 out_rows, in_cols = arr.shape 108 total_vals = out_rows * in_cols 109 n_blocks = (total_vals + 31) // 32 110 flat = arr.ravel() 111 if len(flat) < n_blocks * 32: 112 flat = np.pad(flat, (0, n_blocks * 32 - len(flat))) 113 blocks_2d = flat.reshape(n_blocks, 32) 114 q4_blocks = Q4_0.quantize_blocks(blocks_2d) 115 blocks_per_row = (in_cols + 31) // 32 116 return q4_blocks.reshape(out_rows, blocks_per_row * 18).tobytes() 117 118 119 class CQ4Matmul: 120 """Q4_0 matmul using C AVX2+FMA+OpenMP kernel. 121 122 Zero float32 weight allocation during inference. 123 Uses row-outer accumulation, FMA chain, 4-row register blocking. 124 Auto-tunes thread count to physical cores (not logical HT cores). 125 """ 126 TYPE_Q4_0 = 18 127 TYPE_Q4_1 = 20 128 129 def __init__(self, raw_bytes: bytes, out_rows: int, in_cols: int, 130 type_size: int = 18): 131 self.out_rows = out_rows 132 self.in_cols = in_cols 133 self.type_size = type_size 134 self._raw = (ctypes.c_uint8 * len(raw_bytes)).from_buffer_copy(raw_bytes) 135 self._lib = _get_omp_lib() 136 137 @classmethod 138 def from_gguf_tensor(cls, tensor, type_size: int = 18) -> "CQ4Matmul": 139 arr = __import__('gguf').dequantize(tensor.data, tensor.tensor_type) 140 out_rows, in_cols = arr.shape 141 raw_bytes = _canonical_q4_bytes(tensor) 142 return cls(raw_bytes, out_rows, in_cols, type_size) 143 144 def forward(self, x: np.ndarray, blocked: bool = True) -> np.ndarray: 145 """Compute y = x @ W^T. Row-outer + FMA, optionally 4-row blocked.""" 146 is_1d = x.ndim == 1 147 if is_1d: 148 x = x.reshape(1, -1) 149 batch = x.shape[0] 150 out = np.zeros((batch, self.out_rows), dtype=np.float32) 151 fn = self._lib.q4_matmul_omp_blocked if blocked else self._lib.q4_matmul_omp 152 for b in range(batch): 153 fn( 154 self._raw, 155 x[b].ctypes.data_as(ctypes.POINTER(ctypes.c_float)), 156 out[b].ctypes.data_as(ctypes.POINTER(ctypes.c_float)), 157 self.out_rows, self.in_cols, self.type_size, 158 ) 159 return out.reshape(-1) if is_1d else out 160 161 def forward_t(self, x: np.ndarray) -> np.ndarray: 162 """Legacy API: compute y = x @ W^T with batch support.""" 163 return self.forward(x, blocked=False) 164 165 166 class CQ4RMSNorm: 167 """AVX2+FMA vectorized RMS normalization.""" 168 def __init__(self): 169 self._lib = _get_omp_lib() 170 171 def forward(self, x: np.ndarray, weight: np.ndarray) -> np.ndarray: 172 out = np.empty_like(x) 173 n = len(x) 174 self._lib.q4_rms_norm( 175 x.ctypes.data_as(ctypes.POINTER(ctypes.c_float)), 176 weight.ctypes.data_as(ctypes.POINTER(ctypes.c_float)), 177 out.ctypes.data_as(ctypes.POINTER(ctypes.c_float)), 178 n, 179 ) 180 return out 181 182 183 class CQ4SiLU: 184 """AVX2 vectorized SiLU activation (scalar exp, vectorized multiply).""" 185 def __init__(self): 186 self._lib = _get_omp_lib() 187 188 def forward(self, x: np.ndarray) -> np.ndarray: 189 x = x.copy() 190 self._lib.q4_silu(x.ctypes.data_as(ctypes.POINTER(ctypes.c_float)), len(x)) 191 return x 192 193 194 class CQ4Softmax: 195 """AVX2 vectorized softmax (vectorized max/reduce, scalar exp).""" 196 def __init__(self): 197 self._lib = _get_omp_lib() 198 199 def forward(self, x: np.ndarray) -> np.ndarray: 200 x = x.copy() 201 self._lib.q4_softmax(x.ctypes.data_as(ctypes.POINTER(ctypes.c_float)), len(x)) 202 return x 203 204 205 class CQ4BatchMatmul: 206 """Batched Q4_X matmul — up to 7 projections in one OpenMP call. 207 208 Shares input vector across all projections for maximum cache reuse. 209 Perfect for fused QKV or QKV+O+gate+up+down. 210 """ 211 TYPE_Q4_0 = 18 212 TYPE_Q4_1 = 20 213 MAX_PROJ = 7 214 215 def __init__(self, projections: list): 216 """Initialize with a list of (raw_bytes, out_rows, in_cols, type_size) tuples.""" 217 assert len(projections) <= self.MAX_PROJ 218 self.projections = [] 219 lib = _get_omp_lib() 220 for raw_bytes, out_rows, in_cols, type_size in projections: 221 raw_arr = (ctypes.c_uint8 * len(raw_bytes)).from_buffer_copy(raw_bytes) 222 self.projections.append((raw_arr, out_rows, in_cols, type_size)) 223 224 @classmethod 225 def from_gguf_tensors(cls, tensors: list) -> "CQ4BatchMatmul": 226 """Create from a list of GGUF tensors. 227 228 Each tensor is (gguf_tensor, type_size) tuple. 229 """ 230 projections = [] 231 for tensor, type_size in tensors: 232 arr = __import__('gguf').dequantize(tensor.data, tensor.tensor_type) 233 out_rows, in_cols = arr.shape 234 raw_bytes = _canonical_q4_bytes(tensor) 235 projections.append((raw_bytes, out_rows, in_cols, type_size)) 236 return cls(projections) 237 238 def forward(self, x: np.ndarray) -> list: 239 """Compute all projections sharing the same input vector x. 240 241 Returns a list of output arrays, one per projection. 242 """ 243 batch_lib = _get_batch_lib() 244 n_proj = len(self.projections) 245 w_arr = (ctypes.POINTER(ctypes.c_uint8) * self.MAX_PROJ)() 246 out_arr = (ctypes.POINTER(ctypes.c_float) * self.MAX_PROJ)() 247 nrows_arr = (ctypes.c_int * self.MAX_PROJ)() 248 ncols_arr = (ctypes.c_int * self.MAX_PROJ)() 249 ts_arr = (ctypes.c_int * self.MAX_PROJ)() 250 outputs = [] 251 252 for i, (raw_arr, out_rows, in_cols, type_size) in enumerate(self.projections): 253 w_arr[i] = ctypes.cast(raw_arr, ctypes.POINTER(ctypes.c_uint8)) 254 nrows_arr[i] = out_rows 255 ncols_arr[i] = in_cols 256 ts_arr[i] = type_size 257 out = np.zeros(out_rows, dtype=np.float32) 258 outputs.append(out) 259 out_arr[i] = out.ctypes.data_as(ctypes.POINTER(ctypes.c_float)) 260 261 batch_lib.batch_matmul( 262 w_arr, 263 x.ctypes.data_as(ctypes.POINTER(ctypes.c_float)), 264 out_arr, nrows_arr, ncols_arr, ts_arr, n_proj, 265 ) 266 return outputs 267 268 269 def set_num_threads(n: int): 270 """Set OpenMP thread count for C kernels. Use physical cores for best perf.""" 271 _get_omp_lib().q4_set_num_threads(n) 272 273 274 def get_max_threads() -> int: 275 """Get max available OpenMP threads.""" 276 return _get_omp_lib().q4_get_max_threads() 277 278 279 def get_physical_cores() -> int: 280 """Get number of physical CPU cores (excl. SMT).""" 281 return _detect_physical_cores()