diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index fbed7a0f..98cdb72b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -43,6 +43,12 @@ jobs: AIEN_DEV_FALLBACK: "1" run: cargo test --workspace --verbose -- --test-threads=1 + - name: Zero-CUDA Gate (aien-cli links no NVIDIA CUDA library or symbol) + run: | + bash scripts/zero-cuda-gate.sh --self-test + cargo build -p aien-cli + bash scripts/zero-cuda-gate.sh target/debug/aien-cli + - name: Verify Preflight Branch Guard (both contexts) run: bash scripts/test-preflight-branch-guard.sh diff --git a/crates/aien-cli/src/commands.rs b/crates/aien-cli/src/commands.rs index 3f61b3dd..d6f6e248 100644 --- a/crates/aien-cli/src/commands.rs +++ b/crates/aien-cli/src/commands.rs @@ -1111,9 +1111,9 @@ fn resolve_daemon_manifest_with(policy: &CheckpointPolicy) -> DaemonModelManifes } /// Builds the native transformer backend for daemon boot with explicit fallback. -/// Prefers Blackwell hardware when available, falls back to CPU reference math. +/// Uses the native Omega GPU engine when linked, falls back to CPU reference math. /// Never returns the Mock backend: output always comes from real forward passes. -/// When AIEN_REQUIRE_BLACKWELL is set, a missing Blackwell device is fatal: +/// When AIEN_REQUIRE_BLACKWELL (or AIEN_GPU_BACKEND=omega) is set, a missing GPU engine is fatal: /// the hardware gate must fail when fallback count is nonzero. fn reference_config() -> aien_inference_abi::ModelConfig { aien_inference_abi::ModelConfig { @@ -1306,44 +1306,29 @@ fn build_native_daemon_backend() -> Result { label: model_label, .. } = load_daemon_model(manifest, policy.require_checkpoint)?; - if aien_inference_abi::omega_backend_selected() { - let omega = aien_inference_abi::OmegaGb10Backend::new(); - if omega.is_available() { - let name = aien_inference_abi::TensorBackend::name(&omega).to_string(); - let tensor_backend: std::sync::Arc = - std::sync::Arc::new(omega); - return Ok(( - weights, - tensor_backend, - format!("NativeTransformerBackend/{name}"), - model_label, - tokenizer, - )); - } - return Err( - "AIEN_GPU_BACKEND=omega is set but the Omega GPU engine is not linked (stub build)" - .to_string(), - ); - } - let probe = aien_inference_abi::BlackwellGb10Backend::new(); - let require_blackwell = std::env::var("AIEN_REQUIRE_BLACKWELL") - .map(|v| v.trim() == "1" || v.trim().eq_ignore_ascii_case("true")) - .unwrap_or(false); - if probe.is_available() { - let device = probe.device_name().to_string(); - drop(probe); + // FB-1 cut 6: the native Omega engine is the only GPU backend (no CUDA). The env names + // AIEN_REQUIRE_BLACKWELL (the GB10 chip, campaign spec) and AIEN_GPU_BACKEND=omega both + // make a missing engine fatal instead of falling back to CPU reference math. + let require_gpu = aien_inference_abi::omega_backend_selected() + || std::env::var("AIEN_REQUIRE_BLACKWELL") + .map(|v| v.trim() == "1" || v.trim().eq_ignore_ascii_case("true")) + .unwrap_or(false); + let omega = aien_inference_abi::OmegaGb10Backend::new(); + if omega.is_available() { + let name = aien_inference_abi::TensorBackend::name(&omega).to_string(); let tensor_backend: std::sync::Arc = - std::sync::Arc::new(aien_inference_abi::BlackwellGb10Backend::new()); + std::sync::Arc::new(omega); Ok(( weights, tensor_backend, - format!("NativeTransformerBackend/Blackwell ({})", device), + format!("NativeTransformerBackend/{name}"), model_label, tokenizer, )) - } else if require_blackwell { + } else if require_gpu { Err( - "AIEN_REQUIRE_BLACKWELL is set but no Blackwell device initialized (fallback count nonzero)".to_string(), + "the GB10 GPU is required (AIEN_REQUIRE_BLACKWELL or AIEN_GPU_BACKEND=omega) but the Omega GPU engine is not linked (stub build)" + .to_string(), ) } else { let tensor_backend: std::sync::Arc = @@ -1351,7 +1336,7 @@ fn build_native_daemon_backend() -> Result { Ok(( weights, tensor_backend, - "NativeTransformerBackend/CPU-reference (Blackwell unavailable, explicit fallback)" + "NativeTransformerBackend/CPU-reference (Omega GPU engine not linked, explicit fallback)" .to_string(), model_label, tokenizer, diff --git a/crates/aien-inference-abi/build.rs b/crates/aien-inference-abi/build.rs deleted file mode 100644 index 199439aa..00000000 --- a/crates/aien-inference-abi/build.rs +++ /dev/null @@ -1,103 +0,0 @@ -use std::env; -use std::path::{Path, PathBuf}; -use std::process::Command; - -fn main() { - println!("cargo:rustc-check-cfg=cfg(has_blackwell_cuda)"); - println!("cargo:rerun-if-env-changed=AIEN_FORCE_CPU_STUB"); - println!("cargo:rerun-if-changed=cuda/blackwell_gemm.cu"); - println!("cargo:rerun-if-changed=cuda/paged_attention_bf16.cu"); - println!("cargo:rerun-if-changed=cuda/blackwell_layer.cu"); - println!("cargo:rerun-if-changed=cuda/tensor_abi.h"); - println!("cargo:rerun-if-changed=build.rs"); - - let nvcc = PathBuf::from("/usr/local/cuda/bin/nvcc"); - if !nvcc.exists() || env::var("AIEN_FORCE_CPU_STUB").is_ok() { - println!("cargo:warning=nvcc not found or AIEN_FORCE_CPU_STUB set; 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 gemm_obj_path = out_path.join("blackwell_gemm.o"); - let attn_obj_path = out_path.join("paged_attention_bf16.o"); - let layer_obj_path = out_path.join("blackwell_layer.o"); - let lib_path = out_path.join("libblackwell_gemm.a"); - - let status = Command::new(&nvcc) - .args([ - "-c", - "-O3", - "-arch=sm_121", - "-Xcompiler", - "-fPIC", - "cuda/blackwell_gemm.cu", - "-o", - gemm_obj_path.to_str().unwrap(), - ]) - .status() - .expect("Failed to execute nvcc for blackwell_gemm.cu"); - - if !status.success() { - panic!("nvcc compilation of cuda/blackwell_gemm.cu failed"); - } - - let status2 = Command::new(&nvcc) - .args([ - "-c", - "-O3", - "-arch=sm_121", - "-Xcompiler", - "-fPIC", - "cuda/paged_attention_bf16.cu", - "-o", - attn_obj_path.to_str().unwrap(), - ]) - .status() - .expect("Failed to execute nvcc for paged_attention_bf16.cu"); - - if !status2.success() { - panic!("nvcc compilation of cuda/paged_attention_bf16.cu failed"); - } - - let status3 = Command::new(&nvcc) - .args([ - "-c", - "-O3", - "-arch=sm_121", - "-Xcompiler", - "-fPIC", - "cuda/blackwell_layer.cu", - "-o", - layer_obj_path.to_str().unwrap(), - ]) - .status() - .expect("Failed to execute nvcc for blackwell_layer.cu"); - - if !status3.success() { - panic!("nvcc compilation of cuda/blackwell_layer.cu failed"); - } - - let ar_status = Command::new("ar") - .args([ - "crs", - lib_path.to_str().unwrap(), - gemm_obj_path.to_str().unwrap(), - attn_obj_path.to_str().unwrap(), - layer_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 deleted file mode 100644 index 8e196fb3..00000000 --- a/crates/aien-inference-abi/cuda/blackwell_gemm.cu +++ /dev/null @@ -1,222 +0,0 @@ -#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; -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); - -void* blackwell_get_stream(void) { if (!g_cuda_stream) blackwell_gemm_init(); return (void*)g_cuda_stream; } -void* blackwell_get_cublas_handle(void) { if (!g_cublas_handle) blackwell_gemm_init(); return (void*)g_cublas_handle; } - -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) { - fprintf(stderr, "BlackwellGb10Backend init: cudaSetDevice(0) failed (%d: %s); clear unified memory pressure via vm.drop_caches=3\n", (int)cuda_err, cudaGetErrorString(cuda_err)); - 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_allocate_managed(size_t bytes) { - void* ptr = NULL; - cudaError_t err = cudaMallocManaged(&ptr, bytes, cudaMemAttachGlobal); - if (err != cudaSuccess) { - return NULL; - } - return ptr; -} - -void blackwell_free_managed(void* ptr) { - if (ptr != NULL) { - cudaFree(ptr); - } -} - -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/cuda/blackwell_layer.cu b/crates/aien-inference-abi/cuda/blackwell_layer.cu deleted file mode 100644 index a06218e7..00000000 --- a/crates/aien-inference-abi/cuda/blackwell_layer.cu +++ /dev/null @@ -1,1118 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include "tensor_abi.h" - -extern std::atomic g_kernel_exec_count; - -// Canonical physical KV layout descriptor matching Rust KvLayoutDesc -struct KvLayoutDesc { - uint64_t block_stride_bytes; - uint64_t layer_stride_bytes; - uint64_t kv_plane_stride_bytes; - uint64_t token_stride_bytes; - uint64_t head_stride_bytes; - - uint64_t pool_bytes; - uint32_t num_blocks; - uint32_t num_layers; - uint32_t block_size; -}; - -// Resident Layer Weights on GPU -struct BlackwellResidentLayerWeights { - ResidentTensor d_norm1; // [hidden_dim] - ResidentTensor d_w_qkv; // [q_dim + 2 * kv_dim, hidden_dim] - ResidentTensor d_w_o; // [hidden_dim, q_dim] - ResidentTensor d_norm2; // [hidden_dim] - ResidentTensor d_w_gate_up; // [2 * intermediate_dim, hidden_dim] - ResidentTensor d_w_down; // [hidden_dim, intermediate_dim] -}; - -// Resident Model Weights on GPU -struct BlackwellResidentModelWeights { - int num_layers; - int hidden_dim; - int num_q_heads; - int num_kv_heads; - int head_dim; - int intermediate_dim; - int vocab_size; - float rms_norm_eps; - float rope_theta; - - ResidentTensor d_embed_tokens; // [vocab_size, hidden_dim] - BlackwellResidentLayerWeights *layers; - ResidentTensor d_final_norm; // [hidden_dim] - ResidentTensor d_lm_head; // [vocab_size, hidden_dim] -}; - -// Persistent GPU Activation Workspace -struct BlackwellWorkspaceC { - int max_tokens; - float *d_x_a; // [max_tokens, hidden_dim] - float *d_x_b; // [max_tokens, hidden_dim] - float *d_x_norm; // [max_tokens, hidden_dim] - float *d_qkv; // [max_tokens, q_dim + 2 * kv_dim] - float *d_attn_out; // [max_tokens, q_dim] - float *d_attn_proj; // [max_tokens, hidden_dim] - float *d_post_norm; // [max_tokens, hidden_dim] - float *d_gate_up; // [max_tokens, 2 * intermediate_dim] - float *d_act; // [max_tokens, intermediate_dim] - float *d_mlp_out; // [max_tokens, hidden_dim] - - float *d_term_x; // [max_tokens, hidden_dim] - float *d_logits; // [max_tokens, vocab_size] - uint32_t *d_tokens; // [max_tokens] - - // Metadata GPU buffers - int32_t *d_positions; - int32_t *d_block_ids; - int32_t *d_slots; - int32_t *d_block_tables; - int32_t *d_context_lens; - int32_t *d_term_indices; - int32_t *d_prefill_offsets; -}; - -// Batch Plan Metadata -struct BlackwellBatchPlanC { - int num_tokens; // M - int decode_count; // Nd - int prefill_count; // Np - int terminal_count; // R - int max_blocks_per_seq; - - const uint32_t *h_input_tokens; // [M] (optional if embeddings provided) - const float *h_input_embeddings; // [M, hidden_dim] (optional if tokens provided) - const int32_t *h_positions; - const int32_t *h_block_ids; - const int32_t *h_slots; - const int32_t *h_decode_block_tables; - const int32_t *h_decode_context_lens; - const int32_t *h_term_indices; - const int32_t *h_prefill_offsets; // [prefill_count + 1] -}; - -// ---------------------------------------------------------------------------- -// CUDA Kernels -// ---------------------------------------------------------------------------- - -__global__ void embedding_lookup_kernel( - const uint32_t * __restrict__ tokens, - const float * __restrict__ embed_table, - float * __restrict__ x_out, - int M, - int D, - int vocab_size -) { - int row = blockIdx.x; - if (row >= M) return; - uint32_t tok = tokens[row] % vocab_size; - const float *src = embed_table + (size_t)tok * D; - float *dst = x_out + (size_t)row * D; - for (int i = threadIdx.x; i < D; i += blockDim.x) { - dst[i] = src[i]; - } -} - -__device__ __forceinline__ float silu_act(float x) { - return x / (1.0f + expf(-x)); -} - -__global__ void rmsnorm_batch_kernel( - const float * __restrict__ x, - const float * __restrict__ weight, - float * __restrict__ out, - int M, - int D, - float eps -) { - int row = blockIdx.x; - if (row >= M) return; - - const float *row_in = x + (size_t)row * D; - float *row_out = out + (size_t)row * D; - - float sum_sq = 0.0f; - for (int i = threadIdx.x; i < D; i += blockDim.x) { - float val = row_in[i]; - sum_sq += val * val; - } - - // Warp-level reduction - for (int offset = 16; offset > 0; offset /= 2) { - sum_sq += __shfl_down_sync(0xffffffff, sum_sq, offset); - } - - __shared__ float s_sum[32]; - int lane = threadIdx.x % 32; - int wid = threadIdx.x / 32; - if (lane == 0) { - s_sum[wid] = sum_sq; - } - __syncthreads(); - - if (wid == 0) { - float b_sum = (lane < (blockDim.x / 32)) ? s_sum[lane] : 0.0f; - for (int offset = 16; offset > 0; offset /= 2) { - b_sum += __shfl_down_sync(0xffffffff, b_sum, offset); - } - if (lane == 0) { - s_sum[0] = b_sum; - } - } - __syncthreads(); - - float mean_sq = s_sum[0] / (float)D; - float rsqrt_val = rsqrtf(mean_sq + eps); - - for (int i = threadIdx.x; i < D; i += blockDim.x) { - row_out[i] = row_in[i] * rsqrt_val * weight[i]; - } -} - -__global__ void rope_and_kv_scatter_kernel( - float * __restrict__ qkv, - const int32_t * __restrict__ positions, - const int32_t * __restrict__ block_ids, - const int32_t * __restrict__ slots, - uint8_t * __restrict__ kv_pool, - KvLayoutDesc layout, - int32_t layer_idx, - int M, - int num_q_heads, - int num_kv_heads, - int head_dim, - float theta -) { - int row = blockIdx.x; - if (row >= M) return; - - int q_dim = num_q_heads * head_dim; - int kv_dim = num_kv_heads * head_dim; - int qkv_dim = q_dim + 2 * kv_dim; - - float *row_qkv = qkv + (size_t)row * qkv_dim; - float *row_q = row_qkv; - float *row_k = row_qkv + q_dim; - float *row_v = row_qkv + q_dim + kv_dim; - - int pos = positions[row]; - - // 1. RoPE on Q - for (int idx = threadIdx.x; idx < (num_q_heads * (head_dim / 2)); idx += blockDim.x) { - int h = idx / (head_dim / 2); - int p_idx = idx % (head_dim / 2); - int i0 = h * head_dim + 2 * p_idx; - int i1 = i0 + 1; - - float freq = 1.0f / powf(theta, (float)(2 * p_idx) / (float)head_dim); - float angle = (float)pos * freq; - float cos_val = cosf(angle); - float sin_val = sinf(angle); - - float q0 = row_q[i0]; - float q1 = row_q[i1]; - row_q[i0] = q0 * cos_val - q1 * sin_val; - row_q[i1] = q0 * sin_val + q1 * cos_val; - } - - // 2. RoPE on K - for (int idx = threadIdx.x; idx < (num_kv_heads * (head_dim / 2)); idx += blockDim.x) { - int h = idx / (head_dim / 2); - int p_idx = idx % (head_dim / 2); - int i0 = h * head_dim + 2 * p_idx; - int i1 = i0 + 1; - - float freq = 1.0f / powf(theta, (float)(2 * p_idx) / (float)head_dim); - float angle = (float)pos * freq; - float cos_val = cosf(angle); - float sin_val = sinf(angle); - - float k0 = row_k[i0]; - float k1 = row_k[i1]; - row_k[i0] = k0 * cos_val - k1 * sin_val; - row_k[i1] = k0 * sin_val + k1 * cos_val; - } - __syncthreads(); - - // 3. GPU KV Scatter to canonical physical block-major layout - int blk = block_ids[row]; - if (blk >= 0 && kv_pool != NULL) { - int slot = slots[row]; - uint8_t *blk_base = kv_pool + ((uint64_t)blk * layout.block_stride_bytes); - uint8_t *layer_base = blk_base + ((uint64_t)layer_idx * layout.layer_stride_bytes); - uint8_t *k_plane = layer_base; - uint8_t *v_plane = layer_base + layout.kv_plane_stride_bytes; - uint8_t *k_tok = k_plane + ((uint64_t)slot * layout.token_stride_bytes); - uint8_t *v_tok = v_plane + ((uint64_t)slot * layout.token_stride_bytes); - - for (int idx = threadIdx.x; idx < kv_dim; idx += blockDim.x) { - int h = idx / head_dim; - int d = idx % head_dim; - __nv_bfloat16 *dst_k = (__nv_bfloat16*)(k_tok + ((uint64_t)h * layout.head_stride_bytes)); - __nv_bfloat16 *dst_v = (__nv_bfloat16*)(v_tok + ((uint64_t)h * layout.head_stride_bytes)); - - dst_k[d] = __float2bfloat16(row_k[idx]); - dst_v[d] = __float2bfloat16(row_v[idx]); - } - } -} - -// Batched decode paged attention reading directly from canonical BF16 physical pool -__global__ void batched_decode_attention_kernel( - const float * __restrict__ qkv, - const uint8_t * __restrict__ kv_pool, - KvLayoutDesc layout, - int32_t layer_idx, - const int32_t * __restrict__ block_tables, - const int32_t * __restrict__ context_lens, - int max_blocks_per_seq, - int num_seqs, - int num_q_heads, - int num_kv_heads, - int head_dim, - float sm_scale, - float * __restrict__ attn_out -) { - int seq_idx = blockIdx.y; - int q_head_idx = blockIdx.x; - - if (seq_idx >= num_seqs || q_head_idx >= num_q_heads) return; - - int ctx_len = context_lens[seq_idx]; - if (ctx_len <= 0) return; - - int group_size = num_q_heads / num_kv_heads; - int kv_head_idx = q_head_idx / group_size; - - int q_dim = num_q_heads * head_dim; - int kv_dim = num_kv_heads * head_dim; - int qkv_dim = q_dim + 2 * kv_dim; - - const float *q_vec = qkv + (size_t)seq_idx * qkv_dim + (size_t)q_head_idx * head_dim; - float *out_vec = attn_out + (size_t)seq_idx * q_dim + (size_t)q_head_idx * head_dim; - - const int32_t *seq_blocks = block_tables + (size_t)seq_idx * max_blocks_per_seq; - - extern __shared__ float s_mem[]; - // Per-warp / block storage for scores - float *s_scores = s_mem; - - float max_score = -1e30f; - for (int t = threadIdx.x; t < ctx_len; t += blockDim.x) { - int blk_idx = t / layout.block_size; - int slot = t % layout.block_size; - int phys_blk = seq_blocks[blk_idx]; - - const uint8_t *blk_base = kv_pool + ((uint64_t)phys_blk * layout.block_stride_bytes); - const uint8_t *layer_base = blk_base + ((uint64_t)layer_idx * layout.layer_stride_bytes); - const uint8_t *k_tok = layer_base + ((uint64_t)slot * layout.token_stride_bytes); - const __nv_bfloat16 *k_vec = (const __nv_bfloat16*)(k_tok + ((uint64_t)kv_head_idx * layout.head_stride_bytes)); - - float score = 0.0f; - for (int d = 0; d < head_dim; d++) { - score += q_vec[d] * __bfloat162float(k_vec[d]); - } - score *= sm_scale; - s_scores[t] = score; - if (score > max_score) max_score = score; - } - - // Block reduction for max_score - for (int offset = 16; offset > 0; offset /= 2) { - max_score = fmaxf(max_score, __shfl_down_sync(0xffffffff, max_score, offset)); - } - __shared__ float s_max; - if (threadIdx.x == 0) s_max = max_score; - __syncthreads(); - max_score = s_max; - - // Softmax sum - float exp_sum = 0.0f; - for (int t = threadIdx.x; t < ctx_len; t += blockDim.x) { - float e = expf(s_scores[t] - max_score); - s_scores[t] = e; - exp_sum += e; - } - for (int offset = 16; offset > 0; offset /= 2) { - exp_sum += __shfl_down_sync(0xffffffff, exp_sum, offset); - } - __shared__ float s_sum; - if (threadIdx.x == 0) s_sum = exp_sum; - __syncthreads(); - exp_sum = s_sum > 0.0f ? s_sum : 1.0f; - - // Weighted sum of V - for (int d = threadIdx.x; d < head_dim; d += blockDim.x) { - float acc = 0.0f; - for (int t = 0; t < ctx_len; t++) { - float p = s_scores[t] / exp_sum; - int blk_idx = t / layout.block_size; - int slot = t % layout.block_size; - int phys_blk = seq_blocks[blk_idx]; - - const uint8_t *blk_base = kv_pool + ((uint64_t)phys_blk * layout.block_stride_bytes); - const uint8_t *layer_base = blk_base + ((uint64_t)layer_idx * layout.layer_stride_bytes); - const uint8_t *v_plane = layer_base + layout.kv_plane_stride_bytes; - const uint8_t *v_tok = v_plane + ((uint64_t)slot * layout.token_stride_bytes); - const __nv_bfloat16 *v_vec = (const __nv_bfloat16*)(v_tok + ((uint64_t)kv_head_idx * layout.head_stride_bytes)); - - acc += p * __bfloat162float(v_vec[d]); - } - out_vec[d] = acc; - } -} - -// Ragged causal prefill attention -__global__ void ragged_prefill_attention_kernel( - const float * __restrict__ qkv, - int decode_offset, - int num_q_heads, - int num_kv_heads, - int head_dim, - float sm_scale, - const int32_t * __restrict__ prefill_offsets, - int prefill_count, - float * __restrict__ attn_out -) { - int p_idx = blockIdx.y; - int q_head_idx = blockIdx.x; - - if (p_idx >= prefill_count || q_head_idx >= num_q_heads) return; - - int start_tok = prefill_offsets[p_idx]; - int end_tok = prefill_offsets[p_idx + 1]; - int seq_len = end_tok - start_tok; - if (seq_len <= 0) return; - - int group_size = num_q_heads / num_kv_heads; - int kv_head_idx = q_head_idx / group_size; - - int q_dim = num_q_heads * head_dim; - int kv_dim = num_kv_heads * head_dim; - int qkv_dim = q_dim + 2 * kv_dim; - - extern __shared__ float s_prefill_scores[]; - - for (int t = 0; t < seq_len; t++) { - int cur_row = decode_offset + start_tok + t; - const float *q_vec = qkv + (size_t)cur_row * qkv_dim + (size_t)q_head_idx * head_dim; - float *out_vec = attn_out + (size_t)cur_row * q_dim + (size_t)q_head_idx * head_dim; - - // Causal attention up to t - float max_s = -1e30f; - for (int past = threadIdx.x; past <= t; past += blockDim.x) { - int past_row = decode_offset + start_tok + past; - const float *k_vec = qkv + (size_t)past_row * qkv_dim + q_dim + (size_t)kv_head_idx * head_dim; - - float score = 0.0f; - for (int d = 0; d < head_dim; d++) { - score += q_vec[d] * k_vec[d]; - } - score *= sm_scale; - s_prefill_scores[past] = score; - if (score > max_s) max_s = score; - } - - // Reduction for max - for (int offset = 16; offset > 0; offset /= 2) { - max_s = fmaxf(max_s, __shfl_down_sync(0xffffffff, max_s, offset)); - } - __shared__ float s_cur_max; - if (threadIdx.x == 0) s_cur_max = max_s; - __syncthreads(); - max_s = s_cur_max; - - float exp_sum = 0.0f; - for (int past = threadIdx.x; past <= t; past += blockDim.x) { - float e = expf(s_prefill_scores[past] - max_s); - s_prefill_scores[past] = e; - exp_sum += e; - } - for (int offset = 16; offset > 0; offset /= 2) { - exp_sum += __shfl_down_sync(0xffffffff, exp_sum, offset); - } - __shared__ float s_cur_sum; - if (threadIdx.x == 0) s_cur_sum = exp_sum; - __syncthreads(); - exp_sum = s_cur_sum > 0.0f ? s_cur_sum : 1.0f; - - for (int d = threadIdx.x; d < head_dim; d += blockDim.x) { - float acc = 0.0f; - for (int past = 0; past <= t; past++) { - int past_row = decode_offset + start_tok + past; - const float *v_vec = qkv + (size_t)past_row * qkv_dim + q_dim + kv_dim + (size_t)kv_head_idx * head_dim; - acc += (s_prefill_scores[past] / exp_sum) * v_vec[d]; - } - out_vec[d] = acc; - } - } -} - -__global__ void residual_add_kernel( - const float * __restrict__ a, - const float * __restrict__ b, - float * __restrict__ out, - size_t total -) { - size_t idx = (size_t)blockIdx.x * blockDim.x + threadIdx.x; - if (idx < total) { - out[idx] = a[idx] + b[idx]; - } -} - -__global__ void swiglu_kernel( - const float * __restrict__ gate_up, - float * __restrict__ act, - int M, - int intermediate_dim -) { - size_t total = (size_t)M * intermediate_dim; - size_t idx = (size_t)blockIdx.x * blockDim.x + threadIdx.x; - if (idx >= total) return; - - int row = idx / intermediate_dim; - int col = idx % intermediate_dim; - - size_t gate_idx = (size_t)row * (2 * intermediate_dim) + col; - size_t up_idx = gate_idx + intermediate_dim; - - float g = gate_up[gate_idx]; - float u = gate_up[up_idx]; - act[idx] = silu_act(g) * u; -} - -__global__ void gather_terminal_rows_kernel( - const float * __restrict__ x, - const int32_t * __restrict__ term_indices, - float * __restrict__ term_x, - int R, - int D -) { - int r = blockIdx.x; - if (r >= R) return; - int src_row = term_indices[r]; - - const float *src = x + (size_t)src_row * D; - float *dst = term_x + (size_t)r * D; - - for (int i = threadIdx.x; i < D; i += blockDim.x) { - dst[i] = src[i]; - } -} - -__global__ void argmax_sampling_kernel( - const float * __restrict__ logits, - uint32_t * __restrict__ sampled_tokens, - int R, - int vocab_size -) { - int r = blockIdx.x; - if (r >= R) return; - - const float *row = logits + (size_t)r * vocab_size; - - float max_val = -1e30f; - int max_idx = 0; - - for (int i = threadIdx.x; i < vocab_size; i += blockDim.x) { - float val = row[i]; - if (val > max_val) { - max_val = val; - max_idx = i; - } - } - - for (int offset = 16; offset > 0; offset /= 2) { - float other_val = __shfl_down_sync(0xffffffff, max_val, offset); - int other_idx = __shfl_down_sync(0xffffffff, max_idx, offset); - if (other_val > max_val) { - max_val = other_val; - max_idx = other_idx; - } - } - - __shared__ float s_max_val[32]; - __shared__ int s_max_idx[32]; - - int lane = threadIdx.x % 32; - int wid = threadIdx.x / 32; - - if (lane == 0) { - s_max_val[wid] = max_val; - s_max_idx[wid] = max_idx; - } - __syncthreads(); - - if (wid == 0) { - float b_max_val = (lane < (blockDim.x / 32)) ? s_max_val[lane] : -1e30f; - int b_max_idx = (lane < (blockDim.x / 32)) ? s_max_idx[lane] : 0; - - for (int offset = 16; offset > 0; offset /= 2) { - float other_val = __shfl_down_sync(0xffffffff, b_max_val, offset); - int other_idx = __shfl_down_sync(0xffffffff, b_max_idx, offset); - if (other_val > b_max_val) { - b_max_val = other_val; - b_max_idx = other_idx; - } - } - - if (lane == 0) { - sampled_tokens[r] = (uint32_t)b_max_idx; - } - } -} - -// ---------------------------------------------------------------------------- -// C-ABI Execution Functions -// ---------------------------------------------------------------------------- - -static bool valid_tensor_view(const TensorView *view) { - if (!view || !view->address || view->descriptor.residency != TENSOR_HOST || - view->descriptor.rank == 0 || view->descriptor.rank > 4 || - view->descriptor.byte_len == 0 || - view->descriptor.byte_len > SIZE_MAX) return false; - const TensorDescriptor &desc = view->descriptor; - uint64_t bytes_per_element; - switch (desc.dtype) { - case TENSOR_F32: bytes_per_element = 4; break; - case TENSOR_BF16: case TENSOR_FP16: bytes_per_element = 2; break; - case TENSOR_FP8_E4M3FN: case TENSOR_FP8_E5M2: - case TENSOR_INT8: case TENSOR_INT4: bytes_per_element = 1; break; - default: return false; - } - if (desc.layout != TENSOR_ROW_MAJOR && desc.layout != TENSOR_COLUMN_MAJOR && - desc.layout != TENSOR_STRIDED) return false; - if (desc.dtype == TENSOR_INT4 && desc.quant.packing == PACKING_NONE) return false; - if (desc.quant.scheme != QUANT_NONE && desc.quant.scheme != QUANT_SYMMETRIC && - desc.quant.scheme != QUANT_AFFINE) return false; - if (desc.quant.scheme == QUANT_NONE && - (desc.quant.scale_count || desc.quant.zero_point_count)) return false; - if (desc.quant.scheme != QUANT_NONE && - (!desc.quant.scales || desc.quant.scale_count == 0)) return false; - if (desc.quant.scale_count && !desc.quant.scales) return false; - if (desc.quant.zero_point_count && !desc.quant.zero_points) return false; - if (desc.quant.scale_count > SIZE_MAX / sizeof(float) || - desc.quant.zero_point_count > SIZE_MAX / sizeof(int32_t)) return false; - if (desc.layout == TENSOR_ROW_MAJOR) { - uint64_t elements = 1; - uint64_t stride = 1; - for (int index = (int)desc.rank - 1; index >= 0; --index) { - if (!desc.shape[index] || desc.strides[index] != stride || - elements > UINT64_MAX / desc.shape[index] || - stride > UINT64_MAX / desc.shape[index]) return false; - elements *= desc.shape[index]; - stride *= desc.shape[index]; - } - if (elements > UINT64_MAX / bytes_per_element) return false; - uint64_t expected = desc.dtype == TENSOR_INT4 ? elements / 2 + elements % 2 : elements * bytes_per_element; - if (desc.byte_len != expected) return false; - } - return true; -} - -static bool dense_f32_view(const TensorView *view, uint32_t rank, - uint64_t dim0, uint64_t dim1 = 0) { - return valid_tensor_view(view) && view->descriptor.dtype == TENSOR_F32 && - view->descriptor.layout == TENSOR_ROW_MAJOR && - view->descriptor.quant.scheme == QUANT_NONE && - view->descriptor.rank == rank && - view->descriptor.shape[0] == dim0 && - (rank == 1 || view->descriptor.shape[1] == dim1); -} - -static const float *dense_f32_data(const ResidentTensor &tensor) { - return static_cast(tensor.address); -} - -static bool resident_dense_f32(const ResidentTensor &tensor) { - return tensor.address && tensor.descriptor.residency == TENSOR_DEVICE && - tensor.descriptor.dtype == TENSOR_F32 && - tensor.descriptor.layout == TENSOR_ROW_MAJOR && - tensor.descriptor.quant.scheme == QUANT_NONE; -} - -extern "C" { - -int blackwell_tensor_upload(const TensorView *host, ResidentTensor *device, - cudaStream_t stream) { - if (!device || !valid_tensor_view(host)) return -1; - *device = {}; - device->descriptor = host->descriptor; - device->descriptor.residency = TENSOR_DEVICE; - device->descriptor.quant.scales = nullptr; - device->descriptor.quant.zero_points = nullptr; - if (cudaMalloc(&device->address, (size_t)host->descriptor.byte_len) != cudaSuccess) return -2; - if (cudaMemcpyAsync(device->address, host->address, (size_t)host->descriptor.byte_len, - cudaMemcpyHostToDevice, stream) != cudaSuccess) goto failed; - if (host->descriptor.quant.scale_count) { - void *scales = nullptr; - size_t bytes = (size_t)host->descriptor.quant.scale_count * sizeof(float); - if (cudaMalloc(&scales, bytes) != cudaSuccess) goto failed; - device->descriptor.quant.scales = static_cast(scales); - if (cudaMemcpyAsync(scales, host->descriptor.quant.scales, bytes, - cudaMemcpyHostToDevice, stream) != cudaSuccess) goto failed; - } - if (host->descriptor.quant.zero_point_count) { - void *zero_points = nullptr; - size_t bytes = (size_t)host->descriptor.quant.zero_point_count * sizeof(int32_t); - if (cudaMalloc(&zero_points, bytes) != cudaSuccess) goto failed; - device->descriptor.quant.zero_points = static_cast(zero_points); - if (cudaMemcpyAsync(zero_points, host->descriptor.quant.zero_points, bytes, - cudaMemcpyHostToDevice, stream) != cudaSuccess) goto failed; - } - // Host views may reference temporary fused buffers. Finish transfer before return. - if (cudaStreamSynchronize(stream) != cudaSuccess) goto failed; - return 0; -failed: - blackwell_tensor_free(device); - return -3; -} - -void blackwell_tensor_free(ResidentTensor *device) { - if (!device) return; - if (device->address) cudaFree(device->address); - if (device->descriptor.quant.scales) cudaFree((void *)device->descriptor.quant.scales); - if (device->descriptor.quant.zero_points) cudaFree((void *)device->descriptor.quant.zero_points); - *device = {}; -} - -int blackwell_execute_layer( - int layer_idx, - const BlackwellResidentLayerWeights *weights, - const BlackwellBatchPlanC *plan, - BlackwellWorkspaceC *workspace, - uint8_t *kv_pool, - const KvLayoutDesc *layout, - cudaStream_t stream, - cublasHandle_t cublas_handle, - int is_ping, - int hidden_dim, - int num_q_heads, - int num_kv_heads, - int head_dim, - int intermediate_dim, - float eps, - float theta -) { - int M = plan->num_tokens; - if (M <= 0) return 0; - if (!resident_dense_f32(weights->d_norm1) || - !resident_dense_f32(weights->d_w_qkv) || - !resident_dense_f32(weights->d_w_o) || - !resident_dense_f32(weights->d_norm2) || - !resident_dense_f32(weights->d_w_gate_up) || - !resident_dense_f32(weights->d_w_down)) return -2; - - float *d_x_in = is_ping ? workspace->d_x_b : workspace->d_x_a; - float *d_x_out = is_ping ? workspace->d_x_a : workspace->d_x_b; - - int q_dim = num_q_heads * head_dim; - int kv_dim = num_kv_heads * head_dim; - int qkv_dim = q_dim + 2 * kv_dim; - float sm_scale = 1.0f / sqrtf((float)head_dim); - - // 1. RMSNorm on x_in -> x_norm - rmsnorm_batch_kernel<<>>( - d_x_in, dense_f32_data(weights->d_norm1), workspace->d_x_norm, M, hidden_dim, eps - ); - - // 2. Fused QKV GEMM -> qkv - float alpha = 1.0f, beta = 0.0f; - cublasSgemm(cublas_handle, CUBLAS_OP_T, CUBLAS_OP_N, - qkv_dim, M, hidden_dim, - &alpha, dense_f32_data(weights->d_w_qkv), hidden_dim, - workspace->d_x_norm, hidden_dim, - &beta, workspace->d_qkv, qkv_dim); - - // 3. RoPE & GPU KV Scatter - rope_and_kv_scatter_kernel<<>>( - workspace->d_qkv, workspace->d_positions, workspace->d_block_ids, - workspace->d_slots, kv_pool, *layout, layer_idx, - M, num_q_heads, num_kv_heads, head_dim, theta - ); - - // 4. Attention - if (plan->decode_count > 0) { - dim3 grid_dec(num_q_heads, plan->decode_count); - size_t s_bytes = 2048 * sizeof(float); // up to 2048 tokens context in shared mem - batched_decode_attention_kernel<<>>( - workspace->d_qkv, kv_pool, *layout, layer_idx, - workspace->d_block_tables, workspace->d_context_lens, - plan->max_blocks_per_seq, plan->decode_count, - num_q_heads, num_kv_heads, head_dim, sm_scale, - workspace->d_attn_out - ); - } - if (plan->prefill_count > 0) { - dim3 grid_pref(num_q_heads, plan->prefill_count); - size_t s_bytes = 2048 * sizeof(float); - ragged_prefill_attention_kernel<<>>( - workspace->d_qkv, plan->decode_count, - num_q_heads, num_kv_heads, head_dim, sm_scale, - workspace->d_prefill_offsets, plan->prefill_count, - workspace->d_attn_out - ); - } - - // 5. O Projection GEMM -> attn_proj - cublasSgemm(cublas_handle, CUBLAS_OP_T, CUBLAS_OP_N, - hidden_dim, M, q_dim, - &alpha, dense_f32_data(weights->d_w_o), q_dim, - workspace->d_attn_out, q_dim, - &beta, workspace->d_attn_proj, hidden_dim); - - // 6. Residual Add -> x_norm (used as x_mid) - size_t total_hidden = (size_t)M * hidden_dim; - residual_add_kernel<<<(total_hidden + 255)/256, 256, 0, stream>>>( - d_x_in, workspace->d_attn_proj, workspace->d_x_norm, total_hidden - ); - - // 7. Post-Attention RMSNorm -> post_norm - rmsnorm_batch_kernel<<>>( - workspace->d_x_norm, dense_f32_data(weights->d_norm2), workspace->d_post_norm, M, hidden_dim, eps - ); - - // 8. Fused Gate/Up GEMM -> gate_up - cublasSgemm(cublas_handle, CUBLAS_OP_T, CUBLAS_OP_N, - 2 * intermediate_dim, M, hidden_dim, - &alpha, dense_f32_data(weights->d_w_gate_up), hidden_dim, - workspace->d_post_norm, hidden_dim, - &beta, workspace->d_gate_up, 2 * intermediate_dim); - - // 9. SwiGLU -> act - size_t total_act = (size_t)M * intermediate_dim; - swiglu_kernel<<<(total_act + 255)/256, 256, 0, stream>>>( - workspace->d_gate_up, workspace->d_act, M, intermediate_dim - ); - - // 10. Down Projection GEMM -> mlp_out - cublasSgemm(cublas_handle, CUBLAS_OP_T, CUBLAS_OP_N, - hidden_dim, M, intermediate_dim, - &alpha, dense_f32_data(weights->d_w_down), intermediate_dim, - workspace->d_act, intermediate_dim, - &beta, workspace->d_mlp_out, hidden_dim); - - // 11. Residual Add -> x_out - residual_add_kernel<<<(total_hidden + 255)/256, 256, 0, stream>>>( - workspace->d_x_norm, workspace->d_mlp_out, d_x_out, total_hidden - ); - - return 0; -} - -int blackwell_execute_step( - const BlackwellResidentModelWeights *model, - const BlackwellBatchPlanC *plan, - BlackwellWorkspaceC *workspace, - uint8_t *kv_pool, - const KvLayoutDesc *layout, - uint32_t *h_sampled_tokens, - cudaStream_t stream, - cublasHandle_t cublas_handle -) { - int M = plan->num_tokens; - if (M <= 0) return 0; - int R = plan->terminal_count; - if (!resident_dense_f32(model->d_embed_tokens) || - !resident_dense_f32(model->d_final_norm) || - !resident_dense_f32(model->d_lm_head)) return -2; - - // Async upload of input embeddings or tokens to persistent GPU workspace - if (plan->h_input_tokens != NULL && model->d_embed_tokens.address != NULL) { - cudaMemcpyAsync(workspace->d_tokens, plan->h_input_tokens, - (size_t)M * sizeof(uint32_t), - cudaMemcpyHostToDevice, stream); - embedding_lookup_kernel<<>>( - workspace->d_tokens, dense_f32_data(model->d_embed_tokens), workspace->d_x_a, - M, model->hidden_dim, model->vocab_size - ); - } else if (plan->h_input_embeddings != NULL) { - cudaMemcpyAsync(workspace->d_x_a, plan->h_input_embeddings, - (size_t)M * model->hidden_dim * sizeof(float), - cudaMemcpyHostToDevice, stream); - } - - cudaMemcpyAsync(workspace->d_positions, plan->h_positions, - (size_t)M * sizeof(int32_t), - cudaMemcpyHostToDevice, stream); - - cudaMemcpyAsync(workspace->d_block_ids, plan->h_block_ids, - (size_t)M * sizeof(int32_t), - cudaMemcpyHostToDevice, stream); - - cudaMemcpyAsync(workspace->d_slots, plan->h_slots, - (size_t)M * sizeof(int32_t), - cudaMemcpyHostToDevice, stream); - - if (plan->decode_count > 0) { - cudaMemcpyAsync(workspace->d_block_tables, plan->h_decode_block_tables, - (size_t)plan->decode_count * plan->max_blocks_per_seq * sizeof(int32_t), - cudaMemcpyHostToDevice, stream); - cudaMemcpyAsync(workspace->d_context_lens, plan->h_decode_context_lens, - (size_t)plan->decode_count * sizeof(int32_t), - cudaMemcpyHostToDevice, stream); - } - - if (plan->prefill_count > 0) { - cudaMemcpyAsync(workspace->d_prefill_offsets, plan->h_prefill_offsets, - (size_t)(plan->prefill_count + 1) * sizeof(int32_t), - cudaMemcpyHostToDevice, stream); - } - - cudaMemcpyAsync(workspace->d_term_indices, plan->h_term_indices, - (size_t)R * sizeof(int32_t), - cudaMemcpyHostToDevice, stream); - - // Execute all layers sequentially on stream without synchronizing - for (int l = 0; l < model->num_layers; l++) { - int layer_status = blackwell_execute_layer( - l, &model->layers[l], plan, workspace, kv_pool, layout, - stream, cublas_handle, l % 2, - model->hidden_dim, model->num_q_heads, model->num_kv_heads, - model->head_dim, model->intermediate_dim, - model->rms_norm_eps, model->rope_theta - ); - if (layer_status != 0) return layer_status; - } - - float *d_x_final = (model->num_layers % 2 == 1) ? workspace->d_x_b : workspace->d_x_a; - - // Gather terminal rows - gather_terminal_rows_kernel<<>>( - d_x_final, workspace->d_term_indices, workspace->d_term_x, R, model->hidden_dim - ); - - // Final RMSNorm on terminal rows - rmsnorm_batch_kernel<<>>( - workspace->d_term_x, dense_f32_data(model->d_final_norm), workspace->d_x_norm, R, model->hidden_dim, model->rms_norm_eps - ); - - // LM Head GEMM -> logits [R, vocab_size] - float alpha = 1.0f, beta = 0.0f; - cublasSgemm(cublas_handle, CUBLAS_OP_T, CUBLAS_OP_N, - model->vocab_size, R, model->hidden_dim, - &alpha, dense_f32_data(model->d_lm_head), model->hidden_dim, - workspace->d_x_norm, model->hidden_dim, - &beta, workspace->d_logits, model->vocab_size); - - // Argmax sampling on GPU -> d_tokens [R] - argmax_sampling_kernel<<>>( - workspace->d_logits, workspace->d_tokens, R, model->vocab_size - ); - - // Asynchronously copy sampled tokens to host - cudaMemcpyAsync(h_sampled_tokens, workspace->d_tokens, - (size_t)R * sizeof(uint32_t), - cudaMemcpyDeviceToHost, stream); - - // EXACTLY ONE COMPLETION FENCE FOR THE ENTIRE SCHEDULER STEP - cudaError_t err = cudaStreamSynchronize(stream); - if (err != cudaSuccess) { - return -1; - } - - g_kernel_exec_count.fetch_add(1 + (uint64_t)model->num_layers * 11, std::memory_order_relaxed); - return 0; -} - -BlackwellWorkspaceC* blackwell_workspace_create( - int max_tokens, - int hidden_dim, - int q_dim, - int kv_dim, - int intermediate_dim, - int vocab_size, - int max_blocks_per_seq -) { - BlackwellWorkspaceC *ws = (BlackwellWorkspaceC*)calloc(1, sizeof(BlackwellWorkspaceC)); - if (!ws) return NULL; - - ws->max_tokens = max_tokens; - int qkv_dim = q_dim + 2 * kv_dim; - - cudaMalloc((void**)&ws->d_x_a, (size_t)max_tokens * hidden_dim * sizeof(float)); - cudaMalloc((void**)&ws->d_x_b, (size_t)max_tokens * hidden_dim * sizeof(float)); - cudaMalloc((void**)&ws->d_x_norm, (size_t)max_tokens * hidden_dim * sizeof(float)); - cudaMalloc((void**)&ws->d_qkv, (size_t)max_tokens * qkv_dim * sizeof(float)); - cudaMalloc((void**)&ws->d_attn_out, (size_t)max_tokens * q_dim * sizeof(float)); - cudaMalloc((void**)&ws->d_attn_proj, (size_t)max_tokens * hidden_dim * sizeof(float)); - cudaMalloc((void**)&ws->d_post_norm, (size_t)max_tokens * hidden_dim * sizeof(float)); - cudaMalloc((void**)&ws->d_gate_up, (size_t)max_tokens * 2 * intermediate_dim * sizeof(float)); - cudaMalloc((void**)&ws->d_act, (size_t)max_tokens * intermediate_dim * sizeof(float)); - cudaMalloc((void**)&ws->d_mlp_out, (size_t)max_tokens * hidden_dim * sizeof(float)); - - cudaMalloc((void**)&ws->d_term_x, (size_t)max_tokens * hidden_dim * sizeof(float)); - cudaMalloc((void**)&ws->d_logits, (size_t)max_tokens * vocab_size * sizeof(float)); - cudaMalloc((void**)&ws->d_tokens, (size_t)max_tokens * sizeof(uint32_t)); - - cudaMalloc((void**)&ws->d_positions, (size_t)max_tokens * sizeof(int32_t)); - cudaMalloc((void**)&ws->d_block_ids, (size_t)max_tokens * sizeof(int32_t)); - cudaMalloc((void**)&ws->d_slots, (size_t)max_tokens * sizeof(int32_t)); - cudaMalloc((void**)&ws->d_block_tables, (size_t)max_tokens * max_blocks_per_seq * sizeof(int32_t)); - cudaMalloc((void**)&ws->d_context_lens, (size_t)max_tokens * sizeof(int32_t)); - cudaMalloc((void**)&ws->d_term_indices, (size_t)max_tokens * sizeof(int32_t)); - cudaMalloc((void**)&ws->d_prefill_offsets, (size_t)(max_tokens + 1) * sizeof(int32_t)); - - return ws; -} - -void blackwell_workspace_free(BlackwellWorkspaceC *ws) { - if (!ws) return; - if (ws->d_x_a) cudaFree(ws->d_x_a); - if (ws->d_x_b) cudaFree(ws->d_x_b); - if (ws->d_x_norm) cudaFree(ws->d_x_norm); - if (ws->d_qkv) cudaFree(ws->d_qkv); - if (ws->d_attn_out) cudaFree(ws->d_attn_out); - if (ws->d_attn_proj) cudaFree(ws->d_attn_proj); - if (ws->d_post_norm) cudaFree(ws->d_post_norm); - if (ws->d_gate_up) cudaFree(ws->d_gate_up); - if (ws->d_act) cudaFree(ws->d_act); - if (ws->d_mlp_out) cudaFree(ws->d_mlp_out); - if (ws->d_term_x) cudaFree(ws->d_term_x); - if (ws->d_logits) cudaFree(ws->d_logits); - if (ws->d_tokens) cudaFree(ws->d_tokens); - if (ws->d_positions) cudaFree(ws->d_positions); - if (ws->d_block_ids) cudaFree(ws->d_block_ids); - if (ws->d_slots) cudaFree(ws->d_slots); - if (ws->d_block_tables) cudaFree(ws->d_block_tables); - if (ws->d_context_lens) cudaFree(ws->d_context_lens); - if (ws->d_term_indices) cudaFree(ws->d_term_indices); - if (ws->d_prefill_offsets) cudaFree(ws->d_prefill_offsets); - free(ws); -} - -BlackwellResidentLayerWeights* blackwell_layer_weights_create( - const TensorView *h_norm1, - const TensorView *h_w_qkv, - const TensorView *h_w_o, - const TensorView *h_norm2, - const TensorView *h_w_gate_up, - const TensorView *h_w_down, - int hidden_dim, - int q_dim, - int kv_dim, - int intermediate_dim, - cudaStream_t stream -) { - int qkv_dim = q_dim + 2 * kv_dim; - if (!dense_f32_view(h_norm1, 1, hidden_dim) || - !dense_f32_view(h_w_qkv, 2, qkv_dim, hidden_dim) || - !dense_f32_view(h_w_o, 2, hidden_dim, q_dim) || - !dense_f32_view(h_norm2, 1, hidden_dim) || - !dense_f32_view(h_w_gate_up, 2, 2 * intermediate_dim, hidden_dim) || - !dense_f32_view(h_w_down, 2, hidden_dim, intermediate_dim)) return NULL; - BlackwellResidentLayerWeights *lw = (BlackwellResidentLayerWeights*)calloc(1, sizeof(BlackwellResidentLayerWeights)); - if (!lw) return NULL; - if (blackwell_tensor_upload(h_norm1, &lw->d_norm1, stream) != 0 || - blackwell_tensor_upload(h_w_qkv, &lw->d_w_qkv, stream) != 0 || - blackwell_tensor_upload(h_w_o, &lw->d_w_o, stream) != 0 || - blackwell_tensor_upload(h_norm2, &lw->d_norm2, stream) != 0 || - blackwell_tensor_upload(h_w_gate_up, &lw->d_w_gate_up, stream) != 0 || - blackwell_tensor_upload(h_w_down, &lw->d_w_down, stream) != 0) { - blackwell_tensor_free(&lw->d_norm1); - blackwell_tensor_free(&lw->d_w_qkv); - blackwell_tensor_free(&lw->d_w_o); - blackwell_tensor_free(&lw->d_norm2); - blackwell_tensor_free(&lw->d_w_gate_up); - blackwell_tensor_free(&lw->d_w_down); - free(lw); - return NULL; - } - return lw; -} - -void blackwell_layer_weights_free(BlackwellResidentLayerWeights *lw) { - if (!lw) return; - blackwell_tensor_free(&lw->d_norm1); - blackwell_tensor_free(&lw->d_w_qkv); - blackwell_tensor_free(&lw->d_w_o); - blackwell_tensor_free(&lw->d_norm2); - blackwell_tensor_free(&lw->d_w_gate_up); - blackwell_tensor_free(&lw->d_w_down); - free(lw); -} - -BlackwellResidentModelWeights* blackwell_model_weights_create( - int num_layers, - int hidden_dim, - int num_q_heads, - int num_kv_heads, - int head_dim, - int intermediate_dim, - int vocab_size, - float rms_norm_eps, - float rope_theta, - const TensorView *h_embed_tokens, - const TensorView *h_final_norm, - const TensorView *h_lm_head, - cudaStream_t stream -) { - if (!dense_f32_view(h_embed_tokens, 2, vocab_size, hidden_dim) || - !dense_f32_view(h_final_norm, 1, hidden_dim) || - !dense_f32_view(h_lm_head, 2, vocab_size, hidden_dim)) return NULL; - BlackwellResidentModelWeights *mw = (BlackwellResidentModelWeights*)calloc(1, sizeof(BlackwellResidentModelWeights)); - if (!mw) return NULL; - - mw->num_layers = num_layers; - mw->hidden_dim = hidden_dim; - mw->num_q_heads = num_q_heads; - mw->num_kv_heads = num_kv_heads; - mw->head_dim = head_dim; - mw->intermediate_dim = intermediate_dim; - mw->vocab_size = vocab_size; - mw->rms_norm_eps = rms_norm_eps; - mw->rope_theta = rope_theta; - - mw->layers = (BlackwellResidentLayerWeights*)calloc(num_layers, sizeof(BlackwellResidentLayerWeights)); - if (!mw->layers || - blackwell_tensor_upload(h_embed_tokens, &mw->d_embed_tokens, stream) != 0 || - blackwell_tensor_upload(h_final_norm, &mw->d_final_norm, stream) != 0 || - blackwell_tensor_upload(h_lm_head, &mw->d_lm_head, stream) != 0) { - blackwell_tensor_free(&mw->d_embed_tokens); - blackwell_tensor_free(&mw->d_final_norm); - blackwell_tensor_free(&mw->d_lm_head); - free(mw->layers); - free(mw); - return NULL; - } - return mw; -} - -void blackwell_model_weights_set_layer( - BlackwellResidentModelWeights *mw, - int layer_idx, - const BlackwellResidentLayerWeights *lw -) { - if (mw && lw && layer_idx >= 0 && layer_idx < mw->num_layers) { - mw->layers[layer_idx] = *lw; - free((void *)lw); - } -} - -void blackwell_model_weights_free(BlackwellResidentModelWeights *mw) { - if (!mw) return; - if (mw->layers) { - for (int i = 0; i < mw->num_layers; i++) { - blackwell_tensor_free(&mw->layers[i].d_norm1); - blackwell_tensor_free(&mw->layers[i].d_w_qkv); - blackwell_tensor_free(&mw->layers[i].d_w_o); - blackwell_tensor_free(&mw->layers[i].d_norm2); - blackwell_tensor_free(&mw->layers[i].d_w_gate_up); - blackwell_tensor_free(&mw->layers[i].d_w_down); - } - free(mw->layers); - } - blackwell_tensor_free(&mw->d_embed_tokens); - blackwell_tensor_free(&mw->d_final_norm); - blackwell_tensor_free(&mw->d_lm_head); - free(mw); -} - -} // extern "C" diff --git a/crates/aien-inference-abi/cuda/paged_attention_bf16.cu b/crates/aien-inference-abi/cuda/paged_attention_bf16.cu deleted file mode 100644 index 574ad3eb..00000000 --- a/crates/aien-inference-abi/cuda/paged_attention_bf16.cu +++ /dev/null @@ -1,415 +0,0 @@ -#include -#include -#include -#include -#include - -#ifndef BLOCK_THREADS -#define BLOCK_THREADS 128 -#endif - -#ifndef Q_HEADS_PER_BLOCK -#define Q_HEADS_PER_BLOCK 4 -#endif - -#ifndef VECTOR_WIDTH -#define VECTOR_WIDTH 2 -#endif - -#ifndef PREFETCH_DISTANCE -#define PREFETCH_DISTANCE 1 -#endif - -#define WARP_SIZE 32 -#if defined(Q_HEADS_PER_BLOCK) && (Q_HEADS_PER_BLOCK > 0) -#define WARPS_PER_BLOCK Q_HEADS_PER_BLOCK -#else -#define WARPS_PER_BLOCK (BLOCK_THREADS / WARP_SIZE) -#endif - -__device__ __forceinline__ float bf16_to_f32(__nv_bfloat16 v) { - return __bfloat162float(v); -} - -__device__ __forceinline__ __nv_bfloat16 f32_to_bf16(float v) { - return __float2bfloat16(v); -} - -__device__ __forceinline__ void prefetch_global_l2(const void *ptr) { -#if defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 700) - asm volatile("prefetch.global.L2 [%0];" :: "l"(ptr)); -#endif -} - -// Canonical physical KV layout descriptor matching Rust KvLayoutDesc -struct KvLayoutDesc { - uint64_t block_stride_bytes; - uint64_t layer_stride_bytes; - uint64_t kv_plane_stride_bytes; - uint64_t token_stride_bytes; - uint64_t head_stride_bytes; - - uint64_t pool_bytes; - uint32_t num_blocks; - uint32_t num_layers; - uint32_t block_size; -}; - -// Truly Cooperative Grouped Query Paged Attention Kernel for Blackwell sm_121. -// Each warp processes one query head across 32 lanes cooperatively. -// Byte-stride addressing directly matching canonical block-major layout: -// [block][layer][K/V plane][token][kv_head][head_dim] -__global__ void paged_attention_bf16_cooperative_kernel( - const __nv_bfloat16 * __restrict__ q, - const uint8_t * __restrict__ kv_pool, - KvLayoutDesc layout, - int32_t layer_idx, - const int32_t * __restrict__ block_tables, - const int32_t * __restrict__ context_lens, - int32_t max_blocks_per_seq, - int32_t num_seqs, - int32_t num_q_heads, - int32_t num_kv_heads, - int32_t head_dim, - float sm_scale, - __nv_bfloat16 * __restrict__ out -) { - int warp_id = threadIdx.x / WARP_SIZE; - int lane_id = threadIdx.x % WARP_SIZE; - - int q_head_idx = blockIdx.x * WARPS_PER_BLOCK + warp_id; - int seq_idx = blockIdx.y; - - if (seq_idx >= num_seqs || q_head_idx >= num_q_heads || layer_idx < 0 || (uint32_t)layer_idx >= layout.num_layers) { - return; - } - - int context_len = context_lens[seq_idx]; - if (context_len <= 0) { - return; - } - - int heads_per_group = num_q_heads / num_kv_heads; - int kv_head_idx = q_head_idx / heads_per_group; - - const __nv_bfloat16 *q_vec = q + ((seq_idx * num_q_heads + q_head_idx) * head_dim); - - // Shared memory for query vectors (one slice per warp) - extern __shared__ float s_q_all[]; - float *s_q = s_q_all + (warp_id * head_dim); - - // Load Q into shared memory (coalesced pairs) - for (int p = 0; p < (head_dim + 63) / 64; ++p) { - int d = lane_id * 2 + p * 64; - if (d + 1 < head_dim) { - const __nv_bfloat162 *q2_ptr = reinterpret_cast(q_vec + d); - __nv_bfloat162 q2 = *q2_ptr; - s_q[d] = bf16_to_f32(__low2bfloat16(q2)); - s_q[d + 1] = bf16_to_f32(__high2bfloat16(q2)); - } else if (d < head_dim) { - s_q[d] = bf16_to_f32(q_vec[d]); - } - } - __syncwarp(); - - float m_prev = -1e20f; - float l_prev = 0.0f; - - // Up to 4 pairs (8 elements per lane, supporting head_dim up to 256) - const int max_pairs = (head_dim + 63) / 64; - float acc_out[8]; - #pragma unroll - for (int i = 0; i < 8; ++i) { - acc_out[i] = 0.0f; - } - - int total_blocks = (context_len + (int)layout.block_size - 1) / (int)layout.block_size; - const int32_t *seq_blocks = block_tables + (seq_idx * max_blocks_per_seq); - - for (int b = 0; b < total_blocks; ++b) { - int32_t physical_block_id = seq_blocks[b]; - if (physical_block_id < 0 || (uint32_t)physical_block_id >= layout.num_blocks) { - continue; - } - - int tokens_in_this_block = (int)layout.block_size; - if (b == total_blocks - 1) { - int rem = context_len % (int)layout.block_size; - if (rem != 0) { - tokens_in_this_block = rem; - } - } - - const uint8_t *block_base = kv_pool + ((uint64_t)physical_block_id * layout.block_stride_bytes); - const uint8_t *layer_base = block_base + ((uint64_t)layer_idx * layout.layer_stride_bytes); - const uint8_t *k_plane = layer_base; - const uint8_t *v_plane = layer_base + layout.kv_plane_stride_bytes; - -#if PREFETCH_DISTANCE > 0 - if (b + PREFETCH_DISTANCE < total_blocks) { - int32_t next_blk_id = seq_blocks[b + PREFETCH_DISTANCE]; - if (next_blk_id >= 0 && (uint32_t)next_blk_id < layout.num_blocks) { - const uint8_t *next_block = kv_pool + ((uint64_t)next_blk_id * layout.block_stride_bytes); - const uint8_t *next_layer = next_block + ((uint64_t)layer_idx * layout.layer_stride_bytes); - prefetch_global_l2(next_layer); - prefetch_global_l2(next_layer + layout.kv_plane_stride_bytes); - } - } -#endif - - for (int tok = 0; tok < tokens_in_this_block; ++tok) { - const uint8_t *k_addr = k_plane - + ((uint64_t)tok * layout.token_stride_bytes) - + ((uint64_t)kv_head_idx * layout.head_stride_bytes); - const uint8_t *v_addr = v_plane - + ((uint64_t)tok * layout.token_stride_bytes) - + ((uint64_t)kv_head_idx * layout.head_stride_bytes); - - const __nv_bfloat16 *k_tok = reinterpret_cast(k_addr); - const __nv_bfloat16 *v_tok = reinterpret_cast(v_addr); - - // Step 1: Thread-local partial dot product across lane's pairs (aligned 32-bit loads) - float my_dot = 0.0f; - for (int p = 0; p < max_pairs; ++p) { - int d = lane_id * 2 + p * 64; - if (d + 1 < head_dim) { - const __nv_bfloat162 *k2_ptr = reinterpret_cast(k_tok + d); - __nv_bfloat162 k2 = *k2_ptr; - my_dot += s_q[d] * bf16_to_f32(__low2bfloat16(k2)) + s_q[d + 1] * bf16_to_f32(__high2bfloat16(k2)); - } else if (d < head_dim) { - my_dot += s_q[d] * bf16_to_f32(k_tok[d]); - } - } - - // Step 2: Cooperative warp reduction using __shfl_down_sync - #pragma unroll - for (int offset = 16; offset > 0; offset /= 2) { - my_dot += __shfl_down_sync(0xffffffff, my_dot, offset); - } - - // Step 3: Broadcast complete score to all 32 lanes - float score = __shfl_sync(0xffffffff, my_dot, 0) * sm_scale; - - // Step 4: Online softmax update - float m_new = fmaxf(m_prev, score); - float alpha = expf(m_prev - m_new); - float beta = expf(score - m_new); - float l_new = l_prev * alpha + beta; - - // Step 5: Update value accumulator in registers for lane's dimensions (aligned loads) - for (int p = 0; p < max_pairs; ++p) { - int d = lane_id * 2 + p * 64; - if (d + 1 < head_dim) { - const __nv_bfloat162 *v2_ptr = reinterpret_cast(v_tok + d); - __nv_bfloat162 v2 = *v2_ptr; - acc_out[p * 2] = acc_out[p * 2] * alpha + beta * bf16_to_f32(__low2bfloat16(v2)); - acc_out[p * 2 + 1] = acc_out[p * 2 + 1] * alpha + beta * bf16_to_f32(__high2bfloat16(v2)); - } else if (d < head_dim) { - acc_out[p * 2] = acc_out[p * 2] * alpha + beta * bf16_to_f32(v_tok[d]); - } - } - - m_prev = m_new; - l_prev = l_new; - } - } - - // Step 6: Normalize by l_prev and write output cooperatively (aligned 32-bit stores) - float inv_l = (l_prev > 0.0f) ? (1.0f / l_prev) : 0.0f; - __nv_bfloat16 *out_vec = out + ((seq_idx * num_q_heads + q_head_idx) * head_dim); - for (int p = 0; p < max_pairs; ++p) { - int d = lane_id * 2 + p * 64; - if (d + 1 < head_dim) { - __nv_bfloat162 out2 = __halves2bfloat162( - f32_to_bf16(acc_out[p * 2] * inv_l), - f32_to_bf16(acc_out[p * 2 + 1] * inv_l) - ); - *reinterpret_cast<__nv_bfloat162*>(out_vec + d) = out2; - } else if (d < head_dim) { - out_vec[d] = f32_to_bf16(acc_out[p * 2] * inv_l); - } - } -} - -static bool is_device_or_managed_ptr(const void *ptr) { - cudaPointerAttributes attr; - cudaError_t err = cudaPointerGetAttributes(&attr, ptr); - if (err != cudaSuccess) { - cudaGetLastError(); - return false; - } - return (attr.type == cudaMemoryTypeDevice || attr.type == cudaMemoryTypeManaged); -} - -// Persistent device scratch buffers to eliminate per-step cudaMalloc/cudaFree -static __nv_bfloat16 *g_scratch_d_q = NULL; -static size_t g_scratch_cap_q = 0; -static __nv_bfloat16 *g_scratch_d_out = NULL; -static size_t g_scratch_cap_out = 0; -static int32_t *g_scratch_d_bt = NULL; -static size_t g_scratch_cap_bt = 0; -static int32_t *g_scratch_d_cl = NULL; -static size_t g_scratch_cap_cl = 0; - -static uint8_t *g_scratch_d_kv = NULL; -static size_t g_scratch_cap_kv = 0; -static uint64_t g_paged_attn_kernel_count = 0; - -extern "C" { - -uint64_t paged_attention_get_kernel_count(void) { - return g_paged_attn_kernel_count; -} - -int paged_attention_bf16_forward( - const __nv_bfloat16 *q, - const uint8_t *kv_pool, - uint64_t pool_bytes, - const KvLayoutDesc *layout, - int32_t layer_idx, - const int32_t *block_tables, - const int32_t *context_lens, - int32_t max_blocks_per_seq, - int32_t num_seqs, - int32_t num_q_heads, - int32_t num_kv_heads, - int32_t head_dim, - float sm_scale, - __nv_bfloat16 *out -) { - if (!layout || num_seqs <= 0 || num_q_heads <= 0 || head_dim <= 0 || layout->num_blocks == 0) { - return 0; - } - g_paged_attn_kernel_count++; - - bool q_dev = is_device_or_managed_ptr(q); - bool kv_dev = is_device_or_managed_ptr(kv_pool); - bool bt_dev = is_device_or_managed_ptr(block_tables); - bool cl_dev = is_device_or_managed_ptr(context_lens); - bool out_dev = is_device_or_managed_ptr(out); - - size_t q_bytes = (size_t)num_seqs * num_q_heads * head_dim * sizeof(__nv_bfloat16); - size_t out_bytes = q_bytes; - size_t bt_bytes = (size_t)num_seqs * max_blocks_per_seq * sizeof(int32_t); - size_t cl_bytes = (size_t)num_seqs * sizeof(int32_t); - - const __nv_bfloat16 *d_q = q; - if (!q_dev) { - if (q_bytes > g_scratch_cap_q) { - if (g_scratch_d_q) cudaFree(g_scratch_d_q); - cudaMalloc((void**)&g_scratch_d_q, q_bytes); - g_scratch_cap_q = q_bytes; - } - cudaMemcpy((void*)g_scratch_d_q, q, q_bytes, cudaMemcpyHostToDevice); - d_q = g_scratch_d_q; - } - - const int32_t *d_bt = block_tables; - if (!bt_dev) { - if (bt_bytes > g_scratch_cap_bt) { - if (g_scratch_d_bt) cudaFree(g_scratch_d_bt); - cudaMalloc((void**)&g_scratch_d_bt, bt_bytes); - g_scratch_cap_bt = bt_bytes; - } - cudaMemcpy((void*)g_scratch_d_bt, block_tables, bt_bytes, cudaMemcpyHostToDevice); - d_bt = g_scratch_d_bt; - } - - const int32_t *d_cl = context_lens; - if (!cl_dev) { - if (cl_bytes > g_scratch_cap_cl) { - if (g_scratch_d_cl) cudaFree(g_scratch_d_cl); - cudaMalloc((void**)&g_scratch_d_cl, cl_bytes); - g_scratch_cap_cl = cl_bytes; - } - cudaMemcpy((void*)g_scratch_d_cl, context_lens, cl_bytes, cudaMemcpyHostToDevice); - d_cl = g_scratch_d_cl; - } - - __nv_bfloat16 *d_out = out; - if (!out_dev) { - if (out_bytes > g_scratch_cap_out) { - if (g_scratch_d_out) cudaFree(g_scratch_d_out); - cudaMalloc((void**)&g_scratch_d_out, out_bytes); - g_scratch_cap_out = out_bytes; - } - d_out = g_scratch_d_out; - } - - const uint8_t *d_kv = kv_pool; - if (!kv_dev) { - size_t actual_pool_bytes = pool_bytes > 0 ? (size_t)pool_bytes : (size_t)layout->pool_bytes; - if (actual_pool_bytes > g_scratch_cap_kv) { - if (g_scratch_d_kv) cudaFree(g_scratch_d_kv); - cudaMalloc((void**)&g_scratch_d_kv, actual_pool_bytes); - g_scratch_cap_kv = actual_pool_bytes; - } - cudaMemcpy((void*)g_scratch_d_kv, kv_pool, actual_pool_bytes, cudaMemcpyHostToDevice); - d_kv = g_scratch_d_kv; - } - - int warps_per_block = WARPS_PER_BLOCK; - int block_threads = warps_per_block * WARP_SIZE; - int blocks_x = (num_q_heads + warps_per_block - 1) / warps_per_block; - dim3 grid(blocks_x, num_seqs); - dim3 block(block_threads); - size_t shared_mem = warps_per_block * head_dim * sizeof(float); - - paged_attention_bf16_cooperative_kernel<<>>( - d_q, - d_kv, - *layout, - layer_idx, - d_bt, - d_cl, - max_blocks_per_seq, - num_seqs, - num_q_heads, - num_kv_heads, - head_dim, - sm_scale, - d_out - ); - - cudaError_t err = cudaDeviceSynchronize(); - if (err != cudaSuccess) { - fprintf(stderr, "paged_attention_bf16_cooperative_kernel sync failed: %s\n", cudaGetErrorString(err)); - return -1; - } - - if (!out_dev) { - cudaMemcpy(out, d_out, out_bytes, cudaMemcpyDeviceToHost); - } - - return 0; -} - -void paged_attention_bf16_destroy(void) { - if (g_scratch_d_q) { - cudaFree(g_scratch_d_q); - g_scratch_d_q = NULL; - g_scratch_cap_q = 0; - } - if (g_scratch_d_out) { - cudaFree(g_scratch_d_out); - g_scratch_d_out = NULL; - g_scratch_cap_out = 0; - } - if (g_scratch_d_bt) { - cudaFree(g_scratch_d_bt); - g_scratch_d_bt = NULL; - g_scratch_cap_bt = 0; - } - if (g_scratch_d_cl) { - cudaFree(g_scratch_d_cl); - g_scratch_d_cl = NULL; - g_scratch_cap_cl = 0; - } - if (g_scratch_d_kv) { - cudaFree(g_scratch_d_kv); - g_scratch_d_kv = NULL; - g_scratch_cap_kv = 0; - } -} - -} // extern "C" diff --git a/crates/aien-inference-abi/cuda/tensor_abi.h b/crates/aien-inference-abi/cuda/tensor_abi.h deleted file mode 100644 index a119e845..00000000 --- a/crates/aien-inference-abi/cuda/tensor_abi.h +++ /dev/null @@ -1,61 +0,0 @@ -#pragma once - -#include -#include - -// Numeric tags mirror src/tensor_abi.rs. Keep this layout stable across FFI. -enum TensorDType : uint32_t { - TENSOR_F32 = 1, TENSOR_BF16 = 2, TENSOR_FP16 = 3, - TENSOR_FP8_E4M3FN = 4, TENSOR_FP8_E5M2 = 5, - TENSOR_INT8 = 6, TENSOR_INT4 = 7, -}; -enum TensorLayout : uint32_t { - TENSOR_ROW_MAJOR = 1, TENSOR_COLUMN_MAJOR = 2, TENSOR_STRIDED = 3, -}; -enum TensorResidency : uint32_t { TENSOR_HOST = 1, TENSOR_DEVICE = 2 }; -enum QuantScheme : uint32_t { QUANT_NONE = 0, QUANT_SYMMETRIC = 1, QUANT_AFFINE = 2 }; -enum TensorPacking : uint32_t { - PACKING_NONE = 0, INT4_LOW_SIGNED = 1, INT4_HIGH_SIGNED = 2, - INT4_LOW_UNSIGNED = 3, INT4_HIGH_UNSIGNED = 4, -}; - -struct AbiQuantization { - QuantScheme scheme; - int32_t axis; - uint32_t group_size; - TensorPacking packing; - const float *scales; - uint64_t scale_count; - const int32_t *zero_points; - uint64_t zero_point_count; -}; - -struct TensorDescriptor { - TensorDType dtype; - TensorLayout layout; - uint32_t rank; - TensorResidency residency; - uint64_t shape[4]; - uint64_t strides[4]; - uint64_t byte_len; - AbiQuantization quant; -}; - -struct TensorView { - const void *address; - TensorDescriptor descriptor; -}; - -struct ResidentTensor { - void *address; - TensorDescriptor descriptor; -}; - -static_assert(sizeof(AbiQuantization) == 48, "quant ABI drift"); -static_assert(sizeof(TensorDescriptor) == 136, "tensor descriptor ABI drift"); -static_assert(sizeof(TensorView) == 144, "tensor view ABI drift"); -static_assert(sizeof(ResidentTensor) == 144, "resident tensor ABI drift"); - -extern "C" int blackwell_tensor_upload( - const TensorView *host, ResidentTensor *device, cudaStream_t stream); -extern "C" void blackwell_tensor_free(ResidentTensor *device); diff --git a/crates/aien-inference-abi/examples/profile_blackwell_ops.rs b/crates/aien-inference-abi/examples/profile_blackwell_ops.rs deleted file mode 100644 index 57376cff..00000000 --- a/crates/aien-inference-abi/examples/profile_blackwell_ops.rs +++ /dev/null @@ -1,301 +0,0 @@ -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 deleted file mode 100644 index 66a8f3ee..00000000 --- a/crates/aien-inference-abi/src/blackwell_backend.rs +++ /dev/null @@ -1,632 +0,0 @@ -//! Genuine Blackwell GB10 Hardware Acceleration Backend for DGX Spark. -//! Dispatches single-token GEMV, batched GEMM, and Grouped Query Paged Attention -//! directly to CUDA and cuBLAS 13 on Blackwell sm_121. - -use crate::backend::{ReferenceCpuBackend, TensorBackend}; -use aien_kv_cache::KvLayoutDesc; -use std::ffi::CStr; -use std::os::raw::{c_char, c_float, c_int}; -use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; - -#[cfg(has_blackwell_cuda)] -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 paged_attention_bf16_forward( - q: *const u16, - kv_pool: *const u8, - pool_bytes: u64, - layout: *const KvLayoutDesc, - layer_idx: i32, - block_tables: *const i32, - context_lens: *const i32, - max_blocks_per_seq: c_int, - num_seqs: c_int, - num_q_heads: c_int, - num_kv_heads: c_int, - head_dim: c_int, - sm_scale: c_float, - out: *mut u16, - ) -> c_int; - fn paged_attention_get_kernel_count() -> u64; - #[allow(dead_code)] - fn blackwell_allocate_managed(bytes: usize) -> *mut std::ffi::c_void; - #[allow(dead_code)] - fn blackwell_free_managed(ptr: *mut std::ffi::c_void); - fn blackwell_gemm_destroy(); -} - -#[cfg(not(has_blackwell_cuda))] -unsafe fn blackwell_gemm_init() -> c_int { - -1 -} -#[cfg(not(has_blackwell_cuda))] -unsafe fn blackwell_gemm_get_kernel_count() -> u64 { - 0 -} -#[cfg(not(has_blackwell_cuda))] -unsafe fn paged_attention_get_kernel_count() -> u64 { - 0 -} -#[cfg(not(has_blackwell_cuda))] -unsafe fn blackwell_gemm_get_device_name(_buf: *mut c_char, _max_len: c_int) -> c_int { - -1 -} -#[cfg(not(has_blackwell_cuda))] -unsafe 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 { - -1 -} -#[cfg(not(has_blackwell_cuda))] -unsafe 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 { - -1 -} -#[cfg(not(has_blackwell_cuda))] -unsafe fn paged_attention_bf16_forward( - _q: *const u16, - _kv_pool: *const u8, - _pool_bytes: u64, - _layout: *const KvLayoutDesc, - _layer_idx: i32, - _block_tables: *const i32, - _context_lens: *const i32, - _max_blocks_per_seq: c_int, - _num_seqs: c_int, - _num_q_heads: c_int, - _num_kv_heads: c_int, - _head_dim: c_int, - _sm_scale: c_float, - _out: *mut u16, -) -> c_int { - -1 -} -#[allow(dead_code)] -#[cfg(not(has_blackwell_cuda))] -unsafe fn blackwell_allocate_managed(_bytes: usize) -> *mut std::ffi::c_void { - std::ptr::null_mut() -} -#[allow(dead_code)] -#[cfg(not(has_blackwell_cuda))] -unsafe fn blackwell_free_managed(_ptr: *mut std::ffi::c_void) {} -#[allow(dead_code)] -#[cfg(not(has_blackwell_cuda))] -unsafe fn blackwell_gemm_destroy() {} - -/// Blackwell GB10 GPU Tensor Backend. -/// Executes GEMV, batched GEMM, and Paged Attention on the NVIDIA GB10 Blackwell GPU. -static ACTIVE_BACKENDS: AtomicUsize = AtomicUsize::new(0); - -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 { - ACTIVE_BACKENDS.fetch_add(1, Ordering::SeqCst); - 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() + paged_attention_get_kernel_count() } - } else { - 0 - } - } - - pub fn fallback_count(&self) -> u64 { - self.fallback_counter.load(Ordering::Relaxed) - } - - /// Dispatches Grouped Query Paged Attention on Blackwell sm_121 - pub fn paged_attention_bf16( - &self, - q: &[u16], - kv_pool: &[u8], - layout: KvLayoutDesc, - layer_idx: usize, - block_tables: &[i32], - context_lens: &[i32], - max_blocks_per_seq: usize, - num_seqs: usize, - num_q_heads: usize, - num_kv_heads: usize, - head_dim: usize, - sm_scale: f32, - out: &mut [u16], - ) -> Result<(), String> { - if self.available { - let res = unsafe { - paged_attention_bf16_forward( - q.as_ptr(), - kv_pool.as_ptr(), - kv_pool.len() as u64, - &layout as *const KvLayoutDesc, - layer_idx as i32, - block_tables.as_ptr(), - context_lens.as_ptr(), - max_blocks_per_seq as c_int, - num_seqs as c_int, - num_q_heads as c_int, - num_kv_heads as c_int, - head_dim as c_int, - sm_scale as c_float, - out.as_mut_ptr(), - ) - }; - if res == 0 { - return Ok(()); - } - return Err(format!( - "paged_attention_bf16_forward failed with error code {}", - res - )); - } - Err("Blackwell GPU backend not available".to_string()) - } -} - -impl Default for BlackwellGb10Backend { - fn default() -> Self { - Self::new() - } -} - -impl Drop for BlackwellGb10Backend { - fn drop(&mut self) { - if self.available && ACTIVE_BACKENDS.fetch_sub(1, Ordering::SeqCst) == 1 { - unsafe { - blackwell_gemm_destroy(); - } - } - } -} - -impl TensorBackend for BlackwellGb10Backend { - fn fallback_count(&self) -> u64 { - self.fallback_counter.load(Ordering::Relaxed) - } - - 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); - crate::strict::fallback_taken("BlackwellGb10Backend", "tensor op"); - } - 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::strict::fallback_taken("BlackwellGb10Backend", "tensor op"); - } - 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 paged_attention( - &self, - out: &mut [f32], - q: &[f32], - pool: &aien_kv_cache::UnifiedKvTensorPool, - block_ids: &[usize], - context_len: usize, - layer_idx: usize, - num_q_heads: usize, - num_kv_heads: usize, - head_dim: usize, - ) { - if context_len == 0 || block_ids.is_empty() { - out.fill(0.0); - return; - } - - let i32_blocks: Vec = block_ids.iter().map(|&b| b as i32).collect(); - let context_lens = [context_len as i32]; - self.paged_attention_batch( - out, - q, - pool, - &i32_blocks, - &context_lens, - block_ids.len(), - 1, - layer_idx, - num_q_heads, - num_kv_heads, - head_dim, - ); - } - - fn paged_attention_batch( - &self, - out: &mut [f32], - q: &[f32], - pool: &aien_kv_cache::UnifiedKvTensorPool, - block_tables: &[i32], - context_lens: &[i32], - max_blocks_per_seq: usize, - num_seqs: usize, - layer_idx: usize, - num_q_heads: usize, - num_kv_heads: usize, - head_dim: usize, - ) { - if num_seqs == 0 || max_blocks_per_seq == 0 { - out.fill(0.0); - return; - } - - if self.available && pool.config().dtype == aien_kv_cache::KvDType::Bf16 { - let q_bf16: Vec = q - .iter() - .map(|&v| aien_kv_cache::f32_to_bf16_bits(v)) - .collect(); - - let sm_scale = 1.0f32 / (head_dim as f32).sqrt(); - let mut out_bf16 = vec![0u16; out.len()]; - - let layout_desc = pool.layout_desc(); - let kv_slice = - unsafe { std::slice::from_raw_parts(pool.base_ptr(), pool.total_bytes()) }; - - let res = self.paged_attention_bf16( - &q_bf16, - kv_slice, - layout_desc, - layer_idx, - block_tables, - context_lens, - max_blocks_per_seq, - num_seqs, - num_q_heads, - num_kv_heads, - head_dim, - sm_scale, - &mut out_bf16, - ); - - if res.is_ok() { - for i in 0..out.len() { - out[i] = aien_kv_cache::bf16_bits_to_f32(out_bf16[i]); - } - return; - } - self.fallback_counter.fetch_add(1, Ordering::Relaxed); - crate::strict::fallback_taken("BlackwellGb10Backend", "tensor op"); - } - - self.fallback.paged_attention_batch( - out, - q, - pool, - block_tables, - context_lens, - max_blocks_per_seq, - num_seqs, - layer_idx, - 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); - crate::strict::fallback_taken("BlackwellGb10Backend", "tensor op"); - } - 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); - } - - #[test] - fn test_blackwell_paged_attention_kernel() { - let backend = BlackwellGb10Backend::new(); - if !backend.is_available() { - eprintln!("Skipping GPU test: Blackwell hardware not available"); - return; - } - - let num_seqs = 2; - let num_q_heads = 4; - let num_kv_heads = 2; - let head_dim = 64; - let block_size = 16; - let num_blocks = 8; - let num_layers = 1; - let layer_idx = 0; - let max_blocks_per_seq = 4; - - let config = aien_kv_cache::KvPoolConfig { - num_blocks, - block_size, - num_layers, - num_kv_heads, - head_dim, - dtype: aien_kv_cache::KvDType::Bf16, - }; - let layout = aien_kv_cache::KvLayout::for_bf16(&config).expect("Layout generation failed"); - let layout_desc = layout.to_desc(); - - let q = vec![0x3F80u16; num_seqs * num_q_heads * head_dim]; // 1.0 in BF16 - let mut kv_pool = vec![0u8; layout.total_bytes]; - unsafe { - let u16_ptr = kv_pool.as_mut_ptr() as *mut u16; - for i in 0..(layout.total_bytes / 2) { - *u16_ptr.add(i) = 0x3F80; - } - } - - let block_tables = vec![ - 0, 1, -1, -1, // seq 0: blocks 0, 1 - 2, 3, -1, -1, // seq 1: blocks 2, 3 - ]; - let context_lens = vec![30, 25]; // 30 tokens in seq 0, 25 tokens in seq 1 - let sm_scale = 1.0f32 / (head_dim as f32).sqrt(); - - let mut out = vec![0u16; num_seqs * num_q_heads * head_dim]; - - let res = backend.paged_attention_bf16( - &q, - &kv_pool, - layout_desc, - layer_idx, - &block_tables, - &context_lens, - max_blocks_per_seq, - num_seqs, - num_q_heads, - num_kv_heads, - head_dim, - sm_scale, - &mut out, - ); - - assert!(res.is_ok(), "paged_attention_bf16 failed: {:?}", res.err()); - assert_eq!( - out[0], 0x3F80, - "Expected 1.0 (0x3F80) in BF16, got 0x{:04x}", - out[0] - ); - } -} diff --git a/crates/aien-inference-abi/src/blackwell_batch.rs b/crates/aien-inference-abi/src/blackwell_batch.rs deleted file mode 100644 index 357ffd5c..00000000 --- a/crates/aien-inference-abi/src/blackwell_batch.rs +++ /dev/null @@ -1,186 +0,0 @@ -use crate::ScheduledBatch; -use serde::{Deserialize, Serialize}; -use std::collections::HashMap; - -/// Single token row within a unified Blackwell batch plan. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct BlackwellBatchRow { - pub seq_id: u64, - pub token_id: u32, - pub pos: usize, - pub is_decode: bool, - pub is_terminal: bool, -} - -/// Unified Blackwell execution batch plan with T = D + P rows. -/// Consolidates linear projections (QKV, MLP gate/up, down) into single GEMM operations -/// across all active decode sequences and chunked prefill spans. -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct BlackwellBatchPlan { - pub step_id: u64, - pub rows: Vec, - pub decode_count: usize, - pub prefill_count: usize, - pub total_rows: usize, - pub terminal_row_indices: Vec, - pub block_tables: HashMap>, - pub context_lens: HashMap, - pub max_blocks_per_seq: usize, -} - -impl BlackwellBatchPlan { - /// Constructs a unified batch plan from a ScheduledBatch and current sequence states. - pub fn from_scheduled_batch( - batch: &ScheduledBatch, - last_tokens: &HashMap, - prefill_positions: &HashMap, - ) -> Self { - let mut rows = Vec::new(); - let mut terminal_row_indices = Vec::new(); - let mut decode_count = 0; - let mut prefill_count = 0; - - // 1. Decode rows (D rows) - for &seq_id in &batch.decode_requests { - let (token_id, pos) = last_tokens.get(&seq_id).copied().unwrap_or((1, 0)); - let row_idx = rows.len(); - rows.push(BlackwellBatchRow { - seq_id, - token_id, - pos, - is_decode: true, - is_terminal: true, - }); - terminal_row_indices.push(row_idx); - decode_count += 1; - } - - // 2. Prefill rows (P rows) - for req in &batch.prefill_requests { - let seq_id = req.request_id; - let start_pos = prefill_positions.get(&seq_id).copied().unwrap_or(0); - let n_tokens = req.prompt_tokens.len(); - - for (idx, &token_id) in req.prompt_tokens.iter().enumerate() { - let pos = start_pos + idx; - let is_terminal = idx == n_tokens.saturating_sub(1); - let row_idx = rows.len(); - - rows.push(BlackwellBatchRow { - seq_id, - token_id, - pos, - is_decode: false, - is_terminal, - }); - - if is_terminal { - terminal_row_indices.push(row_idx); - } - prefill_count += 1; - } - } - - let total_rows = rows.len(); - - let mut block_tables = HashMap::new(); - let mut max_blocks = 1; - for (&seq_id, blocks) in &batch.block_tables { - let i32_blocks: Vec = blocks.iter().map(|&b| b as i32).collect(); - if i32_blocks.len() > max_blocks { - max_blocks = i32_blocks.len(); - } - block_tables.insert(seq_id, i32_blocks); - } - - let mut context_lens = HashMap::new(); - for row in &rows { - context_lens.insert(row.seq_id, row.pos + 1); - } - - Self { - step_id: batch.step_id, - rows, - decode_count, - prefill_count, - total_rows, - terminal_row_indices, - block_tables, - context_lens, - max_blocks_per_seq: max_blocks, - } - } - - pub fn is_empty(&self) -> bool { - self.total_rows == 0 - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::{SamplingParams, SequenceRequest}; - - #[test] - fn test_batch_plan_construction_and_terminal_row_indices() { - let mut block_tables = HashMap::new(); - block_tables.insert(1, vec![0, 1]); - block_tables.insert(2, vec![2]); - block_tables.insert(100, vec![3, 4]); - - let prefill_req = SequenceRequest { - request_id: 100, - prompt_tokens: vec![10, 20, 30], - sampling_params: SamplingParams::default(), - arrival_time_ns: 0, - priority: 1, - }; - - let batch = ScheduledBatch { - prefill_requests: vec![prefill_req], - decode_requests: vec![1, 2], - block_tables, - step_id: 42, - }; - - let mut last_tokens = HashMap::new(); - last_tokens.insert(1, (101, 15)); - last_tokens.insert(2, (102, 7)); - - let prefill_positions = HashMap::new(); - - let plan = - BlackwellBatchPlan::from_scheduled_batch(&batch, &last_tokens, &prefill_positions); - - assert_eq!(plan.step_id, 42); - assert_eq!(plan.decode_count, 2); - assert_eq!(plan.prefill_count, 3); - assert_eq!(plan.total_rows, 5); // T = 2 + 3 = 5 - - // Rows 0 and 1 are decode (terminal) - assert!(plan.rows[0].is_decode); - assert!(plan.rows[0].is_terminal); - assert_eq!(plan.rows[0].token_id, 101); - - assert!(plan.rows[1].is_decode); - assert!(plan.rows[1].is_terminal); - assert_eq!(plan.rows[1].token_id, 102); - - // Rows 2 and 3 are intermediate prefill (non-terminal) - assert!(!plan.rows[2].is_decode); - assert!(!plan.rows[2].is_terminal); - assert_eq!(plan.rows[2].token_id, 10); - - assert!(!plan.rows[3].is_decode); - assert!(!plan.rows[3].is_terminal); - assert_eq!(plan.rows[3].token_id, 20); - - // Row 4 is final prefill (terminal) - assert!(!plan.rows[4].is_decode); - assert!(plan.rows[4].is_terminal); - assert_eq!(plan.rows[4].token_id, 30); - - // Terminal rows must be [0, 1, 4] - assert_eq!(plan.terminal_row_indices, vec![0, 1, 4]); - } -} diff --git a/crates/aien-inference-abi/src/blackwell_batch_executor.rs b/crates/aien-inference-abi/src/blackwell_batch_executor.rs deleted file mode 100644 index d954a284..00000000 --- a/crates/aien-inference-abi/src/blackwell_batch_executor.rs +++ /dev/null @@ -1,799 +0,0 @@ -//! Real Batched Blackwell Batch Executor for NVIDIA DGX Spark (Grace Blackwell GB10, sm_121). -//! Enforces: -//! - Resident model weights with fused GQA QKV (q_dim + 2 * kv_dim) and fused Gate/Up projections. -//! - Persistent GPU-visible workspace (zero allocations during step). -//! - Rust-to-layer call boundary (zero cudaDeviceSynchronize inside layers). -//! - Ragged prefill + batched decode attention. -//! - GPU KV scatter directly into canonical BF16 physical pool layout. -//! - Terminal-row logits and GPU-side argmax sampling. -//! - Exactly ONE completion fence per scheduler step. -//! - Strict KV transaction semantics (reserve -> execute -> commit / rollback). -//! - Zero CPU fallback in accelerated mode. - -use crate::tensor_abi::ResidentTensor; -#[cfg(has_blackwell_cuda)] -use crate::tensor_abi::TensorView; -use crate::weights::TransformerWeights; -use crate::{AienInferenceBackend, DecodeOutput, ModelConfig, ScheduledBatch, StepMetrics}; -#[allow(unused_imports)] -use aien_kv_cache::{AienKvManager, KvLayoutDesc, SharedKvManager}; -use async_trait::async_trait; -use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; -use std::time::Instant; - -#[repr(C)] -pub struct BlackwellResidentLayerWeights { - pub d_norm1: ResidentTensor, - pub d_w_qkv: ResidentTensor, - pub d_w_o: ResidentTensor, - pub d_norm2: ResidentTensor, - pub d_w_gate_up: ResidentTensor, - pub d_w_down: ResidentTensor, -} - -#[repr(C)] -pub struct BlackwellResidentModelWeights { - pub num_layers: std::os::raw::c_int, - pub hidden_dim: std::os::raw::c_int, - pub num_q_heads: std::os::raw::c_int, - pub num_kv_heads: std::os::raw::c_int, - pub head_dim: std::os::raw::c_int, - pub intermediate_dim: std::os::raw::c_int, - pub vocab_size: std::os::raw::c_int, - pub rms_norm_eps: f32, - pub rope_theta: f32, - - pub d_embed_tokens: ResidentTensor, - pub layers: *mut BlackwellResidentLayerWeights, - pub d_final_norm: ResidentTensor, - pub d_lm_head: ResidentTensor, -} - -#[repr(C)] -pub struct BlackwellWorkspaceC { - pub max_tokens: std::os::raw::c_int, - pub d_x_a: *mut f32, - pub d_x_b: *mut f32, - pub d_x_norm: *mut f32, - pub d_qkv: *mut f32, - pub d_attn_out: *mut f32, - pub d_attn_proj: *mut f32, - pub d_post_norm: *mut f32, - pub d_gate_up: *mut f32, - pub d_act: *mut f32, - pub d_mlp_out: *mut f32, - - pub d_term_x: *mut f32, - pub d_logits: *mut f32, - pub d_tokens: *mut u32, - - pub d_positions: *mut i32, - pub d_block_ids: *mut i32, - pub d_slots: *mut i32, - pub d_block_tables: *mut i32, - pub d_context_lens: *mut i32, - pub d_term_indices: *mut i32, - pub d_prefill_offsets: *mut i32, -} - -#[repr(C)] -pub struct BlackwellBatchPlanC { - pub num_tokens: std::os::raw::c_int, - pub decode_count: std::os::raw::c_int, - pub prefill_count: std::os::raw::c_int, - pub terminal_count: std::os::raw::c_int, - pub max_blocks_per_seq: std::os::raw::c_int, - - pub h_input_tokens: *const u32, - pub h_input_embeddings: *const f32, - pub h_positions: *const i32, - pub h_block_ids: *const i32, - pub h_slots: *const i32, - pub h_decode_block_tables: *const i32, - pub h_decode_context_lens: *const i32, - pub h_term_indices: *const i32, - pub h_prefill_offsets: *const i32, -} - -#[cfg(has_blackwell_cuda)] -extern "C" { - fn blackwell_gemm_init() -> std::os::raw::c_int; - fn blackwell_gemm_get_kernel_count() -> u64; - fn blackwell_get_stream() -> *mut std::ffi::c_void; - fn blackwell_get_cublas_handle() -> *mut std::ffi::c_void; - - fn blackwell_workspace_create( - max_tokens: std::os::raw::c_int, - hidden_dim: std::os::raw::c_int, - q_dim: std::os::raw::c_int, - kv_dim: std::os::raw::c_int, - intermediate_dim: std::os::raw::c_int, - vocab_size: std::os::raw::c_int, - max_blocks_per_seq: std::os::raw::c_int, - ) -> *mut BlackwellWorkspaceC; - - fn blackwell_workspace_free(ws: *mut BlackwellWorkspaceC); - - fn blackwell_layer_weights_create( - h_norm1: *const TensorView, - h_w_qkv: *const TensorView, - h_w_o: *const TensorView, - h_norm2: *const TensorView, - h_w_gate_up: *const TensorView, - h_w_down: *const TensorView, - hidden_dim: std::os::raw::c_int, - q_dim: std::os::raw::c_int, - kv_dim: std::os::raw::c_int, - intermediate_dim: std::os::raw::c_int, - stream: *mut std::ffi::c_void, - ) -> *mut BlackwellResidentLayerWeights; - - #[allow(dead_code)] - fn blackwell_layer_weights_free(lw: *mut BlackwellResidentLayerWeights); - - fn blackwell_model_weights_create( - num_layers: std::os::raw::c_int, - hidden_dim: std::os::raw::c_int, - num_q_heads: std::os::raw::c_int, - num_kv_heads: std::os::raw::c_int, - head_dim: std::os::raw::c_int, - intermediate_dim: std::os::raw::c_int, - vocab_size: std::os::raw::c_int, - rms_norm_eps: f32, - rope_theta: f32, - h_embed_tokens: *const TensorView, - h_final_norm: *const TensorView, - h_lm_head: *const TensorView, - stream: *mut std::ffi::c_void, - ) -> *mut BlackwellResidentModelWeights; - - fn blackwell_model_weights_set_layer( - mw: *mut BlackwellResidentModelWeights, - layer_idx: std::os::raw::c_int, - lw: *const BlackwellResidentLayerWeights, - ); - - fn blackwell_model_weights_free(mw: *mut BlackwellResidentModelWeights); - - fn blackwell_execute_layer( - layer_idx: std::os::raw::c_int, - weights: *const BlackwellResidentLayerWeights, - plan: *const BlackwellBatchPlanC, - workspace: *mut BlackwellWorkspaceC, - kv_pool: *mut u8, - layout: *const KvLayoutDesc, - stream: *mut std::ffi::c_void, - cublas_handle: *mut std::ffi::c_void, - is_ping: std::os::raw::c_int, - hidden_dim: std::os::raw::c_int, - num_q_heads: std::os::raw::c_int, - num_kv_heads: std::os::raw::c_int, - head_dim: std::os::raw::c_int, - intermediate_dim: std::os::raw::c_int, - eps: f32, - theta: f32, - ) -> std::os::raw::c_int; - - fn blackwell_execute_step( - model: *const BlackwellResidentModelWeights, - plan: *const BlackwellBatchPlanC, - workspace: *mut BlackwellWorkspaceC, - kv_pool: *mut u8, - layout: *const KvLayoutDesc, - h_sampled_tokens: *mut u32, - stream: *mut std::ffi::c_void, - cublas_handle: *mut std::ffi::c_void, - ) -> std::os::raw::c_int; -} - -/// Structured execution plan for a single batched inference step. -#[derive(Debug, Clone, Default)] -pub struct BlackwellBatchPlan { - pub num_tokens: usize, - pub decode_count: usize, - pub prefill_count: usize, - pub terminal_count: usize, - pub max_blocks_per_seq: usize, - - pub input_tokens: Vec, - pub positions: Vec, - pub block_ids: Vec, - pub slots: Vec, - pub decode_block_tables: Vec, - pub decode_context_lens: Vec, - pub terminal_row_indices: Vec, - pub prefill_offsets: Vec, - pub terminal_request_ids: Vec, -} - -/// GPU-resident weights wrapper. -pub struct BlackwellResidentModel { - pub config: ModelConfig, - #[allow(dead_code)] - raw: *mut BlackwellResidentModelWeights, -} - -unsafe impl Send for BlackwellResidentModel {} -unsafe impl Sync for BlackwellResidentModel {} - -impl Drop for BlackwellResidentModel { - fn drop(&mut self) { - #[cfg(has_blackwell_cuda)] - if !self.raw.is_null() { - unsafe { blackwell_model_weights_free(self.raw) }; - self.raw = std::ptr::null_mut(); - } - } -} - -/// Persistent GPU-visible workspace wrapper. -pub struct BlackwellWorkspace { - pub max_tokens: usize, - #[allow(dead_code)] - raw: *mut BlackwellWorkspaceC, -} - -unsafe impl Send for BlackwellWorkspace {} -unsafe impl Sync for BlackwellWorkspace {} - -impl Drop for BlackwellWorkspace { - fn drop(&mut self) { - #[cfg(has_blackwell_cuda)] - if !self.raw.is_null() { - unsafe { blackwell_workspace_free(self.raw) }; - self.raw = std::ptr::null_mut(); - } - } -} - -/// Canonical Blackwell GB10 Batch Executor. -pub struct BlackwellBatchExecutor { - pub config: ModelConfig, - pub resident_model: BlackwellResidentModel, - pub workspace: BlackwellWorkspace, - pub kv_manager: Option, - pub fallback_count: AtomicUsize, - pub step_count: AtomicU64, -} - -impl BlackwellBatchExecutor { - /// Creates a new BlackwellBatchExecutor with resident weights and pre-allocated GPU workspace. - pub fn new(weights: &TransformerWeights, max_tokens: usize) -> Result { - let config = weights.config.clone(); - - #[cfg(has_blackwell_cuda)] - { - let init_res = unsafe { blackwell_gemm_init() }; - if init_res != 0 { - return Err(format!( - "blackwell_gemm_init failed with error {}", - init_res - )); - } - - let stream = unsafe { blackwell_get_stream() }; - let cublas_handle = unsafe { blackwell_get_cublas_handle() }; - - if stream.is_null() || cublas_handle.is_null() { - return Err("Failed to obtain CUDA stream or cuBLAS handle".to_string()); - } - - let hidden_dim = config.hidden_dim(); - let num_q_heads = config.num_heads; - let num_kv_heads = config.num_kv_heads; - let head_dim = config.head_dim; - let q_dim = num_q_heads * head_dim; - let kv_dim = num_kv_heads * head_dim; - let intermediate_dim = config.intermediate_dim(); - let vocab_size = config.vocab_size(); - let max_blocks_per_seq = 256; - - // 1. Allocate persistent workspace - let ws_raw = unsafe { - blackwell_workspace_create( - max_tokens as i32, - hidden_dim as i32, - q_dim as i32, - kv_dim as i32, - intermediate_dim as i32, - vocab_size as i32, - max_blocks_per_seq, - ) - }; - if ws_raw.is_null() { - return Err("Failed to allocate BlackwellWorkspace on GB10".to_string()); - } - let workspace = BlackwellWorkspace { - max_tokens, - raw: ws_raw, - }; - - // 2. Create resident model weights - let embed_view = - TensorView::f32_contiguous(&weights.embed_tokens, &[vocab_size, hidden_dim])?; - let final_norm_view = TensorView::f32_contiguous(&weights.final_norm, &[hidden_dim])?; - let lm_head_view = - TensorView::f32_contiguous(&weights.lm_head, &[vocab_size, hidden_dim])?; - let model_raw = unsafe { - blackwell_model_weights_create( - config.num_layers as i32, - hidden_dim as i32, - num_q_heads as i32, - num_kv_heads as i32, - head_dim as i32, - intermediate_dim as i32, - vocab_size as i32, - config.rms_norm_eps, - config.rope_theta, - embed_view.as_abi(), - final_norm_view.as_abi(), - lm_head_view.as_abi(), - stream, - ) - }; - if model_raw.is_null() { - return Err("Failed to allocate BlackwellResidentModelWeights on GB10".to_string()); - } - let resident_model = BlackwellResidentModel { - config: config.clone(), - raw: model_raw, - }; - - // 3. Fuse and upload layer weights: - // W_qkv has width q_dim + 2 * kv_dim (Section 6 correction) - // W_gate_up has width 2 * intermediate_dim - let qkv_dim = q_dim + 2 * kv_dim; - for (l_idx, lw) in weights.layers.iter().enumerate() { - let mut fused_qkv = vec![0.0f32; qkv_dim * hidden_dim]; - fused_qkv[0..q_dim * hidden_dim].copy_from_slice(&lw.q_proj); - fused_qkv[q_dim * hidden_dim..(q_dim + kv_dim) * hidden_dim] - .copy_from_slice(&lw.k_proj); - fused_qkv[(q_dim + kv_dim) * hidden_dim..(q_dim + 2 * kv_dim) * hidden_dim] - .copy_from_slice(&lw.v_proj); - - let mut fused_gate_up = vec![0.0f32; 2 * intermediate_dim * hidden_dim]; - fused_gate_up[0..intermediate_dim * hidden_dim].copy_from_slice(&lw.gate_proj); - fused_gate_up[intermediate_dim * hidden_dim..2 * intermediate_dim * hidden_dim] - .copy_from_slice(&lw.up_proj); - - let norm1_view = TensorView::f32_contiguous(&lw.input_layernorm, &[hidden_dim])?; - let qkv_view = TensorView::f32_contiguous(&fused_qkv, &[qkv_dim, hidden_dim])?; - let o_view = TensorView::f32_contiguous(&lw.o_proj, &[hidden_dim, q_dim])?; - let norm2_view = - TensorView::f32_contiguous(&lw.post_attention_layernorm, &[hidden_dim])?; - let gate_up_view = TensorView::f32_contiguous( - &fused_gate_up, - &[2 * intermediate_dim, hidden_dim], - )?; - let down_view = - TensorView::f32_contiguous(&lw.down_proj, &[hidden_dim, intermediate_dim])?; - - let layer_raw = unsafe { - blackwell_layer_weights_create( - norm1_view.as_abi(), - qkv_view.as_abi(), - o_view.as_abi(), - norm2_view.as_abi(), - gate_up_view.as_abi(), - down_view.as_abi(), - hidden_dim as i32, - q_dim as i32, - kv_dim as i32, - intermediate_dim as i32, - stream, - ) - }; - - if layer_raw.is_null() { - return Err(format!("Failed to upload layer {} weights to GB10", l_idx)); - } - - unsafe { - blackwell_model_weights_set_layer(model_raw, l_idx as i32, layer_raw); - } - } - - Ok(Self { - config, - resident_model, - workspace, - kv_manager: None, - fallback_count: AtomicUsize::new(0), - step_count: AtomicU64::new(0), - }) - } - - #[cfg(not(has_blackwell_cuda))] - { - let resident_model = BlackwellResidentModel { - config: config.clone(), - raw: std::ptr::null_mut(), - }; - let workspace = BlackwellWorkspace { - max_tokens, - raw: std::ptr::null_mut(), - }; - Ok(Self { - config, - resident_model, - workspace, - kv_manager: None, - fallback_count: AtomicUsize::new(0), - step_count: AtomicU64::new(0), - }) - } - } - - pub fn with_kv_manager(mut self, kv_mgr: SharedKvManager) -> Self { - self.kv_manager = Some(kv_mgr); - self - } - - pub fn fallback_count(&self) -> usize { - self.fallback_count.load(Ordering::SeqCst) - } - - pub fn kernel_exec_count(&self) -> u64 { - #[cfg(has_blackwell_cuda)] - unsafe { - blackwell_gemm_get_kernel_count() - } - #[cfg(not(has_blackwell_cuda))] - 0 - } - - /// Builds structured execution plan reserving KV blocks and slots. - pub fn build_batch_plan( - &self, - batch: &ScheduledBatch, - kv_manager: &mut AienKvManager, - ) -> Result { - let decode_count = batch.decode_requests.len(); - let prefill_count = batch.prefill_requests.len(); - let total_prefill_tokens: usize = batch - .prefill_requests - .iter() - .map(|r| r.prompt_tokens.len()) - .sum(); - let total_tokens = decode_count + total_prefill_tokens; - - if total_tokens > self.workspace.max_tokens { - return Err(format!( - "Batch size {} exceeds persistent workspace capacity {}", - total_tokens, self.workspace.max_tokens - )); - } - - let mut plan = BlackwellBatchPlan { - num_tokens: total_tokens, - decode_count, - prefill_count, - terminal_count: decode_count + prefill_count, - max_blocks_per_seq: 256, - input_tokens: Vec::with_capacity(total_tokens), - positions: Vec::with_capacity(total_tokens), - block_ids: Vec::with_capacity(total_tokens), - slots: Vec::with_capacity(total_tokens), - decode_block_tables: Vec::with_capacity(decode_count * 256), - decode_context_lens: Vec::with_capacity(decode_count), - terminal_row_indices: Vec::with_capacity(decode_count + prefill_count), - prefill_offsets: Vec::with_capacity(prefill_count + 1), - terminal_request_ids: Vec::with_capacity(decode_count + prefill_count), - }; - - // 1. Process Decode Sequences (rows 0 .. decode_count) - for (idx, &req_id) in batch.decode_requests.iter().enumerate() { - let (block_id, slot) = kv_manager.append_token_with_slot(req_id)?; - let table = kv_manager - .get_block_table(req_id) - .ok_or_else(|| format!("BlockTable missing for decode sequence {}", req_id))?; - - let pos = (table.total_tokens.saturating_sub(1)) as i32; - plan.input_tokens.push(1); // placeholder token for decode step - plan.positions.push(pos); - plan.block_ids.push(block_id as i32); - plan.slots.push(slot as i32); - - let mut blocks_padded = vec![0i32; 256]; - for (b_idx, &b_id) in table.block_ids.iter().take(256).enumerate() { - blocks_padded[b_idx] = b_id as i32; - } - plan.decode_block_tables.extend_from_slice(&blocks_padded); - plan.decode_context_lens.push(table.total_tokens as i32); - - plan.terminal_row_indices.push(idx as i32); - plan.terminal_request_ids.push(req_id); - } - - // 2. Process Prefill Sequences (rows decode_count .. total_tokens) - let mut cur_offset = 0i32; - plan.prefill_offsets.push(cur_offset); - - for req in &batch.prefill_requests { - let assigned_blocks = - kv_manager.allocate_sequence(req.request_id, &req.prompt_tokens)?; - let p_len = req.prompt_tokens.len(); - let block_size = kv_manager.block_size(); - - let row_start = plan.input_tokens.len(); - for (t_idx, &tok) in req.prompt_tokens.iter().enumerate() { - let blk_idx = t_idx / block_size; - let slot = t_idx % block_size; - let blk_id = assigned_blocks[blk_idx]; - - plan.input_tokens.push(tok); - plan.positions.push(t_idx as i32); - plan.block_ids.push(blk_id as i32); - plan.slots.push(slot as i32); - } - - cur_offset += p_len as i32; - plan.prefill_offsets.push(cur_offset); - - // Last token of prefill prompt is terminal - let last_row = row_start + p_len - 1; - plan.terminal_row_indices.push(last_row as i32); - plan.terminal_request_ids.push(req.request_id); - } - - Ok(plan) - } - - /// Single layer execution boundary adhering to Section 6 Rust-to-layer doctrine. - /// Rust iterates layers, invoking blackwell_execute_layer without returning intermediates. - /// Zero cudaDeviceSynchronize inside a layer! - pub fn execute_layer( - &mut self, - _layer_idx: usize, - _plan: &BlackwellBatchPlan, - _kv_manager: &AienKvManager, - ) -> Result<(), String> { - #[cfg(has_blackwell_cuda)] - { - let layer_idx = _layer_idx; - let plan = _plan; - let kv_manager = _kv_manager; - let stream = unsafe { blackwell_get_stream() }; - let cublas_handle = unsafe { blackwell_get_cublas_handle() }; - - let plan_c = BlackwellBatchPlanC { - num_tokens: plan.num_tokens as i32, - decode_count: plan.decode_count as i32, - prefill_count: plan.prefill_count as i32, - terminal_count: plan.terminal_count as i32, - max_blocks_per_seq: plan.max_blocks_per_seq as i32, - h_input_tokens: plan.input_tokens.as_ptr(), - h_input_embeddings: std::ptr::null(), - h_positions: plan.positions.as_ptr(), - h_block_ids: plan.block_ids.as_ptr(), - h_slots: plan.slots.as_ptr(), - h_decode_block_tables: plan.decode_block_tables.as_ptr(), - h_decode_context_lens: plan.decode_context_lens.as_ptr(), - h_term_indices: plan.terminal_row_indices.as_ptr(), - h_prefill_offsets: plan.prefill_offsets.as_ptr(), - }; - - let pool = kv_manager - .pool() - .ok_or_else(|| "KV pool not attached".to_string())?; - let kv_pool_ptr = pool.base_ptr() as *mut u8; - let layout = pool.layout_desc(); - - let res = unsafe { - let layer_weights = (*self.resident_model.raw).layers.add(layer_idx); - blackwell_execute_layer( - layer_idx as i32, - layer_weights, - &plan_c, - self.workspace.raw, - kv_pool_ptr, - &layout, - stream, - cublas_handle, - (layer_idx % 2) as i32, - self.config.hidden_dim() as i32, - self.config.num_heads as i32, - self.config.num_kv_heads as i32, - self.config.head_dim as i32, - self.config.intermediate_dim() as i32, - self.config.rms_norm_eps, - self.config.rope_theta, - ) - }; - - if res != 0 { - return Err(format!("blackwell_execute_layer failed with error {}", res)); - } - Ok(()) - } - - #[cfg(not(has_blackwell_cuda))] - { - self.fallback_count.fetch_add(1, Ordering::SeqCst); - crate::strict::fallback_taken("BlackwellBatchExecutor", "batch step"); - Ok(()) - } - } - - /// Executes scheduled batch with strict transactional KV commit/rollback. - pub fn execute_step_transactional( - &mut self, - batch: &ScheduledBatch, - kv_manager: &mut AienKvManager, - ) -> Result<(Vec, StepMetrics), String> { - let t0 = Instant::now(); - - if batch.decode_requests.is_empty() && batch.prefill_requests.is_empty() { - return Ok(( - Vec::new(), - StepMetrics { - prefill_tokens_processed: 0, - decode_tokens_emitted: 0, - step_latency_us: 0, - active_kv_blocks: kv_manager.allocated_block_count(), - }, - )); - } - - // 1. Transaction Start - let mut tx = kv_manager.begin_transaction(); - - // 2. Build Plan & Reserve Physical Pages - let plan = match self.build_batch_plan(batch, kv_manager) { - Ok(p) => p, - Err(e) => { - tx.rollback(kv_manager); - return Err(e); - } - }; - - // 3. GPU Step Execution with Exactly ONE Completion Fence - let mut sampled_tokens = vec![0u32; plan.terminal_count]; - - #[cfg(has_blackwell_cuda)] - { - let stream = unsafe { blackwell_get_stream() }; - let cublas_handle = unsafe { blackwell_get_cublas_handle() }; - - let plan_c = BlackwellBatchPlanC { - num_tokens: plan.num_tokens as i32, - decode_count: plan.decode_count as i32, - prefill_count: plan.prefill_count as i32, - terminal_count: plan.terminal_count as i32, - max_blocks_per_seq: plan.max_blocks_per_seq as i32, - h_input_tokens: plan.input_tokens.as_ptr(), - h_input_embeddings: std::ptr::null(), - h_positions: plan.positions.as_ptr(), - h_block_ids: plan.block_ids.as_ptr(), - h_slots: plan.slots.as_ptr(), - h_decode_block_tables: plan.decode_block_tables.as_ptr(), - h_decode_context_lens: plan.decode_context_lens.as_ptr(), - h_term_indices: plan.terminal_row_indices.as_ptr(), - h_prefill_offsets: plan.prefill_offsets.as_ptr(), - }; - - let pool = kv_manager - .pool() - .ok_or_else(|| "KV pool not attached".to_string())?; - let kv_pool_ptr = pool.base_ptr() as *mut u8; - let layout = pool.layout_desc(); - - let status = unsafe { - blackwell_execute_step( - self.resident_model.raw, - &plan_c, - self.workspace.raw, - kv_pool_ptr, - &layout, - sampled_tokens.as_mut_ptr(), - stream, - cublas_handle, - ) - }; - - if status != 0 { - tx.rollback(kv_manager); - return Err(format!( - "blackwell_execute_step failed with error {}", - status - )); - } - } - - #[cfg(not(has_blackwell_cuda))] - { - self.fallback_count.fetch_add(1, Ordering::SeqCst); - crate::strict::fallback_taken("BlackwellBatchExecutor", "batch step"); - sampled_tokens.fill(100); - } - - // 4. Transaction Commit on Completion Fence Success - tx.commit(); - - self.step_count.fetch_add(1, Ordering::SeqCst); - let elapsed_us = t0.elapsed().as_micros() as u64; - - let mut outputs = Vec::with_capacity(plan.terminal_count); - for (idx, &req_id) in plan.terminal_request_ids.iter().enumerate() { - let tok = sampled_tokens[idx]; - outputs.push(DecodeOutput::Token { - request_id: req_id, - token_id: tok, - logprob: Some(-0.01), - }); - } - - let prefill_tokens_processed = batch - .prefill_requests - .iter() - .map(|r| r.prompt_tokens.len()) - .sum(); - let decode_tokens_emitted = plan.terminal_count; - - Ok(( - outputs, - StepMetrics { - prefill_tokens_processed, - decode_tokens_emitted, - step_latency_us: elapsed_us, - active_kv_blocks: kv_manager.allocated_block_count(), - }, - )) - } -} - -#[cfg(all(test, has_blackwell_cuda))] -mod typed_residency_tests { - use super::*; - use crate::tensor_abi::{AbiDType, AbiResidency}; - - #[test] - fn dense_weights_keep_f32_values_with_typed_residency() { - let config = ModelConfig { - model_id: "typed-residency-test".to_string(), - max_sequence_length: 16, - block_size: 16, - num_layers: 1, - num_heads: 2, - head_dim: 8, - num_kv_heads: 1, - hidden_dim: 16, - intermediate_dim: 32, - vocab_size: 32, - rms_norm_eps: 1e-5, - rope_theta: 10000.0, - }; - let weights = TransformerWeights::reference_test_weights(&config); - let executor = BlackwellBatchExecutor::new(&weights, 2).unwrap(); - let model = unsafe { &*executor.resident_model.raw }; - assert_eq!(model.d_embed_tokens.descriptor.dtype, AbiDType::F32); - assert_eq!( - model.d_embed_tokens.descriptor.residency, - AbiResidency::Device - ); - assert_eq!(model.d_embed_tokens.descriptor.shape[..2], [32, 16]); - let layer = unsafe { &*model.layers }; - assert_eq!(layer.d_w_qkv.descriptor.dtype, AbiDType::F32); - assert_eq!(layer.d_w_qkv.descriptor.shape[..2], [32, 16]); - assert_eq!(layer.d_w_gate_up.descriptor.shape[..2], [64, 16]); - } -} - -#[async_trait] -impl AienInferenceBackend for BlackwellBatchExecutor { - async fn load_model(&mut self, _config: &ModelConfig) -> Result<(), String> { - Ok(()) - } - - async fn execute_step( - &mut self, - batch: &ScheduledBatch, - ) -> Result<(Vec, StepMetrics), String> { - if let Some(kv_mgr_arc) = self.kv_manager.clone() { - let mut mgr = kv_mgr_arc.write(); - self.execute_step_transactional(batch, &mut *mgr) - } else { - Err("No shared KV manager configured on BlackwellBatchExecutor".to_string()) - } - } -} diff --git a/crates/aien-inference-abi/src/lib.rs b/crates/aien-inference-abi/src/lib.rs index 15234b62..678faf7a 100644 --- a/crates/aien-inference-abi/src/lib.rs +++ b/crates/aien-inference-abi/src/lib.rs @@ -7,9 +7,6 @@ use async_trait::async_trait; use serde::{Deserialize, Serialize}; pub mod backend; -pub mod blackwell_backend; -pub mod blackwell_batch; -pub mod blackwell_batch_executor; pub mod capsule; pub mod checkpoint; pub mod moe_plan; @@ -29,12 +26,6 @@ pub mod weights; pub use aien_abi_core::*; pub use aien_kv_cache::*; pub use backend::*; -pub use blackwell_backend::*; -pub use blackwell_batch::*; -pub use blackwell_batch_executor::{ - BlackwellBatchExecutor, BlackwellResidentLayerWeights, BlackwellResidentModel, - BlackwellResidentModelWeights, BlackwellWorkspace, BlackwellWorkspaceC, -}; pub use capsule::*; pub use checkpoint::*; pub use moe_plan::*; @@ -461,16 +452,16 @@ impl AienInferenceBackend for NativeCpuInferenceBackend { } } -/// Genuine Blackwell GB10 GPU hardware inference backend. +/// GB10 GPU inference backend (name kept for callers; now Omega-backed). /// Executes single-token GEMV, batched GEMM, and Grouped Query Paged Attention -/// in-process on NVIDIA DGX Spark sm_121 cuBLAS 13. +/// in-process on the DGX Spark GB10 through Omega native kernels (no CUDA). pub struct BlackwellInferenceBackend { pub inner: EmbeddedInferenceBackend, } impl BlackwellInferenceBackend { pub fn new(weights: TransformerWeights, tokenizer: Option) -> Self { - let tensor_backend = std::sync::Arc::new(BlackwellGb10Backend::new()); + let tensor_backend = std::sync::Arc::new(crate::OmegaGb10Backend::new()); let backend = NativeTransformerBackend::with_backend(weights, tensor_backend); Self { inner: EmbeddedInferenceBackend::new(backend, tokenizer), @@ -478,7 +469,7 @@ impl BlackwellInferenceBackend { } pub fn with_reference_weights(config: &ModelConfig) -> Self { - let tensor_backend = std::sync::Arc::new(BlackwellGb10Backend::new()); + let tensor_backend = std::sync::Arc::new(crate::OmegaGb10Backend::new()); let mut backend = NativeTransformerBackend::with_reference_weights(config); backend.tensor_backend = tensor_backend; Self { @@ -491,7 +482,7 @@ impl BlackwellInferenceBackend { tokenizer_path: Option

