diff --git a/crates/aien-inference-abi/examples/qwen3_attn_kernel_check.rs b/crates/aien-inference-abi/examples/qwen3_attn_kernel_check.rs new file mode 100644 index 00000000..0878bb59 --- /dev/null +++ b/crates/aien-inference-abi/examples/qwen3_attn_kernel_check.rs @@ -0,0 +1,86 @@ +//! Attention kernel in isolation: GPU kv_append + attn vs the f64 CPU +//! reference on synthetic Q/K/V, at many sequence lengths. No weights, no MoE, +//! so routing sensitivity cannot mask or mimic a kernel error. +//! +//! Usage: qwen3_attn_kernel_check +//! PASS bar per case: cosine >= 0.999999 and max_abs <= 1e-4. + +use aien_inference_abi::qwen3_coder::{ + QWEN3_CODER_HEAD_DIM, QWEN3_CODER_KV_DIM, QWEN3_CODER_KV_HEADS, QWEN3_CODER_Q_DIM, + QWEN3_CODER_Q_HEADS, +}; +use aien_inference_abi::qwen3_moe::parity_stats; +use aien_inference_abi::qwen3_serve::{QwenServeLib, QwenServeModel}; +use aien_inference_abi::tensor::scaled_dot_product_attention_single; + +const MAX_POS: usize = 512; +const SEQ_LENS: [usize; 8] = [1, 2, 3, 7, 64, 128, 129, 512]; + +/// Deterministic xorshift in [-1, 1). +struct Rng(u64); +impl Rng { + fn next(&mut self) -> f32 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + (self.0 >> 40) as f32 / (1u64 << 23) as f32 - 1.0 + } + fn vec(&mut self, n: usize, scale: f32) -> Vec { + (0..n).map(|_| self.next() * scale).collect() + } +} + +fn main() { + let lib = QwenServeLib::load(&QwenServeLib::default_path()).expect("load serve .so"); + let serve = QwenServeModel::create(lib).expect("model_create"); + + let mut all_pass = true; + // (label, q/k magnitude): moderate scores, then peaked softmax. + for (case, (label, mag)) in [("moderate", 1.0f32), ("peaked", 4.0f32)] + .iter() + .enumerate() + { + let layer = case; // separate layer per case: fresh resident KV + let mut rng = Rng(0x9E37_79B9_7F4A_7C15 ^ case as u64); + let keys: Vec> = (0..MAX_POS) + .map(|_| rng.vec(QWEN3_CODER_KV_DIM, *mag)) + .collect(); + let values: Vec> = (0..MAX_POS) + .map(|_| rng.vec(QWEN3_CODER_KV_DIM, 1.0)) + .collect(); + for pos in 0..MAX_POS { + serve + .kv_append(layer, &keys[pos], &values[pos], pos) + .expect("kv_append"); + } + let q = rng.vec(QWEN3_CODER_Q_DIM, *mag); + + for &seq in SEQ_LENS.iter() { + let mut gpu = vec![0.0f32; QWEN3_CODER_Q_DIM]; + serve.attn(layer, &q, &mut gpu, seq).expect("attn"); + let mut cpu = vec![0.0f32; QWEN3_CODER_Q_DIM]; + scaled_dot_product_attention_single( + &q, + &keys[..seq], + &values[..seq], + QWEN3_CODER_Q_HEADS, + QWEN3_CODER_KV_HEADS, + QWEN3_CODER_HEAD_DIM, + &mut cpu, + ); + let s = parity_stats(&gpu, &cpu); + let pass = s.cosine >= 0.999999 && s.max_abs <= 1e-4; + all_pass &= pass; + println!( + "{label:>8} seq={seq:>4} cosine={:.9} max_abs={:.3e} {}", + s.cosine, + s.max_abs, + if pass { "ok" } else { "FAIL" } + ); + } + } + println!("{}", if all_pass { "PASS" } else { "FAIL" }); + if !all_pass { + std::process::exit(1); + } +} diff --git a/crates/aien-inference-abi/examples/qwen3_coder_chat.rs b/crates/aien-inference-abi/examples/qwen3_coder_chat.rs new file mode 100644 index 00000000..e2eb7a3d --- /dev/null +++ b/crates/aien-inference-abi/examples/qwen3_coder_chat.rs @@ -0,0 +1,160 @@ +//! Native Qwen3-Coder-30B-A3B chat: full 48-layer forward, no MAX, no Python. +//! +//! Usage: +//! qwen3_coder_chat [checkpoint_dir] [--max-new 256] [--device serve] +//! +//! Lines on stdin are wrapped in the Qwen3 ChatML template and decoded +//! greedily. Default is CPU; `--device serve` routes every GEMM through the +//! resident-weight serve library. Type `quit` to exit. + +use std::io::{self, BufRead, Write}; +use std::path::PathBuf; +use std::time::Instant; + +use aien_inference_abi::qwen3_coder::{ + compute_logits, forward_token, load_qwen3_coder, Qwen3CoderState, Qwen3CoderWeights, +}; +use aien_inference_abi::qwen3_serve::{forward_token_serve, QwenServeLib, QwenServeModel}; +use aien_inference_abi::tensor::sample_argmax; + +fn main() { + let mut args = std::env::args().skip(1); + let mut checkpoint: Option = None; + let mut max_new: usize = 256; + let mut device = false; + while let Some(arg) = args.next() { + if arg == "--max-new" { + max_new = args + .next() + .expect("--max-new needs a value") + .parse() + .expect("--max-new must be a number"); + } else if arg == "--device" { + let kind = args.next().expect("--device needs a value"); + if kind == "serve" { + device = true; + } else { + eprintln!("unknown --device {kind}"); + std::process::exit(2); + } + } else if checkpoint.is_none() { + checkpoint = Some(PathBuf::from(arg)); + } else { + eprintln!("unexpected argument: {arg}"); + std::process::exit(2); + } + } + let checkpoint = checkpoint.unwrap_or_else(|| { + PathBuf::from("/home/drakestapleton/.cache/huggingface/hub/models--Qwen--Qwen3-Coder-30B-A3B-Instruct-FP8/snapshots/dcaee4d4dfc5ee71ad501f01f530e5652438fde0") + }); + + let t0 = Instant::now(); + let weights = load_qwen3_coder(&checkpoint).expect("load Qwen3-Coder weights"); + eprintln!("weights loaded in {:.1}s", t0.elapsed().as_secs_f32()); + + let serve = if device { + let t0 = Instant::now(); + let lib = QwenServeLib::load(&QwenServeLib::default_path()).expect("load serve .so"); + let serve = QwenServeModel::upload_all(lib, &weights, &checkpoint).expect("upload weights"); + eprintln!("device upload in {:.1}s", t0.elapsed().as_secs_f32()); + Some(serve) + } else { + None + }; + + let tokenizer = tokenizers::Tokenizer::from_file(checkpoint.join("tokenizer.json")) + .expect("load tokenizer.json"); + let stop_ids: Vec = ["<|im_end|>", "<|endoftext|>"] + .iter() + .filter_map(|s| { + tokenizer + .encode(*s, false) + .ok() + .and_then(|e| e.get_ids().first().copied()) + }) + .collect(); + eprintln!("stop ids: {stop_ids:?}"); + + let stdin = io::stdin(); + print!("eien> "); + io::stdout().flush().unwrap(); + for line in stdin.lock().lines() { + let line = line.expect("read stdin line"); + let trimmed = line.trim(); + if trimmed.eq_ignore_ascii_case("quit") || trimmed.eq_ignore_ascii_case("exit") { + break; + } + if trimmed.is_empty() { + print!("eien> "); + io::stdout().flush().unwrap(); + continue; + } + let prompt = format!("<|im_start|>user\n{trimmed}<|im_end|>\n<|im_start|>assistant\n"); + let prompt_ids: Vec = tokenizer + .encode(prompt, false) + .expect("encode prompt") + .get_ids() + .to_vec(); + + let mut state = Qwen3CoderState::new(); + let forward = |weights: &Qwen3CoderWeights, + serve: &Option, + state: &mut Qwen3CoderState, + tok: u32, + pos: usize| + -> Vec { + match serve { + Some(s) => forward_token_serve(weights, s, tok, pos, state, None, false) + .expect("device forward"), + None => forward_token(weights, tok, pos, state), + } + }; + let logits = + |weights: &Qwen3CoderWeights, serve: &Option, hidden: &[f32]| -> u32 { + let v = match serve { + Some(s) => { + let mut out = vec![0.0f32; 151936]; + s.logits(hidden, &mut out).expect("device logits"); + out + } + None => compute_logits(weights, hidden), + }; + sample_argmax(&v).0 + }; + let t_pre = Instant::now(); + for (pos, &tok) in prompt_ids.iter().enumerate() { + forward(&weights, &serve, &mut state, tok, pos); + } + let prefill_s = t_pre.elapsed().as_secs_f32(); + let prompt_len = prompt_ids.len(); + let mut prev = *prompt_ids.last().unwrap(); + let mut generated: Vec = Vec::new(); + let t_dec = Instant::now(); + let mut printed_len = 0usize; + for step in 0..max_new { + let hidden = forward(&weights, &serve, &mut state, prev, prompt_len + step); + let next = logits(&weights, &serve, &hidden); + if stop_ids.contains(&next) { + break; + } + generated.push(next); + prev = next; + let text = tokenizer.decode(&generated, true).unwrap_or_default(); + if text.len() > printed_len { + print!("{}", &text[printed_len..]); + io::stdout().flush().unwrap(); + printed_len = text.len(); + } + } + let decode_s = t_dec.elapsed().as_secs_f32(); + println!(); + eprintln!( + "[prefill {:.1} tok/s | decode {:.2} tok/s | {} tokens]", + prompt_ids.len() as f32 / prefill_s.max(1e-6), + generated.len() as f32 / decode_s.max(1e-6), + generated.len() + ); + print!("eien> "); + io::stdout().flush().unwrap(); + } +} diff --git a/crates/aien-inference-abi/examples/qwen3_coder_device_check.rs b/crates/aien-inference-abi/examples/qwen3_coder_device_check.rs new file mode 100644 index 00000000..8c13293b --- /dev/null +++ b/crates/aien-inference-abi/examples/qwen3_coder_device_check.rs @@ -0,0 +1,65 @@ +//! Parity + timing: GPU MoE device forward vs CPU reference through one +//! real layer. Usage: qwen3_coder_device_check [checkpoint_dir] [layer] +//! +//! PASS bar: cosine(device, cpu_fp32) >= 0.999 and per-call device p50 faster +//! than the CPU reference on the same input. + +use std::time::Instant; + +use aien_inference_abi::moe_plan::MoeBatchPlan; +use aien_inference_abi::qwen3_coder::load_qwen3_coder; +use aien_inference_abi::qwen3_moe::{ + parity_stats, reference_moe_forward, reference_router_logits, Qwen3MoeKernels, +}; + +fn main() { + let mut args = std::env::args().skip(1); + let checkpoint = args.next().map(std::path::PathBuf::from).unwrap_or_else(|| { + "/home/drakestapleton/.cache/huggingface/hub/models--Qwen--Qwen3-Coder-30B-A3B-Instruct-FP8/snapshots/dcaee4d4dfc5ee71ad501f01f530e5652438fde0".into() + }); + let layer: usize = args.next().map(|s| s.parse().unwrap()).unwrap_or(23); + + let t0 = Instant::now(); + let weights = load_qwen3_coder(&checkpoint).expect("load weights"); + eprintln!("load: {:.1}s", t0.elapsed().as_secs_f32()); + let kernels = Qwen3MoeKernels::load(&Qwen3MoeKernels::default_path()).expect("load .so"); + let moe = &weights.moes[layer]; + + // Deterministic pseudo-activation: sin-based, scaled like a post-norm row. + let h = 2048usize; + let post: Vec = (0..h) + .map(|i| (i as f32 * 0.37).sin() * 1.7 + (i as f32 * 0.11).cos() * 0.6) + .collect(); + + let t_cpu = Instant::now(); + let router = reference_router_logits(moe, &post, 1); + let plan = MoeBatchPlan::qwen3_coder_a3b(&router, 1).unwrap(); + let cpu = reference_moe_forward(moe, &post, &plan); + let cpu_ms = t_cpu.elapsed().as_secs_f64() * 1000.0; + + let post_bf16: Vec = post + .iter() + .map(|&v| aien_inference_abi::qwen3_moe::f32_to_bf16(v)) + .collect(); + // Warmup, then timed repeats. + kernels.forward(moe, &post_bf16, 1).expect("warmup"); + let t_dev = Instant::now(); + let mut dev = None; + for _ in 0..10 { + dev = Some(kernels.forward(moe, &post_bf16, 1).expect("device forward")); + } + let dev_ms = t_dev.elapsed().as_secs_f64() * 100.0; + let dev = dev.unwrap(); + + let stats = parity_stats(&dev.output, &cpu); + println!( + "layer {layer}: cosine={:.8} max_abs={:.6}", + stats.cosine, stats.max_abs + ); + println!("cpu {cpu_ms:.1}ms/call vs device {dev_ms:.2}ms/call"); + let pass = stats.cosine >= 0.999 && dev_ms < cpu_ms; + println!("{}", if pass { "PASS" } else { "FAIL" }); + if !pass { + std::process::exit(1); + } +} diff --git a/crates/aien-inference-abi/examples/qwen3_noise_floor.rs b/crates/aien-inference-abi/examples/qwen3_noise_floor.rs new file mode 100644 index 00000000..65b27ac1 --- /dev/null +++ b/crates/aien-inference-abi/examples/qwen3_noise_floor.rs @@ -0,0 +1,278 @@ +//! C1 SPEC 5.1 / 5.3 noise-floor calibration for Qwen3-Coder-30B-A3B-FP8. +//! +//! Measures correct-vs-correct logit differences across frozen seeded prompts +//! and positions, and the same metrics for candidate (device vs CPU) pairs. +//! Emits a JSON receipt with per-pair distributions; thresholds are NOT +//! chosen here. Freezing them is a versioned SPEC amendment (Section 14). +//! +//! Usage: qwen3_noise_floor [checkpoint_dir] [prompts] [positions] +//! +//! Pairs (reference first): +//! floor.rerun gemm path vs itself, fresh state (determinism) +//! floor.attention gemm path (f64 CPU attn) vs full device (f32 GPU attn) +//! floor.moe_bf16 CPU f32 MoE I/O vs CPU BF16 MoE I/O +//! cand.dev_cpu CPU f32 reference vs gemm path +//! cand.dev_cpu16 CPU BF16-I/O reference vs gemm path +//! Metrics per compared step (SPEC 5.1): max_abs, max_rel (eps 1e-3), KL(ref||test), +//! top-1 agreement with reference top-2 margin, plus cosine for continuity. +//! +//! Not the SPEC 5.4 Hugging Face reference: this calibrates AIEN paths only. + +use std::collections::BTreeMap; +use std::path::PathBuf; +use std::time::Instant; + +use aien_inference_abi::qwen3_coder::{ + compute_logits, forward_token_with_moe, MoeBackend, Qwen3CoderState, QWEN3_CODER_VOCAB, +}; +use aien_inference_abi::qwen3_moe::parity_stats; +use aien_inference_abi::qwen3_serve::{forward_token_serve, QwenServeLib, QwenServeModel}; +use aien_inference_abi::tensor::sample_argmax; + +const SNAPSHOT: &str = ".cache/huggingface/hub/models--Qwen--Qwen3-Coder-30B-A3B-Instruct-FP8/snapshots/dcaee4d4dfc5ee71ad501f01f530e5652438fde0"; +const REL_EPS: f64 = 1.0e-3; // acceptance.toml relative_error_epsilon +const PROMPT_LEN: usize = 6; +const BASE_SEED: u64 = 0xC1_0000_0000_0053; // frozen: campaign C1, Section 5.3 + +#[derive(Default)] +struct Series { + max_abs: Vec, + max_rel: Vec, + kl: Vec, + cosine: Vec, + top1_disagree: Vec<(usize, usize, f64)>, // (prompt, pos, reference top-2 margin) + steps: usize, +} + +fn softmax_f64(l: &[f32]) -> Vec { + let m = l.iter().fold(f32::NEG_INFINITY, |a, &b| a.max(b)) as f64; + let e: Vec = l.iter().map(|&x| (x as f64 - m).exp()).collect(); + let s: f64 = e.iter().sum(); + e.into_iter().map(|x| x / s).collect() +} + +fn top2_margin(l: &[f32]) -> f64 { + let (mut a, mut b) = (f32::NEG_INFINITY, f32::NEG_INFINITY); + for &x in l { + if x > a { + b = a; + a = x; + } else if x > b { + b = x; + } + } + (a - b) as f64 +} + +impl Series { + fn push(&mut self, reference: &[f32], test: &[f32], prompt: usize, pos: usize) { + let (mut max_abs, mut max_rel) = (0.0f64, 0.0f64); + for (&r, &t) in reference.iter().zip(test) { + let d = (r as f64 - t as f64).abs(); + max_abs = max_abs.max(d); + max_rel = max_rel.max(d / (r as f64).abs().max(REL_EPS)); + } + let (p, q) = (softmax_f64(reference), softmax_f64(test)); + let kl: f64 = p + .iter() + .zip(&q) + .filter(|(&pi, _)| pi > 0.0) + .map(|(&pi, &qi)| pi * (pi / qi.max(f64::MIN_POSITIVE)).ln()) + .sum(); + self.max_abs.push(max_abs); + self.max_rel.push(max_rel); + self.kl.push(kl); + self.cosine.push(parity_stats(test, reference).cosine); + if sample_argmax(reference).0 != sample_argmax(test).0 { + self.top1_disagree + .push((prompt, pos, top2_margin(reference))); + } + self.steps += 1; + } +} + +/// Nearest-rank quantile over a sorted copy (p = 0.0 min, 1.0 max). +fn q(v: &[f64], p: f64) -> f64 { + let mut s = v.to_vec(); + s.sort_by(f64::total_cmp); + s[((s.len() - 1) as f64 * p).round() as usize] +} + +fn summary(s: &Series) -> serde_json::Value { + let hi = + |v: &[f64]| serde_json::json!({"worst": q(v, 1.0), "p99": q(v, 0.99), "p50": q(v, 0.5)}); + let lo = + |v: &[f64]| serde_json::json!({"worst": q(v, 0.0), "p01": q(v, 0.01), "p50": q(v, 0.5)}); + serde_json::json!({ + "steps": s.steps, + "max_abs": hi(&s.max_abs), + "max_rel": hi(&s.max_rel), + "kl": hi(&s.kl), + "cosine": lo(&s.cosine), + "top1_disagreements": s.top1_disagree.iter() + .map(|(p, t, m)| serde_json::json!({"prompt": p, "pos": t, "ref_top2_margin": m})) + .collect::>(), + }) +} + +fn device_logits(serve: &QwenServeModel, hidden: &[f32]) -> Vec { + let mut out = vec![0.0f32; QWEN3_CODER_VOCAB]; + serve.logits(hidden, &mut out).expect("device logits"); + out +} + +fn prompt(seed: u64) -> Vec { + let mut x = seed | 1; + (0..PROMPT_LEN) + .map(|_| { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + // Keep to the regular-token range (below special tokens). + (x % 151_000) as u32 + }) + .collect() +} + +fn sha256_file(path: &std::path::Path) -> String { + use sha2::{Digest, Sha256}; + std::fs::read(path) + .map(|b| format!("{:x}", Sha256::digest(&b))) + .unwrap_or_else(|e| format!("unreadable: {e}")) +} + +fn main() { + let mut args = std::env::args().skip(1); + let out_path = PathBuf::from( + args.next() + .expect("usage: qwen3_noise_floor ..."), + ); + let checkpoint = args + .next() + .map(PathBuf::from) + .or_else(|| std::env::var_os("AIEN_QWEN3_CODER_CKPT").map(PathBuf::from)) + .unwrap_or_else(|| PathBuf::from(std::env::var("HOME").expect("HOME")).join(SNAPSHOT)); + let n_prompts: usize = args + .next() + .map(|s| s.parse().expect("prompts")) + .unwrap_or(6); + let positions: usize = args + .next() + .map(|s| s.parse().expect("positions")) + .unwrap_or(24); + assert!(positions > PROMPT_LEN); + + let started = Instant::now(); + let weights = + aien_inference_abi::qwen3_coder::load_qwen3_coder(&checkpoint).expect("load weights"); + let lib_path = QwenServeLib::default_path(); + let lib = QwenServeLib::load(&lib_path).expect("load serve .so"); + let serve = QwenServeModel::upload_all(lib, &weights, &checkpoint).expect("upload all"); + eprintln!("load+upload: {:.1}s", started.elapsed().as_secs_f32()); + + let names = [ + "floor.rerun", + "floor.attention", + "floor.moe_bf16", + "cand.dev_cpu", + "cand.dev_cpu16", + ]; + let mut series: BTreeMap<&str, Series> = + names.iter().map(|n| (*n, Series::default())).collect(); + + for p in 0..n_prompts { + let tokens = prompt(BASE_SEED.wrapping_add(p as u64)); + let mut cpu = Qwen3CoderState::new(); + let mut cpu16 = Qwen3CoderState::new(); + let mut gemm = Qwen3CoderState::new(); + let mut gemm2 = Qwen3CoderState::new(); + let mut full = Qwen3CoderState::new(); + let mut token = tokens[0]; + for pos in 0..positions { + let h_cpu = + forward_token_with_moe(&weights, token, pos, &mut cpu, &mut MoeBackend::Cpu); + let h_cpu16 = forward_token_with_moe( + &weights, + token, + pos, + &mut cpu16, + &mut MoeBackend::CpuBf16Io, + ); + let h_gemm = forward_token_serve(&weights, &serve, token, pos, &mut gemm, None, false) + .expect("gemm"); + let h_gemm2 = + forward_token_serve(&weights, &serve, token, pos, &mut gemm2, None, false) + .expect("gemm rerun"); + let h_full = forward_token_serve(&weights, &serve, token, pos, &mut full, None, true) + .expect("full"); + + let l_cpu = compute_logits(&weights, &h_cpu); + let l_cpu16 = compute_logits(&weights, &h_cpu16); + let l_gemm = device_logits(&serve, &h_gemm); + let l_gemm2 = device_logits(&serve, &h_gemm2); + let l_full = device_logits(&serve, &h_full); + + series + .get_mut("floor.rerun") + .unwrap() + .push(&l_gemm, &l_gemm2, p, pos); + series + .get_mut("floor.attention") + .unwrap() + .push(&l_gemm, &l_full, p, pos); + series + .get_mut("floor.moe_bf16") + .unwrap() + .push(&l_cpu, &l_cpu16, p, pos); + series + .get_mut("cand.dev_cpu") + .unwrap() + .push(&l_cpu, &l_gemm, p, pos); + series + .get_mut("cand.dev_cpu16") + .unwrap() + .push(&l_cpu16, &l_gemm, p, pos); + + // Teacher-force on the CPU f32 reference's greedy token. + token = tokens + .get(pos + 1) + .copied() + .unwrap_or(sample_argmax(&l_cpu).0); + } + eprintln!( + "prompt {}/{} done at {:.0}s", + p + 1, + n_prompts, + started.elapsed().as_secs_f32() + ); + } + + let git_rev = std::process::Command::new("git") + .args(["rev-parse", "HEAD"]) + .output() + .ok() + .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string()) + .unwrap_or_default(); + let receipt = serde_json::json!({ + "schema": "aien.c1.noise_floor.v1", + "model": "qwen3_coder_30b_a3b_fp8", + "spec": {"campaign": "c1", "spec_version": 1, "sections": ["5.1", "5.3"]}, + "not_hf_reference": true, + "git_rev": git_rev, + "serve_lib": {"path": lib_path.display().to_string(), "sha256": sha256_file(&lib_path)}, + "checkpoint": checkpoint.display().to_string(), + "prompts": n_prompts, "positions": positions, "prompt_len": PROMPT_LEN, + "base_seed": format!("{BASE_SEED:#x}"), + "relative_error_epsilon": REL_EPS, + "teacher_forcing": "cpu_f32_greedy", + "wall_seconds": started.elapsed().as_secs_f64(), + "pairs": series.iter().map(|(k, s)| (k.to_string(), summary(s))).collect::>(), + }); + std::fs::write(&out_path, serde_json::to_string_pretty(&receipt).unwrap()) + .expect("write receipt"); + println!( + "{}", + serde_json::to_string_pretty(&receipt["pairs"]).unwrap() + ); + println!("receipt: {}", out_path.display()); +} diff --git a/crates/aien-inference-abi/examples/qwen3_parity_check.rs b/crates/aien-inference-abi/examples/qwen3_parity_check.rs new file mode 100644 index 00000000..373017ce --- /dev/null +++ b/crates/aien-inference-abi/examples/qwen3_parity_check.rs @@ -0,0 +1,124 @@ +//! Multi-position logits parity: CPU reference vs device GEMM path vs full +//! device path (GPU attention), teacher-forced on the CPU's greedy tokens so +//! all three see identical inputs at every position. +//! +//! Usage: qwen3_parity_check [checkpoint_dir] [positions] +//! checkpoint_dir: else $AIEN_QWEN3_CODER_CKPT, else the HF cache under $HOME. +//! positions: default 16. +//! +//! PASS bars, at every position: +//! device logits vs CPU: cosine >= 0.999 and identical argmax. +//! full-device vs GEMM path (attention isolation): cosine >= 0.99999. + +use std::path::PathBuf; +use std::time::Instant; + +use aien_inference_abi::qwen3_coder::{ + compute_logits, forward_token, forward_token_with_moe, MoeBackend, Qwen3CoderState, + QWEN3_CODER_VOCAB, +}; +use aien_inference_abi::qwen3_moe::parity_stats; +use aien_inference_abi::qwen3_serve::{forward_token_serve, QwenServeLib, QwenServeModel}; +use aien_inference_abi::tensor::sample_argmax; + +const SNAPSHOT: &str = ".cache/huggingface/hub/models--Qwen--Qwen3-Coder-30B-A3B-Instruct-FP8/snapshots/dcaee4d4dfc5ee71ad501f01f530e5652438fde0"; + +/// "def fibonacci(n):" style code prefix; any fixed ids work for parity. +const PROMPT: [u32; 6] = [750, 75698, 1445, 982, 262, 421]; + +fn checkpoint_dir(arg: Option) -> PathBuf { + arg.map(PathBuf::from) + .or_else(|| std::env::var_os("AIEN_QWEN3_CODER_CKPT").map(PathBuf::from)) + .unwrap_or_else(|| { + PathBuf::from(std::env::var("HOME").expect("HOME or a checkpoint argument")) + .join(SNAPSHOT) + }) +} + +fn device_logits(serve: &QwenServeModel, hidden: &[f32]) -> Vec { + let mut out = vec![0.0f32; QWEN3_CODER_VOCAB]; + serve.logits(hidden, &mut out).expect("device logits"); + out +} + +fn main() { + let mut args = std::env::args().skip(1); + let checkpoint = checkpoint_dir(args.next()); + let positions: usize = args + .next() + .map(|s| s.parse().expect("positions")) + .unwrap_or(16); + assert!(positions >= PROMPT.len(), "positions must cover the prompt"); + + let t0 = Instant::now(); + let weights = + aien_inference_abi::qwen3_coder::load_qwen3_coder(&checkpoint).expect("load weights"); + eprintln!("cpu load: {:.1}s", t0.elapsed().as_secs_f32()); + let lib = QwenServeLib::load(&QwenServeLib::default_path()).expect("load serve .so"); + let serve = QwenServeModel::upload_all(lib, &weights, &checkpoint).expect("upload all"); + + let mut cpu_state = Qwen3CoderState::new(); + let mut gemm_state = Qwen3CoderState::new(); + let mut full_state = Qwen3CoderState::new(); + let mut cpu16_state = Qwen3CoderState::new(); + + let mut token = PROMPT[0]; + let (mut min_cos, mut min_iso, mut argmax_misses) = (1.0f64, 1.0f64, 0usize); + let mut min_cos16 = 1.0f64; + println!( + "pos token cos(dev,cpu) cos(full,gemm) cos(gemm,cpu16) cpu_top2_margin argmax cpu/gemm/full" + ); + for pos in 0..positions { + let cpu_h = forward_token(&weights, token, pos, &mut cpu_state); + // Diagnostic: CPU reference with the device's BF16 MoE I/O rounding. + let cpu16_h = forward_token_with_moe( + &weights, + token, + pos, + &mut cpu16_state, + &mut MoeBackend::CpuBf16Io, + ); + let gemm_h = + forward_token_serve(&weights, &serve, token, pos, &mut gemm_state, None, false) + .expect("gemm-path forward"); + let full_h = forward_token_serve(&weights, &serve, token, pos, &mut full_state, None, true) + .expect("full-device forward"); + + let cpu_l = compute_logits(&weights, &cpu_h); + let gemm_l = device_logits(&serve, &gemm_h); + let full_l = device_logits(&serve, &full_h); + + let cos = parity_stats(&gemm_l, &cpu_l) + .cosine + .min(parity_stats(&full_l, &cpu_l).cosine); + let iso = parity_stats(&full_l, &gemm_l).cosine; + let (a_cpu, _) = sample_argmax(&cpu_l); + let (a_gemm, _) = sample_argmax(&gemm_l); + let (a_full, _) = sample_argmax(&full_l); + if a_gemm != a_cpu || a_full != a_cpu { + argmax_misses += 1; + } + min_cos = min_cos.min(cos); + min_iso = min_iso.min(iso); + let cos16 = parity_stats(&gemm_l, &compute_logits(&weights, &cpu16_h)).cosine; + min_cos16 = min_cos16.min(cos16); + let mut sorted = cpu_l.clone(); + sorted.sort_unstable_by(|a, b| b.total_cmp(a)); + let margin = sorted[0] - sorted[1]; + println!( + "{pos:>3} {token:>6} {cos:.8} {iso:.8} {cos16:.8} {margin:>8.4} {a_cpu}/{a_gemm}/{a_full}" + ); + + // Teacher-force: prompt first, then the CPU's greedy choice. + token = PROMPT.get(pos + 1).copied().unwrap_or(a_cpu); + } + + let pass = min_cos >= 0.999 && argmax_misses == 0 && min_iso >= 0.99999; + println!( + "positions={positions} min_cos(dev,cpu)={min_cos:.8} min_cos(full,gemm)={min_iso:.8} min_cos(gemm,cpu16)={min_cos16:.8} argmax_misses={argmax_misses}" + ); + println!("{}", if pass { "PASS" } else { "FAIL" }); + if !pass { + std::process::exit(1); + } +} diff --git a/crates/aien-inference-abi/examples/qwen3_serve_check.rs b/crates/aien-inference-abi/examples/qwen3_serve_check.rs new file mode 100644 index 00000000..a1363ecd --- /dev/null +++ b/crates/aien-inference-abi/examples/qwen3_serve_check.rs @@ -0,0 +1,97 @@ +//! Serve-library validation: uploads all 30GB once, then compares one full +//! device token against the CPU reference and times both. +//! Usage: qwen3_serve_check [checkpoint_dir] +//! +//! PASS bar: cosine(device_hidden, cpu_hidden) >= 0.999. + +use std::time::Instant; + +use aien_inference_abi::qwen3_coder::{forward_token, Qwen3CoderState}; +use aien_inference_abi::qwen3_moe::parity_stats; +use aien_inference_abi::qwen3_serve::{forward_token_serve, QwenServeLib, QwenServeModel}; + +fn main() { + let checkpoint = std::env::args().nth(1).map(std::path::PathBuf::from).unwrap_or_else(|| { + "/home/drakestapleton/.cache/huggingface/hub/models--Qwen--Qwen3-Coder-30B-A3B-Instruct-FP8/snapshots/dcaee4d4dfc5ee71ad501f01f530e5652438fde0".into() + }); + + let t0 = Instant::now(); + let weights = + aien_inference_abi::qwen3_coder::load_qwen3_coder(&checkpoint).expect("load weights"); + eprintln!("cpu load: {:.1}s", t0.elapsed().as_secs_f32()); + + let t0 = Instant::now(); + let lib = QwenServeLib::load(&QwenServeLib::default_path()).expect("load serve .so"); + let serve = QwenServeModel::upload_all(lib, &weights, &checkpoint).expect("upload all"); + eprintln!("device upload: {:.1}s", t0.elapsed().as_secs_f32()); + + // One real token through both paths (fresh KV each). + let token = 42u32; + let t_cpu = Instant::now(); + let cpu = forward_token(&weights, token, 0, &mut Qwen3CoderState::new()); + let cpu_ms = t_cpu.elapsed().as_secs_f64() * 1000.0; + + // Warmup, then timed. + forward_token_serve( + &weights, + &serve, + token, + 0, + &mut Qwen3CoderState::new(), + None, + false, + ) + .expect("warmup"); + let t_dev = Instant::now(); + let mut prof = [0.0f64; 5]; + let dev = forward_token_serve( + &weights, + &serve, + token, + 0, + &mut Qwen3CoderState::new(), + Some(&mut prof), + false, + ) + .expect("device forward"); + let dev_ms = t_dev.elapsed().as_secs_f64() * 1000.0; + + let stats = parity_stats(&dev, &cpu); + println!("cosine={:.8} max_abs={:.6}", stats.cosine, stats.max_abs); + println!("cpu {cpu_ms:.0}ms/token vs device {dev_ms:.1}ms/token"); + println!( + "profile ms/token: proj_qkv={:.1} attn_cpu={:.1} proj_o={:.1} moe={:.1} norm_misc={:.1}", + prof[0], prof[1], prof[2], prof[3], prof[4] + ); + let pass = stats.cosine >= 0.999; + println!("{}", if pass { "PASS" } else { "FAIL" }); + if !pass { + std::process::exit(1); + } + + // Full device path including GPU attention, same token, fresh device KV. + let t_full = Instant::now(); + let full = forward_token_serve( + &weights, + &serve, + token, + 0, + &mut Qwen3CoderState::new(), + None, + true, + ) + .expect("full device forward"); + let full_ms = t_full.elapsed().as_secs_f64() * 1000.0; + let stats_full = parity_stats(&full, &cpu); + let stats_iso = parity_stats(&full, &dev); + println!( + "full-device: cosine_vs_cpu={:.8} cosine_vs_gemm_path={:.8} max_abs={:.6}", + stats_full.cosine, stats_iso.cosine, stats_full.max_abs + ); + println!("full-device {full_ms:.1}ms/token"); + let pass_full = stats_full.cosine >= 0.999; + println!("{}", if pass_full { "PASS-FULL" } else { "FAIL-FULL" }); + if !pass_full { + std::process::exit(1); + } +} diff --git a/crates/aien-inference-abi/mojo/qwencoder_serve/build.sh b/crates/aien-inference-abi/mojo/qwencoder_serve/build.sh new file mode 100755 index 00000000..89fc1a27 --- /dev/null +++ b/crates/aien-inference-abi/mojo/qwencoder_serve/build.sh @@ -0,0 +1,15 @@ +#!/usr/bin/env bash +# Builds libqwencoder_serve.so: resident-weight Qwen3-Coder serve library. +# Reuses the proven MoE pipeline read-only via -I (nothing there is modified). +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +MOE_DIR="${SCRIPT_DIR}/../qwen3_moe" +cd "${SCRIPT_DIR}" + +export MODULAR_CACHE_DIR="${MODULAR_CACHE_DIR:-/tmp/modular_cache}" +mkdir -p "${MODULAR_CACHE_DIR}" + +mojo build --emit shared-lib -I . -I "${MOE_DIR}" qwencoder_serve.mojo -o libqwencoder_serve.so +nm -D libqwencoder_serve.so | grep -E ' T qwencoder_' +echo "Built ${SCRIPT_DIR}/libqwencoder_serve.so" diff --git a/crates/aien-inference-abi/mojo/qwencoder_serve/qwencoder_kernels.mojo b/crates/aien-inference-abi/mojo/qwencoder_serve/qwencoder_kernels.mojo new file mode 100644 index 00000000..2a9d62fa --- /dev/null +++ b/crates/aien-inference-abi/mojo/qwencoder_serve/qwencoder_kernels.mojo @@ -0,0 +1,136 @@ +# Qwen3-Coder-30B-A3B reference kernels (Phase B, GB10 foundry seat). +# Arch: 48 layers, hidden 2048, heads 32Q/4KV (GQA group 8), head_dim 128, +# MoE 128 experts top-8 inter 768, vocab 151936, RoPE theta 1e7, +# RMSNorm eps 1e-6, SwiGLU. Attention + experts FP8-block128 (BF16 inv +# scales); norms/embed/lm_head BF16; per-layer q_norm/k_norm [128]. +# Reference math on CPU first (this file); GPU C-ABI later. Every choice +# mirrors crates/aien-inference-abi/src/qwen3_moe.rs decode formulas. + +from std.math import sqrt, exp2 + + +def rmsnorm_row( + x: Span[Float32, _], weight: Span[Float32, _], dst: Span[mut=True, Float32, _], eps: Float32 +): + """dst[i] = x[i] / sqrt(mean(x^2) + eps) * weight[i]. Qwen eps 1e-6.""" + var n = len(x) + var acc: Float32 = 0.0 + for i in range(n): + acc += x[i] * x[i] + var inv = 1.0 / sqrt(acc / Float32(n) + eps) + for i in range(n): + dst[i] = x[i] * inv * weight[i] + + +def rope_rotate_half_pair( + x0: Float32, x1: Float32, cos: Float32, sin: Float32 +) -> Tuple[Float32, Float32]: + """Qwen rotate_half RoPE pair (same pairing as HF LLaMA).""" + return (x0 * cos - x1 * sin, x0 * sin + x1 * cos) + + +def silu(x: Float32) -> Float32: + return x / (1.0 + exp2(-x * 1.44269504089)) + + +def swiglu_row(gate: Span[Float32, _], up: Span[Float32, _], dst: Span[mut=True, Float32, _]): + """SwiGLU: dst = silu(gate) * up. Qwen expert width 768.""" + var n = len(dst) + for i in range(n): + dst[i] = silu(gate[i]) * up[i] + + +def repeat_kv_head( + kv: Span[Float32, _], dst: Span[mut=True, Float32, _], head_dim: Int, groups: Int +): + """GQA: repeat each KV head `groups` times (Qwen-Coder: 4 KV -> 32 Q, groups=8).""" + var kv_heads = len(kv) // head_dim + for h in range(kv_heads): + for g in range(groups): + var dbase = (h * groups + g) * head_dim + var sbase = h * head_dim + for d in range(head_dim): + dst[dbase + d] = kv[sbase + d] + + +def row_gemv( + dst: Span[mut=True, Float32, _], + mat: Span[Float32, _], + vec: Span[Float32, _], + rows: Int, + cols: Int, +): + """Row-major [rows, cols] FP32 GEMV.""" + for r in range(rows): + var acc: Float32 = 0.0 + var base = r * cols + for c in range(cols): + acc += mat[base + c] * vec[c] + dst[r] = acc + + +def bf16_to_f32(bits: UInt16) -> Float32: + """BF16 decode by arithmetic (matches Rust bf16_to_f32 bit-shift).""" + var sign: Float32 = 1.0 + if (bits & UInt16(0x8000)) != UInt16(0): + sign = -1.0 + var exp = Int((bits >> 7) & UInt16(0xFF)) + var mant = Float32(Int(bits & UInt16(0x7F))) + if exp == 0: + return sign * mant / 128.0 * exp2(Float32(-126)) + return sign * (1.0 + mant / 128.0) * exp2(Float32(exp - 127)) + + +def row_gemv_bf16( + dst: Span[mut=True, Float32, _], + mat: Span[UInt16, _], + vec: Span[Float32, _], + rows: Int, + cols: Int, +): + """Row-major BF16 [rows, cols] GEMV for lm_head/vocab and router.""" + for r in range(rows): + var acc: Float32 = 0.0 + var base = r * cols + for c in range(cols): + acc += bf16_to_f32(mat[base + c]) * vec[c] + dst[r] = acc + + +def fp8_e4m3_to_f32(bits: UInt8) -> Float32: + """E4M3FN decode, bias 7, 0x7f/0xff NaN (matches Rust fp8_e4m3fn_to_f32).""" + var sign: Float32 = 1.0 + if (bits & UInt8(0x80)) != UInt8(0): + sign = -1.0 + var exp = Int((bits >> 3) & UInt8(0x0F)) + var mant = Float32(Int(bits & UInt8(0x07))) + if exp == 15: + if mant == 7.0: + var zero: Float32 = 0.0 + return zero / zero + return sign * (1.0 + mant / 8.0) * exp2(Float32(8)) + if exp == 0: + return sign * mant * exp2(Float32(-9)) + return sign * (1.0 + mant / 8.0) * exp2(Float32(exp - 7)) + + +def row_gemv_fp8_block128( + dst: Span[mut=True, Float32, _], + mat: Span[UInt8, _], + scales: Span[UInt16, _], + vec: Span[Float32, _], + rows: Int, + cols: Int, +): + """FP8 [rows, cols] row-major GEMV, cols % 128 == 0. BF16 inv scales laid + out row-major over 128x128 blocks: scales[(r // 128) * (cols // 128) + b]. + Covers Qwen q/k/v/o projections and expert GEMMs.""" + var k_blocks = cols // 128 + for r in range(rows): + var acc: Float32 = 0.0 + var base = r * cols + for b in range(k_blocks): + var scale = bf16_to_f32(scales[(r // 128) * k_blocks + b]) + for k in range(128): + acc += fp8_e4m3_to_f32(mat[base + b * 128 + k]) * vec[b * 128 + k] * scale + dst[r] = acc diff --git a/crates/aien-inference-abi/mojo/qwencoder_serve/qwencoder_serve.mojo b/crates/aien-inference-abi/mojo/qwencoder_serve/qwencoder_serve.mojo new file mode 100644 index 00000000..6b4b7e70 --- /dev/null +++ b/crates/aien-inference-abi/mojo/qwencoder_serve/qwencoder_serve.mojo @@ -0,0 +1,617 @@ +"""Resident-weight Qwen3-Coder-30B-A3B serve library for GB10 (foundry seat). + +Companion to the proven `libaien_qwen3_moe.so` pipeline: same kernels and +orchestration (`from lib import ...` is read-only reuse, nothing is modified +there), but weights upload ONCE at startup and stay resident. Per decode step +only the 2048-wide activation row crosses the host/device boundary, so the +~40ms per-call upload cost of the batch-oriented API disappears. + +Model shape is fixed (48 layers, hidden 2048, 32Q/4KV, head 128, MoE 128x8x768, +vocab 151936); every buffer is preallocated in `qwencoder_model_create`. +One model per process. Status codes: 0 ok, 1 shape/state, 3 device error. + +Build: ./build.sh (needs -I at the MoE mojo dir, read-only). +""" + +from max.gpu.host import DeviceContext, DeviceBuffer, HostBuffer +from max.gpu.memory import AddressSpace +from max.gpu.sync import barrier +from std.gpu import block_dim, block_idx, thread_idx +from std.math import exp, exp2, max +from std.memory import Layout, alloc, dealloc, stack_allocation + +from kernels import ( + EXPERTS, + TOP_K, + BF16Ptr, + F32Ptr, + U8Ptr, +) +from lib import Workspace, _enqueue_layer + +comptime STATUS_OK: Int32 = 0 +comptime STATUS_BAD_STATE: Int32 = 1 +comptime STATUS_DEVICE_ERROR: Int32 = 3 + +comptime LAYERS = 48 +comptime HIDDEN = 2048 +comptime Q_DIM = 4096 +comptime KV_DIM = 512 +comptime Q_HEADS = 32 +comptime KV_HEADS = 4 +comptime HEAD_DIM = 128 +comptime GQA_GROUP = 8 +comptime INTER = 768 +comptime VOCAB = 151936 +comptime PROJ_SLOTS = 4 +comptime MAX_SEQ = 32768 +comptime SM_SCALE = 0.08838834764831845 # 1 / sqrt(128) + + +def fp8_block128_gemv_kernel( + result: F32Ptr, + weights: U8Ptr, + lut: F32Ptr, + scales: BF16Ptr, + vec: F32Ptr, + rows: Int32, + cols: Int32, +): + """One thread per output row. LUT maps E4M3 codes to FP32; BF16 inv scale + per 128-wide block, scale grid row-major over 128x128 blocks.""" + var row = block_idx.x * block_dim.x + thread_idx.x + if row >= Int(rows): + return + var c = Int(cols) + var kb = c // 128 + var acc = Float32(0.0) + var base = row * c + for b in range(kb): + var sc = scales[(row // 128) * kb + b].cast[DType.float32]() + for k in range(128): + var w = lut[Int(weights[base + b * 128 + k])] + acc += w * vec[b * 128 + k] * sc + result[row] = acc + + +def bf16_gemv_kernel( + result: F32Ptr, weights: BF16Ptr, vec: F32Ptr, rows: Int32, cols: Int32 +): + """One thread per output row, BF16 weights, FP32 accumulation.""" + var row = block_idx.x * block_dim.x + thread_idx.x + if row >= Int(rows): + return + var c = Int(cols) + var acc = Float32(0.0) + var base = row * c + for k in range(c): + acc += weights[base + k].cast[DType.float32]() * vec[k] + result[row] = acc + + +def kv_append_kernel( + k_cache: F32Ptr, v_cache: F32Ptr, k_row: F32Ptr, v_row: F32Ptr, pos: Int32 +): + """Appends one token's K/V rows ([512] each) at position pos. + Grid covers 1024 lanes; d < 512 is K, else V.""" + var d = block_idx.x * block_dim.x + thread_idx.x + if d >= 2 * KV_DIM: + return + var base = Int(pos) * KV_DIM + if d < KV_DIM: + k_cache[base + d] = k_row[d] + else: + v_cache[base + (d - KV_DIM)] = v_row[d - KV_DIM] + + +def attn_scores_kernel( + scores: F32Ptr, q: F32Ptr, k_cache: F32Ptr, seq: Int32, scale: Float32 +): + """One block per Q head. scores[h, t] = dot(q_h, K_t) * scale. + Lanes stride over t; each lane runs full 128-dots from shared q.""" + var h = block_idx.x + var lane = thread_idx.x + var kv_h = h // GQA_GROUP + var sq = stack_allocation[HEAD_DIM, Float32, address_space=AddressSpace.SHARED]() + if lane < HEAD_DIM: + sq[lane] = q[h * HEAD_DIM + lane] + barrier() + var n = Int(seq) + var t = lane + while t < n: + var acc = Float32(0.0) + var kbase = t * KV_DIM + kv_h * HEAD_DIM + for d in range(HEAD_DIM): + acc += sq[d] * k_cache[kbase + d] + scores[h * MAX_SEQ + t] = acc * scale + t += 128 + + +def attn_combine_kernel( + result: F32Ptr, scores: F32Ptr, v_cache: F32Ptr, seq: Int32 +): + """One block per Q head, lane d. Softmax over t then weighted sum of V. + Grid 32 blocks, 128 lanes.""" + var h = block_idx.x + var lane = thread_idx.x + var kv_h = h // GQA_GROUP + var n = Int(seq) + var mx = Float32(-1e30) + for t in range(n): + mx = max(mx, scores[h * MAX_SEQ + t]) + var denom = Float32(0.0) + var acc = Float32(0.0) + for t in range(n): + var w = exp(scores[h * MAX_SEQ + t] - mx) + denom += w + acc += w * v_cache[t * KV_DIM + kv_h * HEAD_DIM + lane] + result[h * HEAD_DIM + lane] = acc / denom + + +struct QwenServeModel(Movable): + """All resident weights, one-token scratch, and staging. ~30GB device.""" + + var ctx: DeviceContext + var moe_router: List[DeviceBuffer[DType.bfloat16]] + var moe_gate_up: List[DeviceBuffer[DType.uint8]] + var moe_gu_scales: List[DeviceBuffer[DType.bfloat16]] + var moe_down: List[DeviceBuffer[DType.uint8]] + var moe_down_scales: List[DeviceBuffer[DType.bfloat16]] + var proj_w: List[DeviceBuffer[DType.uint8]] + var proj_s: List[DeviceBuffer[DType.bfloat16]] + var proj_rows: List[Int] + var proj_cols: List[Int] + var lm_head: DeviceBuffer[DType.bfloat16] + var lut: DeviceBuffer[DType.float32] + var ws: Workspace + var kv_k: List[DeviceBuffer[DType.float32]] + var kv_v: List[DeviceBuffer[DType.float32]] + var attn_scores: DeviceBuffer[DType.float32] + var q_stage: DeviceBuffer[DType.float32] + var attn_out_stage: DeviceBuffer[DType.float32] + var d4096a: DeviceBuffer[DType.float32] + var d4096b: DeviceBuffer[DType.float32] + var d4096c: DeviceBuffer[DType.float32] + var d2048a: DeviceBuffer[DType.float32] + var d2048b: DeviceBuffer[DType.float32] + var d512a: DeviceBuffer[DType.float32] + var d512b: DeviceBuffer[DType.float32] + var dlogits: DeviceBuffer[DType.float32] + var h_attn: HostBuffer[DType.float32] + var h_q: HostBuffer[DType.float32] + var h_k: HostBuffer[DType.float32] + var h_v: HostBuffer[DType.float32] + var h_o: HostBuffer[DType.float32] # o-proj download staging, exactly [2048] + var h_moe: HostBuffer[DType.bfloat16] + var h_status: HostBuffer[DType.int32] + var h_logits: HostBuffer[DType.float32] + var x_stage: DeviceBuffer[DType.bfloat16] + var vec_stage: DeviceBuffer[DType.float32] + var out_stage: DeviceBuffer[DType.float32] + + def __init__(out self) raises: + var ctx = DeviceContext() + self.ctx = ctx + self.moe_router = List[DeviceBuffer[DType.bfloat16]]() + self.moe_gate_up = List[DeviceBuffer[DType.uint8]]() + self.moe_gu_scales = List[DeviceBuffer[DType.bfloat16]]() + self.moe_down = List[DeviceBuffer[DType.uint8]]() + self.moe_down_scales = List[DeviceBuffer[DType.bfloat16]]() + for _ in range(LAYERS): + self.moe_router.append(ctx.enqueue_create_buffer[DType.bfloat16](EXPERTS * HIDDEN)) + self.moe_gate_up.append(ctx.enqueue_create_buffer[DType.uint8](EXPERTS * 2 * INTER * HIDDEN)) + self.moe_gu_scales.append( + ctx.enqueue_create_buffer[DType.bfloat16](EXPERTS * (2 * INTER // 128) * (HIDDEN // 128)) + ) + self.moe_down.append(ctx.enqueue_create_buffer[DType.uint8](EXPERTS * HIDDEN * INTER)) + self.moe_down_scales.append( + ctx.enqueue_create_buffer[DType.bfloat16](EXPERTS * (HIDDEN // 128) * (INTER // 128)) + ) + self.proj_w = List[DeviceBuffer[DType.uint8]]() + self.proj_s = List[DeviceBuffer[DType.bfloat16]]() + self.proj_rows = List[Int]() + self.proj_cols = List[Int]() + # Slot order per layer: 0 = q [4096,2048], 1 = k [512,2048], + # 2 = v [512,2048], 3 = o [2048,4096]. + var slot_rows = List[Int]() + slot_rows.append(Q_DIM) + slot_rows.append(KV_DIM) + slot_rows.append(KV_DIM) + slot_rows.append(HIDDEN) + var slot_cols = List[Int]() + slot_cols.append(HIDDEN) + slot_cols.append(HIDDEN) + slot_cols.append(HIDDEN) + slot_cols.append(Q_DIM) + for _ in range(LAYERS): + for s in range(PROJ_SLOTS): + var r = slot_rows[s] + var c = slot_cols[s] + self.proj_w.append(ctx.enqueue_create_buffer[DType.uint8](r * c)) + self.proj_s.append(ctx.enqueue_create_buffer[DType.bfloat16]((r // 128) * (c // 128))) + self.proj_rows.append(r) + self.proj_cols.append(c) + self.lm_head = ctx.enqueue_create_buffer[DType.bfloat16](VOCAB * HIDDEN) + self.lut = ctx.enqueue_create_buffer[DType.float32](256) + self.ws = Workspace(ctx, 1, HIDDEN, INTER) + self.kv_k = List[DeviceBuffer[DType.float32]]() + self.kv_v = List[DeviceBuffer[DType.float32]]() + for _ in range(LAYERS): + self.kv_k.append(ctx.enqueue_create_buffer[DType.float32](MAX_SEQ * KV_DIM)) + self.kv_v.append(ctx.enqueue_create_buffer[DType.float32](MAX_SEQ * KV_DIM)) + self.attn_scores = ctx.enqueue_create_buffer[DType.float32](Q_HEADS * MAX_SEQ) + self.q_stage = ctx.enqueue_create_buffer[DType.float32](Q_DIM) + self.attn_out_stage = ctx.enqueue_create_buffer[DType.float32](Q_DIM) + self.d4096a = ctx.enqueue_create_buffer[DType.float32](Q_DIM) + self.d4096b = ctx.enqueue_create_buffer[DType.float32](Q_DIM) + self.d4096c = ctx.enqueue_create_buffer[DType.float32](Q_DIM) + self.d2048a = ctx.enqueue_create_buffer[DType.float32](HIDDEN) + self.d2048b = ctx.enqueue_create_buffer[DType.float32](HIDDEN) + self.d512a = ctx.enqueue_create_buffer[DType.float32](KV_DIM) + self.d512b = ctx.enqueue_create_buffer[DType.float32](KV_DIM) + self.dlogits = ctx.enqueue_create_buffer[DType.float32](VOCAB) + self.h_attn = ctx.enqueue_create_host_buffer[DType.float32](Q_DIM) + self.h_q = ctx.enqueue_create_host_buffer[DType.float32](Q_DIM) + self.h_k = ctx.enqueue_create_host_buffer[DType.float32](KV_DIM) + self.h_v = ctx.enqueue_create_host_buffer[DType.float32](KV_DIM) + self.h_o = ctx.enqueue_create_host_buffer[DType.float32](HIDDEN) + self.h_moe = ctx.enqueue_create_host_buffer[DType.bfloat16](HIDDEN) + self.h_status = ctx.enqueue_create_host_buffer[DType.int32](1) + self.h_logits = ctx.enqueue_create_host_buffer[DType.float32](VOCAB) + self.x_stage = ctx.enqueue_create_buffer[DType.bfloat16](HIDDEN) + self.vec_stage = ctx.enqueue_create_buffer[DType.float32](Q_DIM) + self.out_stage = ctx.enqueue_create_buffer[DType.float32](VOCAB) + ctx.synchronize() + + def release(mut self) raises: + """Drops every resident weight buffer (device memory) by reassigning + empty containers; field destructors run on the old values. The struct + shell itself is freed by the caller via `unsafe_free`.""" + self.moe_router = List[DeviceBuffer[DType.bfloat16]]() + self.moe_gate_up = List[DeviceBuffer[DType.uint8]]() + self.moe_gu_scales = List[DeviceBuffer[DType.bfloat16]]() + self.moe_down = List[DeviceBuffer[DType.uint8]]() + self.moe_down_scales = List[DeviceBuffer[DType.bfloat16]]() + self.proj_w = List[DeviceBuffer[DType.uint8]]() + self.proj_s = List[DeviceBuffer[DType.bfloat16]]() + self.proj_rows = List[Int]() + self.proj_cols = List[Int]() + self.lm_head = self.ctx.enqueue_create_buffer[DType.bfloat16](1) + + +comptime ModelPtr = Pointer[QwenServeModel, MutUntrackedOrigin] + + +@export("qwencoder_model_create") +def qwencoder_model_create(handle_out: Pointer[ModelPtr, MutUntrackedOrigin]) abi("C") -> Int32: + try: + var model = QwenServeModel() + # FP8 E4M3 LUT on host, then upload (same formula as the CPU oracle). + var host_lut = model.ctx.enqueue_create_host_buffer[DType.float32](256) + model.ctx.synchronize() + for code in range(256): + var sign = Float32(1.0) + if (code & 0x80) != 0: + sign = -1.0 + var exp = (code >> 3) & 0x0F + var mant = Float32(code & 0x07) + var value = Float32(0.0) + if exp == 15 and mant == 7.0: + value = Float32(0.0) / Float32(0.0) + elif exp == 0: + value = sign * mant * exp2(Float32(-9)) + else: + value = sign * (1.0 + mant / 8.0) * exp2(Float32(exp - 7)) + host_lut[code] = value + model.ctx.enqueue_copy(model.lut, host_lut) + model.ctx.synchronize() + var a = alloc(Layout[QwenServeModel](count=1)) + var p = (a^).unsafe_leak() + p.unsafe_write(model^) + handle_out.unsafe_write(p) + return STATUS_OK + except e: + print("qwencoder_model_create:", e) + return STATUS_DEVICE_ERROR + + +@export("qwencoder_model_free") +def qwencoder_model_free(var model: ModelPtr) abi("C") -> Int32: + try: + ref m = model[] + m.release() + model.unsafe_free() + return STATUS_OK + except e: + print("qwencoder_model_free:", e) + return STATUS_DEVICE_ERROR + + +def _upload_copy[dtype: DType](ctx: DeviceContext, dev: DeviceBuffer[dtype], host: MutPointer[Scalar[dtype], MutAnyOrigin], count: Int) raises: + ctx.enqueue_copy(dev, DeviceBuffer[dtype](ctx, host, count, owning=False)) + + +@export("qwencoder_moe_upload") +def qwencoder_moe_upload( + model: ModelPtr, + layer: Int32, + router: BF16Ptr, + gate_up: U8Ptr, + gu_scales: BF16Ptr, + down: U8Ptr, + down_scales: BF16Ptr, +) abi("C") -> Int32: + if layer < 0 or Int(layer) >= LAYERS: + return STATUS_BAD_STATE + try: + ref m = model[] + var l = Int(layer) + _upload_copy[DType.bfloat16](m.ctx, m.moe_router[l], router, EXPERTS * HIDDEN) + _upload_copy[DType.uint8](m.ctx, m.moe_gate_up[l], gate_up, EXPERTS * 2 * INTER * HIDDEN) + _upload_copy[DType.bfloat16]( + m.ctx, m.moe_gu_scales[l], gu_scales, EXPERTS * (2 * INTER // 128) * (HIDDEN // 128) + ) + _upload_copy[DType.uint8](m.ctx, m.moe_down[l], down, EXPERTS * HIDDEN * INTER) + _upload_copy[DType.bfloat16]( + m.ctx, m.moe_down_scales[l], down_scales, EXPERTS * (HIDDEN // 128) * (INTER // 128) + ) + m.ctx.synchronize() + return STATUS_OK + except e: + print("qwencoder_moe_upload:", e) + return STATUS_DEVICE_ERROR + + +@export("qwencoder_proj_upload") +def qwencoder_proj_upload( + model: ModelPtr, layer: Int32, slot: Int32, weights: U8Ptr, scales: BF16Ptr +) abi("C") -> Int32: + if layer < 0 or Int(layer) >= LAYERS or slot < 0 or Int(slot) >= PROJ_SLOTS: + return STATUS_BAD_STATE + try: + ref m = model[] + var idx = Int(layer) * PROJ_SLOTS + Int(slot) + var r = m.proj_rows[idx] + var c = m.proj_cols[idx] + _upload_copy[DType.uint8](m.ctx, m.proj_w[idx], weights, r * c) + _upload_copy[DType.bfloat16](m.ctx, m.proj_s[idx], scales, (r // 128) * (c // 128)) + m.ctx.synchronize() + return STATUS_OK + except e: + print("qwencoder_proj_upload:", e) + return STATUS_DEVICE_ERROR + + +@export("qwencoder_lm_upload") +def qwencoder_lm_upload(model: ModelPtr, weights: BF16Ptr) abi("C") -> Int32: + """LM head: BF16 [151936, 2048] host -> resident device buffer.""" + try: + ref m = model[] + _upload_copy[DType.bfloat16](m.ctx, m.lm_head, weights, VOCAB * HIDDEN) + m.ctx.synchronize() + return STATUS_OK + except e: + print("qwencoder_lm_upload:", e) + return STATUS_DEVICE_ERROR + + +@export("qwencoder_moe_forward") +def qwencoder_moe_forward(model: ModelPtr, layer: Int32, x: BF16Ptr, output: BF16Ptr) abi("C") -> Int32: + """One token through one resident MoE layer. No routing metadata download.""" + if layer < 0 or Int(layer) >= LAYERS: + return STATUS_BAD_STATE + try: + ref m = model[] + var l = Int(layer) + _upload_copy[DType.bfloat16](m.ctx, m.x_stage, x, HIDDEN) + _enqueue_layer( + m.ctx, + m.ws, + m.x_stage, + m.moe_router[l], + m.moe_gate_up[l], + m.moe_gu_scales[l], + m.moe_down[l], + m.moe_down_scales[l], + 1, + HIDDEN, + INTER, + ) + m.ctx.enqueue_copy(m.h_moe, m.ws.output) + m.ctx.enqueue_copy(m.h_status, m.ws.status) + m.ctx.synchronize() + if m.h_status[0] != 0: + return STATUS_BAD_STATE + for i in range(HIDDEN): + output[unsafe_offset=i] = m.h_moe[i] + return STATUS_OK + except e: + print("qwencoder_moe_forward:", e) + return STATUS_DEVICE_ERROR + + +@export("qwencoder_fp8_gemv") +def qwencoder_fp8_gemv( + model: ModelPtr, layer: Int32, slot: Int32, vec: F32Ptr, output: F32Ptr +) abi("C") -> Int32: + """O-proj only: [2048,4096] FP8 on persistent staging. The launch shape is + fixed, so any other slot would read past a smaller host vector.""" + if layer < 0 or Int(layer) >= LAYERS or Int(slot) != PROJ_SLOTS - 1: + return STATUS_BAD_STATE + try: + ref m = model[] + var idx = Int(layer) * PROJ_SLOTS + Int(slot) + _upload_copy[DType.float32](m.ctx, m.d4096a, vec, Q_DIM) + m.ctx.enqueue_function[fp8_block128_gemv_kernel]( + m.d2048a.unsafe_ptr(), + m.proj_w[idx].unsafe_ptr(), + m.lut.unsafe_ptr(), + m.proj_s[idx].unsafe_ptr(), + m.d4096a.unsafe_ptr(), + Int32(HIDDEN), + Int32(Q_DIM), + grid_dim=(HIDDEN + 255) // 256, + block_dim=256, + ) + m.ctx.enqueue_copy(m.h_o, m.d2048a) + m.ctx.synchronize() + for i in range(HIDDEN): + output[unsafe_offset=i] = m.h_o[i] + return STATUS_OK + except e: + print("qwencoder_fp8_gemv:", e) + return STATUS_DEVICE_ERROR + + +@export("qwencoder_fused_qkv") +def qwencoder_fused_qkv( + model: ModelPtr, layer: Int32, vec: F32Ptr, q_out: F32Ptr, k_out: F32Ptr, v_out: F32Ptr +) abi("C") -> Int32: + """Q/K/V projections in one call: one activation upload, three GEMV + kernels back to back, one synchronize. Slots 0/1/2 of the layer.""" + if layer < 0 or Int(layer) >= LAYERS: + return STATUS_BAD_STATE + try: + ref m = model[] + var base = Int(layer) * PROJ_SLOTS + _upload_copy[DType.float32](m.ctx, m.d2048a, vec, HIDDEN) + # Slot shapes are fixed: q [4096,2048], k/v [512,2048]. + m.ctx.enqueue_function[fp8_block128_gemv_kernel]( + m.d4096a.unsafe_ptr(), + m.proj_w[base].unsafe_ptr(), + m.lut.unsafe_ptr(), + m.proj_s[base].unsafe_ptr(), + m.d2048a.unsafe_ptr(), + Int32(Q_DIM), + Int32(HIDDEN), + grid_dim=(Q_DIM + 255) // 256, + block_dim=256, + ) + m.ctx.enqueue_function[fp8_block128_gemv_kernel]( + m.d512a.unsafe_ptr(), + m.proj_w[base + 1].unsafe_ptr(), + m.lut.unsafe_ptr(), + m.proj_s[base + 1].unsafe_ptr(), + m.d2048a.unsafe_ptr(), + Int32(KV_DIM), + Int32(HIDDEN), + grid_dim=(KV_DIM + 255) // 256, + block_dim=256, + ) + m.ctx.enqueue_function[fp8_block128_gemv_kernel]( + m.d512b.unsafe_ptr(), + m.proj_w[base + 2].unsafe_ptr(), + m.lut.unsafe_ptr(), + m.proj_s[base + 2].unsafe_ptr(), + m.d2048a.unsafe_ptr(), + Int32(KV_DIM), + Int32(HIDDEN), + grid_dim=(KV_DIM + 255) // 256, + block_dim=256, + ) + m.ctx.enqueue_copy(m.h_q, m.d4096a) + m.ctx.enqueue_copy(m.h_k, m.d512a) + m.ctx.enqueue_copy(m.h_v, m.d512b) + m.ctx.synchronize() + for i in range(Q_DIM): + q_out[unsafe_offset=i] = m.h_q[i] + for i in range(KV_DIM): + k_out[unsafe_offset=i] = m.h_k[i] + v_out[unsafe_offset=i] = m.h_v[i] + return STATUS_OK + except e: + print("qwencoder_fused_qkv:", e) + return STATUS_DEVICE_ERROR + + +@export("qwencoder_bf16_gemv") +def qwencoder_bf16_gemv(model: ModelPtr, vec: F32Ptr, output: F32Ptr) abi("C") -> Int32: + """LM head: BF16 [151936, 2048] resident, FP32 vec in, FP32 logits out.""" + try: + ref m = model[] + _upload_copy[DType.float32](m.ctx, m.d2048a, vec, HIDDEN) + m.ctx.enqueue_function[bf16_gemv_kernel]( + m.dlogits.unsafe_ptr(), + m.lm_head.unsafe_ptr(), + m.d2048a.unsafe_ptr(), + Int32(VOCAB), + Int32(HIDDEN), + grid_dim=(VOCAB + 255) // 256, + block_dim=256, + ) + m.ctx.enqueue_copy(m.h_logits, m.dlogits) + m.ctx.synchronize() + for i in range(VOCAB): + output[unsafe_offset=i] = m.h_logits[i] + return STATUS_OK + except e: + print("qwencoder_bf16_gemv:", e) + return STATUS_DEVICE_ERROR + + +@export("qwencoder_kv_append") +def qwencoder_kv_append( + model: ModelPtr, layer: Int32, k_row: F32Ptr, v_row: F32Ptr, pos: Int32 +) abi("C") -> Int32: + """Appends one token's K/V rows ([512] each, RoPE already applied to K) + into the layer's resident cache at position pos.""" + if layer < 0 or Int(layer) >= LAYERS or pos < 0 or Int(pos) >= MAX_SEQ: + return STATUS_BAD_STATE + try: + ref m = model[] + var l = Int(layer) + _upload_copy[DType.float32](m.ctx, m.d512a, k_row, KV_DIM) + _upload_copy[DType.float32](m.ctx, m.d512b, v_row, KV_DIM) + m.ctx.enqueue_function[kv_append_kernel]( + m.kv_k[l].unsafe_ptr(), + m.kv_v[l].unsafe_ptr(), + m.d512a.unsafe_ptr(), + m.d512b.unsafe_ptr(), + pos, + grid_dim=(2 * KV_DIM + 255) // 256, + block_dim=256, + ) + m.ctx.synchronize() + return STATUS_OK + except e: + print("qwencoder_kv_append:", e) + return STATUS_DEVICE_ERROR + + +@export("qwencoder_attn") +def qwencoder_attn( + model: ModelPtr, layer: Int32, q_row: F32Ptr, output: F32Ptr, seq_len: Int32 +) abi("C") -> Int32: + """One query token against the layer's resident KV (positions [0, seq_len)). + q_row is [4096] with QK-norm and RoPE applied; output is [4096].""" + if layer < 0 or Int(layer) >= LAYERS or seq_len <= 0 or Int(seq_len) > MAX_SEQ: + return STATUS_BAD_STATE + try: + ref m = model[] + var l = Int(layer) + _upload_copy[DType.float32](m.ctx, m.q_stage, q_row, Q_DIM) + m.ctx.enqueue_function[attn_scores_kernel]( + m.attn_scores.unsafe_ptr(), + m.q_stage.unsafe_ptr(), + m.kv_k[l].unsafe_ptr(), + seq_len, + Float32(SM_SCALE), + grid_dim=Q_HEADS, + block_dim=128, + ) + m.ctx.enqueue_function[attn_combine_kernel]( + m.attn_out_stage.unsafe_ptr(), + m.attn_scores.unsafe_ptr(), + m.kv_v[l].unsafe_ptr(), + seq_len, + grid_dim=Q_HEADS, + block_dim=128, + ) + m.ctx.enqueue_copy(m.h_attn, m.attn_out_stage) + m.ctx.synchronize() + for i in range(Q_DIM): + output[unsafe_offset=i] = m.h_attn[i] + return STATUS_OK + except e: + print("qwencoder_attn:", e) + return STATUS_DEVICE_ERROR diff --git a/crates/aien-inference-abi/mojo/qwencoder_serve/receipts/noise_floor_2026-09-23.json b/crates/aien-inference-abi/mojo/qwencoder_serve/receipts/noise_floor_2026-09-23.json new file mode 100644 index 00000000..273a1926 --- /dev/null +++ b/crates/aien-inference-abi/mojo/qwencoder_serve/receipts/noise_floor_2026-09-23.json @@ -0,0 +1,382 @@ +{ + "base_seed": "0xc1000000000053", + "checkpoint": "/home/drakestapleton/.cache/huggingface/hub/models--Qwen--Qwen3-Coder-30B-A3B-Instruct-FP8/snapshots/dcaee4d4dfc5ee71ad501f01f530e5652438fde0", + "git_rev": "aef6525a8642c6c73cdf07d8f351ae0db13fc6db", + "model": "qwen3_coder_30b_a3b_fp8", + "not_hf_reference": true, + "pairs": { + "cand.dev_cpu": { + "cosine": { + "p01": 0.9597192865624214, + "p50": 0.9985208354573767, + "worst": 0.9597192865624214 + }, + "kl": { + "p50": 0.008006861746958275, + "p99": 0.1603263933465922, + "worst": 0.1603263933465922 + }, + "max_abs": { + "p50": 0.8577578067779541, + "p99": 2.54876971244812, + "worst": 3.0799083709716797 + }, + "max_rel": { + "p50": 422.3300275429554, + "p99": 1262.1361948549747, + "worst": 1375.7619559764862 + }, + "steps": 144, + "top1_disagreements": [ + { + "pos": 8, + "prompt": 0, + "ref_top2_margin": 0.09674453735351562 + }, + { + "pos": 19, + "prompt": 0, + "ref_top2_margin": 0.10163688659667969 + }, + { + "pos": 21, + "prompt": 0, + "ref_top2_margin": 0.010766983032226562 + }, + { + "pos": 0, + "prompt": 3, + "ref_top2_margin": 1.460988998413086 + }, + { + "pos": 6, + "prompt": 3, + "ref_top2_margin": 0.0983266830444336 + }, + { + "pos": 16, + "prompt": 3, + "ref_top2_margin": 0.069671630859375 + }, + { + "pos": 0, + "prompt": 4, + "ref_top2_margin": 1.460988998413086 + }, + { + "pos": 6, + "prompt": 4, + "ref_top2_margin": 0.0983266830444336 + }, + { + "pos": 16, + "prompt": 4, + "ref_top2_margin": 0.069671630859375 + }, + { + "pos": 2, + "prompt": 5, + "ref_top2_margin": 0.01715373992919922 + }, + { + "pos": 3, + "prompt": 5, + "ref_top2_margin": 0.05727672576904297 + }, + { + "pos": 7, + "prompt": 5, + "ref_top2_margin": 0.0039920806884765625 + } + ] + }, + "cand.dev_cpu16": { + "cosine": { + "p01": 0.9601429785182729, + "p50": 0.9985008852213898, + "worst": 0.9601429785182729 + }, + "kl": { + "p50": 0.0055556657251194345, + "p99": 0.15237157233310822, + "worst": 0.15237157233310822 + }, + "max_abs": { + "p50": 0.8062206506729126, + "p99": 2.9234957695007324, + "worst": 3.000269889831543 + }, + "max_rel": { + "p50": 412.2700909838256, + "p99": 1991.3178458809853, + "worst": 1991.3178458809853 + }, + "steps": 144, + "top1_disagreements": [ + { + "pos": 3, + "prompt": 0, + "ref_top2_margin": 0.0119476318359375 + }, + { + "pos": 8, + "prompt": 0, + "ref_top2_margin": 0.04370594024658203 + }, + { + "pos": 15, + "prompt": 0, + "ref_top2_margin": 0.06796455383300781 + }, + { + "pos": 19, + "prompt": 0, + "ref_top2_margin": 0.0014972686767578125 + }, + { + "pos": 0, + "prompt": 3, + "ref_top2_margin": 1.2356700897216797 + }, + { + "pos": 1, + "prompt": 3, + "ref_top2_margin": 0.5082559585571289 + }, + { + "pos": 6, + "prompt": 3, + "ref_top2_margin": 0.0442352294921875 + }, + { + "pos": 16, + "prompt": 3, + "ref_top2_margin": 0.10863685607910156 + }, + { + "pos": 0, + "prompt": 4, + "ref_top2_margin": 1.2356700897216797 + }, + { + "pos": 1, + "prompt": 4, + "ref_top2_margin": 0.5082559585571289 + }, + { + "pos": 6, + "prompt": 4, + "ref_top2_margin": 0.0442352294921875 + }, + { + "pos": 16, + "prompt": 4, + "ref_top2_margin": 0.10863685607910156 + }, + { + "pos": 6, + "prompt": 5, + "ref_top2_margin": 0.07003211975097656 + } + ] + }, + "floor.attention": { + "cosine": { + "p01": 0.9784253073462237, + "p50": 0.998793786050067, + "worst": 0.9784253073462237 + }, + "kl": { + "p50": 0.005624082134860249, + "p99": 0.26010622500053066, + "worst": 0.26010622500053066 + }, + "max_abs": { + "p50": 0.7934956550598145, + "p99": 2.610480785369873, + "worst": 2.610480785369873 + }, + "max_rel": { + "p50": 387.86355417687446, + "p99": 1305.1864144931064, + "worst": 1305.1864144931064 + }, + "steps": 144, + "top1_disagreements": [ + { + "pos": 3, + "prompt": 0, + "ref_top2_margin": 0.04546356201171875 + }, + { + "pos": 5, + "prompt": 0, + "ref_top2_margin": 0.08934593200683594 + }, + { + "pos": 8, + "prompt": 0, + "ref_top2_margin": 0.03878021240234375 + }, + { + "pos": 15, + "prompt": 0, + "ref_top2_margin": 0.07651138305664062 + }, + { + "pos": 19, + "prompt": 0, + "ref_top2_margin": 0.24606895446777344 + }, + { + "pos": 6, + "prompt": 3, + "ref_top2_margin": 0.029006004333496094 + }, + { + "pos": 15, + "prompt": 3, + "ref_top2_margin": 0.31490325927734375 + }, + { + "pos": 6, + "prompt": 4, + "ref_top2_margin": 0.029006004333496094 + }, + { + "pos": 15, + "prompt": 4, + "ref_top2_margin": 0.31490325927734375 + }, + { + "pos": 3, + "prompt": 5, + "ref_top2_margin": 0.06732749938964844 + } + ] + }, + "floor.moe_bf16": { + "cosine": { + "p01": 0.9660616952973714, + "p50": 0.9992048128681983, + "worst": 0.9660616952973714 + }, + "kl": { + "p50": 0.002609096552690595, + "p99": 0.16485610220575392, + "worst": 0.16485610220575392 + }, + "max_abs": { + "p50": 0.5858150124549866, + "p99": 2.7907309532165527, + "worst": 2.7907309532165527 + }, + "max_rel": { + "p50": 273.720346391201, + "p99": 1585.0952703040093, + "worst": 1585.0952703040093 + }, + "steps": 144, + "top1_disagreements": [ + { + "pos": 3, + "prompt": 0, + "ref_top2_margin": 0.007358551025390625 + }, + { + "pos": 15, + "prompt": 0, + "ref_top2_margin": 0.0006103515625 + }, + { + "pos": 21, + "prompt": 0, + "ref_top2_margin": 0.010766983032226562 + }, + { + "pos": 1, + "prompt": 3, + "ref_top2_margin": 0.426177978515625 + }, + { + "pos": 6, + "prompt": 3, + "ref_top2_margin": 0.0983266830444336 + }, + { + "pos": 1, + "prompt": 4, + "ref_top2_margin": 0.426177978515625 + }, + { + "pos": 6, + "prompt": 4, + "ref_top2_margin": 0.0983266830444336 + }, + { + "pos": 2, + "prompt": 5, + "ref_top2_margin": 0.01715373992919922 + }, + { + "pos": 3, + "prompt": 5, + "ref_top2_margin": 0.05727672576904297 + }, + { + "pos": 6, + "prompt": 5, + "ref_top2_margin": 0.06698799133300781 + }, + { + "pos": 7, + "prompt": 5, + "ref_top2_margin": 0.0039920806884765625 + } + ] + }, + "floor.rerun": { + "cosine": { + "p01": 0.9999999999999998, + "p50": 1.0, + "worst": 0.9999999999999998 + }, + "kl": { + "p50": 0.0, + "p99": 0.0, + "worst": 0.0 + }, + "max_abs": { + "p50": 0.0, + "p99": 0.0, + "worst": 0.0 + }, + "max_rel": { + "p50": 0.0, + "p99": 0.0, + "worst": 0.0 + }, + "steps": 144, + "top1_disagreements": [] + } + }, + "positions": 24, + "prompt_len": 6, + "prompts": 6, + "relative_error_epsilon": 0.001, + "schema": "aien.c1.noise_floor.v1", + "serve_lib": { + "path": "/home/drakestapleton/workspace/aien-sovereign-core/.claude/worktrees/c1-campaign-spec/crates/aien-inference-abi/mojo/qwencoder_serve/libqwencoder_serve.so", + "sha256": "906472e4f9d51d228d1c2dec16a850e3df042dc8d81dfd73b9c8adca67c34be6" + }, + "spec": { + "campaign": "c1", + "sections": [ + "5.1", + "5.3" + ], + "spec_version": 1 + }, + "teacher_forcing": "cpu_f32_greedy", + "wall_seconds": 426.221008663 +} \ No newline at end of file diff --git a/crates/aien-inference-abi/mojo/qwencoder_serve/test_kernels.mojo b/crates/aien-inference-abi/mojo/qwencoder_serve/test_kernels.mojo new file mode 100644 index 00000000..410addb6 --- /dev/null +++ b/crates/aien-inference-abi/mojo/qwencoder_serve/test_kernels.mojo @@ -0,0 +1,122 @@ +# Qwen3-Coder hand-computed kernel oracles. Run: +# nice -n 10 mojo run mojo-kernels/test_kernels.mojo +# Imports sibling via explicit path load (same dir, no package needed). + +from std.testing import assert_true, TestSuite +from qwencoder_kernels import ( + rmsnorm_row, + rope_rotate_half_pair, + silu, + swiglu_row, + repeat_kv_head, + row_gemv, + bf16_to_f32, + row_gemv_bf16, + fp8_e4m3_to_f32, + row_gemv_fp8_block128, +) + + +def close(a: Float32, b: Float64, tol: Float64) -> Bool: + var bb = Float32(b) + var tt = Float32(tol) + var d = a - bb + if d < 0.0: + d = -d + return d <= tt + + +def test_rmsnorm_ones() raises: + # Qwen eps 1e-6. ones, weight 2.0 -> 2.0 + var x: List[Float32] = [1.0, 1.0, 1.0, 1.0] + var w: List[Float32] = [2.0, 2.0, 2.0, 2.0] + var o: List[Float32] = [0.0, 0.0, 0.0, 0.0] + rmsnorm_row(x, w, o, Float32(1e-6)) + assert_true(close(o[0], 2.0, 1e-4)) + assert_true(close(o[3], 2.0, 1e-4)) + + +def test_rope_identity() raises: + var r = rope_rotate_half_pair(1.0, 0.0, 1.0, 0.0) + assert_true(close(r[0], 1.0, 1e-6)) + assert_true(close(r[1], 0.0, 1e-6)) + + +def test_swiglu_zero_gate() raises: + var g: List[Float32] = [0.0, 1.0] + var u: List[Float32] = [5.0, 5.0] + var o: List[Float32] = [0.0, 0.0] + swiglu_row(g, u, o) + assert_true(close(o[0], 0.0, 1e-6)) + # silu(1) = 1/(1+e^-1) ~= 0.7310586; *5 ~= 3.65529 + assert_true(close(o[1], 3.65529, 1e-3)) + + +def test_repeat_kv() raises: + var kv: List[Float32] = [1.0, 2.0] + var o: List[Float32] = [0.0, 0.0, 0.0, 0.0] + repeat_kv_head(kv, o, 2, 2) + assert_true(o[0] == 1.0 and o[1] == 2.0 and o[2] == 1.0 and o[3] == 2.0) + + +def test_gemv_hand() raises: + # 2x3 matrix, vec [1,10,100] -> row0 = 1+20+300=321, row1 = 4+50+600=654 + var m: List[Float32] = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0] + var v: List[Float32] = [1.0, 10.0, 100.0] + var o: List[Float32] = [0.0, 0.0] + row_gemv(o, m, v, 2, 3) + assert_true(close(o[0], 321.0, 1e-3)) + assert_true(close(o[1], 654.0, 1e-3)) + + +def test_bf16_decode() raises: + # 0x3F80 = 1.0, 0xC000 = -2.0 (hand-decoded from sign/exp/mantissa) + assert_true(close(bf16_to_f32(UInt16(0x3F80)), 1.0, 1e-6)) + assert_true(close(bf16_to_f32(UInt16(0xC000)), -2.0, 1e-6)) + + +def test_bf16_gemv_hand() raises: + # [[1,2],[3,4]] . [1,1] = [3,7]; BF16 codes 1.0=0x3F80 2.0=0x4000 3.0=0x4040 4.0=0x4080 + var m = List[UInt16]() + m.append(UInt16(0x3F80)) + m.append(UInt16(0x4000)) + m.append(UInt16(0x4040)) + m.append(UInt16(0x4080)) + var v: List[Float32] = [1.0, 1.0] + var o: List[Float32] = [0.0, 0.0] + row_gemv_bf16(o, m, v, 2, 2) + assert_true(close(o[0], 3.0, 1e-3)) + assert_true(close(o[1], 7.0, 1e-3)) + + +def test_fp8_decode() raises: + # 0x38 = 1.0 (exp 7, mant 0); 0xBC = -1.5 (sign, exp 7, mant 4); 0x00 = 0.0 + assert_true(close(fp8_e4m3_to_f32(UInt8(0x38)), 1.0, 1e-6)) + assert_true(close(fp8_e4m3_to_f32(UInt8(0xBC)), -1.5, 1e-6)) + assert_true(close(fp8_e4m3_to_f32(UInt8(0x00)), 0.0, 1e-6)) + + +def test_fp8_block128_gemv_hand() raises: + # 2x128 all 0x38 (=1.0), one scale block of 1.0, vec ones(128) -> 128.0 per row + var w = List[UInt8]() + for _ in range(256): + w.append(UInt8(0x38)) + var s = List[UInt16]() + s.append(UInt16(0x3F80)) + var v = List[Float32]() + for _ in range(128): + v.append(1.0) + var o: List[Float32] = [0.0, 0.0] + row_gemv_fp8_block128(o, w, s, v, 2, 128) + assert_true(close(o[0], 128.0, 1e-2)) + assert_true(close(o[1], 128.0, 1e-2)) + # same weights, scale 2.0 (0x4000) -> 256.0 per row + var s2 = List[UInt16]() + s2.append(UInt16(0x4000)) + row_gemv_fp8_block128(o, w, s2, v, 2, 128) + assert_true(close(o[0], 256.0, 1e-2)) + assert_true(close(o[1], 256.0, 1e-2)) + + +def main() raises: + TestSuite.discover_tests[__functions_in_module()]().run() diff --git a/crates/aien-inference-abi/src/lib.rs b/crates/aien-inference-abi/src/lib.rs index 248056a5..4eb3f610 100644 --- a/crates/aien-inference-abi/src/lib.rs +++ b/crates/aien-inference-abi/src/lib.rs @@ -15,7 +15,9 @@ pub mod capsule; pub mod checkpoint; pub mod moe_plan; pub mod mojo_backend; +pub mod qwen3_coder; pub mod qwen3_moe; +pub mod qwen3_serve; pub mod tensor; pub mod tensor_abi; pub mod tokenizer; @@ -34,7 +36,9 @@ pub use capsule::*; pub use checkpoint::*; pub use moe_plan::*; pub use mojo_backend::*; +pub use qwen3_coder::*; pub use qwen3_moe::*; +pub use qwen3_serve::*; pub use tensor::*; pub use tensor_abi::*; pub use tokenizer::*; diff --git a/crates/aien-inference-abi/src/qwen3_coder.rs b/crates/aien-inference-abi/src/qwen3_coder.rs new file mode 100644 index 00000000..1f318838 --- /dev/null +++ b/crates/aien-inference-abi/src/qwen3_coder.rs @@ -0,0 +1,532 @@ +//! Native end-to-end Qwen3-Coder-30B-A3B inference in Rust, no MAX graph, no Python. +//! +//! Loads the official FP8 checkpoint (`Qwen/Qwen3-Coder-30B-A3B-Instruct-FP8`) +//! through the same validated shard reader as the MoE path, decodes weights to +//! FP32 once at load, and runs the full 48-layer forward on CPU: embedding, +//! per-layer GQA attention with QK norms and RoPE, the native MoE experts via +//! [`crate::qwen3_moe`], final norm, LM head, and sampling. Every GPU kernel in +//! Phase B plugs into this exact structure, so numerics stay comparable. + +use std::collections::HashMap; +use std::path::{Path, PathBuf}; + +use rayon::prelude::*; + +use crate::moe_plan::MoeBatchPlan; +use crate::qwen3_moe::{ + bf16_to_f32, f32_to_bf16, fp8_table, load_qwen3_fp8_moe_layer, reference_moe_forward, + reference_router_logits, shard_path, Qwen3MoeError, Qwen3MoeKernels, Qwen3MoeLayer, Shard, + FP8_BLOCK, QWEN3_A3B_HIDDEN, QWEN3_A3B_LAYERS, +}; +use crate::tensor::{apply_rope, rmsnorm, sample_argmax, scaled_dot_product_attention_single}; + +pub const QWEN3_CODER_LAYERS: usize = QWEN3_A3B_LAYERS; +pub const QWEN3_CODER_HIDDEN: usize = QWEN3_A3B_HIDDEN; +pub const QWEN3_CODER_Q_HEADS: usize = 32; +pub const QWEN3_CODER_KV_HEADS: usize = 4; +pub const QWEN3_CODER_HEAD_DIM: usize = 128; +pub const QWEN3_CODER_Q_DIM: usize = QWEN3_CODER_Q_HEADS * QWEN3_CODER_HEAD_DIM; +pub const QWEN3_CODER_KV_DIM: usize = QWEN3_CODER_KV_HEADS * QWEN3_CODER_HEAD_DIM; +pub const QWEN3_CODER_VOCAB: usize = 151936; +pub const QWEN3_CODER_RMS_EPS: f32 = 1e-6; +pub const QWEN3_CODER_ROPE_THETA: f32 = 10_000_000.0; + +#[derive(Debug)] +pub enum Qwen3CoderError { + Io(String), + Index(String), + Contract(String), +} + +impl std::fmt::Display for Qwen3CoderError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Io(d) => write!(f, "io: {d}"), + Self::Index(d) => write!(f, "index: {d}"), + Self::Contract(d) => write!(f, "contract: {d}"), + } + } +} + +impl std::error::Error for Qwen3CoderError {} + +impl From for Qwen3CoderError { + fn from(e: Qwen3MoeError) -> Self { + Self::Contract(format!("moe layer: {e}")) + } +} + +/// One layer's attention weights decoded to FP32 row-major at load. +#[derive(Debug, Clone)] +pub struct Qwen3CoderAttention { + pub q_proj: Vec, + pub k_proj: Vec, + pub v_proj: Vec, + pub o_proj: Vec, + pub q_norm: Vec, + pub k_norm: Vec, + pub input_norm: Vec, + pub post_norm: Vec, +} + +/// Full Qwen3-Coder-30B-A3B weights. MoE experts stay in their validated +/// capsule form; everything else is FP32 decoded once at load. +pub struct Qwen3CoderWeights { + pub embed: Vec, + pub attns: Vec, + pub moes: Vec, + pub final_norm: Vec, + pub lm_head: Vec, +} + +/// Per-layer KV cache: one (k, v) pair per decoded position. +#[derive(Debug, Default)] +pub struct Qwen3CoderLayerKv { + pub keys: Vec>, + pub values: Vec>, +} + +#[derive(Debug, Default)] +pub struct Qwen3CoderState { + pub layers: Vec, +} + +impl Qwen3CoderState { + pub fn new() -> Self { + Self { + layers: (0..QWEN3_CODER_LAYERS) + .map(|_| Qwen3CoderLayerKv::default()) + .collect(), + } + } +} + +/// Parallel FP32 vector-matrix multiply, f32 accumulation for speed on the +/// wide projections (Q, O, LM head). Narrow norms stay on `tensor::matmul_vec`. +fn matvec_f32_parallel(x: &[f32], w: &[f32], out: &mut [f32], in_dim: usize, out_dim: usize) { + debug_assert_eq!(x.len(), in_dim); + debug_assert_eq!(w.len(), in_dim * out_dim); + debug_assert_eq!(out.len(), out_dim); + out.par_chunks_exact_mut(1) + .enumerate() + .for_each(|(j, slot)| { + let row = &w[j * in_dim..(j + 1) * in_dim]; + let mut sum = 0.0f32; + for i in 0..in_dim { + sum += x[i] * row[i]; + } + slot[0] = sum; + }); +} + +/// Decodes one FP8 block-128 matrix with BF16 inverse scales to FP32 row-major. +fn decode_fp8_block128(weights: &[u8], scales_inv: &[u16], rows: usize, cols: usize) -> Vec { + let lut = fp8_table(); + let k_blocks = cols / FP8_BLOCK; + assert_eq!(cols % FP8_BLOCK, 0, "cols must split into 128-wide blocks"); + assert_eq!( + scales_inv.len(), + rows.div_ceil(FP8_BLOCK) * k_blocks, + "scale grid must match 128x128 blocks" + ); + let mut out = vec![0.0f32; rows * cols]; + out.par_chunks_mut(cols) + .enumerate() + .for_each(|(r, row_out)| { + let row = &weights[r * cols..(r + 1) * cols]; + for b in 0..k_blocks { + let scale = bf16_to_f32(scales_inv[(r / FP8_BLOCK) * k_blocks + b]); + let dst = &mut row_out[b * FP8_BLOCK..(b + 1) * FP8_BLOCK]; + let src = &row[b * FP8_BLOCK..(b + 1) * FP8_BLOCK]; + for (d, &w) in dst.iter_mut().zip(src.iter()) { + *d = lut[w as usize] * scale; + } + } + }); + out +} + +/// Reinterprets a BF16 payload as u16 words. Panics on odd length or +/// misalignment rather than silently dropping bytes and shifting every word. +pub(crate) fn bf16_words(bytes: &[u8]) -> &[u16] { + assert_eq!(bytes.len() % 2, 0, "bf16 payload must be even length"); + // SAFETY: u16 has no invalid bit patterns; prefix/suffix are checked empty. + let (prefix, words, suffix) = unsafe { bytes.align_to::() }; + assert!( + prefix.is_empty() && suffix.is_empty(), + "bf16 payload misaligned" + ); + words +} + +fn decode_bf16(bytes: &[u8]) -> Vec { + bf16_words(bytes).iter().map(|&b| bf16_to_f32(b)).collect() +} + +pub(crate) struct CoderShardCache { + checkpoint_dir: PathBuf, + weight_map: serde_json::Map, + shards: HashMap, +} + +impl CoderShardCache { + pub(crate) fn open(checkpoint_dir: &Path) -> Result { + 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| Qwen3CoderError::Io(format!("{}: {e}", index_path.display())))?, + ) + .map_err(|e| Qwen3CoderError::Index(format!("{}: {e}", index_path.display())))?; + let weight_map = index + .get("weight_map") + .and_then(|v| v.as_object()) + .cloned() + .ok_or_else(|| Qwen3CoderError::Index("missing weight_map object".to_string()))?; + Ok(Self { + checkpoint_dir: checkpoint_dir.to_path_buf(), + weight_map, + shards: HashMap::new(), + }) + } + + pub(crate) fn read_raw( + &mut self, + name: &str, + dtype: &str, + shape: &[usize], + elem_bytes: usize, + ) -> Result, Qwen3CoderError> { + let filename = self + .weight_map + .get(name) + .and_then(|v| v.as_str()) + .ok_or_else(|| Qwen3CoderError::Index(format!("no shard for {name}")))?; + if !self.shards.contains_key(filename) { + let shard = Shard::open(&shard_path(&self.checkpoint_dir, filename)?) + .map_err(|e| Qwen3CoderError::Contract(format!("shard open: {e}")))?; + self.shards.insert(filename.to_string(), shard); + } + let expect_elems: usize = shape.iter().product(); + let mut dst = vec![0u8; expect_elems * elem_bytes]; + self.shards[filename] + .read(name, dtype, shape, &mut dst) + .map_err(|e| Qwen3CoderError::Contract(format!("shard read: {e}")))?; + Ok(dst) + } + + fn read_bf16_f32(&mut self, name: &str, shape: &[usize]) -> Result, Qwen3CoderError> { + Ok(decode_bf16(&self.read_raw(name, "BF16", shape, 2)?)) + } + + fn read_fp8_f32( + &mut self, + name: &str, + rows: usize, + cols: usize, + ) -> Result, Qwen3CoderError> { + let scale_name = format!("{name}_scale_inv"); + let weights = self.read_raw(name, "F8_E4M3", &[rows, cols], 1)?; + let scales = self.read_raw( + &scale_name, + "BF16", + &[rows / FP8_BLOCK, cols / FP8_BLOCK], + 2, + )?; + Ok(decode_fp8_block128( + &weights, + bf16_words(&scales), + rows, + cols, + )) + } +} + +/// Loads all 48 layers plus embeddings, final norm, and LM head. +pub fn load_qwen3_coder(checkpoint_dir: &Path) -> Result { + let h = QWEN3_CODER_HIDDEN; + let qd = QWEN3_CODER_Q_DIM; + let kvd = QWEN3_CODER_KV_DIM; + let hd = QWEN3_CODER_HEAD_DIM; + let mut cache = CoderShardCache::open(checkpoint_dir)?; + + let embed = cache.read_bf16_f32("model.embed_tokens.weight", &[QWEN3_CODER_VOCAB, h])?; + let final_norm = cache.read_bf16_f32("model.norm.weight", &[h])?; + let lm_head = cache.read_bf16_f32("lm_head.weight", &[QWEN3_CODER_VOCAB, h])?; + + let mut attns = Vec::with_capacity(QWEN3_CODER_LAYERS); + let mut moes = Vec::with_capacity(QWEN3_CODER_LAYERS); + for layer in 0..QWEN3_CODER_LAYERS { + let p = format!("model.layers.{layer}"); + let q_proj = cache.read_fp8_f32(&format!("{p}.self_attn.q_proj.weight"), qd, h)?; + let k_proj = cache.read_fp8_f32(&format!("{p}.self_attn.k_proj.weight"), kvd, h)?; + let v_proj = cache.read_fp8_f32(&format!("{p}.self_attn.v_proj.weight"), kvd, h)?; + let o_proj = cache.read_fp8_f32(&format!("{p}.self_attn.o_proj.weight"), h, qd)?; + let q_norm = cache.read_bf16_f32(&format!("{p}.self_attn.q_norm.weight"), &[hd])?; + let k_norm = cache.read_bf16_f32(&format!("{p}.self_attn.k_norm.weight"), &[hd])?; + let input_norm = cache.read_bf16_f32(&format!("{p}.input_layernorm.weight"), &[h])?; + let post_norm = + cache.read_bf16_f32(&format!("{p}.post_attention_layernorm.weight"), &[h])?; + attns.push(Qwen3CoderAttention { + q_proj, + k_proj, + v_proj, + o_proj, + q_norm, + k_norm, + input_norm, + post_norm, + }); + moes.push(load_qwen3_fp8_moe_layer(checkpoint_dir, layer)?); + } + + Ok(Qwen3CoderWeights { + embed, + attns, + moes, + final_norm, + lm_head, + }) +} + +pub(crate) fn rmsnorm_per_head( + x: &[f32], + weight: &[f32], + eps: f32, + num_heads: usize, + head_dim: usize, + out: &mut [f32], +) { + for h in 0..num_heads { + rmsnorm( + &x[h * head_dim..(h + 1) * head_dim], + weight, + eps, + &mut out[h * head_dim..(h + 1) * head_dim], + ); + } +} + +/// Runs one token through all 48 layers. Returns the final hidden state. +pub fn forward_token( + weights: &Qwen3CoderWeights, + token_id: u32, + pos: usize, + state: &mut Qwen3CoderState, +) -> Vec { + forward_token_with_moe(weights, token_id, pos, state, &mut MoeBackend::Cpu) +} + +/// Where the MoE sublayer runs. Cpu is the bit-exact reference; Device uses +/// the proven `libaien_qwen3_moe.so` forward for the same layer. +pub enum MoeBackend<'a> { + Cpu, + /// CPU reference with the device ABI's precision: MoE input and output + /// rounded to BF16. Separates BF16 activation rounding from kernel error. + CpuBf16Io, + Device(&'a Qwen3MoeKernels), +} + +/// Full 48-layer forward with a selectable MoE backend. Attention, norms, +/// RoPE, and sampling stay on CPU in Phase B1; only the experts move. +pub fn forward_token_with_moe( + weights: &Qwen3CoderWeights, + token_id: u32, + pos: usize, + state: &mut Qwen3CoderState, + moe_backend: &mut MoeBackend, +) -> Vec { + let h = QWEN3_CODER_HIDDEN; + let qd = QWEN3_CODER_Q_DIM; + let kvd = QWEN3_CODER_KV_DIM; + let hd = QWEN3_CODER_HEAD_DIM; + let eps = QWEN3_CODER_RMS_EPS; + + let token_idx = (token_id as usize) % QWEN3_CODER_VOCAB; + let mut x = weights.embed[token_idx * h..(token_idx + 1) * h].to_vec(); + + for (layer_idx, (attn, moe)) in weights.attns.iter().zip(weights.moes.iter()).enumerate() { + let kv = &mut state.layers[layer_idx]; + + let mut x_norm = vec![0.0f32; h]; + rmsnorm(&x, &attn.input_norm, eps, &mut x_norm); + + let mut q = vec![0.0f32; qd]; + let mut k = vec![0.0f32; kvd]; + let mut v = vec![0.0f32; kvd]; + matvec_f32_parallel(&x_norm, &attn.q_proj, &mut q, h, qd); + matvec_f32_parallel(&x_norm, &attn.k_proj, &mut k, h, kvd); + matvec_f32_parallel(&x_norm, &attn.v_proj, &mut v, h, kvd); + + let mut qn = vec![0.0f32; qd]; + let mut kn = vec![0.0f32; kvd]; + rmsnorm_per_head(&q, &attn.q_norm, eps, QWEN3_CODER_Q_HEADS, hd, &mut qn); + rmsnorm_per_head(&k, &attn.k_norm, eps, QWEN3_CODER_KV_HEADS, hd, &mut kn); + + apply_rope( + &mut qn, + &mut kn, + pos, + QWEN3_CODER_Q_HEADS, + QWEN3_CODER_KV_HEADS, + hd, + QWEN3_CODER_ROPE_THETA, + ); + + kv.keys.push(kn); + kv.values.push(v); + + let mut attn_out = vec![0.0f32; qd]; + scaled_dot_product_attention_single( + &qn, + &kv.keys, + &kv.values, + QWEN3_CODER_Q_HEADS, + QWEN3_CODER_KV_HEADS, + hd, + &mut attn_out, + ); + + let mut attn_proj = vec![0.0f32; h]; + matvec_f32_parallel(&attn_out, &attn.o_proj, &mut attn_proj, qd, h); + for i in 0..h { + x[i] += attn_proj[i]; + } + + let mut post = vec![0.0f32; h]; + rmsnorm(&x, &attn.post_norm, eps, &mut post); + + let moe_out = match moe_backend { + MoeBackend::Cpu => { + let router = reference_router_logits(moe, &post, 1); + let plan = + MoeBatchPlan::qwen3_coder_a3b(&router, 1).expect("routing plan must build"); + reference_moe_forward(moe, &post, &plan) + } + MoeBackend::CpuBf16Io => { + let post_r: Vec = post.iter().map(|&v| bf16_to_f32(f32_to_bf16(v))).collect(); + let router = reference_router_logits(moe, &post_r, 1); + let plan = + MoeBatchPlan::qwen3_coder_a3b(&router, 1).expect("routing plan must build"); + reference_moe_forward(moe, &post_r, &plan) + .into_iter() + .map(|v| bf16_to_f32(f32_to_bf16(v))) + .collect() + } + MoeBackend::Device(kernels) => { + let post_bf16: Vec = post.iter().map(|&v| f32_to_bf16(v)).collect(); + kernels + .forward(moe, &post_bf16, 1) + .expect("device MoE forward must succeed") + .output + } + }; + for i in 0..h { + x[i] += moe_out[i]; + } + } + + let mut x_final = vec![0.0f32; h]; + rmsnorm(&x, &weights.final_norm, eps, &mut x_final); + x_final +} + +/// Projects a hidden state to vocabulary logits. +pub fn compute_logits(weights: &Qwen3CoderWeights, hidden: &[f32]) -> Vec { + let h = QWEN3_CODER_HIDDEN; + let mut logits = vec![0.0f32; QWEN3_CODER_VOCAB]; + matvec_f32_parallel(hidden, &weights.lm_head, &mut logits, h, QWEN3_CODER_VOCAB); + logits +} + +/// Prefills prompt tokens, then greedily decodes up to `max_new` tokens, +/// stopping at any id in `stop_ids`. Returns only the new tokens. +pub fn generate_greedy( + weights: &Qwen3CoderWeights, + prompt: &[u32], + max_new: usize, + stop_ids: &[u32], +) -> Vec { + let mut state = Qwen3CoderState::new(); + let mut pos = 0usize; + for &tok in prompt { + forward_token(weights, tok, pos, &mut state); + pos += 1; + } + let mut out = Vec::new(); + let mut prev = *prompt.last().unwrap_or(&0); + for _ in 0..max_new { + let hidden = forward_token(weights, prev, pos, &mut state); + let (next, _) = sample_argmax(&compute_logits(weights, &hidden)); + pos += 1; + if stop_ids.contains(&next) { + break; + } + out.push(next); + prev = next; + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::qwen3_moe::{dequant_matvec, QWEN3_A3B_INTERMEDIATE}; + + /// 2-aligned storage so the misalignment tests control the offset exactly. + fn aligned_bytes(words: &[u16]) -> Vec { + words.to_vec() + } + + #[test] + fn bf16_words_reads_aligned_payload() { + let backing = aligned_bytes(&[0x3f80, 0x4000]); + // SAFETY: u16 storage viewed as bytes; lifetime tied to `backing`. + let bytes = unsafe { std::slice::from_raw_parts(backing.as_ptr() as *const u8, 4) }; + assert_eq!(bf16_words(bytes), &[0x3f80, 0x4000]); + } + + #[test] + #[should_panic(expected = "misaligned")] + fn bf16_words_rejects_misaligned_payload() { + let backing = aligned_bytes(&[0, 0, 0]); + // SAFETY: in-bounds view starting one byte into 2-aligned storage. + let bytes = + unsafe { std::slice::from_raw_parts((backing.as_ptr() as *const u8).add(1), 4) }; + let _ = bf16_words(bytes); + } + + #[test] + #[should_panic(expected = "even length")] + fn bf16_words_rejects_odd_length() { + let backing = aligned_bytes(&[0, 0]); + // SAFETY: in-bounds 3-byte view of 4-byte storage. + let bytes = unsafe { std::slice::from_raw_parts(backing.as_ptr() as *const u8, 3) }; + let _ = bf16_words(bytes); + } + + #[test] + fn coder_constants_match_official_config() { + assert_eq!(QWEN3_CODER_LAYERS, 48); + assert_eq!(QWEN3_CODER_HIDDEN, 2048); + assert_eq!(QWEN3_CODER_Q_HEADS, 32); + assert_eq!(QWEN3_CODER_KV_HEADS, 4); + assert_eq!(QWEN3_CODER_HEAD_DIM, 128); + assert_eq!(QWEN3_CODER_VOCAB, 151936); + assert_eq!(QWEN3_A3B_INTERMEDIATE, 768); + } + + #[test] + fn fp8_block128_roundtrip_spot_check() { + let lut = fp8_table(); + assert!((lut[0x38] - 1.0).abs() < 1e-6); + assert!((lut[0xBC] + 1.5).abs() < 1e-6); + let w = vec![0x38u8; 256]; + // 2x128 is one 128x128 scale block (row blocks round up). + let s = vec![crate::qwen3_moe::f32_to_bf16(1.0); 1]; + let m = decode_fp8_block128(&w, &s, 2, 128); + assert!(m.iter().all(|&v| (v - 1.0).abs() < 1e-6)); + let v = vec![1.0f32; 128]; + let y = dequant_matvec(&w, &s, 2, 128, &v, &lut); + assert!((y[0] - 128.0).abs() < 1e-3); + } +} diff --git a/crates/aien-inference-abi/src/qwen3_moe.rs b/crates/aien-inference-abi/src/qwen3_moe.rs index d7dc365f..193fbe9f 100644 --- a/crates/aien-inference-abi/src/qwen3_moe.rs +++ b/crates/aien-inference-abi/src/qwen3_moe.rs @@ -30,6 +30,7 @@ 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; +pub(crate) const FP8_BLOCK: usize = BLOCK; 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. @@ -259,7 +260,7 @@ fn bytes_of(values: &[u16]) -> &[u8] { /// 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 { +pub(crate) 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)), @@ -269,7 +270,7 @@ fn shard_path(checkpoint_dir: &Path, filename: &str) -> Result Result { + pub(crate) 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(); @@ -313,7 +314,7 @@ impl Shard { } /// Reads one tensor into `dst` after checking dtype, shape and byte range. - fn read( + pub(crate) fn read( &self, name: &str, dtype: &str, @@ -495,7 +496,7 @@ pub fn fp8_e4m3fn_to_f32(bits: u8) -> f32 { } } -fn fp8_table() -> [f32; 256] { +pub(crate) fn fp8_table() -> [f32; 256] { std::array::from_fn(|bits| fp8_e4m3fn_to_f32(bits as u8)) } @@ -580,7 +581,7 @@ pub fn reference_router_logits(layer: &Qwen3MoeLayer, x: &[f32], tokens: usize) } /// out[r] = sum_k W[r, k] * v[k] with W an FP8 [rows, cols] matrix and 128x128 BF16 inverse scales. -fn dequant_matvec( +pub(crate) fn dequant_matvec( weights: &[u8], scales: &[u16], rows: usize, diff --git a/crates/aien-inference-abi/src/qwen3_serve.rs b/crates/aien-inference-abi/src/qwen3_serve.rs new file mode 100644 index 00000000..c5d4c9bf --- /dev/null +++ b/crates/aien-inference-abi/src/qwen3_serve.rs @@ -0,0 +1,499 @@ +//! Rust side of `libqwencoder_serve.so`: resident-weight full-model serve. +//! +//! The library keeps every FP8/BF16 weight on device after one upload pass. +//! Per decode step only activation rows cross the boundary. CPU fallback is +//! always available; every device call is parity-checked against it. + +use std::path::{Path, PathBuf}; + +use libloading::Library; + +use crate::qwen3_coder::{ + bf16_words, rmsnorm_per_head, CoderShardCache, Qwen3CoderError, Qwen3CoderState, + Qwen3CoderWeights, QWEN3_CODER_HEAD_DIM, QWEN3_CODER_HIDDEN, QWEN3_CODER_KV_DIM, + QWEN3_CODER_KV_HEADS, QWEN3_CODER_LAYERS, QWEN3_CODER_Q_DIM, QWEN3_CODER_Q_HEADS, + QWEN3_CODER_RMS_EPS, QWEN3_CODER_ROPE_THETA, QWEN3_CODER_VOCAB, +}; +use crate::qwen3_moe::{bf16_to_f32, f32_to_bf16}; +use crate::tensor::{apply_rope, rmsnorm, scaled_dot_product_attention_single}; + +type CreateFn = unsafe extern "C" fn(*mut u64) -> i32; +type FreeFn = unsafe extern "C" fn(u64) -> i32; +type MoeUploadFn = + unsafe extern "C" fn(u64, i32, *const u16, *const u8, *const u16, *const u8, *const u16) -> i32; +type ProjUploadFn = unsafe extern "C" fn(u64, i32, i32, *const u8, *const u16) -> i32; +type LmUploadFn = unsafe extern "C" fn(u64, *const u16) -> i32; +type MoeForwardFn = unsafe extern "C" fn(u64, i32, *const u16, *mut u16) -> i32; +type Fp8GemvFn = unsafe extern "C" fn(u64, i32, i32, *const f32, *mut f32) -> i32; +type FusedQkvFn = unsafe extern "C" fn(u64, i32, *const f32, *mut f32, *mut f32, *mut f32) -> i32; +type Bf16GemvFn = unsafe extern "C" fn(u64, *const f32, *mut f32) -> i32; +type KvAppendFn = unsafe extern "C" fn(u64, i32, *const f32, *const f32, i32) -> i32; +type AttnFn = unsafe extern "C" fn(u64, i32, *const f32, *mut f32, i32) -> i32; + +fn status(code: i32, what: &str) -> Result<(), Qwen3CoderError> { + if code == 0 { + Ok(()) + } else { + Err(Qwen3CoderError::Contract(format!( + "{what}: device status {code}" + ))) + } +} + +pub struct QwenServeLib { + _lib: Library, + create: CreateFn, + free: FreeFn, + moe_upload: MoeUploadFn, + proj_upload: ProjUploadFn, + lm_upload: LmUploadFn, + moe_forward: MoeForwardFn, + fp8_gemv: Fp8GemvFn, + fused_qkv: FusedQkvFn, + bf16_gemv: Bf16GemvFn, + kv_append: KvAppendFn, + attn: AttnFn, + pub path: PathBuf, +} + +impl QwenServeLib { + /// `AIEN_QWENSERVE_LIB`, else the crate's `mojo/qwencoder_serve/libqwencoder_serve.so`. + pub fn default_path() -> PathBuf { + std::env::var_os("AIEN_QWENSERVE_LIB") + .map(PathBuf::from) + .unwrap_or_else(|| { + std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("mojo/qwencoder_serve/libqwencoder_serve.so") + }) + } + + pub fn load(path: &Path) -> Result { + let err = + |e: libloading::Error| Qwen3CoderError::Contract(format!("{}: {e}", path.display())); + // SAFETY: the library is built from the foundry seat and exports these C signatures. + unsafe { + let lib = Library::new(path).map_err(err)?; + Ok(Self { + create: *lib + .get::(b"qwencoder_model_create\0") + .map_err(err)?, + free: *lib.get::(b"qwencoder_model_free\0").map_err(err)?, + moe_upload: *lib + .get::(b"qwencoder_moe_upload\0") + .map_err(err)?, + proj_upload: *lib + .get::(b"qwencoder_proj_upload\0") + .map_err(err)?, + lm_upload: *lib + .get::(b"qwencoder_lm_upload\0") + .map_err(err)?, + moe_forward: *lib + .get::(b"qwencoder_moe_forward\0") + .map_err(err)?, + fp8_gemv: *lib.get::(b"qwencoder_fp8_gemv\0").map_err(err)?, + fused_qkv: *lib + .get::(b"qwencoder_fused_qkv\0") + .map_err(err)?, + bf16_gemv: *lib + .get::(b"qwencoder_bf16_gemv\0") + .map_err(err)?, + kv_append: *lib + .get::(b"qwencoder_kv_append\0") + .map_err(err)?, + attn: *lib.get::(b"qwencoder_attn\0").map_err(err)?, + _lib: lib, + path: path.to_path_buf(), + }) + } + } +} + +pub struct QwenServeModel { + lib: QwenServeLib, + handle: u64, +} + +/// (rows, cols) per projection slot: 0 = q, 1 = k, 2 = v, 3 = o. +const PROJ_SHAPES: [(usize, usize); 4] = [ + (QWEN3_CODER_Q_DIM, QWEN3_CODER_HIDDEN), + (QWEN3_CODER_KV_DIM, QWEN3_CODER_HIDDEN), + (QWEN3_CODER_KV_DIM, QWEN3_CODER_HIDDEN), + (QWEN3_CODER_HIDDEN, QWEN3_CODER_Q_DIM), +]; +const PROJ_NAMES: [&str; 4] = ["q_proj", "k_proj", "v_proj", "o_proj"]; + +impl QwenServeModel { + /// Creates the device model and uploads every weight. One-time cost + /// (tens of GB); afterwards only activations cross the boundary. + pub fn upload_all( + lib: QwenServeLib, + weights: &Qwen3CoderWeights, + checkpoint_dir: &Path, + ) -> Result { + let this = Self::create(lib)?; + this.upload_weights(weights, checkpoint_dir)?; + Ok(this) + } + + /// Allocates the device model without weights. Kernel-level checks (KV + /// append, attention) run against this without the multi-minute upload. + pub fn create(lib: QwenServeLib) -> Result { + let mut handle = 0u64; + // SAFETY: handle is written by the call. + status(unsafe { (lib.create)(&mut handle) }, "model_create")?; + Ok(Self { lib, handle }) + } + + fn upload_weights( + &self, + weights: &Qwen3CoderWeights, + checkpoint_dir: &Path, + ) -> Result<(), Qwen3CoderError> { + let h = QWEN3_CODER_HIDDEN; + // MoE layers straight from the already-fused capsules: no re-read. + for (layer, moe) in weights.moes.iter().enumerate() { + let l = layer as i32; + // SAFETY: slices outlive the call; device copies synchronously. + status( + unsafe { + (self.lib.moe_upload)( + self.handle, + l, + moe.router_bf16().as_ptr(), + moe.gate_up_fp8().as_ptr(), + moe.gate_up_scale_inv_bf16().as_ptr(), + moe.down_fp8().as_ptr(), + moe.down_scale_inv_bf16().as_ptr(), + ) + }, + "moe_upload", + )?; + } + // Attention projections + LM head re-read raw (loader decoded to f32). + let mut cache = CoderShardCache::open(checkpoint_dir)?; + for layer in 0..QWEN3_CODER_LAYERS { + let p = format!("model.layers.{layer}.self_attn"); + for (slot, (name, (rows, cols))) in + PROJ_NAMES.iter().zip(PROJ_SHAPES.iter()).enumerate() + { + let base = format!("{p}.{name}.weight"); + let w = cache.read_raw(&base, "F8_E4M3", &[*rows, *cols], 1)?; + let s = cache.read_raw( + &format!("{base}_scale_inv"), + "BF16", + &[rows / 128, cols / 128], + 2, + )?; + // SAFETY: buffers outlive the synchronous call. + status( + unsafe { + (self.lib.proj_upload)( + self.handle, + layer as i32, + slot as i32, + w.as_ptr(), + bf16_words(&s).as_ptr(), + ) + }, + "proj_upload", + )?; + } + } + let lm = cache.read_raw("lm_head.weight", "BF16", &[QWEN3_CODER_VOCAB, h], 2)?; + // SAFETY: buffer outlives the synchronous call. + status( + unsafe { (self.lib.lm_upload)(self.handle, bf16_words(&lm).as_ptr()) }, + "lm_upload", + )?; + Ok(()) + } + + /// One token's MoE sublayer on device. `post_bf16`/`out_bf16` are [2048]. + pub fn moe_layer( + &self, + layer: usize, + post_bf16: &[u16], + out_bf16: &mut [u16], + ) -> Result<(), Qwen3CoderError> { + assert_eq!(post_bf16.len(), QWEN3_CODER_HIDDEN); + assert_eq!(out_bf16.len(), QWEN3_CODER_HIDDEN); + // SAFETY: slices outlive the synchronous call. + status( + unsafe { + (self.lib.moe_forward)( + self.handle, + layer as i32, + post_bf16.as_ptr(), + out_bf16.as_mut_ptr(), + ) + }, + "moe_forward", + ) + } + + /// Q/K/V projections in one device call (slots 0/1/2). + pub fn fused_qkv( + &self, + layer: usize, + vec: &[f32], + q: &mut [f32], + k: &mut [f32], + v: &mut [f32], + ) -> Result<(), Qwen3CoderError> { + assert_eq!(vec.len(), QWEN3_CODER_HIDDEN); + assert_eq!(q.len(), QWEN3_CODER_Q_DIM); + assert_eq!(k.len(), QWEN3_CODER_KV_DIM); + assert_eq!(v.len(), QWEN3_CODER_KV_DIM); + // SAFETY: slices outlive the synchronous call. + status( + unsafe { + (self.lib.fused_qkv)( + self.handle, + layer as i32, + vec.as_ptr(), + q.as_mut_ptr(), + k.as_mut_ptr(), + v.as_mut_ptr(), + ) + }, + "fused_qkv", + ) + } + + /// Attention output projection on device: [2048, 4096] x [4096] -> [2048]. + /// The device entry point implements only this shape (q/k/v go through + /// `fused_qkv`), so slot 3 is the only one exposed. + pub fn o_proj( + &self, + layer: usize, + vec: &[f32], + out: &mut [f32], + ) -> Result<(), Qwen3CoderError> { + const O_SLOT: usize = 3; + let (rows, cols) = PROJ_SHAPES[O_SLOT]; + assert_eq!(vec.len(), cols); + assert_eq!(out.len(), rows); + let slot = O_SLOT; + // SAFETY: slices outlive the synchronous call. + status( + unsafe { + (self.lib.fp8_gemv)( + self.handle, + layer as i32, + slot as i32, + vec.as_ptr(), + out.as_mut_ptr(), + ) + }, + "fp8_gemv", + ) + } + + /// Appends one token's K/V rows to the layer's resident cache. + pub fn kv_append( + &self, + layer: usize, + k_row: &[f32], + v_row: &[f32], + pos: usize, + ) -> Result<(), Qwen3CoderError> { + assert_eq!(k_row.len(), QWEN3_CODER_KV_DIM); + assert_eq!(v_row.len(), QWEN3_CODER_KV_DIM); + // SAFETY: slices outlive the synchronous call. + status( + unsafe { + (self.lib.kv_append)( + self.handle, + layer as i32, + k_row.as_ptr(), + v_row.as_ptr(), + pos as i32, + ) + }, + "kv_append", + ) + } + + /// One query token against the layer's resident KV. + pub fn attn( + &self, + layer: usize, + q_row: &[f32], + out: &mut [f32], + seq_len: usize, + ) -> Result<(), Qwen3CoderError> { + assert_eq!(q_row.len(), QWEN3_CODER_Q_DIM); + assert_eq!(out.len(), QWEN3_CODER_Q_DIM); + // SAFETY: slices outlive the synchronous call. + status( + unsafe { + (self.lib.attn)( + self.handle, + layer as i32, + q_row.as_ptr(), + out.as_mut_ptr(), + seq_len as i32, + ) + }, + "attn", + ) + } + + /// Full-vocabulary logits on device. + pub fn logits(&self, hidden: &[f32], out: &mut [f32]) -> Result<(), Qwen3CoderError> { + assert_eq!(hidden.len(), QWEN3_CODER_HIDDEN); + assert_eq!(out.len(), QWEN3_CODER_VOCAB); + // SAFETY: slices outlive the synchronous call. + status( + unsafe { (self.lib.bf16_gemv)(self.handle, hidden.as_ptr(), out.as_mut_ptr()) }, + "bf16_gemv", + ) + } +} + +impl Drop for QwenServeModel { + fn drop(&mut self) { + // SAFETY: handle came from model_create. + unsafe { + (self.lib.free)(self.handle); + } + } +} + +/// Full 48-layer forward with every GEMM on device. Norms, RoPE, attention +/// reduction, and sampling stay on CPU in Phase B1; q/k/v/o, MoE, and the LM +/// head run through the resident serve library. +/// +/// When `profile` is set, per-section milliseconds accumulate into it instead +/// of being discarded: [proj_qkv, attn_cpu, proj_o, moe, norm_misc]. +pub fn forward_token_serve( + weights: &Qwen3CoderWeights, + serve: &QwenServeModel, + token_id: u32, + pos: usize, + state: &mut Qwen3CoderState, + profile: Option<&mut [f64; 5]>, + device_attn: bool, +) -> Result, Qwen3CoderError> { + let h = QWEN3_CODER_HIDDEN; + let qd = QWEN3_CODER_Q_DIM; + let kvd = QWEN3_CODER_KV_DIM; + let hd = QWEN3_CODER_HEAD_DIM; + let eps = QWEN3_CODER_RMS_EPS; + + let token_idx = (token_id as usize) % QWEN3_CODER_VOCAB; + let mut x = weights.embed[token_idx * h..(token_idx + 1) * h].to_vec(); + let mut prof = [0.0f64; 5]; + let want_prof = profile.is_some(); + + for (layer_idx, attn) in weights.attns.iter().enumerate() { + let kv = &mut state.layers[layer_idx]; + + let t = std::time::Instant::now(); + let mut x_norm = vec![0.0f32; h]; + rmsnorm(&x, &attn.input_norm, eps, &mut x_norm); + if want_prof { + prof[4] += t.elapsed().as_secs_f64() * 1000.0; + } + + let t = std::time::Instant::now(); + let mut q = vec![0.0f32; qd]; + let mut k = vec![0.0f32; kvd]; + let mut v = vec![0.0f32; kvd]; + serve.fused_qkv(layer_idx, &x_norm, &mut q, &mut k, &mut v)?; + if want_prof { + prof[0] += t.elapsed().as_secs_f64() * 1000.0; + } + + let t = std::time::Instant::now(); + let mut qn = vec![0.0f32; qd]; + let mut kn = vec![0.0f32; kvd]; + rmsnorm_per_head(&q, &attn.q_norm, eps, QWEN3_CODER_Q_HEADS, hd, &mut qn); + rmsnorm_per_head(&k, &attn.k_norm, eps, QWEN3_CODER_KV_HEADS, hd, &mut kn); + apply_rope( + &mut qn, + &mut kn, + pos, + QWEN3_CODER_Q_HEADS, + QWEN3_CODER_KV_HEADS, + hd, + QWEN3_CODER_ROPE_THETA, + ); + + let mut attn_out = vec![0.0f32; qd]; + // The device and CPU paths keep separate KV caches; mixing them within + // one sequence would attend over a partial history without any error. + let mixed = if device_attn { + !kv.keys.is_empty() + } else { + kv.keys.len() != pos + }; + if mixed { + return Err(Qwen3CoderError::Contract(format!( + "layer {layer_idx}: KV cache mode mismatch at pos {pos} \ + (device_attn={device_attn}, cpu_kv_len={}); use one attention path per sequence", + kv.keys.len() + ))); + } + if device_attn { + serve.kv_append(layer_idx, &kn, &v, pos)?; + serve.attn(layer_idx, &qn, &mut attn_out, pos + 1)?; + } else { + kv.keys.push(kn); + kv.values.push(v); + scaled_dot_product_attention_single( + &qn, + &kv.keys, + &kv.values, + QWEN3_CODER_Q_HEADS, + QWEN3_CODER_KV_HEADS, + hd, + &mut attn_out, + ); + } + + if want_prof { + prof[1] += t.elapsed().as_secs_f64() * 1000.0; + } + + let t = std::time::Instant::now(); + let mut attn_proj = vec![0.0f32; h]; + serve.o_proj(layer_idx, &attn_out, &mut attn_proj)?; + if want_prof { + prof[2] += t.elapsed().as_secs_f64() * 1000.0; + } + + let t = std::time::Instant::now(); + for i in 0..h { + x[i] += attn_proj[i]; + } + + let mut post = vec![0.0f32; h]; + rmsnorm(&x, &attn.post_norm, eps, &mut post); + if want_prof { + prof[4] += t.elapsed().as_secs_f64() * 1000.0; + } + + let t = std::time::Instant::now(); + let post_bf16: Vec = post.iter().map(|&v| f32_to_bf16(v)).collect(); + let mut moe_bf16 = vec![0u16; h]; + serve.moe_layer(layer_idx, &post_bf16, &mut moe_bf16)?; + if want_prof { + prof[3] += t.elapsed().as_secs_f64() * 1000.0; + } + for i in 0..h { + x[i] += bf16_to_f32(moe_bf16[i]); + } + } + + let t = std::time::Instant::now(); + let mut x_final = vec![0.0f32; h]; + rmsnorm(&x, &weights.final_norm, eps, &mut x_final); + if want_prof { + prof[4] += t.elapsed().as_secs_f64() * 1000.0; + } + if let Some(p) = profile { + p.copy_from_slice(&prof); + } + Ok(x_final) +}