Skip to content

armgit / uzu

Public Imported from GitHub
0

A high-performance inference engine for AI models

Support `TreeUpdateSolve` kernel (#576)

CCYeh35190242cd52
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/gdn_tree_verify/gram.rs b/crates/backend-uzu/src/backends/cpu/kernel/gdn_tree_verify/gram.rs
deleted file mode 100644
index 1da6f5688..000000000
--- a/crates/backend-uzu/src/backends/cpu/kernel/gdn_tree_verify/gram.rs
+++ /dev/null
@@ -1,113 +0,0 @@
-use half::bf16;
-use num_traits::Float;
-use proc_macros::kernel;
-
-use crate::{array::ArrayElement, backends::common::gpu_types::trie::TrieNode};
-#[kernel(BuildTreeGram)]
-#[variants(T, f32, bf16)]
-#[variants(USE_MXU, false)]
-pub fn build_tree_gram<T: ArrayElement + Float, const USE_MXU: bool>(
- q: *const T,
- k: *const T,
- trie: *const TrieNode,
- prefix: *const f32,
- beta: *const f32,
- a_mat: *mut f32,
- qkd: *mut f32,
- ainv: *mut f32,
- scale: f32,
- batch_size: u32,
- tree_size: u32,
- k_heads: u32,
- value_heads: u32,
- head_k_dim: u32,
-) {
- let batch_size = batch_size as usize;
- let tree_size = tree_size as usize;
- let k_heads = k_heads as usize;
- let value_heads = value_heads as usize;
- let head_k_dim = head_k_dim as usize;
-
- let groups_per_head = value_heads / k_heads;
-
- for batch in 0..batch_size {
- for hv in 0..value_heads {
- let hk = hv / groups_per_head;
- let mat_base = (batch * value_heads + hv) * tree_size * tree_size;
- let trie_base = batch * tree_size;
-
- for i in 0..tree_size {
- let row_idx = i as u32;
- let prefix_i = unsafe { *prefix.add((batch * tree_size + i) * value_heads + hv) };
- let beta_i = unsafe { *beta.add((batch * tree_size + i) * value_heads + hv) };
- let row_off = ((batch * tree_size + i) * k_heads + hk) * head_k_dim;
- for j in 0..tree_size {
- let out = mat_base + i * tree_size + j;
- let node = unsafe { *trie.add(trie_base + j) };
- let incl = row_idx >= node.trie_start && row_idx <= node.trie_end;
- if !incl {
- unsafe {
- *a_mat.add(out) = 0.0;
- *qkd.add(out) = 0.0;
- }
- continue;
- }
- let col_off = ((batch * tree_size + j) * k_heads + hk) * head_k_dim;
- let mut kk = 0.0f32;
- let mut qk = 0.0f32;
- for d in 0..head_k_dim {
- let ki = unsafe { (*k.add(row_off + d)).to_f32().unwrap() };
- let kj = unsafe { (*k.add(col_off + d)).to_f32().unwrap() };
- let qi = unsafe { (*q.add(row_off + d)).to_f32().unwrap() };
- kk += ki * kj;
- qk += qi * kj;
- }
- let prefix_j = unsafe { *prefix.add((batch * tree_size + j) * value_heads + hv) };
- let dexp = (prefix_i - prefix_j).exp();
- unsafe {
- *a_mat.add(out) = if i != j {
- beta_i * dexp * kk
- } else {
- 0.0
- };
- *qkd.add(out) = dexp * scale * qk;
- }
- }
- }
-
- invert_tree_gram_matrix(a_mat, ainv, mat_base, tree_size);
- }
- }
-}
-
-fn invert_tree_gram_matrix(
- a_mat: *const f32,
- ainv: *mut f32,
- mat_base: usize,
- tree_size: usize,
-) {
- for i in 0..tree_size {
- for j in 0..tree_size {
- unsafe {
- *ainv.add(mat_base + i * tree_size + j) = if i == j {
- 1.0
- } else {
- 0.0
- };
- }
- }
- }
- for i in 0..tree_size {
- for j in 0..i {
- let mut s = 0.0f32;
- for kx in j..i {
- unsafe {
- s += *a_mat.add(mat_base + i * tree_size + kx) * *ainv.add(mat_base + kx * tree_size + j);
- }
- }
- unsafe {
- *ainv.add(mat_base + i * tree_size + j) = -s;
- }
- }
- }
-}
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.rs
index fd1ecd5f5..029372d1e 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,3 +1,4 @@
-pub mod gram;
pub mod out;
pub mod prefix_beta;
+pub mod tree_gram;
+pub mod tree_update_solve;
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/gdn_tree_verify/tree_gram.rs b/crates/backend-uzu/src/backends/cpu/kernel/gdn_tree_verify/tree_gram.rs
new file mode 100644
index 000000000..7cbf882ea
--- /dev/null
+++ b/crates/backend-uzu/src/backends/cpu/kernel/gdn_tree_verify/tree_gram.rs
@@ -0,0 +1,163 @@
+use half::bf16;
+use num_traits::Float;
+use proc_macros::kernel;
+
+use crate::{array::ArrayElement, backends::common::gpu_types::trie::TrieNode};
+
+const BLOCK: usize = 16;
+
+#[kernel(BuildTreeGram)]
+#[variants(T, f32, bf16)]
+#[variants(USE_MXU, false)]
+pub fn build_tree_gram<T: ArrayElement + Float, const USE_MXU: bool>(
+ q: *const T,
+ k: *const T,
+ trie: *const TrieNode,
+ prefix: *const f32,
+ beta: *const f32,
+ #[optional(use_h0)] h0: Option<*const T>,
+ #[optional(use_h0)] h0_idx: Option<*const i32>,
+ a_packed: *mut f32,
+ qkd: *mut f32,
+ a_inv: *mut f32,
+ #[optional(use_h0)] kh0: Option<*mut f32>,
+ scale: f32,
+ batch_size: u32,
+ tree_size: u32,
+ k_heads: u32,
+ value_heads: u32,
+ head_k_dim: u32,
+ head_v_dim: u32,
+ #[specialize] use_h0: bool,
+) {
+ let batch_size = batch_size as usize;
+ let tree_size = tree_size as usize;
+ let k_heads = k_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_key_head = value_heads / k_heads;
+ let num_blocks = tree_size.div_ceil(BLOCK);
+ let num_col_pairs = num_blocks.div_ceil(2);
+
+ for batch in 0..batch_size {
+ for hv in 0..value_heads {
+ let hk = hv / value_heads_per_key_head;
+
+ // qkd[row, col] = scale * exp(prefix[row] - prefix[col]) * dot(q[row], k[col])
+ // for ancestor-or-self, else 0. Dense [T, T].
+ let mat_base = (batch * value_heads + hv) * tree_size * tree_size;
+ for row in 0..tree_size {
+ let prefix_row = unsafe { *prefix.add((batch * tree_size + row) * value_heads + hv) };
+ let row_off = ((batch * tree_size + row) * k_heads + hk) * head_k_dim;
+ for col in 0..tree_size {
+ let out = mat_base + row * tree_size + col;
+ let node = unsafe { *trie.add(batch * tree_size + col) };
+ if (row as u32) < node.trie_start || (row as u32) > node.trie_end {
+ unsafe { *qkd.add(out) = 0.0 };
+ continue;
+ }
+ let col_off = ((batch * tree_size + col) * k_heads + hk) * head_k_dim;
+ let mut qk = 0.0f32;
+ for d in 0..head_k_dim {
+ qk += unsafe { (*q.add(row_off + d)).to_f32().unwrap() }
+ * unsafe { (*k.add(col_off + d)).to_f32().unwrap() };
+ }
+ let prefix_col = unsafe { *prefix.add((batch * tree_size + col) * value_heads + hv) };
+ unsafe { *qkd.add(out) = (prefix_row - prefix_col).exp() * scale * qk };
+ }
+ }
+
+ // A[row, col] = beta[row] * exp(prefix[row] - prefix[col]) * dot(k[row], k[col])
+ // for proper ancestors, else 0; packed [NB, ceil(NB/2), 16, 32] tiles,
+ // only pairs touching the block lower triangle (same tiles the GPU writes).
+ let a_base = (batch * value_heads + hv) * num_blocks * num_col_pairs * BLOCK * 2 * BLOCK;
+ for block in 0..num_blocks {
+ for pair in 0..=block / 2 {
+ let tile_base = a_base + (block * num_col_pairs + pair) * BLOCK * 2 * BLOCK;
+ for local_row in 0..BLOCK {
+ for local_col in 0..2 * BLOCK {
+ let row = block * BLOCK + local_row;
+ let col = pair * 2 * BLOCK + local_col;
+ let mut value = 0.0f32;
+ if row != col && row < tree_size && col < tree_size {
+ let node = unsafe { *trie.add(batch * tree_size + col) };
+ if (row as u32) >= node.trie_start && (row as u32) <= node.trie_end {
+ let row_off = ((batch * tree_size + row) * k_heads + hk) * head_k_dim;
+ let col_off = ((batch * tree_size + col) * k_heads + hk) * head_k_dim;
+ let mut kk = 0.0f32;
+ for d in 0..head_k_dim {
+ kk += unsafe { (*k.add(row_off + d)).to_f32().unwrap() }
+ * unsafe { (*k.add(col_off + d)).to_f32().unwrap() };
+ }
+ let prefix_row =
+ unsafe { *prefix.add((batch * tree_size + row) * value_heads + hv) };
+ let prefix_col =
+ unsafe { *prefix.add((batch * tree_size + col) * value_heads + hv) };
+ let beta_row = unsafe { *beta.add((batch * tree_size + row) * value_heads + hv) };
+ value = beta_row * (prefix_row - prefix_col).exp() * kk;
+ }
+ }
+ unsafe { *a_packed.add(tile_base + local_row * 2 * BLOCK + local_col) = value };
+ }
+ }
+ }
+ }
+
+ // a_inv = (I + A_diag)^-1 per block, compact [NB, 16, 16], identity-padded;
+ // A is f32 so the diagonal values are read back from a_packed unrounded.
+ for block in 0..num_blocks {
+ let block_size = BLOCK.min(tree_size - block * BLOCK);
+ let block_base = ((batch * value_heads + hv) * num_blocks + block) * BLOCK * BLOCK;
+ let diag_tile = a_base + (block * num_col_pairs + block / 2) * BLOCK * 2 * BLOCK;
+ let diag_col = (block % 2) * BLOCK;
+ for row in 0..BLOCK {
+ for col in 0..BLOCK {
+ unsafe {
+ *a_inv.add(block_base + row * BLOCK + col) = if row == col {
+ 1.0
+ } else {
+ 0.0
+ }
+ };
+ }
+ }
+ for row in 0..block_size {
+ for col in 0..row {
+ let mut sum = 0.0f32;
+ for prev_row in col..row {
+ sum += unsafe { *a_packed.add(diag_tile + row * 2 * BLOCK + diag_col + prev_row) }
+ * unsafe { *a_inv.add(block_base + prev_row * BLOCK + col) };
+ }
+ unsafe { *a_inv.add(block_base + row * BLOCK + col) = -sum };
+ }
+ }
+ }
+
+ // kh0[b, token, hv, dv] = dot(k[b, token, hk], h0[slot, hv, dv])
+ if !use_h0 {
+ continue;
+ }
+ let h0 = h0.unwrap();
+ let h0_idx = h0_idx.unwrap();
+ let kh0 = kh0.unwrap();
+ let h0_slot = unsafe { *h0_idx.add(batch) };
+ if h0_slot >= 0 {
+ let h0_head = ((h0_slot as usize) * value_heads + hv) * head_v_dim * head_k_dim;
+ for token in 0..tree_size {
+ let k_off = ((batch * tree_size + token) * k_heads + hk) * head_k_dim;
+ let kh0_off = ((batch * tree_size + token) * value_heads + hv) * head_v_dim;
+ for dv in 0..head_v_dim {
+ let mut sum = 0.0f32;
+ for d in 0..head_k_dim {
+ sum += unsafe { (*k.add(k_off + d)).to_f32().unwrap() }
+ * unsafe { (*h0.add(h0_head + dv * head_k_dim + d)).to_f32().unwrap() };
+ }
+ unsafe { *kh0.add(kh0_off + dv) = sum };
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/gdn_tree_verify/tree_update_solve.rs b/crates/backend-uzu/src/backends/cpu/kernel/gdn_tree_verify/tree_update_solve.rs
new file mode 100644
index 000000000..0d25d0a30
--- /dev/null
+++ b/crates/backend-uzu/src/backends/cpu/kernel/gdn_tree_verify/tree_update_solve.rs
@@ -0,0 +1,132 @@
+use half::bf16;
+use num_traits::Float;
+use proc_macros::kernel;
+
+use crate::array::ArrayElement;
+
+/// Solves chunked GDN update coefficients: `(I + A) U = beta * (v - exp(prefix) * kh0)`.
+/// `kh0 = k @ h0^T` is precomputed by BuildTreeGram.
+#[kernel(TreeUpdateSolve)]
+#[variants(T, f32, bf16)]
+#[variants(BV, 16, 32)]
+#[variants(USE_MXU, false)]
+pub fn tree_update_solve<T: ArrayElement + Float, const BV: u32, const USE_MXU: bool>(
+ #[optional(use_h0)] kh0: Option<*const f32>,
+ v: *const T,
+ prefix: *const f32,
+ beta: *const f32,
+ a_packed: *const f32,
+ a_inv: *const f32,
+ #[optional(use_h0)] h0_idx: Option<*const i32>,
+ u: *mut f32,
+ batch_size: u32,
+ tree_size: u32,
+ value_heads: u32,
+ head_v_dim: u32,
+ #[specialize] use_h0: bool,
+) {
+ let batch_size = batch_size as usize;
+ let tree_size = tree_size as usize;
+ let value_heads = value_heads as usize;
+ let head_v_dim = head_v_dim as usize;
+ let block_size = 16usize;
+
+ if batch_size == 0 || tree_size == 0 || value_heads == 0 || head_v_dim == 0 {
+ return;
+ }
+
+ let num_blocks = tree_size.div_ceil(block_size);
+ let num_col_pairs = num_blocks.div_ceil(2);
+
+ let kh0 = kh0.unwrap_or(std::ptr::null());
+ let h0_idx = h0_idx.unwrap_or(std::ptr::null());
+
+ for batch in 0..batch_size {
+ let h0_slot = if use_h0 {
+ unsafe { *h0_idx.add(batch) }
+ } else {
+ -1
+ };
+
+ for hv in 0..value_heads {
+ let batch_value_head_idx = batch * value_heads + hv;
+
+ for block in 0..num_blocks {
+ let token_base = block * block_size;
+ let mut acc = vec![0.0f32; block_size * head_v_dim];
+
+ for local_token in 0..block_size {
+ let token = token_base + local_token;
+ if token >= tree_size {
+ continue;
+ }
+
+ let prefix_idx = (batch * tree_size + token) * value_heads + hv;
+ let beta_val = unsafe { *beta.add(prefix_idx) };
+ let decay_from_h0 = unsafe { *prefix.add(prefix_idx) }.exp();
+
+ for dv in 0..head_v_dim {
+ let v_idx = (((batch * tree_size + token) * value_heads + hv) * head_v_dim) + dv;
+ let v_val = unsafe { (*v.add(v_idx)).to_f32().unwrap() };
+
+ let kh0_val = if h0_slot >= 0 {
+ unsafe { *kh0.add(v_idx) }
+ } else {
+ 0.0
+ };
+
+ acc[local_token * head_v_dim + dv] = beta_val * (v_val - decay_from_h0 * kh0_val);
+ }
+ }
+
+ for prev_token in 0..token_base {
+ let prev_block = prev_token / block_size;
+ let prev_local = prev_token % block_size;
+ for local_token in 0..block_size {
+ let token = token_base + local_token;
+ if token >= tree_size {
+ continue;
+ }
+
+ // A is packed [B*HV, NB, ceil(NB/2), 16, 32] block-pair tiles.
+ let a_idx = ((batch_value_head_idx * num_blocks + block) * num_col_pairs + prev_block / 2)
+ * (block_size * 2 * block_size)
+ + local_token * (2 * block_size)
+ + (prev_block % 2) * block_size
+ + prev_local;
+ let a_val = unsafe { *a_packed.add(a_idx) };
+ for dv in 0..head_v_dim {
+ let u_prev_idx = (batch_value_head_idx * tree_size + prev_token) * head_v_dim + dv;
+ acc[local_token * head_v_dim + dv] -= a_val * unsafe { *u.add(u_prev_idx) };
+ }
+ }
+ }
+
+ for local_token in 0..block_size {
+ let token = token_base + local_token;
+ if token >= tree_size {
+ continue;
+ }
+
+ for dv in 0..head_v_dim {
+ let mut sum = 0.0f32;
+ for local_prev_token in 0..block_size {
+ let source_token = token_base + local_prev_token;
+ if source_token >= tree_size {
+ continue;
+ }
+ // Ainv is compact [B * HV, ceil(T/BT), BT, BT] diagonal blocks.
+ let inv_idx = ((batch_value_head_idx * num_blocks + block) * block_size + local_token)
+ * block_size
+ + local_prev_token;
+ sum += unsafe { *a_inv.add(inv_idx) } * acc[local_prev_token * head_v_dim + dv];
+ }
+
+ let u_idx = (batch_value_head_idx * tree_size + token) * head_v_dim + dv;
+ unsafe { *u.add(u_idx) = sum };
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/crates/backend-uzu/src/backends/metal/kernel/gdn_tree_verify/gram.metal b/crates/backend-uzu/src/backends/metal/kernel/gdn_tree_verify/gram.metal
deleted file mode 100644
index d6211a506..000000000
--- a/crates/backend-uzu/src/backends/metal/kernel/gdn_tree_verify/gram.metal
+++ /dev/null
@@ -1,260 +0,0 @@
-#include <metal_stdlib>
-#include "../common/defines.h"
-#include "../common/dsl.h"
-#include "../common/thread_context.h"
-#include "../generated/trie.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;
-using namespace uzu::trie;
-
-#define TREE_GRAM_ROW_TILE 16u
-#define TREE_GRAM_COL_TILE 32u
-#define TREE_GRAM_THREADS METAL_SIMD_SIZE
-#define TREE_GRAM_INVALID_ROW 0xffffffffu
-
-METAL_FUNC void invert_tree_gram_diagonal_block(
- device float* ainv,
- threadgroup const float* diag_a_tile,
- const uint mat_base,
- const uint row_base,
- const uint tree_size,
- const uint block_size,
- const uint thread_idx
-);
-
-// Build tree gram matrices for one (batch, value-head) tile.
-//
-// q, k: [B, T, Hg, K], with key head hk = hv / (HV / Hg)
-// trie: [B, T] DFS intervals; col is an ancestor of row when row is in col's interval
-// prefix: [B, T, HV] path log-decay prefix from BuildPrefixBeta
-// beta: [B, T, HV] sigmoid gate from BuildPrefixBeta
-//
-// a_mat[row, col] = beta[row] * exp(prefix[row] - prefix[col]) * dot(k[row], k[col])
-// for proper ancestors only
-// qkd[row, col] = scale * exp(prefix[row] - prefix[col]) * dot(q[row], k[col])
-// for ancestor-or-self
-// ainv = (I + A)^-1 for each diagonal block
-template <typename T, bool USE_MXU>
-VARIANTS(T, float, bfloat)
-VARIANTS(USE_MXU, false, true)
-PUBLIC KERNEL(BuildTreeGram)(
- const device T* q,
- const device T* k,
- const device TrieNode* trie,
- const device float* prefix,
- const device float* beta,
- device float* a_mat,
- device float* qkd,
- device float* ainv,
- constant const float& scale,
- constant const uint& batch_size,
- constant const uint& tree_size,
- constant const uint& k_heads,
- constant const uint& value_heads,
- constant const uint& head_k_dim,
- threadgroup float diag_a_tile[TREE_GRAM_ROW_TILE * TREE_GRAM_ROW_TILE],
- threadgroup float row_prefix[TREE_GRAM_ROW_TILE],
- threadgroup float row_beta[TREE_GRAM_ROW_TILE],
- threadgroup uint row_token[TREE_GRAM_ROW_TILE],
- threadgroup float col_prefix[TREE_GRAM_COL_TILE],
- threadgroup uint col_trie_start[TREE_GRAM_COL_TILE],
- threadgroup uint col_trie_end[TREE_GRAM_COL_TILE],
- const ThreadContext thread_context,
- const uint batch_idx GROUPS(batch_size),
- const uint value_head_idx GROUPS(value_heads),
- const uint tile_idx GROUPS(tree_size.div_ceil(TREE_GRAM_ROW_TILE) * tree_size.div_ceil(TREE_GRAM_COL_TILE)),
- const uint thread_idx THREADS(TREE_GRAM_THREADS)
-) {
- using Ops = metal::conditional_t<USE_MXU, MxuFragmentOps<>, SimdgroupFragmentOps>;
- constexpr ushort ROW_FRAGMENTS = TREE_GRAM_ROW_TILE / Ops::FRAGMENT_ROWS;
- constexpr ushort COL_FRAGMENTS = TREE_GRAM_COL_TILE / Ops::FRAGMENT_COLS;
- using InputType = metal::conditional_t<USE_MXU, T, float>;
- using AccFragment = Fragment<float, ROW_FRAGMENTS, COL_FRAGMENTS, Ops>;
- using LeftFragment = OperandFragment<InputType, ROW_FRAGMENTS, 1, Ops>;
- using RightFragment = OperandFragment<InputType, 1, COL_FRAGMENTS, Ops, ReadTranspose>;
-
- const uint value_heads_per_key_head = value_heads / k_heads;
- const uint key_head_idx = value_head_idx / value_heads_per_key_head;
- const uint qk_stride = k_heads * head_k_dim;
- const uint qk_base = (batch_idx * tree_size * k_heads + key_head_idx) * head_k_dim;
- const uint prefix_base = batch_idx * tree_size * value_heads + value_head_idx;
- const uint trie_base = batch_idx * tree_size;
- const uint mat_base = (batch_idx * value_heads + value_head_idx) * tree_size * tree_size;
-
- const uint col_tiles = div_ceil(tree_size, TREE_GRAM_COL_TILE);
- const uint row_tile_idx = tile_idx / col_tiles;
- const uint col_tile_idx = tile_idx - row_tile_idx * col_tiles;
- const uint row_base = row_tile_idx * TREE_GRAM_ROW_TILE;
- const uint col_base = col_tile_idx * TREE_GRAM_COL_TILE;
- const ushort lane = thread_context.simd_lane_id;
-
- if (row_base >= tree_size) {
- return;
- }
-
- const uint tile_rows = min(TREE_GRAM_ROW_TILE, tree_size - row_base);
- const uint tile_cols = min(TREE_GRAM_COL_TILE, tree_size - col_base);
- const uint tile_base = mat_base + row_base * tree_size + col_base;
-
- if (col_base >= row_base + TREE_GRAM_ROW_TILE) {
- for (uint idx = thread_idx; idx < tile_rows * tile_cols; idx += TREE_GRAM_THREADS) {
- const uint local_row = idx / tile_cols;
- const uint local_col = idx - local_row * tile_cols;
- const uint offset = tile_base + local_row * tree_size + local_col;
- a_mat[offset] = 0.0f;
- qkd[offset] = 0.0f;
- }
- return;
- }
-
- AccFragment kk_acc;
- AccFragment qk_acc;
- kk_acc.clear();
- qk_acc.clear();
-
- for (uint k_block_start = 0; k_block_start < head_k_dim; k_block_start += Ops::FRAGMENT_ROWS) {
- const uint k_remaining = head_k_dim - k_block_start;
- const uint k_tile_size = Ops::FRAGMENT_ROWS;
- const uint valid_k_cols = min(k_remaining, k_tile_size);
-
- LeftFragment k_left;
- LeftFragment q_left;
- RightFragment k_right;
-
- const uint qk_row_base = qk_base + row_base * qk_stride + k_block_start;
- const uint qk_col_base = qk_base + col_base * qk_stride + k_block_start;
- const device T* k_rows = k + qk_row_base;
- const device T* q_rows = q + qk_row_base;
- const device T* k_cols = k + qk_col_base;
-
- const bool full_k_tile = valid_k_cols == k_tile_size;
- if (full_k_tile && row_base + TREE_GRAM_ROW_TILE <= tree_size) {
- k_left.load_from(lane, fragment_source(k_rows, qk_stride));
- q_left.load_from(lane, fragment_source(q_rows, qk_stride));
- } else {
- k_left.load_from(lane, fragment_source(k_rows, qk_stride).bounded(tile_rows, valid_k_cols));
- q_left.load_from(lane, fragment_source(q_rows, qk_stride).bounded(tile_rows, valid_k_cols));
- }
- if (full_k_tile && col_base + TREE_GRAM_COL_TILE <= tree_size) {
- k_right.load_from(lane, fragment_source(k_cols, qk_stride));
- } else {
- k_right.load_from(lane, fragment_source(k_cols, qk_stride).bounded(tile_cols, valid_k_cols));
- }
-
- fragment_mma(kk_acc, k_left, k_right);
- fragment_mma(qk_acc, q_left, k_right);
- }
-
- const bool has_diag = col_base <= row_base && row_base < col_base + TREE_GRAM_COL_TILE;
- const uint diag_col_offset = has_diag ? row_base - col_base : 0;
- const uint diag_size = min(TREE_GRAM_ROW_TILE, tree_size - row_base);
-
- if (thread_idx < TREE_GRAM_COL_TILE) {
- const uint col_token = col_base + thread_idx;
- if (col_token < tree_size) {
- const TrieNode node = trie[trie_base + col_token];
- col_trie_start[thread_idx] = node.trie_start;
- col_trie_end[thread_idx] = node.trie_end;
- col_prefix[thread_idx] = prefix[prefix_base + col_token * value_heads];
- } else {
- col_trie_start[thread_idx] = 1;
- col_trie_end[thread_idx] = 0;
- col_prefix[thread_idx] = 0.0f;
- }
- }
- if (thread_idx < TREE_GRAM_ROW_TILE) {
- const uint token = row_base + thread_idx;
- if (token < tree_size) {
- row_token[thread_idx] = token;
- row_prefix[thread_idx] = prefix[prefix_base + token * value_heads];
- row_beta[thread_idx] = beta[prefix_base + token * value_heads];
- } else {
- row_token[thread_idx] = TREE_GRAM_INVALID_ROW;
- row_prefix[thread_idx] = 0.0f;
- row_beta[thread_idx] = 0.0f;
- }
- }
- threadgroup_barrier(mem_flags::mem_threadgroup);
-
- AccFragment::zip_for_each_coord(
- lane,
- [&](ushort local_row, ushort local_col, thread float& kk, thread float& qk_dot) {
- const uint row_idx = row_token[local_row];
- const uint col_idx = col_base + local_col;
- const bool in_subtree = row_idx >= col_trie_start[local_col] && row_idx <= col_trie_end[local_col];
- const float decay = exp(row_prefix[local_row] - col_prefix[local_col]);
- const float a_value = in_subtree && row_idx != col_idx ? row_beta[local_row] * decay * kk : 0.0f;
- const float qkd_value = in_subtree ? scale * decay * qk_dot : 0.0f;
- if (has_diag && local_row < diag_size && local_col >= diag_col_offset) {
- const uint diag_col = local_col - diag_col_offset;
- if (diag_col < diag_size) {
- diag_a_tile[local_row * TREE_GRAM_ROW_TILE + diag_col] = a_value;
- }
- }
- kk = a_value;
- qk_dot = qkd_value;
- },
- kk_acc,
- qk_acc
- );
-
- const short2 tile_dims = short2(tile_cols, tile_rows);
- device float* a_tile = a_mat + tile_base;
- device float* qkd_tile = qkd + tile_base;
- if (row_base + TREE_GRAM_ROW_TILE <= tree_size && col_base + TREE_GRAM_COL_TILE <= tree_size) {
- kk_acc.store(lane, a_tile, tree_size);
- qk_acc.store(lane, qkd_tile, tree_size);
- } else {
- kk_acc.store_safe(lane, a_tile, tree_size, tile_dims);
- qk_acc.store_safe(lane, qkd_tile, tree_size, tile_dims);
- }
-
- if (has_diag) {
- threadgroup_barrier(mem_flags::mem_threadgroup);
- invert_tree_gram_diagonal_block(ainv, diag_a_tile, mat_base, row_base, tree_size, diag_size, thread_idx);
- }
-}
-
-METAL_FUNC void invert_tree_gram_diagonal_block(
- device float* ainv,
- threadgroup const float* diag_a_tile,
- const uint mat_base,
- const uint row_base,
- const uint tree_size,
- const uint block_size,
- const uint thread_idx
-) {
- if (thread_idx >= block_size) {
- return;
- }
-
- const uint col = thread_idx;
- float inverse_col[TREE_GRAM_ROW_TILE] = {};
- inverse_col[col] = 1.0f;
-
- METAL_PRAGMA_UNROLL
- for (uint row = 0; row < TREE_GRAM_ROW_TILE; row++) {
- if (row > col && row < block_size) {
- float acc = 0.0f;
- METAL_PRAGMA_UNROLL
- for (uint prev_row = 0; prev_row < TREE_GRAM_ROW_TILE; prev_row++) {
- if (prev_row < row) {
- acc += diag_a_tile[row * TREE_GRAM_ROW_TILE + prev_row] * inverse_col[prev_row];
- }
- }
- inverse_col[row] = -acc;
- }
- }
-
- METAL_PRAGMA_UNROLL
- for (uint row = 0; row < TREE_GRAM_ROW_TILE; row++) {
- if (row < block_size) {
- const uint ainv_offset = mat_base + (row_base + row) * tree_size + row_base + col;
- ainv[ainv_offset] = inverse_col[row];
- }
- }
-}
diff --git a/crates/backend-uzu/src/backends/metal/kernel/gdn_tree_verify/tree_gram.metal b/crates/backend-uzu/src/backends/metal/kernel/gdn_tree_verify/tree_gram.metal
new file mode 100644
index 000000000..8ee34866c
--- /dev/null
+++ b/crates/backend-uzu/src/backends/metal/kernel/gdn_tree_verify/tree_gram.metal
@@ -0,0 +1,362 @@
+#include <metal_stdlib>
+#include "../common/defines.h"
+#include "../common/dsl.h"
+#include "../common/thread_context.h"
+#include "../generated/trie.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;
+using namespace uzu::trie;
+
+#define ROW_TILE 16u
+#define COL_TILE 32u
+#define NUM_SIMDGROUPS 2u
+#define INVALID_ROW 0xffffffffu
+
+// Ragged blocks are padded with identity columns so the 16x16 output is fully
+// initialized.
+METAL_FUNC void invert_tree_gram_diagonal_block(
+ device float* a_inv_block,
+ threadgroup const float* diag_a_tile,
+ const uint block_size,
+ const uint lane
+) {
+ if (lane >= ROW_TILE) {
+ return;
+ }
+
+ const uint col = lane;
+ float inverse_col[ROW_TILE] = {};
+ inverse_col[col] = 1.0f;
+
+ METAL_PRAGMA_UNROLL
+ for (uint row = 0; row < ROW_TILE; row++) {
+ if (row > col && row < block_size) {
+ float acc = 0.0f;
+ METAL_PRAGMA_UNROLL
+ for (uint prev_row = 0; prev_row < ROW_TILE; prev_row++) {
+ if (prev_row < row) {
+ acc += diag_a_tile[row * ROW_TILE + prev_row] * inverse_col[prev_row];
+ }
+ }
+ inverse_col[row] = -acc;
+ }
+ }
+
+ METAL_PRAGMA_UNROLL
+ for (uint row = 0; row < ROW_TILE; row++) {
+ a_inv_block[row * ROW_TILE + col] = inverse_col[row];
+ }
+}
+
+// Unscaled gram dots for one tile: kk = k[rows].k[cols], qk = q[rows].k[cols].
+template <typename T, typename Ops, typename AccFragment, typename LeftFragment, typename RightFragment>
+METAL_FUNC void tree_gram_dots(
+ const device T* k_rows,
+ const device T* q_rows,
+ const device T* k_cols,
+ const uint head_k_dim,
+ const uint qk_stride,
+ const bool full_rows,
+ const uint tile_rows,
+ const bool full_cols,
+ const uint tile_cols,
+ const ushort lane,
+ thread AccFragment& kk_acc,
+ thread AccFragment& qk_acc
+) {
+ kk_acc.clear();
+ qk_acc.clear();
+ // head_k_dim is a multiple of the fragment K depth, so the contraction has no tail.
+ for (uint kb = 0; kb < head_k_dim; kb += Ops::FRAGMENT_ROWS) {
+ LeftFragment k_left;
+ LeftFragment q_left;
+ RightFragment k_right;
+ k_left.load_maybe_bounded(lane, k_rows + kb, qk_stride, full_rows, tile_rows, Ops::FRAGMENT_ROWS);
+ q_left.load_maybe_bounded(lane, q_rows + kb, qk_stride, full_rows, tile_rows, Ops::FRAGMENT_ROWS);
+ k_right.load_maybe_bounded(lane, k_cols + kb, qk_stride, full_cols, tile_cols, Ops::FRAGMENT_ROWS);
+ fragment_mma(kk_acc, k_left, k_right);
+ fragment_mma(qk_acc, q_left, k_right);
+ }
+}
+
+// kh0 = k @ h0[h0_idx[batch]]^T for one row-tile, walking head_v_dim in COL_TILE
+// chunks from dv_start by dv_stride. No-op for a zero initial state.
+template <typename T, typename Ops, typename AccFragment, typename LeftFragment, typename RightFragment>
+METAL_FUNC void tree_kh0(
+ const device T* k_rows,
+ const device T* h0,
+ const device int* h0_idx,
+ device float* kh0,
+ const uint batch_idx,
+ const uint value_head_idx,
+ const uint row_base,
+ const uint tile_rows,
+ const bool full_rows,
+ const uint tree_size,
+ const uint value_heads,
+ const uint head_k_dim,
+ const uint head_v_dim,
+ const uint qk_stride,
+ const uint dv_start,
+ const uint dv_stride,
+ const ushort lane
+) {
+ const int h0_slot = h0_idx[batch_idx];
+ if (h0_slot < 0) {
+ return;
+ }
+ const device T* h0_head = h0 + (uint(h0_slot) * value_heads + value_head_idx) * head_v_dim * head_k_dim;
+ device float* kh0_rows =
+ kh0 + (batch_idx * tree_size + row_base) * value_heads * head_v_dim + value_head_idx * head_v_dim;
+ const uint kh0_row_stride = value_heads * head_v_dim;
+
+ for (uint dv_base = dv_start; dv_base < head_v_dim; dv_base += dv_stride) {
+ const uint tile_dvs = min(uint(COL_TILE), head_v_dim - dv_base);
+ AccFragment kh0_acc;
+ kh0_acc.clear();
+
+ const device T* h0_tile = h0_head + dv_base * head_k_dim;
+ const bool full_dvs = tile_dvs == COL_TILE;
+
+ for (uint kb = 0; kb < head_k_dim; kb += Ops::FRAGMENT_ROWS) {
+ LeftFragment k_left;
+ RightFragment h0_right;
+ k_left.load_maybe_bounded(lane, k_rows + kb, qk_stride, full_rows, tile_rows, Ops::FRAGMENT_ROWS);
+ h0_right.load_maybe_bounded(lane, h0_tile + kb, head_k_dim, full_dvs, tile_dvs, Ops::FRAGMENT_ROWS);
+ fragment_mma(kh0_acc, k_left, h0_right);
+ }
+
+ kh0_acc.store_maybe_bounded(
+ lane,
+ kh0_rows + dv_base,
+ kh0_row_stride,
+ full_rows && full_dvs,
+ short2(tile_dvs, tile_rows)
+ );
+ }
+}
+
+// Builds the tree-verify gram products for one (batch, value-head, row-tile,
+// col-tile-group) strip; each of the threadgroup's simdgroups owns one 16x32
+// column tile (above-diagonal tiles are just zero-filled in qkd) and the row's
+// simdgroups share the kh0 dv chunks round-robin:
+// a_packed: A[row, col] = beta[row] * exp(prefix[row] - prefix[col]) * dot(k[row], k[col])
+// for proper ancestors (trie interval test), packed block-pair tiles
+// [B*HV, NB, ceil(NB/2), 16, 32] f32; only lower-triangle tiles written
+// qkd: scale * exp(prefix[row] - prefix[col]) * dot(q[row], k[col]) for
+// ancestor-or-self, dense [B*HV, T, T] f32
+// a_inv: (I + A)^-1 per diagonal block, compact [B*HV, NB, 16, 16]
+// kh0: k @ h0[h0_idx[batch]]^T, [B, T, HV, head_v_dim] f32; skipped when
+// h0_idx[batch] < 0
+template <typename T, bool USE_MXU>
+VARIANTS(T, float, bfloat)
+VARIANTS(USE_MXU, false, true)
+PUBLIC KERNEL(BuildTreeGram)(
+ const device T* q,
+ const device T* k,
+ const device TrieNode* trie,
+ const device float* prefix,
+ const device float* beta,
+ const device T* h0 OPTIONAL(use_h0),
+ const device int* h0_idx OPTIONAL(use_h0),
+ device float* a_packed,
+ device float* qkd,
+ device float* a_inv,
+ device float* kh0 OPTIONAL(use_h0),
+ constant const float& scale,
+ constant const uint& batch_size,
+ constant const uint& tree_size,
+ constant const uint& k_heads,
+ constant const uint& value_heads,
+ constant const uint& head_k_dim,
+ constant const uint& head_v_dim,
+ threadgroup float diag_a_tile[ROW_TILE * ROW_TILE],
+ threadgroup float row_prefix[ROW_TILE],
+ threadgroup float row_beta[ROW_TILE],
+ threadgroup uint row_token[ROW_TILE],
+ threadgroup float col_prefix[NUM_SIMDGROUPS * COL_TILE],
+ threadgroup uint col_trie_start[NUM_SIMDGROUPS * COL_TILE],
+ threadgroup uint col_trie_end[NUM_SIMDGROUPS * COL_TILE],
+ const bool use_h0 SPECIALIZE,
+ const ThreadContext thread_context,
+ const uint batch_idx GROUPS(batch_size),
+ const uint value_head_idx GROUPS(value_heads),
+ const uint tile_idx GROUPS(
+ tree_size.div_ceil(ROW_TILE) * tree_size.div_ceil(COL_TILE).div_ceil(NUM_SIMDGROUPS)
+ ),
+ const uint thread_idx THREADS(NUM_SIMDGROUPS * METAL_SIMD_SIZE)
+) {
+ using Ops = metal::conditional_t<USE_MXU, MxuFragmentOps<>, SimdgroupFragmentOps>;
+ constexpr ushort ROW_FRAGMENTS = ROW_TILE / Ops::FRAGMENT_ROWS;
+ constexpr ushort COL_FRAGMENTS = COL_TILE / Ops::FRAGMENT_COLS;
+ using InputType = metal::conditional_t<USE_MXU, T, float>;
+ using AccFragment = Fragment<float, ROW_FRAGMENTS, COL_FRAGMENTS, Ops>;
+ using LeftFragment = OperandFragment<InputType, ROW_FRAGMENTS, 1, Ops>;
+ using RightFragment = OperandFragment<InputType, 1, COL_FRAGMENTS, Ops, ReadTranspose>;
+ static_assert(COL_TILE == METAL_SIMD_SIZE, "COL_TILE must match the SIMD width");
+
+ const uint value_heads_per_key_head = value_heads / k_heads;
+ const uint key_head_idx = value_head_idx / value_heads_per_key_head;
+ const uint qk_stride = k_heads * head_k_dim;
+ const uint qk_base = (batch_idx * tree_size * k_heads + key_head_idx) * head_k_dim;
+ const uint prefix_base = batch_idx * tree_size * value_heads + value_head_idx;
+ const uint trie_base = batch_idx * tree_size;
+ const uint mat_base = (batch_idx * value_heads + value_head_idx) * tree_size * tree_size;
+
+ const uint col_tiles = div_ceil(tree_size, COL_TILE);
+ const uint col_tile_groups = div_ceil(col_tiles, NUM_SIMDGROUPS);
+ const uint row_tile_idx = tile_idx / col_tile_groups;
+ const uint col_tile_group_idx = tile_idx - row_tile_idx * col_tile_groups;
+ const uint row_base = row_tile_idx * ROW_TILE;
+ const uint tile_rows = min(ROW_TILE, tree_size - row_base);
+ const bool full_rows = row_base + ROW_TILE <= tree_size;
+ const uint in_band_col_tiles = min(row_base / COL_TILE + 1, col_tiles);
+ const uint diag_col_tile = row_base / COL_TILE;
+ const uint diag_col_offset = row_base - diag_col_tile * COL_TILE;
+ const ushort lane = thread_context.simd_lane_id;
+ const uint simdgroup_idx = thread_context.simdgroup_index;
+ const uint col_slice = simdgroup_idx * COL_TILE;
+ threadgroup float* sg_col_prefix = col_prefix + col_slice;
+ threadgroup uint* sg_col_trie_start = col_trie_start + col_slice;
+ threadgroup uint* sg_col_trie_end = col_trie_end + col_slice;
+
+ if (thread_idx < ROW_TILE) {
+ const uint token = row_base + thread_idx;
+ if (token < tree_size) {
+ row_token[thread_idx] = token;
+ row_prefix[thread_idx] = prefix[prefix_base + token * value_heads];
+ row_beta[thread_idx] = beta[prefix_base + token * value_heads];
+ } else {
+ row_token[thread_idx] = INVALID_ROW;
+ row_prefix[thread_idx] = 0.0f;
+ row_beta[thread_idx] = 0.0f;
+ }
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ const uint num_blocks = div_ceil(tree_size, ROW_TILE);
+ const uint num_col_pairs = div_ceil(num_blocks, 2u);
+
+ const device T* k_rows = k + qk_base + row_base * qk_stride;
+ const device T* q_rows = q + qk_base + row_base * qk_stride;
+
+ const uint col_tile_idx = col_tile_group_idx * NUM_SIMDGROUPS + simdgroup_idx;
+ if (col_tile_idx < in_band_col_tiles) {
+ const uint col_base = col_tile_idx * COL_TILE;
+ const uint tile_cols = min(COL_TILE, tree_size - col_base);
+ const uint tile_base = mat_base + row_base * tree_size + col_base;
+
+ const uint col_token = col_base + lane;
+ if (col_token < tree_size) {
+ const TrieNode node = trie[trie_base + col_token];
+ sg_col_trie_start[lane] = node.trie_start;
+ sg_col_trie_end[lane] = node.trie_end;
+ sg_col_prefix[lane] = prefix[prefix_base + col_token * value_heads];
+ } else {
+ sg_col_trie_start[lane] = 1;
+ sg_col_trie_end[lane] = 0;
+ sg_col_prefix[lane] = 0.0f;
+ }
+
+ const device T* k_cols = k + qk_base + col_base * qk_stride;
+ const bool full_cols = col_base + COL_TILE <= tree_size;
+
+ AccFragment kk_acc;
+ AccFragment qk_acc;
+ tree_gram_dots<T, Ops, AccFragment, LeftFragment, RightFragment>(
+ k_rows,
+ q_rows,
+ k_cols,
+ head_k_dim,
+ qk_stride,
+ full_rows,
+ tile_rows,
+ full_cols,
+ tile_cols,
+ lane,
+ kk_acc,
+ qk_acc
+ );
+
+ const bool has_diag = col_tile_idx == diag_col_tile;
+ simdgroup_barrier(mem_flags::mem_threadgroup);
+
+ AccFragment::zip_for_each_coord(
+ lane,
+ [&](ushort local_row, ushort local_col, thread float& kk, thread float& qk_dot) {
+ const uint row_idx = row_token[local_row];
+ const uint col_idx = col_base + local_col;
+ const bool in_subtree = row_idx >= sg_col_trie_start[local_col] && row_idx <= sg_col_trie_end[local_col];
+ const float decay = exp(row_prefix[local_row] - sg_col_prefix[local_col]);
+ const float a_value = in_subtree && row_idx != col_idx ? row_beta[local_row] * decay * kk : 0.0f;
+ const float qkd_value = in_subtree ? scale * decay * qk_dot : 0.0f;
+ if (has_diag && local_row < tile_rows && local_col >= diag_col_offset) {
+ const uint diag_col = local_col - diag_col_offset;
+ if (diag_col < tile_rows) {
+ diag_a_tile[local_row * ROW_TILE + diag_col] = a_value;
+ }
+ }
+ kk = a_value;
+ qk_dot = qkd_value;
+ },
+ kk_acc,
+ qk_acc
+ );
+
+ device float* a_tile =
+ a_packed +
+ (((batch_idx * value_heads + value_head_idx) * num_blocks + row_tile_idx) * num_col_pairs + col_tile_idx) *
+ (ROW_TILE * COL_TILE);
+ device float* qkd_tile = qkd + tile_base;
+ kk_acc.store_maybe_bounded(lane, a_tile, COL_TILE, full_rows, short2(COL_TILE, tile_rows));
+ qk_acc.store_maybe_bounded(lane, qkd_tile, tree_size, full_rows && full_cols, short2(tile_cols, tile_rows));
+
+ if (has_diag) {
+ // diag_a_tile is written and read only by this simdgroup.
+ simdgroup_barrier(mem_flags::mem_threadgroup);
+ device float* a_inv_block =
+ a_inv + ((batch_idx * value_heads + value_head_idx) * num_blocks + row_tile_idx) * (ROW_TILE * ROW_TILE);
+ invert_tree_gram_diagonal_block(a_inv_block, diag_a_tile, tile_rows, lane);
+ }
+ } else if (col_tile_idx < col_tiles) {
+ // Above-diagonal zero fill; COL_TILE == METAL_SIMD_SIZE, so each
+ // lane owns one column and walks rows by pointer increment.
+ const uint col_base = col_tile_idx * COL_TILE;
+ const uint tile_cols = min(COL_TILE, tree_size - col_base);
+ if (lane < tile_cols) {
+ device float* qkd_ptr = qkd + mat_base + row_base * tree_size + col_base + lane;
+ for (uint row = 0; row < tile_rows; ++row, qkd_ptr += tree_size) {
+ *qkd_ptr = 0.0f;
+ }
+ }
+ }
+
+ // kh0 dv chunks are distributed round-robin over this row tile's simdgroups
+ // (across its col-tile-group threadgroups); chunking also bounds registers.
+ if (use_h0) {
+ const uint row_simdgroups = col_tile_groups * NUM_SIMDGROUPS;
+ tree_kh0<T, Ops, AccFragment, LeftFragment, RightFragment>(
+ k_rows,
+ h0,
+ h0_idx,
+ kh0,
+ batch_idx,
+ value_head_idx,
+ row_base,
+ tile_rows,
+ full_rows,
+ tree_size,
+ value_heads,
+ head_k_dim,
+ head_v_dim,
+ qk_stride,
+ col_tile_idx * COL_TILE,
+ row_simdgroups * COL_TILE,
+ lane
+ );
+ }
+}
diff --git a/crates/backend-uzu/src/backends/metal/kernel/gdn_tree_verify/tree_update_solve.metal b/crates/backend-uzu/src/backends/metal/kernel/gdn_tree_verify/tree_update_solve.metal
new file mode 100644
index 000000000..3d4731ef8
--- /dev/null
+++ b/crates/backend-uzu/src/backends/metal/kernel/gdn_tree_verify/tree_update_solve.metal
@@ -0,0 +1,180 @@
+#include <metal_stdlib>
+#include "../common/defines.h"
+#include "../common/dsl.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;
+
+// Block forward substitution for (I + A) U = beta * (v - exp(prefix) * kh0).
+// Per 16-token block i, serially: acc_i = beta * (v_i - exp(prefix_i) * kh0_i);
+// acc_i -= A[i, j] @ U[j] for all j < i; U[i] = Ainv[i] @ acc_i.
+//
+// Shapes (NB = ceil(T/16)):
+// kh0 [B, T, HV, head_v_dim] f32, from BuildTreeGram (absent when !use_h0)
+// v [B, T, HV, head_v_dim] in T
+// prefix, beta [B, T, HV] f32
+// A [B*HV, NB, ceil(NB/2), 16, 32] f32 packed pair tiles from BuildTreeGram
+// (block (i,j) at pair j/2, column (j%2)*16)
+// Ainv [B*HV, NB, 16, 16] f32 diagonal-block inverses from BuildTreeGram
+// h0_idx [B] i32, negative = zero initial state (absent when !use_h0)
+// U [B*HV, T, head_v_dim] f32 (output)
+//
+// Grid: one simdgroup per (batch, value head, BV value-dim tile); the history is
+// consumed one packed pair tile ([16,32] A x [32,BV] U) per fragment_mma plus a
+// single-block tail when i is odd.
+// A and Ainv are kept in f32: the (I + A)^-1 forward-substitution cascade is
+// precision-sensitive.
+template <typename T, uint BV, bool USE_MXU>
+VARIANTS(T, float, bfloat)
+VARIANTS(BV, 16, 32)
+VARIANTS(USE_MXU, false, true)
+CONSTRAINT(!USE_MXU || T != "float")
+CONSTRAINT(!USE_MXU || BV >= 32)
+PUBLIC KERNEL(TreeUpdateSolve)(
+ const device float* kh0 OPTIONAL(use_h0),
+ const device T* v,
+ const device float* prefix,
+ const device float* beta,
+ const device float* a_packed,
+ const device float* a_inv,
+ const device int* h0_idx OPTIONAL(use_h0),
+ device float* u,
+ constant const uint& batch_size,
+ constant const uint& tree_size,
+ constant const uint& value_heads,
+ constant const uint& head_v_dim,
+ const bool use_h0 SPECIALIZE,
+ const uint batch_idx GROUPS(batch_size),
+ const uint value_head_idx GROUPS(value_heads),
+ const uint value_tile_idx GROUPS(head_v_dim.div_ceil(BV)),
+ const uint lane_idx THREADS(METAL_SIMD_SIZE)
+) {
+ constexpr uint BT = 16;
+ using FragmentOps = metal::conditional_t<USE_MXU, MxuFragmentOps<>, SimdgroupFragmentOps>;
+ constexpr ushort TOKEN_FRAGMENTS = BT / FragmentOps::FRAGMENT_ROWS;
+ constexpr ushort VALUE_FRAGMENTS = BV / FragmentOps::FRAGMENT_COLS;
+ using TileFragment = Fragment<float, TOKEN_FRAGMENTS, VALUE_FRAGMENTS, FragmentOps>;
+ using BlockMatrixFragment = OperandFragment<float, TOKEN_FRAGMENTS, TOKEN_FRAGMENTS, FragmentOps>;
+ using ValueTileFragment = OperandFragment<float, TOKEN_FRAGMENTS, VALUE_FRAGMENTS, FragmentOps>;
+ using PairMatrixFragment = OperandFragment<float, TOKEN_FRAGMENTS, 2 * TOKEN_FRAGMENTS, FragmentOps>;
+ using PairValueFragment = OperandFragment<float, 2 * TOKEN_FRAGMENTS, VALUE_FRAGMENTS, FragmentOps>;
+
+ static_assert(BV % FragmentOps::FRAGMENT_COLS == 0, "BV must be a multiple of the fragment column size");
+
+ const uint batch_value_head_idx = batch_idx * value_heads + value_head_idx;
+
+ const uint value_dim_base = value_tile_idx * BV;
+ const uint tile_value_cols = min(BV, head_v_dim - value_dim_base);
+ const uint num_blocks = div_ceil(tree_size, BT);
+ const int h0_slot = use_h0 ? h0_idx[batch_idx] : -1;
+
+ const uint value_token_stride = value_heads * head_v_dim;
+ const uint scalar_token_stride = value_heads;
+
+ const device float* kh0_head_tile =
+ kh0 + (batch_idx * tree_size * value_heads + value_head_idx) * head_v_dim + value_dim_base;
+ const device T* value_head_tile =
+ v + (batch_idx * tree_size * value_heads + value_head_idx) * head_v_dim + value_dim_base;
+ const device float* prefix_head = prefix + batch_idx * tree_size * value_heads + value_head_idx;
+ const device float* beta_head = beta + batch_idx * tree_size * value_heads + value_head_idx;
+ const uint num_col_pairs = div_ceil(num_blocks, 2u);
+ const device float* a_blocks = a_packed + batch_value_head_idx * num_blocks * num_col_pairs * (BT * 2 * BT);
+ const device float* a_inv_blocks = a_inv + batch_value_head_idx * num_blocks * (BT * BT);
+ device float* u_head_tile = u + batch_value_head_idx * tree_size * head_v_dim + value_dim_base;
+
+ for (uint block_idx = 0; block_idx < num_blocks; ++block_idx) {
+ const uint row_base = block_idx * BT;
+ const uint tile_rows = min(BT, tree_size - row_base);
+
+ TileFragment acc;
+
+ if (h0_slot >= 0) {
+ const device float* kh0_block = kh0_head_tile + row_base * value_token_stride;
+ acc.load_maybe_bounded(
+ lane_idx,
+ kh0_block,
+ value_token_stride,
+ tile_rows == BT && tile_value_cols == BV,
+ tile_rows,
+ tile_value_cols
+ );
+ } else {
+ acc.clear();
+ }
+
+ // prefix/beta/exp are per-row: one lane computes them, consumers read via simd_shuffle.
+ float lane_beta = 0.0f;
+ float lane_decay = 0.0f;
+ if (lane_idx < tile_rows) {
+ const uint token_idx = row_base + lane_idx;
+ lane_beta = beta_head[token_idx * scalar_token_stride];
+ lane_decay = exp(prefix_head[token_idx * scalar_token_stride]);
+ }
+
+ TileFragment v_frag;
+ const device T* v_block = value_head_tile + row_base * value_token_stride;
+ v_frag.load_maybe_bounded(
+ lane_idx,
+ v_block,
+ value_token_stride,
+ tile_rows == BT && tile_value_cols == BV,
+ tile_rows,
+ tile_value_cols
+ );
+
+ TileFragment::zip_for_each_coord(
+ lane_idx,
+ [&](ushort local_row_idx, ushort, thread float& acc_value, thread float& v_value) {
+ const float beta_row = simd_shuffle(lane_beta, local_row_idx);
+ const float decay_row = simd_shuffle(lane_decay, local_row_idx);
+ acc_value = beta_row * (v_value - decay_row * acc_value);
+ },
+ acc,
+ v_frag
+ );
+
+ const uint num_full_pairs = block_idx / 2;
+ for (uint pair_idx = 0; pair_idx < num_full_pairs; ++pair_idx) {
+ PairMatrixFragment a_frag;
+ PairValueFragment u_prev_frag;
+
+ const device float* a_pair = a_blocks + (block_idx * num_col_pairs + pair_idx) * (BT * 2 * BT);
+ const device float* u_prev_block = u_head_tile + pair_idx * 2 * BT * head_v_dim;
+ const bool full = tile_rows == BT && tile_value_cols == BV;
+ a_frag.load_maybe_bounded(lane_idx, a_pair, 2 * BT, full, tile_rows, 2 * BT);
+ u_prev_frag.load_maybe_bounded(lane_idx, u_prev_block, head_v_dim, full, 2 * BT, tile_value_cols);
+ a_frag.map([](float value) { return -value; });
+ fragment_mma(acc, a_frag, u_prev_frag);
+ }
+
+ for (uint prev_block_idx = num_full_pairs * 2; prev_block_idx < block_idx; ++prev_block_idx) {
+ const uint prev_row_base = prev_block_idx * BT;
+ BlockMatrixFragment a_frag;
+ ValueTileFragment u_prev_frag;
+
+ const device float* a_block =
+ a_blocks + (block_idx * num_col_pairs + prev_block_idx / 2) * (BT * 2 * BT) + (prev_block_idx % 2) * BT;
+ a_frag.load_from(lane_idx, fragment_source(a_block, 2 * BT).bounded(tile_rows, BT));
+ const device float* u_prev_block = u_head_tile + prev_row_base * head_v_dim;
+ u_prev_frag.load_from(lane_idx, fragment_source(u_prev_block, head_v_dim).bounded(BT, tile_value_cols));
+ a_frag.map([](float value) { return -value; });
+ fragment_mma(acc, a_frag, u_prev_frag);
+ }
+
+ BlockMatrixFragment inv_frag;
+ TileFragment solved;
+ solved.clear();
+
+ const device float* inv_block = a_inv_blocks + block_idx * (BT * BT);
+ inv_frag.load_from(lane_idx, fragment_source(inv_block, BT).bounded(tile_rows, tile_rows));
+ fragment_mma(solved, inv_frag, acc);
+ solved.store_safe(lane_idx, u_head_tile + row_base * head_v_dim, head_v_dim, short2(tile_value_cols, tile_rows));
+
+ // The threadgroup is a single simdgroup, so the block-serial U dependency
+ // only needs a simdgroup-scoped device-memory fence.
+ simdgroup_barrier(mem_flags::mem_device);
+ }
+}
diff --git a/crates/backend-uzu/src/backends/metal/kernel/gdn_tree_verify/tree_update_solve_dispatch_helper.rs b/crates/backend-uzu/src/backends/metal/kernel/gdn_tree_verify/tree_update_solve_dispatch_helper.rs
new file mode 100644
index 000000000..3a860531d
--- /dev/null
+++ b/crates/backend-uzu/src/backends/metal/kernel/gdn_tree_verify/tree_update_solve_dispatch_helper.rs
@@ -0,0 +1,55 @@
+#![allow(dead_code)]
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(crate) struct TreeUpdateSolveVariant {
+ pub use_mxu: bool,
+ pub bv: u32,
+}
+
+/// Fastest TreeUpdateSolve variant per device + shape, from the 9-chip fleet sweep
+/// (raw table in .claude/plans/solve_u_kernel_optimization.md). The kernel is a
+/// latency-bound serial recurrence at B=1 small-T, where the narrower BV16 wins on
+/// occupancy; the tree size at which the wider BV32 takes over grows with GPU
+/// width. MXU chips switch to the matrix unit past that same B=1 small-T corner.
+pub(crate) fn tree_update_solve_variant(
+ supports_mxu: bool,
+ gpu_core_count: u32,
+ batch_size: u32,
+ tree_size: u32,
+) -> TreeUpdateSolveVariant {
+ if supports_mxu {
+ let small_corner = batch_size == 1 && tree_size <= 64;
+ return TreeUpdateSolveVariant {
+ use_mxu: !small_corner,
+ bv: if small_corner {
+ 16
+ } else {
+ 32
+ },
+ };
+ }
+ let bv16 = if gpu_core_count >= 30 {
+ batch_size == 1 || (batch_size <= 8 && tree_size <= 64)
+ } else {
+ let bv16_max_tree = if gpu_core_count >= 10 {
+ 128
+ } else if gpu_core_count >= 8 {
+ 33
+ } else {
+ 0
+ };
+ batch_size == 1 && tree_size <= bv16_max_tree
+ };
+ TreeUpdateSolveVariant {
+ use_mxu: false,
+ bv: if bv16 {
+ 16
+ } else {
+ 32
+ },
+ }
+}
+
+#[cfg(test)]
+#[path = "../../../../../tests/unit/backends/metal/tree_update_solve_dispatch_test.rs"]
+mod tests;
diff --git a/crates/backend-uzu/src/backends/metal/kernel/matmul/common/fragment.h b/crates/backend-uzu/src/backends/metal/kernel/matmul/common/fragment.h
index 860176bdb..e553d8ddc 100644
--- a/crates/backend-uzu/src/backends/metal/kernel/matmul/common/fragment.h
+++ b/crates/backend-uzu/src/backends/metal/kernel/matmul/common/fragment.h
@@ -289,6 +289,42 @@ struct Fragment {
);
}
+ // Single-line load. `bounded` = true when the tile lies fully in the buffer, so
+ // the load takes the fast path with no per-element clamping; false clamps to
+ // (row_bound, col_bound).
+ template <class Ptr>
+ METAL_FUNC void load_maybe_bounded(
+ const ushort simd_lane_id,
+ Ptr base,
+ int row_stride,
+ bool bounded,
+ short row_bound,
+ short col_bound
+ ) thread {
+ FragmentSource<Ptr> src = fragment_source(base, row_stride);
+ if (!bounded) {
+ src = src.bounded(row_bound, col_bound);
+ }
+ load_from(simd_lane_id, src);
+ }
+
+ // Single-line store mirroring `load`: `bounded` = true stores the full tile;
+ // false clamps to `tile_dimensions`.
+ template <class Ptr>
+ METAL_FUNC void store_maybe_bounded(
+ const ushort simd_lane_id,
+ Ptr destination,
+ const int leading_dimension,
+ bool bounded,
+ const short2 tile_dimensions
+ ) thread {
+ if (!bounded) {
+ store_safe(simd_lane_id, destination, leading_dimension, tile_dimensions);
+ } else {
+ store(simd_lane_id, destination, leading_dimension);
+ }
+ }
+
private:
METAL_CONST bool LOAD = true;
METAL_CONST bool STORE = false;
diff --git a/crates/backend-uzu/src/backends/metal/kernel/mod.rs b/crates/backend-uzu/src/backends/metal/kernel/mod.rs
index 774f84df0..1ea726cc4 100644
--- a/crates/backend-uzu/src/backends/metal/kernel/mod.rs
+++ b/crates/backend-uzu/src/backends/metal/kernel/mod.rs
@@ -9,6 +9,8 @@ use crate::backends::{
#[path = "gdn_tree_verify/build_tree_out_dispatch_helper.rs"]
mod build_tree_out_dispatch_helper;
pub mod matmul;
+#[path = "gdn_tree_verify/tree_update_solve_dispatch_helper.rs"]
+mod tree_update_solve_dispatch_helper;
pub const MTLB: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/default.metallib"));
diff --git a/crates/backend-uzu/tests/unit/backends/metal/tree_update_solve_dispatch_test.rs b/crates/backend-uzu/tests/unit/backends/metal/tree_update_solve_dispatch_test.rs
new file mode 100644
index 000000000..db98fffd7
--- /dev/null
+++ b/crates/backend-uzu/tests/unit/backends/metal/tree_update_solve_dispatch_test.rs
@@ -0,0 +1,35 @@
+use proc_macros::uzu_test;
+
+use super::tree_update_solve_variant;
+
+fn variant(
+ supports_mxu: bool,
+ cores: u32,
+ batch: u32,
+ tree: u32,
+) -> (bool, u32) {
+ let v = tree_update_solve_variant(supports_mxu, cores, batch, tree);
+ (v.use_mxu, v.bv)
+}
+
+#[uzu_test]
+fn tree_update_solve_dispatch_matches_fleet() {
+ // MXU chips (M5+): simdgroup BV16 only at the B=1 small-T corner, MXU BV32 else.
+ assert_eq!(variant(true, 40, 1, 64), (false, 16));
+ assert_eq!(variant(true, 40, 1, 128), (true, 32));
+ assert_eq!(variant(true, 40, 8, 256), (true, 32));
+
+ // Max/Ultra (M3/M4 Max, 40): BV16 across B=1 and B<=8 tiny trees, BV32 beyond.
+ assert_eq!(variant(false, 40, 1, 256), (false, 16));
+ assert_eq!(variant(false, 40, 8, 64), (false, 16));
+ assert_eq!(variant(false, 40, 8, 256), (false, 32));
+
+ // Mid (M2/M4/M4 Pro, 10-20): BV16 through B=1 T<=128.
+ assert_eq!(variant(false, 20, 1, 128), (false, 16));
+ assert_eq!(variant(false, 10, 1, 256), (false, 32));
+
+ // Narrow (M1, 8): BV16 only at the tiniest tree. Phone-class (A18, 5): never.
+ assert_eq!(variant(false, 8, 1, 33), (false, 16));
+ assert_eq!(variant(false, 8, 1, 64), (false, 32));
+ assert_eq!(variant(false, 5, 1, 33), (false, 32));
+}
diff --git a/crates/backend-uzu/unit/backends/common/kernel/mod.rs b/crates/backend-uzu/unit/backends/common/kernel/mod.rs
index c5090f69c..e3af1ea6f 100644
--- a/crates/backend-uzu/unit/backends/common/kernel/mod.rs
+++ b/crates/backend-uzu/unit/backends/common/kernel/mod.rs
@@ -3,8 +3,6 @@ mod attention;
mod delta_net_test;
mod embedding;
mod gated_act_mul_test;
-mod gram_bench;
-mod gram_test;
mod hadamard_transform_test;
mod kv_cache_update_test;
mod logit_soft_cap_test;
@@ -23,3 +21,7 @@ mod tensor_add_scale_test;
mod tensor_add_swap_test;
mod tensor_copy_test;
mod token_copy_test;
+mod tree_gram_bench;
+mod tree_gram_test;
+mod tree_update_solve_bench;
+mod tree_update_solve_test;
diff --git a/crates/backend-uzu/unit/backends/common/kernel/gram_bench.rs b/crates/backend-uzu/unit/backends/common/kernel/tree_gram_bench.rs
similarity index 58%
rename from crates/backend-uzu/unit/backends/common/kernel/gram_bench.rs
rename to crates/backend-uzu/unit/backends/common/kernel/tree_gram_bench.rs
index 03a95d760..ff5199ee9 100644
--- a/crates/backend-uzu/unit/backends/common/kernel/gram_bench.rs
+++ b/crates/backend-uzu/unit/backends/common/kernel/tree_gram_bench.rs
@@ -1,6 +1,6 @@
#![cfg(metal_backend)]
-use std::{env, mem::size_of, time::Duration};
+use std::{mem::size_of, time::Duration};
use criterion::{BenchmarkId, Criterion};
use half::bf16;
@@ -8,7 +8,7 @@ use proc_macros::uzu_bench;
use crate::{
backends::{
- common::{Allocation, Backend, Context, Encoder, Kernels, kernel::BuildTreeGramKernel},
+ common::{Allocation, Backend, Context, Kernels, kernel::BuildTreeGramKernel},
metal::Metal,
},
data_type::DataType,
@@ -22,6 +22,7 @@ use crate::{
const K_HEADS: usize = 16;
const VALUE_HEADS: usize = 48;
const HEAD_K_DIM: usize = 128;
+const HEAD_V_DIM: usize = 128;
const TREE_SIZES: &[usize] = &[33, 49, 64, 128, 256, 512];
const BATCH_SIZES: &[usize] = &[1, 2, 4, 8];
@@ -31,9 +32,12 @@ struct TreeGramBuffers {
trie: Allocation<Metal>,
prefix: Allocation<Metal>,
beta: Allocation<Metal>,
- a_mat: Allocation<Metal>,
+ h0: Allocation<Metal>,
+ h0_idx: Allocation<Metal>,
+ a_packed: Allocation<Metal>,
qkd: Allocation<Metal>,
- ainv: Allocation<Metal>,
+ a_inv: Allocation<Metal>,
+ kh0: Allocation<Metal>,
}
fn reranker_like_trie(
@@ -86,15 +90,22 @@ fn make_buffers(
tree_size: usize,
) -> (TreeGramBuffers, f32) {
let qk_len = batch_size * tree_size * K_HEADS * HEAD_K_DIM;
- let head_len = batch_size * tree_size * VALUE_HEADS;
+ let scalar_len = batch_size * tree_size * VALUE_HEADS;
let out_len = batch_size * VALUE_HEADS * tree_size * tree_size;
+ let num_blocks = tree_size.div_ceil(16);
+ let a_len = batch_size * VALUE_HEADS * num_blocks * num_blocks.div_ceil(2) * 16 * 32;
+ let a_inv_len = batch_size * VALUE_HEADS * num_blocks * 16 * 16;
+ let h0_len = batch_size * VALUE_HEADS * HEAD_V_DIM * HEAD_K_DIM;
+ let kh0_len = batch_size * tree_size * VALUE_HEADS * HEAD_V_DIM;
let trie = reranker_like_trie(batch_size, tree_size);
let q = (0..qk_len).map(|i| bf16::from_f32(((i as f32 * 0.017).sin() * 0.2) + 0.01)).collect::<Vec<_>>();
let k = (0..qk_len).map(|i| bf16::from_f32(((i as f32 * 0.019).cos() * 0.18) - 0.02)).collect::<Vec<_>>();
- let prefix = (0..head_len)
+ let prefix = (0..scalar_len)
.map(|i| -((i % tree_size) as f32) * 0.01 - ((i % VALUE_HEADS) as f32) * 0.003)
.collect::<Vec<_>>();
- let beta = (0..head_len).map(|i| 0.25 + ((i as f32 * 0.013).sin() + 1.0) * 0.2).collect::<Vec<_>>();
+ let beta = (0..scalar_len).map(|i| 0.25 + ((i as f32 * 0.013).sin() + 1.0) * 0.2).collect::<Vec<_>>();
+ let h0 = (0..h0_len).map(|i| bf16::from_f32(((i as f32 * 0.007).sin() * 0.05) - 0.01)).collect::<Vec<_>>();
+ let h0_idx = (0..batch_size).map(|i| i as i32).collect::<Vec<_>>();
let scale = (HEAD_K_DIM as f32).sqrt().recip();
(
TreeGramBuffers {
@@ -103,9 +114,12 @@ fn make_buffers(
trie: alloc_allocation_with_data::<Metal, u32>(context, &trie),
prefix: alloc_allocation_with_data::<Metal, f32>(context, &prefix),
beta: alloc_allocation_with_data::<Metal, f32>(context, &beta),
- a_mat: alloc_allocation::<Metal, f32>(context, out_len),
+ h0: alloc_allocation_with_data::<Metal, bf16>(context, &h0),
+ h0_idx: alloc_allocation_with_data::<Metal, i32>(context, &h0_idx),
+ a_packed: alloc_allocation::<Metal, f32>(context, a_len),
qkd: alloc_allocation::<Metal, f32>(context, out_len),
- ainv: alloc_allocation::<Metal, f32>(context, out_len),
+ a_inv: alloc_allocation::<Metal, f32>(context, a_inv_len),
+ kh0: alloc_allocation::<Metal, f32>(context, kh0_len),
},
scale,
)
@@ -116,18 +130,23 @@ fn buffers_bytes(
tree_size: usize,
) -> usize {
let qk_len = batch_size * tree_size * K_HEADS * HEAD_K_DIM;
- let head_len = batch_size * tree_size * VALUE_HEADS;
+ let scalar_len = batch_size * tree_size * VALUE_HEADS;
let out_len = batch_size * VALUE_HEADS * tree_size * tree_size;
- qk_len * size_of::<bf16>() * 2
+ let num_blocks = tree_size.div_ceil(16);
+ let a_len = batch_size * VALUE_HEADS * num_blocks * num_blocks.div_ceil(2) * 16 * 32;
+ let a_inv_len = batch_size * VALUE_HEADS * num_blocks * 16 * 16;
+ let h0_len = batch_size * VALUE_HEADS * HEAD_V_DIM * HEAD_K_DIM;
+ let kh0_len = batch_size * tree_size * VALUE_HEADS * HEAD_V_DIM;
+ (qk_len * 2 + h0_len) * size_of::<bf16>()
+ batch_size * tree_size * 3 * size_of::<u32>()
- + head_len * size_of::<f32>() * 2
- + out_len * size_of::<f32>() * 3
+ + scalar_len * size_of::<f32>() * 2
+ + (out_len + a_len + a_inv_len + kh0_len) * size_of::<f32>()
+ + batch_size * size_of::<i32>()
}
#[uzu_bench]
fn bench_build_tree_gram(c: &mut Criterion) {
let context = <Metal as Backend>::Context::new().expect("metal context");
- let cold_buffers = env::var("UZU_GRAM_COLD_BUFFERS").is_ok();
let kernel_paths = if context.supports_mxu() {
&[("Simdgroup", false), ("MXU", true)][..]
} else {
@@ -136,7 +155,7 @@ fn bench_build_tree_gram(c: &mut Criterion) {
for &(kernel_path, use_mxu) in kernel_paths {
let mut group = c.benchmark_group(format!("Metal/Kernel/GDNTreeVerify/BuildTreeGram/{kernel_path}"));
- group.sample_size(10).warm_up_time(Duration::from_millis(100)).measurement_time(Duration::from_millis(500));
+ group.sample_size(20).warm_up_time(Duration::from_millis(500)).measurement_time(Duration::from_secs(2));
for &batch_size in BATCH_SIZES {
for &tree_size in TREE_SIZES {
@@ -144,6 +163,7 @@ fn bench_build_tree_gram(c: &mut Criterion) {
&context,
DataType::BF16,
use_mxu,
+ true,
)
.expect("BuildTreeGramKernel");
let scale = (HEAD_K_DIM as f32).sqrt().recip();
@@ -153,44 +173,35 @@ fn bench_build_tree_gram(c: &mut Criterion) {
"B{batch_size}_T{tree_size}_Hg{K_HEADS}_HV{VALUE_HEADS}_K{HEAD_K_DIM}"
));
- let encode = |buffers: &mut TreeGramBuffers, encoder: &mut Encoder<Metal>| {
- kernel.encode(
- &buffers.q,
- &buffers.k,
- &buffers.trie,
- &buffers.prefix,
- &buffers.beta,
- &mut buffers.a_mat,
- &mut buffers.qkd,
- &mut buffers.ainv,
- scale,
- batch_size as u32,
- tree_size as u32,
- K_HEADS as u32,
- VALUE_HEADS as u32,
- HEAD_K_DIM as u32,
- encoder,
- );
- };
-
- if cold_buffers {
- let mut buffers = ColdPool::new(buffers_bytes(batch_size, tree_size), || {
- make_buffers(&context, batch_size, tree_size).0
- });
- group.bench_function(benchmark_id, |bencher| {
- iter_encode_loop_named::<Metal, _>(context.as_ref(), bencher, &benchmark_path, |encoder| {
- let buffers = buffers.next_mut();
- encode(buffers, encoder);
- });
- });
- } else {
- let (mut buffers, _) = make_buffers(&context, batch_size, tree_size);
- group.bench_function(benchmark_id, |bencher| {
- iter_encode_loop_named::<Metal, _>(context.as_ref(), bencher, &benchmark_path, |encoder| {
- encode(&mut buffers, encoder);
- });
+ let mut buffers = ColdPool::new(buffers_bytes(batch_size, tree_size), || {
+ make_buffers(&context, batch_size, tree_size).0
+ });
+ group.bench_function(benchmark_id, |bencher| {
+ iter_encode_loop_named::<Metal, _>(context.as_ref(), bencher, &benchmark_path, |encoder| {
+ let buffers = buffers.next_mut();
+ kernel.encode(
+ &buffers.q,
+ &buffers.k,
+ &buffers.trie,
+ &buffers.prefix,
+ &buffers.beta,
+ Some(&buffers.h0),
+ Some(&buffers.h0_idx),
+ &mut buffers.a_packed,
+ &mut buffers.qkd,
+ &mut buffers.a_inv,
+ Some(&mut buffers.kh0),
+ scale,
+ batch_size as u32,
+ tree_size as u32,
+ K_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/gram_test.rs b/crates/backend-uzu/unit/backends/common/kernel/tree_gram_test.rs
similarity index 60%
rename from crates/backend-uzu/unit/backends/common/kernel/gram_test.rs
rename to crates/backend-uzu/unit/backends/common/kernel/tree_gram_test.rs
index 98ff730f3..f492b49c2 100644
--- a/crates/backend-uzu/unit/backends/common/kernel/gram_test.rs
+++ b/crates/backend-uzu/unit/backends/common/kernel/tree_gram_test.rs
@@ -17,6 +17,8 @@ const BATCH_SIZE: usize = 2;
const K_HEADS: usize = 2;
const VALUE_HEADS: usize = 6;
const HEAD_K_DIM: usize = 128;
+// 80 = two full 32-wide kh0 dv chunks plus a ragged 16-wide one.
+const HEAD_V_DIM: usize = 80;
fn get_output<B: Backend>(
q: &[f32],
@@ -24,23 +26,36 @@ fn get_output<B: Backend>(
trie: &[u32],
prefix: &[f32],
beta: &[f32],
+ h0: &[f32],
+ h0_idx: &[i32],
tree_size: usize,
scale: f32,
use_mxu: bool,
-) -> (Vec<f32>, Vec<f32>, Vec<f32>) {
+) -> (Vec<f32>, Vec<f32>, Vec<f32>, Vec<f32>) {
let context = B::Context::new().expect("Failed to create Context");
- let kernel = <<B as Backend>::Kernels as Kernels>::BuildTreeGramKernel::new(&context, DataType::F32, use_mxu)
+ let kernel = <<B as Backend>::Kernels as Kernels>::BuildTreeGramKernel::new(&context, DataType::F32, use_mxu, true)
.expect("Failed to create BuildTreeGramKernel");
let output_len = BATCH_SIZE * VALUE_HEADS * tree_size * tree_size;
+ let num_blocks = tree_size.div_ceil(16);
+ let a_len = BATCH_SIZE * VALUE_HEADS * num_blocks * num_blocks.div_ceil(2) * 16 * 32;
+ let a_inv_len = BATCH_SIZE * VALUE_HEADS * num_blocks * 16 * 16;
+ let kh0_len = BATCH_SIZE * tree_size * VALUE_HEADS * HEAD_V_DIM;
let q = alloc_allocation_with_data::<B, f32>(&context, q);
let k = alloc_allocation_with_data::<B, f32>(&context, k);
let trie = alloc_allocation_with_data::<B, u32>(&context, trie);
let prefix = alloc_allocation_with_data::<B, f32>(&context, prefix);
let beta = alloc_allocation_with_data::<B, f32>(&context, beta);
- let mut a_mat = alloc_allocation::<B, f32>(&context, output_len);
+ let h0 = alloc_allocation_with_data::<B, f32>(&context, h0);
+ let h0_idx = alloc_allocation_with_data::<B, i32>(&context, h0_idx);
+ // The GPU only writes packed-A tiles touching the block lower triangle;
+ // zero-init so CPU and GPU buffers stay comparable elsewhere.
+ let mut a_packed = alloc_allocation_with_data::<B, f32>(&context, &vec![0.0f32; a_len]);
let mut qkd = alloc_allocation::<B, f32>(&context, output_len);
- let mut ainv = alloc_allocation::<B, f32>(&context, output_len);
+ let mut a_inv = alloc_allocation::<B, f32>(&context, a_inv_len);
+ // kh0 is only written for batches with h0_idx >= 0; zero-init so CPU and GPU
+ // outputs stay comparable on the skipped batch.
+ let mut kh0 = alloc_allocation_with_data::<B, f32>(&context, &vec![0.0f32; kh0_len]);
let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");
kernel.encode(
@@ -49,20 +64,24 @@ fn get_output<B: Backend>(
&trie,
&prefix,
&beta,
- &mut a_mat,
+ Some(&h0),
+ Some(&h0_idx),
+ &mut a_packed,
&mut qkd,
- &mut ainv,
+ &mut a_inv,
+ Some(&mut kh0),
scale,
BATCH_SIZE as u32,
tree_size as u32,
K_HEADS as u32,
VALUE_HEADS as u32,
HEAD_K_DIM as u32,
+ HEAD_V_DIM as u32,
&mut encoder,
);
encoder.end_encoding().submit().wait_until_completed().unwrap();
- (allocation_to_vec(&a_mat), allocation_to_vec(&qkd), allocation_to_vec(&ainv))
+ (allocation_to_vec(&a_packed), allocation_to_vec(&qkd), allocation_to_vec(&a_inv), allocation_to_vec(&kh0))
}
fn build_trie(tree_size: usize) -> Vec<u32> {
@@ -84,16 +103,20 @@ fn test_build_tree_gram_matches_cpu() {
for tree_size in [17, 64, 128] {
let q_len = BATCH_SIZE * tree_size * K_HEADS * HEAD_K_DIM;
- let kv_len = BATCH_SIZE * tree_size * VALUE_HEADS;
+ let scalar_len = BATCH_SIZE * tree_size * VALUE_HEADS;
let trie = build_trie(tree_size);
let q = (0..q_len).map(|i| ((i as f32 * 0.017).sin() * 0.2) + 0.01).collect::<Vec<_>>();
let k = (0..q_len).map(|i| ((i as f32 * 0.019).cos() * 0.18) - 0.02).collect::<Vec<_>>();
- let prefix = (0..kv_len)
+ let prefix = (0..scalar_len)
.map(|i| -((i % tree_size) as f32) * 0.01 - ((i % VALUE_HEADS) as f32) * 0.003)
.collect::<Vec<_>>();
- let beta = (0..kv_len).map(|i| 0.25 + ((i as f32 * 0.013).sin() + 1.0) * 0.2).collect::<Vec<_>>();
+ let beta = (0..scalar_len).map(|i| 0.25 + ((i as f32 * 0.013).sin() + 1.0) * 0.2).collect::<Vec<_>>();
+ let h0_len = BATCH_SIZE * VALUE_HEADS * HEAD_V_DIM * HEAD_K_DIM;
+ let h0 = (0..h0_len).map(|i| ((i as f32 * 0.007).sin() * 0.05) - 0.01).collect::<Vec<_>>();
+ // Batch 1 has no initial state: covers the kh0-skip path.
+ let h0_idx: Vec<i32> = vec![0, -1];
- let expected = get_output::<Cpu>(&q, &k, &trie, &prefix, &beta, tree_size, scale, false);
+ let expected = get_output::<Cpu>(&q, &k, &trie, &prefix, &beta, &h0, &h0_idx, tree_size, scale, false);
for_each_non_cpu_backend!(|B| {
let context = <<B as Backend>::Context as Context>::new().expect("Failed to create Context");
@@ -104,34 +127,20 @@ fn test_build_tree_gram_matches_cpu() {
};
for &use_mxu in paths {
- let actual = get_output::<B>(&q, &k, &trie, &prefix, &beta, tree_size, scale, use_mxu);
+ let actual = get_output::<B>(&q, &k, &trie, &prefix, &beta, &h0, &h0_idx, tree_size, scale, use_mxu);
let path = if use_mxu {
"mxu"
} else {
"simdgroup"
};
let msg = format!("backend {} {path} tree_size {tree_size}", std::any::type_name::<B>());
- assert_eq_float::<f32>(&expected.0, &actual.0, 5e-3, &format!("a_mat {msg}"));
+ assert_eq_float::<f32>(&expected.0, &actual.0, 5e-3, &format!("a_packed {msg}"));
assert_eq_float::<f32>(&expected.1, &actual.1, 5e-3, &format!("qkd {msg}"));
- for (expected_matrix, actual_matrix) in
- expected.2.chunks(tree_size * tree_size).zip(actual.2.chunks(tree_size * tree_size))
- {
- for block_start in (0..tree_size).step_by(16) {
- let block_end = (block_start + 16).min(tree_size);
- for i in block_start..block_end {
- for j in block_start..block_end {
- let idx = i * tree_size + j;
- let expected = expected_matrix[idx];
- let actual = actual_matrix[idx];
- assert!(
- (expected - actual).abs() < 1e-2,
- "ainv {msg}. Mismatch at matrix index {idx}: expected {expected}, got {actual}"
- );
- }
- }
- }
- }
+ // Ainv is compact [B * HV, ceil(T/16), 16, 16]; both CPU and GPU
+ // pad ragged blocks with identity, so compare the whole buffer.
+ assert_eq_float::<f32>(&expected.2, &actual.2, 1e-2, &format!("a_inv {msg}"));
+ assert_eq_float::<f32>(&expected.3, &actual.3, 5e-3, &format!("kh0 {msg}"));
}
});
}
diff --git a/crates/backend-uzu/unit/backends/common/kernel/tree_update_solve_bench.rs b/crates/backend-uzu/unit/backends/common/kernel/tree_update_solve_bench.rs
new file mode 100644
index 000000000..897d564fb
--- /dev/null
+++ b/crates/backend-uzu/unit/backends/common/kernel/tree_update_solve_bench.rs
@@ -0,0 +1,245 @@
+#![cfg(metal_backend)]
+
+use std::{mem::size_of, time::Duration};
+
+use criterion::{BenchmarkId, Criterion, Throughput};
+use half::bf16;
+use proc_macros::uzu_bench;
+
+use crate::{
+ backends::{
+ common::{Allocation, Backend, Context, Encoder, Kernels, kernel::TreeUpdateSolveKernel},
+ metal::Metal,
+ },
+ data_type::DataType,
+ tests::{
+ cold_pool::ColdPool,
+ helpers::{alloc_allocation, alloc_allocation_with_data},
+ matmul::iter_encode_loop_named,
+ },
+};
+
+const NUM_V_HEADS: usize = 48;
+const HEAD_V_DIM: usize = 128;
+const BT: usize = 16;
+const BVS: &[usize] = &[16, 32];
+const MXU_BVS: &[usize] = &[32];
+
+const BENCH_SHAPES: &[(usize, usize)] = &[
+ (1, 33),
+ (1, 49),
+ (1, 64),
+ (1, 128),
+ (1, 256),
+ (1, 512),
+ (2, 33),
+ (2, 49),
+ (2, 64),
+ (2, 128),
+ (2, 256),
+ (2, 512),
+ (4, 33),
+ (4, 49),
+ (4, 64),
+ (4, 128),
+ (4, 256),
+ (4, 512),
+ (8, 33),
+ (8, 49),
+ (8, 64),
+ (8, 128),
+ (8, 256),
+ (8, 512),
+];
+
+struct TreeUpdateSolveBuffers {
+ kh0: Allocation<Metal>,
+ v: Allocation<Metal>,
+ prefix: Allocation<Metal>,
+ beta: Allocation<Metal>,
+ a: Allocation<Metal>,
+ a_inv: Allocation<Metal>,
+ h0_idx: Allocation<Metal>,
+ u: Allocation<Metal>,
+}
+
+fn matrix_value(
+ batch_head_matrix_idx: usize,
+ row: usize,
+ col: usize,
+ tree_size: usize,
+) -> f32 {
+ if col < row {
+ ((batch_head_matrix_idx * tree_size * tree_size + row * tree_size + col) as f32 * 0.011).sin() * 0.01
+ } else {
+ 0.0
+ }
+}
+
+// Compact [B * HV, ceil(T/BT), BT, BT] diagonal blocks.
+fn inverse_value(
+ batch_head_matrix_idx: usize,
+ block: usize,
+ row: usize,
+ col: usize,
+ tree_size: usize,
+) -> f32 {
+ if row == col {
+ 1.0
+ } else if col < row {
+ -matrix_value(batch_head_matrix_idx, block * BT + row, block * BT + col, tree_size)
+ } else {
+ 0.0
+ }
+}
+
+fn make_buffers(
+ context: &<Metal as Backend>::Context,
+ batch_size: usize,
+ tree_size: usize,
+) -> TreeUpdateSolveBuffers {
+ let v_len = batch_size * tree_size * NUM_V_HEADS * HEAD_V_DIM;
+ let scalar_len = batch_size * tree_size * NUM_V_HEADS;
+ let num_blocks = tree_size.div_ceil(BT);
+ let num_col_pairs = num_blocks.div_ceil(2);
+ let a_len = batch_size * NUM_V_HEADS * num_blocks * num_col_pairs * BT * 2 * BT;
+ let u_len = batch_size * NUM_V_HEADS * tree_size * HEAD_V_DIM;
+
+ let kh0 = (0..v_len).map(|i| ((i as f32 * 0.019).sin() * 0.2) + 0.01).collect::<Vec<f32>>();
+ let v = (0..v_len).map(|i| bf16::from_f32(((i as f32 * 0.017).cos() * 0.18) - 0.02)).collect::<Vec<_>>();
+ let prefix = (0..scalar_len)
+ .map(|i| -((i % tree_size) as f32) * 0.01 - ((i % NUM_V_HEADS) as f32) * 0.003)
+ .collect::<Vec<_>>();
+ let beta = (0..scalar_len).map(|i| 0.25 + ((i as f32 * 0.013).sin() + 1.0) * 0.2).collect::<Vec<_>>();
+ // Packed [B * HV, NB, ceil(NB/2), BT, 2*BT] block-pair tiles.
+ let a_f32 = (0..a_len)
+ .map(|i| {
+ let local_col = i % (2 * BT);
+ let local_row = (i / (2 * BT)) % BT;
+ let pair = (i / (BT * 2 * BT)) % num_col_pairs;
+ let block = (i / (BT * 2 * BT * num_col_pairs)) % num_blocks;
+ let batch_head_matrix_idx = i / (BT * 2 * BT * num_col_pairs * num_blocks);
+ let row = block * BT + local_row;
+ let col = pair * 2 * BT + local_col;
+ if col < tree_size && row < tree_size && col / BT < block {
+ matrix_value(batch_head_matrix_idx, row, col, tree_size)
+ } else {
+ 0.0
+ }
+ })
+ .collect::<Vec<_>>();
+ let a = alloc_allocation_with_data::<Metal, f32>(context, &a_f32);
+ let inv_len = batch_size * NUM_V_HEADS * tree_size.div_ceil(BT) * BT * BT;
+ let a_inv = (0..inv_len)
+ .map(|i| {
+ let col = i % BT;
+ let row = (i / BT) % BT;
+ let block = (i / (BT * BT)) % tree_size.div_ceil(BT);
+ let batch_head_matrix_idx = i / (BT * BT * tree_size.div_ceil(BT));
+ inverse_value(batch_head_matrix_idx, block, row, col, tree_size)
+ })
+ .collect::<Vec<_>>();
+ let h0_idx = (0..batch_size).map(|i| i as i32).collect::<Vec<_>>();
+
+ TreeUpdateSolveBuffers {
+ kh0: alloc_allocation_with_data::<Metal, f32>(context, &kh0),
+ v: alloc_allocation_with_data::<Metal, bf16>(context, &v),
+ prefix: alloc_allocation_with_data::<Metal, f32>(context, &prefix),
+ beta: alloc_allocation_with_data::<Metal, f32>(context, &beta),
+ a,
+ a_inv: alloc_allocation_with_data::<Metal, f32>(context, &a_inv),
+ h0_idx: alloc_allocation_with_data::<Metal, i32>(context, &h0_idx),
+ u: alloc_allocation::<Metal, f32>(context, u_len),
+ }
+}
+
+fn buffers_bytes(
+ batch_size: usize,
+ tree_size: usize,
+) -> usize {
+ let v_len = batch_size * tree_size * NUM_V_HEADS * HEAD_V_DIM;
+ let scalar_len = batch_size * tree_size * NUM_V_HEADS;
+ let num_blocks = tree_size.div_ceil(BT);
+ let a_len = batch_size * NUM_V_HEADS * num_blocks * num_blocks.div_ceil(2) * BT * 2 * BT;
+ let u_len = batch_size * NUM_V_HEADS * tree_size * HEAD_V_DIM;
+
+ let inv_len = batch_size * NUM_V_HEADS * num_blocks * BT * BT;
+ v_len * size_of::<bf16>()
+ + (scalar_len * 2 + a_len + inv_len + u_len + v_len) * size_of::<f32>()
+ + batch_size * size_of::<i32>()
+}
+
+#[uzu_bench]
+fn bench_tree_update_solve(c: &mut Criterion) {
+ let context = <Metal as Backend>::Context::new().expect("metal context");
+ let kernel_paths = if context.supports_mxu() {
+ &[("Simdgroup", false, BVS), ("MXU", true, MXU_BVS)][..]
+ } else {
+ &[("Simdgroup", false, BVS)][..]
+ };
+
+ for &(kernel_path, use_mxu, bvs) in kernel_paths {
+ for &bv in bvs {
+ let kernel = <<Metal as Backend>::Kernels as Kernels>::TreeUpdateSolveKernel::new(
+ &context,
+ DataType::BF16,
+ bv as u32,
+ use_mxu,
+ true,
+ )
+ .expect("TreeUpdateSolveKernel");
+
+ let mut group =
+ c.benchmark_group(format!("Metal/Kernel/GDNTreeVerify/TreeUpdateSolve/{kernel_path}/BV{bv}"));
+ // 500ms warmup ramps GPU clocks before measuring (µs-scale benches never
+ // ramp otherwise and medians become run-composition artifacts).
+ group.sample_size(20).warm_up_time(Duration::from_millis(500)).measurement_time(Duration::from_secs(2));
+
+ for &(batch_size, tree_size) in BENCH_SHAPES {
+ let benchmark_path = format!(
+ "Metal/Kernel/GDNTreeVerify/TreeUpdateSolve/{kernel_path}/BV{bv}/B{batch_size}_T{tree_size}"
+ );
+ let benchmark_id = BenchmarkId::from_parameter(format!(
+ "B{batch_size}_T{tree_size}_HV{NUM_V_HEADS}_V{HEAD_V_DIM}_BV{bv}"
+ ));
+ let mut buffers = ColdPool::new(buffers_bytes(batch_size, tree_size), || {
+ make_buffers(&context, batch_size, tree_size)
+ });
+
+ group.throughput(Throughput::Elements((batch_size * tree_size * NUM_V_HEADS * HEAD_V_DIM) as u64));
+ group.bench_function(benchmark_id, |bencher| {
+ iter_encode_loop_named::<Metal, _>(context.as_ref(), bencher, &benchmark_path, |encoder| {
+ let buffers = buffers.next_mut();
+ encode(&kernel, buffers, batch_size, tree_size, encoder);
+ });
+ });
+ }
+ group.finish();
+ test_runner::metrics::wait_gpu_cooldown();
+ }
+ }
+}
+
+fn encode(
+ kernel: &impl TreeUpdateSolveKernel<Backend = Metal>,
+ buffers: &mut TreeUpdateSolveBuffers,
+ batch_size: usize,
+ tree_size: usize,
+ encoder: &mut Encoder<Metal>,
+) {
+ kernel.encode(
+ Some(&buffers.kh0),
+ &buffers.v,
+ &buffers.prefix,
+ &buffers.beta,
+ &buffers.a,
+ &buffers.a_inv,
+ Some(&buffers.h0_idx),
+ &mut buffers.u,
+ batch_size as u32,
+ tree_size as u32,
+ NUM_V_HEADS as u32,
+ HEAD_V_DIM as u32,
+ encoder,
+ );
+}
diff --git a/crates/backend-uzu/unit/backends/common/kernel/tree_update_solve_test.rs b/crates/backend-uzu/unit/backends/common/kernel/tree_update_solve_test.rs
new file mode 100644
index 000000000..781ebd6f8
--- /dev/null
+++ b/crates/backend-uzu/unit/backends/common/kernel/tree_update_solve_test.rs
@@ -0,0 +1,219 @@
+use half::bf16;
+use proc_macros::uzu_test;
+use test_runner::for_each_non_cpu_backend;
+
+use crate::{
+ array::ArrayElement,
+ backends::{
+ common::{Backend, Context, Encoder, Kernels, kernel::TreeUpdateSolveKernel},
+ cpu::Cpu,
+ },
+ data_type::DataType,
+ tests::{
+ assert::assert_eq_float,
+ helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec},
+ },
+};
+
+const BT: u32 = 16;
+const BVS: &[u32] = &[16, 32];
+// MXU needs an even number of column fragments or MPP row pairing; BV16 (a single
+// 16x16 fragment) is not supported.
+const MXU_BVS: &[u32] = &[32];
+
+#[derive(Clone, Copy)]
+struct SolveCase {
+ name: &'static str,
+ batch_size: u32,
+ tree_size: u32,
+ num_v_heads: u32,
+ head_v_dim: u32,
+}
+
+const CASES: &[SolveCase] = &[
+ SolveCase {
+ name: "single_full_block",
+ batch_size: 1,
+ tree_size: 16,
+ num_v_heads: 1,
+ head_v_dim: 16,
+ },
+ SolveCase {
+ name: "ragged_second_block",
+ batch_size: 1,
+ tree_size: 17,
+ num_v_heads: 2,
+ head_v_dim: 20,
+ },
+ SolveCase {
+ name: "common_small_tree",
+ batch_size: 1,
+ tree_size: 33,
+ num_v_heads: 4,
+ head_v_dim: 128,
+ },
+ SolveCase {
+ name: "ragged_four_blocks",
+ batch_size: 1,
+ tree_size: 49,
+ num_v_heads: 4,
+ head_v_dim: 128,
+ },
+ SolveCase {
+ // NB=7: exercises pair_idx >= 1, tail blocks >= 4, and a ragged final block.
+ name: "ragged_seven_blocks",
+ batch_size: 1,
+ tree_size: 97,
+ num_v_heads: 2,
+ head_v_dim: 64,
+ },
+ SolveCase {
+ // NB=16: the large-tree regime this kernel exists for; num_full_pairs
+ // reaches 7, so the deep packed-pair accumulation is exercised.
+ name: "large_tree",
+ batch_size: 1,
+ tree_size: 256,
+ num_v_heads: 2,
+ head_v_dim: 64,
+ },
+ SolveCase {
+ name: "batched_optional_h0",
+ batch_size: 2,
+ tree_size: 16,
+ num_v_heads: 2,
+ head_v_dim: 16,
+ },
+];
+
+fn run_case<B: Backend, T: ArrayElement + Copy>(
+ case: SolveCase,
+ bv: u32,
+ use_mxu: bool,
+ use_h0: bool,
+ data_type: DataType,
+ cast: impl Fn(f32) -> T + Copy,
+) -> Vec<f32> {
+ let context = B::Context::new().expect("context");
+ let kernel =
+ <<B as Backend>::Kernels as Kernels>::TreeUpdateSolveKernel::new(&context, data_type, bv, use_mxu, use_h0)
+ .expect("kernel");
+
+ let batch_size = case.batch_size as usize;
+ let tree_size = case.tree_size as usize;
+ let num_v_heads = case.num_v_heads as usize;
+ let head_v_dim = case.head_v_dim as usize;
+
+ let v_len = batch_size * tree_size * num_v_heads * head_v_dim;
+ let scalar_len = batch_size * tree_size * num_v_heads;
+ let num_blocks = tree_size.div_ceil(BT as usize);
+ let num_col_pairs = num_blocks.div_ceil(2);
+ let a_len = batch_size * num_v_heads * num_blocks * num_col_pairs * (BT * 2 * BT) as usize;
+ let inv_len = batch_size * num_v_heads * num_blocks * (BT * BT) as usize;
+ let u_len = batch_size * num_v_heads * tree_size * head_v_dim;
+
+ let kh0 = (0..v_len).map(|i| ((i as f32 * 0.019).sin() * 0.2) + 0.01).collect::<Vec<f32>>();
+ let v = (0..v_len).map(|i| cast(((i as f32 * 0.017).cos() * 0.18) - 0.02)).collect::<Vec<_>>();
+ let prefix = (0..scalar_len)
+ .map(|i| -((i % tree_size) as f32) * 0.01 - ((i % num_v_heads) as f32) * 0.003)
+ .collect::<Vec<_>>();
+ let beta = (0..scalar_len).map(|i| 0.25 + ((i as f32 * 0.013).sin() + 1.0) * 0.2).collect::<Vec<_>>();
+ // Packed [B * HV, NB, ceil(NB/2), BT, 2*BT] block-pair tiles; strictly-lower
+ // blocks get values, everything else zero (the kernel never reads it).
+ let a_f32 = (0..a_len)
+ .map(|i| {
+ let local_col = i % (2 * BT as usize);
+ let local_row = (i / (2 * BT as usize)) % BT as usize;
+ let pair = (i / (BT * 2 * BT) as usize) % num_col_pairs;
+ let block = (i / ((BT * 2 * BT) as usize * num_col_pairs)) % num_blocks;
+ let row = block * BT as usize + local_row;
+ let col = pair * 2 * BT as usize + local_col;
+ if col < tree_size && row < tree_size && col / (BT as usize) < block {
+ // ~0.05 per entry: with the dense lower-triangle fill this puts the
+ // per-row A magnitude near the real l2-normed-key / softplus-decay regime.
+ ((i as f32 * 0.011).sin()) * 0.05
+ } else {
+ 0.0
+ }
+ })
+ .collect::<Vec<_>>();
+ // Compact [B * HV, ceil(T/BT), BT, BT] diagonal blocks.
+ let a_inv = (0..inv_len)
+ .map(|i| {
+ let col = i % BT as usize;
+ let row = (i / BT as usize) % BT as usize;
+ if row == col {
+ 1.0
+ } else if col < row {
+ -((i as f32 * 0.011).sin()) * 0.05
+ } else {
+ 0.0
+ }
+ })
+ .collect::<Vec<_>>();
+ let h0_idx = if case.name == "batched_optional_h0" {
+ vec![0, -1]
+ } else {
+ (0..batch_size).map(|batch| batch as i32).collect::<Vec<_>>()
+ };
+
+ let kh0 = alloc_allocation_with_data::<B, f32>(&context, &kh0);
+ let v = alloc_allocation_with_data::<B, T>(&context, &v);
+ let prefix = alloc_allocation_with_data::<B, f32>(&context, &prefix);
+ let beta = alloc_allocation_with_data::<B, f32>(&context, &beta);
+ let a = alloc_allocation_with_data::<B, f32>(&context, &a_f32);
+ let a_inv = alloc_allocation_with_data::<B, f32>(&context, &a_inv);
+ let h0_idx = alloc_allocation_with_data::<B, i32>(&context, &h0_idx);
+ let mut u = alloc_allocation::<B, f32>(&context, u_len);
+
+ let mut encoder = Encoder::new(context.as_ref()).expect("encoder");
+ kernel.encode(
+ use_h0.then_some(&kh0),
+ &v,
+ &prefix,
+ &beta,
+ &a,
+ &a_inv,
+ use_h0.then_some(&h0_idx),
+ &mut u,
+ case.batch_size,
+ case.tree_size,
+ case.num_v_heads,
+ case.head_v_dim,
+ &mut encoder,
+ );
+ encoder.end_encoding().submit().wait_until_completed().unwrap();
+
+ allocation_to_vec(&u)
+}
+
+#[uzu_test]
+fn test_tree_update_solve_cases() {
+ for &bv in BVS {
+ for &use_h0 in &[true, false] {
+ for &case in CASES {
+ let expected = run_case::<Cpu, f32>(case, bv, false, use_h0, DataType::F32, |x| x);
+ for_each_non_cpu_backend!(|B| {
+ let output = run_case::<B, f32>(case, bv, false, use_h0, DataType::F32, |x| x);
+ assert_eq_float(&expected, &output, 1e-4, &format!("{} BV{bv} h0={use_h0}", case.name));
+ });
+ }
+ }
+ }
+}
+
+#[uzu_test]
+fn test_tree_update_solve_mxu_cases() {
+ for &bv in MXU_BVS {
+ for &use_h0 in &[true, false] {
+ for &case in CASES {
+ let expected = run_case::<Cpu, bf16>(case, bv, false, use_h0, DataType::BF16, bf16::from_f32);
+ for_each_non_cpu_backend!(|B| {
+ if <B as Backend>::Context::new().expect("context").supports_mxu() {
+ let output = run_case::<B, bf16>(case, bv, true, use_h0, DataType::BF16, bf16::from_f32);
+ assert_eq_float(&expected, &output, 1e-2, &format!("{} MXU BV{bv} h0={use_h0}", case.name));
+ }
+ });
+ }
+ }
+ }
+}