A high-performance inference engine for AI models
Gated Deltanet StateAdvance (#606)
CCYeh15b8e73c83ac
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 c752d4cbd..fd25fad36 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,5 +1,6 @@pub mod conv_scan;pub mod out;pub mod prefix_beta;+pub mod state_advance;pub mod tree_gram;pub mod tree_update_solve;diff --git a/crates/backend-uzu/src/backends/cpu/kernel/gdn/tree_verify/state_advance.rs b/crates/backend-uzu/src/backends/cpu/kernel/gdn/tree_verify/state_advance.rsnew file mode 100644index 000000000..81ba1b006--- /dev/null+++ b/crates/backend-uzu/src/backends/cpu/kernel/gdn/tree_verify/state_advance.rs@@ -0,0 +1,56 @@+use half::bf16;+use num_traits::Float;+use proc_macros::kernel;++use crate::array::ArrayElement;++#[kernel(StateAdvance)]+#[variants(T, f32, bf16)]+#[variants(HEAD_K_DIM, 128)]+pub fn state_advance<T: ArrayElement + Float, const HEAD_K_DIM: u32>(+ k_norm: *const f32,+ v: *const T,+ log_decay_buf: *const f32,+ beta_buf: *const f32,+ accepted_indices: *const u32,+ state: *mut f32,+ accepted_len: u32,+ num_v_heads: u32,+ num_k_heads: u32,+) {+ let accepted_len = accepted_len as usize;+ let num_v_heads = num_v_heads as usize;+ let num_k_heads = num_k_heads as usize;+ let head_k_dim = HEAD_K_DIM as usize;+ let head_v_dim = head_k_dim;+ let key_dim = num_k_heads * head_k_dim;+ let value_dim = num_v_heads * head_v_dim;+ let v_heads_per_k_head = num_v_heads / num_k_heads;++ for hv_idx in 0..num_v_heads {+ let hk_idx = hv_idx / v_heads_per_k_head;+ for dv_idx in 0..head_v_dim {+ let state_row_offset = (hv_idx * head_v_dim + dv_idx) * head_k_dim;+ for accepted_idx in 0..accepted_len {+ let tree_idx = unsafe { *accepted_indices.add(accepted_idx) } as usize;+ let tree_head_offset = tree_idx * num_v_heads + hv_idx;+ let decay = unsafe { *log_decay_buf.add(tree_head_offset) }.exp();+ let beta = unsafe { *beta_buf.add(tree_head_offset) };+ let k_offset = tree_idx * key_dim + hk_idx * head_k_dim;++ let mut kv_mem = 0.0;+ for dk_idx in 0..head_k_dim {+ let state_element_ptr = unsafe { state.add(state_row_offset + dk_idx) };+ unsafe { *state_element_ptr *= decay };+ kv_mem += unsafe { *state_element_ptr * *k_norm.add(k_offset + dk_idx) };+ }+ let v_value =+ unsafe { (*v.add(tree_idx * value_dim + hv_idx * head_v_dim + dv_idx)).to_f32().unwrap() };+ let delta = beta * (v_value - kv_mem);+ for dk_idx in 0..head_k_dim {+ unsafe { *state.add(state_row_offset + dk_idx) += *k_norm.add(k_offset + dk_idx) * delta };+ }+ }+ }+ }+}diff --git a/crates/backend-uzu/src/backends/metal/kernel/gdn/tree_verify/state_advance.metal b/crates/backend-uzu/src/backends/metal/kernel/gdn/tree_verify/state_advance.metalnew file mode 100644index 000000000..46d8f63dd--- /dev/null+++ b/crates/backend-uzu/src/backends/metal/kernel/gdn/tree_verify/state_advance.metal@@ -0,0 +1,85 @@+#include <metal_stdlib>+#include "../../common/defines.h"+#include "../../common/dsl.h"+#include "../../common/thread_context.h"++using namespace metal;++// Advances committed GDN state serially along the accepted path.+#define STATE_ADVANCE_THREADS 128+#define DV_PER_SIMDGROUP 4+#define STATE_ADVANCE_DV_GROUPS 8++template <typename T, uint HEAD_K_DIM>+VARIANTS(T, float, bfloat)+VARIANTS(HEAD_K_DIM, 128)+PUBLIC KERNEL(StateAdvance)(+ // [tree_size, num_k_heads, HEAD_K_DIM]+ device const float* k_norm,+ // [tree_size, num_v_heads, HEAD_K_DIM]+ device const T* v,+ // [tree_size, num_v_heads]+ device const float* log_decay_buf,+ // [tree_size, num_v_heads]+ device const float* beta_buf,+ // [accepted_len]+ device const uint* accepted_indices,+ // [num_v_heads, HEAD_K_DIM, HEAD_K_DIM], input/output+ device float* state,+ constant const uint& accepted_len,+ constant const uint& num_v_heads,+ constant const uint& num_k_heads,+ const ThreadContext thread_context,+ const uint hv_idx GROUPS(num_v_heads),+ const uint dv_group_idx GROUPS(STATE_ADVANCE_DV_GROUPS),+ const uint thread_idx THREADS(STATE_ADVANCE_THREADS)+) {+ constexpr uint ELEMS = HEAD_K_DIM / METAL_SIMD_SIZE;+ constexpr uint NUM_SG = STATE_ADVANCE_THREADS / METAL_SIMD_SIZE;+ constexpr uint HEAD_V_DIM = HEAD_K_DIM;+ static_assert(ELEMS == 4, "float4 state advance requires ELEMS == 4");++ const uint lane = thread_context.simd_lane_id;+ const uint simdgroup_idx = thread_context.simdgroup_index;+ const uint dv_base = (dv_group_idx * NUM_SG + simdgroup_idx) * DV_PER_SIMDGROUP;+ const uint dk_base = lane * ELEMS;+ const uint hk_idx = hv_idx / (num_v_heads / num_k_heads);+ const uint key_dim = num_k_heads * HEAD_K_DIM;+ const uint value_dim = num_v_heads * HEAD_V_DIM;++ device float* state_tile = state + (hv_idx * HEAD_V_DIM + dv_base) * HEAD_K_DIM + dk_base;+ float4 state_rows[DV_PER_SIMDGROUP];+ state_rows[0] = *reinterpret_cast<device const float4*>(state_tile + 0 * HEAD_K_DIM);+ state_rows[1] = *reinterpret_cast<device const float4*>(state_tile + 1 * HEAD_K_DIM);+ state_rows[2] = *reinterpret_cast<device const float4*>(state_tile + 2 * HEAD_K_DIM);+ state_rows[3] = *reinterpret_cast<device const float4*>(state_tile + 3 * HEAD_K_DIM);++ for (uint accepted_idx = 0; accepted_idx < accepted_len; ++accepted_idx) {+ const uint tree_idx = accepted_indices[accepted_idx];+ const uint tree_head_offset = tree_idx * num_v_heads + hv_idx;+ const float decay = fast::exp(log_decay_buf[tree_head_offset]);+ const float beta = beta_buf[tree_head_offset];+ const uint k_offset = tree_idx * key_dim + hk_idx * HEAD_K_DIM + dk_base;+ const float4 k = *reinterpret_cast<device const float4*>(k_norm + k_offset);++ state_rows[0] *= decay;+ state_rows[1] *= decay;+ state_rows[2] *= decay;+ state_rows[3] *= decay;+ float4 kv_mem = float4(dot(state_rows[0], k), dot(state_rows[1], k), dot(state_rows[2], k), dot(state_rows[3], k));+ kv_mem = simd_sum(kv_mem);++ const device T* v_row = v + tree_idx * value_dim + hv_idx * HEAD_V_DIM + dv_base;+ const float4 v_value = float4(float(v_row[0]), float(v_row[1]), float(v_row[2]), float(v_row[3]));+ const float4 delta = beta * (v_value - kv_mem);+ state_rows[0] += k * delta[0];+ state_rows[1] += k * delta[1];+ state_rows[2] += k * delta[2];+ state_rows[3] += k * delta[3];+ }++ *reinterpret_cast<device float4*>(state_tile + 0 * HEAD_K_DIM) = state_rows[0];+ *reinterpret_cast<device float4*>(state_tile + 1 * HEAD_K_DIM) = state_rows[1];+ *reinterpret_cast<device float4*>(state_tile + 2 * HEAD_K_DIM) = state_rows[2];+ *reinterpret_cast<device float4*>(state_tile + 3 * HEAD_K_DIM) = state_rows[3];+}diff --git a/crates/backend-uzu/unit/backends/common/kernel/gdn/tree_verify/mod.rs b/crates/backend-uzu/unit/backends/common/kernel/gdn/tree_verify/mod.rsindex 3bab06e07..0416236e8 100644--- a/crates/backend-uzu/unit/backends/common/kernel/gdn/tree_verify/mod.rs+++ b/crates/backend-uzu/unit/backends/common/kernel/gdn/tree_verify/mod.rs@@ -3,6 +3,7 @@ mod out_bench;mod out_test;mod prefix_beta_bench;mod prefix_beta_test;+mod state_advance_test;mod tree_gram_bench;mod tree_gram_test;mod tree_update_solve_bench;diff --git a/crates/backend-uzu/unit/backends/common/kernel/gdn/tree_verify/state_advance_test.rs b/crates/backend-uzu/unit/backends/common/kernel/gdn/tree_verify/state_advance_test.rsnew file mode 100644index 000000000..f40a39e1d--- /dev/null+++ b/crates/backend-uzu/unit/backends/common/kernel/gdn/tree_verify/state_advance_test.rs@@ -0,0 +1,131 @@+#[cfg(metal_backend)]+use std::time::Duration;++#[cfg(metal_backend)]+use criterion::Criterion;+use half::bf16;+use num_traits::Float;+#[cfg(metal_backend)]+use proc_macros::uzu_bench;+use proc_macros::uzu_test;+use test_runner::for_each_non_cpu_backend;++use crate::{+ array::ArrayElement,+ backends::{+ common::{Backend, Context, Encoder, Kernels, kernel::StateAdvanceKernel},+ cpu::Cpu,+ },+ tests::{+ assert::assert_eq_float,+ helpers::{alloc_allocation_with_data, allocation_to_vec},+ },+};+#[cfg(metal_backend)]+use crate::{+ backends::metal::Metal,+ data_type::DataType,+ tests::{cold_pool::ColdPool, helpers::allocation_size_bytes, matmul::iter_encode_loop_named},+};++const TREE_SIZE: usize = 128;+const HEAD_DIM: usize = 128;+const PATH: &[u32] = &[0, 1, 3, 7, 15, 31, 47, 63, 79, 95, 111, 119, 123, 125, 126, 127];+const TEST_NUM_V_HEADS: usize = 6;+const TEST_NUM_K_HEADS: usize = 2;++fn run<B: Backend, T: ArrayElement + Float>(accepted_indices: &[u32]) -> Vec<f32> {+ let context = B::Context::new().expect("context");+ let kernel =+ <<B as Backend>::Kernels as Kernels>::StateAdvanceKernel::new(&context, T::data_type(), HEAD_DIM as u32)+ .expect("kernel");+ let key_len = TREE_SIZE * TEST_NUM_K_HEADS * HEAD_DIM;+ let value_len = TREE_SIZE * TEST_NUM_V_HEADS * HEAD_DIM;+ let scalar_len = TREE_SIZE * TEST_NUM_V_HEADS;+ let state_len = TEST_NUM_V_HEADS * HEAD_DIM * HEAD_DIM;+ let k_norm = (0..key_len).map(|i| (i % 17) as f32 * 0.002 - 0.016).collect::<Vec<_>>();+ let v = (0..value_len).map(|i| T::from((i % 19) as f32 * 0.003 - 0.027).unwrap()).collect::<Vec<_>>();+ let log_decay = (0..scalar_len).map(|i| -0.01 - (i % 7) as f32 * 0.002).collect::<Vec<_>>();+ let beta = (0..scalar_len).map(|i| 0.2 + (i % 5) as f32 * 0.03).collect::<Vec<_>>();+ let initial_state = (0..state_len).map(|i| (i % 23) as f32 * 0.001 - 0.011).collect::<Vec<_>>();++ let k_norm = alloc_allocation_with_data::<B, f32>(&context, &k_norm);+ let v = alloc_allocation_with_data::<B, T>(&context, &v);+ let log_decay = alloc_allocation_with_data::<B, f32>(&context, &log_decay);+ let beta = alloc_allocation_with_data::<B, f32>(&context, &beta);+ let accepted_len = accepted_indices.len();+ let accepted_indices = alloc_allocation_with_data::<B, u32>(&context, accepted_indices);+ let mut committed_state = alloc_allocation_with_data::<B, f32>(&context, &initial_state);++ let mut encoder = Encoder::new(context.as_ref()).expect("encoder");+ kernel.encode(+ &k_norm,+ &v,+ &log_decay,+ &beta,+ &accepted_indices,+ &mut committed_state,+ accepted_len as u32,+ TEST_NUM_V_HEADS as u32,+ TEST_NUM_K_HEADS as u32,+ &mut encoder,+ );+ encoder.end_encoding().submit().wait_until_completed().unwrap();+ allocation_to_vec(&committed_state)+}++#[uzu_test]+fn test_state_advance() {+ for path in [&PATH[..1], &PATH[..8], PATH] {+ for_each_non_cpu_backend!(|B| {+ assert_eq_float(&run::<Cpu, f32>(path), &run::<B, f32>(path), 2e-5, "F32 state");+ assert_eq_float(&run::<Cpu, bf16>(path), &run::<B, bf16>(path), 2e-5, "BF16 state");+ });+ }+}++#[cfg(metal_backend)]+#[uzu_bench]+fn bench_state_advance(c: &mut Criterion) {+ const NUM_V_HEADS: usize = 48;+ const NUM_K_HEADS: usize = 16;+ const BENCHMARK: &str = "Metal/Kernel/GDNTreeVerify/StateAdvance";++ let context = crate::tests::util::shared_metal_context();+ let kernel =+ <<Metal as Backend>::Kernels as Kernels>::StateAdvanceKernel::new(&context, DataType::BF16, HEAD_DIM as u32)+ .expect("kernel");+ let k_norm = alloc_allocation_with_data::<Metal, f32>(&context, &vec![0.001; TREE_SIZE * NUM_K_HEADS * HEAD_DIM]);+ let v = alloc_allocation_with_data::<Metal, bf16>(+ &context,+ &vec![bf16::from_f32(0.01); TREE_SIZE * NUM_V_HEADS * HEAD_DIM],+ );+ let log_decay = alloc_allocation_with_data::<Metal, f32>(&context, &vec![-0.01; TREE_SIZE * NUM_V_HEADS]);+ let beta = alloc_allocation_with_data::<Metal, f32>(&context, &vec![0.2; TREE_SIZE * NUM_V_HEADS]);+ let initial_state = vec![0.01; NUM_V_HEADS * HEAD_DIM * HEAD_DIM];+ let mut group = c.benchmark_group(BENCHMARK);+ group.sample_size(30).warm_up_time(Duration::from_millis(300)).measurement_time(Duration::from_secs(1));++ for accepted_len in [1usize, 4, 8, 16] {+ let accepted_indices = alloc_allocation_with_data::<Metal, u32>(&context, &PATH[..accepted_len]);+ let mut committed_states = ColdPool::new(allocation_size_bytes::<f32>(initial_state.len()), || {+ alloc_allocation_with_data::<Metal, f32>(&context, &initial_state)+ });+ group.bench_function(format!("L{accepted_len}"), |bencher| {+ iter_encode_loop_named::<Metal, _>(&context, bencher, &format!("{BENCHMARK}/L{accepted_len}"), |encoder| {+ kernel.encode(+ &k_norm,+ &v,+ &log_decay,+ &beta,+ &accepted_indices,+ committed_states.next_mut(),+ accepted_len as u32,+ NUM_V_HEADS as u32,+ NUM_K_HEADS as u32,+ encoder,+ );+ });+ });+ }+}