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 / ZIG_ANALYSIS.md

92 lines · 4838 bytes Raw Blame History Source

Zig vs C for MojoLlama Engine — Analysis

Current Architecture

The MojoLlama inference engine is a C AVX2+FMA+OMP pipeline:

Zig's Advantages for This Codebase

DimensionC (current)Zig (proposed)
Memory safetyManual — buffer overflows commonBuilt-in bounds checking (release: safety off)
ComptimePreprocessor macros onlycomptime metaprogramming — generate AVX2/AVX512/fallback at compile time
Cross-compilationRequires per-target toolchainBuilt-in — zig build -Dtarget=x86_64-linux-gnu
C ABINatural — C is the ABIFirst-class — callconv(.C) exports, @cImport for C headers
SIMDAVX2 intrinsics (_mm256_*)@cImport for intrinsics or native std.simd (unstable)
Build systemMakefile/cmakebuild.zig — single file, hermetic, cross-compiling
Error handlingReturn codes, errno!T error unions, try/catch
TestingNo built-in frameworktest blocks, zig test runner
Package managementNonezon packages (immature)
OMP parallelism#pragma omp parallel forNot built-in — needs @cImport to OMP or manual threading
EcosystemMature, every library availableSmall, growing
Team familiarityUniversalLow — small community

Key Analysis

Memory Safety Is the Biggest Win

The MojoLlama C engine has had numerous memory bugs:

Zig eliminates this class of bugs at compile time with bounds-checked slices, optional pointers, and defined initialization.

OpenMP Gap Is the Biggest Loss

The C engine gets parallelization for free with #pragma omp parallel for. Zig has no built-in equivalent. Options:

  1. @cImport calling into OMP C code — works but ugly
  2. std.Thread.Pool — manual work decomposition
  3. Simple thread pool — lightweight but needs to be written

For the MoE dispatch (the hottest path), OMP parallelism is critical. Replacing it would be the hardest part.

Comptime SIMD Dispatch

Zig's comptime can auto-generate AVX2/AVX512/fallback paths:

fn matmul(comptime T: type, w: []const u8, x: []const T, out: []T) void {
    if (comptime @import("builtin").target.cpu.features.isEnabled(.avx2)) {
        avx2_matmul(w, x, out);
    } else {
        scalar_matmul(w, x, out);
    }
}

This eliminates runtime dispatch and #ifdef chains.

Feasibility: Phased Adoption

Given OpenMP dependency and codebase size (~3000 lines C), a full rewrite is not justified. Recommended: Phased Zig incorporation replacing isolated hot spots.

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.

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.

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.

Phase 4 (stretch): Port the fused batch forward function. This requires solving the OpenMP gap — either OMP interop or manual thread pool.

Recommendation: Keep C for Now, Use Zig for New Kernel Development

Keep C for:

  1. The existing quantized matmul kernels (proven, optimized, OMP-parallel)
  2. The fused batch forward functions (complex, OMP-dependent)
  3. OpenMP-dependent MoE dispatch

Use Zig for:

  1. New quantization formats (MXFP8, IQ4_NL, etc.) — Zig's safety catches bugs early
  2. Kernel validation — Zig test blocks are better than pytest for C kernel correctness tests
  3. The autotune engine — Zig's comptime enables compile-time kernel selection
  4. CLI tools — mojollama quantize, mojollama convert as Zig native binaries (faster startup)

Concrete Next Step

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.