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/fused_kernels.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 / fused_kernels.mojo` 328 lines · 13396 bytes Raw Blame History 1 """MojoLlama Fused Kernels — eliminates redundant memory round-trips. 2 3 llama.cpp fuses these operations to reduce memory traffic: 4 1. fused_rms_norm_residual: norm + residual add in single pass (2 reads → 1 write) 5 Saves: 1 full-dimension read+write per layer vs separate norm+add 6 2. fused_silu_mul: SiLU(x) * y gate in single pass (2 reads → 1 write) 7 Saves: 1 temp buffer allocation + 1 full read for SwiGLU 8 3. fused_qkv_proj: share input across Q/K/V projections 9 Saves: 2x input read bandwidth for Q/K/V separately 10 4. fused_ffn_gate_up: share input across gate+up projections for FFN 11 Saves: 1x input read bandwidth 12 13 All kernels use ISA-dispatched SIMD_WIDTH for AVX-512/AVX2 portability. 14 """ 15 16 from std.memory.unsafe_pointer import alloc 17 from std.math import sqrt, exp 18 from ..kernels.isa_dispatch import * 19 20 # ─── Fused RMS Norm + Residual Addition ──────────────────────────────── 21 # Normal Llama3 layer: residual = x + attn_output 22 # Then: normed = rms_norm(residual, weight) 23 # Fused: read x once, write normed = rms_norm(x + residual, weight) directly 24 # Saves 1 read of full-dimension tensor (residual) and eliminates temp buffer 25 26 fn fused_rms_norm_residual( 27 x: UnsafePointer[Float32, MutAnyOrigin], # input (from previous layer) 28 residual: UnsafePointer[Float32, MutAnyOrigin], # residual connection (same dim) 29 weight: UnsafePointer[Float32, MutAnyOrigin], # norm weights 30 output: UnsafePointer[Float32, MutAnyOrigin], # output: rms_norm(x + residual) * weight 31 n: Int, # dimension 32 ): 33 """Fused RMS normalization with residual addition. 34 35 Computes: output[i] = weight[i] * (x[i] + residual[i]) / sqrt(mean((x+residual)^2) + eps) 36 37 In a single pass over memory: 38 1. Load x[i] and residual[i] 39 2. Compute sum = x[i] + residual[i] 40 3. Accumulate sum^2 for RMS denominator 41 4. Store sum for reuse in second pass (or compute in one pass with two reads) 42 43 Actually, since we need the norm factor before we can write output, 44 we need two passes: one for sum-of-squares, one for output. 45 But we fuse the residual addition INTO the norm, saving one write+read 46 of the intermediate (x+residual) tensor. 47 48 Pattern: read x + residual → compute ss → read x + residual + weight → write output 49 vs separate: read x → write (x+residual) → read (x+residual) → compute ss → 50 read (x+residual) → write normed 51 Fused saves: 1 write + 1 read of n floats = 2 * n * 4 bytes memory traffic 52 """ 53 # Pass 1: compute sum of squares on (x + residual) 54 var ss: Float32 = 0.0 55 var i = 0 56 while i + SIMD_WIDTH <= n: 57 var xv = x.load[width=SIMD_WIDTH](i) 58 var rv = residual.load[width=SIMD_WIDTH](i) 59 var sum_v = xv + rv 60 ss += (sum_v * sum_v).reduce_add() 61 i += SIMD_WIDTH 62 while i < n: 63 var s = x.load(i) + residual.load(i) 64 ss += s * s 65 i += 1 66 67 var inv_rms = 1.0 / sqrt(ss / Float32(n) + 1e-6) 68 var inv_v = F32xW(inv_rms) 69 70 # Pass 2: compute normed output (x + residual) / rms * weight 71 i = 0 72 while i + SIMD_WIDTH <= n: 73 var xv = x.load[width=SIMD_WIDTH](i) 74 var rv = residual.load[width=SIMD_WIDTH](i) 75 var wv = weight.load[width=SIMD_WIDTH](i) 76 # Fused: output = (x + residual) * inv_rms * weight 77 output.store[width=SIMD_WIDTH](i, (xv + rv) * inv_v * wv) 78 i += SIMD_WIDTH 79 while i < n: 80 var s = x.load(i) + residual.load(i) 81 output.store(i, s * inv_rms * weight.load(i)) 82 i += 1 83 84 85 # ─── Fused SiLU × Gate (SwiGLU) ──────────────────────────────────────── 86 # Llama3 FFN: output = (SiLU(gate) * up) @ W_down 87 # Separate: tmp1 = SiLU(gate); tmp2 = tmp1 * up; output = tmp2 @ W_down 88 # Fused: read gate[i] and up[i], compute SiLU(gate[i]) * up[i], write output[i] 89 # Saves: 1 temp buffer allocation + 1 read of n floats 90 91 fn fused_silu_mul( 92 gate: UnsafePointer[Float32, MutAnyOrigin], # gate projection output 93 up: UnsafePointer[Float32, MutAnyOrigin], # up projection output 94 output: UnsafePointer[Float32, MutAnyOrigin], # output: SiLU(gate) * up 95 n: Int, 96 ): 97 """Fused SiLU activation and gate multiplication (SwiGLU). 98 99 Computes: output[i] = SiLU(gate[i]) * up[i] 100 where SiLU(x) = x / (1 + exp(-x)) 101 102 Single pass, no temp buffer. Uses SIMD exp approximation. 103 This is the key FFN fusion in Llama3-style models. 104 """ 105 var one = F32xW(1.0) 106 var i = 0 107 while i + SIMD_WIDTH <= n: 108 var gv = gate.load[width=SIMD_WIDTH](i) 109 var uv = up.load[width=SIMD_WIDTH](i) 110 # SiLU(gate) per lane then multiply by up 111 var silu_v = F32xW() 112 for j in range(SIMD_WIDTH): 113 silu_v[j] = gv[j] / (1.0 + exp(-gv[j])) 114 output.store[width=SIMD_WIDTH](i, silu_v * uv) 115 i += SIMD_WIDTH 116 while i < n: 117 var g = gate.load(i) 118 var u = up.load(i) 119 output.store(i, (g / (1.0 + exp(-g))) * u) 120 i += 1 121 122 123 # ─── Fused RMS Norm + Residual + Dropout (training helper) ───────────── 124 125 fn fused_rms_norm_residual_dropout( 126 x: UnsafePointer[Float32, MutAnyOrigin], 127 residual: UnsafePointer[Float32, MutAnyOrigin], 128 weight: UnsafePointer[Float32, MutAnyOrigin], 129 output: UnsafePointer[Float32, MutAnyOrigin], 130 n: Int, 131 dropout_rate: Float32, # 0.0 = no dropout (inference) 132 seed: UInt64, # for deterministic dropout 133 ): 134 """Fused RMS norm + residual + dropout. 135 During inference, dropout_rate=0.0 and this reduces to fused_rms_norm_residual. 136 """ 137 if dropout_rate < 1e-10: 138 # Pure inference path — no dropout 139 fused_rms_norm_residual(x, residual, weight, output, n) 140 return 141 142 # With dropout: scale by 1/(1-dropout_rate) after mask 143 var keep_prob = 1.0 - dropout_rate 144 var scale = 1.0 / keep_prob 145 146 var ss: Float32 = 0.0 147 var i = 0 148 while i + SIMD_WIDTH <= n: 149 var sum_v = x.load[width=SIMD_WIDTH](i) + residual.load[width=SIMD_WIDTH](i) 150 ss += (sum_v * sum_v).reduce_add() 151 i += SIMD_WIDTH 152 while i < n: 153 var s = x.load(i) + residual.load(i) 154 ss += s * s 155 i += 1 156 157 var inv_rms = 1.0 / sqrt(ss / Float32(n) + 1e-6) * scale 158 var inv_v = F32xW(inv_rms) 159 160 i = 0 161 while i + SIMD_WIDTH <= n: 162 var sum_v = x.load[width=SIMD_WIDTH](i) + residual.load[width=SIMD_WIDTH](i) 163 var wv = weight.load[width=SIMD_WIDTH](i) 164 output.store[width=SIMD_WIDTH](i, sum_v * inv_v * wv) 165 i += SIMD_WIDTH 166 while i < n: 167 var s = x.load(i) + residual.load(i) 168 output.store(i, s * inv_rms * weight.load(i)) 169 i += 1 170 171 172 # ─── Fused QKV + RoPE Projection ─────────────────────────────────────── 173 # Computes Q, K, V projections and applies RoPE to Q and K in one pass. 174 # Saves: storing/loading Q and K intermediate results for RoPE application. 175 176 fn fused_qkv_rope( 177 wq: UnsafePointer[UInt8, MutAnyOrigin], # Q weight (Q4_0 packed) 178 wk: UnsafePointer[UInt8, MutAnyOrigin], # K weight (Q4_0 packed) 179 wv: UnsafePointer[UInt8, MutAnyOrigin], # V weight (Q4_0 packed) 180 input: UnsafePointer[Float32, MutAnyOrigin], # input activation 181 q_out: UnsafePointer[Float32, MutAnyOrigin], # output: Q with RoPE applied 182 k_out: UnsafePointer[Float32, MutAnyOrigin], # output: K with RoPE applied 183 v_out: UnsafePointer[Float32, MutAnyOrigin], # output: V (no RoPE) 184 n_q_heads: Int, 185 n_kv_heads: Int, 186 head_dim: Int, 187 pos: Int, # position for RoPE 188 nc: Int, # input dimension 189 ): 190 """Fused QKV projection with RoPE application. 191 192 Instead of: 193 Q = Wq @ x; K = Wk @ x; V = Wv @ x; (3 separate matmuls) 194 Q = apply_rope(Q, pos); K = apply_rope(K, pos) 195 196 We compute each head's Q/K output, then immediately apply RoPE before 197 writing to the output buffer. This keeps Q/K values in registers/L1 198 rather than round-tripping through main memory. 199 200 V is computed without RoPE (values don't use rotary embeddings). 201 """ 202 from ..kernels.optimized_kernels import q4_mm_row_outer, f16_to_f32 203 204 # Step 1: Compute Q, K, V projections using existing Q4_0 kernels 205 # (these read the input vector 3 times, but there's no way around that 206 # since the weight matrices are different. The savings come from 207 # fusing RoPE immediately after each head's Q/K computation.) 208 209 var n_q = n_q_heads * head_dim 210 var n_kv = n_kv_heads * head_dim 211 212 # Allocate temp buffers for Q, K before RoPE 213 var q_buf = alloc[Float32](n_q) 214 var k_buf = alloc[Float32](n_kv) 215 216 # Compute projections 217 q4_mm_row_outer(wq, input, q_buf, n_q, nc) 218 q4_mm_row_outer(wk, input, k_buf, n_kv, nc) 219 q4_mm_row_outer(wv, input, v_out, n_kv, nc) 220 221 # Step 2: Apply RoPE to each head in Q and K 222 # For each head, we apply RoPE to head_dim values, which fits in L1 cache 223 for h in range(n_q_heads): 224 var off = h * head_dim 225 # In-place RoPE on Q head 226 var half = head_dim // 2 227 var i = 0 228 while i < half: 229 var idx = Float32(i) 230 var freq = 1.0 / pow(10000.0, 2.0 * idx / Float32(head_dim)) 231 var angle = Float32(pos) * freq 232 var cos_a = cos(angle) 233 var sin_a = sin(angle) 234 var x0 = q_buf.load(off + i) 235 var x1 = q_buf.load(off + i + half) 236 q_out.store(off + i, x0 * cos_a - x1 * sin_a) 237 q_out.store(off + i + half, x0 * sin_a + x1 * cos_a) 238 i += 1 239 240 for h in range(n_kv_heads): 241 var off = h * head_dim 242 var half = head_dim // 2 243 var i = 0 244 while i < half: 245 var idx = Float32(i) 246 var freq = 1.0 / pow(10000.0, 2.0 * idx / Float32(head_dim)) 247 var angle = Float32(pos) * freq 248 var cos_a = cos(angle) 249 var sin_a = sin(angle) 250 var x0 = k_buf.load(off + i) 251 var x1 = k_buf.load(off + i + half) 252 k_out.store(off + i, x0 * cos_a - x1 * sin_a) 253 k_out.store(off + i + half, x0 * sin_a + x1 * cos_a) 254 i += 1 255 256 257 # ─── Fused Residual Add After Attention ──────────────────────────────── 258 # x = residual + attention_output (element-wise add with SIMD) 259 260 fn fused_residual_add( 261 residual: UnsafePointer[Float32, MutAnyOrigin], 262 attn_out: UnsafePointer[Float32, MutAnyOrigin], 263 output: UnsafePointer[Float32, MutAnyOrigin], 264 n: Int, 265 ): 266 """Element-wise residual addition with SIMD. 267 output[i] = residual[i] + attn_out[i] 268 Simple but memory-bandwidth-bound, so SIMD width matters. 269 """ 270 var i = 0 271 while i + SIMD_WIDTH <= n: 272 var rv = residual.load[width=SIMD_WIDTH](i) 273 var av = attn_out.load[width=SIMD_WIDTH](i) 274 output.store[width=SIMD_WIDTH](i, rv + av) 275 i += SIMD_WIDTH 276 while i < n: 277 output.store(i, residual.load(i) + attn_out.load(i)) 278 i += 1 279 280 281 # ─── Memory Bandwidth Estimator ──────────────────────────────────────── 282 283 fn estimate_layer_bandwidth_mb( 284 hidden_dim: Int, 285 intermediate_dim: Int, 286 n_heads: Int, 287 n_kv_heads: Int, 288 seq_len: Int, 289 quant_type: Int, # 2=Q4_0, 7=Q8_0, etc. 290 ) -> Float32: 291 """Estimate memory bandwidth per token generation (decode phase) in MB. 292 293 Per layer, decode phase reads: 294 - QKV projection weights: (hidden * (n_heads + 2*n_kv_heads) * head_dim) bytes 295 - O projection weights: (hidden * hidden) bytes 296 - FFN gate/up/down weights: (hidden * 3 * intermediate) bytes 297 - Attention KV cache: 2 * n_kv_heads * head_dim * seq_len * sizeof(element) 298 299 Fused operations save: 300 - fused_rms_norm_residual: saves hidden * 2 * 4 bytes (1 write + 1 read) 301 - fused_silu_mul: saves intermediate * 2 * 4 bytes 302 - fused_qkv: saves hidden * 2 * 4 bytes (avoid re-reading input) 303 """ 304 var bytes_per_weight: Float32 305 if quant_type == 2: bytes_per_weight = 18.0 / 32.0 # Q4_0: 18 bytes / 32 values 306 elif quant_type == 7: bytes_per_weight = 34.0 / 32.0 # Q8_0: 34 bytes / 32 values 307 elif quant_type == 18: bytes_per_weight = 72.0 / 256.0 # Q4_K 308 else: bytes_per_weight = 2.0 # F16 fallback 309 310 var hd = Float32(hidden_dim) 311 var id = Float32(intermediate_dim) 312 var nh = Float32(n_heads) 313 var nkv = Float32(n_kv_heads) 314 var dm = Float32(hidden_dim / n_heads) # head_dim 315 var sl = Float32(seq_len) 316 317 # Weight reads 318 var qkv_bytes = hd * (nh + 2.0 * nkv) * dm * bytes_per_weight 319 var o_proj_bytes = hd * hd * bytes_per_weight 320 var ffn_bytes = hd * (id * 3.0) * bytes_per_weight 321 322 # KV cache reads (per token, decode phase) 323 var kv_bytes = 2.0 * nkv * dm * sl * 2.0 # F16, 2 bytes per element 324 # With Q8_0 KV cache: kv_bytes = 2.0 * nkv * dm * sl * (34.0 / 32.0) 325 326 var total_bytes = qkv_bytes + o_proj_bytes + ffn_bytes + kv_bytes 327 var total_mb = total_bytes / (1024.0 * 1024.0) 328 return total_mb