A high-performance inference engine for AI models
Support `BuildPrefixBeta` (#555)
CCYeh1edbd33a30b7
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/gdn_tree_verify/mod.rs b/crates/backend-uzu/src/backends/cpu/kernel/gdn_tree_verify/mod.rsindex 9174b035c..3c791f6e0 100644--- a/crates/backend-uzu/src/backends/cpu/kernel/gdn_tree_verify/mod.rs+++ b/crates/backend-uzu/src/backends/cpu/kernel/gdn_tree_verify/mod.rs@@ -1 +1,2 @@pub mod path_matrix;+pub mod prefix_beta;diff --git a/crates/backend-uzu/src/backends/cpu/kernel/gdn_tree_verify/prefix_beta.rs b/crates/backend-uzu/src/backends/cpu/kernel/gdn_tree_verify/prefix_beta.rsnew file mode 100644index 000000000..a5243386b--- /dev/null+++ b/crates/backend-uzu/src/backends/cpu/kernel/gdn_tree_verify/prefix_beta.rs@@ -0,0 +1,50 @@+use half::{bf16, f16};+use num_traits::Float;+use proc_macros::kernel;++use crate::{array::ArrayElement, backends::common::gpu_types::ActivationType};++#[kernel(BuildPrefixBeta)]+#[variants(T, f32, f16, bf16)]+pub fn build_prefix_beta<T: ArrayElement + Float>(+ path_matrix: *const u8,+ a_transposed: *const T,+ b: *const T,+ a_log: *const f32,+ dt_bias: *const f32,+ prefix: *mut f32,+ beta: *mut f32,+ batch_size: u32,+ tree_size: u32,+ value_heads: u32,+) {+ let batch_size = batch_size as usize;+ let tree_size = tree_size as usize;+ let value_heads = value_heads as usize;++ unsafe {+ for batch in 0..batch_size {+ let path_batch = batch * tree_size * tree_size;+ let batch_offset = batch * tree_size * value_heads;++ for row in 0..tree_size {+ for head in 0..value_heads {+ let out_idx = batch_offset + row * value_heads + head;+ let b_val = (*b.add(out_idx)).to_f32().unwrap();+ *beta.add(out_idx) = 1.0 / (1.0 + (-b_val).exp());++ let mut sum = 0.0f32;+ for col in 0..tree_size {+ if *path_matrix.add(path_batch + row * tree_size + col) == 0 {+ continue;+ }+ let a_val = (*a_transposed.add(batch_offset + head * tree_size + col)).to_f32().unwrap();+ let sp = ActivationType::SOFTPLUS.activate(a_val + *dt_bias.add(head));+ sum -= a_log.add(head).read().exp() * sp;+ }+ *prefix.add(out_idx) = sum;+ }+ }+ }+ }+}diff --git a/crates/backend-uzu/src/backends/metal/kernel/gdn_tree_verify/prefix_beta.metal b/crates/backend-uzu/src/backends/metal/kernel/gdn_tree_verify/prefix_beta.metalnew file mode 100644index 000000000..3ca906ca0--- /dev/null+++ b/crates/backend-uzu/src/backends/metal/kernel/gdn_tree_verify/prefix_beta.metal@@ -0,0 +1,59 @@+#include <metal_stdlib>+#include "../activation/activations.h"+#include "../common/defines.h"+#include "../common/dsl.h"++#define ROWS_PER_THREADGROUP 4++using namespace metal;++// path_matrix: [B, T, T] uint8, inclusive ancestor matrix+// a_transposed: [B, HV, T]+// b: [B, T, HV]+// prefix,beta: [B, T, HV] fp32+template <typename T>+VARIANTS(T, float, half, bfloat)+PUBLIC KERNEL(BuildPrefixBeta)(+ const device uint8_t* path_matrix,+ const device T* a_transposed,+ const device T* b,+ const device float* a_log,+ const device float* dt_bias,+ device float* prefix,+ device float* beta,+ constant const uint& batch_size,+ constant const uint& tree_size,+ constant const uint& value_heads,+ const uint batch_idx GROUPS(batch_size),+ const uint row_idx GROUPS(tree_size),+ const uint head_group_idx GROUPS(value_heads.div_ceil(ROWS_PER_THREADGROUP)),+ const uint tid THREADS(ROWS_PER_THREADGROUP * METAL_SIMD_SIZE)+) {+ const uint simd_group = tid / METAL_SIMD_SIZE;+ const uint lane_id = tid - simd_group * METAL_SIMD_SIZE;+ const uint head_idx = head_group_idx * ROWS_PER_THREADGROUP + simd_group;+ if (head_idx >= value_heads) {+ return;+ }++ const uint batch_offset = batch_idx * tree_size * value_heads;+ const uint path_row_offset = batch_idx * tree_size * tree_size + row_idx * tree_size;+ const uint out_idx = batch_offset + row_idx * value_heads + head_idx;++ const float scale = fast::exp(float(a_log[head_idx]));+ const float dt = float(dt_bias[head_idx]);+ float partial = 0.0f;+ for (uint col_idx = lane_id; col_idx < tree_size; col_idx += METAL_SIMD_SIZE) {+ if (path_matrix[path_row_offset + col_idx] != 0) {+ const uint a_idx = batch_offset + head_idx * tree_size + col_idx;+ partial -= scale * activate_softplus(float(a_transposed[a_idx]) + dt);+ }+ }++ const float sum = simd_sum(partial);+ if (lane_id == 0) {+ const float b_val = float(b[out_idx]);+ beta[out_idx] = 1.0f / (1.0f + fast::exp(-b_val));+ prefix[out_idx] = sum;+ }+}diff --git a/crates/backend-uzu/unit/backends/common/kernel/mod.rs b/crates/backend-uzu/unit/backends/common/kernel/mod.rsindex 10ce27383..dac3eedd0 100644--- a/crates/backend-uzu/unit/backends/common/kernel/mod.rs+++ b/crates/backend-uzu/unit/backends/common/kernel/mod.rs@@ -12,6 +12,8 @@ mod matmul;mod moe;mod path_matrix_test;mod pooling;+mod prefix_beta_bench;+mod prefix_beta_test;mod qk_unpack_test;mod qkv_norm_test;mod rms_norm_bench;diff --git a/crates/backend-uzu/unit/backends/common/kernel/prefix_beta_bench.rs b/crates/backend-uzu/unit/backends/common/kernel/prefix_beta_bench.rsnew file mode 100644index 000000000..40f5813d5--- /dev/null+++ b/crates/backend-uzu/unit/backends/common/kernel/prefix_beta_bench.rs@@ -0,0 +1,89 @@+#![cfg(metal_backend)]++use std::mem::size_of;++use criterion::{BenchmarkId, Criterion, Throughput};+use proc_macros::uzu_bench;++use crate::{+ array::ArrayContextExt,+ backends::{+ common::{Allocation, Backend, Kernels, kernel::BuildPrefixBetaKernel},+ metal::Metal,+ },+ data_type::DataType,+ tests::{cold_pool::ColdPool, matmul::iter_encode_loop_named, util::type_short_name},+};++fn chain_path_matrix(tree_size: usize) -> Vec<u8> {+ let mut path_matrix = vec![0; tree_size * tree_size];+ for row in 0..tree_size {+ for col in 0..=row {+ path_matrix[row * tree_size + col] = 1;+ }+ }+ path_matrix+}++struct PrefixBetaBuffers {+ path_matrix: Allocation<Metal>,+ a_transposed: Allocation<Metal>,+ b: Allocation<Metal>,+ prefix: Allocation<Metal>,+ beta: Allocation<Metal>,+}++#[uzu_bench]+fn bench_build_prefix_beta(c: &mut Criterion) {+ let context = crate::tests::util::shared_metal_context();+ let kernel = <<Metal as Backend>::Kernels as Kernels>::BuildPrefixBetaKernel::new(&context, DataType::F32)+ .expect("BuildPrefixBetaKernel");++ let mut group = c.benchmark_group(format!("{}/Kernel/GDNTreeVerify/BuildPrefixBeta", type_short_name::<Metal>()));++ for tree_size in [49usize, 129] {+ let batch_size = 1usize;+ let value_heads = 48usize;+ let len = batch_size * tree_size * value_heads;+ let path_matrix = chain_path_matrix(tree_size);+ let a_transposed = (0..len).map(|i| (i as f32 * 0.17).sin() - 0.4).collect::<Vec<_>>();+ let b_data = (0..len).map(|i| (i as f32 * 0.11).cos() * 0.8).collect::<Vec<_>>();+ let a_log = (0..value_heads).map(|i| -0.2 + i as f32 * 0.03).collect::<Vec<_>>();+ let dt_bias = (0..value_heads).map(|i| 0.1 - i as f32 * 0.02).collect::<Vec<_>>();++ let a_log = context.create_array_from(&[a_log.len()], &a_log);+ let dt_bias = context.create_array_from(&[dt_bias.len()], &dt_bias);+ let bytes_per_copy = path_matrix.len() + len * size_of::<f32>() * 4;+ let mut buffers = ColdPool::new(bytes_per_copy, || PrefixBetaBuffers {+ path_matrix: context.create_array_from(&[path_matrix.len()], &path_matrix).into_allocation(),+ a_transposed: context.create_array_from(&[a_transposed.len()], &a_transposed).into_allocation(),+ b: context.create_array_from(&[b_data.len()], &b_data).into_allocation(),+ prefix: context.create_array_uninitialized(&[len], DataType::F32).into_allocation(),+ beta: context.create_array_uninitialized(&[len], DataType::F32).into_allocation(),+ });++ group.throughput(Throughput::Elements((len * tree_size) as u64));+ group.bench_function(BenchmarkId::from_parameter(format!("B1_T{tree_size}_HV{value_heads}")), |bencher| {+ let benchmark_path = format!(+ "{}/Kernel/GDNTreeVerify/BuildPrefixBeta/B1_T{tree_size}_HV{value_heads}",+ type_short_name::<Metal>()+ );+ iter_encode_loop_named::<Metal, _>(&context, bencher, &benchmark_path, |encoder| {+ let buffers = buffers.next_mut();+ kernel.encode(+ &buffers.path_matrix,+ &buffers.a_transposed,+ &buffers.b,+ a_log.allocation(),+ dt_bias.allocation(),+ &mut buffers.prefix,+ &mut buffers.beta,+ batch_size as u32,+ tree_size as u32,+ value_heads as u32,+ encoder,+ );+ });+ });+ }+}diff --git a/crates/backend-uzu/unit/backends/common/kernel/prefix_beta_test.rs b/crates/backend-uzu/unit/backends/common/kernel/prefix_beta_test.rsnew file mode 100644index 000000000..d457817fa--- /dev/null+++ b/crates/backend-uzu/unit/backends/common/kernel/prefix_beta_test.rs@@ -0,0 +1,125 @@+use proc_macros::uzu_test;+use test_runner::for_each_non_cpu_backend;++use crate::{+ array::ArrayContextExt,+ backends::{+ common::{Backend, Context, Encoder, Kernels, kernel::BuildPrefixBetaKernel},+ cpu::Cpu,+ },+ data_type::DataType,+ tests::{assert::assert_eq_float, helpers::allocation_to_vec},+};++fn get_output<B: Backend>(+ path_matrix: &[u8],+ a_transposed: &[f32],+ b: &[f32],+ a_log: &[f32],+ dt_bias: &[f32],+ batch_size: u32,+ tree_size: u32,+ value_heads: u32,+) -> (Vec<f32>, Vec<f32>) {+ let context = B::Context::new().expect("Failed to create Context");+ let kernel = <<B as Backend>::Kernels as Kernels>::BuildPrefixBetaKernel::new(&context, DataType::F32)+ .expect("Failed to create BuildPrefixBetaKernel");++ let output_len = a_transposed.len();+ let path_matrix = context.create_array_from(&[path_matrix.len()], path_matrix);+ let a_transposed = context.create_array_from(&[a_transposed.len()], a_transposed);+ let b = context.create_array_from(&[b.len()], b);+ let a_log = context.create_array_from(&[a_log.len()], a_log);+ let dt_bias = context.create_array_from(&[dt_bias.len()], dt_bias);+ let mut prefix = context.create_array_uninitialized(&[output_len], DataType::F32).into_allocation();+ let mut beta = context.create_array_uninitialized(&[output_len], DataType::F32).into_allocation();++ let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");+ kernel.encode(+ path_matrix.allocation(),+ a_transposed.allocation(),+ b.allocation(),+ a_log.allocation(),+ dt_bias.allocation(),+ &mut prefix,+ &mut beta,+ batch_size,+ tree_size,+ value_heads,+ &mut encoder,+ );+ encoder.end_encoding().submit().wait_until_completed().unwrap();++ (allocation_to_vec(&prefix), allocation_to_vec(&beta))+}++fn path_matrix_from_parent(+ parent: &[i32],+ batch_size: usize,+ tree_size: usize,+) -> Vec<u8> {+ let mut path_matrix = vec![0; batch_size * tree_size * tree_size];+ for batch in 0..batch_size {+ for row in 0..tree_size {+ let base = batch * tree_size * tree_size + row * tree_size;+ let mut cur = row as i32;+ while cur >= 0 {+ path_matrix[base + cur as usize] = 1;+ cur = parent[batch * tree_size + cur as usize];+ }+ }+ }+ path_matrix+}++#[uzu_test]+fn test_build_prefix_beta_matches_cpu() {+ let batch_size = 2;+ let value_heads = 5;++ for tree_size in [5, 33, 129] {+ let len = batch_size * tree_size * value_heads;+ let mut parent = vec![-1; batch_size * tree_size];+ for batch in 0..batch_size {+ for node in 1..tree_size {+ parent[batch * tree_size + node] = if batch == 0 {+ (node - 1) as i32+ } else {+ ((node - 1) / 2) as i32+ };+ }+ }++ let path_matrix = path_matrix_from_parent(&parent, batch_size, tree_size);+ let a_transposed = (0..len).map(|i| (i as f32 * 0.13).sin() - 0.4).collect::<Vec<_>>();+ let b = (0..len).map(|i| (i as f32 * 0.11).cos() * 0.8).collect::<Vec<_>>();+ let a_log = (0..value_heads).map(|i| -0.2 + i as f32 * 0.03).collect::<Vec<_>>();+ let dt_bias = (0..value_heads).map(|i| 0.1 - i as f32 * 0.02).collect::<Vec<_>>();+ let expected = get_output::<Cpu>(+ &path_matrix,+ &a_transposed,+ &b,+ &a_log,+ &dt_bias,+ batch_size as u32,+ tree_size as u32,+ value_heads as u32,+ );++ for_each_non_cpu_backend!(|B| {+ let output = get_output::<B>(+ &path_matrix,+ &a_transposed,+ &b,+ &a_log,+ &dt_bias,+ batch_size as u32,+ tree_size as u32,+ value_heads as u32,+ );+ let msg = format!("backend {} tree_size {tree_size}", std::any::type_name::<B>());+ assert_eq_float::<f32>(&expected.0, &output.0, 1e-4, &format!("prefix {msg}"));+ assert_eq_float::<f32>(&expected.1, &output.1, 1e-5, &format!("beta {msg}"));+ });+ }+}