MojoLlama
Archived Mojo/MAX quantizer and serving research repository (read-only history)
Brought by drakestapleton
MojoLlama / src / mojollama / kernels / benchmarks / bench_c_avx2.py
| 1 | #!/usr/bin/env python3 |
| 2 | """Benchmark C AVX2+FMA+OMP kernel performance on Threadripper 3970X.""" |
| 3 | import ctypes |
| 4 | import numpy as np |
| 5 | import time |
| 6 | import os |
| 7 | |
| 8 | KERNEL_DIR = os.path.dirname(os.path.abspath(__file__)) |
| 9 | |
| 10 | def load_omp_lib(): |
| 11 | lib = ctypes.CDLL(os.path.join(KERNEL_DIR, "q4_kernel_omp.so")) |
| 12 | lib.q4_matmul_omp.argtypes = [ |
| 13 | ctypes.POINTER(ctypes.c_uint8), ctypes.POINTER(ctypes.c_float), |
| 14 | ctypes.POINTER(ctypes.c_float), ctypes.c_int, ctypes.c_int, ctypes.c_int, |
| 15 | ] |
| 16 | lib.q4_matmul_omp.restype = None |
| 17 | lib.q4_matmul_omp_blocked.argtypes = [ |
| 18 | ctypes.POINTER(ctypes.c_uint8), ctypes.POINTER(ctypes.c_float), |
| 19 | ctypes.POINTER(ctypes.c_float), ctypes.c_int, ctypes.c_int, ctypes.c_int, |
| 20 | ] |
| 21 | lib.q4_matmul_omp_blocked.restype = None |
| 22 | lib.q4_rms_norm.argtypes = [ |
| 23 | ctypes.POINTER(ctypes.c_float), ctypes.POINTER(ctypes.c_float), |
| 24 | ctypes.POINTER(ctypes.c_float), ctypes.c_int, |
| 25 | ] |
| 26 | lib.q4_rms_norm.restype = None |
| 27 | lib.q4_silu.argtypes = [ctypes.POINTER(ctypes.c_float), ctypes.c_int] |
| 28 | lib.q4_silu.restype = None |
| 29 | lib.q4_get_max_threads.argtypes = [] |
| 30 | lib.q4_get_max_threads.restype = ctypes.c_int |
| 31 | lib.q4_set_num_threads.argtypes = [ctypes.c_int] |
| 32 | lib.q4_set_num_threads.restype = None |
| 33 | return lib |
| 34 | |
| 35 | |
| 36 | def make_q4_weights(n_rows, n_cols): |
| 37 | """Create random Q4_0 weight data (18 bytes per 32-element block).""" |
| 38 | bpr = n_cols // 32 |
| 39 | total_bytes = n_rows * bpr * 18 |
| 40 | return (ctypes.c_uint8 * total_bytes).from_buffer_copy( |
| 41 | np.random.randint(0, 256, total_bytes, dtype=np.uint8).tobytes() |
| 42 | ) |
| 43 | |
| 44 | |
| 45 | def bench(label, fn, n_iters=50): |
| 46 | # Warmup |
| 47 | for _ in range(3): |
| 48 | fn() |
| 49 | times = [] |
| 50 | for _ in range(n_iters): |
| 51 | t0 = time.perf_counter() |
| 52 | fn() |
| 53 | t1 = time.perf_counter() |
| 54 | times.append(t1 - t0) |
| 55 | avg = np.mean(times) * 1000 |
| 56 | std = np.std(times) * 1000 |
| 57 | print(f" {label}: {avg:.2f} ± {std:.2f} ms") |
| 58 | return avg |
| 59 | |
| 60 | |
| 61 | def main(): |
| 62 | lib = load_omp_lib() |
| 63 | |
| 64 | # Detect physical cores |
| 65 | phys_cores = 0 |
| 66 | try: |
| 67 | import glob |
| 68 | cores = set() |
| 69 | for p in glob.glob("/sys/devices/system/cpu/cpu*/topology/core_id"): |
| 70 | with open(p) as f: |
| 71 | cores.add(int(f.read().strip())) |
| 72 | phys_cores = len(cores) if cores else os.cpu_count() // 2 |
| 73 | except: |
| 74 | phys_cores = os.cpu_count() // 2 |
| 75 | |
| 76 | print(f"═══ C AVX2+FMA+OMP Kernel Benchmark ═══") |
| 77 | print(f"Physical cores: {phys_cores}") |
| 78 | print(f"OMP max threads: {lib.q4_get_max_threads()}") |
| 79 | print() |
| 80 | |
| 81 | # Test configs |
| 82 | configs = [ |
| 83 | (2048, 2048, "1B QKV"), |
| 84 | (8192, 2048, "1B FFN"), |
| 85 | (4096, 2048, "1B O_proj"), |
| 86 | ] |
| 87 | |
| 88 | for n_rows, n_cols, label in configs: |
| 89 | w = make_q4_weights(n_rows, n_cols) |
| 90 | x = np.random.randn(n_cols).astype(np.float32) |
| 91 | x_ptr = x.ctypes.data_as(ctypes.POINTER(ctypes.c_float)) |
| 92 | |
| 93 | print(f"── {label}: {n_rows}x{n_cols} ──") |
| 94 | |
| 95 | # Test with different thread counts |
| 96 | for n_threads in [1, phys_cores]: |
| 97 | lib.q4_set_num_threads(n_threads) |
| 98 | out = np.zeros(n_rows, dtype=np.float32) |
| 99 | out_ptr = out.ctypes.data_as(ctypes.POINTER(ctypes.c_float)) |
| 100 | |
| 101 | # Row-outer (standard) |
| 102 | t1 = bench(f"OMP t={n_threads:2d} row_outer", |
| 103 | lambda: lib.q4_matmul_omp(w, x_ptr, out_ptr, n_rows, n_cols, 18)) |
| 104 | |
| 105 | # 4-row blocked |
| 106 | t2 = bench(f"OMP t={n_threads:2d} blocked ", |
| 107 | lambda: lib.q4_matmul_omp_blocked(w, x_ptr, out_ptr, n_rows, n_cols, 18)) |
| 108 | |
| 109 | if t1 > 0 and t2 > 0: |
| 110 | print(f" blocked/row_outer ratio: {t2/t1:.2f}x") |
| 111 | print() |
| 112 | |
| 113 | # Thread sweep |
| 114 | print("── Thread sweep: 2048x2048 ──") |
| 115 | w = make_q4_weights(2048, 2048) |
| 116 | x = np.random.randn(2048).astype(np.float32) |
| 117 | x_ptr = x.ctypes.data_as(ctypes.POINTER(ctypes.c_float)) |
| 118 | |
| 119 | for t in [1, 2, 4, 8, 16, 24, 32, 48, 64]: |
| 120 | if t > os.cpu_count(): |
| 121 | continue |
| 122 | lib.q4_set_num_threads(t) |
| 123 | out = np.zeros(2048, dtype=np.float32) |
| 124 | out_ptr = out.ctypes.data_as(ctypes.POINTER(ctypes.c_float)) |
| 125 | result = bench(f" t={t:2d}", lambda t=t: lib.q4_matmul_omp(w, x_ptr, out_ptr, 2048, 2048, 18)) |
| 126 | |
| 127 | print() |
| 128 | |
| 129 | # RMS norm benchmark |
| 130 | print("── Vectorized ops ──") |
| 131 | n = 2048 |
| 132 | x_data = np.random.randn(n).astype(np.float32) |
| 133 | w_data = np.ones(n, dtype=np.float32) / np.sqrt(n) |
| 134 | x_ptr = x_data.ctypes.data_as(ctypes.POINTER(ctypes.c_float)) |
| 135 | w_ptr = w_data.ctypes.data_as(ctypes.POINTER(ctypes.c_float)) |
| 136 | out_data = np.zeros(n, dtype=np.float32) |
| 137 | out_ptr = out_data.ctypes.data_as(ctypes.POINTER(ctypes.c_float)) |
| 138 | |
| 139 | def bench_rms(): |
| 140 | lib.q4_rms_norm(x_ptr, w_ptr, out_ptr, n) |
| 141 | |
| 142 | bench("RMS norm 2048", bench_rms, 500) |
| 143 | |
| 144 | def bench_silu(): |
| 145 | x_copy = x_data.copy() |
| 146 | lib.q4_silu(x_copy.ctypes.data_as(ctypes.POINTER(ctypes.c_float)), n) |
| 147 | |
| 148 | bench("SiLU 2048", bench_silu, 500) |
| 149 | |
| 150 | # Throughput estimate for Llama 3.2 1B Q4_0 |
| 151 | print() |
| 152 | print("═══ Estimated throughput (1B Q4_0, 32 threads) ═══") |
| 153 | lib.q4_set_num_threads(phys_cores) |
| 154 | |
| 155 | # Measure matmul components |
| 156 | w_qkv = make_q4_weights(3 * 2048, 2048) # QKV combined |
| 157 | w_ffn = make_q4_weights(2 * 8192, 2048) # gate+up |
| 158 | w_down = make_q4_weights(2048, 8192) # down |
| 159 | |
| 160 | x_in = np.random.randn(2048).astype(np.float32) |
| 161 | x_ptr = x_in.ctypes.data_as(ctypes.POINTER(ctypes.c_float)) |
| 162 | |
| 163 | # QKV |
| 164 | out_qkv = np.zeros(3 * 2048, dtype=np.float32) |
| 165 | t_qkv = bench("QKV (6144x2048)", lambda: lib.q4_matmul_omp(w_qkv, x_ptr, out_qkv.ctypes.data_as(ctypes.POINTER(ctypes.c_float)), 3 * 2048, 2048, 18), 20) |
| 166 | |
| 167 | # FFN gate+up |
| 168 | out_ffn = np.zeros(2 * 8192, dtype=np.float32) |
| 169 | t_ffn = bench("FFN gate+up (16384x2048)", lambda: lib.q4_matmul_omp(w_ffn, x_ptr, out_ffn.ctypes.data_as(ctypes.POINTER(ctypes.c_float)), 2 * 8192, 2048, 18), 10) |
| 170 | |
| 171 | # FFN down |
| 172 | x_down = np.random.randn(8192).astype(np.float32) |
| 173 | out_down = np.zeros(2048, dtype=np.float32) |
| 174 | t_down = bench("FFN down (2048x8192)", lambda: lib.q4_matmul_omp(w_down, x_down.ctypes.data_as(ctypes.POINTER(ctypes.c_float)), out_down.ctypes.data_as(ctypes.POINTER(ctypes.c_float)), 2048, 8192, 18), 20) |
| 175 | |
| 176 | total_layer = (t_qkv + t_ffn + t_down + 1.0) * 16 / 1000 # 16 layers + overhead |
| 177 | print(f"\n Total layer: {total_layer*1000:.1f} ms") |
| 178 | print(f" Estimated throughput: {16/(total_layer*1000):.1f} tok/s (decoder)") |
| 179 | print(f" llama.cpp benchmark: ~84 tok/s (for reference)") |
| 180 | |
| 181 | |
| 182 | if __name__ == "__main__": |
| 183 | main() |