A high-performance inference engine for AI models
DFlashTfm improvements (#696)
uuuvnae053c440cbd
diff --git a/crates/backend-uzu/src/backends/common/gpu_types/argmax.rs b/crates/backend-uzu/src/backends/common/gpu_types/argmax.rsdeleted file mode 100644index cd5f06874..000000000--- a/crates/backend-uzu/src/backends/common/gpu_types/argmax.rs+++ /dev/null@@ -1,6 +0,0 @@-#[repr(C)]-#[derive(Debug, Clone, Copy)]-pub struct ArgmaxPair {- pub value: f32,- pub index: u32,-}diff --git a/crates/backend-uzu/src/backends/common/gpu_types/mod.rs b/crates/backend-uzu/src/backends/common/gpu_types/mod.rsindex d595972e0..261cf7294 100644--- a/crates/backend-uzu/src/backends/common/gpu_types/mod.rs+++ b/crates/backend-uzu/src/backends/common/gpu_types/mod.rs@@ -5,7 +5,6 @@pub mod activation_transform;pub mod activation_type;-pub mod argmax;pub mod attention;pub mod gemm;pub mod hadamard_order;@@ -19,7 +18,6 @@ pub mod weaver;pub use activation_transform::*;pub use activation_type::*;-pub use argmax::*;pub use attention::*;pub use hadamard_order::*;pub use kv_cache_update::*;diff --git a/crates/backend-uzu/src/backends/cpu/kernel/attention/ancestor_attention.rs b/crates/backend-uzu/src/backends/cpu/kernel/attention/ancestor_attention.rsindex 7d43495ab..586c9adda 100644--- a/crates/backend-uzu/src/backends/cpu/kernel/attention/ancestor_attention.rs+++ b/crates/backend-uzu/src/backends/cpu/kernel/attention/ancestor_attention.rs@@ -34,7 +34,6 @@ fn ancestor_attention<const HEAD_DIM: u32>(let qkv_width = QKV_COMPONENTS * model_dim;let prefix_length = prefix_length as usize;let node_capacity = node_capacity as usize;- let last_node = node_capacity.saturating_sub(1);let half_dim = head_dim / 2;let row_count = rows as usize;@@ -77,7 +76,8 @@ fn ancestor_attention<const HEAD_DIM: u32>(prefix_length * model_dim,);for offset in 0..ancestor_count {- let ancestor = (*ancestor_indices.add(row * ancestor_stride as usize + offset) as usize).min(last_node);+ let ancestor = *ancestor_indices.add(row * ancestor_stride as usize + offset) as usize;+ assert!(ancestor < node_capacity, "ancestor slot exceeds tree slot count");std::ptr::copy_nonoverlapping(node_kv.add(ancestor * model_dim),keys.as_mut_ptr().add((prefix_length + offset) * model_dim),@@ -124,7 +124,8 @@ fn ancestor_attention<const HEAD_DIM: u32>(false,);if node_capacity > 0 {- let node = (*node_indices.add(row) as usize).min(last_node);+ let node = *node_indices.add(row) as usize;+ assert!(node < node_capacity, "node slot exceeds tree slot count");std::ptr::copy_nonoverlapping(rotated_keys.as_ptr(), node_kv.add(node * model_dim), model_dim);std::ptr::copy_nonoverlapping(current_row.add(VALUE_COMPONENT * model_dim),diff --git a/crates/backend-uzu/src/backends/cpu/kernel/weaver/weaver_frontier_insert_children.rs b/crates/backend-uzu/src/backends/cpu/kernel/weaver/weaver_frontier_insert_children.rsindex 71f6647c8..d07d64105 100644--- a/crates/backend-uzu/src/backends/cpu/kernel/weaver/weaver_frontier_insert_children.rs+++ b/crates/backend-uzu/src/backends/cpu/kernel/weaver/weaver_frontier_insert_children.rs@@ -24,29 +24,29 @@ pub fn weaver_frontier_insert_children(frontier_capacity: u32,tree_slot_count: u32,node_count: u32,- children_per_node: u32,+ expand_width: u32,) {- if frontier_capacity == 0 || tree_slot_count == 0 || children_per_node == 0 {+ if frontier_capacity == 0 || tree_slot_count == 0 || expand_width == 0 {return;}- let (frontier_capacity, tree_slot_count, node_count, children_per_node) =- (frontier_capacity as usize, tree_slot_count as usize, node_count as usize, children_per_node as usize);+ 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 * children_per_node) };- let child_logprobs = unsafe { std::slice::from_raw_parts(child_logprobs, node_count * children_per_node) };+ 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 frontier = unsafe { std::slice::from_raw_parts_mut(frontier, FrontierIdx::COUNT * frontier_capacity) };- for index in 0..node_count * children_per_node {- let row = index / children_per_node;+ 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 * children_per_node + index % children_per_node;+ let slot = parent * expand_width + index % expand_width;if parent >= tree_slot_count || slot >= frontier_capacity {continue;}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.rsindex 04db364a3..0ea58c3c3 100644--- 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@@ -122,9 +122,9 @@ pub fn weaver_frontier_select(node_token_ids[node] = token;node_metadata[MetadataIdx::Depth as usize * node_count + node] = depth.min(max_depth - 1);- node_metadata[MetadataIdx::AncestorCount as usize * node_count + node] = depth.min(ancestor_stride as u32);+ node_metadata[MetadataIdx::AncestorCount as usize * node_count + node] = depth;node_metadata[MetadataIdx::TreeSlot as usize * node_count + node] = tree_slot as u32;- node_valid[node] = u32::from(real && depth < lookahead_count && depth < max_depth);+ node_valid[node] = u32::from(real && depth < lookahead_count);// Every node expands the candidate pool for its own depth.let candidate_depth = (depth as usize).min(candidate_depth_count - 1);diff --git a/crates/backend-uzu/src/backends/cpu/kernel/weaver/weaver_top_children.rs b/crates/backend-uzu/src/backends/cpu/kernel/weaver/weaver_top_children.rsindex d03f8d74a..f4a5bd65c 100644--- a/crates/backend-uzu/src/backends/cpu/kernel/weaver/weaver_top_children.rs+++ b/crates/backend-uzu/src/backends/cpu/kernel/weaver/weaver_top_children.rs@@ -17,13 +17,13 @@ pub fn weaver_top_children(output_model_logprobs: *mut f32,rows: u32,candidates: u32,- children_per_node: u32,+ expand_width: u32,vocab_size: u32,) {let rows = rows as usize;let candidates = candidates as usize;- let children_per_node = children_per_node as usize;- if candidates == 0 || candidates > CANDIDATES_MAX || children_per_node == 0 || children_per_node > candidates {+ let expand_width = expand_width as usize;+ if candidates == 0 || candidates > CANDIDATES_MAX || expand_width == 0 || expand_width > candidates {return;}for row in 0..rows {@@ -43,10 +43,10 @@ pub fn weaver_top_children(indices.sort_by(|&left, &right| {perturbed[right].total_cmp(&perturbed[left]).then_with(|| token(left).cmp(&token(right)))});- for (rank, index) in indices.into_iter().take(children_per_node).enumerate() {+ for (rank, index) in indices.into_iter().take(expand_width).enumerate() {unsafe {- *output_token_ids.add(row * children_per_node + rank) = token(index);- *output_model_logprobs.add(row * children_per_node + rank) = logits[index] - log_sum;+ *output_token_ids.add(row * expand_width + rank) = token(index);+ *output_model_logprobs.add(row * expand_width + rank) = logits[index] - log_sum;}}}diff --git a/crates/backend-uzu/src/backends/metal/kernel/attention/ancestor_attention.metal b/crates/backend-uzu/src/backends/metal/kernel/attention/ancestor_attention.metalindex c4f6f655e..a7079dac6 100644--- a/crates/backend-uzu/src/backends/metal/kernel/attention/ancestor_attention.metal+++ b/crates/backend-uzu/src/backends/metal/kernel/attention/ancestor_attention.metal@@ -138,16 +138,15 @@ PUBLIC KERNEL(AncestorAttention)(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, head_offset, node_value_offset, values, max_score, sum, [&](int step) {- return node_vectors + min(row_ancestors[offset + step], last_node) * model_vectors;+ return node_vectors + row_ancestors[offset + step] * model_vectors;});}for (; offset < ancestor_count; ++offset) {attend_qkv<1>(query, head_offset, node_value_offset, values, max_score, sum, [&](int) {- return node_vectors + min(row_ancestors[offset], last_node) * model_vectors;+ return node_vectors + row_ancestors[offset] * model_vectors;});}@@ -161,7 +160,7 @@ PUBLIC KERNEL(AncestorAttention)(max_score = own_max;if (node_capacity > 0u) {- const uint node = min(node_indices[row], last_node);+ const uint node = node_indices[row];node_vectors[node * model_vectors + head_offset] = bfloat4(rotated_key);node_vectors[node_value_offset + node * model_vectors] = current_row[current_value_offset];diff --git a/crates/backend-uzu/src/backends/metal/kernel/generated/argmax.h b/crates/backend-uzu/src/backends/metal/kernel/generated/argmax.hdeleted file mode 100644index a67743173..000000000--- a/crates/backend-uzu/src/backends/metal/kernel/generated/argmax.h+++ /dev/null@@ -1,12 +0,0 @@-// Auto-generated from gpu_types/argmax - do not edit manually-#pragma once--#include <metal_stdlib>-using namespace metal;--namespace uzu::argmax {-typedef struct {- float value;- uint32_t index;-} ArgmaxPair;-} // namespace uzu::argmaxdiff --git a/crates/backend-uzu/src/backends/metal/kernel/matmul/gemv/kernel.rs b/crates/backend-uzu/src/backends/metal/kernel/matmul/gemv/kernel.rsindex 95eb934e6..2c0a0f998 100644--- a/crates/backend-uzu/src/backends/metal/kernel/matmul/gemv/kernel.rs+++ b/crates/backend-uzu/src/backends/metal/kernel/matmul/gemv/kernel.rs@@ -71,14 +71,13 @@ impl GemvSpecialization {{return None;}- if is_quant {- if shape.n < DEFAULT_RESULTS_PER_SIMDGROUP || shape.m >= 5 {- return None;- }- } else {+ if shape.n < DEFAULT_RESULTS_PER_SIMDGROUP || shape.m > max_gemv_batch_threshold() {+ return None;+ }+ if !is_quant {let mixed_precision = weights_data_type == DataType::F32&& (input_data_type != DataType::F32 || output_data_type != DataType::F32);- if mixed_precision || shape.n < DEFAULT_RESULTS_PER_SIMDGROUP || shape.m > max_gemv_batch_threshold() {+ if mixed_precision {return None;}}diff --git a/crates/backend-uzu/src/backends/metal/kernel/sampling/unified_sampling.metal b/crates/backend-uzu/src/backends/metal/kernel/sampling/unified_sampling.metalindex 70f9deb24..ed6cfb775 100644--- a/crates/backend-uzu/src/backends/metal/kernel/sampling/unified_sampling.metal+++ b/crates/backend-uzu/src/backends/metal/kernel/sampling/unified_sampling.metal@@ -5,10 +5,6 @@#include "../rng.h"-#include "../generated/argmax.h"--using namespace uzu::argmax;-#define THREADGROUP_SIZE 1024#define THREADGROUP_SIZE_IN_SIMDS (THREADGROUP_SIZE / METAL_SIMD_SIZE)#define BITS_IN_U32 32diff --git a/crates/backend-uzu/src/backends/metal/kernel/weaver/weaver_frontier_insert_children.metal b/crates/backend-uzu/src/backends/metal/kernel/weaver/weaver_frontier_insert_children.metalindex d79cf432e..1159407db 100644--- a/crates/backend-uzu/src/backends/metal/kernel/weaver/weaver_frontier_insert_children.metal+++ b/crates/backend-uzu/src/backends/metal/kernel/weaver/weaver_frontier_insert_children.metal@@ -15,14 +15,14 @@ PUBLIC KERNEL(WeaverFrontierInsertChildren)(constant uint& frontier_capacity,constant uint& tree_slot_count,constant uint& node_count,- constant uint& children_per_node,- const uint position AXIS(node_count* children_per_node, 64)+ constant uint& expand_width,+ const uint position AXIS(node_count* expand_width, 64)) {- if (frontier_capacity == 0 || tree_slot_count == 0 || children_per_node == 0) {+ if (frontier_capacity == 0 || tree_slot_count == 0 || expand_width == 0) {return;}- const uint row = position / children_per_node, child = position % children_per_node;+ const uint row = position / expand_width, child = position % expand_width;if (node_valid[row] == 0u) {return;}@@ -31,16 +31,16 @@ PUBLIC KERNEL(WeaverFrontierInsertChildren)(if (parent >= tree_slot_count) {return;}- const uint slot = parent * children_per_node + child;+ const uint slot = parent * expand_width + child;if (slot >= frontier_capacity) {return;}- const float logprob = child_logprobs[row * children_per_node + child];+ 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 * children_per_node + child];+ 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;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.metalindex 7f57fbfee..3f4044580 100644--- 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@@ -128,9 +128,9 @@ PUBLIC KERNEL(WeaverFrontierSelect)(node_token_ids[node] = token;node_metadata[uint(MetadataIdx::Depth) * node_count + node] = min(depth, max_depth - 1u);- node_metadata[uint(MetadataIdx::AncestorCount) * node_count + node] = min(depth, ancestor_stride);+ node_metadata[uint(MetadataIdx::AncestorCount) * node_count + node] = depth;node_metadata[uint(MetadataIdx::TreeSlot) * node_count + node] = tree_slot;- node_valid[node] = real && depth < lookahead_count && depth < max_depth ? 1u : 0u;+ node_valid[node] = real && depth < lookahead_count ? 1u : 0u;node_candidate_depth[node] = min(depth, candidate_depth_count - 1u);}diff --git a/crates/backend-uzu/src/backends/metal/kernel/weaver/weaver_top_children.metal b/crates/backend-uzu/src/backends/metal/kernel/weaver/weaver_top_children.metalindex 7613b0fe0..c4757d6ac 100644--- a/crates/backend-uzu/src/backends/metal/kernel/weaver/weaver_top_children.metal+++ b/crates/backend-uzu/src/backends/metal/kernel/weaver/weaver_top_children.metal@@ -41,7 +41,7 @@ PUBLIC KERNEL(WeaverTopChildren)(device float* output_model_logprobs,constant uint& rows,constant uint& candidates,- constant uint& children_per_node,+ constant uint& expand_width,constant uint& vocab_size,threadgroup float reduce_float[TOP_CHILDREN_SIMDGROUPS],threadgroup uint reduce_score[TOP_CHILDREN_SIMDGROUPS],@@ -55,7 +55,7 @@ PUBLIC KERNEL(WeaverTopChildren)(const uint row GROUPS(rows),const uint lid THREADS(TOP_CHILDREN_THREADS)) {- if (candidates == 0 || candidates > CANDIDATES_MAX || children_per_node == 0 || children_per_node > candidates) {+ if (candidates == 0 || candidates > CANDIDATES_MAX || expand_width == 0 || expand_width > candidates) {return;}@@ -112,7 +112,7 @@ PUBLIC KERNEL(WeaverTopChildren)(}threadgroup_barrier(mem_flags::mem_threadgroup);- for (uint child = 0; child < children_per_node; ++child) {+ for (uint child = 0; child < expand_width; ++child) {uint local_score = 0u;uint local_token = 0xffffffffu;uint local_index = 0xffffffffu;@@ -159,8 +159,8 @@ PUBLIC KERNEL(WeaverTopChildren)(if (lid == 0) {const float winner_logit = candidate_logits[base + winner_index] + float(residual_logits[base + winner_index]);- output_token_ids[row * children_per_node + child] = winner_token;- output_model_logprobs[row * children_per_node + child] = winner_logit - log_sum;+ output_token_ids[row * expand_width + child] = winner_token;+ output_model_logprobs[row * expand_width + child] = winner_logit - log_sum;}first_active = first_active && first_index != winner_index;second_active = second_active && second_index != winner_index;diff --git a/crates/backend-uzu/src/config/speculator/dflash.rs b/crates/backend-uzu/src/config/speculator/dflash.rsindex 626769382..01d108c0c 100644--- a/crates/backend-uzu/src/config/speculator/dflash.rs+++ b/crates/backend-uzu/src/config/speculator/dflash.rs@@ -5,5 +5,5 @@ use crate::config::{dflash::DFlashDraftConfig, weaver::WeaverConfig};#[uzu_config(super::SpeculatorConfig)]pub struct DFlashSpeculatorConfig {pub draft_config: DFlashDraftConfig,- pub weaver_config: WeaverConfig,+ pub weaver_config: Option<WeaverConfig>,}diff --git a/crates/backend-uzu/src/encodable_block/dflash.rs b/crates/backend-uzu/src/encodable_block/dflash.rsindex 436bdf028..475a0c077 100644--- a/crates/backend-uzu/src/encodable_block/dflash.rs+++ b/crates/backend-uzu/src/encodable_block/dflash.rs@@ -3,12 +3,7 @@ use std::any::Any;use thiserror::Error;use crate::{- array::size_for_shape,- backends::common::{- Allocation, Backend, Encoder, Kernels,- gpu_types::trie::TrieNode,- kernel::radix_top_k_small::{MAX_K, RadixTopKSmall},- },+ backends::common::{Allocation, Backend, Encoder, gpu_types::trie::TrieNode},config::{dflash::DFlashDraftConfig, rope::AnyRoPEConfig, token_mixer::AnyTokenMixerConfig},data_type::DataType,encodable_block::{@@ -48,7 +43,6 @@ pub struct DFlash<B: Backend> {layer_kv_dim: usize,layers: Box<[TransformerLayer<B>]>,output_norm: Normalization<B>,- top_k: <B::Kernels as Kernels>::RadixTopKSmall,rope_config: AnyRoPEConfig,model_dim: usize,max_context_length: usize,@@ -60,14 +54,7 @@ pub struct DFlash<B: Backend> {pub struct DFlashOutput<B: Backend> {pub draft_hidden: Allocation<B>,- pub candidates: TopKCandidates<B>,-}--pub struct TopKCandidates<B: Backend> {- pub ids: Allocation<B>,pub logits: Allocation<B>,- pub rows: usize,- pub candidates_per_row: usize,}#[derive(Debug, Error)]@@ -103,7 +90,6 @@ impl<B: Backend> DFlash<B> {parameter_tree: &ParameterTree<B>,data_type: DataType,) -> Result<Self, DFlashNewError<B>> {- let vocab_size = config.vocab_size as u32;let mask_token_id = config.mask_token_id as u32;assert!(config.block_size <= ATTENTION_SUFFIX_CAPACITY, "DFlash block_size exceeds attention suffix capacity");let target_feature_projection = <dyn Linear<B>>::new(@@ -165,8 +151,6 @@ impl<B: Backend> DFlash<B> {¶meter_tree.subtree("output_norm"),context,)?;- let top_k =- <B::Kernels as Kernels>::RadixTopKSmall::new(context, vocab_size).map_err(DFlashNewError::Backend)?;Ok(Self {target_feature_projection,@@ -175,7 +159,6 @@ impl<B: Backend> DFlash<B> {layer_kv_dim,layers,output_norm,- top_k,rope_config: config.rope_config.clone(),model_dim: config.model_dim,max_context_length: *config.rope_config.max_sequence_length(),@@ -186,6 +169,10 @@ impl<B: Backend> DFlash<B> {})}+ pub fn block_size(&self) -> usize {+ self.block_size+ }+pub fn empty_state(&self,context_capacity: usize,@@ -288,32 +275,32 @@ impl<B: Backend> DFlash<B> {state: &mut DFlashState<B>,target_output_token: u32,target_embedding: &Embedding<B>,- candidate_count: usize,+ batch_size: usize,encoder: &mut Encoder<B>,) -> Result<DFlashOutput<B>, DFlashEncodeError<B>> {encoder.push_debug_group("dflash draft");- let batch_dim = self.block_size;+ assert!(batch_size >= 2 && batch_size <= self.block_size, "batch size exceeds DFlash block size");assert!(- state.context_length + batch_dim <= self.max_context_length,+ state.context_length + batch_size <= self.max_context_length,"DFlash block positions exceed configured RoPE capacity");- let mut tokens = vec![self.mask_token_id; batch_dim];+ let mut tokens = vec![self.mask_token_id; batch_size];tokens[0] = target_output_token;let token_ids = encoder.allocate_constant_from_slice(&tokens).map_err(DFlashEncodeError::Backend)?;- let token_embeddings = target_embedding.encode_lookup(&token_ids, batch_dim, encoder)?;+ let token_embeddings = target_embedding.encode_lookup(&token_ids, batch_size, encoder)?;- let nodes = (0..batch_dim)+ let nodes = (0..batch_size).map(|index| TrieNode {trie_start: index as u32,- trie_end: index as u32 + 1,+ trie_end: (batch_size - 1) as u32,height: index as u32,}).collect::<Box<[_]>>();let batch_topology = BatchTopology::new(&nodes, true);- let token_positions = (state.context_length..state.context_length + batch_dim).collect::<Box<[_]>>();+ let token_positions = (state.context_length..state.context_length + batch_size).collect::<Box<[_]>>();let rope = PrecalculatedRoPE::precalculate(&self.rope_config, &token_positions, encoder).map_err(DFlashEncodeError::Backend)?;@@ -321,7 +308,7 @@ impl<B: Backend> DFlash<B> {let mut residual = encoder.allocate_scratch(hidden.size()).map_err(DFlashEncodeError::Backend)?;for (layer, mixer_state) in self.layers.iter().zip(state.layer_states.iter_mut()) {mixer_state- .prepare(state.context_length, batch_dim, encoder.context())+ .prepare(state.context_length, batch_size, encoder.context()).map_err(DFlashEncodeError::Backend)?;hidden = layer.encode(@@ -337,39 +324,20 @@ impl<B: Backend> DFlash<B> {}let draft_hidden = self.output_norm- .encode(&hidden, 0, batch_dim, Some(&mut residual), encoder)+ .encode(&hidden, 0, batch_size, Some(&mut residual), encoder).map_err(DFlashEncodeError::Backend)?;- // The first block row is the target's output token; only the lookahead rows are ranked.- let lookahead_rows = batch_dim - 1;let row_bytes = target_embedding.model_dim() * DataType::BF16.size_in_bytes();let mut lookahead_hidden =- encoder.allocate_scratch(lookahead_rows * row_bytes).map_err(DFlashEncodeError::Backend)?;- encoder.encode_copy(&draft_hidden, row_bytes..batch_dim * row_bytes, &mut lookahead_hidden, ..);- let logits = target_embedding.encode_readout(lookahead_rows, &lookahead_hidden, DataType::F32, encoder)?;-- assert!(candidate_count > 0 && candidate_count <= MAX_K as usize);- let mut ids = encoder- .allocate_scratch(size_for_shape(&[lookahead_rows, candidate_count], DataType::U32))- .map_err(DFlashEncodeError::Backend)?;- let mut candidate_logits = encoder- .allocate_scratch(size_for_shape(&[lookahead_rows, candidate_count], DataType::F32))- .map_err(DFlashEncodeError::Backend)?;- self.top_k- .encode(&logits, &mut ids, &mut candidate_logits, lookahead_rows as u32, candidate_count as u32, encoder)- .map_err(DFlashEncodeError::Backend)?;- let candidates = TopKCandidates {- ids,- logits: candidate_logits,- rows: lookahead_rows,- candidates_per_row: candidate_count,- };+ encoder.allocate_scratch((batch_size - 1) * row_bytes).map_err(DFlashEncodeError::Backend)?;+ encoder.encode_copy(&draft_hidden, row_bytes..batch_size * row_bytes, &mut lookahead_hidden, ..);+ let logits = target_embedding.encode_readout(batch_size - 1, &lookahead_hidden, DataType::F32, encoder)?;encoder.pop_debug_group();Ok(DFlashOutput {draft_hidden,- candidates,+ logits,})}}diff --git a/crates/backend-uzu/src/encodable_block/weaver.rs b/crates/backend-uzu/src/encodable_block/weaver.rsindex 93a6de012..76f519b6b 100644--- a/crates/backend-uzu/src/encodable_block/weaver.rs+++ b/crates/backend-uzu/src/encodable_block/weaver.rs@@ -5,17 +5,17 @@ use crate::{backends::common::{Allocation, Backend, Encoder, Kernels,gpu_types::weaver::{- CANDIDATES_MAX, FRONTIER_MAX_SLOTS, FRONTIER_NO_WINNER, FrontierIdx, MetadataIdx, TreeIdx,+ CANDIDATES_MAX, FRONTIER_MAX_SLOTS, FRONTIER_MAX_WIDTH, FRONTIER_NO_WINNER, FrontierIdx, MetadataIdx,+ TreeIdx,},kernel::{AncestorAttentionKernel, WeaverFrontierInsertChildrenKernel, WeaverFrontierSelectKernel,- WeaverTopChildrenKernel,+ WeaverTopChildrenKernel, radix_top_k_small::RadixTopKSmall,},},config::{rope::AnyRoPEConfig, weaver::WeaverConfig},data_type::DataType,encodable_block::{- dflash::TopKCandidates,embedding::{Embedding, EmbeddingError},linear::{Linear, LinearBlockError},mixer::attention::{AttentionStateType, core::AttentionCoreEncodeArguments, rope::PrecalculatedRoPE},@@ -29,10 +29,11 @@ use crate::{pub(crate) const DATA_TYPE: DataType = DataType::BF16;pub(crate) const ROPE_DATA_TYPE: DataType = DataType::F32;-pub struct TreeShape {+pub struct WeaverTreeShape {pub budget: usize,- pub frontier_width: usize,- pub children_per_node: usize,+ pub depth: usize,+ pub expand_per_round: usize,+ pub expand_width: usize,}pub struct EncodedWeaverTree<B: Backend> {@@ -87,12 +88,14 @@ pub struct Weaver<B: Backend> {readout_norm: Normalization<B>,readout_query_projection: Box<dyn Linear<B>>,rope_config: AnyRoPEConfig,+ top_k: <B::Kernels as Kernels>::RadixTopKSmall,top_children: <B::Kernels as Kernels>::WeaverTopChildrenKernel,frontier_select: <B::Kernels as Kernels>::WeaverFrontierSelectKernel,frontier_insert_children: <B::Kernels as Kernels>::WeaverFrontierInsertChildrenKernel,model_dim: usize,target_model_dim: usize,max_depth: usize,+ candidate_pool_size: usize,}#[derive(Debug, Error)]@@ -137,6 +140,7 @@ impl<B: Backend> Weaver<B> {pub fn new(context: &B::Context,config: &WeaverConfig,+ vocab_size: u32,parameter_tree: &ParameterTree<B>,) -> Result<Self, WeaverNewError<B>> {if config.num_layers == 0 {@@ -219,6 +223,8 @@ impl<B: Backend> Weaver<B> {DATA_TYPE,¶meter_tree.subtree("query_projection"),)?;+ let top_k =+ <B::Kernels as Kernels>::RadixTopKSmall::new(context, vocab_size).map_err(WeaverNewError::Backend)?;let top_children =<B::Kernels as Kernels>::WeaverTopChildrenKernel::new(context).map_err(WeaverNewError::Backend)?;let frontier_select =@@ -234,68 +240,100 @@ impl<B: Backend> Weaver<B> {readout_norm,readout_query_projection,rope_config: config.rope_config.clone(),+ top_k,top_children,frontier_select,frontier_insert_children,model_dim: config.model_dim,target_model_dim: config.target_model_dim,max_depth: config.max_depth,+ candidate_pool_size: config.candidate_pool_size,})}+ pub fn max_depth(&self) -> usize {+ self.max_depth+ }+pub fn encode_tree(&self,target_hidden: &Allocation<B>,draft_hidden: &Allocation<B>,target_embedding: &Embedding<B>,- candidates: &TopKCandidates<B>,+ logits: &Allocation<B>,depth_seeds: &[u64],root_token_id: u32,- shape: TreeShape,+ shape: WeaverTreeShape,encoder: &mut Encoder<B>,) -> Result<EncodedWeaverTree<B>, WeaverEncodeError<B>> {encoder.push_debug_group("weaver tree");- let tree_slot_count = shape.budget + 1;- let frontier_capacity = tree_slot_count * shape.children_per_node;- let lookahead_count = self.max_depth.min(candidates.rows);+ let tree_slot_count = shape.budget;+ let frontier_capacity = tree_slot_count * shape.expand_width;let ancestor_stride = self.max_depth;if shape.budget == 0- || shape.frontier_width == 0- || shape.children_per_node == 0- || shape.children_per_node > candidates.candidates_per_row+ || shape.depth < 2+ || shape.depth > self.max_depth + 1+ || shape.expand_per_round == 0+ || shape.expand_per_round > FRONTIER_MAX_WIDTH+ || shape.expand_width == 0+ || shape.expand_width > self.candidate_pool_size|| frontier_capacity > FRONTIER_MAX_SLOTS- || lookahead_count == 0|| depth_seeds.len() != self.max_depth{return Err(WeaverEncodeError::InvalidTreeInput);}+ // `depth` counts the root: nodes expand up to `depth - 1` edges from it.+ let lookahead_count = shape.depth - 1;++ // Rank the draft logits: the top `candidate_pool_size` tokens per+ // lookahead row form the candidate pool node expansions draw from.+ let vocab_size = target_embedding.vocab_size();+ assert!(+ logits.size() >= lookahead_count * vocab_size * DataType::F32.size_in_bytes(),+ "draft logits do not cover the lookahead rows"+ );+ let mut candidate_ids = encoder+ .allocate_scratch(size_for_shape(&[lookahead_count, self.candidate_pool_size], DataType::U32))+ .map_err(WeaverEncodeError::Backend)?;+ let mut candidate_logits = encoder+ .allocate_scratch(size_for_shape(&[lookahead_count, self.candidate_pool_size], DataType::F32))+ .map_err(WeaverEncodeError::Backend)?;+ self.top_k+ .encode(+ logits,+ &mut candidate_ids,+ &mut candidate_logits,+ lookahead_count as u32,+ self.candidate_pool_size as u32,+ encoder,+ )+ .map_err(WeaverEncodeError::Backend)?;let rope_positions = (0..=self.max_depth).collect::<Box<[_]>>();let rope = PrecalculatedRoPE::precalculate(&self.rope_config, &rope_positions, encoder).map_err(WeaverEncodeError::Backend)?;- // Prefix pass: run the target token and the draft lookahead rows through- // every layer, collecting per-layer KV caches.- let prefix_length = lookahead_count + 1;+ // Prefix pass: run the target token and one draft row per non-root+ // chain node through every layer, collecting per-layer KV caches.let hidden_row_bytes = self.target_model_dim * DATA_TYPE.size_in_bytes();let mut prefix_hidden = encoder- .allocate_scratch(size_for_shape(&[prefix_length, self.target_model_dim], DATA_TYPE))+ .allocate_scratch(size_for_shape(&[shape.depth, self.target_model_dim], DATA_TYPE)).map_err(WeaverEncodeError::Backend)?;encoder.encode_copy(target_hidden, 0..hidden_row_bytes, &mut prefix_hidden, 0..hidden_row_bytes);encoder.encode_copy(draft_hidden,- hidden_row_bytes..prefix_length * hidden_row_bytes,+ hidden_row_bytes..shape.depth * hidden_row_bytes,&mut prefix_hidden,- hidden_row_bytes..prefix_length * hidden_row_bytes,+ hidden_row_bytes..shape.depth * hidden_row_bytes,);let normalized_prefix = self.hidden_state_norm- .encode(&prefix_hidden, 0, prefix_length, None, encoder)+ .encode(&prefix_hidden, 0, shape.depth, None, encoder).map_err(WeaverEncodeError::Backend)?;let mut residual_input = self.hidden_state_projection- .encode(normalized_prefix, prefix_length, encoder)+ .encode(normalized_prefix, shape.depth, encoder).map_err(WeaverEncodeError::Backend)?;let (last_layer, preceding_layers) = self.layers.split_last().expect("Weaver must have at least one layer");let mut residual_state = encoder.allocate_scratch(residual_input.size()).map_err(WeaverEncodeError::Backend)?;@@ -305,12 +343,12 @@ impl<B: Backend> Weaver<B> {queries,kv_cache,} = layer- .encode_prefix_attention(&residual_input, &mut residual_state, &rope, prefix_length, encoder)+ .encode_prefix_attention(&residual_input, &mut residual_state, &rope, shape.depth, encoder).map_err(WeaverEncodeError::Backend)?;let state_type = AttentionStateType::Full {length: 0,};- let kv_plane_bytes = size_for_shape(&[prefix_length, self.model_dim], DATA_TYPE);+ let kv_plane_bytes = size_for_shape(&[shape.depth, self.model_dim], DATA_TYPE);let attention_output = layer.prefix_attention.encode(@@ -318,7 +356,7 @@ impl<B: Backend> Weaver<B> {queries: &queries,keys: &kv_cache,values: (&kv_cache, kv_plane_bytes),- suffix_length: prefix_length,+ suffix_length: shape.depth,trie: None,sinks: None,state_type: &state_type,@@ -327,13 +365,13 @@ impl<B: Backend> Weaver<B> {).map_err(WeaverEncodeError::Backend)?;residual_input = layer- .encode_post_attention(attention_output, &mut residual_state, prefix_length, encoder)+ .encode_post_attention(attention_output, &mut residual_state, shape.depth, encoder).map_err(WeaverEncodeError::Backend)?;prefix_kv_layers.push(kv_cache);}prefix_kv_layers.push(last_layer- .encode_prefix_attention(&residual_input, &mut residual_state, &rope, prefix_length, encoder)+ .encode_prefix_attention(&residual_input, &mut residual_state, &rope, shape.depth, encoder).map_err(WeaverEncodeError::Backend)?.kv_cache,);@@ -360,25 +398,25 @@ impl<B: Backend> Weaver<B> {.allocate_constant_from_slice(&vec![0u32; tree_slot_count * ancestor_stride]).map_err(WeaverEncodeError::Backend)?;- let mut initial_node_token_ids = vec![0u32; shape.frontier_width];+ let mut initial_node_token_ids = vec![0u32; shape.expand_per_round];initial_node_token_ids[0] = root_token_id;- let mut initial_node_valid = vec![0u32; shape.frontier_width];+ let mut initial_node_valid = vec![0u32; shape.expand_per_round];initial_node_valid[0] = 1;let mut node_token_ids =encoder.allocate_constant_from_slice(&initial_node_token_ids).map_err(WeaverEncodeError::Backend)?;let mut node_metadata = encoder- .allocate_constant_from_slice(&vec![0u32; MetadataIdx::COUNT * shape.frontier_width])+ .allocate_constant_from_slice(&vec![0u32; MetadataIdx::COUNT * shape.expand_per_round]).map_err(WeaverEncodeError::Backend)?;let mut node_ancestor_indices = encoder- .allocate_constant_from_slice(&vec![0u32; shape.frontier_width * ancestor_stride])+ .allocate_constant_from_slice(&vec![0u32; shape.expand_per_round * ancestor_stride]).map_err(WeaverEncodeError::Backend)?;let mut node_valid =encoder.allocate_constant_from_slice(&initial_node_valid).map_err(WeaverEncodeError::Backend)?;let mut node_candidate_ids = encoder- .allocate_constant_from_slice(&vec![0u32; shape.frontier_width * candidates.candidates_per_row])+ .allocate_constant_from_slice(&vec![0u32; shape.expand_per_round * self.candidate_pool_size]).map_err(WeaverEncodeError::Backend)?;let mut node_candidate_logits = encoder- .allocate_constant_from_slice(&vec![0.0f32; shape.frontier_width * candidates.candidates_per_row])+ .allocate_constant_from_slice(&vec![0.0f32; shape.expand_per_round * self.candidate_pool_size]).map_err(WeaverEncodeError::Backend)?;let depth_seeds_buffer =encoder.allocate_constant_from_slice(depth_seeds).map_err(WeaverEncodeError::Backend)?;@@ -388,7 +426,7 @@ impl<B: Backend> Weaver<B> {let batch_node_count = if batch_start_slot == 0 {1} else {- shape.frontier_width.min(tree_slot_count - batch_start_slot)+ shape.expand_per_round.min(tree_slot_count - batch_start_slot)};if batch_start_slot > 0 {self.frontier_select.encode(@@ -399,8 +437,8 @@ impl<B: Backend> Weaver<B> {&mut node_metadata,&mut node_ancestor_indices,&mut node_valid,- &candidates.ids,- &candidates.logits,+ &candidate_ids,+ &candidate_logits,&mut node_candidate_ids,&mut node_candidate_logits,frontier_capacity as u32,@@ -410,8 +448,8 @@ impl<B: Backend> Weaver<B> {ancestor_stride as u32,self.max_depth as u32,lookahead_count as u32,- candidates.rows as u32,- candidates.candidates_per_row as u32,+ lookahead_count as u32,+ self.candidate_pool_size as u32,encoder,);}@@ -419,7 +457,7 @@ impl<B: Backend> Weaver<B> {break; // packed-tree slots filled}let (batch_candidate_ids, batch_candidate_logits) = if batch_start_slot == 0 {- (&candidates.ids, &candidates.logits)+ (&candidate_ids, &candidate_logits)} else {(&node_candidate_ids, &node_candidate_logits)};@@ -462,7 +500,7 @@ impl<B: Backend> Weaver<B> {(&node_metadata, MetadataIdx::TreeSlot as usize * metadata_field_bytes),&mut attention_output,batch_node_count as u32,- prefix_length as u32,+ shape.depth as u32,ancestor_stride as u32,tree_slot_count as u32,layer.max_depth as u32,@@ -486,14 +524,14 @@ impl<B: Backend> Weaver<B> {&query,batch_candidate_ids,batch_node_count,- candidates.candidates_per_row,+ self.candidate_pool_size,encoder,)?;let mut child_token_ids = encoder- .allocate_scratch(size_for_shape(&[batch_node_count, shape.children_per_node], DataType::U32))+ .allocate_scratch(size_for_shape(&[batch_node_count, shape.expand_width], DataType::U32)).map_err(WeaverEncodeError::Backend)?;let mut child_logprobs = encoder- .allocate_scratch(size_for_shape(&[batch_node_count, shape.children_per_node], DataType::F32))+ .allocate_scratch(size_for_shape(&[batch_node_count, shape.expand_width], DataType::F32)).map_err(WeaverEncodeError::Backend)?;self.top_children.encode(&logit_residuals,@@ -504,8 +542,8 @@ impl<B: Backend> Weaver<B> {&mut child_token_ids,&mut child_logprobs,batch_node_count as u32,- candidates.candidates_per_row as u32,- shape.children_per_node as u32,+ self.candidate_pool_size as u32,+ shape.expand_width as u32,target_embedding.vocab_size() as u32,encoder,);@@ -520,7 +558,7 @@ impl<B: Backend> Weaver<B> {frontier_capacity as u32,tree_slot_count as u32,batch_node_count as u32,- shape.children_per_node as u32,+ shape.expand_width as u32,encoder,);batch_start_slot += batch_node_count;diff --git a/crates/backend-uzu/src/engine/language_model/stream/stream.rs b/crates/backend-uzu/src/engine/language_model/stream/stream.rsindex 652c131fb..85c02707f 100644--- a/crates/backend-uzu/src/engine/language_model/stream/stream.rs+++ b/crates/backend-uzu/src/engine/language_model/stream/stream.rs@@ -14,7 +14,7 @@ use crate::{gpu_types::trie::TrieNode as GpuTrieNode, kernel::ContextRingUpdateKernel,},data_type::DataType,- encodable_block::{batch_topology::BatchTopology, sampling::SamplingMethod, weaver::TreeShape},+ encodable_block::{batch_topology::BatchTopology, sampling::SamplingMethod},engine::{capture::CaptureSpan,language_model::{@@ -23,6 +23,7 @@ use crate::{stream::{LanguageModelStreamError, LanguageModelStreamOptions},},},+ speculators::dflash_tfm::{DFlashTfmTreeConstructionMethod, DFlashTfmTreeShape},trie::TrieNode,};@@ -544,10 +545,11 @@ impl<'a, B: Backend> LanguageModelStream<'a, B> {None};+ let full_batch_size = 32;let speculation_batch = self.model_state.max_context_length- .map_or(32, |max_context_length| 32.min(max_context_length - context_length));+ .map_or(full_batch_size, |max_context_length| full_batch_size.min(max_context_length - context_length));let mut pending = Vec::new();let (input_trie, chain_copy, full_accept) = if speculation_batch > 1@@ -565,10 +567,17 @@ impl<'a, B: Backend> LanguageModelStream<'a, B> {output_norm,root_token as u32,self.model.decoder.embedding(),- TreeShape {- budget: speculation_batch - 1,- frontier_width: 4,- children_per_node: 4,+ DFlashTfmTreeShape {+ budget: speculation_batch,+ construction_method: if speculator.has_weaver() {+ DFlashTfmTreeConstructionMethod::Weaver {+ depth: 16,+ expand_per_round: 4,+ expand_width: 4,+ }+ } else {+ DFlashTfmTreeConstructionMethod::Argmax+ },},#[cfg(grammar)]self.options.grammar.as_mut(),diff --git a/crates/backend-uzu/src/speculators/dflash_tfm.rs b/crates/backend-uzu/src/speculators/dflash_tfm.rsindex 90d3ccb58..6189534a4 100644--- a/crates/backend-uzu/src/speculators/dflash_tfm.rs+++ b/crates/backend-uzu/src/speculators/dflash_tfm.rs@@ -11,14 +11,15 @@ pub use crate::encodable_block::dflash::DFlashState;#[cfg(grammar)]use crate::engine::language_model::grammar::Grammar;use crate::{- backends::common::{Allocation, AllocationPool, Backend, Encoder},+ backends::common::{Allocation, AllocationPool, Backend, Encoder, gpu_types::trie::TrieNode as GpuTrieNode},config::speculator::{AnySpeculatorConfig, dflash::DFlashSpeculatorConfig, model::SpeculatorModelConfig},data_type::DataType,encodable_block::{+ batch_topology::BatchTopology,dflash::{DFlash, DFlashEncodeError, DFlashNewError},embedding::Embedding,- sampling::PRng,- weaver::{ProposalNode, TreeShape, Weaver, WeaverEncodeError, WeaverNewError},+ sampling::{PRng, Sampling, SamplingMethod},+ weaver::{ProposalNode, Weaver, WeaverEncodeError, WeaverNewError, WeaverTreeShape},},parameters::{HeaderLoadingError, ParameterLoader, ParameterLoaderError},trie::TrieNode,@@ -32,6 +33,8 @@ pub enum DFlashTreeError<B: Backend> {DFlash(#[from] DFlashEncodeError<B>),#[error("Weaver error: {0}")]Weaver(#[from] WeaverEncodeError<B>),+ #[error("invalid tree shape: {0}")]+ InvalidTreeShape(String),}#[derive(Debug, Error)]@@ -50,10 +53,25 @@ pub enum DFlashSpeculatorLoadError<B: Backend> {Weaver(#[from] WeaverNewError<B>),}+pub enum DFlashTfmTreeConstructionMethod {+ Argmax,+ Weaver {+ depth: usize,+ expand_per_round: usize,+ expand_width: usize,+ },+}++pub struct DFlashTfmTreeShape {+ pub budget: usize,+ pub construction_method: DFlashTfmTreeConstructionMethod,+}+pub struct DFlashTfmSpeculator<B: Backend> {context: Arc<B::Context>,dflash: DFlash<B>,- weaver: Weaver<B>,+ weaver: Option<Weaver<B>>,+ sampling: Sampling<B>,config: DFlashSpeculatorConfig,}@@ -73,18 +91,36 @@ impl<B: Backend> DFlashTfmSpeculator<B> {let speculator_tree = weight_loader.tree().subtree("speculator");let dflash = DFlash::new(&*context, &config.draft_config, &speculator_tree.subtree("draft_model"), data_type)?;- let weaver = Weaver::new(&*context, &config.weaver_config, &speculator_tree.subtree("weaver"))?;+ let weaver = config+ .weaver_config+ .as_ref()+ .map(|weaver_config| {+ Weaver::new(+ &*context,+ weaver_config,+ config.draft_config.vocab_size as u32,+ &speculator_tree.subtree("weaver"),+ )+ })+ .transpose()?;weight_loader.tree().assert_all_tensors_validated()?;+ let sampling = Sampling::new(DataType::F32, config.draft_config.vocab_size);+Ok(Self {context,dflash,weaver,+ sampling,config,})}+ pub fn has_weaver(&self) -> bool {+ self.weaver.is_some()+ }+pub fn hidden_feature_layer_indices(&self) -> &[usize] {&self.config.draft_config.target_layer_ids}@@ -112,43 +148,135 @@ impl<B: Backend> DFlashTfmSpeculator<B> {target_output_norm: &Allocation<B>,target_output_token: u32,target_embedding: &Embedding<B>,- shape: TreeShape,+ shape: DFlashTfmTreeShape,#[cfg(grammar)] grammar: Option<&mut Grammar>,prng: &PRng,allocation_pool: Arc<AllocationPool<B>>,) -> Result<TrieNode, DFlashTreeError<B>> {- let candidate_pool_size = self.config.weaver_config.candidate_pool_size;+ assert!(shape.budget >= 2, "tree budget needs at least a root and one draft token");let root_position = state.context_length();let mut encoder = Encoder::new_with_pool_name(&*self.context, allocation_pool, Some("speculator propose")).map_err(DFlashTreeError::Backend)?;- let dflash_output = self.dflash.encode_draft(- state,- target_output_token,- target_embedding,- candidate_pool_size,- &mut encoder,- )?;-- let max_depth = self.config.weaver_config.max_depth;- let depth_seeds =- (0..max_depth).map(|depth| prng.derive((root_position + depth) as u64)).collect::<Box<[u64]>>();- let tree = self.weaver.encode_tree(- target_output_norm,- &dflash_output.draft_hidden,- target_embedding,- &dflash_output.candidates,- &depth_seeds,- target_output_token,- shape,- &mut encoder,- )?;- let completed = encoder.end_encoding().submit().wait_until_completed().map_err(DFlashTreeError::Backend)?;- let nodes = tree.read_nodes();- drop(dflash_output);- drop(completed);+ let nodes = match shape.construction_method {+ DFlashTfmTreeConstructionMethod::Argmax => {+ if shape.budget > self.dflash.block_size() {+ return Err(DFlashTreeError::InvalidTreeShape(format!(+ "argmax chain of {} nodes needs {} draft rows, block size is {}",+ shape.budget,+ shape.budget - 1,+ self.dflash.block_size()+ )));+ }+ let chain_length = shape.budget - 1;+ let mut nodes = Vec::with_capacity(shape.budget);+ nodes.push(ProposalNode {+ token_id: target_output_token,+ depth: 0,+ child_indices: vec![1],+ });+ let dflash_output = self.dflash.encode_draft(+ state,+ target_output_token,+ target_embedding,+ shape.budget,+ &mut encoder,+ )?;+ let topology_nodes = (0..chain_length)+ .map(|index| GpuTrieNode {+ trie_start: index as u32,+ trie_end: (chain_length - 1) as u32,+ height: index as u32,+ })+ .collect::<Box<[_]>>();+ let batch_topology = BatchTopology::new(&topology_nodes, true);+ let sampled = self+ .sampling+ .encode(+ &dflash_output.logits,+ None,+ None,+ None,+ None,+ &SamplingMethod::Greedy,+ &batch_topology,+ 0..chain_length,+ &mut encoder,+ )+ .map_err(DFlashTreeError::Backend)?;+ let completed =+ encoder.end_encoding().submit().wait_until_completed().map_err(DFlashTreeError::Backend)?;+ let tokens = sampled.copyout::<u32>();+ drop(completed);+ nodes.extend(tokens.into_iter().enumerate().map(|(index, token_id)| {+ let depth = index + 1;+ ProposalNode {+ token_id,+ depth,+ child_indices: if depth < chain_length {+ vec![depth + 1]+ } else {+ Vec::new()+ },+ }+ }));+ nodes+ },+ DFlashTfmTreeConstructionMethod::Weaver {+ depth,+ expand_per_round,+ expand_width,+ } => {+ let weaver =+ self.weaver.as_ref().expect("weaver tree construction requires a speculator with weaver weights");+ if depth < 2 {+ return Err(DFlashTreeError::InvalidTreeShape(format!(+ "tree depth {depth} needs at least a root and one level"+ )));+ }+ // `depth` counts the root; the weaver's `max_depth` counts edges.+ if depth > weaver.max_depth() + 1 {+ return Err(DFlashTreeError::InvalidTreeShape(format!(+ "requested tree depth {depth} exceeds weaver max depth {}",+ weaver.max_depth() + 1+ )));+ }+ if depth > self.dflash.block_size() {+ return Err(DFlashTreeError::InvalidTreeShape(format!(+ "tree of depth {depth} needs {} draft rows, block size is {}",+ depth - 1,+ self.dflash.block_size()+ )));+ }+ let dflash_output =+ self.dflash.encode_draft(state, target_output_token, target_embedding, depth, &mut encoder)?;+ let depth_seeds = (0..weaver.max_depth())+ .map(|depth| prng.derive((root_position + depth) as u64))+ .collect::<Box<[u64]>>();+ let tree = weaver.encode_tree(+ target_output_norm,+ &dflash_output.draft_hidden,+ target_embedding,+ &dflash_output.logits,+ &depth_seeds,+ target_output_token,+ WeaverTreeShape {+ budget: shape.budget,+ depth,+ expand_per_round,+ expand_width,+ },+ &mut encoder,+ )?;+ let completed =+ encoder.end_encoding().submit().wait_until_completed().map_err(DFlashTreeError::Backend)?;+ let nodes = tree.read_nodes();+ drop(completed);+ nodes+ },+ };fn recursive_build(nodes: &[ProposalNode],diff --git a/crates/backend-uzu/tests/unit/backends/common/kernel/matmul/gemv_test.rs b/crates/backend-uzu/tests/unit/backends/common/kernel/matmul/gemv_test.rsindex c4fb8a95f..596a31cca 100644--- a/crates/backend-uzu/tests/unit/backends/common/kernel/matmul/gemv_test.rs+++ b/crates/backend-uzu/tests/unit/backends/common/kernel/matmul/gemv_test.rs@@ -241,7 +241,7 @@ fn gemv_gather() {(4, QuantizationMethod::ScaleSymmetric),(8, QuantizationMethod::ScaleZeroPoint),] {- let (m, k, vocab, ids_per_row, group_size) = (4usize, 128usize, 64usize, 8usize, 32u32);+ let (m, k, vocab, ids_per_row, group_size) = (8usize, 128usize, 64usize, 8usize, 32u32);let input = QuantInput::<bf16>::new(m, k, vocab, group_size, bits, method, 0x5EED);let ids: Vec<u32> = (0..m * ids_per_row).map(|i| ((i * 37 + 11) % vocab) as u32).collect();// K_SPLIT == 1 keeps k in one reduction, so gather and dense share the exact accumulation.diff --git a/crates/backend-uzu/tests/unit/backends/common/kernel/matmul/quant_dispatch_test.rs b/crates/backend-uzu/tests/unit/backends/common/kernel/matmul/quant_dispatch_test.rsindex 28c4eaf5e..c36aa3a91 100644--- a/crates/backend-uzu/tests/unit/backends/common/kernel/matmul/quant_dispatch_test.rs+++ b/crates/backend-uzu/tests/unit/backends/common/kernel/matmul/quant_dispatch_test.rs@@ -153,6 +153,8 @@ fn parity_bf16_8bit_splitk(#[case::m1_gs64_8bit_sym(1, 256, 64, 64, 8, QuantizationMethod::ScaleSymmetric)]#[case::m2_gs32_4bit_mlx(2, 256, 64, 32, 4, QuantizationMethod::ScaleBias)]#[case::m4_gs32_4bit_zp(4, 256, 64, 32, 4, QuantizationMethod::ScaleZeroPoint)]+#[case::m8_gs32_4bit_zp(8, 256, 64, 32, 4, QuantizationMethod::ScaleZeroPoint)]+#[case::m8_gs32_4bit_mlx(8, 256, 64, 32, 4, QuantizationMethod::ScaleBias)]fn parity_gemv_bf16(#[case] m: usize,#[case] k: usize,