Skip to content

armgit / uzu

Public Imported from GitHub
0

A high-performance inference engine for AI models

Fuse insert_childernen into top_children (#928)

CCYehe632c2cac50a
diff --git a/crates/uzu-engine/src/backends/cpu/kernel/weaver/mod.rs b/crates/uzu-engine/src/backends/cpu/kernel/weaver/mod.rs
index a199938d1..eeedee5d5 100644
--- a/crates/uzu-engine/src/backends/cpu/kernel/weaver/mod.rs
+++ b/crates/uzu-engine/src/backends/cpu/kernel/weaver/mod.rs
@@ -1,3 +1,2 @@
-pub mod weaver_frontier_insert_children;
pub mod weaver_frontier_select;
pub mod weaver_top_children;
diff --git a/crates/uzu-engine/src/backends/cpu/kernel/weaver/weaver_frontier_insert_children.rs b/crates/uzu-engine/src/backends/cpu/kernel/weaver/weaver_frontier_insert_children.rs
deleted file mode 100644
index 7c6b384e7..000000000
--- a/crates/uzu-engine/src/backends/cpu/kernel/weaver/weaver_frontier_insert_children.rs
+++ /dev/null
@@ -1,68 +0,0 @@
-use uzu_engine_macros::kernel;
-
-use crate::backends::common::gpu_types::weaver::{FrontierIdx, MetadataIdx, TreeIdx};
-
-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
- }
-}
-
-#[kernel(WeaverFrontierInsertChildren)]
-pub fn weaver_frontier_insert_children(
- packed_tree: *const u32,
- node_metadata: *const u32,
- node_valid: *const u32,
- child_ids: *const u32,
- child_logprobs: *const f32,
- child_prune_logprobs: *const f32,
- frontier: *mut u32,
- frontier_capacity: u32,
- tree_slot_count: u32,
- node_count: u32,
- expand_width: u32,
-) {
- if frontier_capacity == 0 || tree_slot_count == 0 || expand_width == 0 {
- return;
- }
- let (frontier_capacity, tree_slot_count, node_count, expand_width) =
- (frontier_capacity as usize, tree_slot_count as usize, node_count as usize, expand_width as usize);
- let packed_tree = unsafe { std::slice::from_raw_parts(packed_tree, TreeIdx::COUNT * tree_slot_count) };
- let parent_indices = unsafe {
- std::slice::from_raw_parts(node_metadata.add(MetadataIdx::TreeSlot as usize * node_count), node_count)
- };
- let node_valid = unsafe { std::slice::from_raw_parts(node_valid, node_count) };
- let child_ids = unsafe { std::slice::from_raw_parts(child_ids, node_count * expand_width) };
- let child_logprobs = unsafe { std::slice::from_raw_parts(child_logprobs, node_count * expand_width) };
- let child_prune_logprobs = unsafe { std::slice::from_raw_parts(child_prune_logprobs, node_count * expand_width) };
- let frontier = unsafe { std::slice::from_raw_parts_mut(frontier, FrontierIdx::COUNT * frontier_capacity) };
-
- for index in 0..node_count * expand_width {
- let row = index / expand_width;
- if node_valid[row] == 0 {
- continue;
- }
- let parent = parent_indices[row] as usize;
- let slot = parent * expand_width + index % expand_width;
- if parent >= tree_slot_count || slot >= frontier_capacity {
- continue;
- }
- let logprob = child_logprobs[index];
- let cumulative_logprob =
- f32::from_bits(packed_tree[TreeIdx::PathLogprobBits as usize * tree_slot_count + parent]) + logprob;
- frontier[FrontierIdx::TokenId as usize * frontier_capacity + slot] = child_ids[index];
- frontier[FrontierIdx::ParentSlot as usize * frontier_capacity + slot] = parent as u32;
- frontier[FrontierIdx::Depth as usize * frontier_capacity + slot] =
- packed_tree[TreeIdx::Depth as usize * tree_slot_count + parent] + 1;
- frontier[FrontierIdx::PathLogprobBits as usize * frontier_capacity + slot] = cumulative_logprob.to_bits();
- frontier[FrontierIdx::EdgeLogprobBits as usize * frontier_capacity + slot] =
- child_prune_logprobs[index].to_bits();
- frontier[FrontierIdx::PathScoreKey as usize * frontier_capacity + slot] = top_k_score_key(cumulative_logprob);
- frontier[FrontierIdx::Active as usize * frontier_capacity + slot] = 1;
- }
-}
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.rs
index 310e5bad9..3a3d144c8 100644
--- 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.rs
@@ -2,7 +2,7 @@ use half::bf16;
use uzu_engine_macros::kernel;
use crate::{
- backends::common::gpu_types::weaver::{CANDIDATES_MAX, MetadataIdx},
+ backends::common::gpu_types::weaver::{CANDIDATES_MAX, FrontierIdx, MetadataIdx, TreeIdx},
encodable_block::sampling::{gumbel_float, revidx},
};
@@ -13,23 +13,40 @@ pub fn weaver_top_children(
candidate_ids: *const u32,
depth_seeds: *const u64,
node_metadata: *const u32,
- output_token_ids: *mut u32,
- output_model_logprobs: *mut f32,
- #[optional(has_prune_noise)] output_prune_logprobs: Option<*mut f32>,
+ 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;
- if candidates == 0 || candidates > CANDIDATES_MAX as usize || expand_width == 0 || expand_width > candidates {
+ 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) };
@@ -58,14 +75,41 @@ pub fn weaver_top_children(
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 {
- *output_token_ids.add(row * expand_width + rank) = token(index);
- *output_model_logprobs.add(row * expand_width + rank) = logits[index] - log_sum;
- if let Some((prune_logits, prune_log_sum)) = &prune {
- *output_prune_logprobs.unwrap().add(row * expand_width + rank) =
- prune_logits[index] - prune_log_sum;
- }
+ 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/weaver/weaver_frontier_insert_children.metal b/crates/uzu-engine/src/backends/metal/kernel/weaver/weaver_frontier_insert_children.metal
deleted file mode 100644
index dcaed28f0..000000000
--- a/crates/uzu-engine/src/backends/metal/kernel/weaver/weaver_frontier_insert_children.metal
+++ /dev/null
@@ -1,53 +0,0 @@
-#include <metal_stdlib>
-#include "../common/dsl.h"
-#include "../common/top_k.h"
-#include "weaver_frontier.h"
-
-using namespace metal;
-
-PUBLIC KERNEL(WeaverFrontierInsertChildren)(
- const device uint* packed_tree,
- const device uint* node_metadata,
- const device uint* node_valid,
- const device uint* child_ids,
- const device float* child_logprobs,
- const device float* child_prune_logprobs,
- device uint* frontier,
- constant uint& frontier_capacity,
- constant uint& tree_slot_count,
- constant uint& node_count,
- constant uint& expand_width,
- const uint position AXIS(node_count* expand_width, 64)
-) {
- if (frontier_capacity == 0 || tree_slot_count == 0 || expand_width == 0) {
- return;
- }
-
- const uint row = position / expand_width, child = position % expand_width;
- if (node_valid[row] == 0u) {
- return;
- }
-
- const uint parent = node_metadata[uint(MetadataIdx::TreeSlot) * node_count + row];
- if (parent >= tree_slot_count) {
- return;
- }
- const uint slot = parent * expand_width + child;
- if (slot >= frontier_capacity) {
- return;
- }
-
- const float logprob = child_logprobs[row * expand_width + child];
- const float cumulative_logprob =
- as_type<float>(packed_tree[uint(TreeIdx::PathLogprobBits) * tree_slot_count + parent]) + logprob;
-
- frontier[uint(FrontierIdx::TokenId) * frontier_capacity + slot] = child_ids[row * expand_width + child];
- frontier[uint(FrontierIdx::ParentSlot) * frontier_capacity + slot] = parent;
- frontier[uint(FrontierIdx::Depth) * frontier_capacity + slot] =
- packed_tree[uint(TreeIdx::Depth) * tree_slot_count + parent] + 1u;
- frontier[uint(FrontierIdx::PathLogprobBits) * frontier_capacity + slot] = as_type<uint>(cumulative_logprob);
- frontier[uint(FrontierIdx::EdgeLogprobBits) * frontier_capacity + slot] =
- as_type<uint>(child_prune_logprobs[row * expand_width + child]);
- frontier[uint(FrontierIdx::PathScoreKey) * frontier_capacity + slot] = top_k_score_key(cumulative_logprob);
- frontier[uint(FrontierIdx::Active) * frontier_capacity + slot] = 1u;
-}
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.metal
index 156462a5c..91c8027d1 100644
--- 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.metal
@@ -47,13 +47,15 @@ PUBLIC KERNEL(WeaverTopChildren)(
const device uint* candidate_ids,
const device uint64_t* depth_seeds,
const device uint* node_metadata,
- device uint* output_token_ids,
- device float* output_model_logprobs,
- device float* output_prune_logprobs OPTIONAL(has_prune_noise),
+ 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],
@@ -68,9 +70,18 @@ PUBLIC KERNEL(WeaverTopChildren)(
const uint row GROUPS(rows),
const uint lid THREADS(TOP_CHILDREN_THREADS)
) {
- if (candidates == 0 || candidates > CANDIDATES_MAX || expand_width == 0 || expand_width > candidates) {
+ 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];
@@ -196,13 +207,32 @@ PUBLIC KERNEL(WeaverTopChildren)(
threadgroup_barrier(mem_flags::mem_threadgroup);
if (lid == 0) {
- const float winner_logit = candidate_logits[base + winner_index] + float(residual_logits[base + winner_index]);
- output_token_ids[row * expand_width + child] = winner_token;
- output_model_logprobs[row * expand_width + child] = winner_logit - log_sum;
+ 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)) {
- output_prune_logprobs[row * expand_width + child] =
- (first_index == winner_index ? first_prune_logit : second_prune_logit) - prune_log_sum;
+ 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.rs
index bb054c5cf..ac02f6e78 100644
--- a/crates/uzu-engine/src/encodable_block/weaver.rs
+++ b/crates/uzu-engine/src/encodable_block/weaver.rs
@@ -9,8 +9,8 @@ use crate::{
CANDIDATES_MAX, FRONTIER_MAX_SLOTS, FRONTIER_MAX_WIDTH, FrontierIdx, MetadataIdx, TreeIdx,
},
kernel::{
- AncestorAttentionKernel, AttentionArguments, AttentionKernel, WeaverFrontierInsertChildrenKernel,
- WeaverFrontierSelectKernel, WeaverTopChildrenKernel, radix_top_k_small::RadixTopKSmall,
+ AncestorAttentionKernel, AttentionArguments, AttentionKernel, WeaverFrontierSelectKernel,
+ WeaverTopChildrenKernel, radix_top_k_small::RadixTopKSmall,
},
},
config::{rope::AnyRoPEConfig, weaver::WeaverConfig},
@@ -124,7 +124,6 @@ pub struct Weaver<B: Backend> {
top_children: <B::Kernels as Kernels>::WeaverTopChildrenKernel,
top_children_with_prune_noise: <B::Kernels as Kernels>::WeaverTopChildrenKernel,
frontier_select: <B::Kernels as Kernels>::WeaverFrontierSelectKernel,
- frontier_insert_children: <B::Kernels as Kernels>::WeaverFrontierInsertChildrenKernel,
model_dim: u32,
target_model_dim: u32,
max_depth: u32,
@@ -264,8 +263,6 @@ impl<B: Backend> Weaver<B> {
<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)?;
- let frontier_insert_children = <B::Kernels as Kernels>::WeaverFrontierInsertChildrenKernel::new(context)
- .map_err(WeaverNewError::Backend)?;
Ok(Self {
token_embedding_norm,
token_embedding_projection,
@@ -279,7 +276,6 @@ impl<B: Backend> Weaver<B> {
top_children,
top_children_with_prune_noise,
frontier_select,
- frontier_insert_children,
model_dim: config.model_dim,
target_model_dim: config.target_model_dim,
max_depth: config.max_depth,
@@ -491,17 +487,6 @@ impl<B: Backend> Weaver<B> {
false,
command_buffer,
)?;
- let mut child_token_ids = command_buffer
- .allocate_scratch_for_shape(&[batch_node_count, shape.expand_width], DataType::U32)
- .map_err(WeaverEncodeError::Backend)?;
- let mut child_logprobs = command_buffer
- .allocate_scratch_for_shape(&[batch_node_count, shape.expand_width], DataType::F32)
- .map_err(WeaverEncodeError::Backend)?;
- let mut child_prune_logprobs = shape
- .prune_noise_scale
- .map(|_| command_buffer.allocate_scratch_for_shape(&[batch_node_count, shape.expand_width], DataType::F32))
- .transpose()
- .map_err(WeaverEncodeError::Backend)?;
let top_children = if shape.prune_noise_scale.is_some() {
&self.top_children_with_prune_noise
} else {
@@ -513,30 +498,16 @@ impl<B: Backend> Weaver<B> {
batch_candidate_ids,
depth_seeds_buffer,
node_metadata,
- &mut child_token_ids,
- &mut child_logprobs,
- child_prune_logprobs.as_mut(),
+ packed_tree.as_ref(),
+ node_valid.as_ref(),
+ frontier.reborrow(),
batch_node_count,
self.candidate_pool_size,
shape.expand_width,
target_embedding.vocab_size(),
- shape.prune_noise_scale,
- command_buffer,
- );
-
- // The edge lane feeds only final pruning; without prune noise it keeps the model logprobs.
- self.frontier_insert_children.encode(
- packed_tree.as_ref(),
- node_metadata,
- node_valid.as_ref(),
- &child_token_ids,
- &child_logprobs,
- child_prune_logprobs.as_ref().unwrap_or(&child_logprobs),
- frontier,
frontier_capacity,
tree_slot_count,
- batch_node_count,
- shape.expand_width,
+ 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.rs
index 08d9b30fe..d24e04d59 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
@@ -4,8 +4,8 @@ use crate::{
backends::{
common::{
Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context, Kernels,
- gpu_types::weaver::{FrontierIdx, MetadataIdx, TreeIdx},
- kernel::{WeaverFrontierInsertChildrenKernel, WeaverFrontierSelectKernel},
+ gpu_types::weaver::{FrontierIdx, TreeIdx},
+ kernel::WeaverFrontierSelectKernel,
},
cpu::Cpu,
},
@@ -77,73 +77,9 @@ fn select<B: Backend>() -> Vec<u32> {
.collect()
}
-const TREE_PATH_LOGPROBS: [f32; 4] = [0.5, -1.0, 2.0, 4.0];
-const MODEL_LOGPROBS: [f32; 9] = [-0.1, -0.2, -0.3, 8.0, 8.0, 8.0, 0.1, 0.2, 0.3];
-const PRUNE_LOGPROBS: [f32; 9] = [-1.1, -1.2, -1.3, -9.0, -9.0, -9.0, -0.6, -0.7, -0.8];
-
-fn insert_children<B: Backend>() -> Vec<u32> {
- let context = create_context::<B>();
- let mut tree = vec![0; TreeIdx::COUNT * 4];
- tree[TreeIdx::PathLogprobBits as usize * 4..(TreeIdx::PathLogprobBits as usize + 1) * 4]
- .copy_from_slice(&TREE_PATH_LOGPROBS.map(f32::to_bits));
- tree[TreeIdx::Depth as usize * 4..(TreeIdx::Depth as usize + 1) * 4].copy_from_slice(&[0, 2, 4, 6]);
- let tree = create_buffer_with_data::<B, u32>(&context, &tree);
- let mut metadata = vec![0; MetadataIdx::COUNT * 3];
- metadata[MetadataIdx::TreeSlot as usize * 3..(MetadataIdx::TreeSlot as usize + 1) * 3].copy_from_slice(&[1, 3, 0]);
- let metadata = create_buffer_with_data::<B, u32>(&context, &metadata);
- let valid = create_buffer_with_data::<B, u32>(&context, &[1, 0, 1]);
- let ids = create_buffer_with_data::<B, u32>(&context, &(10..19).collect::<Vec<_>>());
- let scores = create_buffer_with_data::<B, f32>(&context, &MODEL_LOGPROBS);
- let prune_scores = create_buffer_with_data::<B, f32>(&context, &PRUNE_LOGPROBS);
- let mut frontier = create_buffer_with_data::<B, u32>(&context, &[42; FrontierIdx::COUNT * 16]);
- let kernel = <B::Kernels as Kernels>::WeaverFrontierInsertChildrenKernel::new(&context).unwrap();
- let mut command_buffer = context.create_command_buffer(None, None).unwrap();
- kernel.encode(
- &tree,
- &metadata,
- &valid,
- &ids,
- &scores,
- &prune_scores,
- &mut frontier,
- 16,
- 4,
- 3,
- 3,
- &mut command_buffer,
- );
- command_buffer.end_encoding().submit().wait_until_completed().unwrap();
- buffer_to_vec(&frontier)
-}
-
-/// Expansion follows the model logprobs (path and its order key), final pruning reads the edge lane, which takes the
-/// prune channel. Rows 0 and 2 expand tree slots 1 and 0 into frontier slots 3..6 and 0..3; row 1 is invalid, so no
-/// other slot is written.
-#[uzu_test]
-fn weaver_frontier_insert_children_splits_path_and_edge() {
- let frontier = insert_children::<Cpu>();
- let lane = |field: FrontierIdx, slot: usize| frontier[field as usize * 16 + slot];
- for (row, parent) in [(0, 1), (2, 0)] {
- for child in 0..3 {
- let slot = parent * 3 + child;
- let index = row * 3 + child;
- assert_eq!(lane(FrontierIdx::EdgeLogprobBits, slot), PRUNE_LOGPROBS[index].to_bits());
- assert_eq!(
- lane(FrontierIdx::PathLogprobBits, slot),
- (TREE_PATH_LOGPROBS[parent] + MODEL_LOGPROBS[index]).to_bits()
- );
- assert_eq!(lane(FrontierIdx::Active, slot), 1);
- }
- }
- for slot in 6..16 {
- assert!((0..FrontierIdx::COUNT).all(|field| frontier[field * 16 + slot] == 42));
- }
-}
-
#[uzu_test]
fn weaver_frontier_kernels_match_cpu() {
for_each_non_cpu_backend!(|B| {
assert_eq!(select::<B>(), select::<Cpu>());
- assert_eq!(insert_children::<B>(), insert_children::<Cpu>());
});
}
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.rs
index e507841cd..35d701508 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
@@ -5,12 +5,13 @@ use crate::{
backends::{
common::{
Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context, Kernels,
- gpu_types::weaver::MetadataIdx, kernel::WeaverTopChildrenKernel,
+ gpu_types::weaver::{FrontierIdx, MetadataIdx, TreeIdx},
+ kernel::WeaverTopChildrenKernel,
},
cpu::Cpu,
},
encodable_block::sampling::{gumbel_float, revidx},
- tests::helpers::{buffer_to_vec, create_buffer, create_buffer_with_data, create_context, for_each_non_cpu_backend},
+ tests::helpers::{buffer_to_vec, create_buffer_with_data, create_context, for_each_non_cpu_backend},
};
const CANDIDATES: usize = 512;
@@ -19,6 +20,8 @@ const VOCAB_SIZE: u32 = 131_072;
const DEPTHS: [u32; 3] = [0, 1, 2];
const DEPTH_SEEDS: [u64; 3] = [0x9E3779B97F4A7C15, 0xD1B54A32D192ED03, 0x2545F4914F6CDD1D];
const ROWS: usize = 3;
+const TREE_SLOT_COUNT: usize = ROWS + 1;
+const FRONTIER_CAPACITY: usize = TREE_SLOT_COUNT * CHILDREN;
const PRUNE_NOISE_SCALE: f32 = 1.0 / 1.5;
fn inputs() -> (Vec<bf16>, Vec<f32>, Vec<u32>) {
@@ -33,30 +36,34 @@ fn inputs() -> (Vec<bf16>, Vec<f32>, Vec<u32>) {
(residual, candidate_logits, ids)
}
-fn top_children<B: Backend>(
- residual: &[bf16],
- candidate_logits: &[f32],
- ids: &[u32],
+fn score_key(bits: u32) -> u32 {
+ if bits & 0x8000_0000 == 0 {
+ bits ^ 0x8000_0000
+ } else {
+ !bits
+ }
+}
+
+fn run_top_children<B: Backend>(
prune_noise_scale: Option<f32>,
-) -> (Vec<u32>, Vec<f32>, Option<Vec<f32>>) {
- let rows = residual.len() / CANDIDATES;
- assert_eq!(residual.len(), rows * CANDIDATES);
- assert_eq!(candidate_logits.len(), rows * CANDIDATES);
- assert_eq!(ids.len(), rows * CANDIDATES);
- assert!(rows <= DEPTHS.len());
+ node_valid: &[u32; ROWS],
+ tree_values: &[u32; TreeIdx::COUNT * TREE_SLOT_COUNT],
+) -> Vec<u32> {
+ 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 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 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];
+ 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 mut output_token_ids = create_buffer::<B, u32>(&context, rows * CHILDREN);
- let mut output_model_logprobs = create_buffer::<B, f32>(&context, rows * CHILDREN);
- let mut output_prune_logprobs = prune_noise_scale.map(|_| create_buffer::<B, f32>(&context, rows * CHILDREN));
+ let tree = create_buffer_with_data::<B, u32>(&context, tree_values);
+ let 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 mut command_buffer = context.create_command_buffer(None, None).unwrap();
kernel.encode(
@@ -65,42 +72,91 @@ fn top_children<B: Backend>(
&ids,
&depth_seeds,
&node_metadata,
- &mut output_token_ids,
- &mut output_model_logprobs,
- output_prune_logprobs.as_mut(),
- rows as u32,
+ &tree,
+ &valid,
+ &mut frontier,
+ ROWS as u32,
CANDIDATES as u32,
CHILDREN as u32,
VOCAB_SIZE,
+ FRONTIER_CAPACITY as u32,
+ TREE_SLOT_COUNT as u32,
prune_noise_scale,
&mut command_buffer,
);
command_buffer.end_encoding().submit().wait_until_completed().unwrap();
+ buffer_to_vec(&frontier)
+}
+
+fn top_children<B: Backend>(prune_noise_scale: Option<f32>) -> (Vec<u32>, Vec<f32>, Option<Vec<f32>>) {
+ let frontier = run_top_children::<B>(prune_noise_scale, &[1; ROWS], &[0; TreeIdx::COUNT * TREE_SLOT_COUNT]);
+ let field = |field: FrontierIdx| {
+ frontier[field as usize * FRONTIER_CAPACITY + CHILDREN..(field as usize + 1) * FRONTIER_CAPACITY].to_vec()
+ };
(
- buffer_to_vec(&output_token_ids),
- buffer_to_vec(&output_model_logprobs),
- output_prune_logprobs.as_ref().map(buffer_to_vec),
+ field(FrontierIdx::TokenId),
+ field(FrontierIdx::PathLogprobBits).into_iter().map(f32::from_bits).collect(),
+ prune_noise_scale.map(|_| field(FrontierIdx::EdgeLogprobBits).into_iter().map(f32::from_bits).collect()),
)
}
#[uzu_test]
fn weaver_top_children_matches_cpu() {
- let (residual, candidate_logits, ids) = inputs();
-
+ let mut tree = [0u32; TreeIdx::COUNT * TREE_SLOT_COUNT];
+ for slot in 0..TREE_SLOT_COUNT {
+ tree[TreeIdx::PathLogprobBits as usize * TREE_SLOT_COUNT + slot] = (slot as f32 * -0.25).to_bits();
+ tree[TreeIdx::Depth as usize * TREE_SLOT_COUNT + slot] = slot as u32 * 2;
+ }
for prune_noise_scale in [None, Some(PRUNE_NOISE_SCALE)] {
- for_each_non_cpu_backend!(|B| {
- let expected = top_children::<Cpu>(&residual, &candidate_logits, &ids, prune_noise_scale);
- let actual = top_children::<B>(&residual, &candidate_logits, &ids, prune_noise_scale);
- assert_eq!(actual.0, expected.0);
- for (actual, expected) in actual.1.iter().zip(expected.1) {
- assert!((actual - expected).abs() < 1e-5);
- }
- assert_eq!(actual.2.is_some(), expected.2.is_some());
- // The prune channel also carries the Gumbel transform, which Metal evaluates with fast-math logs.
- for (actual, expected) in actual.2.iter().flatten().zip(expected.2.iter().flatten()) {
- assert!((actual - expected).abs() < 1e-3);
+ let (tokens, model, prune) = top_children::<Cpu>(prune_noise_scale);
+ for valid in [[1, 1, 1], [1, 0, 1]] {
+ let expected = run_top_children::<Cpu>(prune_noise_scale, &valid, &tree);
+ let field = |field: FrontierIdx, slot: usize| expected[field as usize * FRONTIER_CAPACITY + slot];
+ for slot in 0..FRONTIER_CAPACITY {
+ if slot < CHILDREN || valid[slot / CHILDREN - 1] == 0 {
+ assert!((0..FrontierIdx::COUNT).all(|field| expected[field * FRONTIER_CAPACITY + slot] == 42));
+ continue;
+ }
+ let row = slot / CHILDREN - 1;
+ let child = slot % CHILDREN;
+ let index = row * CHILDREN + child;
+ assert_eq!(field(FrontierIdx::TokenId, slot), tokens[index]);
+ assert_eq!(field(FrontierIdx::ParentSlot, slot), (row + 1) as u32);
+ assert_eq!(field(FrontierIdx::Depth, slot), (row as u32 + 1) * 2 + 1);
+ let path_bits = ((row as f32 + 1.0) * -0.25 + model[index]).to_bits();
+ assert_eq!(field(FrontierIdx::PathLogprobBits, slot), path_bits);
+ assert_eq!(
+ field(FrontierIdx::EdgeLogprobBits, slot),
+ prune.as_ref().map_or(model[index], |prune| prune[index]).to_bits()
+ );
+ assert_eq!(field(FrontierIdx::PathScoreKey, slot), score_key(path_bits));
+ assert_eq!(field(FrontierIdx::Active, slot), 1);
}
- });
+ for_each_non_cpu_backend!(|B| {
+ let actual = run_top_children::<B>(prune_noise_scale, &valid, &tree);
+ for offset in 0..expected.len() {
+ let field_index = offset / FRONTIER_CAPACITY;
+ let slot = offset % FRONTIER_CAPACITY;
+ let active = field(FrontierIdx::Active, slot) == 1;
+ if active
+ && (field_index == FrontierIdx::PathLogprobBits as usize
+ || field_index == FrontierIdx::EdgeLogprobBits as usize)
+ {
+ let tolerance = if field_index == FrontierIdx::PathLogprobBits as usize {
+ 1e-5
+ } else {
+ 1e-3
+ };
+ assert!((f32::from_bits(actual[offset]) - f32::from_bits(expected[offset])).abs() < tolerance);
+ } else if active && field_index == FrontierIdx::PathScoreKey as usize {
+ let path_bits = actual[FrontierIdx::PathLogprobBits as usize * FRONTIER_CAPACITY + slot];
+ assert_eq!(actual[offset], score_key(path_bits));
+ } else {
+ assert_eq!(actual[offset], expected[offset]);
+ }
+ }
+ });
+ }
}
}
@@ -111,9 +167,8 @@ fn weaver_top_children_matches_cpu() {
#[uzu_test]
fn weaver_top_children_prune_logprobs_match_reference() {
let (residual, candidate_logits, ids) = inputs();
- let (tokens, model, none) = top_children::<Cpu>(&residual, &candidate_logits, &ids, None);
- let (prune_tokens, prune_model, prune) =
- top_children::<Cpu>(&residual, &candidate_logits, &ids, Some(PRUNE_NOISE_SCALE));
+ let (tokens, model, none) = top_children::<Cpu>(None);
+ let (prune_tokens, prune_model, prune) = top_children::<Cpu>(Some(PRUNE_NOISE_SCALE));
assert!(none.is_none());
let prune = prune.unwrap();
assert_eq!(prune_tokens, tokens);