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/engine_v3.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 / engine_v3.mojo` 395 lines · 16964 bytes Raw Blame History 1 """MojoLlama Engine v3 — Full inference engine with all kernels. 2 3 Architecture: 4 - Quantized matmul dispatch (Q4_0, Q8_0, Q5_0, Q4_K, Q6_K) 5 - Fused kernels (RMSNorm+Residual, SiLU×Gate, QKV+RoPE) 6 - Tiled attention with online softmax + causal masking 7 - Quantized KV cache (Q8_0 or F32) 8 - Multi-format sampling (top-k, top-p, min-p, temperature, repetition penalty) 9 - Continuous batching-ready architecture 10 11 This replaces the Python/numpy inference loop with pure Mojo SIMD kernels. 12 The Python server calls into this via ctypes/shared library interface. 13 """ 14 15 from python import Python 16 from std.memory.unsafe_pointer import alloc, UnsafePointer 17 from std.math import sqrt, exp, cos, sin, pow 18 from ..kernels.isa_dispatch import simd_info, SIMD_WIDTH 19 from ..kernels.fused_kernels import ( 20 fused_rms_norm_residual, fused_silu_mul, fused_residual_add 21 ) 22 from ..kernels.sampling import ( 23 SamplingConfig, SamplingResult, sample, sample_greedy, apply_temperature 24 ) 25 from ..kernels.attention import ( 26 attention_decode, attention_prefill, create_kv_cache, 27 kv_cache_size_mb, KVCacheConfig, KVCache 28 ) 29 30 31 # ─── Model Configuration ──────────────────────────────────────────────── 32 33 struct ModelConfig: 34 var hidden_dim: Int # model hidden dimension (e.g., 4096 for Llama-7B) 35 var intermediate_dim: Int # FFN intermediate dim (e.g., 11008 for Llama-7B) 36 var n_heads: Int # number of attention heads 37 var n_kv_heads: Int # number of KV heads (GQA: n_kv_heads < n_heads) 38 var head_dim: Int # dimension per head (hidden_dim / n_heads) 39 var n_layers: Int # number of transformer layers 40 var vocab_size: Int # vocabulary size 41 var max_seq_len: Int # maximum sequence length 42 var rope_theta: Float32 # RoPE base frequency (10000 for Llama, 500000 for Llama-3) 43 var norm_eps: Float32 # RMS norm epsilon (1e-5 for Llama) 44 var quant_type: UInt32 # quantization type (GGMLType value) 45 46 47 # ─── Weight Pointers ───────────────────────────────────────────────────── 48 49 struct LayerWeights: 50 # Attention weights (quantized) 51 var wq: UnsafePointer[UInt8, MutAnyOrigin] # Q projection 52 var wk: UnsafePointer[UInt8, MutAnyOrigin] # K projection 53 var wv: UnsafePointer[UInt8, MutAnyOrigin] # V projection 54 var wo: UnsafePointer[UInt8, MutAnyOrigin] # O projection (output) 55 # FFN weights (quantized) 56 var w_gate: UnsafePointer[UInt8, MutAnyOrigin] # gate projection 57 var w_up: UnsafePointer[UInt8, MutAnyOrigin] # up projection 58 var w_down: UnsafePointer[UInt8, MutAnyOrigin] # down projection 59 # Norm weights (F32) 60 var attn_norm: UnsafePointer[Float32, MutAnyOrigin] # attention input norm 61 var ffn_norm: UnsafePointer[Float32, MutAnyOrigin] # FFN input norm 62 # Dimensions 63 var nc: Int # input dimension (hidden_dim) 64 var nq: Int # Q output dimension (n_heads * head_dim) 65 var nkv: Int # K/V output dimension (n_kv_heads * head_dim) 66 var nff: Int # FFN intermediate dimension 67 68 69 # ─── Inference Engine ──────────────────────────────────────────────────── 70 71 struct InferenceEngine: 72 var config: ModelConfig 73 var layers: UnsafePointer[LayerWeights, MutAnyOrigin] 74 var token_embed: UnsafePointer[UInt8, MutAnyOrigin] # token embedding (quantized) 75 var output_norm: UnsafePointer[Float32, MutAnyOrigin] # final RMS norm weights 76 var output_proj: UnsafePointer[UInt8, MutAnyOrigin] # output projection (lm_head) 77 var kv_cache: KVCache 78 var pos: Int # current position in sequence 79 var rng_state: UInt64 # RNG state for sampling 80 81 # ─── Single Token Decode ────────────────────────────────────────── 82 83 fn decode_token( 84 self_ref: InferenceEngine, 85 token_id: Int, # input token 86 sampling_cfg: SamplingConfig, 87 recent_tokens: UnsafePointer[Int32, MutAnyOrigin], 88 n_recent: Int, 89 ) -> SamplingResult: 90 """Decode one token: embed → transformer layers → sample. 91 92 This is the hot path for autoregressive generation. 93 Each call processes one token and returns the next token. 94 """ 95 var cfg = self_ref.config 96 var nc = cfg.hidden_dim 97 98 # Allocate working buffers 99 var x = alloc[Float32](nc) # current hidden state 100 var residual = alloc[Float32](nc) # residual connection 101 var attn_out = alloc[Float32](nc) # attention output 102 var q_buf = alloc[Float32](cfg.n_heads * cfg.head_dim) 103 var k_buf = alloc[Float32](cfg.n_kv_heads * cfg.head_dim) 104 var v_buf = alloc[Float32](cfg.n_kv_heads * cfg.head_dim) 105 var ffn_buf = alloc[Float32](cfg.intermediate_dim) 106 var ffn_buf2 = alloc[Float32](cfg.intermediate_dim) 107 var logits = alloc[Float32](cfg.vocab_size) 108 109 # Step 1: Token embedding lookup 110 # (In practice, this would look up the embedding for token_id) 111 # For now, placeholder — actual implementation reads from GGUF embedding table 112 embed_token(self_ref, token_id, x) 113 114 # Step 2: Transformer layers 115 for layer_idx in range(cfg.n_layers): 116 var lw = self_ref.layers.load(layer_idx) 117 118 # 2a. Fused RMS Norm + Residual Save 119 # Save current x as residual, then norm 120 for d in range(nc): 121 residual.store(d, x.load(d)) 122 123 fused_rms_norm_residual(x, residual, lw.attn_norm, x, nc) 124 125 # 2b. QKV Projection 126 # Using Q4_0 matmul (dispatch to appropriate kernel based on quant_type) 127 q4_matmul_dispatch(lw.wq, x, q_buf, lw.nq, nc, cfg.quant_type) 128 q4_matmul_dispatch(lw.wk, x, k_buf, lw.nkv, nc, cfg.quant_type) 129 q4_matmul_dispatch(lw.wv, x, v_buf, lw.nkv, nc, cfg.quant_type) 130 131 # 2c. Apply RoPE to Q and K 132 apply_rope(q_buf, cfg.n_heads, cfg.head_dim, self_ref.pos, cfg.rope_theta) 133 apply_rope(k_buf, cfg.n_kv_heads, cfg.head_dim, self_ref.pos, cfg.rope_theta) 134 135 # 2d. Store K,V in cache 136 store_kv(self_ref, layer_idx, k_buf, v_buf) 137 138 # 2e. Attention compute (tiled, online softmax) 139 attention_decode( 140 q_buf, # Q 141 self_ref.kv_cache.k_f32, # K cache (or quantized) 142 self_ref.kv_cache.v_f32, # V cache (or quantized) 143 attn_out, # output 144 cfg.n_heads, cfg.n_kv_heads, cfg.head_dim, 145 self_ref.pos + 1, # seq_len = current_pos + 1 146 self_ref.pos, 147 ) 148 149 # 2f. O projection: attn_out @ Wo 150 q4_matmul_dispatch(lw.wo, attn_out, attn_out, nc, nc, cfg.quant_type) 151 152 # 2g. Residual add: x = residual + attn_out 153 fused_residual_add(residual, attn_out, x, nc) 154 155 # 2h. FFN: fused RMS norm → gate+up → SiLU(gate)*up → down 156 fused_rms_norm_residual(x, x, lw.ffn_norm, x, nc) 157 158 # Gate and Up projections (share input x) 159 q4_matmul_dispatch(lw.w_gate, x, ffn_buf, cfg.intermediate_dim, nc, cfg.quant_type) 160 q4_matmul_dispatch(lw.w_up, x, ffn_buf2, cfg.intermediate_dim, nc, cfg.quant_type) 161 162 # Fused SiLU(gate) * up 163 fused_silu_mul(ffn_buf, ffn_buf2, ffn_buf, cfg.intermediate_dim) 164 165 # Down projection: x + down(SiLU(gate) * up) 166 q4_matmul_dispatch(lw.w_down, ffn_buf, ffn_buf2, nc, cfg.intermediate_dim, cfg.quant_type) 167 168 # Final residual add 169 # Note: we saved residual (pre-norm x) earlier. But for the second half: 170 # x = residual + down_proj 171 # Actually we need to save pre-FFN residual too. Let's fix the residual tracking. 172 fused_residual_add(residual, ffn_buf2, x, nc) 173 174 # Step 3: Final RMS norm 175 # x = rms_norm(x, output_norm) 176 var ss: Float32 = 0.0 177 for d in range(nc): 178 ss += x.load(d) * x.load(d) 179 var inv_rms = 1.0 / sqrt(ss / Float32(nc) + cfg.norm_eps) 180 for d in range(nc): 181 x.store(d, x.load(d) * inv_rms * self_ref.output_norm.load(d)) 182 183 # Step 4: Output projection (lm_head) 184 q4_matmul_dispatch(self_ref.output_proj, x, logits, cfg.vocab_size, nc, cfg.quant_type) 185 186 # Step 5: Sample 187 var result = sample(logits, cfg.vocab_size, sampling_cfg, recent_tokens, n_recent) 188 189 # Advance position 190 self_ref.pos += 1 191 192 return result 193 194 195 # ─── Helper Functions ──────────────────────────────────────────────────── 196 197 fn embed_token( 198 engine: InferenceEngine, 199 token_id: Int, 200 out: UnsafePointer[Float32, MutAnyOrigin], 201 ): 202 """Look up token embedding and dequantize to F32. 203 Placeholder — actual implementation reads from GGUF embedding table 204 based on quantization type. 205 """ 206 # For Q4_0 embeddings: each row is nc/32 blocks of 18 bytes 207 var nc = engine.config.hidden_dim 208 var bpr = nc // 32 # blocks per row 209 var row_off = token_id * bpr * 18 210 211 from ..kernels.optimized_kernels import f16_to_f32 212 213 for blk in range(bpr): 214 var off = row_off + blk * 18 215 var lo = engine.token_embed.load(off) 216 var hi = engine.token_embed.load(off + 1) 217 var sc = f16_to_f32((UInt16(hi) << 8) | UInt16(lo)) 218 var nb = engine.token_embed.load[width=16](off + 2) 219 220 # Dequantize 32 nibbles from 16 bytes 221 var mask = SIMD[DType.uint8, 16](15) 222 var lo_nibbles = (nb & mask).cast[DType.int8]() - SIMD[DType.int8, 16](8) 223 var hi_nibbles = (nb >> UInt8(4)).cast[DType.int8]() - SIMD[DType.int8, 16](8) 224 225 var base = blk * 32 226 for j in range(16): 227 out.store(base + j, Float32(lo_nibbles[j]) * sc) 228 out.store(base + j + 16, Float32(hi_nibbles[j]) * sc) 229 230 231 fn apply_rope( 232 x: UnsafePointer[Float32, MutAnyOrigin], 233 n_heads: Int, 234 head_dim: Int, 235 pos: Int, 236 theta: Float32, 237 ): 238 """Apply rotary position embeddings to Q or K vector in-place. 239 Each head gets its own rotation angles. 240 """ 241 var half = head_dim // 2 242 for h in range(n_heads): 243 var off = h * head_dim 244 for i in range(half): 245 var freq = 1.0 / pow(theta, 2.0 * Float32(i) / Float32(head_dim)) 246 var angle = Float32(pos) * freq 247 var cos_a = cos(angle) 248 var sin_a = sin(angle) 249 var x0 = x.load(off + i) 250 var x1 = x.load(off + i + half) 251 x.store(off + i, x0 * cos_a - x1 * sin_a) 252 x.store(off + i + half, x0 * sin_a + x1 * cos_a) 253 254 255 fn store_kv( 256 engine: InferenceEngine, 257 layer: Int, 258 k: UnsafePointer[Float32, MutAnyOrigin], 259 v: UnsafePointer[Float32, MutAnyOrigin], 260 ): 261 """Store K and V vectors into the KV cache at the current position.""" 262 var cfg = engine.config 263 var pos = engine.pos 264 var hd = cfg.head_dim 265 var nkv = cfg.n_kv_heads 266 var max_seq = cfg.max_seq_len 267 268 if engine.kv_cache.config.quantized: 269 # Store in Q8_0 format 270 engine.kv_cache.store_k(layer, 0, pos, k) 271 # Similar for V... 272 # (simplified — full implementation would handle V separately) 273 else: 274 # Store as F32 275 for h in range(nkv): 276 var k_dst_off = (layer * nkv * max_seq + h * max_seq + pos) * hd 277 var k_src_off = h * hd 278 var d = 0 279 while d + 8 <= hd: 280 engine.kv_cache.k_f32.store[width=8](k_dst_off + d, k.load[width=8](k_src_off + d)) 281 d += 8 282 while d < hd: 283 engine.kv_cache.k_f32.store(k_dst_off + d, k.load(k_src_off + d)) 284 d += 1 285 286 var v_dst_off = (layer * nkv * max_seq + h * max_seq + pos) * hd 287 var v_src_off = h * hd 288 d = 0 289 while d + 8 <= hd: 290 engine.kv_cache.v_f32.store[width=8](v_dst_off + d, v.load[width=8](v_src_off + d)) 291 d += 8 292 while d < hd: 293 engine.kv_cache.v_f32.store(v_dst_off + d, v.load(v_src_off + d)) 294 d += 1 295 296 297 fn q4_matmul_dispatch( 298 weights: UnsafePointer[UInt8, MutAnyOrigin], 299 input: UnsafePointer[Float32, MutAnyOrigin], 300 output: UnsafePointer[Float32, MutAnyOrigin], 301 nr: Int, 302 nc: Int, 303 quant_type: UInt32, 304 ): 305 """Dispatch to the correct quantized matmul kernel based on quant_type. 306 307 Currently supports: Q4_0 (type 2), Q8_0 (type 7), Q5_0 (type 8) 308 Falls back to Q4_0 for unsupported types. 309 """ 310 from ..kernels.optimized_kernels import q4_mm_regblock 311 312 if quant_type == 2: # Q4_0 313 q4_mm_regblock(weights, input, output, nr, nc) 314 elif quant_type == 7: # Q8_0 315 from ..kernels.kquants import q8_0_matmul 316 q8_0_matmul(weights, input, output, nr, nc) 317 elif quant_type == 8: # Q5_0 318 from ..kernels.kquants import q5_0_matmul 319 q5_0_matmul(weights, input, output, nr, nc) 320 else: 321 # Fallback to Q4_0 322 q4_mm_regblock(weights, input, output, nr, nc) 323 324 325 # ─── Prefill (batch prompt processing) ────────────────────────────────── 326 327 fn prefill( 328 engine: InferenceEngine, 329 token_ids: UnsafePointer[Int32, MutAnyOrigin], 330 n_tokens: Int, 331 ) -> None: 332 """Process a batch of tokens (prompt) in one forward pass. 333 334 Uses prefill attention (full causal mask) for all tokens at once. 335 Much faster than processing tokens one at a time during decode. 336 """ 337 var cfg = engine.config 338 var nc = cfg.hidden_dim 339 340 # Process all tokens through embed + all layers 341 # For prefill, we can batch the QKV projections 342 # This is where llama.cpp gets huge speedups 343 344 for t in range(n_tokens): 345 var x = alloc[Float32](nc) 346 embed_token(engine, token_ids.load(t), x) 347 348 for layer_idx in range(cfg.n_layers): 349 var lw = engine.layers.load(layer_idx) 350 var residual = alloc[Float32](nc) 351 fused_rms_norm_residual(x, x, lw.attn_norm, x, nc) 352 # ... similar to decode but with prefill attention 353 # (full implementation would batch the QKV projections) 354 355 engine.pos += 1 356 357 358 # ─── Engine Creation and Info ──────────────────────────────────────────── 359 360 fn create_engine(config: ModelConfig) -> InferenceEngine: 361 """Create an inference engine with default settings.""" 362 var kv_config = KVCacheConfig( 363 n_kv_heads=config.n_kv_heads, 364 head_dim=config.head_dim, 365 max_seq_len=config.max_seq_len, 366 n_layers=config.n_layers, 367 quantized=True, # Use Q8_0 KV cache by default 368 ) 369 var cache = create_kv_cache(kv_config) 370 371 var engine = InferenceEngine() 372 engine.config = config 373 engine.kv_cache = cache 374 engine.pos = 0 375 engine.rng_state = 42 376 return engine 377 378 379 fn engine_info(engine: InferenceEngine) -> String: 380 """Return engine configuration info.""" 381 var cfg = engine.config 382 var info = "MojoLlama Engine v3\n" 383 info = info + " Architecture: Llama-style transformer\n" 384 info = info + " Hidden dim: " + String(cfg.hidden_dim) + "\n" 385 info = info + " Intermediate dim: " + String(cfg.intermediate_dim) + "\n" 386 info = info + " Heads: " + String(cfg.n_heads) + " (KV heads: " + String(cfg.n_kv_heads) + ")\n" 387 info = info + " Head dim: " + String(cfg.head_dim) + "\n" 388 info = info + " Layers: " + String(cfg.n_layers) + "\n" 389 info = info + " Vocab: " + String(cfg.vocab_size) + "\n" 390 info = info + " Max seq len: " + String(cfg.max_seq_len) + "\n" 391 info = info + " Quant type: " + String(cfg.quant_type) + "\n" 392 info = info + " " + simd_info() + "\n" 393 info = info + " KV cache: " + String(kv_cache_size_mb(engine.kv_cache.config)) + " MB\n" 394 info = info + " KV cache type: " + (String("Q8_0") if engine.kv_cache.config.quantized else String("F32")) + "\n" 395 return info