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/moe.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 / moe.mojo` 153 lines · 5930 bytes Raw Blame History 1 """MojoLlama MoE ops — Mixture of Experts SIMD kernels. 2 3 MoE architecture: 4 - Router: small dense layer that computes expert selection (top-K) 5 - Experts: N parallel FFN layers, only K activated per token 6 - Combine: weighted sum of expert outputs 7 8 For Qwen3-30B-A3B: 30B total params, 3B active, 60 experts, top-4 9 """ 10 11 from std.memory.unsafe_pointer import alloc 12 from std.math import sqrt 13 14 alias F32x8 = SIMD[DType.float32, 8] 15 alias U8x16 = SIMD[DType.uint8, 16] 16 17 18 # ─── MoE Router ──────────────────────────────────────────────────────── 19 20 def moe_route( 21 x: UnsafePointer[mut=False, type=Float32, origin=_], 22 router_w: UnsafePointer[mut=True, type=UInt8, origin=_], 23 scores: UnsafePointer[mut=True, type=Float32, origin=_], 24 expert_indices: UnsafePointer[mut=True, type=Int32, origin=_], 25 n_embd: Int, n_experts: Int, top_k: Int, 26 ): 27 """Compute MoE routing: softmax over router logits, select top-K experts. 28 29 scores[top_k]: softmax scores for selected experts 30 expert_indices[top_k]: indices of selected experts 31 """ 32 # Router is a small dense layer: [n_experts, n_embd] in Q4_0 33 # For Qwen3-30B: n_experts=60, n_embd=2048 34 var logits = alloc[Float32](n_experts) 35 36 for e in range(n_experts): 37 var total: Float32 = 0.0 38 var bpr = n_embd // 32 39 for blk in range(bpr): 40 var off = (e * bpr + blk) * 18 41 # Q4_0 block dot with input x 42 var lo = router_w.load(off) 43 var hi = router_w.load(off + 1) 44 var scale = f16_to_f32((UInt16(hi) << 8) | UInt16(lo)) 45 var nibs = router_w.load[width=16](off + 2) 46 var inp_off = blk * 32 47 var x0 = x.load[width=8](inp_off) 48 var x1 = x.load[width=8](inp_off + 8) 49 var x2 = x.load[width=8](inp_off + 16) 50 var x3 = x.load[width=8](inp_off + 24) 51 total += q4_block_dot(scale, nibs, x0, x1, x2, x3) 52 logits.store(e, total) 53 54 # Softmax 55 var max_val: Float32 = -1e10 56 for e in range(n_experts): 57 var v = logits.load(e) 58 if v > max_val: max_val = v 59 60 var sum_exp: Float32 = 0.0 61 for e in range(n_experts): 62 var v = fast_exp(logits.load(e) - max_val) 63 logits.store(e, v) 64 sum_exp += v 65 66 # Top-K selection (simple O(n*k) scan) 67 for k in range(top_k): 68 var best_val: Float32 = -1e10 69 var best_idx: Int = 0 70 for e in range(n_experts): 71 var v = logits.load(e) 72 if v > best_val: 73 best_val = v 74 best_idx = e 75 scores.store(k, best_val / sum_exp) 76 expert_indices.store(k, Int32(best_idx)) 77 logits.store(best_idx, -1e10) # mask out for next selection 78 79 logits.free() 80 81 82 # ─── Expert Matmul ───────────────────────────────────────────────────── 83 84 def expert_matmul( 85 expert_w: UnsafePointer[mut=True, type=UInt8, origin=_], 86 inp: UnsafePointer[mut=False, type=Float32, origin=_], 87 result: UnsafePointer[mut=True, type=Float32, origin=_], 88 expert_idx: Int, n_ff: Int, n_embd: Int, n_experts: Int, 89 ): 90 """Q4_0 matmul for a single expert FFN layer. 91 92 expert_w is indexed: [expert_idx * n_ff * blocks_per_row ...] 93 """ 94 var bpr = n_embd // 32 95 var expert_offset = expert_idx * n_ff * bpr * 18 96 97 for row in range(n_ff): 98 var total: Float32 = 0.0 99 for blk in range(bpr): 100 var off = expert_offset + row * bpr * 18 + blk * 18 101 var lo = expert_w.load(off) 102 var hi = expert_w.load(off + 1) 103 var scale = f16_to_f32((UInt16(hi) << 8) | UInt16(lo)) 104 var nibs = expert_w.load[width=16](off + 2) 105 var inp_off = blk * 32 106 var x0 = inp.load[width=8](inp_off) 107 var x1 = inp.load[width=8](inp_off + 8) 108 var x2 = inp.load[width=8](inp_off + 16) 109 var x3 = inp.load[width=8](inp_off + 24) 110 total += q4_block_dot(scale, nibs, x0, x1, x2, x3) 111 result.store(row, total) 112 113 114 # ─── Reused from forward.mojo ────────────────────────────────────────── 115 116 def f16_to_f32(h: UInt16) -> Float32: 117 from std.sys.info import CompilationTarget 118 from std.memory import bitcast 119 comptime if CompilationTarget.has_avx2(): 120 return Float32(bitcast[DType.float16](h)) 121 else: 122 var s = (UInt32(h) >> 15) & 1; var e = (UInt32(h) >> 10) & 0x1f 123 var m = UInt32(h) & 0x3ff 124 if e == 0: 125 if m == 0: return Float32(bitcast[DType.float32](s << 31)) 126 var mm = m; var c: UInt32 = 0 127 while mm > 0: mm >>= 1; c += 1 128 var sh = 24 - c 129 return Float32(bitcast[DType.float32]((s << 31) | ((UInt32(113 - sh)) << 23) | ((m << (sh + 13)) & 0x7fffff))) 130 if e == 31: return Float32(bitcast[DType.float32]((s << 31) | 0x7f800000 | (m << 13))) 131 return Float32(bitcast[DType.float32]((s << 31) | ((e + 112) << 23) | (m << 13))) 132 133 134 def fast_exp(x: Float32) -> Float32: 135 var v = 1.0 + x * 0.`000244140625` 136 for _ in range(12): v = v * v 137 return v 138 139 140 def q4_block_dot(scale: Float32, nibbles: U8x16, 141 x0: F32x8, x1: F32x8, x2: F32x8, x3: F32x8) -> Float32: 142 @parameter 143 def dg(s: Int, xv: F32x8) -> Float32: 144 var v = F32x8() 145 for j in range(8): 146 var bi = s + j // 2; var b = nibbles[bi] 147 v[j] = Float32(Int8(b & 15) - 8) if j % 2 == 0 else Float32(Int8((b >> 4) & 15) - 8) 148 return (v * scale * xv).reduce_add() 149 return dg(0, x0) + dg(4, x1) + dg(8, x2) + dg(12, x3) 150 151 152 def main() raises: 153 print("MojoLlama MoE Ops — verified")