Skip to content

armgit / uzu

Public Imported from GitHub
0

A high-performance inference engine for AI models

GPU-resident DFlash tree construction (#628)

CCYeha9853515541f
diff --git a/crates/backend-uzu/src/backends/common/kernel/weaver/mod.rs b/crates/backend-uzu/src/backends/common/kernel/weaver/mod.rs
index 81b3d20d4..480024288 100644
--- a/crates/backend-uzu/src/backends/common/kernel/weaver/mod.rs
+++ b/crates/backend-uzu/src/backends/common/kernel/weaver/mod.rs
@@ -1 +1,27 @@
pub(crate) const MAX_CANDIDATES: usize = 512;
+
+pub(crate) const FRONTIER_LANE_TOKEN: usize = 0;
+pub(crate) const FRONTIER_LANE_PARENT: usize = 1;
+pub(crate) const FRONTIER_LANE_DEPTH: usize = 2;
+pub(crate) const FRONTIER_LANE_CUM: usize = 3;
+pub(crate) const FRONTIER_LANE_LOGPROB: usize = 4;
+pub(crate) const FRONTIER_LANE_KEY: usize = 5;
+pub(crate) const FRONTIER_LANE_ACTIVE: usize = 6;
+pub(crate) const FRONTIER_LANE_COUNT: usize = FRONTIER_LANE_ACTIVE + 1;
+
+pub(crate) const TREE_LANE_TOKEN: usize = 0;
+pub(crate) const TREE_LANE_PARENT: usize = 1;
+pub(crate) const TREE_LANE_DEPTH: usize = 2;
+pub(crate) const TREE_LANE_CUM: usize = 3;
+pub(crate) const TREE_LANE_LOGPROB: usize = 4;
+pub(crate) const TREE_LANE_MASK: usize = 5;
+pub(crate) const TREE_LANE_COUNT: usize = TREE_LANE_MASK + 1;
+
+pub(crate) const METADATA_LANE_DEPTH: usize = 0;
+pub(crate) const METADATA_LANE_ANCESTOR_COUNT: usize = 1;
+pub(crate) const METADATA_LANE_NODE_INDEX: usize = 2;
+pub(crate) const METADATA_LANE_COUNT: usize = METADATA_LANE_NODE_INDEX + 1;
+
+pub(crate) const NO_WINNER: u32 = u32::MAX;
+pub(crate) const MAX_FRONTIER_SLOTS: usize = 2048;
+pub(crate) const MAX_FRONTIER_WIDTH: usize = 32;
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/attention/attention_last_query.rs b/crates/backend-uzu/src/backends/cpu/kernel/attention/attention_last_query.rs
index 1ba4acb36..dd1e4d075 100644
--- a/crates/backend-uzu/src/backends/cpu/kernel/attention/attention_last_query.rs
+++ b/crates/backend-uzu/src/backends/cpu/kernel/attention/attention_last_query.rs
@@ -15,6 +15,7 @@ fn attention_last_query<const HEAD_DIM: u32>(
rows: u32,
prefix_length: u32,
ancestor_stride: u32,
+ node_capacity: u32,
scale: f32,
#[specialize] num_heads: u32,
) {
@@ -27,6 +28,7 @@ fn attention_last_query<const HEAD_DIM: u32>(
let qkv_width = QKV_COMPONENTS * num_heads * head_dim;
let kv_offset = KEY_COMPONENT * num_heads * head_dim;
let kv_width = KV_COMPONENTS * num_heads * head_dim;
+ let last_node = node_capacity.saturating_sub(1) as usize;
for row in 0..rows as usize {
unsafe {
@@ -37,7 +39,7 @@ fn attention_last_query<const HEAD_DIM: u32>(
let mut sequence = vec![bf16::ZERO; length * qkv_width];
std::ptr::copy_nonoverlapping(prefix_qkv, sequence.as_mut_ptr(), prefix_length as usize * qkv_width);
for offset in 0..ancestor_count {
- let ancestor = *ancestor_indices.add(row * ancestor_stride as usize + offset) as usize;
+ let ancestor = (*ancestor_indices.add(row * ancestor_stride as usize + offset) as usize).min(last_node);
std::ptr::copy_nonoverlapping(
node_qkv.add(ancestor * qkv_width + kv_offset),
sequence.as_mut_ptr().add((prefix_length as usize + offset) * qkv_width + kv_offset),
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/weaver/mod.rs b/crates/backend-uzu/src/backends/cpu/kernel/weaver/mod.rs
index c70352ab3..f7c44e340 100644
--- a/crates/backend-uzu/src/backends/cpu/kernel/weaver/mod.rs
+++ b/crates/backend-uzu/src/backends/cpu/kernel/weaver/mod.rs
@@ -1,2 +1,4 @@
+pub mod weaver_frontier_scatter;
+pub mod weaver_frontier_select;
pub mod weaver_node_cache_write;
pub mod weaver_top_children;
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/weaver/weaver_frontier_scatter.rs b/crates/backend-uzu/src/backends/cpu/kernel/weaver/weaver_frontier_scatter.rs
new file mode 100644
index 000000000..2acfe32c2
--- /dev/null
+++ b/crates/backend-uzu/src/backends/cpu/kernel/weaver/weaver_frontier_scatter.rs
@@ -0,0 +1,66 @@
+use proc_macros::kernel;
+
+use crate::backends::common::kernel::weaver::*;
+
+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(WeaverFrontierScatter)]
+pub fn weaver_frontier_scatter(
+ tree: *const u32,
+ round_metadata: *const u32,
+ round_valid: *const u32,
+ child_ids: *const u32,
+ child_logprobs: *const f32,
+ frontier: *mut u32,
+ capacity: u32,
+ tree_slots: u32,
+ rows: u32,
+ fanout: u32,
+) {
+ if capacity == 0 || tree_slots == 0 || fanout == 0 {
+ return;
+ }
+ let (capacity, tree_slots, rows, fanout) = (capacity as usize, tree_slots as usize, rows as usize, fanout as usize);
+ let tree = unsafe { std::slice::from_raw_parts(tree, TREE_LANE_COUNT * tree_slots) };
+ let parent_indices =
+ unsafe { std::slice::from_raw_parts(round_metadata.add(METADATA_LANE_NODE_INDEX * rows), rows) };
+ let round_valid = unsafe { std::slice::from_raw_parts(round_valid, rows) };
+ let child_ids = unsafe { std::slice::from_raw_parts(child_ids, rows * fanout) };
+ let child_logprobs = unsafe { std::slice::from_raw_parts(child_logprobs, rows * fanout) };
+ let frontier = unsafe { std::slice::from_raw_parts_mut(frontier, FRONTIER_LANE_COUNT * capacity) };
+
+ for index in 0..rows * fanout {
+ let row = index / fanout;
+ if round_valid[row] == 0 {
+ continue;
+ }
+ let parent = parent_indices[row] as usize;
+ let slot = parent * fanout + index % fanout;
+ if parent >= tree_slots || slot >= capacity {
+ continue;
+ }
+ let logprob = child_logprobs[index];
+ let cumulative_logprob = f32::from_bits(tree[TREE_LANE_CUM * tree_slots + parent]) + logprob;
+ let values = [
+ child_ids[index],
+ parent as u32,
+ tree[TREE_LANE_DEPTH * tree_slots + parent] + 1,
+ cumulative_logprob.to_bits(),
+ logprob.to_bits(),
+ top_k_score_key(cumulative_logprob),
+ 1,
+ ];
+ for (lane, value) in values.into_iter().enumerate() {
+ frontier[lane * capacity + slot] = value;
+ }
+ }
+}
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/weaver/weaver_frontier_select.rs b/crates/backend-uzu/src/backends/cpu/kernel/weaver/weaver_frontier_select.rs
new file mode 100644
index 000000000..b8f58767d
--- /dev/null
+++ b/crates/backend-uzu/src/backends/cpu/kernel/weaver/weaver_frontier_select.rs
@@ -0,0 +1,133 @@
+use proc_macros::kernel;
+
+use crate::backends::common::kernel::weaver::*;
+
+#[kernel(WeaverFrontierSelect)]
+pub fn weaver_frontier_select(
+ frontier: *mut u32,
+ tree: *mut u32,
+ slot_ancestors: *mut u32,
+ round_token_ids: *mut u32,
+ round_metadata: *mut u32,
+ round_ancestors: *mut u32,
+ round_valid: *mut u32,
+ candidate_pool_ids: *const u32,
+ candidate_pool_scores: *const f32,
+ round_candidate_ids: *mut u32,
+ round_candidate_scores: *mut f32,
+ capacity: u32,
+ tree_slots: u32,
+ width: u32,
+ slot_start: u32,
+ ancestor_stride: u32,
+ max_depth: u32,
+ lookahead_count: u32,
+ candidate_pool_rows: u32,
+ candidate_pool_size: u32,
+) {
+ if capacity == 0
+ || capacity as usize > MAX_FRONTIER_SLOTS
+ || width == 0
+ || width as usize > MAX_FRONTIER_WIDTH
+ || ancestor_stride == 0
+ || max_depth == 0
+ || tree_slots == 0
+ || slot_start + width > tree_slots
+ || candidate_pool_rows == 0
+ || candidate_pool_size == 0
+ {
+ return;
+ }
+ let (capacity, slots, width, stride) =
+ (capacity as usize, tree_slots as usize, width as usize, ancestor_stride as usize);
+ let (candidate_pool_rows, candidate_pool_size) = (candidate_pool_rows as usize, candidate_pool_size as usize);
+ let pool_len = candidate_pool_rows * candidate_pool_size;
+ let frontier = unsafe { std::slice::from_raw_parts_mut(frontier, FRONTIER_LANE_COUNT * capacity) };
+ let tree = unsafe { std::slice::from_raw_parts_mut(tree, TREE_LANE_COUNT * slots) };
+ let slot_ancestors = unsafe { std::slice::from_raw_parts_mut(slot_ancestors, slots * stride) };
+ let round_token_ids = unsafe { std::slice::from_raw_parts_mut(round_token_ids, width) };
+ let round_metadata = unsafe { std::slice::from_raw_parts_mut(round_metadata, METADATA_LANE_COUNT * width) };
+ let round_ancestors = unsafe { std::slice::from_raw_parts_mut(round_ancestors, width * stride) };
+ let round_valid = unsafe { std::slice::from_raw_parts_mut(round_valid, width) };
+ let candidate_pool_ids = unsafe { std::slice::from_raw_parts(candidate_pool_ids, pool_len) };
+ let candidate_pool_scores = unsafe { std::slice::from_raw_parts(candidate_pool_scores, pool_len) };
+ let round_candidate_ids =
+ unsafe { std::slice::from_raw_parts_mut(round_candidate_ids, width * candidate_pool_size) };
+ let round_candidate_scores =
+ unsafe { std::slice::from_raw_parts_mut(round_candidate_scores, width * candidate_pool_size) };
+
+ for row in 0..width {
+ let (mut key, mut parent, mut token, mut winner) = (0, NO_WINNER, NO_WINNER, NO_WINNER);
+ for slot in 0..capacity {
+ if frontier[FRONTIER_LANE_ACTIVE * capacity + slot] == 0 {
+ continue;
+ }
+ let next = (
+ frontier[FRONTIER_LANE_KEY * capacity + slot],
+ frontier[FRONTIER_LANE_PARENT * capacity + slot],
+ frontier[FRONTIER_LANE_TOKEN * 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 != NO_WINNER;
+ let winner = if real {
+ winner as usize
+ } else {
+ 0
+ };
+ let tree_slot = slot_start as usize + row;
+ let lane_value = |lane: usize| u32::from(real) * frontier[lane * capacity + winner];
+ let token = lane_value(FRONTIER_LANE_TOKEN);
+ let depth = lane_value(FRONTIER_LANE_DEPTH);
+ let cumulative_logprob = lane_value(FRONTIER_LANE_CUM);
+ let logprob = lane_value(FRONTIER_LANE_LOGPROB);
+
+ tree[TREE_LANE_TOKEN * slots + tree_slot] = token;
+ tree[TREE_LANE_PARENT * slots + tree_slot] = if real {
+ parent
+ } else {
+ NO_WINNER
+ };
+ tree[TREE_LANE_DEPTH * slots + tree_slot] = depth;
+ tree[TREE_LANE_CUM * slots + tree_slot] = cumulative_logprob;
+ tree[TREE_LANE_LOGPROB * slots + tree_slot] = logprob;
+ tree[TREE_LANE_MASK * slots + tree_slot] = u32::from(real);
+
+ if real {
+ frontier[FRONTIER_LANE_ACTIVE * capacity + winner] = 0;
+ }
+
+ let parent_slot = if real && (parent as usize) < slots {
+ parent as usize
+ } else {
+ 0
+ };
+ for index in 0..stride {
+ let ancestor = if real && index + 1 < depth as usize {
+ slot_ancestors[parent_slot * stride + index]
+ } else if real && index + 1 == depth as usize {
+ parent_slot as u32
+ } else {
+ 0
+ };
+ slot_ancestors[tree_slot * stride + index] = ancestor;
+ round_ancestors[row * stride + index] = ancestor;
+ }
+
+ round_token_ids[row] = token;
+ round_metadata[METADATA_LANE_DEPTH * width + row] = depth.min(max_depth - 1);
+ round_metadata[METADATA_LANE_ANCESTOR_COUNT * width + row] = depth.min(stride as u32);
+ round_metadata[METADATA_LANE_NODE_INDEX * width + row] = tree_slot as u32;
+ round_valid[row] = u32::from(real && depth < lookahead_count && depth < max_depth);
+
+ // Every row of a round expands the pool for its own depth, so the winner's pool row is
+ // copied into the contiguous per-round buffer the Weaver step reads.
+ let candidate_pool_row = (depth as usize).min(candidate_pool_rows - 1);
+ let source = candidate_pool_row * candidate_pool_size..(candidate_pool_row + 1) * candidate_pool_size;
+ let destination = row * candidate_pool_size..(row + 1) * candidate_pool_size;
+ round_candidate_ids[destination.clone()].copy_from_slice(&candidate_pool_ids[source.clone()]);
+ round_candidate_scores[destination].copy_from_slice(&candidate_pool_scores[source]);
+ }
+}
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/weaver/weaver_node_cache_write.rs b/crates/backend-uzu/src/backends/cpu/kernel/weaver/weaver_node_cache_write.rs
index 94d831d26..346d9bdd2 100644
--- a/crates/backend-uzu/src/backends/cpu/kernel/weaver/weaver_node_cache_write.rs
+++ b/crates/backend-uzu/src/backends/cpu/kernel/weaver/weaver_node_cache_write.rs
@@ -11,15 +11,21 @@ pub fn weaver_node_cache_write<T: ArrayElement + Float>(
node_qkv: *mut T,
node_indices: *const u32,
model_dim: u32,
+ node_capacity: u32,
total: u32,
) {
+ if node_capacity == 0 {
+ return;
+ }
let model_dim = model_dim as usize;
let qkv_width = 3 * model_dim;
+ let last_node = (node_capacity - 1) as usize;
unsafe {
for position in 0..total as usize {
let row = position / (2 * model_dim);
let offset = position - row * 2 * model_dim;
- *node_qkv.add(*node_indices.add(row) as usize * qkv_width + model_dim + offset) =
+ let node = (*node_indices.add(row) as usize).min(last_node);
+ *node_qkv.add(node * qkv_width + model_dim + offset) =
*current_qkv.add(row * qkv_width + model_dim + offset);
}
}
diff --git a/crates/backend-uzu/src/backends/metal/kernel/attention/attention_last_query.metal b/crates/backend-uzu/src/backends/metal/kernel/attention/attention_last_query.metal
index f4b749570..0f6aabaac 100644
--- a/crates/backend-uzu/src/backends/metal/kernel/attention/attention_last_query.metal
+++ b/crates/backend-uzu/src/backends/metal/kernel/attention/attention_last_query.metal
@@ -61,6 +61,7 @@ PUBLIC KERNEL(AttentionLastQuery)(
constant uint& rows,
constant uint& prefix_length,
constant uint& ancestor_stride,
+ constant uint& node_capacity,
constant float& scale,
const uint num_heads SPECIALIZE,
const ThreadContext thread_context,
@@ -105,15 +106,16 @@ PUBLIC KERNEL(AttentionLastQuery)(
const uint ancestor_count = ancestor_counts[row];
const device uint* row_ancestors = ancestor_indices + row * ancestor_stride;
+ const uint last_node = node_capacity == 0 ? 0u : node_capacity - 1u;
uint offset = 0;
for (; offset + unroll_count - 1 < ancestor_count; offset += unroll_count) {
attend_qkv<unroll_count>(query, key_offset, value_offset, values, max_score, sum, [&](int step) {
- return node_vectors + row_ancestors[offset + step] * qkv_vectors;
+ return node_vectors + min(row_ancestors[offset + step], last_node) * qkv_vectors;
});
}
for (; offset < ancestor_count; ++offset) {
attend_qkv<1>(query, key_offset, value_offset, values, max_score, sum, [&](int) {
- return node_vectors + row_ancestors[offset] * qkv_vectors;
+ return node_vectors + min(row_ancestors[offset], last_node) * qkv_vectors;
});
}
diff --git a/crates/backend-uzu/src/backends/metal/kernel/weaver/weaver_frontier.h b/crates/backend-uzu/src/backends/metal/kernel/weaver/weaver_frontier.h
new file mode 100644
index 000000000..47a803776
--- /dev/null
+++ b/crates/backend-uzu/src/backends/metal/kernel/weaver/weaver_frontier.h
@@ -0,0 +1,29 @@
+#pragma once
+
+using namespace metal;
+
+constant uint WEAVER_FRONTIER_LANE_TOKEN = 0;
+constant uint WEAVER_FRONTIER_LANE_PARENT = 1;
+constant uint WEAVER_FRONTIER_LANE_DEPTH = 2;
+constant uint WEAVER_FRONTIER_LANE_CUM = 3;
+constant uint WEAVER_FRONTIER_LANE_LOGPROB = 4;
+constant uint WEAVER_FRONTIER_LANE_KEY = 5;
+constant uint WEAVER_FRONTIER_LANE_ACTIVE = 6;
+
+constant uint WEAVER_TREE_LANE_TOKEN = 0;
+constant uint WEAVER_TREE_LANE_PARENT = 1;
+constant uint WEAVER_TREE_LANE_DEPTH = 2;
+constant uint WEAVER_TREE_LANE_CUM = 3;
+constant uint WEAVER_TREE_LANE_LOGPROB = 4;
+constant uint WEAVER_TREE_LANE_MASK = 5;
+
+constant uint WEAVER_METADATA_LANE_DEPTH = 0;
+constant uint WEAVER_METADATA_LANE_ANCESTOR_COUNT = 1;
+constant uint WEAVER_METADATA_LANE_NODE_INDEX = 2;
+
+constant uint WEAVER_FRONTIER_NO_WINNER = 0xffffffffu;
+constant uint WEAVER_FRONTIER_SELECT_THREADS = 256;
+constant uint WEAVER_FRONTIER_SELECT_SIMDGROUPS = 8;
+constant uint WEAVER_FRONTIER_ENTRIES_PER_THREAD = 8;
+constant uint WEAVER_FRONTIER_MAX_SLOTS = 2048;
+constant uint WEAVER_FRONTIER_MAX_WIDTH = 32;
diff --git a/crates/backend-uzu/src/backends/metal/kernel/weaver/weaver_frontier_scatter.metal b/crates/backend-uzu/src/backends/metal/kernel/weaver/weaver_frontier_scatter.metal
new file mode 100644
index 000000000..13756a247
--- /dev/null
+++ b/crates/backend-uzu/src/backends/metal/kernel/weaver/weaver_frontier_scatter.metal
@@ -0,0 +1,49 @@
+#include <metal_stdlib>
+#include "../common/dsl.h"
+#include "../common/top_k.h"
+#include "weaver_frontier.h"
+
+using namespace metal;
+
+PUBLIC KERNEL(WeaverFrontierScatter)(
+ const device uint* tree,
+ const device uint* round_metadata,
+ const device uint* round_valid,
+ const device uint* child_ids,
+ const device float* child_logprobs,
+ device uint* frontier,
+ constant uint& capacity,
+ constant uint& tree_slots,
+ constant uint& rows,
+ constant uint& fanout,
+ const uint position AXIS(rows* fanout, 64)
+) {
+ if (capacity == 0 || tree_slots == 0 || fanout == 0) {
+ return;
+ }
+
+ const uint row = position / fanout, child = position % fanout;
+ if (round_valid[row] == 0u) {
+ return;
+ }
+
+ const uint parent = round_metadata[WEAVER_METADATA_LANE_NODE_INDEX * rows + row];
+ if (parent >= tree_slots) {
+ return;
+ }
+ const uint slot = parent * fanout + child;
+ if (slot >= capacity) {
+ return;
+ }
+
+ const float logprob = child_logprobs[row * fanout + child];
+ const float cumulative_logprob = as_type<float>(tree[WEAVER_TREE_LANE_CUM * tree_slots + parent]) + logprob;
+
+ frontier[WEAVER_FRONTIER_LANE_TOKEN * capacity + slot] = child_ids[row * fanout + child];
+ frontier[WEAVER_FRONTIER_LANE_PARENT * capacity + slot] = parent;
+ frontier[WEAVER_FRONTIER_LANE_DEPTH * capacity + slot] = tree[WEAVER_TREE_LANE_DEPTH * tree_slots + parent] + 1u;
+ frontier[WEAVER_FRONTIER_LANE_CUM * capacity + slot] = as_type<uint>(cumulative_logprob);
+ frontier[WEAVER_FRONTIER_LANE_LOGPROB * capacity + slot] = as_type<uint>(logprob);
+ frontier[WEAVER_FRONTIER_LANE_KEY * capacity + slot] = top_k_score_key(cumulative_logprob);
+ frontier[WEAVER_FRONTIER_LANE_ACTIVE * capacity + slot] = 1u;
+}
diff --git a/crates/backend-uzu/src/backends/metal/kernel/weaver/weaver_frontier_select.metal b/crates/backend-uzu/src/backends/metal/kernel/weaver/weaver_frontier_select.metal
new file mode 100644
index 000000000..ac8968116
--- /dev/null
+++ b/crates/backend-uzu/src/backends/metal/kernel/weaver/weaver_frontier_select.metal
@@ -0,0 +1,148 @@
+#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* tree,
+ device uint* slot_ancestors,
+ device uint* round_token_ids,
+ device uint* round_metadata,
+ device uint* round_ancestors,
+ device uint* round_valid,
+ const device uint* candidate_pool_ids,
+ const device float* candidate_pool_scores,
+ device uint* round_candidate_ids,
+ device float* round_candidate_scores,
+ constant uint& capacity,
+ constant uint& tree_slots,
+ constant uint& width,
+ constant uint& slot_start,
+ constant uint& ancestor_stride,
+ constant uint& max_depth,
+ constant uint& lookahead_count,
+ constant uint& candidate_pool_rows,
+ constant uint& candidate_pool_size,
+ threadgroup uint4 reduce[WEAVER_FRONTIER_SELECT_SIMDGROUPS],
+ threadgroup uint winner_slot[WEAVER_FRONTIER_MAX_WIDTH],
+ threadgroup uint row_candidate_pool_row[WEAVER_FRONTIER_MAX_WIDTH],
+ const ThreadContext thread_context,
+ const uint group_index GROUPS(1),
+ const uint lid THREADS(256)
+) {
+ (void)group_index;
+ if (capacity == 0 || capacity > WEAVER_FRONTIER_MAX_SLOTS || width == 0 || width > WEAVER_FRONTIER_MAX_WIDTH ||
+ ancestor_stride == 0 || max_depth == 0 || tree_slots == 0 || slot_start + width > tree_slots ||
+ candidate_pool_rows == 0 || candidate_pool_size == 0) {
+ return;
+ }
+
+ bool entry_active[WEAVER_FRONTIER_ENTRIES_PER_THREAD];
+ for (uint entry = 0; entry < WEAVER_FRONTIER_ENTRIES_PER_THREAD; ++entry) {
+ const uint slot = lid + entry * WEAVER_FRONTIER_SELECT_THREADS;
+ entry_active[entry] = slot < capacity && frontier[WEAVER_FRONTIER_LANE_ACTIVE * capacity + slot] != 0u;
+ }
+
+ for (uint child = 0; child < width; ++child) {
+ uint4 local = uint4(0u, WEAVER_FRONTIER_NO_WINNER, WEAVER_FRONTIER_NO_WINNER, WEAVER_FRONTIER_NO_WINNER);
+ for (uint entry = 0; entry < WEAVER_FRONTIER_ENTRIES_PER_THREAD; ++entry) {
+ const uint slot = lid + entry * WEAVER_FRONTIER_SELECT_THREADS;
+ if (entry_active[entry]) {
+ const uint key = frontier[WEAVER_FRONTIER_LANE_KEY * capacity + slot];
+ const uint parent = frontier[WEAVER_FRONTIER_LANE_PARENT * capacity + slot];
+ const uint token = frontier[WEAVER_FRONTIER_LANE_TOKEN * capacity + slot];
+ if (key > local.x || (key == local.x && (parent < local.y || (parent == local.y && token < local.z)))) {
+ local = uint4(key, parent, token, slot);
+ }
+ }
+ }
+
+ uint4 simd;
+ simd.x = simd_max(local.x);
+ simd.y = simd_min(local.x == simd.x ? local.y : WEAVER_FRONTIER_NO_WINNER);
+ simd.z = simd_min(all(local.xy == simd.xy) ? local.z : WEAVER_FRONTIER_NO_WINNER);
+ simd.w = simd_min(all(local.xyz == simd.xyz) ? local.w : WEAVER_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 < WEAVER_FRONTIER_SELECT_SIMDGROUPS
+ ? reduce[thread_context.simd_lane_id]
+ : uint4(0u, WEAVER_FRONTIER_NO_WINNER, WEAVER_FRONTIER_NO_WINNER, WEAVER_FRONTIER_NO_WINNER);
+ uint4 selected;
+ selected.x = simd_max(partial.x);
+ selected.y = simd_min(partial.x == selected.x ? partial.y : WEAVER_FRONTIER_NO_WINNER);
+ selected.z = simd_min(all(partial.xy == selected.xy) ? partial.z : WEAVER_FRONTIER_NO_WINNER);
+ selected.w = simd_min(all(partial.xyz == selected.xyz) ? partial.w : WEAVER_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 < WEAVER_FRONTIER_ENTRIES_PER_THREAD; ++entry) {
+ entry_active[entry] = entry_active[entry] && (lid + entry * WEAVER_FRONTIER_SELECT_THREADS) != selected;
+ }
+ }
+
+ if (lid < width) {
+ const uint row = lid;
+ const uint slot = winner_slot[row];
+ const bool real = slot != WEAVER_FRONTIER_NO_WINNER;
+ const uint tree_slot = slot_start + row;
+
+ const uint token = real ? frontier[WEAVER_FRONTIER_LANE_TOKEN * capacity + slot] : 0u;
+ const uint parent = real ? frontier[WEAVER_FRONTIER_LANE_PARENT * capacity + slot] : WEAVER_FRONTIER_NO_WINNER;
+ const uint depth = real ? frontier[WEAVER_FRONTIER_LANE_DEPTH * capacity + slot] : 0u;
+ const uint cumulative_logprob = real ? frontier[WEAVER_FRONTIER_LANE_CUM * capacity + slot] : 0u;
+ const uint logprob = real ? frontier[WEAVER_FRONTIER_LANE_LOGPROB * capacity + slot] : 0u;
+
+ tree[WEAVER_TREE_LANE_TOKEN * tree_slots + tree_slot] = token;
+ tree[WEAVER_TREE_LANE_PARENT * tree_slots + tree_slot] = parent;
+ tree[WEAVER_TREE_LANE_DEPTH * tree_slots + tree_slot] = depth;
+ tree[WEAVER_TREE_LANE_CUM * tree_slots + tree_slot] = cumulative_logprob;
+ tree[WEAVER_TREE_LANE_LOGPROB * tree_slots + tree_slot] = logprob;
+ tree[WEAVER_TREE_LANE_MASK * tree_slots + tree_slot] = real ? 1u : 0u;
+
+ if (real) {
+ frontier[WEAVER_FRONTIER_LANE_ACTIVE * capacity + slot] = 0u;
+ }
+
+ const uint parent_slot = real && parent < tree_slots ? 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;
+ round_ancestors[row * ancestor_stride + index] = ancestor;
+ }
+
+ round_token_ids[row] = token;
+ round_metadata[WEAVER_METADATA_LANE_DEPTH * width + row] = min(depth, max_depth - 1u);
+ round_metadata[WEAVER_METADATA_LANE_ANCESTOR_COUNT * width + row] = min(depth, ancestor_stride);
+ round_metadata[WEAVER_METADATA_LANE_NODE_INDEX * width + row] = tree_slot;
+ round_valid[row] = real && depth < lookahead_count && depth < max_depth ? 1u : 0u;
+
+ row_candidate_pool_row[row] = min(depth, candidate_pool_rows - 1u);
+ }
+
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ for (uint row = 0; row < width; ++row) {
+ const uint source = row_candidate_pool_row[row] * candidate_pool_size;
+ const uint destination = row * candidate_pool_size;
+ for (uint candidate = lid; candidate < candidate_pool_size; candidate += WEAVER_FRONTIER_SELECT_THREADS) {
+ round_candidate_ids[destination + candidate] = candidate_pool_ids[source + candidate];
+ round_candidate_scores[destination + candidate] = candidate_pool_scores[source + candidate];
+ }
+ }
+}
diff --git a/crates/backend-uzu/src/backends/metal/kernel/weaver/weaver_node_cache_write.metal b/crates/backend-uzu/src/backends/metal/kernel/weaver/weaver_node_cache_write.metal
index c0a56d3eb..4c22b966f 100644
--- a/crates/backend-uzu/src/backends/metal/kernel/weaver/weaver_node_cache_write.metal
+++ b/crates/backend-uzu/src/backends/metal/kernel/weaver/weaver_node_cache_write.metal
@@ -11,11 +11,16 @@ PUBLIC KERNEL(WeaverNodeCacheWrite)(
device T* node_qkv,
const device uint* node_indices,
constant uint& model_dim,
+ constant uint& node_capacity,
constant uint& total,
const uint position AXIS(total, 256)
) {
+ if (node_capacity == 0) {
+ return;
+ }
const uint row = position / (2 * model_dim);
const uint offset = position - row * 2 * model_dim;
const uint qkv_width = 3 * model_dim;
- node_qkv[node_indices[row] * qkv_width + model_dim + offset] = current_qkv[row * qkv_width + model_dim + offset];
+ const uint node = min(node_indices[row], node_capacity - 1u);
+ node_qkv[node * qkv_width + model_dim + offset] = current_qkv[row * qkv_width + model_dim + offset];
}
diff --git a/crates/backend-uzu/src/encodable_block/weaver.rs b/crates/backend-uzu/src/encodable_block/weaver.rs
index 370634e6e..ca5cd814a 100644
--- a/crates/backend-uzu/src/encodable_block/weaver.rs
+++ b/crates/backend-uzu/src/encodable_block/weaver.rs
@@ -6,7 +6,8 @@ use crate::{
Allocation, AllocationType, Backend, Context, Encoder, Kernels,
kernel::{
ActivationKernel, AttentionLastQueryKernel, AttentionPrepareKernel, TensorAddBiasKernel,
- TensorAddSwapKernel, WeaverNodeCacheWriteKernel, WeaverTopChildrenKernel, weaver::MAX_CANDIDATES,
+ TensorAddSwapKernel, WeaverNodeCacheWriteKernel, WeaverTopChildrenKernel,
+ weaver::{MAX_CANDIDATES, METADATA_LANE_COUNT},
},
},
config::{normalization::NormalizationConfig, weaver::WeaverConfig},
@@ -28,26 +29,19 @@ pub(crate) struct WeaverPrefix<B: Backend> {
pub(crate) length: usize,
}
-pub(crate) struct WeaverBatchStepInput<'a> {
- pub node_index: usize,
- pub parent_token: u32,
- pub candidates: &'a [u32],
- pub candidate_scores: &'a [f32],
- pub ancestors: &'a [usize],
- pub depth: usize,
+pub(crate) struct WeaverStepBatch<'a, B: Backend> {
+ pub row_count: usize,
+ pub candidate_count: usize,
+ pub ancestor_stride: usize,
+ pub parent_token_ids: &'a Allocation<B>,
+ pub candidate_ids: &'a Allocation<B>,
+ pub candidate_scores: &'a Allocation<B>,
+ pub ancestor_indices: &'a Allocation<B>,
+ pub node_metadata: &'a Allocation<B>,
}
pub(crate) struct WeaverNodeState<B: Backend> {
layer_qkv: Box<[Allocation<B>]>,
- capacity: usize,
-}
-
-struct WeaverStepInputs<B: Backend> {
- candidate_ids: Allocation<B>,
- candidate_scores: Allocation<B>,
- ancestor_indices: Allocation<B>,
- metadata: Allocation<B>,
- ancestor_stride: usize,
}
pub(crate) struct Weaver<B: Backend> {
@@ -205,7 +199,6 @@ impl<B: Backend> Weaver<B> {
.collect::<Result<Box<[_]>, _>>()?;
Ok(WeaverNodeState {
layer_qkv,
- capacity,
})
}
@@ -306,7 +299,7 @@ impl<B: Backend> Weaver<B> {
lookaheads: &Allocation<B>,
lookahead_offset: usize,
lookahead_count: usize,
- context: &B::Context,
+ encoder: &mut Encoder<B>,
) -> Result<WeaverPrefix<B>, WeaverEncodeError<B>> {
let length = lookahead_count + 1;
assert!(lookahead_count <= self.max_depth);
@@ -314,7 +307,7 @@ impl<B: Backend> Weaver<B> {
assert!(target_hidden.size() >= row_bytes);
assert!(lookaheads.size() >= (lookahead_offset + lookahead_count) * row_bytes);
- let mut encoder = Encoder::new(context).map_err(WeaverEncodeError::Backend)?;
+ let context = encoder.context();
let mut input = encoder
.allocate_scratch(size_for_shape(&[length, self.target_model_dim], self.data_type))
.map_err(WeaverEncodeError::Backend)?;
@@ -327,12 +320,9 @@ impl<B: Backend> Weaver<B> {
row_bytes..length * row_bytes,
);
}
- let normalized =
- self.hidden_state_norm.encode(&input, length, &mut encoder).map_err(WeaverEncodeError::Backend)?;
- let mut hidden = self
- .hidden_state_projection
- .encode(normalized, length, &mut encoder)
- .map_err(WeaverEncodeError::Backend)?;
+ let normalized = self.hidden_state_norm.encode(&input, length, encoder).map_err(WeaverEncodeError::Backend)?;
+ let mut hidden =
+ self.hidden_state_projection.encode(normalized, length, encoder).map_err(WeaverEncodeError::Backend)?;
let position_elements = lookahead_count * self.model_dim;
self.position_add.encode(
None::<&Allocation<B>>,
@@ -341,187 +331,95 @@ impl<B: Backend> Weaver<B> {
(&mut hidden, self.model_dim * self.data_type.size_in_bytes()),
position_elements as u32,
position_elements as u32,
- &mut encoder,
+ encoder,
);
let mut layer_qkv = Vec::with_capacity(self.blocks.len());
for block in &self.blocks {
let (next_hidden, qkv) =
- block.encode_prefix(hidden, length, &mut encoder).map_err(WeaverEncodeError::Backend)?;
+ block.encode_prefix(hidden, length, encoder).map_err(WeaverEncodeError::Backend)?;
let mut cached_qkv =
context.create_allocation(qkv.size(), AllocationType::Global).map_err(WeaverEncodeError::Backend)?;
encoder.encode_copy(&qkv, .., &mut cached_qkv, ..);
layer_qkv.push(cached_qkv);
hidden = next_hidden;
}
- let completed = encoder.end_encoding().submit().wait_until_completed().map_err(WeaverEncodeError::Backend)?;
drop(input);
drop(hidden);
- drop(completed);
Ok(WeaverPrefix {
layer_qkv: layer_qkv.into_boxed_slice(),
length,
})
}
- pub(crate) fn step_batch(
- &self,
- prefix: &WeaverPrefix<B>,
- inputs: &[WeaverBatchStepInput<'_>],
- state: &mut WeaverNodeState<B>,
- children: usize,
- target_embedding: &Embedding<B>,
- context: &B::Context,
- ) -> Result<Vec<Vec<(u32, f32)>>, WeaverEncodeError<B>> {
- assert!(!inputs.is_empty());
- let mut encoder = Encoder::new(context).map_err(WeaverEncodeError::Backend)?;
- let (child_ids, child_logprobs) =
- self.encode_step_batch(prefix, inputs, state, children, target_embedding, &mut encoder)?;
- let completed = encoder.end_encoding().submit().wait_until_completed().map_err(WeaverEncodeError::Backend)?;
- let child_ids_output = child_ids.copyout::<u32>();
- let child_logprobs_output = child_logprobs.copyout::<f32>();
- let outputs = (0..inputs.len())
- .map(|batch_index| {
- (0..children)
- .map(|child| {
- let index = batch_index * children + child;
- (child_ids_output[index], child_logprobs_output[index])
- })
- .collect()
- })
- .collect();
- drop(child_ids);
- drop(child_logprobs);
- drop(completed);
- Ok(outputs)
- }
-
- fn encode_step_batch(
+ pub(crate) fn encode_step_batch(
&self,
prefix: &WeaverPrefix<B>,
- inputs: &[WeaverBatchStepInput<'_>],
+ input: &WeaverStepBatch<'_, B>,
state: &mut WeaverNodeState<B>,
children: usize,
target_embedding: &Embedding<B>,
encoder: &mut Encoder<B>,
) -> Result<(Allocation<B>, Allocation<B>), WeaverEncodeError<B>> {
- let rows = inputs.len();
- let candidates = inputs[0].candidates.len();
+ let rows = input.row_count;
+ let candidates = input.candidate_count;
+ assert!(rows > 0);
assert!(candidates > 0 && candidates <= MAX_CANDIDATES);
assert!(children > 0 && children <= candidates);
- // Indices reach the GPU unchecked, so they must stay inside the arena.
- // Batch nodes are expected to be mutually independent: a child only
- // enters the frontier once its parent's step has been read back, so a
- // parent and child can never share a batch.
- assert!(
- inputs.iter().all(|input| {
- input.candidates.len() == candidates
- && input.candidate_scores.len() == candidates
- && input.depth < self.max_depth
- && input.node_index < state.capacity
- && input.ancestors.iter().all(|&ancestor| ancestor < state.capacity)
- }),
- "inputs must reference node indices within the node-state capacity"
- );
-
- let (mut current, step) = self.encode_step_inputs(inputs, target_embedding, encoder)?;
+ assert!(input.ancestor_stride > 0);
+ let word = DataType::U32.size_in_bytes();
+ debug_assert!(input.node_metadata.size() >= METADATA_LANE_COUNT * rows * word);
+ debug_assert!(input.parent_token_ids.size() >= rows * word);
+ debug_assert!(input.ancestor_indices.size() >= rows * input.ancestor_stride * word);
- for (layer_index, block) in self.blocks.iter().enumerate() {
- current = block
- .encode_step(
- current,
- &prefix.layer_qkv[layer_index],
- &mut state.layer_qkv[layer_index],
- &step,
- prefix.length,
- rows,
- encoder,
- )
- .map_err(WeaverEncodeError::Backend)?;
- }
-
- self.encode_step_output(&current, &step, rows, candidates, children, target_embedding, encoder)
- }
-
- fn encode_step_inputs(
- &self,
- inputs: &[WeaverBatchStepInput<'_>],
- target_embedding: &Embedding<B>,
- encoder: &mut Encoder<B>,
- ) -> Result<(Allocation<B>, WeaverStepInputs<B>), WeaverEncodeError<B>> {
- let rows = inputs.len();
- let token_ids = encoder
- .allocate_constant_from_slice(&inputs.iter().map(|input| input.parent_token).collect::<Vec<_>>())
- .map_err(WeaverEncodeError::Backend)?;
- let candidate_ids = encoder
- .allocate_constant_from_slice(
- &inputs.iter().flat_map(|input| input.candidates.iter().copied()).collect::<Vec<_>>(),
- )
- .map_err(WeaverEncodeError::Backend)?;
- let candidate_scores = encoder
- .allocate_constant_from_slice(
- &inputs.iter().flat_map(|input| input.candidate_scores.iter().copied()).collect::<Vec<_>>(),
- )
- .map_err(WeaverEncodeError::Backend)?;
- let token_embedding = target_embedding.encode_lookup(&token_ids, rows, encoder)?;
+ let token_embedding = target_embedding.encode_lookup(input.parent_token_ids, rows, encoder)?;
let embedding_normalized =
self.embedding_norm.encode(&token_embedding, rows, encoder).map_err(WeaverEncodeError::Backend)?;
let mut current = self
.embedding_projection
.encode(embedding_normalized, rows, encoder)
.map_err(WeaverEncodeError::Backend)?;
- // [depths, ancestor counts, node indices]
- let mut metadata_values = Vec::with_capacity(3 * rows);
- metadata_values.extend(inputs.iter().map(|input| input.depth as u32));
- metadata_values.extend(inputs.iter().map(|input| input.ancestors.len() as u32));
- metadata_values.extend(inputs.iter().map(|input| input.node_index as u32));
- let metadata = encoder.allocate_constant_from_slice(&metadata_values).map_err(WeaverEncodeError::Backend)?;
self.indexed_position_add.encode(
None::<&Allocation<B>>,
&self.position_embeddings,
- Some(&metadata),
+ Some(input.node_metadata),
&mut current,
self.model_dim as u32,
(rows * self.model_dim) as u32,
encoder,
);
- let ancestor_stride = inputs.iter().map(|input| input.ancestors.len()).max().unwrap().max(1);
- let mut ancestors = vec![0u32; rows * ancestor_stride];
- for (row, input) in inputs.iter().enumerate() {
- for (offset, &ancestor) in input.ancestors.iter().enumerate() {
- ancestors[row * ancestor_stride + offset] = ancestor as u32;
- }
+ for (layer_index, block) in self.blocks.iter().enumerate() {
+ current = block
+ .encode_step(
+ current,
+ &prefix.layer_qkv[layer_index],
+ &mut state.layer_qkv[layer_index],
+ input,
+ prefix.length,
+ encoder,
+ )
+ .map_err(WeaverEncodeError::Backend)?;
}
- let ancestor_indices = encoder.allocate_constant_from_slice(&ancestors).map_err(WeaverEncodeError::Backend)?;
- Ok((
- current,
- WeaverStepInputs {
- candidate_ids,
- candidate_scores,
- ancestor_indices,
- metadata,
- ancestor_stride,
- },
- ))
+
+ self.encode_step_output(&current, input, children, target_embedding, encoder)
}
/// Outputs must outlive the batch.
fn encode_step_output(
&self,
current: &Allocation<B>,
- step: &WeaverStepInputs<B>,
- rows: usize,
- candidates: usize,
+ step: &WeaverStepBatch<'_, B>,
children: usize,
target_embedding: &Embedding<B>,
encoder: &mut Encoder<B>,
) -> Result<(Allocation<B>, Allocation<B>), WeaverEncodeError<B>> {
+ let (rows, candidates) = (step.row_count, step.candidate_count);
let output_normalized = self.output_norm.encode(current, rows, encoder).map_err(WeaverEncodeError::Backend)?;
let query =
self.query_projection.encode(output_normalized, rows, encoder).map_err(WeaverEncodeError::Backend)?;
let candidate_logits =
- target_embedding.encode_readout_sparse(&query, &step.candidate_ids, rows, candidates, encoder)?;
+ target_embedding.encode_readout_sparse(&query, step.candidate_ids, rows, candidates, encoder)?;
let mut child_ids = encoder
.allocate_scratch(size_for_shape(&[rows, children], DataType::U32))
.map_err(WeaverEncodeError::Backend)?;
@@ -530,8 +428,8 @@ impl<B: Backend> Weaver<B> {
.map_err(WeaverEncodeError::Backend)?;
self.top_children.encode(
&candidate_logits,
- &step.candidate_scores,
- &step.candidate_ids,
+ step.candidate_scores,
+ step.candidate_ids,
&mut child_ids,
&mut child_logprobs,
rows as u32,
@@ -621,27 +519,29 @@ impl<B: Backend> WeaverBlock<B> {
current: Allocation<B>,
prefix_qkv: &Allocation<B>,
state_qkv: &mut Allocation<B>,
- step: &WeaverStepInputs<B>,
+ step: &WeaverStepBatch<'_, B>,
prefix_length: usize,
- rows: usize,
encoder: &mut Encoder<B>,
) -> Result<Allocation<B>, B::Error> {
+ let rows = step.row_count;
let normalized = self.pre_attention_norm.encode(&current, rows, encoder)?;
let current_qkv = self.qkv_projection.encode(normalized, rows, encoder)?;
let metadata_row_bytes = rows * DataType::U32.size_in_bytes();
- let ancestor_counts = (&step.metadata, metadata_row_bytes);
- let node_indices = (&step.metadata, 2 * metadata_row_bytes);
+ let ancestor_counts = (step.node_metadata, metadata_row_bytes);
+ let node_indices = (step.node_metadata, 2 * metadata_row_bytes);
let mut attention = encoder.allocate_scratch(size_for_shape(&[rows, self.model_dim], self.data_type))?;
+ let node_capacity = (state_qkv.size() / size_for_shape(&[3, self.model_dim], self.data_type)) as u32;
self.last_query_attention.encode(
prefix_qkv,
&*state_qkv,
&current_qkv,
- &step.ancestor_indices,
+ step.ancestor_indices,
ancestor_counts,
&mut attention,
rows as u32,
prefix_length as u32,
step.ancestor_stride as u32,
+ node_capacity,
self.attention_scale,
encoder,
);
@@ -652,6 +552,7 @@ impl<B: Backend> WeaverBlock<B> {
state_qkv,
node_indices,
self.model_dim as u32,
+ node_capacity,
(rows * 2 * self.model_dim) as u32,
encoder,
);
diff --git a/crates/backend-uzu/src/speculators/dflash_speculator.rs b/crates/backend-uzu/src/speculators/dflash_speculator.rs
index ab680e6af..33edb8212 100644
--- a/crates/backend-uzu/src/speculators/dflash_speculator.rs
+++ b/crates/backend-uzu/src/speculators/dflash_speculator.rs
@@ -1,16 +1,25 @@
-use std::{cmp::Ordering, collections::BinaryHeap, sync::Arc};
+use std::sync::Arc;
use thiserror::Error;
pub use crate::encodable_block::dflash::DFlashState;
use crate::{
- backends::common::{Allocation, AllocationType, Backend, Completed, Context, Encoder},
+ backends::common::{
+ Allocation, AllocationType, Backend, Context, Encoder, Kernels,
+ kernel::{
+ WeaverFrontierScatterKernel, WeaverFrontierSelectKernel,
+ weaver::{
+ FRONTIER_LANE_COUNT, MAX_FRONTIER_SLOTS, METADATA_LANE_COUNT, NO_WINNER, TREE_LANE_COUNT,
+ TREE_LANE_DEPTH, TREE_LANE_LOGPROB, TREE_LANE_MASK, TREE_LANE_PARENT, TREE_LANE_TOKEN,
+ },
+ },
+ },
config::speculator::dflash::DFlashSpeculatorConfig,
data_type::DataType,
encodable_block::{
dflash::DFlashDraft,
embedding::{Embedding, EmbeddingError},
- weaver::{Weaver, WeaverBatchStepInput, WeaverEncodeError, WeaverNodeState, WeaverPrefix},
+ weaver::{Weaver, WeaverEncodeError, WeaverNodeState, WeaverPrefix, WeaverStepBatch},
},
engine::language_model::LanguageModel,
};
@@ -23,7 +32,7 @@ pub struct DFlashTreeOptions {
}
const MAX_TREE_BUDGET: usize = 4096;
-const MAX_FRONTIER_WIDTH: usize = 8;
+const MAX_TREE_FRONTIER_WIDTH: usize = 8;
const MAX_CHILDREN_PER_NODE: usize = 8;
impl Default for DFlashTreeOptions {
@@ -64,180 +73,14 @@ struct HostTreeNode {
parent: Option<usize>,
depth: usize,
logprob: f32,
- score: f32,
children: Vec<usize>,
}
-#[derive(Clone, Copy, Debug)]
-struct FrontierEntry {
- score: f32,
- parent: usize,
- token: u32,
- logprob: f32,
-}
-
-impl PartialEq for FrontierEntry {
- fn eq(
- &self,
- other: &Self,
- ) -> bool {
- self.score == other.score && self.parent == other.parent && self.token == other.token
- }
-}
-
-impl Eq for FrontierEntry {}
-
-impl PartialOrd for FrontierEntry {
- fn partial_cmp(
- &self,
- other: &Self,
- ) -> Option<Ordering> {
- Some(self.cmp(other))
- }
-}
-
-impl Ord for FrontierEntry {
- fn cmp(
- &self,
- other: &Self,
- ) -> Ordering {
- self.score
- .total_cmp(&other.score)
- .then_with(|| other.parent.cmp(&self.parent))
- .then_with(|| other.token.cmp(&self.token))
- }
-}
-
-fn build_host_tree<E>(
- mut nodes: Vec<HostTreeNode>,
- budget: usize,
- frontier_width: usize,
- mut expand: impl FnMut(&[usize], &mut [HostTreeNode], &mut BinaryHeap<FrontierEntry>) -> Result<(), E>,
-) -> Result<Vec<HostTreeNode>, E> {
- let mut frontier = BinaryHeap::new();
- expand(&[0], &mut nodes, &mut frontier)?;
- while nodes.len() < budget + 1 && !frontier.is_empty() {
- let remaining = budget + 1 - nodes.len();
- let mut expanded = Vec::with_capacity(frontier_width.min(remaining));
- for _ in 0..frontier_width.min(remaining) {
- let Some(entry) = frontier.pop() else {
- break;
- };
- let parent_index = entry.parent;
- let index = nodes.len();
- nodes.push(HostTreeNode {
- token: entry.token,
- parent: Some(parent_index),
- depth: nodes[parent_index].depth + 1,
- logprob: entry.logprob,
- score: entry.score,
- children: Vec::new(),
- });
- nodes[parent_index].children.push(index);
- expanded.push(index);
- }
- expand(&expanded, &mut nodes, &mut frontier)?;
- }
- Ok(nodes)
-}
-
-/// GPU-produced draft data pulled back to the host by the DFlash chain: one
-/// candidate `(token, score)` pool per lookahead row, the full logits (only
-/// materialized when Weaver is absent), and the draft-hidden / completion
-/// handles the caller keeps alive until Weaver's prefix build is done.
struct DFlashChainOutput<B: Backend> {
- candidate_pools: Vec<Vec<(u32, f32)>>,
- host_logits: Option<Vec<f32>>,
+ pool_ids: Allocation<B>,
+ pool_scores: Allocation<B>,
+ draft_logits: Allocation<B>,
draft_hidden: Allocation<B>,
- completed: Completed<B>,
-}
-
-/// Per-round driver for the best-first frontier loop: assembles one Weaver
-/// batch from the round's winners, runs it, and pushes the resulting child
-/// edges onto the frontier.
-struct WeaverExpansion<'a, B: Backend> {
- speculator: &'a DFlashSpeculator<B>,
- weaver: &'a Weaver<B>,
- prefix: &'a WeaverPrefix<B>,
- weaver_state: &'a mut WeaverNodeState<B>,
- target_embedding: &'a Embedding<B>,
- candidate_pools: &'a [Vec<(u32, f32)>],
- children_per_node: usize,
- lookahead_count: usize,
- max_depth: usize,
-}
-
-impl<B: Backend> WeaverExpansion<'_, B> {
- fn expand_round(
- &mut self,
- parent_indices: &[usize],
- nodes: &mut [HostTreeNode],
- frontier: &mut BinaryHeap<FrontierEntry>,
- ) -> Result<(), DFlashTreeError<B>> {
- let parent_indices = parent_indices
- .iter()
- .copied()
- .filter(|&index| nodes[index].depth < self.lookahead_count && nodes[index].depth < self.max_depth)
- .collect::<Vec<_>>();
- if parent_indices.is_empty() {
- return Ok(());
- }
- let candidate_ids = parent_indices
- .iter()
- .map(|&index| self.candidate_pools[nodes[index].depth].iter().map(|&(token, _)| token).collect::<Vec<_>>())
- .collect::<Vec<_>>();
- let candidate_scores = parent_indices
- .iter()
- .map(|&index| self.candidate_pools[nodes[index].depth].iter().map(|&(_, score)| score).collect::<Vec<_>>())
- .collect::<Vec<_>>();
- let ancestor_indices = parent_indices
- .iter()
- .map(|&parent_index| {
- let mut indices = Vec::new();
- let mut ancestor = nodes[parent_index].parent;
- while let Some(index) = ancestor {
- indices.push(index);
- ancestor = nodes[index].parent;
- }
- indices.reverse();
- indices
- })
- .collect::<Vec<_>>();
- let steps = {
- let inputs = parent_indices
- .iter()
- .enumerate()
- .map(|(batch_index, &parent_index)| WeaverBatchStepInput {
- node_index: parent_index,
- parent_token: nodes[parent_index].token,
- candidates: &candidate_ids[batch_index],
- candidate_scores: &candidate_scores[batch_index],
- ancestors: &ancestor_indices[batch_index],
- depth: nodes[parent_index].depth,
- })
- .collect::<Vec<_>>();
- self.weaver.step_batch(
- self.prefix,
- &inputs,
- self.weaver_state,
- self.children_per_node,
- self.target_embedding,
- &self.speculator.context,
- )?
- };
- for (parent_index, children) in parent_indices.into_iter().zip(steps) {
- for (token, logprob) in children {
- let score = nodes[parent_index].score + logprob;
- frontier.push(FrontierEntry {
- score,
- parent: parent_index,
- token,
- logprob,
- });
- }
- }
- Ok(())
- }
}
pub struct DFlashSpeculator<B: Backend> {
@@ -247,7 +90,6 @@ pub struct DFlashSpeculator<B: Backend> {
pub(crate) config: DFlashSpeculatorConfig,
}
-/// DFlash-TfM bound to target embedding weights.
#[derive(Clone, Copy)]
pub struct DFlashTfm<'a, B: Backend> {
speculator: &'a DFlashSpeculator<B>,
@@ -269,21 +111,17 @@ impl<B: Backend> DFlashSpeculator<B> {
}
}
- fn propose_tree_with_embedding(
+ fn propose_tree(
&self,
state: &mut DFlashState<B>,
bonus_token: u32,
target_embedding: &Embedding<B>,
options: DFlashTreeOptions,
) -> Result<TreeProposal<B>, DFlashTreeError<B>> {
- // `append_state` queues work on the caller's encoder. Its target
- // feature allocation must be complete before this host-side copyout;
- // the decoder seam therefore submits/waits that encoder between the
- // append and this method.
if options.budget == 0
|| options.budget > MAX_TREE_BUDGET
|| options.frontier_width == 0
- || options.frontier_width > MAX_FRONTIER_WIDTH
+ || options.frontier_width > MAX_TREE_FRONTIER_WIDTH
|| options.children_per_node == 0
|| options.children_per_node > MAX_CHILDREN_PER_NODE
{
@@ -304,83 +142,95 @@ impl<B: Backend> DFlashSpeculator<B> {
return Err(DFlashTreeError::InvalidOptions);
}
+ let mut encoder = Encoder::new(&*self.context).map_err(DFlashTreeError::Backend)?;
let DFlashChainOutput {
- candidate_pools,
- host_logits,
+ pool_ids,
+ pool_scores,
+ draft_logits,
draft_hidden,
- completed,
- } = self.encode_dflash_chain(state, bonus_token, target_embedding, block_size, target_model_dim, pool_size)?;
+ } = self.encode_dflash_chain(
+ &mut encoder,
+ state,
+ bonus_token,
+ target_embedding,
+ block_size,
+ target_model_dim,
+ pool_size,
+ )?;
+
+ if let Some(weaver) = self.weaver.as_ref() {
+ let max_depth = self.config.weaver_config.as_ref().expect("a Weaver implies a Weaver config").max_depth;
+ let lookahead_count = max_depth.min(block_size.saturating_sub(1));
+ // The frontier holds one slot per (tree slot, child) pair; the select
+ // kernel silently no-ops past its capacity.
+ if (options.budget + 1) * options.children_per_node > MAX_FRONTIER_SLOTS || lookahead_count == 0 {
+ return Err(DFlashTreeError::InvalidOptions);
+ }
+ let target_hidden = state.target_output_norm().ok_or(DFlashTreeError::MissingTargetHidden)?;
+ let prefix = weaver.build_prefix(target_hidden, &draft_hidden, 1, lookahead_count, &mut encoder)?;
+ drop(draft_hidden);
+ drop(draft_logits);
+ let mut weaver_state = weaver.create_node_state(options.budget + 1, &self.context)?;
+ let arguments = TreeEncodingArguments {
+ weaver,
+ prefix: &prefix,
+ target_embedding,
+ pool_ids: &pool_ids,
+ pool_scores: &pool_scores,
+ pool_rows: block_size - 1,
+ pool_size,
+ options,
+ max_depth,
+ lookahead_count,
+ bonus_token,
+ };
+ let tree = self.encode_tree(&mut encoder, &arguments, &mut weaver_state)?;
+ let completed = encoder.end_encoding().submit().wait_until_completed().map_err(DFlashTreeError::Backend)?;
+ let slots = tree.copyout::<u32>();
+ drop(tree);
+ drop(pool_ids);
+ drop(pool_scores);
+ drop(completed);
+ return Self::finish_tree(&self.context, tree_from_slots(&slots));
+ }
+
+ let completed = encoder.end_encoding().submit().wait_until_completed().map_err(DFlashTreeError::Backend)?;
+ let pool_id_values = pool_ids.copyout::<u32>();
+ let host_logits = draft_logits.copyout::<f32>();
+ drop(pool_ids);
+ drop(pool_scores);
+ drop(draft_logits);
+ drop(draft_hidden);
+ drop(completed);
let mut nodes = vec![HostTreeNode {
token: bonus_token,
parent: None,
depth: 0,
logprob: 0.0,
- score: 0.0,
children: Vec::new(),
}];
- let Some(weaver) = self.weaver.as_ref() else {
- let logits = host_logits.as_ref().unwrap();
- for depth in 0..options.budget.min(block_size.saturating_sub(1)) {
- let (token, _) = candidate_pools[depth][0];
- let row_start = depth * vocab_size;
- let logprob = log_softmax(&logits[row_start..row_start + vocab_size])[token as usize];
- let parent = nodes.len() - 1;
- let index = nodes.len();
- nodes.push(HostTreeNode {
- token,
- parent: Some(parent),
- depth: depth + 1,
- logprob,
- score: nodes[parent].score + logprob,
- children: Vec::new(),
- });
- nodes[parent].children.push(index);
- }
- let tree = Self::finish_tree(&self.context, nodes)?;
- drop(draft_hidden);
- drop(completed);
- return Ok(tree);
- };
-
- let max_depth = self.config.weaver_config.as_ref().unwrap().max_depth;
- let lookahead_count = max_depth.min(block_size.saturating_sub(1));
- let target_hidden = state.target_output_norm().ok_or(DFlashTreeError::MissingTargetHidden)?;
- let prefix = weaver.build_prefix(target_hidden, &draft_hidden, 1, lookahead_count, &self.context)?;
- drop(draft_hidden);
- drop(completed);
- let mut weaver_state = weaver.create_node_state(options.budget + 1, &self.context)?;
- // Expand the root once to seed the frontier. Thereafter the heap
- // contains candidate edges, not already-materialized tree nodes: each
- // iteration pops the globally best `frontier_width` edges, materializes
- // those nodes, and expands only those winners.
- let mut expansion = WeaverExpansion {
- speculator: self,
- weaver,
- prefix: &prefix,
- weaver_state: &mut weaver_state,
- target_embedding,
- candidate_pools: &candidate_pools,
- children_per_node: options.children_per_node,
- lookahead_count,
- max_depth,
- };
-
- let nodes = build_host_tree(nodes, options.budget, options.frontier_width, |parents, nodes, frontier| {
- expansion.expand_round(parents, nodes, frontier)
- })?;
-
- let tree = Self::finish_tree(&self.context, nodes)?;
- Ok(tree)
+ for depth in 0..options.budget.min(block_size.saturating_sub(1)) {
+ let token = pool_id_values[depth * pool_size];
+ let row_start = depth * vocab_size;
+ let logprob = log_softmax(&host_logits[row_start..row_start + vocab_size])[token as usize];
+ let parent = nodes.len() - 1;
+ let index = nodes.len();
+ nodes.push(HostTreeNode {
+ token,
+ parent: Some(parent),
+ depth: depth + 1,
+ logprob,
+ children: Vec::new(),
+ });
+ nodes[parent].children.push(index);
+ }
+ Self::finish_tree(&self.context, nodes)
}
- /// Runs the DFlash draft chain on the GPU and pulls its results back to the
- /// host: builds the noise block, encodes lookup -> draft transformer ->
- /// readout -> top-k in one command buffer, waits, copies out the candidate
- /// ids/scores (and full logits when Weaver is absent), and reshapes them
- /// into per-row candidate pools. Records every timing this stage owns.
fn encode_dflash_chain(
&self,
+ encoder: &mut Encoder<B>,
state: &mut DFlashState<B>,
bonus_token: u32,
target_embedding: &Embedding<B>,
@@ -393,49 +243,32 @@ impl<B: Backend> DFlashSpeculator<B> {
return Err(DFlashTreeError::InvalidOptions);
}
- let mut encoder = Encoder::new(&*self.context).map_err(DFlashTreeError::Backend)?;
let mut noise_ids =
encoder.allocate_constant(block_size * DataType::U32.size_in_bytes()).map_err(DFlashTreeError::Backend)?;
let mut noise = vec![self.config.draft_config.mask_token_id as u32; block_size];
noise[0] = bonus_token;
noise_ids.copyin(&noise);
- let token_embeddings = target_embedding.encode_lookup(&noise_ids, block_size, &mut encoder)?;
+ let token_embeddings = target_embedding.encode_lookup(&noise_ids, block_size, encoder)?;
let draft_hidden =
- self.model.encode_block(state, token_embeddings, &mut encoder).map_err(DFlashTreeError::Backend)?;
+ self.model.encode_block(state, token_embeddings, encoder).map_err(DFlashTreeError::Backend)?;
// The first block row is the bonus token; only the lookahead rows are ranked.
let row_bytes = target_embedding.model_dim() * DataType::BF16.size_in_bytes();
let mut lookahead_hidden =
encoder.allocate_scratch((block_size - 1) * row_bytes).map_err(DFlashTreeError::Backend)?;
encoder.encode_copy(&draft_hidden, row_bytes..block_size * row_bytes, &mut lookahead_hidden, ..);
let draft_logits =
- target_embedding.encode_readout(block_size - 1, &lookahead_hidden, DataType::F32, &mut encoder)?;
- let (candidate_ids_allocation, candidate_scores_allocation) = self
+ target_embedding.encode_readout(block_size - 1, &lookahead_hidden, DataType::F32, encoder)?;
+ let (pool_ids, pool_scores) = self
.model
- .encode_top_k(&draft_logits, block_size - 1, pool_size, &mut encoder)
+ .encode_top_k(&draft_logits, block_size - 1, pool_size, encoder)
.map_err(DFlashTreeError::Backend)?;
- let completed = encoder.end_encoding().submit().wait_until_completed().map_err(DFlashTreeError::Backend)?;
- let candidate_ids = candidate_ids_allocation.copyout::<u32>();
- let candidate_scores = candidate_scores_allocation.copyout::<f32>();
- drop(candidate_ids_allocation);
- drop(candidate_scores_allocation);
- let host_logits = self.weaver.is_none().then(|| draft_logits.copyout::<f32>());
- drop(draft_logits);
drop(noise_ids);
- let candidate_pools = (0..block_size - 1)
- .map(|row| {
- (0..pool_size)
- .map(|rank| {
- let index = row * pool_size + rank;
- (candidate_ids[index], candidate_scores[index])
- })
- .collect::<Vec<_>>()
- })
- .collect::<Vec<_>>();
+ drop(lookahead_hidden);
Ok(DFlashChainOutput {
- candidate_pools,
- host_logits,
+ pool_ids,
+ pool_scores,
+ draft_logits,
draft_hidden,
- completed,
})
}
@@ -465,10 +298,10 @@ impl<B: Backend> DFlashSpeculator<B> {
depths[dfs] = nodes[index].depth as u32;
draft_logprobs[dfs] = nodes[index].logprob;
}
- let tokens = global_allocation(context, &tokens).map_err(DFlashTreeError::Backend)?;
- let parents = global_allocation(context, &parents).map_err(DFlashTreeError::Backend)?;
- let depths = global_allocation(context, &depths).map_err(DFlashTreeError::Backend)?;
- let draft_logprobs = global_allocation(context, &draft_logprobs).map_err(DFlashTreeError::Backend)?;
+ let tokens = global_allocation::<B, _>(context, &tokens).map_err(DFlashTreeError::Backend)?;
+ let parents = global_allocation::<B, _>(context, &parents).map_err(DFlashTreeError::Backend)?;
+ let depths = global_allocation::<B, _>(context, &depths).map_err(DFlashTreeError::Backend)?;
+ let draft_logprobs = global_allocation::<B, _>(context, &draft_logprobs).map_err(DFlashTreeError::Backend)?;
Ok(TreeProposal {
token_ids: tokens,
parents,
@@ -477,6 +310,178 @@ impl<B: Backend> DFlashSpeculator<B> {
length: order.len(),
})
}
+
+ fn encode_tree(
+ &self,
+ encoder: &mut Encoder<B>,
+ params: &TreeEncodingArguments<'_, B>,
+ state: &mut WeaverNodeState<B>,
+ ) -> Result<Allocation<B>, DFlashTreeError<B>> {
+ let context = &*self.context;
+ let slots = params.options.budget + 1;
+ let fanout = params.options.children_per_node;
+ let capacity = slots * fanout;
+ let width = params.options.frontier_width;
+ let stride = params.max_depth;
+ let pool_size = params.pool_size;
+
+ let select =
+ <B::Kernels as Kernels>::WeaverFrontierSelectKernel::new(context).map_err(DFlashTreeError::Backend)?;
+ let scatter =
+ <B::Kernels as Kernels>::WeaverFrontierScatterKernel::new(context).map_err(DFlashTreeError::Backend)?;
+
+ let mut tree_values = vec![0u32; TREE_LANE_COUNT * slots];
+ for slot in 0..slots {
+ tree_values[TREE_LANE_PARENT * slots + slot] = NO_WINNER;
+ }
+ tree_values[TREE_LANE_TOKEN * slots] = params.bonus_token;
+ tree_values[TREE_LANE_MASK * slots] = 1;
+
+ let mut tree = encoder.allocate_constant_from_slice(&tree_values).map_err(DFlashTreeError::Backend)?;
+ let mut frontier = encoder
+ .allocate_constant_from_slice(&vec![0u32; FRONTIER_LANE_COUNT * capacity])
+ .map_err(DFlashTreeError::Backend)?;
+ let mut slot_ancestors =
+ encoder.allocate_constant_from_slice(&vec![0u32; slots * stride]).map_err(DFlashTreeError::Backend)?;
+
+ let mut round_token_id_values = vec![0u32; width];
+ round_token_id_values[0] = params.bonus_token;
+ let mut round_valid_values = vec![0u32; width];
+ round_valid_values[0] = 1;
+ let mut round_token_ids =
+ encoder.allocate_constant_from_slice(&round_token_id_values).map_err(DFlashTreeError::Backend)?;
+ let mut round_metadata = encoder
+ .allocate_constant_from_slice(&vec![0u32; METADATA_LANE_COUNT * width])
+ .map_err(DFlashTreeError::Backend)?;
+ let mut round_ancestors =
+ encoder.allocate_constant_from_slice(&vec![0u32; width * stride]).map_err(DFlashTreeError::Backend)?;
+ let mut round_valid =
+ encoder.allocate_constant_from_slice(&round_valid_values).map_err(DFlashTreeError::Backend)?;
+ let mut round_candidate_ids =
+ encoder.allocate_constant_from_slice(&vec![0u32; width * pool_size]).map_err(DFlashTreeError::Backend)?;
+ let mut round_candidate_scores =
+ encoder.allocate_constant_from_slice(&vec![0.0f32; width * pool_size]).map_err(DFlashTreeError::Backend)?;
+
+ let mut slot_start = 0;
+ while slot_start < slots {
+ let rows = if slot_start == 0 {
+ 1
+ } else {
+ width.min(slots - slot_start)
+ };
+ if slot_start > 0 {
+ select.encode(
+ &mut frontier,
+ &mut tree,
+ &mut slot_ancestors,
+ &mut round_token_ids,
+ &mut round_metadata,
+ &mut round_ancestors,
+ &mut round_valid,
+ params.pool_ids,
+ params.pool_scores,
+ &mut round_candidate_ids,
+ &mut round_candidate_scores,
+ capacity as u32,
+ slots as u32,
+ rows as u32,
+ slot_start as u32,
+ stride as u32,
+ params.max_depth as u32,
+ params.lookahead_count as u32,
+ params.pool_rows as u32,
+ pool_size as u32,
+ encoder,
+ );
+ }
+ let (candidate_ids, candidate_scores) = if slot_start == 0 {
+ (params.pool_ids, params.pool_scores)
+ } else {
+ (&round_candidate_ids, &round_candidate_scores)
+ };
+ let input = WeaverStepBatch {
+ row_count: rows,
+ candidate_count: pool_size,
+ ancestor_stride: stride,
+ parent_token_ids: &round_token_ids,
+ candidate_ids,
+ candidate_scores,
+ ancestor_indices: &round_ancestors,
+ node_metadata: &round_metadata,
+ };
+ let (child_ids, child_logprobs) = params.weaver.encode_step_batch(
+ params.prefix,
+ &input,
+ state,
+ fanout,
+ params.target_embedding,
+ encoder,
+ )?;
+ scatter.encode(
+ &tree,
+ &round_metadata,
+ &round_valid,
+ &child_ids,
+ &child_logprobs,
+ &mut frontier,
+ capacity as u32,
+ slots as u32,
+ rows as u32,
+ fanout as u32,
+ encoder,
+ );
+ drop(child_ids);
+ drop(child_logprobs);
+ slot_start += rows;
+ }
+ Ok(tree)
+ }
+}
+
+fn tree_from_slots(tree: &[u32]) -> Vec<HostTreeNode> {
+ assert!(tree.len().is_multiple_of(TREE_LANE_COUNT), "tree array must contain {TREE_LANE_COUNT} equal-length lanes");
+ let slots = tree.len() / TREE_LANE_COUNT;
+ let lane = |lane: usize, slot: usize| tree[lane * slots + slot];
+ let mut slot_to_node = vec![usize::MAX; slots];
+ let mut nodes: Vec<HostTreeNode> = Vec::with_capacity(slots);
+ for slot in 0..slots {
+ if lane(TREE_LANE_MASK, slot) == 0 {
+ continue;
+ }
+ let parent_slot = lane(TREE_LANE_PARENT, slot) as i32;
+ let parent = (parent_slot >= 0).then(|| {
+ let parent = slot_to_node[parent_slot as usize];
+ assert_ne!(parent, usize::MAX, "tree slot {slot} names padding slot {parent_slot} as its parent");
+ parent
+ });
+ let index = nodes.len();
+ slot_to_node[slot] = index;
+ if let Some(parent) = parent {
+ nodes[parent].children.push(index);
+ }
+ nodes.push(HostTreeNode {
+ token: lane(TREE_LANE_TOKEN, slot),
+ parent,
+ depth: lane(TREE_LANE_DEPTH, slot) as usize,
+ logprob: f32::from_bits(lane(TREE_LANE_LOGPROB, slot)),
+ children: Vec::new(),
+ });
+ }
+ nodes
+}
+
+struct TreeEncodingArguments<'a, B: Backend> {
+ weaver: &'a Weaver<B>,
+ prefix: &'a WeaverPrefix<B>,
+ target_embedding: &'a Embedding<B>,
+ pool_ids: &'a Allocation<B>,
+ pool_scores: &'a Allocation<B>,
+ pool_rows: usize,
+ pool_size: usize,
+ options: DFlashTreeOptions,
+ max_depth: usize,
+ lookahead_count: usize,
+ bonus_token: u32,
}
impl<'a, B: Backend> DFlashTfm<'a, B> {
@@ -522,7 +527,7 @@ impl<B: Backend> DFlashTfm<'_, B> {
bonus_token: u32,
options: DFlashTreeOptions,
) -> Result<TreeProposal<B>, DFlashTreeError<B>> {
- self.speculator.propose_tree_with_embedding(state, bonus_token, self.target_embedding, options)
+ self.speculator.propose_tree(state, bonus_token, self.target_embedding, options)
}
}
diff --git a/crates/backend-uzu/tests/unit/backends/common/kernel/attention/attention_last_query_test.rs b/crates/backend-uzu/tests/unit/backends/common/kernel/attention/attention_last_query_test.rs
index 0e36f1cf4..64c1228ed 100644
--- a/crates/backend-uzu/tests/unit/backends/common/kernel/attention/attention_last_query_test.rs
+++ b/crates/backend-uzu/tests/unit/backends/common/kernel/attention/attention_last_query_test.rs
@@ -32,6 +32,7 @@ struct Runner<B: Backend> {
rows: u32,
prefix_length: u32,
ancestor_stride: u32,
+ node_capacity: u32,
}
impl<B: Backend> Runner<B> {
@@ -74,6 +75,7 @@ impl<B: Backend> Runner<B> {
rows: rows as u32,
prefix_length: prefix_length as u32,
ancestor_stride: ancestor_stride as u32,
+ node_capacity: nodes as u32,
}
}
@@ -93,6 +95,7 @@ impl<B: Backend> Runner<B> {
self.rows,
self.prefix_length,
self.ancestor_stride,
+ self.node_capacity,
1.0 / (HEAD_DIM as f32).sqrt(),
&mut encoder,
);
diff --git a/crates/backend-uzu/tests/unit/backends/common/kernel/weaver/mod.rs b/crates/backend-uzu/tests/unit/backends/common/kernel/weaver/mod.rs
index 34c4d8777..52d3b29e3 100644
--- a/crates/backend-uzu/tests/unit/backends/common/kernel/weaver/mod.rs
+++ b/crates/backend-uzu/tests/unit/backends/common/kernel/weaver/mod.rs
@@ -1,2 +1,3 @@
+mod weaver_frontier_test;
mod weaver_node_cache_write_test;
mod weaver_top_children_test;
diff --git a/crates/backend-uzu/tests/unit/backends/common/kernel/weaver/weaver_frontier_test.rs b/crates/backend-uzu/tests/unit/backends/common/kernel/weaver/weaver_frontier_test.rs
new file mode 100644
index 000000000..38a255c7c
--- /dev/null
+++ b/crates/backend-uzu/tests/unit/backends/common/kernel/weaver/weaver_frontier_test.rs
@@ -0,0 +1,112 @@
+use proc_macros::uzu_test;
+use test_runner::for_each_non_cpu_backend;
+
+use crate::{
+ backends::{
+ common::{
+ Backend, Encoder, Kernels,
+ kernel::{
+ WeaverFrontierScatterKernel, WeaverFrontierSelectKernel,
+ weaver::{
+ FRONTIER_LANE_COUNT, METADATA_LANE_COUNT, METADATA_LANE_NODE_INDEX, TREE_LANE_COUNT, TREE_LANE_CUM,
+ TREE_LANE_DEPTH,
+ },
+ },
+ },
+ cpu::Cpu,
+ },
+ tests::helpers::{alloc_allocation_with_data, allocation_to_vec, create_context},
+};
+
+fn select<B: Backend>() -> Vec<u32> {
+ let context = create_context::<B>();
+ let mut frontier = vec![0; FRONTIER_LANE_COUNT * 8];
+ for (slot, (token, parent, depth, cum, key, active)) in [
+ (9, 1, 1, 0x3f00_0000, 100, 1),
+ (8, 0, 2, 0x3f00_0001, 100, 1),
+ (7, 0, 2, 0x3f00_0002, 100, 1),
+ (7, 0, 2, 0x3f00_0003, 100, 1),
+ (2, 1, 3, 0x3f00_0004, 90, 1),
+ (0, 0, 0, 0x3f00_0005, 200, 0),
+ (4, 1, 3, 0x3f00_0006, 80, 1),
+ (5, 1, 1, 0x3f00_0007, 70, 1),
+ ]
+ .into_iter()
+ .enumerate()
+ {
+ for (lane, value) in [token, parent, depth, cum, 0xbf80_0000, key, active].into_iter().enumerate() {
+ frontier[lane * 8 + slot] = value;
+ }
+ }
+ let mut frontier = alloc_allocation_with_data::<B, u32>(&context, &frontier);
+ let mut tree = alloc_allocation_with_data::<B, u32>(&context, &[55; TREE_LANE_COUNT * 7]);
+ let mut slot_ancestors = alloc_allocation_with_data::<B, u32>(&context, &(0u32..7 * 3).collect::<Vec<_>>());
+ let mut token = alloc_allocation_with_data::<B, u32>(&context, &[66; 4]);
+ let mut metadata = alloc_allocation_with_data::<B, u32>(&context, &[77; 3 * 4]);
+ let mut ancestors = alloc_allocation_with_data::<B, u32>(&context, &[88; 4 * 3]);
+ let mut valid = alloc_allocation_with_data::<B, u32>(&context, &[99; 4]);
+ let candidate_pool_ids = alloc_allocation_with_data::<B, u32>(&context, &(0..12).collect::<Vec<_>>());
+ let candidate_pool_scores =
+ alloc_allocation_with_data::<B, f32>(&context, &(0..12).map(|value| value as f32).collect::<Vec<_>>());
+ let mut candidate_ids = alloc_allocation_with_data::<B, u32>(&context, &[0; 4 * 3]);
+ let mut candidate_scores = alloc_allocation_with_data::<B, f32>(&context, &[0.0; 4 * 3]);
+ let kernel = <B::Kernels as Kernels>::WeaverFrontierSelectKernel::new(&context).unwrap();
+ let mut encoder = Encoder::new(context.as_ref()).unwrap();
+ kernel.encode(
+ &mut frontier,
+ &mut tree,
+ &mut slot_ancestors,
+ &mut token,
+ &mut metadata,
+ &mut ancestors,
+ &mut valid,
+ &candidate_pool_ids,
+ &candidate_pool_scores,
+ &mut candidate_ids,
+ &mut candidate_scores,
+ 8,
+ 7,
+ 4,
+ 2,
+ 3,
+ 4,
+ 3,
+ 4,
+ 3,
+ &mut encoder,
+ );
+ encoder.end_encoding().submit().wait_until_completed().unwrap();
+ [frontier, tree, slot_ancestors, token, metadata, ancestors, valid, candidate_ids]
+ .iter()
+ .flat_map(allocation_to_vec)
+ .chain(allocation_to_vec::<B, f32>(&candidate_scores).into_iter().map(f32::to_bits))
+ .collect()
+}
+
+fn scatter<B: Backend>() -> Vec<u32> {
+ let context = create_context::<B>();
+ let mut tree = vec![0; TREE_LANE_COUNT * 4];
+ tree[TREE_LANE_CUM * 4..(TREE_LANE_CUM + 1) * 4].copy_from_slice(&[0.5, -1.0, 2.0, 4.0].map(f32::to_bits));
+ tree[TREE_LANE_DEPTH * 4..(TREE_LANE_DEPTH + 1) * 4].copy_from_slice(&[0, 2, 4, 6]);
+ let tree = alloc_allocation_with_data::<B, u32>(&context, &tree);
+ let mut metadata = vec![0; METADATA_LANE_COUNT * 3];
+ metadata[METADATA_LANE_NODE_INDEX * 3..(METADATA_LANE_NODE_INDEX + 1) * 3].copy_from_slice(&[1, 3, 0]);
+ let metadata = alloc_allocation_with_data::<B, u32>(&context, &metadata);
+ let valid = alloc_allocation_with_data::<B, u32>(&context, &[1, 0, 1]);
+ let ids = alloc_allocation_with_data::<B, u32>(&context, &(10..19).collect::<Vec<_>>());
+ let scores = alloc_allocation_with_data::<B, f32>(&context, &[-0.1, -0.2, -0.3, 8.0, 8.0, 8.0, 0.1, 0.2, 0.3]);
+ let mut frontier = alloc_allocation_with_data::<B, u32>(&context, &[42; FRONTIER_LANE_COUNT * 16]);
+ let kernel = <B::Kernels as Kernels>::WeaverFrontierScatterKernel::new(&context).unwrap();
+ let mut encoder = Encoder::new(context.as_ref()).unwrap();
+ kernel.encode(&tree, &metadata, &valid, &ids, &scores, &mut frontier, 16, 4, 3, 3, &mut encoder);
+ encoder.end_encoding().submit().wait_until_completed().unwrap();
+ allocation_to_vec(&frontier)
+}
+
+#[uzu_test]
+fn weaver_frontier_kernels_match_cpu() {
+ for_each_non_cpu_backend!(|B| {
+ assert_eq!(select::<B>(), select::<Cpu>());
+ assert_eq!(scatter::<B>(), scatter::<Cpu>());
+ });
+}
diff --git a/crates/backend-uzu/tests/unit/backends/common/kernel/weaver/weaver_node_cache_write_test.rs b/crates/backend-uzu/tests/unit/backends/common/kernel/weaver/weaver_node_cache_write_test.rs
index eefb0f025..ba6d27ab2 100644
--- a/crates/backend-uzu/tests/unit/backends/common/kernel/weaver/weaver_node_cache_write_test.rs
+++ b/crates/backend-uzu/tests/unit/backends/common/kernel/weaver/weaver_node_cache_write_test.rs
@@ -58,6 +58,7 @@ impl<B: Backend> Runner<B> {
&mut self.node_qkv,
&self.node_indices,
MODEL_DIM as u32,
+ NODES as u32,
(ROWS * 2 * MODEL_DIM) as u32,
&mut encoder,
);