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/kernels/q4_matmul.mojo # 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 / kernels / q4_matmul.mojo` 282 lines · 9980 bytes Raw Blame History 1 """MojoLlama Q4_0 SIMD Kernel — Updated for Mojo 1.0.0b1 heap APIs. 2 3 Q4_0 block: 32 values packed into 18 bytes (2b f16 scale + 16b nibbles). 4 Full weight matrix matmul using Mojo heap allocation and SIMD. 5 6 Python integration: compiled as shared library (.so) using @export, 7 or called via Python interop from within Mojo. 8 """ 9 10 from std.sys.info import CompilationTarget 11 from std.memory import bitcast 12 from std.memory.unsafe_pointer import alloc, pointer_to_int 13 14 # SIMD types for AVX2 (256-bit) 15 alias F32x8 = SIMD[DType.float32, 8] 16 alias I8x32 = SIMD[DType.int8, 32] 17 alias U8x16 = SIMD[DType.uint8, 16] 18 19 20 # ─── Float16 → Float32 ──────────────────────────────────────────────── 21 22 @always_inline 23 def f16_to_f32(h: UInt16) -> Float32: 24 """float16 bits → float32. Uses F16C VCVTPH2PS when AVX2 available.""" 25 comptime if CompilationTarget.has_avx2(): 26 var f16 = bitcast[DType.float16](h) 27 return Float32(f16) 28 else: 29 # Software IEEE 754-2008 fallback 30 var sign = (UInt32(h) >> 15) & 1 31 var exp = (UInt32(h) >> 10) & 0x1f 32 var mant = UInt32(h) & 0x3ff 33 var bits: UInt32 = 0 34 if exp == 0: 35 if mant == 0: 36 bits = sign << 31 37 else: 38 var m = mant 39 var count: UInt32 = 0 40 while m > 0: 41 m = m >> 1 42 count += 1 43 var shift = 24 - count 44 bits = (sign << 31) | ((UInt32(113 - shift)) << 23) | ((mant << (shift + 13)) & 0x7fffff) 45 elif exp == 31: 46 bits = (sign << 31) | 0x7f800000 | (mant << 13) 47 else: 48 bits = (sign << 31) | ((exp + 112) << 23) | (mant << 13) 49 return Float32(bitcast[DType.float32](bits)) 50 51 52 # ─── Q4_0 Block Utilities ───────────────────────────────────────────── 53 54 struct Q4_0Block: 55 """One GGUF Q4_0 block: 18 bytes, 32 values.""" 56 var raw_scale: UInt16 # f16 57 var nibbles: UInt8 # first byte of 16 — accessed via pointer offsets 58 59 @always_inline 60 def q4_block_read_scale(block_ptr: UnsafePointer[UInt8, _]) -> Float32: 61 """Read f16 scale from a Q4_0 block.""" 62 var lo = block_ptr.load(0) # UInt8 low byte 63 var hi = block_ptr.load(1) # UInt8 high byte 64 var bits = (UInt16(hi) << 8) | UInt16(lo) 65 return f16_to_f32(bits) 66 67 @always_inline 68 def q4_block_read_nibbles(block_ptr: UnsafePointer[UInt8, _]) -> U8x16: 69 """Read 16 nibble bytes from a Q4_0 block (offset +2).""" 70 # Load 16 bytes from offset 2 using SIMD 71 var nibble_ptr = block_ptr + 2 72 return nibble_ptr.load[width=16]() 73 74 75 # ─── Q4_0 Block Dot Product ───────────────────────────────────────────── 76 77 @always_inline 78 def q4_block_dot(scale: Float32, nibbles: U8x16, x: F32x8, x1: F32x8, 79 x2: F32x8, x3: F32x8) -> Float32: 80 """Dot product of one Q4_0 block with 32 float32 inputs. 81 82 Fused dequant + dot: Σ_i (nibble_i - 8) * scale * x_i 83 """ 84 @parameter 85 def dot_group(start_byte: Int, xv: F32x8) -> Float32: 86 var vals = F32x8() 87 for j in range(8): 88 var byte_idx = start_byte + j // 2 89 var b = nibbles[byte_idx] 90 if j % 2 == 0: 91 vals[j] = Float32(Int8(b & 15) - 8) 92 else: 93 vals[j] = Float32(Int8((b >> 4) & 15) - 8) 94 return (vals * scale * xv).reduce_add() 95 96 var total: Float32 = 0.0 97 total += dot_group(0, x) 98 total += dot_group(4, x1) 99 total += dot_group(8, x2) 100 total += dot_group(12, x3) 101 return total 102 103 104 # ─── Full Q4_0 Matmul (heap-allocated) ───────────────────────────────── 105 106 def q4_matmul_forward( 107 weights_data_ptr: Int, # raw address of Q4_0 weight data (from numpy) 108 num_rows: Int, # output feature count 109 num_cols: Int, # input feature count 110 input_ptr: Int, # raw address of float32 input 111 output_ptr: Int, # raw address of float32 output buffer 112 ): 113 """Compute y = W @ x for a Q4_0 weight matrix. 114 115 weights_data: Q4_0 blocks, row-major. Each row has (num_cols/32) blocks. 116 input: float32 vector of size num_cols (single token / batch item). 117 output: float32 vector of size num_rows. 118 119 All pointers are raw Int addresses (from numpy array __array_interface__). 120 121 NOTE: In Mojo 1.0.0b1, UnsafePointer(unsafe_from_address=...) is not 122 available in compiled form, but pointer_to_int + manual offset works. 123 We use a workaround: mmap-backed temp files for data transfer, 124 or call via Python interop where Mojo imports numpy directly. 125 """ 126 # For now, this is the reference — the actual pointer construction 127 # from raw addresses will use Python interop (Mojo imports numpy). 128 print("Q4 matmul forward: rows=", num_rows, " cols=", num_cols) 129 130 131 # ─── Tests ───────────────────────────────────────────────────────────── 132 133 def test_f16(): 134 """Test float16→float32 conversion.""" 135 print("f16→f32 tests:") 136 var f = f16_to_f32(UInt16(0x3c00)) 137 print(" 0x3c00 →", f, "(expect 1.0)") 138 139 f = f16_to_f32(UInt16(0x3800)) 140 print(" 0x3800 →", f, "(expect 0.5)") 141 142 f = f16_to_f32(UInt16(0xbc00)) 143 print(" 0xbc00 →", f, "(expect -1.0)") 144 print() 145 146 147 def test_q4_block_zero(): 148 """Test block dot with all-zero quantized values.""" 149 var scale = f16_to_f32(UInt16(0x3800)) # 0.5 150 var nibbles = U8x16() # all zeros 151 var x = F32x8(2.0) 152 var dot = q4_block_dot(scale, nibbles, x, x, x, x) 153 print("zero block dot:", dot, "(expect -256.0)") 154 if abs(dot - (-256.0)) < 1.0: 155 print(" PASS") 156 else: 157 print(" FAIL") 158 print() 159 160 161 def test_q4_block_varied(): 162 var scale = f16_to_f32(UInt16(0x3c00)) # 1.0 163 var nibbles = U8x16() 164 for i in range(16): 165 nibbles[i] = 0x00 if i % 2 == 0 else 0xFF 166 var x = F32x8(1.0) 167 var dot = q4_block_dot(scale, nibbles, x, x, x, x) 168 print("varied block dot:", dot, "(expect -16.0)") 169 if abs(dot - (-16.0)) < 1.0: 170 print(" PASS") 171 else: 172 print(" FAIL") 173 print() 174 175 176 def test_heap_alloc(): 177 """Test heap allocation of Q4_0 data using Mojo 1.0.0b1's alloc.""" 178 print("Heap allocation tests:") 179 180 # Allocate space for 1024 Q4_0 blocks = 1024 * 18 bytes 181 var n_blocks: Int = 1024 182 var buf = alloc[UInt8](n_blocks * 18) 183 184 # Write some test data 185 for i in range(1024 * 18): 186 buf.store(i, UInt8(0)) 187 188 print(" Allocated", n_blocks * 18, "bytes for Q4_0 data") 189 190 # Read back via pointer math 191 var first = buf.load(0) 192 print(" First byte:", first, "(expect 0)") 193 194 buf.free() 195 print(" Freed OK") 196 print() 197 198 199 # ─── Full matmul test with heap data ───────────────────────────────── 200 201 def test_full_matmul(): 202 """Test Q4_0 matmul with heap-allocated weight data. 203 204 Simulates a small weight matrix: 16 rows × 64 cols (2 blocks per row). 205 Writes known Q4_0 values, runs dequant+matmul, checks result. 206 """ 207 print("Full matmul test (16×64 Q4_0 → float32):") 208 209 var n_rows = 16 210 var n_cols = 64 211 var blocks_per_row = n_cols // 32 # Q4_0 has 32 values per block 212 213 # Allocate weight data on heap: n_rows * blocks_per_row * 18 bytes 214 var w = alloc[UInt8](n_rows * blocks_per_row * 18) 215 216 # Fill with known pattern: scale=1.0 (0x3c00), nibbles=8 (zero point) 217 for row in range(n_rows): 218 for blk in range(blocks_per_row): 219 var off = (row * blocks_per_row + blk) * 18 220 # Scale = 1.0 → f16 bytes: 0x00, 0x3c 221 w.store(off, UInt8(0x00)) 222 w.store(off + 1, UInt8(0x3c)) 223 # Nibbles = 8 (zero point) → all zeros in quantized form 224 for b in range(16): 225 w.store(off + 2 + b, UInt8(0x88)) # hi=8, lo=8 226 227 # Allocate input (all 1.0) and output 228 var inp = alloc[Float32](n_cols) 229 var out = alloc[Float32](n_rows) 230 231 for c in range(n_cols): 232 inp.store(c, Float32(1.0)) 233 for r in range(n_rows): 234 out.store(r, Float32(0.0)) 235 236 # Run matmul: for each row, for each block, compute dot 237 for row in range(n_rows): 238 var total: Float32 = 0.0 239 for blk in range(blocks_per_row): 240 var off = (row * blocks_per_row + blk) * 18 241 var block_ptr = w + off 242 var scale = q4_block_read_scale(block_ptr) 243 var nibbles = q4_block_read_nibbles(block_ptr) 244 245 # Load 32 input values 246 var inp_off = blk * 32 247 var x0 = inp.load[width=8](inp_off) 248 var x1 = inp.load[width=8](inp_off + 8) 249 var x2 = inp.load[width=8](inp_off + 16) 250 var x3 = inp.load[width=8](inp_off + 24) 251 252 total += q4_block_dot(scale, nibbles, x0, x1, x2, x3) 253 254 out.store(row, total) 255 256 # Verify: each nibble=8 → dequant=0 → dot=0 (since 8-8=0) 257 var ok = True 258 for r in range(n_rows): 259 var v = out.load(r) 260 if abs(v - 0.0) > 0.001: 261 print(" FAIL row", r, ":", v, "expect 0.0") 262 ok = False 263 264 if ok: 265 print(" PASS: all outputs match expected (zero-center nibbles)") 266 267 inp.free() 268 out.free() 269 w.free() 270 print() 271 272 273 def main(): 274 print("=== Q4_0 Mojo SIMD Kernel (Mojo 1.0.0b1) ===\n") 275 276 test_f16() 277 test_q4_block_zero() 278 test_q4_block_varied() 279 test_heap_alloc() 280 test_full_matmul() 281 282 print("Done.")