A high-performance inference engine for AI models
Conf Head (#1042)
eugene9297d126f3b4
diff --git a/crates/uzu-engine/src/backends/common/gpu_types/confidence_head.rs b/crates/uzu-engine/src/backends/common/gpu_types/confidence_head.rsnew file mode 100644index 000000000..4b4349afd--- /dev/null+++ b/crates/uzu-engine/src/backends/common/gpu_types/confidence_head.rs@@ -0,0 +1,20 @@+pub const MODEL_MAX: u32 = 64;+pub const POOL_HIDDEN_MAX: u32 = 16;+pub const EDGE_HIDDEN_MAX: u32 = 128;+pub const CHILDREN_MAX: u32 = 4;+pub const SLOT_NUMBERS: u32 = 4;+pub const POOL_FEATURES: u32 = 3;+pub const POOL_INPUTS: u32 = 3;+pub const RELATIONS: u32 = 6;+pub const TREE_ROWS_MAX: u32 = 1024;++#[derive(Clone, Copy, Debug)]+#[repr(C)]+pub struct ConfidenceHeadParams {+ pub candidates: u32,+ pub children: u32,+ pub tree_slot_count: u32,+ pub vocab_size: u32,+ pub logit_cap: f32,+ pub epsilon: f32,+}diff --git a/crates/uzu-engine/src/backends/common/gpu_types/mod.rs b/crates/uzu-engine/src/backends/common/gpu_types/mod.rsindex 071b12df6..f9efc7864 100644--- a/crates/uzu-engine/src/backends/common/gpu_types/mod.rs+++ b/crates/uzu-engine/src/backends/common/gpu_types/mod.rs@@ -6,6 +6,7 @@pub mod activation_transform;pub mod activation_type;+pub mod confidence_head;pub mod d4s4;pub mod embedding;pub mod gated_act_mul;diff --git a/crates/uzu-engine/src/backends/cpu/kernel/confidence_head/edges.rs b/crates/uzu-engine/src/backends/cpu/kernel/confidence_head/edges.rsnew file mode 100644index 000000000..7874466b3--- /dev/null+++ b/crates/uzu-engine/src/backends/cpu/kernel/confidence_head/edges.rs@@ -0,0 +1,196 @@+use half::bf16;+use uzu_engine_macros::kernel;++use super::head::{LOG_PROB_FLOOR, NONE, dense, layer_norm, log_sum, weights};+use crate::backends::{+ common::gpu_types::{+ activation_type::ActivationType,+ confidence_head::{ConfidenceHeadParams, POOL_FEATURES, SLOT_NUMBERS},+ weaver::{FrontierIdx, MetadataIdx, TreeIdx},+ },+ cpu::kernel::weaver::weaver_selection::top_k_score_key,+};++#[kernel(ConfidenceHeadEdges)]+pub fn confidence_head_edges(+ #[optional(!refine)] node_metadata: Option<*const u32>,+ #[optional(!refine)] node_valid: Option<*const u32>,+ #[optional(!refine)] candidate_ids: Option<*const u32>,+ #[optional(!refine)] pool_features: Option<*const f32>,+ #[optional(!refine)] slot_stats: Option<*const bf16>,+ slot_rows: *mut u32,+ #[optional(!refine)] row_slots: Option<*mut u32>,+ nodes: *const bf16,+ #[optional(refine)] node_shifts: Option<*const bf16>,+ #[optional(refine)] child_shifts: Option<*const bf16>,+ token_features: *const bf16,+ child_numbers: *mut f32,+ child_pools: *mut u32,+ scores: *const f32,+ frontier: *mut u32,+ packed_tree: *mut u32,+ #[optional(!refine)] child_inputs: Option<*mut bf16>,+ input_norm: *const bf16,+ entry_weights: *const bf16,+ entry_biases: *const bf16,+ block_norm: *const bf16,+ up_weights: *const bf16,+ up_biases: *const bf16,+ down_weights: *const bf16,+ down_biases: *const bf16,+ final_norm: *const bf16,+ readout_weights: *const bf16,+ readout_biases: *const bf16,+ params: ConfidenceHeadParams,+ groups: u32,+ #[specialize] model_dim: u32,+ #[specialize] edge_hidden: u32,+ #[specialize] refine: bool,+) {+ let (slots, candidates, children) =+ (params.tree_slot_count as usize, params.candidates as usize, params.children as usize);+ let (width, hidden, groups) = (model_dim as usize, edge_hidden as usize, groups as usize);+ let slot_numbers = SLOT_NUMBERS as usize;+ let inputs = 3 * width + slot_numbers;+ let norm = |buffer: *const bf16, count: usize| {+ let values = weights(buffer, 2 * count);+ (values[..count].to_vec(), values[count..].to_vec())+ };+ let readout = (weights(readout_weights, 3 * width), weights(readout_biases, 3));+ let input_norm = norm(input_norm, inputs);+ let entry_layer = (weights(entry_weights, width * inputs), weights(entry_biases, width));+ let block_norm = norm(block_norm, width);+ let up = (weights(up_weights, hidden * width), weights(up_biases, hidden));+ let down = (weights(down_weights, width * hidden), weights(down_biases, width));+ let final_norm = norm(final_norm, width);+ let capacity = slots * children;+ let value = |buffer: *const bf16, index: usize| unsafe { (*buffer.add(index)).to_f32() };+ let shift = |buffer: Option<*const bf16>, index: usize| buffer.map_or(0.0, |buffer| value(buffer, index));+ let token_of = |entry: usize| unsafe { *frontier.add(FrontierIdx::TokenId as usize * capacity + entry) };+ for group in 0..groups {+ let slot = match node_metadata {+ Some(metadata) => (unsafe { *metadata.add(MetadataIdx::TreeSlot as usize * groups + group) }) as usize,+ None => group,+ };+ let skip = slot >= slots+ || match node_valid {+ Some(valid) => (unsafe { *valid.add(group) }) == 0,+ None => (unsafe { *slot_rows.add(slot) }) == NONE,+ };+ if skip {+ continue;+ }+ let entries = (slot * children..(slot + 1) * children).collect::<Vec<_>>();+ if let (Some(metadata), Some(ids), Some(features), Some(stats), Some(row_slots)) =+ (node_metadata, candidate_ids, pool_features, slot_stats, row_slots)+ {+ let depth = (unsafe { *metadata.add(MetadataIdx::Depth as usize * groups + group) }) as usize;+ let stats = weights(stats, 2 * slot_numbers);+ let feature = |index: usize| unsafe { *features.add(depth * POOL_FEATURES as usize * candidates + index) };+ for &entry in &entries {+ let token = token_of(entry);+ if let Some(index) =+ (0..candidates).find(|&index| (unsafe { *ids.add(depth * candidates + index) }) == token)+ {+ let numbers = [+ feature(index),+ (unsafe { *scores.add(2 * slot * candidates + index) }).max(LOG_PROB_FLOOR),+ unsafe { *scores.add((2 * slot + 1) * candidates + index) },+ feature(2 * candidates + index),+ ];+ unsafe {+ *child_pools.add(entry) = index as u32;+ for (number, value) in numbers.into_iter().enumerate() {+ *child_numbers.add(entry * slot_numbers + number) =+ (value - stats[number]) / stats[slot_numbers + number];+ }+ }+ }+ }+ let own_row = if slot == 0 {+ 0+ } else {+ let tree = |index: TreeIdx| unsafe { *packed_tree.add(index as usize * slots + slot) };+ let parent = tree(TreeIdx::ParentSlot) as usize;+ let own_token = tree(TreeIdx::TokenId);+ (0..children)+ .rev()+ .find(|&child| token_of(parent * children + child) == own_token)+ .map_or(0, |child| 1 + parent * children + child)+ };+ unsafe {+ *slot_rows.add(slot) = own_row as u32;+ *row_slots.add(own_row) = slot as u32;+ }+ }+ let row = (unsafe { *slot_rows.add(slot) }) as usize;+ let node = (0..width)+ .map(|unit| value(nodes, slot * width + unit) + shift(node_shifts, row * width + unit))+ .collect::<Vec<_>>();+ let raw = dense(&readout.0[width..], &readout.1[1..], &node);+ let [alpha, beta] =+ [raw[0], raw[1]].map(|value| ActivationType::SOFTPLUS.activate(value).min(params.logit_cap));+ let mut logits = (0..candidates)+ .map(|index| unsafe {+ alpha * *scores.add(2 * slot * candidates + index)+ + beta * *scores.add((2 * slot + 1) * candidates + index)+ })+ .collect::<Vec<_>>();+ let mut child_rows = Vec::new();+ for &entry in &entries {+ let token = token_of(entry) as usize;+ let tokens = (0..width)+ .map(|unit| {+ value(token_features, token * width + unit) + shift(child_shifts, (1 + entry) * width + unit)+ })+ .collect::<Vec<_>>();+ let numbers = unsafe { std::slice::from_raw_parts(child_numbers.add(entry * slot_numbers), slot_numbers) };+ let input = node+ .iter()+ .chain(&tokens)+ .copied()+ .chain(node.iter().zip(&tokens).map(|(node, token)| node * token))+ .chain(numbers.iter().copied())+ .collect::<Vec<_>>();+ let input = layer_norm(&input, &input_norm.0, &input_norm.1, params.epsilon);+ let state = dense(&entry_layer.0, &entry_layer.1, &input);+ let block = layer_norm(&state, &block_norm.0, &block_norm.1, params.epsilon);+ let raised = dense(&up.0, &up.1, &block)+ .into_iter()+ .map(|value| ActivationType::SILU.activate(value))+ .collect::<Vec<_>>();+ let lowered = dense(&down.0, &down.1, &raised);+ let state = state.iter().zip(lowered).map(|(state, lowered)| state + lowered).collect::<Vec<_>>();+ let state = layer_norm(&state, &final_norm.0, &final_norm.1, params.epsilon);+ let pool = unsafe { *child_pools.add(entry) } as usize;+ logits[pool] += dense(&readout.0[..width], &readout.1[..1], &state)[0];+ child_rows.push((pool, tokens.into_iter().chain(numbers.iter().copied()).collect::<Vec<_>>()));+ }+ let log_sum = log_sum(&logits);+ let parent_path = f32::from_bits(unsafe { *packed_tree.add(TreeIdx::PathLogprobBits as usize * slots + slot) });+ for (&entry, (pool, row_values)) in entries.iter().zip(&child_rows) {+ let edge = (logits[*pool] - log_sum).min(0.0);+ let field = |index: FrontierIdx| unsafe { frontier.add(index as usize * capacity + entry) };+ unsafe { *field(FrontierIdx::EdgeLogprobBits) = edge.to_bits() };+ if refine {+ let token = unsafe { *field(FrontierIdx::TokenId) };+ for other in 0..slots {+ let tree = |index: TreeIdx| unsafe { packed_tree.add(index as usize * slots + other) };+ if unsafe { *tree(TreeIdx::ParentSlot) } == slot as u32+ && unsafe { *tree(TreeIdx::TokenId) } == token+ {+ unsafe { *tree(TreeIdx::EdgeLogprobBits) = edge.to_bits() };+ }+ }+ } else if let Some(child_inputs) = child_inputs {+ unsafe {+ *field(FrontierIdx::PathLogprobBits) = (parent_path + edge).to_bits();+ *field(FrontierIdx::PathScoreKey) = top_k_score_key(parent_path + edge);+ for (column, value) in row_values.iter().enumerate() {+ *child_inputs.add(entry * (width + slot_numbers) + column) = bf16::from_f32(*value);+ }+ }+ }+ }+ }+}diff --git a/crates/uzu-engine/src/backends/cpu/kernel/confidence_head/head.rs b/crates/uzu-engine/src/backends/cpu/kernel/confidence_head/head.rsnew file mode 100644index 000000000..b4e6c7b08--- /dev/null+++ b/crates/uzu-engine/src/backends/cpu/kernel/confidence_head/head.rs@@ -0,0 +1,47 @@+use half::bf16;++pub const NONE: u32 = u32::MAX;+pub const LOG_PROB_FLOOR: f32 = -30.0;++pub fn weights(+ values: *const bf16,+ len: usize,+) -> Vec<f32> {+ (0..len).map(|index| unsafe { (*values.add(index)).to_f32() }).collect()+}++pub fn dense(+ weights: &[f32],+ biases: &[f32],+ input: &[f32],+) -> Vec<f32> {+ biases+ .iter()+ .enumerate()+ .map(|(unit, bias)| {+ bias + weights[unit * input.len()..(unit + 1) * input.len()]+ .iter()+ .zip(input)+ .map(|(weight, value)| weight * value)+ .sum::<f32>()+ })+ .collect()+}++pub fn layer_norm(+ input: &[f32],+ scales: &[f32],+ biases: &[f32],+ epsilon: f32,+) -> Vec<f32> {+ let count = input.len() as f32;+ let mean = input.iter().sum::<f32>() / count;+ let variance = input.iter().map(|value| (value - mean).powi(2)).sum::<f32>() / count;+ let scale = (variance + epsilon).sqrt().recip();+ input.iter().zip(scales).zip(biases).map(|((value, gain), bias)| (value - mean) * scale * gain + bias).collect()+}++pub fn log_sum(values: &[f32]) -> f32 {+ let top = values.iter().copied().fold(f32::NEG_INFINITY, f32::max);+ top + values.iter().map(|value| (value - top).exp()).sum::<f32>().ln()+}diff --git a/crates/uzu-engine/src/backends/cpu/kernel/confidence_head/mod.rs b/crates/uzu-engine/src/backends/cpu/kernel/confidence_head/mod.rsnew file mode 100644index 000000000..52820f604--- /dev/null+++ b/crates/uzu-engine/src/backends/cpu/kernel/confidence_head/mod.rs@@ -0,0 +1,7 @@+pub mod edges;+pub mod head;+pub mod nodes;+pub mod pools;+pub mod tree_attention;+pub mod tree_input;+pub mod tree_relations;diff --git a/crates/uzu-engine/src/backends/cpu/kernel/confidence_head/nodes.rs b/crates/uzu-engine/src/backends/cpu/kernel/confidence_head/nodes.rsnew file mode 100644index 000000000..9a61fb00b--- /dev/null+++ b/crates/uzu-engine/src/backends/cpu/kernel/confidence_head/nodes.rs@@ -0,0 +1,87 @@+use half::bf16;+use uzu_engine_macros::kernel;++use super::head::{LOG_PROB_FLOOR, dense, log_sum, weights};+use crate::backends::common::gpu_types::{+ activation_type::ActivationType,+ confidence_head::{ConfidenceHeadParams, POOL_FEATURES, POOL_INPUTS},+ weaver::MetadataIdx,+};++#[kernel(ConfidenceHeadNodes)]+pub fn confidence_head_nodes(+ residual_logits: *const bf16,+ candidate_logits: *const f32,+ pool_features: *const f32,+ round_metadata: *const u32,+ round_valid: *const u32,+ draft: *const bf16,+ pool_entry_weights: *const bf16,+ pool_entry_biases: *const bf16,+ pool_hidden_weights: *const bf16,+ pool_hidden_biases: *const bf16,+ pool_out_weights: *const bf16,+ pool_out_biases: *const bf16,+ scores: *mut f32,+ nodes: *mut bf16,+ node_inputs: *mut bf16,+ params: ConfidenceHeadParams,+ rows: u32,+ #[specialize] model_dim: u32,+ #[specialize] pool_hidden: u32,+) {+ let (rows, slots, candidates) = (rows as usize, params.tree_slot_count as usize, params.candidates as usize);+ let (width, pool) = (model_dim as usize, pool_hidden as usize);+ let features_count = POOL_FEATURES as usize * candidates;+ let entry_weights = weights(pool_entry_weights, POOL_INPUTS as usize * pool);+ let entry_biases = weights(pool_entry_biases, pool);+ let hidden_weights = weights(pool_hidden_weights, pool * pool);+ let hidden_biases = weights(pool_hidden_biases, pool);+ let out_weights = weights(pool_out_weights, width * 2 * pool);+ let out_biases = weights(pool_out_biases, width);+ let read = |buffer: *const u32, index: usize| unsafe { *buffer.add(index) };+ for row in 0..rows {+ let slot = read(round_metadata, MetadataIdx::TreeSlot as usize * rows + row) as usize;+ if read(round_valid, row) == 0 || slot >= slots {+ continue;+ }+ let depth = read(round_metadata, MetadataIdx::Depth as usize * rows + row) as usize;+ let features = unsafe { std::slice::from_raw_parts(pool_features.add(depth * features_count), features_count) };+ let logits = (0..candidates)+ .map(|index| unsafe {+ *candidate_logits.add(depth * candidates + index)+ + (*residual_logits.add(row * candidates + index)).to_f32()+ })+ .collect::<Vec<_>>();+ let log_sum = log_sum(&logits);+ let mut mean = vec![0.0f32; pool];+ let mut peak = vec![f32::NEG_INFINITY; pool];+ for (index, logit) in logits.iter().enumerate() {+ let (log_draft, noise) = (features[index], features[candidates + index]);+ let log_logit = logit - log_sum;+ let floored = log_logit.max(LOG_PROB_FLOOR);+ let hidden = dense(&entry_weights, &entry_biases, &[log_draft, floored - log_draft, noise])+ .into_iter()+ .map(|value| ActivationType::SILU.activate(value))+ .collect::<Vec<_>>();+ let encoded = dense(&hidden_weights, &hidden_biases, &hidden);+ for (unit, value) in encoded.into_iter().enumerate() {+ mean[unit] += log_logit.exp() * value;+ peak[unit] = peak[unit].max(value);+ }+ unsafe {+ *scores.add(2 * slot * candidates + index) = log_logit;+ *scores.add((2 * slot + 1) * candidates + index) = noise;+ }+ }+ let summary = mean.into_iter().chain(peak).collect::<Vec<_>>();+ let node = dense(&out_weights, &out_biases, &summary);+ for (unit, value) in node.into_iter().enumerate() {+ let value = bf16::from_f32(value + unsafe { (*draft.add(depth * width + unit)).to_f32() });+ unsafe {+ *nodes.add(slot * width + unit) = value;+ *node_inputs.add(slot * width + unit) = value;+ }+ }+ }+}diff --git a/crates/uzu-engine/src/backends/cpu/kernel/confidence_head/pools.rs b/crates/uzu-engine/src/backends/cpu/kernel/confidence_head/pools.rsnew file mode 100644index 000000000..58e42f3a1--- /dev/null+++ b/crates/uzu-engine/src/backends/cpu/kernel/confidence_head/pools.rs@@ -0,0 +1,34 @@+use uzu_engine_macros::kernel;++use super::head::{LOG_PROB_FLOOR, log_sum};+use crate::{+ backends::common::gpu_types::confidence_head::ConfidenceHeadParams,+ encodable_block::sampling::{gumbel_float, revidx},+};++#[kernel(ConfidenceHeadPools)]+pub fn confidence_head_pools(+ candidate_logits: *const f32,+ candidate_ids: *const u32,+ depth_seeds: *const u64,+ pool_features: *mut f32,+ params: ConfidenceHeadParams,+ depths: u32,+) {+ let candidates = params.candidates as usize;+ for depth in 0..depths as usize {+ let logits = unsafe { std::slice::from_raw_parts(candidate_logits.add(depth * candidates), candidates) };+ let log_sum = log_sum(logits);+ let seed = unsafe { *depth_seeds.add(depth) };+ for (index, logit) in logits.iter().enumerate() {+ let rank = logits.iter().filter(|other| *other > logit).count() as f32;+ let token = unsafe { *candidate_ids.add(depth * candidates + index) };+ let features = unsafe { pool_features.add(depth * 3 * candidates) };+ unsafe {+ *features.add(index) = (logit - log_sum).max(LOG_PROB_FLOOR);+ *features.add(candidates + index) = gumbel_float(seed, revidx(token, params.vocab_size));+ *features.add(2 * candidates + index) = rank.ln_1p();+ }+ }+ }+}diff --git a/crates/uzu-engine/src/backends/cpu/kernel/confidence_head/tree_attention.rs b/crates/uzu-engine/src/backends/cpu/kernel/confidence_head/tree_attention.rsnew file mode 100644index 000000000..42b796147--- /dev/null+++ b/crates/uzu-engine/src/backends/cpu/kernel/confidence_head/tree_attention.rs@@ -0,0 +1,57 @@+use half::bf16;+use uzu_engine_macros::kernel;++use super::tree_relations::ABSENT;+use crate::backends::common::gpu_types::confidence_head::RELATIONS;++#[kernel(ConfidenceHeadTreeAttention)]+pub fn confidence_head_tree_attention(+ qkv: *const bf16,+ relations: *const u32,+ relation_bias: *const bf16,+ output: *mut bf16,+ rows: u32,+ #[specialize] num_heads: u32,+ #[specialize] head_dim: u32,+) {+ let (rows, heads, head_dim) = (rows as usize, num_heads as usize, head_dim as usize);+ let width = heads * head_dim;+ let scale = (head_dim as f32).sqrt().recip();+ let element = |row: usize, part: usize, head: usize, unit: usize| unsafe {+ (*qkv.add(row * 3 * width + part * width + head * head_dim + unit)).to_f32()+ };+ for query in 0..rows {+ let relation = |key: usize| unsafe { *relations.add(query * rows + key) };+ let keys = if relation(query) == ABSENT {+ Vec::new()+ } else {+ (0..rows).filter(|&key| relation(key) != ABSENT).collect::<Vec<_>>()+ };+ for head in 0..heads {+ let scores = keys+ .iter()+ .map(|&key| {+ let bias = match relation(key) {+ 0 => 0.0,+ code => unsafe { (*relation_bias.add(head * RELATIONS as usize + code as usize - 1)).to_f32() },+ };+ (0..head_dim).map(|unit| element(query, 0, head, unit) * element(key, 1, head, unit)).sum::<f32>()+ * scale+ + bias+ })+ .collect::<Vec<_>>();+ let top = scores.iter().copied().fold(f32::NEG_INFINITY, f32::max);+ let weights = scores.iter().map(|score| (score - top).exp()).collect::<Vec<_>>();+ let total = weights.iter().sum::<f32>();+ for unit in 0..head_dim {+ let value = if keys.is_empty() {+ 0.0+ } else {+ keys.iter().zip(&weights).map(|(&key, weight)| weight * element(key, 2, head, unit)).sum::<f32>()+ / total+ };+ unsafe { *output.add(query * width + head * head_dim + unit) = bf16::from_f32(value) };+ }+ }+ }+}diff --git a/crates/uzu-engine/src/backends/cpu/kernel/confidence_head/tree_input.rs b/crates/uzu-engine/src/backends/cpu/kernel/confidence_head/tree_input.rsnew file mode 100644index 000000000..9391a8e97--- /dev/null+++ b/crates/uzu-engine/src/backends/cpu/kernel/confidence_head/tree_input.rs@@ -0,0 +1,41 @@+use half::bf16;+use uzu_engine_macros::kernel;++use super::head::NONE;+use crate::backends::common::gpu_types::weaver::FrontierIdx;++#[kernel(ConfidenceHeadTreeInput)]+pub fn confidence_head_tree_input(+ depth_embedding: *const bf16,+ child_in: *const bf16,+ node_in: *const bf16,+ frontier: *const u32,+ row_slots: *const u32,+ output: *mut bf16,+ rows: u32,+ width: u32,+) {+ let (rows, width) = (rows as usize, width as usize);+ let value = |buffer: *const bf16, index: usize| unsafe { (*buffer.add(index)).to_f32() };+ for row in 0..rows {+ let depth = if row == 0 {+ 0+ } else {+ unsafe { *frontier.add(FrontierIdx::Depth as usize * (rows - 1) + row - 1) }+ };+ let slot = unsafe { *row_slots.add(row) };+ for unit in 0..width {+ let mut sum = 0.0;+ if row == 0 || depth != 0 {+ sum = value(depth_embedding, depth as usize * width + unit);+ if row != 0 {+ sum += value(child_in, (row - 1) * width + unit);+ }+ if slot != NONE {+ sum += value(node_in, slot as usize * width + unit);+ }+ }+ unsafe { *output.add(row * width + unit) = bf16::from_f32(sum) };+ }+ }+}diff --git a/crates/uzu-engine/src/backends/cpu/kernel/confidence_head/tree_relations.rs b/crates/uzu-engine/src/backends/cpu/kernel/confidence_head/tree_relations.rsnew file mode 100644index 000000000..739f827c6--- /dev/null+++ b/crates/uzu-engine/src/backends/cpu/kernel/confidence_head/tree_relations.rs@@ -0,0 +1,65 @@+use uzu_engine_macros::kernel;++use crate::backends::common::gpu_types::{confidence_head::RELATIONS, weaver::FrontierIdx};++pub const ABSENT: u32 = RELATIONS + 1;++#[kernel(ConfidenceHeadTreeRelations)]+pub fn confidence_head_tree_relations(+ frontier: *const u32,+ slot_ancestors: *const u32,+ slot_rows: *const u32,+ relations: *mut u32,+ rows: u32,+ ancestor_stride: u32,+) {+ let (rows, stride) = (rows as usize, ancestor_stride as usize);+ let read = |buffer: *const u32, index: usize| unsafe { *buffer.add(index) } as usize;+ let tree_row = |row: usize| {+ if row == 0 {+ (0, usize::MAX)+ } else {+ (+ read(frontier, FrontierIdx::Depth as usize * (rows - 1) + row - 1),+ read(frontier, FrontierIdx::ParentSlot as usize * (rows - 1) + row - 1),+ )+ }+ };+ let ancestor_row = |(depth, parent): (usize, usize), level: usize| {+ read(+ slot_rows,+ if level + 1 == depth {+ parent+ } else {+ read(slot_ancestors, parent * stride + level)+ },+ )+ };+ for query in 0..rows {+ for key in 0..rows {+ let (query_row, key_row) = (tree_row(query), tree_row(key));+ let relation = if (query != 0 && query_row.0 == 0) || (key != 0 && key_row.0 == 0) {+ ABSENT+ } else if query == key {+ 1+ } else if key_row.0 < query_row.0 && ancestor_row(query_row, key_row.0) == key {+ if key_row.0 + 1 == query_row.0 {+ 2+ } else {+ 4+ }+ } else if query_row.0 < key_row.0 && ancestor_row(key_row, query_row.0) == query {+ if query_row.0 + 1 == key_row.0 {+ 3+ } else {+ 5+ }+ } else if query_row.0 == key_row.0 && query_row.0 != 0 && query_row.1 == key_row.1 {+ 6+ } else {+ 0+ };+ unsafe { *relations.add(query * rows + key) = relation };+ }+ }+}diff --git a/crates/uzu-engine/src/backends/cpu/kernel/mod.rs b/crates/uzu-engine/src/backends/cpu/kernel/mod.rsindex 743b4bcb5..c5d9798f1 100644--- a/crates/uzu-engine/src/backends/cpu/kernel/mod.rs+++ b/crates/uzu-engine/src/backends/cpu/kernel/mod.rs@@ -6,6 +6,7 @@ use crate::backends::{mod activation;pub(crate) mod activation_transform;mod attention;+mod confidence_head;mod convolution;mod embedding;mod gated_act_mul;diff --git a/crates/uzu-engine/src/backends/cpu/kernel/weaver/weaver_selection.rs b/crates/uzu-engine/src/backends/cpu/kernel/weaver/weaver_selection.rsindex 02e766fe6..8e8973d97 100644--- a/crates/uzu-engine/src/backends/cpu/kernel/weaver/weaver_selection.rs+++ b/crates/uzu-engine/src/backends/cpu/kernel/weaver/weaver_selection.rs@@ -253,7 +253,7 @@ pub fn weaver_select<const BLOCK_THREADS: u32>(const F32_SIGN_BIT: u32 = 1 << (u32::BITS - 1);-fn top_k_score_key(score: f32) -> u32 {+pub fn top_k_score_key(score: f32) -> u32 {let bits = score.to_bits();if bits & F32_SIGN_BIT == 0 {bits ^ F32_SIGN_BITdiff --git a/crates/uzu-engine/src/backends/metal/kernel/confidence_head/edges.metal b/crates/uzu-engine/src/backends/metal/kernel/confidence_head/edges.metalnew file mode 100644index 000000000..737beadc6--- /dev/null+++ b/crates/uzu-engine/src/backends/metal/kernel/confidence_head/edges.metal@@ -0,0 +1,294 @@+#include <metal_stdlib>+#include "../common/dsl.h"+#include "../common/top_k.h"+#include "../weaver/weaver_frontier.h"+#include "head.h"++using namespace metal;++struct EdgesMemory {+ float reduce[2u * HEAD_SIMDGROUPS];+ float coefficients[2];+ float node[MODEL_MAX];+ float tokens[CHILDREN_MAX * MODEL_MAX];+ float numbers[CHILDREN_MAX * SLOT_NUMBERS];+ float input[CHILDREN_MAX * HEAD_EDGE_INPUT_MAX];+ float state[CHILDREN_MAX * MODEL_MAX];+ float block[CHILDREN_MAX * MODEL_MAX];+ float raised[CHILDREN_MAX * EDGE_HIDDEN_MAX];+ float deltas[CHILDREN_MAX];+ float edges[CHILDREN_MAX];+ uint pools[CHILDREN_MAX];+};++PUBLIC KERNEL(ConfidenceHeadEdges)(+ const device uint* node_metadata OPTIONAL(!refine),+ const device uint* node_valid OPTIONAL(!refine),+ const device uint* candidate_ids OPTIONAL(!refine),+ const device float* pool_features OPTIONAL(!refine),+ const device bfloat* slot_stats OPTIONAL(!refine),+ device uint* slot_rows,+ device uint* row_slots OPTIONAL(!refine),+ const device bfloat* nodes,+ const device bfloat* node_shifts OPTIONAL(refine),+ const device bfloat* child_shifts OPTIONAL(refine),+ const device bfloat* token_features,+ device float* child_numbers,+ device uint* child_pools,+ const device float* scores,+ device uint* frontier,+ device uint* packed_tree,+ device bfloat* child_inputs OPTIONAL(!refine),+ const device bfloat* input_norm,+ const device bfloat* entry_weights,+ const device bfloat* entry_biases,+ const device bfloat* block_norm,+ const device bfloat* up_weights,+ const device bfloat* up_biases,+ const device bfloat* down_weights,+ const device bfloat* down_biases,+ const device bfloat* final_norm,+ const device bfloat* readout_weights,+ const device bfloat* readout_biases,+ const constant ConfidenceHeadParams& params,+ const constant uint& groups,+ const uint model_dim SPECIALIZE,+ const uint edge_hidden SPECIALIZE,+ const bool refine SPECIALIZE,+ threadgroup EdgesMemory& memory,+ const ThreadContext context,+ const uint group GROUPS(groups),+ const uint lid THREADS(HEAD_THREADS)+) {+ const uint tree_slot_count = params.tree_slot_count;+ const uint children = params.children;+ const uint candidates = params.candidates;+ const uint capacity = tree_slot_count * children;+ const uint slot = refine ? group : node_metadata[uint(MetadataIdx::TreeSlot) * groups + group];+ if (slot >= tree_slot_count || (refine ? slot_rows[slot] == HEAD_NONE : node_valid[group] == 0u)) {+ return;+ }+ const uint first_entry = slot * children;+ const uint simdgroup = context.simdgroup_index;+ const uint lane = context.simd_lane_id;+ const uint inputs = 3u * model_dim + SLOT_NUMBERS;+ const uint row = refine ? slot_rows[slot] : 0u;+ if (refine) {+ if (lid < children) {+ memory.pools[lid] = child_pools[first_entry + lid];+ }+ if (lid < children * SLOT_NUMBERS) {+ memory.numbers[lid] = child_numbers[first_entry * SLOT_NUMBERS + lid];+ }+ } else {+ uint child_tokens[CHILDREN_MAX];+ METAL_PRAGMA_UNROLL+ for (uint child = 0; child < CHILDREN_MAX; ++child) {+ child_tokens[child] =+ child < children ? frontier[uint(FrontierIdx::TokenId) * capacity + first_entry + child] : HEAD_NONE;+ }+ if (lid < candidates) {+ const uint depth = node_metadata[uint(MetadataIdx::Depth) * groups + group];+ const uint candidate_id = candidate_ids[depth * candidates + lid];+ for (uint child = 0; child < children; ++child) {+ if (candidate_id == child_tokens[child]) {+ const uint entry = first_entry + child;+ const device float* features = pool_features + depth * POOL_FEATURES * candidates;+ const float numbers[SLOT_NUMBERS] = {+ features[lid],+ max(scores[(2 * slot) * candidates + lid], HEAD_LOG_PROB_FLOOR),+ scores[(2 * slot + 1) * candidates + lid],+ features[2 * candidates + lid]+ };+ memory.pools[child] = lid;+ child_pools[entry] = lid;+ for (uint number = 0; number < SLOT_NUMBERS; ++number) {+ const float value =+ (numbers[number] - float(slot_stats[number])) / float(slot_stats[SLOT_NUMBERS + number]);+ memory.numbers[child * SLOT_NUMBERS + number] = value;+ child_numbers[entry * SLOT_NUMBERS + number] = value;+ }+ }+ }+ }+ if (simdgroup == 0) {+ uint own_row = 0;+ if (slot != 0) {+ const uint parent = packed_tree[uint(TreeIdx::ParentSlot) * tree_slot_count + slot];+ const uint own_token = packed_tree[uint(TreeIdx::TokenId) * tree_slot_count + slot];+ const bool hit =+ lane < children && frontier[uint(FrontierIdx::TokenId) * capacity + parent * children + lane] == own_token;+ own_row = simd_max(hit ? 1 + parent * children + lane : 0u);+ }+ if (lane == 0) {+ slot_rows[slot] = own_row;+ row_slots[own_row] = slot;+ }+ }+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);+ if (simdgroup < children) {+ const uint entry = first_entry + simdgroup;+ const uint token = frontier[uint(FrontierIdx::TokenId) * capacity + entry];+ threadgroup float* line = memory.input + simdgroup * HEAD_EDGE_INPUT_MAX;+ float total = 0.0f;+ for (uint unit = lane; unit < model_dim; unit += METAL_SIMD_SIZE) {+ const float node =+ float(nodes[slot * model_dim + unit]) + (refine ? float(node_shifts[row * model_dim + unit]) : 0.0f);+ const float vector = float(token_features[token * model_dim + unit]) ++ (refine ? float(child_shifts[(1 + entry) * model_dim + unit]) : 0.0f);+ line[unit] = node;+ line[model_dim + unit] = vector;+ line[2u * model_dim + unit] = node * vector;+ memory.tokens[simdgroup * MODEL_MAX + unit] = vector;+ if (simdgroup == 0) {+ memory.node[unit] = node;+ }+ total += node + vector + node * vector;+ }+ if (lane < SLOT_NUMBERS) {+ const float number = memory.numbers[simdgroup * SLOT_NUMBERS + lane];+ line[3u * model_dim + lane] = number;+ total += number;+ }+ simdgroup_barrier(mem_flags::mem_threadgroup);+ const float mean = simd_sum(total) / float(inputs);+ float spread = 0.0f;+ for (uint column = lane; column < inputs; column += METAL_SIMD_SIZE) {+ spread += (line[column] - mean) * (line[column] - mean);+ }+ const float scale = rsqrt(simd_sum(spread) / float(inputs) + params.epsilon);+ for (uint column = lane; column < inputs; column += METAL_SIMD_SIZE) {+ line[column] = (line[column] - mean) * scale * float(input_norm[column]) + float(input_norm[inputs + column]);+ }+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);+ head_dense(+ entry_weights,+ entry_biases,+ memory.input,+ HEAD_EDGE_INPUT_MAX,+ memory.state,+ MODEL_MAX,+ inputs,+ model_dim,+ children,+ false,+ false,+ context+ );+ head_layer_norm(+ memory.state,+ memory.block,+ MODEL_MAX,+ model_dim,+ children,+ block_norm,+ block_norm + model_dim,+ params.epsilon,+ context+ );+ head_dense(+ up_weights,+ up_biases,+ memory.block,+ MODEL_MAX,+ memory.raised,+ EDGE_HIDDEN_MAX,+ model_dim,+ edge_hidden,+ children,+ true,+ false,+ context+ );+ head_dense(+ down_weights,+ down_biases,+ memory.raised,+ EDGE_HIDDEN_MAX,+ memory.state,+ MODEL_MAX,+ edge_hidden,+ model_dim,+ children,+ false,+ true,+ context+ );+ if (simdgroup < children) {+ const threadgroup float* line = memory.state + simdgroup * MODEL_MAX;+ float total = 0.0f;+ for (uint unit = lane; unit < model_dim; unit += METAL_SIMD_SIZE) {+ total += line[unit];+ }+ const float mean = simd_sum(total) / float(model_dim);+ float spread = 0.0f;+ for (uint unit = lane; unit < model_dim; unit += METAL_SIMD_SIZE) {+ spread += (line[unit] - mean) * (line[unit] - mean);+ }+ const float scale = rsqrt(simd_sum(spread) / float(model_dim) + params.epsilon);+ float delta = 0.0f;+ for (uint unit = lane; unit < model_dim; unit += METAL_SIMD_SIZE) {+ const float normed = (line[unit] - mean) * scale * float(final_norm[unit]) + float(final_norm[model_dim + unit]);+ delta += float(readout_weights[unit]) * normed;+ }+ delta = simd_sum(delta);+ if (lane == 0) {+ memory.deltas[simdgroup] = delta + float(readout_biases[0]);+ }+ } else if (simdgroup >= CHILDREN_MAX && simdgroup < CHILDREN_MAX + 2u) {+ const uint output = simdgroup - CHILDREN_MAX;+ const float value = head_simd_dot(readout_weights + (1 + output) * model_dim, memory.node, model_dim, lane) ++ float(readout_biases[1 + output]);+ if (lane == 0) {+ memory.coefficients[output] = min(activate_softplus(value), params.logit_cap);+ }+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);++ const bool valid = lid < candidates;+ float score = valid ? memory.coefficients[0] * scores[(2 * slot) * candidates + lid] ++ memory.coefficients[1] * scores[(2 * slot + 1) * candidates + lid]+ : -INFINITY;+ for (uint child = 0; child < children; ++child) {+ score += memory.pools[child] == lid ? memory.deltas[child] : 0.0f;+ }+ const float log_sum = head_log_sum_exp(score, memory.reduce, context);+ const float parent_path = as_type<float>(packed_tree[uint(TreeIdx::PathLogprobBits) * tree_slot_count + slot]);+ for (uint child = 0; child < children; ++child) {+ if (memory.pools[child] == lid) {+ const uint entry = first_entry + child;+ const float edge = min(score - log_sum, 0.0f);+ memory.edges[child] = edge;+ frontier[uint(FrontierIdx::EdgeLogprobBits) * capacity + entry] = as_type<uint>(edge);+ if (!refine) {+ frontier[uint(FrontierIdx::PathLogprobBits) * capacity + entry] = as_type<uint>(parent_path + edge);+ frontier[uint(FrontierIdx::PathScoreKey) * capacity + entry] = top_k_score_key(parent_path + edge);+ }+ }+ }+ if (!refine) {+ const uint width = model_dim + SLOT_NUMBERS;+ for (uint index = lid; index < children * width; index += HEAD_THREADS) {+ const uint child = index / width;+ const uint column = index % width;+ child_inputs[(first_entry + child) * width + column] = bfloat(+ column < model_dim ? memory.tokens[child * MODEL_MAX + column]+ : memory.numbers[child * SLOT_NUMBERS + column - model_dim]+ );+ }+ return;+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);+ for (uint other = lid; other < tree_slot_count; other += HEAD_THREADS) {+ if (packed_tree[uint(TreeIdx::ParentSlot) * tree_slot_count + other] == slot) {+ const uint token = packed_tree[uint(TreeIdx::TokenId) * tree_slot_count + other];+ for (uint child = 0; child < children; ++child) {+ if (frontier[uint(FrontierIdx::TokenId) * capacity + first_entry + child] == token) {+ packed_tree[uint(TreeIdx::EdgeLogprobBits) * tree_slot_count + other] = as_type<uint>(memory.edges[child]);+ }+ }+ }+ }+}diff --git a/crates/uzu-engine/src/backends/metal/kernel/confidence_head/head.h b/crates/uzu-engine/src/backends/metal/kernel/confidence_head/head.hnew file mode 100644index 000000000..8b9217e19--- /dev/null+++ b/crates/uzu-engine/src/backends/metal/kernel/confidence_head/head.h@@ -0,0 +1,212 @@+#pragma once++#include <metal_stdlib>+#include "../common/defines.h"+#include "../common/thread_context.h"+#include "../activation/activations.h"+#include "../generated/confidence_head.h"++using namespace metal;+using namespace uzu::confidence_head;++#define HEAD_THREADS 512u+#define HEAD_SIMDGROUPS (HEAD_THREADS / 32u)+#define HEAD_EDGE_INPUT_MAX (3u * MODEL_MAX + SLOT_NUMBERS)+#define HEAD_DENSE_UNITS 4u+#define HEAD_NONE 0xffffffffu+#define HEAD_LOG_PROB_FLOOR (-30.0f)+#define HEAD_RELATION_ABSENT (RELATIONS + 1u)++template <uint SIMDGROUPS = HEAD_SIMDGROUPS>+METAL_FUNC float head_log_sum_exp(float value, threadgroup float* reduce, const thread ThreadContext& context) {+ static_assert(SIMDGROUPS <= 32u, "a lane per simdgroup");+ const float top = simd_max(value);+ const float total = simd_sum(value == -INFINITY ? 0.0f : exp(value - top));+ if (context.simd_lane_id == 0) {+ reduce[2 * context.simdgroup_index] = top;+ reduce[2 * context.simdgroup_index + 1] = total;+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);+ const bool owned = context.simd_lane_id < SIMDGROUPS;+ const float part_top = owned ? reduce[2 * context.simd_lane_id] : -INFINITY;+ const float part_total = owned ? reduce[2 * context.simd_lane_id + 1] : 0.0f;+ threadgroup_barrier(mem_flags::mem_threadgroup);+ const float overall = simd_max(part_top);+ return overall + log(simd_sum(part_top == -INFINITY ? 0.0f : part_total * exp(part_top - overall)));+}++template <bool MAXIMUM>+METAL_FUNC float head_combine(float left, float right) {+ return MAXIMUM ? max(left, right) : left + right;+}++template <bool MAXIMUM, uint COUNT, ushort LANES = 32>+METAL_FUNC float head_reduce(thread float* values, uint lane) {+ static_assert(COUNT <= LANES && LANES <= 32u, "a lane group per value");+ if constexpr (COUNT > 1u) {+ constexpr ushort mask = LANES / 2u;+ const bool high = (lane & mask) != 0u;+ METAL_PRAGMA_UNROLL+ for (uint index = 0; index < COUNT / 2u; ++index) {+ const float kept = high ? values[COUNT / 2u + index] : values[index];+ const float sent = high ? values[index] : values[COUNT / 2u + index];+ values[index] = head_combine<MAXIMUM>(kept, simd_shuffle_xor(sent, mask));+ }+ return head_reduce<MAXIMUM, COUNT / 2u, mask>(values, lane);+ } else {+ float value = values[0];+ METAL_PRAGMA_UNROLL+ for (ushort mask = LANES / 2u; mask > 0u; mask /= 2u) {+ value = head_combine<MAXIMUM>(value, simd_shuffle_xor(value, mask));+ }+ return value;+ }+}++template <ushort LANES>+METAL_FUNC void head_dense_lanes(+ const device bfloat* weights,+ const device bfloat* biases,+ const threadgroup float* input,+ uint input_stride,+ threadgroup float* output,+ uint output_stride,+ uint inputs,+ uint outputs,+ uint rows,+ bool activate,+ bool accumulate,+ const thread ThreadContext& context+) {+ static_assert(HEAD_DENSE_UNITS * CHILDREN_MAX == 16u, "the butterfly reduces sixteen sums");+ constexpr uint parts = 32u / LANES;+ const uint lane = context.simd_lane_id % LANES;+ for (uint first = HEAD_DENSE_UNITS * (parts * context.simdgroup_index + context.simd_lane_id / LANES);+ first < outputs;+ first += HEAD_DENSE_UNITS * parts * HEAD_SIMDGROUPS) {+ float sums[HEAD_DENSE_UNITS * CHILDREN_MAX];+ METAL_PRAGMA_UNROLL+ for (uint index = 0; index < HEAD_DENSE_UNITS * CHILDREN_MAX; ++index) {+ sums[index] = 0.0f;+ }+ for (uint column = 4u * lane; column < inputs; column += 4u * LANES) {+ float4 values[CHILDREN_MAX];+ METAL_PRAGMA_UNROLL+ for (uint row = 0; row < CHILDREN_MAX; ++row) {+ values[row] =+ row < rows+ ? float4(*reinterpret_cast<const threadgroup packed_float4*>(input + row * input_stride + column))+ : float4(0.0f);+ }+ METAL_PRAGMA_UNROLL+ for (uint unit = 0; unit < HEAD_DENSE_UNITS; ++unit) {+ const float4 weight =+ first + unit < outputs+ ? float4(*reinterpret_cast<const device bfloat4*>(weights + (first + unit) * inputs + column))+ : float4(0.0f);+ METAL_PRAGMA_UNROLL+ for (uint row = 0; row < CHILDREN_MAX; ++row) {+ sums[unit * CHILDREN_MAX + row] += dot(weight, values[row]);+ }+ }+ }+ const float total = head_reduce<false, HEAD_DENSE_UNITS * CHILDREN_MAX, LANES>(sums, context.simd_lane_id);+ const uint index = LANES == 32 ? (lane >> 1u) & 15u : lane;+ const uint unit = first + index / CHILDREN_MAX;+ const uint row = index % CHILDREN_MAX;+ if ((LANES != 32 || (lane & 1u) == 0u) && unit < outputs && row < rows) {+ float value = total + float(biases[unit]);+ value = activate ? activate_silu(value) : value;+ threadgroup float* target = output + row * output_stride + unit;+ *target = accumulate ? *target + value : value;+ }+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);+}++METAL_FUNC void head_dense(+ const device bfloat* weights,+ const device bfloat* biases,+ const threadgroup float* input,+ uint input_stride,+ threadgroup float* output,+ uint output_stride,+ uint inputs,+ uint outputs,+ uint rows,+ bool activate,+ bool accumulate,+ const thread ThreadContext& context+) {+ if (inputs <= 64u) {+ head_dense_lanes<16>(+ weights,+ biases,+ input,+ input_stride,+ output,+ output_stride,+ inputs,+ outputs,+ rows,+ activate,+ accumulate,+ context+ );+ } else {+ head_dense_lanes<32>(+ weights,+ biases,+ input,+ input_stride,+ output,+ output_stride,+ inputs,+ outputs,+ rows,+ activate,+ accumulate,+ context+ );+ }+}++METAL_FUNC void head_layer_norm(+ const threadgroup float* input,+ threadgroup float* output,+ uint stride,+ uint count,+ uint rows,+ const device bfloat* scales,+ const device bfloat* biases,+ float epsilon,+ const thread ThreadContext& context+) {+ const uint row = context.simdgroup_index;+ const uint lane = context.simd_lane_id;+ if (row < rows) {+ const threadgroup float* values = input + row * stride;+ float total = 0.0f;+ for (uint index = lane; index < count; index += 32u) {+ total += values[index];+ }+ const float mean = simd_sum(total) / float(count);+ float spread = 0.0f;+ for (uint index = lane; index < count; index += 32u) {+ spread += (values[index] - mean) * (values[index] - mean);+ }+ const float scale = rsqrt(simd_sum(spread) / float(count) + epsilon);+ for (uint index = lane; index < count; index += 32u) {+ output[row * stride + index] = (values[index] - mean) * scale * float(scales[index]) + float(biases[index]);+ }+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);+}++METAL_FUNC float head_simd_dot(const device bfloat* weights, const threadgroup float* values, uint count, uint lane) {+ float total = 0.0f;+ for (uint index = lane; index < count; index += 32u) {+ total += float(weights[index]) * values[index];+ }+ return simd_sum(total);+}diff --git a/crates/uzu-engine/src/backends/metal/kernel/confidence_head/nodes.metal b/crates/uzu-engine/src/backends/metal/kernel/confidence_head/nodes.metalnew file mode 100644index 000000000..51eb0049e--- /dev/null+++ b/crates/uzu-engine/src/backends/metal/kernel/confidence_head/nodes.metal@@ -0,0 +1,153 @@+#include <metal_stdlib>+#include "../common/dsl.h"+#include "../weaver/weaver_frontier.h"+#include "head.h"++using namespace metal;++#define NODES_THREADS 1024u+#define NODES_SIMDGROUPS (NODES_THREADS / 32u)+#define NODES_UNITS (POOL_HIDDEN_MAX / 2u)++static_assert(NODES_THREADS == 2u * CANDIDATES_MAX, "two threads per candidate, each with half of the pool units");+static_assert(2u * POOL_HIDDEN_MAX <= NODES_SIMDGROUPS, "a simdgroup per pool summary value");++struct NodesMemory {+ float4 pool_entry[POOL_HIDDEN_MAX];+ float4 pool_hidden[POOL_HIDDEN_MAX * POOL_HIDDEN_MAX / 4u];+ float pool_hidden_biases[POOL_HIDDEN_MAX];+ float reduce[2u * NODES_SIMDGROUPS * NODES_UNITS];+ float summary[2u * POOL_HIDDEN_MAX];+ float node[MODEL_MAX];+};++PUBLIC KERNEL(ConfidenceHeadNodes)(+ const device bfloat* residual_logits,+ const device float* candidate_logits,+ const device float* pool_features,+ const device uint* round_metadata,+ const device uint* round_valid,+ const device bfloat* draft,+ const device bfloat* pool_entry_weights,+ const device bfloat* pool_entry_biases,+ const device bfloat* pool_hidden_weights,+ const device bfloat* pool_hidden_biases,+ const device bfloat* pool_out_weights,+ const device bfloat* pool_out_biases,+ device float* scores,+ device bfloat* nodes,+ device bfloat* node_inputs,+ const constant ConfidenceHeadParams& params,+ const constant uint& rows,+ const uint model_dim SPECIALIZE,+ const uint pool_hidden SPECIALIZE,+ threadgroup NodesMemory& memory,+ const ThreadContext context,+ const uint row GROUPS(rows),+ const uint lid THREADS(NODES_THREADS)+) {+ const uint slot = round_metadata[uint(MetadataIdx::TreeSlot) * rows + row];+ if (round_valid[row] == 0u || slot >= params.tree_slot_count) {+ return;+ }+ const uint depth = round_metadata[uint(MetadataIdx::Depth) * rows + row];+ const uint candidates = params.candidates;+ const device float* features = pool_features + depth * POOL_FEATURES * candidates;+ const uint candidate = lid % CANDIDATES_MAX;+ const uint half_index = lid / CANDIDATES_MAX;+ const bool valid = candidate < candidates;+ const float logit =+ valid ? candidate_logits[depth * candidates + candidate] + float(residual_logits[row * candidates + candidate])+ : -INFINITY;+ const float log_draft = valid ? features[candidate] : 0.0f;+ const float noise = valid ? features[candidates + candidate] : 0.0f;+ if (lid < POOL_HIDDEN_MAX) {+ const bool used = lid < pool_hidden;+ memory.pool_entry[lid] = used ? float4(+ float(pool_entry_weights[POOL_INPUTS * lid]),+ float(pool_entry_weights[POOL_INPUTS * lid + 1u]),+ float(pool_entry_weights[POOL_INPUTS * lid + 2u]),+ float(pool_entry_biases[lid])+ )+ : float4(0.0f);+ memory.pool_hidden_biases[lid] = used ? float(pool_hidden_biases[lid]) : 0.0f;+ }+ for (uint index = lid; index < POOL_HIDDEN_MAX * POOL_HIDDEN_MAX; index += NODES_THREADS) {+ const uint unit = index / POOL_HIDDEN_MAX;+ const uint inner = index % POOL_HIDDEN_MAX;+ reinterpret_cast<threadgroup float*>(memory.pool_hidden)[index] =+ unit < pool_hidden && inner < pool_hidden ? float(pool_hidden_weights[unit * pool_hidden + inner]) : 0.0f;+ }+ if (lid < model_dim) {+ memory.node[lid] = float(draft[depth * model_dim + lid]);+ }++ const float log_logit =+ logit - head_log_sum_exp<NODES_SIMDGROUPS>(half_index == 0u ? logit : -INFINITY, memory.reduce, context);+ if (valid) {+ scores[(2 * slot + half_index) * candidates + candidate] = half_index == 0u ? log_logit : noise;+ }+ const float floored = max(log_logit, HEAD_LOG_PROB_FLOOR);+ const float weight = valid ? exp(log_logit) : 0.0f;+ const float4 inputs = float4(log_draft, floored - log_draft, noise, 1.0f);+ float4 hidden[POOL_HIDDEN_MAX / 4u];+ METAL_PRAGMA_UNROLL+ for (uint unit = 0; unit < POOL_HIDDEN_MAX; ++unit) {+ const float value = dot(memory.pool_entry[unit], inputs);+ hidden[unit / 4u][unit % 4u] = unit < pool_hidden ? activate_silu(value) : 0.0f;+ }+ float means[NODES_UNITS];+ float peaks[NODES_UNITS];+ METAL_PRAGMA_UNROLL+ for (uint offset = 0; offset < NODES_UNITS; ++offset) {+ const uint unit = half_index * NODES_UNITS + offset;+ float value = memory.pool_hidden_biases[unit];+ METAL_PRAGMA_UNROLL+ for (uint quad = 0; quad < POOL_HIDDEN_MAX / 4u; ++quad) {+ value += dot(memory.pool_hidden[unit * (POOL_HIDDEN_MAX / 4u) + quad], hidden[quad]);+ }+ means[offset] = weight * value;+ peaks[offset] = valid ? value : -INFINITY;+ }+ const uint lane = context.simd_lane_id;+ const float mean = head_reduce<false, NODES_UNITS>(means, lane);+ const float peak = head_reduce<true, NODES_UNITS>(peaks, lane);+ const uint offset = (lane / (32u / NODES_UNITS)) % NODES_UNITS;+ if (lane % (32u / NODES_UNITS) == 0u && half_index * NODES_UNITS + offset < pool_hidden) {+ memory.reduce[(2 * context.simdgroup_index) * NODES_UNITS + offset] = mean;+ memory.reduce[(2 * context.simdgroup_index + 1) * NODES_UNITS + offset] = peak;+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);+ if (context.simdgroup_index < 2u * pool_hidden) {+ const bool is_mean = context.simdgroup_index < pool_hidden;+ const uint unit = context.simdgroup_index % pool_hidden;+ const uint groups = CANDIDATES_MAX / 32u;+ const uint group = unit / NODES_UNITS * groups + lane;+ const float part = lane < groups+ ? memory.reduce[(2 * group + (is_mean ? 0u : 1u)) * NODES_UNITS + unit % NODES_UNITS]+ : (is_mean ? 0.0f : -INFINITY);+ const float value = is_mean ? simd_sum(part) : simd_max(part);+ if (lane == 0u) {+ memory.summary[context.simdgroup_index] = value;+ }+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);+ head_dense(+ pool_out_weights,+ pool_out_biases,+ memory.summary,+ 0,+ memory.node,+ 0,+ 2u * pool_hidden,+ model_dim,+ 1,+ false,+ true,+ context+ );+ if (lid < model_dim) {+ nodes[slot * model_dim + lid] = bfloat(memory.node[lid]);+ node_inputs[slot * model_dim + lid] = bfloat(memory.node[lid]);+ }+}diff --git a/crates/uzu-engine/src/backends/metal/kernel/confidence_head/pools.metal b/crates/uzu-engine/src/backends/metal/kernel/confidence_head/pools.metalnew file mode 100644index 000000000..17f819bea--- /dev/null+++ b/crates/uzu-engine/src/backends/metal/kernel/confidence_head/pools.metal@@ -0,0 +1,41 @@+#include <metal_stdlib>+#include "../common/dsl.h"+#include "../rng.h"+#include "head.h"++using namespace metal;++struct PoolsMemory {+ float logits[HEAD_THREADS];+ float reduce[2u * HEAD_SIMDGROUPS];+};++PUBLIC KERNEL(ConfidenceHeadPools)(+ const device float* candidate_logits,+ const device uint* candidate_ids,+ const device uint64_t* depth_seeds,+ device float* pool_features,+ const constant ConfidenceHeadParams& params,+ const constant uint& depths,+ threadgroup PoolsMemory& memory,+ const ThreadContext context,+ const uint depth GROUPS(depths),+ const uint lid THREADS(HEAD_THREADS)+) {+ const uint candidates = params.candidates;+ const bool valid = lid < candidates;+ const float logit = valid ? candidate_logits[depth * candidates + lid] : -INFINITY;+ memory.logits[lid] = logit;+ const float log_sum = head_log_sum_exp(logit, memory.reduce, context);+ if (valid) {+ float rank = 0.0f;+ for (uint other = 0; other < candidates; ++other) {+ rank += memory.logits[other] > logit ? 1.0f : 0.0f;+ }+ device float* features = pool_features + depth * POOL_FEATURES * candidates;+ features[lid] = max(logit - log_sum, HEAD_LOG_PROB_FLOOR);+ features[candidates + lid] =+ target_gumbel_noise(depth_seeds[depth], candidate_ids[depth * candidates + lid], params.vocab_size);+ features[2 * candidates + lid] = log(1.0f + rank);+ }+}diff --git a/crates/uzu-engine/src/backends/metal/kernel/confidence_head/tree_attention.metal b/crates/uzu-engine/src/backends/metal/kernel/confidence_head/tree_attention.metalnew file mode 100644index 000000000..f66eeb1b6--- /dev/null+++ b/crates/uzu-engine/src/backends/metal/kernel/confidence_head/tree_attention.metal@@ -0,0 +1,86 @@+#include <metal_stdlib>+#include "../common/defines.h"+#include "../common/dsl.h"+#include "head.h"++using namespace metal;++#define QUADS_MAX 16u++struct TreeAttentionMemory {+ float weights[TREE_ROWS_MAX];+};++PUBLIC KERNEL(ConfidenceHeadTreeAttention)(+ const device bfloat* qkv,+ const device uint* relations,+ const device bfloat* relation_bias,+ device bfloat* output,+ const constant uint& rows,+ const uint num_heads SPECIALIZE,+ const uint head_dim SPECIALIZE,+ threadgroup TreeAttentionMemory& memory,+ const uint index GROUPS(rows* num_heads),+ const uint lane THREADS(METAL_SIMD_SIZE)+) {+ const uint query = index / num_heads;+ const uint head = index % num_heads;+ const uint width = num_heads * head_dim;+ const uint quads = head_dim / 4u;+ const device uint* relation = relations + query * rows;+ device bfloat* out = output + query * width + head * head_dim;+ if (relation[query] == HEAD_RELATION_ABSENT) {+ for (uint unit = lane; unit < head_dim; unit += METAL_SIMD_SIZE) {+ out[unit] = bfloat(0.0f);+ }+ return;+ }+ const float scale = rsqrt(float(head_dim));+ const device bfloat4* q = reinterpret_cast<const device bfloat4*>(qkv + query * 3 * width + head * head_dim);+ float4 query_values[QUADS_MAX];+ METAL_PRAGMA_UNROLL+ for (uint quad = 0; quad < QUADS_MAX; ++quad) {+ query_values[quad] = quad < quads ? float4(q[quad]) * scale : float4(0.0f);+ }++ float local_max = -INFINITY;+ for (uint key = lane; key < rows; key += METAL_SIMD_SIZE) {+ const uint code = relation[key];+ float score = -INFINITY;+ if (code != HEAD_RELATION_ABSENT) {+ const device bfloat4* k =+ reinterpret_cast<const device bfloat4*>(qkv + key * 3 * width + width + head * head_dim);+ score = code == 0 ? 0.0f : float(relation_bias[head * RELATIONS + code - 1]);+ METAL_PRAGMA_UNROLL+ for (uint quad = 0; quad < QUADS_MAX; ++quad) {+ score += quad < quads ? dot(query_values[quad], float4(k[quad])) : 0.0f;+ }+ }+ memory.weights[key] = score;+ local_max = max(local_max, score);+ }+ const float top = simd_max(local_max);+ float local_total = 0.0f;+ for (uint key = lane; key < rows; key += METAL_SIMD_SIZE) {+ const float weight = exp(memory.weights[key] - top);+ memory.weights[key] = weight;+ local_total += weight;+ }+ const float total = simd_sum(local_total);+ threadgroup_barrier(mem_flags::mem_threadgroup);++ const uint group = lane % quads;+ const uint split = lane / quads;+ const uint splits = METAL_SIMD_SIZE / quads;+ float4 value = 0.0f;+ const device bfloat* v = qkv + 2 * width + head * head_dim + 4 * group;+ for (uint key = split; key < rows; key += splits) {+ value += memory.weights[key] * float4(*reinterpret_cast<const device bfloat4*>(v + key * 3 * width));+ }+ for (uint offset = quads; offset < METAL_SIMD_SIZE; offset *= 2) {+ value += simd_shuffle_down(value, ushort(offset));+ }+ if (split == 0) {+ *reinterpret_cast<device bfloat4*>(out + 4 * group) = bfloat4(value / total);+ }+}diff --git a/crates/uzu-engine/src/backends/metal/kernel/confidence_head/tree_input.metal b/crates/uzu-engine/src/backends/metal/kernel/confidence_head/tree_input.metalnew file mode 100644index 000000000..59d8463aa--- /dev/null+++ b/crates/uzu-engine/src/backends/metal/kernel/confidence_head/tree_input.metal@@ -0,0 +1,34 @@+#include <metal_stdlib>+#include "../common/dsl.h"+#include "../weaver/weaver_frontier.h"+#include "head.h"++using namespace metal;++PUBLIC KERNEL(ConfidenceHeadTreeInput)(+ const device bfloat* depth_embedding,+ const device bfloat* child_in,+ const device bfloat* node_in,+ const device uint* frontier,+ const device uint* row_slots,+ device bfloat* output,+ const constant uint& rows,+ const constant uint& width,+ const uint index AXIS(rows* width, 256)+) {+ const uint row = index / width;+ const uint unit = index % width;+ const uint depth = row == 0 ? 0u : frontier[uint(FrontierIdx::Depth) * (rows - 1) + row - 1];+ float value = 0.0f;+ if (row == 0 || depth != 0) {+ value = float(depth_embedding[depth * width + unit]);+ if (row != 0) {+ value += float(child_in[(row - 1) * width + unit]);+ }+ const uint slot = row_slots[row];+ if (slot != HEAD_NONE) {+ value += float(node_in[slot * width + unit]);+ }+ }+ output[index] = bfloat(value);+}diff --git a/crates/uzu-engine/src/backends/metal/kernel/confidence_head/tree_relations.metal b/crates/uzu-engine/src/backends/metal/kernel/confidence_head/tree_relations.metalnew file mode 100644index 000000000..0bd19d0f5--- /dev/null+++ b/crates/uzu-engine/src/backends/metal/kernel/confidence_head/tree_relations.metal@@ -0,0 +1,60 @@+#include <metal_stdlib>+#include "../common/dsl.h"+#include "head.h"+#include "../weaver/weaver_frontier.h"++using namespace metal;++struct TreeRow {+ uint depth;+ uint parent;+ bool present;+};++METAL_FUNC TreeRow tree_row(const device uint* frontier, uint capacity, uint row) {+ if (row == 0) {+ return {0u, 0xffffffffu, true};+ }+ const uint depth = frontier[uint(FrontierIdx::Depth) * capacity + row - 1];+ return {depth, frontier[uint(FrontierIdx::ParentSlot) * capacity + row - 1], depth != 0};+}++METAL_FUNC uint tree_ancestor_row(+ const device uint* slot_ancestors,+ const device uint* slot_rows,+ TreeRow row,+ uint depth,+ uint ancestor_stride+) {+ return slot_rows[depth + 1 == row.depth ? row.parent : slot_ancestors[row.parent * ancestor_stride + depth]];+}++PUBLIC KERNEL(ConfidenceHeadTreeRelations)(+ const device uint* frontier,+ const device uint* slot_ancestors,+ const device uint* slot_rows,+ device uint* relations,+ const constant uint& rows,+ const constant uint& ancestor_stride,+ const uint index AXIS(rows* rows, 256)+) {+ const uint query = index / rows;+ const uint key = index % rows;+ const TreeRow query_row = tree_row(frontier, rows - 1, query);+ const TreeRow key_row = tree_row(frontier, rows - 1, key);+ uint relation = 0;+ if (!query_row.present || !key_row.present) {+ relation = HEAD_RELATION_ABSENT;+ } else if (query == key) {+ relation = 1;+ } else if (key_row.depth < query_row.depth &&+ tree_ancestor_row(slot_ancestors, slot_rows, query_row, key_row.depth, ancestor_stride) == key) {+ relation = key_row.depth + 1 == query_row.depth ? 2 : 4;+ } else if (query_row.depth < key_row.depth &&+ tree_ancestor_row(slot_ancestors, slot_rows, key_row, query_row.depth, ancestor_stride) == query) {+ relation = query_row.depth + 1 == key_row.depth ? 3 : 5;+ } else if (query_row.depth == key_row.depth && query_row.depth != 0 && query_row.parent == key_row.parent) {+ relation = 6;+ }+ relations[index] = relation;+}diff --git a/crates/uzu-engine/src/backends/metal/kernel/generated/confidence_head.h b/crates/uzu-engine/src/backends/metal/kernel/generated/confidence_head.hnew file mode 100644index 000000000..02d567e03--- /dev/null+++ b/crates/uzu-engine/src/backends/metal/kernel/generated/confidence_head.h@@ -0,0 +1,34 @@+// Auto-generated from gpu_types/confidence_head - do not edit manually+#pragma once++#include <metal_stdlib>+using namespace metal;++namespace uzu::confidence_head {+static constant constexpr uint32_t MODEL_MAX = 64;++static constant constexpr uint32_t POOL_HIDDEN_MAX = 16;++static constant constexpr uint32_t EDGE_HIDDEN_MAX = 128;++static constant constexpr uint32_t CHILDREN_MAX = 4;++static constant constexpr uint32_t SLOT_NUMBERS = 4;++static constant constexpr uint32_t POOL_FEATURES = 3;++static constant constexpr uint32_t POOL_INPUTS = 3;++static constant constexpr uint32_t RELATIONS = 6;++static constant constexpr uint32_t TREE_ROWS_MAX = 1024;++typedef struct {+ uint32_t candidates;+ uint32_t children;+ uint32_t tree_slot_count;+ uint32_t vocab_size;+ float logit_cap;+ float epsilon;+} ConfidenceHeadParams;+} // namespace uzu::confidence_headdiff --git a/crates/uzu-engine/src/backends/metal/kernel/rng.h b/crates/uzu-engine/src/backends/metal/kernel/rng.hindex adcdd9b6c..5daf62c5a 100644--- a/crates/uzu-engine/src/backends/metal/kernel/rng.h+++ b/crates/uzu-engine/src/backends/metal/kernel/rng.h@@ -1,6 +1,7 @@#pragma once#include <metal_stdlib>+#include "common/defines.h"/* ───────────── Philox4x32-10 RNG ───────────── */@@ -118,3 +119,30 @@ inline uint philox_next(thread PhiloxState* state) {inline float uniform_float(thread PhiloxState* state) {return float(metal::max(philox_next(state) >> 8, 1u)) * (1.0f / 16777216.0f);}++#define GUMBEL_THREADGROUP_SIZE 1024u+#define GUMBEL_WORDS_PER_OFFSET 4u++METAL_FUNC metal::uint2 gumbel_revidx(uint logit_idx, uint vocab_size) {+ const uint thread_idx = logit_idx % GUMBEL_THREADGROUP_SIZE;+ const uint thread_offset = div_ceil(vocab_size, GUMBEL_THREADGROUP_SIZE * GUMBEL_WORDS_PER_OFFSET) * thread_idx;+ const uint block_idx = logit_idx / GUMBEL_THREADGROUP_SIZE;+ return metal::uint2(thread_offset + block_idx / GUMBEL_WORDS_PER_OFFSET, block_idx % GUMBEL_WORDS_PER_OFFSET);+}++METAL_FUNC float gumbel_noise(uint64_t seed, uint logit_idx, uint vocab_size) {+ const metal::uint2 offset_word = gumbel_revidx(logit_idx, vocab_size);+ PhiloxState rng;+ philox_init(&rng, seed, offset_word.x);+ const float uniform = float(rng.output[offset_word.y]) * (1.0f / 4294967296.0f);+ return -metal::log(-metal::log(uniform));+}++// The noise the target sampler adds for this token: the 24-bit uniform of `uniform_float` keeps it finite.+METAL_FUNC float target_gumbel_noise(uint64_t seed, uint logit_idx, uint vocab_size) {+ const metal::uint2 offset_word = gumbel_revidx(logit_idx, vocab_size);+ PhiloxState rng;+ philox_init(&rng, seed, offset_word.x);+ const float uniform = float(metal::max(rng.output[offset_word.y] >> 8, 1u)) * (1.0f / 16777216.0f);+ return -metal::log(-metal::log(uniform));+}diff --git a/crates/uzu-engine/src/backends/metal/kernel/weaver/weaver_selection.metal b/crates/uzu-engine/src/backends/metal/kernel/weaver/weaver_selection.metalindex 92d7784ab..7ed52fed0 100644--- a/crates/uzu-engine/src/backends/metal/kernel/weaver/weaver_selection.metal+++ b/crates/uzu-engine/src/backends/metal/kernel/weaver/weaver_selection.metal@@ -9,33 +9,6 @@using namespace metal;-#define GUMBEL_THREADGROUP_SIZE 1024u-#define GUMBEL_WORDS_PER_OFFSET 4u--METAL_FUNC uint2 gumbel_revidx(uint logit_idx, uint vocab_size) {- const uint thread_idx = logit_idx % GUMBEL_THREADGROUP_SIZE;- const uint thread_offset = div_ceil(vocab_size, GUMBEL_THREADGROUP_SIZE * GUMBEL_WORDS_PER_OFFSET) * thread_idx;- const uint block_idx = logit_idx / GUMBEL_THREADGROUP_SIZE;- return uint2(thread_offset + block_idx / GUMBEL_WORDS_PER_OFFSET, block_idx % GUMBEL_WORDS_PER_OFFSET);-}--METAL_FUNC float gumbel_noise(uint64_t seed, uint logit_idx, uint vocab_size) {- const uint2 offset_word = gumbel_revidx(logit_idx, vocab_size);- PhiloxState rng;- philox_init(&rng, seed, offset_word.x);- const float uniform = float(rng.output[offset_word.y]) * (1.0f / 4294967296.0f);- return -log(-log(uniform));-}--// The noise the target sampler adds for this token: the 24-bit uniform of `uniform_float` in rng.h keeps it finite.-METAL_FUNC float target_gumbel_noise(uint64_t seed, uint logit_idx, uint vocab_size) {- const uint2 offset_word = gumbel_revidx(logit_idx, vocab_size);- PhiloxState rng;- philox_init(&rng, seed, offset_word.x);- const float uniform = float(max(rng.output[offset_word.y] >> 8, 1u)) * (1.0f / 16777216.0f);- return -log(-log(uniform));-}-METAL_FUNC bool weaver_better(uint score, uint token, uint index, uint best_score, uint best_token, uint best_index) {return score > best_score ||(score == best_score && (token < best_token || (token == best_token && index < best_index)));diff --git a/crates/uzu-engine/src/backends/slang/kernel/confidence_head/edges.slang b/crates/uzu-engine/src/backends/slang/kernel/confidence_head/edges.slangnew file mode 100644index 000000000..8d9a9c094--- /dev/null+++ b/crates/uzu-engine/src/backends/slang/kernel/confidence_head/edges.slang@@ -0,0 +1,44 @@+// Autogenerated stub+import definitions;+import generated.confidence_head;++[[Public]] [[Kernel]] func ConfidenceHeadEdges(+ [[Optional("!refine")]] StructuredBuffer<uint> node_metadata,+ [[Optional("!refine")]] StructuredBuffer<uint> node_valid,+ [[Optional("!refine")]] StructuredBuffer<uint> candidate_ids,+ [[Optional("!refine")]] StructuredBuffer<float> pool_features,+ [[Optional("!refine")]] StructuredBuffer<BFloat16> slot_stats,+ RWStructuredBuffer<uint> slot_rows,+ [[Optional("!refine")]] RWStructuredBuffer<uint> row_slots,+ StructuredBuffer<BFloat16> nodes,+ [[Optional("refine")]] StructuredBuffer<BFloat16> node_shifts,+ [[Optional("refine")]] StructuredBuffer<BFloat16> child_shifts,+ StructuredBuffer<BFloat16> token_features,+ RWStructuredBuffer<float> child_numbers,+ RWStructuredBuffer<uint> child_pools,+ StructuredBuffer<float> scores,+ RWStructuredBuffer<uint> frontier,+ RWStructuredBuffer<uint> packed_tree,+ [[Optional("!refine")]] RWStructuredBuffer<BFloat16> child_inputs,+ StructuredBuffer<BFloat16> input_norm,+ StructuredBuffer<BFloat16> entry_weights,+ StructuredBuffer<BFloat16> entry_biases,+ StructuredBuffer<BFloat16> block_norm,+ StructuredBuffer<BFloat16> up_weights,+ StructuredBuffer<BFloat16> up_biases,+ StructuredBuffer<BFloat16> down_weights,+ StructuredBuffer<BFloat16> down_biases,+ StructuredBuffer<BFloat16> final_norm,+ StructuredBuffer<BFloat16> readout_weights,+ StructuredBuffer<BFloat16> readout_biases,+ ConfidenceHeadParams params,+ uint groups,+ [[Specialize]] uint model_dim,+ [[Specialize]] uint edge_hidden,+ [[Specialize]] bool refine,+ ThreadContext context,+ [[Groups("groups")]] uint group,+ [[Threads("512")]] uint lid,+) {+ // TODO+}diff --git a/crates/uzu-engine/src/backends/slang/kernel/confidence_head/nodes.slang b/crates/uzu-engine/src/backends/slang/kernel/confidence_head/nodes.slangnew file mode 100644index 000000000..909d5391c--- /dev/null+++ b/crates/uzu-engine/src/backends/slang/kernel/confidence_head/nodes.slang@@ -0,0 +1,30 @@+// Autogenerated stub+import definitions;+import generated.confidence_head;++[[Public]] [[Kernel]] func ConfidenceHeadNodes(+ StructuredBuffer<BFloat16> residual_logits,+ StructuredBuffer<float> candidate_logits,+ StructuredBuffer<float> pool_features,+ StructuredBuffer<uint> round_metadata,+ StructuredBuffer<uint> round_valid,+ StructuredBuffer<BFloat16> draft,+ StructuredBuffer<BFloat16> pool_entry_weights,+ StructuredBuffer<BFloat16> pool_entry_biases,+ StructuredBuffer<BFloat16> pool_hidden_weights,+ StructuredBuffer<BFloat16> pool_hidden_biases,+ StructuredBuffer<BFloat16> pool_out_weights,+ StructuredBuffer<BFloat16> pool_out_biases,+ RWStructuredBuffer<float> scores,+ RWStructuredBuffer<BFloat16> nodes,+ RWStructuredBuffer<BFloat16> node_inputs,+ ConfidenceHeadParams params,+ uint rows,+ [[Specialize]] uint model_dim,+ [[Specialize]] uint pool_hidden,+ ThreadContext context,+ [[Groups("rows")]] uint row,+ [[Threads("1024")]] uint lid,+) {+ // TODO+}diff --git a/crates/uzu-engine/src/backends/slang/kernel/confidence_head/pools.slang b/crates/uzu-engine/src/backends/slang/kernel/confidence_head/pools.slangnew file mode 100644index 000000000..0ad2f2fce--- /dev/null+++ b/crates/uzu-engine/src/backends/slang/kernel/confidence_head/pools.slang@@ -0,0 +1,17 @@+// Autogenerated stub+import definitions;+import generated.confidence_head;++[[Public]] [[Kernel]] func ConfidenceHeadPools(+ StructuredBuffer<float> candidate_logits,+ StructuredBuffer<uint> candidate_ids,+ StructuredBuffer<uint64_t> depth_seeds,+ RWStructuredBuffer<float> pool_features,+ ConfidenceHeadParams params,+ uint depths,+ ThreadContext context,+ [[Groups("depths")]] uint depth,+ [[Threads("512")]] uint lid,+) {+ // TODO+}diff --git a/crates/uzu-engine/src/backends/slang/kernel/confidence_head/tree_attention.slang b/crates/uzu-engine/src/backends/slang/kernel/confidence_head/tree_attention.slangnew file mode 100644index 000000000..dd90d2273--- /dev/null+++ b/crates/uzu-engine/src/backends/slang/kernel/confidence_head/tree_attention.slang@@ -0,0 +1,16 @@+// Autogenerated stub+import definitions;++[[Public]] [[Kernel]] func ConfidenceHeadTreeAttention(+ StructuredBuffer<BFloat16> qkv,+ StructuredBuffer<uint> relations,+ StructuredBuffer<BFloat16> relation_bias,+ RWStructuredBuffer<BFloat16> output,+ uint rows,+ [[Specialize]] uint num_heads,+ [[Specialize]] uint head_dim,+ [[Groups("rows * num_heads")]] uint index,+ [[Threads("32")]] uint lane,+) {+ // TODO+}diff --git a/crates/uzu-engine/src/backends/slang/kernel/confidence_head/tree_input.slang b/crates/uzu-engine/src/backends/slang/kernel/confidence_head/tree_input.slangnew file mode 100644index 000000000..058f26d1b--- /dev/null+++ b/crates/uzu-engine/src/backends/slang/kernel/confidence_head/tree_input.slang@@ -0,0 +1,16 @@+// Autogenerated stub+import definitions;++[[Public]] [[Kernel]] func ConfidenceHeadTreeInput(+ StructuredBuffer<BFloat16> depth_embedding,+ StructuredBuffer<BFloat16> child_in,+ StructuredBuffer<BFloat16> node_in,+ StructuredBuffer<uint> frontier,+ StructuredBuffer<uint> row_slots,+ RWStructuredBuffer<BFloat16> output,+ uint rows,+ uint width,+ [[Axis("rows * width", "256")]] uint index,+) {+ // TODO+}diff --git a/crates/uzu-engine/src/backends/slang/kernel/confidence_head/tree_relations.slang b/crates/uzu-engine/src/backends/slang/kernel/confidence_head/tree_relations.slangnew file mode 100644index 000000000..03722733c--- /dev/null+++ b/crates/uzu-engine/src/backends/slang/kernel/confidence_head/tree_relations.slang@@ -0,0 +1,14 @@+// Autogenerated stub+import definitions;++[[Public]] [[Kernel]] func ConfidenceHeadTreeRelations(+ StructuredBuffer<uint> frontier,+ StructuredBuffer<uint> slot_ancestors,+ StructuredBuffer<uint> slot_rows,+ RWStructuredBuffer<uint> relations,+ uint rows,+ uint ancestor_stride,+ [[Axis("rows * rows", "256")]] uint index,+) {+ // TODO+}diff --git a/crates/uzu-engine/src/backends/slang/kernel/generated/confidence_head.slang b/crates/uzu-engine/src/backends/slang/kernel/generated/confidence_head.slangnew file mode 100644index 000000000..09f0f88e6--- /dev/null+++ b/crates/uzu-engine/src/backends/slang/kernel/generated/confidence_head.slang@@ -0,0 +1,26 @@+static const uint MODEL_MAX = 64;++static const uint POOL_HIDDEN_MAX = 16;++static const uint EDGE_HIDDEN_MAX = 128;++static const uint CHILDREN_MAX = 4;++static const uint SLOT_NUMBERS = 4;++static const uint POOL_FEATURES = 3;++static const uint POOL_INPUTS = 3;++static const uint RELATIONS = 6;++static const uint TREE_ROWS_MAX = 1024;++struct ConfidenceHeadParams {+ uint candidates;+ uint children;+ uint tree_slot_count;+ uint vocab_size;+ float logit_cap;+ float epsilon;+};\ No newline at end of filediff --git a/crates/uzu-engine/src/config/confidence_head.rs b/crates/uzu-engine/src/config/confidence_head.rsnew file mode 100644index 000000000..2653073ec--- /dev/null+++ b/crates/uzu-engine/src/config/confidence_head.rs@@ -0,0 +1,16 @@+use uzu_engine_macros::uzu_config;++use crate::config::{+ confidence_head_tree_attention::ConfidenceHeadTreeAttentionConfig, normalization::NormalizationConfig,+};++#[uzu_config]+pub struct ConfidenceHeadConfig {+ pub model_dim: u32,+ pub pool_hidden_dim: u32,+ pub edge_hidden_dim: u32,+ pub logit_cap: f32,+ pub max_depth: u32,+ pub norm_config: NormalizationConfig,+ pub tree_attention_config: Option<ConfidenceHeadTreeAttentionConfig>,+}diff --git a/crates/uzu-engine/src/config/confidence_head_tree_attention.rs b/crates/uzu-engine/src/config/confidence_head_tree_attention.rsnew file mode 100644index 000000000..c73bf5037--- /dev/null+++ b/crates/uzu-engine/src/config/confidence_head_tree_attention.rs@@ -0,0 +1,9 @@+use uzu_engine_macros::uzu_config;++#[uzu_config]+pub struct ConfidenceHeadTreeAttentionConfig {+ pub model_dim: u32,+ pub num_layers: u32,+ pub num_heads: u32,+ pub hidden_dim: u32,+}diff --git a/crates/uzu-engine/src/config/mod.rs b/crates/uzu-engine/src/config/mod.rsindex 91d66c95a..7d60d3c95 100644--- a/crates/uzu-engine/src/config/mod.rs+++ b/crates/uzu-engine/src/config/mod.rs@@ -1,6 +1,8 @@pub mod activation;pub mod classifier;pub mod clipping;+pub mod confidence_head;+pub mod confidence_head_tree_attention;pub mod decoder;pub mod dflash;pub mod embedding;diff --git a/crates/uzu-engine/src/config/speculator/dflash.rs b/crates/uzu-engine/src/config/speculator/dflash.rsindex 833f7d476..df08ef220 100644--- a/crates/uzu-engine/src/config/speculator/dflash.rs+++ b/crates/uzu-engine/src/config/speculator/dflash.rs@@ -1,9 +1,11 @@use uzu_engine_macros::uzu_config;-use crate::config::{dflash::DFlashDraftConfig, weaver::WeaverConfig};+use crate::config::{confidence_head::ConfidenceHeadConfig, dflash::DFlashDraftConfig, weaver::WeaverConfig};#[uzu_config(super::SpeculatorConfig)]pub struct DFlashSpeculatorConfig {pub draft_config: DFlashDraftConfig,pub weaver_config: Option<WeaverConfig>,+ #[serde(default)]+ pub confidence_head_config: Option<ConfidenceHeadConfig>,}diff --git a/crates/uzu-engine/src/encodable_block/confidence_head/edges.rs b/crates/uzu-engine/src/encodable_block/confidence_head/edges.rsnew file mode 100644index 000000000..a4a8bfed2--- /dev/null+++ b/crates/uzu-engine/src/encodable_block/confidence_head/edges.rs@@ -0,0 +1,133 @@+use crate::{+ backends::common::{+ Backend, BufferMut, BufferRef, CommandBuffer, Kernels,+ gpu_types::confidence_head::{ConfidenceHeadParams, SLOT_NUMBERS},+ kernel::ConfidenceHeadEdgesKernel,+ },+ config::confidence_head::ConfidenceHeadConfig,+ encodable_block::confidence_head::{ConfidenceHeadError, DATA_TYPE},+ safetensors::ParameterTree,+};++pub struct Edges<B: Backend> {+ steer: <B::Kernels as Kernels>::ConfidenceHeadEdgesKernel,+ refine: <B::Kernels as Kernels>::ConfidenceHeadEdgesKernel,+ slot_stats: B::GlobalGpuBuffer,+ input_norm: B::GlobalGpuBuffer,+ entry_weights: B::GlobalGpuBuffer,+ entry_biases: B::GlobalGpuBuffer,+ block_norm: B::GlobalGpuBuffer,+ up_weights: B::GlobalGpuBuffer,+ up_biases: B::GlobalGpuBuffer,+ down_weights: B::GlobalGpuBuffer,+ down_biases: B::GlobalGpuBuffer,+ final_norm: B::GlobalGpuBuffer,+ readout_weights: B::GlobalGpuBuffer,+ readout_biases: B::GlobalGpuBuffer,+}++impl<B: Backend> Edges<B> {+ pub async fn new(+ config: &ConfidenceHeadConfig,+ parameter_tree: &ParameterTree<'_, B>,+ context: &B::Context,+ ) -> Result<Self, ConfidenceHeadError<B>> {+ let (width, hidden) = (config.model_dim, config.edge_hidden_dim);+ let inputs = 3 * width + SLOT_NUMBERS;+ let kernel = |refine| {+ <B::Kernels as Kernels>::ConfidenceHeadEdgesKernel::new(context, width, hidden, refine)+ .map_err(ConfidenceHeadError::Backend)+ };+ let slot_stats = parameter_tree.read_buffer("slot.stats", &[2, SLOT_NUMBERS], DATA_TYPE).await?;+ let input_norm = parameter_tree.read_buffer("edge.input_norm", &[2, inputs], DATA_TYPE).await?;+ let entry_weights = parameter_tree.read_buffer("edge.entry.weights", &[width, inputs], DATA_TYPE).await?;+ let entry_biases = parameter_tree.read_buffer("edge.entry.biases", &[width], DATA_TYPE).await?;+ let block_norm = parameter_tree.read_buffer("edge.block_norm", &[2, width], DATA_TYPE).await?;+ let up_weights = parameter_tree.read_buffer("edge.up.weights", &[hidden, width], DATA_TYPE).await?;+ let up_biases = parameter_tree.read_buffer("edge.up.biases", &[hidden], DATA_TYPE).await?;+ let down_weights = parameter_tree.read_buffer("edge.down.weights", &[width, hidden], DATA_TYPE).await?;+ let down_biases = parameter_tree.read_buffer("edge.down.biases", &[width], DATA_TYPE).await?;+ let final_norm = parameter_tree.read_buffer("edge.final_norm", &[2, width], DATA_TYPE).await?;+ let readout_weights = parameter_tree.read_buffer("edge.readout.weights", &[3, width], DATA_TYPE).await?;+ let readout_biases = parameter_tree.read_buffer("edge.readout.biases", &[3], DATA_TYPE).await?;+ Ok(Self {+ slot_stats,+ input_norm,+ entry_weights,+ entry_biases,+ block_norm,+ up_weights,+ up_biases,+ down_weights,+ down_biases,+ final_norm,+ readout_weights,+ readout_biases,+ steer: kernel(false)?,+ refine: kernel(true)?,+ })+ }++ pub fn encode(+ &self,+ node_metadata: Option<impl BufferRef<Backend = B>>,+ node_valid: Option<impl BufferRef<Backend = B>>,+ candidate_ids: Option<impl BufferRef<Backend = B>>,+ pool_features: Option<impl BufferRef<Backend = B>>,+ slot_rows: impl BufferMut<Backend = B>,+ row_slots: Option<impl BufferMut<Backend = B>>,+ nodes: impl BufferRef<Backend = B>,+ node_shifts: Option<impl BufferRef<Backend = B>>,+ child_shifts: Option<impl BufferRef<Backend = B>>,+ token_features: impl BufferRef<Backend = B>,+ child_numbers: impl BufferMut<Backend = B>,+ child_pools: impl BufferMut<Backend = B>,+ scores: impl BufferRef<Backend = B>,+ frontier: impl BufferMut<Backend = B>,+ packed_tree: impl BufferMut<Backend = B>,+ child_inputs: Option<impl BufferMut<Backend = B>>,+ params: ConfidenceHeadParams,+ groups: u32,+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,+ ) {+ let refine = node_shifts.is_some();+ let kernel = if refine {+ &self.refine+ } else {+ &self.steer+ };+ kernel.encode(+ node_metadata,+ node_valid,+ candidate_ids,+ pool_features,+ (!refine).then_some(&self.slot_stats),+ slot_rows,+ row_slots,+ nodes,+ node_shifts,+ child_shifts,+ token_features,+ child_numbers,+ child_pools,+ scores,+ frontier,+ packed_tree,+ child_inputs,+ &self.input_norm,+ &self.entry_weights,+ &self.entry_biases,+ &self.block_norm,+ &self.up_weights,+ &self.up_biases,+ &self.down_weights,+ &self.down_biases,+ &self.final_norm,+ &self.readout_weights,+ &self.readout_biases,+ params,+ groups,+ command_buffer,+ );+ }+}diff --git a/crates/uzu-engine/src/encodable_block/confidence_head/error.rs b/crates/uzu-engine/src/encodable_block/confidence_head/error.rsnew file mode 100644index 000000000..9b1402172--- /dev/null+++ b/crates/uzu-engine/src/encodable_block/confidence_head/error.rs@@ -0,0 +1,30 @@+use derive_more::Debug;+use thiserror::Error;++use crate::{+ backends::common::Backend,+ encodable_block::{+ embedding::EmbeddingError,+ linear::{LinearBlockError, LinearEncodeError},+ normalization::NormalizationNewError,+ },+ safetensors::ParameterLoaderError,+};++#[derive(Debug, Error)]+pub enum ConfidenceHeadError<B: Backend> {+ #[error("backend error: {0}")]+ Backend(#[source] B::Error),+ #[error("parameter error: {0}")]+ Parameter(#[from] ParameterLoaderError<B>),+ #[error("normalization error: {0}")]+ Normalization(#[from] NormalizationNewError<B>),+ #[error("linear error: {0}")]+ Linear(#[from] LinearBlockError<B>),+ #[error("linear encode error: {0}")]+ LinearEncode(#[from] LinearEncodeError<B>),+ #[error("embedding error: {0}")]+ Embedding(#[from] EmbeddingError<B>),+ #[error("the kernels do not support {0}")]+ UnsupportedShape(String),+}diff --git a/crates/uzu-engine/src/encodable_block/confidence_head/head.rs b/crates/uzu-engine/src/encodable_block/confidence_head/head.rsnew file mode 100644index 000000000..2d5d54bac--- /dev/null+++ b/crates/uzu-engine/src/encodable_block/confidence_head/head.rs@@ -0,0 +1,358 @@+use crate::{+ backends::common::{+ Backend, BufferMut, BufferRef, CommandBuffer, CommandBufferEncoding, CommandBufferExecutable,+ CommandBufferPending, Context, Kernels,+ gpu_types::{+ confidence_head::{+ CHILDREN_MAX, ConfidenceHeadParams, EDGE_HIDDEN_MAX, MODEL_MAX, POOL_FEATURES, POOL_HIDDEN_MAX,+ SLOT_NUMBERS,+ },+ weaver::{CANDIDATES_MAX, MetadataIdx},+ },+ kernel::ConfidenceHeadPoolsKernel,+ },+ config::confidence_head::ConfidenceHeadConfig,+ data_type::DataType,+ encodable_block::{+ confidence_head::{ConfidenceHeadError, DATA_TYPE, Edges, Nodes, TreeAttention},+ embedding::Embedding,+ linear::Linear,+ normalization::{Normalization, PostLayerScalar, ShortcutMode},+ },+ safetensors::ParameterTree,+ utils::size_for_shape::size_for_shape,+};++const TOKEN_CHUNK: u32 = 2048;++pub struct ConfidenceHeadStep<B: Backend> {+ draft: B::ScratchBuffer,+ pool_features: B::ScratchBuffer,+ scores: B::ScratchBuffer,+ nodes: B::ScratchBuffer,+ node_inputs: B::ScratchBuffer,+ child_inputs: B::ScratchBuffer,+ child_pools: B::ScratchBuffer,+ child_numbers: B::ScratchBuffer,+ slot_rows: B::ScratchBuffer,+ row_slots: B::ScratchBuffer,+ round_metadata: B::ScratchBuffer,+ round_valid: B::ScratchBuffer,+ params: ConfidenceHeadParams,+}++pub struct ConfidenceHead<B: Backend> {+ config: ConfidenceHeadConfig,+ draft_norm: Normalization<B>,+ draft_projection: Box<dyn Linear<B>>,+ token_features: B::GlobalGpuBuffer,+ pools: <B::Kernels as Kernels>::ConfidenceHeadPoolsKernel,+ nodes: Nodes<B>,+ edges: Edges<B>,+ tree_attention: Option<TreeAttention<B>>,+}++impl<B: Backend> ConfidenceHead<B> {+ pub async fn new(+ config: &ConfidenceHeadConfig,+ parameter_tree: &ParameterTree<'_, B>,+ target_embedding: &Embedding<B>,+ tree_depth: u32,+ context: &B::Context,+ ) -> Result<Self, ConfidenceHeadError<B>> {+ let width = config.model_dim;+ if width > MODEL_MAX+ || config.pool_hidden_dim > POOL_HIDDEN_MAX+ || config.edge_hidden_dim > EDGE_HIDDEN_MAX+ || !width.is_multiple_of(4)+ || !config.pool_hidden_dim.is_multiple_of(2)+ || !config.edge_hidden_dim.is_multiple_of(4)+ || config.max_depth < tree_depth+ {+ return Err(ConfidenceHeadError::UnsupportedShape(format!(+ "width {width}, pool width {}, edge width {} and depth {} for trees of depth {tree_depth}",+ config.pool_hidden_dim, config.edge_hidden_dim, config.max_depth+ )));+ }+ let target_dim = target_embedding.model_dim();+ let norm_config = &config.norm_config;+ let draft_norm = Normalization::new(+ target_dim,+ DATA_TYPE,+ DATA_TYPE,+ None,+ ShortcutMode::None,+ PostLayerScalar::None,+ norm_config,+ ¶meter_tree.subtree("draft_norm"),+ context,+ )+ .await?;+ let draft_projection = <dyn Linear<B>>::new(+ target_dim,+ width,+ DATA_TYPE,+ true,+ ¶meter_tree.subtree("draft_projection"),+ context,+ )+ .await?;+ let token_norm = Normalization::new(+ target_dim,+ DATA_TYPE,+ DATA_TYPE,+ None,+ ShortcutMode::None,+ PostLayerScalar::None,+ norm_config,+ ¶meter_tree.subtree("token_norm"),+ context,+ )+ .await?;+ let token_projection = <dyn Linear<B>>::new(+ target_dim,+ width,+ DATA_TYPE,+ true,+ ¶meter_tree.subtree("token_projection"),+ context,+ )+ .await?;+ let token_features =+ encode_token_features(&token_norm, &*token_projection, target_embedding, width, context).await?;+ let nodes = Nodes::new(config, parameter_tree, context).await?;+ let edges = Edges::new(config, parameter_tree, context).await?;+ let tree_attention = match &config.tree_attention_config {+ Some(tree_config) => {+ Some(TreeAttention::new(config, tree_config, ¶meter_tree.subtree("tree"), context).await?)+ },+ None => None,+ };+ Ok(Self {+ config: config.clone(),+ draft_norm,+ draft_projection,+ token_features,+ nodes,+ edges,+ tree_attention,+ pools: <B::Kernels as Kernels>::ConfidenceHeadPoolsKernel::new(context)+ .map_err(ConfidenceHeadError::Backend)?,+ })+ }++ pub fn encode_step(+ &self,+ draft_hidden: impl BufferRef<Backend = B>,+ candidate_logits: impl BufferRef<Backend = B>,+ candidate_ids: impl BufferRef<Backend = B>,+ depth_seeds: impl BufferRef<Backend = B>,+ depths: u32,+ candidates: u32,+ children: u32,+ tree_slot_count: u32,+ vocab_size: u32,+ round_rows: u32,+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,+ ) -> Result<ConfidenceHeadStep<B>, ConfidenceHeadError<B>> {+ let params = ConfidenceHeadParams {+ candidates,+ children,+ tree_slot_count,+ vocab_size,+ logit_cap: self.config.logit_cap,+ epsilon: self.config.norm_config.epsilon,+ };+ if candidates > CANDIDATES_MAX || children > CHILDREN_MAX {+ return Err(ConfidenceHeadError::UnsupportedShape(format!(+ "{} candidates and {} children",+ params.candidates, params.children+ )));+ }+ let normalized = self+ .draft_norm+ .encode(draft_hidden, 1, depths, None::<&mut B::ScratchBuffer>, command_buffer)+ .map_err(ConfidenceHeadError::Backend)?;+ let draft = self.draft_projection.encode(normalized, depths, command_buffer)?;+ let (slots, width) = (params.tree_slot_count, self.config.model_dim);+ let entries = slots * params.children;+ let mut scratch = |shape: &[u32], data_type: DataType| {+ command_buffer.allocate_scratch_for_shape(shape, data_type).map_err(ConfidenceHeadError::Backend)+ };+ let mut pool_features = scratch(&[depths, POOL_FEATURES, params.candidates], DataType::F32)?;+ let scores = scratch(&[slots, 2, params.candidates], DataType::F32)?;+ let nodes = scratch(&[slots, width], DATA_TYPE)?;+ let node_inputs = scratch(&[slots, width], DATA_TYPE)?;+ let child_inputs = scratch(&[entries, width + SLOT_NUMBERS], DATA_TYPE)?;+ let child_pools = scratch(&[entries], DataType::U32)?;+ let child_numbers = scratch(&[entries, SLOT_NUMBERS], DataType::F32)?;+ let mut slot_rows = scratch(&[slots], DataType::U32)?;+ let mut row_slots = scratch(&[1 + entries], DataType::U32)?;+ let round_metadata = scratch(&[MetadataIdx::COUNT as u32, round_rows], DataType::U32)?;+ let round_valid = scratch(&[round_rows], DataType::U32)?;+ command_buffer.encode_fill(&mut slot_rows, 0xff);+ command_buffer.encode_fill(&mut row_slots, 0xff);+ self.pools.encode(+ candidate_logits,+ candidate_ids,+ depth_seeds,+ &mut pool_features,+ params,+ depths,+ command_buffer,+ );+ Ok(ConfidenceHeadStep {+ draft,+ pool_features,+ scores,+ nodes,+ node_inputs,+ child_inputs,+ child_pools,+ child_numbers,+ slot_rows,+ row_slots,+ round_metadata,+ round_valid,+ params,+ })+ }++ pub fn encode_rows(+ &self,+ step: &mut ConfidenceHeadStep<B>,+ node_metadata: impl BufferRef<Backend = B>,+ node_valid: impl BufferRef<Backend = B>,+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,+ ) {+ command_buffer.encode_copy(node_metadata, &mut step.round_metadata);+ command_buffer.encode_copy(node_valid, &mut step.round_valid);+ }++ pub fn encode_round(+ &self,+ step: &mut ConfidenceHeadStep<B>,+ residual_logits: impl BufferRef<Backend = B>,+ candidate_logits: impl BufferRef<Backend = B>,+ candidate_ids: impl BufferRef<Backend = B>,+ packed_tree: impl BufferMut<Backend = B>,+ frontier: impl BufferMut<Backend = B>,+ rows: u32,+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,+ ) {+ self.nodes.encode(+ residual_logits,+ candidate_logits,+ &step.pool_features,+ &step.round_metadata,+ &step.round_valid,+ &step.draft,+ &mut step.scores,+ &mut step.nodes,+ &mut step.node_inputs,+ step.params,+ rows,+ command_buffer,+ );+ self.edges.encode(+ Some(&step.round_metadata),+ Some(&step.round_valid),+ Some(candidate_ids),+ Some(&step.pool_features),+ &mut step.slot_rows,+ Some(&mut step.row_slots),+ &step.nodes,+ None::<&B::ScratchBuffer>,+ None::<&B::ScratchBuffer>,+ &self.token_features,+ &mut step.child_numbers,+ &mut step.child_pools,+ &step.scores,+ frontier,+ packed_tree,+ Some(&mut step.child_inputs),+ step.params,+ rows,+ command_buffer,+ );+ }++ pub fn encode_prune(+ &self,+ mut step: ConfidenceHeadStep<B>,+ mut packed_tree: impl BufferMut<Backend = B>,+ mut frontier: impl BufferMut<Backend = B>,+ slot_ancestors: impl BufferRef<Backend = B>,+ ancestor_stride: u32,+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,+ ) -> Result<(), ConfidenceHeadError<B>> {+ let Some(tree_attention) = &self.tree_attention else {+ return Ok(());+ };+ let slots = step.params.tree_slot_count;+ let (node_shifts, child_shifts) = tree_attention.encode(+ step.node_inputs,+ step.child_inputs,+ frontier.as_ref(),+ &step.row_slots,+ &step.slot_rows,+ slot_ancestors,+ ancestor_stride,+ slots,+ 1 + slots * step.params.children,+ command_buffer,+ )?;+ self.edges.encode(+ None::<&B::ScratchBuffer>,+ None::<&B::ScratchBuffer>,+ None::<&B::ScratchBuffer>,+ None::<&B::ScratchBuffer>,+ &mut step.slot_rows,+ None::<&mut B::ScratchBuffer>,+ &step.nodes,+ Some(&node_shifts),+ Some(&child_shifts),+ &self.token_features,+ &mut step.child_numbers,+ &mut step.child_pools,+ &step.scores,+ frontier.reborrow(),+ packed_tree.reborrow(),+ None::<&mut B::ScratchBuffer>,+ step.params,+ slots,+ command_buffer,+ );+ Ok(())+ }+}++async fn encode_token_features<B: Backend>(+ token_norm: &Normalization<B>,+ token_projection: &dyn Linear<B>,+ target_embedding: &Embedding<B>,+ width: u32,+ context: &B::Context,+) -> Result<B::GlobalGpuBuffer, ConfidenceHeadError<B>> {+ let vocab_size = target_embedding.vocab_size();+ let row_bytes = size_for_shape(&[width], DATA_TYPE);+ let mut table = context.create_buffer_gpu(vocab_size as usize * row_bytes).map_err(ConfidenceHeadError::Backend)?;+ for start in (0..vocab_size).step_by(TOKEN_CHUNK as usize) {+ let count = TOKEN_CHUNK.min(vocab_size - start);+ let mut command_buffer = context+ .create_command_buffer(Some("confidence head tokens"), None)+ .map_err(ConfidenceHeadError::Backend)?;+ let ids = (start..start + count).collect::<Box<[u32]>>();+ let ids = command_buffer.allocate_constant_from_slice(&ids).map_err(ConfidenceHeadError::Backend)?;+ let rows = target_embedding.encode_lookup(&ids, count, &mut command_buffer)?;+ drop(ids);+ let normalized = token_norm+ .encode(&rows, 0, count, None::<&mut B::ScratchBuffer>, &mut command_buffer)+ .map_err(ConfidenceHeadError::Backend)?;+ let projected = token_projection.encode(normalized, count, &mut command_buffer)?;+ let range = start as usize * row_bytes..(start + count) as usize * row_bytes;+ command_buffer.encode_copy(&projected, (&mut table).subrange_mut(range));+ command_buffer.end_encoding().submit().wait_until_completed().await.map_err(ConfidenceHeadError::Backend)?;+ }+ Ok(table)+}diff --git a/crates/uzu-engine/src/encodable_block/confidence_head/mod.rs b/crates/uzu-engine/src/encodable_block/confidence_head/mod.rsnew file mode 100644index 000000000..be359cd4f--- /dev/null+++ b/crates/uzu-engine/src/encodable_block/confidence_head/mod.rs@@ -0,0 +1,15 @@+mod edges;+mod error;+mod head;+mod nodes;+mod tree_attention;++use edges::Edges;+pub use error::ConfidenceHeadError;+pub use head::{ConfidenceHead, ConfidenceHeadStep};+use nodes::Nodes;+use tree_attention::TreeAttention;++use crate::data_type::DataType;++const DATA_TYPE: DataType = DataType::BF16;diff --git a/crates/uzu-engine/src/encodable_block/confidence_head/nodes.rs b/crates/uzu-engine/src/encodable_block/confidence_head/nodes.rsnew file mode 100644index 000000000..a5b634ca7--- /dev/null+++ b/crates/uzu-engine/src/encodable_block/confidence_head/nodes.rs@@ -0,0 +1,86 @@+use crate::{+ backends::common::{+ Backend, BufferMut, BufferRef, CommandBuffer, Kernels,+ gpu_types::confidence_head::{ConfidenceHeadParams, POOL_INPUTS},+ kernel::ConfidenceHeadNodesKernel,+ },+ config::confidence_head::ConfidenceHeadConfig,+ encodable_block::confidence_head::{ConfidenceHeadError, DATA_TYPE},+ safetensors::ParameterTree,+};++pub struct Nodes<B: Backend> {+ kernel: <B::Kernels as Kernels>::ConfidenceHeadNodesKernel,+ pool_entry_weights: B::GlobalGpuBuffer,+ pool_entry_biases: B::GlobalGpuBuffer,+ pool_hidden_weights: B::GlobalGpuBuffer,+ pool_hidden_biases: B::GlobalGpuBuffer,+ pool_out_weights: B::GlobalGpuBuffer,+ pool_out_biases: B::GlobalGpuBuffer,+}++impl<B: Backend> Nodes<B> {+ pub async fn new(+ config: &ConfidenceHeadConfig,+ parameter_tree: &ParameterTree<'_, B>,+ context: &B::Context,+ ) -> Result<Self, ConfidenceHeadError<B>> {+ let (width, pool) = (config.model_dim, config.pool_hidden_dim);+ let pool_entry_weights =+ parameter_tree.read_buffer("pool_set.entry.weights", &[pool, POOL_INPUTS], DATA_TYPE).await?;+ let pool_entry_biases = parameter_tree.read_buffer("pool_set.entry.biases", &[pool], DATA_TYPE).await?;+ let pool_hidden_weights =+ parameter_tree.read_buffer("pool_set.hidden.weights", &[pool, pool], DATA_TYPE).await?;+ let pool_hidden_biases = parameter_tree.read_buffer("pool_set.hidden.biases", &[pool], DATA_TYPE).await?;+ let pool_out_weights =+ parameter_tree.read_buffer("pool_set.out.weights", &[width, 2 * pool], DATA_TYPE).await?;+ let pool_out_biases = parameter_tree.read_buffer("pool_set.out.biases", &[width], DATA_TYPE).await?;+ Ok(Self {+ pool_entry_weights,+ pool_entry_biases,+ pool_hidden_weights,+ pool_hidden_biases,+ pool_out_weights,+ pool_out_biases,+ kernel: <B::Kernels as Kernels>::ConfidenceHeadNodesKernel::new(context, width, pool)+ .map_err(ConfidenceHeadError::Backend)?,+ })+ }++ pub fn encode(+ &self,+ residual_logits: impl BufferRef<Backend = B>,+ candidate_logits: impl BufferRef<Backend = B>,+ pool_features: impl BufferRef<Backend = B>,+ round_metadata: impl BufferRef<Backend = B>,+ round_valid: impl BufferRef<Backend = B>,+ draft: impl BufferRef<Backend = B>,+ scores: impl BufferMut<Backend = B>,+ nodes: impl BufferMut<Backend = B>,+ node_inputs: impl BufferMut<Backend = B>,+ params: ConfidenceHeadParams,+ rows: u32,+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,+ ) {+ self.kernel.encode(+ residual_logits,+ candidate_logits,+ pool_features,+ round_metadata,+ round_valid,+ draft,+ &self.pool_entry_weights,+ &self.pool_entry_biases,+ &self.pool_hidden_weights,+ &self.pool_hidden_biases,+ &self.pool_out_weights,+ &self.pool_out_biases,+ scores,+ nodes,+ node_inputs,+ params,+ rows,+ command_buffer,+ );+ }+}diff --git a/crates/uzu-engine/src/encodable_block/confidence_head/tree_attention.rs b/crates/uzu-engine/src/encodable_block/confidence_head/tree_attention.rsnew file mode 100644index 000000000..24ccb743e--- /dev/null+++ b/crates/uzu-engine/src/encodable_block/confidence_head/tree_attention.rs@@ -0,0 +1,274 @@+use crate::{+ backends::common::{+ Backend, Buffer, BufferRef, CommandBuffer, CommandBufferEncoding, Kernels,+ gpu_types::{+ activation_type::ActivationType,+ confidence_head::{RELATIONS, SLOT_NUMBERS, TREE_ROWS_MAX},+ },+ kernel::{+ ActivationKernel, ConfidenceHeadTreeAttentionKernel, ConfidenceHeadTreeInputKernel,+ ConfidenceHeadTreeRelationsKernel,+ },+ },+ config::{+ confidence_head::ConfidenceHeadConfig, confidence_head_tree_attention::ConfidenceHeadTreeAttentionConfig,+ },+ data_type::DataType,+ encodable_block::{+ confidence_head::{ConfidenceHeadError, DATA_TYPE},+ linear::Linear,+ normalization::{Normalization, PostLayerScalar, ShortcutMode},+ },+ safetensors::ParameterTree,+};++struct TreeAttentionLayer<B: Backend> {+ attention_norm: Normalization<B>,+ qkv: Box<dyn Linear<B>>,+ out: Box<dyn Linear<B>>,+ mlp_norm: Normalization<B>,+ up: Box<dyn Linear<B>>,+ down: Box<dyn Linear<B>>,+}++pub struct TreeAttention<B: Backend> {+ config: ConfidenceHeadTreeAttentionConfig,+ node_in: Box<dyn Linear<B>>,+ child_in: Box<dyn Linear<B>>,+ depth_embedding: B::GlobalGpuBuffer,+ relation_bias: B::GlobalGpuBuffer,+ layers: Box<[TreeAttentionLayer<B>]>,+ final_norm: Normalization<B>,+ couple_node: Box<dyn Linear<B>>,+ couple_child: Box<dyn Linear<B>>,+ activation: <B::Kernels as Kernels>::ActivationKernel,+ input: <B::Kernels as Kernels>::ConfidenceHeadTreeInputKernel,+ relations: <B::Kernels as Kernels>::ConfidenceHeadTreeRelationsKernel,+ attention: <B::Kernels as Kernels>::ConfidenceHeadTreeAttentionKernel,+}++impl<B: Backend> TreeAttention<B> {+ pub async fn new(+ head_config: &ConfidenceHeadConfig,+ config: &ConfidenceHeadTreeAttentionConfig,+ parameter_tree: &ParameterTree<'_, B>,+ context: &B::Context,+ ) -> Result<Self, ConfidenceHeadError<B>> {+ let width = config.model_dim;+ let norm_config = &head_config.norm_config;+ let mut layers = Vec::with_capacity(config.num_layers as usize);+ for index in 0..config.num_layers {+ let layer = parameter_tree.subtree("layers").subtree(&index.to_string());+ let first = if index == 0 {+ ShortcutMode::Copy+ } else {+ ShortcutMode::Add+ };+ let attention_norm = Normalization::new(+ width,+ DATA_TYPE,+ DATA_TYPE,+ None,+ first,+ PostLayerScalar::None,+ norm_config,+ &layer.subtree("attention_norm"),+ context,+ )+ .await?;+ let qkv = <dyn Linear<B>>::new(width, 3 * width, DATA_TYPE, true, &layer.subtree("qkv"), context).await?;+ let out = <dyn Linear<B>>::new(width, width, DATA_TYPE, true, &layer.subtree("out"), context).await?;+ let mlp_norm = Normalization::new(+ width,+ DATA_TYPE,+ DATA_TYPE,+ None,+ ShortcutMode::Add,+ PostLayerScalar::None,+ norm_config,+ &layer.subtree("mlp_norm"),+ context,+ )+ .await?;+ let up =+ <dyn Linear<B>>::new(width, config.hidden_dim, DATA_TYPE, true, &layer.subtree("up"), context).await?;+ let down = <dyn Linear<B>>::new(config.hidden_dim, width, DATA_TYPE, true, &layer.subtree("down"), context)+ .await?;+ layers.push(TreeAttentionLayer {+ attention_norm,+ qkv,+ out,+ mlp_norm,+ up,+ down,+ });+ }+ let final_mode = if layers.is_empty() {+ ShortcutMode::None+ } else {+ ShortcutMode::Add+ };+ let node_in = <dyn Linear<B>>::new(+ head_config.model_dim,+ width,+ DATA_TYPE,+ true,+ ¶meter_tree.subtree("node_in"),+ context,+ )+ .await?;+ let child_in = <dyn Linear<B>>::new(+ head_config.model_dim + SLOT_NUMBERS,+ width,+ DATA_TYPE,+ true,+ ¶meter_tree.subtree("child_in"),+ context,+ )+ .await?;+ let depth_embedding =+ parameter_tree.read_buffer("depth_embedding", &[head_config.max_depth + 1, width], DATA_TYPE).await?;+ let relation_bias =+ parameter_tree.read_buffer("relation_bias", &[config.num_heads, RELATIONS], DATA_TYPE).await?;+ let final_norm = Normalization::new(+ width,+ DATA_TYPE,+ DATA_TYPE,+ None,+ final_mode,+ PostLayerScalar::None,+ norm_config,+ ¶meter_tree.subtree("final_norm"),+ context,+ )+ .await?;+ let couple_node = <dyn Linear<B>>::new(+ width,+ head_config.model_dim,+ DATA_TYPE,+ true,+ ¶meter_tree.subtree("couple_node"),+ context,+ )+ .await?;+ let couple_child = <dyn Linear<B>>::new(+ width,+ head_config.model_dim,+ DATA_TYPE,+ true,+ ¶meter_tree.subtree("couple_child"),+ context,+ )+ .await?;+ let head_dim = width / config.num_heads;+ if !matches!(head_dim, 32 | 64) {+ return Err(ConfidenceHeadError::UnsupportedShape(format!("tree attention heads of width {head_dim}")));+ }+ let attention =+ <B::Kernels as Kernels>::ConfidenceHeadTreeAttentionKernel::new(context, config.num_heads, head_dim)+ .map_err(ConfidenceHeadError::Backend)?;+ Ok(Self {+ config: config.clone(),+ node_in,+ child_in,+ depth_embedding,+ relation_bias,+ layers: layers.into_boxed_slice(),+ final_norm,+ couple_node,+ couple_child,+ activation: <B::Kernels as Kernels>::ActivationKernel::new(context, DATA_TYPE, true)+ .map_err(ConfidenceHeadError::Backend)?,+ input: <B::Kernels as Kernels>::ConfidenceHeadTreeInputKernel::new(context)+ .map_err(ConfidenceHeadError::Backend)?,+ relations: <B::Kernels as Kernels>::ConfidenceHeadTreeRelationsKernel::new(context)+ .map_err(ConfidenceHeadError::Backend)?,+ attention,+ })+ }++ pub fn encode(+ &self,+ node_inputs: B::ScratchBuffer,+ child_inputs: B::ScratchBuffer,+ frontier: impl BufferRef<Backend = B>,+ row_slots: &B::ScratchBuffer,+ slot_rows: &B::ScratchBuffer,+ slot_ancestors: impl BufferRef<Backend = B>,+ ancestor_stride: u32,+ slots: u32,+ rows: u32,+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,+ ) -> Result<(B::ScratchBuffer, B::ScratchBuffer), ConfidenceHeadError<B>> {+ if rows > TREE_ROWS_MAX {+ return Err(ConfidenceHeadError::UnsupportedShape(format!("tree attention over {rows} rows")));+ }+ let width = self.config.model_dim;+ let child_in = self.child_in.encode(child_inputs, rows - 1, command_buffer)?;+ let node_in = self.node_in.encode(node_inputs, slots, command_buffer)?;+ let mut hidden = command_buffer+ .allocate_scratch_for_shape(&[rows, width], DATA_TYPE)+ .map_err(ConfidenceHeadError::Backend)?;+ self.input.encode(+ &self.depth_embedding,+ &child_in,+ &node_in,+ frontier,+ row_slots,+ &mut hidden,+ rows,+ width,+ command_buffer,+ );++ let mut relations = command_buffer+ .allocate_scratch_for_shape(&[rows, rows], DataType::U32)+ .map_err(ConfidenceHeadError::Backend)?;+ self.relations.encode(+ frontier,+ slot_ancestors,+ slot_rows,+ &mut relations,+ rows,+ ancestor_stride,+ command_buffer,+ );+ let mut residual = command_buffer+ .allocate_scratch_for_shape(&[rows, width], DATA_TYPE)+ .map_err(ConfidenceHeadError::Backend)?;+ for layer in &self.layers {+ let normalized = layer+ .attention_norm+ .encode(&hidden, 0, rows, Some(&mut residual), command_buffer)+ .map_err(ConfidenceHeadError::Backend)?;+ let qkv = layer.qkv.encode(normalized, rows, command_buffer)?;+ let mut attended = command_buffer+ .allocate_scratch_for_shape(&[rows, width], DATA_TYPE)+ .map_err(ConfidenceHeadError::Backend)?;+ self.attention.encode(&qkv, &relations, &self.relation_bias, &mut attended, rows, command_buffer);+ let projected = layer.out.encode(attended, rows, command_buffer)?;+ let normalized = layer+ .mlp_norm+ .encode(&projected, 0, rows, Some(&mut residual), command_buffer)+ .map_err(ConfidenceHeadError::Backend)?;+ let mut raised = layer.up.encode(normalized, rows, command_buffer)?;+ self.activation.encode(+ None::<&B::ScratchBuffer>,+ &mut raised,+ rows * self.config.hidden_dim,+ ActivationType::SILU,+ command_buffer,+ );+ hidden = layer.down.encode(raised, rows, command_buffer)?;+ }+ let shortcut = (!self.layers.is_empty()).then_some(&mut residual);+ let finished =+ self.final_norm.encode(&hidden, 0, rows, shortcut, command_buffer).map_err(ConfidenceHeadError::Backend)?;+ let mut finished_copy =+ command_buffer.allocate_scratch(finished.size()).map_err(ConfidenceHeadError::Backend)?;+ command_buffer.encode_copy(&finished, &mut finished_copy);+ let node_shifts = self.couple_node.encode(finished, rows, command_buffer)?;+ let child_shifts = self.couple_child.encode(finished_copy, rows, command_buffer)?;+ Ok((node_shifts, child_shifts))+ }+}diff --git a/crates/uzu-engine/src/encodable_block/mod.rs b/crates/uzu-engine/src/encodable_block/mod.rsindex f7d7aaf35..baa5ab656 100644--- a/crates/uzu-engine/src/encodable_block/mod.rs+++ b/crates/uzu-engine/src/encodable_block/mod.rs@@ -1,5 +1,6 @@pub mod batch_topology;pub mod classifier;+pub mod confidence_head;pub mod convolution;pub mod decision;pub mod decoder;diff --git a/crates/uzu-engine/src/encodable_block/weaver.rs b/crates/uzu-engine/src/encodable_block/weaver.rsindex 67776e039..8499e59e5 100644--- a/crates/uzu-engine/src/encodable_block/weaver.rs+++ b/crates/uzu-engine/src/encodable_block/weaver.rs@@ -18,6 +18,7 @@ use crate::{config::{rope::AnyRoPEConfig, weaver::WeaverConfig},data_type::DataType,encodable_block::{+ confidence_head::{ConfidenceHead, ConfidenceHeadError, ConfidenceHeadStep},embedding::{Embedding, EmbeddingError},linear::{Linear, LinearBlockError, LinearEncodeError, RHTLinearWrapper},mixer::attention::{KVCache, KVCacheView, rope::PrecalculatedRoPE},@@ -180,6 +181,8 @@ pub enum WeaverNewError<B: Backend> {pub enum WeaverEncodeError<B: Backend> {#[error("backend error: {0}")]Backend(#[source] B::Error),+ #[error("confidence head error: {0}")]+ ConfidenceHead(#[from] ConfidenceHeadError<B>),#[error("Linear error: {0}")]Linear(#[from] LinearEncodeError<B>),#[error("MLP error: {0}")]@@ -456,13 +459,14 @@ impl<B: Backend> Weaver<B> {shape: &WeaverTreeShape,batch_node_count: u32,batch_start_slot: u32,+ mut head: Option<(&ConfidenceHead<B>, &mut ConfidenceHeadStep<B>)>,command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,) -> Result<(), WeaverEncodeError<B>> {let tree_slot_count = shape.slot_count();let ancestor_stride = self.max_depth;let frontier_capacity = tree_slot_count * shape.expand_width;- let fuse_select = shape.expand_per_round <= 4 && shape.prune_noise_scale.is_none();+ let fuse_select = shape.expand_per_round <= 4 && shape.prune_noise_scale.is_none() && head.is_none();if batch_start_slot > 0 && !fuse_select {self.frontier_select.encode(None::<&B::ScratchBuffer>,@@ -494,6 +498,9 @@ impl<B: Backend> Weaver<B> {command_buffer,);}+ if let Some((head, step)) = head.as_mut() {+ head.encode_rows(step, node_metadata.as_ref(), node_valid.as_ref(), command_buffer);+ }let batch_candidate_ids = if batch_start_slot == 0 {candidate_ids.subrange(..)} else {@@ -609,6 +616,18 @@ impl<B: Backend> Weaver<B> {shape.prune_noise_scale,command_buffer,);+ if let Some((head, step)) = head {+ head.encode_round(+ step,+ &logit_residuals,+ candidate_logits,+ candidate_ids,+ packed_tree,+ frontier,+ batch_node_count,+ command_buffer,+ );+ }Ok(())}@@ -622,6 +641,7 @@ impl<B: Backend> Weaver<B> {depth_seeds: &[u64],root_token_id: u32,shape: WeaverTreeShape,+ confidence_head: Option<&ConfidenceHead<B>>,command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,) -> Result<EncodedWeaverTree<B>, WeaverEncodeError<B>> {let (packed_tree, frontier) = {@@ -743,6 +763,23 @@ impl<B: Backend> Weaver<B> {.map_err(WeaverEncodeError::Backend)?;let depth_seeds_buffer =command_buffer.allocate_constant_from_slice(depth_seeds).map_err(WeaverEncodeError::Backend)?;+ let mut head_step = confidence_head+ .map(|head| {+ head.encode_step(+ draft_hidden,+ &candidate_logits,+ &candidate_ids,+ &depth_seeds_buffer,+ pool_depth_count,+ self.candidate_pool_size,+ shape.expand_width,+ tree_slot_count,+ vocab_size,+ shape.expand_per_round,+ command_buffer,+ )+ })+ .transpose()?;let mut batch_start_slot = 0;for round in 0..shape.rounds {@@ -772,10 +809,21 @@ impl<B: Backend> Weaver<B> {&shape,batch_node_count,batch_start_slot,+ confidence_head.zip(head_step.as_mut()),command_buffer,)?;batch_start_slot += batch_node_count;}+ if let (Some(head), Some(step)) = (confidence_head, head_step) {+ head.encode_prune(+ step,+ &mut packed_tree,+ &mut frontier,+ &slot_ancestors,+ ancestor_stride,+ command_buffer,+ )?;+ }(packed_tree, frontier)};diff --git a/crates/uzu-engine/src/speculators/dflash_tfm.rs b/crates/uzu-engine/src/speculators/dflash_tfm.rsindex f8cf89288..ebb165fc7 100644--- a/crates/uzu-engine/src/speculators/dflash_tfm.rs+++ b/crates/uzu-engine/src/speculators/dflash_tfm.rs@@ -19,6 +19,7 @@ use crate::{data_type::DataType,encodable_block::{batch_topology::BatchTopology,+ confidence_head::{ConfidenceHead, ConfidenceHeadError},dflash::{DFlash, DFlashEncodeError, DFlashNewError},embedding::Embedding,sampling::{PRng, Sampling, SamplingMethod},@@ -57,6 +58,8 @@ pub enum DFlashSpeculatorLoadError<B: Backend> {DFlash(#[from] DFlashNewError<B>),#[error("Weaver error: {0}")]Weaver(#[from] WeaverNewError<B>),+ #[error("confidence head error: {0}")]+ ConfidenceHead(#[from] ConfidenceHeadError<B>),}#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]@@ -88,6 +91,7 @@ pub struct DFlashTfmSpeculator<B: Backend> {context: Arc<B::Context>,dflash: DFlash<B>,weaver: Option<Weaver<B>>,+ confidence_head: Option<ConfidenceHead<B>>,sampling: Sampling<B>,config: DFlashSpeculatorConfig,shape: DFlashTfmTreeShape,@@ -140,6 +144,19 @@ impl<B: Backend> DFlashTfmSpeculator<B> {} else {None};+ let confidence_head = match &config.confidence_head_config {+ Some(head_config) => Some(+ ConfidenceHead::new(+ head_config,+ &speculator_tree.subtree("confidence_head"),+ target_embedding,+ weaver.as_ref().map_or(0, Weaver::max_depth),+ &*context,+ )+ .await?,+ ),+ None => None,+ };weight_loader.assert_all_tensors_read()?;@@ -149,6 +166,7 @@ impl<B: Backend> DFlashTfmSpeculator<B> {context,dflash,weaver,+ confidence_head,sampling,config,shape,@@ -332,11 +350,14 @@ impl<B: Backend> DFlashTfmSpeculator<B> {let depth_seeds = (0..weaver.max_depth()).map(|depth| prng.derive(root_position as u64 + depth as u64)).collect::<Box<[u64]>>();- let prune_sigma = match sampling_method {- SamplingMethod::Greedy => None,+ let (head, prune_sigma) = match sampling_method {+ SamplingMethod::Greedy => (None, None),SamplingMethod::Stochastic {..- } => prune_sigma,+ } => match &self.confidence_head {+ Some(head) => (Some(head), None),+ None => (None, prune_sigma),+ },};let tree = weaver.encode_tree(target_output_norm,@@ -354,6 +375,7 @@ impl<B: Backend> DFlashTfmSpeculator<B> {expand_width,prune_noise_scale: prune_sigma.map(f32::recip),},+ head,&mut command_buffer,)?;let completed =diff --git a/crates/uzu-engine/unit/backends/common/kernel/confidence_head_test.rs b/crates/uzu-engine/unit/backends/common/kernel/confidence_head_test.rsnew file mode 100644index 000000000..e0958c282--- /dev/null+++ b/crates/uzu-engine/unit/backends/common/kernel/confidence_head_test.rs@@ -0,0 +1,569 @@+use futures::executor::block_on;+use half::bf16;+use uzu_engine_macros::uzu_test;++use crate::{+ backends::{+ common::{+ Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context, Kernels,+ gpu_types::{+ confidence_head::ConfidenceHeadParams,+ weaver::{FrontierIdx, MetadataIdx, TreeIdx},+ },+ kernel::{+ ConfidenceHeadEdgesKernel, ConfidenceHeadNodesKernel, ConfidenceHeadPoolsKernel,+ ConfidenceHeadTreeAttentionKernel, ConfidenceHeadTreeInputKernel, ConfidenceHeadTreeRelationsKernel,+ },+ },+ cpu::Cpu,+ },+ tests::helpers::{buffer_to_vec, create_buffer_with_data, create_context, for_each_non_cpu_backend},+};++const NONE: u32 = u32::MAX;+const SLOTS: usize = 5;+const CHILDREN: usize = 4;+const CAPACITY: usize = SLOTS * CHILDREN;+const ROWS: usize = 1 + CAPACITY;+const STRIDE: usize = 4;+const CANDIDATES: u32 = 300;+const VOCAB: u32 = 65_536;+const WIDTH: u32 = 16;+const POOL_HIDDEN: u32 = 8;+const EDGE_HIDDEN: u32 = 32;+const SLOT_ENTRY: [u32; SLOTS] = [NONE, 1, 2, 5, 13];+const EXPANDED: [bool; SLOTS] = [true, true, false, true, true];+const CHILD_INDEX: [u32; CHILDREN] = [5, 290, 0, 17];+const DEPTHS: usize = 4;++fn values(+ count: usize,+ salt: f32,+ scale: f32,+) -> Vec<f32> {+ (0..count).map(|index| ((index as f32 * 0.731 + salt).sin() * 43758.547).fract() * scale).collect()+}++fn bf16s(values: &[f32]) -> Vec<bf16> {+ values.iter().copied().map(bf16::from_f32).collect()+}++fn floats(values: &[bf16]) -> Vec<f32> {+ values.iter().map(|value| value.to_f32()).collect()+}++fn assert_close(+ name: &str,+ actual: &[f32],+ expected: &[f32],+ tolerance: f32,+) {+ assert_eq!(actual.len(), expected.len(), "{name}: lengths differ");+ for (index, (actual, expected)) in actual.iter().zip(expected).enumerate() {+ assert!(+ (actual - expected).abs() <= tolerance * (1.0 + expected.abs()),+ "{name}[{index}]: {actual} != {expected}"+ );+ }+}++fn pool_token(+ slot: usize,+ index: u32,+) -> u32 {+ 1000 + slot as u32 * 7919 + index * 37+}++fn depth(slot: usize) -> usize {+ match SLOT_ENTRY[slot] {+ NONE => 0,+ entry => 1 + depth(entry as usize / CHILDREN),+ }+}++fn entry_token(entry: usize) -> u32 {+ let (slot, child) = (entry / CHILDREN, entry % CHILDREN);+ pool_token(slot, CHILD_INDEX[child] + slot as u32)+}++struct Tree {+ frontier: Vec<u32>,+ packed_tree: Vec<u32>,+ slot_ancestors: Vec<u32>,+ slot_rows: Vec<u32>,+ row_slots: Vec<u32>,+}++fn tree() -> Tree {+ let mut frontier = vec![0; FrontierIdx::COUNT * CAPACITY];+ for entry in (0..CAPACITY).filter(|entry| EXPANDED[entry / CHILDREN]) {+ let slot = entry / CHILDREN;+ frontier[FrontierIdx::TokenId as usize * CAPACITY + entry] = entry_token(entry);+ frontier[FrontierIdx::ParentSlot as usize * CAPACITY + entry] = slot as u32;+ frontier[FrontierIdx::Depth as usize * CAPACITY + entry] = depth(slot) as u32 + 1;+ frontier[FrontierIdx::Active as usize * CAPACITY + entry] = u32::from(!SLOT_ENTRY.contains(&(entry as u32)));+ }+ let mut packed_tree = vec![0; TreeIdx::COUNT * SLOTS];+ let mut slot_ancestors = vec![0; SLOTS * STRIDE];+ let mut slot_rows = vec![NONE; SLOTS];+ let mut row_slots = vec![NONE; ROWS];+ for slot in 0..SLOTS {+ let entry = SLOT_ENTRY[slot];+ let field = |index: TreeIdx| index as usize * SLOTS + slot;+ packed_tree[field(TreeIdx::TokenId)] = if entry == NONE {+ 7+ } else {+ entry_token(entry as usize)+ };+ packed_tree[field(TreeIdx::ParentSlot)] = if entry == NONE {+ NONE+ } else {+ entry / CHILDREN as u32+ };+ packed_tree[field(TreeIdx::Depth)] = depth(slot) as u32;+ packed_tree[field(TreeIdx::PathLogprobBits)] = (-0.3 * slot as f32).to_bits();+ packed_tree[field(TreeIdx::Valid)] = 1;+ let mut ancestor = slot;+ while SLOT_ENTRY[ancestor] != NONE {+ ancestor = SLOT_ENTRY[ancestor] as usize / CHILDREN;+ slot_ancestors[slot * STRIDE + depth(ancestor)] = ancestor as u32;+ }+ if EXPANDED[slot] {+ let row = if entry == NONE {+ 0+ } else {+ 1 + entry+ };+ slot_rows[slot] = row;+ row_slots[row as usize] = slot as u32;+ }+ }+ Tree {+ frontier,+ packed_tree,+ slot_ancestors,+ slot_rows,+ row_slots,+ }+}++fn params() -> ConfidenceHeadParams {+ ConfidenceHeadParams {+ candidates: CANDIDATES,+ children: CHILDREN as u32,+ tree_slot_count: SLOTS as u32,+ vocab_size: VOCAB,+ logit_cap: 50.0,+ epsilon: 1e-5,+ }+}++fn weights<const N: usize>(+ sizes: [usize; N],+ salt: f32,+) -> [Vec<f32>; N] {+ std::array::from_fn(|index| values(sizes[index], salt + index as f32, 0.6))+}++fn node_weights() -> [Vec<f32>; 6] {+ let (width, pool) = (WIDTH as usize, POOL_HIDDEN as usize);+ weights([3 * pool, pool, pool * pool, pool, width * 2 * pool, width], 0.7)+}++fn edge_weights() -> [Vec<f32>; 12] {+ let (width, hidden) = (WIDTH as usize, EDGE_HIDDEN as usize);+ let inputs = 3 * width + 4;+ let mut weights = weights(+ [+ 8,+ 2 * inputs,+ width * inputs,+ width,+ 2 * width,+ hidden * width,+ hidden,+ width * hidden,+ width,+ 2 * width,+ 3 * width,+ 3,+ ],+ 3.3,+ );+ weights[0][4..].copy_from_slice(&[1.0, 1.5, 2.0, 2.5]);+ weights+}++fn pool_inputs() -> (Vec<u32>, Vec<u32>, Vec<f32>) {+ let mut metadata = vec![0; MetadataIdx::COUNT * SLOTS];+ for slot in 0..SLOTS {+ metadata[MetadataIdx::Depth as usize * SLOTS + slot] = depth(slot) as u32;+ metadata[MetadataIdx::AncestorCount as usize * SLOTS + slot] = depth(slot) as u32;+ metadata[MetadataIdx::TreeSlot as usize * SLOTS + slot] = slot as u32;+ }+ let ids = (0..DEPTHS)+ .flat_map(|depth| {+ let slot = (0..SLOTS).find(|&slot| self::depth(slot) == depth).unwrap_or(0);+ (0..CANDIDATES).map(move |index| pool_token(slot, index))+ })+ .collect::<Vec<_>>();+ let mut features = values(DEPTHS * 3 * CANDIDATES as usize, 4.1, 3.0);+ for depth in 0..DEPTHS {+ for index in 0..CANDIDATES as usize {+ features[depth * 3 * CANDIDATES as usize + index] =+ -features[depth * 3 * CANDIDATES as usize + index].abs();+ }+ }+ (metadata, ids, features)+}++fn run_pools<B: Backend>() -> Vec<f32> {+ let context = create_context::<B>();+ let candidate_logits = create_buffer_with_data::<B, f32>(&context, &values(DEPTHS * CANDIDATES as usize, 0.3, 6.0));+ let candidate_ids = create_buffer_with_data::<B, u32>(+ &context,+ &(0..DEPTHS).flat_map(|depth| (0..CANDIDATES).map(move |index| pool_token(depth, index))).collect::<Vec<_>>(),+ );+ let depth_seeds = create_buffer_with_data::<B, u64>(&context, &[0x9E3779B97F4A7C15, 0xD1B54A32D192ED03, 7, 9]);+ let mut pool_features = create_buffer_with_data::<B, f32>(&context, &vec![0.0; DEPTHS * 3 * CANDIDATES as usize]);+ let kernel = <B::Kernels as Kernels>::ConfidenceHeadPoolsKernel::new(&context).unwrap();+ let mut command_buffer = context.create_command_buffer(None, None).unwrap();+ kernel.encode(+ &candidate_logits,+ &candidate_ids,+ &depth_seeds,+ &mut pool_features,+ params(),+ DEPTHS as u32,+ &mut command_buffer,+ );+ block_on(command_buffer.end_encoding().submit().wait_until_completed()).unwrap();+ buffer_to_vec::<B, f32>(&context, &pool_features)+}++#[uzu_test]+fn pools_match_cpu() {+ let expected = run_pools::<Cpu>();+ for_each_non_cpu_backend!(|B| assert_close("pool features", &run_pools::<B>(), &expected, 1e-4));+}++fn run_nodes<B: Backend>() -> (Vec<f32>, Vec<f32>, Vec<f32>) {+ let context = create_context::<B>();+ let (metadata, _, features) = pool_inputs();+ let u32s = |data: &[u32]| create_buffer_with_data::<B, u32>(&context, data);+ let f32s = |data: &[f32]| create_buffer_with_data::<B, f32>(&context, data);+ let bf16_buffer = |data: &[f32]| create_buffer_with_data::<B, bf16>(&context, &bf16s(data));+ let residual_logits = bf16_buffer(&values(SLOTS * CANDIDATES as usize, 1.7, 2.0));+ let candidate_logits = f32s(&values(DEPTHS * CANDIDATES as usize, 0.3, 6.0));+ let pool_features = f32s(&features);+ let round_metadata = u32s(&metadata);+ let round_valid = u32s(&EXPANDED.map(u32::from));+ let draft = bf16_buffer(&values(DEPTHS * WIDTH as usize, 2.3, 1.0));+ let [+ pool_entry_weights,+ pool_entry_biases,+ pool_hidden_weights,+ pool_hidden_biases,+ pool_out_weights,+ pool_out_biases,+ ] = node_weights().map(|values| bf16_buffer(&values));+ let mut scores = f32s(&vec![0.0; SLOTS * 2 * CANDIDATES as usize]);+ let mut nodes = bf16_buffer(&vec![0.0; SLOTS * WIDTH as usize]);+ let mut node_inputs = bf16_buffer(&vec![0.0; SLOTS * WIDTH as usize]);+ let kernel = <B::Kernels as Kernels>::ConfidenceHeadNodesKernel::new(&context, WIDTH, POOL_HIDDEN).unwrap();+ let mut command_buffer = context.create_command_buffer(None, None).unwrap();+ kernel.encode(+ &residual_logits,+ &candidate_logits,+ &pool_features,+ &round_metadata,+ &round_valid,+ &draft,+ &pool_entry_weights,+ &pool_entry_biases,+ &pool_hidden_weights,+ &pool_hidden_biases,+ &pool_out_weights,+ &pool_out_biases,+ &mut scores,+ &mut nodes,+ &mut node_inputs,+ params(),+ SLOTS as u32,+ &mut command_buffer,+ );+ block_on(command_buffer.end_encoding().submit().wait_until_completed()).unwrap();+ (+ buffer_to_vec::<B, f32>(&context, &scores),+ floats(&buffer_to_vec::<B, bf16>(&context, &nodes)),+ floats(&buffer_to_vec::<B, bf16>(&context, &node_inputs)),+ )+}++#[uzu_test]+fn nodes_match_cpu() {+ let (scores, nodes, _) = run_nodes::<Cpu>();+ for_each_non_cpu_backend!(|B| {+ let actual = run_nodes::<B>();+ assert_close("scores", &actual.0, &scores, 1e-4);+ assert_close("nodes", &actual.1, &nodes, 2e-2);+ assert_eq!(actual.2, actual.1);+ });+}++fn frontier_floats(+ frontier: &[u32],+ field: FrontierIdx,+) -> Vec<f32> {+ frontier[field as usize * CAPACITY..(field as usize + 1) * CAPACITY]+ .iter()+ .map(|bits| f32::from_bits(*bits))+ .collect()+}++fn packed_edges(packed_tree: &[u32]) -> Vec<f32> {+ packed_tree[TreeIdx::EdgeLogprobBits as usize * SLOTS..][..SLOTS].iter().map(|bits| f32::from_bits(*bits)).collect()+}++struct EdgesOutput {+ frontier: Vec<u32>,+ packed_tree: Vec<u32>,+ child_inputs: Vec<f32>,+ child_pools: Vec<u32>,+ child_numbers: Vec<f32>,+ slot_rows: Vec<u32>,+ row_slots: Vec<u32>,+}++fn child_pool_indices() -> Vec<u32> {+ (0..CAPACITY).map(|entry| CHILD_INDEX[entry % CHILDREN] + (entry / CHILDREN) as u32).collect()+}++fn run_edges<B: Backend>(refine: bool) -> EdgesOutput {+ let context = create_context::<B>();+ let tree = tree();+ let (metadata, ids, features) = pool_inputs();+ let u32s = |data: &[u32]| create_buffer_with_data::<B, u32>(&context, data);+ let f32s = |data: &[f32]| create_buffer_with_data::<B, f32>(&context, data);+ let bf16_buffer = |data: &[f32]| create_buffer_with_data::<B, bf16>(&context, &bf16s(data));+ let node_metadata = u32s(&metadata);+ let node_valid = u32s(&EXPANDED.map(u32::from));+ let candidate_ids = u32s(&ids);+ let pool_features = f32s(&features);+ let nodes = bf16_buffer(&values(SLOTS * WIDTH as usize, 1.1, 1.0));+ let node_shifts = bf16_buffer(&values(ROWS * WIDTH as usize, 1.3, 0.5));+ let child_shifts = bf16_buffer(&values(ROWS * WIDTH as usize, 1.9, 0.5));+ let token_features = bf16_buffer(&values(VOCAB as usize * WIDTH as usize, 3.1, 1.0));+ let scores = f32s(&values(SLOTS * 2 * CANDIDATES as usize, 0.5, 4.0));+ let [+ slot_stats,+ input_norm,+ entry_weights,+ entry_biases,+ block_norm,+ up_weights,+ up_biases,+ down_weights,+ down_biases,+ final_norm,+ readout_weights,+ readout_biases,+ ] = edge_weights().map(|values| bf16_buffer(&values));+ let mut slot_rows = u32s(&if refine {+ tree.slot_rows.clone()+ } else {+ vec![NONE; SLOTS]+ });+ let mut row_slots = u32s(&[NONE; ROWS]);+ let mut child_numbers = f32s(&if refine {+ values(CAPACITY * 4, 2.7, 1.0)+ } else {+ vec![0.0; CAPACITY * 4]+ });+ let mut child_pools = u32s(&if refine {+ child_pool_indices()+ } else {+ vec![0; CAPACITY]+ });+ let mut frontier = u32s(&tree.frontier);+ let mut packed_tree = u32s(&tree.packed_tree);+ let mut child_inputs = bf16_buffer(&vec![0.0; CAPACITY * (WIDTH as usize + 4)]);+ let kernel = <B::Kernels as Kernels>::ConfidenceHeadEdgesKernel::new(&context, WIDTH, EDGE_HIDDEN, refine).unwrap();+ let mut command_buffer = context.create_command_buffer(None, None).unwrap();+ kernel.encode(+ (!refine).then_some(&node_metadata),+ (!refine).then_some(&node_valid),+ (!refine).then_some(&candidate_ids),+ (!refine).then_some(&pool_features),+ (!refine).then_some(&slot_stats),+ &mut slot_rows,+ (!refine).then_some(&mut row_slots),+ &nodes,+ refine.then_some(&node_shifts),+ refine.then_some(&child_shifts),+ &token_features,+ &mut child_numbers,+ &mut child_pools,+ &scores,+ &mut frontier,+ &mut packed_tree,+ (!refine).then_some(&mut child_inputs),+ &input_norm,+ &entry_weights,+ &entry_biases,+ &block_norm,+ &up_weights,+ &up_biases,+ &down_weights,+ &down_biases,+ &final_norm,+ &readout_weights,+ &readout_biases,+ params(),+ SLOTS as u32,+ &mut command_buffer,+ );+ block_on(command_buffer.end_encoding().submit().wait_until_completed()).unwrap();+ EdgesOutput {+ frontier: buffer_to_vec::<B, u32>(&context, &frontier),+ packed_tree: buffer_to_vec::<B, u32>(&context, &packed_tree),+ child_inputs: floats(&buffer_to_vec::<B, bf16>(&context, &child_inputs)),+ child_pools: buffer_to_vec::<B, u32>(&context, &child_pools),+ child_numbers: buffer_to_vec::<B, f32>(&context, &child_numbers),+ slot_rows: buffer_to_vec::<B, u32>(&context, &slot_rows),+ row_slots: buffer_to_vec::<B, u32>(&context, &row_slots),+ }+}++#[uzu_test]+fn edges_match_cpu() {+ let tree = tree();+ for refine in [false, true] {+ let expected = run_edges::<Cpu>(refine);+ let edges = frontier_floats(&expected.frontier, FrontierIdx::EdgeLogprobBits);+ assert!(edges[..8].iter().chain(&edges[12..]).all(|edge| *edge < 0.0));+ if refine {+ assert!(packed_edges(&expected.packed_tree)[1..].iter().all(|edge| *edge < 0.0));+ } else {+ assert_eq!(expected.slot_rows, tree.slot_rows);+ assert_eq!(expected.row_slots, tree.row_slots);+ let pools = child_pool_indices();+ for entry in (0..CAPACITY).filter(|entry| EXPANDED[entry / CHILDREN]) {+ assert_eq!(expected.child_pools[entry], pools[entry]);+ }+ }+ for_each_non_cpu_backend!(|B| {+ let actual = run_edges::<B>(refine);+ for field in [FrontierIdx::EdgeLogprobBits, FrontierIdx::PathLogprobBits] {+ assert_close(+ "frontier",+ &frontier_floats(&actual.frontier, field),+ &frontier_floats(&expected.frontier, field),+ 1e-3,+ );+ }+ assert_close("tree edges", &packed_edges(&actual.packed_tree), &packed_edges(&expected.packed_tree), 1e-3);+ assert_close("child inputs", &actual.child_inputs, &expected.child_inputs, 2e-2);+ assert_close("child numbers", &actual.child_numbers, &expected.child_numbers, 1e-4);+ assert_eq!(actual.child_pools, expected.child_pools);+ assert_eq!(actual.slot_rows, expected.slot_rows);+ assert_eq!(actual.row_slots, expected.row_slots);+ });+ }+}++fn run_tree_input<B: Backend>() -> Vec<f32> {+ let context = create_context::<B>();+ let tree = tree();+ let width = 32u32;+ let bf16_buffer = |data: &[f32]| create_buffer_with_data::<B, bf16>(&context, &bf16s(data));+ let depth_embedding = bf16_buffer(&values((STRIDE + 1) * width as usize, 0.2, 1.0));+ let child_in = bf16_buffer(&values(CAPACITY * width as usize, 0.4, 1.0));+ let node_in = bf16_buffer(&values(SLOTS * width as usize, 0.6, 1.0));+ let frontier = create_buffer_with_data::<B, u32>(&context, &tree.frontier);+ let row_slots = create_buffer_with_data::<B, u32>(&context, &tree.row_slots);+ let mut output = bf16_buffer(&vec![0.0; ROWS * width as usize]);+ let kernel = <B::Kernels as Kernels>::ConfidenceHeadTreeInputKernel::new(&context).unwrap();+ let mut command_buffer = context.create_command_buffer(None, None).unwrap();+ kernel.encode(+ &depth_embedding,+ &child_in,+ &node_in,+ &frontier,+ &row_slots,+ &mut output,+ ROWS as u32,+ width,+ &mut command_buffer,+ );+ block_on(command_buffer.end_encoding().submit().wait_until_completed()).unwrap();+ floats(&buffer_to_vec::<B, bf16>(&context, &output))+}++#[uzu_test]+fn tree_input_matches_cpu() {+ let expected = run_tree_input::<Cpu>();+ assert!(expected[9 * 32..13 * 32].iter().all(|value| *value == 0.0));+ for_each_non_cpu_backend!(|B| assert_close("tree_input", &run_tree_input::<B>(), &expected, 1e-2));+}++fn run_tree_relations<B: Backend>() -> Vec<u32> {+ let context = create_context::<B>();+ let tree = tree();+ let frontier = create_buffer_with_data::<B, u32>(&context, &tree.frontier);+ let slot_ancestors = create_buffer_with_data::<B, u32>(&context, &tree.slot_ancestors);+ let slot_rows = create_buffer_with_data::<B, u32>(&context, &tree.slot_rows);+ let mut relations = create_buffer_with_data::<B, u32>(&context, &[0; ROWS * ROWS]);+ let kernel = <B::Kernels as Kernels>::ConfidenceHeadTreeRelationsKernel::new(&context).unwrap();+ let mut command_buffer = context.create_command_buffer(None, None).unwrap();+ kernel.encode(+ &frontier,+ &slot_ancestors,+ &slot_rows,+ &mut relations,+ ROWS as u32,+ STRIDE as u32,+ &mut command_buffer,+ );+ block_on(command_buffer.end_encoding().submit().wait_until_completed()).unwrap();+ buffer_to_vec::<B, u32>(&context, &relations)+}++#[uzu_test]+fn tree_relations_match_cpu() {+ let expected = run_tree_relations::<Cpu>();+ let relation = |query: usize, key: usize| expected[query * ROWS + key];+ assert_eq!([relation(6, 6), relation(6, 2), relation(2, 6), relation(6, 0), relation(0, 14)], [1, 2, 3, 4, 5]);+ assert_eq!([relation(6, 7), relation(9, 0), relation(6, 3)], [6, 7, 0]);+ for_each_non_cpu_backend!(|B| assert_eq!(run_tree_relations::<B>(), expected));+}++fn run_tree_attention<B: Backend>() -> Vec<f32> {+ let (heads, head_dim) = (2u32, 32u32);+ let context = create_context::<B>();+ let codes = (0..ROWS * ROWS)+ .map(|index| match (index / ROWS, index % ROWS) {+ (row, _) | (_, row) if (9..13).contains(&row) => 7,+ (query, key) if query == key => 1,+ _ => (index as u32 * 5 + (index / ROWS) as u32) % 7,+ })+ .collect::<Vec<_>>();+ let qkv =+ create_buffer_with_data::<B, bf16>(&context, &bf16s(&values(ROWS * 3 * (heads * head_dim) as usize, 0.6, 2.0)));+ let relations = create_buffer_with_data::<B, u32>(&context, &codes);+ let relation_bias = create_buffer_with_data::<B, bf16>(&context, &bf16s(&values(12, 2.2, 3.0)));+ let mut output =+ create_buffer_with_data::<B, bf16>(&context, &vec![bf16::ZERO; ROWS * (heads * head_dim) as usize]);+ let kernel = <B::Kernels as Kernels>::ConfidenceHeadTreeAttentionKernel::new(&context, heads, head_dim).unwrap();+ let mut command_buffer = context.create_command_buffer(None, None).unwrap();+ kernel.encode(&qkv, &relations, &relation_bias, &mut output, ROWS as u32, &mut command_buffer);+ block_on(command_buffer.end_encoding().submit().wait_until_completed()).unwrap();+ floats(&buffer_to_vec::<B, bf16>(&context, &output))+}++#[uzu_test]+fn tree_attention_matches_cpu() {+ let expected = run_tree_attention::<Cpu>();+ assert!(expected[9 * 64..13 * 64].iter().all(|value| *value == 0.0));+ for_each_non_cpu_backend!(|B| assert_close("tree_attention", &run_tree_attention::<B>(), &expected, 1e-2));+}diff --git a/crates/uzu-engine/unit/backends/common/kernel/mod.rs b/crates/uzu-engine/unit/backends/common/kernel/mod.rsindex 46caa148b..5389de780 100644--- a/crates/uzu-engine/unit/backends/common/kernel/mod.rs+++ b/crates/uzu-engine/unit/backends/common/kernel/mod.rs@@ -1,6 +1,7 @@mod activation_test;mod activation_transform_test;mod attention;+mod confidence_head_test;mod embedding;mod gated_act_mul_test;mod gdn;