Skip to content

armgit / uzu

Public Imported from GitHub
0

A high-performance inference engine for AI models

Common "kernels" are encodable blocks (+remove dead code and other nonsense) (#469)

uuuvn21ff7f243804
diff --git a/crates/backend-uzu/src/backends/common/kernel/mod.rs b/crates/backend-uzu/src/backends/common/kernel/mod.rs
index 7df26e067..a5bc649f6 100644
--- a/crates/backend-uzu/src/backends/common/kernel/mod.rs
+++ b/crates/backend-uzu/src/backends/common/kernel/mod.rs
@@ -6,10 +6,4 @@ pub trait ManualKernels: Kernels {
type MatmulKernel: matmul::MatmulKernel<Backend = Self::Backend>;
}
-pub mod attention;
-pub mod kv_cache_update;
pub mod matmul;
-pub mod mlp_gate_act_mul;
-pub mod moe;
-pub mod sampling;
-pub mod ssd_prefill;
diff --git a/crates/backend-uzu/src/backends/common/kernel/moe/experts_single.rs b/crates/backend-uzu/src/backends/common/kernel/moe/experts_single.rs
deleted file mode 100644
index 0ad75c0b4..000000000
--- a/crates/backend-uzu/src/backends/common/kernel/moe/experts_single.rs
+++ /dev/null
@@ -1,106 +0,0 @@
-// TODO(LuckyIYI): figure out if this was made dead code by accident and restore or delete
-
-use crate::{
- DataType,
- array::size_for_shape,
- backends::common::{
- Allocation, Backend, Encoder, Kernels,
- kernel::{MoeExpertsDecodeSinglePassAKernel, MoeExpertsDecodeSinglePassBKernel},
- },
-};
-
-/// Arguments for single-token MoE decode (T=1 optimized path)
-pub struct MoeExpertsSingleDecodeArguments<'a, B: Backend> {
- /// Input activation [d_model]
- pub x: &'a Allocation<B>,
- /// Top-K expert indices from router [K]
- pub topk_ids: &'a Allocation<B>,
- /// Top-K probabilities from router [K]
- pub topk_probs: &'a Allocation<B>,
- /// Up/gate projection weights [E, 2*d_ff, d_model]
- pub w13_all: &'a Allocation<B>,
- /// Down projection weights [E, d_model, d_ff]
- pub w2_all: &'a Allocation<B>,
- /// Up/gate biases [E, 2*d_ff]
- pub up_biases: &'a Allocation<B>,
- /// Down biases [E, d_model]
- pub down_biases: &'a Allocation<B>,
- /// Model dimension
- pub d_model: usize,
- /// FFN hidden dimension
- pub d_ff: usize,
- /// Number of active experts per token
- pub k: usize,
- /// SiLU activation alpha parameter
- pub silu_alpha: f32,
- /// Gate clipping min
- pub gate_clip_min: f32,
- /// Gate clipping max
- pub gate_clip_max: f32,
- /// Up clipping min
- pub up_clip_min: f32,
- /// Up clipping max
- pub up_clip_max: f32,
-}
-
-pub struct MoeExpertsSingleDecodeKernels<B: Backend> {
- pass_a: <B::Kernels as Kernels>::MoeExpertsDecodeSinglePassAKernel,
- pass_b: <B::Kernels as Kernels>::MoeExpertsDecodeSinglePassBKernel,
- data_type: DataType,
-}
-
-impl<B: Backend> MoeExpertsSingleDecodeKernels<B> {
- pub fn new(
- ctx: &B::Context,
- data_type: DataType,
- gating_code: u32,
- ) -> Result<Self, B::Error> {
- Ok(Self {
- pass_a: <B::Kernels as Kernels>::MoeExpertsDecodeSinglePassAKernel::new(ctx, data_type, gating_code)?,
- pass_b: <B::Kernels as Kernels>::MoeExpertsDecodeSinglePassBKernel::new(ctx, data_type)?,
- data_type,
- })
- }
-
- pub fn encode(
- &self,
- args: MoeExpertsSingleDecodeArguments<B>,
- encoder: &mut Encoder<B>,
- ) -> Result<Allocation<B>, B::Error> {
- // Pass A: x @ W13[expert] -> hidden
- let mut hidden = encoder.allocate_scratch(size_for_shape(&[args.k, args.d_ff], DataType::F32))?;
- self.pass_a.encode(
- args.x,
- args.topk_ids,
- args.w13_all,
- args.up_biases,
- &mut hidden,
- args.d_model as u32,
- args.d_ff as u32,
- args.k as u32,
- args.silu_alpha,
- args.gate_clip_min,
- args.gate_clip_max,
- args.up_clip_min,
- args.up_clip_max,
- encoder,
- );
-
- // Pass B: 8 simdgroups (256 threads), outputs final y directly
- let mut output = encoder.allocate_scratch(size_for_shape(&[args.d_model], self.data_type))?;
- self.pass_b.encode(
- &hidden,
- args.topk_ids,
- args.topk_probs,
- args.w2_all,
- args.down_biases,
- &mut output,
- args.d_model as u32,
- args.d_ff as u32,
- args.k as u32,
- encoder,
- );
-
- Ok(output)
- }
-}
diff --git a/crates/backend-uzu/src/backends/common/kernel/moe/mod.rs b/crates/backend-uzu/src/backends/common/kernel/moe/mod.rs
deleted file mode 100644
index 0da69a0fe..000000000
--- a/crates/backend-uzu/src/backends/common/kernel/moe/mod.rs
+++ /dev/null
@@ -1,9 +0,0 @@
-mod experts_single;
-mod experts_two_pass_decode;
-mod experts_two_pass_prefill;
-mod gather;
-
-pub use experts_single::{MoeExpertsSingleDecodeArguments, MoeExpertsSingleDecodeKernels};
-pub use experts_two_pass_decode::MoeExpertsTwoPassDecodeBlock;
-pub use experts_two_pass_prefill::{MoeExpertsTwoPassArguments, MoeExpertsTwoPassPrefillBlock};
-pub use gather::MoeGatherKernel;
diff --git a/crates/backend-uzu/src/backends/common/kernel/attention.rs b/crates/backend-uzu/src/encodable_block/attention/gemm.rs
similarity index 98%
rename from crates/backend-uzu/src/backends/common/kernel/attention.rs
rename to crates/backend-uzu/src/encodable_block/attention/gemm.rs
index d162b91d1..1ce2a3d9f 100644
--- a/crates/backend-uzu/src/backends/common/kernel/attention.rs
+++ b/crates/backend-uzu/src/encodable_block/attention/gemm.rs
@@ -26,7 +26,6 @@ pub struct AttentionGemmArguments<'a, B: Backend, KVBuf: AsBufferRangeRef> {
pub suffix_length: usize, // qL
pub sequence_length: usize, // kL (prefix + suffix)
pub segment_prefix_length: usize, // qL_off
- pub max_sequence_length: usize, // stride for K/V cache
pub ring_params: Option<RingParams>,
pub head_dim: usize,
pub sliding_window_size: Option<usize>,
@@ -166,3 +165,7 @@ struct KernelKey {
is_sliding_window: bool,
has_sinks: bool,
}
+
+#[cfg(test)]
+#[path = "../../../tests/unit/encodable_block/attention_gemm_test.rs"]
+mod tests;
diff --git a/crates/backend-uzu/src/encodable_block/attention.rs b/crates/backend-uzu/src/encodable_block/attention/mod.rs
similarity index 99%
rename from crates/backend-uzu/src/encodable_block/attention.rs
rename to crates/backend-uzu/src/encodable_block/attention/mod.rs
index 704f9387b..e6e5717d3 100644
--- a/crates/backend-uzu/src/encodable_block/attention.rs
+++ b/crates/backend-uzu/src/encodable_block/attention/mod.rs
@@ -1,7 +1,10 @@
//! Attention kernel encodable.
+mod gemm;
+
use std::{cell::RefCell, collections::HashMap, rc::Rc};
+use gemm::{AttentionGemmArguments, AttentionGemmBlock};
use itertools::iproduct;
use thiserror::Error;
@@ -16,7 +19,6 @@ use crate::{
AttentionFallbackScatterScoresKernel, AttentionFallbackScatterValuesKernel, AttentionSinglePassKernel,
AttentionTwoPass1Kernel, AttentionTwoPass2Kernel, AttentionUpdateKVCacheKernel, ManualKernels,
SigmoidGateKernel, SoftmaxKernel,
- attention::{AttentionGemmArguments, AttentionGemmBlock},
matmul::{MatmulArguments, MatmulB, MatmulDOps, MatmulKernel},
},
},
@@ -514,7 +516,6 @@ impl<B: Backend> Attention<B> {
self.num_groups,
suffix_length,
segment_prefix_length,
- max_sequence_length,
self.head_dim,
encoder,
)?
@@ -610,7 +611,6 @@ impl<B: Backend> Attention<B> {
num_groups: usize,
suffix_length: usize,
segment_prefix_length: usize,
- max_sequence_length: usize,
head_dim: usize,
encoder: &mut Encoder<B>,
) -> Result<Allocation<B>, B::Error> {
@@ -630,7 +630,6 @@ impl<B: Backend> Attention<B> {
suffix_length,
sequence_length,
segment_prefix_length,
- max_sequence_length,
ring_params,
head_dim,
is_causal: self.is_causal,
@@ -879,5 +878,5 @@ struct KernelKey {
}
#[cfg(test)]
-#[path = "../../tests/unit/encodable_block/attention_test.rs"]
+#[path = "../../../tests/unit/encodable_block/attention_test.rs"]
mod tests;
diff --git a/crates/backend-uzu/src/encodable_block/decoder.rs b/crates/backend-uzu/src/encodable_block/decoder.rs
index 83089a518..5836dbc96 100644
--- a/crates/backend-uzu/src/encodable_block/decoder.rs
+++ b/crates/backend-uzu/src/encodable_block/decoder.rs
@@ -129,7 +129,7 @@ impl<B: Backend> Decoder<B> {
})
}
- pub(crate) fn build_transformer_layers_and_norm(
+ pub fn build_transformer_layers_and_norm(
context: &B::Context,
decoder_config: &DecoderConfig,
root_weight_loader: &ParameterTree<B>,
diff --git a/crates/backend-uzu/src/encodable_block/delta_net_mixer.rs b/crates/backend-uzu/src/encodable_block/delta_net_mixer.rs
index aa8028ddc..f00b3fb03 100644
--- a/crates/backend-uzu/src/encodable_block/delta_net_mixer.rs
+++ b/crates/backend-uzu/src/encodable_block/delta_net_mixer.rs
@@ -28,7 +28,7 @@ pub enum DeltaNetMixerError<B: Backend> {
ParameterLoaderError(#[from] ParameterLoaderError<B>),
}
-pub(crate) struct DeltaNetMixer<B: Backend> {
+pub struct DeltaNetMixer<B: Backend> {
kernel_size: usize,
num_heads: usize,
num_groups: usize,
@@ -58,13 +58,13 @@ pub(crate) struct DeltaNetMixer<B: Backend> {
inner_data_type: DataType,
}
-pub(crate) struct DeltaNetArguments<'a, B: Backend> {
+pub struct DeltaNetArguments<'a, B: Backend> {
pub active_row_count: usize,
pub layer: &'a mut DeltaNetLayer<B>,
}
impl<B: Backend> DeltaNetMixer<B> {
- pub(crate) fn new(
+ pub fn new(
context: &B::Context,
config: &DeltaNetConfig,
model_dim: usize,
@@ -347,7 +347,7 @@ impl<B: Backend> DeltaNetMixer<B> {
Ok(out)
}
- pub(crate) fn encode(
+ pub fn encode(
&self,
args: DeltaNetArguments<B>,
input: Allocation<B>,
diff --git a/crates/backend-uzu/src/backends/common/kernel/kv_cache_update.rs b/crates/backend-uzu/src/encodable_block/kv_cache_update.rs
similarity index 92%
rename from crates/backend-uzu/src/backends/common/kernel/kv_cache_update.rs
rename to crates/backend-uzu/src/encodable_block/kv_cache_update.rs
index 2da61b6a3..1635ad08b 100644
--- a/crates/backend-uzu/src/backends/common/kernel/kv_cache_update.rs
+++ b/crates/backend-uzu/src/encodable_block/kv_cache_update.rs
@@ -25,16 +25,10 @@ pub enum KVCacheUpdateError<B: Backend> {
IndicesCountMismatch,
#[error("Shape mismatch between key and value tensors")]
ShapeMismatch,
- #[error("Unsupported data type")]
- UnsupportedDataType,
#[error("Backend error: {0}")]
BackendError(#[source] B::Error),
#[error("Swap count exceeds maximum sequence length")]
MaxSequenceLengthExceeded,
- #[error("Buffer creation failed")]
- BufferCreationFailed,
- #[error("Function not found: {0}")]
- FunctionNotFound(String),
}
impl<B: Backend> KVCacheUpdate<B> {
@@ -118,5 +112,5 @@ pub fn create_swaps_direct(
}
#[cfg(test)]
-#[path = "../../../../tests/unit/backends/common/kernel/kv_cache_update_test.rs"]
+#[path = "../../tests/unit/encodable_block/kv_cache_update_test.rs"]
mod tests;
diff --git a/crates/backend-uzu/src/encodable_block/layer/executables.rs b/crates/backend-uzu/src/encodable_block/layer/executables.rs
index afe203009..45b4db2c4 100644
--- a/crates/backend-uzu/src/encodable_block/layer/executables.rs
+++ b/crates/backend-uzu/src/encodable_block/layer/executables.rs
@@ -61,7 +61,7 @@ pub struct LayerExecutables<B: Backend> {
#[cfg(feature = "tracing")]
pub tensor_add: <B::Kernels as Kernels>::TensorAddBiasKernel,
pub pre_mixer_norm: RMSNorm<B>,
- pub(crate) mixer: MixerExecutables<B>,
+ mixer: MixerExecutables<B>,
pub post_mixer_norm: Option<RMSNorm<B>>,
pub pre_mlp_norm: RMSNorm<B>,
pub mlp: Box<dyn Mlp<B>>,
diff --git a/crates/backend-uzu/src/encodable_block/layer/mixer.rs b/crates/backend-uzu/src/encodable_block/layer/mixer.rs
index 2acf6117e..5c8b412c9 100644
--- a/crates/backend-uzu/src/encodable_block/layer/mixer.rs
+++ b/crates/backend-uzu/src/encodable_block/layer/mixer.rs
@@ -6,7 +6,7 @@ use crate::{
};
/// Mixer component - either attention, state space, short conv, or delta net.
-pub(crate) enum MixerExecutables<B: Backend> {
+pub enum MixerExecutables<B: Backend> {
Attention {
attention: Attention<B>,
},
diff --git a/crates/backend-uzu/src/encodable_block/layer/mod.rs b/crates/backend-uzu/src/encodable_block/layer/mod.rs
index 99ea4fb08..4898e3959 100644
--- a/crates/backend-uzu/src/encodable_block/layer/mod.rs
+++ b/crates/backend-uzu/src/encodable_block/layer/mod.rs
@@ -4,4 +4,4 @@ mod executables;
mod mixer;
pub use executables::{LayerArguments, LayerExecutables, LayerExecutablesError};
-pub(crate) use mixer::MixerExecutables;
+use mixer::MixerExecutables;
diff --git a/crates/backend-uzu/src/encodable_block/mamba_mixer.rs b/crates/backend-uzu/src/encodable_block/mamba_mixer/mod.rs
similarity index 96%
rename from crates/backend-uzu/src/encodable_block/mamba_mixer.rs
rename to crates/backend-uzu/src/encodable_block/mamba_mixer/mod.rs
index d8d490331..86f0e2b3e 100644
--- a/crates/backend-uzu/src/encodable_block/mamba_mixer.rs
+++ b/crates/backend-uzu/src/encodable_block/mamba_mixer/mod.rs
@@ -1,7 +1,10 @@
//! Mamba2 SSM mixer encodable.
+mod ssd_prefill;
+
use std::env;
+use ssd_prefill::{SSDPrefillArguments, SSDPrefillBlock, SSDPrefillMode};
use thiserror::Error;
use crate::{
@@ -10,10 +13,7 @@ use crate::{
backends::common::{
Allocation, Backend, Encoder, Kernels,
gpu_types::ActivationType,
- kernel::{
- Conv1dDecodeKernel, Conv1dPackKernel, Conv1dScanKernel, SSDUpdateKernel, SplitInProjKernel,
- ssd_prefill::{SSDPrefillArguments, SSDPrefillKernels, SSDPrefillMode},
- },
+ kernel::{Conv1dDecodeKernel, Conv1dPackKernel, Conv1dScanKernel, SSDUpdateKernel, SplitInProjKernel},
},
config::token_mixer::mamba2::Mamba2Config,
encodable_block::linear::{Linear, LinearBlockError},
@@ -31,7 +31,7 @@ pub enum MambaMixerError<B: Backend> {
ParameterLoaderError(#[from] ParameterLoaderError<B>),
}
-pub(crate) struct MambaMixer<B: Backend> {
+pub struct MambaMixer<B: Backend> {
conv_dim: usize,
inner_dim: usize,
num_heads: usize,
@@ -46,7 +46,7 @@ pub(crate) struct MambaMixer<B: Backend> {
conv_decode: <B::Kernels as Kernels>::Conv1dDecodeKernel,
conv_pack: <B::Kernels as Kernels>::Conv1dPackKernel,
conv_scan: <B::Kernels as Kernels>::Conv1dScanKernel,
- ssd_prefill: SSDPrefillKernels<B>,
+ ssd_prefill: SSDPrefillBlock<B>,
ssd_update: <B::Kernels as Kernels>::SSDUpdateKernel,
conv_weight: Allocation<B>,
conv_bias: Option<Allocation<B>>,
@@ -56,7 +56,7 @@ pub(crate) struct MambaMixer<B: Backend> {
inner_data_type: DataType,
}
-pub(crate) struct MambaArguments<'a, B: Backend> {
+pub struct MambaArguments<'a, B: Backend> {
pub active_row_count: usize,
pub layer: &'a mut SSMLayer<B>,
}
@@ -85,7 +85,7 @@ fn resolve_prefill_mode_from_env() -> SSDPrefillMode {
}
impl<B: Backend> MambaMixer<B> {
- pub(crate) fn new(
+ pub fn new(
context: &B::Context,
mamba_config: &Mamba2Config,
model_dim: usize,
@@ -153,7 +153,7 @@ impl<B: Backend> MambaMixer<B> {
.map_err(MambaMixerError::BackendError)?;
let conv_pack = <B::Kernels as Kernels>::Conv1dPackKernel::new(context, inner_data_type)
.map_err(MambaMixerError::BackendError)?;
- let ssd_prefill = SSDPrefillKernels::new(context, inner_data_type).map_err(MambaMixerError::BackendError)?;
+ let ssd_prefill = SSDPrefillBlock::new(context, inner_data_type).map_err(MambaMixerError::BackendError)?;
let ssd_update = <B::Kernels as Kernels>::SSDUpdateKernel::new(context, inner_data_type, true)
.map_err(MambaMixerError::BackendError)?;
let prefill_mode = resolve_prefill_mode_from_env();
@@ -403,7 +403,7 @@ impl<B: Backend> MambaMixer<B> {
Ok(out)
}
- pub(crate) fn encode(
+ pub fn encode(
&self,
args: MambaArguments<B>,
input: Allocation<B>,
diff --git a/crates/backend-uzu/src/backends/common/kernel/ssd_prefill.rs b/crates/backend-uzu/src/encodable_block/mamba_mixer/ssd_prefill.rs
similarity index 96%
rename from crates/backend-uzu/src/backends/common/kernel/ssd_prefill.rs
rename to crates/backend-uzu/src/encodable_block/mamba_mixer/ssd_prefill.rs
index 127e275a9..6a6ef4879 100644
--- a/crates/backend-uzu/src/backends/common/kernel/ssd_prefill.rs
+++ b/crates/backend-uzu/src/encodable_block/mamba_mixer/ssd_prefill.rs
@@ -32,14 +32,14 @@ pub struct SSDPrefillArguments<'a, B: Backend> {
pub head_dim: usize,
}
-pub struct SSDPrefillKernels<B: Backend> {
+pub struct SSDPrefillBlock<B: Backend> {
single: <B::Kernels as Kernels>::SSDPrefillKernel,
single_64: <B::Kernels as Kernels>::SSDPrefill64Kernel,
sequential: <B::Kernels as Kernels>::SSDPrefillSequentialKernel,
data_type: DataType,
}
-impl<B: Backend> SSDPrefillKernels<B> {
+impl<B: Backend> SSDPrefillBlock<B> {
pub fn new(
context: &B::Context,
data_type: DataType,
@@ -139,5 +139,5 @@ impl<B: Backend> SSDPrefillKernels<B> {
}
#[cfg(test)]
-#[path = "../../../../tests/unit/backends/common/kernel/ssd_prefill_test.rs"]
+#[path = "../../../tests/unit/encodable_block/mamba_mixer/ssd_prefill_test.rs"]
mod tests;
diff --git a/crates/backend-uzu/src/encodable_block/mlp/dense.rs b/crates/backend-uzu/src/encodable_block/mlp/dense.rs
index dd34e49cf..b0407a775 100644
--- a/crates/backend-uzu/src/encodable_block/mlp/dense.rs
+++ b/crates/backend-uzu/src/encodable_block/mlp/dense.rs
@@ -1,7 +1,7 @@
//! MLP block encodable.
-use super::{super::linear::Linear, Mlp};
-use crate::backends::common::{Allocation, Backend, Encoder, kernel::mlp_gate_act_mul::MlpGateActMulEncodable};
+use super::{super::linear::Linear, Mlp, gate_act_mul::MlpGateActMulEncodable};
+use crate::backends::common::{Allocation, Backend, Encoder};
pub struct DenseMlp<B: Backend> {
up: Box<dyn Linear<B>>,
diff --git a/crates/backend-uzu/src/backends/common/kernel/mlp_gate_act_mul.rs b/crates/backend-uzu/src/encodable_block/mlp/gate_act_mul.rs
similarity index 100%
rename from crates/backend-uzu/src/backends/common/kernel/mlp_gate_act_mul.rs
rename to crates/backend-uzu/src/encodable_block/mlp/gate_act_mul.rs
diff --git a/crates/backend-uzu/src/encodable_block/mlp/mod.rs b/crates/backend-uzu/src/encodable_block/mlp/mod.rs
index 1dfcefee9..87a544e43 100644
--- a/crates/backend-uzu/src/encodable_block/mlp/mod.rs
+++ b/crates/backend-uzu/src/encodable_block/mlp/mod.rs
@@ -1,14 +1,16 @@
mod dense;
+mod gate_act_mul;
mod moe;
pub use dense::DenseMlp;
+use gate_act_mul::MlpGateActMulEncodable;
pub use moe::{MoeBlock, MoeBlockError};
use thiserror::Error;
use super::linear::{Linear, LinearBlockError};
use crate::{
DataType,
- backends::common::{Allocation, Backend, Encoder, kernel::mlp_gate_act_mul::MlpGateActMulEncodable},
+ backends::common::{Allocation, Backend, Encoder},
config::mlp::AnyMLPConfig,
parameters::{ParameterLoaderError, ParameterTree},
};
diff --git a/crates/backend-uzu/src/backends/common/kernel/moe/experts_two_pass_decode.rs b/crates/backend-uzu/src/encodable_block/mlp/moe/experts_two_pass_decode.rs
similarity index 98%
rename from crates/backend-uzu/src/backends/common/kernel/moe/experts_two_pass_decode.rs
rename to crates/backend-uzu/src/encodable_block/mlp/moe/experts_two_pass_decode.rs
index f12e83e6f..21fb99a82 100644
--- a/crates/backend-uzu/src/backends/common/kernel/moe/experts_two_pass_decode.rs
+++ b/crates/backend-uzu/src/encodable_block/mlp/moe/experts_two_pass_decode.rs
@@ -1,3 +1,4 @@
+use super::MoeExpertsTwoPassArguments;
use crate::{
DataType,
array::size_for_shape,
@@ -6,7 +7,7 @@ use crate::{
kernel::{
Kernels, MoeExpertsDecodeDownFused2DKernel, MoeExpertsDecodePassAKernel, MoePassABuildRowMapKernel,
MoePassABuildTileMapKernel, MoePassATileCountsKernel, MoePassATileScanKernel,
- MoePassAWriteDispatchArgsKernel, moe::MoeExpertsTwoPassArguments,
+ MoePassAWriteDispatchArgsKernel,
},
},
};
diff --git a/crates/backend-uzu/src/backends/common/kernel/moe/experts_two_pass_prefill.rs b/crates/backend-uzu/src/encodable_block/mlp/moe/experts_two_pass_prefill.rs
similarity index 100%
rename from crates/backend-uzu/src/backends/common/kernel/moe/experts_two_pass_prefill.rs
rename to crates/backend-uzu/src/encodable_block/mlp/moe/experts_two_pass_prefill.rs
diff --git a/crates/backend-uzu/src/backends/common/kernel/moe/gather.rs b/crates/backend-uzu/src/encodable_block/mlp/moe/gather.rs
similarity index 70%
rename from crates/backend-uzu/src/backends/common/kernel/moe/gather.rs
rename to crates/backend-uzu/src/encodable_block/mlp/moe/gather.rs
index 5a263d2d3..3e0ad5c28 100644
--- a/crates/backend-uzu/src/backends/common/kernel/moe/gather.rs
+++ b/crates/backend-uzu/src/encodable_block/mlp/moe/gather.rs
@@ -7,26 +7,26 @@ use crate::{
},
};
-enum MoeGatherKernelType<B: Backend> {
+enum MoeGatherVariant<B: Backend> {
OneD(<B::Kernels as Kernels>::MoeGatherXPerm1DKernel),
TwoD(<B::Kernels as Kernels>::MoeGatherXPerm2DKernel),
}
-pub struct MoeGatherKernel<B: Backend> {
- kernel: MoeGatherKernelType<B>,
+pub struct MoeGather<B: Backend> {
+ variant: MoeGatherVariant<B>,
data_type: DataType,
}
-impl<B: Backend> MoeGatherKernel<B> {
+impl<B: Backend> MoeGather<B> {
pub fn new(
ctx: &B::Context,
data_type: DataType,
) -> Result<Self, B::Error> {
Ok(Self {
- kernel: if data_type == DataType::BF16 {
- MoeGatherKernelType::TwoD(<B::Kernels as Kernels>::MoeGatherXPerm2DKernel::new(ctx, data_type)?)
+ variant: if data_type == DataType::BF16 {
+ MoeGatherVariant::TwoD(<B::Kernels as Kernels>::MoeGatherXPerm2DKernel::new(ctx, data_type)?)
} else {
- MoeGatherKernelType::OneD(<B::Kernels as Kernels>::MoeGatherXPerm1DKernel::new(ctx, data_type)?)
+ MoeGatherVariant::OneD(<B::Kernels as Kernels>::MoeGatherXPerm1DKernel::new(ctx, data_type)?)
},
data_type,
})
@@ -46,8 +46,8 @@ impl<B: Backend> MoeGatherKernel<B> {
encoder.allocate_scratch(size_for_shape(&[batch_dim * num_active_experts, d_model], self.data_type))?;
encoder.encode_fill(&mut x_perm, 0);
- match &self.kernel {
- MoeGatherKernelType::OneD(kernel) => kernel.encode(
+ match &self.variant {
+ MoeGatherVariant::OneD(kernel) => kernel.encode(
input,
bucketed_ids,
&mut x_perm,
@@ -57,7 +57,7 @@ impl<B: Backend> MoeGatherKernel<B> {
num_active_experts as u32,
encoder,
),
- MoeGatherKernelType::TwoD(kernel) => kernel.encode(
+ MoeGatherVariant::TwoD(kernel) => kernel.encode(
input,
bucketed_ids,
&mut x_perm,
@@ -72,3 +72,7 @@ impl<B: Backend> MoeGatherKernel<B> {
Ok(x_perm)
}
}
+
+#[cfg(test)]
+#[path = "../../../../tests/unit/encodable_block/moe/moe_gather_test.rs"]
+mod tests;
diff --git a/crates/backend-uzu/src/encodable_block/mlp/moe.rs b/crates/backend-uzu/src/encodable_block/mlp/moe/mod.rs
similarity index 96%
rename from crates/backend-uzu/src/encodable_block/mlp/moe.rs
rename to crates/backend-uzu/src/encodable_block/mlp/moe/mod.rs
index 33e18c6b1..7f2d076ea 100644
--- a/crates/backend-uzu/src/encodable_block/mlp/moe.rs
+++ b/crates/backend-uzu/src/encodable_block/mlp/moe/mod.rs
@@ -1,5 +1,12 @@
//! MoE (Mixture of Experts) block encodable.
+mod experts_two_pass_decode;
+mod experts_two_pass_prefill;
+mod gather;
+
+use experts_two_pass_decode::MoeExpertsTwoPassDecodeBlock;
+use experts_two_pass_prefill::{MoeExpertsTwoPassArguments, MoeExpertsTwoPassPrefillBlock};
+use gather::MoeGather;
use thiserror::Error;
use crate::{
@@ -11,10 +18,6 @@ use crate::{
kernel::{
MoeBlockBasesFromPartialsKernel, MoeCountsOffsetsFusedKernel, MoeFinalizeKernel, MoeRouterTopKKernel,
MoeScatterBucketsMapKernel,
- moe::{
- MoeExpertsTwoPassArguments, MoeExpertsTwoPassDecodeBlock, MoeExpertsTwoPassPrefillBlock,
- MoeGatherKernel,
- },
},
},
config::{
@@ -30,7 +33,7 @@ pub struct MoeBlock<B: Backend> {
counts_offsets_kernel: <B::Kernels as Kernels>::MoeCountsOffsetsFusedKernel,
scatter_bases_kernel: <B::Kernels as Kernels>::MoeBlockBasesFromPartialsKernel,
scatter_map_kernel: <B::Kernels as Kernels>::MoeScatterBucketsMapKernel,
- gather_kernel: MoeGatherKernel<B>,
+ gather: MoeGather<B>,
experts_two_pass_decode_block: MoeExpertsTwoPassDecodeBlock<B>,
experts_two_pass_prefill_block: MoeExpertsTwoPassPrefillBlock<B>,
finalize_kernel: <B::Kernels as Kernels>::MoeFinalizeKernel,
@@ -164,7 +167,7 @@ impl<B: Backend> MoeBlock<B> {
let scatter_map_kernel = <B::Kernels as Kernels>::MoeScatterBucketsMapKernel::new(context, data_type)
.map_err(MoeBlockError::BackendError)?;
- let gather_kernels = MoeGatherKernel::new(context, data_type).map_err(MoeBlockError::BackendError)?;
+ let gather = MoeGather::new(context, data_type).map_err(MoeBlockError::BackendError)?;
let experts_two_pass_decode_block =
MoeExpertsTwoPassDecodeBlock::new(context, data_type, gating_code).map_err(MoeBlockError::BackendError)?;
let experts_two_pass_prefill_block =
@@ -180,7 +183,7 @@ impl<B: Backend> MoeBlock<B> {
counts_offsets_kernel,
scatter_bases_kernel,
scatter_map_kernel,
- gather_kernel: gather_kernels,
+ gather,
experts_two_pass_decode_block,
experts_two_pass_prefill_block,
finalize_kernel,
@@ -287,7 +290,7 @@ impl<B: Backend> Mlp<B> for MoeBlock<B> {
encoder,
);
- let x_perm = self.gather_kernel.encode(
+ let x_perm = self.gather.encode(
&input,
&bucketed_ids,
&sumk,
@@ -338,5 +341,5 @@ impl<B: Backend> Mlp<B> for MoeBlock<B> {
}
#[cfg(test)]
-#[path = "../../../tests/unit/encodable_block/moe/mod.rs"]
+#[path = "../../../../tests/unit/encodable_block/moe/mod.rs"]
mod tests;
diff --git a/crates/backend-uzu/src/encodable_block/mod.rs b/crates/backend-uzu/src/encodable_block/mod.rs
index 26942ab18..06adcf01f 100644
--- a/crates/backend-uzu/src/encodable_block/mod.rs
+++ b/crates/backend-uzu/src/encodable_block/mod.rs
@@ -3,11 +3,12 @@ mod classifier_layer;
mod decoder;
mod delta_net_mixer;
mod embedding;
+mod kv_cache_update;
mod layer;
mod layer_norm;
-pub(crate) mod linear;
+mod linear;
mod mamba_mixer;
-pub(crate) mod mlp;
+mod mlp;
mod normalization;
mod pooling;
mod prediction_head;
@@ -21,12 +22,13 @@ mod short_conv_mixer;
pub use attention::{Attention, AttentionError};
pub use classifier_layer::ClassifierLayer;
pub use decoder::{Decoder, DecoderArguments, DecoderDecodeInput};
-pub(crate) use delta_net_mixer::{DeltaNetArguments, DeltaNetMixer, DeltaNetMixerError};
+pub use delta_net_mixer::{DeltaNetArguments, DeltaNetMixer, DeltaNetMixerError};
pub use embedding::Embedding;
+pub use kv_cache_update::{KVCacheUpdate, KVLayerData};
pub use layer::{LayerArguments, LayerExecutables};
pub use layer_norm::{LayerNorm, LayerNormError};
pub use linear::Linear;
-pub(crate) use mamba_mixer::{MambaArguments, MambaMixer, MambaMixerError};
+pub use mamba_mixer::{MambaArguments, MambaMixer, MambaMixerError};
pub use mlp::{Mlp, MlpBlockError};
pub use normalization::{Normalization, NormalizationError};
pub use pooling::Pooling;
@@ -35,7 +37,5 @@ pub use qk_unpack::QkUnpack;
pub use qkv_norm::QKVNorm;
pub use rms_norm::{PostLayerScalar, RMSNorm, RMSNormError};
pub use rope::Rope;
-pub(crate) use sampling::SamplingInputs;
-pub use sampling::{Sampling, SamplingArguments};
-pub(crate) use short_conv_mixer::ShortConvArguments;
-pub use short_conv_mixer::{ShortConvMixer, ShortConvMixerError};
+pub use sampling::{Sampling, SamplingArguments, SamplingInputs};
+pub use short_conv_mixer::{ShortConvArguments, ShortConvMixer, ShortConvMixerError};
diff --git a/crates/backend-uzu/src/backends/common/kernel/sampling.rs b/crates/backend-uzu/src/encodable_block/sampling/block.rs
similarity index 62%
rename from crates/backend-uzu/src/backends/common/kernel/sampling.rs
rename to crates/backend-uzu/src/encodable_block/sampling/block.rs
index 34e78135f..19630fbbb 100644
--- a/crates/backend-uzu/src/backends/common/kernel/sampling.rs
+++ b/crates/backend-uzu/src/encodable_block/sampling/block.rs
@@ -8,63 +8,38 @@ use crate::{
Allocation, Backend, Encoder, Kernels,
gpu_types::ArgmaxPair,
kernel::{
- ArgmaxFinalKernel, ArgmaxMainKernel, ArgmaxSingleKernel, BitmaskKernel, GumbelKernel, MinPKernel,
- TemperatureKernel, TopKKernel, TopPKernel,
+ ArgmaxFinalKernel, ArgmaxMainKernel, BitmaskKernel, GumbelKernel, MinPKernel, TemperatureKernel,
+ TopKKernel, TopPKernel,
},
},
session::parameter::{SamplingMethod, SamplingProcessingOrder},
};
-#[derive(Debug, Clone, Copy, PartialEq)]
-pub enum ArgmaxStrategy {
- SinglePass, // One threadgroup per batch item
- TwoPass, // Two-stage reduction
-}
-
-enum ArgmaxImplementation<B: Backend> {
- SinglePass {
- kernel: <B::Kernels as Kernels>::ArgmaxSingleKernel,
- },
- TwoPass {
- main_kernel: <B::Kernels as Kernels>::ArgmaxMainKernel,
- final_kernel: <B::Kernels as Kernels>::ArgmaxFinalKernel,
- },
-}
-
-pub struct SamplingKernel<B: Backend> {
+pub struct SamplingBlock<B: Backend> {
bitmask: <B::Kernels as Kernels>::BitmaskKernel,
temperature: <B::Kernels as Kernels>::TemperatureKernel,
topk: <B::Kernels as Kernels>::TopKKernel,
topp: <B::Kernels as Kernels>::TopPKernel,
minp: <B::Kernels as Kernels>::MinPKernel,
gumbel: <B::Kernels as Kernels>::GumbelKernel,
- argmax_implementation: ArgmaxImplementation<B>,
+ argmax_main: <B::Kernels as Kernels>::ArgmaxMainKernel,
+ argmax_final: <B::Kernels as Kernels>::ArgmaxFinalKernel,
}
#[derive(Debug, Error)]
pub enum SamplingError<B: Backend> {
#[error("Backend error: {0}")]
BackendError(#[source] B::Error),
- #[error("Function not found: {0}")]
- FunctionNotFound(String),
#[error("batch size must be greater than 0")]
EmptyBatch,
#[error("vocab size must be greater than 0")]
EmptyVocab,
}
-impl<B: Backend> SamplingKernel<B> {
+impl<B: Backend> SamplingBlock<B> {
pub fn new(
context: &B::Context,
data_type: DataType,
- ) -> Result<Self, SamplingError<B>> {
- Self::new_with_strategy(context, data_type, ArgmaxStrategy::TwoPass)
- }
-
- pub fn new_with_strategy(
- context: &B::Context,
- data_type: DataType,
- argmax_strategy: ArgmaxStrategy,
) -> Result<Self, SamplingError<B>> {
let bitmask = <B::Kernels as Kernels>::BitmaskKernel::new(context, data_type, true)
.map_err(SamplingError::BackendError)?;
@@ -78,28 +53,10 @@ impl<B: Backend> SamplingKernel<B> {
<B::Kernels as Kernels>::MinPKernel::new(context, data_type, true).map_err(SamplingError::BackendError)?;
let gumbel = <B::Kernels as Kernels>::GumbelKernel::new(context, data_type, true)
.map_err(SamplingError::BackendError)?;
-
- let argmax_implementation = match argmax_strategy {
- ArgmaxStrategy::SinglePass => {
- let kernel = <B::Kernels as Kernels>::ArgmaxSingleKernel::new(context, data_type)
- .map_err(SamplingError::BackendError)?;
-
- ArgmaxImplementation::SinglePass {
- kernel,
- }
- },
- ArgmaxStrategy::TwoPass => {
- let main_kernel = <B::Kernels as Kernels>::ArgmaxMainKernel::new(context, data_type)
- .map_err(SamplingError::BackendError)?;
- let final_kernel =
- <B::Kernels as Kernels>::ArgmaxFinalKernel::new(context).map_err(SamplingError::BackendError)?;
-
- ArgmaxImplementation::TwoPass {
- main_kernel,
- final_kernel,
- }
- },
- };
+ let argmax_main =
+ <B::Kernels as Kernels>::ArgmaxMainKernel::new(context, data_type).map_err(SamplingError::BackendError)?;
+ let argmax_final =
+ <B::Kernels as Kernels>::ArgmaxFinalKernel::new(context).map_err(SamplingError::BackendError)?;
Ok(Self {
bitmask,
@@ -108,7 +65,8 @@ impl<B: Backend> SamplingKernel<B> {
topp,
minp,
gumbel,
- argmax_implementation,
+ argmax_main,
+ argmax_final,
})
}
@@ -217,29 +175,21 @@ impl<B: Backend> SamplingKernel<B> {
);
}
- match &self.argmax_implementation {
- ArgmaxImplementation::SinglePass {
- kernel,
- } => {
- kernel.encode(&*logits, sampled_tokens, batch_size as u32, vocab_size as u32, encoder);
- },
- ArgmaxImplementation::TwoPass {
- main_kernel,
- final_kernel,
- } => {
- let block_size = 1024;
- let grain_size = 4;
- let elements_per_group = block_size * grain_size;
- let vocab_groups_per_batch = vocab_size.div_ceil(elements_per_group);
- let partial_results_count = batch_size * vocab_groups_per_batch;
- let mut partial_results = encoder
- .allocate_scratch(partial_results_count * size_of::<ArgmaxPair>())
- .map_err(SamplingError::BackendError)?;
- main_kernel.encode(&*logits, &mut partial_results, batch_size as u32, vocab_size as u32, encoder);
- final_kernel.encode(&partial_results, sampled_tokens, batch_size as u32, vocab_size as u32, encoder);
- },
- }
+ let block_size = 1024;
+ let grain_size = 4;
+ let elements_per_group = block_size * grain_size;
+ let vocab_groups_per_batch = vocab_size.div_ceil(elements_per_group);
+ let partial_results_count = batch_size * vocab_groups_per_batch;
+ let mut partial_results = encoder
+ .allocate_scratch(partial_results_count * size_of::<ArgmaxPair>())
+ .map_err(SamplingError::BackendError)?;
+ self.argmax_main.encode(&*logits, &mut partial_results, batch_size as u32, vocab_size as u32, encoder);
+ self.argmax_final.encode(&partial_results, sampled_tokens, batch_size as u32, vocab_size as u32, encoder);
Ok(())
}
}
+
+#[cfg(test)]
+#[path = "../../../tests/unit/encodable_block/sampling_top_p_test.rs"]
+mod top_p_tests;
diff --git a/crates/backend-uzu/src/encodable_block/sampling.rs b/crates/backend-uzu/src/encodable_block/sampling/mod.rs
similarity index 82%
rename from crates/backend-uzu/src/encodable_block/sampling.rs
rename to crates/backend-uzu/src/encodable_block/sampling/mod.rs
index 47c2c30ca..cb53213a7 100644
--- a/crates/backend-uzu/src/encodable_block/sampling.rs
+++ b/crates/backend-uzu/src/encodable_block/sampling/mod.rs
@@ -1,19 +1,20 @@
-//! Sampling kernel encodable.
+//! Sampling encodable.
+mod block;
+
+use block::SamplingBlock;
+pub use block::SamplingError;
use ndarray::ArrayView2;
use crate::{
DataType,
array::{Array, ArrayContextExt},
- backends::common::{
- Allocation, Backend, Encoder,
- kernel::sampling::{SamplingError, SamplingKernel},
- },
+ backends::common::{Allocation, Backend, Encoder},
session::parameter::SamplingMethod,
};
pub struct Sampling<B: Backend> {
- kernel: SamplingKernel<B>,
+ block: SamplingBlock<B>,
}
pub struct SamplingArguments<'a, B: Backend> {
@@ -26,13 +27,13 @@ pub struct SamplingArguments<'a, B: Backend> {
pub vocab_size: usize,
}
-pub(crate) struct SamplingInputs<B: Backend> {
+pub struct SamplingInputs<B: Backend> {
pub seeds: Array<B>,
pub bitmask: Option<Array<B>>,
}
impl<B: Backend> SamplingInputs<B> {
- pub(crate) fn bitmask_array_from_slice(
+ pub fn bitmask_array_from_slice(
context: &B::Context,
row_count: usize,
token_bitmask: &[u32],
@@ -45,7 +46,7 @@ impl<B: Backend> SamplingInputs<B> {
array
}
- pub(crate) fn from_slices(
+ pub fn from_slices(
context: &B::Context,
token_seeds: &[u64],
token_bitmask: Option<&[u32]>,
@@ -73,9 +74,9 @@ impl<B: Backend> Sampling<B> {
context: &B::Context,
data_type: DataType,
) -> Result<Self, SamplingError<B>> {
- let kernel = SamplingKernel::new(context, data_type)?;
+ let block = SamplingBlock::new(context, data_type)?;
Ok(Self {
- kernel,
+ block,
})
}
@@ -84,7 +85,7 @@ impl<B: Backend> Sampling<B> {
args: SamplingArguments<B>,
encoder: &mut Encoder<B>,
) -> Result<(), SamplingError<B>> {
- self.kernel.encode(
+ self.block.encode(
args.logits,
args.seeds,
args.bitmask,
@@ -98,5 +99,5 @@ impl<B: Backend> Sampling<B> {
}
#[cfg(test)]
-#[path = "../../tests/unit/encodable_block/sampling_test.rs"]
+#[path = "../../../tests/unit/encodable_block/sampling_test.rs"]
mod tests;
diff --git a/crates/backend-uzu/src/forward_pass/cache_layers.rs b/crates/backend-uzu/src/forward_pass/cache_layers.rs
index 83292b51d..70b271b76 100644
--- a/crates/backend-uzu/src/forward_pass/cache_layers.rs
+++ b/crates/backend-uzu/src/forward_pass/cache_layers.rs
@@ -3,8 +3,9 @@ use std::cell::Cell;
use crate::{
DataType,
array::size_for_shape,
- backends::common::{AllocationType, Backend, Context, Encoder, kernel::kv_cache_update::KVCacheUpdate},
+ backends::common::{AllocationType, Backend, Context, Encoder},
config::token_mixer::AnyTokenMixerConfig,
+ encodable_block::KVCacheUpdate,
forward_pass::{
delta_net_layer::DeltaNetLayer,
kv_cache_layer::{KVCacheLayerState, KVCacheLayerTrait, KVSlice},
diff --git a/crates/backend-uzu/src/forward_pass/kv_cache_layer.rs b/crates/backend-uzu/src/forward_pass/kv_cache_layer.rs
index 5a769a090..bea96400b 100644
--- a/crates/backend-uzu/src/forward_pass/kv_cache_layer.rs
+++ b/crates/backend-uzu/src/forward_pass/kv_cache_layer.rs
@@ -3,10 +3,8 @@ use std::{any::Any, ops::Range};
use crate::{
DataType,
array::{Array, ArrayContextExt, size_for_shape},
- backends::common::{
- AsBufferRangeMut, AsBufferRangeRef, Backend, Buffer, Context, Encoder, SparseBuffer,
- kernel::kv_cache_update::{KVCacheUpdate, KVLayerData},
- },
+ backends::common::{AsBufferRangeMut, AsBufferRangeRef, Backend, Buffer, Context, Encoder, SparseBuffer},
+ encodable_block::{KVCacheUpdate, KVLayerData},
};
pub enum KVSlice<B: Backend> {
diff --git a/crates/backend-uzu/src/language_model/language_model_generator_context.rs b/crates/backend-uzu/src/language_model/language_model_generator_context.rs
index 79419832e..d4a82a291 100644
--- a/crates/backend-uzu/src/language_model/language_model_generator_context.rs
+++ b/crates/backend-uzu/src/language_model/language_model_generator_context.rs
@@ -9,12 +9,9 @@ use std::{
use crate::{
DataType,
array::{Array, ArrayContextExt},
- backends::common::{
- Backend, Context, Kernels,
- kernel::{TokenCopySampledKernel, kv_cache_update::KVCacheUpdate},
- },
+ backends::common::{Backend, Context, Kernels, kernel::TokenCopySampledKernel},
config::{decoder::DecoderConfig, model::language_model::LanguageModelConfig},
- encodable_block::{Decoder, Sampling},
+ encodable_block::{Decoder, KVCacheUpdate, Sampling},
forward_pass::{cache_layers::CacheLayers, model_shape::ModelShape, state::SharedBuffers},
language_model::rng::PRng,
parameters::ParameterLoader,
diff --git a/crates/backend-uzu/src/session/tts_session.rs b/crates/backend-uzu/src/session/tts_session.rs
index 09f2a0b32..c1f4e1db7 100644
--- a/crates/backend-uzu/src/session/tts_session.rs
+++ b/crates/backend-uzu/src/session/tts_session.rs
@@ -34,12 +34,11 @@ use crate::{
Backend, Context as BackendContext, Encoder, Kernels,
kernel::{
EmbeddingRowsSumKernel, ManualKernels, TensorAddScaleKernel, TokenCopySampledKernel,
- kv_cache_update::KVCacheUpdate,
matmul::{MatmulArguments, MatmulB, MatmulDOps, MatmulKernel},
},
},
config::{model::tts_model::TTSModelConfig, token_codec::tts_codec::TTSCodecConfig},
- encodable_block::{Decoder, Sampling as GpuSampling},
+ encodable_block::{Decoder, KVCacheUpdate, Sampling as GpuSampling},
forward_pass::{cache_layers::CacheLayers, model_shape::ModelShape, state::SharedBuffers},
parameters::ParameterLoader,
session::{
diff --git a/crates/backend-uzu/tests/integration/tracer/trace_validator.rs b/crates/backend-uzu/tests/integration/tracer/trace_validator.rs
index 4d9977880..715ad141e 100644
--- a/crates/backend-uzu/tests/integration/tracer/trace_validator.rs
+++ b/crates/backend-uzu/tests/integration/tracer/trace_validator.rs
@@ -16,10 +16,10 @@ use std::{
use backend_uzu::{
_private::{
ActivationTrace, AnyModelConfig, ArgmaxSampler, CacheLayers, Classifier, DecoderDecodeInput, KVCacheLayer,
- LanguageModelGeneratorContext, LogitsSampler, ParameterLoaderError, ParameterTree, Sampling, TokenInputs,
+ LanguageModelGeneratorContext, LogitsSampler, ParameterLoaderError, ParameterTree, TokenInputs,
},
Array, ArrayElement, DataType, ParameterLoader,
- backends::common::{Allocation, AllocationType, Backend, Context, Encoder, kernel::kv_cache_update::KVCacheUpdate},
+ backends::common::{Allocation, AllocationType, Backend, Context, Encoder},
read_safetensors_metadata,
session::{
config::{DecodingConfig, SpeculatorConfig},
@@ -1001,14 +1001,6 @@ impl<B: Backend> TraceValidator<B> {
resolved_prefix_length,
desired_suffix_length,
)));
-
- context.kv_cache_update = Box::new(
- KVCacheUpdate::new(context.context.as_ref(), context.model_shape.data_type, resolved_prefix_length)
- .expect("Failed to create KV cache update kernel"),
- );
-
- context.gpu_sampler = Sampling::new(context.context.as_ref(), context.model_shape.data_type)
- .expect("Failed to create sampling kernel");
}
fn get_tokens_from_logits(logits: &Array<B>) -> Vec<u64> {
diff --git a/crates/backend-uzu/tests/performance/encodable_block/mod.rs b/crates/backend-uzu/tests/performance/encodable_block/mod.rs
deleted file mode 100644
index 8ea0dc867..000000000
--- a/crates/backend-uzu/tests/performance/encodable_block/mod.rs
+++ /dev/null
@@ -1 +0,0 @@
-mod moe;
diff --git a/crates/backend-uzu/tests/performance/encodable_block/moe/mod.rs b/crates/backend-uzu/tests/performance/encodable_block/moe/mod.rs
deleted file mode 100644
index 9dbe3439b..000000000
--- a/crates/backend-uzu/tests/performance/encodable_block/moe/mod.rs
+++ /dev/null
@@ -1,2 +0,0 @@
-mod moe_experts_perf_test;
-mod moe_perf_test;
diff --git a/crates/backend-uzu/tests/performance/encodable_block/moe/moe_experts_perf_test.rs b/crates/backend-uzu/tests/performance/encodable_block/moe/moe_experts_perf_test.rs
index 08dd1a400..e97cf3246 100644
--- a/crates/backend-uzu/tests/performance/encodable_block/moe/moe_experts_perf_test.rs
+++ b/crates/backend-uzu/tests/performance/encodable_block/moe/moe_experts_perf_test.rs
@@ -1,19 +1,19 @@
use std::time::Instant;
-use backend_uzu::{
- DataType,
- backends::common::{
- Backend, Encoder,
- kernel::moe::{
- MoeExpertsSingleDecodeArguments, MoeExpertsSingleDecodeKernels, MoeExpertsTwoPassArguments,
- MoeExpertsTwoPassDecodeBlock, MoeExpertsTwoPassPrefillBlock,
- },
- },
-};
use half::bf16;
use rand::{RngExt, SeedableRng, rngs::StdRng};
-use crate::common::helpers::{alloc_allocation_with_data, create_context};
+use super::{MoeExpertsTwoPassArguments, MoeExpertsTwoPassDecodeBlock, MoeExpertsTwoPassPrefillBlock};
+use crate::{
+ DataType,
+ backends::common::{Backend, Encoder},
+};
+
+#[macro_use]
+#[path = "../../../common/mod.rs"]
+mod common;
+
+use common::helpers::{alloc_allocation_with_data, create_context};
fn build_offsets(
e: usize,
@@ -268,326 +268,6 @@ fn run_two_pass_prefill_case<B: Backend>(
eprintln!(" → Throughput: {:.1} µs/token (mean / sum_k)", (mean / sum_k as f64) * 1000.0);
}
-fn run_fused_single_token_case<B: Backend>(
- ctx: &B::Context,
- name: &str,
- d_model: usize,
- d_ff: usize,
- e: usize,
- k: usize,
- warmup: usize,
- iters: usize,
-) {
- let mut rng = StdRng::seed_from_u64(0xF053ED);
-
- eprintln!("\n[fused single-token] {} => D={}, FF={}, E={}, K={}", name, d_model, d_ff, e, k);
-
- let x: Vec<bf16> = (0..d_model).map(|_| bf16::from_f32(rng.random_range(-1.0..1.0))).collect();
-
- let topk_ids: Vec<i32> = (0..k).map(|i| (i % e) as i32).collect();
-
- let topk_probs: Vec<bf16> = {
- let raw: Vec<f32> = (0..k).map(|_| rng.random_range(0.1..1.0)).collect();
- let sum: f32 = raw.iter().sum();
- raw.iter().map(|p| bf16::from_f32(p / sum)).collect()
- };
-
- let w13_all: Vec<bf16> =
- (0..e * 2 * d_ff * d_model).map(|_| bf16::from_f32(rng.random_range(-0.05..0.05))).collect();
- let w2_all: Vec<bf16> = (0..e * d_ff * d_model).map(|_| bf16::from_f32(rng.random_range(-0.05..0.05))).collect();
- let up_biases: Vec<bf16> = (0..e * 2 * d_ff).map(|_| bf16::from_f32(rng.random_range(-0.01..0.01))).collect();
- let down_biases: Vec<bf16> = (0..e * d_model).map(|_| bf16::from_f32(rng.random_range(-0.01..0.01))).collect();
-
- let fused_kernel = MoeExpertsSingleDecodeKernels::<B>::new(ctx, DataType::BF16, 2).expect("fused kernel");
-
- let x_buf = alloc_allocation_with_data::<B, bf16>(ctx, &x);
- let topk_ids_buf = alloc_allocation_with_data::<B, i32>(ctx, &topk_ids);
- let topk_probs_buf = alloc_allocation_with_data::<B, bf16>(ctx, &topk_probs);
- let w13_buf = alloc_allocation_with_data::<B, bf16>(ctx, &w13_all);
- let w2_buf = alloc_allocation_with_data::<B, bf16>(ctx, &w2_all);
- let up_biases_buf = alloc_allocation_with_data::<B, bf16>(ctx, &up_biases);
- let down_biases_buf = alloc_allocation_with_data::<B, bf16>(ctx, &down_biases);
- for _ in 0..warmup {
- let mut encoder = Encoder::new(ctx).expect("Failed to create encoder");
- let output = fused_kernel
- .encode(
- MoeExpertsSingleDecodeArguments {
- x: &x_buf,
- topk_ids: &topk_ids_buf,
- topk_probs: &topk_probs_buf,
- w13_all: &w13_buf,
- w2_all: &w2_buf,
- up_biases: &up_biases_buf,
- down_biases: &down_biases_buf,
- d_model,
- d_ff,
- k,
- silu_alpha: 1.0,
- gate_clip_min: f32::NEG_INFINITY,
- gate_clip_max: f32::INFINITY,
- up_clip_min: f32::NEG_INFINITY,
- up_clip_max: f32::INFINITY,
- },
- &mut encoder,
- )
- .expect("failed to encode MoE experts");
- let completed = encoder.end_encoding().submit().wait_until_completed().unwrap();
- drop(output);
- drop(completed);
- }
-
- let mut times = Vec::with_capacity(iters);
- for _ in 0..iters {
- let start = Instant::now();
- let mut encoder = Encoder::new(ctx).expect("Failed to create encoder");
- let output = fused_kernel
- .encode(
- MoeExpertsSingleDecodeArguments {
- x: &x_buf,
- topk_ids: &topk_ids_buf,
- topk_probs: &topk_probs_buf,
- w13_all: &w13_buf,
- w2_all: &w2_buf,
- up_biases: &up_biases_buf,
- down_biases: &down_biases_buf,
- d_model,
- d_ff,
- k,
- silu_alpha: 1.0,
- gate_clip_min: f32::NEG_INFINITY,
- gate_clip_max: f32::INFINITY,
- up_clip_min: f32::NEG_INFINITY,
- up_clip_max: f32::INFINITY,
- },
- &mut encoder,
- )
- .expect("failed to encode MoE experts");
- let completed = encoder.end_encoding().submit().wait_until_completed().unwrap();
- drop(output);
- drop(completed);
- times.push(start.elapsed().as_secs_f64() * 1000.0);
- }
-
- times.sort_by(|a, b| a.partial_cmp(b).unwrap());
- let mean = times.iter().sum::<f64>() / times.len() as f64;
- let median = times[times.len() / 2];
- let min = times[0];
- let max = times[times.len() - 1];
- let var = times.iter().map(|t| (t - mean).powi(2)).sum::<f64>() / times.len() as f64;
- let std = var.sqrt();
-
- eprintln!(" mean={:.3}ms median={:.3}ms min={:.3}ms max={:.3}ms std={:.3}ms", mean, median, min, max, std);
- eprintln!(" → Latency: {:.1} µs/token", mean * 1000.0);
-}
-
-fn run_indirect_decode_timed<B: Backend>(
- ctx: &B::Context,
- t: usize,
- d_model: usize,
- d_ff: usize,
- e: usize,
- k: usize,
- warmup: usize,
- iters: usize,
-) -> f64 {
- let mut rng = StdRng::seed_from_u64(0xDEC0DE1234567890);
- let sum_k = t * k;
-
- let x_perm: Vec<bf16> = (0..sum_k * d_model).map(|_| bf16::from_f32(rng.random_range(-1.0..1.0))).collect();
- let offsets = build_offsets(e, sum_k);
-
- let w13_original: Vec<bf16> =
- (0..e * d_model * 2 * d_ff).map(|_| bf16::from_f32(rng.random_range(-0.05..0.05))).collect();
-
- let mut w13 = vec![bf16::from_f32(0.0); e * d_model * 2 * d_ff];
- for expert in 0..e {
- let src_offset = expert * d_model * 2 * d_ff;
- let dst_offset = expert * 2 * d_ff * d_model;
- for dm in 0..d_model {
- for ff in 0..(2 * d_ff) {
- let src_idx = src_offset + dm * 2 * d_ff + ff;
- let dst_idx = dst_offset + ff * d_model + dm;
- w13[dst_idx] = w13_original[src_idx];
- }
- }
- }
- let w2: Vec<bf16> = (0..e * d_ff * d_model).map(|_| bf16::from_f32(rng.random_range(-0.05..0.05))).collect();
- let up_biases: Vec<bf16> = (0..e * 2 * d_ff).map(|_| bf16::from_f32(rng.random_range(-0.01..0.01))).collect();
- let down_biases: Vec<bf16> = (0..e * d_model).map(|_| bf16::from_f32(rng.random_range(-0.01..0.01))).collect();
-
- let experts_kernel = MoeExpertsTwoPassDecodeBlock::<B>::new(ctx, DataType::BF16, 2).expect("decode kernel");
-
- let x_perm_buf = alloc_allocation_with_data::<B, bf16>(ctx, &x_perm);
- let offsets_buf = alloc_allocation_with_data::<B, u32>(ctx, &offsets);
- let w13_buf = alloc_allocation_with_data::<B, bf16>(ctx, &w13);
- let w2_buf = alloc_allocation_with_data::<B, bf16>(ctx, &w2);
- let up_biases_buf = alloc_allocation_with_data::<B, bf16>(ctx, &up_biases);
- let down_biases_buf = alloc_allocation_with_data::<B, bf16>(ctx, &down_biases);
-
- for _ in 0..warmup {
- let mut encoder = Encoder::new(ctx).expect("Failed to create encoder");
- let output = experts_kernel
- .encode(
- MoeExpertsTwoPassArguments {
- x_perm: &x_perm_buf,
- expert_offsets: &offsets_buf,
- w13_all: &w13_buf,
- w2_all: &w2_buf,
- up_biases: &up_biases_buf,
- down_biases: &down_biases_buf,
- total_rows: sum_k,
- d_model,
- d_ff,
- num_routed_experts: e,
- gate_clip_min: f32::NEG_INFINITY,
- gate_clip_max: f32::INFINITY,
- up_clip_min: f32::NEG_INFINITY,
- up_clip_max: f32::INFINITY,
- silu_alpha: 1.0,
- },
- &mut encoder,
- )
- .expect("failed to encode MoE experts");
- let completed = encoder.end_encoding().submit().wait_until_completed().unwrap();
- drop(output);
- drop(completed);
- }
-
- let mut times = Vec::with_capacity(iters);
- for _ in 0..iters {
- let start = Instant::now();
- let mut encoder = Encoder::new(ctx).expect("Failed to create encoder");
- let output = experts_kernel
- .encode(
- MoeExpertsTwoPassArguments {
- x_perm: &x_perm_buf,
- expert_offsets: &offsets_buf,
- w13_all: &w13_buf,
- w2_all: &w2_buf,
- up_biases: &up_biases_buf,
- down_biases: &down_biases_buf,
- total_rows: sum_k,
- d_model,
- d_ff,
- num_routed_experts: e,
- gate_clip_min: f32::NEG_INFINITY,
- gate_clip_max: f32::INFINITY,
- up_clip_min: f32::NEG_INFINITY,
- up_clip_max: f32::INFINITY,
- silu_alpha: 1.0,
- },
- &mut encoder,
- )
- .expect("failed to encode MoE experts");
- let completed = encoder.end_encoding().submit().wait_until_completed().unwrap();
- drop(output);
- drop(completed);
- times.push(start.elapsed().as_secs_f64() * 1000.0);
- }
-
- times.iter().sum::<f64>() / times.len() as f64
-}
-
-fn run_fused_decode_timed<B: Backend>(
- ctx: &B::Context,
- d_model: usize,
- d_ff: usize,
- e: usize,
- k: usize,
- warmup: usize,
- iters: usize,
-) -> f64 {
- let mut rng = StdRng::seed_from_u64(0xF053ED);
-
- let x: Vec<bf16> = (0..d_model).map(|_| bf16::from_f32(rng.random_range(-1.0..1.0))).collect();
-
- let topk_ids: Vec<i32> = (0..k).map(|i| (i % e) as i32).collect();
-
- let topk_probs: Vec<bf16> = {
- let raw: Vec<f32> = (0..k).map(|_| rng.random_range(0.1..1.0)).collect();
- let sum: f32 = raw.iter().sum();
- raw.iter().map(|p| bf16::from_f32(p / sum)).collect()
- };
-
- let w13_all: Vec<bf16> =
- (0..e * 2 * d_ff * d_model).map(|_| bf16::from_f32(rng.random_range(-0.05..0.05))).collect();
- let w2_all: Vec<bf16> = (0..e * d_ff * d_model).map(|_| bf16::from_f32(rng.random_range(-0.05..0.05))).collect();
- let up_biases: Vec<bf16> = (0..e * 2 * d_ff).map(|_| bf16::from_f32(rng.random_range(-0.01..0.01))).collect();
- let down_biases: Vec<bf16> = (0..e * d_model).map(|_| bf16::from_f32(rng.random_range(-0.01..0.01))).collect();
-
- let fused_kernel = MoeExpertsSingleDecodeKernels::<B>::new(ctx, DataType::BF16, 2).expect("fused kernel");
-
- let x_buf = alloc_allocation_with_data::<B, bf16>(ctx, &x);
- let topk_ids_buf = alloc_allocation_with_data::<B, i32>(ctx, &topk_ids);
- let topk_probs_buf = alloc_allocation_with_data::<B, bf16>(ctx, &topk_probs);
- let w13_buf = alloc_allocation_with_data::<B, bf16>(ctx, &w13_all);
- let w2_buf = alloc_allocation_with_data::<B, bf16>(ctx, &w2_all);
- let up_biases_buf = alloc_allocation_with_data::<B, bf16>(ctx, &up_biases);
- let down_biases_buf = alloc_allocation_with_data::<B, bf16>(ctx, &down_biases);
- for _ in 0..warmup {
- let mut encoder = Encoder::new(ctx).expect("Failed to create encoder");
- let output = fused_kernel
- .encode(
- MoeExpertsSingleDecodeArguments {
- x: &x_buf,
- topk_ids: &topk_ids_buf,
- topk_probs: &topk_probs_buf,
- w13_all: &w13_buf,
- w2_all: &w2_buf,
- up_biases: &up_biases_buf,
- down_biases: &down_biases_buf,
- d_model,
- d_ff,
- k,
- silu_alpha: 1.0,
- gate_clip_min: f32::NEG_INFINITY,
- gate_clip_max: f32::INFINITY,
- up_clip_min: f32::NEG_INFINITY,
- up_clip_max: f32::INFINITY,
- },
- &mut encoder,
- )
- .expect("failed to encode MoE experts");
- let completed = encoder.end_encoding().submit().wait_until_completed().unwrap();
- drop(output);
- drop(completed);
- }
-
- let mut times = Vec::with_capacity(iters);
- for _ in 0..iters {
- let start = Instant::now();
- let mut encoder = Encoder::new(ctx).expect("Failed to create encoder");
- let output = fused_kernel
- .encode(
- MoeExpertsSingleDecodeArguments {
- x: &x_buf,
- topk_ids: &topk_ids_buf,
- topk_probs: &topk_probs_buf,
- w13_all: &w13_buf,
- w2_all: &w2_buf,
- up_biases: &up_biases_buf,
- down_biases: &down_biases_buf,
- d_model,
- d_ff,
- k,
- silu_alpha: 1.0,
- gate_clip_min: f32::NEG_INFINITY,
- gate_clip_max: f32::INFINITY,
- up_clip_min: f32::NEG_INFINITY,
- up_clip_max: f32::INFINITY,
- },
- &mut encoder,
- )
- .expect("failed to encode MoE experts");
- let completed = encoder.end_encoding().submit().wait_until_completed().unwrap();
- drop(output);
- drop(completed);
- times.push(start.elapsed().as_secs_f64() * 1000.0);
- }
-
- times.iter().sum::<f64>() / times.len() as f64
-}
-
#[test]
#[ignore]
fn test_two_pass_decode_speed() {
@@ -622,54 +302,3 @@ fn test_two_pass_prefill_speed() {
}
})
}
-
-#[test]
-#[ignore]
-fn test_fused_single_token_speed() {
- for_each_non_cpu_backend!(|B| {
- let ctx = create_context::<B>();
-
- let cases = vec![
- ("E16_D1024_F4096_K4", 1024, 4096, 16, 4, 3, 20),
- ("E8_D2048_F8192_K4", 2048, 8192, 8, 4, 3, 20),
- ("E8_D512_F2048_K2", 512, 2048, 8, 2, 3, 20),
- ];
-
- for (name, d_model, d_ff, e, k, warmup, iters) in cases {
- run_fused_single_token_case::<B>(&ctx, name, d_model, d_ff, e, k, warmup, iters);
- }
- });
-}
-
-/// Compare indirect decode vs fused decode for single-token (T=1)
-#[test]
-#[ignore]
-fn test_single_token_indirect_vs_fused() {
- for_each_non_cpu_backend!(|B| {
- let ctx = create_context::<B>();
-
- let cases = vec![
- ("E8_D512_F2048_K2", 512, 2048, 8, 2),
- ("E16_D1024_F4096_K4", 1024, 4096, 16, 4),
- ("E8_D2048_F8192_K4", 2048, 8192, 8, 4),
- ];
-
- eprintln!("\n=== Single-Token Decode: Indirect vs Fused ===\n");
-
- for (name, d_model, d_ff, e, k) in cases {
- let warmup = 3;
- let iters = 20;
-
- eprintln!("[{}] D={}, FF={}, E={}, K={}", name, d_model, d_ff, e, k);
-
- // Run indirect decode (T=1)
- let indirect_mean = run_indirect_decode_timed::<B>(&ctx, 1, d_model, d_ff, e, k, warmup, iters);
-
- // Run fused decode
- let fused_mean = run_fused_decode_timed::<B>(&ctx, d_model, d_ff, e, k, warmup, iters);
-
- let speedup = indirect_mean / fused_mean;
- eprintln!(" Indirect: {:.3}ms, Fused: {:.3}ms, Speedup: {:.2}x\n", indirect_mean, fused_mean, speedup);
- }
- });
-}
diff --git a/crates/backend-uzu/tests/performance/encodable_block/moe/moe_perf_test.rs b/crates/backend-uzu/tests/performance/encodable_block/moe/moe_perf_test.rs
index 8b9da4b14..040c1e23d 100644
--- a/crates/backend-uzu/tests/performance/encodable_block/moe/moe_perf_test.rs
+++ b/crates/backend-uzu/tests/performance/encodable_block/moe/moe_perf_test.rs
@@ -1,18 +1,23 @@
-use backend_uzu::{
+use half::bf16;
+use rand::{RngExt, SeedableRng, rngs::StdRng};
+
+use super::{MoeExpertsTwoPassArguments, MoeExpertsTwoPassDecodeBlock, MoeGather};
+use crate::{
DataType,
backends::common::{
Backend, Encoder, Kernels,
kernel::{
MoeBlockBasesFromPartialsKernel, MoeCountsOffsetsFusedKernel, MoeFinalizeKernel, MoeRouterTopKKernel,
MoeScatterBucketsMapKernel,
- moe::{MoeExpertsTwoPassArguments, MoeExpertsTwoPassDecodeBlock, MoeGatherKernel},
},
},
};
-use half::bf16;
-use rand::{RngExt, SeedableRng, rngs::StdRng};
-use crate::common::{
+#[macro_use]
+#[path = "../../../common/mod.rs"]
+mod common;
+
+use common::{
helpers::{alloc_allocation, alloc_allocation_with_data, create_context},
perf::run_perf_with_warmup,
};
@@ -210,7 +215,7 @@ fn test_moe_pipeline_breakdown_decode() {
let scatter_map_kernel =
<<B as Backend>::Kernels as Kernels>::MoeScatterBucketsMapKernel::new(&ctx, DataType::BF16)
.expect("<<Metal as Backend>::Kernels as Kernels>::MoeScatterBucketsMapKernel");
- let gather_kernel = MoeGatherKernel::<B>::new(&ctx, DataType::BF16).expect("gather");
+ let gather = MoeGather::<B>::new(&ctx, DataType::BF16).expect("gather");
let experts_kernel =
MoeExpertsTwoPassDecodeBlock::<B>::new(&ctx, DataType::BF16, 2).expect("experts two-pass decode");
let finalize_kernel =
@@ -286,7 +291,7 @@ fn test_moe_pipeline_breakdown_decode() {
let gather_perf = run_perf_with_warmup("Gather", 2, 5, || {
let mut encoder = Encoder::new(ctx.as_ref()).expect("Failed to create encoder");
- let x_perm = gather_kernel
+ let x_perm = gather
.encode(&x_buf, &bucketed_ids_buf, &sumk_buf, t, k, d_model, &mut encoder)
.expect("failed to encode MoE gather");
let completed = encoder.end_encoding().submit().wait_until_completed().unwrap();
@@ -296,7 +301,7 @@ fn test_moe_pipeline_breakdown_decode() {
let (x_perm_buf, x_perm_completed) = {
let mut encoder = Encoder::new(ctx.as_ref()).expect("Failed to create encoder");
- let x_perm = gather_kernel
+ let x_perm = gather
.encode(&x_buf, &bucketed_ids_buf, &sumk_buf, t, k, d_model, &mut encoder)
.expect("failed to encode MoE gather");
let completed = encoder.end_encoding().submit().wait_until_completed().unwrap();
diff --git a/crates/backend-uzu/tests/performance/mod.rs b/crates/backend-uzu/tests/performance/mod.rs
index a980f17d8..b975c0c04 100644
--- a/crates/backend-uzu/tests/performance/mod.rs
+++ b/crates/backend-uzu/tests/performance/mod.rs
@@ -3,5 +3,4 @@
mod common;
mod audio_kernel_perf_test;
-mod encodable_block;
mod model_loading_perf_test;
diff --git a/crates/backend-uzu/tests/unit/kernel/attention/attention_gemm_test.rs b/crates/backend-uzu/tests/unit/encodable_block/attention_gemm_test.rs
similarity index 92%
rename from crates/backend-uzu/tests/unit/kernel/attention/attention_gemm_test.rs
rename to crates/backend-uzu/tests/unit/encodable_block/attention_gemm_test.rs
index be3989145..b91b36427 100644
--- a/crates/backend-uzu/tests/unit/kernel/attention/attention_gemm_test.rs
+++ b/crates/backend-uzu/tests/unit/encodable_block/attention_gemm_test.rs
@@ -3,22 +3,22 @@ use std::fmt::{Debug, Display};
use backend_uzu::{
ArrayElement, DataType,
backends::{
- common::{
- Allocation, Backend, Context, Encoder,
- kernel::attention::{AttentionGemmArguments, AttentionGemmBlock},
- },
+ common::{Allocation, Backend, Context, Encoder},
cpu::Cpu,
},
};
use half::{bf16, f16};
use num_traits::Float;
-use crate::{
- common::{
- assert::assert_eq_float,
- helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec},
- },
- uzu_test,
+use super::{AttentionGemmArguments, AttentionGemmBlock};
+
+#[macro_use]
+#[path = "../../common/mod.rs"]
+mod common;
+
+use common::{
+ assert::assert_eq_float,
+ helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec},
};
struct Input<T: ArrayElement + Float> {
@@ -108,7 +108,6 @@ fn get_output<T: ArrayElement + Float, B: Backend>(input: &Input<T>) -> Vec<T> {
suffix_length: input.suffix_length,
sequence_length: input.sequence_length,
segment_prefix_length,
- max_sequence_length: input.sequence_length,
ring_params: None,
head_dim: input.head_dim,
sliding_window_size: None,
@@ -199,81 +198,81 @@ fn test_unaligned<T: ArrayElement + Float + Debug + Display>() {
}
// Basic tests
-#[uzu_test]
+#[test]
fn test_basic_f32() {
test_basic::<f32>();
}
-#[uzu_test]
+#[test]
fn test_basic_f16() {
test_basic::<f16>();
}
-#[uzu_test]
+#[test]
fn test_basic_bf16() {
test_basic::<bf16>();
}
// Causal tests
-#[uzu_test]
+#[test]
fn test_causal_f32() {
test_causal::<f32>();
}
-#[uzu_test]
+#[test]
fn test_causal_f16() {
test_causal::<f16>();
}
-#[uzu_test]
+#[test]
fn test_causal_bf16() {
test_causal::<bf16>();
}
// GQA tests
-#[uzu_test]
+#[test]
fn test_gqa_f32() {
test_gqa::<f32>();
}
-#[uzu_test]
+#[test]
fn test_gqa_f16() {
test_gqa::<f16>();
}
-#[uzu_test]
+#[test]
fn test_gqa_bf16() {
test_gqa::<bf16>();
}
// Head dim 128
-#[uzu_test]
+#[test]
fn test_head_dim_128_f32() {
test_head_dim::<f32>(128);
}
-#[uzu_test]
+#[test]
fn test_head_dim_128_f16() {
test_head_dim::<f16>(128);
}
-#[uzu_test]
+#[test]
fn test_head_dim_128_bf16() {
test_head_dim::<bf16>(128);
}
// Unaligned tests
-#[uzu_test]
+#[test]
fn test_unaligned_f32() {
test_unaligned::<f32>();
}
-#[uzu_test]
+#[test]
fn test_unaligned_f16() {
test_unaligned::<f16>();
}
-#[uzu_test]
+#[test]
fn test_unaligned_bf16() {
test_unaligned::<bf16>();
}
diff --git a/crates/backend-uzu/tests/unit/encodable_block/attention_test.rs b/crates/backend-uzu/tests/unit/encodable_block/attention_test.rs
index 0122377f3..66ffda5cb 100644
--- a/crates/backend-uzu/tests/unit/encodable_block/attention_test.rs
+++ b/crates/backend-uzu/tests/unit/encodable_block/attention_test.rs
@@ -3,15 +3,13 @@
use ndarray::{Array4, s};
use test_tag::tag;
+use super::{AttentionGemmArguments, AttentionGemmBlock};
use crate::{
DataType,
backends::{
common::{
Allocation, Backend, Context, Encoder, Kernels,
- kernel::{
- AttentionSinglePassKernel, AttentionTwoPass1Kernel, AttentionTwoPass2Kernel,
- attention::{AttentionGemmArguments, AttentionGemmBlock},
- },
+ kernel::{AttentionSinglePassKernel, AttentionTwoPass1Kernel, AttentionTwoPass2Kernel},
},
metal::Metal,
},
@@ -340,7 +338,6 @@ fn run_gemm_attention(
suffix_length: seq_len,
sequence_length: seq_len,
segment_prefix_length: 0,
- max_sequence_length: seq_len,
ring_params: None,
head_dim,
sliding_window_size: None,
diff --git a/crates/backend-uzu/tests/unit/backends/common/kernel/kv_cache_update_test.rs b/crates/backend-uzu/tests/unit/encodable_block/kv_cache_update_test.rs
similarity index 99%
rename from crates/backend-uzu/tests/unit/backends/common/kernel/kv_cache_update_test.rs
rename to crates/backend-uzu/tests/unit/encodable_block/kv_cache_update_test.rs
index 9b7ea8237..a3b53f41c 100644
--- a/crates/backend-uzu/tests/unit/backends/common/kernel/kv_cache_update_test.rs
+++ b/crates/backend-uzu/tests/unit/encodable_block/kv_cache_update_test.rs
@@ -1,7 +1,7 @@
#![cfg(metal_backend)]
#[macro_use]
-#[path = "../../../../common/mod.rs"]
+#[path = "../../common/mod.rs"]
mod common;
use ndarray::{Array, Array3, s};
diff --git a/crates/backend-uzu/tests/unit/backends/common/kernel/ssd_prefill_test.rs b/crates/backend-uzu/tests/unit/encodable_block/mamba_mixer/ssd_prefill_test.rs
similarity index 95%
rename from crates/backend-uzu/tests/unit/backends/common/kernel/ssd_prefill_test.rs
rename to crates/backend-uzu/tests/unit/encodable_block/mamba_mixer/ssd_prefill_test.rs
index 92092e1ce..575339abb 100644
--- a/crates/backend-uzu/tests/unit/backends/common/kernel/ssd_prefill_test.rs
+++ b/crates/backend-uzu/tests/unit/encodable_block/mamba_mixer/ssd_prefill_test.rs
@@ -1,17 +1,13 @@
+use super::{SSDPrefillArguments, SSDPrefillBlock, SSDPrefillMode};
use crate::{
DataType,
backends::common::{
- Allocation, Backend, Context, Encoder, Kernels,
- gpu_types::ActivationType,
- kernel::{
- Conv1dScanKernel,
- ssd_prefill::{SSDPrefillArguments, SSDPrefillKernels, SSDPrefillMode},
- },
+ Allocation, Backend, Context, Encoder, Kernels, gpu_types::ActivationType, kernel::Conv1dScanKernel,
},
};
#[macro_use]
-#[path = "../../../../common/mod.rs"]
+#[path = "../../../common/mod.rs"]
mod common;
use common::helpers::allocation_to_vec;
@@ -150,7 +146,7 @@ impl SSDPrefillFixture {
fn run_prefill_kernel_mode<B: Backend>(
ctx: &B::Context,
- kernel: &SSDPrefillKernels<B>,
+ block: &SSDPrefillBlock<B>,
fixture: &SSDPrefillFixture,
mode: SSDPrefillMode,
) -> (Vec<f32>, Vec<f32>, Option<(Vec<f32>, Vec<f32>, Vec<f32>, Vec<f32>)>) {
@@ -182,7 +178,7 @@ fn run_prefill_kernel_mode<B: Backend>(
};
let mut encoder = Encoder::new(ctx).unwrap();
- let y_buf = kernel.encode(&mut encoder, args, mode).expect("Failed to encode SSD prefill");
+ let y_buf = block.encode(&mut encoder, args, mode).expect("Failed to encode SSD prefill");
let completed = encoder.end_encoding().submit().wait_until_completed().unwrap();
let y_vec = allocation_to_vec::<B, f32>(&y_buf);
@@ -273,11 +269,11 @@ fn assert_deterministic_for_mode<B: Backend>(mode: SSDPrefillMode) {
eprintln!("Skipping SSD prefill determinism test: no Metal device");
return;
};
- let kernel = SSDPrefillKernels::<B>::new(&ctx, DataType::F32).unwrap();
+ let block = SSDPrefillBlock::<B>::new(&ctx, DataType::F32).unwrap();
let fixture = SSDPrefillFixture::new();
- let (y_a, state_a, _) = run_prefill_kernel_mode::<B>(&ctx, &kernel, &fixture, mode);
- let (y_b, state_b, _) = run_prefill_kernel_mode::<B>(&ctx, &kernel, &fixture, mode);
+ let (y_a, state_a, _) = run_prefill_kernel_mode::<B>(&ctx, &block, &fixture, mode);
+ let (y_b, state_b, _) = run_prefill_kernel_mode::<B>(&ctx, &block, &fixture, mode);
assert_eq!(y_a, y_b, "Prefill outputs differ in {:?} mode", mode);
assert_eq!(state_a, state_b, "Prefill states differ in {:?} mode", mode);
@@ -288,7 +284,7 @@ fn assert_matches_cpu_reference<B: Backend>(mode: SSDPrefillMode) {
eprintln!("Skipping SSD prefill reference test: no Metal device");
return;
};
- let kernel = SSDPrefillKernels::<B>::new(&ctx, DataType::F32).unwrap();
+ let block = SSDPrefillBlock::<B>::new(&ctx, DataType::F32).unwrap();
let fixture = SSDPrefillFixture::new();
let (y_ref, state_ref) = ssd_prefill_cpu_reference(
@@ -310,7 +306,7 @@ fn assert_matches_cpu_reference<B: Backend>(mode: SSDPrefillMode) {
fixture.state_strides,
);
- let (y_gpu, state_gpu, _) = run_prefill_kernel_mode::<B>(&ctx, &kernel, &fixture, mode);
+ let (y_gpu, state_gpu, _) = run_prefill_kernel_mode::<B>(&ctx, &block, &fixture, mode);
let tolerance = 5e-5f32;
let mut max_y_diff = 0.0f32;
diff --git a/crates/backend-uzu/tests/unit/encodable_block/moe/mod.rs b/crates/backend-uzu/tests/unit/encodable_block/moe/mod.rs
index ab39cee6b..b9e801ad4 100644
--- a/crates/backend-uzu/tests/unit/encodable_block/moe/mod.rs
+++ b/crates/backend-uzu/tests/unit/encodable_block/moe/mod.rs
@@ -2,8 +2,18 @@
#[path = "../../../common/mod.rs"]
mod common;
+use super::{
+ experts_two_pass_decode::MoeExpertsTwoPassDecodeBlock,
+ experts_two_pass_prefill::{MoeExpertsTwoPassArguments, MoeExpertsTwoPassPrefillBlock},
+ gather::MoeGather,
+};
+
mod moe_block_e2e_test;
+#[path = "../../../performance/encodable_block/moe/moe_experts_perf_test.rs"]
+mod moe_experts_perf_test;
mod moe_experts_test;
+#[path = "../../../performance/encodable_block/moe/moe_perf_test.rs"]
+mod moe_perf_test;
mod moe_tiles_test;
/// CPU reference for tile counts: count number of BM-sized tiles per expert
diff --git a/crates/backend-uzu/tests/unit/encodable_block/moe/moe_block_e2e_test.rs b/crates/backend-uzu/tests/unit/encodable_block/moe/moe_block_e2e_test.rs
index 40538f4af..1494faf44 100644
--- a/crates/backend-uzu/tests/unit/encodable_block/moe/moe_block_e2e_test.rs
+++ b/crates/backend-uzu/tests/unit/encodable_block/moe/moe_block_e2e_test.rs
@@ -6,15 +6,17 @@ use backend_uzu::{
kernel::{
MoeBlockBasesFromPartialsKernel, MoeCountsOffsetsFusedKernel, MoeFinalizeKernel, MoeRouterTopKKernel,
MoeScatterBucketsMapKernel,
- moe::{MoeExpertsTwoPassArguments, MoeExpertsTwoPassPrefillBlock, MoeGatherKernel},
},
},
};
use half::bf16;
use rand::{RngExt, SeedableRng, rngs::StdRng};
-use crate::encodable_block::mlp::moe::tests::common::helpers::{
- alloc_allocation, alloc_allocation_with_data, allocation_prefix_to_vec, allocation_to_vec, create_context,
+use super::{
+ MoeExpertsTwoPassArguments, MoeExpertsTwoPassPrefillBlock, MoeGather,
+ common::helpers::{
+ alloc_allocation, alloc_allocation_with_data, allocation_prefix_to_vec, allocation_to_vec, create_context,
+ },
};
fn moe_cpu_reference(
@@ -373,7 +375,7 @@ fn run_moe_parity_test_internal<B: Backend>(
&mut encoder,
);
- let gather = MoeGatherKernel::<B>::new(&ctx, DataType::BF16).expect("gather");
+ let gather = MoeGather::<B>::new(&ctx, DataType::BF16).expect("gather");
let x_perm_buf = gather.encode(&x_buf, &bucketed_ids_buf, &sumk_buf, t, k, d_model, &mut encoder).expect("gather");
let total_rows = t * k;
diff --git a/crates/backend-uzu/tests/unit/encodable_block/moe/moe_experts_test.rs b/crates/backend-uzu/tests/unit/encodable_block/moe/moe_experts_test.rs
index 1bb46fca3..d1a6c4f9d 100644
--- a/crates/backend-uzu/tests/unit/encodable_block/moe/moe_experts_test.rs
+++ b/crates/backend-uzu/tests/unit/encodable_block/moe/moe_experts_test.rs
@@ -11,16 +11,13 @@ use backend_uzu::{
backends::common::{
Encoder,
gpu_types::{ActivationType, activation_silu_alpha},
- kernel::moe::{
- MoeExpertsSingleDecodeArguments, MoeExpertsSingleDecodeKernels, MoeExpertsTwoPassArguments,
- MoeExpertsTwoPassDecodeBlock, MoeExpertsTwoPassPrefillBlock,
- },
},
};
use half::bf16;
use rand::{RngExt, SeedableRng, rngs::StdRng};
-use crate::encodable_block::mlp::moe::tests::{
+use super::{
+ MoeExpertsTwoPassArguments, MoeExpertsTwoPassDecodeBlock, MoeExpertsTwoPassPrefillBlock,
common::{
assert::assert_eq_float,
helpers::{alloc_allocation_with_data, allocation_prefix_to_vec, create_context},
@@ -634,252 +631,3 @@ fn test_tile_infrastructure() {
eprintln!("[tile infrastructure] ✓ PASSED");
}
-
-#[test]
-fn test_fused_single_token_decode() {
- for_each_non_cpu_backend!(|B| {
- let ctx = create_context::<B>();
- let mut rng = StdRng::seed_from_u64(0xF053ED);
-
- let d_model = 512;
- let d_ff = 2048;
- let e = 8;
- let k = 2;
-
- eprintln!("[fused single-token] d_model={}, d_ff={}, E={}, K={}", d_model, d_ff, e, k);
-
- // Generate test data
- let x: Vec<bf16> = (0..d_model).map(|_| bf16::from_f32(rng.random_range(-1.0..1.0))).collect();
-
- let topk_ids: Vec<i32> = (0..k).map(|i| (i % e) as i32).collect();
-
- let topk_probs: Vec<bf16> = {
- let raw: Vec<f32> = (0..k).map(|_| rng.random_range(0.1..1.0)).collect();
- let sum: f32 = raw.iter().sum();
- raw.iter().map(|p| bf16::from_f32(p / sum)).collect()
- };
-
- let w13_all: Vec<bf16> =
- (0..e * 2 * d_ff * d_model).map(|_| bf16::from_f32(rng.random_range(-0.05..0.05))).collect();
- let w2_all: Vec<bf16> =
- (0..e * d_ff * d_model).map(|_| bf16::from_f32(rng.random_range(-0.05..0.05))).collect();
- let up_biases: Vec<bf16> = (0..e * 2 * d_ff).map(|_| bf16::from_f32(rng.random_range(-0.01..0.01))).collect();
- let down_biases: Vec<bf16> = (0..e * d_model).map(|_| bf16::from_f32(rng.random_range(-0.01..0.01))).collect();
-
- // CPU reference (gating_code=2 for SwiGLU)
- let gating_code = 2u32;
- let silu_alpha = 1.0f32;
- let y_expected = cpu_moe_reference(
- &x,
- &topk_ids,
- &topk_probs,
- &w13_all,
- &w2_all,
- &up_biases,
- &down_biases,
- 1, // T=1 for single token
- d_model,
- d_ff,
- k,
- gating_code,
- silu_alpha,
- f32::NEG_INFINITY,
- f32::INFINITY,
- f32::NEG_INFINITY,
- f32::INFINITY,
- );
-
- // GPU buffers
- let x_buf = alloc_allocation_with_data::<B, bf16>(&ctx, &x);
- let topk_ids_buf = alloc_allocation_with_data::<B, i32>(&ctx, &topk_ids);
- let topk_probs_buf = alloc_allocation_with_data::<B, bf16>(&ctx, &topk_probs);
- let w13_buf = alloc_allocation_with_data::<B, bf16>(&ctx, &w13_all);
- let w2_buf = alloc_allocation_with_data::<B, bf16>(&ctx, &w2_all);
- let up_biases_buf = alloc_allocation_with_data::<B, bf16>(&ctx, &up_biases);
- let down_biases_buf = alloc_allocation_with_data::<B, bf16>(&ctx, &down_biases);
- // Run fused decode kernel
- let fused_kernel = MoeExpertsSingleDecodeKernels::<B>::new(&ctx, DataType::BF16, gating_code)
- .expect("MoeExpertsSingleDecodeKernel::new");
- let mut encoder = Encoder::new(ctx.as_ref()).expect("Failed to create encoder");
-
- let y_buf = fused_kernel
- .encode(
- MoeExpertsSingleDecodeArguments {
- x: &x_buf,
- topk_ids: &topk_ids_buf,
- topk_probs: &topk_probs_buf,
- w13_all: &w13_buf,
- w2_all: &w2_buf,
- up_biases: &up_biases_buf,
- down_biases: &down_biases_buf,
- d_model,
- d_ff,
- k,
- silu_alpha: 1.0, // Standard SiLU for testing
- gate_clip_min: f32::NEG_INFINITY,
- gate_clip_max: f32::INFINITY,
- up_clip_min: f32::NEG_INFINITY,
- up_clip_max: f32::INFINITY,
- },
- &mut encoder,
- )
- .expect("failed to encode MoE experts");
-
- let completed = encoder.end_encoding().submit().wait_until_completed().unwrap();
-
- // Read GPU output
- let y_gpu = allocation_prefix_to_vec::<B, bf16>(&y_buf, d_model);
-
- // Compute error metrics
- let mut max_abs_error = 0.0f32;
- let mut sum_abs_error = 0.0f32;
- let mut max_idx = 0;
-
- for (i, (&gpu_val, &cpu_val)) in y_gpu.iter().zip(y_expected.iter()).enumerate() {
- let abs_error = (f32::from(gpu_val) - f32::from(cpu_val)).abs();
- sum_abs_error += abs_error;
- if abs_error > max_abs_error {
- max_abs_error = abs_error;
- max_idx = i;
- }
- }
- let mean_abs_error = sum_abs_error / d_model as f32;
-
- eprintln!(
- "[fused single-token] Max error: {:.6} at idx {} (GPU={:.6}, CPU={:.6}), Mean error: {:.6}",
- max_abs_error,
- max_idx,
- f32::from(y_gpu[max_idx]),
- f32::from(y_expected[max_idx]),
- mean_abs_error
- );
-
- let tolerance = 0.02;
- assert_eq_float(&y_expected, &y_gpu, tolerance, "fused single-token output");
-
- eprintln!("[fused single-token] PASSED (tolerance={:.4})", tolerance);
- drop(y_buf);
- drop(completed);
- });
-}
-
-#[test]
-fn test_fused_single_token_k4() {
- for_each_non_cpu_backend!(|B| {
- let ctx = create_context::<B>();
- let mut rng = StdRng::seed_from_u64(0xE001A);
-
- let d_model = 512;
- let d_ff = 2048;
- let e = 8;
- let k = 4;
-
- eprintln!("[fused single-token K=4] d_model={}, d_ff={}, E={}, K={}", d_model, d_ff, e, k);
-
- let x: Vec<bf16> = (0..d_model).map(|_| bf16::from_f32(rng.random_range(-1.0..1.0))).collect();
-
- let topk_ids: Vec<i32> = (0..k).map(|i| ((i * 2) % e) as i32).collect();
-
- let topk_probs: Vec<bf16> = {
- let raw: Vec<f32> = (0..k).map(|_| rng.random_range(0.1..1.0)).collect();
- let sum: f32 = raw.iter().sum();
- raw.iter().map(|p| bf16::from_f32(p / sum)).collect()
- };
-
- let w13_all: Vec<bf16> =
- (0..e * 2 * d_ff * d_model).map(|_| bf16::from_f32(rng.random_range(-0.05..0.05))).collect();
- let w2_all: Vec<bf16> =
- (0..e * d_ff * d_model).map(|_| bf16::from_f32(rng.random_range(-0.05..0.05))).collect();
- let up_biases: Vec<bf16> = (0..e * 2 * d_ff).map(|_| bf16::from_f32(rng.random_range(-0.01..0.01))).collect();
- let down_biases: Vec<bf16> = (0..e * d_model).map(|_| bf16::from_f32(rng.random_range(-0.01..0.01))).collect();
-
- let gating_code = 2u32;
- let silu_alpha = 1.0f32;
- let y_expected = cpu_moe_reference(
- &x,
- &topk_ids,
- &topk_probs,
- &w13_all,
- &w2_all,
- &up_biases,
- &down_biases,
- 1, // T=1 for single token
- d_model,
- d_ff,
- k,
- gating_code,
- silu_alpha,
- f32::NEG_INFINITY,
- f32::INFINITY,
- f32::NEG_INFINITY,
- f32::INFINITY,
- );
-
- let x_buf = alloc_allocation_with_data::<B, bf16>(&ctx, &x);
- let topk_ids_buf = alloc_allocation_with_data::<B, i32>(&ctx, &topk_ids);
- let topk_probs_buf = alloc_allocation_with_data::<B, bf16>(&ctx, &topk_probs);
- let w13_buf = alloc_allocation_with_data::<B, bf16>(&ctx, &w13_all);
- let w2_buf = alloc_allocation_with_data::<B, bf16>(&ctx, &w2_all);
- let up_biases_buf = alloc_allocation_with_data::<B, bf16>(&ctx, &up_biases);
- let down_biases_buf = alloc_allocation_with_data::<B, bf16>(&ctx, &down_biases);
- let fused_kernel =
- MoeExpertsSingleDecodeKernels::<B>::new(&ctx, DataType::BF16, gating_code).expect("fused kernel");
- let mut encoder = Encoder::new(ctx.as_ref()).expect("Failed to create encoder");
- let y_buf = fused_kernel
- .encode(
- MoeExpertsSingleDecodeArguments {
- x: &x_buf,
- topk_ids: &topk_ids_buf,
- topk_probs: &topk_probs_buf,
- w13_all: &w13_buf,
- w2_all: &w2_buf,
- up_biases: &up_biases_buf,
- down_biases: &down_biases_buf,
- d_model,
- d_ff,
- k,
- silu_alpha,
- gate_clip_min: f32::NEG_INFINITY,
- gate_clip_max: f32::INFINITY,
- up_clip_min: f32::NEG_INFINITY,
- up_clip_max: f32::INFINITY,
- },
- &mut encoder,
- )
- .expect("failed to encode MoE experts");
- let completed = encoder.end_encoding().submit().wait_until_completed().unwrap();
-
- let y_gpu = allocation_prefix_to_vec::<B, bf16>(&y_buf, d_model);
-
- // Compute error metrics
- let mut max_abs_error = 0.0f32;
- let mut sum_abs_error = 0.0f32;
- let mut max_idx = 0;
-
- for (i, (&gpu_val, &cpu_val)) in y_gpu.iter().zip(y_expected.iter()).enumerate() {
- let abs_error = (f32::from(gpu_val) - f32::from(cpu_val)).abs();
- sum_abs_error += abs_error;
- if abs_error > max_abs_error {
- max_abs_error = abs_error;
- max_idx = i;
- }
- }
- let mean_abs_error = sum_abs_error / d_model as f32;
-
- eprintln!(
- "[fused single-token K=4] Max error: {:.6} at idx {} (GPU={:.6}, CPU={:.6}), Mean error: {:.6}",
- max_abs_error,
- max_idx,
- f32::from(y_gpu[max_idx]),
- f32::from(y_expected[max_idx]),
- mean_abs_error
- );
-
- let tolerance = 0.02;
- assert_eq_float(&y_gpu, &y_expected, tolerance, "fused single-token K=4 output");
-
- eprintln!("[fused single-token K=4] PASSED (tolerance={:.4})", tolerance);
- drop(y_buf);
- drop(completed);
- });
-}
diff --git a/crates/backend-uzu/tests/unit/kernel/moe/moe_gather_test.rs b/crates/backend-uzu/tests/unit/encodable_block/moe/moe_gather_test.rs
similarity index 86%
rename from crates/backend-uzu/tests/unit/kernel/moe/moe_gather_test.rs
rename to crates/backend-uzu/tests/unit/encodable_block/moe/moe_gather_test.rs
index 46ecd3448..e8602c36d 100644
--- a/crates/backend-uzu/tests/unit/kernel/moe/moe_gather_test.rs
+++ b/crates/backend-uzu/tests/unit/encodable_block/moe/moe_gather_test.rs
@@ -1,7 +1,7 @@
use backend_uzu::{
ArrayElement,
backends::{
- common::{Backend, Encoder, kernel::moe::MoeGatherKernel},
+ common::{Backend, Encoder},
cpu::Cpu,
},
};
@@ -9,12 +9,15 @@ use half::bf16;
use num_traits::Float;
use rand::{RngExt, SeedableRng, rngs::StdRng};
-use crate::{
- common::{
- assert::assert_eq_float,
- helpers::{alloc_allocation_with_data, allocation_to_vec, create_context},
- },
- uzu_test,
+use super::MoeGather;
+
+#[macro_use]
+#[path = "../../../common/mod.rs"]
+mod common;
+
+use common::{
+ assert::assert_eq_float,
+ helpers::{alloc_allocation_with_data, allocation_to_vec, create_context},
};
struct Input<T: ArrayElement + Float> {
@@ -32,7 +35,7 @@ fn get_output<B: Backend, T: ArrayElement + Float>(input: &Input<T>) -> Vec<T> {
let x_allocation = alloc_allocation_with_data::<B, T>(&context, &input.x);
let ids_allocation = alloc_allocation_with_data::<B, i32>(&context, &input.bucket_ids);
let sumk_allocation = alloc_allocation_with_data::<B, u32>(&context, &sumk_data);
- let gather = MoeGatherKernel::<B>::new(&context, T::data_type()).expect("MoeGatherKernel::new");
+ let gather = MoeGather::<B>::new(&context, T::data_type()).expect("MoeGather::new");
let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");
let x_perm_allocation = gather
.encode(
@@ -77,22 +80,22 @@ fn test_gather_internal(
})
}
-#[uzu_test]
+#[test]
fn test_gather_single_token() {
test_gather_internal(1, 2, 64);
}
-#[uzu_test]
+#[test]
fn test_gather_small_batch() {
test_gather_internal(4, 8, 128);
}
-#[uzu_test]
+#[test]
fn test_gather_medium_batch() {
test_gather_internal(16, 32, 256)
}
-#[uzu_test]
+#[test]
fn test_gather_large_batch() {
test_gather_internal(64, 128, 512)
}
diff --git a/crates/backend-uzu/tests/unit/encodable_block/sampling_test.rs b/crates/backend-uzu/tests/unit/encodable_block/sampling_test.rs
index f52078d55..07a69e204 100644
--- a/crates/backend-uzu/tests/unit/encodable_block/sampling_test.rs
+++ b/crates/backend-uzu/tests/unit/encodable_block/sampling_test.rs
@@ -3,15 +3,13 @@
use rand::seq::SliceRandom;
// for Vec::shuffle
+use super::block::SamplingBlock;
use crate::{
DataType,
backends::{
common::{
Backend, Context, Encoder, Kernels,
- kernel::{
- MinPKernel, TemperatureKernel,
- sampling::{ArgmaxStrategy, SamplingKernel},
- },
+ kernel::{MinPKernel, TemperatureKernel},
},
metal::Metal,
},
@@ -45,7 +43,8 @@ fn cpu_reference_min_p(
.collect()
}
-fn test_argmax_sampling_with_strategy(strategy: ArgmaxStrategy) {
+#[test]
+fn test_argmax_sampling() {
let context = match <Metal as Backend>::Context::new() {
Ok(ctx) => ctx,
Err(e) => {
@@ -57,8 +56,7 @@ fn test_argmax_sampling_with_strategy(strategy: ArgmaxStrategy) {
let batch_size = 2;
let vocab_size = 4;
- let kernel = SamplingKernel::<Metal>::new_with_strategy(&context, DataType::F32, strategy)
- .expect("Failed to create argmax kernel");
+ let block = SamplingBlock::<Metal>::new(&context, DataType::F32).expect("Failed to create sampling block");
// Create test data: batch_size=2, vocab_size=4
// First batch: [1.0, 3.0, 2.0, 0.5] -> should select index 1
@@ -73,7 +71,7 @@ fn test_argmax_sampling_with_strategy(strategy: ArgmaxStrategy) {
let mut output_buffer = alloc_allocation::<Metal, u32>(context.as_ref(), batch_size);
let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");
- kernel
+ block
.encode(
&mut logits_buffer,
&seeds_buffer,
@@ -93,26 +91,12 @@ fn test_argmax_sampling_with_strategy(strategy: ArgmaxStrategy) {
assert_eq!(results[0], 1, "First batch should select token 1 (highest logit: 3.0)");
assert_eq!(results[1], 2, "Second batch should select token 2 (highest logit: 2.5)");
- println!("✓ Argmax sampling test passed with {:?} strategy - selected tokens: {:?}", strategy, results);
-}
-
-#[test]
-fn test_argmax_sampling_single_pass() {
- test_argmax_sampling_with_strategy(ArgmaxStrategy::SinglePass);
+ println!("✓ Argmax sampling test passed - selected tokens: {:?}", results);
}
#[test]
-fn test_argmax_sampling_two_pass() {
- test_argmax_sampling_with_strategy(ArgmaxStrategy::TwoPass);
-}
-
-#[test]
-fn test_argmax_sampling() {
- // Keep the original test for backward compatibility - defaults to single-pass
- test_argmax_sampling_with_strategy(ArgmaxStrategy::SinglePass);
-}
-
-fn perf_argmax_128k_vocab_with_strategy(strategy: ArgmaxStrategy) {
+#[ignore = "performance-only check"]
+fn perf_argmax_128k_vocab() {
use std::time::Instant;
use rand::{RngExt, SeedableRng, rngs::StdRng};
@@ -131,8 +115,7 @@ fn perf_argmax_128k_vocab_with_strategy(strategy: ArgmaxStrategy) {
const VOCAB: usize = 128000; // 128K
// ---- Kernel ----
- let kernel = SamplingKernel::<Metal>::new_with_strategy(&context, DataType::F32, strategy)
- .expect("Failed to create Argmax kernel");
+ let block = SamplingBlock::<Metal>::new(&context, DataType::F32).expect("Failed to create sampling block");
// ---- Build random logits ----
let mut rng = StdRng::seed_from_u64(123);
@@ -151,7 +134,7 @@ fn perf_argmax_128k_vocab_with_strategy(strategy: ArgmaxStrategy) {
// ---- Launch once and time ----
let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");
- kernel
+ block
.encode(
&mut logits_buf,
&seeds_buf,
@@ -171,8 +154,8 @@ fn perf_argmax_128k_vocab_with_strategy(strategy: ArgmaxStrategy) {
let gpu_time_ms = completed.gpu_execution_time().as_secs_f64() * 1e3;
println!(
- "Argmax sampling perf (batch={}, vocab={}, strategy={:?}): GPU={:.2} ms, Host-side={:.2} ms",
- BATCH, VOCAB, strategy, gpu_time_ms, host_elapsed_ms
+ "Argmax sampling perf (batch={}, vocab={}): GPU={:.2} ms, Host-side={:.2} ms",
+ BATCH, VOCAB, gpu_time_ms, host_elapsed_ms
);
// Ensure the kernel produced *some* output (sanity).
@@ -200,19 +183,7 @@ fn perf_argmax_128k_vocab_with_strategy(strategy: ArgmaxStrategy) {
);
}
- println!("✓ Argmax correctness verified with {:?} strategy", strategy);
-}
-
-#[test]
-#[ignore = "performance-only check"]
-fn perf_argmax_128k_vocab_single_pass() {
- perf_argmax_128k_vocab_with_strategy(ArgmaxStrategy::SinglePass);
-}
-
-#[test]
-#[ignore = "performance-only check"]
-fn perf_argmax_128k_vocab_two_pass() {
- perf_argmax_128k_vocab_with_strategy(ArgmaxStrategy::TwoPass);
+ println!("✓ Argmax correctness verified");
}
#[test]
@@ -228,7 +199,7 @@ fn test_categorical_sampling() {
let batch_size = 2;
let vocab_size = 4;
- let kernel = SamplingKernel::<Metal>::new(&context, DataType::F32).expect("Failed to create sampling kernel");
+ let block = SamplingBlock::<Metal>::new(&context, DataType::F32).expect("Failed to create sampling block");
// Create test data with different probability distributions
// First batch: [1.0, 2.0, 1.5, 0.5] -> softmax: [0.134, 0.366, 0.201, 0.082]
@@ -253,7 +224,7 @@ fn test_categorical_sampling() {
let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");
- kernel
+ block
.encode(
&mut logits_buffer,
&seeds_buffer,
@@ -335,7 +306,7 @@ fn test_categorical_sampling_statistical() {
const NUM_SAMPLES: usize = 5000;
const TOLERANCE: f32 = 0.05; // 5% tolerance
- let kernel = SamplingKernel::<Metal>::new(&context, DataType::F32).expect("Failed to create sampling kernel");
+ let block = SamplingBlock::<Metal>::new(&context, DataType::F32).expect("Failed to create sampling block");
// Generate random logits
let mut rng = StdRng::seed_from_u64(42);
@@ -377,7 +348,7 @@ fn test_categorical_sampling_statistical() {
let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");
- kernel
+ block
.encode(
&mut logits_buffer,
&seeds_buffer,
@@ -447,7 +418,7 @@ fn perf_categorical_128k_vocab() {
const BATCH: usize = 8;
const VOCAB: usize = 128000; // 128K
- let kernel = SamplingKernel::<Metal>::new(&context, DataType::F32).expect("Failed to create sampling kernel");
+ let block = SamplingBlock::<Metal>::new(&context, DataType::F32).expect("Failed to create sampling block");
// Build random logits
let mut rng = StdRng::seed_from_u64(123);
@@ -466,7 +437,7 @@ fn perf_categorical_128k_vocab() {
// Launch and time
let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");
- kernel
+ block
.encode(
&mut logits_buf,
&seeds_buf,
@@ -615,7 +586,7 @@ fn test_minp_sampling_exact_match(
},
};
- let kernel = SamplingKernel::<Metal>::new(&context, DataType::F32).expect("Failed to create sampling kernel");
+ let block = SamplingBlock::<Metal>::new(&context, DataType::F32).expect("Failed to create sampling block");
// Build logits where some tokens have high probability and others have low
// For min_p filtering, tokens with probability < min_p * max_prob are masked
@@ -653,7 +624,7 @@ fn test_minp_sampling_exact_match(
let seeds_buf = alloc_allocation_with_data::<Metal, _>(context.as_ref(), &seeds);
let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");
- kernel
+ block
.encode(
&mut logits_buf,
&seeds_buf,
diff --git a/crates/backend-uzu/tests/unit/kernel/sampling/top_p_test.rs b/crates/backend-uzu/tests/unit/encodable_block/sampling_top_p_test.rs
similarity index 94%
rename from crates/backend-uzu/tests/unit/kernel/sampling/top_p_test.rs
rename to crates/backend-uzu/tests/unit/encodable_block/sampling_top_p_test.rs
index b1b13e119..8ef1d0e08 100644
--- a/crates/backend-uzu/tests/unit/kernel/sampling/top_p_test.rs
+++ b/crates/backend-uzu/tests/unit/encodable_block/sampling_top_p_test.rs
@@ -6,10 +6,7 @@ use std::{
use backend_uzu::{
ArrayContextExt, ArrayElement, DataType,
backends::{
- common::{
- AllocationType, Backend, Context, Encoder, Kernels,
- kernel::{TopPKernel, sampling::SamplingKernel},
- },
+ common::{AllocationType, Backend, Context, Encoder, Kernels, kernel::TopPKernel},
cpu::Cpu,
},
session::parameter::{SamplingMethod, SamplingProcessingOrder},
@@ -18,10 +15,13 @@ use half::{bf16, f16};
use num_traits::Float;
use rand::{RngExt, SeedableRng, rngs::StdRng, seq::SliceRandom};
-use crate::{
- common::helpers::{alloc_allocation_with_data, allocation_to_vec},
- uzu_test,
-};
+use super::SamplingBlock;
+
+#[macro_use]
+#[path = "../../common/mod.rs"]
+mod common;
+
+use common::helpers::{alloc_allocation_with_data, allocation_to_vec};
const TEST_SAMPLING_SEED: u64 = 42;
@@ -77,7 +77,7 @@ fn get_output<T: ArrayElement + Float, B: Backend>(input: &Input<T>) -> Vec<T> {
encoder.end_encoding().submit().wait_until_completed().unwrap();
- crate::common::helpers::allocation_to_vec(&output)
+ allocation_to_vec(&output)
}
fn assert_top_p_equal<T: ArrayElement + Float + Display>(
@@ -135,54 +135,54 @@ fn test_internal<T: ArrayElement + Float + Debug + Display>(
}
// Out-of-place tests (same data as sampling_test::test_topp_gpu_cpu_match)
-#[uzu_test]
+#[test]
fn test_f32() {
test_internal::<f32>(4, 1024, 0.9, false);
}
-#[uzu_test]
+#[test]
fn test_f16() {
test_internal::<f16>(4, 1024, 0.9, false);
}
-#[uzu_test]
+#[test]
fn test_bf16() {
test_internal::<bf16>(4, 1024, 0.9, false);
}
// In-place tests
-#[uzu_test]
+#[test]
fn test_in_place_f32() {
test_internal::<f32>(4, 1024, 0.9, true);
}
-#[uzu_test]
+#[test]
fn test_in_place_f16() {
test_internal::<f16>(4, 1024, 0.9, true);
}
-#[uzu_test]
+#[test]
fn test_in_place_bf16() {
test_internal::<bf16>(4, 1024, 0.9, true);
}
// Edge cases
-#[uzu_test]
+#[test]
fn test_single_batch_f32() {
test_internal::<f32>(1, 1024, 0.9, false);
}
-#[uzu_test]
+#[test]
fn test_top_p_very_small() {
test_internal::<f32>(4, 1024, 0.01, false);
}
-#[uzu_test]
+#[test]
fn test_top_p_near_1() {
test_internal::<f32>(4, 1024, 0.99, false);
}
-// --- Sampling-level top-p tests (test the full SamplingKernel with top_p) ---
+// --- Sampling-level top-p tests (test the full SamplingBlock with top_p) ---
fn cpu_reference_top_p(
row_logits: &[f32],
@@ -230,7 +230,7 @@ fn test_topp_sampling_from_prob_exact_match_internal<B: Backend>(
let p = (k as f32) * 0.1;
- let kernel = SamplingKernel::<B>::new(&context, DataType::F32).expect("Failed to create sampling kernel");
+ let block = SamplingBlock::<B>::new(&context, DataType::F32).expect("Failed to create sampling block");
// Build probability table
let low_prob = (1.0 - p) / (vocab_size - k) as f32;
@@ -274,7 +274,7 @@ fn test_topp_sampling_from_prob_exact_match_internal<B: Backend>(
let seeds_allocation = alloc_allocation_with_data::<B, u64>(&context, &seeds);
let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");
- kernel
+ block
.encode(
&mut logits_allocation,
&seeds_allocation,
@@ -325,21 +325,21 @@ fn test_topp_sampling_from_prob_exact_match_internal<B: Backend>(
);
}
-#[uzu_test]
+#[test]
fn test_topp_sampling_match_small() {
for_each_non_cpu_backend!(|B| {
test_topp_sampling_from_prob_exact_match_internal::<B>(8, 10, 1024);
});
}
-#[uzu_test]
+#[test]
fn test_topp_sampling_match_large() {
for_each_non_cpu_backend!(|B| {
test_topp_sampling_from_prob_exact_match_internal::<B>(32, 50, 4096);
});
}
-#[uzu_test]
+#[test]
fn test_topp_sampling_statistical_large() {
for_each_non_cpu_backend!(|B| {
const BATCH: usize = 32;
@@ -350,7 +350,7 @@ fn test_topp_sampling_statistical_large() {
let context = <B as Backend>::Context::new().expect("Failed to create Context");
- let kernel = SamplingKernel::<B>::new(&context, DataType::F32).expect("Failed to create sampling kernel");
+ let block = SamplingBlock::<B>::new(&context, DataType::F32).expect("Failed to create sampling block");
let mut rng = StdRng::seed_from_u64(42);
let mut logits = vec![0.0f32; BATCH * VOCAB];
@@ -378,7 +378,7 @@ fn test_topp_sampling_statistical_large() {
let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");
- kernel
+ block
.encode(
&mut logits_allocation,
&seeds_allocation,
@@ -428,7 +428,7 @@ fn test_topp_sampling_statistical_large() {
});
}
-#[uzu_test]
+#[test]
fn perf_topp_128k_vocab() {
for_each_non_cpu_backend!(|B| {
const BATCH: usize = 8;
@@ -437,7 +437,7 @@ fn perf_topp_128k_vocab() {
let context = <B as Backend>::Context::new().expect("Failed to create Context");
- let kernel = SamplingKernel::<B>::new(&context, DataType::F32).expect("Failed to create sampling kernel");
+ let block = SamplingBlock::<B>::new(&context, DataType::F32).expect("Failed to create sampling block");
let mut rng = StdRng::seed_from_u64(123);
let mut logits = vec![0.0f32; BATCH * VOCAB];
@@ -454,7 +454,7 @@ fn perf_topp_128k_vocab() {
let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");
- kernel
+ block
.encode(
&mut logits_allocation,
&seeds_allocation,
diff --git a/crates/backend-uzu/tests/unit/forward_pass/kv_cache_state_test.rs b/crates/backend-uzu/tests/unit/forward_pass/kv_cache_state_test.rs
index 03cceef5f..d5d2ab1dd 100644
--- a/crates/backend-uzu/tests/unit/forward_pass/kv_cache_state_test.rs
+++ b/crates/backend-uzu/tests/unit/forward_pass/kv_cache_state_test.rs
@@ -5,9 +5,10 @@ use backend_uzu::forward_pass::kv_cache_layer::KVCacheLayerTrait;
use crate::{
DataType,
backends::{
- common::{Backend, Context, Encoder, kernel::kv_cache_update::KVCacheUpdate},
+ common::{Backend, Context, Encoder},
metal::Metal,
},
+ encodable_block::KVCacheUpdate,
forward_pass::kv_cache_layer::{KVCacheLayer, KVCacheLayerState},
};
diff --git a/crates/backend-uzu/tests/unit/kernel/attention/mod.rs b/crates/backend-uzu/tests/unit/kernel/attention/mod.rs
index 796bfc81e..08f4c10bb 100644
--- a/crates/backend-uzu/tests/unit/kernel/attention/mod.rs
+++ b/crates/backend-uzu/tests/unit/kernel/attention/mod.rs
@@ -1,5 +1,4 @@
mod attention_fallback_test;
-mod attention_gemm_test;
mod attention_single_pass_test;
mod attention_two_pass_test;
mod attention_update_kv_cache_test;
diff --git a/crates/backend-uzu/tests/unit/kernel/moe/mod.rs b/crates/backend-uzu/tests/unit/kernel/moe/mod.rs
index 94a554024..ec94c9afb 100644
--- a/crates/backend-uzu/tests/unit/kernel/moe/mod.rs
+++ b/crates/backend-uzu/tests/unit/kernel/moe/mod.rs
@@ -1,5 +1,4 @@
mod moe_counts_offsets_fused_test;
mod moe_finalize_test;
-mod moe_gather_test;
mod moe_router_topk_test;
mod moe_scatter_test;
diff --git a/crates/backend-uzu/tests/unit/kernel/sampling/mod.rs b/crates/backend-uzu/tests/unit/kernel/sampling/mod.rs
index 1331ba3df..bc67c32fb 100644
--- a/crates/backend-uzu/tests/unit/kernel/sampling/mod.rs
+++ b/crates/backend-uzu/tests/unit/kernel/sampling/mod.rs
@@ -5,4 +5,3 @@ mod min_p_test;
mod temperature_test;
mod test_argmax;
mod top_k_test;
-mod top_p_test;