A high-performance inference engine for AI models
Simplify MoE (#410)
uuuvn9664a1375097
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.rsindex 30ce0effd..0ad75c0b4 100644--- a/crates/backend-uzu/src/backends/common/kernel/moe/experts_single.rs+++ b/crates/backend-uzu/src/backends/common/kernel/moe/experts_single.rs@@ -1,3 +1,5 @@+// TODO(LuckyIYI): figure out if this was made dead code by accident and restore or delete+use crate::{DataType,array::size_for_shape,@@ -7,8 +9,6 @@ use crate::{},};-static DTYPES: [DataType; 3] = [DataType::F16, DataType::BF16, DataType::F32];-/// Arguments for single-token MoE decode (T=1 optimized path)pub struct MoeExpertsSingleDecodeArguments<'a, B: Backend> {/// Input activation [d_model]@@ -31,8 +31,6 @@ pub struct MoeExpertsSingleDecodeArguments<'a, B: Backend> {pub d_ff: usize,/// Number of active experts per tokenpub k: usize,- /// Gating activation: 0=GELU, 1=SiLU, 2=SwiGLU, 3=GEGLU- pub gating_code: u32,/// SiLU activation alpha parameterpub silu_alpha: f32,/// Gate clipping min@@ -43,54 +41,35 @@ pub struct MoeExpertsSingleDecodeArguments<'a, B: Backend> {pub up_clip_min: f32,/// Up clipping maxpub up_clip_max: f32,- /// Data type- pub data_type: DataType,}pub struct MoeExpertsSingleDecodeKernels<B: Backend> {- pass_a: Vec<Vec<<B::Kernels as Kernels>::MoeExpertsDecodeSinglePassAKernel>>,- pass_b: Vec<<B::Kernels as Kernels>::MoeExpertsDecodeSinglePassBKernel>,+ 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) -> Result<Self, B::Error> {- let mut pass_a = vec![];- for gate in 0..4 {- let mut kernels = vec![];- for dtype in &DTYPES {- let kernel =- <B::Kernels as Kernels>::MoeExpertsDecodeSinglePassAKernel::new(ctx, (*dtype).into(), gate)?;- kernels.push(kernel)- }- pass_a.push(kernels);- }-- let mut pass_b = Vec::with_capacity(DTYPES.len());- for dtype in &DTYPES {- pass_b.push(<B::Kernels as Kernels>::MoeExpertsDecodeSinglePassBKernel::new(ctx, (*dtype).into())?);- }-+ pub fn new(+ ctx: &B::Context,+ data_type: DataType,+ gating_code: u32,+ ) -> Result<Self, B::Error> {Ok(Self {- pass_a,- pass_b,+ 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,- encoder: &mut Encoder<B>,args: MoeExpertsSingleDecodeArguments<B>,+ encoder: &mut Encoder<B>,) -> Result<Allocation<B>, B::Error> {- assert!(args.k > 0, "MoE single decode requires at least one active expert");-- let gate_idx = args.gating_code.min(3) as usize;- let dtype_idx = DTYPES.iter().position(|dtype| *dtype == args.data_type).unwrap();- let mut hidden = encoder.allocate_scratch(size_for_shape(&[args.k, args.d_ff], DataType::F32))?;- let mut output = encoder.allocate_scratch(size_for_shape(&[args.d_model], args.data_type))?;-// Pass A: x @ W13[expert] -> hidden- let kernel = &self.pass_a[gate_idx][dtype_idx];- kernel.encode(+ 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,@@ -108,8 +87,8 @@ impl<B: Backend> MoeExpertsSingleDecodeKernels<B> {);// Pass B: 8 simdgroups (256 threads), outputs final y directly- let kernel = &self.pass_b[dtype_idx];- kernel.encode(+ 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,@@ -121,6 +100,7 @@ impl<B: Backend> MoeExpertsSingleDecodeKernels<B> {args.k as u32,encoder,);+Ok(output)}}diff --git a/crates/backend-uzu/src/backends/common/kernel/moe/experts_two_pass_decode.rs b/crates/backend-uzu/src/backends/common/kernel/moe/experts_two_pass_decode.rsindex 8ba310214..f12e83e6f 100644--- a/crates/backend-uzu/src/backends/common/kernel/moe/experts_two_pass_decode.rs+++ b/crates/backend-uzu/src/backends/common/kernel/moe/experts_two_pass_decode.rs@@ -1,76 +1,88 @@-use super::{MoeExpertsTwoPassArguments, MoePassATileKernels};use crate::{DataType,array::size_for_shape,backends::common::{Allocation, Backend, Encoder,- kernel::{Kernels, MoeExpertsDecodeDownFused2DKernel, MoeExpertsDecodePassAKernel},+ kernel::{+ Kernels, MoeExpertsDecodeDownFused2DKernel, MoeExpertsDecodePassAKernel, MoePassABuildRowMapKernel,+ MoePassABuildTileMapKernel, MoePassATileCountsKernel, MoePassATileScanKernel,+ MoePassAWriteDispatchArgsKernel, moe::MoeExpertsTwoPassArguments,+ },},};-static DTYPES: [DataType; 3] = [DataType::F16, DataType::BF16, DataType::F32];-pub struct MoeExpertsTwoPassDecodeBlock<B: Backend> {- pass_a_tile: MoePassATileKernels<B>,- pass_a_indirect: Vec<Vec<<B::Kernels as Kernels>::MoeExpertsDecodePassAKernel>>,- fused_down: Vec<<B::Kernels as Kernels>::MoeExpertsDecodeDownFused2DKernel>,+ counts: <B::Kernels as Kernels>::MoePassATileCountsKernel,+ scan: <B::Kernels as Kernels>::MoePassATileScanKernel,+ row_map: <B::Kernels as Kernels>::MoePassABuildRowMapKernel,+ build_map: <B::Kernels as Kernels>::MoePassABuildTileMapKernel,+ dispatch: <B::Kernels as Kernels>::MoePassAWriteDispatchArgsKernel,+ pass_a_indirect: <B::Kernels as Kernels>::MoeExpertsDecodePassAKernel,+ fused_down: <B::Kernels as Kernels>::MoeExpertsDecodeDownFused2DKernel,+ data_type: DataType,}impl<B: Backend> MoeExpertsTwoPassDecodeBlock<B> {- pub fn new(ctx: &B::Context) -> Result<Self, B::Error> {- let mut pass_a_indirect = vec![];- for gate in 0u32..4u32 {- let mut kernels = vec![];- for dtype in &DTYPES {- let kernel = <B::Kernels as Kernels>::MoeExpertsDecodePassAKernel::new(ctx, *dtype, gate)?;- kernels.push(kernel);- }- pass_a_indirect.push(kernels);- }-- let mut fused_down = Vec::with_capacity(DTYPES.len());- for dtype in &DTYPES {- let kernel = <B::Kernels as Kernels>::MoeExpertsDecodeDownFused2DKernel::new(ctx, *dtype, DataType::F32)?;- fused_down.push(kernel);- }-+ pub fn new(+ ctx: &B::Context,+ data_type: DataType,+ gating_code: u32,+ ) -> Result<Self, B::Error> {Ok(Self {- pass_a_tile: MoePassATileKernels::new(ctx)?,- pass_a_indirect,- fused_down,+ counts: <B::Kernels as Kernels>::MoePassATileCountsKernel::new(ctx)?,+ scan: <B::Kernels as Kernels>::MoePassATileScanKernel::new(ctx)?,+ row_map: <B::Kernels as Kernels>::MoePassABuildRowMapKernel::new(ctx)?,+ build_map: <B::Kernels as Kernels>::MoePassABuildTileMapKernel::new(ctx)?,+ dispatch: <B::Kernels as Kernels>::MoePassAWriteDispatchArgsKernel::new(ctx)?,+ pass_a_indirect: <B::Kernels as Kernels>::MoeExpertsDecodePassAKernel::new(ctx, data_type, gating_code)?,+ fused_down: <B::Kernels as Kernels>::MoeExpertsDecodeDownFused2DKernel::new(ctx, data_type, DataType::F32)?,+ data_type,})}pub fn encode(&self,- encoder: &mut Encoder<B>,args: MoeExpertsTwoPassArguments<B>,+ encoder: &mut Encoder<B>,) -> Result<Allocation<B>, B::Error> {- const BLOCK_M: u32 = 4;- let h_blocks = (args.d_ff as u32 + BLOCK_M - 1) / BLOCK_M;- let tile_counts = self.pass_a_tile.encode_counts(encoder, args.expert_offsets, args.e, h_blocks)?;+ const BLOCK_M: usize = 4;+ let h_blocks = args.d_ff.div_ceil(BLOCK_M) as u32;- let tile_scan = self.pass_a_tile.encode_scan(encoder, &tile_counts, args.e)?;+ let mut tile_counts = encoder.allocate_scratch(size_for_shape(&[args.num_routed_experts], DataType::U32))?;+ self.counts.encode(args.expert_offsets, &mut tile_counts, args.num_routed_experts as u32, h_blocks, encoder);- let row_expert_map = self.pass_a_tile.encode_row_map(encoder, args.expert_offsets, args.total_rows, args.e)?;+ let mut tile_offsets =+ encoder.allocate_scratch(size_for_shape(&[args.num_routed_experts + 1], DataType::U32))?;+ let mut total_tiles = encoder.allocate_scratch(size_for_shape(&[1], DataType::U32))?;+ self.scan.encode(&tile_counts, &mut tile_offsets, &mut total_tiles, args.num_routed_experts as u32, encoder);- let tile_map = self.pass_a_tile.encode_build_map(+ let mut row_expert_map = encoder.allocate_scratch(size_for_shape(&[args.total_rows], DataType::U32))?;+ self.row_map.encode(+ args.expert_offsets,+ &mut row_expert_map,+ args.total_rows as u32,+ args.num_routed_experts as u32,encoder,+ );++ let mut tile_map =+ encoder.allocate_scratch(size_for_shape(&[args.total_rows * h_blocks as usize * 3], DataType::U32))?;+ self.build_map.encode(args.expert_offsets,- &tile_scan.tile_offsets,+ &tile_offsets,&row_expert_map,- args.total_rows,+ &mut tile_map,+ args.total_rows as u32,h_blocks,- )?;+ encoder,+ );- let dispatch_args = self.pass_a_tile.encode_dispatch_args(encoder, &tile_scan.total_tiles, 1)?;+ let mut dispatch_args = encoder.allocate_scratch(size_for_shape(&[3], DataType::U32))?;+ self.dispatch.encode(&total_tiles, &mut dispatch_args, 1, encoder);- let gate_idx = args.gating_code.min(3) as usize;- let dtype_idx = DTYPES.iter().position(|dtype| *dtype == args.data_type).unwrap();let mut hidden = encoder.allocate_scratch(size_for_shape(&[args.total_rows, args.d_ff], DataType::F32))?;- let pass_a_kernel = &self.pass_a_indirect[gate_idx][dtype_idx];- pass_a_kernel.encode(+ self.pass_a_indirect.encode(args.x_perm,args.expert_offsets,args.w13_all,@@ -78,7 +90,7 @@ impl<B: Backend> MoeExpertsTwoPassDecodeBlock<B> {args.up_biases,args.d_model as u32,args.d_ff as u32,- args.e as u32,+ args.num_routed_experts as u32,args.gate_clip_min,args.gate_clip_max,args.up_clip_min,@@ -89,9 +101,8 @@ impl<B: Backend> MoeExpertsTwoPassDecodeBlock<B> {encoder,);- let mut output = encoder.allocate_scratch(size_for_shape(&[args.total_rows, args.d_model], args.data_type))?;- let pass_b_kernel = &self.fused_down[dtype_idx];- pass_b_kernel.encode(+ let mut output = encoder.allocate_scratch(size_for_shape(&[args.total_rows, args.d_model], self.data_type))?;+ self.fused_down.encode(&hidden,&row_expert_map,args.w2_all,@@ -100,9 +111,10 @@ impl<B: Backend> MoeExpertsTwoPassDecodeBlock<B> {args.total_rows as u32,args.d_model as u32,args.d_ff as u32,- args.e as u32,+ args.num_routed_experts as u32,encoder,);+Ok(output)}}diff --git a/crates/backend-uzu/src/backends/common/kernel/moe/experts_two_pass_prefill.rs b/crates/backend-uzu/src/backends/common/kernel/moe/experts_two_pass_prefill.rsindex d4d4e745a..0d36b3e90 100644--- a/crates/backend-uzu/src/backends/common/kernel/moe/experts_two_pass_prefill.rs+++ b/crates/backend-uzu/src/backends/common/kernel/moe/experts_two_pass_prefill.rs@@ -1,88 +1,75 @@-use super::MoeTileMapKernels;use crate::{DataType,array::size_for_shape,backends::common::{Allocation, Backend, Encoder, Kernels,- kernel::{MoeExpertsPrefillPassAKernel, MoeExpertsPrefillPassBKernel},+ kernel::{+ MoeBuildTileMapKernel, MoeExpertsPrefillPassAKernel, MoeExpertsPrefillPassBKernel, MoeTileCountsKernel,+ MoeTileScanKernel, MoeWriteDispatchArgsKernel,+ },},};-const DTYPES: [DataType; 3] = [DataType::F16, DataType::BF16, DataType::F32];-pub struct MoeExpertsTwoPassPrefillBlock<B: Backend> {- tile_map: MoeTileMapKernels<B>,- pass_a_indirect: Vec<Vec<<B::Kernels as Kernels>::MoeExpertsPrefillPassAKernel>>, // [gate][dtype]- pass_b_indirect: Vec<<B::Kernels as Kernels>::MoeExpertsPrefillPassBKernel>, // [dtype]+ counts: <B::Kernels as Kernels>::MoeTileCountsKernel,+ scan: <B::Kernels as Kernels>::MoeTileScanKernel,+ build: <B::Kernels as Kernels>::MoeBuildTileMapKernel,+ dispatch: <B::Kernels as Kernels>::MoeWriteDispatchArgsKernel,+ pass_a_indirect: <B::Kernels as Kernels>::MoeExpertsPrefillPassAKernel,+ pass_b_indirect: <B::Kernels as Kernels>::MoeExpertsPrefillPassBKernel,+ data_type: DataType,}impl<B: Backend> MoeExpertsTwoPassPrefillBlock<B> {- pub fn new(ctx: &B::Context) -> Result<Self, B::Error> {- let dtypes = [DataType::F16, DataType::BF16, DataType::F32];-- let mut pass_a_indirect = vec![];- for gate in 0u32..4u32 {- let mut kernels = vec![];- for dtype in dtypes {- let kernel = <B::Kernels as Kernels>::MoeExpertsPrefillPassAKernel::new(ctx, dtype, gate)?;- kernels.push(kernel);- }- pass_a_indirect.push(kernels);- }-- let mut pass_b_indirect = vec![];- for dtype in dtypes {- let kernel = <B::Kernels as Kernels>::MoeExpertsPrefillPassBKernel::new(ctx, dtype)?;- pass_b_indirect.push(kernel);- }-+ pub fn new(+ ctx: &B::Context,+ data_type: DataType,+ gating_code: u32,+ ) -> Result<Self, B::Error> {Ok(Self {- tile_map: MoeTileMapKernels::new(ctx)?,- pass_a_indirect,- pass_b_indirect,+ counts: <B::Kernels as Kernels>::MoeTileCountsKernel::new(ctx)?,+ scan: <B::Kernels as Kernels>::MoeTileScanKernel::new(ctx)?,+ build: <B::Kernels as Kernels>::MoeBuildTileMapKernel::new(ctx)?,+ dispatch: <B::Kernels as Kernels>::MoeWriteDispatchArgsKernel::new(ctx)?,+ pass_a_indirect: <B::Kernels as Kernels>::MoeExpertsPrefillPassAKernel::new(ctx, data_type, gating_code)?,+ pass_b_indirect: <B::Kernels as Kernels>::MoeExpertsPrefillPassBKernel::new(ctx, data_type)?,+ data_type,})}pub fn encode(&self,- encoder: &mut Encoder<B>,args: MoeExpertsTwoPassArguments<B>,+ encoder: &mut Encoder<B>,) -> Result<Allocation<B>, B::Error> {- let tile_counts = self.tile_map.encode_counts(encoder, args.expert_offsets, args.e)?;+ let mut tile_counts = encoder.allocate_scratch(size_for_shape(&[args.num_routed_experts], DataType::U32))?;+ self.counts.encode(args.expert_offsets, &mut tile_counts, args.num_routed_experts as u32, encoder);- let tile_scan = self.tile_map.encode_scan(encoder, &tile_counts, args.e)?;+ let mut tile_offsets =+ encoder.allocate_scratch(size_for_shape(&[args.num_routed_experts + 1], DataType::U32))?;+ let mut total_tiles = encoder.allocate_scratch(size_for_shape(&[8], DataType::U32))?;+ self.scan.encode(&tile_counts, &mut tile_offsets, &mut total_tiles, args.num_routed_experts as u32, encoder);- let tile_map = self.tile_map.encode_build_map(- encoder,+ let mut tile_map = encoder.allocate_scratch(size_for_shape(&[args.total_rows * 3], DataType::U32))?;+ self.build.encode(args.expert_offsets,- &tile_scan.tile_offsets,+ &tile_offsets,&tile_counts,- args.total_rows,- args.e,- )?;- let d_model_u32 = args.d_model as u32;- let d_ff_u32 = args.d_ff as u32;- const COL_TILE_FF: u32 = 32; // Must match PASSA_BN in kernel- const COL_TILE_MODEL: u32 = 64;- let n_tiles_ff = if d_ff_u32 == 0 {- 0- } else {- (d_ff_u32 + COL_TILE_FF - 1) / COL_TILE_FF- };- let n_tiles_model = if d_model_u32 == 0 {- 0- } else {- (d_model_u32 + COL_TILE_MODEL - 1) / COL_TILE_MODEL- };- let pass_a_dispatch_args = self.tile_map.encode_dispatch_args(encoder, &tile_scan.total_tiles, n_tiles_ff)?;+ &mut tile_map,+ args.num_routed_experts as u32,+ encoder,+ );++ const COL_TILE_FF: usize = 32; // Must match PASSA_BN in kernel+ let n_tiles_ff = args.d_ff.div_ceil(COL_TILE_FF) as u32;++ let mut pass_a_dispatch_args = encoder.allocate_scratch(size_for_shape(&[3], DataType::U32))?;+ self.dispatch.encode(&total_tiles, &mut pass_a_dispatch_args, n_tiles_ff, encoder);- let gate_idx = args.gating_code.min(3) as usize;- let dtype_idx = DTYPES.iter().position(|t| *t == args.data_type).unwrap();let mut hidden = encoder.allocate_scratch(size_for_shape(&[args.total_rows, args.d_ff], DataType::F32))?;encoder.encode_fill(&mut hidden, 0);- let kernel_pass_a = &self.pass_a_indirect[gate_idx][dtype_idx];- kernel_pass_a.encode(+ self.pass_a_indirect.encode(args.x_perm,args.expert_offsets,args.w13_all,@@ -90,7 +77,7 @@ impl<B: Backend> MoeExpertsTwoPassPrefillBlock<B> {&mut hidden,args.d_model as u32,args.d_ff as u32,- args.e as u32,+ args.num_routed_experts as u32,args.gate_clip_min,args.gate_clip_max,args.up_clip_min,@@ -101,12 +88,14 @@ impl<B: Backend> MoeExpertsTwoPassPrefillBlock<B> {encoder,);- let pass_b_dispatch_args =- self.tile_map.encode_dispatch_args(encoder, &tile_scan.total_tiles, n_tiles_model)?;+ const COL_TILE_MODEL: usize = 64;+ let n_tiles_model = args.d_model.div_ceil(COL_TILE_MODEL) as u32;++ let mut pass_b_dispatch_args = encoder.allocate_scratch(size_for_shape(&[3], DataType::U32))?;+ self.dispatch.encode(&total_tiles, &mut pass_b_dispatch_args, n_tiles_model, encoder);- let mut output = encoder.allocate_scratch(size_for_shape(&[args.total_rows, args.d_model], args.data_type))?;- let kernel_pass_b = &self.pass_b_indirect[dtype_idx];- kernel_pass_b.encode(+ let mut output = encoder.allocate_scratch(size_for_shape(&[args.total_rows, args.d_model], self.data_type))?;+ self.pass_b_indirect.encode(&hidden,args.expert_offsets,args.w2_all,@@ -114,7 +103,7 @@ impl<B: Backend> MoeExpertsTwoPassPrefillBlock<B> {&mut output,args.d_model as u32,args.d_ff as u32,- args.e as u32,+ args.num_routed_experts as u32,&tile_map,&pass_b_dispatch_args,encoder,@@ -133,12 +122,10 @@ pub struct MoeExpertsTwoPassArguments<'a, B: Backend> {pub total_rows: usize,pub d_model: usize,pub d_ff: usize,- pub e: usize,- pub gating_code: u32,+ pub num_routed_experts: usize,pub gate_clip_min: f32,pub gate_clip_max: f32,pub up_clip_min: f32,pub up_clip_max: f32,pub silu_alpha: f32,- pub data_type: DataType,}diff --git a/crates/backend-uzu/src/backends/common/kernel/moe/gather.rs b/crates/backend-uzu/src/backends/common/kernel/moe/gather.rsindex ad740ad4d..5a263d2d3 100644--- a/crates/backend-uzu/src/backends/common/kernel/moe/gather.rs+++ b/crates/backend-uzu/src/backends/common/kernel/moe/gather.rs@@ -7,72 +7,68 @@ use crate::{},};-pub struct MoeGatherArguments<'a, B: Backend> {- pub x: &'a Allocation<B>,- pub bucketed_ids: &'a Allocation<B>,- pub sumk: &'a Allocation<B>,- pub t: usize,- pub k: usize,- pub d_model: usize,+enum MoeGatherKernelType<B: Backend> {+ OneD(<B::Kernels as Kernels>::MoeGatherXPerm1DKernel),+ TwoD(<B::Kernels as Kernels>::MoeGatherXPerm2DKernel),}-pub struct MoeGatherKernels<B: Backend> {- bf16: <B::Kernels as Kernels>::MoeGatherXPerm2DKernel,- f16: <B::Kernels as Kernels>::MoeGatherXPerm1DKernel,- f32: <B::Kernels as Kernels>::MoeGatherXPerm1DKernel,+pub struct MoeGatherKernel<B: Backend> {+ kernel: MoeGatherKernelType<B>,+ data_type: DataType,}-impl<B: Backend> MoeGatherKernels<B> {- pub fn new(ctx: &B::Context) -> Result<Self, B::Error> {+impl<B: Backend> MoeGatherKernel<B> {+ pub fn new(+ ctx: &B::Context,+ data_type: DataType,+ ) -> Result<Self, B::Error> {Ok(Self {- bf16: <B::Kernels as Kernels>::MoeGatherXPerm2DKernel::new(ctx, DataType::BF16)?,- f16: <B::Kernels as Kernels>::MoeGatherXPerm1DKernel::new(ctx, DataType::F16)?,- f32: <B::Kernels as Kernels>::MoeGatherXPerm1DKernel::new(ctx, DataType::F32)?,+ kernel: if data_type == DataType::BF16 {+ MoeGatherKernelType::TwoD(<B::Kernels as Kernels>::MoeGatherXPerm2DKernel::new(ctx, data_type)?)+ } else {+ MoeGatherKernelType::OneD(<B::Kernels as Kernels>::MoeGatherXPerm1DKernel::new(ctx, data_type)?)+ },+ data_type,})}pub fn encode(&self,+ input: &Allocation<B>,+ bucketed_ids: &Allocation<B>,+ sumk: &Allocation<B>,+ batch_dim: usize,+ num_active_experts: usize,+ d_model: usize,encoder: &mut Encoder<B>,- dtype: DataType,- args: MoeGatherArguments<B>,) -> Result<Allocation<B>, B::Error> {- let mut x_perm = encoder.allocate_scratch(size_for_shape(&[args.t * args.k, args.d_model], dtype))?;+ let mut x_perm =+ encoder.allocate_scratch(size_for_shape(&[batch_dim * num_active_experts, d_model], self.data_type))?;encoder.encode_fill(&mut x_perm, 0);- match dtype {- DataType::F32 => self.f32.encode(- args.x,- args.bucketed_ids,+ match &self.kernel {+ MoeGatherKernelType::OneD(kernel) => kernel.encode(+ input,+ bucketed_ids,&mut x_perm,- args.sumk,- args.d_model as u32,- args.t as u32,- args.k as u32,+ sumk,+ d_model as u32,+ batch_dim as u32,+ num_active_experts as u32,encoder,),- DataType::F16 => self.f16.encode(- args.x,- args.bucketed_ids,+ MoeGatherKernelType::TwoD(kernel) => kernel.encode(+ input,+ bucketed_ids,&mut x_perm,- args.sumk,- args.d_model as u32,- args.t as u32,- args.k as u32,+ sumk,+ d_model as u32,+ batch_dim as u32,+ num_active_experts as u32,encoder,),- DataType::BF16 => self.bf16.encode(- args.x,- args.bucketed_ids,- &mut x_perm,- args.sumk,- args.d_model as u32,- args.t as u32,- args.k as u32,- encoder,- ),- _ => panic!("Unsupported data type: {:?}", dtype),};+Ok(x_perm)}}diff --git a/crates/backend-uzu/src/backends/common/kernel/moe/mod.rs b/crates/backend-uzu/src/backends/common/kernel/moe/mod.rsindex a7dc41735..0da69a0fe 100644--- a/crates/backend-uzu/src/backends/common/kernel/moe/mod.rs+++ b/crates/backend-uzu/src/backends/common/kernel/moe/mod.rs@@ -2,12 +2,8 @@ mod experts_single;mod experts_two_pass_decode;mod experts_two_pass_prefill;mod gather;-mod tiles_map;-mod tiles_pass_a;pub use experts_single::{MoeExpertsSingleDecodeArguments, MoeExpertsSingleDecodeKernels};pub use experts_two_pass_decode::MoeExpertsTwoPassDecodeBlock;pub use experts_two_pass_prefill::{MoeExpertsTwoPassArguments, MoeExpertsTwoPassPrefillBlock};-pub use gather::{MoeGatherArguments, MoeGatherKernels};-pub use tiles_map::{MoeTileMapKernels, MoeTileScanOutput};-pub use tiles_pass_a::{MoePassATileKernels, MoePassATileScanOutput};+pub use gather::MoeGatherKernel;diff --git a/crates/backend-uzu/src/backends/common/kernel/moe/tiles_map.rs b/crates/backend-uzu/src/backends/common/kernel/moe/tiles_map.rsdeleted file mode 100644index b549a6801..000000000--- a/crates/backend-uzu/src/backends/common/kernel/moe/tiles_map.rs+++ /dev/null@@ -1,82 +0,0 @@-use crate::{- DataType,- array::size_for_shape,- backends::common::{- Allocation, Backend, Encoder, Kernels,- kernel::{MoeBuildTileMapKernel, MoeTileCountsKernel, MoeTileScanKernel, MoeWriteDispatchArgsKernel},- },-};--pub struct MoeTileMapKernels<B: Backend> {- counts: <B::Kernels as Kernels>::MoeTileCountsKernel,- scan: <B::Kernels as Kernels>::MoeTileScanKernel,- build: <B::Kernels as Kernels>::MoeBuildTileMapKernel,- dispatch: <B::Kernels as Kernels>::MoeWriteDispatchArgsKernel,-}--impl<B: Backend> MoeTileMapKernels<B> {- pub fn new(ctx: &B::Context) -> Result<Self, B::Error> {- Ok(Self {- counts: <B::Kernels as Kernels>::MoeTileCountsKernel::new(ctx)?,- scan: <B::Kernels as Kernels>::MoeTileScanKernel::new(ctx)?,- build: <B::Kernels as Kernels>::MoeBuildTileMapKernel::new(ctx)?,- dispatch: <B::Kernels as Kernels>::MoeWriteDispatchArgsKernel::new(ctx)?,- })- }-- pub fn encode_counts(- &self,- encoder: &mut Encoder<B>,- offsets: &Allocation<B>,- e: usize,- ) -> Result<Allocation<B>, B::Error> {- let mut tile_counts = encoder.allocate_scratch(size_for_shape(&[e], DataType::U32))?;- self.counts.encode(offsets, &mut tile_counts, e as u32, encoder);- Ok(tile_counts)- }-- pub fn encode_scan(- &self,- encoder: &mut Encoder<B>,- tile_counts: &Allocation<B>,- e: usize,- ) -> Result<MoeTileScanOutput<B>, B::Error> {- let mut tile_offsets = encoder.allocate_scratch(size_for_shape(&[e + 1], DataType::U32))?;- let mut total_tiles = encoder.allocate_scratch(size_for_shape(&[8], DataType::U32))?;- self.scan.encode(tile_counts, &mut tile_offsets, &mut total_tiles, e as u32, encoder);- Ok(MoeTileScanOutput {- tile_offsets,- total_tiles,- })- }-- pub fn encode_build_map(- &self,- encoder: &mut Encoder<B>,- expert_offsets: &Allocation<B>,- tile_offsets: &Allocation<B>,- tile_counts: &Allocation<B>,- total_rows: usize,- e: usize,- ) -> Result<Allocation<B>, B::Error> {- let mut tile_map = encoder.allocate_scratch(size_for_shape(&[total_rows * 3], DataType::U32))?;- self.build.encode(expert_offsets, tile_offsets, tile_counts, &mut tile_map, e as u32, encoder);- Ok(tile_map)- }-- pub fn encode_dispatch_args(- &self,- encoder: &mut Encoder<B>,- total_tiles: &Allocation<B>,- num_tiles_x: u32,- ) -> Result<Allocation<B>, B::Error> {- let mut dispatch_args = encoder.allocate_scratch(size_for_shape(&[3], DataType::U32))?;- self.dispatch.encode(total_tiles, &mut dispatch_args, num_tiles_x, encoder);- Ok(dispatch_args)- }-}--pub struct MoeTileScanOutput<B: Backend> {- pub tile_offsets: Allocation<B>,- pub total_tiles: Allocation<B>,-}diff --git a/crates/backend-uzu/src/backends/common/kernel/moe/tiles_pass_a.rs b/crates/backend-uzu/src/backends/common/kernel/moe/tiles_pass_a.rsdeleted file mode 100644index ad8fc9b47..000000000--- a/crates/backend-uzu/src/backends/common/kernel/moe/tiles_pass_a.rs+++ /dev/null@@ -1,109 +0,0 @@-use crate::{- DataType,- array::size_for_shape,- backends::common::{- Allocation, Backend, Encoder,- kernel::{- Kernels, MoePassABuildRowMapKernel, MoePassABuildTileMapKernel, MoePassATileCountsKernel,- MoePassATileScanKernel, MoePassAWriteDispatchArgsKernel,- },- },-};--pub struct MoePassATileScanOutput<B: Backend> {- pub tile_offsets: Allocation<B>,- pub total_tiles: Allocation<B>,-}--pub struct MoePassATileKernels<B: Backend> {- counts: <B::Kernels as Kernels>::MoePassATileCountsKernel,- scan: <B::Kernels as Kernels>::MoePassATileScanKernel,- row_map: <B::Kernels as Kernels>::MoePassABuildRowMapKernel,- build_map: <B::Kernels as Kernels>::MoePassABuildTileMapKernel,- dispatch: <B::Kernels as Kernels>::MoePassAWriteDispatchArgsKernel,-}--impl<B: Backend> MoePassATileKernels<B> {- pub fn new(ctx: &B::Context) -> Result<Self, B::Error> {- Ok(Self {- counts: <B::Kernels as Kernels>::MoePassATileCountsKernel::new(ctx)?,- scan: <B::Kernels as Kernels>::MoePassATileScanKernel::new(ctx)?,- row_map: <B::Kernels as Kernels>::MoePassABuildRowMapKernel::new(ctx)?,- build_map: <B::Kernels as Kernels>::MoePassABuildTileMapKernel::new(ctx)?,- dispatch: <B::Kernels as Kernels>::MoePassAWriteDispatchArgsKernel::new(ctx)?,- })- }-- pub fn encode_counts(- &self,- encoder: &mut Encoder<B>,- expert_offsets: &Allocation<B>,- e: usize,- h_blocks: u32,- ) -> Result<Allocation<B>, B::Error> {- let mut tile_counts = encoder.allocate_scratch(size_for_shape(&[e], DataType::U32))?;- self.counts.encode(expert_offsets, &mut tile_counts, e as u32, h_blocks, encoder);- Ok(tile_counts)- }-- pub fn encode_scan(- &self,- encoder: &mut Encoder<B>,- tile_counts: &Allocation<B>,- e: usize,- ) -> Result<MoePassATileScanOutput<B>, B::Error> {- let mut tile_offsets = encoder.allocate_scratch(size_for_shape(&[e + 1], DataType::U32))?;- let mut total_tiles = encoder.allocate_scratch(size_for_shape(&[1], DataType::U32))?;- self.scan.encode(tile_counts, &mut tile_offsets, &mut total_tiles, e as u32, encoder);- Ok(MoePassATileScanOutput {- tile_offsets,- total_tiles,- })- }-- pub fn encode_row_map(- &self,- encoder: &mut Encoder<B>,- expert_offsets: &Allocation<B>,- total_rows: usize,- e: usize,- ) -> Result<Allocation<B>, B::Error> {- let mut row_expert_map = encoder.allocate_scratch(size_for_shape(&[total_rows], DataType::U32))?;- self.row_map.encode(expert_offsets, &mut row_expert_map, total_rows as u32, e as u32, encoder);- Ok(row_expert_map)- }-- pub fn encode_build_map(- &self,- encoder: &mut Encoder<B>,- expert_offsets: &Allocation<B>,- tile_offsets: &Allocation<B>,- row_expert_map: &Allocation<B>,- total_rows: usize,- h_blocks: u32,- ) -> Result<Allocation<B>, B::Error> {- let mut tile_map =- encoder.allocate_scratch(size_for_shape(&[total_rows * h_blocks as usize * 3], DataType::U32))?;- self.build_map.encode(- expert_offsets,- tile_offsets,- row_expert_map,- &mut tile_map,- total_rows as u32,- h_blocks,- encoder,- );- Ok(tile_map)- }-- pub fn encode_dispatch_args(- &self,- encoder: &mut Encoder<B>,- total_tiles: &Allocation<B>,- num_tiles_y: u32,- ) -> Result<Allocation<B>, B::Error> {- let mut dispatch_args = encoder.allocate_scratch(size_for_shape(&[3], DataType::U32))?;- self.dispatch.encode(total_tiles, &mut dispatch_args, num_tiles_y, encoder);- Ok(dispatch_args)- }-}diff --git a/crates/backend-uzu/src/encodable_block/mlp/moe.rs b/crates/backend-uzu/src/encodable_block/mlp/moe.rsindex a12621c8e..b118420a7 100644--- a/crates/backend-uzu/src/encodable_block/mlp/moe.rs+++ b/crates/backend-uzu/src/encodable_block/mlp/moe.rs@@ -13,7 +13,7 @@ use crate::{MoeScatterBucketsMapKernel,moe::{MoeExpertsTwoPassArguments, MoeExpertsTwoPassDecodeBlock, MoeExpertsTwoPassPrefillBlock,- MoeGatherArguments, MoeGatherKernels,+ MoeGatherKernel,},},},@@ -22,34 +22,32 @@ use crate::{parameters::{ParameterLoaderError, ParameterTree},};-struct RouterBlock<B: Backend> {- weights: Allocation<B>,- biases: Allocation<B>,-}--struct SharedMoeWeights<B: Backend> {- pub w13: Allocation<B>,- pub w2: Allocation<B>,- pub up_biases: Allocation<B>,- pub down_biases: Allocation<B>,-}-pub struct MoeBlock<B: Backend> {- router: RouterBlock<B>,- router_renorm: bool,router_topk_kernel: <B::Kernels as Kernels>::MoeRouterTopKKernel,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_kernels: MoeGatherKernels<B>,- experts_two_pass_decode_kernel: MoeExpertsTwoPassDecodeBlock<B>,- experts_two_pass_prefill_kernel: MoeExpertsTwoPassPrefillBlock<B>,+ gather_kernel: MoeGatherKernel<B>,+ experts_two_pass_decode_block: MoeExpertsTwoPassDecodeBlock<B>,+ experts_two_pass_prefill_block: MoeExpertsTwoPassPrefillBlock<B>,finalize_kernel: <B::Kernels as Kernels>::MoeFinalizeKernel,- moe_config: MixtureOfExpertsConfig,+ router_weights: Allocation<B>,+ router_biases: Allocation<B>,+ router_renorm: bool,+ w13: Allocation<B>,+ w2: Allocation<B>,+ up_biases: Allocation<B>,+ down_biases: Allocation<B>,model_dim: usize,hidden_dim: usize,+ num_routed_experts: usize,+ num_active_experts: usize,+ gate_clip_min: f32,+ gate_clip_max: f32,+ up_clip_min: f32,+ up_clip_max: f32,+ silu_alpha: f32,data_type: DataType,- shared_weights: SharedMoeWeights<B>,}#[derive(Debug, Error)]@@ -58,7 +56,11 @@ pub enum MoeBlockError<B: Backend> {BackendError(#[source] B::Error),#[error("Parameter loader error: {0}")]ParameterLoaderError(#[from] ParameterLoaderError<B>),- #[error("MoE num_active_routed_experts must be greater than 0")]+ #[error("MoE requires model_dim % 4 == 0")]+ InvalidModelDim,+ #[error("MoE num_routed_experts must be <= 512")]+ InvalidRoutedExpertCount,+ #[error("MoE num_active_routed_experts must be > 0 and <= 128")]InvalidActiveExpertCount,#[error("MoE shared experts are not supported")]UnsupportedSharedExperts,@@ -73,32 +75,43 @@ impl<B: Backend> MoeBlock<B> {model_dim: usize,parameter_tree: &ParameterTree<B::Context>,) -> Result<Self, MoeBlockError<B>> {- if moe_config.num_active_routed_experts == 0 {+ if model_dim % 4 != 0 {+ return Err(MoeBlockError::InvalidModelDim);+ }+ if moe_config.num_active_routed_experts == 0 || moe_config.num_active_routed_experts > 128 {return Err(MoeBlockError::InvalidActiveExpertCount);}+ if moe_config.num_routed_experts > 512 {+ return Err(MoeBlockError::InvalidRoutedExpertCount);+ }if moe_config.num_shared_experts != 0 {return Err(MoeBlockError::UnsupportedSharedExperts);}if moe_config.gate_config.is_some() {return Err(MoeBlockError::UnsupportedExpertGate);}+let data_type: DataType = moe_config.expert_config.linear_config.activation_precision().into();+ let gating_code = match moe_config.expert_config.activation.act_type() {+ ActivationType::GELU => 3,+ ActivationType::SILU {+ ..+ } => 2,+ _ => {+ panic!("{:?} is not supported for MoE kernels", moe_config.expert_config.activation.act_type())+ },+ };let router_data_type: DataType = moe_config.router_config.activation_precision().into();let router_renorm = matches!(moe_config.routing_function, RoutingFunctionConfig::SoftmaxRouting);let router_tree = parameter_tree.subtree("router")?;- let LinearConfig::FullPrecision {- ..- } = &moe_config.router_config- else {+ if !matches!(moe_config.router_config, LinearConfig::FullPrecision { .. }) {unimplemented!("Only FullPrecision MoE router is supported; got {:?}", moe_config.router_config);- };- let router = RouterBlock {- weights: router_tree.leaf_allocation("weights")?,- biases: router_tree.leaf_allocation("biases")?,- };+ }+ let router_weights = router_tree.leaf_allocation("weights")?;+ let router_biases = router_tree.leaf_allocation("biases")?;let router_topk_kernel = <B::Kernels as Kernels>::MoeRouterTopKKernel::new(context, router_data_type).map_err(MoeBlockError::BackendError)?;@@ -109,54 +122,54 @@ 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 = MoeGatherKernels::new(context).map_err(MoeBlockError::BackendError)?;- let experts_two_pass_decode_kernel =- MoeExpertsTwoPassDecodeBlock::new(context).map_err(MoeBlockError::BackendError)?;- let experts_two_pass_prefill_kernel =- MoeExpertsTwoPassPrefillBlock::new(context).map_err(MoeBlockError::BackendError)?;+ let gather_kernels = MoeGatherKernel::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 =+ MoeExpertsTwoPassPrefillBlock::new(context, data_type, gating_code).map_err(MoeBlockError::BackendError)?;let finalize_kernel =<B::Kernels as Kernels>::MoeFinalizeKernel::new(context, data_type).map_err(MoeBlockError::BackendError)?;let experts_tree = parameter_tree.subtree("experts")?;let up_tree = experts_tree.subtree("up_projection")?;let down_tree = experts_tree.subtree("down_projection")?;- let shared_weights = SharedMoeWeights {- w13: up_tree.leaf_allocation("weights")?,- w2: down_tree.leaf_allocation("weights")?,- up_biases: up_tree.leaf_allocation("biases")?,- down_biases: down_tree.leaf_allocation("biases")?,- };++ let w13 = up_tree.leaf_allocation("weights")?;+ let w2 = down_tree.leaf_allocation("weights")?;+ let up_biases = up_tree.leaf_allocation("biases")?;+ let down_biases = down_tree.leaf_allocation("biases")?;++ let (gate_lo, gate_hi) = moe_config.expert_config.gate_clipping.unwrap_or_default();+ let (up_lo, up_hi) = moe_config.expert_config.up_clipping.unwrap_or_default();Ok(Self {- router,- router_renorm,router_topk_kernel,counts_offsets_kernel,scatter_bases_kernel,scatter_map_kernel,- gather_kernels,- experts_two_pass_decode_kernel,- experts_two_pass_prefill_kernel,+ gather_kernel: gather_kernels,+ experts_two_pass_decode_block,+ experts_two_pass_prefill_block,finalize_kernel,- moe_config: moe_config.clone(),+ router_weights,+ router_biases,+ router_renorm,+ w13,+ w2,+ up_biases,+ down_biases,model_dim,hidden_dim: moe_config.expert_hidden_dim,+ num_routed_experts: moe_config.num_routed_experts,+ num_active_experts: moe_config.num_active_routed_experts,+ gate_clip_min: gate_lo.unwrap_or(f32::NEG_INFINITY),+ gate_clip_max: gate_hi.unwrap_or(f32::INFINITY),+ up_clip_min: up_lo.unwrap_or(f32::NEG_INFINITY),+ up_clip_max: up_hi.unwrap_or(f32::INFINITY),+ silu_alpha: moe_config.expert_config.activation.alpha(),data_type,- shared_weights,})}-- fn gating_code_from_activation(activation: &ActivationType) -> u32 {- match activation {- ActivationType::GELU => 3,- ActivationType::SILU {- ..- } => 2,- _ => {- panic!("{:?} is not supported for MoE kernels", activation)- },- }- }}impl<B: Backend> Mlp<B> for MoeBlock<B> {@@ -166,52 +179,32 @@ impl<B: Backend> Mlp<B> for MoeBlock<B> {batch_dim: usize,encoder: &mut Encoder<B>,) -> Result<Allocation<B>, B::Error> {- let suffix_length = batch_dim;- if suffix_length == 0 {- return Ok(input);- }-- let e = self.moe_config.num_routed_experts;- let k = self.moe_config.num_active_routed_experts;- let total_rows = suffix_length * k;- let num_blocks = suffix_length.div_ceil(256).max(1);- let num_tiles = e.div_ceil(512).max(1);-- // Use fused Router+TopK kernel for non-quantized routers- if self.model_dim % 4 != 0 {- panic!("MoE fused router+topk failed: {} % 4 != 0", self.model_dim);- }- if e > 512 {- panic!("MoE fused router+topk failed: {e} > 512");- }- if k > 128 {- panic!("MoE fused router+bottomk failed: {k} > 128");- }-- let mut topk_ids = encoder.allocate_scratch(size_for_shape(&[suffix_length, k], DataType::I32))?;- let mut topk_probs = encoder.allocate_scratch(size_for_shape(&[suffix_length, k], self.data_type))?;-- if suffix_length > 0 && k > 0 {- encoder.encode_fill(&mut topk_ids, 0xFF);- }-- if suffix_length > 0 && e > 0 && k > 0 {- self.router_topk_kernel.encode(- &input,- &self.router.weights,- &self.router.biases,- &mut topk_ids,- &mut topk_probs,- suffix_length as u32,- self.model_dim as u32,- e as u32,- k as u32,- self.router_renorm,- encoder,- );- }+ let total_rows = batch_dim * self.num_active_experts;+ let num_blocks = batch_dim.div_ceil(256);+ let num_tiles = self.num_routed_experts.div_ceil(512);++ let mut topk_ids =+ encoder.allocate_scratch(size_for_shape(&[batch_dim, self.num_active_experts], DataType::I32))?;+ let mut topk_probs =+ encoder.allocate_scratch(size_for_shape(&[batch_dim, self.num_active_experts], self.data_type))?;++ encoder.encode_fill(&mut topk_ids, 0xFF);++ self.router_topk_kernel.encode(+ &input,+ &self.router_weights,+ &self.router_biases,+ &mut topk_ids,+ &mut topk_probs,+ batch_dim as u32,+ self.model_dim as u32,+ self.num_routed_experts as u32,+ self.num_active_experts as u32,+ self.router_renorm,+ encoder,+ );- let mut offsets = encoder.allocate_scratch(size_for_shape(&[e + 1], DataType::U32))?;+ let mut offsets = encoder.allocate_scratch(size_for_shape(&[self.num_routed_experts + 1], DataType::U32))?;let mut sumk = encoder.allocate_scratch(size_for_shape(&[1], DataType::U32))?;let scatter_entries = num_blocks * num_tiles * 512;let mut partials = encoder.allocate_scratch(size_for_shape(&[scatter_entries], DataType::U32))?;@@ -220,9 +213,9 @@ impl<B: Backend> Mlp<B> for MoeBlock<B> {&mut offsets,&mut sumk,&mut partials,- suffix_length as u32,- e as u32,- k as u32,+ batch_dim as u32,+ self.num_routed_experts as u32,+ self.num_active_experts as u32,encoder,);@@ -232,15 +225,13 @@ impl<B: Backend> Mlp<B> for MoeBlock<B> {let mut bucketed_probs = encoder.allocate_scratch(size_for_shape(&[total_rows], self.data_type))?;let mut tok2row = encoder.allocate_scratch(size_for_shape(&[total_rows], DataType::I32))?;- if suffix_length > 0 && k > 0 {- encoder.encode_fill(&mut tok2row, 0xFF);- }+ encoder.encode_fill(&mut tok2row, 0xFF);self.scatter_bases_kernel.encode(&partials,&mut block_bases,&mut block_alloc,- e as u32,+ self.num_routed_experts as u32,num_blocks as u32,num_tiles as u32,0u32,@@ -254,93 +245,58 @@ impl<B: Backend> Mlp<B> for MoeBlock<B> {&block_alloc,&mut bucketed_ids,&mut bucketed_probs,- suffix_length as u32,- e as u32,- k as u32,+ batch_dim as u32,+ self.num_routed_experts as u32,+ self.num_active_experts as u32,num_blocks as u32,num_tiles as u32,&mut tok2row,encoder,);- let x_perm = self.gather_kernels.encode(+ let x_perm = self.gather_kernel.encode(+ &input,+ &bucketed_ids,+ &sumk,+ batch_dim,+ self.num_active_experts,+ self.model_dim,encoder,- self.data_type,- MoeGatherArguments {- x: &input,- bucketed_ids: &bucketed_ids,- sumk: &sumk,- t: suffix_length,- k,- d_model: self.model_dim,- },)?;- let gating_code = Self::gating_code_from_activation(&self.moe_config.expert_config.activation.act_type());-- let (gate_lo, gate_hi) = self.moe_config.expert_config.gate_clipping.unwrap_or_default();- let (up_lo, up_hi) = self.moe_config.expert_config.up_clipping.unwrap_or_default();- let gate_clip_min = gate_lo.unwrap_or(f32::NEG_INFINITY);- let gate_clip_max = gate_hi.unwrap_or(f32::INFINITY);- let up_clip_min = up_lo.unwrap_or(f32::NEG_INFINITY);- let up_clip_max = up_hi.unwrap_or(f32::INFINITY);- let silu_alpha = self.moe_config.expert_config.activation.alpha();+ let args = MoeExpertsTwoPassArguments {+ x_perm: &x_perm,+ expert_offsets: &offsets,+ w13_all: &self.w13,+ w2_all: &self.w2,+ up_biases: &self.up_biases,+ down_biases: &self.down_biases,+ total_rows,+ d_model: self.model_dim,+ d_ff: self.hidden_dim,+ num_routed_experts: self.num_routed_experts,+ gate_clip_min: self.gate_clip_min,+ gate_clip_max: self.gate_clip_max,+ up_clip_min: self.up_clip_min,+ up_clip_max: self.up_clip_max,+ silu_alpha: self.silu_alpha,+ };- let y_partial = if suffix_length == 1 {- self.experts_two_pass_decode_kernel.encode(- encoder,- MoeExpertsTwoPassArguments {- x_perm: &x_perm,- expert_offsets: &offsets,- w13_all: &self.shared_weights.w13,- w2_all: &self.shared_weights.w2,- up_biases: &self.shared_weights.up_biases,- down_biases: &self.shared_weights.down_biases,- total_rows,- d_model: self.model_dim,- d_ff: self.hidden_dim,- e,- gating_code,- gate_clip_min,- gate_clip_max,- up_clip_min,- up_clip_max,- silu_alpha,- data_type: self.data_type,- },- )?+ let y_partial = if batch_dim == 1 {+ self.experts_two_pass_decode_block.encode(args, encoder)?} else {- let args = MoeExpertsTwoPassArguments {- x_perm: &x_perm,- expert_offsets: &offsets,- w13_all: &self.shared_weights.w13,- w2_all: &self.shared_weights.w2,- up_biases: &self.shared_weights.up_biases,- down_biases: &self.shared_weights.down_biases,- total_rows,- d_model: self.model_dim,- d_ff: self.hidden_dim,- e,- gating_code,- gate_clip_min,- gate_clip_max,- up_clip_min,- up_clip_max,- silu_alpha,- data_type: self.data_type,- };- self.experts_two_pass_prefill_kernel.encode(encoder, args)?+ self.experts_two_pass_prefill_block.encode(args, encoder)?};- let mut output = encoder.allocate_scratch(size_for_shape(&[suffix_length, self.model_dim], self.data_type))?;+ let mut output = encoder.allocate_scratch(size_for_shape(&[batch_dim, self.model_dim], self.data_type))?;self.finalize_kernel.encode(&tok2row,&topk_probs,&y_partial,&mut output,- suffix_length as u32,+ batch_dim as u32,self.model_dim as u32,- k as u32,+ self.num_active_experts as u32,encoder,);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.rsindex 544285f2a..08dd1a400 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@@ -73,7 +73,7 @@ fn run_decode_case<B: Backend>(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).expect("experts decode kernel");+ let experts_kernel = MoeExpertsTwoPassDecodeBlock::<B>::new(ctx, DataType::BF16, 2).expect("experts 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);@@ -86,7 +86,6 @@ fn run_decode_case<B: Backend>(let mut encoder = Encoder::new(ctx).expect("Failed to create encoder");let output = experts_kernel.encode(- &mut encoder,MoeExpertsTwoPassArguments {x_perm: &x_perm_buf,expert_offsets: &offsets_buf,@@ -97,15 +96,14 @@ fn run_decode_case<B: Backend>(total_rows: sum_k,d_model,d_ff,- e,- gating_code: 2,+ 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.702,- data_type: DataType::BF16,},+ &mut encoder,).expect("failed to encode MoE experts");let completed = encoder.end_encoding().submit().wait_until_completed().unwrap();@@ -119,7 +117,6 @@ fn run_decode_case<B: Backend>(let mut encoder = Encoder::new(ctx).expect("Failed to create encoder");let output = experts_kernel.encode(- &mut encoder,MoeExpertsTwoPassArguments {x_perm: &x_perm_buf,expert_offsets: &offsets_buf,@@ -130,15 +127,14 @@ fn run_decode_case<B: Backend>(total_rows: sum_k,d_model,d_ff,- e,- gating_code: 2,+ 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.702,- data_type: DataType::BF16,},+ &mut encoder,).expect("failed to encode MoE experts");let completed = encoder.end_encoding().submit().wait_until_completed().unwrap();@@ -197,7 +193,8 @@ fn run_two_pass_prefill_case<B: Backend>(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 = MoeExpertsTwoPassPrefillBlock::<B>::new(ctx).expect("experts prefill kernel");+ let experts_kernel =+ MoeExpertsTwoPassPrefillBlock::<B>::new(ctx, DataType::BF16, 2).expect("experts prefill 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);@@ -218,16 +215,14 @@ fn run_two_pass_prefill_case<B: Backend>(total_rows: sum_k,d_model,d_ff,- e,- gating_code: 2,+ 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.702,- data_type: DataType::BF16,};- let output = experts_kernel.encode(&mut encoder, args).expect("failed to encode MoE experts");+ let output = experts_kernel.encode(args, &mut encoder).expect("failed to encode MoE experts");let completed = encoder.end_encoding().submit().wait_until_completed().unwrap();drop(output);drop(completed);@@ -247,16 +242,14 @@ fn run_two_pass_prefill_case<B: Backend>(total_rows: sum_k,d_model,d_ff,- e,- gating_code: 2,+ 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.702,- data_type: DataType::BF16,};- let output = experts_kernel.encode(&mut encoder, args).expect("failed to encode MoE experts");+ let output = experts_kernel.encode(args, &mut encoder).expect("failed to encode MoE experts");let completed = encoder.end_encoding().submit().wait_until_completed().unwrap();drop(output);drop(completed);@@ -305,7 +298,7 @@ fn run_fused_single_token_case<B: Backend>(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).expect("fused kernel");+ 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);@@ -318,7 +311,6 @@ fn run_fused_single_token_case<B: Backend>(let mut encoder = Encoder::new(ctx).expect("Failed to create encoder");let output = fused_kernel.encode(- &mut encoder,MoeExpertsSingleDecodeArguments {x: &x_buf,topk_ids: &topk_ids_buf,@@ -330,14 +322,13 @@ fn run_fused_single_token_case<B: Backend>(d_model,d_ff,k,- gating_code: 2, // SwiGLUsilu_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,- data_type: DataType::BF16,},+ &mut encoder,).expect("failed to encode MoE experts");let completed = encoder.end_encoding().submit().wait_until_completed().unwrap();@@ -351,7 +342,6 @@ fn run_fused_single_token_case<B: Backend>(let mut encoder = Encoder::new(ctx).expect("Failed to create encoder");let output = fused_kernel.encode(- &mut encoder,MoeExpertsSingleDecodeArguments {x: &x_buf,topk_ids: &topk_ids_buf,@@ -363,14 +353,13 @@ fn run_fused_single_token_case<B: Backend>(d_model,d_ff,k,- gating_code: 2, // SwiGLUsilu_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,- data_type: DataType::BF16,},+ &mut encoder,).expect("failed to encode MoE experts");let completed = encoder.end_encoding().submit().wait_until_completed().unwrap();@@ -426,7 +415,7 @@ fn run_indirect_decode_timed<B: Backend>(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).expect("decode kernel");+ 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);@@ -439,7 +428,6 @@ fn run_indirect_decode_timed<B: Backend>(let mut encoder = Encoder::new(ctx).expect("Failed to create encoder");let output = experts_kernel.encode(- &mut encoder,MoeExpertsTwoPassArguments {x_perm: &x_perm_buf,expert_offsets: &offsets_buf,@@ -450,15 +438,14 @@ fn run_indirect_decode_timed<B: Backend>(total_rows: sum_k,d_model,d_ff,- e,- gating_code: 2,+ 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,- data_type: DataType::BF16,},+ &mut encoder,).expect("failed to encode MoE experts");let completed = encoder.end_encoding().submit().wait_until_completed().unwrap();@@ -472,7 +459,6 @@ fn run_indirect_decode_timed<B: Backend>(let mut encoder = Encoder::new(ctx).expect("Failed to create encoder");let output = experts_kernel.encode(- &mut encoder,MoeExpertsTwoPassArguments {x_perm: &x_perm_buf,expert_offsets: &offsets_buf,@@ -483,15 +469,14 @@ fn run_indirect_decode_timed<B: Backend>(total_rows: sum_k,d_model,d_ff,- e,- gating_code: 2,+ 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,- data_type: DataType::BF16,},+ &mut encoder,).expect("failed to encode MoE experts");let completed = encoder.end_encoding().submit().wait_until_completed().unwrap();@@ -530,7 +515,7 @@ fn run_fused_decode_timed<B: Backend>(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).expect("fused kernel");+ 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);@@ -543,7 +528,6 @@ fn run_fused_decode_timed<B: Backend>(let mut encoder = Encoder::new(ctx).expect("Failed to create encoder");let output = fused_kernel.encode(- &mut encoder,MoeExpertsSingleDecodeArguments {x: &x_buf,topk_ids: &topk_ids_buf,@@ -555,14 +539,13 @@ fn run_fused_decode_timed<B: Backend>(d_model,d_ff,k,- gating_code: 2,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,- data_type: DataType::BF16,},+ &mut encoder,).expect("failed to encode MoE experts");let completed = encoder.end_encoding().submit().wait_until_completed().unwrap();@@ -576,7 +559,6 @@ fn run_fused_decode_timed<B: Backend>(let mut encoder = Encoder::new(ctx).expect("Failed to create encoder");let output = fused_kernel.encode(- &mut encoder,MoeExpertsSingleDecodeArguments {x: &x_buf,topk_ids: &topk_ids_buf,@@ -588,14 +570,13 @@ fn run_fused_decode_timed<B: Backend>(d_model,d_ff,k,- gating_code: 2,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,- data_type: DataType::BF16,},+ &mut encoder,).expect("failed to encode MoE experts");let completed = encoder.end_encoding().submit().wait_until_completed().unwrap();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.rsindex b6a2950c4..8b9da4b14 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@@ -5,7 +5,7 @@ use backend_uzu::{kernel::{MoeBlockBasesFromPartialsKernel, MoeCountsOffsetsFusedKernel, MoeFinalizeKernel, MoeRouterTopKKernel,MoeScatterBucketsMapKernel,- moe::{MoeExpertsTwoPassArguments, MoeExpertsTwoPassDecodeBlock, MoeGatherArguments, MoeGatherKernels},+ moe::{MoeExpertsTwoPassArguments, MoeExpertsTwoPassDecodeBlock, MoeGatherKernel},},},};@@ -210,8 +210,9 @@ 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 = MoeGatherKernels::<B>::new(&ctx).expect("gather");- let experts_kernel = MoeExpertsTwoPassDecodeBlock::<B>::new(&ctx).expect("experts two-pass decode");+ let gather_kernel = MoeGatherKernel::<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 =<<B as Backend>::Kernels as Kernels>::MoeFinalizeKernel::new(&ctx, DataType::BF16).expect("finalize");let router_topk_fused_kernel =@@ -286,18 +287,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- .encode(- &mut encoder,- DataType::BF16,- MoeGatherArguments {- x: &x_buf,- bucketed_ids: &bucketed_ids_buf,- sumk: &sumk_buf,- t,- k,- d_model,- },- )+ .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();drop(x_perm);@@ -307,18 +297,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- .encode(- &mut encoder,- DataType::BF16,- MoeGatherArguments {- x: &x_buf,- bucketed_ids: &bucketed_ids_buf,- sumk: &sumk_buf,- t,- k,- d_model,- },- )+ .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();(x_perm, completed)@@ -328,7 +307,6 @@ fn test_moe_pipeline_breakdown_decode() {let mut encoder = Encoder::new(ctx.as_ref()).expect("Failed to create encoder");let output = experts_kernel.encode(- &mut encoder,MoeExpertsTwoPassArguments {x_perm: &x_perm_buf,expert_offsets: &offsets_buf,@@ -339,15 +317,14 @@ fn test_moe_pipeline_breakdown_decode() {total_rows: sum_k,d_model,d_ff,- e,- gating_code: 2, // SILU+ num_routed_experts: e,gate_clip_min: f32::NEG_INFINITY,gate_clip_max: 20.0,up_clip_min: -19.0,up_clip_max: 21.0,silu_alpha: 1.702,- data_type: DataType::BF16,},+ &mut encoder,).expect("failed to encode MoE experts");let completed = encoder.end_encoding().submit().wait_until_completed().unwrap();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.rsindex 64cc0747e..37d8c8b42 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,7 +6,7 @@ use backend_uzu::{kernel::{MoeBlockBasesFromPartialsKernel, MoeCountsOffsetsFusedKernel, MoeFinalizeKernel, MoeRouterTopKKernel,MoeScatterBucketsMapKernel,- moe::{MoeExpertsTwoPassArguments, MoeExpertsTwoPassPrefillBlock, MoeGatherArguments, MoeGatherKernels},+ moe::{MoeExpertsTwoPassArguments, MoeExpertsTwoPassPrefillBlock, MoeGatherKernel},},},};@@ -373,25 +373,12 @@ fn run_moe_parity_test_internal<B: Backend>(&mut encoder,);- let gather = MoeGatherKernels::<B>::new(&ctx).expect("gather");- let x_perm_buf = gather- .encode(- &mut encoder,- DataType::BF16,- MoeGatherArguments {- x: &x_buf,- bucketed_ids: &bucketed_ids_buf,- sumk: &sumk_buf,- t,- k,- d_model,- },- )- .expect("gather");+ let gather = MoeGatherKernel::<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;- let experts = MoeExpertsTwoPassPrefillBlock::<B>::new(&ctx).expect("experts");+ let experts = MoeExpertsTwoPassPrefillBlock::<B>::new(&ctx, DataType::BF16, gating_code).expect("experts");let args = MoeExpertsTwoPassArguments {x_perm: &x_perm_buf,expert_offsets: &offsets_buf,@@ -402,16 +389,14 @@ fn run_moe_parity_test_internal<B: Backend>(total_rows,d_model,d_ff,- e,- gating_code,+ num_routed_experts: e,gate_clip_min: gate_clip.0,gate_clip_max: gate_clip.1,up_clip_min: up_clip.0,up_clip_max: up_clip.1,silu_alpha,- data_type: DataType::BF16,};- let y_partial_buf = experts.encode(&mut encoder, args).expect("failed to encode MoE experts");+ let y_partial_buf = experts.encode(args, &mut encoder).expect("failed to encode MoE experts");let finalize = <B::Kernels as Kernels>::MoeFinalizeKernel::new(&ctx, DataType::BF16).expect("finalize");finalize.encode(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.rsindex 296a005fc..2240c5a41 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@@ -371,12 +371,12 @@ fn test_two_pass_decode_correctness() {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 experts_kernel = MoeExpertsTwoPassDecodeBlock::<B>::new(&ctx).expect("MoeExpertsTwoPassDecodeKernel::new");+ let experts_kernel = MoeExpertsTwoPassDecodeBlock::<B>::new(&ctx, DataType::BF16, gating_code)+ .expect("MoeExpertsTwoPassDecodeKernel::new");let mut encoder = Encoder::new(ctx.as_ref()).expect("Failed to create encoder");let y_partial_buf = experts_kernel.encode(- &mut encoder,MoeExpertsTwoPassArguments {x_perm: &x_perm_buf,expert_offsets: &offsets_buf,@@ -387,15 +387,14 @@ fn test_two_pass_decode_correctness() {total_rows: sum_k,d_model,d_ff,- e,- gating_code,+ 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,- data_type: DataType::BF16,},+ &mut encoder,).expect("failed to encode MoE experts");@@ -496,11 +495,10 @@ fn test_two_pass_decode_multi_token() {let up_biases_buf = alloc_allocation_with_data::<B, bf16>(&ctx, &data.up_biases);let down_biases_buf = alloc_allocation_with_data::<B, bf16>(&ctx, &data.down_biases);- let experts_kernel = MoeExpertsTwoPassDecodeBlock::<B>::new(&ctx).expect("kernel");+ let experts_kernel = MoeExpertsTwoPassDecodeBlock::<B>::new(&ctx, DataType::BF16, gating_code).expect("kernel");let mut encoder = Encoder::new(ctx.as_ref()).expect("Failed to create encoder");let y_partial_buf = experts_kernel.encode(- &mut encoder,MoeExpertsTwoPassArguments {x_perm: &x_perm_buf,expert_offsets: &offsets_buf,@@ -511,15 +509,14 @@ fn test_two_pass_decode_multi_token() {total_rows: sum_k,d_model,d_ff,- e,- gating_code,+ 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,- data_type: DataType::BF16,},+ &mut encoder,).expect("failed to encode MoE experts");let completed = encoder.end_encoding().submit().wait_until_completed().unwrap();@@ -582,7 +579,8 @@ fn test_two_pass_prefill_correctness() {let up_biases_buf = alloc_allocation_with_data::<B, bf16>(&ctx, &data.up_biases);let down_biases_buf = alloc_allocation_with_data::<B, bf16>(&ctx, &data.down_biases);- let experts_kernel = MoeExpertsTwoPassPrefillBlock::<B>::new(&ctx).expect("kernel");+ let experts_kernel =+ MoeExpertsTwoPassPrefillBlock::<B>::new(&ctx, DataType::BF16, gating_code).expect("kernel");let mut encoder = Encoder::new(ctx.as_ref()).expect("Failed to create encoder");let args = MoeExpertsTwoPassArguments {x_perm: &x_perm_buf,@@ -594,16 +592,14 @@ fn test_two_pass_prefill_correctness() {total_rows: sum_k,d_model,d_ff,- e,- gating_code,+ 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,- data_type: DataType::BF16,};- let y_partial_buf = experts_kernel.encode(&mut encoder, args).expect("failed to encode MoE experts");+ let y_partial_buf = experts_kernel.encode(args, &mut encoder).expect("failed to encode MoE experts");let completed = encoder.end_encoding().submit().wait_until_completed().unwrap();let y_partial_gpu = allocation_prefix_to_vec::<B, bf16>(&y_partial_buf, sum_k * d_model);@@ -702,12 +698,12 @@ fn test_fused_single_token_decode() {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).expect("MoeExpertsSingleDecodeKernel::new");+ 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(- &mut encoder,MoeExpertsSingleDecodeArguments {x: &x_buf,topk_ids: &topk_ids_buf,@@ -719,14 +715,13 @@ fn test_fused_single_token_decode() {d_model,d_ff,k,- gating_code,silu_alpha: 1.0, // Standard SiLU for testinggate_clip_min: f32::NEG_INFINITY,gate_clip_max: f32::INFINITY,up_clip_min: f32::NEG_INFINITY,up_clip_max: f32::INFINITY,- data_type: DataType::BF16,},+ &mut encoder,).expect("failed to encode MoE experts");@@ -827,11 +822,11 @@ fn test_fused_single_token_k4() {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).expect("fused kernel");+ 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(- &mut encoder,MoeExpertsSingleDecodeArguments {x: &x_buf,topk_ids: &topk_ids_buf,@@ -843,14 +838,13 @@ fn test_fused_single_token_k4() {d_model,d_ff,k,- gating_code,silu_alpha,gate_clip_min: f32::NEG_INFINITY,gate_clip_max: f32::INFINITY,up_clip_min: f32::NEG_INFINITY,up_clip_max: f32::INFINITY,- data_type: DataType::BF16,},+ &mut encoder,).expect("failed to encode MoE experts");let completed = encoder.end_encoding().submit().wait_until_completed().unwrap();diff --git a/crates/backend-uzu/tests/unit/encodable_block/moe/moe_tiles_test.rs b/crates/backend-uzu/tests/unit/encodable_block/moe/moe_tiles_test.rsindex 25af38012..dddfa407f 100644--- a/crates/backend-uzu/tests/unit/encodable_block/moe/moe_tiles_test.rs+++ b/crates/backend-uzu/tests/unit/encodable_block/moe/moe_tiles_test.rs@@ -1,8 +1,13 @@-use backend_uzu::backends::common::{Encoder, kernel::moe::MoeTileMapKernels};+use backend_uzu::backends::common::{+ Backend, Encoder, Kernels,+ kernel::{MoeTileCountsKernel, MoeTileScanKernel},+};use rand::{RngExt, SeedableRng, rngs::StdRng};use crate::encodable_block::mlp::moe::tests::{- common::helpers::{alloc_allocation_with_data, allocation_prefix_to_vec, allocation_to_vec, create_context},+ common::helpers::{+ alloc_allocation, alloc_allocation_with_data, allocation_prefix_to_vec, allocation_to_vec, create_context,+ },cpu_tile_counts, cpu_tile_scan,};@@ -31,10 +36,11 @@ fn test_tile_counts_correctness() {let offsets_buf = alloc_allocation_with_data::<B, u32>(&ctx, &offsets);// Execute kernel using kernel struct- let tile_kernel = MoeTileMapKernels::<B>::new(&ctx).expect("MoeTileMapKernel::new");+ let counts_kernel =+ <<B as Backend>::Kernels as Kernels>::MoeTileCountsKernel::new(&ctx).expect("MoeTileCountsKernel::new");let mut encoder = Encoder::new(ctx.as_ref()).expect("Failed to create encoder");- let tile_counts_buf =- tile_kernel.encode_counts(&mut encoder, &offsets_buf, e).expect("MoeTileMapKernels::encode_counts");+ let mut tile_counts_buf = alloc_allocation::<B, u32>(&ctx, e);+ counts_kernel.encode(&offsets_buf, &mut tile_counts_buf, e as u32, &mut encoder);let completed = encoder.end_encoding().submit().wait_until_completed().unwrap();let tile_counts_gpu = allocation_prefix_to_vec::<B, u32>(&tile_counts_buf, e);@@ -69,15 +75,18 @@ fn test_tile_scan_correctness() {let tile_counts_buf = alloc_allocation_with_data::<B, u32>(&ctx, &tile_counts);// Execute kernel using kernel struct- let tile_kernel = MoeTileMapKernels::<B>::new(&ctx).expect("MoeTileMapKernel::new");+ let scan_kernel =+ <<B as Backend>::Kernels as Kernels>::MoeTileScanKernel::new(&ctx).expect("MoeTileScanKernel::new");let mut encoder = Encoder::new(ctx.as_ref()).expect("Failed to create encoder");- let tile_scan =- tile_kernel.encode_scan(&mut encoder, &tile_counts_buf, e).expect("MoeTileMapKernels::encode_scan");+ let mut tile_offsets_buf = alloc_allocation::<B, u32>(&ctx, e + 1);+ let mut total_tiles_buf = alloc_allocation::<B, u32>(&ctx, 8);+ scan_kernel.encode(&tile_counts_buf, &mut tile_offsets_buf, &mut total_tiles_buf, e as u32, &mut encoder);let completed = encoder.end_encoding().submit().wait_until_completed().unwrap();- let tile_offsets_gpu = allocation_prefix_to_vec::<B, u32>(&tile_scan.tile_offsets, e + 1);- let total_tiles_gpu = allocation_to_vec::<B, u32>(&tile_scan.total_tiles)[0];- drop(tile_scan);+ let tile_offsets_gpu = allocation_prefix_to_vec::<B, u32>(&tile_offsets_buf, e + 1);+ let total_tiles_gpu = allocation_to_vec::<B, u32>(&total_tiles_buf)[0];+ drop(tile_offsets_buf);+ drop(total_tiles_buf);drop(completed);assert_eq!(tile_offsets_gpu, tile_offsets_cpu, "Tile offsets mismatch for E={}", e);@@ -102,10 +111,11 @@ fn test_tile_edge_cases() {let offsets_buf = alloc_allocation_with_data::<B, u32>(&ctx, &offsets);- let tile_kernel = MoeTileMapKernels::<B>::new(&ctx).expect("MoeTileMapKernel::new");+ let counts_kernel =+ <<B as Backend>::Kernels as Kernels>::MoeTileCountsKernel::new(&ctx).expect("MoeTileCountsKernel::new");let mut encoder = Encoder::new(ctx.as_ref()).expect("Failed to create encoder");- let tile_counts_buf =- tile_kernel.encode_counts(&mut encoder, &offsets_buf, e).expect("MoeTileMapKernels::encode_counts");+ let mut tile_counts_buf = alloc_allocation::<B, u32>(&ctx, e);+ counts_kernel.encode(&offsets_buf, &mut tile_counts_buf, e as u32, &mut encoder);let completed = encoder.end_encoding().submit().wait_until_completed().unwrap();let tile_counts_gpu = allocation_prefix_to_vec::<B, u32>(&tile_counts_buf, e);@@ -126,10 +136,11 @@ fn test_tile_edge_cases() {let offsets_buf = alloc_allocation_with_data::<B, u32>(&ctx, &offsets);- let tile_kernel = MoeTileMapKernels::<B>::new(&ctx).expect("MoeTileMapKernels::new");+ let counts_kernel =+ <<B as Backend>::Kernels as Kernels>::MoeTileCountsKernel::new(&ctx).expect("MoeTileCountsKernel::new");let mut encoder = Encoder::new(ctx.as_ref()).expect("Failed to create encoder");- let tile_counts_buf =- tile_kernel.encode_counts(&mut encoder, &offsets_buf, e).expect("MoeTileMapKernels::encode_counts");+ let mut tile_counts_buf = alloc_allocation::<B, u32>(&ctx, e);+ counts_kernel.encode(&offsets_buf, &mut tile_counts_buf, e as u32, &mut encoder);let completed = encoder.end_encoding().submit().wait_until_completed().unwrap();let tile_counts_gpu = allocation_prefix_to_vec::<B, u32>(&tile_counts_buf, e);diff --git a/crates/backend-uzu/tests/unit/kernel/moe/moe_gather_test.rs b/crates/backend-uzu/tests/unit/kernel/moe/moe_gather_test.rsindex 4d2e04c6b..f3cd8f653 100644--- a/crates/backend-uzu/tests/unit/kernel/moe/moe_gather_test.rs+++ b/crates/backend-uzu/tests/unit/kernel/moe/moe_gather_test.rs@@ -1,16 +1,16 @@-use half::bf16;-use num_traits::Float;-use rand::{RngExt, SeedableRng, rngs::StdRng};use backend_uzu::{ArrayElement,backends::{common::{Backend, Encoder,- kernel::moe::{MoeGatherArguments, MoeGatherKernels},+ kernel::moe::MoeGatherKernel,},cpu::Cpu,},};+use half::bf16;+use num_traits::Float;+use rand::{RngExt, SeedableRng, rngs::StdRng};use crate::{common::{@@ -35,20 +35,17 @@ 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 = MoeGatherKernels::<B>::new(&context).expect("MoeGatherKernel::new");+ let gather = MoeGatherKernel::<B>::new(&context, T::data_type()).expect("MoeGatherKernel::new");let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");let x_perm_allocation = gather.encode(+ &x_allocation,+ &ids_allocation,+ &sumk_allocation,+ input.t,+ input.sum_k / input.t,+ input.d_model,&mut encoder,- T::data_type(),- MoeGatherArguments {- x: &x_allocation,- bucketed_ids: &ids_allocation,- sumk: &sumk_allocation,- t: input.t,- k: input.sum_k / input.t, // Decompose sum_k into k per token- d_model: input.d_model,- },).expect("Failed to encode MoE gather");let completed = encoder.end_encoding().submit().wait_until_completed().unwrap();