MojoLlama
Archived Mojo/MAX quantizer and serving research repository (read-only history)
Brought by drakestapleton
MojoLlama / src / mojollama / mojo_engine / perf_helper.c
| 1 | /* perf_helper.c — Performance helpers for MojoLlama (cache-aligned alloc, prefetch, thread pinning) |
| 2 | * WHAT: Wrappers for AVX2 optimizations Mojo can't express directly. |
| 3 | * WHY: Mojo 1.0.0b1 can't emit x86 intrinsics or set thread affinity. |
| 4 | * C handles the unavoidable I/O + platform operations. |
| 5 | * WHEN: 2026-05-22 |
| 6 | * |
| 7 | * Functions: |
| 8 | * _ml_memalign(sz, align) — cache-aligned memory allocation (64-byte boundary) |
| 9 | * _ml_free(ptr) — free aligned memory |
| 10 | * _ml_prefetch_L1(addr) — software prefetch to L1 cache (T0 hint) |
| 11 | * _ml_prefetch_L2(addr) — software prefetch to L2 cache (T1 hint) |
| 12 | * _ml_prefetch_NTA(addr) — software prefetch non-temporal (skip cache) |
| 13 | * _ml_pin_to_cpu(cpu) — pin current thread to specific CPU core |
| 14 | * _ml_pin_range(start, end) — pin current thread to CPU range [start, end] |
| 15 | */ |
| 16 | |
| 17 | #include <stdlib.h> |
| 18 | #include <stdint.h> |
| 19 | #include <pthread.h> |
| 20 | #include <sched.h> |
| 21 | #include <xmmintrin.h> /* _mm_prefetch */ |
| 22 | |
| 23 | /* ── Aligned memory allocation (64-byte cache line) ── */ |
| 24 | void* _ml_memalign(size_t sz, size_t align) { |
| 25 | void *ptr = NULL; |
| 26 | if (posix_memalign(&ptr, align, sz) != 0) return NULL; |
| 27 | return ptr; |
| 28 | } |
| 29 | |
| 30 | void _ml_free(void *ptr) { free(ptr); } |
| 31 | |
| 32 | /* ── Software prefetch (x86 SSE intrinsics) ── */ |
| 33 | void _ml_prefetch_L1(const void *addr) { |
| 34 | _mm_prefetch((const char*)addr, _MM_HINT_T0); |
| 35 | } |
| 36 | void _ml_prefetch_L2(const void *addr) { |
| 37 | _mm_prefetch((const char*)addr, _MM_HINT_T1); |
| 38 | } |
| 39 | void _ml_prefetch_NTA(const void *addr) { |
| 40 | _mm_prefetch((const char*)addr, _MM_HINT_NTA); |
| 41 | } |
| 42 | |
| 43 | /* ── Thread/process pinning ── */ |
| 44 | void _ml_pin_to_cpu(int cpu) { |
| 45 | cpu_set_t cpuset; |
| 46 | CPU_ZERO(&cpuset); |
| 47 | CPU_SET(cpu, &cpuset); |
| 48 | pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t), &cpuset); |
| 49 | } |
| 50 | |
| 51 | void _ml_pin_range(int start, int end) { |
| 52 | cpu_set_t cpuset; |
| 53 | CPU_ZERO(&cpuset); |
| 54 | for (int c = start; c <= end; c++) CPU_SET(c, &cpuset); |
| 55 | pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t), &cpuset); |
| 56 | } |
| 57 | |
| 58 | /* ── Process-level pinning: pin all threads to physical cores 0-31 ── */ |
| 59 | void _ml_pin_process(void) { |
| 60 | cpu_set_t cpuset; |
| 61 | CPU_ZERO(&cpuset); |
| 62 | for (int c = 0; c < 32; c++) CPU_SET(c, &cpuset); |
| 63 | sched_setaffinity(0, sizeof(cpu_set_t), &cpuset); |
| 64 | } |