MojoLlama
Archived Mojo/MAX quantizer and serving research repository (read-only history)
Brought by drakestapleton
MojoLlama / ZIG_ANALYSIS.md
| 1 | # Zig vs C for MojoLlama Engine — Analysis |
| 2 | |
| 3 | ## Current Architecture |
| 4 | |
| 5 | The MojoLlama inference engine is a C AVX2+FMA+OMP pipeline: |
| 6 | - `quant_kernels_omp.c` — quantized matmuls (Q4_K, Q6_K, Q8_0, MXFP4), MoE dispatch |
| 7 | - `cengine_batch_instr.c` — fused batch forward (qwen36, zaya, gemma4) |
| 8 | - `simd_ops.c` — RMS norm, SiLU, softmax |
| 9 | - Combined into `combined_engine.so`, called from Python via ctypes |
| 10 | |
| 11 | ## Zig's Advantages for This Codebase |
| 12 | |
| 13 | | Dimension | C (current) | Zig (proposed) | |
| 14 | |-----------|-------------|----------------| |
| 15 | | **Memory safety** | Manual — buffer overflows common | Built-in bounds checking (release: safety off) | |
| 16 | | **Comptime** | Preprocessor macros only | `comptime` metaprogramming — generate AVX2/AVX512/fallback at compile time | |
| 17 | | **Cross-compilation** | Requires per-target toolchain | Built-in — `zig build -Dtarget=x86_64-linux-gnu` | |
| 18 | | **C ABI** | Natural — C is the ABI | First-class — `callconv(.C)` exports, `@cImport` for C headers | |
| 19 | | **SIMD** | AVX2 intrinsics (`_mm256_*`) | `@cImport` for intrinsics or native `std.simd` (unstable) | |
| 20 | | **Build system** | Makefile/cmake | `build.zig` — single file, hermetic, cross-compiling | |
| 21 | | **Error handling** | Return codes, errno | `!T` error unions, `try`/`catch` | |
| 22 | | **Testing** | No built-in framework | `test` blocks, `zig test` runner | |
| 23 | | **Package management** | None | `zon` packages (immature) | |
| 24 | | **OMP parallelism** | `#pragma omp parallel for` | Not built-in — needs `@cImport` to OMP or manual threading | |
| 25 | | **Ecosystem** | Mature, every library available | Small, growing | |
| 26 | | **Team familiarity** | Universal | Low — small community | |
| 27 | |
| 28 | ## Key Analysis |
| 29 | |
| 30 | ### Memory Safety Is the Biggest Win |
| 31 | |
| 32 | The MojoLlama C engine has had numerous memory bugs: |
| 33 | - Buffer overflows in workspace allocation (qwen36_batch_forward `S=8192` too small for GPT-OSS) |
| 34 | - Pointer corruption from ctypes type-size mismatch (`cf` vs `c_float`) |
| 35 | - Use-after-free in expert weight pointer arrays |
| 36 | - NaN from uninitialized/out-of-bounds reads |
| 37 | |
| 38 | Zig eliminates this class of bugs at compile time with bounds-checked slices, optional pointers, and defined initialization. |
| 39 | |
| 40 | ### OpenMP Gap Is the Biggest Loss |
| 41 | |
| 42 | The C engine gets parallelization for free with `#pragma omp parallel for`. Zig has no built-in equivalent. Options: |
| 43 | 1. `@cImport` calling into OMP C code — works but ugly |
| 44 | 2. `std.Thread.Pool` — manual work decomposition |
| 45 | 3. Simple thread pool — lightweight but needs to be written |
| 46 | |
| 47 | For the MoE dispatch (the hottest path), OMP parallelism is critical. Replacing it would be the hardest part. |
| 48 | |
| 49 | ### Comptime SIMD Dispatch |
| 50 | |
| 51 | Zig's `comptime` can auto-generate AVX2/AVX512/fallback paths: |
| 52 | |
| 53 | ```zig |
| 54 | fn matmul(comptime T: type, w: []const u8, x: []const T, out: []T) void { |
| 55 | if (comptime @import("builtin").target.cpu.features.isEnabled(.avx2)) { |
| 56 | avx2_matmul(w, x, out); |
| 57 | } else { |
| 58 | scalar_matmul(w, x, out); |
| 59 | } |
| 60 | } |
| 61 | ``` |
| 62 | |
| 63 | This eliminates runtime dispatch and `#ifdef` chains. |
| 64 | |
| 65 | ### Feasibility: Phased Adoption |
| 66 | |
| 67 | Given OpenMP dependency and codebase size (~3000 lines C), a full rewrite is not justified. **Recommended: Phased Zig incorporation replacing isolated hot spots.** |
| 68 | |
| 69 | **Phase 1 (NOW)**: Zig shared library wrapping C (Zig calls C quant_matmul_omp). Zero performance change, adds safety layer for new code, demonstrates the bridge. |
| 70 | |
| 71 | **Phase 2**: Port MXFP4 decoder and row dot product to Zig. Currently these are in C with AVX2 intrinsics. A Zig-native version with comptime SIMD dispatch provides the same performance with better safety. |
| 72 | |
| 73 | **Phase 3 (future)**: Port individual quantized matmul kernels (Q4_K first — it's simplest). This requires implementing block-level dequant+dot in Zig, matching or beating C AVX2. |
| 74 | |
| 75 | **Phase 4 (stretch)**: Port the fused batch forward function. This requires solving the OpenMP gap — either OMP interop or manual thread pool. |
| 76 | |
| 77 | ## Recommendation: Keep C for Now, Use Zig for New Kernel Development |
| 78 | |
| 79 | ### Keep C for: |
| 80 | 1. The existing quantized matmul kernels (proven, optimized, OMP-parallel) |
| 81 | 2. The fused batch forward functions (complex, OMP-dependent) |
| 82 | 3. OpenMP-dependent MoE dispatch |
| 83 | |
| 84 | ### Use Zig for: |
| 85 | 1. **New quantization formats** (MXFP8, IQ4_NL, etc.) — Zig's safety catches bugs early |
| 86 | 2. **Kernel validation** — Zig test blocks are better than pytest for C kernel correctness tests |
| 87 | 3. **The autotune engine** — Zig's comptime enables compile-time kernel selection |
| 88 | 4. **CLI tools** — `mojollama quantize`, `mojollama convert` as Zig native binaries (faster startup) |
| 89 | |
| 90 | ### Concrete Next Step |
| 91 | |
| 92 | Add `zig_engine.zig` and `build.zig` to the repo. Include the Zig bridge in CI. Port the MXFP4 dot product to Zig as a proof of concept. Add a `zig build test` step that runs alongside the existing C tests. This incorporates Zig into the project without disrupting the working C engine. |