A high-performance inference engine for AI models
fuse weaver top_children and frontier_selection (#1022)
CCYeh13b138ebaa94
diff --git a/crates/uzu-engine/src/backends/common/gpu_types/weaver.rs b/crates/uzu-engine/src/backends/common/gpu_types/weaver.rsindex 7906652ef..3d3d568a8 100644--- a/crates/uzu-engine/src/backends/common/gpu_types/weaver.rs+++ b/crates/uzu-engine/src/backends/common/gpu_types/weaver.rs@@ -1,5 +1,13 @@pub const CANDIDATES_MAX: u32 = 512;+#[repr(C)]+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum WeaverSelectionMode {+ Children,+ Frontier,+ Fused,+}+#[repr(C)]#[derive(Clone, Copy)]pub enum FrontierIdx {diff --git a/crates/uzu-engine/src/backends/cpu/kernel/weaver/mod.rs b/crates/uzu-engine/src/backends/cpu/kernel/weaver/mod.rsindex eeedee5d5..8febb3020 100644--- a/crates/uzu-engine/src/backends/cpu/kernel/weaver/mod.rs+++ b/crates/uzu-engine/src/backends/cpu/kernel/weaver/mod.rs@@ -1,2 +1 @@-pub mod weaver_frontier_select;-pub mod weaver_top_children;+pub mod weaver_selection;diff --git a/crates/uzu-engine/src/backends/cpu/kernel/weaver/weaver_frontier_select.rs b/crates/uzu-engine/src/backends/cpu/kernel/weaver/weaver_frontier_select.rsdeleted file mode 100644index 6ddf5760e..000000000--- a/crates/uzu-engine/src/backends/cpu/kernel/weaver/weaver_frontier_select.rs+++ /dev/null@@ -1,147 +0,0 @@-use std::range::Range;--use uzu_engine_macros::kernel;--use crate::backends::common::gpu_types::weaver::{- FRONTIER_MAX_SLOTS, FRONTIER_MAX_WIDTH, FRONTIER_NO_WINNER, FrontierIdx, MetadataIdx, PADDING_DEPTH, TreeIdx,-};--#[kernel(WeaverFrontierSelect)]-pub fn weaver_frontier_select(- frontier: *mut u32,- packed_tree: *mut u32,- slot_ancestors: *mut u32,- node_token_ids: *mut u32,- node_metadata: *mut u32,- node_ancestor_indices: *mut u32,- node_valid: *mut u32,- candidate_pool_ids: *const u32,- candidate_pool_logits: *const f32,- node_candidate_ids: *mut u32,- node_candidate_logits: *mut f32,- frontier_capacity: u32,- tree_slot_count: u32,- node_count: u32,- batch_start_slot: u32,- ancestor_stride: u32,- max_depth: u32,- lookahead_count: u32,- candidate_depth_count: u32,- candidates_per_depth: u32,-) {- if frontier_capacity == 0- || frontier_capacity > FRONTIER_MAX_SLOTS- || node_count == 0- || node_count > FRONTIER_MAX_WIDTH- || ancestor_stride == 0- || max_depth == 0- || tree_slot_count == 0- || batch_start_slot + node_count > tree_slot_count- || candidate_depth_count == 0- || candidates_per_depth == 0- {- return;- }- let (frontier_capacity, tree_slot_count, node_count, ancestor_stride) =- (frontier_capacity as usize, tree_slot_count as usize, node_count as usize, ancestor_stride as usize);- let (candidate_depth_count, candidates_per_depth) = (candidate_depth_count as usize, candidates_per_depth as usize);- let pool_len = candidate_depth_count * candidates_per_depth;- let frontier = unsafe { std::slice::from_raw_parts_mut(frontier, FrontierIdx::COUNT * frontier_capacity) };- let packed_tree = unsafe { std::slice::from_raw_parts_mut(packed_tree, TreeIdx::COUNT * tree_slot_count) };- let slot_ancestors = unsafe { std::slice::from_raw_parts_mut(slot_ancestors, tree_slot_count * ancestor_stride) };- let node_token_ids = unsafe { std::slice::from_raw_parts_mut(node_token_ids, node_count) };- let node_metadata = unsafe { std::slice::from_raw_parts_mut(node_metadata, MetadataIdx::COUNT * node_count) };- let node_ancestor_indices =- unsafe { std::slice::from_raw_parts_mut(node_ancestor_indices, node_count * ancestor_stride) };- let node_valid = unsafe { std::slice::from_raw_parts_mut(node_valid, node_count) };- let candidate_pool_ids = unsafe { std::slice::from_raw_parts(candidate_pool_ids, pool_len) };- let candidate_pool_logits = unsafe { std::slice::from_raw_parts(candidate_pool_logits, pool_len) };- let node_candidate_ids =- unsafe { std::slice::from_raw_parts_mut(node_candidate_ids, node_count * candidates_per_depth) };- let node_candidate_logits =- unsafe { std::slice::from_raw_parts_mut(node_candidate_logits, node_count * candidates_per_depth) };-- for node in 0..node_count {- let (mut key, mut parent, mut token, mut winner) =- (0, FRONTIER_NO_WINNER, FRONTIER_NO_WINNER, FRONTIER_NO_WINNER);- for slot in 0..frontier_capacity {- if frontier[FrontierIdx::Active as usize * frontier_capacity + slot] == 0 {- continue;- }- let score_key = frontier[FrontierIdx::PathScoreKey as usize * frontier_capacity + slot];- let expandable =- u32::from(frontier[FrontierIdx::Depth as usize * frontier_capacity + slot] < lookahead_count);- let next = (- (expandable << 31) | (score_key >> 1),- frontier[FrontierIdx::ParentSlot as usize * frontier_capacity + slot],- frontier[FrontierIdx::TokenId as usize * frontier_capacity + slot],- );- if next.0 > key || (next.0 == key && (next.1 < parent || (next.1 == parent && next.2 < token))) {- (key, parent, token, winner) = (next.0, next.1, next.2, slot as u32);- }- }- let real = winner != FRONTIER_NO_WINNER;- let winner = if real {- winner as usize- } else {- 0- };- let tree_slot = batch_start_slot as usize + node;- let field_value = |field: FrontierIdx| u32::from(real) * frontier[field as usize * frontier_capacity + winner];- let token = field_value(FrontierIdx::TokenId);- let depth = field_value(FrontierIdx::Depth);- let cumulative_logprob = field_value(FrontierIdx::PathLogprobBits);- let logprob = field_value(FrontierIdx::EdgeLogprobBits);-- packed_tree[TreeIdx::TokenId as usize * tree_slot_count + tree_slot] = token;- packed_tree[TreeIdx::ParentSlot as usize * tree_slot_count + tree_slot] = if real {- parent- } else {- FRONTIER_NO_WINNER- };- packed_tree[TreeIdx::Depth as usize * tree_slot_count + tree_slot] = depth;- packed_tree[TreeIdx::PathLogprobBits as usize * tree_slot_count + tree_slot] = cumulative_logprob;- packed_tree[TreeIdx::EdgeLogprobBits as usize * tree_slot_count + tree_slot] = logprob;- packed_tree[TreeIdx::Valid as usize * tree_slot_count + tree_slot] = u32::from(real);-- if real {- frontier[FrontierIdx::Active as usize * frontier_capacity + winner] = 0;- }-- let parent_slot = if real && (parent as usize) < tree_slot_count {- parent as usize- } else {- 0- };- for index in 0..ancestor_stride {- let ancestor = if real && index + 1 < depth as usize {- slot_ancestors[parent_slot * ancestor_stride + index]- } else if real && index + 1 == depth as usize {- parent_slot as u32- } else {- 0- };- slot_ancestors[tree_slot * ancestor_stride + index] = ancestor;- node_ancestor_indices[node * ancestor_stride + index] = ancestor;- }-- node_token_ids[node] = token;- let expandable = depth < lookahead_count;- node_metadata[MetadataIdx::Depth as usize * node_count + node] = if expandable {- depth- } else {- PADDING_DEPTH- };- node_metadata[MetadataIdx::AncestorCount as usize * node_count + node] = depth;- node_metadata[MetadataIdx::TreeSlot as usize * node_count + node] = tree_slot as u32;- node_valid[node] = u32::from(real && expandable);-- if (depth as usize) < candidate_depth_count {- let source =- Range::from(depth as usize * candidates_per_depth..(depth as usize + 1) * candidates_per_depth);- let destination = Range::from(node * candidates_per_depth..(node + 1) * candidates_per_depth);- node_candidate_ids[destination].copy_from_slice(&candidate_pool_ids[source]);- node_candidate_logits[destination].copy_from_slice(&candidate_pool_logits[source]);- }- }-}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.rsnew file mode 100644index 000000000..02e766fe6--- /dev/null+++ b/crates/uzu-engine/src/backends/cpu/kernel/weaver/weaver_selection.rs@@ -0,0 +1,263 @@+use std::range::Range;++use half::bf16;+use uzu_engine_macros::kernel;++use crate::{+ backends::common::gpu_types::weaver::{+ CANDIDATES_MAX, FRONTIER_MAX_SLOTS, FRONTIER_MAX_WIDTH, FRONTIER_NO_WINNER, FrontierIdx, MetadataIdx,+ PADDING_DEPTH, TreeIdx, WeaverSelectionMode,+ },+ encodable_block::sampling::{gumbel_float, revidx},+};++#[kernel(WeaverSelect)]+#[variants(BLOCK_THREADS, 256, 1024)]+pub fn weaver_select<const BLOCK_THREADS: u32>(+ #[optional(mode != WeaverSelectionMode::Frontier)] residual_logits: Option<*const bf16>,+ #[optional(mode != WeaverSelectionMode::Frontier)] depth_seeds: Option<*const u64>,+ frontier: *mut u32,+ packed_tree: *mut u32,+ #[optional(mode != WeaverSelectionMode::Children)] slot_ancestors: Option<*mut u32>,+ #[optional(mode != WeaverSelectionMode::Children)] node_token_ids: Option<*mut u32>,+ node_metadata: *mut u32,+ #[optional(mode != WeaverSelectionMode::Children)] node_ancestor_indices: Option<*mut u32>,+ node_valid: *mut u32,+ candidate_pool_ids: *const u32,+ candidate_pool_logits: *const f32,+ node_candidate_ids: *mut u32,+ node_candidate_logits: *mut f32,+ children_rows: u32,+ children_from_pool: u32,+ candidates: u32,+ expand_width: u32,+ vocab_size: u32,+ frontier_capacity: u32,+ tree_slot_count: u32,+ node_count: u32,+ batch_start_slot: u32,+ ancestor_stride: u32,+ lookahead_count: u32,+ candidate_depth_count: u32,+ #[optional(has_prune_noise)] prune_noise_scale: Option<f32>,+ #[specialize] mode: WeaverSelectionMode,+ #[specialize] has_prune_noise: bool,+) {+ if mode != WeaverSelectionMode::Frontier+ && candidates != 0+ && candidates <= CANDIDATES_MAX+ && expand_width != 0+ && expand_width <= candidates+ && frontier_capacity != 0+ && tree_slot_count != 0+ {+ let residual_logits = residual_logits.unwrap();+ let depth_seeds = depth_seeds.unwrap();+ let (candidate_logits, candidate_ids) = if children_from_pool != 0 {+ (candidate_pool_logits, candidate_pool_ids)+ } else {+ (node_candidate_logits as *const f32, node_candidate_ids as *const u32)+ };++ let rows = children_rows as usize;+ let candidates = candidates as usize;+ let expand_width = expand_width as usize;+ let frontier_capacity = frontier_capacity as usize;+ let tree_slot_count = tree_slot_count as usize;+ for row in 0..rows {+ if unsafe { *node_valid.add(row) == 0 } {+ continue;+ }+ let tree_slot = unsafe { *node_metadata.add(MetadataIdx::TreeSlot as usize * rows + row) as usize };+ if tree_slot >= tree_slot_count {+ continue;+ }+ let base = row * candidates;+ let depth = unsafe { *node_metadata.add(MetadataIdx::Depth as usize * rows + row) } as usize;+ let seed = unsafe { *depth_seeds.add(depth) };+ let token = |index: usize| unsafe { *candidate_ids.add(base + index) };+ let logits = (0..candidates)+ .map(|index| unsafe {+ *candidate_logits.add(base + index) + (*residual_logits.add(base + index)).to_f32()+ })+ .collect::<Vec<_>>();+ let max = logits.iter().copied().fold(f32::NEG_INFINITY, f32::max);+ let log_sum = logits.iter().map(|value| (value - max).exp()).sum::<f32>().ln() + max;+ let perturbed = (0..candidates)+ .map(|index| logits[index] + gumbel_float(seed, revidx(token(index), vocab_size)))+ .collect::<Vec<_>>();+ // Final pruning weighs each edge by the pool softmax of logits plus the target's noise scaled by 1 / sigma.+ let prune = has_prune_noise.then(|| {+ let scale = prune_noise_scale.unwrap();+ let prune_logits = (0..candidates)+ .map(|index| logits[index] + scale * gumbel_float(seed, revidx(token(index), vocab_size)))+ .collect::<Vec<_>>();+ let prune_max = prune_logits.iter().copied().fold(f32::NEG_INFINITY, f32::max);+ let prune_log_sum =+ prune_logits.iter().map(|value| (value - prune_max).exp()).sum::<f32>().ln() + prune_max;+ (prune_logits, prune_log_sum)+ });+ let mut indices = (0..candidates).collect::<Vec<_>>();+ indices.sort_by(|&left, &right| {+ perturbed[right].total_cmp(&perturbed[left]).then_with(|| token(left).cmp(&token(right)))+ });+ for (rank, index) in indices.into_iter().take(expand_width).enumerate() {+ let slot = tree_slot * expand_width + rank;+ if slot >= frontier_capacity {+ continue;+ }+ let model_logprob = logits[index] - log_sum;+ unsafe {+ let path_logprob = f32::from_bits(+ *packed_tree.add(TreeIdx::PathLogprobBits as usize * tree_slot_count + tree_slot),+ );+ let depth = *packed_tree.add(TreeIdx::Depth as usize * tree_slot_count + tree_slot) + 1;+ let cumulative_logprob = path_logprob + model_logprob;+ let edge_logprob = prune+ .as_ref()+ .map_or(model_logprob, |(prune_logits, prune_log_sum)| prune_logits[index] - prune_log_sum);+ *frontier.add(FrontierIdx::TokenId as usize * frontier_capacity + slot) = token(index);+ *frontier.add(FrontierIdx::ParentSlot as usize * frontier_capacity + slot) = tree_slot as u32;+ *frontier.add(FrontierIdx::Depth as usize * frontier_capacity + slot) = depth;+ *frontier.add(FrontierIdx::PathLogprobBits as usize * frontier_capacity + slot) =+ cumulative_logprob.to_bits();+ *frontier.add(FrontierIdx::EdgeLogprobBits as usize * frontier_capacity + slot) =+ edge_logprob.to_bits();+ *frontier.add(FrontierIdx::PathScoreKey as usize * frontier_capacity + slot) =+ top_k_score_key(cumulative_logprob);+ *frontier.add(FrontierIdx::Active as usize * frontier_capacity + slot) = 1;+ }+ }+ }+ }+ if mode != WeaverSelectionMode::Children {+ let slot_ancestors = slot_ancestors.unwrap();+ let node_token_ids = node_token_ids.unwrap();+ let node_ancestor_indices = node_ancestor_indices.unwrap();+ if frontier_capacity == 0+ || frontier_capacity > FRONTIER_MAX_SLOTS+ || node_count == 0+ || node_count > FRONTIER_MAX_WIDTH+ || ancestor_stride == 0+ || tree_slot_count == 0+ || batch_start_slot + node_count > tree_slot_count+ || candidate_depth_count == 0+ || candidates == 0+ {+ return;+ }+ let (frontier_capacity, tree_slot_count, node_count, ancestor_stride) =+ (frontier_capacity as usize, tree_slot_count as usize, node_count as usize, ancestor_stride as usize);+ let (candidate_depth_count, candidates) = (candidate_depth_count as usize, candidates as usize);+ let pool_len = candidate_depth_count * candidates;+ let frontier = unsafe { std::slice::from_raw_parts_mut(frontier, FrontierIdx::COUNT * frontier_capacity) };+ let packed_tree = unsafe { std::slice::from_raw_parts_mut(packed_tree, TreeIdx::COUNT * tree_slot_count) };+ let slot_ancestors =+ unsafe { std::slice::from_raw_parts_mut(slot_ancestors, tree_slot_count * ancestor_stride) };+ let node_token_ids = unsafe { std::slice::from_raw_parts_mut(node_token_ids, node_count) };+ let node_metadata = unsafe { std::slice::from_raw_parts_mut(node_metadata, MetadataIdx::COUNT * node_count) };+ let node_ancestor_indices =+ unsafe { std::slice::from_raw_parts_mut(node_ancestor_indices, node_count * ancestor_stride) };+ let node_valid = unsafe { std::slice::from_raw_parts_mut(node_valid, node_count) };+ let candidate_pool_ids = unsafe { std::slice::from_raw_parts(candidate_pool_ids, pool_len) };+ let candidate_pool_logits = unsafe { std::slice::from_raw_parts(candidate_pool_logits, pool_len) };+ let node_candidate_ids = unsafe { std::slice::from_raw_parts_mut(node_candidate_ids, node_count * candidates) };+ let node_candidate_logits =+ unsafe { std::slice::from_raw_parts_mut(node_candidate_logits, node_count * candidates) };++ for node in 0..node_count {+ let (mut key, mut parent, mut token, mut winner) =+ (0, FRONTIER_NO_WINNER, FRONTIER_NO_WINNER, FRONTIER_NO_WINNER);+ for slot in 0..frontier_capacity {+ if frontier[FrontierIdx::Active as usize * frontier_capacity + slot] == 0 {+ continue;+ }+ let score_key = frontier[FrontierIdx::PathScoreKey as usize * frontier_capacity + slot];+ let expandable =+ u32::from(frontier[FrontierIdx::Depth as usize * frontier_capacity + slot] < lookahead_count);+ let next = (+ (expandable << 31) | (score_key >> 1),+ frontier[FrontierIdx::ParentSlot as usize * frontier_capacity + slot],+ frontier[FrontierIdx::TokenId as usize * frontier_capacity + slot],+ );+ if next.0 > key || (next.0 == key && (next.1 < parent || (next.1 == parent && next.2 < token))) {+ (key, parent, token, winner) = (next.0, next.1, next.2, slot as u32);+ }+ }+ let real = winner != FRONTIER_NO_WINNER;+ let winner = if real {+ winner as usize+ } else {+ 0+ };+ let tree_slot = batch_start_slot as usize + node;+ let field_value =+ |field: FrontierIdx| u32::from(real) * frontier[field as usize * frontier_capacity + winner];+ let token = field_value(FrontierIdx::TokenId);+ let depth = field_value(FrontierIdx::Depth);+ let cumulative_logprob = field_value(FrontierIdx::PathLogprobBits);+ let logprob = field_value(FrontierIdx::EdgeLogprobBits);++ packed_tree[TreeIdx::TokenId as usize * tree_slot_count + tree_slot] = token;+ packed_tree[TreeIdx::ParentSlot as usize * tree_slot_count + tree_slot] = if real {+ parent+ } else {+ FRONTIER_NO_WINNER+ };+ packed_tree[TreeIdx::Depth as usize * tree_slot_count + tree_slot] = depth;+ packed_tree[TreeIdx::PathLogprobBits as usize * tree_slot_count + tree_slot] = cumulative_logprob;+ packed_tree[TreeIdx::EdgeLogprobBits as usize * tree_slot_count + tree_slot] = logprob;+ packed_tree[TreeIdx::Valid as usize * tree_slot_count + tree_slot] = u32::from(real);++ if real {+ frontier[FrontierIdx::Active as usize * frontier_capacity + winner] = 0;+ }++ let parent_slot = if real && (parent as usize) < tree_slot_count {+ parent as usize+ } else {+ 0+ };+ for index in 0..ancestor_stride {+ let ancestor = if real && index + 1 < depth as usize {+ slot_ancestors[parent_slot * ancestor_stride + index]+ } else if real && index + 1 == depth as usize {+ parent_slot as u32+ } else {+ 0+ };+ slot_ancestors[tree_slot * ancestor_stride + index] = ancestor;+ node_ancestor_indices[node * ancestor_stride + index] = ancestor;+ }++ node_token_ids[node] = token;+ let expandable = depth < lookahead_count;+ node_metadata[MetadataIdx::Depth as usize * node_count + node] = if expandable {+ depth+ } else {+ PADDING_DEPTH+ };+ node_metadata[MetadataIdx::AncestorCount as usize * node_count + node] = depth;+ node_metadata[MetadataIdx::TreeSlot as usize * node_count + node] = tree_slot as u32;+ node_valid[node] = u32::from(real && expandable);++ if (depth as usize) < candidate_depth_count {+ let source = Range::from(depth as usize * candidates..(depth as usize + 1) * candidates);+ let destination = Range::from(node * candidates..(node + 1) * candidates);+ node_candidate_ids[destination].copy_from_slice(&candidate_pool_ids[source]);+ node_candidate_logits[destination].copy_from_slice(&candidate_pool_logits[source]);+ }+ }+ }+}++const F32_SIGN_BIT: u32 = 1 << (u32::BITS - 1);++fn top_k_score_key(score: f32) -> u32 {+ let bits = score.to_bits();+ if bits & F32_SIGN_BIT == 0 {+ bits ^ F32_SIGN_BIT+ } else {+ !bits+ }+}diff --git a/crates/uzu-engine/src/backends/cpu/kernel/weaver/weaver_top_children.rs b/crates/uzu-engine/src/backends/cpu/kernel/weaver/weaver_top_children.rsdeleted file mode 100644index 3a3d144c8..000000000--- a/crates/uzu-engine/src/backends/cpu/kernel/weaver/weaver_top_children.rs+++ /dev/null@@ -1,115 +0,0 @@-use half::bf16;-use uzu_engine_macros::kernel;--use crate::{- backends::common::gpu_types::weaver::{CANDIDATES_MAX, FrontierIdx, MetadataIdx, TreeIdx},- encodable_block::sampling::{gumbel_float, revidx},-};--#[kernel(WeaverTopChildren)]-pub fn weaver_top_children(- residual_logits: *const bf16,- candidate_logits: *const f32,- candidate_ids: *const u32,- depth_seeds: *const u64,- node_metadata: *const u32,- packed_tree: *const u32,- node_valid: *const u32,- frontier: *mut u32,- rows: u32,- candidates: u32,- expand_width: u32,- vocab_size: u32,- frontier_capacity: u32,- tree_slot_count: u32,- #[optional(has_prune_noise)] prune_noise_scale: Option<f32>,- #[specialize] has_prune_noise: bool,-) {- let rows = rows as usize;- let candidates = candidates as usize;- let expand_width = expand_width as usize;- let frontier_capacity = frontier_capacity as usize;- let tree_slot_count = tree_slot_count as usize;- if candidates == 0- || candidates > CANDIDATES_MAX as usize- || expand_width == 0- || expand_width > candidates- || frontier_capacity == 0- || tree_slot_count == 0- {- return;- }- for row in 0..rows {- if unsafe { *node_valid.add(row) == 0 } {- continue;- }- let tree_slot = unsafe { *node_metadata.add(MetadataIdx::TreeSlot as usize * rows + row) as usize };- if tree_slot >= tree_slot_count {- continue;- }- let base = row * candidates;- let depth = unsafe { *node_metadata.add(MetadataIdx::Depth as usize * rows + row) } as usize;- let seed = unsafe { *depth_seeds.add(depth) };- let token = |index: usize| unsafe { *candidate_ids.add(base + index) };- let logits = (0..candidates)- .map(|index| unsafe { *candidate_logits.add(base + index) + (*residual_logits.add(base + index)).to_f32() })- .collect::<Vec<_>>();- let max = logits.iter().copied().fold(f32::NEG_INFINITY, f32::max);- let log_sum = logits.iter().map(|value| (value - max).exp()).sum::<f32>().ln() + max;- let perturbed = (0..candidates)- .map(|index| logits[index] + gumbel_float(seed, revidx(token(index), vocab_size)))- .collect::<Vec<_>>();- // Final pruning weighs each edge by the pool softmax of logits plus the target's noise scaled by 1 / sigma.- let prune = has_prune_noise.then(|| {- let scale = prune_noise_scale.unwrap();- let prune_logits = (0..candidates)- .map(|index| logits[index] + scale * gumbel_float(seed, revidx(token(index), vocab_size)))- .collect::<Vec<_>>();- let prune_max = prune_logits.iter().copied().fold(f32::NEG_INFINITY, f32::max);- let prune_log_sum =- prune_logits.iter().map(|value| (value - prune_max).exp()).sum::<f32>().ln() + prune_max;- (prune_logits, prune_log_sum)- });- let mut indices = (0..candidates).collect::<Vec<_>>();- indices.sort_by(|&left, &right| {- perturbed[right].total_cmp(&perturbed[left]).then_with(|| token(left).cmp(&token(right)))- });- for (rank, index) in indices.into_iter().take(expand_width).enumerate() {- let slot = tree_slot * expand_width + rank;- if slot >= frontier_capacity {- continue;- }- let model_logprob = logits[index] - log_sum;- unsafe {- let path_logprob =- f32::from_bits(*packed_tree.add(TreeIdx::PathLogprobBits as usize * tree_slot_count + tree_slot));- let depth = *packed_tree.add(TreeIdx::Depth as usize * tree_slot_count + tree_slot) + 1;- let cumulative_logprob = path_logprob + model_logprob;- let edge_logprob = prune- .as_ref()- .map_or(model_logprob, |(prune_logits, prune_log_sum)| prune_logits[index] - prune_log_sum);- *frontier.add(FrontierIdx::TokenId as usize * frontier_capacity + slot) = token(index);- *frontier.add(FrontierIdx::ParentSlot as usize * frontier_capacity + slot) = tree_slot as u32;- *frontier.add(FrontierIdx::Depth as usize * frontier_capacity + slot) = depth;- *frontier.add(FrontierIdx::PathLogprobBits as usize * frontier_capacity + slot) =- cumulative_logprob.to_bits();- *frontier.add(FrontierIdx::EdgeLogprobBits as usize * frontier_capacity + slot) =- edge_logprob.to_bits();- *frontier.add(FrontierIdx::PathScoreKey as usize * frontier_capacity + slot) =- top_k_score_key(cumulative_logprob);- *frontier.add(FrontierIdx::Active as usize * frontier_capacity + slot) = 1;- }- }- }-}--const F32_SIGN_BIT: u32 = 1 << (u32::BITS - 1);--fn top_k_score_key(score: f32) -> u32 {- let bits = score.to_bits();- if bits & F32_SIGN_BIT == 0 {- bits ^ F32_SIGN_BIT- } else {- !bits- }-}diff --git a/crates/uzu-engine/src/backends/metal/kernel/generated/weaver.h b/crates/uzu-engine/src/backends/metal/kernel/generated/weaver.hindex 9533a3269..c9ea22ba1 100644--- a/crates/uzu-engine/src/backends/metal/kernel/generated/weaver.h+++ b/crates/uzu-engine/src/backends/metal/kernel/generated/weaver.h@@ -7,6 +7,12 @@ using namespace metal;namespace uzu::weaver {static constant constexpr uint32_t CANDIDATES_MAX = 512;+enum class WeaverSelectionMode : uint32_t {+ Children = 0,+ Frontier = 1,+ Fused = 2,+};+enum class FrontierIdx : uint32_t {TokenId = 0,ParentSlot = 1,diff --git a/crates/uzu-engine/src/backends/metal/kernel/mod.rs b/crates/uzu-engine/src/backends/metal/kernel/mod.rsindex 856bcf824..82de4ac0e 100644--- a/crates/uzu-engine/src/backends/metal/kernel/mod.rs+++ b/crates/uzu-engine/src/backends/metal/kernel/mod.rs@@ -3,9 +3,8 @@ use crate::backends::{metal::{Metal,buffer::MetalBufferExt,- gpu_types::{- gemm::{gemm_tiling_simdgroups_per_column, gemm_tiling_simdgroups_per_k, gemm_tiling_simdgroups_per_row},- weaver::{FRONTIER_SELECT_THREADS, TOP_CHILDREN_THREADS},+ gpu_types::gemm::{+ gemm_tiling_simdgroups_per_column, gemm_tiling_simdgroups_per_k, gemm_tiling_simdgroups_per_row,},},};diff --git a/crates/uzu-engine/src/backends/metal/kernel/weaver/weaver_frontier_select.metal b/crates/uzu-engine/src/backends/metal/kernel/weaver/weaver_frontier_select.metaldeleted file mode 100644index 591601ff2..000000000--- a/crates/uzu-engine/src/backends/metal/kernel/weaver/weaver_frontier_select.metal+++ /dev/null@@ -1,154 +0,0 @@-#include <metal_simdgroup>-#include <metal_stdlib>-#include "../common/dsl.h"-#include "../common/thread_context.h"-#include "weaver_frontier.h"--using namespace metal;--PUBLIC KERNEL(WeaverFrontierSelect)(- device uint* frontier,- device uint* packed_tree,- device uint* slot_ancestors,- device uint* node_token_ids,- device uint* node_metadata,- device uint* node_ancestor_indices,- device uint* node_valid,- const device uint* candidate_pool_ids,- const device float* candidate_pool_logits,- device uint* node_candidate_ids,- device float* node_candidate_logits,- constant uint& frontier_capacity,- constant uint& tree_slot_count,- constant uint& node_count,- constant uint& batch_start_slot,- constant uint& ancestor_stride,- constant uint& max_depth,- constant uint& lookahead_count,- constant uint& candidate_depth_count,- constant uint& candidates_per_depth,- threadgroup uint4 reduce[FRONTIER_SELECT_SIMDGROUPS],- threadgroup uint winner_slot[FRONTIER_MAX_WIDTH],- threadgroup uint node_candidate_depth[FRONTIER_MAX_WIDTH],- const ThreadContext thread_context,- const uint group_index GROUPS(1),- const uint lid THREADS(FRONTIER_SELECT_THREADS)-) {- (void)group_index;- if (frontier_capacity == 0 || frontier_capacity > FRONTIER_MAX_SLOTS || node_count == 0 ||- node_count > FRONTIER_MAX_WIDTH || ancestor_stride == 0 || max_depth == 0 || tree_slot_count == 0 ||- batch_start_slot + node_count > tree_slot_count || candidate_depth_count == 0 || candidates_per_depth == 0) {- return;- }-- bool entry_active[FRONTIER_ENTRIES_PER_THREAD];- for (uint entry = 0; entry < FRONTIER_ENTRIES_PER_THREAD; ++entry) {- const uint slot = lid + entry * FRONTIER_SELECT_THREADS;- entry_active[entry] =- slot < frontier_capacity && frontier[uint(FrontierIdx::Active) * frontier_capacity + slot] != 0u;- }-- for (uint child = 0; child < node_count; ++child) {- uint4 local = uint4(0u, FRONTIER_NO_WINNER, FRONTIER_NO_WINNER, FRONTIER_NO_WINNER);- for (uint entry = 0; entry < FRONTIER_ENTRIES_PER_THREAD; ++entry) {- const uint slot = lid + entry * FRONTIER_SELECT_THREADS;- if (entry_active[entry]) {- const uint depth = frontier[uint(FrontierIdx::Depth) * frontier_capacity + slot];- const uint key = frontier[uint(FrontierIdx::PathScoreKey) * frontier_capacity + slot];- const uint parent = frontier[uint(FrontierIdx::ParentSlot) * frontier_capacity + slot];- const uint token = frontier[uint(FrontierIdx::TokenId) * frontier_capacity + slot];- const uint packed_key = ((depth < lookahead_count ? 1u : 0u) << 31) | (key >> 1);- if (packed_key > local.x ||- (packed_key == local.x && (parent < local.y || (parent == local.y && token < local.z)))) {- local = uint4(packed_key, parent, token, slot);- }- }- }-- uint4 simd;- simd.x = simd_max(local.x);- simd.y = simd_min(local.x == simd.x ? local.y : FRONTIER_NO_WINNER);- simd.z = simd_min(all(local.xy == simd.xy) ? local.z : FRONTIER_NO_WINNER);- simd.w = simd_min(all(local.xyz == simd.xyz) ? local.w : FRONTIER_NO_WINNER);- if (thread_context.simd_lane_id == 0) {- reduce[thread_context.simdgroup_index] = simd;- }- threadgroup_barrier(mem_flags::mem_threadgroup);-- if (thread_context.simdgroup_index == 0) {- const uint4 partial = thread_context.simd_lane_id < FRONTIER_SELECT_SIMDGROUPS- ? reduce[thread_context.simd_lane_id]- : uint4(0u, FRONTIER_NO_WINNER, FRONTIER_NO_WINNER, FRONTIER_NO_WINNER);- uint4 selected;- selected.x = simd_max(partial.x);- selected.y = simd_min(partial.x == selected.x ? partial.y : FRONTIER_NO_WINNER);- selected.z = simd_min(all(partial.xy == selected.xy) ? partial.z : FRONTIER_NO_WINNER);- selected.w = simd_min(all(partial.xyz == selected.xyz) ? partial.w : FRONTIER_NO_WINNER);- if (thread_context.simd_lane_id == 0) {- winner_slot[child] = selected.w;- }- }- threadgroup_barrier(mem_flags::mem_threadgroup);-- const uint selected = winner_slot[child];- for (uint entry = 0; entry < FRONTIER_ENTRIES_PER_THREAD; ++entry) {- entry_active[entry] = entry_active[entry] && (lid + entry * FRONTIER_SELECT_THREADS) != selected;- }- }-- if (lid < node_count) {- const uint node = lid;- const uint slot = winner_slot[node];- const bool real = slot != FRONTIER_NO_WINNER;- const uint tree_slot = batch_start_slot + node;-- const uint token = real ? frontier[uint(FrontierIdx::TokenId) * frontier_capacity + slot] : 0u;- const uint parent = real ? frontier[uint(FrontierIdx::ParentSlot) * frontier_capacity + slot] : FRONTIER_NO_WINNER;- const uint depth = real ? frontier[uint(FrontierIdx::Depth) * frontier_capacity + slot] : 0u;- const uint cumulative_logprob = real ? frontier[uint(FrontierIdx::PathLogprobBits) * frontier_capacity + slot] : 0u;- const uint logprob = real ? frontier[uint(FrontierIdx::EdgeLogprobBits) * frontier_capacity + slot] : 0u;-- packed_tree[uint(TreeIdx::TokenId) * tree_slot_count + tree_slot] = token;- packed_tree[uint(TreeIdx::ParentSlot) * tree_slot_count + tree_slot] = parent;- packed_tree[uint(TreeIdx::Depth) * tree_slot_count + tree_slot] = depth;- packed_tree[uint(TreeIdx::PathLogprobBits) * tree_slot_count + tree_slot] = cumulative_logprob;- packed_tree[uint(TreeIdx::EdgeLogprobBits) * tree_slot_count + tree_slot] = logprob;- packed_tree[uint(TreeIdx::Valid) * tree_slot_count + tree_slot] = real ? 1u : 0u;-- if (real) {- frontier[uint(FrontierIdx::Active) * frontier_capacity + slot] = 0u;- }-- const uint parent_slot = real && parent < tree_slot_count ? parent : 0u;- for (uint index = 0; index < ancestor_stride; ++index) {- const uint ancestor =- real && index + 1u <= depth- ? (index + 1u == depth ? parent_slot : slot_ancestors[parent_slot * ancestor_stride + index])- : 0u;- slot_ancestors[tree_slot * ancestor_stride + index] = ancestor;- node_ancestor_indices[node * ancestor_stride + index] = ancestor;- }-- node_token_ids[node] = token;- node_metadata[uint(MetadataIdx::Depth) * node_count + node] = depth < lookahead_count ? depth : PADDING_DEPTH;- node_metadata[uint(MetadataIdx::AncestorCount) * node_count + node] = depth;- node_metadata[uint(MetadataIdx::TreeSlot) * node_count + node] = tree_slot;- node_valid[node] = real && depth < lookahead_count ? 1u : 0u;-- node_candidate_depth[node] = depth;- }-- threadgroup_barrier(mem_flags::mem_threadgroup);-- for (uint node = 0; node < node_count; ++node) {- if (node_candidate_depth[node] >= candidate_depth_count) {- continue;- }- const uint source = node_candidate_depth[node] * candidates_per_depth;- const uint destination = node * candidates_per_depth;- for (uint candidate = lid; candidate < candidates_per_depth; candidate += FRONTIER_SELECT_THREADS) {- node_candidate_ids[destination + candidate] = candidate_pool_ids[source + candidate];- node_candidate_logits[destination + candidate] = candidate_pool_logits[source + candidate];- }- }-}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.metalnew file mode 100644index 000000000..92d7784ab--- /dev/null+++ b/crates/uzu-engine/src/backends/metal/kernel/weaver/weaver_selection.metal@@ -0,0 +1,396 @@+#include <metal_stdlib>+#include "../common/defines.h"+#include "../common/dsl.h"+#include "../common/thread_context.h"+#include "../common/threadgroup_reduce.h"+#include "../common/top_k.h"+#include "../rng.h"+#include "weaver_frontier.h"++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)));+}++template <uint BLOCK_THREADS>+VARIANTS(BLOCK_THREADS, 256, 1024)+PUBLIC KERNEL(WeaverSelect)(+ const device bfloat* residual_logits OPTIONAL(mode != WeaverSelectionMode::Frontier),+ const device uint64_t* depth_seeds OPTIONAL(mode != WeaverSelectionMode::Frontier),+ device uint* frontier,+ device uint* packed_tree,+ device uint* slot_ancestors OPTIONAL(mode != WeaverSelectionMode::Children),+ device uint* node_token_ids OPTIONAL(mode != WeaverSelectionMode::Children),+ device uint* node_metadata,+ device uint* node_ancestor_indices OPTIONAL(mode != WeaverSelectionMode::Children),+ device uint* node_valid,+ const device uint* candidate_pool_ids,+ const device float* candidate_pool_logits,+ device uint* node_candidate_ids,+ device float* node_candidate_logits,+ constant uint& children_rows,+ constant uint& children_from_pool,+ constant uint& candidates,+ constant uint& expand_width,+ constant uint& vocab_size,+ constant uint& frontier_capacity,+ constant uint& tree_slot_count,+ constant uint& node_count,+ constant uint& batch_start_slot,+ constant uint& ancestor_stride,+ constant uint& lookahead_count,+ constant uint& candidate_depth_count,+ constant float& prune_noise_scale OPTIONAL(has_prune_noise),+ const WeaverSelectionMode mode SPECIALIZE,+ const bool has_prune_noise SPECIALIZE,+ threadgroup float shared_float[TOP_CHILDREN_SIMDGROUPS * (BLOCK_THREADS / TOP_CHILDREN_THREADS)],+ threadgroup uint4 reduce_storage[FRONTIER_SELECT_SIMDGROUPS * (BLOCK_THREADS / TOP_CHILDREN_THREADS)],+ threadgroup float statistics[2 * (BLOCK_THREADS / TOP_CHILDREN_THREADS)],+ threadgroup uint top_winners[2 * (BLOCK_THREADS / TOP_CHILDREN_THREADS)],+ threadgroup uint winner_slot[FRONTIER_MAX_WIDTH],+ threadgroup uint node_candidate_depth[FRONTIER_MAX_WIDTH],+ const ThreadContext global_context,+ const uint group_index GROUPS(if mode == WeaverSelectionMode::Children { children_rows } else {1}),+ const uint global_lid THREADS(BLOCK_THREADS)+) {+ if (mode != WeaverSelectionMode::Frontier && candidates != 0 && candidates <= CANDIDATES_MAX && expand_width != 0 &&+ expand_width <= candidates && frontier_capacity != 0 && tree_slot_count != 0) {+ const uint rows = children_rows;+ const uint block = global_lid / TOP_CHILDREN_THREADS;+ const uint row = mode == WeaverSelectionMode::Fused ? block : group_index;+ const uint lid = global_lid % TOP_CHILDREN_THREADS;+ ThreadContext thread_context = global_context;+ thread_context.simdgroup_index %= TOP_CHILDREN_SIMDGROUPS;+ threadgroup float* reduce_float = shared_float + block * TOP_CHILDREN_SIMDGROUPS;+ threadgroup uint* reduce_score =+ reinterpret_cast<threadgroup uint*>(reduce_storage) + block * TOP_CHILDREN_SIMDGROUPS * 3;+ threadgroup uint* reduce_token = reduce_score + TOP_CHILDREN_SIMDGROUPS;+ threadgroup uint* reduce_index = reduce_token + TOP_CHILDREN_SIMDGROUPS;+ threadgroup float& logit_max = statistics[block * 2];+ threadgroup float& log_sum = statistics[block * 2 + 1];+ threadgroup uint& winner_token = top_winners[block * 2];+ threadgroup uint& winner_index = top_winners[block * 2 + 1];+ const device float* candidate_logits = children_from_pool != 0u ? candidate_pool_logits : node_candidate_logits;+ const device uint* candidate_ids = children_from_pool != 0u ? candidate_pool_ids : node_candidate_ids;+ const bool row_active = row < rows && node_valid[row] != 0u &&+ node_metadata[uint(MetadataIdx::TreeSlot) * rows + row] < tree_slot_count;+ if (mode == WeaverSelectionMode::Children && !row_active) {+ return;+ }+ const uint tree_slot = row_active ? node_metadata[uint(MetadataIdx::TreeSlot) * rows + row] : 0u;+ const uint frontier_base = tree_slot * expand_width;++ const uint base = row * candidates;+ const uint depth = row_active ? node_metadata[uint(MetadataIdx::Depth) * rows + row] : 0u;+ const uint64_t seed = row_active ? depth_seeds[depth] : 0ul;+ const uint first_index = lid;+ const uint second_index = lid + TOP_CHILDREN_THREADS;+ const bool first_valid = row_active && first_index < candidates;+ const bool second_valid = row_active && second_index < candidates;+ const float first_logit =+ first_valid ? candidate_logits[base + first_index] + float(residual_logits[base + first_index]) : -INFINITY;+ const float second_logit =+ second_valid ? candidate_logits[base + second_index] + float(residual_logits[base + second_index]) : -INFINITY;+ const uint first_token = first_valid ? uint(candidate_ids[base + first_index]) : 0xffffffffu;+ const uint second_token = second_valid ? uint(candidate_ids[base + second_index]) : 0xffffffffu;+ const uint first_score =+ first_valid ? top_k_score_key(first_logit + gumbel_noise(seed, first_token, vocab_size)) : 0u;+ const uint second_score =+ second_valid ? top_k_score_key(second_logit + gumbel_noise(seed, second_token, vocab_size)) : 0u;+ bool first_active = first_valid;+ bool second_active = second_valid;++ const float local_max = fmax(first_logit, second_logit);+ const float simd_maximum = simd_max(local_max);+ if (thread_context.simd_lane_id == 0) {+ reduce_float[thread_context.simdgroup_index] = simd_maximum;+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);+ if (thread_context.simdgroup_index == 0) {+ const float group_value =+ thread_context.simd_lane_id < TOP_CHILDREN_SIMDGROUPS ? reduce_float[thread_context.simd_lane_id] : -INFINITY;+ const float maximum = simd_max(group_value);+ if (thread_context.simd_lane_id == 0) {+ logit_max = maximum;+ }+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);++ const float local_sum =+ (first_valid ? exp(first_logit - logit_max) : 0.0f) + (second_valid ? exp(second_logit - logit_max) : 0.0f);+ const float simd_total = simd_sum(local_sum);+ if (thread_context.simd_lane_id == 0) {+ reduce_float[thread_context.simdgroup_index] = simd_total;+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);+ if (thread_context.simdgroup_index == 0) {+ const float group_value =+ thread_context.simd_lane_id < TOP_CHILDREN_SIMDGROUPS ? reduce_float[thread_context.simd_lane_id] : 0.0f;+ const float total = simd_sum(group_value);+ if (thread_context.simd_lane_id == 0) {+ log_sum = log(total) + logit_max;+ }+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);++ // Final pruning weighs each edge by the pool softmax of logits plus the target's noise scaled by 1 / sigma.+ float first_prune_logit = -INFINITY;+ float second_prune_logit = -INFINITY;+ float prune_log_sum = 0.0f;+ if (has_prune_noise) {+ if (first_valid) {+ first_prune_logit = first_logit + prune_noise_scale * target_gumbel_noise(seed, first_token, vocab_size);+ }+ if (second_valid) {+ second_prune_logit = second_logit + prune_noise_scale * target_gumbel_noise(seed, second_token, vocab_size);+ }+ const float prune_max = threadgroup_cooperative_reduce<SimdReduceMax<float>, TOP_CHILDREN_THREADS>(+ fmax(first_prune_logit, second_prune_logit),+ reduce_float,+ thread_context+ );+ const float prune_total = threadgroup_cooperative_reduce<SimdReduceSum<float>, TOP_CHILDREN_THREADS>(+ (first_valid ? exp(first_prune_logit - prune_max) : 0.0f) ++ (second_valid ? exp(second_prune_logit - prune_max) : 0.0f),+ reduce_float,+ thread_context+ );+ prune_log_sum = log(prune_total) + prune_max;+ }++ for (uint child = 0; child < expand_width; ++child) {+ uint local_score = 0u;+ uint local_token = 0xffffffffu;+ uint local_index = 0xffffffffu;+ if (first_active) {+ local_score = first_score;+ local_token = first_token;+ local_index = first_index;+ }+ if (second_active &&+ weaver_better(second_score, second_token, second_index, local_score, local_token, local_index)) {+ local_score = second_score;+ local_token = second_token;+ local_index = second_index;+ }++ const uint simd_score = simd_max(local_score);+ const uint simd_token = simd_min(local_score == simd_score ? local_token : 0xffffffffu);+ const uint simd_index =+ simd_min(local_score == simd_score && local_token == simd_token ? local_index : 0xffffffffu);+ if (thread_context.simd_lane_id == 0) {+ reduce_score[thread_context.simdgroup_index] = simd_score;+ reduce_token[thread_context.simdgroup_index] = simd_token;+ reduce_index[thread_context.simdgroup_index] = simd_index;+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);++ if (thread_context.simdgroup_index == 0) {+ const bool lane_valid = thread_context.simd_lane_id < TOP_CHILDREN_SIMDGROUPS;+ const uint group_score = lane_valid ? reduce_score[thread_context.simd_lane_id] : 0u;+ const uint selected_score = simd_max(group_score);+ const uint group_token =+ lane_valid && group_score == selected_score ? reduce_token[thread_context.simd_lane_id] : 0xffffffffu;+ const uint selected_token = simd_min(group_token);+ const uint group_index = lane_valid && group_score == selected_score && group_token == selected_token+ ? reduce_index[thread_context.simd_lane_id]+ : 0xffffffffu;+ const uint selected_index = simd_min(group_index);+ if (thread_context.simd_lane_id == 0) {+ winner_token = selected_token;+ winner_index = selected_index;+ }+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);++ if (row_active && lid == 0) {+ const uint slot = frontier_base + child;+ if (slot < frontier_capacity) {+ const float winner_logit =+ candidate_logits[base + winner_index] + float(residual_logits[base + winner_index]);+ const float model_logprob = winner_logit - log_sum;+ const float path_logprob =+ as_type<float>(packed_tree[uint(TreeIdx::PathLogprobBits) * tree_slot_count + tree_slot]);+ const float cumulative_logprob = path_logprob + model_logprob;+ const uint depth = packed_tree[uint(TreeIdx::Depth) * tree_slot_count + tree_slot] + 1u;+ frontier[uint(FrontierIdx::TokenId) * frontier_capacity + slot] = winner_token;+ frontier[uint(FrontierIdx::ParentSlot) * frontier_capacity + slot] = tree_slot;+ frontier[uint(FrontierIdx::Depth) * frontier_capacity + slot] = depth;+ frontier[uint(FrontierIdx::PathLogprobBits) * frontier_capacity + slot] = as_type<uint>(cumulative_logprob);+ if (!has_prune_noise) {+ frontier[uint(FrontierIdx::EdgeLogprobBits) * frontier_capacity + slot] = as_type<uint>(model_logprob);+ }+ frontier[uint(FrontierIdx::PathScoreKey) * frontier_capacity + slot] = top_k_score_key(cumulative_logprob);+ frontier[uint(FrontierIdx::Active) * frontier_capacity + slot] = 1u;+ }+ }+ if (has_prune_noise && (first_index == winner_index || second_index == winner_index)) {+ const uint slot = frontier_base + child;+ if (slot < frontier_capacity) {+ const float edge_logprob =+ (first_index == winner_index ? first_prune_logit : second_prune_logit) - prune_log_sum;+ frontier[uint(FrontierIdx::EdgeLogprobBits) * frontier_capacity + slot] = as_type<uint>(edge_logprob);+ }+ }+ first_active = first_active && first_index != winner_index;+ second_active = second_active && second_index != winner_index;+ }+ }+ if (mode != WeaverSelectionMode::Children) {+ threadgroup_barrier(mem_flags::mem_device | mem_flags::mem_threadgroup);+ const ThreadContext thread_context = global_context;+ const uint lid = global_lid;+ const uint threads = BLOCK_THREADS;+ const uint groups = BLOCK_THREADS / METAL_SIMD_SIZE;+ const uint entries = FRONTIER_MAX_SLOTS / threads;+ threadgroup uint4* reduce = reduce_storage;++ if (frontier_capacity == 0 || frontier_capacity > FRONTIER_MAX_SLOTS || node_count == 0 ||+ node_count > FRONTIER_MAX_WIDTH || ancestor_stride == 0 || tree_slot_count == 0 ||+ batch_start_slot + node_count > tree_slot_count || candidate_depth_count == 0 || candidates == 0) {+ return;+ }++ bool entry_active[FRONTIER_MAX_SLOTS / BLOCK_THREADS];+ for (uint entry = 0; entry < entries; ++entry) {+ const uint slot = lid + entry * threads;+ entry_active[entry] =+ slot < frontier_capacity && frontier[uint(FrontierIdx::Active) * frontier_capacity + slot] != 0u;+ }++ for (uint child = 0; child < node_count; ++child) {+ uint4 local = uint4(0u, FRONTIER_NO_WINNER, FRONTIER_NO_WINNER, FRONTIER_NO_WINNER);+ for (uint entry = 0; entry < entries; ++entry) {+ const uint slot = lid + entry * threads;+ if (entry_active[entry]) {+ const uint depth = frontier[uint(FrontierIdx::Depth) * frontier_capacity + slot];+ const uint key = frontier[uint(FrontierIdx::PathScoreKey) * frontier_capacity + slot];+ const uint parent = frontier[uint(FrontierIdx::ParentSlot) * frontier_capacity + slot];+ const uint token = frontier[uint(FrontierIdx::TokenId) * frontier_capacity + slot];+ const uint packed_key = ((depth < lookahead_count ? 1u : 0u) << 31) | (key >> 1);+ if (packed_key > local.x ||+ (packed_key == local.x && (parent < local.y || (parent == local.y && token < local.z)))) {+ local = uint4(packed_key, parent, token, slot);+ }+ }+ }++ uint4 simd;+ simd.x = simd_max(local.x);+ simd.y = simd_min(local.x == simd.x ? local.y : FRONTIER_NO_WINNER);+ simd.z = simd_min(all(local.xy == simd.xy) ? local.z : FRONTIER_NO_WINNER);+ simd.w = simd_min(all(local.xyz == simd.xyz) ? local.w : FRONTIER_NO_WINNER);+ if (thread_context.simd_lane_id == 0) {+ reduce[thread_context.simdgroup_index] = simd;+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);++ if (thread_context.simdgroup_index == 0) {+ const uint4 partial = thread_context.simd_lane_id < groups+ ? reduce[thread_context.simd_lane_id]+ : uint4(0u, FRONTIER_NO_WINNER, FRONTIER_NO_WINNER, FRONTIER_NO_WINNER);+ uint4 selected;+ selected.x = simd_max(partial.x);+ selected.y = simd_min(partial.x == selected.x ? partial.y : FRONTIER_NO_WINNER);+ selected.z = simd_min(all(partial.xy == selected.xy) ? partial.z : FRONTIER_NO_WINNER);+ selected.w = simd_min(all(partial.xyz == selected.xyz) ? partial.w : FRONTIER_NO_WINNER);+ if (thread_context.simd_lane_id == 0) {+ winner_slot[child] = selected.w;+ }+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);++ const uint selected = winner_slot[child];+ for (uint entry = 0; entry < entries; ++entry) {+ entry_active[entry] = entry_active[entry] && (lid + entry * threads) != selected;+ }+ }++ if (lid < node_count) {+ const uint node = lid;+ const uint slot = winner_slot[node];+ const bool real = slot != FRONTIER_NO_WINNER;+ const uint tree_slot = batch_start_slot + node;++ const uint token = real ? frontier[uint(FrontierIdx::TokenId) * frontier_capacity + slot] : 0u;+ const uint parent =+ real ? frontier[uint(FrontierIdx::ParentSlot) * frontier_capacity + slot] : FRONTIER_NO_WINNER;+ const uint depth = real ? frontier[uint(FrontierIdx::Depth) * frontier_capacity + slot] : 0u;+ const uint cumulative_logprob =+ real ? frontier[uint(FrontierIdx::PathLogprobBits) * frontier_capacity + slot] : 0u;+ const uint logprob = real ? frontier[uint(FrontierIdx::EdgeLogprobBits) * frontier_capacity + slot] : 0u;++ packed_tree[uint(TreeIdx::TokenId) * tree_slot_count + tree_slot] = token;+ packed_tree[uint(TreeIdx::ParentSlot) * tree_slot_count + tree_slot] = parent;+ packed_tree[uint(TreeIdx::Depth) * tree_slot_count + tree_slot] = depth;+ packed_tree[uint(TreeIdx::PathLogprobBits) * tree_slot_count + tree_slot] = cumulative_logprob;+ packed_tree[uint(TreeIdx::EdgeLogprobBits) * tree_slot_count + tree_slot] = logprob;+ packed_tree[uint(TreeIdx::Valid) * tree_slot_count + tree_slot] = real ? 1u : 0u;++ if (real) {+ frontier[uint(FrontierIdx::Active) * frontier_capacity + slot] = 0u;+ }++ const uint parent_slot = real && parent < tree_slot_count ? parent : 0u;+ for (uint index = 0; index < ancestor_stride; ++index) {+ const uint ancestor =+ real && index + 1u <= depth+ ? (index + 1u == depth ? parent_slot : slot_ancestors[parent_slot * ancestor_stride + index])+ : 0u;+ slot_ancestors[tree_slot * ancestor_stride + index] = ancestor;+ node_ancestor_indices[node * ancestor_stride + index] = ancestor;+ }++ node_token_ids[node] = token;+ node_metadata[uint(MetadataIdx::Depth) * node_count + node] = depth < lookahead_count ? depth : PADDING_DEPTH;+ node_metadata[uint(MetadataIdx::AncestorCount) * node_count + node] = depth;+ node_metadata[uint(MetadataIdx::TreeSlot) * node_count + node] = tree_slot;+ node_valid[node] = real && depth < lookahead_count ? 1u : 0u;++ node_candidate_depth[node] = depth;+ }++ threadgroup_barrier(mem_flags::mem_threadgroup);++ for (uint node = 0; node < node_count; ++node) {+ if (node_candidate_depth[node] >= candidate_depth_count) {+ continue;+ }+ const uint source = node_candidate_depth[node] * candidates;+ const uint destination = node * candidates;+ for (uint candidate = lid; candidate < candidates; candidate += threads) {+ node_candidate_ids[destination + candidate] = candidate_pool_ids[source + candidate];+ node_candidate_logits[destination + candidate] = candidate_pool_logits[source + candidate];+ }+ }+ }+}diff --git a/crates/uzu-engine/src/backends/metal/kernel/weaver/weaver_top_children.metal b/crates/uzu-engine/src/backends/metal/kernel/weaver/weaver_top_children.metaldeleted file mode 100644index 91c8027d1..000000000--- a/crates/uzu-engine/src/backends/metal/kernel/weaver/weaver_top_children.metal+++ /dev/null@@ -1,240 +0,0 @@-#include <metal_stdlib>-#include "../common/defines.h"-#include "../common/dsl.h"-#include "../common/thread_context.h"-#include "../common/threadgroup_reduce.h"-#include "../common/top_k.h"-#include "../rng.h"-#include "weaver_frontier.h"--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)));-}--PUBLIC KERNEL(WeaverTopChildren)(- const device bfloat* residual_logits,- const device float* candidate_logits,- const device uint* candidate_ids,- const device uint64_t* depth_seeds,- const device uint* node_metadata,- const device uint* packed_tree,- const device uint* node_valid,- device uint* frontier,- constant uint& rows,- constant uint& candidates,- constant uint& expand_width,- constant uint& vocab_size,- constant uint& frontier_capacity,- constant uint& tree_slot_count,- constant float& prune_noise_scale OPTIONAL(has_prune_noise),- const bool has_prune_noise SPECIALIZE,- threadgroup float reduce_float[TOP_CHILDREN_SIMDGROUPS],- threadgroup uint reduce_score[TOP_CHILDREN_SIMDGROUPS],- threadgroup uint reduce_token[TOP_CHILDREN_SIMDGROUPS],- threadgroup uint reduce_index[TOP_CHILDREN_SIMDGROUPS],- threadgroup float& logit_max,- threadgroup float& log_sum,- threadgroup uint& winner_token,- threadgroup uint& winner_index,- const ThreadContext thread_context,- const uint row GROUPS(rows),- const uint lid THREADS(TOP_CHILDREN_THREADS)-) {- if (candidates == 0 || candidates > CANDIDATES_MAX || expand_width == 0 || expand_width > candidates ||- frontier_capacity == 0 || tree_slot_count == 0) {- return;- }- if (node_valid[row] == 0u) {- return;- }- const uint tree_slot = node_metadata[uint(MetadataIdx::TreeSlot) * rows + row];- if (tree_slot >= tree_slot_count) {- return;- }- const uint frontier_base = tree_slot * expand_width;-- const uint base = row * candidates;- const uint depth = node_metadata[uint(MetadataIdx::Depth) * rows + row];- const uint64_t seed = depth_seeds[depth];- const uint first_index = lid;- const uint second_index = lid + TOP_CHILDREN_THREADS;- const bool first_valid = first_index < candidates;- const bool second_valid = second_index < candidates;- const float first_logit =- first_valid ? candidate_logits[base + first_index] + float(residual_logits[base + first_index]) : -INFINITY;- const float second_logit =- second_valid ? candidate_logits[base + second_index] + float(residual_logits[base + second_index]) : -INFINITY;- const uint first_token = first_valid ? uint(candidate_ids[base + first_index]) : 0xffffffffu;- const uint second_token = second_valid ? uint(candidate_ids[base + second_index]) : 0xffffffffu;- const uint first_score =- first_valid ? top_k_score_key(first_logit + gumbel_noise(seed, first_token, vocab_size)) : 0u;- const uint second_score =- second_valid ? top_k_score_key(second_logit + gumbel_noise(seed, second_token, vocab_size)) : 0u;- bool first_active = first_valid;- bool second_active = second_valid;-- const float local_max = fmax(first_logit, second_logit);- const float simd_maximum = simd_max(local_max);- if (thread_context.simd_lane_id == 0) {- reduce_float[thread_context.simdgroup_index] = simd_maximum;- }- threadgroup_barrier(mem_flags::mem_threadgroup);- if (thread_context.simdgroup_index == 0) {- const float group_value =- thread_context.simd_lane_id < TOP_CHILDREN_SIMDGROUPS ? reduce_float[thread_context.simd_lane_id] : -INFINITY;- const float maximum = simd_max(group_value);- if (thread_context.simd_lane_id == 0) {- logit_max = maximum;- }- }- threadgroup_barrier(mem_flags::mem_threadgroup);-- const float local_sum =- (first_valid ? exp(first_logit - logit_max) : 0.0f) + (second_valid ? exp(second_logit - logit_max) : 0.0f);- const float simd_total = simd_sum(local_sum);- if (thread_context.simd_lane_id == 0) {- reduce_float[thread_context.simdgroup_index] = simd_total;- }- threadgroup_barrier(mem_flags::mem_threadgroup);- if (thread_context.simdgroup_index == 0) {- const float group_value =- thread_context.simd_lane_id < TOP_CHILDREN_SIMDGROUPS ? reduce_float[thread_context.simd_lane_id] : 0.0f;- const float total = simd_sum(group_value);- if (thread_context.simd_lane_id == 0) {- log_sum = log(total) + logit_max;- }- }- threadgroup_barrier(mem_flags::mem_threadgroup);-- // Final pruning weighs each edge by the pool softmax of logits plus the target's noise scaled by 1 / sigma.- float first_prune_logit = -INFINITY;- float second_prune_logit = -INFINITY;- float prune_log_sum = 0.0f;- if (has_prune_noise) {- if (first_valid) {- first_prune_logit = first_logit + prune_noise_scale * target_gumbel_noise(seed, first_token, vocab_size);- }- if (second_valid) {- second_prune_logit = second_logit + prune_noise_scale * target_gumbel_noise(seed, second_token, vocab_size);- }- const float prune_max = threadgroup_cooperative_reduce<SimdReduceMax<float>, TOP_CHILDREN_THREADS>(- fmax(first_prune_logit, second_prune_logit),- reduce_float,- thread_context- );- const float prune_total = threadgroup_cooperative_reduce<SimdReduceSum<float>, TOP_CHILDREN_THREADS>(- (first_valid ? exp(first_prune_logit - prune_max) : 0.0f) +- (second_valid ? exp(second_prune_logit - prune_max) : 0.0f),- reduce_float,- thread_context- );- prune_log_sum = log(prune_total) + prune_max;- }-- for (uint child = 0; child < expand_width; ++child) {- uint local_score = 0u;- uint local_token = 0xffffffffu;- uint local_index = 0xffffffffu;- if (first_active) {- local_score = first_score;- local_token = first_token;- local_index = first_index;- }- if (second_active &&- weaver_better(second_score, second_token, second_index, local_score, local_token, local_index)) {- local_score = second_score;- local_token = second_token;- local_index = second_index;- }-- const uint simd_score = simd_max(local_score);- const uint simd_token = simd_min(local_score == simd_score ? local_token : 0xffffffffu);- const uint simd_index =- simd_min(local_score == simd_score && local_token == simd_token ? local_index : 0xffffffffu);- if (thread_context.simd_lane_id == 0) {- reduce_score[thread_context.simdgroup_index] = simd_score;- reduce_token[thread_context.simdgroup_index] = simd_token;- reduce_index[thread_context.simdgroup_index] = simd_index;- }- threadgroup_barrier(mem_flags::mem_threadgroup);-- if (thread_context.simdgroup_index == 0) {- const bool lane_valid = thread_context.simd_lane_id < TOP_CHILDREN_SIMDGROUPS;- const uint group_score = lane_valid ? reduce_score[thread_context.simd_lane_id] : 0u;- const uint selected_score = simd_max(group_score);- const uint group_token =- lane_valid && group_score == selected_score ? reduce_token[thread_context.simd_lane_id] : 0xffffffffu;- const uint selected_token = simd_min(group_token);- const uint group_index = lane_valid && group_score == selected_score && group_token == selected_token- ? reduce_index[thread_context.simd_lane_id]- : 0xffffffffu;- const uint selected_index = simd_min(group_index);- if (thread_context.simd_lane_id == 0) {- winner_token = selected_token;- winner_index = selected_index;- }- }- threadgroup_barrier(mem_flags::mem_threadgroup);-- if (lid == 0) {- const uint slot = frontier_base + child;- if (slot < frontier_capacity) {- const float winner_logit = candidate_logits[base + winner_index] + float(residual_logits[base + winner_index]);- const float model_logprob = winner_logit - log_sum;- const float path_logprob =- as_type<float>(packed_tree[uint(TreeIdx::PathLogprobBits) * tree_slot_count + tree_slot]);- const float cumulative_logprob = path_logprob + model_logprob;- const uint depth = packed_tree[uint(TreeIdx::Depth) * tree_slot_count + tree_slot] + 1u;- frontier[uint(FrontierIdx::TokenId) * frontier_capacity + slot] = winner_token;- frontier[uint(FrontierIdx::ParentSlot) * frontier_capacity + slot] = tree_slot;- frontier[uint(FrontierIdx::Depth) * frontier_capacity + slot] = depth;- frontier[uint(FrontierIdx::PathLogprobBits) * frontier_capacity + slot] = as_type<uint>(cumulative_logprob);- if (!has_prune_noise) {- frontier[uint(FrontierIdx::EdgeLogprobBits) * frontier_capacity + slot] = as_type<uint>(model_logprob);- }- frontier[uint(FrontierIdx::PathScoreKey) * frontier_capacity + slot] = top_k_score_key(cumulative_logprob);- frontier[uint(FrontierIdx::Active) * frontier_capacity + slot] = 1u;- }- }- if (has_prune_noise && (first_index == winner_index || second_index == winner_index)) {- const uint slot = frontier_base + child;- if (slot < frontier_capacity) {- const float edge_logprob =- (first_index == winner_index ? first_prune_logit : second_prune_logit) - prune_log_sum;- frontier[uint(FrontierIdx::EdgeLogprobBits) * frontier_capacity + slot] = as_type<uint>(edge_logprob);- }- }- first_active = first_active && first_index != winner_index;- second_active = second_active && second_index != winner_index;- }-}diff --git a/crates/uzu-engine/src/encodable_block/weaver.rs b/crates/uzu-engine/src/encodable_block/weaver.rsindex f20a044db..43a89cca4 100644--- a/crates/uzu-engine/src/encodable_block/weaver.rs+++ b/crates/uzu-engine/src/encodable_block/weaver.rs@@ -6,10 +6,11 @@ use crate::{Backend, Buffer, BufferMut, BufferRef, CommandBuffer, CommandBufferEncoding, Context, Kernels,gpu_types::weaver::{CANDIDATES_MAX, FRONTIER_MAX_SLOTS, FRONTIER_MAX_WIDTH, FrontierIdx, MetadataIdx, TreeIdx,+ WeaverSelectionMode::{Children, Frontier, Fused},},kernel::{AncestorAttentionKernel, AttentionArguments, AttentionInput, AttentionKernel, FullPrecisionInput,- WeaverFrontierSelectKernel, WeaverTopChildrenKernel, radix_top_k_small::RadixTopKSmall,+ WeaverSelectKernel, radix_top_k_small::RadixTopKSmall,},},config::{rope::AnyRoPEConfig, weaver::WeaverConfig},@@ -121,9 +122,10 @@ pub struct Weaver<B: Backend> {readout_query_projection: Box<dyn Linear<B>>,rope_config: AnyRoPEConfig,top_k: <B::Kernels as Kernels>::RadixTopKSmall,- top_children: <B::Kernels as Kernels>::WeaverTopChildrenKernel,- top_children_with_prune_noise: <B::Kernels as Kernels>::WeaverTopChildrenKernel,- frontier_select: <B::Kernels as Kernels>::WeaverFrontierSelectKernel,+ top_children: <B::Kernels as Kernels>::WeaverSelectKernel,+ top_children_with_prune_noise: <B::Kernels as Kernels>::WeaverSelectKernel,+ frontier_select: <B::Kernels as Kernels>::WeaverSelectKernel,+ expand_select: <B::Kernels as Kernels>::WeaverSelectKernel,model_dim: u32,target_model_dim: u32,max_depth: u32,@@ -265,12 +267,15 @@ impl<B: Backend> Weaver<B> {)?;let top_k =<B::Kernels as Kernels>::RadixTopKSmall::new(context, vocab_size).map_err(WeaverNewError::Backend)?;- let top_children =- <B::Kernels as Kernels>::WeaverTopChildrenKernel::new(context, false).map_err(WeaverNewError::Backend)?;+ let top_children = <B::Kernels as Kernels>::WeaverSelectKernel::new(context, 256, Children, false)+ .map_err(WeaverNewError::Backend)?;let top_children_with_prune_noise =- <B::Kernels as Kernels>::WeaverTopChildrenKernel::new(context, true).map_err(WeaverNewError::Backend)?;- let frontier_select =- <B::Kernels as Kernels>::WeaverFrontierSelectKernel::new(context).map_err(WeaverNewError::Backend)?;+ <B::Kernels as Kernels>::WeaverSelectKernel::new(context, 256, Children, true)+ .map_err(WeaverNewError::Backend)?;+ let frontier_select = <B::Kernels as Kernels>::WeaverSelectKernel::new(context, 256, Frontier, false)+ .map_err(WeaverNewError::Backend)?;+ let expand_select = <B::Kernels as Kernels>::WeaverSelectKernel::new(context, 1024, Fused, false)+ .map_err(WeaverNewError::Backend)?;Ok(Self {token_embedding_norm,token_embedding_projection,@@ -284,6 +289,7 @@ impl<B: Backend> Weaver<B> {top_children,top_children_with_prune_noise,frontier_select,+ expand_select,model_dim: config.model_dim,target_model_dim: config.target_model_dim,max_depth: config.max_depth,@@ -370,7 +376,7 @@ impl<B: Backend> Weaver<B> {mut node_kv_layers: impl Iterator<Item = impl BufferMut<Backend = B>>,mut packed_tree: impl BufferMut<Backend = B>,mut frontier: impl BufferMut<Backend = B>,- slot_ancestors: impl BufferMut<Backend = B>,+ mut slot_ancestors: impl BufferMut<Backend = B>,mut node_token_ids: impl BufferMut<Backend = B>,mut node_metadata: impl BufferMut<Backend = B>,mut node_ancestor_indices: impl BufferMut<Backend = B>,@@ -389,35 +395,42 @@ impl<B: Backend> Weaver<B> {let ancestor_stride = self.max_depth;let frontier_capacity = tree_slot_count * shape.expand_width;- if batch_start_slot > 0 {+ let fuse_select = shape.expand_per_round <= 4 && shape.prune_noise_scale.is_none();+ if batch_start_slot > 0 && !fuse_select {self.frontier_select.encode(+ None::<&B::ScratchBuffer>,+ None::<&B::ScratchBuffer>,frontier.reborrow(),packed_tree.reborrow(),- slot_ancestors,- node_token_ids.reborrow(),+ Some(slot_ancestors.reborrow()),+ Some(node_token_ids.reborrow()),node_metadata.reborrow(),- node_ancestor_indices.reborrow(),+ Some(node_ancestor_indices.reborrow()),node_valid.reborrow(),candidate_ids,candidate_logits,node_candidate_ids.reborrow(),node_candidate_logits.reborrow(),+ 0,+ 0,+ self.candidate_pool_size,+ shape.expand_width,+ target_embedding.vocab_size(),frontier_capacity,tree_slot_count,batch_node_count,batch_start_slot,ancestor_stride,- self.max_depth,shape.max_depth - 1,shape.dflash_depth - 1,- self.candidate_pool_size,+ None,command_buffer,);}- let (batch_candidate_ids, batch_candidate_logits) = if batch_start_slot == 0 {- (candidate_ids.subrange(..), candidate_logits.subrange(..))+ let batch_candidate_ids = if batch_start_slot == 0 {+ candidate_ids.subrange(..)} else {- (node_candidate_ids.as_ref().subrange(..), node_candidate_logits.as_ref().subrange(..))+ node_candidate_ids.as_ref().subrange(..)};// Node expansion: embed the batch's tokens, run every layer against@@ -432,7 +445,7 @@ impl<B: Backend> Weaver<B> {self.token_embedding_projection.encode(normalized_embedding, batch_node_count, command_buffer)?;let mut residual_state =command_buffer.allocate_scratch(residual_input.size()).map_err(WeaverEncodeError::Backend)?;- let node_metadata = node_metadata.as_ref();+ let node_metadata_ref = node_metadata.as_ref();let metadata_field_bytes = size_for_shape(&[batch_node_count], DataType::U32);for layer in &self.layers {let input = layer@@ -449,10 +462,10 @@ impl<B: Backend> Weaver<B> {¤t_qkv,&rope.cosines,&rope.sines,- node_metadata,+ node_metadata_ref,node_ancestor_indices.as_ref(),- node_metadata.subrange(MetadataIdx::AncestorCount as usize * metadata_field_bytes..),- node_metadata.subrange(MetadataIdx::TreeSlot as usize * metadata_field_bytes..),+ node_metadata_ref.subrange(MetadataIdx::AncestorCount as usize * metadata_field_bytes..),+ node_metadata_ref.subrange(MetadataIdx::TreeSlot as usize * metadata_field_bytes..),&mut attention_output,batch_node_count,shape.dflash_depth,@@ -479,26 +492,45 @@ impl<B: Backend> Weaver<B> {false,command_buffer,)?;- let top_children = if shape.prune_noise_scale.is_some() {+ let next_batch_start = batch_start_slot + batch_node_count;+ let fuse_next = fuse_select && next_batch_start < tree_slot_count;+ let select = if fuse_next {+ &self.expand_select+ } else if shape.prune_noise_scale.is_some() {&self.top_children_with_prune_noise} else {&self.top_children};- top_children.encode(- &logit_residuals,- batch_candidate_logits,- batch_candidate_ids,- depth_seeds_buffer,- node_metadata,- packed_tree.as_ref(),- node_valid.as_ref(),+ select.encode(+ Some(&logit_residuals),+ Some(depth_seeds_buffer),frontier.reborrow(),+ packed_tree.reborrow(),+ fuse_next.then_some(slot_ancestors.reborrow()),+ fuse_next.then_some(node_token_ids.reborrow()),+ node_metadata.reborrow(),+ fuse_next.then_some(node_ancestor_indices.reborrow()),+ node_valid.reborrow(),+ candidate_ids,+ candidate_logits,+ node_candidate_ids.reborrow(),+ node_candidate_logits.reborrow(),batch_node_count,+ u32::from(batch_start_slot == 0),self.candidate_pool_size,shape.expand_width,target_embedding.vocab_size(),frontier_capacity,tree_slot_count,+ if fuse_next {+ shape.expand_per_round+ } else {+ 0+ },+ next_batch_start,+ ancestor_stride,+ shape.max_depth - 1,+ shape.dflash_depth - 1,shape.prune_noise_scale,command_buffer,);diff --git a/crates/uzu-engine/unit/backends/common/kernel/weaver/weaver_frontier_test.rs b/crates/uzu-engine/unit/backends/common/kernel/weaver/weaver_frontier_test.rsindex 113d45e06..02d0fc252 100644--- a/crates/uzu-engine/unit/backends/common/kernel/weaver/weaver_frontier_test.rs+++ b/crates/uzu-engine/unit/backends/common/kernel/weaver/weaver_frontier_test.rs@@ -5,8 +5,8 @@ use crate::{backends::{common::{Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context, Kernels,- gpu_types::weaver::{FrontierIdx, TreeIdx},- kernel::WeaverFrontierSelectKernel,+ gpu_types::weaver::{FrontierIdx, TreeIdx, WeaverSelectionMode},+ kernel::WeaverSelectKernel,},cpu::Cpu,},@@ -45,29 +45,36 @@ fn select<B: Backend>() -> Vec<u32> {create_buffer_with_data::<B, f32>(&context, &(0..12).map(|value| value as f32).collect::<Vec<_>>());let mut candidate_ids = create_buffer_with_data::<B, u32>(&context, &[0; 4 * 3]);let mut candidate_scores = create_buffer_with_data::<B, f32>(&context, &[0.0; 4 * 3]);- let kernel = <B::Kernels as Kernels>::WeaverFrontierSelectKernel::new(&context).unwrap();+ let kernel =+ <B::Kernels as Kernels>::WeaverSelectKernel::new(&context, 256, WeaverSelectionMode::Frontier, false).unwrap();let mut command_buffer = context.create_command_buffer(None, None).unwrap();kernel.encode(+ None::<&B::ScratchBuffer>,+ None::<&B::ScratchBuffer>,&mut frontier,&mut tree,- &mut slot_ancestors,- &mut token,+ Some(&mut slot_ancestors),+ Some(&mut token),&mut metadata,- &mut ancestors,+ Some(&mut ancestors),&mut valid,&candidate_pool_ids,&candidate_pool_scores,&mut candidate_ids,&mut candidate_scores,+ 0,+ 0,+ 3,+ 0,+ 0,8,7,4,2,3,- 4,3,4,- 3,+ None,&mut command_buffer,);block_on(command_buffer.end_encoding().submit().wait_until_completed()).unwrap();diff --git a/crates/uzu-engine/unit/backends/common/kernel/weaver/weaver_top_children_test.rs b/crates/uzu-engine/unit/backends/common/kernel/weaver/weaver_top_children_test.rsindex 3b1c9d7f8..b580fc232 100644--- a/crates/uzu-engine/unit/backends/common/kernel/weaver/weaver_top_children_test.rs+++ b/crates/uzu-engine/unit/backends/common/kernel/weaver/weaver_top_children_test.rs@@ -6,8 +6,8 @@ use crate::{backends::{common::{Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context, Kernels,- gpu_types::weaver::{FrontierIdx, MetadataIdx, TreeIdx},- kernel::WeaverTopChildrenKernel,+ gpu_types::weaver::{FrontierIdx, MetadataIdx, TreeIdx, WeaverSelectionMode::Children},+ kernel::WeaverSelectKernel,},cpu::Cpu,},@@ -53,35 +53,49 @@ fn run_top_children<B: Backend>(let (residual, candidate_logits, ids) = inputs();let context = create_context::<B>();let residual = create_buffer_with_data::<B, bf16>(&context, &residual);- let candidate_logits = create_buffer_with_data::<B, f32>(&context, &candidate_logits);- let ids = create_buffer_with_data::<B, u32>(&context, &ids);+ let pool_logits = create_buffer_with_data::<B, f32>(&context, &candidate_logits);+ let mut candidate_logits = create_buffer_with_data::<B, f32>(&context, &candidate_logits);+ let pool_ids = create_buffer_with_data::<B, u32>(&context, &ids);+ let mut ids = create_buffer_with_data::<B, u32>(&context, &ids);let depth_seeds = create_buffer_with_data::<B, u64>(&context, &DEPTH_SEEDS);let mut metadata_values = vec![0u32; ROWS * MetadataIdx::COUNT];for row in 0..ROWS {metadata_values[MetadataIdx::Depth as usize * ROWS + row] = DEPTHS[row];metadata_values[MetadataIdx::TreeSlot as usize * ROWS + row] = row as u32 + 1;}- let node_metadata = create_buffer_with_data::<B, u32>(&context, &metadata_values);- let tree = create_buffer_with_data::<B, u32>(&context, tree_values);- let valid = create_buffer_with_data::<B, u32>(&context, node_valid);+ let mut node_metadata = create_buffer_with_data::<B, u32>(&context, &metadata_values);+ let mut tree = create_buffer_with_data::<B, u32>(&context, tree_values);+ let mut valid = create_buffer_with_data::<B, u32>(&context, node_valid);let mut frontier = create_buffer_with_data::<B, u32>(&context, &vec![42; FrontierIdx::COUNT * FRONTIER_CAPACITY]);- let kernel = <B::Kernels as Kernels>::WeaverTopChildrenKernel::new(&context, prune_noise_scale.is_some()).unwrap();+ let kernel =+ <B::Kernels as Kernels>::WeaverSelectKernel::new(&context, 256, Children, prune_noise_scale.is_some()).unwrap();let mut command_buffer = context.create_command_buffer(None, None).unwrap();kernel.encode(- &residual,- &candidate_logits,- &ids,- &depth_seeds,- &node_metadata,- &tree,- &valid,+ Some(&residual),+ Some(&depth_seeds),&mut frontier,+ &mut tree,+ None::<&mut B::ScratchBuffer>,+ None::<&mut B::ScratchBuffer>,+ &mut node_metadata,+ None::<&mut B::ScratchBuffer>,+ &mut valid,+ &pool_ids,+ &pool_logits,+ &mut ids,+ &mut candidate_logits,ROWS as u32,+ 1,CANDIDATES as u32,CHILDREN as u32,VOCAB_SIZE,FRONTIER_CAPACITY as u32,TREE_SLOT_COUNT as u32,+ 0,+ 0,+ 0,+ 0,+ 0,prune_noise_scale,&mut command_buffer,);