MojoLlama
Archived Mojo/MAX quantizer and serving research repository (read-only history)
Brought by drakestapleton
MojoLlama / src / mojollama / kernels / simd_ops.c
| 1 | /* simd_ops.c — AVX2 SIMD vector operations for LLM inference |
| 2 | * |
| 3 | * Provides C-callable SIMD-optimized operations that replace |
| 4 | * numpy vector ops in the Python forward pass: |
| 5 | * - RMS normalization |
| 6 | * - SiLU activation |
| 7 | * - Residual add |
| 8 | * - Softmax (attention scores) |
| 9 | * - RoPE (rotary positional embedding) |
| 10 | * - Weighted V accumulation (attention) |
| 11 | * |
| 12 | * These ops currently take ~6.9ms in Python (28% of total). |
| 13 | * AVX2 SIMD should bring this down to ~1-2ms. |
| 14 | * |
| 15 | * Compile: gcc -O3 -mavx2 -mfma -mf16c -fopenmp -shared -fPIC \ |
| 16 | * -o simd_ops.so simd_ops.c -lm |
| 17 | */ |
| 18 | |
| 19 | #include <stdint.h> |
| 20 | #include <math.h> |
| 21 | #include <string.h> |
| 22 | #include <immintrin.h> |
| 23 | #include <omp.h> |
| 24 | |
| 25 | static inline float hsum_ps(__m256 v) { |
| 26 | __m128 lo = _mm256_castps256_ps128(v); |
| 27 | __m128 hi = _mm256_extractf128_ps(v, 1); |
| 28 | lo = _mm_add_ps(lo, hi); |
| 29 | lo = _mm_hadd_ps(lo, lo); |
| 30 | lo = _mm_hadd_ps(lo, lo); |
| 31 | return _mm_cvtss_f32(lo); |
| 32 | } |
| 33 | |
| 34 | /* RMS normalization: out = x * weight / sqrt(mean(x^2) + eps) */ |
| 35 | void rms_norm(float *restrict out, const float *restrict x, |
| 36 | const float *restrict weight, int n, float eps) { |
| 37 | __m256 sum_sq = _mm256_setzero_ps(); |
| 38 | int i; |
| 39 | for (i = 0; i <= n - 8; i += 8) { |
| 40 | __m256 v = _mm256_loadu_ps(x + i); |
| 41 | sum_sq = _mm256_fmadd_ps(v, v, sum_sq); |
| 42 | } |
| 43 | float ss = hsum_ps(sum_sq); |
| 44 | for (; i < n; i++) ss += x[i] * x[i]; |
| 45 | float inv_rms = 1.0f / sqrtf(ss / n + eps); |
| 46 | __m256 inv_v = _mm256_set1_ps(inv_rms); |
| 47 | for (i = 0; i <= n - 8; i += 8) { |
| 48 | __m256 v = _mm256_loadu_ps(x + i); |
| 49 | __m256 w = _mm256_loadu_ps(weight + i); |
| 50 | _mm256_storeu_ps(out + i, _mm256_mul_ps(_mm256_mul_ps(v, inv_v), w)); |
| 51 | } |
| 52 | for (; i < n; i++) out[i] = x[i] * inv_rms * weight[i]; |
| 53 | } |
| 54 | |
| 55 | /* SiLU activation: out = x * sigmoid(x), in-place if out == x */ |
| 56 | void silu(float *restrict out, const float *restrict x, int n) { |
| 57 | /* Use tanh approximation for fast sigmoid: sig(x) ≈ 0.5 + 0.5*tanh(x/2) */ |
| 58 | int i; |
| 59 | for (i = 0; i <= n - 8; i += 8) { |
| 60 | __m256 v = _mm256_loadu_ps(x + i); |
| 61 | __m256 half_v = _mm256_mul_ps(v, _mm256_set1_ps(0.5f)); |
| 62 | /* tanh(x) ≈ x*(27+x²)/(27+9x²) — Pade approximation, max error ~0.003 */ |
| 63 | __m256 v2 = _mm256_mul_ps(half_v, half_v); |
| 64 | __m256 num = _mm256_mul_ps(half_v, _mm256_add_ps(_mm256_set1_ps(27.0f), v2)); |
| 65 | __m256 den = _mm256_add_ps(_mm256_set1_ps(27.0f), _mm256_mul_ps(_mm256_set1_ps(9.0f), v2)); |
| 66 | __m256 tanh_v = _mm256_div_ps(num, den); |
| 67 | __m256 sigmoid = _mm256_add_ps(_mm256_set1_ps(0.5f), _mm256_mul_ps(_mm256_set1_ps(0.5f), tanh_v)); |
| 68 | _mm256_storeu_ps(out + i, _mm256_mul_ps(v, sigmoid)); |
| 69 | } |
| 70 | for (; i < n; i++) { |
| 71 | float sig = 1.0f / (1.0f + expf(-x[i])); |
| 72 | out[i] = x[i] * sig; |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | /* Residual add: out = a + b */ |
| 77 | void residual_add(float *restrict out, const float *restrict a, |
| 78 | const float *restrict b, int n) { |
| 79 | int i; |
| 80 | for (i = 0; i <= n - 8; i += 8) { |
| 81 | _mm256_storeu_ps(out + i, _mm256_add_ps(_mm256_loadu_ps(a + i), |
| 82 | _mm256_loadu_ps(b + i))); |
| 83 | } |
| 84 | for (; i < n; i++) out[i] = a[i] + b[i]; |
| 85 | } |
| 86 | |
| 87 | /* Softmax in-place: x[i] = exp(x[i]) / sum(exp(x[j])) */ |
| 88 | void softmax(float *restrict x, int n) { |
| 89 | float max_val = -INFINITY; |
| 90 | for (int i = 0; i < n; i++) |
| 91 | if (x[i] > max_val) max_val = x[i]; |
| 92 | |
| 93 | __m256 max_v = _mm256_set1_ps(max_val); |
| 94 | __m256 sum_v = _mm256_setzero_ps(); |
| 95 | int i; |
| 96 | for (i = 0; i <= n - 8; i += 8) { |
| 97 | __m256 v = _mm256_sub_ps(_mm256_loadu_ps(x + i), max_v); |
| 98 | /* exp using exp2: exp(x) = exp2(x/log2(e)) */ |
| 99 | /* Faster: use the fact that exp(x) ≈ 2^(x*1.4427) for small x */ |
| 100 | /* Actually, just use scalar expf — softmax n is small (≤2048) */ |
| 101 | for (int j = 0; j < 8; j++) { |
| 102 | x[i+j] = expf(x[i+j] - max_val); |
| 103 | sum_v = _mm256_add_ps(sum_v, _mm256_set1_ps(x[i+j])); |
| 104 | } |
| 105 | } |
| 106 | float sum = hsum_ps(sum_v); |
| 107 | for (; i < n; i++) { |
| 108 | x[i] = expf(x[i] - max_val); |
| 109 | sum += x[i]; |
| 110 | } |
| 111 | float inv_sum = 1.0f / sum; |
| 112 | __m256 inv_v = _mm256_set1_ps(inv_sum); |
| 113 | for (i = 0; i <= n - 8; i += 8) { |
| 114 | _mm256_storeu_ps(x + i, _mm256_mul_ps(_mm256_loadu_ps(x + i), inv_v)); |
| 115 | } |
| 116 | for (; i < n; i++) x[i] *= inv_sum; |
| 117 | } |
| 118 | |
| 119 | /* RoPE: apply rotary positional embedding to Q and K |
| 120 | * q: [n_heads * head_dim], k: [n_kv_heads * head_dim] |
| 121 | */ |
| 122 | void apply_rope(float *restrict q, float *restrict k, |
| 123 | int n_heads, int n_kv_heads, int head_dim, |
| 124 | int pos, float rope_base) { |
| 125 | for (int h = 0; h < n_heads; h++) { |
| 126 | for (int d = 0; d < head_dim; d += 2) { |
| 127 | float freq = 1.0f / powf(rope_base, (float)(d / 2) / (head_dim / 2)); |
| 128 | float angle = pos * freq; |
| 129 | float cos_a = cosf(angle); |
| 130 | float sin_a = sinf(angle); |
| 131 | int idx = h * head_dim + d; |
| 132 | float q0 = q[idx], q1 = q[idx + 1]; |
| 133 | q[idx] = q0 * cos_a - q1 * sin_a; |
| 134 | q[idx + 1] = q0 * sin_a + q1 * cos_a; |
| 135 | } |
| 136 | } |
| 137 | for (int h = 0; h < n_kv_heads; h++) { |
| 138 | for (int d = 0; d < head_dim; d += 2) { |
| 139 | float freq = 1.0f / powf(rope_base, (float)(d / 2) / (head_dim / 2)); |
| 140 | float angle = pos * freq; |
| 141 | float cos_a = cosf(angle); |
| 142 | float sin_a = sinf(angle); |
| 143 | int idx = h * head_dim + d; |
| 144 | float k0 = k[idx], k1 = k[idx + 1]; |
| 145 | k[idx] = k0 * cos_a - k1 * sin_a; |
| 146 | k[idx + 1] = k0 * sin_a + k1 * cos_a; |
| 147 | } |
| 148 | } |
| 149 | } |
| 150 | |
| 151 | /* Attention: compute scores = Q @ K^T / sqrt(d), softmax, then V * scores |
| 152 | * q: [n_heads, head_dim] |
| 153 | * k_cache: [n_past+1, n_kv_heads, head_dim] |
| 154 | * v_cache: [n_past+1, n_kv_heads, head_dim] |
| 155 | * out: [n_heads, head_dim] |
| 156 | * This is a batched operation for all heads. |
| 157 | * Uses GQA: each Q head maps to kv_h = h * n_kv_heads / n_heads |
| 158 | */ |
| 159 | void attention_forward( |
| 160 | const float *restrict q, /* [n_heads * head_dim] */ |
| 161 | const float *restrict k_cache, /* [max_seq * n_kv_heads * head_dim] */ |
| 162 | const float *restrict v_cache, /* [max_seq * n_kv_heads * head_dim] */ |
| 163 | float *restrict out, /* [n_heads * head_dim] */ |
| 164 | int n_heads, int n_kv_heads, int head_dim, |
| 165 | int n_past, int max_seq) { |
| 166 | |
| 167 | float scale = 1.0f / sqrtf((float)head_dim); |
| 168 | |
| 169 | /* Allocate temp buffer for attention scores on stack or heap */ |
| 170 | /* n_past+1 scores per head, at most 4096 */ |
| 171 | float scores[4096]; /* VLA would be better but C99 VLA on stack */ |
| 172 | int seq_len = n_past + 1; |
| 173 | |
| 174 | for (int h = 0; h < n_heads; h++) { |
| 175 | int kv_h = h * n_kv_heads / n_heads; |
| 176 | const float *q_h = q + h * head_dim; |
| 177 | |
| 178 | /* Compute Q @ K^T */ |
| 179 | for (int t = 0; t < seq_len; t++) { |
| 180 | const float *k_t = k_cache + t * n_kv_heads * head_dim + kv_h * head_dim; |
| 181 | __m256 dot_v = _mm256_setzero_ps(); |
| 182 | for (int d = 0; d <= head_dim - 8; d += 8) { |
| 183 | __m256 qv = _mm256_loadu_ps(q_h + d); |
| 184 | __m256 kv = _mm256_loadu_ps(k_t + d); |
| 185 | dot_v = _mm256_fmadd_ps(qv, kv, dot_v); |
| 186 | } |
| 187 | scores[t] = hsum_ps(dot_v) * scale; |
| 188 | } |
| 189 | |
| 190 | /* Softmax */ |
| 191 | softmax(scores, seq_len); |
| 192 | |
| 193 | /* Weighted V accumulation */ |
| 194 | float *out_h = out + h * head_dim; |
| 195 | memset(out_h, 0, head_dim * sizeof(float)); |
| 196 | for (int t = 0; t < seq_len; t++) { |
| 197 | const float *v_t = v_cache + t * n_kv_heads * head_dim + kv_h * head_dim; |
| 198 | __m256 sw = _mm256_set1_ps(scores[t]); |
| 199 | for (int d = 0; d <= head_dim - 8; d += 8) { |
| 200 | __m256 vd = _mm256_loadu_ps(v_t + d); |
| 201 | __m256 acc = _mm256_loadu_ps(out_h + d); |
| 202 | _mm256_storeu_ps(out_h + d, _mm256_fmadd_ps(sw, vd, acc)); |
| 203 | } |
| 204 | } |
| 205 | } |
| 206 | } |
| 207 | |
| 208 | /* Copy KV values into cache */ |
| 209 | void kv_cache_update(float *restrict k_cache, float *restrict v_cache, |
| 210 | const float *restrict k_new, const float *restrict v_new, |
| 211 | int layer, int n_past, int max_seq, |
| 212 | int n_kv_heads, int head_dim) { |
| 213 | int offset = n_past * n_kv_heads * head_dim; |
| 214 | memcpy(k_cache + offset, k_new, n_kv_heads * head_dim * sizeof(float)); |
| 215 | memcpy(v_cache + offset, v_new, n_kv_heads * head_dim * sizeof(float)); |
| 216 | } |
| 217 | |
| 218 | /* Set OMP threads */ |
| 219 | void set_num_threads(int n) { omp_set_num_threads(n); } |