diff --git a/crates/aien-inference-abi/build.rs b/crates/aien-inference-abi/build.rs index cb4c3677..e900683b 100644 --- a/crates/aien-inference-abi/build.rs +++ b/crates/aien-inference-abi/build.rs @@ -4,6 +4,7 @@ use std::process::Command; fn main() { println!("cargo:rerun-if-changed=cuda/blackwell_gemm.cu"); + println!("cargo:rerun-if-changed=cuda/paged_attention_bf16.cu"); println!("cargo:rerun-if-changed=build.rs"); let nvcc = PathBuf::from("/usr/local/cuda/bin/nvcc"); @@ -14,11 +15,10 @@ fn main() { let out_dir = env::var("OUT_DIR").expect("OUT_DIR not set"); let out_path = Path::new(&out_dir); - let obj_path = out_path.join("blackwell_gemm.o"); + let gemm_obj_path = out_path.join("blackwell_gemm.o"); + let attn_obj_path = out_path.join("paged_attention_bf16.o"); let lib_path = out_path.join("libblackwell_gemm.a"); - let cuda_src = "cuda/blackwell_gemm.cu"; - let status = Command::new(&nvcc) .args([ "-c", @@ -26,22 +26,41 @@ fn main() { "-arch=sm_121", "-Xcompiler", "-fPIC", - cuda_src, + "cuda/blackwell_gemm.cu", "-o", - obj_path.to_str().unwrap(), + gemm_obj_path.to_str().unwrap(), ]) .status() - .expect("Failed to execute nvcc"); + .expect("Failed to execute nvcc for blackwell_gemm.cu"); if !status.success() { - panic!("nvcc compilation of {} failed", cuda_src); + 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 ar_status = Command::new("ar") .args([ "crs", lib_path.to_str().unwrap(), - obj_path.to_str().unwrap(), + gemm_obj_path.to_str().unwrap(), + attn_obj_path.to_str().unwrap(), ]) .status() .expect("Failed to execute ar"); diff --git a/crates/aien-inference-abi/cuda/blackwell_gemm.cu b/crates/aien-inference-abi/cuda/blackwell_gemm.cu index 145e7455..3671f417 100644 --- a/crates/aien-inference-abi/cuda/blackwell_gemm.cu +++ b/crates/aien-inference-abi/cuda/blackwell_gemm.cu @@ -185,6 +185,21 @@ int blackwell_gemv_f32(const float *x, const float *weight, float *out, int in_d 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) { diff --git a/crates/aien-inference-abi/cuda/paged_attention_bf16.cu b/crates/aien-inference-abi/cuda/paged_attention_bf16.cu new file mode 100644 index 00000000..cd4c4191 --- /dev/null +++ b/crates/aien-inference-abi/cuda/paged_attention_bf16.cu @@ -0,0 +1,386 @@ +#include +#include +#include +#include +#include + +// Parameterized autotuning search space with compile-time overrides +#ifndef PAGE_SIZE +#define PAGE_SIZE 16 +#endif + +#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 +} + +// Truly Cooperative Grouped Query Paged Attention Kernel for Blackwell sm_121. +// Each warp processes one query head across 32 lanes cooperatively. +// Coalesced 128-byte vectorized (32-bit __nv_bfloat162) memory accesses. +// Online softmax is maintained in registers; dot products reduce via __shfl_down_sync. +__global__ void paged_attention_bf16_cooperative_kernel( + const __nv_bfloat16 * __restrict__ q, + const __nv_bfloat16 * __restrict__ k_pool, + const __nv_bfloat16 * __restrict__ v_pool, + 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) { + 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 + PAGE_SIZE - 1) / PAGE_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) { + continue; + } + + int tokens_in_this_block = PAGE_SIZE; + if (b == total_blocks - 1) { + int rem = context_len % PAGE_SIZE; + if (rem != 0) { + tokens_in_this_block = rem; + } + } + + size_t block_offset = (size_t)physical_block_id * num_kv_heads * PAGE_SIZE * head_dim; + const __nv_bfloat16 *k_block = k_pool + block_offset + (kv_head_idx * PAGE_SIZE * head_dim); + const __nv_bfloat16 *v_block = v_pool + block_offset + (kv_head_idx * PAGE_SIZE * head_dim); + +#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) { + size_t next_offset = (size_t)next_blk_id * num_kv_heads * PAGE_SIZE * head_dim; + const void *next_k = k_pool + next_offset + (kv_head_idx * PAGE_SIZE * head_dim); + const void *next_v = v_pool + next_offset + (kv_head_idx * PAGE_SIZE * head_dim); + prefetch_global_l2(next_k); + prefetch_global_l2(next_v); + } + } +#endif + + for (int tok = 0; tok < tokens_in_this_block; ++tok) { + const __nv_bfloat16 *k_tok = k_block + (tok * head_dim); + const __nv_bfloat16 *v_tok = v_block + (tok * head_dim); + + // 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; + +extern "C" { + +int paged_attention_bf16_forward( + const __nv_bfloat16 *q, + const __nv_bfloat16 *k_pool, + const __nv_bfloat16 *v_pool, + 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 (num_seqs <= 0 || num_q_heads <= 0 || head_dim <= 0) { + return 0; + } + + bool q_dev = is_device_or_managed_ptr(q); + bool k_dev = is_device_or_managed_ptr(k_pool); + bool v_dev = is_device_or_managed_ptr(v_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 __nv_bfloat16 *d_k = k_pool; + const __nv_bfloat16 *d_v = v_pool; + __nv_bfloat16 *temp_k = NULL; + __nv_bfloat16 *temp_v = NULL; + + if (!k_dev || !v_dev) { + int max_block_id = 0; + for (int i = 0; i < num_seqs * max_blocks_per_seq; ++i) { + if (block_tables[i] > max_block_id) { + max_block_id = block_tables[i]; + } + } + size_t total_pages = max_block_id + 1; + size_t pool_bytes = total_pages * num_kv_heads * PAGE_SIZE * head_dim * sizeof(__nv_bfloat16); + + if (!k_dev) { + cudaMalloc((void**)&temp_k, pool_bytes); + cudaMemcpy((void*)temp_k, k_pool, pool_bytes, cudaMemcpyHostToDevice); + d_k = temp_k; + } + if (!v_dev) { + cudaMalloc((void**)&temp_v, pool_bytes); + cudaMemcpy((void*)temp_v, v_pool, pool_bytes, cudaMemcpyHostToDevice); + d_v = temp_v; + } + } + + 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_k, + d_v, + 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)); + if (temp_k) cudaFree(temp_k); + if (temp_v) cudaFree(temp_v); + return -1; + } + + if (!out_dev) { + cudaMemcpy(out, d_out, out_bytes, cudaMemcpyDeviceToHost); + } + + if (temp_k) cudaFree(temp_k); + if (temp_v) cudaFree(temp_v); + + 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; } +} + +} diff --git a/crates/aien-inference-abi/src/backend.rs b/crates/aien-inference-abi/src/backend.rs index a110e854..b7886fe6 100644 --- a/crates/aien-inference-abi/src/backend.rs +++ b/crates/aien-inference-abi/src/backend.rs @@ -51,6 +51,7 @@ pub trait TensorBackend: Send + Sync { /// SwiGLU activation: out = (gate * silu) * up = silu(gate) * up fn swiglu(&self, out: &mut [f32], gate: &[f32], up: &[f32]); + /// Grouped-Query Attention (GQA) with multi-head queries and shared key-value heads. /// Grouped-Query Attention (GQA) with multi-head queries and shared key-value heads. /// Operates over flattened key and value cache slices with causal history. fn gqa_attention( @@ -65,6 +66,84 @@ pub trait TensorBackend: Send + Sync { head_dim: usize, ); + /// Grouped-Query Paged Attention directly over a physical Copy-on-Write page pool. + /// Default implementation evaluates online softmax token-by-token across physical blocks + /// with zero intermediate array allocation or contiguous gathering. + 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 gqa_ratio = num_q_heads / num_kv_heads; + let inv_sqrt_d = 1.0 / (head_dim as f64).sqrt(); + let block_size = pool.config().block_size; + + for h in 0..num_q_heads { + let kv_head = h / gqa_ratio; + let q_head = &q[h * head_dim..(h + 1) * head_dim]; + + let mut m_prev = f64::NEG_INFINITY; + let mut l_prev = 0.0f64; + let mut acc = vec![0.0f64; head_dim]; + + for t in 0..context_len { + let blk_idx = t / block_size; + if blk_idx >= block_ids.len() { + break; + } + let blk_id = block_ids[blk_idx]; + let slot = t % block_size; + + let head_offset_bytes = kv_head * head_dim * std::mem::size_of::(); + let k_offset = pool.element_offset(blk_id, layer_idx, false, slot) + head_offset_bytes; + let v_offset = pool.element_offset(blk_id, layer_idx, true, slot) + head_offset_bytes; + + let k_slice = unsafe { + std::slice::from_raw_parts(pool.base_ptr().add(k_offset) as *const f32, head_dim) + }; + let v_slice = unsafe { + std::slice::from_raw_parts(pool.base_ptr().add(v_offset) as *const f32, head_dim) + }; + + let mut dot = 0.0f64; + for d in 0..head_dim { + dot += (q_head[d] as f64) * (k_slice[d] as f64); + } + let score = dot * inv_sqrt_d; + + let m_new = m_prev.max(score); + let alpha = (m_prev - m_new).exp(); + let beta = (score - m_new).exp(); + let l_new = l_prev * alpha + beta; + + for d in 0..head_dim { + acc[d] = acc[d] * alpha + beta * (v_slice[d] as f64); + } + + m_prev = m_new; + l_prev = l_new; + } + + let inv_l = if l_prev > 0.0 { 1.0 / l_prev } else { 0.0 }; + let out_head = &mut out[h * head_dim..(h + 1) * head_dim]; + for d in 0..head_dim { + out_head[d] = (acc[d] * inv_l) as f32; + } + } + } + /// Projects hidden states to vocabulary logits: logits = hidden * W^T fn compute_logits( &self, diff --git a/crates/aien-inference-abi/src/blackwell_backend.rs b/crates/aien-inference-abi/src/blackwell_backend.rs index 34468919..4cf396c2 100644 --- a/crates/aien-inference-abi/src/blackwell_backend.rs +++ b/crates/aien-inference-abi/src/blackwell_backend.rs @@ -1,5 +1,6 @@ //! Genuine Blackwell GB10 Hardware Acceleration Backend for DGX Spark. -//! Dispatches single-token GEMV and batched GEMM directly to cuBLAS 13 on Blackwell sm_121. +//! 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 std::ffi::CStr; @@ -25,11 +26,27 @@ extern "C" { in_dim: c_int, out_dim: c_int, ) -> c_int; + fn paged_attention_bf16_forward( + q: *const u16, + k_pool: *const u16, + v_pool: *const u16, + 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 blackwell_allocate_managed(bytes: usize) -> *mut std::ffi::c_void; + fn blackwell_free_managed(ptr: *mut std::ffi::c_void); fn blackwell_gemm_destroy(); } /// Blackwell GB10 GPU Tensor Backend. -/// Executes GEMV and batched GEMM operations on the NVIDIA GB10 Blackwell GPU. +/// Executes GEMV, batched GEMM, and Paged Attention on the NVIDIA GB10 Blackwell GPU. pub struct BlackwellGb10Backend { fallback: ReferenceCpuBackend, device_name: String, @@ -56,6 +73,14 @@ impl BlackwellGb10Backend { } if available { + unsafe fn custom_alloc(bytes: usize) -> *mut u8 { + blackwell_allocate_managed(bytes) as *mut u8 + } + unsafe fn custom_free(ptr: *mut u8, _bytes: usize) { + blackwell_free_managed(ptr as *mut std::ffi::c_void); + } + aien_kv_cache::register_unified_allocator(custom_alloc, custom_free); + eprintln!( "BlackwellGb10Backend: Successfully bound to device '{}' (sm_121 cuBLAS 13)", device_name @@ -91,6 +116,50 @@ impl BlackwellGb10Backend { 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], + k_pool: &[u16], + v_pool: &[u16], + 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(), + k_pool.as_ptr(), + v_pool.as_ptr(), + 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 { @@ -209,6 +278,76 @@ impl TensorBackend for BlackwellGb10Backend { .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; + } + + if self.available && pool.config().dtype == aien_kv_cache::KvDType::Bf16 { + let q_bf16: Vec = q.iter().map(|&v| { + let bits = v.to_bits(); + (bits >> 16) as u16 + }).collect(); + + let sm_scale = 1.0f32 / (head_dim as f32).sqrt(); + let mut out_bf16 = vec![0u16; out.len()]; + let i32_block_tables: Vec = block_ids.iter().map(|&b| b as i32).collect(); + let context_lens = [context_len as i32]; + let max_blocks = block_ids.len(); + + let k_ptr = pool.base_ptr() as *const u16; + let v_ptr = pool.base_ptr() as *const u16; + + let res = self.paged_attention_bf16( + &q_bf16, + unsafe { std::slice::from_raw_parts(k_ptr, pool.total_bytes() / 2) }, + unsafe { std::slice::from_raw_parts(v_ptr, pool.total_bytes() / 2) }, + &i32_block_tables, + &context_lens, + max_blocks, + 1, + num_q_heads, + num_kv_heads, + head_dim, + sm_scale, + &mut out_bf16, + ); + + if res.is_ok() { + for i in 0..out.len() { + let bits = (out_bf16[i] as u32) << 16; + out[i] = f32::from_bits(bits); + } + return; + } + self.fallback_counter.fetch_add(1, Ordering::Relaxed); + } + + self.fallback.paged_attention( + out, + q, + pool, + block_ids, + context_len, + layer_idx, + num_q_heads, + num_kv_heads, + head_dim, + ); + } + fn compute_logits( &self, logits: &mut [f32], @@ -294,4 +433,56 @@ mod tests { ); 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 page_size = 16; + let total_pages = 8; + let max_blocks_per_seq = 4; + + let q = vec![0x3F80u16; num_seqs * num_q_heads * head_dim]; // 1.0 in BF16 + let k_pool = vec![0x3F80u16; total_pages * num_kv_heads * page_size * head_dim]; + let v_pool = vec![0x3F80u16; total_pages * num_kv_heads * page_size * head_dim]; + + 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, + &k_pool, + &v_pool, + &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/transformer_backend.rs b/crates/aien-inference-abi/src/transformer_backend.rs index 86dcd717..84427898 100644 --- a/crates/aien-inference-abi/src/transformer_backend.rs +++ b/crates/aien-inference-abi/src/transformer_backend.rs @@ -200,17 +200,25 @@ impl NativeTransformerBackend { let parent_seq = self .sequences .get(&parent.0) - .ok_or_else(|| format!("Parent context {} not found", parent.0))? - .clone(); + .ok_or_else(|| format!("Parent context {} not found", parent.0))?; let child_id = NEXT_HANDLE_ID.fetch_add(1, Ordering::SeqCst); let child = BranchHandle(child_id); + let child_seq = if self.kv_manager.is_some() { + SequenceState { + tokens: parent_seq.tokens.clone(), + layers: Vec::new(), + } + } else { + parent_seq.clone() + }; + if let Some(kv_mgr) = &self.kv_manager { kv_mgr.write().fork_context(parent.0, child.0)?; } - self.sequences.insert(child.0, parent_seq); + self.sequences.insert(child.0, child_seq); Ok(child) } @@ -348,8 +356,6 @@ impl NativeTransformerBackend { }; for (layer_idx, layer_w) in weights.layers.iter().enumerate() { - let kv_cache = &mut seq_state.layers[layer_idx]; - backend.rmsnorm(&mut x_norm, &x, &layer_w.input_layernorm, eps); 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); @@ -368,27 +374,23 @@ impl NativeTransformerBackend { if let (Some((block_id, slot)), Some(mgr)) = (block_slot, kv_manager) { let _ = mgr.write().write_explicit_token_kv(block_id, layer_idx, slot, &k, &v); - let mut flat_k = Vec::new(); - let mut flat_v = Vec::new(); - let _ = mgr.read().gather_sequence_layer_kv(seq_id, layer_idx, &mut flat_k, &mut flat_v); - - kv_cache.cached_k.push(k.clone()); - kv_cache.cached_v.push(v.clone()); - kv_cache.flat_k = flat_k.clone(); - kv_cache.flat_v = flat_v.clone(); - - let seq_len = kv_cache.cached_k.len(); - backend.gqa_attention( - &mut attn_out, - &q, - &flat_k, - &flat_v, - seq_len, - num_heads, - num_kv_heads, - head_dim, - ); + let mgr_read = mgr.read(); + if let (Some(pool), Some(table)) = (mgr_read.tensor_pool(), mgr_read.get_block_table(seq_id)) { + let total_tokens = table.total_tokens; + backend.paged_attention( + &mut attn_out, + &q, + pool, + &table.block_ids, + total_tokens, + layer_idx, + num_heads, + num_kv_heads, + head_dim, + ); + } } else { + let kv_cache = &mut seq_state.layers[layer_idx]; kv_cache.cached_k.push(k.clone()); kv_cache.cached_v.push(v.clone()); kv_cache.flat_k.extend_from_slice(&k); @@ -605,6 +607,10 @@ impl NativeTransformerBackend { } } + if kv_manager.is_some() { + seq_state.layers.clear(); + } + let last_x = &states[n - 1]; let mut x_final = vec![0.0f32; hidden_dim]; backend.rmsnorm(&mut x_final, last_x, &weights.final_norm, eps); diff --git a/crates/aien-kv-cache/src/lib.rs b/crates/aien-kv-cache/src/lib.rs index aa7dbddd..0e348910 100644 --- a/crates/aien-kv-cache/src/lib.rs +++ b/crates/aien-kv-cache/src/lib.rs @@ -101,13 +101,38 @@ impl KvPoolConfig { } } +pub type CustomAllocFn = unsafe fn(usize) -> *mut u8; +pub type CustomFreeFn = unsafe fn(*mut u8, usize); + +static CUSTOM_ALLOCATOR: parking_lot::RwLock> = + parking_lot::RwLock::new(None); + +/// Registers a custom physical memory allocator (e.g. cudaMallocManaged on Blackwell). +pub fn register_unified_allocator(alloc_fn: CustomAllocFn, free_fn: CustomFreeFn) { + let mut g = CUSTOM_ALLOCATOR.write(); + *g = Some((alloc_fn, free_fn)); +} + +/// Unregisters any custom physical memory allocator. +pub fn unregister_unified_allocator() { + let mut g = CUSTOM_ALLOCATOR.write(); + *g = None; +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PoolMemoryKind { + Mmap, + Heap, + CustomManaged, +} + /// Physical unified-memory KV tensor pool backing virtual block IDs on hardware silicon. pub struct UnifiedKvTensorPool { config: KvPoolConfig, base_ptr: *mut u8, total_bytes: usize, block_bytes: usize, - is_mmap: bool, + memory_kind: PoolMemoryKind, } unsafe impl Send for UnifiedKvTensorPool {} @@ -122,8 +147,21 @@ impl UnifiedKvTensorPool { return Err("Cannot allocate zero-sized KV tensor pool".to_string()); } + if let Some((alloc_fn, _)) = *CUSTOM_ALLOCATOR.read() { + let ptr = unsafe { alloc_fn(total_bytes) }; + if !ptr.is_null() { + return Ok(Self { + config, + base_ptr: ptr, + total_bytes, + block_bytes, + memory_kind: PoolMemoryKind::CustomManaged, + }); + } + } + #[cfg(unix)] - let (base_ptr, is_mmap) = { + let (base_ptr, memory_kind) = { let ptr = unsafe { libc::mmap( std::ptr::null_mut(), @@ -147,11 +185,11 @@ impl UnifiedKvTensorPool { let _ = libc::mlock(ptr, total_bytes); } - (ptr as *mut u8, true) + (ptr as *mut u8, PoolMemoryKind::Mmap) }; #[cfg(not(unix))] - let (base_ptr, is_mmap) = { + let (base_ptr, memory_kind) = { let layout = std::alloc::Layout::from_size_align(total_bytes, 4096) .map_err(|e| format!("Invalid memory layout: {}", e))?; let ptr = unsafe { std::alloc::alloc_zeroed(layout) }; @@ -161,7 +199,7 @@ impl UnifiedKvTensorPool { total_bytes )); } - (ptr, true) + (ptr, PoolMemoryKind::Heap) }; Ok(Self { @@ -169,7 +207,7 @@ impl UnifiedKvTensorPool { base_ptr, total_bytes, block_bytes, - is_mmap, + memory_kind, }) } @@ -337,20 +375,61 @@ impl UnifiedKvTensorPool { tokens_gathered += tokens_in_this_block; } } + + #[inline] + pub fn memory_kind(&self) -> PoolMemoryKind { + self.memory_kind + } + + #[inline] + pub fn token_kv_offset( + &self, + block_id: BlockId, + layer_idx: usize, + is_value: bool, + token_in_block: usize, + ) -> usize { + self.element_offset(block_id, layer_idx, is_value, token_in_block) + } + + #[inline] + pub unsafe fn token_kv_ptr( + &self, + block_id: BlockId, + layer_idx: usize, + is_value: bool, + token_in_block: usize, + ) -> *const u8 { + let offset = self.element_offset(block_id, layer_idx, is_value, token_in_block); + self.base_ptr.add(offset) + } } impl Drop for UnifiedKvTensorPool { fn drop(&mut self) { - if self.is_mmap && !self.base_ptr.is_null() { - #[cfg(unix)] - unsafe { - let _ = libc::munlock(self.base_ptr as *const libc::c_void, self.total_bytes); - libc::munmap(self.base_ptr as *mut libc::c_void, self.total_bytes); - } - #[cfg(not(unix))] - unsafe { - if let Ok(layout) = std::alloc::Layout::from_size_align(self.total_bytes, 4096) { - std::alloc::dealloc(self.base_ptr, layout); + if !self.base_ptr.is_null() { + match self.memory_kind { + PoolMemoryKind::CustomManaged => { + if let Some((_, free_fn)) = *CUSTOM_ALLOCATOR.read() { + unsafe { + free_fn(self.base_ptr, self.total_bytes); + } + } + } + PoolMemoryKind::Mmap => { + #[cfg(unix)] + unsafe { + let _ = libc::munlock(self.base_ptr as *const libc::c_void, self.total_bytes); + libc::munmap(self.base_ptr as *mut libc::c_void, self.total_bytes); + } + } + PoolMemoryKind::Heap => { + #[cfg(not(unix))] + unsafe { + if let Ok(layout) = std::alloc::Layout::from_size_align(self.total_bytes, 4096) { + std::alloc::dealloc(self.base_ptr, layout); + } + } } } }