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 / .hermes / plans / 2026-05-20_1045-hybrid-mxfp4-fp8-moe-tiering.md

476 lines · 17998 bytes Raw Blame History Rendered
1# Hybrid MXFP4→FP8 + Hot/Cold MoE Tiering — Implementation Plan
2
3> **For Hermes:** Execute using subagent-driven-development, targeting GTX 1660 for all non-FP8 work. Ada 2000 needed only for Phase 5.
4
5**Goal:** Build a hybrid GPU/CPU inference backend for MojoLlama that (a) converts MXFP4-quantized weights to FP8 E4M3 for tensor core matmuls on Ada GPUs, (b) profiles expert routing to identify hot/cold experts, and (c) dispatches hot experts to GPU (FP8 tensor cores) and cold experts to CPU (existing C engine).
6
7**Architecture:** Runtime GPU capability detection (`sm_89+` = FP8 path, `sm_70+` = FP16 fallback, else FP32 fallback). MXFP4 weights are converted to FP8 at load time. Expert routing profiler runs once per model, tags experts as hot/cold per layer. Hybrid dispatch sorts the top-K selected experts into GPU list and CPU list, executes both paths in parallel, and combines results weighted by router scores.
8
9**Tech Stack:** C (existing C engine), CUDA C (cuBLAS FP8 matmul wrapper), Python (orchestrator, profiler, conversion), Mojo (optional — MAXBackend for full-GPU fallback).
10
11**Dev strategy:** GTX 1660 (sm_75, no FP8) for Phases 1-4 using FP32 fallback. Ada 2000 for Phase 5 (FP8 activation + benchmark). Everything except the FP8 cuBLAS call compiles and runs on sm_75.
12
13**Dependency:** Existing C engine (`cengine_batch_instr.c`), existing MojoLlama server (`server_moe.py`), existing hardware detection (`detect.py`), existing MXFP4 format (`block_mxfp4`, type 39).
14
15---
16
17## Phase 0: Infrastructure — GPU Capability Detection
18
19### Task 0.1: Add runtime GPU feature detection
20
21**Files:**
22- Modify: `src/mojollama/detect.py` (add `gpu_caps()` function)
23
24Add a function that probes CUDA device properties and returns available features:
25
26```python
27def gpu_caps(dev_id=0) -> dict:
28 """Probe GPU at runtime. Returns format support and VRAM info."""
29 import ctypes
30 # cudaGetDeviceProperties via ctypes
31 props = ... # struct with major, minor, totalGlobalMem, name
32 cc = props.major * 10 + props.minor
33 return {
34 "name": props.name,
35 "cc": f"{props.major}.{props.minor}",
36 "vram_bytes": props.totalGlobalMem,
37 "vram_gb": props.totalGlobalMem / 1e9,
38 "has_fp8_tensor_cores": cc >= 89,
39 "has_fp16_tensor_cores": cc >= 70,
40 "has_tensor_cores": cc >= 70,
41 "best_matmul_format": "fp8" if cc >= 89 else "fp16" if cc >= 70 else "fp32",
42 }
43```
44
45Test: on GTX 1660 returns `has_fp8_tensor_cores=False, best_matmul_format="fp32"`. On Ada 2000 returns `has_fp8_tensor_cores=True, best_matmul_format="fp8"`.
46
47### Task 0.2: Create GPU matmul dispatch wrapper
48
49**Files:**
50- Create: `src/mojollama/backends/gpu_matmul.py`
51
52```python
53class GpuMatmulDispatcher:
54 """Dispatch matmul to best available GPU path based on capability."""
55
56 def __init__(self, dev_id=0):
57 self.caps = gpu_caps(dev_id)
58 self.lib = ctypes.CDLL("libgpu_backend.so") # compiled CUDA wrapper
59
60 def matmul(self, weights_gpu, input_gpu, output_gpu, M, N, K, fmt=None):
61 """Dispatch to best available format."""
62 fmt = fmt or self.caps["best_matmul_format"]
63 if fmt == "fp8":
64 self.lib.fp8_matmul(weights_gpu, input_gpu, output_gpu, M, N, K)
65 elif fmt == "fp16":
66 self.lib.fp16_matmul(weights_gpu, input_gpu, output_gpu, M, N, K)
67 else:
68 self.lib.fp32_matmul(weights_gpu, input_gpu, output_gpu, M, N, K)
69```
70
71### Task 0.3: Create CUDA stub lib that compiles on sm_75 and sm_89
72
73**Files:**
74- Create: `src/mojollama/kernels/gpu_backend.cu`
75- Create: `src/mojollama/kernels/Makefile.gpu`
76
77```
78gpu_backend.cu contains:
79- fp32_matmul() — cublasSgemm, works on ALL CUDA GPUs
80- fp16_matmul() — cublasGemmEx with CUDA_R_16F, works sm_70+
81- fp8_matmul() — cublasLtMatmul with CUBLAS_COMPUTE_32F_FAST_FP8, sm_89+
82 → compiled with --generate-code=arch=compute_89,code=sm_89
83 → on sm_75: stub returns error code at runtime
84```
85
86Makefile compiles two fatbin versions (sm_75 + sm_89). At runtime, CUDA driver loads the matching cubin.
87
88---
89
90## Phase 1: MXFP4 → FP8 Converter
91
92### Task 1.1: Write CPU-side MXFP4 → FP8 E4M3 bit converter
93
94**Files:**
95- Create: `src/mojollama/backends/fp8_convert.py`
96
97```python
98import numpy as np
99
100# MXFP4 constants
101MXFP4_BLOCK_SIZE = 32 # elements per block
102MXFP4_BLOCK_BYTES = 17 # 16 bytes q + 1 byte e
103
104def mxfp4_block_to_fp8_e4m3(q_bytes: np.ndarray, e_byte: int) -> np.ndarray:
105 """Convert one MXFP4 block (32×4bit + E8M0) → 32×FP8 E4M3 bytes.
106
107 This is a pure-Python reference. The GPU kernel will do the same.
108 """
109 # 1. Unpack 16 packed bytes → 32 × 4-bit values
110 nibbles = np.unpackbits(q_bytes, bitorder='little').reshape(-1, 4)
111 # Hmm, actually unpackbits gives bits. We have packed nibbles.
112 # Better: each byte has two 4-bit values: low_nibble, high_nibble
113 low = q_bytes & 0x0F
114 high = (q_bytes >> 4) & 0x0F
115 vals_4bit = np.empty(32, dtype=np.int8)
116 vals_4bit[0::2] = low
117 vals_4bit[1::2] = high
118
119 # 2. Twos-complement decode: nibble > 7 → neg (nibble - 16)
120 vals_int = np.where(vals_4bit > 7, vals_4bit.astype(np.int16) - 16,
121 vals_4bit.astype(np.int16))
122
123 # 3. Apply shared E8M0 scale
124 scale = 2.0 ** (int(e_byte) - 127)
125 vals_f32 = vals_int.astype(np.float32) * scale
126
127 # 4. Clamp to FP8 E4M3 range [-240, 240]
128 vals_f32 = np.clip(vals_f32, -240.0, 240.0)
129
130 # 5. Pack to FP8 E4M3 bit representation
131 # E4M3: sign(1) | exponent(4) | mantissa(3)
132 # Bias = 7
133 fp8_bytes = f32_to_fp8_e4m3(vals_f32)
134 return fp8_bytes
135
136def f32_to_fp8_e4m3(f32_array: np.ndarray) -> np.ndarray:
137 """Convert float32 array to FP8 E4M3 byte array."""
138 # Implementation: handle sign, handle zero/subnorm, normal encode
139 # ...
140 pass
141```
142
143Verification: round-trip test — convert known MXFP4 patterns, verify bit-exact FP8 output matches a CUDA-calculated reference.
144
145### Task 1.2: Write GPU-side MXFP4 → FP8 bulk converter kernel
146
147**Files:**
148- Create: `src/mojollama/kernels/mxfp4_to_fp8.cu`
149
150```cuda
151// Launch config: 256 threads, process N blocks of MXFP4
152// Each thread handles multiple blocks
153__global__ void convert_mxfp4_to_fp8(
154 const uint8_t* src, // MXFP4 blocks, 17 bytes each
155 uint8_t* dst, // FP8 E4M3 bytes, 32 bytes per original block
156 int num_blocks
157) {
158 int tid = blockIdx.x * blockDim.x + threadIdx.x;
159 if (tid >= num_blocks) return;
160
161 const uint8_t* block = src + (size_t)tid * 17;
162 uint8_t e_byte = block[16];
163 float scale = __exp2f((float)(int)e_byte - 127); // 2^(e-127)
164
165 // Unpack 16 bytes → 32 nibbles, sign-extend, scale, pack FP8
166 for (int i = 0; i < 16; i++) {
167 uint8_t low = block[i] & 0x0F;
168 uint8_t high = (block[i] >> 4) & 0x0F;
169 // ... twos-complement, scale, clamp, FP8 pack ...
170 dst[(size_t)tid * 32 + i * 2] = fp8_low;
171 dst[(size_t)tid * 32 + i * 2 + 1] = fp8_high;
172 }
173}
174```
175
176Verification: CPU reference and GPU kernel produce same FP8 bytes for random MXFP4 data. Test passes on both GTX 1660 (convert on CPU, use FP32 fallback) and Ada 2000.
177
178### Task 1.3: Write MXFP4 tensor → FP8 tensor converter (model load time)
179
180**Files:**
181- Modify: `src/mojollama/backends/gpu_matmul.py` (add weight conversion)
182
183At model load time: iterate all MXFP4 (type 39) weight tensors from the GGUF, convert each block to FP8 on GPU, store the FP8 buffer. Original MXFP4 weights remain in CPU memory for cold-expert fallback.
184
185For GPT-OSS-20B (72× MXFP4 experts at ~6MB each = ~430MB to convert): conversion takes ~50ms on GPU. Done once at load, not per-token.
186
187---
188
189## Phase 2: Expert Routing Profiler
190
191### Task 2.1: Add routing statistics collector to MoE engine
192
193**Files:**
194- Modify: `src/mojollama/kernels/turbo_engine_v7_moe.py` (add `profiler.py` hook)
195
196```python
197class RoutingProfiler:
198 """Collect expert routing statistics per layer."""
199
200 def __init__(self, n_layers, n_experts, n_top_k):
201 self.counts = np.zeros((n_layers, n_experts), dtype=np.int64)
202 self.total = 0
203 self.n_top_k = n_top_k
204
205 def record(self, layer, top_indices):
206 """Record which experts were selected for one token."""
207 self.counts[layer, top_indices] += 1
208 self.total += 1
209
210 def summary(self, coverage=0.80):
211 """Return list of hot expert IDs per layer covering `coverage` fraction."""
212 hot_per_layer = []
213 for l in range(self.counts.shape[0]):
214 counts = self.counts[l]
215 order = np.argsort(-counts) # descending
216 cumsum = np.cumsum(counts[order]) / max(1, counts.sum())
217 n_hot = int((cumsum < coverage).sum()) + 1
218 hot_per_layer.append(set(order[:n_hot].tolist()))
219 return hot_per_layer
220```
221
222### Task 2.2: Create hybrid-profile CLI command
223
224**Files:**
225- Modify: `src/mojollama/studio/__init__.py` (add `hybrid-profile` subcommand)
226
227```bash
228mojollama hybrid-profile model.gguf --calibration-file wiki.txt --output routing.json
229
230# Output:
231{
232 "model": "Qwen3-30B-A3B-Instruct-2507-Q4_K_M.gguf",
233 "n_layers": 48,
234 "n_experts": 256,
235 "n_top_k": 8,
236 "tokens_profiled": 8192,
237 "routing": {
238 "layer_0": {"total_hits": 65536, "hot_80pct": [12, 45, 67, ...], "distribution_zipf_param": 1.2},
239 ...
240 }
241}
242```
243
244Verification: run on Qwen3-30B, confirm hot experts are ~20-40 per layer and cover ~80% of routing.
245
246### Task 2.3: Add VRAM budget calculator
247
248**Files:**
249- Create: `src/mojollama/backends/vram_budget.py`
250
251Given GPU VRAM (16GB for Ada 2000, 6GB for GTX 1660) and model metadata, calculate how many hot experts per layer fit in VRAM after MXFP4→FP8 conversion (2× size increase).
252
253```python
254def calc_vram_budget(model_size_gb, gpu_vram_gb, n_layers, n_experts,
255 expert_params_per_layer_mb, conversion_expansion=2.0):
256 """Calculate max hot experts per layer given VRAM constraints."""
257 model_on_gpu = model_size_gb * conversion_expansion # if converting all
258 available = gpu_vram_gb - 2.0 # 2GB reserve for KV cache + buffers
259 expert_mb = n_layers * n_experts * expert_params_per_layer_mb
260 hot_fraction = available / (expert_mb / 1024 * conversion_expansion)
261 return max(1, int(n_experts * hot_fraction))
262```
263
264---
265
266## Phase 3: Hybrid GGUF Format
267
268### Task 3.1: Define hybrid metadata schema
269
270**Files:**
271- Create: `src/mojollama/backends/hybrid_schema.py`
272
273```python
274HYBRID_METADATA_KEYS = {
275 "hybrid.enabled": "bool",
276 "hybrid.hot_experts": "json", # per-layer list of hot expert IDs
277 "hybrid.profile": "json", # routing_profile.json embedded
278 "hybrid.conversion": "json", # {hot_format, cold_format, vram_usage}
279 "hybrid.gpu_caps_min": "string", # minimal CC e.g. "8.9" for FP8
280}
281```
282
283### Task 3.2: Write hybrid-convert CLI command
284
285**Files:**
286- Create: `src/mojollama/studio/cmd_hybrid_convert.py`
287- Modify: `src/mojollama/studio/__init__.py` (register subcommand)
288
289```bash
290mojollama hybrid-convert model.gguf \
291 --profile routing.json \
292 --hot-experts 32 \
293 --dry-run
294# Output: "Would tag 32 experts/layer as GPU-hot. VRAM estimate: 14.2 GB. Suitable for RTX 2000 Ada."
295
296mojollama hybrid-convert model.gguf \
297 --profile routing.json \
298 --hot-experts 40 \
299 --output model.hybrid.gguf
300# Writes same GGUF with added hybrid metadata keys
301# Does NOT rewrite weights — just adds metadata
302```
303
304---
305
306## Phase 4: Hybrid Inference Orchestrator
307
308### Task 4.1: Build GPU expert weight manager
309
310**Files:**
311- Create: `src/mojollama/backends/gpu_weights.py`
312
313```python
314class GpuExpertManager:
315 """Manages hot expert weights on GPU."""
316
317 def __init__(self, caps, dispatcher):
318 self.caps = caps
319 self.dispatcher = dispatcher
320 self.hot_ptrs = {} # (layer, expert_id) → GPU pointer
321 self.gpu_mem_pool = []
322
323 def load_hot_experts(self, model, hot_map):
324 """Convert hot expert MXFP4→FP8 and upload to GPU."""
325 total_bytes = 0
326 for layer in range(model.n_layers):
327 for eid in hot_map[layer]:
328 src = model.get_expert_weights(layer, eid) # MXFP4 bytes
329 fp8_bytes = convert_mxfp4_to_fp8(src) # Task 1.1
330 gpu_ptr = cuda_malloc(fp8_bytes.nbytes)
331 cuda_memcpy_htod(gpu_ptr, fp8_bytes)
332 self.hot_ptrs[(layer, eid)] = gpu_ptr
333 total_bytes += fp8_bytes.nbytes
334 return total_bytes
335```
336
337### Task 4.2: Build hybrid MoE FFN dispatcher
338
339**Files:**
340- Create: `src/mojollama/backends/hybrid_ffn.py`
341
342```python
343class HybridMoEFFN:
344 """Route selected experts to GPU (hot) or CPU (cold), combine results."""
345
346 def __init__(self, engine, gpu_mgr, hot_map):
347 self.engine = engine # CPU C engine
348 self.gpu = gpu_mgr # GPU weight manager
349 self.hot_map = hot_map # per-layer set of hot expert IDs
350
351 def forward(self, layer, x_hidden_state, top_indices, top_weights):
352 hot_list = [e for e in top_indices if e in self.hot_map[layer]]
353 cold_list = [e for e in top_indices if e not in self.hot_map[layer]]
354
355 result = np.zeros_like(x_hidden_state)
356
357 # GPU path: batch all hot experts into one GPU matmul call
358 if hot_list:
359 gpu_out = self.gpu.batch_expert_ffn(layer, hot_list, x_hidden_state)
360 result += self._weighted_sum(gpu_out, hot_list, top_weights)
361
362 # CPU path: existing C engine for cold experts
363 if cold_list:
364 cpu_out = self.engine.cpu_expert_ffn(layer, cold_list, x_hidden_state)
365 result += self._weighted_sum(cpu_out, cold_list, top_weights)
366
367 return result
368```
369
370### Task 4.3: Integrate into server_moe.py
371
372**Files:**
373- Modify: `src/mojollama/server_moe.py` (add `--hybrid` flag)
374
375```python
376if args.hybrid:
377 caps = gpu_caps()
378 if caps["vram_gb"] < model_size_gb * 0.5:
379 print(f"[Hybrid] GPU VRAM ({caps['vram_gb']:.0f}GB) < model, enabling hot/cold tiering")
380 hot_map = load_hot_map(args.hybrid) # from GGUF metadata
381 gpu_mgr = GpuExpertManager(caps, dispatcher)
382 gpu_mgr.load_hot_experts(engine.model, hot_map)
383 engine.moe_ffn = HybridMoEFFN(engine, gpu_mgr, hot_map)
384```
385
386---
387
388## Phase 5: FP8 Tensor Core Activation (Ada 2000 Only)
389
390### Task 5.1: Write cuBLAS FP8 matmul wrapper
391
392**Files:**
393- Modify: `src/mojollama/kernels/gpu_backend.cu` (add fp8_matmul)
394
395```cuda
396// sm_89+ only — guard with __CUDA_ARCH__ >= 890
397cudaError_t fp8_matmul(const void* A, const void* B, void* C,
398 int M, int N, int K) {
399#if __CUDA_ARCH__ >= 890
400 cublasLtMatmulDesc_t op_desc;
401 cublasLtMatmulDescCreate(&op_desc, CUBLAS_COMPUTE_32F_FAST_FP8);
402
403 cublasLtMatrixLayout_t Adesc, Bdesc, Cdesc;
404 cublasLtMatrixLayoutCreate(&Adesc, CUDA_R_8F_E4M3, M, K, M);
405 cublasLtMatrixLayoutCreate(&Bdesc, CUDA_R_8F_E4M3, K, N, K);
406 cublasLtMatrixLayoutCreate(&Cdesc, CUDA_R_32F, M, N, M);
407
408 cublasLtMatmul(handle, op_desc,
409 &alpha, A, Adesc, B, Bdesc, &beta, C, Cdesc, Cdesc,
410 NULL, NULL, 0);
411 return CUBLAS_STATUS_SUCCESS;
412#else
413 return CUBLAS_STATUS_NOT_SUPPORTED;
414#endif
415}
416```
417
418### Task 5.2: Add FP8 weight pre-packing to GpuExpertManager
419
420On Ada 2000, the MXFP4→FP8 conversion (Task 1.1) runs on GPU as a pre-processing kernel (Task 1.2). This happens once at model load and takes <100ms for all hot expert weights.
421
422### Task 5.3: End-to-end benchmark
423
424**Files:**
425- Modify: `src/mojollama/bench_tok.py` (add `--hybrid` flag)
426
427```bash
428# Qwen3-30B on Ada 2000, hybrid mode
429OMP_NUM_THREADS=32 python3 -u bench_tok.py \
430 --model /tmp/models/qwen3.hybrid.gguf \
431 --hybrid
432
433# Baseline: CPU-only
434OMP_NUM_THREADS=32 python3 -u bench_tok.py \
435 --model /tmp/models/Qwen3-30B.gguf
436
437# Baseline: llama.cpp on CPU
438/tmp/llama.cpp/build/bin/llama-bench -m /tmp/models/Qwen3-30B.gguf -n 128 -t 32 -p 512 -r 3
439```
440
441Track: tok/s, ms/token, CPU→GPU transfer bytes/token, hot/cold hit rate.
442
443---
444
445## File Inventory
446
447### New files (~1,800 lines total):
448- `src/mojollama/backends/gpu_matmul.py` — GPU matmul dispatch (150 lines)
449- `src/mojollama/backends/fp8_convert.py` — MXFP4↔FP8 converter (200 lines)
450- `src/mojollama/backends/vram_budget.py` — VRAM budget calculator (80 lines)
451- `src/mojollama/backends/hybrid_schema.py` — hybrid GGUF metadata schema (50 lines)
452- `src/mojollama/backends/gpu_weights.py` — GPU expert weight manager (200 lines)
453- `src/mojollama/backends/hybrid_ffn.py` — Hybrid MoE FFN dispatcher (300 lines)
454- `src/mojollama/kernels/gpu_backend.cu` — CUDA matmul wrappers (300 lines)
455- `src/mojollama/kernels/mxfp4_to_fp8.cu` — GPU MXFP4→FP8 converter (200 lines)
456- `src/mojollama/kernels/Makefile.gpu` — GPU kernel build (40 lines)
457- `src/mojollama/studio/cmd_hybrid_convert.py` — CLI command (150 lines)
458- `tests/test_hybrid_*.py` — test suite (~5 files, 400 lines total)
459
460### Modified files:
461- `src/mojollama/detect.py` — add `gpu_caps()` (+40 lines)
462- `src/mojollama/server_moe.py` — add `--hybrid` flag (+80 lines)
463- `src/mojollama/studio/__init__.py` — register hybrid-* subcommands (+20 lines)
464- `src/mojollama/kernels/turbo_engine_v7_moe.py` — add profiler hook (+60 lines)
465
466---
467
468## Verification Milestones
469
4701. `gpu_caps()` returns correct capabilities on GTX 1660 (fp32) and Ada 2000 (fp8)
4712. MXFP4→FP8 round-trip: same float32 values (±1ULP) for random test data
4723. Routing profiler on Qwen3-30B produces Zipfian distribution, hot-80% = ~30 experts/layer
4734. Hybrid GGUF written and re-read with correct metadata
4745. `--hybrid` server runs on GTX 1660 with FP32 fallback — correct output, all tests pass
4756. `--hybrid` server on Ada 2000 with FP8 — correct output, 1.5-2× tok/s vs CPU-only
4767. Benchmark: hot coverage ≥80%, cold expert overhead <10% of total time