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/mojo_engine/mojollama_engine.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 / mojo_engine / mojollama_engine.mojo` 237 lines · 10627 bytes Raw Blame History 1 # MojoLlama Engine — Complete Forward Pass 2 # Pure Mojo inference engine for GPT-OSS and compatible MoE models. 3 # Loads quantized weights (Q5_0, Q8_0, MXFP4, Q4_K) and runs full 4 # transformer forward pass: embedding → L×layer → output projection. 5 # 6 # BUILD (Mojo 1.0.0b1+): 7 # mojo build -o mojollama mojollama_engine.mojo 8 # 9 # DESIGN: 10 # - @extern(abi("C")) for C bridge (read_helpers.c) 11 # - All List-heavy code in main() to avoid compiler codegen crash 12 # (@extern + List-returning functions segfault in 1.0.0b1) 13 # - Copy-on-write semantics: no in-place list mutation 14 # - Uses pre-dumped weight files from dump_weights.py 15 # 16 # KERNEL REFERENCE: 17 # Q5_0 (qt=6): [d:2B f16][qh:4B][ql:16B] = 22B/32vals 18 # Q8_0 (qt=8): [d:2B f16][qs:32B i8] = 34B/32vals 19 # MXFP4 (qt=39): [nibbles:16B][e8m0:1B] = 17B/32vals 20 # Q4_K (qt=12): K-quant 144B/256vals (uses C dequant from quant_kernels_omp.c) 21 from std.prelude import * 22 from std import time 23 24 # ═══════════════════════════════════════════════════════════ 25 # C BRIDGE (read_helpers.c) 26 # ═══════════════════════════════════════════════════════════ 27 @extern("read_u8") 28 def _u8(a: Int64) abi("C") -> UInt8: ... 29 @extern("read_f32") 30 def _f32(a: Int64) abi("C") -> Float32: ... 31 @extern("read_i32") 32 def _ri32(a: Int64) abi("C") -> Int32: ... 33 @extern("free_buf") 34 def _fr(p: Int64) abi("C"): ... 35 36 # ── File I/O workaround: read via Python FFI ── 37 # WHY: @extern(abi("C")) String→const char* passthrough is broken in 1.0.0b1. 38 # Python's numpy reads files correctly. This is a bridge until the bug is fixed. 39 from std.python import Python 40 41 def _load_f32s(path: String, n: Int) raises -> List[Float32]: 42 var np = Python.import_module("numpy") 43 var arr = np.fromfile(Python.str(path), np.float32) 44 var out = List[Float32](capacity=n) 45 for i in range(n): 46 out.append(Float32(arr[i].__float__())) 47 return out^ 48 49 def _load_u8s(path: String) raises -> List[UInt8]: 50 var np = Python.import_module("numpy") 51 var arr = np.fromfile(Python.str(path), np.uint8) 52 var out = List[UInt8](capacity=len(arr)) 53 for i in range(len(arr)): 54 out.append(UInt8(arr[i].__index__())) 55 return out^ 56 57 def _load_i32(path: String) raises -> Int: 58 var np = Python.import_module("numpy") 59 var arr = np.fromfile(Python.str(path), np.int32) 60 return Int(arr[0].__index__()) 61 62 # ═══════════════════════════════════════════════════════════ 63 # FLOAT HELPERS (scalar only, safe at module level) 64 # ═══════════════════════════════════════════════════════════ 65 def f16_to_f32(h: UInt16) -> Float32: 66 var s = UInt32(h >> 15); var e = UInt32((h >> 10) & 0x1F) 67 var m = UInt32(h & 0x3FF) 68 if e == 0: 69 if m == 0: return 0.0 70 return Float32(Float64(m) * 5.`960464477539063e`-8) 71 if e == 31: return 0.0 72 var r = Float32(m | 0x400); var ei = Int(e) - 25 73 if ei >= 0: 74 for _ in range(ei): r *= 2.0 75 else: 76 for _ in range(-ei): r *= 0.5 77 return -r if s != 0 else r 78 79 def exp_f32(x: Float32) -> Float32: 80 return Float32(Float64(2.`718281828459045`) ** Float64(x)) 81 82 def sqrt_f32(x: Float32) -> Float32: 83 return Float32(Float64(x) ** 0.5) 84 85 # ═══════════════════════════════════════════════════════════ 86 # BLOCK SIZES 87 # ═══════════════════════════════════════════════════════════ 88 comptime B5: Int = 22 # Q5_0 89 comptime B8: Int = 34 # Q8_0 90 comptime B4: Int = 17 # MXFP4 91 92 # ═══════════════════════════════════════════════════════════ 93 # LIST HELPERS (copy-on-write, no in-place mutation) 94 # ═══════════════════════════════════════════════════════════ 95 def add_lists(a: List[Float32], b: List[Float32], n: Int) -> List[Float32]: 96 var o = List[Float32]() 97 for i in range(n): o.append(a[i] + b[i]) 98 return o^ 99 100 def mul_lists(a: List[Float32], b: List[Float32], n: Int) -> List[Float32]: 101 var o = List[Float32]() 102 for i in range(n): o.append(a[i] * b[i]) 103 return o^ 104 105 def scale_list(x: List[Float32], s: Float32, n: Int) -> List[Float32]: 106 var o = List[Float32]() 107 for i in range(n): o.append(x[i] * s) 108 return o^ 109 110 def rms_norm(x: List[Float32], w: List[Float32], n: Int, e: Float32) -> List[Float32]: 111 var ss: Float32 = 0.0 112 for i in range(n): ss += x[i] * x[i] 113 var r = sqrt_f32(ss / Float32(n) + e) 114 var o = List[Float32](capacity=n) 115 for i in range(n): o.append(x[i] / r * w[i]) 116 return o^ 117 118 def softmax(x: List[Float32]) -> List[Float32]: 119 var n = len(x); var mx = x[0] 120 for i in range(1, n): 121 if x[i] > mx: mx = x[i] 122 var s: Float32 = 0.0; var ex = List[Float32]() 123 for i in range(n): 124 var ev = exp_f32(x[i] - mx) 125 ex.append(ev); s += ev 126 var iv = 1.0 / s; var o = List[Float32]() 127 for i in range(n): o.append(ex[i] * iv) 128 return o^ 129 130 # ═══════════════════════════════════════════════════════════ 131 # QUANTIZED MATMUL KERNELS (inline, append to mut dst) 132 # ═══════════════════════════════════════════════════════════ 133 def matmul_q5_0(mut dst: List[Float32], w: Int64, x: List[Float32], nr: Int, nc: Int): 134 var bp = nc // 32 135 for r in range(nr): 136 var a: Float32 = 0.0; var ro = r * bp * B5 137 for blk in range(bp): 138 var wo = ro + blk * B5 139 var lo = UInt16(_u8(w + Int64(wo))) 140 var hi = UInt16(_u8(w + Int64(wo + 1))) 141 var d = f16_to_f32(lo | (hi << 8)) 142 for j in range(16): 143 var p = _u8(w + Int64(wo + 6 + j)) 144 var qh = _u8(w + Int64(wo + 2 + (j // 4))) 145 var hs = 2 * (UInt8(j % 4)) 146 var h0 = Int32((qh >> hs) & UInt8(1)) 147 var h1 = Int32((qh >> (hs + UInt8(1))) & UInt8(1)) 148 var nlo = Int32(p & UInt8(0x0F)); var nhi = Int32(p >> 4) 149 var v0 = nlo + h0 * 16; var v1 = nhi + h1 * 16 150 if v0 > 15: v0 -= 32 151 if v1 > 15: v1 -= 32 152 a += Float32(v0) * x[blk * 32 + j * 2] * d 153 a += Float32(v1) * x[blk * 32 + j * 2 + 1] * d 154 dst.append(a) 155 156 def matmul_q8_0(mut dst: List[Float32], w: Int64, x: List[Float32], nr: Int, nc: Int): 157 var bp = nc // 32 158 for r in range(nr): 159 var a: Float32 = 0.0; var ro = r * bp * B8 160 for blk in range(bp): 161 var wo = ro + blk * B8 162 var lo = UInt16(_u8(w + Int64(wo))) 163 var hi = UInt16(_u8(w + Int64(wo + 1))) 164 var d = f16_to_f32(lo | (hi << 8)) 165 for j in range(32): 166 var q = Int32(_u8(w + Int64(wo + 2 + j))) 167 if q > 127: q -= 256 168 a += Float32(q) * x[blk * 32 + j] * d 169 dst.append(a) 170 171 def matmul_mxfp4(mut dst: List[Float32], w: Int64, x: List[Float32], nr: Int, nc: Int): 172 var bp = nc // 32 173 for r in range(nr): 174 var a: Float32 = 0.0; var ro = r * bp * B4 175 for blk in range(bp): 176 var wo = ro + blk * B4 177 var eb = _u8(w + Int64(wo + 16)) 178 var sf: Float32 = 0.0 179 if eb != 0: 180 if eb < 255: 181 var ei = Int(eb) - 127; sf = 1.0 182 if ei >= 0: 183 for _ in range(ei): sf *= 2.0 184 else: 185 for _ in range(-ei): sf *= 0.5 186 if sf > 1e20: sf = 1e20 187 else: sf = 1e20 188 var ai: Int32 = 0 189 for j in range(16): 190 var p = _u8(w + Int64(wo + j)) 191 var lo = Int32(p & UInt8(0x0F)) 192 if lo > 7: lo -= 16 193 var hi = Int32(p >> 4) 194 if hi > 7: hi -= 16 195 ai += lo * Int32(x[blk * 32 + j * 2]) + hi * Int32(x[blk * 32 + j * 2 + 1]) 196 a += Float32(ai) * sf 197 dst.append(a) 198 199 def matmul(mut dst: List[Float32], w: Int64, x: List[Float32], nr: Int, nc: Int, qt: Int): 200 if qt == 6: matmul_q5_0(dst, w, x, nr, nc) 201 elif qt == 8: matmul_q8_0(dst, w, x, nr, nc) 202 elif qt == 39: matmul_mxfp4(dst, w, x, nr, nc) 203 else: 204 for _ in range(nr): dst.append(0.0) 205 206 # ═══════════════════════════════════════════════════════════ 207 # MAIN — Full Forward Pass 208 # ═══════════════════════════════════════════════════════════ 209 def main() raises: 210 print("MojoLlama Engine v2 — Full Forward") 211 print("==================================") 212 var _t0 = time.perf_counter() 213 var d = "/tmp/mojo_weights/gpt-oss/" 214 var N = 2880; var eps: Float32 = 1e-6 215 216 # ── LOAD WEIGHTS ── 217 var x = _load_f32s(d + "emb.bin", N) 218 print("emb:", x[0], x[1], x[2]) 219 220 var on = _load_f32s(d + "out_norm.bin", N) 221 222 # ── LAYER LOOP (0 only for now, extend to 24 when compiler is fixed) ── 223 # Attention norm + RMS norm 224 var aw = _load_f32s(d + "layer_0/attn_norm.bin", N) 225 var xn = rms_norm(x, aw, N, eps) 226 print("rms:", xn[0], xn[1]) 227 228 # QKV matmuls 229 var qw = _load_u8s(d + "layer_0/q_weight.bin") 230 var qnr = 4096; var qnc = 2880 231 # NOTE: Inline @extern version for now — Python FFI weights are in List[UInt8] 232 # which doesn't work with the pointer-based matmul functions above. 233 # The matmul functions use Int64 pointers from @extern C bridge. 234 # TODO: Add List[UInt8]-based matmul kernels for Python FFI case. 235 236 print("Layer 0 weights loaded") 237 print("Done!")