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/attention.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 / attention.mojo` 182 lines · 5653 bytes Raw Blame History 1 """MojoLlama Attention Kernel — CPU MHA with SIMD softmax. 2 3 Multi-head attention for Llama3: softmax(Q @ K.T / sqrt(d)) @ V. 4 When heap APIs land, integrates with MAX's mha.mojo from: 5 /tmp/modular/max/kernels/src/nn/attention/cpu/mha.mojo 6 7 For now: stack-allocated SIMD vectors and scalar fallbacks for verification. 8 """ 9 10 from std.sys.info import CompilationTarget 11 from std.math import exp 12 13 alias F32x8 = SIMD[DType.float32, 8] 14 15 16 # ─── Softmax (single vector) ──────────────────────────────────────────── 17 18 @always_inline 19 fn softmax_max(x: F32x8) -> Float32: 20 """Horizontal max of 8 float32 values.""" 21 var m = x[0] 22 for i in range(1, 8): 23 if x[i] > m: 24 m = x[i] 25 return m 26 27 @always_inline 28 fn softmax_sum(x: F32x8) -> Float32: 29 """Horizontal sum of 8 float32 values.""" 30 var s: Float32 = 0.0 31 for i in range(8): 32 s += x[i] 33 return s 34 35 @always_inline 36 fn softmax(x: F32x8) -> F32x8: 37 """In-place softmax for one SIMD vector of 8 values. 38 39 Numerically stable: subtracts max before exp. 40 Reference: MAX's softmax.mojo 41 """ 42 var m = softmax_max(x) 43 var e = F32x8() 44 for i in range(8): 45 e[i] = exp(x[i] - m) 46 var s = softmax_sum(e) 47 var inv_s = 1.0 / s 48 for i in range(8): 49 e[i] = e[i] * inv_s 50 return e 51 52 53 # ─── Attention Score (single head, small kv) ──────────────────────────── 54 55 @always_inline 56 fn attn_score(q: F32x8, k: F32x8) -> Float32: 57 """Dot product of query and key: q @ k for one head. 58 59 One step of Q @ K.T for attention scores. 60 Both are 8-dimensional float32 vectors. 61 """ 62 var s: Float32 = 0.0 63 for i in range(8): 64 s += q[i] * k[i] 65 return s 66 67 68 @always_inline 69 fn attn_scores_head(q: F32x8, keys: AnyType, n_keys: Int) -> F32x8: 70 """Compute attention scores for one head against N keys. 71 72 Returns a SIMD vector of scores. For n_keys <= 8, returns F32x8. 73 For larger n_keys, this would be a tiled approach. 74 75 NOTE: AnyType not subscriptable in 0.26.2 — placeholder for pointer-based version. 76 """ 77 # In 0.26.2: can't index AnyType. This becomes pointer-based when APIs land. 78 # For now, the tests use fixed-size hardcoded values. 79 return F32x8() 80 81 82 # ─── Full Attention Step (simplified for verification) ─────────────────── 83 84 @always_inline 85 fn attention_step_single(q: F32x8, k0: F32x8, k1: F32x8, 86 v0: F32x8, v1: F32x8, mask: F32x8) -> F32x8: 87 """Single-head attention: softmax(Q @ K.T / sqrt(d)) @ V 88 89 Simplified for 2 key vectors (n_keys=2), 8-dim hidden. 90 Verifies correctness of the softmax + weighted sum pattern. 91 92 Args: 93 q: query vector (8-dim) 94 k0, k1: key vectors 95 v0, v1: value vectors 96 mask: attention mask (-inf for masked positions) 97 98 Returns: 99 output vector (8-dim) = weighted sum of values 100 """ 101 # Scores: s_i = q @ k_i / sqrt(8) 102 var s0 = attn_score(q, k0) / 2.828 + mask[0] 103 var s1 = attn_score(q, k1) / 2.828 + mask[1] 104 105 # Softmax 106 var m = s0 if s0 > s1 else s1 107 var e0 = exp(s0 - m) 108 var e1 = exp(s1 - m) 109 var inv_sum = 1.0 / (e0 + e1) 110 var a0 = e0 * inv_sum 111 var a1 = e1 * inv_sum 112 113 # Apply: out = Σ a_i * v_i 114 var out = F32x8() 115 for i in range(8): 116 out[i] = a0 * v0[i] + a1 * v1[i] 117 118 return out 119 120 121 # ─── Tests ────────────────────────────────────────────────────────────── 122 123 fn test_softmax(): 124 """Test softmax with known values. 125 126 Input: [2.0, 1.0, 0.0, -1.0, 0.0, 1.0, 2.0, 3.0] 127 Max = 3.0 128 exp([-1, -2, -3, -4, -3, -2, -1, 0]) = [0.368, 0.135, 0.050, 0.018, 0.050, 0.135, 0.368, 1.0] 129 Sum = 2.124 130 """ 131 var x = F32x8(2.0, 1.0, 0.0, -1.0, 0.0, 1.0, 2.0, 3.0) 132 var s = softmax(x) 133 print("softmax([2,1,0,-1,0,1,2,3]):") 134 var total: Float32 = 0.0 135 for i in range(8): 136 print(" [", i, "]:", s[i]) 137 total += s[i] 138 print(" sum:", total, "(expect ~1.0)") 139 if abs(total - 1.0) < 0.01: 140 print(" PASS") 141 else: 142 print(" FAIL") 143 144 145 fn test_attention(): 146 """Test single-head attention with known values. 147 148 q = [1, 0, 0, 0, 0, 0, 0, 0] (query looking at first dim) 149 k0 = [1, 0, 0, 0, 0, 0, 0, 0] (key matching q) 150 k1 = [0, 1, 0, 0, 0, 0, 0, 0] (key not matching q) 151 v0 = [2, 0, 0, 0, 0, 0, 0, 0] (value for first key) 152 v1 = [0, 0, 0, 0, 0, 0, 0, 0] (value for second key) 153 mask = [0, 0] (no masking) 154 155 Expected: s0 = 1/2.828 = 0.354, s1 = 0/2.828 = 0 156 Softmax: ~0.587, ~0.413 157 Output: ~0.587 * v0 + 0.413 * v1 = [1.174, 0, ...] 158 """ 159 var q = F32x8(1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0) 160 var k0 = F32x8(1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0) 161 var k1 = F32x8(0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0) 162 var v0 = F32x8(2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0) 163 var v1 = F32x8(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0) 164 var mask = F32x8(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0) 165 166 var out = attention_step_single(q, k0, k1, v0, v1, mask) 167 print("attention output[0]:", out[0], "(expect ~1.174)") 168 if abs(out[0] - 1.174) < 0.01: 169 print(" PASS") 170 else: 171 print(" FAIL") 172 173 174 fn main(): 175 print("=== MojoLlama Attention Kernel ===") 176 print() 177 178 test_softmax() 179 print() 180 test_attention() 181 print() 182 print("Done.")