Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-sovereign-core-mv/patches/c69dedd8260d917c # aien-sovereign-core-mv AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers ## GitHub aien-dev/aien-sovereign-core-mv#43 (code only) closed derived `c69dedd8260d917c` #43 Imported from GitHub aien-dev/aien-sovereign-core-mv#43 (code only) GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed). Base `bf7d015b5ebaff7501ef8ac4597c5e12a85f1043` · Head `6e2f865ae7720b1b6643920a4afe8952993362ec` ### Apply it ``` git checkout -b patch-c69dedd8260d917c bf7d015b5ebaff7501ef8ac4597c5e12a85f1043 curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/c69dedd8260d917c.patch | git am ``` Raw patch (mbox) · Diff ### Provenance This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record: ``` github-import 1 aien-dev/aien-sovereign-core-mv 43 6e2f865ae7720b1b6643920a4afe8952993362ec ``` ``` {"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":43,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/43","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:37:09Z","metadata":"unavailable","state_derived":true} ``` ### Changes ``` diff --git a/benchmarks/crates/bench_apples_to_apples/src/engine_aien.rs b/benchmarks/crates/bench_apples_to_apples/src/engine_aien.rs index 7f4406bc..46cd38b6 100644 --- a/benchmarks/crates/bench_apples_to_apples/src/engine_aien.rs +++ b/benchmarks/crates/bench_apples_to_apples/src/engine_aien.rs @@ -173,7 +173,8 @@ pub async fn run_aien_concurrency_sweep( concurrency: usize, ) -> Result { eprintln!( - "Executing AIEN (MojoGb10Backend) benchmark at concurrency C={}...", + "Executing AIEN FP32 Native ({}) benchmark at concurrency C={}...", + handle.backend.tensor_backend.name(), concurrency ); @@ -263,7 +264,7 @@ pub async fn run_aien_concurrency_sweep( .unwrap_or_default(); Ok(ConcurrencyRunResult { - engine: "AIEN (MojoGb10Backend)".to_string(), + engine: format!("AIEN FP32 ({})", handle.backend.tensor_backend.name()), concurrency, total_requests: all_results.len(), total_output_tokens, diff --git a/benchmarks/crates/bench_apples_to_apples/src/main.rs b/benchmarks/crates/bench_apples_to_apples/src/main.rs index 2d865110..7ba88c5c 100644 --- a/benchmarks/crates/bench_apples_to_apples/src/main.rs +++ b/benchmarks/crates/bench_apples_to_apples/src/main.rs @@ -88,7 +88,7 @@ async fn main() -> Result<(), Box> { println!(" AIEN SOVEREIGN CORE: NEUTRAL APPLES-TO-APPLES BENCHMARK SUITE (DGX SPARK) "); println!("================================================================================"); println!("Hardware: NVIDIA DGX Spark (GB10 Grace Blackwell, 128 GB Unified LPDDR5x)"); - println!("Model: TinyLlama/TinyLlama-1.1B-Chat-v1.0 (BF16)"); + println!("Model: TinyLlama/TinyLlama-1.1B-Chat-v1.0 (BF16 for MAX/vLLM GPU, FP32 for AIEN Native Reference)"); println!("Workload: 128 input tokens -> 128 output tokens (Greedy, Temp=0.0)"); println!("Engines: {:?}", target_engines); println!("Concurrency levels: {:?}", concurrency_levels); @@ -188,7 +188,7 @@ async fn main() -> Result<(), Box> { benchmark_timestamp: chrono::Utc::now().to_rfc3339(), hardware: "NVIDIA DGX Spark GB10 Grace Blackwell 128GB Unified Memory".to_string(), model_id: "TinyLlama/TinyLlama-1.1B-Chat-v1.0".to_string(), - precision: "BF16".to_string(), + precision: "BF16 (MAX/vLLM GPU) vs FP32 (AIEN Native Reference)".to_string(), prompt_tokens: config.prompt_token_count, target_output_tokens: config.output_token_count, results: all_results, diff --git a/crates/aien-inference-abi/build.rs b/crates/aien-inference-abi/build.rs new file mode 100644 index 00000000..cb4c3677 --- /dev/null +++ b/crates/aien-inference-abi/build.rs @@ -0,0 +1,60 @@ +use std::env; +use std::path::{Path, PathBuf}; +use std::process::Command; + +fn main() { + println!("cargo:rerun-if-changed=cuda/blackwell_gemm.cu"); + println!("cargo:rerun-if-changed=build.rs"); + + let nvcc = PathBuf::from("/usr/local/cuda/bin/nvcc"); + if !nvcc.exists() { + println!("cargo:warning=nvcc not found at /usr/local/cuda/bin/nvcc; Blackwell CUDA backend disabled."); + return; + } + + let out_dir = env::var("OUT_DIR").expect("OUT_DIR not set"); + let out_path = Path::new(&out_dir); + let obj_path = out_path.join("blackwell_gemm.o"); + let lib_path = out_path.join("libblackwell_gemm.a"); + + let cuda_src = "cuda/blackwell_gemm.cu"; + + let status = Command::new(&nvcc) + .args([ + "-c", + "-O3", + "-arch=sm_121", + "-Xcompiler", + "-fPIC", + cuda_src, + "-o", + obj_path.to_str().unwrap(), + ]) + .status() + .expect("Failed to execute nvcc"); + + if !status.success() { + panic!("nvcc compilation of {} failed", cuda_src); + } + + let ar_status = Command::new("ar") + .args([ + "crs", + lib_path.to_str().unwrap(), + obj_path.to_str().unwrap(), + ]) + .status() + .expect("Failed to execute ar"); + + if !ar_status.success() { + panic!("ar archive creation failed"); + } + + println!("cargo:rustc-link-search=native={}", out_dir); + println!("cargo:rustc-link-lib=static=blackwell_gemm"); + println!("cargo:rustc-link-search=native=/usr/local/cuda/lib64"); + println!("cargo:rustc-link-lib=dylib=cublas"); + println!("cargo:rustc-link-lib=dylib=cudart"); + println!("cargo:rustc-link-lib=dylib=stdc++"); + println!("cargo:rustc-cfg=has_blackwell_cuda"); +} diff --git a/crates/aien-inference-abi/cuda/blackwell_gemm.cu b/crates/aien-inference-abi/cuda/blackwell_gemm.cu new file mode 100644 index 00000000..145e7455 --- /dev/null +++ b/crates/aien-inference-abi/cuda/blackwell_gemm.cu @@ -0,0 +1,201 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +static cublasHandle_t g_cublas_handle = NULL; +static cudaStream_t g_cuda_stream = NULL; +static std::recursive_mutex g_backend_mutex; +static std::atomic g_kernel_exec_count{0}; + +// Pre-allocated scratch activation buffers on GB10 device +static float *g_d_a = NULL; +static size_t g_cap_a = 0; +static float *g_d_c = NULL; +static size_t g_cap_c = 0; + +// Device cache for model weight tensors to eliminate per-token HtoD copies +static std::unordered_map g_weight_cache; + +extern "C" { + +int blackwell_gemm_init(void) { + std::lock_guard lock(g_backend_mutex); + if (g_cublas_handle != NULL) { + return 0; + } + + cudaError_t cuda_err = cudaSetDevice(0); + if (cuda_err != cudaSuccess) { + return -1; + } + + cuda_err = cudaStreamCreateWithFlags(&g_cuda_stream, cudaStreamNonBlocking); + if (cuda_err != cudaSuccess) { + return -2; + } + + cublasStatus_t cublas_stat = cublasCreate(&g_cublas_handle); + if (cublas_stat != CUBLAS_STATUS_SUCCESS) { + return -3; + } + + cublas_stat = cublasSetStream(g_cublas_handle, g_cuda_stream); + if (cublas_stat != CUBLAS_STATUS_SUCCESS) { + return -4; + } + + // Pre-allocate initial 16MB scratch buffers for activations + g_cap_a = 2048 * 2048; + cudaMalloc(&g_d_a, g_cap_a * sizeof(float)); + + g_cap_c = 2048 * 2048; + cudaMalloc(&g_d_c, g_cap_c * sizeof(float)); + + return 0; +} + +uint64_t blackwell_gemm_get_kernel_count(void) { + return g_kernel_exec_count.load(std::memory_order_relaxed); +} + +int blackwell_gemm_get_device_name(char *buf, int max_len) { + if (!buf || max_len <= 0) return -1; + cudaDeviceProp prop; + cudaError_t err = cudaGetDeviceProperties(&prop, 0); + if (err != cudaSuccess) return -2; + strncpy(buf, prop.name, max_len - 1); + buf[max_len - 1] = 0; + return 0; +} + +static float* internal_get_cached_weight(const float *h_w, size_t count) { + auto it = g_weight_cache.find(h_w); + if (it != g_weight_cache.end()) { + return it->second; + } + + float *d_w = NULL; + cudaError_t err = cudaMalloc(&d_w, count * sizeof(float)); + if (err != cudaSuccess) { + return NULL; + } + + err = cudaMemcpyAsync(d_w, h_w, count * sizeof(float), cudaMemcpyHostToDevice, g_cuda_stream); + if (err != cudaSuccess) { + cudaFree(d_w); + return NULL; + } + + g_weight_cache[h_w] = d_w; + return d_w; +} + +static float* internal_ensure_scratch_a(size_t count) { + if (count > g_cap_a) { + if (g_d_a) cudaFree(g_d_a); + if (cudaMalloc(&g_d_a, count * sizeof(float)) != cudaSuccess) { + g_cap_a = 0; + return NULL; + } + g_cap_a = count; + } + return g_d_a; +} + +static float* internal_ensure_scratch_c(size_t count) { + if (count > g_cap_c) { + if (g_d_c) cudaFree(g_d_c); + if (cudaMalloc(&g_d_c, count * sizeof(float)) != cudaSuccess) { + g_cap_c = 0; + return NULL; + } + g_cap_c = count; + } + return g_d_c; +} + +int blackwell_gemm_f32(const float *a, const float *b, float *c, int m, int k, int n) { + if (!a || !b || !c || m <= 0 || k <= 0 || n <= 0) { + return -1; + } + + std::lock_guard lock(g_backend_mutex); + if (g_cublas_handle == NULL) { + if (blackwell_gemm_init() != 0) { + return -2; + } + } + + float *d_a = internal_ensure_scratch_a((size_t)m * k); + float *d_c = internal_ensure_scratch_c((size_t)m * n); + float *d_b = internal_get_cached_weight(b, (size_t)n * k); + + if (!d_a || !d_b || !d_c) { + return -3; + } + + cudaError_t err = cudaMemcpyAsync(d_a, a, (size_t)m * k * sizeof(float), cudaMemcpyHostToDevice, g_cuda_stream); + if (err != cudaSuccess) { + return -4; + } + + float alpha = 1.0f; + float beta = 0.0f; + + // Row-major: C [m, n] = A [m, k] * B^T [k, n] (where B is row-major [n, k]) + // Col-major equivalent: C^T [n, m] = B [n, k] * A^T [k, m] + // B as col-major is (k, n), op(B) = CUBLAS_OP_T -> (n, k) + // A as col-major is (k, m), op(A) = CUBLAS_OP_N -> (k, m) + cublasStatus_t stat = cublasSgemm( + g_cublas_handle, + CUBLAS_OP_T, + CUBLAS_OP_N, + n, m, k, + &alpha, + d_b, k, + d_a, k, + &beta, + d_c, n + ); + + if (stat != CUBLAS_STATUS_SUCCESS) { + return -5; + } + + err = cudaMemcpyAsync(c, d_c, (size_t)m * n * sizeof(float), cudaMemcpyDeviceToHost, g_cuda_stream); + if (err != cudaSuccess) { + return -6; + } + + err = cudaStreamSynchronize(g_cuda_stream); + if (err != cudaSuccess) { + return -7; + } + + g_kernel_exec_count.fetch_add(1, std::memory_order_relaxed); + return 0; +} + +int blackwell_gemv_f32(const float *x, const float *weight, float *out, int in_dim, int out_dim) { + return blackwell_gemm_f32(x, weight, out, 1, in_dim, out_dim); +} + +void blackwell_gemm_destroy(void) { + std::lock_guard lock(g_backend_mutex); + for (auto &pair : g_weight_cache) { + if (pair.second) cudaFree(pair.second); + } + g_weight_cache.clear(); + + if (g_d_a) { cudaFree(g_d_a); g_d_a = NULL; g_cap_a = 0; } + if (g_d_c) { cudaFree(g_d_c); g_d_c = NULL; g_cap_c = 0; } + if (g_cublas_handle) { cublasDestroy(g_cublas_handle); g_cublas_handle = NULL; } + if (g_cuda_stream) { cudaStreamDestroy(g_cuda_stream); g_cuda_stream = NULL; } +} + +} diff --git a/crates/aien-inference-abi/examples/profile_blackwell_ops.rs b/crates/aien-inference-abi/examples/profile_blackwell_ops.rs new file mode 100644 index 00000000..f63f3795 --- /dev/null +++ b/crates/aien-inference-abi/examples/profile_blackwell_ops.rs @@ -0,0 +1,239 @@ +use aien_inference_abi::backend::TensorBackend; +use aien_inference_abi::blackwell_backend::BlackwellGb10Backend; +use aien_inference_abi::weights::{LayerKvCache, SequenceState, TransformerWeights}; +use aien_inference_abi::ModelConfig; +use std::time::Instant; + +fn main() { + println!("=== AIEN NATIVE TRANSFORMER PER-OP PROFILE ON DGX SPARK ==="); + let model_config = ModelConfig { + model_id: "TinyLlama/TinyLlama-1.1B-Chat-v1.0".to_string(), + max_sequence_length: 2048, + block_size: 16, + num_layers: 22, + num_heads: 32, + head_dim: 64, + num_kv_heads: 4, + hidden_dim: 2048, + intermediate_dim: 5632, + vocab_size: 32000, + rms_norm_eps: 1e-5, + rope_theta: 10000.0, + }; + + let safetensors_path = "/home/drakestapleton/.cache/huggingface/hub/models--TinyLlama--TinyLlama-1.1B-Chat-v1.0/snapshots/fe8a4ea1ffedaf415f4da2f062534de366a451e6/model.safetensors"; + let weights = TransformerWeights::load_from_safetensors(safetensors_path, &model_config) + .expect("Failed to load safetensors"); + + let backend = BlackwellGb10Backend::new(); + println!("Using Backend: {}", backend.name()); + + let hidden_dim = model_config.hidden_dim; + let intermediate_dim = model_config.intermediate_dim; + let vocab_size = model_config.vocab_size; + let num_heads = model_config.num_heads; + let num_kv_heads = model_config.num_kv_heads; + let head_dim = model_config.head_dim; + let q_dim = num_heads * head_dim; + let kv_dim = num_kv_heads * head_dim; + let eps = model_config.rms_norm_eps; + let theta = model_config.rope_theta; + + // Simulate seq_len = 128 (decode step 128) + let seq_len = 128; + let mut seq_state = SequenceState { + tokens: vec![1u32; seq_len], + layers: vec![LayerKvCache { + cached_k: vec![vec![0.01f32; kv_dim]; seq_len], + cached_v: vec![vec![0.01f32; kv_dim]; seq_len], + flat_k: vec![0.01f32; seq_len * kv_dim], + flat_v: vec![0.01f32; seq_len * kv_dim], + }; 22], + }; + + let warmup_iters = 2; + let bench_iters = 5; + + // Accumulators in microseconds + let mut time_rmsnorm_input_us = 0u128; + let mut time_qkv_gemm_us = 0u128; + let mut time_rope_us = 0u128; + let mut time_kv_flatten_us = 0u128; + let mut time_gqa_attn_us = 0u128; + let mut time_oproj_gemm_us = 0u128; + let mut time_rmsnorm_post_us = 0u128; + let mut time_mlp_gate_up_us = 0u128; + let mut time_swiglu_us = 0u128; + let mut time_mlp_down_us = 0u128; + let mut time_rmsnorm_final_us = 0u128; + let mut time_lm_head_us = 0u128; + let mut time_alloc_overhead_us = 0u128; + let mut total_token_us = 0u128; + + for iter in 0..(warmup_iters + bench_iters) { + let is_bench = iter >= warmup_iters; + let t_token_start = Instant::now(); + + // 1. Embedding lookup + let mut x = vec![0.01f32; hidden_dim]; + + for (layer_idx, layer_w) in weights.layers.iter().enumerate() { + let kv_cache = &mut seq_state.layers[layer_idx]; + + // Allocation timing + let t_alloc = Instant::now(); + let mut x_norm = vec![0.0f32; hidden_dim]; + let mut q = vec![0.0f32; q_dim]; + let mut k = vec![0.0f32; kv_dim]; + let mut v = vec![0.0f32; kv_dim]; + let mut attn_out = vec![0.0f32; q_dim]; + let mut attn_proj = vec![0.0f32; hidden_dim]; + let mut post_norm = vec![0.0f32; hidden_dim]; + let mut gate = vec![0.0f32; intermediate_dim]; + let mut up = vec![0.0f32; intermediate_dim]; + let mut activated = vec![0.0f32; intermediate_dim]; + let mut mlp_out = vec![0.0f32; hidden_dim]; + let alloc_elapsed = t_alloc.elapsed().as_micros(); + if is_bench { + time_alloc_overhead_us += alloc_elapsed; + } + + // Input RMSNorm + let t0 = Instant::now(); + backend.rmsnorm(&mut x_norm, &x, &layer_w.input_layernorm, eps); + if is_bench { + time_rmsnorm_input_us += t0.elapsed().as_micros(); + } + + // QKV GEMVs + let t0 = Instant::now(); + backend.matmul_vec(&mut q, &x_norm, &layer_w.q_proj, q_dim, hidden_dim); + backend.matmul_vec(&mut k, &x_norm, &layer_w.k_proj, kv_dim, hidden_dim); + backend.matmul_vec(&mut v, &x_norm, &layer_w.v_proj, kv_dim, hidden_dim); + if is_bench { + time_qkv_gemm_us += t0.elapsed().as_micros(); + } + + // RoPE + let t0 = Instant::now(); + backend.apply_rope(&mut q, &mut k, seq_len, head_dim, num_heads, num_kv_heads, theta); + if is_bench { + time_rope_us += t0.elapsed().as_micros(); + } + + // KV flatten & append + let t0 = Instant::now(); + let mut flat_k = Vec::with_capacity(seq_len * kv_dim); + let mut flat_v = Vec::with_capacity(seq_len * kv_dim); + for t in 0..seq_len { + flat_k.extend_from_slice(&kv_cache.cached_k[t]); + flat_v.extend_from_slice(&kv_cache.cached_v[t]); + } + if is_bench { + time_kv_flatten_us += t0.elapsed().as_micros(); + } + + // GQA Attention + let t0 = Instant::now(); + backend.gqa_attention(&mut attn_out, &q, &flat_k, &flat_v, seq_len, num_heads, num_kv_heads, head_dim); + if is_bench { + time_gqa_attn_us += t0.elapsed().as_micros(); + } + + // O-proj + let t0 = Instant::now(); + backend.matmul_vec(&mut attn_proj, &attn_out, &layer_w.o_proj, hidden_dim, q_dim); + for i in 0..hidden_dim { + x[i] += attn_proj[i]; + } + if is_bench { + time_oproj_gemm_us += t0.elapsed().as_micros(); + } + + // Post RMSNorm + let t0 = Instant::now(); + backend.rmsnorm(&mut post_norm, &x, &layer_w.post_attention_layernorm, eps); + if is_bench { + time_rmsnorm_post_us += t0.elapsed().as_micros(); + } + + // MLP Gate & Up + let t0 = Instant::now(); + backend.matmul_vec(&mut gate, &post_norm, &layer_w.gate_proj, intermediate_dim, hidden_dim); + backend.matmul_vec(&mut up, &post_norm, &layer_w.up_proj, intermediate_dim, hidden_dim); + if is_bench { + time_mlp_gate_up_us += t0.elapsed().as_micros(); + } + + // SwiGLU + let t0 = Instant::now(); + backend.swiglu(&mut activated, &gate, &up); + if is_bench { + time_swiglu_us += t0.elapsed().as_micros(); + } + + // MLP Down + let t0 = Instant::now(); + backend.matmul_vec(&mut mlp_out, &activated, &layer_w.down_proj, hidden_dim, intermediate_dim); + for i in 0..hidden_dim { + x[i] += mlp_out[i]; + } + if is_bench { + time_mlp_down_us += t0.elapsed().as_micros(); + } + } + + // Final RMSNorm + let mut x_final = vec![0.0f32; hidden_dim]; + let t0 = Instant::now(); + backend.rmsnorm(&mut x_final, &x, &weights.final_norm, eps); + if is_bench { + time_rmsnorm_final_us += t0.elapsed().as_micros(); + } + + // LM Head + let mut logits = vec![0.0f32; vocab_size]; + let t0 = Instant::now(); + backend.compute_logits(&mut logits, &x_final, &weights.lm_head, vocab_size, hidden_dim); + if is_bench { + time_lm_head_us += t0.elapsed().as_micros(); + } + + let elapsed = t_token_start.elapsed().as_micros(); + if is_bench { + total_token_us += elapsed; + } + } + + let n = bench_iters as f64; + println!("\n--- PER-TOKEN DECODE WALL TIME BREAKDOWN (Avg over {} iters, seq_len={}) ---", bench_iters, seq_len); + let ms = |us: u128| (us as f64) / (n * 1000.0); + let total_ms = ms(total_token_us); + + let row = |name: &str, us: u128| { + let val_ms = ms(us); + let pct = (val_ms / total_ms) * 100.0; + println!("{:<32} | {:>8.2} ms | {:>6.2} %", name, val_ms, pct); + }; + + println!("{:<32} | {:>11} | {:>8}", "Operation", "Wall Time", "Share"); + println!("{:-<32}-+-{:-<11}-+-{:-<8}", "", "", ""); + row("Input RMSNorm (22 layers)", time_rmsnorm_input_us); + row("QKV GEMVs (22 layers)", time_qkv_gemm_us); + row("RoPE (22 layers)", time_rope_us); + row("KV Flattening (22 layers)", time_kv_flatten_us); + row("GQA Attention (22 layers)", time_gqa_attn_us); + row("O-proj GEMV (22 layers)", time_oproj_gemm_us); + row("Post RMSNorm (22 layers)", time_rmsnorm_post_us); + row("MLP Gate+Up GEMVs (22 layers)", time_mlp_gate_up_us); + row("SwiGLU Activation (22 layers)", time_swiglu_us); + row("MLP Down GEMV (22 layers)", time_mlp_down_us); + row("Final RMSNorm (1 layer)", time_rmsnorm_final_us); + row("LM Head GEMV (32k vocab)", time_lm_head_us); + row("Heap Allocation / Buffers", time_alloc_overhead_us); + println!("{:-<32}-+-{:-<11}-+-{:-<8}", "", "", ""); + println!("{:<32} | {:>8.2} ms | 100.00 %", "Total Single-Token Decode", total_ms); + println!("Theoretical Decode Throughput: {:.2} tokens/sec", 1000.0 / total_ms); + println!("Blackwell GPU Kernel Launches: {}", backend.kernel_exec_count()); + println!("CPU Fallback Executions: {}", backend.fallback_count()); +} diff --git a/crates/aien-inference-abi/src/blackwell_backend.rs b/crates/aien-inference-abi/src/blackwell_backend.rs new file mode 100644 index 00000000..34468919 --- /dev/null +++ b/crates/aien-inference-abi/src/blackwell_backend.rs @@ -0,0 +1,297 @@ +//! Genuine Blackwell GB10 Hardware Acceleration Backend for DGX Spark. +//! Dispatches single-token GEMV and batched GEMM directly to cuBLAS 13 on Blackwell sm_121. + +use crate::backend::{ReferenceCpuBackend, TensorBackend}; +use std::ffi::CStr; +use std::os::raw::{c_char, c_float, c_int}; +use std::sync::atomic::{AtomicU64, Ordering}; + +extern "C" { + fn blackwell_gemm_init() -> c_int; + fn blackwell_gemm_get_kernel_count() -> u64; + fn blackwell_gemm_get_device_name(buf: *mut c_char, max_len: c_int) -> c_int; + fn blackwell_gemm_f32( + a: *const c_float, + b: *const c_float, + c: *mut c_float, + m: c_int, + k: c_int, + n: c_int, + ) -> c_int; + fn blackwell_gemv_f32( + x: *const c_float, + weight: *const c_float, + out: *mut c_float, + in_dim: c_int, + out_dim: c_int, + ) -> c_int; + fn blackwell_gemm_destroy(); +} + +/// Blackwell GB10 GPU Tensor Backend. +/// Executes GEMV and batched GEMM operations on the NVIDIA GB10 Blackwell GPU. +pub struct BlackwellGb10Backend { + fallback: ReferenceCpuBackend, + device_name: String, + available: bool, + fallback_counter: AtomicU64, +} + +impl BlackwellGb10Backend { + pub fn new() -> Self { + let mut available = false; + let mut device_name = "Unknown".to_string(); + + unsafe { + if blackwell_gemm_init() == 0 { + let mut buf = [0 as c_char; 256]; + if blackwell_gemm_get_device_name(buf.as_mut_ptr(), 256) == 0 { + let c_str = CStr::from_ptr(buf.as_ptr()); + if let Ok(s) = c_str.to_str() { + device_name = s.to_string(); + available = true; + } + } + } + } + + if available { + eprintln!( + "BlackwellGb10Backend: Successfully bound to device '{}' (sm_121 cuBLAS 13)", + device_name + ); + } else { + eprintln!("BlackwellGb10Backend: Hardware initialization failed, using CPU fallback"); + } + + Self { + fallback: ReferenceCpuBackend::new(), + device_name, + available, + fallback_counter: AtomicU64::new(0), + } + } + + pub fn is_available(&self) -> bool { + self.available + } + + pub fn device_name(&self) -> &str { + &self.device_name + } + + pub fn kernel_exec_count(&self) -> u64 { + if self.available { + unsafe { blackwell_gemm_get_kernel_count() } + } else { + 0 + } + } + + pub fn fallback_count(&self) -> u64 { + self.fallback_counter.load(Ordering::Relaxed) + } +} + +impl Default for BlackwellGb10Backend { + fn default() -> Self { + Self::new() + } +} + +impl Drop for BlackwellGb10Backend { + fn drop(&mut self) { + if self.available { + unsafe { + blackwell_gemm_destroy(); + } + } + } +} + +impl TensorBackend for BlackwellGb10Backend { + fn name(&self) -> &'static str { + if self.available { + "BlackwellGb10Backend (NVIDIA GB10 sm_121 cuBLAS)" + } else { + "BlackwellGb10Backend (FallbackCpu)" + } + } + + fn rmsnorm(&self, out: &mut [f32], x: &[f32], weight: &[f32], eps: f32) { + self.fallback.rmsnorm(out, x, weight, eps); + } + + fn apply_rope( + &self, + q: &mut [f32], + k: &mut [f32], + pos: usize, + head_dim: usize, + num_q_heads: usize, + num_kv_heads: usize, + theta: f32, + ) { + self.fallback + .apply_rope(q, k, pos, head_dim, num_q_heads, num_kv_heads, theta); + } + + fn matmul_vec( + &self, + out: &mut [f32], + x: &[f32], + weight: &[f32], + out_dim: usize, + in_dim: usize, + ) { + if self.available { + let res = unsafe { + blackwell_gemv_f32( + x.as_ptr(), + weight.as_ptr(), + out.as_mut_ptr(), + in_dim as c_int, + out_dim as c_int, + ) + }; + if res == 0 { + return; + } + self.fallback_counter.fetch_add(1, Ordering::Relaxed); + } + self.fallback.matmul_vec(out, x, weight, out_dim, in_dim); + } + + fn matmul_batch( + &self, + out: &mut [f32], + x: &[f32], + weight: &[f32], + batch_size: usize, + in_dim: usize, + out_dim: usize, + ) { + if self.available { + let res = unsafe { + blackwell_gemm_f32( + x.as_ptr(), + weight.as_ptr(), + out.as_mut_ptr(), + batch_size as c_int, + in_dim as c_int, + out_dim as c_int, + ) + }; + if res == 0 { + return; + } + self.fallback_counter.fetch_add(1, Ordering::Relaxed); + } + crate::tensor::matmul_batch(x, weight, out, batch_size, in_dim, out_dim); + } + + fn swiglu(&self, out: &mut [f32], gate: &[f32], up: &[f32]) { + self.fallback.swiglu(out, gate, up); + } + + fn gqa_attention( + &self, + out: &mut [f32], + q: &[f32], + k_cache: &[f32], + v_cache: &[f32], + seq_len: usize, + num_q_heads: usize, + num_kv_heads: usize, + head_dim: usize, + ) { + self.fallback + .gqa_attention(out, q, k_cache, v_cache, seq_len, num_q_heads, num_kv_heads, head_dim); + } + + fn compute_logits( + &self, + logits: &mut [f32], + hidden: &[f32], + embed_weight: &[f32], + vocab_size: usize, + hidden_dim: usize, + ) { + if self.available { + let res = unsafe { + blackwell_gemv_f32( + hidden.as_ptr(), + embed_weight.as_ptr(), + logits.as_mut_ptr(), + hidden_dim as c_int, + vocab_size as c_int, + ) + }; + if res == 0 { + return; + } + self.fallback_counter.fetch_add(1, Ordering::Relaxed); + } + self.fallback + .compute_logits(logits, hidden, embed_weight, vocab_size, hidden_dim); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_blackwell_backend_creation() { + let backend = BlackwellGb10Backend::new(); + assert!(backend.name().starts_with("BlackwellGb10Backend")); + if backend.is_available() { + assert!(backend.device_name().contains("GB10") || !backend.device_name().is_empty()); + } + } + + #[test] + fn test_blackwell_gemm_parity_with_cpu() { + let gpu_backend = BlackwellGb10Backend::new(); + let cpu_backend = ReferenceCpuBackend::new(); + + if !gpu_backend.is_available() { + eprintln!("Skipping GPU test: Blackwell hardware not available"); + return; + } + + let m = 16; + let k = 128; + let n = 128; + + let mut a = vec![0.0f32; m * k]; + let mut b = vec![0.0f32; n * k]; + for i in 0..a.len() { + a[i] = (i % 37) as f32 * 0.05; + } + for i in 0..b.len() { + b[i] = ((i + 13) % 43) as f32 * 0.05; + } + + let mut c_gpu = vec![0.0f32; m * n]; + let mut c_cpu = vec![0.0f32; m * n]; + + gpu_backend.matmul_batch(&mut c_gpu, &a, &b, m, k, n); + cpu_backend.matmul_batch(&mut c_cpu, &a, &b, m, k, n); + + let mut max_diff = 0.0f32; + for i in 0..c_gpu.len() { + let diff = (c_gpu[i] - c_cpu[i]).abs(); + if diff > max_diff { + max_diff = diff; + } + } + + assert!( + max_diff < 1e-3, + "Blackwell GEMM diverged from CPU: max_diff = {}", + max_diff + ); + assert!(gpu_backend.kernel_exec_count() > 0); + } +} diff --git a/crates/aien-inference-abi/src/lib.rs b/crates/aien-inference-abi/src/lib.rs index bded087b..0784ea05 100644 --- a/crates/aien-inference-abi/src/lib.rs +++ b/crates/aien-inference-abi/src/lib.rs @@ -3,6 +3,7 @@ use serde::{Deserialize, Serialize}; use std::collections::HashMap; pub mod backend; +pub mod blackwell_backend; pub mod checkpoint; pub mod mojo_backend; pub mod tensor; @@ -11,6 +12,7 @@ pub mod transformer_backend; pub mod weights; pub use backend::*; +pub use blackwell_backend::*; pub use checkpoint::*; pub use mojo_backend::*; pub use tensor::*; diff --git a/crates/aien-inference-abi/src/mojo_backend.rs b/crates/aien-inference-abi/src/mojo_backend.rs index f0b4a2c6..18a4f82c 100644 --- a/crates/aien-inference-abi/src/mojo_backend.rs +++ b/crates/aien-inference-abi/src/mojo_backend.rs @@ -205,13 +205,12 @@ impl Default for MojoGb10Backend { } } +/// Type alias for honest architectural labeling of current multi-core CPU backend. +pub type NativeCpuBackend = MojoGb10Backend; + impl TensorBackend for MojoGb10Backend { fn name(&self) -> &'static str { - if self.bindings.is_some() { - "MojoGb10Backend(Accelerated)" - } else { - "MojoGb10Backend(FallbackCpu)" - } + "NativeCpuBackend (Rayon Multi-Core)" } fn rmsnorm(&self, out: &mut [f32], x: &[f32], weight: &[f32], eps: f32) { @@ -353,7 +352,7 @@ mod tests { #[test] fn test_mojo_backend_creation_and_name() { let backend = MojoGb10Backend::new(); - assert!(backend.name().starts_with("MojoGb10Backend")); + assert_eq!(backend.name(), "NativeCpuBackend (Rayon Multi-Core)"); } #[test] diff --git a/crates/aien-inference-abi/src/transformer_backend.rs b/crates/aien-inference-abi/src/transformer_backend.rs index ed8a19d8..b545e8a9 100644 --- a/crates/aien-inference-abi/src/transformer_backend.rs +++ b/crates/aien-inference-abi/src/transformer_backend.rs @@ -2,6 +2,7 @@ //! Dispatches tensor math through the decoupled TensorBackend trait for CPU and Mojo/GB10 execution. use crate::backend::{ReferenceCpuBackend, TensorBackend}; +use crate::blackwell_backend::BlackwellGb10Backend; use crate::mojo_backend::MojoGb10Backend; use crate::tensor::{sample_argmax, sample_temperature}; use crate::weights::{LayerKvCache, SequenceState, TransformerWeights}; @@ -61,6 +62,17 @@ impl NativeTransformerBackend { Self::new_mojo(weights) } + /// Explicit constructor for genuine Blackwell GB10 GPU accelerated backend (sm_121 cuBLAS). + pub fn new_blackwell(weights: TransformerWeights) -> Self { + Self::with_backend(weights, Arc::new(BlackwellGb10Backend::new())) + } + + /// Convenience constructor with deterministic reference weights and BlackwellGb10Backend. + pub fn with_blackwell_backend(config: &ModelConfig) -> Self { + let weights = TransformerWeights::reference_test_weights(config); + Self::new_blackwell(weights) + } + /// Implementation helper executing forward pass on disjoint struct fields. pub fn forward_token_impl( weights: &TransformerWeights, @@ -477,7 +489,10 @@ mod tests { assert_eq!(cpu_backend.tensor_backend.name(), "ReferenceCpuBackend"); let mojo_backend = NativeTransformerBackend::with_mojo_backend(&config); - assert!(mojo_backend.tensor_backend.name().starts_with("MojoGb10Backend")); + assert!(mojo_backend.tensor_backend.name().starts_with("NativeCpuBackend")); + + let blackwell_backend = NativeTransformerBackend::with_blackwell_backend(&config); + assert!(blackwell_backend.tensor_backend.name().starts_with("BlackwellGb10Backend")); } #[test] diff --git a/crates/aien-inference-abi/tests/transformer_parity.rs b/crates/aien-inference-abi/tests/transformer_parity.rs index 68fd4366..8aeb0d4d 100644 --- a/crates/aien-inference-abi/tests/transformer_parity.rs +++ b/crates/aien-inference-abi/tests/transformer_parity.rs @@ -203,3 +203,91 @@ fn test_safetensors_bytes_parser() { assert!((weights.final_norm[1] - 0.1).abs() < 1e-6); assert!((weights.final_norm[10] - 1.0).abs() < 1e-6); } + +#[tokio::test] +async fn test_blackwell_vs_reference_cpu_autoregressive_parity() { + let config = test_model_config(); + let mut cpu_backend = NativeTransformerBackend::with_reference_weights(&config); + let mut gpu_backend = NativeTransformerBackend::with_blackwell_backend(&config); + + let prompt = vec![7u32, 19u32, 42u32, 108u32]; + let req_cpu = SequenceRequest { + request_id: 3001, + prompt_tokens: prompt.clone(), + sampling_params: SamplingParams { + temperature: 0.0, + top_p: 1.0, + max_tokens: 16, + stop_token_ids: vec![0], + }, + arrival_time_ns: 0, + priority: 1, + }; + let req_gpu = SequenceRequest { + request_id: 3001, + prompt_tokens: prompt.clone(), + sampling_params: SamplingParams { + temperature: 0.0, + top_p: 1.0, + max_tokens: 16, + stop_token_ids: vec![0], + }, + arrival_time_ns: 0, + priority: 1, + }; + + let mut batch_cpu = ScheduledBatch { + prefill_requests: vec![req_cpu], + decode_requests: Vec::new(), + block_tables: { + let mut m = HashMap::new(); + m.insert(3001, vec![0, 1]); + m + }, + step_id: 1, + }; + let mut batch_gpu = ScheduledBatch { + prefill_requests: vec![req_gpu], + decode_requests: Vec::new(), + block_tables: { + let mut m = HashMap::new(); + m.insert(3001, vec![0, 1]); + m + }, + step_id: 1, + }; + + let mut cpu_tokens = Vec::new(); + let mut gpu_tokens = Vec::new(); + + let (out_cpu, _) = cpu_backend.execute_step(&batch_cpu).await.unwrap(); + let (out_gpu, _) = gpu_backend.execute_step(&batch_gpu).await.unwrap(); + + if let (DecodeOutput::Token { token_id: t_cpu, .. }, DecodeOutput::Token { token_id: t_gpu, .. }) = (&out_cpu[0], &out_gpu[0]) { + assert_eq!(t_cpu, t_gpu, "Prefill first token mismatch between CPU and Blackwell GPU"); + cpu_tokens.push(*t_cpu); + gpu_tokens.push(*t_gpu); + } + + for step in 2..=8 { + batch_cpu.prefill_requests.clear(); + batch_cpu.decode_requests = vec![3001]; + batch_cpu.step_id = step; + + batch_gpu.prefill_requests.clear(); + batch_gpu.decode_requests = vec![3001]; + batch_gpu.step_id = step; + + let (step_out_cpu, _) = cpu_backend.execute_step(&batch_cpu).await.unwrap(); + let (step_out_gpu, _) = gpu_backend.execute_step(&batch_gpu).await.unwrap(); + + if let (DecodeOutput::Token { token_id: t_cpu, .. }, DecodeOutput::Token { token_id: t_gpu, .. }) = (&step_out_cpu[0], &step_out_gpu[0]) { + assert_eq!(t_cpu, t_gpu, "Decode step {} token mismatch: CPU={}, GPU={}", step, t_cpu, t_gpu); + cpu_tokens.push(*t_cpu); + gpu_tokens.push(*t_gpu); + } + } + + assert_eq!(cpu_tokens, gpu_tokens, "Autoregressive generation must match bitwise between CPU and Blackwell GPU"); + println!("Parity verified over {} tokens: {:?}", cpu_tokens.len(), cpu_tokens); +} ```