interplane.Get Omega
Read in your language

MojoLlama

Archived Mojo/MAX quantizer and serving research repository (read-only history)

Brought by drakestapleton

branch main Branches Tags History

MojoLlama / IMPROVEMENT_ROADMAP.md

379 lines · 16967 bytes Raw Blame History Rendered
1# MojoLlama Improvement Roadmap
2
3**Date:** 2026-05-20
4**Baseline:** v0.5.0 — 41K Python lines, 12K C lines, 5.6K HTML, 17 Mojo files, 60+ architectures
5
6---
7
8## Executive Summary
9
10MojoLlama has a strong core (C engine with AVX2+OMP, MoE optimization, concurrent serving) but suffers from **accumulated tech debt** from rapid iteration: 24 stale `.so` files in `legacy-c/`, 15+ single-use debug/inspect scripts, no unit test framework, no packaging, and a CI that only compiles C kernels without running tests. The gap between the CODING-SOUL vision (Mojo+MAX native) and the current reality (Python + C + llama.cpp dependency) is the biggest strategic risk.
11
12---
13
14## Phase 1: Clean Foundation (Weeks 1-2) — HIGH IMPACT, LOW EFFORT
15
16### 1.1 Eliminate Dead Code & Build Artifacts
17**Impact:** HIGH | **Effort:** S
18
19| Action | Details |
20|--------|---------|
21| Remove `kernels/legacy-c/` directory | 24 stale `.so` files, 12 abandoned `.c` files (c_engine.c, cengine2.c, cengine3.c, cengine_batch_clean.c, cengine_batch_full_bak.c, etc.). None are imported by current code. |
22| Remove single-use debug scripts | `check_attr.py`, `debug_forward.py`, `inspect_gptoss.py`, `inspect_mxfp4.py`, `compare_q_proj.py`, `q4k_compare.py`, `bench_gpt.py`, `run_gdb_test.py` — all are one-off debugging tools, not production code. |
23| Remove stale `.so` from `kernels/` root | `cengine_batch_instr.so`, `gqa_attention.so`, `quant_kernels_omp.so`, `simd_ops.so` — should be built, not committed. Add to `.gitignore`. |
24| Archive `numpy_reference.py` | Pure-numpy reference for correctness validation — move to `tools/` or `benchmarks/`, not top-level. |
25
26### 1.2 Add `.gitignore` for Build Artifacts
27**Impact:** HIGH | **Effort:** S
28
29```
30*.so
31*.dylib
32__pycache__/
33*.pyc
34*.egg-info/
35.venv/
36```
37
38### 1.3 Consolidate Test Infrastructure
39**Impact:** HIGH | **Effort:** M
40
41**Current state:** 12 test files (1,532 lines total), all are ad-hoc scripts that `print()` results — no assertions, no pytest, no CI integration. Only `test_prefix_cache.py` uses proper `assert` statements.
42
43| Action | Details |
44|--------|---------|
45| Add `pytest` to dependencies | `pip install pytest` |
46| Convert all `test_*.py` to pytest format | Replace `print("[PASS]")` with `assert`, use `@pytest.fixture` for engine setup, `@pytest.mark.parametrize` for model variants |
47| Add `conftest.py` | Shared fixtures: model paths, engine instances, thread counts |
48| Add `pytest.ini` or `pyproject.toml [tool.pytest]` | Test discovery config |
49| Add test job to `.onedev-buildspec.yml` | Run `pytest src/mojollama/tests/` after kernel compilation |
50
51### 1.4 Add `pyproject.toml` for Packaging
52**Impact:** HIGH | **Effort:** S
53
54**Current state:** No `pyproject.toml`, no `setup.py`. Project is not pip-installable.
55
56```toml
57[project]
58name = "mojollama"
59version = "0.5.0"
60description = "High-throughput CPU LLM inference engine"
61requires-python = ">=3.11"
62dependencies = ["numpy", "gguf", "regex", "ftfy", "flask"]
63
64[project.scripts]
65mojollama = "mojollama.__main__:main"
66
67[build-system]
68requires = ["setuptools>=68.0"]
69build-backend = "setuptools.backends._legacy:_Backend"
70```
71
72---
73
74## Phase 2: Test Coverage & Reliability (Weeks 3-5) — HIGH IMPACT, MEDIUM EFFORT
75
76### 2.1 Core Engine Tests
77**Impact:** HIGH | **Effort:** M
78
79| Test | What | Coverage Gap |
80|------|------|-------------|
81| `test_cengine_matmul.py` | Q4_0, Q4_K, Q5_K, Q6_K, Q8_0, MXFP4 dequant + matmul against numpy reference | **ZERO** — no quant kernel tests exist |
82| `test_batch_forward.py` | Full forward pass on TinyLlama, verify logits match llama.cpp within tolerance | Partial — `test_tinyllama.py` runs but doesn't assert correctness |
83| `test_moe_dispatch.py` | Expert routing correctness, top-k selection, shared expert path | **ZERO** — GPT-OSS and Qwen3.6 MoE paths untested |
84| `test_ssm_decode.py` | Mamba-2 selective scan kernel (Qwen3.6 hybrid layers) | **ZERO** — SSM path is the most complex and least tested |
85| `test_paged_attention.py` | KV cache allocation, page table mapping, physical-logical mapping | **ZERO** — critical for concurrent serving |
86| `test_rms_norm.py` | RMS norm + fused clamp against numpy reference | **ZERO** |
87| `test_rope.py` | RoPE positional embeddings (full, partial for Qwen3.6) | **ZERO** |
88
89### 2.2 Integration Tests
90**Impact:** HIGH | **Effort:** L
91
92| Test | What |
93|------|------|
94| `test_server_api.py` | All 12 API endpoints: `/v1/chat/completions`, `/v1/completions`, `/v1/models`, `/health`, `/api/metrics`, etc. |
95| `test_concurrent_serving.py` | Multi-worker spawn, shared mmap weights, aggregate throughput |
96| `test_quantizer.py` | All 35 quant types, round-trip dequant error < threshold |
97| `test_architecture_detect.py` | All 60+ architectures load without error from GGUF metadata |
98
99### 2.3 Property-Based Testing
100**Impact:** MED | **Effort:** M
101
102| Action | Details |
103|--------|---------|
104| Add `hypothesis` library | Property-based testing for quantization: `@given(weights=arrays(...))` |
105| Fuzz GGUF parser | Random GGUF-like binary data, verify parser doesn't crash |
106| Fuzz token sequences | Random token sequences through forward pass, no NaN/inf allowed |
107
108### 2.4 Memory Safety Tests
109**Impact:** HIGH | **Effort:** M
110
111| Action | Details |
112|--------|---------|
113| Add Valgrind/ASAN to CI | Run C engine under AddressSanitizer: `gcc -fsanitize=address` |
114| Test for known heap corruption | README mentions "Qwen3.6 MXFP4 cleanup crash — heap corruption on exit" — write a regression test |
115| Leak detection | Run forward pass 1000x, verify RSS doesn't grow |
116
117---
118
119## Phase 3: Performance Optimization (Weeks 6-8) — HIGH IMPACT, LARGE EFFORT
120
121### 3.1 Profile-Guided Optimization
122**Impact:** HIGH | **Effort:** M
123
124**Current state:** `profile_qwen36.py` exists but results are not documented or acted upon.
125
126| Action | Details |
127|--------|---------|
128| Run per-component profiling | `cProfile` + `line_profiler` on Qwen3.6-35B, GPT-OSS-20B, TinyLlama |
129| Publish flamegraph | `py-spy` or `perf` output as SVG in repo |
130| Identify top 3 bottlenecks | Data-driven, not guessed |
131
132**Expected bottlenecks (educated guess, needs verification):**
1331. Python→C ctypes call overhead in `turbo_engine_v7_moe.py` (24 ctypes calls per layer for MoE)
1342. Q8_0 input quantization in Python before C matmul (should be in C)
1353. MoE expert dispatch routing (softmax + top-k in Python)
136
137### 3.2 Move Q8_0 Quantization to C
138**Impact:** HIGH | **Effort:** M
139
140**README explicitly lists this as near-term:** "Q8_0 input quantization in C engine batch_matmul functions — match `quant_kernels_omp` performance (2-4× per-matmul improvement)"
141
142| Action | Details |
143|--------|---------|
144| Add `quantize_q8_0_avx2()` to `cengine_batch_instr.c` | SIMD quantization of F32→Q8_0 |
145| Update `batch_forward()` to accept F32 input, quantize internally | Eliminates Python quantization step |
146| Benchmark before/after | Target: 2-4× per-matmul improvement |
147
148### 3.3 Reduce ctypes Call Overhead
149**Impact:** HIGH | **Effort:** L
150
151**Current state:** `moe_forward_omp()` already fuses expert calls, but the per-layer loop still does Python→C transitions for attention, norm, RoPE, etc.
152
153| Action | Details |
154|--------|---------|
155| Fuse entire transformer block into single C call | `block_forward(layer_id, tokens, kv_cache)` replaces 5+ ctypes calls |
156| Pre-compute RoPE cos/sin tables in C, not Python | Eliminates per-request table lookup |
157| Batch norm + SiLU + residual into single SIMD pass | `fused_norm_silu_residual()` |
158
159### 3.4 Continuous Batching
160**Impact:** HIGH | **Effort:** XL
161
162**README lists this as near-term:** "True continuous batching — merge B users' MoE routing into single batched matmuls"
163
164| Action | Details |
165|--------|---------|
166| Implement token-level scheduling | Not request-level — schedule individual tokens across users |
167| Merge MoE routing across batch | Single top-k computation for all active tokens |
168| Dynamic KV cache management | PagedAttention already exists, needs integration with scheduler |
169
170---
171
172## Phase 4: Code Quality & Architecture (Weeks 9-12) — MED IMPACT, LARGE EFFORT
173
174### 4.1 Unified Engine Interface
175**Impact:** MED | **Effort:** L
176
177**Current state:** Three separate engines with incompatible APIs:
178- `TurboEngineV7MoE` (MoE models)
179- `TurboEngineV77` (dense models)
180- `TurboEngineDSV4` (DeepSeek V4)
181
182| Action | Details |
183|--------|---------|
184| Define `Engine` ABC | `load()`, `forward()`, `reset()`, `get_logits()`, `get_vocab()` |
185| Refactor all engines to implement `Engine` | Single interface for server, studio, benchmarks |
186| Factory function | `create_engine(model_path) → Engine` auto-detects MoE/dense/SSM |
187
188### 4.2 Remove llama.cpp Dependency
189**Impact:** HIGH | **Effort:** XL
190
191**Current state:** `server.py` hardcodes paths to llama.cpp binaries:
192```python
193LLAMA_SERVER_PATH = "/tmp/llama.cpp/build/bin/llama-server"
194CONVERTER_PATH = "/tmp/llama.cpp/convert_hf_to_gguf.py"
195```
196
197`backends.py` routes to llama.cpp as the primary CPU backend.
198
199| Action | Details |
200|--------|---------|
201| Make llama.cpp optional fallback | `AutoBackend` should prefer native C engine, fall back to llama.cpp |
202| Bundle GGUF converter | Replace `convert_hf_to_gguf.py` dependency with native converter in `quantizer.py` |
203| Remove hardcoded paths | Use `shutil.which()` or config file |
204
205### 4.3 Error Handling & Input Validation
206**Impact:** MED | **Effort:** M
207
208**Current state:** Minimal error handling. `server.py` returns 500 on any exception. `turbo_engine_v7_moe.py` has no input validation.
209
210| Action | Details |
211|--------|---------|
212| Add custom exception hierarchy | `MojoLlamaError`, `ModelError`, `QuantError`, `BackendError` |
213| Validate all user inputs in server | Model path exists, GGUF format valid, quant type supported |
214| Graceful degradation | If C engine fails, fall back to numpy (slow but correct) |
215| Add request timeout | Prevent hanging on malformed prompts |
216
217### 4.4 Type Hints & Docstrings
218**Impact:** LOW | **Effort:** L
219
220**Current state:** 41K Python lines, ~0% type hint coverage. Module docstrings exist but function-level docs are sparse.
221
222| Action | Details |
223|--------|---------|
224| Add `mypy` to CI | Start with `--ignore-missing-imports`, gradually tighten |
225| Add type hints to public APIs | `server.py`, `studio.py`, engine interfaces |
226| Add docstrings to all public functions | Use Google or NumPy style consistently |
227
228---
229
230## Phase 5: Feature Gaps (Weeks 13-16) — MED IMPACT, LARGE EFFORT
231
232### 5.1 Complete GGUF Quant Pipeline
233**Impact:** MED | **Effort:** L
234
235**Current state:** `quantizer.py` has 35 quant types but no imatrix support.
236
237| Action | Details |
238|--------|---------|
239| Implement importance matrix generation | `mojollama imatrix -m model.gguf -d calibration.txt` |
240| IQ2/IQ3/IQ4 quantization | Import-aware quantization for better quality at low bits |
241| Per-tensor quant type selection | Mix Q4_K for attention, Q2_K for FFN |
242
243### 5.2 Speculative Decoding
244**Impact:** MED | **Effort:** L
245
246**Current state:** `speculative.py` exists but is not integrated into server.
247
248| Action | Details |
249|--------|---------|
250| Integrate into server | `--draft-model tinyllama.gguf` flag |
251| Shared vocabulary optimization | Current 21% acceptance rate → target 40%+ |
252| Benchmark vs baseline | Measure speedup on different model pairs |
253
254### 5.3 Prefix Caching Integration
255**Impact:** MED | **Effort:** S
256
257**Current state:** `prefix_cache.py` exists with good tests but is not wired into server.
258
259| Action | Details |
260|--------|---------|
261| Wire into server request pipeline | Check cache before forward pass |
262| Multi-tenant prefix cache | Per-user or shared cache |
263| Benchmark cache hit rate | Real-world conversation patterns |
264
265### 5.4 Mojo Kernel Integration
266**Impact:** HIGH (strategic) | **Effort:** XL
267
268**Current state:** 17 Mojo files exist but are not compiled or used. `bridge.py` is a "placeholder" per CODING-SOUL.
269
270| Action | Details |
271|--------|---------|
272| Compile Mojo kernels with nightly | `q4_matmul.mojo`, `norms.mojo`, `attention.mojo` |
273| FFI bridge from Python to Mojo | Replace C engine hot paths with Mojo equivalents |
274| Benchmark Mojo vs C | Verify Mojo SIMD matches or beats AVX2 C |
275| MAX GPU backend | When MAX becomes installable, integrate graph compiler |
276
277---
278
279## Phase 6: Deployment & DX (Weeks 17-18) — MED IMPACT, MEDIUM EFFORT
280
281### 6.1 CI/CD Improvements
282**Impact:** HIGH | **Effort:** M
283
284**Current state:** `.onedev-buildspec.yml` has 4 jobs but:
285- No test execution (only HTML validation)
286- No linting (no `ruff`, `flake8`, `mypy`)
287- No benchmark regression detection
288- Docker build only on `main` branch
289
290| Action | Details |
291|--------|---------|
292| Add test job to buildspec | Run `pytest` after kernel compilation, block merge on failure |
293| Add lint job | `ruff check src/`, `ruff format --check src/` |
294| Add benchmark regression job | Run `bench_batch_gptoss.py`, compare against baseline, fail if >10% regression |
295| Build Docker on `dev` too | Catch Docker issues before merge to main |
296| Add matrix builds | Test on AVX2, AVX512, NEON (if CI runners support it) |
297
298### 6.2 Developer Experience
299**Impact:** MED | **Effort:** M
300
301| Action | Details |
302|--------|---------|
303| Add `Makefile` at project root | `make build`, `make test`, `make lint`, `make bench`, `make docker` |
304| Add `justfile` or `noxfile.py` | Cross-platform task runner |
305| Add pre-commit hooks | `ruff`, `mypy`, `pytest` on `git commit` |
306| Add `CONTRIBUTING.md` | How to build, test, submit PRs |
307| Add architecture decision records (ADRs) | `docs/adrs/` — why C engine over llama.cpp, why multiprocessing over threading, etc. |
308
309### 6.3 Documentation
310**Impact:** MED | **Effort:** L
311
312| Gap | Action |
313|-----|--------|
314| No API docs | Generate with `pdoc` or `sphinx` — publish to `~site/api/` |
315| No architecture docs | `docs/architecture.md` — engine design, data flow, memory model |
316| No quantization guide | `docs/quantization.md` — which quant type for which use case |
317| No troubleshooting guide | `docs/troubleshooting.md` — common errors, heap corruption, OOM |
318| README is benchmark-heavy | Add quick-start tutorial, model compatibility table, FAQ |
319
320### 6.4 Distribution
321**Impact:** MED | **Effort:** L
322
323| Action | Details |
324|--------|---------|
325| Publish to PyPI | `pip install mojollama` (with pre-built wheels for Linux x86_64) |
326| Build wheels with C extensions | `cibuildwheel` for manylinux2014 |
327| Homebrew formula | `brew install mojollama` for macOS |
328| Static binary | `PyInstaller` or `cx_Freeze` for single-file distribution |
329| Desktop app | Complete `desktop/` Electron app (exists but incomplete) |
330
331---
332
333## Priority Matrix
334
335| Priority | Item | Impact | Effort | Phase |
336|----------|------|--------|--------|-------|
337| **P0** | Remove dead code + .gitignore | HIGH | S | 1 |
338| **P0** | Add pytest + CI test job | HIGH | M | 1-2 |
339| **P0** | Add pyproject.toml | HIGH | S | 1 |
340| **P1** | C engine quant kernel tests | HIGH | M | 2 |
341| **P1** | Server API integration tests | HIGH | M | 2 |
342| **P1** | Move Q8_0 quant to C | HIGH | M | 3 |
343| **P1** | Fix heap corruption bug | HIGH | S | 2 |
344| **P2** | Unified Engine interface | MED | L | 4 |
345| **P2** | Remove llama.cpp dependency | HIGH | XL | 4 |
346| **P2** | Error handling + validation | MED | M | 4 |
347| **P2** | CI lint + benchmark jobs | HIGH | M | 6 |
348| **P3** | Mojo kernel compilation | HIGH | XL | 5 |
349| **P3** | Continuous batching | HIGH | XL | 3 |
350| **P3** | PyPI + wheel distribution | MED | L | 6 |
351| **P4** | Type hints + docstrings | LOW | L | 4 |
352| **P4** | Speculative decoding integration | MED | L | 5 |
353| **P4** | Prefix caching integration | MED | S | 5 |
354
355---
356
357## Risk Assessment
358
359| Risk | Likelihood | Impact | Mitigation |
360|------|-----------|--------|------------|
361| Mojo pointer APIs don't stabilize | Medium | High | Keep C engine as fallback (CODING-SOUL already plans this) |
362| MAX graph compiler never ships | Low | Medium | C engine is already competitive; MAX is optional |
363| llama.cpp removes GGUF compatibility | Very Low | High | GGUF spec is open; we can maintain our own reader |
364| Heap corruption in MXFP4 path is systemic | Medium | High | ASAN testing in CI, isolate MXFP4 code path |
365| Python GIL limits concurrent serving | Low | Medium | Already using multiprocessing; consider `multiprocessing` → `ray` migration |
366
367---
368
369## Metrics to Track
370
371| Metric | Current | Target | How |
372|--------|---------|--------|-----|
373| Test coverage | ~5% (ad-hoc scripts) | 60%+ | `pytest --cov` |
374| CI pass rate | N/A (no tests) | 95%+ | OneDev build status |
375| Qwen3.6-35B tok/s | 25.5 (1 user) | 35+ (1 user) | `bench_batch_qwen36.py` |
376| Concurrent throughput | 47 agg (10 users) | 70+ agg (10 users) | `bench_concurrent_qwen36.py` |
377| Memory leaks | Known (heap corruption) | Zero | ASAN + RSS monitoring |
378| Dead code files | 40+ | 0 | `git ls-files` audit |
379| Time to first inference | 4s (worker load) | <2s | mmap optimization |