diff --git a/crates/aien-inference-abi/examples/qwen3_moe_bench.rs b/crates/aien-inference-abi/examples/qwen3_moe_bench.rs new file mode 100644 index 00000000..fb98f98c --- /dev/null +++ b/crates/aien-inference-abi/examples/qwen3_moe_bench.rs @@ -0,0 +1,160 @@ +//! Batch-size curve for one official Qwen3-Coder-A3B FP8 expert layer on GB10. +//! +//! cargo run --release -p aien-inference-abi --example qwen3_moe_bench -- \ +//! [--layer 0] [--tokens 1,8,16,32,64,128,256,500,1024] \ +//! [--warmup 1] [--repeats 5] [--seed 42] [--out receipt.json] +//! +//! Prints a JSON receipt that identifies exactly what produced each timing: +//! git commit, capsule digest, kernel source and library digests, Mojo version, +//! driver/CUDA version, device name, input seed and digest, and raw samples. + +use aien_inference_abi::{ + load_qwen3_fp8_moe_layer, reference_router_logits, seeded_bf16_input, source_digest, + MoeBatchPlan, Qwen3MoeKernels, +}; +use std::path::{Path, PathBuf}; +use std::process::Command; + +fn command_output(program: &str, args: &[&str]) -> String { + Command::new(program) + .args(args) + .output() + .ok() + .filter(|o| o.status.success()) + .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string()) + .unwrap_or_else(|| "unavailable".to_string()) +} + +fn file_digest(path: &Path) -> String { + std::fs::read(path) + .map(|bytes| source_digest(&bytes)) + .unwrap_or_else(|e| format!("unreadable: {e}")) +} + +fn peak_host_rss_bytes() -> u64 { + std::fs::read_to_string("/proc/self/status") + .ok() + .and_then(|status| { + status + .lines() + .find(|l| l.starts_with("VmHWM:")) + .and_then(|l| l.split_whitespace().nth(1)?.parse::().ok()) + }) + .map(|kib| kib * 1024) + .unwrap_or(0) +} + +fn median(samples: &mut [u64]) -> f64 { + samples.sort_unstable(); + let n = samples.len(); + if n % 2 == 1 { + samples[n / 2] as f64 + } else { + (samples[n / 2 - 1] + samples[n / 2]) as f64 / 2.0 + } +} + +fn main() { + let mut args = std::env::args().skip(1); + let checkpoint = PathBuf::from( + args.next() + .expect("usage: qwen3_moe_bench [options]"), + ); + let (mut layer_index, mut warmup, mut repeats, mut seed) = (0usize, 1usize, 5usize, 42u64); + let mut token_counts = vec![1usize, 8, 16, 32, 64, 128, 256, 500, 1024]; + let mut out: Option = None; + while let Some(flag) = args.next() { + let value = args + .next() + .unwrap_or_else(|| panic!("{flag} needs a value")); + match flag.as_str() { + "--layer" => layer_index = value.parse().expect("--layer"), + "--warmup" => warmup = value.parse().expect("--warmup"), + "--repeats" => repeats = value.parse().expect("--repeats"), + "--seed" => seed = value.parse().expect("--seed"), + "--tokens" => { + token_counts = value + .split(',') + .map(|t| t.parse().expect("--tokens")) + .collect() + } + "--out" => out = Some(PathBuf::from(value)), + other => panic!("unknown flag {other}"), + } + } + + let kernels = Qwen3MoeKernels::load(&Qwen3MoeKernels::default_path()) + .expect("build mojo/qwen3_moe first"); + let layer = load_qwen3_fp8_moe_layer(&checkpoint, layer_index).expect("load layer"); + let kernel_dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("mojo/qwen3_moe"); + + let mut points = Vec::new(); + for &tokens in &token_counts { + let (bits, x) = seeded_bf16_input(seed, tokens, layer.hidden, 0.25); + let input_bytes: Vec = bits.iter().flat_map(|b| b.to_le_bytes()).collect(); + let mut samples = kernels + .benchmark(&layer, &bits, tokens, warmup, repeats) + .expect("benchmark"); + let raw_samples = samples.clone(); + let median_ns = median(&mut samples); + let plan = + MoeBatchPlan::qwen3_coder_a3b(&reference_router_logits(&layer, &x, tokens), tokens) + .expect("routing"); + let telemetry = plan.telemetry(); + eprintln!( + "tokens={tokens:5} median={:9.3} ms {:9.1} tok/s", + median_ns / 1e6, + tokens as f64 / (median_ns / 1e9) + ); + points.push(serde_json::json!({ + "tokens": tokens, + "assignments": tokens * 8, + "input_seed": seed, + "input_digest": source_digest(&input_bytes), + "layer_latency_ms_median": median_ns / 1e6, + "layer_tokens_per_sec_median": tokens as f64 / (median_ns / 1e9), + "assignments_per_sec_median": (tokens * 8) as f64 / (median_ns / 1e9), + "samples_ns": raw_samples, + "experts_touched": telemetry.experts_touched, + "expert_batch_p50": telemetry.expert_batch_p50, + "expert_batch_p95": telemetry.expert_batch_p95, + "expert_batch_max": telemetry.max_expert_batch, + "routing_entropy_bits": telemetry.routing_entropy_bits, + })); + } + + let receipt = serde_json::json!({ + "model": "Qwen/Qwen3-Coder-30B-A3B-Instruct-FP8", + "layer": layer_index, + "expert_compute": "native grouped FP8 E4M3 mma.sync m16n8k32 (Mojo, SM121a)", + "weight_dtype": "fp8_e4m3fn with bf16 128x128 inverse scales", + "resident_dtype": "fp8_e4m3fn", + "activation_quantization": "fp8_e4m3fn per row and 128 channels, fp32 scales", + "capsule_digest": layer.capsule.capsule_digest, + "capsule_source_digest": layer.capsule.source_digest, + "checkpoint_index_digest": file_digest(&checkpoint.join("model.safetensors.index.json")), + "resident_weight_bytes": layer.resident_weight_bytes(), + "git_commit": command_output("git", &["-C", env!("CARGO_MANIFEST_DIR"), "rev-parse", "HEAD"]), + "git_dirty": !command_output("git", &["-C", env!("CARGO_MANIFEST_DIR"), "status", "--porcelain"]).is_empty(), + "kernel_source_digests": { + "kernels.mojo": file_digest(&kernel_dir.join("kernels.mojo")), + "lib.mojo": file_digest(&kernel_dir.join("lib.mojo")), + }, + "kernel_library": kernels.path.display().to_string(), + "kernel_library_digest": file_digest(&kernels.path), + "mojo_version": command_output("mojo", &["--version"]), + "gpu": command_output("nvidia-smi", &["--query-gpu=name,driver_version,compute_cap", "--format=csv,noheader"]), + "cuda_version": command_output("nvidia-smi", &[]).lines().find(|l| l.contains("CUDA Version")).map(|l| l.trim().to_string()).unwrap_or_default(), + "warmup": warmup, + "repeats": repeats, + "timing": "wall time from first enqueue to device synchronize, weights and input resident", + "peak_host_rss_bytes": peak_host_rss_bytes(), + "note": "one MoE layer; excludes attention, norms, embedding and sampling", + "points": points, + }); + let text = serde_json::to_string_pretty(&receipt).unwrap(); + match out { + Some(path) => std::fs::write(&path, text + "\n").expect("write receipt"), + None => println!("{text}"), + } +} diff --git a/crates/aien-inference-abi/max/FP8_GROUPED_KERNEL.md b/crates/aien-inference-abi/max/FP8_GROUPED_KERNEL.md deleted file mode 100644 index 9dd4050f..00000000 --- a/crates/aien-inference-abi/max/FP8_GROUPED_KERNEL.md +++ /dev/null @@ -1,22 +0,0 @@ -# Grouped FP8 expert GEMM prototype - -`kernels/qwen3_fp8_gemm.mojo` registers `aien.qwen3_moe.grouped_fp8_gemm`. -It consumes grouped FP8 E4M3 activations `[assignments, K]`, FP32 inverse -activation scales `[assignments, K/128]`, checkpoint FP8 E4M3 weights -`[experts, N, K]`, BF16 inverse weight scales `[experts, N/128, K/128]`, -and expert offsets `[experts+1]`. It returns FP32 `[assignments, N]`. -The weights remain packed FP8 throughout. One warp owns one expert and eight -output channels, walks that expert's ragged token rows in groups of 16, and -uses `mma.sync.aligned.m16n8k32.row.col.f32.e4m3.e4m3.f32`. The result of -each 128-channel K block is multiplied by the corresponding activation and -weight inverse scales before accumulation. Both Qwen gate/up and down -projections fit this contract. - -This primitive expects activations quantized to E4M3 in 128-channel blocks -with a corresponding inverse scale. Activation quantization and integration -with the layer graph are separate work. The standalone GPU parity test is -`test_fp8_grouped_gemm.py`; it checks ragged expert offsets, every MMA -fragment position, both K blocks, and distinct weight and activation scales. -The test is required before using the kernel for model inference. - -Reference: [PTX m16n8k32 fragment layout](https://docs.nvidia.com/cuda/parallel-thread-execution/index.html#matrix-fragments-for-mma-m16n8k32). diff --git a/crates/aien-inference-abi/max/README.md b/crates/aien-inference-abi/max/README.md deleted file mode 100644 index e74fbb71..00000000 --- a/crates/aien-inference-abi/max/README.md +++ /dev/null @@ -1,61 +0,0 @@ -# Qwen3-Coder-30B-A3B MoE layer on Mojo and MAX - -This directory contains an executable MoE layer for the official -`Qwen/Qwen3-Coder-30B-A3B-Instruct-FP8` checkpoint. It is an accelerator -implementation, separate from the existing dense FP32 executor. - -The checkpoint reader validates safetensors names, dtypes, shapes and byte -ranges against the Qwen3-Coder-A3B layer contract. It mmaps one shard and -packs 128 experts into FP8 E4M3 gate/up and down tensors. Router and 128x128 -inverse scales stay BF16. The Mojo upload kernel reads FP8 bytes and BF16 -scales on the GPU. It creates BF16 resident expert buffers once per layer, -without constructing a complete FP32 model copy. - -The MAX execution graph performs: - -1. BF16 router matmul, FP32 top-8 routing and normalization in a Mojo GPU op. -2. Token-to-expert permutation and expert offsets with MAX MoE index ops. -3. Grouped BF16 gate/up GEMM, SwiGLU, grouped BF16 down GEMM. -4. Inverse permutation and weighted reduction to the original token order. - -The Rust `MoeBatchPlan` provides a deterministic routing oracle, inverse map -and per-expert telemetry. Its 500-token test covers all assignment slots. - -## Verification - -Run the synthetic GPU parity test: - -```bash -python crates/aien-inference-abi/max/test_qwen3_moe.py -``` - -With the official checkpoint index and the shard containing layer 0: - -```bash -OPENBLAS_NUM_THREADS=1 python crates/aien-inference-abi/max/verify_real_layer.py \ - /path/to/Qwen3-Coder-30B-A3B-Instruct-FP8 --layer 0 - -OPENBLAS_NUM_THREADS=1 python crates/aien-inference-abi/max/benchmark_moe_layer.py \ - /path/to/Qwen3-Coder-30B-A3B-Instruct-FP8 --layer 0 --tokens 500 -``` - -The real-layer verifier compares MAX output against a CPU calculation that -decodes only the eight selected experts. On GB10, layer 0 with an all-ones -input produced cosine similarity 0.99998766 and p95 relative error 2.13%. -The 500-token layer benchmark touched all 128 experts and measured median -165.2 ms across three runs. These are layer measurements, not full-model -generation results. - -## Current boundary - -MAX 26.5's block-scaled FP8 grouped GEMM rejects SM121a at graph compile -time, so the GB10 path stages each layer in BF16 device memory before grouped -GEMM. The packed FP8 bytes are consumed directly by the Mojo upload kernel. -Full-model residency, attention, tokenizer integration, Rust scheduler wiring -and token generation are outside this layer implementation. The BF16 staging -would require about twice the FP8 expert weight memory if retained across all -48 layers. A native SM121a grouped FP8 kernel is the next performance step. - -Sources: [Qwen3-Coder checkpoint](https://huggingface.co/Qwen/Qwen3-Coder-30B-A3B-Instruct-FP8), -[Modular custom ops](https://docs.modular.com/develop/build-custom-ops), -[MAX grouped FP8 API](https://docs.modular.com/api/mojo/linalg/grouped_matmul_sm100_blockwise_fp8/grouped_matmul_sm100_blockwise_scaled_fp8). diff --git a/crates/aien-inference-abi/max/benchmark_moe_layer.py b/crates/aien-inference-abi/max/benchmark_moe_layer.py deleted file mode 100644 index 6a528292..00000000 --- a/crates/aien-inference-abi/max/benchmark_moe_layer.py +++ /dev/null @@ -1,79 +0,0 @@ -"""Measure routed Qwen3 expert layer throughput across AIEN branch tokens.""" - -import argparse -import json -from pathlib import Path -import time - -import numpy as np -from max.driver import Accelerator, Buffer, CPU -from max.dtype import DType -from max.engine import InferenceSession -from max.graph import DeviceRef - -from checkpoint_fp8 import load_fp8_moe_layer -from qwen3_moe import Qwen3MoeShape, build_fp8_unpack_graph, build_qwen3_moe_graph - - -def main() -> None: - parser = argparse.ArgumentParser() - parser.add_argument("checkpoint_dir", type=Path) - parser.add_argument("--layer", type=int, default=0) - parser.add_argument("--tokens", type=int, default=500) - parser.add_argument("--repeats", type=int, default=3) - args = parser.parse_args() - if args.tokens < 1 or args.repeats < 1: - parser.error("tokens and repeats must be positive") - - packed = load_fp8_moe_layer(args.checkpoint_dir, args.layer) - device = Accelerator() - ref = DeviceRef.from_device(device) - session = InferenceSession(devices=[device]) - shape = Qwen3MoeShape(tokens=args.tokens) - unpack = session.init(session.compile(build_fp8_unpack_graph(shape, ref))) - layer = session.init(session.compile(build_qwen3_moe_graph(shape, ref))) - router, gate_up, gate_up_scales, down, down_scales = packed.to_device(device) - resident_gate_up, resident_down = unpack.execute( - gate_up, gate_up_scales, down, down_scales - ) - del gate_up, gate_up_scales, down, down_scales - - rng = np.random.default_rng(42) - x = rng.normal(0.0, 0.25, (args.tokens, 2048)).astype(np.float32) - x_bits = (x.view(np.uint32) >> 16).astype(np.uint16) - x = (x_bits.astype(np.uint32) << 16).view(np.float32) - x_device = Buffer.from_numpy(x_bits).view(DType.bfloat16).to(device) - - def run_once() -> float: - started = time.perf_counter() - output = layer.execute(x_device, router, resident_gate_up, resident_down)[0] - output.to(CPU()) # Synchronize the device queue for a complete layer time. - return time.perf_counter() - started - - run_once() - timings = [run_once() for _ in range(args.repeats)] - router_f32 = (packed.router_bf16.astype(np.uint32) << 16).view(np.float32) - logits = x @ router_f32.T - selected = np.argsort(-logits, axis=1, kind="stable")[:, :8] - counts = np.bincount(selected.reshape(-1), minlength=128) - active = counts[counts > 0] - probability = active / active.sum() - receipt = { - "model": "Qwen3-Coder-30B-A3B-Instruct-FP8", - "layer": args.layer, - "tokens": args.tokens, - "top_k": 8, - "experts_touched": int(active.size), - "expert_batch_p50": float(np.percentile(active, 50)), - "expert_batch_p95": float(np.percentile(active, 95)), - "routing_entropy_bits": float(-(probability * np.log2(probability)).sum()), - "layer_latency_ms_median": float(np.median(timings) * 1e3), - "layer_tokens_per_sec_median": float(args.tokens / np.median(timings)), - "timings_sec": timings, - "note": "one MoE layer, excludes attention, norms, embedding and sampling", - } - print(json.dumps(receipt, indent=2)) - - -if __name__ == "__main__": - main() diff --git a/crates/aien-inference-abi/max/checkpoint_fp8.py b/crates/aien-inference-abi/max/checkpoint_fp8.py deleted file mode 100644 index 41c99f30..00000000 --- a/crates/aien-inference-abi/max/checkpoint_fp8.py +++ /dev/null @@ -1,123 +0,0 @@ -"""Strict, sharded Qwen3-Coder-A3B FP8 expert ingest for MAX. - -This reads raw safetensors bytes with mmap. Expert weights remain uint8 FP8 -payloads and inverse scales remain BF16 bits until MAX receives them. -""" - -from contextlib import ExitStack -from dataclasses import dataclass -import json -import mmap -from pathlib import Path -import struct - -import numpy as np -from max.driver import Buffer, Device -from max.dtype import DType - - -@dataclass -class PackedMoeLayer: - router_bf16: np.ndarray - gate_up_fp8: np.ndarray - gate_up_scales_bf16: np.ndarray - down_fp8: np.ndarray - down_scales_bf16: np.ndarray - - def to_device(self, device: Device) -> tuple[Buffer, Buffer, Buffer, Buffer, Buffer]: - def bf16(bits: np.ndarray) -> Buffer: - return Buffer.from_numpy(bits).view(DType.bfloat16).to(device) - - def fp8(bits: np.ndarray) -> Buffer: - return Buffer.from_numpy(bits).view(DType.float8_e4m3fn).to(device) - - return ( - bf16(self.router_bf16), - fp8(self.gate_up_fp8), - bf16(self.gate_up_scales_bf16), - fp8(self.down_fp8), - bf16(self.down_scales_bf16), - ) - - -class SafetensorsShard: - def __init__(self, path: Path) -> None: - self._file = path.open("rb") - self._mapping = mmap.mmap(self._file.fileno(), 0, access=mmap.ACCESS_READ) - if len(self._mapping) < 8: - raise ValueError(f"truncated safetensors shard: {path}") - header_size = struct.unpack_from(" len(self._mapping): - raise ValueError(f"invalid safetensors header size: {path}") - self._header = json.loads(self._mapping[8 : self._payload_start]) - - def __enter__(self) -> "SafetensorsShard": - return self - - def __exit__(self, *_unused: object) -> None: - self._mapping.close() - self._file.close() - - def tensor(self, name: str, dtype: str, shape: tuple[int, ...]) -> np.ndarray: - entry = self._header.get(name) - if entry is None: - raise KeyError(f"missing checkpoint tensor: {name}") - if entry["dtype"] != dtype or tuple(entry["shape"]) != shape: - raise ValueError(f"checkpoint tensor contract mismatch: {name}: {entry}") - raw_dtype = {"F8_E4M3": np.uint8, "BF16": np.uint16}[dtype] - start, end = entry["data_offsets"] - byte_count = int(np.prod(shape)) * np.dtype(raw_dtype).itemsize - if start < 0 or end - start != byte_count or self._payload_start + end > len(self._mapping): - raise ValueError(f"checkpoint tensor byte range mismatch: {name}") - return np.ndarray( - shape, - dtype=raw_dtype, - buffer=self._mapping, - offset=self._payload_start + start, - ) - - -def load_fp8_moe_layer(checkpoint_dir: Path, layer: int) -> PackedMoeLayer: - """Pack one official FP8 layer without decoding any expert matrix to FP32.""" - if layer < 0 or layer >= 48: - raise ValueError("Qwen3-Coder-30B-A3B layer must be in [0, 48)") - index_path = checkpoint_dir / "model.safetensors.index.json" - index = json.loads(index_path.read_text()) - weight_map = index["weight_map"] - prefix = f"model.layers.{layer}.mlp" - - with ExitStack() as stack: - shards: dict[str, SafetensorsShard] = {} - - def tensor(name: str, dtype: str, shape: tuple[int, ...]) -> np.ndarray: - filename = weight_map.get(name) - if filename is None: - raise KeyError(f"missing checkpoint index entry: {name}") - if filename not in shards: - shards[filename] = stack.enter_context(SafetensorsShard(checkpoint_dir / filename)) - return shards[filename].tensor(name, dtype, shape) - - router = np.array(tensor(f"{prefix}.gate.weight", "BF16", (128, 2048))) - gate_up = np.empty((128, 1536, 2048), dtype=np.uint8) - gate_up_scales = np.empty((128, 12, 16), dtype=np.uint16) - down = np.empty((128, 2048, 768), dtype=np.uint8) - down_scales = np.empty((128, 16, 6), dtype=np.uint16) - for expert in range(128): - base = f"{prefix}.experts.{expert}" - for offset, projection in ((0, "gate_proj"), (768, "up_proj")): - name = f"{base}.{projection}" - gate_up[expert, offset : offset + 768] = tensor( - f"{name}.weight", "F8_E4M3", (768, 2048) - ) - gate_up_scales[expert, offset // 128 : (offset + 768) // 128] = tensor( - f"{name}.weight_scale_inv", "BF16", (6, 16) - ) - down[expert] = tensor( - f"{base}.down_proj.weight", "F8_E4M3", (2048, 768) - ) - down_scales[expert] = tensor( - f"{base}.down_proj.weight_scale_inv", "BF16", (16, 6) - ) - - return PackedMoeLayer(router, gate_up, gate_up_scales, down, down_scales) diff --git a/crates/aien-inference-abi/max/kernels/__init__.mojo b/crates/aien-inference-abi/max/kernels/__init__.mojo deleted file mode 100644 index 62f5dd36..00000000 --- a/crates/aien-inference-abi/max/kernels/__init__.mojo +++ /dev/null @@ -1,2 +0,0 @@ -# AIEN MAX custom operators. -from .qwen3_fp8_gemm import Qwen3GroupedFp8Gemm diff --git a/crates/aien-inference-abi/max/kernels/qwen3_fp8_gemm.mojo b/crates/aien-inference-abi/max/kernels/qwen3_fp8_gemm.mojo deleted file mode 100644 index 833ca8ce..00000000 --- a/crates/aien-inference-abi/max/kernels/qwen3_fp8_gemm.mojo +++ /dev/null @@ -1,123 +0,0 @@ -"""Grouped FP8 E4M3 GEMM for GB10, 16x8x32 warp MMA. - -Inputs are grouped token rows, packed row-major [expert, output, input] -checkpoint weights, BF16 inverse scales per 128x128 weight block, -FP32 activation inverse scales per token and 128 input channels, and -expert offsets. FP8 weight storage is never expanded to BF16. -""" - -import extensibility -from extensibility import InputTensor, OutputTensor, ManagedTensorSlice -from max.gpu.host import DeviceContext -from std.gpu import block_idx, thread_idx -from std.sys._assembly import inlined_assembly -from std.sys import _RegisterPackType -from std.memory import bitcast -from std.utils.index import IndexList - - -def mma_e4m3(a: SIMD[DType.uint32, 4], b: SIMD[DType.uint32, 2], partial: SIMD[DType.float32, 4]) -> SIMD[DType.float32, 4]: - var mma = inlined_assembly[ - "mma.sync.aligned.m16n8k32.row.col.f32.e4m3.e4m3.f32 " - "{$0,$1,$2,$3}, {$4,$5,$6,$7}, {$8,$9}, {$10,$11,$12,$13};", - _RegisterPackType[Float32, Float32, Float32, Float32], - constraints="=f,=f,=f,=f,r,r,r,r,r,r,f,f,f,f", - has_side_effect=False, - ](a[0], a[1], a[2], a[3], b[0], b[1], partial[0], partial[1], partial[2], partial[3]) - return SIMD[DType.float32, 4](mma[0], mma[1], mma[2], mma[3]) - - -def _gemm_gpu( - result: ManagedTensorSlice[dtype=DType.float32, rank=2, mut=True, ...], - activations: ManagedTensorSlice[dtype=DType.float8_e4m3fn, rank=2, ...], - activation_scales: ManagedTensorSlice[dtype=DType.float32, rank=2, ...], - weights: ManagedTensorSlice[dtype=DType.float8_e4m3fn, rank=3, ...], - weight_scales: ManagedTensorSlice[dtype=DType.bfloat16, rank=3, ...], - offsets: ManagedTensorSlice[dtype=DType.int32, rank=1, ...], - ctx: DeviceContext, -) raises: - var experts = weights.dim_size(0) - var output_channels = weights.dim_size(1) - var input_channels = weights.dim_size(2) - var assignments = activations.dim_size(0) - if input_channels % 128 != 0 or output_channels % 128 != 0: - raise Error("FP8 expert dimensions must align to 128") - if activations.dim_size(1) != input_channels or result.dim_size(0) != assignments or result.dim_size(1) != output_channels: - raise Error("FP8 grouped GEMM shape mismatch") - if activation_scales.dim_size(0) != assignments or activation_scales.dim_size(1) != input_channels // 128: - raise Error("FP8 activation scale shape mismatch") - if weight_scales.dim_size(0) != experts or weight_scales.dim_size(1) != output_channels // 128 or weight_scales.dim_size(2) != input_channels // 128: - raise Error("FP8 weight scale shape mismatch") - if offsets.dim_size(0) != experts + 1: - raise Error("FP8 expert offset shape mismatch") - - @parameter - def mma_kernel(expert_count: Int32, out_channels: Int32, in_channels: Int32): - var lane = thread_idx.x - var expert = block_idx.x - var out_tile = block_idx.y * 8 - var group = lane // 4 - var quad = lane % 4 - var begin = Int(offsets.load[1](IndexList[1](expert))[0]) - var end = Int(offsets.load[1](IndexList[1](expert + 1))[0]) - # Each warp owns an expert and eight output columns. It walks the - # expert's ragged rows in 16-row tiles, so the launch grid is compact. - for row_tile in range(begin, end, 16): - var total = SIMD[DType.float32, 4](0.0) - for block in range(Int(in_channels) // 128): - var partial = SIMD[DType.float32, 4](0.0) - for k_tile in range(0, 128, 32): - var a = SIMD[DType.uint32, 4](0) - var b = SIMD[DType.uint32, 2](0) - # PTX m16n8k32 operand layout. Four packed E4M3 values - # occupy each 32-bit operand register. - for frag in range(4): - var row = row_tile + group + (8 if frag % 2 == 1 else 0) - var k0 = block * 128 + k_tile + quad * 4 + (16 if frag >= 2 else 0) - var packed: UInt32 = 0 - for byte in range(4): - var value: UInt32 = 0 - if row < end: - value = UInt32(bitcast[DType.uint8, 1](activations.load[1](IndexList[2](row, k0 + byte)))[0]) - packed |= value << UInt32(byte * 8) - a[frag] = packed - for frag in range(2): - var k0 = block * 128 + k_tile + quad * 4 + frag * 16 - var packed: UInt32 = 0 - for byte in range(4): - var raw = weights.load[1](IndexList[3](expert, out_tile + group, k0 + byte))[0] - packed |= UInt32(bitcast[DType.uint8, 1](raw)[0]) << UInt32(byte * 8) - b[frag] = packed - partial = mma_e4m3(a, b, partial) - var w_scale = Float32(weight_scales.load[1](IndexList[3](expert, out_tile // 128, block))[0]) - for frag in range(4): - var row = row_tile + group + (8 if frag >= 2 else 0) - if row < end: - total[frag] += partial[frag] * w_scale * activation_scales.load[1](IndexList[2](row, block))[0] - for frag in range(4): - var row = row_tile + group + (8 if frag >= 2 else 0) - if row < end: - result.store[1](IndexList[2](row, out_tile + quad * 2 + frag % 2), SIMD[DType.float32, 1](total[frag])) - - ctx.enqueue_function[mma_kernel]( - Int32(experts), Int32(output_channels), Int32(input_channels), - grid_dim=(experts, output_channels // 8), block_dim=32, - ) - - -@extensibility.register("aien.qwen3_moe.grouped_fp8_gemm") -struct Qwen3GroupedFp8Gemm: - @staticmethod - def execute[target: StaticString]( - result: OutputTensor[dtype=DType.float32, rank=2, ...], - activations: InputTensor[dtype=DType.float8_e4m3fn, rank=2, ...], - activation_scales: InputTensor[dtype=DType.float32, rank=2, ...], - weights: InputTensor[dtype=DType.float8_e4m3fn, rank=3, ...], - weight_scales: InputTensor[dtype=DType.bfloat16, rank=3, ...], - offsets: InputTensor[dtype=DType.int32, rank=1, ...], - ctx: DeviceContext, - ) raises: - comptime if target == "gpu": - _gemm_gpu(result, activations, activation_scales, weights, weight_scales, offsets, ctx) - else: - raise Error("Grouped FP8 GEMM requires a GPU") diff --git a/crates/aien-inference-abi/max/kernels/qwen3_fp8_unpack.mojo b/crates/aien-inference-abi/max/kernels/qwen3_fp8_unpack.mojo deleted file mode 100644 index 94361bd0..00000000 --- a/crates/aien-inference-abi/max/kernels/qwen3_fp8_unpack.mojo +++ /dev/null @@ -1,59 +0,0 @@ -import extensibility -from extensibility import InputTensor, OutputTensor, ManagedTensorSlice -from max.gpu.host import DeviceContext -from std.gpu import block_idx, thread_idx -from std.utils.index import IndexList - - -def _unpack_gpu( - output: ManagedTensorSlice[dtype=DType.bfloat16, rank=3, mut=True, ...], - packed: ManagedTensorSlice[dtype=DType.float8_e4m3fn, rank=3, ...], - inverse_scales: ManagedTensorSlice[dtype=DType.bfloat16, rank=3, ...], - ctx: DeviceContext, -) raises: - var experts = packed.dim_size(0) - var rows = packed.dim_size(1) - var columns = packed.dim_size(2) - if rows % 128 != 0 or columns % 128 != 0: - raise Error("FP8 expert dimensions must align to 128") - if inverse_scales.dim_size(0) != experts or inverse_scales.dim_size(1) != rows // 128 or inverse_scales.dim_size(2) != columns // 128: - raise Error("FP8 expert scale shape is incompatible with 128x128 blocks") - var elements = experts * rows * columns - - @parameter - def unpack_kernel(element_count: Int32, rows_dev: Int32, columns_dev: Int32): - var linear = block_idx.x * 256 + thread_idx.x - if linear >= Int(element_count): - return - var cols = Int(columns_dev) - var nrows = Int(rows_dev) - var expert = linear // (nrows * cols) - var row = (linear // cols) % nrows - var col = linear % cols - var raw = Float32(packed.load[1](IndexList[3](expert, row, col))[0]) - var scale = Float32(inverse_scales.load[1](IndexList[3](expert, row // 128, col // 128))[0]) - output.store[1]( - IndexList[3](expert, row, col), - SIMD[DType.bfloat16, 1](BFloat16(raw * scale)), - ) - - ctx.enqueue_function[unpack_kernel]( - Int32(elements), Int32(rows), Int32(columns), - grid_dim=(elements + 255) // 256, - block_dim=256, - ) - - -@extensibility.register("aien.qwen3_moe.unpack_fp8_block128") -struct Qwen3UnpackFp8: - @staticmethod - def execute[target: StaticString]( - output: OutputTensor[dtype=DType.bfloat16, rank=3, ...], - packed: InputTensor[dtype=DType.float8_e4m3fn, rank=3, ...], - inverse_scales: InputTensor[dtype=DType.bfloat16, rank=3, ...], - ctx: DeviceContext, - ) raises: - comptime if target == "gpu": - _unpack_gpu(output, packed, inverse_scales, ctx) - else: - raise Error("Qwen3 FP8 unpack requires a GPU") diff --git a/crates/aien-inference-abi/max/kernels/qwen3_router.mojo b/crates/aien-inference-abi/max/kernels/qwen3_router.mojo deleted file mode 100644 index 1f0ecfe6..00000000 --- a/crates/aien-inference-abi/max/kernels/qwen3_router.mojo +++ /dev/null @@ -1,70 +0,0 @@ -import extensibility -from extensibility import InputTensor, OutputTensor, ManagedTensorSlice -from std.gpu import block_idx, thread_idx -from max.gpu.host import DeviceContext -from std.math import exp -from std.collections import InlineArray -from std.utils.index import IndexList - -def _route_gpu( - expert_ids: ManagedTensorSlice[dtype=DType.int32, rank=2, mut=True, ...], - weights: ManagedTensorSlice[dtype=DType.float32, rank=2, mut=True, ...], - logits: ManagedTensorSlice[rank=2, ...], - ctx: DeviceContext, -) raises: - var num_tokens = logits.dim_size(0) - var num_experts = logits.dim_size(1) - if num_experts != 128 or expert_ids.dim_size(1) != 8: - raise Error("Qwen3-Coder-A3B router requires 128 experts and top 8") - - @parameter - def route_kernel(token_count: Int32): - var token = block_idx.x * 128 + thread_idx.x - if token >= Int(token_count): - return - var selected = InlineArray[Int32, 8](fill=-1) - var selected_logits = InlineArray[Float32, 8](fill=0.0) - for slot in range(8): - var best_expert: Int32 = -1 - var best_logit = Float32(-1.0e30) - for expert in range(128): - var seen = False - for previous in range(slot): - if selected[previous] == Int32(expert): - seen = True - if not seen: - var value = Float32(logits.load[1](IndexList[2](token, expert))[0]) - if value > best_logit: - best_logit = value - best_expert = Int32(expert) - selected[slot] = best_expert - selected_logits[slot] = best_logit - var denominator = Float32(0.0) - for slot in range(8): - denominator += exp(selected_logits[slot] - selected_logits[0]) - for slot in range(8): - expert_ids.store[1](IndexList[2](token, slot), SIMD[DType.int32, 1](selected[slot])) - weights.store[1](IndexList[2](token, slot), SIMD[DType.float32, 1](exp(selected_logits[slot] - selected_logits[0]) / denominator)) - - ctx.enqueue_function[route_kernel]( - Int32(num_tokens), - grid_dim=(num_tokens + 127) // 128, - block_dim=128, - ) - - -# Each GPU lane routes one token. This keeps routing local to the device and -# never materializes router logits or assignment lists on the Rust host. -@extensibility.register("aien.qwen3_moe.route_top8") -struct Qwen3RouteTop8: - @staticmethod - def execute[target: StaticString]( - expert_ids: OutputTensor[dtype=DType.int32, rank=2, ...], - weights: OutputTensor[dtype=DType.float32, rank=2, ...], - logits: InputTensor[rank=2, ...], - ctx: DeviceContext, - ) raises: - comptime if target == "gpu": - _route_gpu(expert_ids, weights, logits, ctx) - else: - raise Error("Qwen3-Coder-A3B routing requires a GPU") diff --git a/crates/aien-inference-abi/max/qwen3_moe.py b/crates/aien-inference-abi/max/qwen3_moe.py deleted file mode 100644 index 1f9c89bb..00000000 --- a/crates/aien-inference-abi/max/qwen3_moe.py +++ /dev/null @@ -1,119 +0,0 @@ -"""Qwen3-Coder-A3B routed expert layer on MAX and Mojo. - -The upload graph accepts FP8 E4M3 checkpoint bytes and 128x128 inverse -scales, converting one layer into BF16 device buffers. No full FP32 model -copy is built. The execution graph uses MAX's grouped BF16 GEMM on GB10. -""" - -from dataclasses import dataclass -from pathlib import Path - -from max.dtype import DType -from max.graph import DeviceRef, Graph, TensorType, ops -from max.nn.moe.moe import grouped_matmul_ragged, moe_create_indices - - -@dataclass(frozen=True) -class Qwen3MoeShape: - tokens: int - hidden: int = 2048 - intermediate: int = 768 - experts: int = 128 - top_k: int = 8 - - def __post_init__(self) -> None: - if self.tokens < 1 or self.hidden % 128 or self.intermediate % 128: - raise ValueError("token count must be positive and channels must align to 128") - if self.experts != 128 or self.top_k != 8: - raise ValueError("this graph targets Qwen3-Coder-30B-A3B routing") - - -def build_fp8_unpack_graph(shape: Qwen3MoeShape, device: DeviceRef) -> Graph: - """Convert raw FP8 checkpoint blocks to BF16 once, entirely on device.""" - - def unpack(gate_up, gate_up_scales, down, down_scales): - def one(packed, scales): - return ops.custom( - name="aien.qwen3_moe.unpack_fp8_block128", - device=device, - values=[packed, scales], - out_types=[TensorType(DType.bfloat16, packed.shape, device=device)], - )[0].tensor - - return one(gate_up, gate_up_scales), one(down, down_scales) - - return Graph( - "aien_qwen3_coder_a3b_unpack_fp8", - forward=unpack, - input_types=[ - TensorType( - DType.float8_e4m3fn, - [shape.experts, shape.intermediate * 2, shape.hidden], - device=device, - ), - TensorType( - DType.bfloat16, - [shape.experts, shape.intermediate * 2 // 128, shape.hidden // 128], - device=device, - ), - TensorType( - DType.float8_e4m3fn, - [shape.experts, shape.hidden, shape.intermediate], - device=device, - ), - TensorType( - DType.bfloat16, - [shape.experts, shape.hidden // 128, shape.intermediate // 128], - device=device, - ), - ], - custom_extensions=[Path(__file__).parent / "kernels"], - ) - - -def build_qwen3_moe_graph(shape: Qwen3MoeShape, device: DeviceRef) -> Graph: - """Build a complete Qwen3 MoE layer using the resident BF16 expert buffers.""" - - def forward(x, router, gate_up, down): - logits = ops.cast(x @ ops.transpose(router, 0, 1), DType.float32) - routed = ops.custom( - name="aien.qwen3_moe.route_top8", - device=device, - values=[logits], - out_types=[ - TensorType(DType.int32, [shape.tokens, 8], device=device), - TensorType(DType.float32, [shape.tokens, 8], device=device), - ], - ) - ids, probabilities = routed[0].tensor, routed[1].tensor - order, offsets, restore, expert_ids, usage = moe_create_indices( - ops.reshape(ids, [-1]), shape.experts - ) - gathered = ops.gather( - x, - ops.cast(ops.floor_div(order, shape.top_k), DType.int32), - axis=0, - ) - gate_up_result = grouped_matmul_ragged(gathered, gate_up, offsets, expert_ids, usage) - gate = gate_up_result[:, : shape.intermediate] - up = gate_up_result[:, shape.intermediate :] - activated = gate * ops.sigmoid(gate) * up - expert_output = grouped_matmul_ragged(activated, down, offsets, expert_ids, usage) - restored = ops.gather(expert_output, restore, axis=0) - restored = ops.reshape(restored, [shape.tokens, shape.top_k, shape.hidden]) - weighted = ops.cast(restored, DType.float32) * ops.unsqueeze( - probabilities, axis=2 - ) - return ops.cast(ops.squeeze(ops.sum(weighted, axis=1), axis=1), DType.bfloat16) - - return Graph( - "aien_qwen3_coder_a3b_moe_bf16", - forward=forward, - input_types=[ - TensorType(DType.bfloat16, [shape.tokens, shape.hidden], device=device), - TensorType(DType.bfloat16, [shape.experts, shape.hidden], device=device), - TensorType(DType.bfloat16, [shape.experts, shape.intermediate * 2, shape.hidden], device=device), - TensorType(DType.bfloat16, [shape.experts, shape.hidden, shape.intermediate], device=device), - ], - custom_extensions=[Path(__file__).parent / "kernels"], - ) diff --git a/crates/aien-inference-abi/max/test_fp8_grouped_gemm.py b/crates/aien-inference-abi/max/test_fp8_grouped_gemm.py deleted file mode 100644 index 342480e5..00000000 --- a/crates/aien-inference-abi/max/test_fp8_grouped_gemm.py +++ /dev/null @@ -1,87 +0,0 @@ -"""Standalone grouped FP8 tensor-core parity test on GB10.""" - -from pathlib import Path -import unittest - -import numpy as np -from max.driver import Accelerator, Buffer, CPU, accelerator_count -from max.dtype import DType -from max.engine import InferenceSession -from max.graph import DeviceRef, Graph, TensorType, ops - - -def fp8_buffer(bits: np.ndarray, device: Accelerator) -> Buffer: - return Buffer.from_numpy(bits.astype(np.uint8)).view(DType.float8_e4m3fn).to(device) - - -def bf16_buffer(values: np.ndarray, device: Accelerator) -> Buffer: - bits = (values.astype(np.float32).view(np.uint32) >> 16).astype(np.uint16) - return Buffer.from_numpy(bits).view(DType.bfloat16).to(device) - - -@unittest.skipUnless(accelerator_count() > 0, "requires a MAX accelerator") -class GroupedFp8GemmTest(unittest.TestCase): - def test_ragged_group_and_block_scales(self) -> None: - device = Accelerator() - ref = DeviceRef.from_device(device) - rows, experts, channels = 26, 2, 256 - - def forward(activations, activation_scales, weights, weight_scales, offsets): - return ops.custom( - name="aien.qwen3_moe.grouped_fp8_gemm", - device=ref, - values=[activations, activation_scales, weights, weight_scales, offsets], - out_types=[TensorType(DType.float32, [rows, channels], device=ref)], - )[0].tensor - - graph = Graph( - "aien_grouped_fp8_parity", - forward=forward, - input_types=[ - TensorType(DType.float8_e4m3fn, [rows, channels], device=ref), - TensorType(DType.float32, [rows, 2], device=ref), - TensorType(DType.float8_e4m3fn, [experts, channels, channels], device=ref), - TensorType(DType.bfloat16, [experts, 2, 2], device=ref), - TensorType(DType.int32, [experts + 1], device=ref), - ], - custom_extensions=[Path(__file__).parent / "kernels"], - ) - session = InferenceSession(devices=[device]) - model = session.init(session.compile(graph)) - # All values are exactly representable E4M3 values, with distinct - # rows/columns/experts to expose fragment mapping and grouped offsets. - values = np.array([0.0, 0.5, 1.0, 2.0, -0.5, -1.0, -2.0], dtype=np.float32) - bits = np.array([0x00, 0x30, 0x38, 0x40, 0xB0, 0xB8, 0xC0], dtype=np.uint8) - row_indices = (np.arange(rows)[:, None] * 3 + np.arange(channels)[None, :] * 5) % 7 - weight_indices = ( - np.arange(experts)[:, None, None] * 2 - + np.arange(channels)[None, :, None] * 3 - + np.arange(channels)[None, None, :] * 5 - ) % 7 - a = bits[row_indices] - w = bits[weight_indices] - a_scale = np.where(np.arange(rows)[:, None] % 2 == 0, 1.0, 0.5).astype(np.float32) * np.array([1.0, 2.0], dtype=np.float32) - w_scale = np.array([[[1.0, 0.5], [2.0, 1.0]], [[0.5, 2.0], [1.0, 0.5]]], dtype=np.float32) - offsets = np.array([0, 19, rows], dtype=np.int32) - actual = model.execute( - fp8_buffer(a, device), - Buffer.from_numpy(a_scale).to(device), - fp8_buffer(w, device), - bf16_buffer(w_scale, device), - Buffer.from_numpy(offsets).to(device), - )[0].to(CPU()).to_numpy() - expected = np.empty_like(actual) - for row in range(rows): - expert = 0 if row < offsets[1] else 1 - for output in range(channels): - total = 0.0 - for block in range(2): - av = values[row_indices[row, block * 128 : (block + 1) * 128]] - wv = values[weight_indices[expert, output, block * 128 : (block + 1) * 128]] - total += float(np.dot(av, wv)) * float(a_scale[row, block]) * float(w_scale[expert, output // 128, block]) - expected[row, output] = total - np.testing.assert_allclose(actual, expected, rtol=0, atol=2e-4) - - -if __name__ == "__main__": - unittest.main() diff --git a/crates/aien-inference-abi/max/test_qwen3_moe.py b/crates/aien-inference-abi/max/test_qwen3_moe.py deleted file mode 100644 index 664a3f0c..00000000 --- a/crates/aien-inference-abi/max/test_qwen3_moe.py +++ /dev/null @@ -1,76 +0,0 @@ -"""Run with `python crates/aien-inference-abi/max/test_qwen3_moe.py`.""" - -import unittest - -import numpy as np -from max.driver import Accelerator, Buffer, CPU, accelerator_count -from max.dtype import DType -from max.engine import InferenceSession -from max.graph import DeviceRef - -from qwen3_moe import Qwen3MoeShape, build_fp8_unpack_graph, build_qwen3_moe_graph - - -def bf16_buffer(values: np.ndarray, device: Accelerator) -> Buffer: - bits = (values.astype(np.float32).view(np.uint32) >> 16).astype(np.uint16) - return Buffer.from_numpy(bits).view(DType.bfloat16).to(device) - - -def fp8_buffer(raw: np.ndarray, device: Accelerator) -> Buffer: - assert raw.dtype == np.uint8 - return Buffer.from_numpy(raw).view(DType.float8_e4m3fn).to(device) - - -def read_bf16(buffer: Buffer) -> np.ndarray: - bits = buffer.to(CPU()).view(DType.uint16).to_numpy().astype(np.uint32) << 16 - return bits.view(np.float32) - - -@unittest.skipUnless(accelerator_count() > 0, "requires a MAX accelerator") -class Qwen3MoeGpuTest(unittest.TestCase): - def test_fp8_upload_and_complete_routed_layer(self) -> None: - shape = Qwen3MoeShape(tokens=2, hidden=128, intermediate=128) - device = Accelerator() - device_ref = DeviceRef.from_device(device) - session = InferenceSession(devices=[device]) - unpack = session.init(session.compile(build_fp8_unpack_graph(shape, device_ref))) - layer = session.init(session.compile(build_qwen3_moe_graph(shape, device_ref))) - - # 0x38 is exact FP8 E4M3 1.0. All 128 experts carry identity - # gate/up/down projections so routing and weighted reduction have - # a nonzero, independently calculable result. - gate_up = np.zeros((128, 256, 128), dtype=np.uint8) - down = np.zeros((128, 128, 128), dtype=np.uint8) - for expert in range(128): - for channel in range(128): - gate_up[expert, channel, channel] = 0x38 - gate_up[expert, 128 + channel, channel] = 0x38 - down[expert, channel, channel] = 0x38 - gate_up_scales = np.ones((128, 2, 1), dtype=np.float32) - down_scales = np.ones((128, 1, 1), dtype=np.float32) - resident_gate_up, resident_down = unpack.execute( - fp8_buffer(gate_up, device), - bf16_buffer(gate_up_scales, device), - fp8_buffer(down, device), - bf16_buffer(down_scales, device), - ) - self.assertEqual(resident_gate_up.dtype, DType.bfloat16) - self.assertEqual(resident_down.dtype, DType.bfloat16) - self.assertEqual(read_bf16(resident_gate_up)[0, 0, 0], 1.0) - - activations = np.ones((2, 128), dtype=np.float32) - router = np.zeros((128, 128), dtype=np.float32) - result = layer.execute( - bf16_buffer(activations, device), - bf16_buffer(router, device), - resident_gate_up, - resident_down, - )[0] - actual = read_bf16(result) - expected = 1.0 / (1.0 + np.exp(-1.0)) - self.assertEqual(actual.shape, (2, 128)) - self.assertLess(np.max(np.abs(actual - expected)), 0.003) - - -if __name__ == "__main__": - unittest.main() diff --git a/crates/aien-inference-abi/max/verify_real_layer.py b/crates/aien-inference-abi/max/verify_real_layer.py deleted file mode 100644 index 45c46951..00000000 --- a/crates/aien-inference-abi/max/verify_real_layer.py +++ /dev/null @@ -1,116 +0,0 @@ -"""Verify one official FP8 Qwen3-Coder-A3B MoE layer on GB10. - -Usage: python verify_real_layer.py /path/to/checkpoint-dir --layer 0 -Only the shard containing the selected layer is required. -""" - -import argparse -from pathlib import Path -import time - -import numpy as np -from max.driver import Accelerator, Buffer, CPU -from max.dtype import DType -from max.engine import InferenceSession -from max.graph import DeviceRef - -from checkpoint_fp8 import load_fp8_moe_layer -from qwen3_moe import Qwen3MoeShape, build_fp8_unpack_graph, build_qwen3_moe_graph - - -def bf16_to_float(bits: np.ndarray) -> np.ndarray: - return (bits.astype(np.uint32) << 16).view(np.float32) - - -def fp8_lookup() -> np.ndarray: - bits = np.arange(256, dtype=np.uint16) - exponent = (bits >> 3) & 15 - mantissa = bits & 7 - value = np.where( - exponent == 0, - np.ldexp(mantissa.astype(np.float32), -9), - np.ldexp(1.0 + mantissa.astype(np.float32) / 8.0, exponent.astype(int) - 7), - ) - value = np.where((bits & 128) != 0, -value, value) - value[(exponent == 15) & (mantissa == 7)] = np.nan - return value - - -def dequant(raw: np.ndarray, scales: np.ndarray, lut: np.ndarray) -> np.ndarray: - rows, columns = raw.shape - values = lut[raw].reshape(rows // 128, 128, columns // 128, 128) - scale_f32 = bf16_to_float(scales) - return (values * scale_f32[:, None, :, None]).reshape(rows, columns) - - -def main() -> None: - parser = argparse.ArgumentParser() - parser.add_argument("checkpoint_dir", type=Path) - parser.add_argument("--layer", type=int, default=0) - args = parser.parse_args() - - started = time.monotonic() - packed = load_fp8_moe_layer(args.checkpoint_dir, args.layer) - print(f"checkpoint layer packed in {time.monotonic() - started:.2f}s", flush=True) - device = Accelerator() - ref = DeviceRef.from_device(device) - shape = Qwen3MoeShape(tokens=1) - session = InferenceSession(devices=[device]) - unpack = session.init(session.compile(build_fp8_unpack_graph(shape, ref))) - layer = session.init(session.compile(build_qwen3_moe_graph(shape, ref))) - print("MAX graphs compiled", flush=True) - - router, gate_up, gate_up_scales, down, down_scales = packed.to_device(device) - resident_gate_up, resident_down = unpack.execute( - gate_up, gate_up_scales, down, down_scales - ) - del gate_up, gate_up_scales, down, down_scales - x = np.ones((1, 2048), dtype=np.float32) - x_bits = (x.view(np.uint32) >> 16).astype(np.uint16) - x_device = Buffer.from_numpy(x_bits).view(DType.bfloat16).to(device) - output = layer.execute(x_device, router, resident_gate_up, resident_down)[0] - output_bits = output.to(CPU()).view(DType.uint16).to_numpy() - actual = bf16_to_float(output_bits)[0] - if not np.isfinite(actual).all(): - raise AssertionError("MAX MoE output contains non-finite values") - print(f"MAX output shape={actual.shape}, sample={actual[:8]}", flush=True) - - # Independent CPU reference decodes only the eight selected experts. - router_f32 = bf16_to_float(packed.router_bf16) - logits = router_f32 @ x[0] - selected = np.argsort(-logits, kind="stable")[:8] - scores = np.exp(logits[selected] - logits[selected[0]]) - scores /= scores.sum() - lut = fp8_lookup() - expected = np.zeros(2048, dtype=np.float32) - for expert, score in zip(selected, scores): - gate = dequant( - packed.gate_up_fp8[expert, :768], - packed.gate_up_scales_bf16[expert, :6], - lut, - ) @ x[0] - up = dequant( - packed.gate_up_fp8[expert, 768:], - packed.gate_up_scales_bf16[expert, 6:], - lut, - ) @ x[0] - hidden = (gate / (1.0 + np.exp(-np.clip(gate, -80, 80)))) * up - expert_out = dequant( - packed.down_fp8[expert], packed.down_scales_bf16[expert], lut - ) @ hidden - expected += score * expert_out - absolute = np.abs(actual - expected) - relative = absolute / np.maximum(np.abs(expected), 0.05) - cosine = float(actual @ expected / (np.linalg.norm(actual) * np.linalg.norm(expected))) - print( - f"layer={args.layer} selected={selected.tolist()} " - f"max_abs={absolute.max():.6f} p95_rel={np.percentile(relative, 95):.6f} " - f"cosine={cosine:.8f}", - flush=True, - ) - if cosine < 0.995 or np.percentile(relative, 95) > 0.15: - raise AssertionError("MAX MoE layer diverges from FP8 CPU reference") - - -if __name__ == "__main__": - main() diff --git a/crates/aien-inference-abi/mojo/qwen3_moe/README.md b/crates/aien-inference-abi/mojo/qwen3_moe/README.md new file mode 100644 index 00000000..f6c1f85a --- /dev/null +++ b/crates/aien-inference-abi/mojo/qwen3_moe/README.md @@ -0,0 +1,116 @@ +# Qwen3-Coder-30B-A3B routed expert layer on GB10 + +One routed MoE layer of `Qwen/Qwen3-Coder-30B-A3B-Instruct-FP8`, executed +entirely in Mojo on the GB10 with packed FP8 expert weights. Rust loads the +checkpoint, owns the tensor contract, and calls the layer through a C ABI. +There is no Python and no MAX graph API anywhere in the path. + +```text +official sharded safetensors + -> load_qwen3_fp8_moe_layer (Rust): index + header + byte-range validation + -> ModelCapsule: typed FP8/BF16 tensor views, capsule digest + -> libaien_qwen3_moe.so (Mojo), per call: + router logits (FP32 accumulate) + top-8 routing, non-finite logits fail closed + stable counting sort by expert (MoeBatchPlan contract) + gather, FP8 E4M3 activation quantization (per row, 128 channels) + grouped FP8 gate/up GEMM (mma.sync m16n8k32 e4m3) + SwiGLU, FP8 quantization, grouped FP8 down GEMM + weighted inverse reduction to token order, BF16 output +``` + +## Build and test + +```bash +crates/aien-inference-abi/mojo/qwen3_moe/build.sh + +# Kernel, routing, fail-closed and synthetic-layer parity (seconds). +AIEN_REQUIRE_GPU_TESTS=1 cargo test -p aien-inference-abi --test qwen3_moe_gpu + +# Official checkpoint parity; needs the index plus the shards holding the layers. +AIEN_REQUIRE_GPU_TESTS=1 AIEN_QWEN3_FP8_CHECKPOINT=/path/to/Qwen3-Coder-30B-A3B-Instruct-FP8 \ + AIEN_QWEN3_LAYERS=0,1,23,24,47 AIEN_QWEN3_SEEDS=1,2,3 \ + cargo test -p aien-inference-abi --test qwen3_moe_gpu official -- --nocapture + +# Batch-size curve with a reproducible receipt. +cargo run --release -p aien-inference-abi --example qwen3_moe_bench -- \ + /path/to/Qwen3-Coder-30B-A3B-Instruct-FP8 --layer 0 --out receipt.json +``` + +Without the built library the GPU tests skip with a message. +`AIEN_REQUIRE_GPU_TESTS=1` turns a missing library into a failure. + +## What the tests prove + +| Test | Claim | +| --- | --- | +| `grouped_fp8_gemm_matches_block_scaled_reference` | MMA fragment mapping, ragged groups, expert remapping and both scale axes against an exact reference. | +| `grouped_fp8_gemm_rejects_out_of_range_groups` | Out-of-range expert IDs and bad offsets are refused before launch. | +| `device_routing_matches_moe_batch_plan_exactly` | Rust router == Mojo router == device permutation == inverse map, over 1024 tokens including full ties and ties across the 64-expert mask split. | +| `device_router_fails_closed_on_non_finite_logits` | NaN and +/-Inf logits return status 2; no output is produced. | +| `layer_rejects_non_finite_input_without_output` | The same through the full layer. | +| `synthetic_layer_with_distinct_experts_matches_fp32_oracle` | Distinct random experts and router, 1/37/130 tokens: device matches an oracle that quantizes activations the same way. | +| `official_checkpoint_layers_match_fp32_oracle` | Official layers against both oracles, tolerances below. | + +Two oracles are used. `OracleActivations::Fp8Block128` quantizes activations +exactly as the device does, so only accumulation order separates it from the +device: any indexing, scaling or routing defect shows up there. `Fp32` keeps +activations in FP32 and measures the real cost of FP8 activation quantization. +Both oracles route with the device's own logits, because FP32 summation order +can reorder experts separated by a few ULPs; the logits themselves are checked +against the CPU separately (observed error under 3e-6). + +## Official checkpoint tolerances + +Frozen from layers 0, 1, 23, 24 and 47, seeds 1 to 3, 16 tokens each, with +limits at about 1.5x to 2x the worst observed error: + +| Oracle | Metric | Worst observed | Limit | +| --- | --- | ---: | ---: | +| FP8-emulated | cosine | 0.99999843 | 0.99999 | +| FP8-emulated | max abs / max\|expected\| | 0.33% | 1% | +| FP32 | cosine | 0.99910 (layer 23) | 0.9985 | +| FP32 | p95 relative error | 1.73% (layer 47) | 2.5% | +| FP32 | max abs / max\|expected\| | 3.2% (layer 24) | 5% | +| both | non-finite outputs | 0 | 0 | +| both | device top-8 vs MoeBatchPlan on device logits | identical | identical | + +The FP32 gap is the cost of FP8 E4M3 activations in 128-channel blocks, the +W8A8 block scheme this checkpoint is published for. It is larger on middle +layers (cosine about 0.9991) than on layer 0 (about 0.9998). + +## Performance + +Official layer 0, seed 42, two warmups and five timed runs per point, median +milliseconds for the whole routed layer (routing, grouping, both FP8 GEMMs, +SwiGLU, quantization and reduction). Receipt: +`receipts/gb10_qwen3_a3b_layer0_mojo_fp8_curve_2026-09-23.json`. + +| Tokens | This library | Earlier MAX graph, FP8 | Earlier MAX graph, BF16 | +| ---: | ---: | ---: | ---: | +| 1 | 0.565 | 1.086 | 1.131 | +| 8 | 2.506 | 5.451 | 4.626 | +| 16 | 3.816 | 8.682 | 7.986 | +| 32 | 5.523 | 11.581 | 12.011 | +| 64 | 7.774 | 13.328 | 22.336 | +| 128 | 10.780 | 15.969 | 43.875 | +| 256 | 18.193 | 24.992 | 86.080 | +| 500 | 32.170 | 43.529 | 165.718 | +| 1024 | 62.916 | 77.416 | 338.866 | + +The timing methods are close but not identical: this library times enqueue to +device synchronize with input resident; the earlier driver also copied the +BF16 output back to the host. Read the comparison as indicative. Tokens per +second here is one layer only; the model has 48 plus attention. + +The receipt in `receipts/gb10_qwen3_a3b_layer0_fp8_curve_2026-09-23.json` is +the earlier MAX-graph measurement, kept for its BF16 grouped-GEMM baseline. +That baseline depended on the Python MAX graph API and is no longer built. + +## Boundaries + +This is one MoE layer. Attention, norms, embeddings, sampling, scheduler +wiring and full-model residency are not implemented here. Each call creates +its device context and uploads weights; a resident-weight handle is the next +step before scheduler integration. Test inputs are seeded random hidden +states, not hidden states from real prompts. diff --git a/crates/aien-inference-abi/mojo/qwen3_moe/build.sh b/crates/aien-inference-abi/mojo/qwen3_moe/build.sh new file mode 100755 index 00000000..a4366500 --- /dev/null +++ b/crates/aien-inference-abi/mojo/qwen3_moe/build.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +# Builds libaien_qwen3_moe.so, the GB10 routed expert layer, with a C ABI for Rust. +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +cd "${SCRIPT_DIR}" + +export MODULAR_CACHE_DIR="${MODULAR_CACHE_DIR:-/tmp/modular_cache}" +mkdir -p "${MODULAR_CACHE_DIR}" + +mojo build --emit shared-lib -I . lib.mojo -o libaien_qwen3_moe.so +nm -D libaien_qwen3_moe.so | grep -E ' T aien_qwen3_' +echo "Built ${SCRIPT_DIR}/libaien_qwen3_moe.so" diff --git a/crates/aien-inference-abi/mojo/qwen3_moe/kernels.mojo b/crates/aien-inference-abi/mojo/qwen3_moe/kernels.mojo new file mode 100644 index 00000000..231804be --- /dev/null +++ b/crates/aien-inference-abi/mojo/qwen3_moe/kernels.mojo @@ -0,0 +1,261 @@ +"""Device kernels for the Qwen3-Coder-A3B routed expert layer on GB10. + +Every kernel takes raw device pointers and Int32 extents. Expert weights stay +packed FP8 E4M3 with BF16 inverse scales per 128x128 block; activations are +quantized per row and 128-channel block before each grouped FP8 GEMM. +""" + +from std.gpu import block_idx, thread_idx +from std.gpu.primitives import warp +from max.gpu.sync import barrier +from max.gpu.memory import AddressSpace +from std.memory import bitcast, stack_allocation +from std.math import exp, max, abs +from std.sys._assembly import inlined_assembly +from std.sys import _RegisterPackType + +comptime EXPERTS = 128 +comptime TOP_K = 8 +comptime BLOCK = 128 + +comptime F32Ptr = MutPointer[Float32, MutAnyOrigin] +comptime BF16Ptr = MutPointer[BFloat16, MutAnyOrigin] +comptime U8Ptr = MutPointer[UInt8, MutAnyOrigin] +comptime U32Ptr = MutPointer[UInt32, MutAnyOrigin] +comptime I32Ptr = MutPointer[Int32, MutAnyOrigin] + + +def router_logits_kernel(logits: F32Ptr, x: BF16Ptr, router: BF16Ptr, hidden: Int32): + """One warp per (expert, token). FP32 accumulation, no BF16 rounding of logits.""" + var expert = block_idx.x + var token = block_idx.y + var lane = thread_idx.x + var h = Int(hidden) + var acc = Float32(0.0) + for k in range(lane, h, 32): + acc += x[unsafe_offset=token * h + k].cast[DType.float32]() * router[ + unsafe_offset=expert * h + k + ].cast[DType.float32]() + acc = warp.sum(acc) + if lane == 0: + logits[unsafe_offset=token * EXPERTS + expert] = acc + + +def route_top8_kernel(ids: I32Ptr, weights: F32Ptr, logits: F32Ptr, status: I32Ptr, tokens: Int32): + """One lane per token. Ties select the lower expert ID, matching MoeBatchPlan. + + A non-finite logit sets `status[0] = 1` and routes the token to experts 0..7 + with zero weight, so downstream indexing stays in bounds while the host + rejects the whole call. + """ + var token = block_idx.x * 128 + thread_idx.x + if token >= Int(tokens): + return + var row = logits.unsafe_offset(token * EXPERTS) + var finite = True + for expert in range(EXPERTS): + var value = row[unsafe_offset=expert] + # (v - v) is NaN for both NaN and +/-Inf. + if not (value - value == 0.0): + finite = False + if not finite: + status[unsafe_offset=0] = 1 + for slot in range(TOP_K): + ids[unsafe_offset=token * TOP_K + slot] = Int32(slot) + weights[unsafe_offset=token * TOP_K + slot] = 0.0 + return + + var taken_lo: UInt64 = 0 + var taken_hi: UInt64 = 0 + var selected = InlineArray[Int32, TOP_K](fill=0) + var selected_logits = InlineArray[Float32, TOP_K](fill=0.0) + for slot in range(TOP_K): + var best_expert = -1 + var best_logit = Float32(0.0) + for expert in range(EXPERTS): + var bit = UInt64(1) << UInt64(expert % 64) + var taken = (taken_lo & bit) if expert < 64 else (taken_hi & bit) + if taken != 0: + continue + var value = row[unsafe_offset=expert] + if best_expert < 0 or value > best_logit: + best_expert = expert + best_logit = value + if best_expert < 64: + taken_lo |= UInt64(1) << UInt64(best_expert) + else: + taken_hi |= UInt64(1) << UInt64(best_expert - 64) + selected[slot] = Int32(best_expert) + selected_logits[slot] = best_logit + # The full softmax denominator cancels under top-k renormalization. + var denominator = Float32(0.0) + for slot in range(TOP_K): + denominator += exp(selected_logits[slot] - selected_logits[0]) + for slot in range(TOP_K): + ids[unsafe_offset=token * TOP_K + slot] = selected[slot] + weights[unsafe_offset=token * TOP_K + slot] = ( + exp(selected_logits[slot] - selected_logits[0]) / denominator + ) + + +def group_by_expert_kernel( + offsets: U32Ptr, order: U32Ptr, restore: U32Ptr, ids: I32Ptr, assignments: Int32 +): + """Single block, one lane per expert: a stable counting sort. + + Grouped rows are ordered by expert, then by token-major assignment index, + which is exactly MoeBatchPlan's grouped_to_assignment contract. + """ + var expert = thread_idx.x + var n = Int(assignments) + var starts = stack_allocation[EXPERTS, Scalar[DType.uint32], address_space=AddressSpace.SHARED]() + var count: UInt32 = 0 + for a in range(n): + if Int(ids[unsafe_offset=a]) == expert: + count += 1 + starts[unsafe_offset=expert] = count + barrier() + if expert == 0: + var running: UInt32 = 0 + offsets[unsafe_offset=0] = 0 + for e in range(EXPERTS): + var c = starts[unsafe_offset=e] + starts[unsafe_offset=e] = running + running += c + offsets[unsafe_offset=e + 1] = running + barrier() + var position = starts[unsafe_offset=expert] + for a in range(n): + if Int(ids[unsafe_offset=a]) == expert: + order[unsafe_offset=Int(position)] = UInt32(a) + restore[unsafe_offset=a] = position + position += 1 + + +def gather_rows_kernel(gathered: F32Ptr, x: BF16Ptr, order: U32Ptr, hidden: Int32): + """gathered[r] = x[order[r] / TOP_K] in FP32.""" + var row = block_idx.x + var h = Int(hidden) + var token = Int(order[unsafe_offset=row]) // TOP_K + for c in range(thread_idx.x, h, 256): + gathered[unsafe_offset=row * h + c] = x[unsafe_offset=token * h + c].cast[DType.float32]() + + +def quantize_fp8_kernel(result: U8Ptr, inverse_scales: F32Ptr, activations: F32Ptr, columns: Int32): + """Per-row, per-128-channel E4M3 quantization. Grid (columns/128, rows), block 32.""" + var block = block_idx.x + var row = block_idx.y + var lane = thread_idx.x + var cols = Int(columns) + var base = row * cols + block * 128 + lane * 4 + var values = activations.unsafe_load[width=4](base) + var maximum = warp.max(max(max(abs(values[0]), abs(values[1])), max(abs(values[2]), abs(values[3])))) + # E4M3FN's largest finite value is 448. Zero blocks use scale 1. + var scale = Float32(1.0) + if maximum > 0.0: + scale = maximum / 448.0 + if lane == 0: + inverse_scales[unsafe_offset=row * (cols // 128) + block] = scale + var quantized = bitcast[DType.uint8, 4]((values / scale).cast[DType.float8_e4m3fn]()) + result.unsafe_store[width=4](base, quantized) + + +def mma_e4m3(a: SIMD[DType.uint32, 4], b: SIMD[DType.uint32, 2], partial: SIMD[DType.float32, 4]) -> SIMD[DType.float32, 4]: + var mma = inlined_assembly[ + "mma.sync.aligned.m16n8k32.row.col.f32.e4m3.e4m3.f32 " + "{$0,$1,$2,$3}, {$4,$5,$6,$7}, {$8,$9}, {$10,$11,$12,$13};", + _RegisterPackType[Float32, Float32, Float32, Float32], + constraints="=f,=f,=f,=f,r,r,r,r,r,r,f,f,f,f", + has_side_effect=False, + ](a[0], a[1], a[2], a[3], b[0], b[1], partial[0], partial[1], partial[2], partial[3]) + return SIMD[DType.float32, 4](mma[0], mma[1], mma[2], mma[3]) + + +def grouped_fp8_gemm_kernel( + result: F32Ptr, + activations: U8Ptr, + activation_scales: F32Ptr, + weights: U8Ptr, + weight_scales: BF16Ptr, + offsets: U32Ptr, + expert_ids: I32Ptr, + out_channels: Int32, + in_channels: Int32, +): + """result[r, o] = sum_k a[r, k] * w[expert(r), o, k], grouped by expert. + + Grid (groups, out_channels / 8), block 32. Each warp owns one group and + eight output columns and walks the group's ragged rows in 16-row MMA tiles. + Weights are row-major [expert, output, input] packed E4M3. + """ + var lane = thread_idx.x + var group_id = block_idx.x + var begin = Int(offsets[unsafe_offset=group_id]) + var end = Int(offsets[unsafe_offset=group_id + 1]) + if begin == end: + return + var expert = Int(expert_ids[unsafe_offset=group_id]) + var out_tile = block_idx.y * 8 + var group = lane // 4 + var quad = lane % 4 + var n_out = Int(out_channels) + var n_in = Int(in_channels) + var k_blocks = n_in // 128 + var expert_weights = weights.unsafe_offset(expert * n_out * n_in) + for row_tile in range(begin, end, 16): + var total = SIMD[DType.float32, 4](0.0) + for block in range(k_blocks): + var partial = SIMD[DType.float32, 4](0.0) + for k_tile in range(0, 128, 32): + var a = SIMD[DType.uint32, 4](0) + var b = SIMD[DType.uint32, 2](0) + # PTX m16n8k32 operand layout: four packed E4M3 values per register. + for frag in range(4): + var row = row_tile + group + (8 if frag % 2 == 1 else 0) + var k0 = block * 128 + k_tile + quad * 4 + (16 if frag >= 2 else 0) + if row < end: + a[frag] = bitcast[DType.uint32, 1](activations.unsafe_load[width=4](row * n_in + k0)) + for frag in range(2): + var k0 = block * 128 + k_tile + quad * 4 + frag * 16 + b[frag] = bitcast[DType.uint32, 1]( + expert_weights.unsafe_load[width=4]((out_tile + group) * n_in + k0) + ) + partial = mma_e4m3(a, b, partial) + var w_scale = weight_scales[ + unsafe_offset=(expert * (n_out // 128) + out_tile // 128) * k_blocks + block + ].cast[DType.float32]() + for frag in range(4): + var row = row_tile + group + (8 if frag >= 2 else 0) + if row < end: + total[frag] += partial[frag] * w_scale * activation_scales[unsafe_offset=row * k_blocks + block] + for frag in range(4): + var row = row_tile + group + (8 if frag >= 2 else 0) + if row < end: + result[unsafe_offset=row * n_out + out_tile + quad * 2 + frag % 2] = total[frag] + + +def swiglu_kernel(activated: F32Ptr, gate_up: F32Ptr, rows: Int32, intermediate: Int32): + """activated[r, j] = silu(gate[r, j]) * up[r, j] with gate|up packed per row.""" + var i = block_idx.x * 256 + thread_idx.x + var inter = Int(intermediate) + if i >= Int(rows) * inter: + return + var row = i // inter + var column = i % inter + var gate = gate_up[unsafe_offset=row * 2 * inter + column] + var up = gate_up[unsafe_offset=row * 2 * inter + inter + column] + activated[unsafe_offset=i] = gate / (1.0 + exp(-gate)) * up + + +def weighted_restore_kernel( + output: BF16Ptr, expert_output: F32Ptr, weights: F32Ptr, restore: U32Ptr, hidden: Int32 +): + """output[t] = sum over slots of weight * expert_output[restore[t, slot]], in slot order.""" + var token = block_idx.x + var h = Int(hidden) + for c in range(thread_idx.x, h, 256): + var acc = Float32(0.0) + for slot in range(TOP_K): + var a = token * TOP_K + slot + acc += weights[unsafe_offset=a] * expert_output[unsafe_offset=Int(restore[unsafe_offset=a]) * h + c] + output[unsafe_offset=token * h + c] = acc.cast[DType.bfloat16]() diff --git a/crates/aien-inference-abi/mojo/qwen3_moe/lib.mojo b/crates/aien-inference-abi/mojo/qwen3_moe/lib.mojo new file mode 100644 index 00000000..17a02882 --- /dev/null +++ b/crates/aien-inference-abi/mojo/qwen3_moe/lib.mojo @@ -0,0 +1,361 @@ +"""C ABI for the Qwen3-Coder-A3B routed expert layer on GB10. + +Rust loads libaien_qwen3_moe.so with libloading and passes host pointers. +Status codes: 0 ok, 1 invalid shape, 2 non-finite router logits, 3 device error. +Built by build.sh; no Python or MAX graph API is involved. +""" + +from std.time import perf_counter_ns +from max.gpu.host import DeviceContext, DeviceBuffer + +from kernels import ( + EXPERTS, + TOP_K, + BF16Ptr, + F32Ptr, + I32Ptr, + U32Ptr, + U8Ptr, + router_logits_kernel, + route_top8_kernel, + group_by_expert_kernel, + gather_rows_kernel, + quantize_fp8_kernel, + grouped_fp8_gemm_kernel, + swiglu_kernel, + weighted_restore_kernel, +) + +comptime STATUS_OK: Int32 = 0 +comptime STATUS_INVALID_SHAPE: Int32 = 1 +comptime STATUS_NON_FINITE: Int32 = 2 +comptime STATUS_DEVICE_ERROR: Int32 = 3 + + +def _upload[dtype: DType](ctx: DeviceContext, host: MutPointer[Scalar[dtype], MutAnyOrigin], count: Int) raises -> DeviceBuffer[dtype]: + var device = ctx.enqueue_create_buffer[dtype](count) + ctx.enqueue_copy(device, DeviceBuffer[dtype](ctx, host, count, owning=False)) + return device + + +def _download[dtype: DType](ctx: DeviceContext, host: MutPointer[Scalar[dtype], MutAnyOrigin], device: DeviceBuffer[dtype], count: Int) raises: + ctx.enqueue_copy(DeviceBuffer[dtype](ctx, host, count, owning=False), device) + + +def _valid_shape(tokens: Int32, hidden: Int32, intermediate: Int32) -> Bool: + return tokens > 0 and hidden > 0 and intermediate > 0 and hidden % 128 == 0 and intermediate % 128 == 0 + + +struct Workspace(Movable): + """Per-call device buffers for one layer invocation of `tokens` tokens.""" + + var logits: DeviceBuffer[DType.float32] + var ids: DeviceBuffer[DType.int32] + var weights: DeviceBuffer[DType.float32] + var status: DeviceBuffer[DType.int32] + var offsets: DeviceBuffer[DType.uint32] + var order: DeviceBuffer[DType.uint32] + var restore: DeviceBuffer[DType.uint32] + var expert_ids: DeviceBuffer[DType.int32] + var gathered: DeviceBuffer[DType.float32] + var quantized_in: DeviceBuffer[DType.uint8] + var scales_in: DeviceBuffer[DType.float32] + var gate_up_out: DeviceBuffer[DType.float32] + var activated: DeviceBuffer[DType.float32] + var quantized_mid: DeviceBuffer[DType.uint8] + var scales_mid: DeviceBuffer[DType.float32] + var expert_out: DeviceBuffer[DType.float32] + var output: DeviceBuffer[DType.bfloat16] + + def __init__(out self, ctx: DeviceContext, tokens: Int, hidden: Int, intermediate: Int) raises: + var rows = tokens * TOP_K + self.logits = ctx.enqueue_create_buffer[DType.float32](tokens * EXPERTS) + self.ids = ctx.enqueue_create_buffer[DType.int32](rows) + self.weights = ctx.enqueue_create_buffer[DType.float32](rows) + self.status = ctx.enqueue_create_buffer[DType.int32](1) + self.offsets = ctx.enqueue_create_buffer[DType.uint32](EXPERTS + 1) + self.order = ctx.enqueue_create_buffer[DType.uint32](rows) + self.restore = ctx.enqueue_create_buffer[DType.uint32](rows) + self.expert_ids = ctx.enqueue_create_buffer[DType.int32](EXPERTS) + self.gathered = ctx.enqueue_create_buffer[DType.float32](rows * hidden) + self.quantized_in = ctx.enqueue_create_buffer[DType.uint8](rows * hidden) + self.scales_in = ctx.enqueue_create_buffer[DType.float32](rows * (hidden // 128)) + self.gate_up_out = ctx.enqueue_create_buffer[DType.float32](rows * 2 * intermediate) + self.activated = ctx.enqueue_create_buffer[DType.float32](rows * intermediate) + self.quantized_mid = ctx.enqueue_create_buffer[DType.uint8](rows * intermediate) + self.scales_mid = ctx.enqueue_create_buffer[DType.float32](rows * (intermediate // 128)) + self.expert_out = ctx.enqueue_create_buffer[DType.float32](rows * hidden) + self.output = ctx.enqueue_create_buffer[DType.bfloat16](tokens * hidden) + # Groups are indexed by expert directly; empty groups exit immediately. + var identity = ctx.enqueue_create_host_buffer[DType.int32](EXPERTS) + ctx.synchronize() + for e in range(EXPERTS): + identity[e] = Int32(e) + ctx.enqueue_copy(self.expert_ids, identity) + ctx.synchronize() + + +def _enqueue_routing(ctx: DeviceContext, mut ws: Workspace, tokens: Int) raises: + ws.status.enqueue_fill(0) + ctx.enqueue_function[route_top8_kernel]( + ws.ids.unsafe_ptr(), ws.weights.unsafe_ptr(), ws.logits.unsafe_ptr(), ws.status.unsafe_ptr(), Int32(tokens), + grid_dim=(tokens + 127) // 128, block_dim=128, + ) + ctx.enqueue_function[group_by_expert_kernel]( + ws.offsets.unsafe_ptr(), ws.order.unsafe_ptr(), ws.restore.unsafe_ptr(), ws.ids.unsafe_ptr(), Int32(tokens * TOP_K), + grid_dim=1, block_dim=EXPERTS, + ) + + +def _enqueue_layer( + ctx: DeviceContext, + mut ws: Workspace, + mut x: DeviceBuffer[DType.bfloat16], + mut router: DeviceBuffer[DType.bfloat16], + mut gate_up: DeviceBuffer[DType.uint8], + mut gate_up_scales: DeviceBuffer[DType.bfloat16], + mut down: DeviceBuffer[DType.uint8], + mut down_scales: DeviceBuffer[DType.bfloat16], + tokens: Int, + hidden: Int, + intermediate: Int, +) raises: + var rows = tokens * TOP_K + ctx.enqueue_function[router_logits_kernel]( + ws.logits.unsafe_ptr(), x.unsafe_ptr(), router.unsafe_ptr(), Int32(hidden), + grid_dim=(EXPERTS, tokens), block_dim=32, + ) + _enqueue_routing(ctx, ws, tokens) + ctx.enqueue_function[gather_rows_kernel]( + ws.gathered.unsafe_ptr(), x.unsafe_ptr(), ws.order.unsafe_ptr(), Int32(hidden), + grid_dim=rows, block_dim=256, + ) + ctx.enqueue_function[quantize_fp8_kernel]( + ws.quantized_in.unsafe_ptr(), ws.scales_in.unsafe_ptr(), ws.gathered.unsafe_ptr(), Int32(hidden), + grid_dim=(hidden // 128, rows), block_dim=32, + ) + ctx.enqueue_function[grouped_fp8_gemm_kernel]( + ws.gate_up_out.unsafe_ptr(), ws.quantized_in.unsafe_ptr(), ws.scales_in.unsafe_ptr(), + gate_up.unsafe_ptr(), gate_up_scales.unsafe_ptr(), ws.offsets.unsafe_ptr(), ws.expert_ids.unsafe_ptr(), + Int32(2 * intermediate), Int32(hidden), + grid_dim=(EXPERTS, 2 * intermediate // 8), block_dim=32, + ) + ctx.enqueue_function[swiglu_kernel]( + ws.activated.unsafe_ptr(), ws.gate_up_out.unsafe_ptr(), Int32(rows), Int32(intermediate), + grid_dim=(rows * intermediate + 255) // 256, block_dim=256, + ) + ctx.enqueue_function[quantize_fp8_kernel]( + ws.quantized_mid.unsafe_ptr(), ws.scales_mid.unsafe_ptr(), ws.activated.unsafe_ptr(), Int32(intermediate), + grid_dim=(intermediate // 128, rows), block_dim=32, + ) + ctx.enqueue_function[grouped_fp8_gemm_kernel]( + ws.expert_out.unsafe_ptr(), ws.quantized_mid.unsafe_ptr(), ws.scales_mid.unsafe_ptr(), + down.unsafe_ptr(), down_scales.unsafe_ptr(), ws.offsets.unsafe_ptr(), ws.expert_ids.unsafe_ptr(), + Int32(hidden), Int32(intermediate), + grid_dim=(EXPERTS, hidden // 8), block_dim=32, + ) + ctx.enqueue_function[weighted_restore_kernel]( + ws.output.unsafe_ptr(), ws.expert_out.unsafe_ptr(), ws.weights.unsafe_ptr(), ws.restore.unsafe_ptr(), Int32(hidden), + grid_dim=tokens, block_dim=256, + ) + + +def _status_flag(ctx: DeviceContext, ws: Workspace) raises -> Int32: + var host = ctx.enqueue_create_host_buffer[DType.int32](1) + ctx.enqueue_copy(host, ws.status) + ctx.synchronize() + return host[0] + + +@export("aien_qwen3_moe_forward") +def aien_qwen3_moe_forward( + tokens: Int32, + hidden: Int32, + intermediate: Int32, + x: BF16Ptr, + router: BF16Ptr, + gate_up: U8Ptr, + gate_up_scales: BF16Ptr, + down: U8Ptr, + down_scales: BF16Ptr, + output: BF16Ptr, + logits_out: F32Ptr, + ids_out: I32Ptr, + weights_out: F32Ptr, + offsets_out: U32Ptr, + order_out: U32Ptr, +) abi("C") -> Int32: + """Run one routed expert layer and return routing metadata for parity checks. + + `output` is [tokens, hidden] BF16. It is written only when status is 0. + """ + if not _valid_shape(tokens, hidden, intermediate): + return STATUS_INVALID_SHAPE + try: + var t = Int(tokens) + var h = Int(hidden) + var i = Int(intermediate) + var ctx = DeviceContext() + var ws = Workspace(ctx, t, h, i) + var x_dev = _upload[DType.bfloat16](ctx, x, t * h) + var router_dev = _upload[DType.bfloat16](ctx, router, EXPERTS * h) + var gate_up_dev = _upload[DType.uint8](ctx, gate_up, EXPERTS * 2 * i * h) + var gate_up_scales_dev = _upload[DType.bfloat16](ctx, gate_up_scales, EXPERTS * (2 * i // 128) * (h // 128)) + var down_dev = _upload[DType.uint8](ctx, down, EXPERTS * h * i) + var down_scales_dev = _upload[DType.bfloat16](ctx, down_scales, EXPERTS * (h // 128) * (i // 128)) + _enqueue_layer(ctx, ws, x_dev, router_dev, gate_up_dev, gate_up_scales_dev, down_dev, down_scales_dev, t, h, i) + _download[DType.float32](ctx, logits_out, ws.logits, t * EXPERTS) + _download[DType.int32](ctx, ids_out, ws.ids, t * TOP_K) + _download[DType.float32](ctx, weights_out, ws.weights, t * TOP_K) + _download[DType.uint32](ctx, offsets_out, ws.offsets, EXPERTS + 1) + _download[DType.uint32](ctx, order_out, ws.order, t * TOP_K) + ctx.synchronize() + if _status_flag(ctx, ws) != 0: + return STATUS_NON_FINITE + _download[DType.bfloat16](ctx, output, ws.output, t * h) + ctx.synchronize() + return STATUS_OK + except e: + print("aien_qwen3_moe_forward:", e) + return STATUS_DEVICE_ERROR + + +@export("aien_qwen3_moe_benchmark") +def aien_qwen3_moe_benchmark( + tokens: Int32, + hidden: Int32, + intermediate: Int32, + x: BF16Ptr, + router: BF16Ptr, + gate_up: U8Ptr, + gate_up_scales: BF16Ptr, + down: U8Ptr, + down_scales: BF16Ptr, + warmup: Int32, + repeats: Int32, + samples_ns: MutPointer[UInt64, MutAnyOrigin], +) abi("C") -> Int32: + """Time `repeats` complete layer executions with weights and input resident. + + Each sample is wall time from first enqueue to device synchronization. + """ + if not _valid_shape(tokens, hidden, intermediate) or warmup < 0 or repeats < 1: + return STATUS_INVALID_SHAPE + try: + var t = Int(tokens) + var h = Int(hidden) + var i = Int(intermediate) + var ctx = DeviceContext() + var ws = Workspace(ctx, t, h, i) + var x_dev = _upload[DType.bfloat16](ctx, x, t * h) + var router_dev = _upload[DType.bfloat16](ctx, router, EXPERTS * h) + var gate_up_dev = _upload[DType.uint8](ctx, gate_up, EXPERTS * 2 * i * h) + var gate_up_scales_dev = _upload[DType.bfloat16](ctx, gate_up_scales, EXPERTS * (2 * i // 128) * (h // 128)) + var down_dev = _upload[DType.uint8](ctx, down, EXPERTS * h * i) + var down_scales_dev = _upload[DType.bfloat16](ctx, down_scales, EXPERTS * (h // 128) * (i // 128)) + ctx.synchronize() + for _ in range(Int(warmup)): + _enqueue_layer(ctx, ws, x_dev, router_dev, gate_up_dev, gate_up_scales_dev, down_dev, down_scales_dev, t, h, i) + ctx.synchronize() + for sample in range(Int(repeats)): + var started = perf_counter_ns() + _enqueue_layer(ctx, ws, x_dev, router_dev, gate_up_dev, gate_up_scales_dev, down_dev, down_scales_dev, t, h, i) + ctx.synchronize() + samples_ns[unsafe_offset=sample] = UInt64(perf_counter_ns() - started) + if _status_flag(ctx, ws) != 0: + return STATUS_NON_FINITE + return STATUS_OK + except e: + print("aien_qwen3_moe_benchmark:", e) + return STATUS_DEVICE_ERROR + + +@export("aien_qwen3_route_top8") +def aien_qwen3_route_top8( + tokens: Int32, + logits: F32Ptr, + ids_out: I32Ptr, + weights_out: F32Ptr, + offsets_out: U32Ptr, + order_out: U32Ptr, + restore_out: U32Ptr, +) abi("C") -> Int32: + """Route caller-supplied logits [tokens, 128] on the GPU and group assignments. + + Lets the host feed identical logits to MoeBatchPlan and the device router. + """ + if tokens < 1: + return STATUS_INVALID_SHAPE + try: + var t = Int(tokens) + var ctx = DeviceContext() + var ws = Workspace(ctx, t, 128, 128) + ctx.enqueue_copy(ws.logits, DeviceBuffer[DType.float32](ctx, logits, t * EXPERTS, owning=False)) + _enqueue_routing(ctx, ws, t) + _download[DType.int32](ctx, ids_out, ws.ids, t * TOP_K) + _download[DType.float32](ctx, weights_out, ws.weights, t * TOP_K) + _download[DType.uint32](ctx, offsets_out, ws.offsets, EXPERTS + 1) + _download[DType.uint32](ctx, order_out, ws.order, t * TOP_K) + _download[DType.uint32](ctx, restore_out, ws.restore, t * TOP_K) + ctx.synchronize() + if _status_flag(ctx, ws) != 0: + return STATUS_NON_FINITE + return STATUS_OK + except e: + print("aien_qwen3_route_top8:", e) + return STATUS_DEVICE_ERROR + + +@export("aien_qwen3_grouped_fp8_gemm") +def aien_qwen3_grouped_fp8_gemm( + rows: Int32, + groups: Int32, + experts: Int32, + out_channels: Int32, + in_channels: Int32, + activations: U8Ptr, + activation_scales: F32Ptr, + weights: U8Ptr, + weight_scales: BF16Ptr, + offsets: U32Ptr, + expert_ids: I32Ptr, + result: F32Ptr, +) abi("C") -> Int32: + """Standalone grouped FP8 GEMM for kernel parity tests. + + offsets has groups + 1 entries; expert_ids maps each group to an expert. + """ + if rows < 1 or groups < 1 or experts < 1 or out_channels % 128 != 0 or in_channels % 128 != 0 or out_channels < 128 or in_channels < 128: + return STATUS_INVALID_SHAPE + # The kernel trusts offsets and expert IDs, so reject anything out of range here. + if offsets[unsafe_offset=0] != 0 or Int(offsets[unsafe_offset=Int(groups)]) != Int(rows): + return STATUS_INVALID_SHAPE + for group in range(Int(groups)): + var id = expert_ids[unsafe_offset=group] + if id < 0 or id >= experts or offsets[unsafe_offset=group] > offsets[unsafe_offset=group + 1]: + return STATUS_INVALID_SHAPE + try: + var r = Int(rows) + var g = Int(groups) + var e = Int(experts) + var o = Int(out_channels) + var k = Int(in_channels) + var ctx = DeviceContext() + var a_dev = _upload[DType.uint8](ctx, activations, r * k) + var a_scales_dev = _upload[DType.float32](ctx, activation_scales, r * (k // 128)) + var w_dev = _upload[DType.uint8](ctx, weights, e * o * k) + var w_scales_dev = _upload[DType.bfloat16](ctx, weight_scales, e * (o // 128) * (k // 128)) + var offsets_dev = _upload[DType.uint32](ctx, offsets, g + 1) + var ids_dev = _upload[DType.int32](ctx, expert_ids, g) + var out_dev = ctx.enqueue_create_buffer[DType.float32](r * o) + ctx.enqueue_function[grouped_fp8_gemm_kernel]( + out_dev.unsafe_ptr(), a_dev.unsafe_ptr(), a_scales_dev.unsafe_ptr(), w_dev.unsafe_ptr(), + w_scales_dev.unsafe_ptr(), offsets_dev.unsafe_ptr(), ids_dev.unsafe_ptr(), Int32(o), Int32(k), + grid_dim=(g, o // 8), block_dim=32, + ) + _download[DType.float32](ctx, result, out_dev, r * o) + ctx.synchronize() + return STATUS_OK + except e: + print("aien_qwen3_grouped_fp8_gemm:", e) + return STATUS_DEVICE_ERROR diff --git a/crates/aien-inference-abi/mojo/qwen3_moe/receipts/gb10_qwen3_a3b_layer0_fp8_curve_2026-09-23.json b/crates/aien-inference-abi/mojo/qwen3_moe/receipts/gb10_qwen3_a3b_layer0_fp8_curve_2026-09-23.json new file mode 100644 index 00000000..20a36537 --- /dev/null +++ b/crates/aien-inference-abi/mojo/qwen3_moe/receipts/gb10_qwen3_a3b_layer0_fp8_curve_2026-09-23.json @@ -0,0 +1,250 @@ +{ + "measurement_date": "2026-09-23", + "model": "Qwen/Qwen3-Coder-30B-A3B-Instruct-FP8", + "layer": 0, + "checkpoint_index_sha256": "270f54aead2ae634567310218340069621fd8dfa2ad80001b69888ea5cc03477", + "checkpoint_shard_sha256": "04665458e2332cc10409cd51298c95627000ed44cf29134663203e3f15c3c053", + "checkpoint_shard": "model-00001-of-00004.safetensors", + "base_git_commit": "7b7119b16928548e2aab189cef17eb0d4b396296", + "source_sha256": { + "qwen3_moe.py": "adb3dc112cdee68b81c3d2bfab881d829e606390a7442d6271c8d3ea7e340a87", + "kernels/qwen3_fp8_gemm.mojo": "a2b30d0705180ad15f8a1032fecf69d186d0d50df416c0a659d79e43446eb687", + "kernels/qwen3_fp8_quantize.mojo": "ac85da4e1784584e1512eddbe9e47bff17944508df0b678e9ed5885900beb45a", + "kernels/qwen3_router.mojo": "2be47a0c82ba901c9e6a91351e4dcc88d8909ced18d547e5b89464a1d8747dde", + "benchmark_moe_layer.py": "f387821403e07768c86ff47b0d95fd324bbb2424b0fe4eda4fc09325f4fc1a6b" + }, + "hardware": { + "gpu": "NVIDIA GB10", + "gpu_uuid": "GPU-fb8e53f0-3207-e89b-d02f-acdfe2695b59", + "driver": "580.173.02", + "cuda": "13.0" + }, + "software": { + "max": "26.5.0", + "mojo": "1.0.0" + }, + "input_seed": 42, + "warmup_runs": 1, + "timed_runs": 3, + "packed_fp8_expert_weight_bytes": 603979776, + "bf16_resident_expert_weight_bytes": 1207959552, + "note": "One routed MoE layer including routing, permutation, activation, two expert projections, and weighted inverse reduction. Excludes attention, norms, embedding, sampling, model scheduling, and allocator peaks.", + "curve": [ + { + "tokens": 1, + "input_bf16_sha256": "6007308498a7b411b8dd0aa8836d94f24707756713e845bf1f4c398108d3ccd9", + "experts_touched": 8, + "expert_batch_p50": 1.0, + "expert_batch_p95": 1.0, + "routing_entropy_bits": 3.0, + "native_fp8": { + "timings_sec": [ + 0.0022070680279284716, + 0.001086357980966568, + 0.0010768380016088486 + ], + "median_ms": 1.086357980966568 + }, + "bf16_grouped": { + "timings_sec": [ + 0.0011307270033285022, + 0.002204091986641288, + 0.00112536596134305 + ], + "median_ms": 1.1307270033285022 + } + }, + { + "tokens": 8, + "input_bf16_sha256": "9680d321c0fc4085a3bbd95efd495895b377eaa6396595f9a98a91dd50d914fe", + "experts_touched": 53, + "expert_batch_p50": 1.0, + "expert_batch_p95": 2.0, + "routing_entropy_bits": 5.65625, + "native_fp8": { + "timings_sec": [ + 0.005256077041849494, + 0.005550734931603074, + 0.00545103894546628 + ], + "median_ms": 5.45103894546628 + }, + "bf16_grouped": { + "timings_sec": [ + 0.004625897039659321, + 0.005026731989346445, + 0.004558713058941066 + ], + "median_ms": 4.625897039659321 + } + }, + { + "tokens": 16, + "input_bf16_sha256": "a60528c7a7212366a1455a758bb2de6363cafe72fa54207026cf20402ef7ec19", + "experts_touched": 84, + "expert_batch_p50": 1.0, + "expert_batch_p95": 3.0, + "routing_entropy_bits": 6.241729296672174, + "native_fp8": { + "timings_sec": [ + 0.008554286905564368, + 0.008682047948241234, + 0.008783616940490901 + ], + "median_ms": 8.682047948241234 + }, + "bf16_grouped": { + "timings_sec": [ + 0.008280524984002113, + 0.007366233039647341, + 0.007986140088178217 + ], + "median_ms": 7.986140088178217 + } + }, + { + "tokens": 32, + "input_bf16_sha256": "9bf10ebdb851c3ea8cc78ed1890de3ef23c1a3a8d735205645b451815b279408", + "experts_touched": 109, + "expert_batch_p50": 2.0, + "expert_batch_p95": 5.0, + "routing_entropy_bits": 6.517712002459941, + "native_fp8": { + "timings_sec": [ + 0.010807642946019769, + 0.011581343947909772, + 0.011711215949617326 + ], + "median_ms": 11.581343947909772 + }, + "bf16_grouped": { + "timings_sec": [ + 0.011914656963199377, + 0.01201094500720501, + 0.012862038100138307 + ], + "median_ms": 12.01094500720501 + } + }, + { + "tokens": 64, + "input_bf16_sha256": "8df6d0774ba7fa4d202e1873bb6f137eb0993c38d2d38dd70d12f487909eaea1", + "experts_touched": 124, + "expert_batch_p50": 4.0, + "expert_batch_p95": 9.0, + "routing_entropy_bits": 6.694762218399914, + "native_fp8": { + "timings_sec": [ + 0.013446712982840836, + 0.013328391942195594, + 0.012778694042935967 + ], + "median_ms": 13.328391942195594 + }, + "bf16_grouped": { + "timings_sec": [ + 0.022926107980310917, + 0.022296697017736733, + 0.022335849003866315 + ], + "median_ms": 22.335849003866315 + } + }, + { + "tokens": 128, + "input_bf16_sha256": "e152c2d68cb2608dfd8d2d37a03f7a178b6e543bb850e8b6c0757e58dda2ad7c", + "experts_touched": 128, + "expert_batch_p50": 7.0, + "expert_batch_p95": 16.64999999999999, + "routing_entropy_bits": 6.787588706654907, + "native_fp8": { + "timings_sec": [ + 0.01624680799432099, + 0.0159240699140355, + 0.01596874208189547 + ], + "median_ms": 15.96874208189547 + }, + "bf16_grouped": { + "timings_sec": [ + 0.044573616003617644, + 0.043874797062017024, + 0.04374580294825137 + ], + "median_ms": 43.874797062017024 + } + }, + { + "tokens": 256, + "input_bf16_sha256": "355324881395b00f59571307b3f94238025d918a8f21ba439667acc4a42bbdc1", + "experts_touched": 128, + "expert_batch_p50": 15.0, + "expert_batch_p95": 31.0, + "routing_entropy_bits": 6.839505190022951, + "native_fp8": { + "timings_sec": [ + 0.025146135943941772, + 0.024992229999043047, + 0.02458627603482455 + ], + "median_ms": 24.992229999043047 + }, + "bf16_grouped": { + "timings_sec": [ + 0.08559928997419775, + 0.08611942199058831, + 0.08608033298514783 + ], + "median_ms": 86.08033298514783 + } + }, + { + "tokens": 500, + "input_bf16_sha256": "ddc8a00213d4e26cf61e3c399ee9f16d6a4b1f2fbd6d47c9e0860f94c2e354df", + "experts_touched": 128, + "expert_batch_p50": 30.0, + "expert_batch_p95": 60.0, + "routing_entropy_bits": 6.838271507336273, + "native_fp8": { + "timings_sec": [ + 0.04238313902169466, + 0.043528777081519365, + 0.044222221011295915 + ], + "median_ms": 43.528777081519365 + }, + "bf16_grouped": { + "timings_sec": [ + 0.16571792704053223, + 0.16575227899011225, + 0.165413654060103 + ], + "median_ms": 165.71792704053223 + } + }, + { + "tokens": 1024, + "input_bf16_sha256": "77b1bc90b9a4b5faf306d7d4d25eb4184440d00c053515ae25a7c94393d240b0", + "experts_touched": 128, + "expert_batch_p50": 57.5, + "expert_batch_p95": 125.0, + "routing_entropy_bits": 6.839041874784641, + "native_fp8": { + "timings_sec": [ + 0.0781254090834409, + 0.07636124000418931, + 0.07741618901491165 + ], + "median_ms": 77.41618901491165 + }, + "bf16_grouped": { + "timings_sec": [ + 0.33894684503320605, + 0.3388656920287758, + 0.3383831779938191 + ], + "median_ms": 338.8656920287758 + } + } + ] +} diff --git a/crates/aien-inference-abi/mojo/qwen3_moe/receipts/gb10_qwen3_a3b_layer0_mojo_fp8_curve_2026-09-23.json b/crates/aien-inference-abi/mojo/qwen3_moe/receipts/gb10_qwen3_a3b_layer0_mojo_fp8_curve_2026-09-23.json new file mode 100644 index 00000000..c5ebe4a1 --- /dev/null +++ b/crates/aien-inference-abi/mojo/qwen3_moe/receipts/gb10_qwen3_a3b_layer0_mojo_fp8_curve_2026-09-23.json @@ -0,0 +1,219 @@ +{ + "activation_quantization": "fp8_e4m3fn per row and 128 channels, fp32 scales", + "capsule_digest": "3662f4037252a21dfc2044b0fba26622c5110bf0074cf00b4c7dcd2eb9050231", + "capsule_source_digest": "10805e43fdd8b1c946fb4008f68a6fac53d65a9d75f357106821f3240051648c", + "checkpoint_index_digest": "270f54aead2ae634567310218340069621fd8dfa2ad80001b69888ea5cc03477", + "cuda_version": "| NVIDIA-SMI 580.173.02 Driver Version: 580.173.02 CUDA Version: 13.0 |", + "expert_compute": "native grouped FP8 E4M3 mma.sync m16n8k32 (Mojo, SM121a)", + "git_commit": "d4726c7dcb51df4fe4cb3ec50cbb17174514659c", + "git_dirty": false, + "gpu": "NVIDIA GB10, 580.173.02, 12.1", + "kernel_library": "/home/drakestapleton/workspace/hive-worktrees/qwen3-fp8-layer-integration/crates/aien-inference-abi/mojo/qwen3_moe/libaien_qwen3_moe.so", + "kernel_library_digest": "372760529a7cba6cbc14e240db8f62b2bd4535c0893535225dbb7caba4066080", + "kernel_source_digests": { + "kernels.mojo": "3ccb4184e7dd4560e68b953fb102f2f7462bbac622c9be9877d1236d1edd7c0b", + "lib.mojo": "05ecbc8e55a9f29f1376c842f1d9f39483cb961768dc376485003441d6bb580a" + }, + "layer": 0, + "model": "Qwen/Qwen3-Coder-30B-A3B-Instruct-FP8", + "mojo_version": "Mojo 1.0.0 (ed45d567)", + "note": "one MoE layer; excludes attention, norms, embedding and sampling", + "peak_host_rss_bytes": 2133278720, + "points": [ + { + "assignments": 8, + "assignments_per_sec_median": 14152.603990680509, + "expert_batch_max": 1, + "expert_batch_p50": 1, + "expert_batch_p95": 1, + "experts_touched": 8, + "input_digest": "1e0a3ddd1be81f971051881b475b6eb7eb5fcc82eaca1a9621fa573cd86703fa", + "input_seed": 42, + "layer_latency_ms_median": 0.565267, + "layer_tokens_per_sec_median": 1769.0754988350636, + "routing_entropy_bits": 3.0, + "samples_ns": [ + 565187, + 571666, + 573234, + 565267, + 558018 + ], + "tokens": 1 + }, + { + "assignments": 64, + "assignments_per_sec_median": 25542.019615472876, + "expert_batch_max": 4, + "expert_batch_p50": 1, + "expert_batch_p95": 3, + "experts_touched": 46, + "input_digest": "4b1fa295f445fa847e382e769cd8e402bc804b05b153418365e159d48c0433eb", + "input_seed": 42, + "layer_latency_ms_median": 2.505675, + "layer_tokens_per_sec_median": 3192.7524519341096, + "routing_entropy_bits": 5.339614648336088, + "samples_ns": [ + 2505675, + 2501626, + 2506650, + 2506859, + 2503610 + ], + "tokens": 8 + }, + { + "assignments": 128, + "assignments_per_sec_median": 33542.28253660367, + "expert_batch_max": 5, + "expert_batch_p50": 2, + "expert_batch_p95": 4, + "experts_touched": 72, + "input_digest": "8f48eabdc3abc4dc267f3a2e81aedd7962b081998464beb0427ea9be8be0ae9c", + "input_seed": 42, + "layer_latency_ms_median": 3.816079, + "layer_tokens_per_sec_median": 4192.785317075459, + "routing_entropy_bits": 5.980441457312361, + "samples_ns": [ + 3813135, + 3812128, + 3816672, + 3816079, + 3821680 + ], + "tokens": 16 + }, + { + "assignments": 256, + "assignments_per_sec_median": 46350.42040374475, + "expert_batch_max": 7, + "expert_batch_p50": 2, + "expert_batch_p95": 6, + "experts_touched": 96, + "input_digest": "2af5d8a475fc251a1767fcb8b72872c5d76ecfce7a28cb670bf90fe8c8768c7d", + "input_seed": 42, + "layer_latency_ms_median": 5.523143, + "layer_tokens_per_sec_median": 5793.802550468094, + "routing_entropy_bits": 6.328878250935345, + "samples_ns": [ + 5954696, + 5485943, + 5437830, + 6107017, + 5523143 + ], + "tokens": 32 + }, + { + "assignments": 512, + "assignments_per_sec_median": 65862.59416292759, + "expert_batch_max": 11, + "expert_batch_p50": 4, + "expert_batch_p95": 10, + "experts_touched": 119, + "input_digest": "19a2c78bb562df2a7a8fce927ab0c638e14b4b09d7febd4f9d9b74676298f74e", + "input_seed": 42, + "layer_latency_ms_median": 7.77376, + "layer_tokens_per_sec_median": 8232.824270365949, + "routing_entropy_bits": 6.650045932984798, + "samples_ns": [ + 7733056, + 7773760, + 8396946, + 8353075, + 7741439 + ], + "tokens": 64 + }, + { + "assignments": 1024, + "assignments_per_sec_median": 94994.1426463216, + "expert_batch_max": 22, + "expert_batch_p50": 8, + "expert_batch_p95": 17, + "experts_touched": 127, + "input_digest": "2038011e845df0d6ac6e3dd6be38752c34366d813ef537b5497fa5b838f6e627", + "input_seed": 42, + "layer_latency_ms_median": 10.779612, + "layer_tokens_per_sec_median": 11874.2678307902, + "routing_entropy_bits": 6.77759237971053, + "samples_ns": [ + 10676188, + 11386062, + 10775501, + 10779612, + 11335567 + ], + "tokens": 128 + }, + { + "assignments": 2048, + "assignments_per_sec_median": 112570.15640930663, + "expert_batch_max": 44, + "expert_batch_p50": 15, + "expert_batch_p95": 29, + "experts_touched": 128, + "input_digest": "7cd04445017ddc3b44c673d38f3fd2a9eaf9e00766e72c830708f840ca8415da", + "input_seed": 42, + "layer_latency_ms_median": 18.193099, + "layer_tokens_per_sec_median": 14071.269551163328, + "routing_entropy_bits": 6.8399994480377, + "samples_ns": [ + 18193099, + 18226091, + 18207803, + 17706713, + 17695081 + ], + "tokens": 256 + }, + { + "assignments": 4000, + "assignments_per_sec_median": 124340.48253805783, + "expert_batch_max": 78, + "expert_batch_p50": 30, + "expert_batch_p95": 54, + "experts_touched": 128, + "input_digest": "aba9d2f253b5a57bfbcdf3af4bf5030656408bf017ef0d4aba316ad3deca41c7", + "input_seed": 42, + "layer_latency_ms_median": 32.169732, + "layer_tokens_per_sec_median": 15542.560317257228, + "routing_entropy_bits": 6.863687470749908, + "samples_ns": [ + 32198469, + 32169732, + 32117428, + 32178117, + 31641986 + ], + "tokens": 500 + }, + { + "assignments": 8192, + "assignments_per_sec_median": 130204.45293825054, + "expert_batch_max": 159, + "expert_batch_p50": 60, + "expert_batch_p95": 111, + "experts_touched": 128, + "input_digest": "1ab04b1478d342e85e81a73bd456feeb6bc90d69875d04bd590f4f7e7ed5c612", + "input_seed": 42, + "layer_latency_ms_median": 62.916435, + "layer_tokens_per_sec_median": 16275.556617281318, + "routing_entropy_bits": 6.859991282968842, + "samples_ns": [ + 62282560, + 63117556, + 63174292, + 62256513, + 62916435 + ], + "tokens": 1024 + } + ], + "repeats": 5, + "resident_dtype": "fp8_e4m3fn", + "resident_weight_bytes": 604577792, + "timing": "wall time from first enqueue to device synchronize, weights and input resident", + "warmup": 2, + "weight_dtype": "fp8_e4m3fn with bf16 128x128 inverse scales" +} diff --git a/crates/aien-inference-abi/src/lib.rs b/crates/aien-inference-abi/src/lib.rs index 6faca85c..248056a5 100644 --- a/crates/aien-inference-abi/src/lib.rs +++ b/crates/aien-inference-abi/src/lib.rs @@ -15,6 +15,7 @@ pub mod capsule; pub mod checkpoint; pub mod moe_plan; pub mod mojo_backend; +pub mod qwen3_moe; pub mod tensor; pub mod tensor_abi; pub mod tokenizer; @@ -33,6 +34,7 @@ pub use capsule::*; pub use checkpoint::*; pub use moe_plan::*; pub use mojo_backend::*; +pub use qwen3_moe::*; pub use tensor::*; pub use tensor_abi::*; pub use tokenizer::*; diff --git a/crates/aien-inference-abi/src/moe_plan.rs b/crates/aien-inference-abi/src/moe_plan.rs index 17641735..cec1586e 100644 --- a/crates/aien-inference-abi/src/moe_plan.rs +++ b/crates/aien-inference-abi/src/moe_plan.rs @@ -1,7 +1,7 @@ //! Branch-agnostic MoE routing plan for Qwen3-Coder-30B-A3B. //! //! This is the host-side correctness oracle and batch metadata contract for -//! Mojo/MAX execution. Expert GEMMs consume assignments in grouped order; +//! the Mojo GB10 layer (`qwen3_moe`). Expert GEMMs consume assignments in grouped order; //! the inverse map restores each token's original top-k slots. use std::fmt; @@ -33,7 +33,7 @@ impl fmt::Display for MoePlanError { impl std::error::Error for MoePlanError {} -/// Assignment offsets and maps use u32 to match MAX's MoE index operators. +/// Assignment offsets and maps use u32 to match the Mojo grouping kernel (`mojo/qwen3_moe`). #[derive(Debug, Clone, PartialEq)] pub struct MoeBatchPlan { pub tokens: usize, @@ -202,7 +202,7 @@ impl MoeBatchPlan { } } - /// Reference weighted inverse permutation for parity checks with MAX. + /// Reference weighted inverse permutation for device parity checks. pub fn reduce_grouped( &self, grouped_output: &[f32], diff --git a/crates/aien-inference-abi/src/qwen3_moe.rs b/crates/aien-inference-abi/src/qwen3_moe.rs new file mode 100644 index 00000000..d7dc365f --- /dev/null +++ b/crates/aien-inference-abi/src/qwen3_moe.rs @@ -0,0 +1,1325 @@ +//! Qwen3-Coder-30B-A3B routed expert layer on GB10. +//! +//! Three pieces share one tensor contract: +//! - sharded FP8 checkpoint ingest into a [`ModelCapsule`] (one layer, no FP32 copy), +//! - the C ABI binding to `libaien_qwen3_moe.so` (Mojo, built by `mojo/qwen3_moe/build.sh`), +//! - an FP32 CPU oracle that dequantizes only the experts a token selected. +//! +//! Capsule tensors, all row-major: +//! `router` BF16 [128, H]; `gate_up` FP8 E4M3 [128, 2I, H] (gate rows then up rows); +//! `gate_up_scale_inv` BF16 [128, 2I/128, H/128]; `down` FP8 E4M3 [128, H, I]; +//! `down_scale_inv` BF16 [128, H/128, I/128]. + +use std::collections::HashMap; +use std::fmt; +use std::fs::File; +use std::os::unix::fs::FileExt; +use std::path::{Component, Path, PathBuf}; +use std::sync::Arc; + +use libloading::{Library, Symbol}; +use rayon::prelude::*; + +use crate::capsule::{ + capsule_digest, row_major_strides, source_digest, CapsuleTensor, ModelCapsule, + QuantizationDescriptor, TensorLayout, WeightDType, +}; +use crate::moe_plan::{MoeBatchPlan, MoePlanError, QWEN3_CODER_A3B_EXPERTS, QWEN3_CODER_A3B_TOP_K}; + +pub const QWEN3_A3B_HIDDEN: usize = 2048; +pub const QWEN3_A3B_INTERMEDIATE: usize = 768; +pub const QWEN3_A3B_LAYERS: usize = 48; +const BLOCK: usize = 128; +const EXPERTS: usize = QWEN3_CODER_A3B_EXPERTS; +const TOP_K: usize = QWEN3_CODER_A3B_TOP_K; +/// Largest safetensors JSON header accepted; real Qwen shards use about 2 MB. +const MAX_HEADER_BYTES: u64 = 256 << 20; + +pub const ROUTER: &str = "router"; +pub const GATE_UP: &str = "gate_up"; +pub const GATE_UP_SCALE_INV: &str = "gate_up_scale_inv"; +pub const DOWN: &str = "down"; +pub const DOWN_SCALE_INV: &str = "down_scale_inv"; + +#[derive(Debug, Clone, PartialEq)] +pub enum Qwen3MoeError { + Io(String), + Index(String), + Contract(String), + Library(String), + /// Nonzero status from the Mojo library: 1 invalid shape, 2 non-finite router logits, 3 device error. + Kernel(i32), + Plan(MoePlanError), +} + +impl fmt::Display for Qwen3MoeError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Io(detail) => write!(f, "checkpoint I/O: {detail}"), + Self::Index(detail) => write!(f, "checkpoint index: {detail}"), + Self::Contract(detail) => write!(f, "tensor contract: {detail}"), + Self::Library(detail) => write!(f, "Qwen3 MoE kernel library: {detail}"), + Self::Kernel(1) => write!(f, "Qwen3 MoE kernel rejected the shape"), + Self::Kernel(2) => write!(f, "Qwen3 MoE router saw non-finite logits"), + Self::Kernel(code) => write!(f, "Qwen3 MoE kernel device error (status {code})"), + Self::Plan(error) => write!(f, "routing plan: {error}"), + } + } +} + +impl std::error::Error for Qwen3MoeError {} + +impl From for Qwen3MoeError { + fn from(error: MoePlanError) -> Self { + Self::Plan(error) + } +} + +/// One routed expert layer held in a capsule. Accessors borrow typed views of it. +#[derive(Debug, Clone)] +pub struct Qwen3MoeLayer { + pub hidden: usize, + pub intermediate: usize, + pub capsule: ModelCapsule, +} + +fn fp8_block_quant() -> Option { + Some(QuantizationDescriptor { + scheme: "fp8-e4m3fn-block128x128-bf16-scale-inv".to_string(), + axis: 0, + group_size: BLOCK, + scales: Vec::new(), + zero_points: Vec::new(), + packing: "none".to_string(), + }) +} + +/// (name, dtype, shape, element bytes) for every capsule tensor, in payload order. +fn layer_tensor_specs( + hidden: usize, + intermediate: usize, +) -> [(&'static str, WeightDType, Vec, usize); 5] { + let (h, i) = (hidden, intermediate); + [ + (ROUTER, WeightDType::Bf16, vec![EXPERTS, h], 2), + (GATE_UP, WeightDType::Fp8E4M3Fn, vec![EXPERTS, 2 * i, h], 1), + ( + GATE_UP_SCALE_INV, + WeightDType::Bf16, + vec![EXPERTS, 2 * i / BLOCK, h / BLOCK], + 2, + ), + (DOWN, WeightDType::Fp8E4M3Fn, vec![EXPERTS, h, i], 1), + ( + DOWN_SCALE_INV, + WeightDType::Bf16, + vec![EXPERTS, h / BLOCK, i / BLOCK], + 2, + ), + ] +} + +fn as_u16(bytes: &[u8]) -> &[u16] { + // SAFETY: u16 has no invalid bit patterns; alignment is checked below. + let (prefix, values, suffix) = unsafe { bytes.align_to::() }; + assert!( + prefix.is_empty() && suffix.is_empty(), + "BF16 capsule view misaligned" + ); + values +} + +impl Qwen3MoeLayer { + /// Packs raw tensors into a capsule. BF16 tensors are raw bits; FP8 tensors are raw E4M3 bytes. + pub fn from_parts( + hidden: usize, + intermediate: usize, + router: &[u16], + gate_up: &[u8], + gate_up_scale_inv: &[u16], + down: &[u8], + down_scale_inv: &[u16], + ) -> Result { + Self::build(hidden, intermediate, |name, dst| { + let src: &[u8] = match name { + ROUTER => bytes_of(router), + GATE_UP => gate_up, + GATE_UP_SCALE_INV => bytes_of(gate_up_scale_inv), + DOWN => down, + _ => bytes_of(down_scale_inv), + }; + if src.len() != dst.len() { + return Err(Qwen3MoeError::Contract(format!( + "{name}: {} bytes supplied, {} expected", + src.len(), + dst.len() + ))); + } + dst.copy_from_slice(src); + Ok(()) + }) + } + + /// Allocates the capsule payload once and lets `fill` write each tensor in place. + fn build( + hidden: usize, + intermediate: usize, + mut fill: impl FnMut(&str, &mut [u8]) -> Result<(), Qwen3MoeError>, + ) -> Result { + if hidden == 0 + || intermediate == 0 + || !hidden.is_multiple_of(BLOCK) + || !intermediate.is_multiple_of(BLOCK) + { + return Err(Qwen3MoeError::Contract(format!( + "hidden {hidden} and intermediate {intermediate} must be positive multiples of {BLOCK}" + ))); + } + let specs = layer_tensor_specs(hidden, intermediate); + let mut ranges = Vec::with_capacity(specs.len()); + let mut cursor = 0usize; + for (_, _, shape, element_bytes) in &specs { + // 256-byte alignment keeps every view aligned for vector loads. + let start = cursor.div_ceil(256) * 256; + let end = start + shape.iter().product::() * element_bytes; + ranges.push(start..end); + cursor = end; + } + let mut payload = vec![0u8; cursor]; + for ((name, ..), range) in specs.iter().zip(&ranges) { + fill(name, &mut payload[range.clone()])?; + } + let bytes: Arc<[u8]> = Arc::from(payload); + let mut tensors = HashMap::new(); + for ((name, dtype, shape, _), range) in specs.into_iter().zip(ranges) { + let quant = if dtype == WeightDType::Fp8E4M3Fn { + fp8_block_quant() + } else { + None + }; + tensors.insert( + name.to_string(), + CapsuleTensor { + dtype, + layout: TensorLayout::RowMajor, + logical_strides: row_major_strides(&shape), + shape, + byte_range: range, + quant, + }, + ); + } + Ok(Self { + hidden, + intermediate, + capsule: ModelCapsule { + source_digest: source_digest(&bytes), + capsule_digest: capsule_digest(&bytes, &tensors), + bytes, + tensors, + }, + }) + } + + fn view(&self, name: &str) -> &[u8] { + self.capsule + .tensor_bytes(name) + .expect("Qwen3MoeLayer capsule always holds its five tensors") + } + + pub fn router_bf16(&self) -> &[u16] { + as_u16(self.view(ROUTER)) + } + pub fn gate_up_fp8(&self) -> &[u8] { + self.view(GATE_UP) + } + pub fn gate_up_scale_inv_bf16(&self) -> &[u16] { + as_u16(self.view(GATE_UP_SCALE_INV)) + } + pub fn down_fp8(&self) -> &[u8] { + self.view(DOWN) + } + pub fn down_scale_inv_bf16(&self) -> &[u16] { + as_u16(self.view(DOWN_SCALE_INV)) + } + + /// Bytes resident on the device for this layer's weights. + pub fn resident_weight_bytes(&self) -> usize { + [ROUTER, GATE_UP, GATE_UP_SCALE_INV, DOWN, DOWN_SCALE_INV] + .iter() + .map(|name| self.view(name).len()) + .sum() + } +} + +fn bytes_of(values: &[u16]) -> &[u8] { + // SAFETY: any u16 slice is a valid byte slice of twice the length. + unsafe { std::slice::from_raw_parts(values.as_ptr().cast::(), values.len() * 2) } +} + +/// Resolves a shard filename from the index. Only a single plain path component +/// is accepted, so an index entry cannot point outside `checkpoint_dir`. +fn shard_path(checkpoint_dir: &Path, filename: &str) -> Result { + let mut components = Path::new(filename).components(); + match (components.next(), components.next()) { + (Some(Component::Normal(name)), None) if name == filename => Ok(checkpoint_dir.join(name)), + _ => Err(Qwen3MoeError::Index(format!( + "shard filename {filename:?} is not a plain file name inside the checkpoint directory" + ))), + } +} + +struct Shard { + file: File, + payload_start: u64, + file_len: u64, + header: serde_json::Map, +} + +impl Shard { + fn open(path: &Path) -> Result { + let io = |e: std::io::Error| Qwen3MoeError::Io(format!("{}: {e}", path.display())); + let file = File::open(path).map_err(io)?; + let file_len = file.metadata().map_err(io)?.len(); + let mut prefix = [0u8; 8]; + file.read_exact_at(&mut prefix, 0).map_err(io)?; + let header_len = u64::from_le_bytes(prefix); + if header_len > MAX_HEADER_BYTES || 8 + header_len > file_len { + return Err(Qwen3MoeError::Contract(format!( + "{}: header length {header_len} is invalid for a {file_len}-byte file", + path.display() + ))); + } + let mut header = vec![0u8; header_len as usize]; + file.read_exact_at(&mut header, 8).map_err(io)?; + let header: serde_json::Value = serde_json::from_slice(&header).map_err(|e| { + Qwen3MoeError::Contract(format!("{}: header JSON: {e}", path.display())) + })?; + let header = match header { + serde_json::Value::Object(map) => map, + _ => { + return Err(Qwen3MoeError::Contract(format!( + "{}: header is not a JSON object", + path.display() + ))) + } + }; + Ok(Self { + file, + payload_start: 8 + header_len, + file_len, + header, + }) + } + + /// Reads one tensor into `dst` after checking dtype, shape and byte range. + fn read( + &self, + name: &str, + dtype: &str, + shape: &[usize], + dst: &mut [u8], + ) -> Result<(), Qwen3MoeError> { + let contract = |detail: String| Qwen3MoeError::Contract(format!("{name}: {detail}")); + let entry = self + .header + .get(name) + .ok_or_else(|| contract("missing from shard header".to_string()))?; + if entry.get("dtype").and_then(|v| v.as_str()) != Some(dtype) { + return Err(contract(format!( + "dtype {:?}, expected {dtype}", + entry.get("dtype") + ))); + } + let actual_shape: Option> = + entry.get("shape").and_then(|v| v.as_array()).map(|dims| { + dims.iter() + .filter_map(|d| d.as_u64().map(|d| d as usize)) + .collect() + }); + if actual_shape.as_deref() != Some(shape) { + return Err(contract(format!( + "shape {actual_shape:?}, expected {shape:?}" + ))); + } + let offsets: Vec = entry + .get("data_offsets") + .and_then(|v| v.as_array()) + .map(|o| o.iter().filter_map(|v| v.as_u64()).collect()) + .unwrap_or_default(); + let [start, end] = offsets[..] else { + return Err(contract("data_offsets must hold two integers".to_string())); + }; + if start > end + || end - start != dst.len() as u64 + || self.payload_start + end > self.file_len + { + return Err(contract(format!( + "byte range {start}..{end} does not hold {} bytes inside the shard", + dst.len() + ))); + } + self.file + .read_exact_at(dst, self.payload_start + start) + .map_err(|e| Qwen3MoeError::Io(format!("{name}: {e}"))) + } +} + +/// Loads one official `Qwen3-Coder-30B-A3B-Instruct-FP8` expert layer into a capsule. +/// +/// Only the shards holding that layer are opened, and only the layer's tensors are +/// read. Expert weights stay FP8; nothing is decoded. +pub fn load_qwen3_fp8_moe_layer( + checkpoint_dir: &Path, + layer: usize, +) -> Result { + load_moe_layer( + checkpoint_dir, + layer, + QWEN3_A3B_HIDDEN, + QWEN3_A3B_INTERMEDIATE, + ) +} + +fn load_moe_layer( + checkpoint_dir: &Path, + layer: usize, + h: usize, + i: usize, +) -> Result { + if layer >= QWEN3_A3B_LAYERS { + return Err(Qwen3MoeError::Contract(format!( + "layer {layer} outside [0, {QWEN3_A3B_LAYERS})" + ))); + } + let index_path = checkpoint_dir.join("model.safetensors.index.json"); + let index: serde_json::Value = serde_json::from_slice( + &std::fs::read(&index_path) + .map_err(|e| Qwen3MoeError::Io(format!("{}: {e}", index_path.display())))?, + ) + .map_err(|e| Qwen3MoeError::Index(format!("{}: {e}", index_path.display())))?; + let weight_map = index + .get("weight_map") + .and_then(|v| v.as_object()) + .ok_or_else(|| Qwen3MoeError::Index("missing weight_map object".to_string()))?; + + let prefix = format!("model.layers.{layer}.mlp"); + let mut shards: HashMap = HashMap::new(); + let mut read = + |name: &str, dtype: &str, shape: &[usize], dst: &mut [u8]| -> Result<(), Qwen3MoeError> { + let filename = weight_map + .get(name) + .and_then(|v| v.as_str()) + .ok_or_else(|| Qwen3MoeError::Index(format!("no shard for {name}")))?; + if !shards.contains_key(filename) { + let shard = Shard::open(&shard_path(checkpoint_dir, filename)?)?; + shards.insert(filename.to_string(), shard); + } + shards[filename].read(name, dtype, shape, dst) + }; + + Qwen3MoeLayer::build(h, i, |tensor, dst| match tensor { + ROUTER => read(&format!("{prefix}.gate.weight"), "BF16", &[EXPERTS, h], dst), + GATE_UP | GATE_UP_SCALE_INV => { + let scales = tensor == GATE_UP_SCALE_INV; + let per_expert = dst.len() / EXPERTS; + for (expert, chunk) in dst.chunks_exact_mut(per_expert).enumerate() { + let (gate, up) = chunk.split_at_mut(per_expert / 2); + for (projection, half) in [("gate_proj", gate), ("up_proj", up)] { + let base = format!("{prefix}.experts.{expert}.{projection}"); + if scales { + read( + &format!("{base}.weight_scale_inv"), + "BF16", + &[i / BLOCK, h / BLOCK], + half, + )?; + } else { + read(&format!("{base}.weight"), "F8_E4M3", &[i, h], half)?; + } + } + } + Ok(()) + } + _ => { + let scales = tensor == DOWN_SCALE_INV; + let per_expert = dst.len() / EXPERTS; + for (expert, chunk) in dst.chunks_exact_mut(per_expert).enumerate() { + let base = format!("{prefix}.experts.{expert}.down_proj"); + if scales { + read( + &format!("{base}.weight_scale_inv"), + "BF16", + &[h / BLOCK, i / BLOCK], + chunk, + )?; + } else { + read(&format!("{base}.weight"), "F8_E4M3", &[h, i], chunk)?; + } + } + Ok(()) + } + }) +} + +// --------------------------------------------------------------------------- +// Numeric helpers and the FP32 CPU oracle. +// --------------------------------------------------------------------------- + +pub fn bf16_to_f32(bits: u16) -> f32 { + f32::from_bits((bits as u32) << 16) +} + +/// Round-to-nearest-even FP32 to BF16. NaN stays NaN. +pub fn f32_to_bf16(value: f32) -> u16 { + let bits = value.to_bits(); + if value.is_nan() { + return ((bits >> 16) | 0x40) as u16; + } + let rounding = 0x7fff + ((bits >> 16) & 1); + ((bits + rounding) >> 16) as u16 +} + +/// E4M3FN decode: bias 7, no infinities, 0x7f/0xff are NaN. +pub fn fp8_e4m3fn_to_f32(bits: u8) -> f32 { + let sign = if bits & 0x80 != 0 { -1.0 } else { 1.0 }; + let exponent = ((bits >> 3) & 0x0f) as i32; + let mantissa = (bits & 0x07) as f32; + if exponent == 0x0f && bits & 0x07 == 0x07 { + return f32::NAN; + } + if exponent == 0 { + sign * mantissa * 2f32.powi(-9) + } else { + sign * (1.0 + mantissa / 8.0) * 2f32.powi(exponent - 7) + } +} + +fn fp8_table() -> [f32; 256] { + std::array::from_fn(|bits| fp8_e4m3fn_to_f32(bits as u8)) +} + +/// Round-to-nearest-even FP32 to E4M3FN, saturating at +/-448. NaN maps to 0x7f. +pub fn f32_to_fp8_e4m3fn(value: f32) -> u8 { + if value.is_nan() { + return 0x7f; + } + let sign = if value.is_sign_negative() { 0x80u8 } else { 0 }; + let magnitude = value.abs(); + // Positive codes 0x00..=0x7e are monotonically increasing in value. + let (mut lo, mut hi) = (0u8, 0x7eu8); + if magnitude >= fp8_e4m3fn_to_f32(hi) { + return sign | hi; + } + while hi - lo > 1 { + let mid = lo + (hi - lo) / 2; + if fp8_e4m3fn_to_f32(mid) <= magnitude { + lo = mid; + } else { + hi = mid; + } + } + let (below, above) = (fp8_e4m3fn_to_f32(lo), fp8_e4m3fn_to_f32(hi)); + let code = match (magnitude - below).partial_cmp(&(above - magnitude)) { + Some(std::cmp::Ordering::Less) => lo, + Some(std::cmp::Ordering::Greater) => hi, + _ => { + if lo & 1 == 0 { + lo + } else { + hi + } + } + }; + sign | code +} + +/// How the oracle treats activations entering each expert GEMM. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum OracleActivations { + /// Exact FP32 activations: measures the device's end-to-end numeric quality. + Fp32, + /// Quantize each row's 128-channel blocks to E4M3 exactly as the device does + /// (scale = max|v| / 448). Isolates indexing and accumulation from rounding. + Fp8Block128, +} + +fn quantize_block128_in_place(values: &mut [f32]) { + for block in values.chunks_mut(BLOCK) { + let maximum = block.iter().fold(0.0f32, |m, v| m.max(v.abs())); + let scale = if maximum > 0.0 { maximum / 448.0 } else { 1.0 }; + for v in block.iter_mut() { + *v = fp8_e4m3fn_to_f32(f32_to_fp8_e4m3fn(*v / scale)) * scale; + } + } +} + +/// FP32 router logits [tokens, 128] from BF16-representable inputs. +pub fn reference_router_logits(layer: &Qwen3MoeLayer, x: &[f32], tokens: usize) -> Vec { + let h = layer.hidden; + let router: Vec = layer + .router_bf16() + .iter() + .map(|&b| bf16_to_f32(b)) + .collect(); + let mut logits = vec![0.0f32; tokens * EXPERTS]; + logits + .par_chunks_mut(EXPERTS) + .enumerate() + .for_each(|(t, row)| { + let xt = &x[t * h..(t + 1) * h]; + for (e, logit) in row.iter_mut().enumerate() { + *logit = xt + .iter() + .zip(&router[e * h..(e + 1) * h]) + .map(|(a, b)| a * b) + .sum(); + } + }); + logits +} + +/// out[r] = sum_k W[r, k] * v[k] with W an FP8 [rows, cols] matrix and 128x128 BF16 inverse scales. +fn dequant_matvec( + weights: &[u8], + scales: &[u16], + rows: usize, + cols: usize, + v: &[f32], + lut: &[f32; 256], +) -> Vec { + let k_blocks = cols / BLOCK; + (0..rows) + .map(|r| { + let row = &weights[r * cols..(r + 1) * cols]; + (0..k_blocks) + .map(|b| { + let dot: f32 = row[b * BLOCK..(b + 1) * BLOCK] + .iter() + .zip(&v[b * BLOCK..(b + 1) * BLOCK]) + .map(|(&w, &x)| lut[w as usize] * x) + .sum(); + dot * bf16_to_f32(scales[(r / BLOCK) * k_blocks + b]) + }) + .sum() + }) + .collect() +} + +/// Independent FP32 layer output [tokens, H] for a routing plan. +/// +/// Weights are dequantized exactly from FP8; activations are not quantized, so the +/// difference to the device measures the device's activation quantization and +/// accumulation order. +pub fn reference_moe_forward(layer: &Qwen3MoeLayer, x: &[f32], plan: &MoeBatchPlan) -> Vec { + reference_moe_forward_with(layer, x, plan, OracleActivations::Fp32) +} + +pub fn reference_moe_forward_with( + layer: &Qwen3MoeLayer, + x: &[f32], + plan: &MoeBatchPlan, + activations: OracleActivations, +) -> Vec { + let quantize = activations == OracleActivations::Fp8Block128; + let (h, i) = (layer.hidden, layer.intermediate); + let lut = fp8_table(); + let gate_up = layer.gate_up_fp8(); + let gate_up_scales = layer.gate_up_scale_inv_bf16(); + let down = layer.down_fp8(); + let down_scales = layer.down_scale_inv_bf16(); + let gu_scale_len = (2 * i / BLOCK) * (h / BLOCK); + let down_scale_len = (h / BLOCK) * (i / BLOCK); + let mut output = vec![0.0f32; plan.tokens * h]; + output.par_chunks_mut(h).enumerate().for_each(|(t, out)| { + let mut xt = x[t * h..(t + 1) * h].to_vec(); + if quantize { + quantize_block128_in_place(&mut xt); + } + for slot in 0..plan.top_k { + let assignment = t * plan.top_k + slot; + let e = plan.topk_experts[assignment] as usize; + let weight = plan.topk_weights[assignment]; + let projected = dequant_matvec( + &gate_up[e * 2 * i * h..(e + 1) * 2 * i * h], + &gate_up_scales[e * gu_scale_len..(e + 1) * gu_scale_len], + 2 * i, + h, + &xt, + &lut, + ); + let mut hidden: Vec = (0..i) + .map(|j| { + let gate = projected[j]; + gate / (1.0 + (-gate).exp()) * projected[i + j] + }) + .collect(); + if quantize { + quantize_block128_in_place(&mut hidden); + } + let expert_out = dequant_matvec( + &down[e * h * i..(e + 1) * h * i], + &down_scales[e * down_scale_len..(e + 1) * down_scale_len], + h, + i, + &hidden, + &lut, + ); + for (o, v) in out.iter_mut().zip(expert_out) { + *o += weight * v; + } + } + }); + output +} + +/// Agreement between a device output and the oracle. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct ParityStats { + pub cosine: f64, + pub max_abs: f32, + /// 95th percentile of |a - e| / max(|e|, 0.05). + pub p95_rel: f32, + pub max_abs_expected: f32, + pub non_finite: usize, +} + +pub fn parity_stats(actual: &[f32], expected: &[f32]) -> ParityStats { + assert_eq!(actual.len(), expected.len()); + let (mut dot, mut na, mut ne) = (0.0f64, 0.0f64, 0.0f64); + let mut max_abs = 0.0f32; + let mut max_abs_expected = 0.0f32; + let mut non_finite = 0; + let mut relative = Vec::with_capacity(actual.len()); + for (&a, &e) in actual.iter().zip(expected) { + if !a.is_finite() { + non_finite += 1; + continue; + } + dot += a as f64 * e as f64; + na += a as f64 * a as f64; + ne += e as f64 * e as f64; + let diff = (a - e).abs(); + max_abs = max_abs.max(diff); + max_abs_expected = max_abs_expected.max(e.abs()); + relative.push(diff / e.abs().max(0.05)); + } + relative.sort_by(f32::total_cmp); + let p95_rel = relative + .get((relative.len().saturating_sub(1) * 95).div_ceil(100)) + .copied() + .unwrap_or(f32::NAN); + ParityStats { + cosine: dot / (na.sqrt() * ne.sqrt()), + max_abs, + p95_rel, + max_abs_expected, + non_finite, + } +} + +// --------------------------------------------------------------------------- +// Mojo library binding. +// --------------------------------------------------------------------------- + +type ForwardFn = unsafe extern "C" fn( + i32, + i32, + i32, + *const u16, + *const u16, + *const u8, + *const u16, + *const u8, + *const u16, + *mut u16, + *mut f32, + *mut i32, + *mut f32, + *mut u32, + *mut u32, +) -> i32; +type BenchmarkFn = unsafe extern "C" fn( + i32, + i32, + i32, + *const u16, + *const u16, + *const u8, + *const u16, + *const u8, + *const u16, + i32, + i32, + *mut u64, +) -> i32; +type RouteFn = + unsafe extern "C" fn(i32, *const f32, *mut i32, *mut f32, *mut u32, *mut u32, *mut u32) -> i32; +type GemmFn = unsafe extern "C" fn( + i32, + i32, + i32, + i32, + i32, + *const u8, + *const f32, + *const u8, + *const u16, + *const u32, + *const i32, + *mut f32, +) -> i32; + +/// Device outputs of one layer call. Routing metadata is returned for parity checks. +#[derive(Debug, Clone)] +pub struct Qwen3MoeDeviceOutput { + pub output: Vec, + pub logits: Vec, + pub expert_ids: Vec, + pub weights: Vec, + pub offsets: Vec, + pub order: Vec, +} + +/// Device routing of caller-supplied logits. +#[derive(Debug, Clone)] +pub struct Qwen3DeviceRouting { + pub expert_ids: Vec, + pub weights: Vec, + pub offsets: Vec, + pub order: Vec, + pub restore: Vec, +} + +pub struct Qwen3MoeKernels { + _lib: Library, + forward: ForwardFn, + benchmark: BenchmarkFn, + route: RouteFn, + gemm: GemmFn, + pub path: PathBuf, +} + +fn status(code: i32) -> Result<(), Qwen3MoeError> { + if code == 0 { + Ok(()) + } else { + Err(Qwen3MoeError::Kernel(code)) + } +} + +fn dim(value: usize, what: &str) -> Result { + i32::try_from(value).map_err(|_| Qwen3MoeError::Contract(format!("{what} {value} exceeds i32"))) +} + +impl Qwen3MoeKernels { + /// `AIEN_QWEN3_MOE_LIB`, else the crate's `mojo/qwen3_moe/libaien_qwen3_moe.so`. + pub fn default_path() -> PathBuf { + std::env::var_os("AIEN_QWEN3_MOE_LIB") + .map(PathBuf::from) + .unwrap_or_else(|| { + Path::new(env!("CARGO_MANIFEST_DIR")).join("mojo/qwen3_moe/libaien_qwen3_moe.so") + }) + } + + pub fn load(path: &Path) -> Result { + let err = |e: libloading::Error| Qwen3MoeError::Library(format!("{}: {e}", path.display())); + // SAFETY: the library is built from mojo/qwen3_moe and exports these C signatures. + unsafe { + let lib = Library::new(path).map_err(err)?; + let forward = *lib + .get::(b"aien_qwen3_moe_forward\0") + .map_err(err)?; + let benchmark = *lib + .get::(b"aien_qwen3_moe_benchmark\0") + .map_err(err)?; + let route = *lib + .get::(b"aien_qwen3_route_top8\0") + .map_err(err)?; + let gemm: Symbol = lib.get(b"aien_qwen3_grouped_fp8_gemm\0").map_err(err)?; + let gemm = *gemm; + Ok(Self { + _lib: lib, + forward, + benchmark, + route, + gemm, + path: path.to_path_buf(), + }) + } + } + + /// Runs the full layer on `tokens` BF16 input rows ([tokens, H] raw bits). + pub fn forward( + &self, + layer: &Qwen3MoeLayer, + x_bf16: &[u16], + tokens: usize, + ) -> Result { + let h = layer.hidden; + if tokens == 0 || x_bf16.len() != tokens * h { + return Err(Qwen3MoeError::Contract(format!( + "input must be [{tokens}, {h}]" + ))); + } + let mut output = vec![0u16; tokens * h]; + let mut logits = vec![0.0f32; tokens * EXPERTS]; + let mut expert_ids = vec![0i32; tokens * TOP_K]; + let mut weights = vec![0.0f32; tokens * TOP_K]; + let mut offsets = vec![0u32; EXPERTS + 1]; + let mut order = vec![0u32; tokens * TOP_K]; + // SAFETY: every buffer is sized for the shape passed alongside it. + status(unsafe { + (self.forward)( + dim(tokens, "tokens")?, + dim(h, "hidden")?, + dim(layer.intermediate, "intermediate")?, + x_bf16.as_ptr(), + layer.router_bf16().as_ptr(), + layer.gate_up_fp8().as_ptr(), + layer.gate_up_scale_inv_bf16().as_ptr(), + layer.down_fp8().as_ptr(), + layer.down_scale_inv_bf16().as_ptr(), + output.as_mut_ptr(), + logits.as_mut_ptr(), + expert_ids.as_mut_ptr(), + weights.as_mut_ptr(), + offsets.as_mut_ptr(), + order.as_mut_ptr(), + ) + })?; + Ok(Qwen3MoeDeviceOutput { + output: output.into_iter().map(bf16_to_f32).collect(), + logits, + expert_ids, + weights, + offsets, + order, + }) + } + + /// Per-sample wall time in nanoseconds for `repeats` resident-weight layer calls. + pub fn benchmark( + &self, + layer: &Qwen3MoeLayer, + x_bf16: &[u16], + tokens: usize, + warmup: usize, + repeats: usize, + ) -> Result, Qwen3MoeError> { + if tokens == 0 || x_bf16.len() != tokens * layer.hidden || repeats == 0 { + return Err(Qwen3MoeError::Contract("benchmark shape".to_string())); + } + let mut samples = vec![0u64; repeats]; + // SAFETY: as in `forward`; `samples` holds `repeats` entries. + status(unsafe { + (self.benchmark)( + dim(tokens, "tokens")?, + dim(layer.hidden, "hidden")?, + dim(layer.intermediate, "intermediate")?, + x_bf16.as_ptr(), + layer.router_bf16().as_ptr(), + layer.gate_up_fp8().as_ptr(), + layer.gate_up_scale_inv_bf16().as_ptr(), + layer.down_fp8().as_ptr(), + layer.down_scale_inv_bf16().as_ptr(), + dim(warmup, "warmup")?, + dim(repeats, "repeats")?, + samples.as_mut_ptr(), + ) + })?; + Ok(samples) + } + + /// Routes caller-supplied logits [tokens, 128] with the device router and grouping. + pub fn route( + &self, + logits: &[f32], + tokens: usize, + ) -> Result { + if tokens == 0 || logits.len() != tokens * EXPERTS { + return Err(Qwen3MoeError::Contract(format!( + "logits must be [{tokens}, {EXPERTS}]" + ))); + } + let n = tokens * TOP_K; + let mut routing = Qwen3DeviceRouting { + expert_ids: vec![0; n], + weights: vec![0.0; n], + offsets: vec![0; EXPERTS + 1], + order: vec![0; n], + restore: vec![0; n], + }; + // SAFETY: buffers sized for `tokens`. + status(unsafe { + (self.route)( + dim(tokens, "tokens")?, + logits.as_ptr(), + routing.expert_ids.as_mut_ptr(), + routing.weights.as_mut_ptr(), + routing.offsets.as_mut_ptr(), + routing.order.as_mut_ptr(), + routing.restore.as_mut_ptr(), + ) + })?; + Ok(routing) + } + + /// Standalone grouped FP8 GEMM. Weights [experts, out, in], offsets [groups + 1]. + #[allow(clippy::too_many_arguments)] + pub fn grouped_fp8_gemm( + &self, + rows: usize, + experts: usize, + out_channels: usize, + in_channels: usize, + activations: &[u8], + activation_scales: &[f32], + weights: &[u8], + weight_scales_bf16: &[u16], + offsets: &[u32], + expert_ids: &[i32], + ) -> Result, Qwen3MoeError> { + let groups = expert_ids.len(); + if activations.len() != rows * in_channels + || activation_scales.len() != rows * (in_channels / BLOCK) + || weights.len() != experts * out_channels * in_channels + || weight_scales_bf16.len() != experts * (out_channels / BLOCK) * (in_channels / BLOCK) + || offsets.len() != groups + 1 + { + return Err(Qwen3MoeError::Contract( + "grouped FP8 GEMM buffer sizes".to_string(), + )); + } + let mut result = vec![0.0f32; rows * out_channels]; + // SAFETY: sizes validated above; the library validates offsets and expert IDs. + status(unsafe { + (self.gemm)( + dim(rows, "rows")?, + dim(groups, "groups")?, + dim(experts, "experts")?, + dim(out_channels, "out_channels")?, + dim(in_channels, "in_channels")?, + activations.as_ptr(), + activation_scales.as_ptr(), + weights.as_ptr(), + weight_scales_bf16.as_ptr(), + offsets.as_ptr(), + expert_ids.as_ptr(), + result.as_mut_ptr(), + ) + })?; + Ok(result) + } +} + +/// Deterministic N(0, sigma) inputs rounded to BF16: (bits, exact f32 values). +pub fn seeded_bf16_input( + seed: u64, + tokens: usize, + hidden: usize, + sigma: f32, +) -> (Vec, Vec) { + let mut state = seed; + let mut next = move || { + // splitmix64 + state = state.wrapping_add(0x9e37_79b9_7f4a_7c15); + let mut z = state; + z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9); + z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb); + ((z ^ (z >> 31)) >> 11) as f64 / (1u64 << 53) as f64 + }; + let bits: Vec = (0..tokens * hidden) + .map(|_| { + let (u1, u2) = (next().max(1e-12), next()); + let normal = (-2.0 * u1.ln()).sqrt() * (2.0 * std::f64::consts::PI * u2).cos(); + f32_to_bf16(normal as f32 * sigma) + }) + .collect(); + let values = bits.iter().map(|&b| bf16_to_f32(b)).collect(); + (bits, values) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn fp8_e4m3fn_decodes_known_values() { + assert_eq!(fp8_e4m3fn_to_f32(0x38), 1.0); + assert_eq!(fp8_e4m3fn_to_f32(0x30), 0.5); + assert_eq!(fp8_e4m3fn_to_f32(0xc0), -2.0); + assert_eq!(fp8_e4m3fn_to_f32(0x7e), 448.0); + assert_eq!(fp8_e4m3fn_to_f32(0x01), 2f32.powi(-9)); + assert!(fp8_e4m3fn_to_f32(0x7f).is_nan()); + assert!(fp8_e4m3fn_to_f32(0xff).is_nan()); + } + + #[test] + fn fp8_encode_rounds_to_nearest_even_and_saturates() { + for bits in 0u8..=0x7e { + for code in [bits, bits | 0x80] { + assert_eq!( + f32_to_fp8_e4m3fn(fp8_e4m3fn_to_f32(code)), + code, + "exact {code:#x}" + ); + } + } + // 1.0625 lies halfway between 1.0 (0x38, even) and 1.125 (0x39). + assert_eq!(f32_to_fp8_e4m3fn(1.0625), 0x38); + // 1.1875 lies halfway between 1.125 (0x39) and 1.25 (0x3a, even). + assert_eq!(f32_to_fp8_e4m3fn(1.1875), 0x3a); + assert_eq!(f32_to_fp8_e4m3fn(1.07), 0x39); + assert_eq!(f32_to_fp8_e4m3fn(1000.0), 0x7e); + assert_eq!(f32_to_fp8_e4m3fn(-1000.0), 0xfe); + assert_eq!(f32_to_fp8_e4m3fn(-0.0), 0x80); + } + + #[test] + fn bf16_rounds_to_nearest_even() { + assert_eq!(f32_to_bf16(1.0), 0x3f80); + assert_eq!(bf16_to_f32(f32_to_bf16(1.0 + 1.0 / 256.0)), 1.0); + assert_eq!( + bf16_to_f32(f32_to_bf16(1.0 + 3.0 / 256.0)), + 1.0 + 4.0 / 256.0 + ); + assert!(bf16_to_f32(f32_to_bf16(f32::NAN)).is_nan()); + } + + #[test] + fn shard_names_cannot_escape_the_checkpoint_directory() { + let dir = Path::new("/ckpt"); + assert_eq!( + shard_path(dir, "model-00001-of-00004.safetensors").unwrap(), + PathBuf::from("/ckpt/model-00001-of-00004.safetensors") + ); + for bad in [ + "../secret", + "/etc/passwd", + "sub/model.safetensors", + "..", + ".", + "", + "./x", + ] { + assert!(shard_path(dir, bad).is_err(), "{bad:?} must be rejected"); + } + } + + #[test] + fn capsule_views_round_trip_and_digest_covers_payload() { + let (h, i) = (128, 128); + let router: Vec = (0..EXPERTS * h).map(|v| v as u16).collect(); + let gate_up = vec![0x38u8; EXPERTS * 2 * i * h]; + let gate_up_scales = vec![0x3f80u16; EXPERTS * 2]; + let down = vec![0x30u8; EXPERTS * h * i]; + let down_scales = vec![0x4000u16; EXPERTS]; + let layer = Qwen3MoeLayer::from_parts( + h, + i, + &router, + &gate_up, + &gate_up_scales, + &down, + &down_scales, + ) + .unwrap(); + assert_eq!(layer.router_bf16(), &router[..]); + assert_eq!(layer.gate_up_fp8(), &gate_up[..]); + assert_eq!(layer.gate_up_scale_inv_bf16(), &gate_up_scales[..]); + assert_eq!(layer.down_fp8(), &down[..]); + assert_eq!(layer.down_scale_inv_bf16(), &down_scales[..]); + assert_eq!( + layer.capsule.tensor(GATE_UP).unwrap().dtype, + WeightDType::Fp8E4M3Fn + ); + assert!(layer.capsule.tensor(GATE_UP).unwrap().quant.is_some()); + + let mut changed_down = down.clone(); + changed_down[7] = 0x38; + let changed = Qwen3MoeLayer::from_parts( + h, + i, + &router, + &gate_up, + &gate_up_scales, + &changed_down, + &down_scales, + ) + .unwrap(); + assert_ne!(layer.capsule.capsule_digest, changed.capsule.capsule_digest); + + assert!(Qwen3MoeLayer::from_parts( + h, + i, + &router, + &gate_up, + &gate_up_scales, + &down[1..], + &down_scales + ) + .is_err()); + assert!(Qwen3MoeLayer::from_parts( + 100, + i, + &router, + &gate_up, + &gate_up_scales, + &down, + &down_scales + ) + .is_err()); + } + + #[test] + fn loader_reads_one_layer_from_a_sharded_checkpoint_and_rejects_bad_contracts() { + let dir = std::env::temp_dir().join(format!("aien-qwen3-loader-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let (h, i) = (256, 128); + let prefix = "model.layers.3.mlp"; + // Two shards: router and experts 0..63 in the first, the rest in the second. + // (name, dtype, shape, payload) per shard. + type ShardTensors<'a> = Vec<(String, &'a str, Vec, Vec)>; + let mut shard_tensors: [ShardTensors; 2] = [Vec::new(), Vec::new()]; + shard_tensors[0].push(( + format!("{prefix}.gate.weight"), + "BF16", + vec![EXPERTS, h], + vec![0x11; EXPERTS * h * 2], + )); + for expert in 0..EXPERTS { + let shard = usize::from(expert >= 64); + let base = format!("{prefix}.experts.{expert}"); + let tag = expert as u8; + shard_tensors[shard].push(( + format!("{base}.gate_proj.weight"), + "F8_E4M3", + vec![i, h], + vec![tag; i * h], + )); + shard_tensors[shard].push(( + format!("{base}.up_proj.weight"), + "F8_E4M3", + vec![i, h], + vec![tag ^ 0x80; i * h], + )); + shard_tensors[shard].push(( + format!("{base}.down_proj.weight"), + "F8_E4M3", + vec![h, i], + vec![tag ^ 0x40; h * i], + )); + for projection in ["gate_proj", "up_proj"] { + shard_tensors[shard].push(( + format!("{base}.{projection}.weight_scale_inv"), + "BF16", + vec![i / BLOCK, h / BLOCK], + vec![tag; (i / BLOCK) * (h / BLOCK) * 2], + )); + } + shard_tensors[shard].push(( + format!("{base}.down_proj.weight_scale_inv"), + "BF16", + vec![h / BLOCK, i / BLOCK], + vec![tag; (h / BLOCK) * (i / BLOCK) * 2], + )); + } + let mut weight_map = serde_json::Map::new(); + for (index, tensors) in shard_tensors.iter().enumerate() { + let filename = format!("shard-{index}.safetensors"); + let mut header = serde_json::Map::new(); + let mut payload = Vec::new(); + for (name, dtype, shape, bytes) in tensors { + header.insert(name.clone(), serde_json::json!({"dtype": dtype, "shape": shape, "data_offsets": [payload.len(), payload.len() + bytes.len()]})); + payload.extend_from_slice(bytes); + weight_map.insert(name.clone(), serde_json::json!(filename)); + } + let header = serde_json::to_vec(&header).unwrap(); + let mut file = (header.len() as u64).to_le_bytes().to_vec(); + file.extend_from_slice(&header); + file.extend_from_slice(&payload); + std::fs::write(dir.join(&filename), file).unwrap(); + } + let write_index = |map: &serde_json::Map| { + std::fs::write( + dir.join("model.safetensors.index.json"), + serde_json::to_vec(&serde_json::json!({"weight_map": map})).unwrap(), + ) + .unwrap(); + }; + write_index(&weight_map); + + let layer = load_moe_layer(&dir, 3, h, i).unwrap(); + let per_expert = 2 * i * h; + for expert in [0usize, 63, 64, 127] { + let tag = expert as u8; + assert_eq!(layer.gate_up_fp8()[expert * per_expert], tag); + assert_eq!(layer.gate_up_fp8()[expert * per_expert + i * h], tag ^ 0x80); + assert_eq!(layer.down_fp8()[expert * h * i], tag ^ 0x40); + } + assert!(layer.router_bf16().iter().all(|&v| v == 0x1111)); + assert!( + load_moe_layer(&dir, 4, h, i).is_err(), + "layer 4 is not in the checkpoint" + ); + assert!(load_qwen3_fp8_moe_layer(&dir, QWEN3_A3B_LAYERS).is_err()); + + let mut escaping = weight_map.clone(); + escaping.insert( + format!("{prefix}.gate.weight"), + serde_json::json!("../shard-0.safetensors"), + ); + write_index(&escaping); + assert!(matches!( + load_moe_layer(&dir, 3, h, i), + Err(Qwen3MoeError::Index(_)) + )); + + let mut wrong_shard = weight_map.clone(); + wrong_shard.insert( + format!("{prefix}.experts.5.down_proj.weight"), + serde_json::json!("shard-1.safetensors"), + ); + write_index(&wrong_shard); + assert!(matches!( + load_moe_layer(&dir, 3, h, i), + Err(Qwen3MoeError::Contract(_)) + )); + std::fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn oracle_matches_hand_computed_identity_expert() { + let (h, i) = (128, 128); + let mut gate_up = vec![0u8; EXPERTS * 2 * i * h]; + let mut down = vec![0u8; EXPERTS * h * i]; + for e in 0..EXPERTS { + for c in 0..128 { + gate_up[e * 2 * i * h + c * h + c] = 0x38; + gate_up[e * 2 * i * h + (i + c) * h + c] = 0x40; // 2.0 + down[e * h * i + c * i + c] = 0x38; + } + } + let layer = Qwen3MoeLayer::from_parts( + h, + i, + &vec![0u16; EXPERTS * h], + &gate_up, + &vec![0x3f80; EXPERTS * 2], + &down, + &vec![0x3f80; EXPERTS], + ) + .unwrap(); + let x = vec![1.0f32; h]; + let plan = + MoeBatchPlan::qwen3_coder_a3b(&reference_router_logits(&layer, &x, 1), 1).unwrap(); + let out = reference_moe_forward(&layer, &x, &plan); + let expected = 2.0 / (1.0 + (-1.0f32).exp()); + assert!( + out.iter().all(|v| (v - expected).abs() < 1e-5), + "{:?}", + &out[..4] + ); + } +} diff --git a/crates/aien-inference-abi/tests/qwen3_moe_gpu.rs b/crates/aien-inference-abi/tests/qwen3_moe_gpu.rs new file mode 100644 index 00000000..8e8bb056 --- /dev/null +++ b/crates/aien-inference-abi/tests/qwen3_moe_gpu.rs @@ -0,0 +1,468 @@ +//! GB10 parity tests for the Mojo Qwen3-Coder-A3B routed expert layer. +//! +//! Build the library first: `crates/aien-inference-abi/mojo/qwen3_moe/build.sh`. +//! Without it these tests skip, unless `AIEN_REQUIRE_GPU_TESTS=1` makes that a failure. +//! `AIEN_QWEN3_FP8_CHECKPOINT=` enables the official-checkpoint test; +//! `AIEN_QWEN3_LAYERS=0,1,23,24,47` picks its layers. + +use aien_inference_abi::{ + bf16_to_f32, f32_to_bf16, fp8_e4m3fn_to_f32, load_qwen3_fp8_moe_layer, parity_stats, + reference_moe_forward_with, reference_router_logits, seeded_bf16_input, MoeBatchPlan, + OracleActivations, Qwen3MoeError, Qwen3MoeKernels, Qwen3MoeLayer, + QWEN3_CODER_A3B_EXPERTS as EXPERTS, QWEN3_CODER_A3B_TOP_K as TOP_K, +}; +use std::path::PathBuf; +use std::sync::{Mutex, MutexGuard, OnceLock}; + +/// Tests share one GPU; serialize them so each gets a clean device context. +fn gpu() -> Option<(MutexGuard<'static, ()>, &'static Qwen3MoeKernels)> { + static LOCK: Mutex<()> = Mutex::new(()); + static KERNELS: OnceLock> = OnceLock::new(); + let guard = LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let kernels = KERNELS.get_or_init(|| { + let path = Qwen3MoeKernels::default_path(); + match Qwen3MoeKernels::load(&path) { + Ok(kernels) => Some(kernels), + Err(error) if std::env::var_os("AIEN_REQUIRE_GPU_TESTS").is_some() => { + panic!( + "AIEN_REQUIRE_GPU_TESTS is set but the kernel library is unavailable: {error}" + ) + } + Err(error) => { + eprintln!("skipping Qwen3 MoE GPU test: {error}"); + None + } + } + }); + kernels.as_ref().map(|k| (guard, k)) +} + +/// Deterministic generator for test data. +struct Rng(u64); +impl Rng { + fn next(&mut self) -> u64 { + self.0 = self + .0 + .wrapping_mul(6364136223846793005) + .wrapping_add(1442695040888963407); + self.0 >> 33 + } + fn uniform(&mut self) -> f32 { + (self.next() % 1_000_000) as f32 / 1_000_000.0 + } + /// A finite E4M3 byte with magnitude at most 2. + fn fp8(&mut self) -> u8 { + let magnitude = (self.next() % 0x41) as u8; // 0x00..=0x40, up to 2.0 + magnitude + | if self.next().is_multiple_of(2) { + 0x80 + } else { + 0 + } + } +} + +#[test] +fn grouped_fp8_gemm_matches_block_scaled_reference() { + let Some((_gpu, kernels)) = gpu() else { return }; + // Two experts, ragged groups, two 128-channel blocks on each axis, and + // distinct values per row, column and expert to expose fragment mapping. + let (rows, experts, channels) = (26usize, 2usize, 256usize); + let values = [0.0f32, 0.5, 1.0, 2.0, -0.5, -1.0, -2.0]; + let bits = [0x00u8, 0x30, 0x38, 0x40, 0xb0, 0xb8, 0xc0]; + let a_index = |r: usize, k: usize| (r * 3 + k * 5) % 7; + let w_index = |e: usize, o: usize, k: usize| (e * 2 + o * 3 + k * 5) % 7; + let activations: Vec = (0..rows * channels) + .map(|i| bits[a_index(i / channels, i % channels)]) + .collect(); + let weights: Vec = (0..experts * channels * channels) + .map(|i| { + bits[w_index( + i / (channels * channels), + (i / channels) % channels, + i % channels, + )] + }) + .collect(); + let a_scales: Vec = (0..rows * 2) + .map(|i| if (i / 2) % 2 == 0 { 1.0 } else { 0.5 } * [1.0, 2.0][i % 2]) + .collect(); + let w_scales_f32 = [1.0f32, 0.5, 2.0, 1.0, 0.5, 2.0, 1.0, 0.5]; + let w_scales: Vec = w_scales_f32.iter().map(|&v| f32_to_bf16(v)).collect(); + let offsets = [0u32, 19, rows as u32]; + let expert_ids = [1i32, 0]; + + let actual = kernels + .grouped_fp8_gemm( + rows, + experts, + channels, + channels, + &activations, + &a_scales, + &weights, + &w_scales, + &offsets, + &expert_ids, + ) + .unwrap(); + for row in 0..rows { + let expert = expert_ids[usize::from(row >= 19)] as usize; + for out in 0..channels { + let mut total = 0.0f64; + for block in 0..2 { + let dot: f64 = (block * 128..(block + 1) * 128) + .map(|k| { + values[a_index(row, k)] as f64 * values[w_index(expert, out, k)] as f64 + }) + .sum(); + total += dot + * a_scales[row * 2 + block] as f64 + * w_scales_f32[expert * 4 + (out / 128) * 2 + block] as f64; + } + let got = actual[row * channels + out] as f64; + assert!( + (got - total).abs() <= 2e-4, + "row {row} out {out}: {got} vs {total}" + ); + } + } +} + +#[test] +fn grouped_fp8_gemm_rejects_out_of_range_groups() { + let Some((_gpu, kernels)) = gpu() else { return }; + let (rows, c) = (4usize, 128usize); + let run = |offsets: &[u32], ids: &[i32]| { + kernels.grouped_fp8_gemm( + rows, + 1, + c, + c, + &vec![0x38; rows * c], + &vec![1.0; rows], + &vec![0x38; c * c], + &[0x3f80], + offsets, + ids, + ) + }; + assert!(run(&[0, 4], &[0]).is_ok()); + assert_eq!( + run(&[0, 4], &[1]).unwrap_err(), + Qwen3MoeError::Kernel(1), + "expert id beyond weights" + ); + assert_eq!( + run(&[0, 4], &[-1]).unwrap_err(), + Qwen3MoeError::Kernel(1), + "negative expert id" + ); + assert_eq!( + run(&[0, 5], &[0]).unwrap_err(), + Qwen3MoeError::Kernel(1), + "offsets past the last row" + ); + assert_eq!( + run(&[0, 3, 2, 4].as_slice()[..3], &[0, 0]).unwrap_err(), + Qwen3MoeError::Kernel(1), + "non-monotonic offsets" + ); +} + +/// Rust router == Mojo router == device grouping permutation == inverse map. +#[test] +fn device_routing_matches_moe_batch_plan_exactly() { + let Some((_gpu, kernels)) = gpu() else { return }; + let tokens = 1024; + let mut rng = Rng(7); + let mut logits: Vec = (0..tokens * EXPERTS) + .map(|_| rng.uniform() * 8.0 - 4.0) + .collect(); + // Token 0: every logit tied, so selection is purely by lowest expert ID. + logits[..EXPERTS].fill(0.25); + // Token 1: ties straddling the top-8 boundary and the 64-expert mask split. + logits[EXPERTS..2 * EXPERTS].fill(-10.0); + for (expert, value) in [ + (3, 5.0), + (70, 5.0), + (64, 4.0), + (63, 4.0), + (100, 3.0), + (2, 3.0), + (127, 3.0), + (0, 3.0), + (1, 3.0), + ] { + logits[EXPERTS + expert] = value; + } + // Token 2: a skewed router that sends most weight to one expert. + logits[2 * EXPERTS + 17] = 30.0; + + let device = kernels.route(&logits, tokens).unwrap(); + let plan = MoeBatchPlan::qwen3_coder_a3b(&logits, tokens).unwrap(); + + let device_ids: Vec = device.expert_ids.iter().map(|&id| id as u32).collect(); + assert_eq!(device_ids, plan.topk_experts, "top-8 expert selection"); + assert_eq!( + &device_ids[..TOP_K], + &[0, 1, 2, 3, 4, 5, 6, 7], + "all-tied token uses lowest IDs" + ); + assert_eq!( + &device_ids[TOP_K..2 * TOP_K], + &[3, 70, 63, 64, 0, 1, 2, 100], + "ties resolve by lower ID" + ); + for (a, (d, p)) in device.weights.iter().zip(&plan.topk_weights).enumerate() { + assert!((d - p).abs() <= 1e-6, "assignment {a}: weight {d} vs {p}"); + } + assert_eq!(device.offsets, plan.expert_offsets, "expert offsets"); + assert_eq!( + device.order, plan.grouped_to_assignment, + "grouped permutation" + ); + assert_eq!(device.restore, plan.assignment_to_grouped, "inverse map"); +} + +#[test] +fn device_router_fails_closed_on_non_finite_logits() { + let Some((_gpu, kernels)) = gpu() else { return }; + for poison in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] { + let mut logits = vec![0.0f32; 3 * EXPERTS]; + logits[EXPERTS + 77] = poison; + assert_eq!( + kernels.route(&logits, 3).unwrap_err(), + Qwen3MoeError::Kernel(2), + "{poison}" + ); + assert!( + MoeBatchPlan::qwen3_coder_a3b(&logits, 3).is_err(), + "host plan agrees for {poison}" + ); + } +} + +/// A layer small enough for a fast oracle but with every expert distinct, varied +/// routing, multiple 128-channel blocks and a ragged token count. +fn synthetic_layer(seed: u64, hidden: usize, intermediate: usize) -> Qwen3MoeLayer { + let mut rng = Rng(seed); + let router: Vec = (0..EXPERTS * hidden) + .map(|_| f32_to_bf16((rng.uniform() - 0.5) * 0.5)) + .collect(); + let gate_up: Vec = (0..EXPERTS * 2 * intermediate * hidden) + .map(|_| rng.fp8()) + .collect(); + let down: Vec = (0..EXPERTS * hidden * intermediate) + .map(|_| rng.fp8()) + .collect(); + let mut scale = |count: usize| -> Vec { + (0..count) + .map(|_| f32_to_bf16(0.01 + rng.uniform() * 0.05)) + .collect() + }; + let gate_up_scales = scale(EXPERTS * (2 * intermediate / 128) * (hidden / 128)); + let down_scales = scale(EXPERTS * (hidden / 128) * (intermediate / 128)); + Qwen3MoeLayer::from_parts( + hidden, + intermediate, + &router, + &gate_up, + &gate_up_scales, + &down, + &down_scales, + ) + .unwrap() +} + +/// Checks a device layer call against the oracle. The oracle routes with the +/// device's own logits so near-tie reordering from FP32 summation order cannot +/// change which experts are compared; the logits themselves are checked separately. +fn check_layer( + kernels: &Qwen3MoeKernels, + layer: &Qwen3MoeLayer, + x_bits: &[u16], + x: &[f32], + tokens: usize, + oracle: OracleActivations, + label: &str, +) -> aien_inference_abi::ParityStats { + let device = kernels.forward(layer, x_bits, tokens).unwrap(); + let cpu_logits = reference_router_logits(layer, x, tokens); + let logit_scale = cpu_logits.iter().fold(1.0f32, |m, v| m.max(v.abs())); + let logit_error = device + .logits + .iter() + .zip(&cpu_logits) + .fold(0.0f32, |m, (d, c)| m.max((d - c).abs())); + assert!( + logit_error <= 1e-4 * logit_scale, + "{label}: router logits differ by {logit_error}" + ); + + let plan = MoeBatchPlan::qwen3_coder_a3b(&device.logits, tokens).unwrap(); + let ids: Vec = device.expert_ids.iter().map(|&id| id as u32).collect(); + assert_eq!( + ids, plan.topk_experts, + "{label}: device top-8 vs MoeBatchPlan on device logits" + ); + assert_eq!(device.offsets, plan.expert_offsets, "{label}: offsets"); + assert_eq!( + device.order, plan.grouped_to_assignment, + "{label}: grouped order" + ); + + let expected = reference_moe_forward_with(layer, x, &plan, oracle); + let stats = parity_stats(&device.output, &expected); + eprintln!( + "{label} ({oracle:?} oracle): tokens={tokens} cosine={:.8} p95_rel={:.5} max_abs={:.6} max_abs_expected={:.4} router_logit_err={logit_error:.2e}", + stats.cosine, stats.p95_rel, stats.max_abs, stats.max_abs_expected + ); + assert_eq!(stats.non_finite, 0, "{label}: non-finite outputs"); + stats +} + +// Against an oracle that quantizes activations exactly as the device does, the +// only differences left are FP32 accumulation order and rare one-ULP rounding +// flips at E4M3 ties, so any indexing, scaling or routing bug shows up here. +const EMULATED_COSINE_MIN: f64 = 0.99999; +const EMULATED_MAX_ABS_FRACTION: f32 = 0.01; + +#[test] +fn synthetic_layer_with_distinct_experts_matches_fp32_oracle() { + let Some((_gpu, kernels)) = gpu() else { return }; + let layer = synthetic_layer(11, 256, 256); + for (tokens, seed) in [(1usize, 1u64), (37, 2), (130, 3)] { + let (bits, x) = seeded_bf16_input(seed, tokens, layer.hidden, 1.0); + let stats = check_layer( + kernels, + &layer, + &bits, + &x, + tokens, + OracleActivations::Fp8Block128, + "synthetic", + ); + assert!( + stats.cosine >= EMULATED_COSINE_MIN, + "cosine {}", + stats.cosine + ); + assert!( + stats.max_abs <= EMULATED_MAX_ABS_FRACTION * stats.max_abs_expected, + "max_abs {}", + stats.max_abs + ); + // Reported, not gated: random-sign synthetic weights amplify E4M3 rounding. + check_layer( + kernels, + &layer, + &bits, + &x, + tokens, + OracleActivations::Fp32, + "synthetic", + ); + } +} + +#[test] +fn layer_rejects_non_finite_input_without_output() { + let Some((_gpu, kernels)) = gpu() else { return }; + let layer = synthetic_layer(5, 128, 128); + let (mut bits, _) = seeded_bf16_input(9, 4, layer.hidden, 1.0); + bits[2 * layer.hidden + 5] = f32_to_bf16(f32::NAN); + assert_eq!( + kernels.forward(&layer, &bits, 4).unwrap_err(), + Qwen3MoeError::Kernel(2) + ); +} + +#[test] +fn e4m3_test_generator_stays_finite_and_bounded() { + let mut rng = Rng(3); + for _ in 0..10_000 { + let value = fp8_e4m3fn_to_f32(rng.fp8()); + assert!(value.is_finite() && value.abs() <= 2.0); + } + assert_eq!(bf16_to_f32(f32_to_bf16(0.5)), 0.5); +} + +/// Official checkpoint tolerances against the FP32-activation oracle, frozen from +/// layers 0, 1, 23, 24 and 47 with seeds 1, 2 and 3 (16 tokens each). Worst observed: +/// cosine 0.99910 (layer 23), p95 0.0173 (layer 47), max_abs 3.2% of max|expected| +/// (layer 24). Limits allow about 1.5x to 2x that error. See mojo/qwen3_moe/README.md. +const REAL_COSINE_MIN: f64 = 0.9985; +const REAL_P95_REL_MAX: f32 = 0.025; +const REAL_MAX_ABS_FRACTION: f32 = 0.05; + +#[test] +fn official_checkpoint_layers_match_fp32_oracle() { + let Some(dir) = std::env::var_os("AIEN_QWEN3_FP8_CHECKPOINT").map(PathBuf::from) else { + eprintln!("skipping official checkpoint parity: AIEN_QWEN3_FP8_CHECKPOINT not set"); + return; + }; + let Some((_gpu, kernels)) = gpu() else { return }; + let layers: Vec = std::env::var("AIEN_QWEN3_LAYERS") + .unwrap_or_else(|_| "0,1,23,24,47".to_string()) + .split(',') + .map(|l| { + l.trim() + .parse() + .expect("AIEN_QWEN3_LAYERS must be integers") + }) + .collect(); + let seeds: Vec = std::env::var("AIEN_QWEN3_SEEDS") + .unwrap_or_else(|_| "1".to_string()) + .split(',') + .map(|s| s.trim().parse().expect("AIEN_QWEN3_SEEDS must be integers")) + .collect(); + let tokens = 16; + // Measure every case before asserting so one run reports the whole corpus. + let mut failures = Vec::new(); + for layer_index in layers { + let layer = load_qwen3_fp8_moe_layer(&dir, layer_index).unwrap(); + for &seed in &seeds { + let (bits, x) = + seeded_bf16_input(1000 * seed + layer_index as u64, tokens, layer.hidden, 0.25); + let label = format!( + "layer {layer_index} seed {seed} capsule {}", + &layer.capsule.capsule_digest[..12] + ); + let emulated = check_layer( + kernels, + &layer, + &bits, + &x, + tokens, + OracleActivations::Fp8Block128, + &label, + ); + if emulated.cosine < EMULATED_COSINE_MIN + || emulated.max_abs > EMULATED_MAX_ABS_FRACTION * emulated.max_abs_expected + { + failures.push(format!("{label}: emulated {emulated:?}")); + } + let stats = check_layer( + kernels, + &layer, + &bits, + &x, + tokens, + OracleActivations::Fp32, + &label, + ); + if stats.cosine < REAL_COSINE_MIN + || stats.p95_rel > REAL_P95_REL_MAX + || stats.max_abs > REAL_MAX_ABS_FRACTION * stats.max_abs_expected + { + failures.push(format!("{label}: fp32 {stats:?}")); + } + } + } + assert!( + failures.is_empty(), + "outside tolerance:\n{}", + failures.join("\n") + ); +}