A high-performance inference engine for AI models
Support `BuildTreeOut` kernel (#572)
CCYehb01d6383f432
diff --git a/Cargo.lock b/Cargo.lockindex b64e57d07..fc97bb867 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -154,9 +154,9 @@ dependencies = [[[package]]name = "anyhow"-version = "1.0.102"+version = "1.0.103"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c"+checksum = "2a4385e2e34eb35d6b3efe798b9eb88096925d87726c0798709bf56d9ed84af3"[[package]]name = "apple-native-keyring-store"diff --git a/crates/backend-uzu/build/metal/ast.rs b/crates/backend-uzu/build/metal/ast.rsindex aef2459c6..3b79ef099 100644--- a/crates/backend-uzu/build/metal/ast.rs+++ b/crates/backend-uzu/build/metal/ast.rs@@ -1,12 +1,42 @@use anyhow::{Context, bail};+use quote::quote;use serde::{Deserialize, Serialize};use crate::common::{+ expr_rewrite::rewrite_paths_with,identifiers::{ArgumentName, KernelName},kernel::{Kernel, KernelArgument, KernelArgumentType, KernelBufferAccess, KernelParameter, KernelParameterType},};pub type MetalAstNode = clang_ast::Node<MetalAstKind>;+type IntegerObjectDefines = Box<[(Box<str>, u64)]>;++fn integer_object_defines_from_source(source: &str) -> IntegerObjectDefines {+ source+ .lines()+ .filter_map(|line| {+ let rest = line.trim_start().strip_prefix("#define")?.trim_start();+ let (name, value) = rest.split_once(char::is_whitespace)?;+ let value = value.split_whitespace().next()?.trim_end_matches(['u', 'U']).parse::<u64>().ok()?;+ Some((name.into(), value))+ })+ .collect()+}++fn expand_integer_defines_in_threadgroup_dimension(+ dimension_expression: &str,+ defines: &IntegerObjectDefines,+) -> Box<str> {+ let Ok(mut expr) = syn::parse_str::<syn::Expr>(dimension_expression) else {+ return dimension_expression.into();+ };+ rewrite_paths_with(&mut expr, |path| {+ let ident = path.get_ident()?;+ let (_, value) = defines.iter().find(|(name, _)| ident == name.as_ref())?;+ syn::parse_str::<syn::Expr>(&value.to_string()).ok()+ });+ quote!(#expr).to_string().into_boxed_str()+}#[derive(Debug, Clone, Deserialize)]pub struct MetalAstType {@@ -183,6 +213,7 @@ impl MetalArgument {fn from_ast_node_and_source(argument_node: MetalAstNode,source: &str,+ integer_defines: &IntegerObjectDefines,) -> anyhow::Result<Self> {let MetalAstKind::ParmVarDecl {name,@@ -215,7 +246,8 @@ impl MetalArgument {let source: Box<str> =str::from_utf8(&source.as_bytes()[start_offset..=end_offset]).context("source range is not utf-8")?.into();- let (argument_type, condition) = parse_argument_annotation(&c_type, &source, annotation.as_deref())?;+ let (argument_type, condition) =+ parse_argument_annotation(&c_type, &source, annotation.as_deref(), integer_defines)?;Ok(Self {name: ArgumentName::from(name),@@ -245,6 +277,7 @@ fn parse_argument_annotation(c_type: &str,source: &str,annotation: Option<&[Box<str>]>,+ integer_defines: &IntegerObjectDefines,) -> anyhow::Result<(MetalArgumentType, Option<Box<str>>)> {if let Some(annotation) = annotation&& annotation.first().map(|s| s.as_ref()) == Some("dsl.optional")@@ -252,7 +285,7 @@ fn parse_argument_annotation(if annotation.len() != 2 {bail!("dsl.optional takes 1 argument, found {}", annotation.len() - 1);}- let argument_type = parse_argument_type(c_type, source, None)?;+ let argument_type = parse_argument_type(c_type, source, None, integer_defines)?;if !matches!(argument_type,MetalArgumentType::Buffer(_) | MetalArgumentType::Constant(_) | MetalArgumentType::Shared(_)@@ -262,7 +295,7 @@ fn parse_argument_annotation(return Ok((argument_type, Some(annotation[1].clone())));}- let argument_type = parse_argument_type(c_type, source, annotation)?;+ let argument_type = parse_argument_type(c_type, source, annotation, integer_defines)?;Ok((argument_type, None))}@@ -270,6 +303,7 @@ fn parse_argument_type(c_type: &str,source: &str,annotation: Option<&[Box<str>]>,+ integer_defines: &IntegerObjectDefines,) -> anyhow::Result<MetalArgumentType> {if let Some(annotation) = annotation {let mut annotation = annotation.to_vec();@@ -349,7 +383,10 @@ fn parse_argument_type(if c_type.contains("threadgroup") && c_type.contains('*') {let lbracket = source.find('[').context("threadgroup missing size bracket")? + 1;let rbracket = source.rfind(']').context("threadgroup missing size bracket")?;- return Ok(MetalArgumentType::Shared(Some(source[lbracket..rbracket].into())));+ return Ok(MetalArgumentType::Shared(Some(expand_integer_defines_in_threadgroup_dimension(+ &source[lbracket..rbracket],+ integer_defines,+ ))));}if c_type.contains("threadgroup") && c_type.contains('&') {@@ -621,9 +658,10 @@ impl MetalKernelInfo {}).collect::<anyhow::Result<_>>()?;+ let integer_defines = integer_object_defines_from_source(source);let arguments = arg_nodes.into_iter()- .map(|an| MetalArgument::from_ast_node_and_source(an, source))+ .map(|an| MetalArgument::from_ast_node_and_source(an, source, &integer_defines)).collect::<anyhow::Result<Box<[_]>>>()?;Ok(Some(MetalKernelInfo {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 dfd9a7402..fd1ecd5f5 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,2 +1,3 @@pub mod gram;+pub mod out;pub mod prefix_beta;diff --git a/crates/backend-uzu/src/backends/cpu/kernel/gdn_tree_verify/out.rs b/crates/backend-uzu/src/backends/cpu/kernel/gdn_tree_verify/out.rsnew file mode 100644index 000000000..d3ac41635--- /dev/null+++ b/crates/backend-uzu/src/backends/cpu/kernel/gdn_tree_verify/out.rs@@ -0,0 +1,89 @@+use half::bf16;+use num_traits::Float;+use proc_macros::kernel;++use crate::array::ArrayElement;++#[kernel(BuildTreeOut)]+#[variants(T, f32, bf16)]+pub fn build_tree_out<T: ArrayElement + Float>(+ q: *const T,+ prefix: *const f32,+ qkd: *const f32,+ u: *const T,+ #[optional(use_h0)] h0: Option<*const f32>,+ #[optional(use_h0)] h0_indices: Option<*const i32>,+ o: *mut T,+ scale: f32,+ batch_size: u32,+ tree_size: u32,+ qk_heads: u32,+ value_heads: u32,+ head_k_dim: u32,+ head_v_dim: u32,+ #[allow(unused)]+ #[specialize]+ use_mxu: bool,+ #[allow(unused)]+ #[specialize]+ transposed_h0: bool,+ #[allow(unused)]+ #[specialize]+ use_h0: bool,+) {+ let batch_size = batch_size as usize;+ let tree_size = tree_size as usize;+ let qk_heads = qk_heads as usize;+ let value_heads = value_heads as usize;+ let head_k_dim = head_k_dim as usize;+ let head_v_dim = head_v_dim as usize;+ let value_heads_per_qk_head = value_heads / qk_heads;+ let h0 = h0.unwrap_or(std::ptr::null());+ let h0_indices = h0_indices.unwrap_or(std::ptr::null());++ for batch in 0..batch_size {+ let h0_index = if use_h0 {+ unsafe { *h0_indices.add(batch) }+ } else {+ -1+ };+ for value_head in 0..value_heads {+ let qk_head = value_head / value_heads_per_qk_head;+ let q_head_base = (batch * tree_size * qk_heads + qk_head) * head_k_dim;+ let prefix_base = batch * tree_size * value_heads + value_head;+ let qkd_base = (batch * value_heads + value_head) * tree_size * tree_size;+ let u_base = (batch * value_heads + value_head) * tree_size * head_v_dim;+ let out_base = ((batch * tree_size) * value_heads + value_head) * head_v_dim;++ for row in 0..tree_size {+ let q_row = q_head_base + row * qk_heads * head_k_dim;+ for value_col in 0..head_v_dim {+ let mut acc = 0.0f32;++ if use_h0 && h0_index >= 0 {+ let h0_base =+ ((h0_index as usize * value_heads + value_head) * head_v_dim + value_col) * head_k_dim;+ let mut dot = 0.0f32;+ for dim in 0..head_k_dim {+ let qv = unsafe { (*q.add(q_row + dim)).to_f32().unwrap() };+ let hv = unsafe { *h0.add(h0_base + dim) };+ dot += qv * hv;+ }+ let prefix_row = unsafe { *prefix.add(prefix_base + row * value_heads) };+ acc += prefix_row.exp() * scale * dot;+ }++ for col in 0..tree_size {+ let qkd_value = unsafe { *qkd.add(qkd_base + row * tree_size + col) };+ let u_value = unsafe { (*u.add(u_base + col * head_v_dim + value_col)).to_f32().unwrap() };+ acc += qkd_value * u_value;+ }++ unsafe {+ *o.add(out_base + row * value_heads * head_v_dim + value_col) = T::from(acc).unwrap();+ }+ }+ }+ }+ }+}diff --git a/crates/backend-uzu/src/backends/metal/kernel/gdn_tree_verify/build_tree_out_dispatch_helper.rs b/crates/backend-uzu/src/backends/metal/kernel/gdn_tree_verify/build_tree_out_dispatch_helper.rsnew file mode 100644index 000000000..a57e2f54e--- /dev/null+++ b/crates/backend-uzu/src/backends/metal/kernel/gdn_tree_verify/build_tree_out_dispatch_helper.rs@@ -0,0 +1,11 @@+#![allow(dead_code)]++use crate::backends::metal::device_tier::DeviceTier;++pub(crate) fn build_tree_out_transposed_h0(+ use_mxu: bool,+ device_tier: DeviceTier,+ use_h0: bool,+) -> bool {+ use_h0 && !use_mxu && matches!(device_tier, DeviceTier::SmallLegacy | DeviceTier::SmallApple8)+}diff --git a/crates/backend-uzu/src/backends/metal/kernel/gdn_tree_verify/out.metal b/crates/backend-uzu/src/backends/metal/kernel/gdn_tree_verify/out.metalnew file mode 100644index 000000000..93564eeff--- /dev/null+++ b/crates/backend-uzu/src/backends/metal/kernel/gdn_tree_verify/out.metal@@ -0,0 +1,161 @@+#include <metal_stdlib>+#include "../common/defines.h"+#include "../common/dsl.h"+#include "../common/thread_context.h"+#include "../matmul/common/fragment.h"+#include "../matmul/common/mxu_fragment_ops.h"+#include "../matmul/common/simdgroup_fragment_ops.h"++using namespace metal;+using namespace uzu::matmul;++#define MATMUL_MXU_ROWS 16u+#define MATMUL_SIMDGROUP_ROWS 8u+#define MATMUL_COLS 32u+#define SIMDGROUPS_PER_TG 4u++// Build tree output for one (batch, value-head, row, value) tile.+//+// q: [B, T, Hg, K], with query head hq = hv / (HV / Hg)+// prefix: [B, T, HV] path log-decay prefix from BuildPrefixBeta+// qkd: [B, HV, T, T] from BuildTreeGram+// u: [B, HV, T, V]+// h0: [H0, HV, V, K]+//+// o[row, value] = exp(prefix[row]) * scale * dot(q[row], h0[value])+// + sum_j qkd[row, j] * u[j, value]+template <+ typename T,+ bool use_mxu,+ bool transposed_h0>+VARIANTS(T, float, bfloat)+VARIANTS(use_mxu, false, true)+VARIANTS(transposed_h0, false, true)+CONSTRAINT(!(use_mxu && transposed_h0))+PUBLIC KERNEL(BuildTreeOut)(+ const device T* q,+ const device float* prefix,+ const device float* qkd,+ const device T* u,+ const device float* h0 OPTIONAL(use_h0),+ const device int* h0_indices OPTIONAL(use_h0),+ device T* o,+ constant const float& scale,+ constant const uint& batch_size,+ constant const uint& tree_size,+ constant const uint& qk_heads,+ constant const uint& value_heads,+ constant const uint& head_k_dim,+ constant const uint& head_v_dim,+ threadgroup uint u_tile_scratch OPTIONAL(transposed_h0)[MATMUL_SIMDGROUP_ROWS * MATMUL_COLS],+ const bool use_h0 SPECIALIZE,+ const ThreadContext thread_context,+ const uint v_tile_idx GROUPS(head_v_dim.div_ceil(MATMUL_COLS)),+ const uint row_tile_group_idx GROUPS(tree_size.div_ceil(+ if use_mxu {+ SIMDGROUPS_PER_TG * MATMUL_MXU_ROWS+ } else {+ SIMDGROUPS_PER_TG * MATMUL_SIMDGROUP_ROWS+ }+ )),+ const uint batch_value_head_idx GROUPS(batch_size * value_heads),+ const uint tid THREADS(SIMDGROUPS_PER_TG * METAL_SIMD_SIZE)+) {+ using Ops = metal::conditional_t<use_mxu, MxuFragmentOps<>, SimdgroupFragmentOps>;+ using InputType = metal::conditional_t<use_mxu, T, float>;+ using H0Read = metal::conditional_t<transposed_h0, ReadTranspose, ReadDirect>;+ constexpr ushort ROWS = Ops::FRAGMENT_ROWS;+ constexpr ushort COL_FRAGMENTS = MATMUL_COLS / Ops::FRAGMENT_COLS;+ using AccFragment = Fragment<float, 1, COL_FRAGMENTS, Ops>;+ using QFragment = OperandFragment<InputType, 1, 1, Ops>;+ using H0Fragment = OperandFragment<float, 1, COL_FRAGMENTS, Ops, H0Read>;+ using QkdFragment = OperandFragment<float, 1, 1, Ops>;+ using UFragment = OperandFragment<InputType, 1, COL_FRAGMENTS, Ops>;+ threadgroup T* u_tile = reinterpret_cast<threadgroup T*>(u_tile_scratch);++ const uint batch_idx = batch_value_head_idx / value_heads;+ const uint value_head_idx = batch_value_head_idx - batch_idx * value_heads;+ const uint value_heads_per_qk_head = value_heads / qk_heads;+ const uint qk_head_idx = value_head_idx / value_heads_per_qk_head;+ const uint row_base = (row_tile_group_idx * SIMDGROUPS_PER_TG + thread_context.simdgroup_index) * ROWS;+ const uint value_base = v_tile_idx * MATMUL_COLS;++ const short valid_rows = short(min(uint(ROWS), tree_size - min(row_base, tree_size)));+ const short valid_cols = short(min(MATMUL_COLS, head_v_dim - min(value_base, head_v_dim)));++ AccFragment acc;+ acc.clear();++ const int h0_index = use_h0 ? h0_indices[batch_idx] : -1;+ if (use_h0 && h0_index >= 0) {+ const uint q_base = (batch_idx * tree_size * qk_heads + row_base * qk_heads + qk_head_idx) * head_k_dim;+ const uint h0_base = ((uint(h0_index) * value_heads + value_head_idx) * head_v_dim + value_base) * head_k_dim;+ for (uint k0 = 0; k0 < head_k_dim; k0 += ROWS) {+ const short valid_k = short(min(uint(ROWS), head_k_dim - k0));+ QFragment q_frag;+ H0Fragment h0_frag;+ q_frag.load_from(+ thread_context.simd_lane_id,+ fragment_source(q + q_base + k0, int(qk_heads * head_k_dim)).bounded(valid_rows, valid_k)+ );+ if constexpr (transposed_h0) {+ h0_frag.load_from(+ thread_context.simd_lane_id,+ fragment_source(h0 + h0_base + k0, int(head_k_dim)).bounded(valid_cols, valid_k)+ );+ } else {+ h0_frag.load_from(+ thread_context.simd_lane_id,+ fragment_source(h0 + h0_base + k0, 1, int(head_k_dim)).bounded(valid_k, valid_cols)+ );+ }+ fragment_mma(acc, q_frag, h0_frag);+ }++ acc.map_coords(thread_context.simd_lane_id, [&](short row, short, float value) {+ const uint global_row = row_base + uint(row);+ const float row_scale =+ global_row < tree_size+ ? exp(prefix[(batch_idx * tree_size + global_row) * value_heads + value_head_idx]) * scale+ : 0.0f;+ return value * row_scale;+ });+ }++ const uint qkd_base = (batch_idx * value_heads + value_head_idx) * tree_size * tree_size + row_base * tree_size;+ const uint u_base = (batch_idx * value_heads + value_head_idx) * tree_size * head_v_dim + value_base;+ for (uint j0 = 0; j0 < tree_size; j0 += ROWS) {+ const short valid_j = short(min(uint(ROWS), tree_size - j0));+ QkdFragment qkd_frag;+ UFragment u_frag;+ qkd_frag.load_from(+ thread_context.simd_lane_id,+ fragment_source(qkd + qkd_base + j0, int(tree_size)).bounded(valid_rows, valid_j)+ );+ if constexpr (transposed_h0) {+ for (uint index = tid; index < uint(ROWS) * MATMUL_COLS; index += SIMDGROUPS_PER_TG * METAL_SIMD_SIZE) {+ const uint local_j = index / MATMUL_COLS;+ const uint local_col = index - local_j * MATMUL_COLS;+ const bool in_bounds = local_j < uint(valid_j) && local_col < uint(valid_cols);+ u_tile[index] = in_bounds ? u[u_base + (j0 + local_j) * head_v_dim + local_col] : T(0);+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);+ u_frag.load_from(+ thread_context.simd_lane_id,+ fragment_source(u_tile, int(MATMUL_COLS)).bounded(valid_j, valid_cols)+ );+ fragment_mma(acc, qkd_frag, u_frag);+ threadgroup_barrier(mem_flags::mem_threadgroup);+ } else {+ u_frag.load_from(+ thread_context.simd_lane_id,+ fragment_source(u + u_base + j0 * head_v_dim, int(head_v_dim)).bounded(valid_j, valid_cols)+ );+ fragment_mma(acc, qkd_frag, u_frag);+ }+ }++ device T* out_tile =+ o + ((batch_idx * tree_size + row_base) * value_heads + value_head_idx) * head_v_dim + value_base;+ acc.store_safe(thread_context.simd_lane_id, out_tile, int(value_heads * head_v_dim), short2(valid_cols, valid_rows));+}diff --git a/crates/backend-uzu/src/backends/metal/kernel/mod.rs b/crates/backend-uzu/src/backends/metal/kernel/mod.rsindex 171e16851..774f84df0 100644--- a/crates/backend-uzu/src/backends/metal/kernel/mod.rs+++ b/crates/backend-uzu/src/backends/metal/kernel/mod.rs@@ -6,6 +6,8 @@ use crate::backends::{metal::Metal,};+#[path = "gdn_tree_verify/build_tree_out_dispatch_helper.rs"]+mod build_tree_out_dispatch_helper;pub mod matmul;pub const MTLB: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/default.metallib"));diff --git a/crates/backend-uzu/unit/backends/common/kernel/mod.rs b/crates/backend-uzu/unit/backends/common/kernel/mod.rsindex 0d9a5e47c..df6ce3c0d 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 layer_norm_test;mod logit_soft_cap_test;mod matmul;mod moe;+mod out_bench;+mod out_test;mod pooling;mod prefix_beta_bench;mod prefix_beta_test;diff --git a/crates/backend-uzu/unit/backends/common/kernel/out_bench.rs b/crates/backend-uzu/unit/backends/common/kernel/out_bench.rsnew file mode 100644index 000000000..f0db6d0f9--- /dev/null+++ b/crates/backend-uzu/unit/backends/common/kernel/out_bench.rs@@ -0,0 +1,139 @@+#![cfg(metal_backend)]++use std::time::Duration;++use criterion::{BenchmarkId, Criterion};+use half::bf16;+use num_traits::Float;+use proc_macros::uzu_bench;++use crate::{+ array::{ArrayContextExt, ArrayElement},+ backends::{+ common::{Allocation, Backend, Context, Kernels, kernel::BuildTreeOutKernel},+ metal::Metal,+ },+ tests::matmul::iter_encode_loop_named,+};++const QK_HEADS: usize = 16;+const VALUE_HEADS: usize = 48;+const HEAD_K_DIM: usize = 128;+const HEAD_V_DIM: usize = 128;+const TREE_OUT_MATMUL_MXU_ROWS: usize = 16;+const TREE_OUT_MATMUL_SIMDGROUP_ROWS: usize = 8;+const TREE_SIZES: &[usize] = &[33, 49, 64, 128, 256, 512];+const BATCH_SIZES: &[usize] = &[1, 2, 4, 8];+const TREE_OUT_VALUE_COLS: usize = 32;+const TREE_OUT_SIMDGROUPS_PER_TG: usize = 4;+const BUILD_TREE_OUT_PATHS: &[(&str, bool, bool, usize)] = &[+ ("Simdgroup/H0Direct", false, false, TREE_OUT_MATMUL_SIMDGROUP_ROWS),+ ("Simdgroup/H0Transposed", false, true, TREE_OUT_MATMUL_SIMDGROUP_ROWS),+ ("MXU/H0Direct", true, false, TREE_OUT_MATMUL_MXU_ROWS),+];++struct TreeOutBuffers {+ q: Allocation<Metal>,+ prefix: Allocation<Metal>,+ qkd: Allocation<Metal>,+ u: Allocation<Metal>,+ h0: Allocation<Metal>,+ h0_indices: Allocation<Metal>,+ o: Allocation<Metal>,+}++fn make_buffers<T: ArrayElement + Float>(+ context: &<Metal as Backend>::Context,+ batch_size: usize,+ tree_size: usize,+) -> TreeOutBuffers {+ let q_len = batch_size * tree_size * QK_HEADS * HEAD_K_DIM;+ let prefix_len = batch_size * tree_size * VALUE_HEADS;+ let qkd_len = batch_size * VALUE_HEADS * tree_size * tree_size;+ let uv_len = batch_size * VALUE_HEADS * tree_size * HEAD_V_DIM;+ let h0_len = batch_size * VALUE_HEADS * HEAD_V_DIM * HEAD_K_DIM;+ let q = (0..q_len).map(|i| T::from(((i as f32 * 0.017).sin() * 0.2) + 0.01).unwrap()).collect::<Vec<_>>();+ let prefix = (0..prefix_len)+ .map(|i| -((i % tree_size) as f32) * 0.01 - ((i % VALUE_HEADS) as f32) * 0.003)+ .collect::<Vec<_>>();+ let qkd = (0..qkd_len).map(|i| ((i as f32 * 0.013).cos() * 0.03) - 0.01).collect::<Vec<_>>();+ let u = (0..uv_len).map(|i| T::from(((i as f32 * 0.011).sin() * 0.3) + 0.04).unwrap()).collect::<Vec<_>>();+ let h0 = (0..h0_len).map(|i| ((i as f32 * 0.019).cos() * 0.2) - 0.01).collect::<Vec<_>>();+ let h0_indices = (0..batch_size as i32).collect::<Vec<_>>();++ TreeOutBuffers {+ q: context.create_array_from(&[q.len()], &q).into_allocation(),+ prefix: context.create_array_from(&[prefix.len()], &prefix).into_allocation(),+ qkd: context.create_array_from(&[qkd.len()], &qkd).into_allocation(),+ u: context.create_array_from(&[u.len()], &u).into_allocation(),+ h0: context.create_array_from(&[h0.len()], &h0).into_allocation(),+ h0_indices: context.create_array_from(&[h0_indices.len()], &h0_indices).into_allocation(),+ o: context.create_array_uninitialized(&[uv_len], T::data_type()).into_allocation(),+ }+}++#[uzu_bench]+fn bench_build_tree_out(c: &mut Criterion) {+ let context = <Metal as Backend>::Context::new().expect("metal context");+ bench_build_tree_out_type::<bf16>(c, &context, "BF16");+ bench_build_tree_out_type::<f32>(c, &context, "F32");+}++fn bench_build_tree_out_type<T: ArrayElement + Float>(+ c: &mut Criterion,+ context: &<Metal as Backend>::Context,+ data_type_name: &str,+) {+ for &(path, use_mxu, transposed_h0, tile_rows) in BUILD_TREE_OUT_PATHS {+ if use_mxu && !context.supports_mxu() {+ continue;+ }+ let tile_name = format!("Rows{tile_rows}_VCols{TREE_OUT_VALUE_COLS}_SG{TREE_OUT_SIMDGROUPS_PER_TG}");+ let mut group =+ c.benchmark_group(format!("Metal/Kernel/GDNTreeVerify/BuildTreeOut/{data_type_name}/{path}/{tile_name}"));+ group.sample_size(10).warm_up_time(Duration::from_millis(100)).measurement_time(Duration::from_millis(500));++ for &batch_size in BATCH_SIZES {+ for &tree_size in TREE_SIZES {+ let mut buffers = make_buffers::<T>(context, batch_size, tree_size);+ let benchmark_path = format!(+ "Metal/Kernel/GDNTreeVerify/BuildTreeOut/{data_type_name}/{path}/{tile_name}/B{batch_size}_T{tree_size}"+ );+ let benchmark_id = BenchmarkId::from_parameter(format!(+ "B{batch_size}_T{tree_size}_QK{QK_HEADS}_HV{VALUE_HEADS}_K{HEAD_K_DIM}_V{HEAD_V_DIM}"+ ));++ let kernel = <<Metal as Backend>::Kernels as Kernels>::BuildTreeOutKernel::new(+ context,+ T::data_type(),+ use_mxu,+ transposed_h0,+ true,+ )+ .expect("BuildTreeOutKernel");+ group.bench_function(benchmark_id, |bencher| {+ iter_encode_loop_named::<Metal, _>(context, bencher, &benchmark_path, |encoder| {+ kernel.encode(+ &buffers.q,+ &buffers.prefix,+ &buffers.qkd,+ &buffers.u,+ Some(&buffers.h0),+ Some(&buffers.h0_indices),+ &mut buffers.o,+ (HEAD_K_DIM as f32).sqrt().recip(),+ batch_size as u32,+ tree_size as u32,+ QK_HEADS as u32,+ VALUE_HEADS as u32,+ HEAD_K_DIM as u32,+ HEAD_V_DIM as u32,+ encoder,+ );+ });+ });+ }+ }+ group.finish();+ }+}diff --git a/crates/backend-uzu/unit/backends/common/kernel/out_test.rs b/crates/backend-uzu/unit/backends/common/kernel/out_test.rsnew file mode 100644index 000000000..ca8b72a20--- /dev/null+++ b/crates/backend-uzu/unit/backends/common/kernel/out_test.rs@@ -0,0 +1,181 @@+use half::bf16;+use num_traits::Float;+use proc_macros::uzu_test;+use test_runner::for_each_non_cpu_backend;++use crate::{+ array::{ArrayContextExt, ArrayElement},+ backends::{+ common::{Backend, Context, Encoder, Kernels, kernel::BuildTreeOutKernel},+ cpu::Cpu,+ },+ tests::{assert::assert_eq_float, helpers::allocation_to_vec},+};++#[derive(Clone, Copy)]+struct Shape {+ batch_size: usize,+ tree_size: usize,+ qk_heads: usize,+ value_heads: usize,+ head_k_dim: usize,+ head_v_dim: usize,+}++struct Inputs<T> {+ q: Vec<T>,+ prefix: Vec<f32>,+ qkd: Vec<f32>,+ u: Vec<T>,+ h0: Vec<f32>,+ h0_indices: Vec<i32>,+}++const BUILD_TREE_OUT_PATHS: &[(&str, bool, bool)] = &[+ ("Simdgroup/H0Direct/Rows8_VCols32_SG4", false, false),+ ("Simdgroup/H0Transposed/Rows8_VCols32_SG4", false, true),+ ("MXU/H0Direct/Rows16_VCols32_SG4", true, false),+];++fn make_inputs<T: ArrayElement + Float>(shape: Shape) -> Inputs<T> {+ let q_len = shape.batch_size * shape.tree_size * shape.qk_heads * shape.head_k_dim;+ let prefix_len = shape.batch_size * shape.tree_size * shape.value_heads;+ let qkd_len = shape.batch_size * shape.value_heads * shape.tree_size * shape.tree_size;+ let u_len = shape.batch_size * shape.value_heads * shape.tree_size * shape.head_v_dim;+ let h0_pool = shape.batch_size + 1;+ let h0_len = h0_pool * shape.value_heads * shape.head_v_dim * shape.head_k_dim;++ Inputs {+ q: (0..q_len).map(|i| T::from(((i as f32 * 0.017).sin() * 0.2) + 0.01).unwrap()).collect(),+ prefix: (0..prefix_len)+ .map(|i| -((i % shape.tree_size) as f32) * 0.01 - ((i % shape.value_heads) as f32) * 0.003)+ .collect(),+ qkd: (0..qkd_len).map(|i| ((i as f32 * 0.013).cos() * 0.1) - 0.02).collect(),+ u: (0..u_len).map(|i| T::from(((i as f32 * 0.011).sin() * 0.3) + 0.04).unwrap()).collect(),+ h0: (0..h0_len).map(|i| ((i as f32 * 0.019).cos() * 0.2) - 0.01).collect(),+ h0_indices: (0..shape.batch_size)+ .map(|i| {+ if i + 1 == shape.batch_size {+ -1+ } else {+ i as i32+ }+ })+ .collect(),+ }+}++fn run_build_tree_out<B: Backend, T: ArrayElement + Float>(+ shape: Shape,+ inputs: &Inputs<T>,+ use_h0: bool,+ use_mxu: bool,+ transposed_h0: bool,+) -> Vec<T> {+ let context = B::Context::new().expect("Failed to create Context");+ let kernel = <<B as Backend>::Kernels as Kernels>::BuildTreeOutKernel::new(+ &context,+ T::data_type(),+ use_mxu,+ transposed_h0,+ use_h0,+ )+ .expect("BuildTreeOutKernel");+ let q = context.as_ref().create_array_from(&[inputs.q.len()], &inputs.q).into_allocation();+ let prefix = context.as_ref().create_array_from(&[inputs.prefix.len()], &inputs.prefix).into_allocation();+ let qkd = context.as_ref().create_array_from(&[inputs.qkd.len()], &inputs.qkd).into_allocation();+ let u = context.as_ref().create_array_from(&[inputs.u.len()], &inputs.u).into_allocation();+ let h0 = use_h0.then(|| context.as_ref().create_array_from(&[inputs.h0.len()], &inputs.h0).into_allocation());+ let h0_indices = use_h0+ .then(|| context.as_ref().create_array_from(&[inputs.h0_indices.len()], &inputs.h0_indices).into_allocation());+ let mut o = context+ .as_ref()+ .create_array_uninitialized(+ &[shape.batch_size * shape.tree_size * shape.value_heads * shape.head_v_dim],+ T::data_type(),+ )+ .into_allocation();++ let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");+ kernel.encode(+ &q,+ &prefix,+ &qkd,+ &u,+ h0.as_ref(),+ h0_indices.as_ref(),+ &mut o,+ (shape.head_k_dim as f32).sqrt().recip(),+ shape.batch_size as u32,+ shape.tree_size as u32,+ shape.qk_heads as u32,+ shape.value_heads as u32,+ shape.head_k_dim as u32,+ shape.head_v_dim as u32,+ &mut encoder,+ );+ encoder.end_encoding().submit().wait_until_completed().unwrap();+ allocation_to_vec(&o)+}++fn check_shape<T: ArrayElement + Float + std::fmt::Display>(+ shape: Shape,+ eps: f32,+) {+ let inputs = make_inputs::<T>(shape);++ for use_h0 in [false, true] {+ let expected = run_build_tree_out::<Cpu, T>(shape, &inputs, use_h0, false, false);+ for_each_non_cpu_backend!(|B| {+ let context = <B as Backend>::Context::new().expect("Failed to create Context");+ for &(path, use_mxu, transposed_h0) in BUILD_TREE_OUT_PATHS {+ if use_mxu && !context.supports_mxu() {+ continue;+ }+ if transposed_h0 && !use_h0 {+ continue;+ }+ let actual = run_build_tree_out::<B, T>(shape, &inputs, use_h0, use_mxu, transposed_h0);+ let msg = format!(+ "backend {} path {path} use_h0 {use_h0} B{}_T{}_QK{}_HV{}_K{}_V{}",+ std::any::type_name::<B>(),+ shape.batch_size,+ shape.tree_size,+ shape.qk_heads,+ shape.value_heads,+ shape.head_k_dim,+ shape.head_v_dim+ );+ assert_eq_float::<T>(&expected, &actual, eps, &msg);+ }+ });+ }+}++#[uzu_test]+fn test_build_tree_out_small() {+ let shape = Shape {+ batch_size: 2,+ tree_size: 17,+ qk_heads: 2,+ value_heads: 6,+ head_k_dim: 32,+ head_v_dim: 32,+ };+ check_shape::<bf16>(shape, 0.08);+ check_shape::<f32>(shape, 5e-3);+}++#[uzu_test]+fn test_build_tree_out_gdn_shape() {+ let shape = Shape {+ batch_size: 1,+ tree_size: 49,+ qk_heads: 16,+ value_heads: 48,+ head_k_dim: 128,+ head_v_dim: 128,+ };+ check_shape::<bf16>(shape, 0.08);+ check_shape::<f32>(shape, 5e-3);+}