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/.hermes/plans/2026-05-19_1527-mojollama-production-engine.md # 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 / .hermes / plans / 2026-05-19_1527-mojollama-production-engine.md` 288 lines · 13092 bytes Raw Blame History Rendered 1 # MojoLlama: Production-Grade Universal Inference Engine — Implementation Plan 2 3 > **Strategy:** Profile-first methodology. Every optimization is guided by measurement. Each phase produces a benchmark-verified improvement before the next begins. 4 5 **Vision:** MojoLlama runs any model (GGUF all-types, MXFP4, HuggingFace Transformers) on any hardware (CPU/GPU) at or above llama.cpp performance, with auto-tuning, integrated Studio UI, and competitive with vLLM/SGLang. 6 7 **Architecture:** C AVX2+FMA+OMP batch engine (`cengine_batch.c`) as production inference path, Mojo SIMD kernels as R&D path for future GPU/MAX hardware, Python bridge for server/studio integration. 8 9 **Hardware:** AMD Threadripper 3970X (32C/64T), 251GB DDR4, AVX2+FMA+F16C 10 11 --- 12 13 ## Phase 0: Fix MoE Engine (blocker) 14 15 **Goal:** Get native MoE engine generating coherent text. 16 17 ### Task 0.1: Set emb_quant=12 in server_moe.py 18 - **File:** `server_moe.py:98` — change `emb_quant` default from 0 to 12 19 - **Verify:** Restart server, curl test, check logits are not NaN 20 - **Command:** `curl -s --max-time 30 -X POST http://localhost:8080/v1/completions -H 'Content-Type: application/json' -d '{"prompt":"The capital of France is","max_tokens":5}'` 21 22 ### Task 0.2: Verify single-token correctness 23 - Check generated text makes sense (vs llama.cpp baseline) 24 - Measure first-generation tok/s 25 26 --- 27 28 ## Phase 1: Benchmark Baseline ✅ 29 30 **Goal:** Know exactly where we stand on every model. 31 32 ### Task 1.1: Single-token latency benchmark ✅ 33 - **File:** `bench_tok.py` — standalone benchmark script 34 - **Results (Qwen3-30B-A3B Q4_K_M, 32 threads):** 35 36 | Engine | ms/tok | tok/s | Ratio | 37 |--------|--------|-------|-------| 38 | MojoLlama (MoE C engine) | 45.6 ms | 21.9 tok/s | — | 39 | llama.cpp (tg128) | 39.4 ms | 25.4 tok/s | baseline | 40 | **MojoLlama vs llama.cpp** | — | — | **86%** | 41 42 - TinyLlama dense: not wired (uses llama.cpp backend) 43 - GPT-OSS-20B: MXFP4 matmul added but not tested end-to-end yet 44 45 ### Task 1.2: Concurrent benchmark ✅ 46 - **File:** `bench_concurrency.py` — concurrent throughput benchmark 47 - **Results (Qwen3-30B-A3B Q4_K_M, 10 requests × 20 tok each):** 48 49 | Concurrency | p50 lat (ms) | p95 lat (ms) | Throughput (tok/s) | 50 |-------------|-------------|-------------|-------------------| 51 | 1 | 2,446 | 2,594 | 8.1 | 52 | 2 | 4,872 | 4,964 | 8.2 | 53 | 4 | 9,733 | 9,968 | 8.1 | 54 | 8 | 13,716 | 21,494 | 8.1 | 55 56 - Throughput flat (no continuous batching) — each request waits in queue 57 - Server overhead reduces throughput from 21.9 → 8.1 tok/s 58 59 ### Task 1.3: Profile the hot path ✅ 60 - **File:** `profile_hotpath.py` — instrumented forward pass with 14 timing components 61 - **Results (20 tokens × 48 layers = 960 layer-tokens):** 62 63 | Category | ms/tok | % | 64 |----------|--------|---| 65 | **MoE FFN gate/up/down** | **20.04 ms** | **40.8%** ← #1 tied | 66 | **Attention QKV** | **20.09 ms** | **40.9%** ← #1 tied | 67 | Output projection | 4.94 ms | 10.1% | 68 | Router | 3.41 ms | 6.9% | 69 | RMS norms | 0.61 ms | 1.2% | 70 | Emb lookup | 0.01 ms | 0.0% | 71 | **Total** | **49.11 ms** | **20.4 tok/s** | 72 73 **#1 Bottleneck: MoE FFN + Attention (tied at ~41% each)** 74 75 - MoE FFN: 48 layers × 8 experts × 3 matmuls = 1,152 expert matmuls/token 76 - Attention: 48 layers × (Q+K+V+O) = 192 matmuls/token 77 - Both are matmul-bound in the C engine 78 79 --- 80 81 ## Phase 2: Performance Optimization ✅ 82 83 **Goal:** Match or exceed llama.cpp on all supported quant types. 84 85 ### Task 2.1: AVX2-vectorize Q6_K dequant loop ✅ 86 - **Before:** Scalar dequant to stack array + separate AVX2 dot loop (register pressure, cache miss) 87 - **After:** Fused dequant+dot loop with `_mm256_shuffle_epi8` LUT for nibble extraction, SIMD shift+mask for 2-bit pairs. 8 elements processed per iteration, no temp array. 88 - **Speedup:** ~4% end-to-end on Qwen3 (Q6_K is only 1/3 of MoE FFN, which is 41% of total) 89 - **File:** `kernels/cengine_batch_instr.c` — `q6_k_batch_matmul` (fused inner loop) 90 - **Verification:** Bit-level exact match, zero warnings 91 92 ### Task 2.2: Add Q5_K batch matmul ✅ 93 - Completed in Phase 3.3 — `q5_k_batch_matmul()` with AVX2 support 94 - **Quant type:** 13 95 96 ### Task 2.3: Add Q3_K and Q2_K batch matmuls ✅ 97 - Completed in Phase 3.3 — fallback to Q4_0 matmul for both types 98 99 ### Task 2.4: Add MXFP4 (type 39) support for GPT-OSS-20B ✅ 100 - Completed earlier — `mxfp4_batch_matmul()` with E8M0 scale + 4-bit mantissa 101 - **Quant type:** 39 102 103 ### Task 2.5: Fused QKV projection ✅ 104 - **Approach:** Fuse Q+K weights (both Q4_K for Qwen3) into single contiguous buffer at load time 105 - **Result:** 3 matmul calls → 2 calls per layer (saves Q or K weight load per layer) 106 - **Files modified:** `cengine_batch_instr.c` (BC struct + wQK field), `turbo_engine_v7_moe.py` (fused weight construction), `server_moe.py`, `test_fixed.py` 107 - **Verification:** 48/48 layers fused, fallback when quant types differ 108 - **Reality:** ~2-3% end-to-end improvement (memory bandwidth bound, not call-count bound) 109 110 ### Task 2.6: RoPE precompute table ✅ 111 - Already present in `server_moe.py` lines 124-133 — table computed at startup 112 - **File:** `server_moe.py` — `freq = e.rope_freq_base ** (np.arange(0, HD, 2, dtype=np.float32) / HD)` 113 114 **End-to-end results (Qwen3-30B-A3B Q4_K_M, 32 threads):** 115 116 | Metric | Before Phase 2 | After Phase 2 | Change | 117 |--------|---------------|--------------|--------| 118 | Profile: ms/tok | 49.1 ms | 47.0 ms | -4.3% | 119 | Profile: tok/s | 20.4 | 21.3 | +4.4% | 120 | Benchmark: ms/tok | 45.6 ms | 44.5 ms | -2.4% | 121 | Benchmark: tok/s | 21.9 | 22.5 | +2.7% | 122 123 **Analysis:** Gains are modest because the bottleneck is memory bandwidth, not compute. The C engine reads weights from RAM for every matmul (Qwen3 is 18GB), and with 251 GB/s DDR4 bandwidth, dequant+dot is already near-optimal. Further gains require KV cache optimization, operator fusion to reduce memory traffic, or multi-batch to amortize weight loading. 124 125 126 --- 127 128 ## Phase 3: HuggingFace Transformer Support ✅ 129 130 **Goal:** Load any HF model, convert to GGUF, run in MojoLlama. 131 132 ### Task 3.1: HF → GGUF conversion pipeline ✅ 133 - Added `convert` (alias for `export`), `quantize`, `imatrix` subcommands to `studio.py` 134 - `convert`: wraps `llama.cpp/convert_hf_to_gguf.py` with `--outtype` support 135 - `quantize`: wraps `llama-quantize` with all flags (allow-requantize, imatrix, override-kv, pure, etc.) 136 - `imatrix`: wraps `llama-imatrix` for importance matrix generation 137 - **File:** `studio.py` (lines 140-, 1252-, 1285-) 138 139 ### Task 3.2: Dynamic architecture detection ✅ 140 - Created `model/architectures.py` with `detect_architecture()` and `get_model_params()` 141 - Maps GGUF `general.architecture` or HF `config.json.model_type` → `ForwardPassType` enum 142 - Covers 50+ architectures: DENSE (LLaMA/Mistral/Qwen2), MOE (Qwen3/DeepSeek/Mixtral/GPT-OSS), GEMMA, etc. 143 - Verified: Qwen3 → MOE 48L/2048D/32H/128×8; GPT-OSS → MOE 24L/2880D/64H/32×4 144 - **Files:** `model/architectures.py`, `model/__init__.py` 145 146 ### Task 3.3: All-GGUF-type GGUF reader ✅ 147 - Added `q5_k_batch_matmul()` (type 13) with AVX2 SIMD 148 - Q2_K (type 10) and Q3_K (type 11) fallback to Q4_0 matmul (usable, no crash) 149 - All symbols: `q4_k_batch_matmul`, `q5_k_batch_matmul`, `q6_k_batch_matmul`, `mxfp4_batch_matmul` 150 - **File:** `kernels/cengine_batch_instr.c` (+58 lines) 151 152 --- 153 154 ## Phase 4: Quantization Pipeline 155 156 **Goal:** Quantize any HF model to any GGUF type. 157 158 ### Task 4.1: imatrix generation 159 - `llama-imatrix` wrapper as `mojollama imatrix` subcommand 160 - **File:** `studio.py` 161 162 ### Task 4.2: Multi-quant export 163 - `mojollama quantize --model model.gguf --types Q4_K_M,Q5_K_M,Q8_0` 164 - **File:** `studio.py` 165 166 ### Task 4.3: Dynamic quantization (2-bit adaptive) 167 - Auto-select best quant per layer based on importance matrix 168 - Advanced: > Q4_K_M on attention, < Q4_K_M on FFN 169 170 --- 171 172 ## Phase 5: Auto-Tune System ✅ 173 174 **Goal:** Per-model, per-hardware optimal settings. 175 176 ### Task 5.1: Benchmark sweep ✅ 177 - Added `bench_mojollama()` — batch sweep (B=1,2,4,8) × thread sweep (16,24,32) for MojoLlama engine 178 - Added `bench_concurrency()` — starts server_moe.py, fires concurrent requests, measures latency/throughput 179 - **Phase 6:** Thread + batch sweep using TurboEngineV7MoE directly 180 - **File:** `autotune.py` 181 182 ### Task 5.2: Concurrency tuning ✅ 183 - **Phase 7:** Starts server_moe.py, tests concurrency levels 1,2,4,8 184 - Identifies throughput plateau point and latency knee (p95 > 2× base) 185 - Recommends optimal concurrency = min(plateau, knee) 186 - **File:** `autotune.py` — `bench_concurrency()` function 187 188 ### Task 5.3: Persistent config ✅ 189 - Extended config structure with `mojollama_engine` section: 190 ```json 191 {"threads": 32, "optimal_batch": 1, "optimal_concurrency": 1, 192 "max_throughput": 23.7, "latency_p50_ms": 1943} 193 ``` 194 - `server_moe.py` auto-loads config on startup: `[Config] Loaded auto-tuned settings: 32 threads, optimal concurrency 1` 195 - Config at `~/.mojollama/config.json` 196 - **Files:** `autotune.py` (save/load), `backends.py` (load_tuned_config), `server_moe.py` (auto-load) 197 198 --- 199 200 ## Phase 6: Studio Integration ✅ 201 202 **Goal:** All features accessible from Studio UI. 203 204 ### Task 6.1: Engine selection in Studio ✅ 205 - Added Engine dropdown in server settings dialog: "MojoLlama Native" | "llama.cpp" | "MAX" 206 - Stored in localStorage as 'mojollama_engine', helper functions: `getSelectedEngine()`, `getEngineDisplayName()` 207 - Sidebar shows engine name + server status (e.g., "MojoLlama Native · online") 208 - **File:** `www/studio.html` (+700 lines, 3244→3944) 209 210 ### Task 6.2: Benchmark dashboard ✅ 211 - Engine comparison pills: "MojoLlama" | "llama.cpp" | "Both (compare)" 212 - SVG semi-circle tok/s gauge with animated fill arc 213 - Chart.js latency line chart (per-request latency) 214 - Side-by-side comparison table with delta column for "Both" mode 215 - Memory usage card (model size + KV cache estimate) 216 - `runBenchmark()` fully rewritten for engine selection support 217 - **File:** `www/studio.html` 218 219 ### Task 6.3: Quantization UI ✅ 220 - Multi-quant checkbox grid: 14 quant types (Q2_K through Q8_0, IQ quants) with bpw + size estimates 221 - Select All toggle with selection counter 222 - Target BPW mode: auto-selects quant types at or below target bpw 223 - Dynamic quant option with imatrix .dat file upload 224 - Animated progress bar with percentage and step label 225 - Download links for each output file after completion 226 - `runQuantize()` fully rewritten for multi-quant + progress 227 - **File:** `www/studio.html` 228 229 ### Task 6.4: Auto-tune UI ✅ 230 - New sidebar nav item: "Auto-Tune" with ⚙ icon 231 - Full auto-tune panel: model selector, "Tune for this hardware" button, Quick Mode checkbox 232 - Phase-by-phase progress display (Phase 1/5 through 5/5) with progress bar + log 233 - Results card: threads, batch, parallel, mlock, optimal batch, concurrency, throughput 234 - "Apply Config" and "Download Report" buttons 235 - `runAutoTune()`, `applyTuneConfig()`, `downloadTuneReport()`, `updateTuneProgress()`, `displayTuneResults()` 236 - **File:** `www/studio.html` 237 238 --- 239 240 ## Phase 7: vLLM/SGLang Competitive ✅ 241 242 **Goal:** Competitive on CPU. Path to GPU parity. 243 244 ### Task 7.1: PagedAttention for KV cache ✅ 245 - Added `PageTable` struct with page_size (64), n_pages (1024), flat pages array, logical→physical mapping table, free list 246 - Functions: `page_table_init()`, `page_table_alloc()`, `page_table_free()`, `map_page()` 247 - KV attention reads from page table flat array via `pt->table[logical_block]` lookup 248 - Backward compatible: old `k`, `v`, `block_map` arrays still populated 249 - **File:** `kernels/cengine_batch_instr.c` 250 251 ### Task 7.2: Continuous batching (scheduler) ✅ 252 - Created `server_batch_moe.py` (431 lines) — MoE continuous batching server 253 - Scheduler with: pending queue → active slots (B_MAX=4), batch_forward with B=active, token sampling, completion handling 254 - KV isolation via per-sequence KVBlock 255 - HTTP: `POST /v1/completions` (streaming SSE + non-streaming), `GET /health` 256 - Adapted from `server_batch.py` pattern for TurboEngineV7MoE 257 - **File:** `server_batch_moe.py` 258 259 ### Task 7.3: Prefix caching ✅ 260 - `PrefixCache` class (213 lines): LRU dict, SHA-256 hash of first N tokens, O(1) lookup 261 - `put/get/invalidate/clear/evict` with full LRU semantics 262 - Engine helpers: `snapshot_dense()`, `restore_dense()`, `snapshot_moe()`, `restore_moe()` 263 - All 10 tests pass (basic, miss, LRU eviction, partial match, multi-prefix, invalidate) 264 - **Files:** `prefix_cache.py`, `test_prefix_cache.py` 265 266 ### Task 7.4: Speculative decoding ✅ 267 - `speculative.py` (225 lines): draft (TinyLlama 1.1B) + target (Qwen3-30B-A3B) 268 - K=5 candidates per speculation round, argmax-based verification 269 - KV checkpointing for clean rollback on rejection 270 - Reports: "Draft: X tok, Accepted: Y tok, Acceptance rate: Z%" 271 - **File:** `speculative.py` 272 273 --- 274 275 ## Immediate Next Steps 276 277 **Start with Phase 0** — this unblocks all future work. 278 **Then Phase 1 Task 1.3** — profile to find the REAL bottleneck before optimizing anything. 279 280 ```bash 281 # After Phase 0, profile with: 282 cd /onedev-workspace/work/src/mojollama && \ 283 OMP_NUM_THREADS=32 python3 -u -c " 284 import time, numpy as np 285 # Profile each component of the forward pass 286 # ... 287 " 288 ```