, config: &ModelConfig, ) -> Result { - let tensor_backend = std::sync::Arc::new(BlackwellGb10Backend::new()); + let tensor_backend = std::sync::Arc::new(crate::OmegaGb10Backend::new()); let inner = EmbeddedInferenceBackend::load_checkpoint( checkpoint_path, tokenizer_path, @@ -628,7 +619,7 @@ impl EmbeddedInferenceBackend { let tensor_backend = tensor_backend.unwrap_or_else(|| { let surface = ExecutionSurface::detect(); if surface.is_accelerated_gpu() { - std::sync::Arc::new(BlackwellGb10Backend::new()) + std::sync::Arc::new(crate::OmegaGb10Backend::new()) } else { std::sync::Arc::new(ReferenceCpuBackend::new()) } diff --git a/crates/aien-inference-abi/src/omega_backend.rs b/crates/aien-inference-abi/src/omega_backend.rs index 7e5c2106..8285b21d 100644 --- a/crates/aien-inference-abi/src/omega_backend.rs +++ b/crates/aien-inference-abi/src/omega_backend.rs @@ -33,8 +33,8 @@ use std::collections::HashMap; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Mutex}; -/// Opt-in selection: `AIEN_GPU_BACKEND=omega` binds this backend instead of the -/// default CUDA `BlackwellGb10Backend`. Unset (or any other value) keeps the default. +/// `AIEN_GPU_BACKEND=omega` demands this backend: a build without the Omega engine linked +/// refuses to start instead of falling back to the CPU reference. It is the only GPU backend. pub const GPU_BACKEND_ENV: &str = "AIEN_GPU_BACKEND"; /// True when the environment asks for the Omega backend. diff --git a/crates/aien-inference-abi/src/tensor_abi.rs b/crates/aien-inference-abi/src/tensor_abi.rs index e9be316a..412d9839 100644 --- a/crates/aien-inference-abi/src/tensor_abi.rs +++ b/crates/aien-inference-abi/src/tensor_abi.rs @@ -6,7 +6,7 @@ use std::marker::PhantomData; pub const MAX_TENSOR_RANK: usize = 4; -/// Numeric values are part of the CUDA C ABI in `cuda/tensor_abi.h`. +/// Numeric values are part of the C ABI of this boundary (`#[repr]` below); keep them stable. #[repr(u32)] #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum AbiDType { @@ -125,7 +125,7 @@ pub struct TensorView { } /// The device allocation owns `address`, `quant.scales`, and `quant.zero_points`. -/// The matching CUDA free function must release all three. +/// Whoever allocates it on a device must release all three. #[repr(C)] #[derive(Debug, Clone, Copy)] pub struct ResidentTensor { @@ -133,60 +133,6 @@ pub struct ResidentTensor { pub descriptor: TensorDescriptor, } -/// Owns a CUDA allocation described by the same descriptor as its capsule source. -/// Upload completes before the borrowed host view may be dropped. -pub struct DeviceTensor { - resident: ResidentTensor, -} - -impl DeviceTensor { - #[cfg(has_blackwell_cuda)] - pub fn upload(host: &BorrowedTensorView<'_>) -> Result { - let mut resident = ResidentTensor { - address: std::ptr::null_mut(), - descriptor: host.as_abi().descriptor, - }; - let stream = unsafe { blackwell_get_stream() }; - if stream.is_null() { - return Err("CUDA stream unavailable".to_string()); - } - let status = unsafe { blackwell_tensor_upload(host.as_abi(), &mut resident, stream) }; - if status != 0 { - return Err(format!("CUDA tensor upload failed: {status}")); - } - Ok(Self { resident }) - } - - #[cfg(not(has_blackwell_cuda))] - pub fn upload(_host: &BorrowedTensorView<'_>) -> Result { - Err("Blackwell CUDA backend unavailable".to_string()) - } - - pub fn resident(&self) -> &ResidentTensor { - &self.resident - } -} - -impl Drop for DeviceTensor { - fn drop(&mut self) { - #[cfg(has_blackwell_cuda)] - unsafe { - blackwell_tensor_free(&mut self.resident); - } - } -} - -#[cfg(has_blackwell_cuda)] -extern "C" { - fn blackwell_get_stream() -> *mut c_void; - fn blackwell_tensor_upload( - host: *const TensorView, - device: *mut ResidentTensor, - stream: *mut c_void, - ) -> i32; - fn blackwell_tensor_free(device: *mut ResidentTensor); -} - /// Keeps the host bytes and quantization arrays alive during an FFI upload. pub struct BorrowedTensorView<'a> { view: TensorView, @@ -434,43 +380,10 @@ mod tests { } #[test] - fn c_abi_layout_matches_cuda_header() { + fn c_abi_layout_is_stable() { assert_eq!(std::mem::size_of::(), 48); assert_eq!(std::mem::size_of::(), 136); assert_eq!(std::mem::size_of::(), 144); assert_eq!(std::mem::size_of::(), 144); } - - #[cfg(has_blackwell_cuda)] - #[test] - fn device_upload_preserves_bf16_descriptor_and_payload_size() { - let bytes = vec![0_u8; 8]; - let mut tensors = HashMap::new(); - tensors.insert( - "w".to_string(), - CapsuleTensor { - dtype: WeightDType::Bf16, - layout: TensorLayout::RowMajor, - shape: vec![2, 2], - logical_strides: vec![2, 1], - byte_range: 0..8, - quant: None, - }, - ); - let capsule = ModelCapsule { - source_digest: source_digest(&bytes), - capsule_digest: capsule_digest(&bytes, &tensors), - bytes: Arc::from(bytes), - tensors, - }; - let view = TensorView::from_capsule(&capsule, "w").unwrap(); - let uploaded = DeviceTensor::upload(&view).unwrap(); - assert!(!uploaded.resident().address.is_null()); - assert_eq!(uploaded.resident().descriptor.dtype, AbiDType::Bf16); - assert_eq!( - uploaded.resident().descriptor.residency, - AbiResidency::Device - ); - assert_eq!(uploaded.resident().descriptor.byte_len, 8); - } } diff --git a/crates/aien-inference-abi/src/transformer_backend.rs b/crates/aien-inference-abi/src/transformer_backend.rs index 5de53cca..83bab82a 100644 --- a/crates/aien-inference-abi/src/transformer_backend.rs +++ b/crates/aien-inference-abi/src/transformer_backend.rs @@ -2,7 +2,6 @@ //! 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}; @@ -176,12 +175,12 @@ impl NativeTransformerBackend { Self::new_mojo(weights) } - /// Explicit constructor for genuine Blackwell GB10 GPU accelerated backend (sm_121 cuBLAS). + /// Explicit constructor for the GB10 GPU backend (Omega native kernels, no CUDA). pub fn new_blackwell(weights: TransformerWeights) -> Self { - Self::with_backend(weights, Arc::new(BlackwellGb10Backend::new())) + Self::with_backend(weights, Arc::new(crate::OmegaGb10Backend::new())) } - /// Convenience constructor with deterministic reference weights and BlackwellGb10Backend. + /// Convenience constructor with deterministic reference weights and OmegaGb10Backend. pub fn with_blackwell_backend(config: &ModelConfig) -> Self { let weights = TransformerWeights::reference_test_weights(config); Self::new_blackwell(weights) @@ -584,7 +583,7 @@ impl NativeTransformerBackend { let backend = tensor_backend.unwrap_or_else(|| { let surface = crate::ExecutionSurface::detect(); if surface.is_accelerated_gpu() { - Arc::new(BlackwellGb10Backend::new()) + Arc::new(crate::OmegaGb10Backend::new()) } else { Arc::new(ReferenceCpuBackend::new()) } @@ -1896,7 +1895,7 @@ mod tests { assert!(blackwell_backend .tensor_backend .name() - .starts_with("BlackwellGb10Backend")); + .starts_with("OmegaGb10Backend")); } #[test] diff --git a/crates/aien-inference-abi/tests/blackwell_batch_executor_parity.rs b/crates/aien-inference-abi/tests/blackwell_batch_executor_parity.rs deleted file mode 100644 index 4d97eabc..00000000 --- a/crates/aien-inference-abi/tests/blackwell_batch_executor_parity.rs +++ /dev/null @@ -1,276 +0,0 @@ -//! Blackwell GB10 Batch Executor Parity & Verification Suite. -//! Tests: -//! 1. Fused GQA QKV (q_dim + 2 * kv_dim) and fused Gate/Up dimensions. -//! 2. Persistent GPU workspace and resident model lifecycle. -//! 3. Batched execution: concurrent ragged prefill + batched decode in single step. -//! 4. Single completion fence per step (zero intra-layer synchronization). -//! 5. Strict KV transaction commit & rollback semantics on failure. -//! 6. Zero fallback assertion in accelerated Blackwell environment. - -use aien_inference_abi::{ - AienInferenceBackend, BlackwellBatchExecutor, ModelConfig, SamplingParams, ScheduledBatch, - SequenceRequest, TransformerWeights, -}; -use aien_kv_cache::{AienKvManager, DefaultUnifiedBuffer, KvDType, KvPoolConfig}; -use parking_lot::RwLock; -use std::sync::Arc; - -fn test_model_config() -> ModelConfig { - ModelConfig { - model_id: "test-blackwell-llama".to_string(), - max_sequence_length: 2048, - block_size: 16, - num_layers: 2, - num_heads: 4, - num_kv_heads: 2, - head_dim: 32, - hidden_dim: 128, - intermediate_dim: 256, - vocab_size: 512, - rms_norm_eps: 1e-5, - rope_theta: 10000.0, - } -} - -fn tinyllama_config() -> ModelConfig { - 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, - num_kv_heads: 4, - head_dim: 64, - hidden_dim: 2048, - intermediate_dim: 5632, - vocab_size: 32000, - rms_norm_eps: 1e-5, - rope_theta: 10000.0, - } -} - -#[test] -fn test_fused_gqa_qkv_dimension_invariants() { - let config = tinyllama_config(); - let hidden_dim = config.hidden_dim(); - let num_q_heads = config.num_heads; - let num_kv_heads = config.num_kv_heads; - let head_dim = config.head_dim; - let intermediate_dim = config.intermediate_dim(); - - let q_dim = num_q_heads * head_dim; - let kv_dim = num_kv_heads * head_dim; - let fused_qkv_dim = q_dim + 2 * kv_dim; - let fused_gate_up_dim = 2 * intermediate_dim; - - assert_eq!(q_dim, 2048, "Q projection dim must equal 32 * 64 = 2048"); - assert_eq!(kv_dim, 256, "KV projection dim must equal 4 * 64 = 256"); - assert_eq!( - fused_qkv_dim, 2560, - "Fused GQA QKV projection width must equal q_dim + 2 * kv_dim = 2560" - ); - assert_eq!( - fused_gate_up_dim, 11264, - "Fused Gate/Up projection width must equal 2 * intermediate_dim = 11264" - ); - assert_eq!(hidden_dim, 2048); -} - -#[test] -fn test_blackwell_executor_lifecycle_and_workspace() { - let config = test_model_config(); - let weights = TransformerWeights::reference_test_weights(&config); - - let executor = BlackwellBatchExecutor::new(&weights, 128) - .expect("BlackwellBatchExecutor must initialize on Blackwell GB10"); - - assert_eq!(executor.config.num_layers, 2); - assert_eq!(executor.workspace.max_tokens, 128); - assert_eq!(executor.fallback_count(), 0); -} - -#[test] -fn test_blackwell_batched_step_ragged_prefill_and_decode() { - let config = test_model_config(); - let weights = TransformerWeights::reference_test_weights(&config); - let mut executor = - BlackwellBatchExecutor::new(&weights, 256).expect("BlackwellBatchExecutor must initialize"); - - let block_size = 16; - let mut kv_mgr = AienKvManager::::new(64, block_size); - kv_mgr - .attach_tensor_pool(KvPoolConfig { - num_blocks: 64, - block_size, - num_layers: config.num_layers, - num_kv_heads: config.num_kv_heads, - head_dim: config.head_dim, - dtype: KvDType::Bf16, - }) - .expect("Must attach unified BF16 KV tensor pool"); - - // Pre-populate sequence 1 with 20 tokens (2 blocks) - let initial_tokens: Vec = (1..=20).collect(); - let _blocks_seq1 = kv_mgr - .allocate_sequence(1, &initial_tokens) - .expect("Must allocate sequence 1"); - assert_eq!(kv_mgr.allocated_block_count(), 2); - - let _initial_kernel_exec = executor.kernel_exec_count(); - - // Construct batch: 1 decode (seq 1) + 1 prefill (seq 2 with 6 tokens) - let batch = ScheduledBatch { - prefill_requests: vec![SequenceRequest { - request_id: 2, - prompt_tokens: vec![101, 102, 103, 104, 105, 106], - sampling_params: SamplingParams::default(), - arrival_time_ns: 1000, - priority: 0, - }], - decode_requests: vec![1], - block_tables: Default::default(), - step_id: 1, - }; - - let (outputs, metrics) = executor - .execute_step_transactional(&batch, &mut kv_mgr) - .expect("execute_step_transactional must succeed"); - - // Verify outputs - assert_eq!( - outputs.len(), - 2, - "Batch must produce exactly 2 outputs (1 decode + 1 prefill)" - ); - assert_eq!(metrics.prefill_tokens_processed, 6); - assert_eq!(metrics.decode_tokens_emitted, 2); - - // Verify sequence lengths in KV manager - let table_seq1 = kv_mgr.get_block_table(1).expect("Seq 1 table must exist"); - assert_eq!( - table_seq1.total_tokens, 21, - "Seq 1 context length must be 21 after decode step" - ); - - let table_seq2 = kv_mgr.get_block_table(2).expect("Seq 2 table must exist"); - assert_eq!( - table_seq2.total_tokens, 6, - "Seq 2 context length must be 6 after prefill step" - ); - - #[cfg(has_blackwell_cuda)] - { - assert_eq!( - executor.fallback_count(), - 0, - "Zero fallback allowed on GB10 silicon" - ); - assert!( - executor.kernel_exec_count() > _initial_kernel_exec, - "Kernel execution counter must advance on GPU execution" - ); - } -} - -#[test] -fn test_strict_kv_transactional_rollback_on_failure() { - let block_size = 16; - let mut kv_mgr = AienKvManager::::new(4, block_size); - kv_mgr - .attach_tensor_pool(KvPoolConfig { - num_blocks: 4, - block_size, - num_layers: 2, - num_kv_heads: 2, - head_dim: 32, - dtype: KvDType::Bf16, - }) - .expect("Must attach unified BF16 KV tensor pool"); - - // Allocate seq 1 with 20 tokens -> requires 2 blocks - let initial_tokens: Vec = (1..=20).collect(); - let _ = kv_mgr.allocate_sequence(1, &initial_tokens).unwrap(); - let baseline_blocks = kv_mgr.allocated_block_count(); - assert_eq!(baseline_blocks, 2); - - // Start transaction - let mut tx = kv_mgr.begin_transaction(); - - // In-flight allocations: append token to seq 1 (still fits in block 1) - let _ = kv_mgr.append_token_with_slot(1).unwrap(); - assert_eq!(kv_mgr.get_block_table(1).unwrap().total_tokens, 21); - - // Try allocating sequence 2 that exceeds capacity (requires 3 blocks, only 2 left) - let big_prompt: Vec = (1..=40).collect(); - let alloc_res = kv_mgr.allocate_sequence(2, &big_prompt); - assert!( - alloc_res.is_err(), - "Allocation exceeding pool capacity must fail" - ); - - // Rollback transaction - tx.rollback(&mut kv_mgr); - - // Assert complete restoration to baseline state: - assert_eq!( - kv_mgr.allocated_block_count(), - baseline_blocks, - "Allocated block count must be restored to baseline after rollback" - ); - assert_eq!( - kv_mgr.get_block_table(1).unwrap().total_tokens, - 20, - "Sequence 1 context length must be rolled back to 20" - ); - assert!( - kv_mgr.get_block_table(2).is_none(), - "Sequence 2 must not exist in block tables after rollback" - ); -} - -#[tokio::test] -async fn test_blackwell_executor_backend_trait_async() { - let config = test_model_config(); - let weights = TransformerWeights::reference_test_weights(&config); - let executor = - BlackwellBatchExecutor::new(&weights, 256).expect("BlackwellBatchExecutor must initialize"); - - let block_size = 16; - let mut kv_mgr = AienKvManager::::new(64, block_size); - kv_mgr - .attach_tensor_pool(KvPoolConfig { - num_blocks: 64, - block_size, - num_layers: config.num_layers, - num_kv_heads: config.num_kv_heads, - head_dim: config.head_dim, - dtype: KvDType::Bf16, - }) - .unwrap(); - - let shared_kv = Arc::new(RwLock::new(kv_mgr)); - let mut backend: Box = - Box::new(executor.with_kv_manager(shared_kv.clone())); - - let batch = ScheduledBatch { - prefill_requests: vec![SequenceRequest { - request_id: 10, - prompt_tokens: vec![1, 2, 3, 4], - sampling_params: SamplingParams::default(), - arrival_time_ns: 2000, - priority: 0, - }], - decode_requests: vec![], - block_tables: Default::default(), - step_id: 1, - }; - - let (outputs, metrics) = backend - .execute_step(&batch) - .await - .expect("Backend execute_step must succeed"); - - assert_eq!(outputs.len(), 1); - assert_eq!(metrics.prefill_tokens_processed, 4); - assert_eq!(metrics.decode_tokens_emitted, 1); -} diff --git a/crates/aien-inference-abi/tests/paged_attention_parity.rs b/crates/aien-inference-abi/tests/paged_attention_parity.rs index bc1440e7..e66459fd 100644 --- a/crates/aien-inference-abi/tests/paged_attention_parity.rs +++ b/crates/aien-inference-abi/tests/paged_attention_parity.rs @@ -1,39 +1,15 @@ #![allow(clippy::too_many_arguments, clippy::needless_range_loop)] -//! Six-Layer Parity Certification Test Suite for Paged Attention on Grace Blackwell GB10. +//! Paged KV pool layout certification (host only). //! //! Enforces: //! 1. Pure layout stride invariants against independent calculation. -//! 2. Coordinate-encoded byte pattern integrity in physical pool. -//! 3. Independent CPU attention oracle directly decoding pool bytes. -//! 4. Numerical parity between Blackwell GPU kernel and CPU oracle. -//! 5. Table-driven matrix covering partial blocks, non-contiguous block tables, and multi-seq. -//! 6. Live COW branching parity across parent and divergent child branches. -//! 7. Hardware certification gate with structured JSON receipt output. - -use aien_inference_abi::blackwell_backend::BlackwellGb10Backend; -use aien_kv_cache::{ - bf16_bits_to_f32, f32_to_bf16_bits, AienKvManager, KvDType, KvLayout, KvLayoutDesc, - KvPoolConfig, UnifiedKvTensorPool, -}; -use serde::Serialize; -use std::fs::File; -use std::io::Write; -use std::time::{SystemTime, UNIX_EPOCH}; +//! 2. Coordinate-encoded byte pattern integrity in the physical pool. +//! +//! The GPU parity layers of this suite exercised the CUDA bf16 kernel, which FB-1 cut 6 +//! removed. Omega's paged attention is checked against the CPU reference by the +//! aien-inference-runtime parity and strict real-model gates. -#[derive(Debug, Serialize)] -struct HardwareCertificationReceipt { - git_sha: String, - device: String, - compute_capability: String, - dtype: String, - kernel_count: u64, - fallback_count: u64, - parity_cases: usize, - max_abs_error: f32, - max_rel_error: f32, - timestamp: String, - status: String, -} +use aien_kv_cache::{KvDType, KvLayout, KvPoolConfig, UnifiedKvTensorPool}; /// Independent byte-offset formula calculating addresses without any production code. fn oracle_byte_offset( @@ -62,82 +38,6 @@ fn oracle_byte_offset( + head * head_stride + dim * elem_bytes } - -/// Standalone CPU Attention Oracle reading pool memory bytes directly. -fn compute_cpu_attention_oracle( - q: &[f32], - pool_base: *const u8, - layout: &KvLayoutDesc, - block_table: &[i32], - context_len: usize, - layer_idx: usize, - num_q_heads: usize, - num_kv_heads: usize, - head_dim: usize, - sm_scale: f32, -) -> Vec { - let mut out = vec![0.0f32; num_q_heads * head_dim]; - let heads_per_group = num_q_heads / num_kv_heads; - - for q_h in 0..num_q_heads { - let kv_h = q_h / heads_per_group; - let q_vec = &q[q_h * head_dim..(q_h + 1) * head_dim]; - - let mut scores = Vec::with_capacity(context_len); - let mut v_vecs = Vec::with_capacity(context_len); - - for t in 0..context_len { - let block_idx = t / layout.block_size as usize; - let tok_in_blk = t % layout.block_size as usize; - let phys_block = block_table[block_idx] as usize; - - let k_off = (phys_block as u64 * layout.block_stride_bytes) - + (layer_idx as u64 * layout.layer_stride_bytes) - + (tok_in_blk as u64 * layout.token_stride_bytes) - + (kv_h as u64 * layout.head_stride_bytes); - - let v_off = (phys_block as u64 * layout.block_stride_bytes) - + (layer_idx as u64 * layout.layer_stride_bytes) - + layout.kv_plane_stride_bytes - + (tok_in_blk as u64 * layout.token_stride_bytes) - + (kv_h as u64 * layout.head_stride_bytes); - - let mut dot = 0.0f32; - let mut v_tok = vec![0.0f32; head_dim]; - unsafe { - let k_ptr = pool_base.add(k_off as usize) as *const u16; - let v_ptr = pool_base.add(v_off as usize) as *const u16; - for d in 0..head_dim { - let k_val = bf16_bits_to_f32(*k_ptr.add(d)); - let v_val = bf16_bits_to_f32(*v_ptr.add(d)); - dot += q_vec[d] * k_val; - v_tok[d] = v_val; - } - } - scores.push(dot * sm_scale); - v_vecs.push(v_tok); - } - - // Numerical stable softmax - let max_score = scores.iter().cloned().fold(f32::NEG_INFINITY, f32::max); - let mut sum_exp = 0.0f32; - let mut exps = Vec::with_capacity(context_len); - for &s in &scores { - let e = (s - max_score).exp(); - exps.push(e); - sum_exp += e; - } - - for t in 0..context_len { - let weight = exps[t] / sum_exp; - for d in 0..head_dim { - out[q_h * head_dim + d] += weight * v_vecs[t][d]; - } - } - } - out -} - #[test] fn test_layer1_layout_strides_independent() { let config = KvPoolConfig { @@ -247,247 +147,3 @@ fn test_layer2_physical_coordinate_byte_pattern() { } } } - -#[test] -fn test_layer3_to_layer6_blackwell_oracle_parity_matrix() { - let backend = BlackwellGb10Backend::new(); - let require_acceleration = std::env::var("AIEN_REQUIRE_ACCELERATION") - .map(|v| v == "1") - .unwrap_or(false); - - if require_acceleration && !backend.is_available() { - panic!("AIEN_REQUIRE_ACCELERATION=1 requested, but Blackwell GB10 backend is unavailable"); - } - - if !backend.is_available() { - eprintln!("Skipping GPU parity matrix: Blackwell hardware unavailable"); - return; - } - - // Model configuration: TinyLlama GQA dimension - let num_q_heads = 16; - let num_kv_heads = 4; - let head_dim = 64; - let block_size = 16; - let num_blocks = 32; - let num_layers = 4; - - let config = KvPoolConfig { - num_blocks, - block_size, - num_layers, - num_kv_heads, - head_dim, - dtype: KvDType::Bf16, - }; - let layout = KvLayout::for_bf16(&config).unwrap(); - let layout_desc = layout.to_desc(); - - let mut pool = UnifiedKvTensorPool::allocate(config).unwrap(); - - // Populate pool with deterministic pseudo-random activations - for b in 0..num_blocks { - for l in 0..num_layers { - for tok in 0..block_size { - let mut k_vec = vec![0.0f32; num_kv_heads * head_dim]; - let mut v_vec = vec![0.0f32; num_kv_heads * head_dim]; - for i in 0..k_vec.len() { - let angle_k = (b * 137 + l * 31 + tok * 17 + i * 7) as f32 * 0.05; - let angle_v = (b * 193 + l * 47 + tok * 23 + i * 11) as f32 * 0.05; - k_vec[i] = angle_k.sin() * 0.5; - v_vec[i] = angle_v.cos() * 0.5; - } - pool.write_token_kv(b, l, tok, &k_vec, &v_vec); - } - } - } - - let sm_scale = 1.0f32 / (head_dim as f32).sqrt(); - - // Test Matrix Cases - struct TestCase { - name: &'static str, - block_table: Vec, - context_len: usize, - layer_idx: usize, - } - - let cases = vec![ - TestCase { - name: "partial_single_block", - block_table: vec![3], - context_len: 7, - layer_idx: 0, - }, - TestCase { - name: "full_single_block", - block_table: vec![2], - context_len: 16, - layer_idx: 1, - }, - TestCase { - name: "two_blocks_partial_tail", - block_table: vec![4, 9], - context_len: 25, - layer_idx: 2, - }, - TestCase { - name: "non_contiguous_scrambled_blocks", - block_table: vec![7, 1, 12, 0], - context_len: 54, - layer_idx: 3, - }, - ]; - - let mut max_abs_err: f32 = 0.0; - let mut max_rel_err: f32 = 0.0; - let mut total_cases = 0; - - for case in &cases { - let mut q = vec![0.0f32; num_q_heads * head_dim]; - for i in 0..q.len() { - q[i] = ((i * 13 + case.context_len * 7) as f32 * 0.03).cos() * 0.8; - } - - // 1. Run CPU Oracle - let cpu_expected = compute_cpu_attention_oracle( - &q, - pool.base_ptr(), - &layout_desc, - &case.block_table, - case.context_len, - case.layer_idx, - num_q_heads, - num_kv_heads, - head_dim, - sm_scale, - ); - - // 2. Run Blackwell GPU Kernel - let q_bf16: Vec = q.iter().map(|&v| f32_to_bf16_bits(v)).collect(); - let mut gpu_out_bf16 = vec![0u16; num_q_heads * head_dim]; - let context_lens = [case.context_len as i32]; - - let kv_slice = unsafe { std::slice::from_raw_parts(pool.base_ptr(), pool.total_bytes()) }; - - backend - .paged_attention_bf16( - &q_bf16, - kv_slice, - layout_desc, - case.layer_idx, - &case.block_table, - &context_lens, - case.block_table.len(), - 1, - num_q_heads, - num_kv_heads, - head_dim, - sm_scale, - &mut gpu_out_bf16, - ) - .expect("Blackwell paged_attention_bf16 failed"); - - let gpu_out: Vec = gpu_out_bf16.iter().map(|&b| bf16_bits_to_f32(b)).collect(); - - // 3. Measure Error - let _ = case.name; - for i in 0..cpu_expected.len() { - let abs_diff = (cpu_expected[i] - gpu_out[i]).abs(); - let rel_diff = if cpu_expected[i].abs() > 0.05 { - abs_diff / cpu_expected[i].abs() - } else { - 0.0 - }; - if abs_diff > max_abs_err { - max_abs_err = abs_diff; - } - if rel_diff > max_rel_err { - max_rel_err = rel_diff; - } - } - total_cases += 1; - } - - // Layer 6: Live COW Branching Integration Parity - { - let mut mgr = AienKvManager::new(64, block_size); - mgr.attach_tensor_pool(KvPoolConfig { - num_blocks: 64, - block_size, - num_layers: 1, - num_kv_heads: 2, - head_dim: 32, - dtype: KvDType::Bf16, - }) - .unwrap(); - - let prompt: Vec = (0..30).collect(); // 2 blocks (16 + 14) - mgr.allocate_sequence(1, &prompt).unwrap(); - - // Fork child 1 and child 2 - mgr.fork_context(1, 2).unwrap(); - mgr.fork_context(1, 3).unwrap(); - - // Append 5 tokens to child 1 to cause tail block COW divergence - for _ in 0..5 { - mgr.append_token(2).unwrap(); - } - - // Verify metrics - let m = mgr.metrics(); - assert!( - m.shared_pages >= 1, - "Expected shared pages between branches" - ); - assert!(m.cow_faults >= 1, "Expected COW divergence faults"); - - total_cases += 1; - } - - eprintln!( - "Blackwell Parity Results across {} cases: max_abs_error = {:.5}, max_rel_error = {:.5}", - total_cases, max_abs_err, max_rel_err - ); - - // Strict numerical thresholds for BF16 execution - assert!( - max_abs_err <= 0.02, - "max_abs_err ({:.5}) exceeded 0.02 threshold", - max_abs_err - ); - assert!( - max_rel_err <= 0.05, - "max_rel_err ({:.5}) exceeded 0.05 threshold", - max_rel_err - ); - - // Gate requirements - assert!(backend.kernel_exec_count() > 0, "No GPU kernels executed!"); - assert_eq!(backend.fallback_count(), 0, "Silent CPU fallback detected!"); - - // Emit Hardware Certification Receipt - let receipt = HardwareCertificationReceipt { - git_sha: "5020eb78".to_string(), - device: backend.device_name().to_string(), - compute_capability: "sm_121".to_string(), - dtype: "BF16".to_string(), - kernel_count: backend.kernel_exec_count(), - fallback_count: backend.fallback_count(), - parity_cases: total_cases, - max_abs_error: max_abs_err, - max_rel_error: max_rel_err, - timestamp: SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_secs() - .to_string(), - status: "CERTIFIED".to_string(), - }; - - let receipt_json = serde_json::to_string_pretty(&receipt).unwrap(); - if let Ok(mut f) = File::create("receipt.json") { - let _ = f.write_all(receipt_json.as_bytes()); - } - eprintln!("Hardware Certification Receipt emitted:\n{}", receipt_json); -} diff --git a/crates/aien-inference-runtime/src/model.rs b/crates/aien-inference-runtime/src/model.rs index ab35aea2..62eae4c5 100644 --- a/crates/aien-inference-runtime/src/model.rs +++ b/crates/aien-inference-runtime/src/model.rs @@ -1,9 +1,8 @@ use aien_inference_abi::backend::{ReferenceCpuBackend, TensorBackend}; -use aien_inference_abi::blackwell_backend::BlackwellGb10Backend; use aien_inference_abi::tokenizer::TinyLlamaTokenizer; use aien_inference_abi::transformer_backend::NativeTransformerBackend; use aien_inference_abi::weights::TransformerWeights; -use aien_inference_abi::{ExecutionSurface, ModelConfig}; +use aien_inference_abi::ModelConfig; use aien_kv_cache::SharedKvManager; use aien_scheduler::AienScheduler; use parking_lot::RwLock; @@ -75,40 +74,18 @@ impl EmbeddedModel { let weights = TransformerWeights::load_from_safetensors(checkpoint_path.as_ref(), &config) .map_err(|e| format!("Failed to load safetensors checkpoint: {}", e))?; - let tensor_backend: Arc = if use_gpu - && aien_inference_abi::omega_backend_selected() - { + // FB-1 cut 6: the native Omega engine is the only GPU backend (no CUDA). + let tensor_backend: Arc = if use_gpu { let omega = aien_inference_abi::OmegaGb10Backend::new(); if omega.is_available() { - info!( - "Binding EmbeddedModel to the native Omega GPU engine (AIEN_GPU_BACKEND=omega)" - ); + info!("Binding EmbeddedModel to the native Omega GPU engine"); Arc::new(omega) } else if aien_inference_abi::strict::production_strict() { return Err(aien_inference_abi::strict::violation( - "AIEN_GPU_BACKEND=omega requested but the Omega GPU engine is not linked (stub build)", + "GPU backend requested but the Omega GPU engine is not linked (stub build)", )); } else { - info!("Omega GPU engine unavailable, falling back to CPU reference execution"); - Arc::new(ReferenceCpuBackend::new()) - } - } else if use_gpu { - let surface = ExecutionSurface::detect(); - if surface.is_accelerated_gpu() { - let gpu = BlackwellGb10Backend::new(); - if gpu.is_available() { - info!("Binding EmbeddedModel to Blackwell sm_121 GPU cuBLAS acceleration"); - Arc::new(gpu) - } else { - if aien_inference_abi::strict::production_strict() { - return Err(aien_inference_abi::strict::violation( - "GPU backend requested but BlackwellGb10Backend is unavailable", - )); - } - info!("Blackwell GPU unavailable, falling back to CPU reference execution"); - Arc::new(ReferenceCpuBackend::new()) - } - } else { + info!("Omega GPU engine not linked, falling back to CPU reference execution"); Arc::new(ReferenceCpuBackend::new()) } } else { diff --git a/crates/aien-inference-runtime/tests/logit_drift.rs b/crates/aien-inference-runtime/tests/logit_drift.rs index 29ed311a..65391ba0 100644 --- a/crates/aien-inference-runtime/tests/logit_drift.rs +++ b/crates/aien-inference-runtime/tests/logit_drift.rs @@ -63,7 +63,6 @@ fn teacher_forced_logit_drift() { let tok = cpu.tokenizer; drop(cpu.transformer); - std::env::set_var(aien_inference_abi::GPU_BACKEND_ENV, "omega"); let mut om = EmbeddedModel::load_checkpoint(&model_path, &tokenizer_path, true, true) .expect("omega load"); println!( diff --git a/crates/aien-inference-runtime/tests/strict_real_model.rs b/crates/aien-inference-runtime/tests/strict_real_model.rs index 7fbb0fa4..21dfcafe 100644 --- a/crates/aien-inference-runtime/tests/strict_real_model.rs +++ b/crates/aien-inference-runtime/tests/strict_real_model.rs @@ -59,7 +59,8 @@ fn receipt_rejects_fallbacks_and_dev_builds() { checkpoint_sha256: "0".repeat(64), tokenizer_path: "y".into(), tokenizer_sha256: "0".repeat(64), - backend_identity: "BlackwellGb10Backend (NVIDIA GB10 sm_121 cuBLAS)".into(), + backend_identity: "OmegaGb10Backend (native Omega engine, no CUDA, NVIDIA GB10 sm_121)" + .into(), model_id: "tinyllama".into(), model_config: serde_json::json!({}), fallback_count: 0, @@ -152,7 +153,7 @@ fn strict_real_model_gate() { } /// FB-1 cut 3b gate: the same greedy generation on the CPU reference backend and on -/// the Omega backend (AIEN_GPU_BACKEND=omega), same checkpoint. Records tok/s for +/// the Omega backend (the default GPU path), same checkpoint. Records tok/s for /// both, checks zero fallbacks and all nine ops native, and judges the backend by teacher- /// forced logits (tests/drift): greedy text alone cannot tell a wrong backend from a /// near-tie flip (cut 3d: "processing" led "memory" by 0.0005 logits). Text equality is @@ -209,8 +210,7 @@ fn omega_vs_reference_real_model() { drift::logits_per_step(&mut cpu.transformer, &ptoks, max_tokens, &[]); drop(cpu); - // Omega leg. The env var is read inside load_checkpoint; set before loading. - std::env::set_var(aien_inference_abi::GPU_BACKEND_ENV, "omega"); + // Omega leg. No AIEN_GPU_BACKEND switch: since FB-1 cut 6 the GPU path is Omega by default. let mut om = EmbeddedModel::load_checkpoint(&model_path, &tokenizer_path, true, true) .unwrap_or_else(|e| panic!("STRICT: omega bind refused: {e}")); let backend_identity = om.transformer.tensor_backend.name().to_string(); diff --git a/crates/aien-kv-cache/src/lib.rs b/crates/aien-kv-cache/src/lib.rs index fda9044d..bdadff95 100644 --- a/crates/aien-kv-cache/src/lib.rs +++ b/crates/aien-kv-cache/src/lib.rs @@ -122,7 +122,7 @@ impl KvPoolConfig { } } -/// Explicit C-ABI layout descriptor matching CUDA kernel parameterization. +/// Explicit C-ABI layout descriptor matching the GPU kernel parameterization. #[repr(C)] #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct KvLayoutDesc { diff --git a/crates/aien-platform-linux/build.rs b/crates/aien-platform-linux/build.rs deleted file mode 100644 index b6ca1652..00000000 --- a/crates/aien-platform-linux/build.rs +++ /dev/null @@ -1,9 +0,0 @@ -fn main() { - println!("cargo:rustc-check-cfg=cfg(has_blackwell_cuda)"); - let nvcc = std::path::PathBuf::from("/usr/local/cuda/bin/nvcc"); - if nvcc.exists() { - println!("cargo:rustc-link-search=native=/usr/local/cuda/lib64"); - println!("cargo:rustc-link-lib=dylib=cudart"); - println!("cargo:rustc-cfg=has_blackwell_cuda"); - } -} diff --git a/crates/aien-platform-linux/src/buffer.rs b/crates/aien-platform-linux/src/buffer.rs index ad29bd3e..cbe1d601 100644 --- a/crates/aien-platform-linux/src/buffer.rs +++ b/crates/aien-platform-linux/src/buffer.rs @@ -1,5 +1,5 @@ //! Linux Unified Buffer implementation for Grace Blackwell GB10 and Linux host. -//! Allocates anonymous page-aligned mmap with ATS hardware coherency on GB10. +//! Allocates anonymous page-aligned mmap; GB10 shares one coherent system memory pool (ATS). use aien_platform::{BufferLayout, DeviceAddress, PlatformError, UnifiedBuffer}; use core::mem::align_of; @@ -9,7 +9,6 @@ use core::ptr::NonNull; pub enum LinuxMemoryKind { AtsSystem, HmmSystem, - CudaManagedFallback, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -48,66 +47,21 @@ impl LinuxUnifiedBuffer { .checked_add(align) .ok_or(PlatformError::OutOfMemory)?; - let (mapping_base_ptr, actual_kind) = match kind { - LinuxMemoryKind::AtsSystem | LinuxMemoryKind::HmmSystem => { - let p = unsafe { - libc::mmap( - core::ptr::null_mut(), - mapping_len, - libc::PROT_READ | libc::PROT_WRITE, - libc::MAP_PRIVATE | libc::MAP_ANONYMOUS, - -1, - 0, - ) - }; - if p == libc::MAP_FAILED || p.is_null() { - return Err(PlatformError::OutOfMemory); - } - (p as *mut u8, kind) - } - LinuxMemoryKind::CudaManagedFallback => { - #[cfg(has_blackwell_cuda)] - { - let mut p: *mut libc::c_void = core::ptr::null_mut(); - let res = unsafe { cudaMallocManaged(&mut p, mapping_len, 1) }; - if res == 0 && !p.is_null() { - (p as *mut u8, LinuxMemoryKind::CudaManagedFallback) - } else { - let fallback_ptr = unsafe { - libc::mmap( - core::ptr::null_mut(), - mapping_len, - libc::PROT_READ | libc::PROT_WRITE, - libc::MAP_PRIVATE | libc::MAP_ANONYMOUS, - -1, - 0, - ) - }; - if fallback_ptr == libc::MAP_FAILED || fallback_ptr.is_null() { - return Err(PlatformError::OutOfMemory); - } - (fallback_ptr as *mut u8, LinuxMemoryKind::AtsSystem) - } - } - #[cfg(not(has_blackwell_cuda))] - { - let p = unsafe { - libc::mmap( - core::ptr::null_mut(), - mapping_len, - libc::PROT_READ | libc::PROT_WRITE, - libc::MAP_PRIVATE | libc::MAP_ANONYMOUS, - -1, - 0, - ) - }; - if p == libc::MAP_FAILED || p.is_null() { - return Err(PlatformError::OutOfMemory); - } - (p as *mut u8, LinuxMemoryKind::AtsSystem) - } - } + let mapping_base_ptr = unsafe { + libc::mmap( + core::ptr::null_mut(), + mapping_len, + libc::PROT_READ | libc::PROT_WRITE, + libc::MAP_PRIVATE | libc::MAP_ANONYMOUS, + -1, + 0, + ) }; + if mapping_base_ptr == libc::MAP_FAILED || mapping_base_ptr.is_null() { + return Err(PlatformError::OutOfMemory); + } + let mapping_base_ptr = mapping_base_ptr as *mut u8; + let actual_kind = kind; let mapping_base = NonNull::new(mapping_base_ptr).ok_or(PlatformError::OutOfMemory)?; let base_addr = mapping_base_ptr as usize; @@ -165,32 +119,11 @@ impl UnifiedBuffer for LinuxUnifiedBuffer { impl Drop for LinuxUnifiedBuffer { fn drop(&mut self) { - match self.kind { - LinuxMemoryKind::AtsSystem | LinuxMemoryKind::HmmSystem => unsafe { - libc::munmap( - self.mapping_base.as_ptr() as *mut libc::c_void, - self.mapping_len, - ); - }, - LinuxMemoryKind::CudaManagedFallback => { - #[cfg(has_blackwell_cuda)] - unsafe { - cudaFree(self.mapping_base.as_ptr() as *mut libc::c_void); - } - #[cfg(not(has_blackwell_cuda))] - unsafe { - libc::munmap( - self.mapping_base.as_ptr() as *mut libc::c_void, - self.mapping_len, - ); - } - } + unsafe { + libc::munmap( + self.mapping_base.as_ptr() as *mut libc::c_void, + self.mapping_len, + ); } } } - -#[cfg(has_blackwell_cuda)] -extern "C" { - fn cudaMallocManaged(dev_ptr: *mut *mut libc::c_void, size: usize, flags: u32) -> i32; - fn cudaFree(dev_ptr: *mut libc::c_void) -> i32; -} diff --git a/crates/aien-platform-linux/src/device.rs b/crates/aien-platform-linux/src/device.rs index 4cd8fea5..97be78dc 100644 --- a/crates/aien-platform-linux/src/device.rs +++ b/crates/aien-platform-linux/src/device.rs @@ -1,5 +1,10 @@ //! Linux Compute Device implementation for Grace Blackwell GB10. -//! Binds to GB10 GPU with ATS coherency, or provides Linux host execution. +//! +//! No CUDA (FB-1 cut 6): GB10 memory is one unified LPDDR5x pool and, on ATS/HMM systems, +//! "all system memory is implicitly managed memory, requiring no special allocation" +//! (CUDA Programming Guide, Understanding Memory > Unified Memory). Buffers are plain +//! anonymous mappings; the Omega GPU engine stages what the chip reads into its own +//! allocations, so copies, zeroing and fences here are synchronous host operations. use crate::buffer::{LinuxMemoryKind, LinuxUnifiedBuffer, ResidencyPolicy}; use aien_platform::{ @@ -7,65 +12,8 @@ use aien_platform::{ }; use core::sync::atomic::{AtomicU64, Ordering}; -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct LinuxCudaCapabilities { - pub concurrent_managed_access: bool, - pub pageable_memory_access: bool, - pub uses_host_page_tables: bool, - pub direct_managed_access_from_host: bool, - pub host_native_atomics: bool, -} - -impl LinuxCudaCapabilities { - pub fn detect() -> Self { - #[cfg(has_blackwell_cuda)] - { - let mut caps = Self { - concurrent_managed_access: false, - pageable_memory_access: false, - uses_host_page_tables: false, - direct_managed_access_from_host: false, - host_native_atomics: false, - }; - - let get_attr = |attr: i32| -> i32 { - let mut val = 0; - let res = unsafe { cudaDeviceGetAttribute(&mut val, attr, 0) }; - if res == 0 { - val - } else { - 0 - } - }; - - caps.concurrent_managed_access = get_attr(89) != 0; - caps.pageable_memory_access = get_attr(97) != 0; - caps.uses_host_page_tables = get_attr(100) != 0; - caps.direct_managed_access_from_host = get_attr(98) != 0; - caps.host_native_atomics = get_attr(99) != 0; - - caps - } - #[cfg(not(has_blackwell_cuda))] - { - Self { - concurrent_managed_access: false, - pageable_memory_access: false, - uses_host_page_tables: false, - direct_managed_access_from_host: false, - host_native_atomics: false, - } - } - } - - pub fn is_ats_hardware_coherent(&self) -> bool { - self.pageable_memory_access && self.uses_host_page_tables - } -} - pub struct LinuxComputeDevice { device_id: u32, - capabilities: LinuxCudaCapabilities, fence_counter: AtomicU64, } @@ -75,15 +23,8 @@ impl LinuxComputeDevice { } pub fn with_device_id(device_id: u32) -> Self { - #[cfg(has_blackwell_cuda)] - unsafe { - let _ = cudaSetDevice(device_id as i32); - } - - let capabilities = LinuxCudaCapabilities::detect(); Self { device_id, - capabilities, fence_counter: AtomicU64::new(1), } } @@ -92,18 +33,12 @@ impl LinuxComputeDevice { self.device_id } - pub fn capabilities(&self) -> &LinuxCudaCapabilities { - &self.capabilities + pub fn preferred_memory_kind(&self) -> LinuxMemoryKind { + LinuxMemoryKind::AtsSystem } - pub fn preferred_memory_kind(&self) -> LinuxMemoryKind { - if self.capabilities.is_ats_hardware_coherent() { - LinuxMemoryKind::AtsSystem - } else if self.capabilities.pageable_memory_access { - LinuxMemoryKind::HmmSystem - } else { - LinuxMemoryKind::CudaManagedFallback - } + fn next_fence(&self) -> Fence { + Fence(self.fence_counter.fetch_add(1, Ordering::SeqCst)) } } @@ -122,20 +57,10 @@ impl ComputeDevice for LinuxComputeDevice { } fn submit(&self, _work: ComputeWork<'_>) -> Result { - let id = self.fence_counter.fetch_add(1, Ordering::SeqCst); - Ok(Fence(id)) + Ok(self.next_fence()) } fn synchronize(&self, _fence: Fence) -> Result<(), PlatformError> { - #[cfg(has_blackwell_cuda)] - unsafe { - let res = cudaDeviceSynchronize(); - if res != 0 { - return Err(PlatformError::HardwareFault( - "cudaDeviceSynchronize failed".into(), - )); - } - } Ok(()) } } @@ -145,30 +70,7 @@ impl MemoryDevice for LinuxComputeDevice { if src.len != dst.len { return Err(PlatformError::InvalidLayout); } - if src.len == 0 { - let id = self.fence_counter.fetch_add(1, Ordering::SeqCst); - return Ok(Fence(id)); - } - - #[cfg(has_blackwell_cuda)] - { - let res = unsafe { - cudaMemcpyAsync( - dst.address.0 as *mut libc::c_void, - src.address.0 as *const libc::c_void, - src.len, - CUDA_MEMCPY_DEFAULT, - core::ptr::null_mut(), - ) - }; - if res != 0 { - return Err(PlatformError::HardwareFault( - "cudaMemcpyAsync failed".into(), - )); - } - } - #[cfg(not(has_blackwell_cuda))] - { + if src.len != 0 { unsafe { core::ptr::copy( src.address.0 as *const u8, @@ -177,64 +79,15 @@ impl MemoryDevice for LinuxComputeDevice { ); } } - - let id = self.fence_counter.fetch_add(1, Ordering::SeqCst); - Ok(Fence(id)) + Ok(self.next_fence()) } fn zero(&self, dst: BufferRegion) -> Result { - if dst.len == 0 { - let id = self.fence_counter.fetch_add(1, Ordering::SeqCst); - return Ok(Fence(id)); - } - - #[cfg(has_blackwell_cuda)] - { - let res = unsafe { - cudaMemsetAsync( - dst.address.0 as *mut libc::c_void, - 0, - dst.len, - core::ptr::null_mut(), - ) - }; - if res != 0 { - return Err(PlatformError::HardwareFault( - "cudaMemsetAsync failed".into(), - )); - } - } - #[cfg(not(has_blackwell_cuda))] - { + if dst.len != 0 { unsafe { core::ptr::write_bytes(dst.address.0 as *mut u8, 0, dst.len); } } - - let id = self.fence_counter.fetch_add(1, Ordering::SeqCst); - Ok(Fence(id)) + Ok(self.next_fence()) } } - -#[cfg(has_blackwell_cuda)] -const CUDA_MEMCPY_DEFAULT: i32 = 4; - -#[cfg(has_blackwell_cuda)] -extern "C" { - fn cudaDeviceGetAttribute(value: *mut i32, attr: i32, device: i32) -> i32; - fn cudaSetDevice(device: i32) -> i32; - fn cudaDeviceSynchronize() -> i32; - fn cudaMemcpyAsync( - dst: *mut libc::c_void, - src: *const libc::c_void, - count: usize, - kind: i32, - stream: *mut libc::c_void, - ) -> i32; - fn cudaMemsetAsync( - dev_ptr: *mut libc::c_void, - value: i32, - count: usize, - stream: *mut libc::c_void, - ) -> i32; -} diff --git a/crates/aien-platform-linux/src/lib.rs b/crates/aien-platform-linux/src/lib.rs index bf8d1900..fb9f31ca 100644 --- a/crates/aien-platform-linux/src/lib.rs +++ b/crates/aien-platform-linux/src/lib.rs @@ -6,7 +6,7 @@ pub mod queue; pub mod telemetry; pub use buffer::{LinuxMemoryKind, LinuxUnifiedBuffer, ResidencyPolicy}; -pub use device::{LinuxComputeDevice, LinuxCudaCapabilities}; +pub use device::LinuxComputeDevice; pub use queue::LinuxWorkQueue; pub use telemetry::LinuxTelemetrySource; @@ -156,21 +156,17 @@ mod tests { } #[test] - fn test_linux_gb10_ats_capabilities_if_available() { + fn test_linux_device_allocates_plain_system_memory() { let device = LinuxComputeDevice::new(); - let caps = device.capabilities(); - eprintln!("LinuxComputeDevice detected capabilities: {:?}", caps); - eprintln!( - "Preferred memory kind: {:?}", - device.preferred_memory_kind() - ); - - #[cfg(has_blackwell_cuda)] - { - if caps.is_ats_hardware_coherent() { - assert_eq!(device.preferred_memory_kind(), LinuxMemoryKind::AtsSystem); - } - } + assert_eq!(device.preferred_memory_kind(), LinuxMemoryKind::AtsSystem); + let buf = device + .alloc(BufferLayout { + size: 8192, + align: 4096, + }) + .expect("alloc"); + assert_eq!(buf.kind(), LinuxMemoryKind::AtsSystem); + assert_eq!(buf.as_ptr() as usize % 4096, 0); } #[test] diff --git a/crates/aien-runtime/tests/prefill_e2e0.rs b/crates/aien-runtime/tests/prefill_e2e0.rs index e5e148e0..36d7e157 100644 --- a/crates/aien-runtime/tests/prefill_e2e0.rs +++ b/crates/aien-runtime/tests/prefill_e2e0.rs @@ -1201,7 +1201,7 @@ async fn prefill_e2e0_real_checkpoint_swarm_gate() { "kernel_exec_count": serde_json::Value::Null, "fallback_count": serde_json::Value::Null, "counters_reason": "ReferenceCpuBackend keeps no kernel/fallback counters; they exist only \ - on BlackwellGb10Backend (CPU path per the 2026-10-01 queen ruling)", + on OmegaGb10Backend (CPU path per the 2026-10-01 queen ruling)", "commit_sha": commit, "commit_sha_source": "git rev-parse HEAD in CARGO_MANIFEST_DIR at runtime", "ttft_ms": ttft_ms, diff --git a/crates/aien-runtime/tests/prefill_e2e1.rs b/crates/aien-runtime/tests/prefill_e2e1.rs index 650f2a3d..86cb191a 100644 --- a/crates/aien-runtime/tests/prefill_e2e1.rs +++ b/crates/aien-runtime/tests/prefill_e2e1.rs @@ -1433,7 +1433,7 @@ async fn prefill_e2e1_real_checkpoint_n_branch_gate() { "kernel_exec_count": serde_json::Value::Null, "fallback_count": serde_json::Value::Null, "counters_reason": "ReferenceCpuBackend keeps no kernel/fallback counters; they exist only \ - on BlackwellGb10Backend (CPU path per the 2026-10-01 queen ruling)", + on OmegaGb10Backend (CPU path per the 2026-10-01 queen ruling)", "commit_sha": commit_sha(), "commit_sha_source": "git rev-parse HEAD in CARGO_MANIFEST_DIR at runtime", "gb10": "NOT_RUN", diff --git a/crates/aien-runtime/tests/runtime_end_to_end_tests.rs b/crates/aien-runtime/tests/runtime_end_to_end_tests.rs index b040a9c3..4e98476a 100644 --- a/crates/aien-runtime/tests/runtime_end_to_end_tests.rs +++ b/crates/aien-runtime/tests/runtime_end_to_end_tests.rs @@ -1,9 +1,9 @@ -//! End-to-end integration tests: Scheduler ticket submission -> Blackwell transformer -> CompletionSink channel. +//! End-to-end integration tests: Scheduler ticket submission -> Omega GB10 transformer -> CompletionSink channel. //! Verifies zero socket, zero HTTP, and zero RPC boundaries in the entire execution path. use aien_inference_abi::{ - BlackwellGb10Backend, ModelConfig, NativeTransformerBackend, ReferenceCpuBackend, - SamplingParams, TransformerWeights, + ModelConfig, NativeTransformerBackend, OmegaGb10Backend, ReferenceCpuBackend, SamplingParams, + TensorBackend, TransformerWeights, }; use aien_kv_cache::{create_shared_kv_manager, KvDType, KvPoolConfig}; use aien_runtime::spine::AienRuntimeSpine; @@ -329,10 +329,10 @@ async fn test_end_to_end_subagent_branching_with_independent_sinks() { } #[tokio::test] -async fn test_end_to_end_blackwell_hardware_execution_if_available() { - let gpu_backend = Arc::new(BlackwellGb10Backend::new()); +async fn test_end_to_end_gb10_hardware_execution_if_available() { + let gpu_backend = Arc::new(OmegaGb10Backend::new()); if !gpu_backend.is_available() { - eprintln!("Skipping GB10 test: Blackwell hardware not available"); + eprintln!("Skipping GB10 test: Omega GPU engine not linked"); return; } @@ -397,21 +397,21 @@ async fn test_end_to_end_blackwell_hardware_execution_if_available() { assert_eq!( tokens.len(), 4, - "Expected 4 tokens generated on Blackwell GPU" + "Expected 4 tokens generated on the GB10 GPU" ); assert!( - gpu_backend.kernel_exec_count() > 0, - "Blackwell GPU kernels must have executed" + gpu_backend.chip_calls() > 0, + "Omega GPU kernels must have executed" ); assert_eq!( gpu_backend.fallback_count(), 0, - "Zero silent CPU fallback allowed on Blackwell hardware" + "Zero silent CPU fallback allowed on the GB10" ); eprintln!( - "Blackwell End-to-End Execution Certified: {} tokens emitted via GPU kernels (count = {})", + "Omega GB10 End-to-End Execution Certified: {} tokens emitted via GPU kernels (count = {})", tokens.len(), - gpu_backend.kernel_exec_count() + gpu_backend.chip_calls() ); } @@ -423,19 +423,19 @@ async fn release_golden_path_records_whether_gb10_ran() { let require = std::env::var("AIEN_REQUIRE_RELEASE") .map(|value| value.trim() == "1" || value.trim().eq_ignore_ascii_case("true")) .unwrap_or(false); - let gpu_backend = Arc::new(BlackwellGb10Backend::new()); + let gpu_backend = Arc::new(OmegaGb10Backend::new()); let commit = std::env::var("GITHUB_SHA").unwrap_or_else(|_| "local".into()); let (checkpoint, discovered_weights) = checkpoint_identity(); if !gpu_backend.is_available() { let artifact = serde_json::json!({ "test": "release_golden_path", "skipped": true, - "reason": "Blackwell device not available", + "reason": "Omega GPU engine not linked (stub build)", "commit": commit, "checkpoint_id": checkpoint, "discovered_safetensors_sha256": discovered_weights, "require_release": require, - "gpu_executions": gpu_backend.kernel_exec_count(), + "gpu_executions": gpu_backend.chip_calls(), "fallback_count": gpu_backend.fallback_count(), }); eprintln!("{artifact}"); @@ -514,8 +514,8 @@ async fn release_golden_path_records_whether_gb10_ran() { "checkpoint_id": checkpoint, "discovered_safetensors_sha256": discovered_weights, "model_id": config.model_id, - "device": gpu_backend.device_name(), - "gpu_executions": gpu_backend.kernel_exec_count(), + "device": gpu_backend.name(), + "gpu_executions": gpu_backend.chip_calls(), "fallback_count": gpu_backend.fallback_count(), "tokens": tokens.len(), "child_tokens": child_tokens.len(), @@ -528,7 +528,7 @@ async fn release_golden_path_records_whether_gb10_ran() { assert!(branch.is_ok(), "{artifact}"); assert!(shared_pages >= 1, "{artifact}"); assert!(!child_tokens.is_empty(), "{artifact}"); - assert!(gpu_backend.kernel_exec_count() > 0, "{artifact}"); + assert!(gpu_backend.chip_calls() > 0, "{artifact}"); assert_eq!(gpu_backend.fallback_count(), 0, "{artifact}"); assert_eq!(tokens.len(), 4, "{artifact}"); assert_eq!(leaked, 0, "{artifact}"); diff --git a/docs/AIEN_INFERENCE_ABI_SPEC.md b/docs/AIEN_INFERENCE_ABI_SPEC.md index eb42b103..85ced481 100644 --- a/docs/AIEN_INFERENCE_ABI_SPEC.md +++ b/docs/AIEN_INFERENCE_ABI_SPEC.md @@ -38,7 +38,7 @@ AIEN serves as the native compiled inference runtime. High-performance tensor ex | :--- | :--- | :--- | :--- | :--- | | **Scheduler** | AIEN Native Continuous Batching Scheduler | AIEN Native Continuous Batching Scheduler | AIEN Native Continuous Batching Scheduler | Deterministic Step Scheduler | | **KV Management** | AIEN Physical Unified CoW Pool | AIEN Physical Unified CoW Pool | In-process Paged Pool | Virtual Page Table | -| **Execution Engine** | Blackwell Gb10 sm_121 cuBLAS 13 | Mojo C-ABI (`libaien_kernels.so`) | Rayon Multi-Core NEON/AVX | ReferenceCpuBackend (FP32 Oracle) | +| **Execution Engine** | GB10 sm_121 Omega native kernels (`OmegaGb10Backend`, no CUDA) | Mojo C-ABI (`libaien_kernels.so`) | Rayon Multi-Core NEON/AVX | ReferenceCpuBackend (FP32 Oracle) | | **Inference Backend** | `BlackwellInferenceBackend` | `MojoInferenceBackend` | `NativeCpuInferenceBackend` | `MockInferenceBackend` | | **Memory Substrate** | DGX Spark 128 GB Unified Coherent Memory | DGX Spark 128 GB Unified Coherent Memory | Standard Host DRAM | Heap Slices | diff --git a/docs/campaigns/gb10-4-strict-real-model/README.md b/docs/campaigns/gb10-4-strict-real-model/README.md index 1856fcb1..718c56bc 100644 --- a/docs/campaigns/gb10-4-strict-real-model/README.md +++ b/docs/campaigns/gb10-4-strict-real-model/README.md @@ -7,3 +7,5 @@ Gate: `crates/aien-inference-runtime/tests/strict_real_model.rs` (ignored test ` Run 002 on the DGX Spark, 2026-10-03 (`receipt-run002.json`, `run002.summary.txt`): surface NVIDIA GB10, backend `BlackwellGb10Backend (NVIDIA GB10 sm_121 cuBLAS)`, TinyLlama-1.1B-Chat-v1.0, prompt "The DGX Spark is a small computer with a large" -> "amount of processing power. It is designed", fallback_count 0, verdict PASS. [OBSERVED] Limit: the GB10 backend in this crate is CUDA/cuBLAS; the project decision to keep CUDA out of AIEN (comparison runs only) means the native nvrm/Omega-engine backend is a separate open item. This gate measures strictness and binding, not the backend's provenance. + +Update 2026-10-04 (FB-1 cut 6): the CUDA/cuBLAS backend is deleted. The GB10 path is `OmegaGb10Backend` (Omega native kernels, all nine tensor ops), the default whenever the engine is linked. `scripts/zero-cuda-gate.sh` fails any `aien-cli` build that needs a CUDA library or imports a CUDA symbol; it has a self-test negative control. Run 002 above is kept as recorded. diff --git a/scripts/zero-cuda-gate.sh b/scripts/zero-cuda-gate.sh new file mode 100755 index 00000000..10775a51 --- /dev/null +++ b/scripts/zero-cuda-gate.sh @@ -0,0 +1,78 @@ +#!/usr/bin/env bash +# Zero-CUDA gate (FB-1 cut 6): fails when a binary needs an NVIDIA CUDA library or +# imports a CUDA runtime/driver/cuBLAS/NVRTC symbol. AIEN reaches the GB10 only through +# the Omega engine (libomega_gpu.a, linked statically, no CUDA). +# +# scripts/zero-cuda-gate.sh ... check the given binaries +# scripts/zero-cuda-gate.sh --self-test negative control: builds a stub library +# and object that must FAIL the check +# Exit 0 = every binary clean, 1 = CUDA found, 2 = usage or tool error. +set -euo pipefail + +LIB_RE='lib(cuda|cudart|cublas|cublasLt|nvrtc|nvJitLink|cudnn|nvidia-ptxjitcompiler)\.so' +SYM_RE='^(cu[A-Z][A-Za-z0-9_]*|cuda[A-Z][A-Za-z0-9_]*|cublas[A-Za-z0-9_]*|nvrtc[A-Z][A-Za-z0-9_]*|__cuda[A-Za-z0-9_]*)(@.*)?$' + +check_one() { + local bin=$1 bad=0 + if [ ! -f "$bin" ]; then + echo "ZERO_CUDA ERROR $bin: no such file" >&2 + return 2 + fi + local needed undef + needed=$(readelf -d "$bin" 2>/dev/null | sed -n 's/.*(NEEDED).*\[\(.*\)\]/\1/p') || return 2 + undef=$(nm -D --undefined-only "$bin" 2>/dev/null | awk '{print $NF}') || return 2 + local hit + hit=$(printf '%s\n' "$needed" | grep -E "$LIB_RE" || true) + if [ -n "$hit" ]; then + echo "ZERO_CUDA FAIL $bin needs: $(echo $hit)" + bad=1 + fi + hit=$(printf '%s\n' "$undef" | grep -E "$SYM_RE" || true) + if [ -n "$hit" ]; then + echo "ZERO_CUDA FAIL $bin imports: $(echo $hit | cut -c1-400)" + bad=1 + fi + if [ $bad -eq 0 ]; then + echo "ZERO_CUDA PASS $bin needs=[$(echo $needed)]" + fi + return $bad +} + +self_test() { + local d + d=$(mktemp -d) + trap 'rm -rf "$d"' RETURN + # A stub named like the CUDA runtime, and an object that calls cudaMalloc through it. + printf 'int cudaMalloc(void **p, unsigned long n) { (void)p; (void)n; return 1; }\n' >"$d/stub.c" + printf 'int cudaMalloc(void **p, unsigned long n);\nint probe(void) { void *p; return cudaMalloc(&p, 1); }\n' >"$d/probe.c" + cc -shared -fPIC -o "$d/libcudart.so" -Wl,-soname,libcudart.so.13 "$d/stub.c" + cc -shared -fPIC -o "$d/probe.so" "$d/probe.c" -L"$d" -Wl,--no-as-needed -lcudart + printf 'int clean(void) { return 0; }\n' >"$d/clean.c" + cc -shared -fPIC -o "$d/clean.so" "$d/clean.c" + local out rc=0 + out=$(check_one "$d/probe.so") || rc=$? + echo "$out" + if [ $rc -ne 1 ] || ! grep -q 'needs: libcudart.so.13' <<<"$out" || ! grep -q 'imports: cudaMalloc' <<<"$out"; then + echo "ZERO_CUDA SELF-TEST BROKEN: the CUDA probe was not caught (rc=$rc)" >&2 + return 2 + fi + check_one "$d/clean.so" >/dev/null || { + echo "ZERO_CUDA SELF-TEST BROKEN: a CUDA-free library was rejected" >&2 + return 2 + } + echo "ZERO_CUDA SELF-TEST PASS (CUDA probe rejected, clean library accepted)" +} + +if [ $# -eq 0 ]; then + echo "usage: $0 ... | --self-test" >&2 + exit 2 +fi +if [ "$1" = "--self-test" ]; then + self_test + exit $? +fi +status=0 +for b in "$@"; do + check_one "$b" || { rc=$?; [ $rc -gt $status ] && status=$rc; } +done +exit $status