A high-performance inference engine for AI models
Speculative decoding improvements
LuckyIYI6ba52914d15a
diff --git a/Cargo.lock b/Cargo.lockindex 55f571af4..fd2ac520e 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -307,7 +307,7 @@ checksum = "3a8241f3ebb85c056b509d4327ad0358fbbba6ffb340bf388f26350aeda225b1"[[package]]name = "benchmarks"-version = "0.1.7"+version = "0.1.8"dependencies = ["half","libc",@@ -561,7 +561,7 @@ checksum = "c3e64b0cc0439b12df2fa678eae89a1c56a529fd067a9115f7827f1fffd22b32"[[package]]name = "cli"-version = "0.1.7"+version = "0.1.8"dependencies = ["benchmarks","clap",@@ -4326,7 +4326,7 @@ dependencies = [[[package]]name = "uzu"-version = "0.1.7"+version = "0.1.8"dependencies = ["anyhow","async-trait",diff --git a/Cargo.toml b/Cargo.tomlindex d6ebffc3a..0c7adbcb3 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -3,7 +3,7 @@ members = ["crates/cli", "crates/uzu", "crates/benchmarks"]resolver = "3"[workspace.package]-version = "0.1.7"+version = "0.1.8"edition = "2024"rust-version = "1.93"license = "MIT"diff --git a/README.md b/README.mdindex b08ecbcf8..edb6af1e2 100644--- a/README.md+++ b/README.md@@ -4,8 +4,6 @@</picture></p>-<a href="https://artifacts.trymirai.com/social/about_us.mp3"><img src="https://img.shields.io/badge/Listen-Podcast-red" alt="Listen to our podcast"></a>-<a href="https://docsend.com/v/76bpr/mirai2025"><img src="https://img.shields.io/badge/View-Deck-red" alt="View our deck"></a><a href="https://discord.com/invite/trymirai"><img src="https://img.shields.io/discord/1377764166764462120?label=Discord" alt="Discord"></a><a href="mailto:[email protected]?subject=Interested%20in%20Mirai"><img src="https://img.shields.io/badge/Send-Email-green" alt="Contact us"></a><a href="https://docs.trymirai.com/overview/uzu"><img src="https://img.shields.io/badge/Read-Docs-blue" alt="Read docs"></a>diff --git a/crates/uzu/src/backends/metal/encodable_block/short_conv_mixer.rs b/crates/uzu/src/backends/metal/encodable_block/short_conv_mixer.rsindex be4122178..8e53a1bc1 100644--- a/crates/uzu/src/backends/metal/encodable_block/short_conv_mixer.rs+++ b/crates/uzu/src/backends/metal/encodable_block/short_conv_mixer.rs@@ -13,6 +13,7 @@ use crate::{kernel::short_conv::{ShortConvDecodeArguments, ShortConvKernel,ShortConvPackArguments, ShortConvPrefillArguments,+ ShortConvTrieArguments,},},},@@ -135,11 +136,7 @@ impl ShortConvMixer {let encoder = command_buffer.new_compute_command_encoder().expect("Failed to create compute command encoder");- if active_suffix_length == 1 {- self.run_decode_conv(state, &encoder, active_suffix_length);- } else {- self.run_prefill_conv(state, &encoder, active_suffix_length);- }+ self.run_conv(state, &encoder, active_suffix_length);encoder.end_encoding();self.out_projection.encode(state, command_buffer, parameters);@@ -164,16 +161,81 @@ impl ShortConvMixer {self.in_projection.encode_with_shared_encoder(state, encoder, parameters);- if active_suffix_length == 1 {- self.run_decode_conv(state, encoder, active_suffix_length);- } else {- self.run_prefill_conv(state, encoder, active_suffix_length);- }+ self.run_conv(state, encoder, active_suffix_length);self.out_projection.encode_with_shared_encoder(state, encoder, parameters);}+ fn clear_suffix_state_valid_range(+ &self,+ state: &ForwardPassState<Metal>,+ ) {+ let Some(cache_layers) = state.cache_layers() else {+ return;+ };+ let cache = cache_layers.borrow();+ let layer = cache.data[self.layer_index]+ .as_short_conv()+ .expect("Expected ShortConv layer");+ layer.clear_suffix_state_valid_range();+ }++ fn set_suffix_state_valid_range(+ &self,+ state: &ForwardPassState<Metal>,+ start: usize,+ len: usize,+ ) {+ let Some(cache_layers) = state.cache_layers() else {+ return;+ };+ let cache = cache_layers.borrow();+ let layer = cache.data[self.layer_index]+ .as_short_conv()+ .expect("Expected ShortConv layer");+ layer.set_suffix_state_valid_range(start, len);+ }++ fn run_conv(+ &self,+ state: &mut ForwardPassState<Metal>,+ compute: &ProtocolObject<dyn MTLComputeCommandEncoder>,+ active_suffix_length: usize,+ ) {+ self.clear_suffix_state_valid_range(state);++ if active_suffix_length == 1 {+ self.run_decode_conv(state, compute, 1);+ return;+ }++ let sampling_len = state.sampling_length();+ if sampling_len == 0 {+ self.run_prefill_conv(state, compute, active_suffix_length);+ return;+ }++ let sampling_start = state.sampling_start();+ let trie_len = sampling_len;++ if trie_len <= 1 {+ self.run_prefill_conv(state, compute, active_suffix_length);+ return;+ }++ if sampling_start > 0 {+ if sampling_start == 1 {+ self.run_decode_conv(state, compute, 1);+ } else {+ self.run_prefill_conv(state, compute, sampling_start);+ }+ }++ self.run_trie_conv(state, compute, sampling_start, trie_len);+ self.set_suffix_state_valid_range(state, sampling_start, trie_len);+ }+fn run_prefill_conv(&self,state: &mut ForwardPassState<Metal>,@@ -248,6 +310,87 @@ impl ShortConvMixer {.expect("Failed to encode short conv prefill kernel");}+ fn run_trie_conv(+ &self,+ state: &mut ForwardPassState<Metal>,+ compute: &ProtocolObject<dyn MTLComputeCommandEncoder>,+ sampling_start: usize,+ trie_len: usize,+ ) {+ if trie_len == 0 {+ return;+ }++ let arrays = state.arrays(&[+ ArrayId::SsmInProj,+ ArrayId::TokenParents,+ ArrayId::ShortConvState(self.layer_index),+ ArrayId::ShortConvSuffixState(self.layer_index),+ ArrayId::AttentionOutput,+ ]);++ let in_proj = arrays[0].borrow_mut();+ let parents = arrays[1].borrow_mut();+ let conv_state = arrays[2].borrow_mut();+ let suffix_state = arrays[3].borrow_mut();+ let out = arrays[4].borrow_mut();++ let in_proj_buf = in_proj.buffer().clone();+ let parents_buf = parents.buffer().clone();+ let base_state_buf = conv_state.buffer().clone();+ let suffix_state_buf = suffix_state.buffer().clone();+ let out_buf = out.buffer().clone();++ let data_type: DataType =+ self.config.in_projection_config.activation_precision().into();+ let elem_bytes = data_type.size_in_bytes();++ let kernel_size = self.config.kernel_size;+ let state_stride = kernel_size.saturating_sub(1);+ let in_proj_stride = self.model_dim * 3;++ let in_proj_offset = in_proj.offset()+ + sampling_start * in_proj_stride * elem_bytes;+ let out_offset = out.offset() + sampling_start * self.model_dim * elem_bytes;+ let suffix_state_offset = suffix_state.offset()+ + sampling_start * self.model_dim * state_stride * elem_bytes;+ let base_state_offset = conv_state.offset();+ let parents_offset = parents.offset()+ + sampling_start * std::mem::size_of::<i32>();++ let conv_weight = self.conv_weight.clone();+ let weight_buf = conv_weight.buffer().clone();+ let bias_buf = self.conv_bias.as_ref().map(|b| {+ let b = b.clone();+ b.buffer().clone()+ });++ self.short_conv_kernel+ .encode_trie(+ compute,+ ShortConvTrieArguments {+ in_proj: &in_proj_buf,+ in_proj_offset,+ w: &weight_buf,+ b: bias_buf.as_deref(),+ base_state: &base_state_buf,+ base_state_offset,+ parents: &parents_buf,+ parents_offset,+ out: &out_buf,+ out_offset,+ suffix_state: &suffix_state_buf,+ suffix_state_offset,+ suffix_len: trie_len,+ kernel_size: kernel_size as i32,+ in_proj_stride,+ state_stride,+ model_dim: self.model_dim,+ },+ )+ .expect("Failed to encode short conv trie kernel");+ }+fn run_decode_conv(&self,state: &mut ForwardPassState<Metal>,diff --git a/crates/uzu/src/backends/metal/kernel/matmul/gemv/dispatch_descriptor.rs b/crates/uzu/src/backends/metal/kernel/matmul/gemv/dispatch_descriptor.rsindex 2a5d6d0bf..4df5febee 100644--- a/crates/uzu/src/backends/metal/kernel/matmul/gemv/dispatch_descriptor.rs+++ b/crates/uzu/src/backends/metal/kernel/matmul/gemv/dispatch_descriptor.rs@@ -1,3 +1,5 @@+use std::sync::OnceLock;+use super::pipeline_configuration::{PipelineConfiguration, select_configuration,};@@ -8,6 +10,19 @@ use crate::{},};+const DEFAULT_GEMV_MAX_BATCH: i32 = 8;++static GEMV_MAX_BATCH: OnceLock<i32> = OnceLock::new();++fn max_gemv_batch_threshold() -> i32 {+ *GEMV_MAX_BATCH.get_or_init(|| {+ std::env::var("UZU_GEMV_MAX_BATCH")+ .ok()+ .and_then(|s| s.parse().ok())+ .unwrap_or(DEFAULT_GEMV_MAX_BATCH)+ })+}+#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub(crate) enum AxpbySource {None,@@ -31,6 +46,12 @@ pub(crate) struct DispatchDescriptor {pub(crate) matrix_batch_stride: [i64; 1],pub(crate) bias_batch_stride: [i64; 1],pub(crate) bias_stride: i32,+ /// Number of batch rows (M dimension) - used for batched GEMV+ pub(crate) batch_rows: i32,+ /// Leading dimension of output (ldd)+ pub(crate) output_ld: i32,+ /// Leading dimension of input vector (lda)+ pub(crate) vector_ld: i32,pub(crate) threadgroups: MTLSize,pub(crate) threads_per_threadgroup: MTLSize,}@@ -54,7 +75,14 @@ impl DispatchDescriptor {let m = arguments.batch;let n = arguments.output_dim;- if m != 1 && n != 1 {++ let max_gemv_batch = max_gemv_batch_threshold();++ if n == 1 {+ if m != 1 {+ return Ok(None);+ }+ } else if m > max_gemv_batch {return Ok(None);}@@ -86,10 +114,28 @@ impl DispatchDescriptor {} else {arguments.batch};++ let mut batch_pack = 1;+ if m == 4+ && arguments.input_dim <= 2048+ && (1536..=3072).contains(&output_dimension)+ {+ batch_pack = 2;+ } else if m <= 8 {+ batch_pack = if m >= 4 && m % 4 == 0 {+ 4+ } else if m >= 2 && m % 2 == 0 {+ 2+ } else {+ 1+ };+ }+let pipeline_configuration = select_configuration(arguments.transpose_a,arguments.transpose_b,transpose_matrix,+ batch_pack as u32,arguments.input_dim,output_dimension,false,@@ -144,14 +190,20 @@ impl DispatchDescriptor {/ output_elements_per_threadgroup) as u64;let threadgroup_count_z = batch_groups.max(1) as u64;+ let batch_rows = arguments.batch;+ let threadgroup_count_y = (batch_rows / batch_pack).max(1) as u64;+let threadgroups = MTLSize::new(threadgroup_count_x as usize,- 1,+ threadgroup_count_y as usize,threadgroup_count_z as usize,);let threads_per_threadgroup =pipeline_configuration.threads_per_threadgroup();+ let output_ld = arguments.ldd;+ let vector_ld = arguments.lda;+Ok(Some(Self {pipeline_configuration,matrix_is_rhs,@@ -167,6 +219,9 @@ impl DispatchDescriptor {matrix_batch_stride,bias_batch_stride,bias_stride,+ batch_rows,+ output_ld,+ vector_ld,threadgroups,threads_per_threadgroup,}))diff --git a/crates/uzu/src/backends/metal/kernel/matmul/gemv/kernel.rs b/crates/uzu/src/backends/metal/kernel/matmul/gemv/kernel.rsindex a6135614b..ef92b6b37 100644--- a/crates/uzu/src/backends/metal/kernel/matmul/gemv/kernel.rs+++ b/crates/uzu/src/backends/metal/kernel/matmul/gemv/kernel.rs@@ -31,11 +31,13 @@ fn gemv_kernel_name(let prefix = if config.transpose_matrix {"gemv_t"+ } else if config.batch_pack > 1 {+ "gemv_bp"} else {"gemv"};- Ok(format!(+ let suffix = format!("{prefix}_{dtype_name}_bm{}_bn{}_sm{}_sn{}_tm{}_tn{}_nc{}_axpby{}",config.threadgroup_rows,config.threadgroup_cols,@@ -45,7 +47,13 @@ fn gemv_kernel_name(config.elements_per_thread_col,config.non_contiguous_batch as u8,config.do_axpby as u8,- ))+ );++ if config.batch_pack > 1 && !config.transpose_matrix {+ Ok(format!("{suffix}_bp{}", config.batch_pack))+ } else {+ Ok(suffix)+ }}pub struct Kernel {@@ -87,6 +95,7 @@ impl Kernel {transpose_a: false,transpose_b: true,transpose_matrix: false,+ batch_pack: 1,threadgroup_rows,threadgroup_cols: 1,threads_per_simdgroup_row: 1,@@ -182,6 +191,9 @@ impl Kernel {encoder.set_slice(&descriptor.matrix_batch_stride, 12);encoder.set_slice(&descriptor.bias_batch_stride, 13);encoder.set_value(&descriptor.bias_stride, 14);+ encoder.set_value(&descriptor.batch_rows, 15);+ encoder.set_value(&descriptor.output_ld, 16);+ encoder.set_value(&descriptor.vector_ld, 17);encoder.dispatch_threadgroups(descriptor.threadgroups,diff --git a/crates/uzu/src/backends/metal/kernel/matmul/gemv/pipeline_configuration.rs b/crates/uzu/src/backends/metal/kernel/matmul/gemv/pipeline_configuration.rsindex c07897c6d..e21e979ec 100644--- a/crates/uzu/src/backends/metal/kernel/matmul/gemv/pipeline_configuration.rs+++ b/crates/uzu/src/backends/metal/kernel/matmul/gemv/pipeline_configuration.rs@@ -5,6 +5,7 @@ pub struct PipelineConfiguration {pub transpose_a: bool,pub transpose_b: bool,pub transpose_matrix: bool,+ pub batch_pack: u32,pub threadgroup_rows: u32,pub threadgroup_cols: u32,pub threads_per_simdgroup_row: u32,@@ -37,10 +38,13 @@ impl PipelineConfiguration {}}+const FORCE_TILESET_SMALL_BATCH: i32 = 0;+pub fn select_configuration(transpose_a: bool,transpose_b: bool,transpose_matrix: bool,+ batch_pack: u32,input_dimension: i32,output_dimension: i32,non_contiguous_batch: bool,@@ -50,7 +54,14 @@ pub fn select_configuration(let (threads_per_simdgroup_row, threads_per_simdgroup_col);let (elements_per_thread_row, elements_per_thread_col);- if transpose_matrix {+ if FORCE_TILESET_SMALL_BATCH == 1 && !transpose_matrix {+ threadgroup_rows = 4;+ threadgroup_cols = 1;+ threads_per_simdgroup_row = 1;+ threads_per_simdgroup_col = 32;+ elements_per_thread_row = 2;+ elements_per_thread_col = 4;+ } else if transpose_matrix {let mut sm = 8;let mut sn = 4;if input_dimension >= 8192 && output_dimension >= 2048 {@@ -115,6 +126,7 @@ pub fn select_configuration(transpose_a,transpose_b,transpose_matrix,+ batch_pack,threadgroup_rows,threadgroup_cols,threads_per_simdgroup_row,diff --git a/crates/uzu/src/backends/metal/kernel/matmul/gemv/shaders/gemv.metal b/crates/uzu/src/backends/metal/kernel/matmul/gemv/shaders/gemv.metalindex 9d5538a0e..4946439ca 100644--- a/crates/uzu/src/backends/metal/kernel/matmul/gemv/shaders/gemv.metal+++ b/crates/uzu/src/backends/metal/kernel/matmul/gemv/shaders/gemv.metal@@ -31,6 +31,7 @@ template <const int TM, /* Thread rows (in elements) */const int TN, /* Thread cols (in elements) */const bool kDoAxpby, /* Do out = alpha * out + beta * bias */+ const int BP, /* Batch rows per threadgroup */typename AccT = typename DefaultAccT<T>::type>struct GEMVKernel {using acc_type = AccT;@@ -68,7 +69,7 @@ struct GEMVKernel {// * The last thread that partially overlaps with the matrix is shifted// inwards such that the thread block fits exactly in the matrix- MTL_CONST short tgp_mem_size = BN > 1 ? BN*(blockM + TM) : 0;+ MTL_CONST short tgp_mem_size = BN > 1 ? BN*(blockM + TM)*BP : 0;MTL_CONST bool needs_tgp_reduction = BN > 1;template <typename U = T>@@ -116,6 +117,7 @@ struct GEMVKernel {const constant float& alpha [[buffer(7)]],const constant float& beta [[buffer(8)]],const constant int& bias_stride [[buffer(14)]],+ const int batch_row_base,threadgroup AccT* tgp_memory [[threadgroup(0)]],uint3 tid [[threadgroup_position_in_grid]],uint3 lid [[thread_position_in_threadgroup]],@@ -126,9 +128,9 @@ struct GEMVKernel {(void)lid;// Thread local accumulation results- thread AccT result[TM] = {0};+ thread AccT result[BP][TM] = {{0}};thread T inter[TN];- thread AccT v_coeff[TN];+ thread AccT v_coeff[BP][TN];const int thrM = SN != 32 ? simd_lid / SN : 0;const int thrN = SN != 32 ? simd_lid % SN : int(simd_lid);@@ -162,7 +164,12 @@ struct GEMVKernel {// Loop over in_vec in blocks of blockNfor (int i = 0; i < n_iter; ++i) {- load_unsafe<AccT>(in_vec, v_coeff, bn);+ MTL_PRAGMA_UNROLL+ for (int bp = 0; bp < BP; bp++) {+ const int batch_row = batch_row_base + bp;+ const device T* vec_ptr = in_vec + batch_row * in_vec_size;+ load_unsafe<AccT>(vec_ptr, v_coeff[bp], bn);+ }// Per thread work loopint mat_offset = 0;@@ -173,8 +180,11 @@ struct GEMVKernel {// Accumulate resultsMTL_PRAGMA_UNROLL- for (int tn = 0; tn < TN; tn++) {- result[tm] += inter[tn] * v_coeff[tn];+ for (int bp = 0; bp < BP; bp++) {+ MTL_PRAGMA_UNROLL+ for (int tn = 0; tn < TN; tn++) {+ result[bp][tm] += inter[tn] * v_coeff[bp][tn];+ }}mat_offset += matrix_ld;@@ -184,7 +194,12 @@ struct GEMVKernel {}if (leftover > 0) {- load_safe<AccT>(in_vec, v_coeff, bn, in_size);+ MTL_PRAGMA_UNROLL+ for (int bp = 0; bp < BP; bp++) {+ const int batch_row = batch_row_base + bp;+ const device T* vec_ptr = in_vec + batch_row * in_vec_size;+ load_safe<AccT>(vec_ptr, v_coeff[bp], bn, in_size);+ }// Per thread work loopMTL_PRAGMA_UNROLL@@ -194,38 +209,54 @@ struct GEMVKernel {// Accumulate resultsMTL_PRAGMA_UNROLL- for (int tn = 0; tn < TN; tn++) {- result[tm] += inter[tn] * v_coeff[tn];+ for (int bp = 0; bp < BP; bp++) {+ MTL_PRAGMA_UNROLL+ for (int tn = 0; tn < TN; tn++) {+ result[bp][tm] += inter[tn] * v_coeff[bp][tn];+ }}}}// Simdgroup accumulationsMTL_PRAGMA_UNROLL- for (int tm = 0; tm < TM; tm++) {+ for (int bp = 0; bp < BP; bp++) {MTL_PRAGMA_UNROLL- for (ushort sn = (SN / 2); sn >= 1; sn >>= 1) {- result[tm] += simd_shuffle_down(result[tm], sn);+ for (int tm = 0; tm < TM; tm++) {+ MTL_PRAGMA_UNROLL+ for (ushort sn = (SN / 2); sn >= 1; sn >>= 1) {+ result[bp][tm] += simd_shuffle_down(result[bp][tm], sn);+ }}}// Threadgroup accumulation resultsif (needs_tgp_reduction) {- threadgroup AccT* tgp_results = tgp_memory + sgN * (blockM + TM) + bm;if (thrN == 0) {MTL_PRAGMA_UNROLL- for (int tm = 0; tm < TM; tm++) {- tgp_results[tm] = result[tm];+ for (int bp = 0; bp < BP; bp++) {+ threadgroup AccT* tgp_results =+ tgp_memory + bp * (BN * (blockM + TM)) ++ sgN * (blockM + TM) + bm;+ MTL_PRAGMA_UNROLL+ for (int tm = 0; tm < TM; tm++) {+ tgp_results[tm] = result[bp][tm];+ }}threadgroup_barrier(mem_flags::mem_none);if (sgN == 0) {MTL_PRAGMA_UNROLL- for (int sgn = 1; sgn < BN; sgn++) {+ for (int bp = 0; bp < BP; bp++) {+ threadgroup AccT* tgp_results =+ tgp_memory + bp * (BN * (blockM + TM)) + bm;MTL_PRAGMA_UNROLL- for (int tm = 0; tm < TM; tm++) {- result[tm] += tgp_results[sgn * (blockM + TM) + tm];+ for (int sgn = 1; sgn < BN; sgn++) {+ MTL_PRAGMA_UNROLL+ for (int tm = 0; tm < TM; tm++) {+ result[bp][tm] += tgp_results[sgn * (blockM + TM) + tm];+ }}}}@@ -235,13 +266,19 @@ struct GEMVKernel {// Write outputsif (simdN == 0 && thrN == 0) {MTL_PRAGMA_UNROLL- for (int tm = 0; tm < TM; tm++) {- if (kDoAxpby) {- out_vec[out_row + tm] =- static_cast<T>(alpha) * static_cast<T>(result[tm]) +- static_cast<T>(beta) * bias[(out_row + tm) * bias_stride];- } else {- out_vec[out_row + tm] = static_cast<T>(result[tm]);+ for (int bp = 0; bp < BP; bp++) {+ const int batch_row = batch_row_base + bp;+ device T* out_row_ptr = out_vec + batch_row * out_vec_size;+ MTL_PRAGMA_UNROLL+ for (int tm = 0; tm < TM; tm++) {+ if (kDoAxpby) {+ out_row_ptr[out_row + tm] =+ static_cast<T>(alpha) * static_cast<T>(result[bp][tm]) ++ static_cast<T>(beta) * bias[(out_row + tm) * bias_stride];+ } else {+ out_row_ptr[out_row + tm] =+ static_cast<T>(result[bp][tm]);+ }}}}@@ -466,15 +503,22 @@ template <const constant int64_t* matrix_batch_stride [[buffer(12)]],const constant int64_t* bias_batch_stride [[buffer(13)]],const constant int& bias_stride [[buffer(14)]],+ const constant int& batch_rows [[buffer(15)]],uint3 tid [[threadgroup_position_in_grid]],uint3 lid [[thread_position_in_threadgroup]],uint simd_gid [[simdgroup_index_in_threadgroup]],uint simd_lid [[thread_index_in_simdgroup]]) {- using gemv_kernel = GEMVKernel<T, BM, BN, SM, SN, TM, TN, kDoAxpby>;+ using gemv_kernel = GEMVKernel<T, BM, BN, SM, SN, TM, TN, kDoAxpby, 1>;threadgroup typename gemv_kernel::acc_type tgp_memory[gemv_kernel::tgp_mem_size == 0 ? 1 : gemv_kernel::tgp_mem_size];+ // Batched GEMV: tid.y is the batch row index+ const int batch_row = tid.y;+ if (batch_row >= batch_rows) {+ return;+ }+// Update batch offsetsif (kDoNCBatch) {in_vec += elem_to_loc(tid.z, batch_shape, vector_batch_stride, batch_ndim);@@ -493,7 +537,112 @@ template <}}- out_vec += tid.z * out_vec_size;+ const int batch_row_base = batch_row;+ out_vec += tid.z * batch_rows * out_vec_size;++ gemv_kernel::run(+ mat,+ in_vec,+ bias,+ out_vec,+ in_vec_size,+ out_vec_size,+ marix_ld,+ alpha,+ beta,+ bias_stride,+ batch_row_base,+ gemv_kernel::tgp_mem_size == 0 ? nullptr : tgp_memory,+ tid,+ lid,+ simd_gid,+ simd_lid+ );+}++#define instantiate_gemv_bp_helper( \+ name, \+ itype, \+ bm, \+ bn, \+ sm, \+ sn, \+ tm, \+ nc, \+ axpby, \+ bp \+) \+ instantiate_kernel( \+ "gemv_bp_" #name "_bm" #bm "_bn" #bn "_sm" #sm "_sn" #sn \+ "_tm" #tm "_tn4_nc" #nc "_axpby" #axpby "_bp" #bp, \+ gemv_bp, \+ itype, \+ bm, \+ bn, \+ sm, \+ sn, \+ tm, \+ nc, \+ axpby, \+ bp \+ )++template <+ typename T,+ const int BM, /* Threadgroup rows (in simdgroups) */+ const int BN, /* Threadgroup cols (in simdgroups) */+ const int SM, /* Simdgroup rows (in threads) */+ const int SN, /* Simdgroup cols (in threads) */+ const int TM, /* Thread rows (in elements) */+ const bool kDoNCBatch, /* Batch ndim > 1 */+ const bool kDoAxpby, /* Do out = alpha * out + beta * bias */+ const int BP> /* Batch rows per threadgroup */+[[kernel, max_total_threads_per_threadgroup(BM * BN * 32)]] void gemv_bp(+ const device T* mat [[buffer(0)]],+ const device T* in_vec [[buffer(1)]],+ const device T* bias [[buffer(2)]],+ device T* out_vec [[buffer(3)]],+ const constant int& in_vec_size [[buffer(4)]],+ const constant int& out_vec_size [[buffer(5)]],+ const constant int& marix_ld [[buffer(6)]],+ const constant float& alpha [[buffer(7)]],+ const constant float& beta [[buffer(8)]],+ const constant int& batch_ndim [[buffer(9)]],+ const constant int* batch_shape [[buffer(10)]],+ const constant int64_t* vector_batch_stride [[buffer(11)]],+ const constant int64_t* matrix_batch_stride [[buffer(12)]],+ const constant int64_t* bias_batch_stride [[buffer(13)]],+ const constant int& bias_stride [[buffer(14)]],+ const constant int& batch_rows [[buffer(15)]],+ uint3 tid [[threadgroup_position_in_grid]],+ uint3 lid [[thread_position_in_threadgroup]],+ uint simd_gid [[simdgroup_index_in_threadgroup]],+ uint simd_lid [[thread_index_in_simdgroup]]+) {+ using gemv_kernel = GEMVKernel<T, BM, BN, SM, SN, TM, 4, kDoAxpby, BP>;+ threadgroup typename gemv_kernel::acc_type tgp_memory+ [gemv_kernel::tgp_mem_size == 0 ? 1 : gemv_kernel::tgp_mem_size];++ const int batch_row_base = int(tid.y) * BP;++ if (kDoNCBatch) {+ in_vec += elem_to_loc(tid.z, batch_shape, vector_batch_stride, batch_ndim);+ mat += elem_to_loc(tid.z, batch_shape, matrix_batch_stride, batch_ndim);++ if (kDoAxpby) {+ bias += elem_to_loc(tid.z, batch_shape, bias_batch_stride, batch_ndim);+ }++ } else {+ in_vec += tid.z * vector_batch_stride[0];+ mat += tid.z * matrix_batch_stride[0];++ if (kDoAxpby) {+ bias += tid.z * bias_batch_stride[0];+ }+ }++ out_vec += tid.z * batch_rows * out_vec_size;gemv_kernel::run(mat,@@ -506,6 +655,7 @@ template <alpha,beta,bias_stride,+ batch_row_base,gemv_kernel::tgp_mem_size == 0 ? nullptr : tgp_memory,tid,lid,@@ -548,6 +698,12 @@ template <instantiate_gemv_helper(name, itype, bm, bn, sm, sn, tm, tn, 1, 0) \instantiate_gemv_helper(name, itype, bm, bn, sm, sn, tm, tn, 1, 1) // clang-format on+#define instantiate_gemv_bp(name, itype, bm, bn, sm, sn, tm, bp) \+ instantiate_gemv_bp_helper(name, itype, bm, bn, sm, sn, tm, 0, 0, bp) \+ instantiate_gemv_bp_helper(name, itype, bm, bn, sm, sn, tm, 0, 1, bp) \+ instantiate_gemv_bp_helper(name, itype, bm, bn, sm, sn, tm, 1, 0, bp) \+ instantiate_gemv_bp_helper(name, itype, bm, bn, sm, sn, tm, 1, 1, bp) // clang-format on+// clang-format off#define instantiate_gemv_blocks(name, itype) \instantiate_gemv(name, itype, 1, 8, 1, 32, 4, 4) \@@ -558,10 +714,26 @@ template <instantiate_gemv(name, itype, 4, 1, 1, 32, 4, 4) \instantiate_gemv(name, itype, 8, 1, 1, 32, 4, 4) // clang-format on+#define instantiate_gemv_bp_blocks(name, itype, bp) \+ instantiate_gemv_bp(name, itype, 1, 8, 1, 32, 4, bp) \+ instantiate_gemv_bp(name, itype, 1, 8, 1, 32, 1, bp) \+ instantiate_gemv_bp(name, itype, 1, 1, 8, 4, 4, bp) \+ instantiate_gemv_bp(name, itype, 1, 1, 8, 4, 1, bp) \+ instantiate_gemv_bp(name, itype, 4, 1, 1, 32, 1, bp) \+ instantiate_gemv_bp(name, itype, 4, 1, 1, 32, 4, bp) \+ instantiate_gemv_bp(name, itype, 8, 1, 1, 32, 4, bp) // clang-format on+instantiate_gemv_blocks(float32, float);instantiate_gemv_blocks(float16, half);instantiate_gemv_blocks(bfloat16, bfloat16_t);instantiate_gemv_blocks(complex64, complex64_t);+instantiate_gemv_bp_blocks(float32, float, 2);+instantiate_gemv_bp_blocks(float16, half, 2);+instantiate_gemv_bp_blocks(bfloat16, bfloat16_t, 2);+instantiate_gemv_bp_blocks(float32, float, 4);+instantiate_gemv_bp_blocks(float16, half, 4);+instantiate_gemv_bp_blocks(bfloat16, bfloat16_t, 4);+template <typename T,@@ -597,7 +769,7 @@ template <uint simd_gid [[simdgroup_index_in_threadgroup]],uint simd_lid [[thread_index_in_simdgroup]]) {- using gemv_kernel = GEMVKernel<T, BM, BN, SM, SN, TM, TN, false>;+ using gemv_kernel = GEMVKernel<T, BM, BN, SM, SN, TM, TN, false, 1>;threadgroup typename gemv_kernel::acc_type tgp_memory[gemv_kernel::tgp_mem_size == 0 ? 1 : gemv_kernel::tgp_mem_size];@@ -659,7 +831,8 @@ template <marix_ld,alpha,beta,- batch_ndim, // Not used+ out_vec_size,+ 0,gemv_kernel::tgp_mem_size == 0 ? nullptr : tgp_memory,tid,lid,@@ -715,6 +888,9 @@ template <const constant int64_t* matrix_batch_stride [[buffer(12)]],const constant int64_t* bias_batch_stride [[buffer(13)]],const constant int& bias_stride [[buffer(14)]],+ const constant int& batch_rows [[buffer(15)]],+ const constant int& output_ld [[buffer(16)]],+ const constant int& vector_ld [[buffer(17)]],uint3 tid [[threadgroup_position_in_grid]],uint3 lid [[thread_position_in_threadgroup]],uint simd_gid [[simdgroup_index_in_threadgroup]],@@ -724,6 +900,12 @@ template <threadgroup typename gemv_kernel::acc_type tgp_memory[gemv_kernel::tgp_mem_size == 0 ? 1 : gemv_kernel::tgp_mem_size];+ // Batched GEMV: tid.y is the batch row index+ const int batch_row = tid.y;+ if (batch_row >= batch_rows) {+ return;+ }+// Update batch offsetsif (kDoNCBatch) {in_vec += elem_to_loc(tid.z, batch_shape, vector_batch_stride, batch_ndim);@@ -742,7 +924,9 @@ template <}}- out_vec += tid.z * out_vec_size;+ // Offset by batch row (tid.y)+ in_vec += batch_row * vector_ld;+ out_vec += tid.z * batch_rows * output_ld + batch_row * output_ld;gemv_kernel::run(mat,diff --git a/crates/uzu/src/backends/metal/kernel/short_conv/mod.rs b/crates/uzu/src/backends/metal/kernel/short_conv/mod.rsindex 3ba1ee509..bf42ba391 100644--- a/crates/uzu/src/backends/metal/kernel/short_conv/mod.rs+++ b/crates/uzu/src/backends/metal/kernel/short_conv/mod.rs@@ -30,14 +30,12 @@ fn make_function_constants(pub struct ShortConvKernel {pack_pipeline: Retained<ProtocolObject<dyn MTLComputePipelineState>>,- prefill_pipeline_no_bias:- Retained<ProtocolObject<dyn MTLComputePipelineState>>,- prefill_pipeline_with_bias:- Retained<ProtocolObject<dyn MTLComputePipelineState>>,- decode_pipeline_no_bias:- Retained<ProtocolObject<dyn MTLComputePipelineState>>,- decode_pipeline_with_bias:- Retained<ProtocolObject<dyn MTLComputePipelineState>>,+ prefill_pipeline_no_bias: Retained<ProtocolObject<dyn MTLComputePipelineState>>,+ prefill_pipeline_with_bias: Retained<ProtocolObject<dyn MTLComputePipelineState>>,+ decode_pipeline_no_bias: Retained<ProtocolObject<dyn MTLComputePipelineState>>,+ decode_pipeline_with_bias: Retained<ProtocolObject<dyn MTLComputePipelineState>>,+ trie_pipeline_no_bias: Retained<ProtocolObject<dyn MTLComputePipelineState>>,+ trie_pipeline_with_bias: Retained<ProtocolObject<dyn MTLComputePipelineState>>,}pub struct ShortConvPackArguments<'a> {@@ -78,6 +76,31 @@ pub struct ShortConvDecodeArguments<'a> {pub model_dim: usize,}+pub struct ShortConvTrieArguments<'a> {+ pub in_proj: &'a ProtocolObject<dyn MTLBuffer>,+ /// Byte offset into `in_proj`.+ pub in_proj_offset: usize,+ pub w: &'a ProtocolObject<dyn MTLBuffer>,+ pub b: Option<&'a ProtocolObject<dyn MTLBuffer>>,+ pub base_state: &'a ProtocolObject<dyn MTLBuffer>,+ /// Byte offset into `base_state`.+ pub base_state_offset: usize,+ pub parents: &'a ProtocolObject<dyn MTLBuffer>,+ /// Byte offset into `parents`.+ pub parents_offset: usize,+ pub out: &'a ProtocolObject<dyn MTLBuffer>,+ /// Byte offset into `out`.+ pub out_offset: usize,+ pub suffix_state: &'a ProtocolObject<dyn MTLBuffer>,+ /// Byte offset into `suffix_state`.+ pub suffix_state_offset: usize,+ pub suffix_len: usize,+ pub kernel_size: i32,+ pub in_proj_stride: usize,+ pub state_stride: usize,+ pub model_dim: usize,+}+impl ShortConvKernel {pub fn new(context: &MTLContext,@@ -89,6 +112,8 @@ impl ShortConvKernel {format!("short_conv_prefill_kernel_{}", fn_suffix(data_type));let decode_name =format!("short_conv_decode_kernel_{}", fn_suffix(data_type));+ let trie_name =+ format!("short_conv_trie_kernel_{}", fn_suffix(data_type));let pack_pipeline = context.compute_pipeline_state(&pack_name, None)@@ -139,12 +164,37 @@ impl ShortConvKernel {.map_err(ShortConvKernelError::MetalError)?};+ let trie_pipeline_no_bias = {+ let function_constants = make_function_constants(false);+ let cache_key = format!("{}_has_bias_0", trie_name);+ context+ .compute_pipeline_state_cached(+ &cache_key,+ &trie_name,+ Some(&function_constants),+ )+ .map_err(ShortConvKernelError::MetalError)?+ };+ let trie_pipeline_with_bias = {+ let function_constants = make_function_constants(true);+ let cache_key = format!("{}_has_bias_1", trie_name);+ context+ .compute_pipeline_state_cached(+ &cache_key,+ &trie_name,+ Some(&function_constants),+ )+ .map_err(ShortConvKernelError::MetalError)?+ };+Ok(Self {pack_pipeline,prefill_pipeline_no_bias,prefill_pipeline_with_bias,decode_pipeline_no_bias,decode_pipeline_with_bias,+ trie_pipeline_no_bias,+ trie_pipeline_with_bias,})}@@ -277,4 +327,64 @@ impl ShortConvKernel {Ok(())}++ pub fn encode_trie(+ &self,+ compute_encoder: &ProtocolObject<dyn MTLComputeCommandEncoder>,+ args: ShortConvTrieArguments,+ ) -> Result<(), ShortConvKernelError> {+ if args.model_dim == 0 || args.suffix_len == 0 {+ return Ok(());+ }++ let has_bias = args.b.is_some();+ let pipeline = if has_bias {+ &self.trie_pipeline_with_bias+ } else {+ &self.trie_pipeline_no_bias+ };+ compute_encoder.set_compute_pipeline_state(pipeline);++ compute_encoder.set_buffer(Some(args.in_proj), args.in_proj_offset, 0);+ compute_encoder.set_buffer(Some(args.w), 0, 1);+ if has_bias {+ compute_encoder.set_buffer(args.b, 0, 2);+ }+ compute_encoder.set_buffer(+ Some(args.base_state),+ args.base_state_offset,+ 3,+ );+ compute_encoder.set_buffer(+ Some(args.parents),+ args.parents_offset,+ 4,+ );+ compute_encoder.set_buffer(Some(args.out), args.out_offset, 5);+ compute_encoder.set_buffer(+ Some(args.suffix_state),+ args.suffix_state_offset,+ 6,+ );++ compute_encoder.set_value(&args.suffix_len, 7);+ compute_encoder.set_value(&args.kernel_size, 8);+ compute_encoder.set_value(&args.in_proj_stride, 9);+ compute_encoder.set_value(&args.state_stride, 10);+ compute_encoder.set_value(&(args.model_dim as u32), 11);++ let threads_per_threadgroup = MTLSize {+ width: 32,+ height: 1,+ depth: 1,+ };+ let threadgroups = MTLSize {+ width: args.model_dim,+ height: 1,+ depth: 1,+ };++ compute_encoder.dispatch_threads(threadgroups, threads_per_threadgroup);+ Ok(())+ }}diff --git a/crates/uzu/src/backends/metal/kernel/short_conv/short_conv.metal b/crates/uzu/src/backends/metal/kernel/short_conv/short_conv.metalindex d184f9262..6c5ee6878 100644--- a/crates/uzu/src/backends/metal/kernel/short_conv/short_conv.metal+++ b/crates/uzu/src/backends/metal/kernel/short_conv/short_conv.metal@@ -176,6 +176,75 @@ void short_conv_decode_kernel(}}+template <typename T>+[[kernel, max_total_threads_per_threadgroup(32)]]+void short_conv_trie_kernel(+ device const T* in_proj [[buffer(0)]],+ device const T* w [[buffer(1)]],+ device const T* b [[buffer(2), function_constant(has_bias)]],+ device const T* base_state [[buffer(3)]],+ device const int* parents [[buffer(4)]],+ device T* out [[buffer(5)]],+ device T* suffix_state [[buffer(6)]],+ constant const size_t& suffix_len [[buffer(7)]],+ constant const int& kernel_size [[buffer(8)]],+ constant const size_t& in_proj_stride [[buffer(9)]],+ constant const size_t& state_stride [[buffer(10)]],+ constant const uint& model_dim [[buffer(11)]],+ uint channel_idx [[thread_position_in_grid]]+) {+ if (channel_idx >= model_dim) {+ return;+ }++ const int tap_count = max(kernel_size - 1, 0);+ const device T* w_row = w + size_t(channel_idx) * size_t(kernel_size);+ const size_t base_state_offset = size_t(channel_idx) * state_stride;++ for (size_t node = 0; node < suffix_len; ++node) {+ // Read gated input from in_proj+ const size_t in_proj_idx = node * in_proj_stride + size_t(channel_idx);+ float pre_conv_gate = float(in_proj[in_proj_idx]);+ float post_conv_gate = float(in_proj[in_proj_idx + model_dim]);+ float x_in = float(in_proj[in_proj_idx + 2 * model_dim]);+ float x = x_in * pre_conv_gate;++ // Select parent state (root uses base_state)+ const int parent = parents[node];+ const device T* parent_state = (parent < 0)+ ? (base_state + base_state_offset)+ : (suffix_state + (size_t(parent) * model_dim + size_t(channel_idx)) * state_stride);++ float acc = 0.0f;+ if (has_bias) {+ acc = float(b[channel_idx]);+ }++ for (int tap = 0; tap < tap_count; ++tap) {+ float sample = float(parent_state[size_t(tap)]);+ acc += float(w_row[tap]) * sample;+ }++ acc += float(w_row[tap_count]) * x;++ // Apply post-gate+ float gated_output = acc * post_conv_gate;++ // Write output+ out[node * model_dim + size_t(channel_idx)] = static_cast<T>(gated_output);++ // Write post-state for this node+ if (tap_count > 0) {+ device T* dst_state =+ suffix_state + (node * model_dim + size_t(channel_idx)) * state_stride;+ for (int tap = 0; tap < tap_count - 1; ++tap) {+ dst_state[size_t(tap)] = parent_state[size_t(tap + 1)];+ }+ dst_state[size_t(tap_count - 1)] = static_cast<T>(x);+ }+ }+}+// ============================================================================// Template instantiations// ============================================================================@@ -226,6 +295,24 @@ void short_conv_decode_kernel(uint2 grid_idx [[thread_position_in_grid]] \);+#define instantiate_short_conv_trie_kernel(type_name, type) \+ template [[host_name("short_conv_trie_kernel_" #type_name)]] \+ kernel void short_conv_trie_kernel<type>( \+ device const type* in_proj [[buffer(0)]], \+ device const type* w [[buffer(1)]], \+ device const type* b [[buffer(2), function_constant(has_bias)]], \+ device const type* base_state [[buffer(3)]], \+ device const int* parents [[buffer(4)]], \+ device type* out [[buffer(5)]], \+ device type* suffix_state [[buffer(6)]], \+ constant const size_t& suffix_len [[buffer(7)]], \+ constant const int& kernel_size [[buffer(8)]], \+ constant const size_t& in_proj_stride [[buffer(9)]], \+ constant const size_t& state_stride [[buffer(10)]], \+ constant const uint& model_dim [[buffer(11)]], \+ uint channel_idx [[thread_position_in_grid]] \+ );+instantiate_short_conv_pack_kernel(float, float);instantiate_short_conv_pack_kernel(bfloat, bfloat);instantiate_short_conv_pack_kernel(half, half);@@ -238,6 +325,11 @@ instantiate_short_conv_decode_kernel(float, float);instantiate_short_conv_decode_kernel(bfloat, bfloat);instantiate_short_conv_decode_kernel(half, half);+instantiate_short_conv_trie_kernel(float, float);+instantiate_short_conv_trie_kernel(bfloat, bfloat);+instantiate_short_conv_trie_kernel(half, half);+#undef instantiate_short_conv_pack_kernel#undef instantiate_short_conv_prefill_kernel#undef instantiate_short_conv_decode_kernel+#undef instantiate_short_conv_trie_kerneldiff --git a/crates/uzu/src/forward_pass/cache_layers.rs b/crates/uzu/src/forward_pass/cache_layers.rsindex b5da2272a..a95909ae8 100644--- a/crates/uzu/src/forward_pass/cache_layers.rs+++ b/crates/uzu/src/forward_pass/cache_layers.rs@@ -1,4 +1,7 @@-use std::{cell::RefCell, collections::HashMap};+use std::{+ cell::{Cell, RefCell},+ collections::HashMap,+};use crate::{array::{Array, ArrayContextExt},@@ -37,6 +40,8 @@ const ARRAY_STATE_SPACE_SSM_STATE_LABEL: &str ="cache_layers_state_space_ssm_state";const ARRAY_SHORT_CONV_CONV_STATE_LABEL: &str ="cache_layers_short_conv_conv_state";+const ARRAY_SHORT_CONV_SUFFIX_STATE_LABEL: &str =+ "cache_layers_short_conv_suffix_state";impl<B: Backend> CacheLayer<B> {pub fn as_transformer(&self) -> Option<&KVCacheLayer<B>> {@@ -196,6 +201,11 @@ impl<B: Backend> CacheLayers<B> {model_shape.model_dim(),kernel_size.saturating_sub(1),];+ let suffix_state_shape = [+ max_suffix_length,+ model_shape.model_dim(),+ kernel_size.saturating_sub(1),+ ];let dtype = model_shape.activation_data_type();CacheLayer::ShortConv(ShortConvLayer {@@ -206,6 +216,15 @@ impl<B: Backend> CacheLayers<B> {"{ARRAY_SHORT_CONV_CONV_STATE_LABEL}_{layer_index}"),)),+ suffix_state: RefCell::new(context.create_array(+ &suffix_state_shape,+ dtype,+ &format!(+ "{ARRAY_SHORT_CONV_SUFFIX_STATE_LABEL}_{layer_index}"+ ),+ )),+ suffix_state_valid_start: Cell::new(0),+ suffix_state_valid_len: Cell::new(0),})},})@@ -301,6 +320,8 @@ impl<B: Backend> CacheLayers<B> {command_buffer: &B::CommandBuffer,kv_cache_update: &KVCacheUpdate<B>,) {+ let short_conv_commit_index =+ accepted_suffix_indices.last().copied().unwrap_or(0);for layer in self.data.iter_mut() {if let Some(layer) = layer.as_transformer_mut() {layer.update_after_acceptance(@@ -309,6 +330,9 @@ impl<B: Backend> CacheLayers<B> {command_buffer,kv_cache_update,);+ } else if let Some(layer) = layer.as_short_conv() {+ layer+ .commit_from_suffix_state_if_valid(short_conv_commit_index);}}}@@ -495,8 +519,25 @@ impl<B: Backend> CacheLayers<B> {new_conv.copy_from_array(&conv_src);}+ let suffix_shape =+ layer.suffix_state.borrow().shape().to_vec();+ let suffix_dtype = layer.suffix_state.borrow().data_type();+ let mut new_suffix = context.create_array(+ &suffix_shape,+ suffix_dtype,+ &format!(+ "{ARRAY_SHORT_CONV_SUFFIX_STATE_LABEL}_{layer_index}"+ ),+ );+ {+ new_suffix.as_bytes_mut().fill(0);+ }+CacheLayer::ShortConv(ShortConvLayer {conv_state: RefCell::new(new_conv),+ suffix_state: RefCell::new(new_suffix),+ suffix_state_valid_start: Cell::new(0),+ suffix_state_valid_len: Cell::new(0),})},})diff --git a/crates/uzu/src/forward_pass/scratch_buffers.rs b/crates/uzu/src/forward_pass/scratch_buffers.rsindex af1ab7279..a203e0f31 100644--- a/crates/uzu/src/forward_pass/scratch_buffers.rs+++ b/crates/uzu/src/forward_pass/scratch_buffers.rs@@ -15,6 +15,7 @@ pub struct ScratchBuffers<B: Backend> {// 1-Dpub token_ids: ArrayCell<B>,pub token_positions: ArrayCell<B>,+ pub token_parents: ArrayCell<B>,pub token_bitmask: ArrayCell<B>,pub token_seeds: ArrayCell<B>,pub sampling_output: ArrayCell<B>,@@ -111,6 +112,11 @@ impl<B: Backend> ScratchBuffers<B> {DataType::I32,"token_positions",),+ token_parents: alloc(+ &[max_suffix_len],+ DataType::I32,+ "token_parents",+ ),token_bitmask: alloc(&model_shape.bitmask_shape(max_suffix_len),DataType::U32,diff --git a/crates/uzu/src/forward_pass/short_conv_layer.rs b/crates/uzu/src/forward_pass/short_conv_layer.rsindex 7763a7eb0..d6fe83e6a 100644--- a/crates/uzu/src/forward_pass/short_conv_layer.rs+++ b/crates/uzu/src/forward_pass/short_conv_layer.rs@@ -1,3 +1,5 @@+use std::cell::Cell;+use bytemuck::fill_zeroes;use crate::{array::ArrayCell, backends::common::Backend};@@ -5,11 +7,102 @@ use crate::{array::ArrayCell, backends::common::Backend};#[derive(Debug)]pub struct ShortConvLayer<B: Backend> {pub conv_state: ArrayCell<B>,+ /// Per-token post-state written during speculative runs.+ ///+ /// Shape: [max_suffix_length, model_dim, state_stride]+ pub suffix_state: ArrayCell<B>,+ /// Start index (in the suffix batch) for which `suffix_state` contains+ /// valid post-states for this layer.+ pub suffix_state_valid_start: Cell<usize>,+ /// Number of consecutive tokens (from `suffix_state_valid_start`) for which+ /// `suffix_state` contains valid post-states for this layer.+ pub suffix_state_valid_len: Cell<usize>,}impl<B: Backend> ShortConvLayer<B> {pub fn zero(&self) {+ {+ let mut conv = self.conv_state.borrow_mut();+ fill_zeroes(conv.as_bytes_mut());+ }+ {+ let mut suffix = self.suffix_state.borrow_mut();+ fill_zeroes(suffix.as_bytes_mut());+ }+ self.clear_suffix_state_valid_range();+ }++ pub fn clear_suffix_state_valid_range(&self) {+ self.suffix_state_valid_start.set(0);+ self.suffix_state_valid_len.set(0);+ }++ pub fn set_suffix_state_valid_range(+ &self,+ start: usize,+ len: usize,+ ) {+ self.suffix_state_valid_start.set(start);+ self.suffix_state_valid_len.set(len);+ }++ pub fn commit_from_suffix_state_if_valid(+ &self,+ commit_index: usize,+ ) {+ let start = self.suffix_state_valid_start.get();+ let len = self.suffix_state_valid_len.get();+ if len == 0 {+ return;+ }+ if commit_index < start || commit_index >= start + len {+ return;+ }+let mut conv = self.conv_state.borrow_mut();- fill_zeroes(conv.as_bytes_mut());+ let suffix = self.suffix_state.borrow();++ assert_eq!(+ conv.data_type(),+ suffix.data_type(),+ "ShortConv conv_state / suffix_state dtype mismatch"+ );++ let [model_dim, state_stride] = {+ let shape = conv.shape();+ assert_eq!(+ shape.len(),+ 2,+ "ShortConv conv_state expected 2-D [model_dim, state_stride], got {:?}",+ shape+ );+ [shape[0], shape[1]]+ };++ let suffix_shape = suffix.shape();+ assert!(+ suffix_shape.len() == 3+ && suffix_shape[1] == model_dim+ && suffix_shape[2] == state_stride,+ "ShortConv suffix_state expected 3-D [suffix_len, model_dim, state_stride], got {:?}",+ suffix_shape+ );+ assert!(+ commit_index < suffix_shape[0],+ "ShortConv commit_index {} out of suffix_state range {}",+ commit_index,+ suffix_shape[0]+ );++ let elem_bytes = conv.data_type().size_in_bytes();+ let bytes_per_token = model_dim+ .saturating_mul(state_stride)+ .saturating_mul(elem_bytes);+ let src_start = commit_index.saturating_mul(bytes_per_token);+ let src_end = src_start.saturating_add(bytes_per_token);++ let src = &suffix.as_bytes()[src_start..src_end];+ let dst = conv.as_bytes_mut();+ dst.copy_from_slice(src);}}diff --git a/crates/uzu/src/forward_pass/state/array_id.rs b/crates/uzu/src/forward_pass/state/array_id.rsindex de32f4a8b..4a07ef521 100644--- a/crates/uzu/src/forward_pass/state/array_id.rs+++ b/crates/uzu/src/forward_pass/state/array_id.rs@@ -17,6 +17,7 @@ use super::RopeType;pub enum ArrayId {TokenIds,TokenPositions,+ TokenParents,TokenBitmask,Logits,TokenSeeds,@@ -40,6 +41,7 @@ pub enum ArrayId {SsmDt(usize),SsmZ(usize),ShortConvState(usize),+ ShortConvSuffixState(usize),RotatedQueries,RotatedKeys,diff --git a/crates/uzu/src/forward_pass/state/state.rs b/crates/uzu/src/forward_pass/state/state.rsindex 7b3326c0c..19070e80c 100644--- a/crates/uzu/src/forward_pass/state/state.rs+++ b/crates/uzu/src/forward_pass/state/state.rs@@ -52,6 +52,7 @@ pub struct ForwardPassState<B: Backend> {context: Rc<B::Context>,token_ids: ArrayCell<B>,token_positions: ArrayCell<B>,+ token_parents: ArrayCell<B>,token_bitmask: Option<ArrayCell<B>>,attention_bias: HashMap<Option<usize>, ArrayCell<B>>,pub shared_buffers: Rc<RefCell<SharedBuffers<B>>>,@@ -90,6 +91,57 @@ impl<B: Backend> ForwardPassState<B> {token_positions_array}+ fn init_token_parents(+ scratch: &ScratchBuffers<B>,+ token_positions: &[usize],+ sampling_start: usize,+ sampling_length: usize,+ ) -> ArrayCell<B> {+ let suffix_length = token_positions.len();+ let token_parents_array = scratch.token_parents.view(&[suffix_length]);+ {+ let mut token_parents = token_parents_array.borrow_mut();+ let parents = token_parents.as_slice_mut::<i32>();+ parents.fill(-1);++ if sampling_length > 0 {+ let root_pos =+ token_positions.get(sampling_start).copied().unwrap_or(0);++ let mut stack: Vec<usize> = Vec::new();++ for local_idx in 0..sampling_length {+ let abs_idx = sampling_start + local_idx;+ let Some(&pos) = token_positions.get(abs_idx) else {+ break;+ };+ let depth = pos.saturating_sub(root_pos);++ let parent_local: i32 = if depth == 0 {+ -1+ } else if let Some(&p) = stack.get(depth - 1) {+ p as i32+ } else {+ debug_assert!(+ false,+ "invalid trie depth ordering: depth={depth}, stack_len={}",+ stack.len()+ );+ -1+ };+ parents[abs_idx] = parent_local;++ if stack.len() <= depth {+ stack.resize(depth + 1, 0);+ }+ stack[depth] = local_idx;+ stack.truncate(depth + 1);+ }+ }+ }+ token_parents_array+ }+// ========================================================================// LLM Constructor// ========================================================================@@ -150,6 +202,15 @@ impl<B: Backend> ForwardPassState<B> {Self::init_token_positions(scratch, token_positions)};+ // Trie parent indices (relative, within the sampling segment).+ // Only meaningful when sampling_length > 0.+ let token_parents_cell = Self::init_token_parents(+ scratch,+ token_positions,+ sampling_start,+ sampling_length,+ );+// Token bitmasklet token_bitmask_cell = token_bitmask.map(|bitmask| {let bitmask_shape = model_shape.bitmask_shape(suffix_length);@@ -233,6 +294,7 @@ impl<B: Backend> ForwardPassState<B> {context,token_ids: token_ids_cell,token_positions: token_positions_cell,+ token_parents: token_parents_cell,token_bitmask: token_bitmask_cell,attention_bias,shared_buffers,@@ -304,6 +366,8 @@ impl<B: Backend> ForwardPassState<B> {let token_ids_cell = Self::init_token_ids(scratch, token_ids);let token_positions_cell =Self::init_token_positions(scratch, token_positions);+ let token_parents_cell =+ Self::init_token_parents(scratch, token_positions, 0, 0);// Attention bias (bidirectional or causal)let attention_bias = Self::init_classifier_attention_bias(@@ -332,6 +396,7 @@ impl<B: Backend> ForwardPassState<B> {context,token_ids: token_ids_cell,token_positions: token_positions_cell,+ token_parents: token_parents_cell,token_bitmask: None,attention_bias,shared_buffers,@@ -530,6 +595,7 @@ impl<B: Backend> ForwardPassState<B> {// Common arraysArrayId::TokenIds => self.token_ids.clone(),ArrayId::TokenPositions => self.token_positions.clone(),+ ArrayId::TokenParents => self.token_parents.clone(),ArrayId::TokenBitmask => {self.token_bitmask.clone().expect("Token bitmask not available")},@@ -644,6 +710,14 @@ impl<B: Backend> ForwardPassState<B> {.conv_state.clone()},+ ArrayId::ShortConvSuffixState(layer_index) => {+ let cache = self.llm_state().cache_layers.borrow();+ cache.data[layer_index]+ .as_short_conv()+ .expect("Expected ShortConv layer")+ .suffix_state+ .clone()+ },// MoE arrays (LLM only)ArrayId::MoeTopkIds => selfdiff --git a/crates/uzu/src/language_model/language_model_generator.rs b/crates/uzu/src/language_model/language_model_generator.rsindex 526248a34..a0e76b611 100644--- a/crates/uzu/src/language_model/language_model_generator.rs+++ b/crates/uzu/src/language_model/language_model_generator.rs@@ -96,7 +96,11 @@ impl LanguageModelGenerator {let speculator = &self.decoding_config.speculator_config.speculator;- let suffix_length = prefill_size - tokens_length;+ let suffix_length = if sample_suffix {+ self.decoding_config.generate_suffix_length().saturating_sub(1)+ } else {+ prefill_size - tokens_length+ };let suffix_root = TrieNode::from_speculator(&tokens,&self.context.seed,diff --git a/crates/uzu/src/session/chat_session.rs b/crates/uzu/src/session/chat_session.rsindex 2f6c7c009..f46663535 100644--- a/crates/uzu/src/session/chat_session.rs+++ b/crates/uzu/src/session/chat_session.rs@@ -91,18 +91,22 @@ impl ChatSession {Error::UnableToLoadConfig})?;- let is_ssm = model_metadata+ let (has_non_attention_mixer, has_mamba_mixer) = model_metadata.model_config.as_language_model().and_then(|lm| lm.decoder_config().ok()).and_then(|dc| dc.layer_configs).map(|layers| {- layers.iter().any(|layer| {+ let has_non_attention = layers.iter().any(|layer| {!matches!(layer.mixer_config, MixerConfig::Attention(_))- })+ });+ let has_mamba = layers.iter().any(|layer| {+ matches!(layer.mixer_config, MixerConfig::Mamba(_))+ });+ (has_non_attention, has_mamba)})- .unwrap_or(false);- if is_ssm {+ .unwrap_or((false, false));+ if has_non_attention_mixer {match decoding_config.context_mode {ContextMode::None => {},ContextMode::Static {@@ -114,11 +118,12 @@ impl ChatSession {return Err(Error::UnsupportedContextModeForModel);},}+ }- if decoding_config.speculator_config.number_of_speculated_tokens > 0- {- return Err(Error::UnsupportedSpeculatorConfigForModel);- }+ if has_mamba_mixer+ && decoding_config.speculator_config.number_of_speculated_tokens > 0+ {+ return Err(Error::UnsupportedSpeculatorConfigForModel);}let language_model_config = model_metadatadiff --git a/crates/uzu/src/session/config/speculator_config.rs b/crates/uzu/src/session/config/speculator_config.rsindex 5ba59db53..cdcee7f6f 100644--- a/crates/uzu/src/session/config/speculator_config.rs+++ b/crates/uzu/src/session/config/speculator_config.rs@@ -15,8 +15,13 @@ impl SpeculatorConfig {number_of_speculated_tokens: usize,speculator: Arc<dyn Speculator>,) -> Self {- Self {+ let max_number_of_speculated_tokens: usize = 64;+ let effective_number_of_speculated_tokens = std::cmp::min(number_of_speculated_tokens,+ max_number_of_speculated_tokens,+ );+ Self {+ number_of_speculated_tokens: effective_number_of_speculated_tokens,speculator,}}diff --git a/tools/helpers/main.py b/tools/helpers/main.pyindex afdaa9367..58036252c 100644--- a/tools/helpers/main.py+++ b/tools/helpers/main.py@@ -1,11 +1,15 @@+import base64import json+import osfrom dataclasses import asdict+from itertools import chainfrom pathlib import Pathfrom typing import Annotated+import google_crc32cimport requestsimport tomllib-from model import BenchmarkTask, Message, Model, Registry, Role+from model import BenchmarkTask, File, Message, Model, Registry, Rolefrom rich.console import Consolefrom rich.progress import (BarColumn,@@ -34,6 +38,14 @@ app = Typer()+def crc32c_file(path, chunk_size=8 * 1024 * 1024):+ checksum = google_crc32c.Checksum()+ with open(path, "rb") as file:+ for chunk in iter(lambda: file.read(chunk_size), b""):+ checksum.update(chunk)+ return base64.b64encode(checksum.digest()).decode("ascii")++def get_uzu_version() -> str:with open(CARGO_TOML_PATH, "rb") as file:cargo_toml = tomllib.load(file)@@ -120,12 +132,38 @@ def download_model(console.print(f"[green]✓[/green] {benchmark_task_name} generated")files_to_download = []++ def need_to_download(file: File, file_path: Path) -> bool:+ if file_path.exists():+ if file.crc32c != crc32c_file(file_path):+ os.remove(file_path)+ else:+ return False+ return True+for file in model.files:file_path = model_path / file.name- if file_path.exists():+ need_to_download_file = need_to_download(file, file_path)+ if not need_to_download_file:console.print(f"[green]✓[/green] {file.name} already exists")else:files_to_download.append((file, file_path))++ speculators_path = model_path / "speculators"+ speculators_path.mkdir(parents=True, exist_ok=True)++ for speculator in model.speculators:+ speculator_path = speculators_path / speculator.use_case+ speculator_path.mkdir(parents=True, exist_ok=True)++ for file in speculator.files:+ file_path = speculator_path / file.name+ need_to_download_file = need_to_download(file, file_path)+ if not need_to_download_file:+ console.print(f"[green]✓[/green] {file.name} already exists")+ else:+ files_to_download.append((file, file_path))+if not files_to_download:console.print("[green]All files already downloaded![/green]")returndiff --git a/tools/helpers/model.py b/tools/helpers/model.pyindex 7cf841409..40d06be03 100644--- a/tools/helpers/model.py+++ b/tools/helpers/model.py@@ -7,10 +7,30 @@ from typing import Listclass File:name: strurl: str+ crc32c: str@classmethoddef from_dict(cls, data: dict) -> "File":- return cls(name=data["name"], url=data["url"])+ return cls(name=data["name"], url=data["url"], crc32c=data["crc32c"])+++@dataclass(frozen=True)+class Speculator:+ id: str+ title: str+ description: str+ use_case: str+ files: List[File]++ @classmethod+ def from_dict(cls, data: dict) -> "Speculator":+ return cls(+ id=data["id"],+ title=data["title"],+ description=data["description"],+ use_case=data["useCase"],+ files=[File.from_dict(file) for file in data["files"]],+ )@dataclass(frozen=True)@@ -19,6 +39,7 @@ class Model:toolchain_version: strrepod_id: strname: str+ speculators: List[Speculator]files: List[File]@classmethod@@ -28,6 +49,9 @@ class Model:toolchain_version=data["toolchainVersion"],repod_id=data["repoId"],name=data["name"],+ speculators=[+ Speculator.from_dict(speculator) for speculator in data["speculators"]+ ],files=[File.from_dict(file) for file in data["files"]],)diff --git a/tools/helpers/pyproject.toml b/tools/helpers/pyproject.tomlindex b0a18ce64..6da448630 100644--- a/tools/helpers/pyproject.toml+++ b/tools/helpers/pyproject.toml@@ -3,6 +3,7 @@ name = "tools"version = "0.1.0"requires-python = ">=3.12"dependencies = [+ "google-crc32c>=1.8.0","requests>=2.32.5","rich>=14.1.0","typer>=0.19.2",diff --git a/tools/helpers/uv.lock b/tools/helpers/uv.lockindex 632477377..135f01b8e 100644--- a/tools/helpers/uv.lock+++ b/tools/helpers/uv.lock@@ -74,6 +74,29 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" },]+[[package]]+name = "google-crc32c"+version = "1.8.0"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/03/41/4b9c02f99e4c5fb477122cd5437403b552873f014616ac1d19ac8221a58d/google_crc32c-1.8.0.tar.gz", hash = "sha256:a428e25fb7691024de47fecfbff7ff957214da51eddded0da0ae0e0f03a2cf79", size = 14192, upload-time = "2025-12-16T00:35:25.142Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/e9/5f/7307325b1198b59324c0fa9807cafb551afb65e831699f2ce211ad5c8240/google_crc32c-1.8.0-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:4b8286b659c1335172e39563ab0a768b8015e88e08329fa5321f774275fc3113", size = 31300, upload-time = "2025-12-16T00:21:56.723Z" },+ { url = "https://files.pythonhosted.org/packages/21/8e/58c0d5d86e2220e6a37befe7e6a94dd2f6006044b1a33edf1ff6d9f7e319/google_crc32c-1.8.0-cp312-cp312-macosx_12_0_x86_64.whl", hash = "sha256:2a3dc3318507de089c5384cc74d54318401410f82aa65b2d9cdde9d297aca7cb", size = 30867, upload-time = "2025-12-16T00:38:31.302Z" },+ { url = "https://files.pythonhosted.org/packages/ce/a9/a780cc66f86335a6019f557a8aaca8fbb970728f0efd2430d15ff1beae0e/google_crc32c-1.8.0-cp312-cp312-manylinux1_x86_64.manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:14f87e04d613dfa218d6135e81b78272c3b904e2a7053b841481b38a7d901411", size = 33364, upload-time = "2025-12-16T00:40:22.96Z" },+ { url = "https://files.pythonhosted.org/packages/21/3f/3457ea803db0198c9aaca2dd373750972ce28a26f00544b6b85088811939/google_crc32c-1.8.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:cb5c869c2923d56cb0c8e6bcdd73c009c36ae39b652dbe46a05eb4ef0ad01454", size = 33740, upload-time = "2025-12-16T00:40:23.96Z" },+ { url = "https://files.pythonhosted.org/packages/df/c0/87c2073e0c72515bb8733d4eef7b21548e8d189f094b5dad20b0ecaf64f6/google_crc32c-1.8.0-cp312-cp312-win_amd64.whl", hash = "sha256:3cc0c8912038065eafa603b238abf252e204accab2a704c63b9e14837a854962", size = 34437, upload-time = "2025-12-16T00:35:21.395Z" },+ { url = "https://files.pythonhosted.org/packages/d1/db/000f15b41724589b0e7bc24bc7a8967898d8d3bc8caf64c513d91ef1f6c0/google_crc32c-1.8.0-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:3ebb04528e83b2634857f43f9bb8ef5b2bbe7f10f140daeb01b58f972d04736b", size = 31297, upload-time = "2025-12-16T00:23:20.709Z" },+ { url = "https://files.pythonhosted.org/packages/d7/0d/8ebed0c39c53a7e838e2a486da8abb0e52de135f1b376ae2f0b160eb4c1a/google_crc32c-1.8.0-cp313-cp313-macosx_12_0_x86_64.whl", hash = "sha256:450dc98429d3e33ed2926fc99ee81001928d63460f8538f21a5d6060912a8e27", size = 30867, upload-time = "2025-12-16T00:43:14.628Z" },+ { url = "https://files.pythonhosted.org/packages/ce/42/b468aec74a0354b34c8cbf748db20d6e350a68a2b0912e128cabee49806c/google_crc32c-1.8.0-cp313-cp313-manylinux1_x86_64.manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:3b9776774b24ba76831609ffbabce8cdf6fa2bd5e9df37b594221c7e333a81fa", size = 33344, upload-time = "2025-12-16T00:40:24.742Z" },+ { url = "https://files.pythonhosted.org/packages/1c/e8/b33784d6fc77fb5062a8a7854e43e1e618b87d5ddf610a88025e4de6226e/google_crc32c-1.8.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:89c17d53d75562edfff86679244830599ee0a48efc216200691de8b02ab6b2b8", size = 33694, upload-time = "2025-12-16T00:40:25.505Z" },+ { url = "https://files.pythonhosted.org/packages/92/b1/d3cbd4d988afb3d8e4db94ca953df429ed6db7282ed0e700d25e6c7bfc8d/google_crc32c-1.8.0-cp313-cp313-win_amd64.whl", hash = "sha256:57a50a9035b75643996fbf224d6661e386c7162d1dfdab9bc4ca790947d1007f", size = 34435, upload-time = "2025-12-16T00:35:22.107Z" },+ { url = "https://files.pythonhosted.org/packages/21/88/8ecf3c2b864a490b9e7010c84fd203ec8cf3b280651106a3a74dd1b0ca72/google_crc32c-1.8.0-cp314-cp314-macosx_12_0_arm64.whl", hash = "sha256:e6584b12cb06796d285d09e33f63309a09368b9d806a551d8036a4207ea43697", size = 31301, upload-time = "2025-12-16T00:24:48.527Z" },+ { url = "https://files.pythonhosted.org/packages/36/c6/f7ff6c11f5ca215d9f43d3629163727a272eabc356e5c9b2853df2bfe965/google_crc32c-1.8.0-cp314-cp314-macosx_12_0_x86_64.whl", hash = "sha256:f4b51844ef67d6cf2e9425983274da75f18b1597bb2c998e1c0a0e8d46f8f651", size = 30868, upload-time = "2025-12-16T00:48:12.163Z" },+ { url = "https://files.pythonhosted.org/packages/56/15/c25671c7aad70f8179d858c55a6ae8404902abe0cdcf32a29d581792b491/google_crc32c-1.8.0-cp314-cp314-manylinux1_x86_64.manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:b0d1a7afc6e8e4635564ba8aa5c0548e3173e41b6384d7711a9123165f582de2", size = 33381, upload-time = "2025-12-16T00:40:26.268Z" },+ { url = "https://files.pythonhosted.org/packages/42/fa/f50f51260d7b0ef5d4898af122d8a7ec5a84e2984f676f746445f783705f/google_crc32c-1.8.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:8b3f68782f3cbd1bce027e48768293072813469af6a61a86f6bb4977a4380f21", size = 33734, upload-time = "2025-12-16T00:40:27.028Z" },+ { url = "https://files.pythonhosted.org/packages/08/a5/7b059810934a09fb3ccb657e0843813c1fee1183d3bc2c8041800374aa2c/google_crc32c-1.8.0-cp314-cp314-win_amd64.whl", hash = "sha256:d511b3153e7011a27ab6ee6bb3a5404a55b994dc1a7322c0b87b29606d9790e2", size = 34878, upload-time = "2025-12-16T00:35:23.142Z" },+]+[[package]]name = "idna"version = "3.10"@@ -155,6 +178,7 @@ name = "tools"version = "0.1.0"source = { virtual = "." }dependencies = [+ { name = "google-crc32c" },{ name = "requests" },{ name = "rich" },{ name = "typer" },@@ -162,6 +186,7 @@ dependencies = [[package.metadata]requires-dist = [+ { name = "google-crc32c", specifier = ">=1.8.0" },{ name = "requests", specifier = ">=2.32.5" },{ name = "rich", specifier = ">=14.1.0" },{ name = "typer", specifier = ">=0.19.2" },