Skip to content

armgit / uzu

Public Imported from GitHub
0

A high-performance inference engine for AI models

MoE (#37)

LuckyIYI85f732ed1d7c
diff --git a/Cargo.lock b/Cargo.lock
index 4cb11608b..43787a2a4 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -317,7 +317,7 @@ checksum = "b94f61472cee1439c0b966b47e3aca9ae07e45d070759512cd390ea2bebc6675"
[[package]]
name = "cli"
-version = "0.1.4"
+version = "0.1.5"
dependencies = [
"clap",
"console 0.16.0",
@@ -2640,7 +2640,7 @@ dependencies = [
[[package]]
name = "uzu"
-version = "0.1.4"
+version = "0.1.5"
dependencies = [
"bitflags 2.9.4",
"bytemuck",
diff --git a/Cargo.toml b/Cargo.toml
index c69d8505e..59248de2d 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -3,7 +3,7 @@ members = ["crates/cli", "crates/uzu"]
resolver = "3"
[workspace.package]
-version = "0.1.4"
+version = "0.1.5"
edition = "2024"
license = "MIT"
authors = ["Mirai Tech <https://trymirai.com>"]
diff --git a/crates/cli/Cargo.toml b/crates/cli/Cargo.toml
index d65e5724f..218fbe6d2 100644
--- a/crates/cli/Cargo.toml
+++ b/crates/cli/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "cli"
-version = "0.1.4"
+version = "0.1.5"
edition = "2024"
[[bin]]
diff --git a/crates/cli/src/server/chat_completions.rs b/crates/cli/src/server/chat_completions.rs
index 9e7a88d99..4aa113269 100644
--- a/crates/cli/src/server/chat_completions.rs
+++ b/crates/cli/src/server/chat_completions.rs
@@ -127,6 +127,7 @@ pub fn handle_chat_completions(
suffix_length: 0,
tokens_count: 0,
tokens_per_second: 0.0,
+ processed_tokens_per_second: 0.0,
model_run: RunStats {
count: 0,
average_duration: 0.0,
@@ -172,6 +173,7 @@ pub fn handle_chat_completions(
suffix_length: 0,
tokens_count: 0,
tokens_per_second: 0.0,
+ processed_tokens_per_second: 0.0,
model_run: RunStats {
count: 0,
average_duration: 0.0,
diff --git a/crates/uzu/Cargo.toml b/crates/uzu/Cargo.toml
index ce96d709c..6d33165ee 100644
--- a/crates/uzu/Cargo.toml
+++ b/crates/uzu/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "uzu"
-version = "0.1.4"
+version = "0.1.5"
edition = "2024"
build = "build.rs"
@@ -33,3 +33,7 @@ serde_json5 = "0.2.1"
[features]
default = ["metal-shaders"]
metal-shaders = []
+
+[[test]]
+name = "moe"
+path = "tests/moe/mod.rs"
diff --git a/crates/uzu/src/backends/metal/executable_builder/layer_executables.rs b/crates/uzu/src/backends/metal/executable_builder/layer_executables.rs
index 0d0d17180..21575ac3b 100644
--- a/crates/uzu/src/backends/metal/executable_builder/layer_executables.rs
+++ b/crates/uzu/src/backends/metal/executable_builder/layer_executables.rs
@@ -220,6 +220,7 @@ impl LayerExecutables {
kernel_data_type,
layer_index,
attention_scale,
+ layer_config.attention_config.has_sinks,
)
.expect("Failed to create AttentionWrapper with Metal kernel"),
);
diff --git a/crates/uzu/src/backends/metal/forward_pass/buffers.rs b/crates/uzu/src/backends/metal/forward_pass/buffers.rs
index 07084db99..2716e0341 100644
--- a/crates/uzu/src/backends/metal/forward_pass/buffers.rs
+++ b/crates/uzu/src/backends/metal/forward_pass/buffers.rs
@@ -2,8 +2,15 @@ use std::collections::HashMap;
use metal::Buffer as MTLBuffer;
-use super::{super::MTLContext, model_shape::ModelShape};
-use crate::{DataType, array::array_size_in_bytes};
+use super::{
+ super::MTLContext,
+ model_shape::ModelShape,
+};
+use crate::{
+ DataType,
+ array::array_size_in_bytes,
+ config::{DecoderConfig, MLPConfig},
+};
/// Holds one shared Metal buffer for every temporary tensor that can appear during a forward pass.
/// Each buffer is large enough for the worst-case shape: `max_suffix_len` / `max_prefix_len`.
@@ -34,6 +41,26 @@ pub struct ForwardPassBuffers {
pub attention_partials: MTLBuffer, // [num_heads * max_suffix_len * total_blocks_count * head_dim]
pub attention_sums: MTLBuffer, // [num_heads * max_suffix_len * total_blocks_count]
pub attention_maxs: MTLBuffer, // [num_heads * max_suffix_len * total_blocks_count]
+
+ pub moe_topk_ids: Option<MTLBuffer>,
+ pub moe_topk_probs: Option<MTLBuffer>,
+ pub moe_offsets: Option<MTLBuffer>,
+ pub moe_sumk: Option<MTLBuffer>,
+ pub moe_bucketed_token_ids: Option<MTLBuffer>,
+ pub moe_bucketed_probs: Option<MTLBuffer>,
+ pub moe_x_perm: Option<MTLBuffer>,
+ pub moe_tok2row: Option<MTLBuffer>,
+ pub moe_y_partial: Option<MTLBuffer>,
+ pub moe_hidden: Option<MTLBuffer>,
+ pub moe_two_pass_row_expert_map: Option<MTLBuffer>,
+ pub moe_tile_counts: Option<MTLBuffer>,
+ pub moe_tile_offsets: Option<MTLBuffer>,
+ pub moe_tile_map: Option<MTLBuffer>,
+ pub moe_total_tiles: Option<MTLBuffer>,
+ pub moe_dispatch_args: Option<MTLBuffer>,
+ pub moe_scatter_partials: Option<MTLBuffer>,
+ pub moe_scatter_block_bases: Option<MTLBuffer>,
+ pub moe_block_alloc: Option<MTLBuffer>,
}
impl ForwardPassBuffers {
@@ -41,6 +68,7 @@ impl ForwardPassBuffers {
/// Allocate the buffers with `StorageModeShared` so that they are CPU-accessible as well.
pub fn new(
context: &MTLContext,
+ decoder_config: &DecoderConfig,
model_shape: &ModelShape,
max_prefix_len: usize,
max_suffix_len: usize,
@@ -109,6 +137,185 @@ impl ForwardPassBuffers {
attention_partials: alloc(&partials_shape, act_ty),
attention_sums: alloc(&sums_maxs_shape, act_ty),
attention_maxs: alloc(&sums_maxs_shape, act_ty),
+
+ moe_topk_ids: match &decoder_config.layer_config.mlp_config {
+ MLPConfig::MixtureOfExperts(moe) => {
+ let shape = model_shape.moe_topk_ids_shape(
+ max_suffix_len,
+ moe.num_experts_per_token,
+ );
+ Some(alloc(&shape, DataType::U32))
+ },
+ _ => None,
+ },
+ moe_topk_probs: match &decoder_config.layer_config.mlp_config {
+ MLPConfig::MixtureOfExperts(moe) => {
+ let shape = model_shape.moe_topk_probs_shape(
+ max_suffix_len,
+ moe.num_experts_per_token,
+ );
+ Some(alloc(&shape, act_ty))
+ },
+ _ => None,
+ },
+ moe_offsets: match &decoder_config.layer_config.mlp_config {
+ MLPConfig::MixtureOfExperts(moe) => {
+ let shape = model_shape.moe_offsets_shape(moe.mixture_size);
+ Some(alloc(&shape, DataType::U32))
+ },
+ _ => None,
+ },
+ moe_sumk: match &decoder_config.layer_config.mlp_config {
+ MLPConfig::MixtureOfExperts(_) => {
+ let shape = model_shape.moe_sumk_shape();
+ Some(alloc(&shape, DataType::U32))
+ },
+ _ => None,
+ },
+ moe_bucketed_token_ids: match &decoder_config
+ .layer_config
+ .mlp_config
+ {
+ MLPConfig::MixtureOfExperts(moe) => {
+ let max_routed = max_suffix_len * moe.num_experts_per_token;
+ let shape =
+ model_shape.moe_bucketed_token_ids_shape(max_routed);
+ Some(alloc(&shape, DataType::U32))
+ },
+ _ => None,
+ },
+ moe_bucketed_probs: match &decoder_config.layer_config.mlp_config {
+ MLPConfig::MixtureOfExperts(moe) => {
+ let max_routed = max_suffix_len * moe.num_experts_per_token;
+ let shape =
+ model_shape.moe_bucketed_probs_shape(max_routed);
+ Some(alloc(&shape, act_ty))
+ },
+ _ => None,
+ },
+ moe_x_perm: match &decoder_config.layer_config.mlp_config {
+ MLPConfig::MixtureOfExperts(moe) => {
+ let max_routed = max_suffix_len * moe.num_experts_per_token;
+ let shape = model_shape.moe_x_perm_shape(max_routed);
+ Some(alloc(&shape, DataType::F16))
+ },
+ _ => None,
+ },
+ moe_tok2row: match &decoder_config.layer_config.mlp_config {
+ MLPConfig::MixtureOfExperts(moe) => {
+ let shape = model_shape.moe_tok2row_shape(
+ max_suffix_len,
+ moe.num_experts_per_token,
+ );
+ Some(alloc(&shape, DataType::I32))
+ },
+ _ => None,
+ },
+ moe_y_partial: match &decoder_config.layer_config.mlp_config {
+ MLPConfig::MixtureOfExperts(moe) => {
+ let max_routed = max_suffix_len * moe.num_experts_per_token;
+ let shape = model_shape.moe_y_partial_shape(max_routed);
+ Some(alloc(&shape, DataType::F16))
+ },
+ _ => None,
+ },
+ moe_hidden: match &decoder_config.layer_config.mlp_config {
+ MLPConfig::MixtureOfExperts(moe) => {
+ let max_routed = max_suffix_len * moe.num_experts_per_token;
+ let shape = model_shape.moe_hidden_shape(max_routed);
+ Some(alloc(&shape, DataType::F32))
+ },
+ _ => None,
+ },
+ moe_two_pass_row_expert_map: match &decoder_config
+ .layer_config
+ .mlp_config
+ {
+ MLPConfig::MixtureOfExperts(moe) => {
+ let max_routed = max_suffix_len * moe.num_experts_per_token;
+ Some(alloc(&[max_routed], DataType::U32))
+ },
+ _ => None,
+ },
+ moe_tile_counts: match &decoder_config.layer_config.mlp_config {
+ MLPConfig::MixtureOfExperts(moe) => {
+ let shape = model_shape.moe_counts_shape(moe.mixture_size);
+ Some(alloc(&shape, DataType::U32))
+ },
+ _ => None,
+ },
+ moe_tile_offsets: match &decoder_config.layer_config.mlp_config {
+ MLPConfig::MixtureOfExperts(moe) => {
+ let shape = model_shape.moe_offsets_shape(moe.mixture_size);
+ Some(alloc(&shape, DataType::U32))
+ },
+ _ => None,
+ },
+ moe_tile_map: match &decoder_config.layer_config.mlp_config {
+ MLPConfig::MixtureOfExperts(moe) => {
+ let max_routed = max_suffix_len * moe.num_experts_per_token;
+ let shape = model_shape.moe_tile_map_shape(max_routed);
+ Some(alloc(&shape, DataType::U32))
+ },
+ _ => None,
+ },
+ moe_total_tiles: match &decoder_config.layer_config.mlp_config {
+ MLPConfig::MixtureOfExperts(_) => {
+ let shape = model_shape.moe_total_tiles_shape();
+ Some(alloc(&shape, DataType::U32))
+ },
+ _ => None,
+ },
+ moe_dispatch_args: match &decoder_config.layer_config.mlp_config {
+ MLPConfig::MixtureOfExperts(_) => {
+ let shape = model_shape.moe_dispatch_args_shape();
+ Some(alloc(&shape, DataType::U32))
+ },
+ _ => None,
+ },
+ moe_scatter_partials: match &decoder_config.layer_config.mlp_config
+ {
+ MLPConfig::MixtureOfExperts(moe) => {
+ let num_blocks = ((max_suffix_len + 255) / 256).max(1);
+ let num_tiles = ((moe.mixture_size + 512 - 1) / 512).max(1);
+ let entries = num_blocks * num_tiles * 512;
+ let bytes = (entries * std::mem::size_of::<u32>()) as u64;
+ Some(context.device.new_buffer(
+ bytes,
+ metal::MTLResourceOptions::StorageModeShared,
+ ))
+ },
+ _ => None,
+ },
+ moe_scatter_block_bases: match &decoder_config
+ .layer_config
+ .mlp_config
+ {
+ MLPConfig::MixtureOfExperts(moe) => {
+ let num_blocks = ((max_suffix_len + 255) / 256).max(1);
+ let num_tiles = ((moe.mixture_size + 512 - 1) / 512).max(1);
+ let entries = num_blocks * num_tiles * 512;
+ let bytes = (entries * std::mem::size_of::<u32>()) as u64;
+ Some(context.device.new_buffer(
+ bytes,
+ metal::MTLResourceOptions::StorageModeShared,
+ ))
+ },
+ _ => None,
+ },
+ moe_block_alloc: match &decoder_config.layer_config.mlp_config {
+ MLPConfig::MixtureOfExperts(moe) => {
+ let num_blocks = ((max_suffix_len + 255) / 256).max(1);
+ let num_tiles = ((moe.mixture_size + 512 - 1) / 512).max(1);
+ let entries = num_blocks * num_tiles * 512;
+ let bytes = (entries * std::mem::size_of::<u32>()) as u64;
+ Some(context.device.new_buffer(
+ bytes,
+ metal::MTLResourceOptions::StorageModeShared,
+ ))
+ },
+ _ => None,
+ },
}
}
}
diff --git a/crates/uzu/src/backends/metal/forward_pass/model_shape.rs b/crates/uzu/src/backends/metal/forward_pass/model_shape.rs
index e0469041c..60b26d349 100644
--- a/crates/uzu/src/backends/metal/forward_pass/model_shape.rs
+++ b/crates/uzu/src/backends/metal/forward_pass/model_shape.rs
@@ -19,12 +19,15 @@ pub struct ModelShape {
impl ModelShape {
pub fn from_decoder_config(decoder_config: &DecoderConfig) -> Self {
- let activation_type: DataType = decoder_config
- .layer_config
- .mlp_config
- .linear_config
- .activation_precision()
- .into();
+ let activation_type: DataType =
+ match &decoder_config.layer_config.mlp_config {
+ crate::config::MLPConfig::Dense(d) => {
+ d.linear_config.activation_precision().into()
+ },
+ crate::config::MLPConfig::MixtureOfExperts(m) => {
+ m.expert_config.linear_config.activation_precision().into()
+ },
+ };
let num_layers = decoder_config.num_layers;
Self {
activation_type,
@@ -100,7 +103,7 @@ impl ModelShape {
}
pub fn embeddings_output_shape(&self) -> [usize; 2] {
- [self.model_dim, self.vocabulary_size]
+ [self.vocabulary_size, self.model_dim]
}
pub fn quantized_embeddings_weights_shape(&self) -> [usize; 2] {
@@ -170,4 +173,118 @@ impl ModelShape {
const TOTAL_BLOCKS_COUNT: usize = 32;
[self.num_heads * suffix_length * TOTAL_BLOCKS_COUNT]
}
+
+ pub fn moe_router_logits_shape(
+ &self,
+ suffix_length: usize,
+ num_experts: usize,
+ ) -> [usize; 2] {
+ [suffix_length, num_experts]
+ }
+
+ pub fn moe_topk_ids_shape(
+ &self,
+ suffix_length: usize,
+ k: usize,
+ ) -> [usize; 2] {
+ [suffix_length, k]
+ }
+
+ pub fn moe_topk_probs_shape(
+ &self,
+ suffix_length: usize,
+ k: usize,
+ ) -> [usize; 2] {
+ [suffix_length, k]
+ }
+
+ pub fn moe_counts_shape(
+ &self,
+ num_experts: usize,
+ ) -> [usize; 1] {
+ [num_experts]
+ }
+
+ pub fn moe_offsets_shape(
+ &self,
+ num_experts: usize,
+ ) -> [usize; 1] {
+ [num_experts + 1]
+ }
+
+ pub fn moe_sumk_shape(&self) -> [usize; 1] {
+ [1]
+ }
+
+ pub fn moe_bucketed_token_ids_shape(
+ &self,
+ max_routed_tokens: usize,
+ ) -> [usize; 1] {
+ [max_routed_tokens]
+ }
+
+ pub fn moe_bucketed_probs_shape(
+ &self,
+ max_routed_tokens: usize,
+ ) -> [usize; 1] {
+ [max_routed_tokens]
+ }
+
+ pub fn moe_tok2row_shape(
+ &self,
+ suffix_length: usize,
+ k: usize,
+ ) -> [usize; 1] {
+ [suffix_length * k]
+ }
+
+ pub fn moe_y_partial_shape(
+ &self,
+ max_routed_tokens: usize,
+ ) -> [usize; 2] {
+ [max_routed_tokens, self.model_dim]
+ }
+
+ pub fn moe_hidden_shape(
+ &self,
+ max_routed_tokens: usize,
+ ) -> [usize; 2] {
+ [max_routed_tokens, self.hidden_dim]
+ }
+
+ pub fn moe_x_perm_shape(
+ &self,
+ max_routed_tokens: usize,
+ ) -> [usize; 2] {
+ [max_routed_tokens, self.model_dim]
+ }
+
+ pub fn moe_tile_map_shape(
+ &self,
+ max_routed_tokens: usize,
+ ) -> [usize; 1] {
+ // For tiled GEMM: max_routed_tokens * 3
+ // For two-pass decode indirect dispatch: max_routed_tokens * h_blocks * 3
+ // where h_blocks = (d_ff + 3) / 4
+ // We size for the larger (two-pass decode)
+ let d_ff = self.hidden_dim;
+ if d_ff > 0 {
+ let h_blocks = (d_ff + 3) / 4;
+ [max_routed_tokens * h_blocks * 3]
+ } else {
+ [max_routed_tokens * 3]
+ }
+ }
+
+ pub fn moe_dispatch_args_shape(&self) -> [usize; 1] {
+ [3]
+ }
+
+ pub fn moe_total_tiles_shape(&self) -> [usize; 1] {
+ // layout: [total_tiles, total_jobs,
+ // nan_fc1_count, nan_fc2_count,
+ // nan_fc1_bits, nan_fc2_bits,
+ // nan_gate_bits, nan_up_bits]
+ [8]
+ }
}
diff --git a/crates/uzu/src/backends/metal/forward_pass/state.rs b/crates/uzu/src/backends/metal/forward_pass/state.rs
index 7997291da..a01b0f608 100644
--- a/crates/uzu/src/backends/metal/forward_pass/state.rs
+++ b/crates/uzu/src/backends/metal/forward_pass/state.rs
@@ -1,6 +1,7 @@
#![allow(dead_code)]
use std::{cell::RefCell, collections::HashMap, rc::Rc};
+use half::{bf16, f16};
use serde::{Deserialize, Serialize};
use super::{
@@ -12,7 +13,8 @@ use super::{
use crate::{
DataType, DeviceContext,
backends::metal::forward_pass::traces::DecoderActivationTrace,
- config::{DecoderConfig, EmbeddingConfig},
+ config::{DecoderConfig, EmbeddingConfig, MLPConfig},
+ device::array::Array,
parameters::ParameterTree,
session::parameter::SamplingMethod,
};
@@ -173,6 +175,14 @@ pub struct SharedBuffers {
pub embeddings: EmbeddingsBuffers,
pub global_rope: RopeBuffers,
pub local_rope: Option<RopeBuffers>,
+ pub moe_expert_weights: Option<Vec<MoeExpertWeights>>,
+ pub attention_sinks: Option<Vec<ArrayCell>>,
+}
+
+pub struct MoeExpertWeights {
+ pub w1: ArrayCell,
+ pub w2: ArrayCell,
+ pub w3: ArrayCell,
}
impl SharedBuffers {
@@ -195,10 +205,38 @@ impl SharedBuffers {
None
};
+ let moe_expert_weights = if matches!(
+ decoder_config.layer_config.mlp_config,
+ crate::config::MLPConfig::MixtureOfExperts(_)
+ ) {
+ Some(Vec::new())
+ } else {
+ None
+ };
+
+ let attention_sinks =
+ if decoder_config.layer_config.attention_config.has_sinks {
+ let num_heads = decoder_config.num_heads;
+ Some(
+ (0..decoder_config.num_layers)
+ .map(|_| unsafe {
+ RefCell::new(context.array_uninitialized(
+ &[num_heads],
+ DataType::F32,
+ ))
+ })
+ .collect(),
+ )
+ } else {
+ None
+ };
+
Self {
embeddings,
global_rope,
local_rope,
+ moe_expert_weights,
+ attention_sinks,
}
}
@@ -212,6 +250,47 @@ impl SharedBuffers {
if let Some(local_rope) = &mut self.local_rope {
local_rope.update_data(parameter_tree, String::from("local_rope"));
}
+
+ if let Some(sinks_vec) = &mut self.attention_sinks {
+ for (layer_idx, sink_cell) in sinks_vec.iter_mut().enumerate() {
+ let layer_tree = parameter_tree
+ .subtree(&format!("layers.{}", layer_idx))
+ .unwrap();
+ let attn_tree = layer_tree.subtree("attention").unwrap();
+ let sinks_arr = attn_tree.leaf("sinks").unwrap();
+ let mut dst = sink_cell.borrow_mut();
+ let dst_slice = dst.as_slice_mut::<f32>().unwrap();
+
+ match sinks_arr.data_type() {
+ DataType::F32 => {
+ let src = sinks_arr.as_slice::<f32>().unwrap();
+ dst_slice.copy_from_slice(src);
+ },
+ DataType::BF16 => {
+ let src = sinks_arr.as_slice::<bf16>().unwrap();
+ for (dst_val, src_val) in
+ dst_slice.iter_mut().zip(src.iter())
+ {
+ *dst_val = f32::from(*src_val);
+ }
+ },
+ DataType::F16 => {
+ let src = sinks_arr.as_slice::<f16>().unwrap();
+ for (dst_val, src_val) in
+ dst_slice.iter_mut().zip(src.iter())
+ {
+ *dst_val = f32::from(*src_val);
+ }
+ },
+ other => {
+ panic!(
+ "Unsupported attention sink data type: {:?}",
+ other
+ );
+ },
+ }
+ }
+ }
}
}
@@ -239,11 +318,32 @@ struct AuxBuffers {
attention_sums: ArrayCell,
/// [num_heads * suffix_length * total_blocks_count]
attention_maxs: ArrayCell,
+
+ moe_topk_ids: Option<ArrayCell>,
+ moe_topk_probs: Option<ArrayCell>,
+ moe_offsets: Option<ArrayCell>,
+ moe_sumk: Option<ArrayCell>,
+ moe_bucketed_token_ids: Option<ArrayCell>,
+ moe_bucketed_probs: Option<ArrayCell>,
+ moe_x_perm: Option<ArrayCell>,
+ moe_tok2row: Option<ArrayCell>,
+ moe_y_partial: Option<ArrayCell>,
+ moe_hidden: Option<ArrayCell>,
+ moe_two_pass_row_expert_map: Option<ArrayCell>,
+ moe_tile_counts: Option<ArrayCell>,
+ moe_tile_offsets: Option<ArrayCell>,
+ moe_tile_map: Option<ArrayCell>,
+ moe_total_tiles: Option<ArrayCell>,
+ moe_dispatch_args: Option<ArrayCell>,
+ moe_scatter_partials: Option<ArrayCell>,
+ moe_scatter_block_bases: Option<ArrayCell>,
+ moe_block_alloc: Option<ArrayCell>,
}
impl AuxBuffers {
fn new(
scratch: &ForwardPassBuffers,
+ decoder_config: &DecoderConfig,
model_shape: &ModelShape,
suffix_length: usize,
) -> Self {
@@ -306,6 +406,293 @@ impl AuxBuffers {
&model_shape.attention_maxs_shape(suffix_length),
act_dtype,
)),
+
+ moe_topk_ids: match &decoder_config.layer_config.mlp_config {
+ MLPConfig::MixtureOfExperts(moe) => {
+ scratch.moe_topk_ids.as_ref().map(|buf| {
+ RefCell::new(MetalArray::new(
+ buf.clone(),
+ &model_shape.moe_topk_ids_shape(
+ suffix_length,
+ moe.num_experts_per_token,
+ ),
+ DataType::U32,
+ ))
+ })
+ },
+ _ => None,
+ },
+ moe_topk_probs: match &decoder_config.layer_config.mlp_config {
+ MLPConfig::MixtureOfExperts(moe) => {
+ scratch.moe_topk_probs.as_ref().map(|buf| {
+ RefCell::new(MetalArray::new(
+ buf.clone(),
+ &model_shape.moe_topk_probs_shape(
+ suffix_length,
+ moe.num_experts_per_token,
+ ),
+ act_dtype,
+ ))
+ })
+ },
+ _ => None,
+ },
+ moe_offsets: match &decoder_config.layer_config.mlp_config {
+ MLPConfig::MixtureOfExperts(moe) => {
+ scratch.moe_offsets.as_ref().map(|buf| {
+ RefCell::new(MetalArray::new(
+ buf.clone(),
+ &model_shape
+ .moe_offsets_shape(moe.mixture_size),
+ DataType::U32,
+ ))
+ })
+ },
+ _ => None,
+ },
+ moe_sumk: match &decoder_config.layer_config.mlp_config {
+ MLPConfig::MixtureOfExperts(_) => {
+ scratch.moe_sumk.as_ref().map(|buf| {
+ RefCell::new(MetalArray::new(
+ buf.clone(),
+ &model_shape.moe_sumk_shape(),
+ DataType::U32,
+ ))
+ })
+ },
+ _ => None,
+ },
+ moe_bucketed_token_ids: match &decoder_config
+ .layer_config
+ .mlp_config
+ {
+ MLPConfig::MixtureOfExperts(moe) => {
+ let max_routed =
+ suffix_length * moe.num_experts_per_token;
+ scratch.moe_bucketed_token_ids.as_ref().map(|buf| {
+ RefCell::new(MetalArray::new(
+ buf.clone(),
+ &model_shape
+ .moe_bucketed_token_ids_shape(max_routed),
+ DataType::U32,
+ ))
+ })
+ },
+ _ => None,
+ },
+ moe_bucketed_probs: match &decoder_config
+ .layer_config
+ .mlp_config
+ {
+ MLPConfig::MixtureOfExperts(moe) => {
+ let max_routed =
+ suffix_length * moe.num_experts_per_token;
+ scratch.moe_bucketed_probs.as_ref().map(|buf| {
+ RefCell::new(MetalArray::new(
+ buf.clone(),
+ &model_shape
+ .moe_bucketed_probs_shape(max_routed),
+ act_dtype,
+ ))
+ })
+ },
+ _ => None,
+ },
+ moe_x_perm: match &decoder_config.layer_config.mlp_config {
+ MLPConfig::MixtureOfExperts(moe) => {
+ let max_routed =
+ suffix_length * moe.num_experts_per_token;
+ scratch.moe_x_perm.as_ref().map(|buf| {
+ RefCell::new(MetalArray::new(
+ buf.clone(),
+ &model_shape.moe_x_perm_shape(max_routed),
+ DataType::F16,
+ ))
+ })
+ },
+ _ => None,
+ },
+ moe_tok2row: match &decoder_config.layer_config.mlp_config {
+ MLPConfig::MixtureOfExperts(moe) => {
+ scratch.moe_tok2row.as_ref().map(|buf| {
+ RefCell::new(MetalArray::new(
+ buf.clone(),
+ &model_shape.moe_tok2row_shape(
+ suffix_length,
+ moe.num_experts_per_token,
+ ),
+ DataType::I32,
+ ))
+ })
+ },
+ _ => None,
+ },
+ moe_y_partial: match &decoder_config.layer_config.mlp_config {
+ MLPConfig::MixtureOfExperts(moe) => {
+ let max_routed =
+ suffix_length * moe.num_experts_per_token;
+ scratch.moe_y_partial.as_ref().map(|buf| {
+ RefCell::new(MetalArray::new(
+ buf.clone(),
+ &model_shape.moe_y_partial_shape(max_routed),
+ DataType::F16,
+ ))
+ })
+ },
+ _ => None,
+ },
+ moe_hidden: match &decoder_config.layer_config.mlp_config {
+ MLPConfig::MixtureOfExperts(moe) => {
+ let max_routed =
+ suffix_length * moe.num_experts_per_token;
+ scratch.moe_hidden.as_ref().map(|buf| {
+ RefCell::new(MetalArray::new(
+ buf.clone(),
+ &model_shape.moe_hidden_shape(max_routed),
+ act_dtype,
+ ))
+ })
+ },
+ _ => None,
+ },
+ moe_two_pass_row_expert_map: match &decoder_config
+ .layer_config
+ .mlp_config
+ {
+ MLPConfig::MixtureOfExperts(moe) => {
+ let max_routed =
+ suffix_length * moe.num_experts_per_token;
+ scratch.moe_two_pass_row_expert_map.as_ref().map(
+ |buf| {
+ RefCell::new(MetalArray::new(
+ buf.clone(),
+ &[max_routed],
+ DataType::U32,
+ ))
+ },
+ )
+ },
+ _ => None,
+ },
+ moe_tile_counts: match &decoder_config.layer_config.mlp_config {
+ MLPConfig::MixtureOfExperts(moe) => {
+ scratch.moe_tile_counts.as_ref().map(|buf| {
+ RefCell::new(MetalArray::new(
+ buf.clone(),
+ &model_shape.moe_counts_shape(moe.mixture_size),
+ DataType::U32,
+ ))
+ })
+ },
+ _ => None,
+ },
+ moe_tile_offsets: match &decoder_config.layer_config.mlp_config
+ {
+ MLPConfig::MixtureOfExperts(moe) => {
+ scratch.moe_tile_offsets.as_ref().map(|buf| {
+ RefCell::new(MetalArray::new(
+ buf.clone(),
+ &model_shape
+ .moe_offsets_shape(moe.mixture_size),
+ DataType::U32,
+ ))
+ })
+ },
+ _ => None,
+ },
+ moe_tile_map: match &decoder_config.layer_config.mlp_config {
+ MLPConfig::MixtureOfExperts(moe) => {
+ let max_routed =
+ suffix_length * moe.num_experts_per_token;
+ scratch.moe_tile_map.as_ref().map(|buf| {
+ RefCell::new(MetalArray::new(
+ buf.clone(),
+ &model_shape.moe_tile_map_shape(max_routed),
+ DataType::U32,
+ ))
+ })
+ },
+ _ => None,
+ },
+ moe_total_tiles: match &decoder_config.layer_config.mlp_config {
+ MLPConfig::MixtureOfExperts(_) => {
+ scratch.moe_total_tiles.as_ref().map(|buf| {
+ RefCell::new(MetalArray::new(
+ buf.clone(),
+ &model_shape.moe_total_tiles_shape(),
+ DataType::U32,
+ ))
+ })
+ },
+ _ => None,
+ },
+ moe_dispatch_args: match &decoder_config.layer_config.mlp_config
+ {
+ MLPConfig::MixtureOfExperts(_) => {
+ scratch.moe_dispatch_args.as_ref().map(|buf| {
+ RefCell::new(MetalArray::new(
+ buf.clone(),
+ &model_shape.moe_dispatch_args_shape(),
+ DataType::U32,
+ ))
+ })
+ },
+ _ => None,
+ },
+ moe_scatter_partials: scratch
+ .moe_scatter_partials
+ .as_ref()
+ .map(|buf| {
+ let num_blocks = ((suffix_length + 255) / 256).max(1);
+ match &decoder_config.layer_config.mlp_config {
+ MLPConfig::MixtureOfExperts(moe) => {
+ let num_tiles =
+ ((moe.mixture_size + 512 - 1) / 512).max(1);
+ let entries = num_blocks * num_tiles * 512;
+ RefCell::new(MetalArray::new(
+ buf.clone(),
+ &[entries],
+ DataType::U32,
+ ))
+ },
+ _ => unreachable!(),
+ }
+ }),
+ moe_scatter_block_bases: scratch
+ .moe_scatter_block_bases
+ .as_ref()
+ .map(|buf| {
+ let num_blocks = ((suffix_length + 255) / 256).max(1);
+ match &decoder_config.layer_config.mlp_config {
+ MLPConfig::MixtureOfExperts(moe) => {
+ let num_tiles =
+ ((moe.mixture_size + 512 - 1) / 512).max(1);
+ let entries = num_blocks * num_tiles * 512;
+ RefCell::new(MetalArray::new(
+ buf.clone(),
+ &[entries],
+ DataType::U32,
+ ))
+ },
+ _ => unreachable!(),
+ }
+ }),
+ moe_block_alloc: scratch.moe_block_alloc.as_ref().map(|buf| {
+ let num_blocks = ((suffix_length + 255) / 256).max(1);
+ match &decoder_config.layer_config.mlp_config {
+ MLPConfig::MixtureOfExperts(moe) => {
+ let num_tiles =
+ ((moe.mixture_size + 512 - 1) / 512).max(1);
+ let entries = num_blocks * num_tiles * 512;
+ RefCell::new(MetalArray::new(
+ buf.clone(),
+ &[entries],
+ DataType::U32,
+ ))
+ },
+ _ => unreachable!(),
+ }
+ }),
}
}
}
@@ -338,6 +725,7 @@ pub struct ForwardPassState {
impl ForwardPassState {
pub fn new(
context: Rc<MTLContext>,
+ decoder_config: &DecoderConfig,
model_shape: &ModelShape,
scratch: &ForwardPassBuffers,
kv_cache: Rc<RefCell<KVCache>>,
@@ -361,7 +749,12 @@ impl ForwardPassState {
kv_cache.borrow().max_suffix_length(),
suffix_length
);
- let aux_buffers = AuxBuffers::new(scratch, model_shape, suffix_length);
+ let aux_buffers = AuxBuffers::new(
+ scratch,
+ decoder_config,
+ model_shape,
+ suffix_length,
+ );
// --------------------
// Token IDs
@@ -571,6 +964,31 @@ impl ForwardPassState {
.sines
.clone(),
},
+
+ ArrayId::MoeTopkIds => self.aux_buffers.moe_topk_ids.as_ref().expect("MoE topk ids buffer not initialized").clone(),
+ ArrayId::MoeTopkProbs => self.aux_buffers.moe_topk_probs.as_ref().expect("MoE topk probs buffer not initialized").clone(),
+ ArrayId::MoeOffsets => self.aux_buffers.moe_offsets.as_ref().expect("MoE offsets buffer not initialized").clone(),
+ ArrayId::MoeSumK => self.aux_buffers.moe_sumk.as_ref().expect("MoE sumk buffer not initialized").clone(),
+ ArrayId::MoeBucketedTokenIds => self.aux_buffers.moe_bucketed_token_ids.as_ref().expect("MoE bucketed token ids buffer not initialized").clone(),
+ ArrayId::MoeBucketedProbs => self.aux_buffers.moe_bucketed_probs.as_ref().expect("MoE bucketed probs buffer not initialized").clone(),
+ ArrayId::MoeXPerm => self.aux_buffers.moe_x_perm.as_ref().expect("MoE x_perm buffer not initialized").clone(),
+ ArrayId::MoeTok2Row => self.aux_buffers.moe_tok2row.as_ref().expect("MoE tok2row buffer not initialized").clone(),
+ ArrayId::MoeYPartial => self.aux_buffers.moe_y_partial.as_ref().expect("MoE y_partial buffer not initialized").clone(),
+ ArrayId::MoeHidden => self.aux_buffers.moe_hidden.as_ref().expect("MoE hidden buffer not initialized").clone(),
+ ArrayId::MoeTwoPassRowExpertMap => self.aux_buffers.moe_two_pass_row_expert_map.as_ref().expect("MoE two-pass row expert map buffer not initialized").clone(),
+ ArrayId::MoeTileCounts => self.aux_buffers.moe_tile_counts.as_ref().expect("MoE tile counts buffer not initialized").clone(),
+ ArrayId::MoeTileOffsets => self.aux_buffers.moe_tile_offsets.as_ref().expect("MoE tile offsets buffer not initialized").clone(),
+ ArrayId::MoeTileMap => self.aux_buffers.moe_tile_map.as_ref().expect("MoE tile map buffer not initialized").clone(),
+ ArrayId::MoeTotalTiles => self.aux_buffers.moe_total_tiles.as_ref().expect("MoE total tiles buffer not initialized").clone(),
+ ArrayId::MoeDispatchArgs => self.aux_buffers.moe_dispatch_args.as_ref().expect("MoE dispatch args buffer not initialized").clone(),
+ ArrayId::MoeScatterPartials => self.aux_buffers.moe_scatter_partials.as_ref().expect("MoE scatter partials buffer not initialized").clone(),
+ ArrayId::MoeScatterBlockBases => self.aux_buffers.moe_scatter_block_bases.as_ref().expect("MoE scatter block bases buffer not initialized").clone(),
+ ArrayId::MoeBlockAlloc => self.aux_buffers.moe_block_alloc.as_ref().expect("MoE block alloc buffer not initialized").clone(),
+
+ ArrayId::AttentionSinks(layer_index) => {
+ self.shared_buffers.borrow().attention_sinks.as_ref()
+ .expect("Attention sinks not initialized")[layer_index].clone()
+ },
}
}
@@ -608,6 +1026,14 @@ impl ForwardPassState {
.borrow_mut()
.copy_from_array(&self.arrays(&[source_array_id])[0].borrow());
}
+
+ pub fn aux_buffers_suffix_length(&self) -> usize {
+ self.aux_buffers.suffix_length()
+ }
+
+ pub fn mtl_context(&self) -> &Rc<MTLContext> {
+ &self.context
+ }
}
impl Drop for ForwardPassState {
@@ -672,6 +1098,28 @@ pub enum ArrayId {
EmbeddingsScales,
RopeCosines(RopeType),
RopeSines(RopeType),
+
+ AttentionSinks(usize),
+
+ MoeTopkIds,
+ MoeTopkProbs,
+ MoeOffsets,
+ MoeSumK,
+ MoeBucketedTokenIds,
+ MoeBucketedProbs,
+ MoeXPerm,
+ MoeTok2Row,
+ MoeYPartial,
+ MoeHidden,
+ MoeTwoPassRowExpertMap,
+ MoeTileCounts,
+ MoeTileOffsets,
+ MoeTileMap,
+ MoeTotalTiles,
+ MoeDispatchArgs,
+ MoeScatterPartials,
+ MoeScatterBlockBases,
+ MoeBlockAlloc,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
diff --git a/crates/uzu/src/backends/metal/forward_pass/transformer_layer.rs b/crates/uzu/src/backends/metal/forward_pass/transformer_layer.rs
index 68c850c97..fd4f3f22a 100644
--- a/crates/uzu/src/backends/metal/forward_pass/transformer_layer.rs
+++ b/crates/uzu/src/backends/metal/forward_pass/transformer_layer.rs
@@ -22,7 +22,10 @@ use crate::{
embeddings_dequantize_weights_subgraph, embeddings_embed_subgraph,
embeddings_readout_subgraph,
},
- kernel::{QuantizedLinearKernelBlock, mlp::MlpGateActMulEncodable},
+ kernel::{
+ MoeBlockEncodable, QuantizedLinearKernelBlock,
+ mlp::MlpGateActMulEncodable,
+ },
},
config::{
DecoderConfig, EmbeddingConfig, LinearConfig, MLPConfig,
@@ -138,69 +141,98 @@ pub fn mlp_block(
parameter_tree: &ParameterTree<Rc<MTLContext>>,
compilation_descriptor: &CompilationDescriptor,
) -> Box<dyn super::encodable_with_state::EncodableWithState> {
- if let crate::config::LinearConfig::Quantized(ref quant_config) =
- config.linear_config
- {
- // Quantized MLP path: up (2H) -> act+mul -> down
- let dtype: DataType =
- config.linear_config.activation_precision().into();
-
- // Up fused: Main -> MlpFusedUp
- let up = QuantizedLinearKernelBlock::new(
- context,
- quant_config,
- model_dim,
- 2 * hidden_dim,
- &parameter_tree.subtree("up_projection").unwrap(),
- ArrayId::Main,
- ArrayId::MlpFusedUp,
- )
- .expect("Failed to build MLP up quantized block");
-
- // Activation+mul: MlpFusedUp -> MlpHidden
- let gate_op = MlpGateActMulEncodable::new(
- context,
- dtype,
- config.activation.clone(),
- hidden_dim,
- )
- .expect("Failed to build MLP gate activation kernel");
+ if let crate::config::MLPConfig::Dense(dense) = config {
+ if let crate::config::LinearConfig::Quantized(ref quant_config) =
+ dense.linear_config
+ {
+ // Quantized MLP path: up (2H) -> act+mul -> down
+ let dtype: DataType =
+ dense.linear_config.activation_precision().into();
+
+ // Up fused: Main -> MlpFusedUp
+ let up = QuantizedLinearKernelBlock::new(
+ context,
+ quant_config,
+ model_dim,
+ 2 * hidden_dim,
+ &parameter_tree.subtree("up_projection").unwrap(),
+ ArrayId::Main,
+ ArrayId::MlpFusedUp,
+ )
+ .expect("Failed to build MLP up quantized block");
+
+ // Activation+mul: MlpFusedUp -> MlpHidden
+ let gate_op = MlpGateActMulEncodable::new(
+ context,
+ dtype,
+ dense.activation,
+ hidden_dim,
+ )
+ .expect("Failed to build MLP gate activation kernel");
+
+ // Down: MlpHidden -> Main
+ let down = QuantizedLinearKernelBlock::new(
+ context,
+ quant_config,
+ hidden_dim,
+ model_dim,
+ &parameter_tree.subtree("down_projection").unwrap(),
+ ArrayId::MlpHidden,
+ ArrayId::Main,
+ )
+ .expect("Failed to build MLP down quantized block");
+
+ let enc =
+ crate::backends::metal::kernel::mlp::MlpBlockEncodable::new(
+ up, gate_op, down,
+ );
+ return Box::new(enc);
+ }
+ }
- // Down: MlpHidden -> Main
- let down = QuantizedLinearKernelBlock::new(
+ // STEP 2: Enable MOE block creation (encode will be minimal)
+ if let crate::config::MLPConfig::MixtureOfExperts(moe) = config {
+ let moe_block = MoeBlockEncodable::new(
context,
- quant_config,
- hidden_dim,
+ moe,
model_dim,
- &parameter_tree.subtree("down_projection").unwrap(),
- ArrayId::MlpHidden,
- ArrayId::Main,
+ hidden_dim,
+ parameter_tree,
)
- .expect("Failed to build MLP down quantized block");
-
- let enc = crate::backends::metal::kernel::mlp::MlpBlockEncodable::new(
- up, gate_op, down,
- );
- return Box::new(enc);
+ .expect("Failed to build MoE block");
+ return Box::new(moe_block);
}
+
+ // Non-quantized Dense path is handled via MPSGraph below
autoreleasepool(|_| {
let graph = Graph::new();
let input_shape = [-1, model_dim as isize];
- let input_data_type: DataType =
- config.linear_config.activation_precision().into();
+ let input_data_type: DataType = match config {
+ crate::config::MLPConfig::Dense(dense) => {
+ dense.linear_config.activation_precision().into()
+ },
+ crate::config::MLPConfig::MixtureOfExperts(moe) => {
+ moe.expert_config.linear_config.activation_precision().into()
+ },
+ };
let input_placeholder =
placeholder(&graph, &input_shape, input_data_type);
- let output = mlp_subgraph(
- &graph,
- config,
- model_dim,
- hidden_dim,
- &input_placeholder,
- parameter_tree,
- )
- .unwrap();
+ let output = match config {
+ crate::config::MLPConfig::Dense(dense) => mlp_subgraph(
+ &graph,
+ &MLPConfig::Dense(dense.clone()),
+ model_dim,
+ hidden_dim,
+ &input_placeholder,
+ parameter_tree,
+ )
+ .unwrap(),
+ crate::config::MLPConfig::MixtureOfExperts(_moe) => {
+ unreachable!("MoE uses MoeBlockEncodable, not MPSGraph")
+ },
+ };
let retained_shaped_type = shaped_type(&input_shape, input_data_type);
let feeds =
@@ -464,17 +496,19 @@ pub fn readout_block(
..
} => {
let weights_shape =
- [config.model_dim as isize, config.vocab_size as isize];
+ [config.vocab_size as isize, config.model_dim as isize];
let weights_data_type: DataType = precision.into();
let weights_shaped_type =
shaped_type(&weights_shape, weights_data_type);
let weights_placeholder =
placeholder(&graph, &weights_shape, weights_data_type);
+ let weights_transposed =
+ graph.transpose(&weights_placeholder, &[1, 0], None);
let output = embeddings_readout_subgraph(
&graph,
&input_placeholder,
- &weights_placeholder,
+ &weights_transposed,
)
.unwrap();
diff --git a/crates/uzu/src/backends/metal/graph/common.rs b/crates/uzu/src/backends/metal/graph/common.rs
index f2903b291..a7b2978d3 100644
--- a/crates/uzu/src/backends/metal/graph/common.rs
+++ b/crates/uzu/src/backends/metal/graph/common.rs
@@ -50,7 +50,9 @@ pub fn activation(
data_type: DataType,
) -> Retained<Tensor> {
match config {
- Activation::SILU => {
+ Activation::SILU {
+ ..
+ } => {
let sigmoid_result = graph.sigmoid(input, Some("sigmoid"));
graph.multiplication(input, &sigmoid_result, Some("silu_output"))
},
diff --git a/crates/uzu/src/backends/metal/graph/linear.rs b/crates/uzu/src/backends/metal/graph/linear.rs
index f2259cba2..e12dff387 100644
--- a/crates/uzu/src/backends/metal/graph/linear.rs
+++ b/crates/uzu/src/backends/metal/graph/linear.rs
@@ -24,7 +24,7 @@ fn full_precision_weights_subgraph<const N: usize>(
graph,
parameter_tree,
"weights",
- &[input_dim, output_dim_sum],
+ &[output_dim_sum, input_dim],
precision,
)
}
@@ -148,7 +148,7 @@ fn full_precision_matmul_subgraph<const N: usize>(
)?;
Ok(graph.transpose(
&graph.matrix_multiplication(
- &graph.transpose(&weights, &[1, 0], None),
+ &weights,
&graph.transpose(input, &[1, 0], None),
None,
),
diff --git a/crates/uzu/src/backends/metal/graph/mlp.rs b/crates/uzu/src/backends/metal/graph/mlp.rs
index d9b4884c3..509e30dc3 100644
--- a/crates/uzu/src/backends/metal/graph/mlp.rs
+++ b/crates/uzu/src/backends/metal/graph/mlp.rs
@@ -17,40 +17,48 @@ pub fn mlp_subgraph(
input: &Tensor,
parameter_tree: &ParameterTree<Rc<MTLContext>>,
) -> Result<Retained<Tensor>, GraphConstructionError> {
- let up_tree = parameter_tree.subtree("up_projection")?;
- let down_tree = parameter_tree.subtree("down_projection")?;
-
- let fused_hidden_gate = linear_subgraph(
- graph,
- &config.linear_config,
- model_dim,
- [hidden_dim, hidden_dim],
- false,
- input,
- &up_tree,
- )?;
-
- let split_results = graph.split_num_splits(&fused_hidden_gate, 2, 1, None);
- let up_proj = &split_results[0];
- let gate = &split_results[1];
-
- let activated_gate = activation(
- graph,
- &config.activation,
- &*gate,
- config.linear_config.activation_precision().into(),
- );
- let hidden = graph.multiplication(&activated_gate, up_proj, None);
-
- let result = linear_subgraph(
- graph,
- &config.linear_config,
- hidden_dim,
- [model_dim],
- false,
- &*hidden,
- &down_tree,
- )?;
-
- Ok(result)
+ match config {
+ MLPConfig::Dense(dense) => {
+ let up_tree = parameter_tree.subtree("up_projection")?;
+ let down_tree = parameter_tree.subtree("down_projection")?;
+
+ let fused_hidden_gate = linear_subgraph(
+ graph,
+ &dense.linear_config,
+ model_dim,
+ [hidden_dim, hidden_dim],
+ false,
+ input,
+ &up_tree,
+ )?;
+
+ let split_results =
+ graph.split_num_splits(&fused_hidden_gate, 2, 1, None);
+ let up_proj = &split_results[0];
+ let gate = &split_results[1];
+
+ let activated_gate = activation(
+ graph,
+ &dense.activation,
+ &*gate,
+ dense.linear_config.activation_precision().into(),
+ );
+ let hidden = graph.multiplication(&activated_gate, up_proj, None);
+
+ let result = linear_subgraph(
+ graph,
+ &dense.linear_config,
+ hidden_dim,
+ [model_dim],
+ false,
+ &*hidden,
+ &down_tree,
+ )?;
+
+ Ok(result)
+ },
+ MLPConfig::MixtureOfExperts(_moe) => {
+ unreachable!("MoE uses MoeBlockEncodable, not MPSGraph")
+ },
+ }
}
diff --git a/crates/uzu/src/backends/metal/kernel/attention/attention.metal b/crates/uzu/src/backends/metal/kernel/attention/attention.metal
index a419d48ef..988114b99 100644
--- a/crates/uzu/src/backends/metal/kernel/attention/attention.metal
+++ b/crates/uzu/src/backends/metal/kernel/attention/attention.metal
@@ -9,6 +9,7 @@ constant bool query_transposed [[function_constant(21)]];
constant bool do_causal [[function_constant(22)]];
constant bool bool_mask [[function_constant(23)]];
constant bool float_mask [[function_constant(24)]];
+constant bool has_sinks [[function_constant(25)]];
template <typename T, int head_dim, int value_dim = head_dim>
void attention_single_pass_impl(
@@ -28,8 +29,9 @@ void attention_single_pass_impl(
const constant int& mask_kv_seq_stride,
const constant int& mask_q_seq_stride,
const constant int& mask_head_stride,
- uint3 tid, // thread index in threadgroup
- uint3 tpg, // threads per group
+ const device float* sinks,
+ uint3 tid, // threadgroup position in grid
+ uint3 tpg, // threadgroups per grid
uint simd_gid, // simdgroup index in threadgroup
uint simd_lid, // thread index in simdgroup
threadgroup float* shared_max_scores,
@@ -78,6 +80,12 @@ void attention_single_pass_impl(
U max_score = -INFINITY;
U sum_exp_score = 0;
+ if (has_sinks && simd_gid == 0) {
+ const int num_q_heads = static_cast<int>(tpg.x);
+ int q_head_idx = head_idx % num_q_heads;
+ max_score = static_cast<U>(sinks[q_head_idx]);
+ sum_exp_score = 1;
+ }
// For each key
for (int i = simd_gid; i < sequence_length; i += sequence_block_size) {
@@ -176,8 +184,9 @@ void attention_2pass_1_impl(
const constant int& mask_kv_seq_stride,
const constant int& mask_q_seq_stride,
const constant int& mask_head_stride,
- uint3 tid, // thread index in threadgroup
- uint3 tpg, // threads per group
+ const device float* sinks,
+ uint3 tid, // threadgroup position in grid
+ uint3 tpg, // threadgroups per grid
uint simd_gid, // simdgroup index in threadgroup
uint simd_lid, // thread index in simdgroup
threadgroup float* shared_max_scores,
@@ -229,6 +238,12 @@ void attention_2pass_1_impl(
U max_score = -1e9;
U sum_exp_score = 0;
+ if (has_sinks && block_idx == 0 && simd_gid == 0) {
+ const int num_q_heads = static_cast<int>(tpg.x);
+ int q_head_idx = head_idx % num_q_heads;
+ max_score = static_cast<U>(sinks[q_head_idx]);
+ sum_exp_score = 1;
+ }
// For each key
for (int i = block_idx * sequence_block_size + simd_gid; i < sequence_length; i += total_blocks_count * sequence_block_size) {
@@ -389,6 +404,7 @@ void attention_single_pass(
const constant int& mask_kv_seq_stride,
const constant int& mask_q_seq_stride,
const constant int& mask_head_stride,
+ const device float* sinks,
uint3 tid,
uint3 tpg,
uint simd_gid,
@@ -401,6 +417,7 @@ void attention_single_pass(
queries, keys, values, out, gqa_factor, sequence_length,
k_head_stride, k_seq_stride, v_head_stride, v_seq_stride,
scale, bmask, fmask, mask_kv_seq_stride, mask_q_seq_stride, mask_head_stride,
+ sinks,
tid, tpg, simd_gid, simd_lid,
shared_max_scores, shared_sum_exp_scores, shared_outputs
);
@@ -426,6 +443,7 @@ void attention_2pass_1(
const constant int& mask_kv_seq_stride,
const constant int& mask_q_seq_stride,
const constant int& mask_head_stride,
+ const device float* sinks,
uint3 tid,
uint3 tpg,
uint simd_gid,
@@ -438,6 +456,7 @@ void attention_2pass_1(
queries, keys, values, out, sums, maxs, gqa_factor, sequence_length,
k_head_stride, k_seq_stride, v_head_stride, v_seq_stride,
scale, bmask, fmask, mask_kv_seq_stride, mask_q_seq_stride, mask_head_stride,
+ sinks,
tid, tpg, simd_gid, simd_lid,
shared_max_scores, shared_sum_exp_scores, shared_outputs
);
@@ -477,6 +496,7 @@ void attention_2pass_2(
const constant int& mask_kv_seq_stride [[ buffer(13), function_constant(has_mask) ]], \
const constant int& mask_q_seq_stride [[ buffer(14), function_constant(has_mask) ]], \
const constant int& mask_head_stride [[ buffer(15), function_constant(has_mask) ]], \
+ const device float* sinks [[ buffer(16), function_constant(has_sinks) ]], \
uint3 tid [[ threadgroup_position_in_grid ]], \
uint3 tpg [[ threadgroups_per_grid ]], \
uint simd_gid [[ simdgroup_index_in_threadgroup ]], \
@@ -485,7 +505,7 @@ void attention_2pass_2(
#define innerArguments \
(queries, keys, values, out, gqa_factor, sequence_length, k_head_stride, k_seq_stride, \
v_head_stride, v_seq_stride, scale, bmask, fmask, mask_kv_seq_stride, \
- mask_q_seq_stride, mask_head_stride, tid, tpg, simd_gid, simd_lid, \
+ mask_q_seq_stride, mask_head_stride, sinks, tid, tpg, simd_gid, simd_lid, \
shared_max_scores, shared_sum_exp_scores, shared_outputs) \
// Generate single-pass kernels for different head dimensions
@@ -541,6 +561,7 @@ GENERATE_SINGLE_PASS_KERNELS(256)
const constant int& mask_kv_seq_stride [[ buffer(15), function_constant(has_mask) ]], \
const constant int& mask_q_seq_stride [[ buffer(16), function_constant(has_mask) ]], \
const constant int& mask_head_stride [[ buffer(17), function_constant(has_mask) ]], \
+ const device float* sinks [[ buffer(18), function_constant(has_sinks) ]], \
uint3 tid [[ threadgroup_position_in_grid ]], \
uint3 tpg [[ threadgroups_per_grid ]], \
uint simd_gid [[ simdgroup_index_in_threadgroup ]], \
@@ -549,7 +570,7 @@ GENERATE_SINGLE_PASS_KERNELS(256)
#define innerArguments \
(queries, keys, values, out, sums, maxs, gqa_factor, sequence_length, k_head_stride, k_seq_stride, \
v_head_stride, v_seq_stride, scale, bmask, fmask, mask_kv_seq_stride, \
- mask_q_seq_stride, mask_head_stride, tid, tpg, simd_gid, simd_lid, \
+ mask_q_seq_stride, mask_head_stride, sinks, tid, tpg, simd_gid, simd_lid, \
shared_max_scores, shared_sum_exp_scores, shared_outputs) \
// Generate 2-pass Pass 1 kernels for different head dimensions
@@ -687,4 +708,4 @@ void update_kv_cache(
generateKernels(update_kv_cache)
#undef outerArguments
-#undef innerArguments
\ No newline at end of file
+#undef innerArguments
diff --git a/crates/uzu/src/backends/metal/kernel/attention/mod.rs b/crates/uzu/src/backends/metal/kernel/attention/mod.rs
index 077d34034..63b8d8cb7 100644
--- a/crates/uzu/src/backends/metal/kernel/attention/mod.rs
+++ b/crates/uzu/src/backends/metal/kernel/attention/mod.rs
@@ -25,9 +25,11 @@ pub enum AttentionKernelVariant {
TwoPass,
}
+type PipelineKey = (usize, bool);
+
pub struct AttentionKernelPipelines {
- single_pass: HashMap<usize, MTLComputePipelineState>,
- two_pass_1: HashMap<usize, MTLComputePipelineState>,
+ single_pass: HashMap<PipelineKey, MTLComputePipelineState>,
+ two_pass_1: HashMap<PipelineKey, MTLComputePipelineState>,
two_pass_2: HashMap<usize, MTLComputePipelineState>,
kv_cache_update: Option<MTLComputePipelineState>,
}
@@ -62,6 +64,7 @@ pub struct AttentionSinglePassArguments<'a> {
pub mask_kv_seq_stride: i32, // buffer(13)
pub mask_q_seq_stride: i32, // buffer(14)
pub mask_head_stride: i32, // buffer(15)
+ pub sinks_buffer: Option<&'a MTLBuffer>, // buffer(16)
pub num_heads: usize,
pub suffix_length: usize,
pub head_dim: usize,
@@ -86,6 +89,7 @@ pub struct AttentionTwoPassArguments<'a> {
pub mask_kv_seq_stride: i32, // buffer(15)
pub mask_q_seq_stride: i32, // buffer(16)
pub mask_head_stride: i32, // buffer(17)
+ pub sinks_buffer: Option<&'a MTLBuffer>, // buffer(18)
pub num_heads: usize,
pub suffix_length: usize,
pub head_dim: usize,
@@ -104,6 +108,49 @@ pub struct KVCacheUpdateArguments<'a> {
pub max_sequence_length: usize,
}
+fn make_function_constants(has_sinks_value: bool) -> FunctionConstantValues {
+ let function_constants = FunctionConstantValues::new();
+
+ let has_mask_value = true;
+ let query_transposed_value = false;
+ let do_causal_value = false;
+ let bool_mask_value = false;
+ let float_mask_value = true;
+
+ function_constants.set_constant_value_at_index(
+ &has_mask_value as *const bool as *const std::ffi::c_void,
+ MTLDataType::Bool,
+ 20,
+ ); // has_mask
+ function_constants.set_constant_value_at_index(
+ &query_transposed_value as *const bool as *const std::ffi::c_void,
+ MTLDataType::Bool,
+ 21,
+ ); // query_transposed
+ function_constants.set_constant_value_at_index(
+ &do_causal_value as *const bool as *const std::ffi::c_void,
+ MTLDataType::Bool,
+ 22,
+ ); // do_causal
+ function_constants.set_constant_value_at_index(
+ &bool_mask_value as *const bool as *const std::ffi::c_void,
+ MTLDataType::Bool,
+ 23,
+ ); // bool_mask
+ function_constants.set_constant_value_at_index(
+ &float_mask_value as *const bool as *const std::ffi::c_void,
+ MTLDataType::Bool,
+ 24,
+ ); // float_mask
+ function_constants.set_constant_value_at_index(
+ &has_sinks_value as *const bool as *const std::ffi::c_void,
+ MTLDataType::Bool,
+ 25,
+ ); // has_sinks
+
+ function_constants
+}
+
impl AttentionKernel {
pub fn new(
context: &MTLContext,
@@ -111,75 +158,53 @@ impl AttentionKernel {
) -> Result<Self, AttentionError> {
let data_suffix = data_type.function_name_suffix();
- let function_constants = FunctionConstantValues::new();
-
- let has_mask_value = true;
- let query_transposed_value = false;
- let do_causal_value = false;
- let bool_mask_value = false;
- let float_mask_value = true;
-
- function_constants.set_constant_value_at_index(
- &has_mask_value as *const bool as *const std::ffi::c_void,
- MTLDataType::Bool,
- 20,
- ); // has_mask
- function_constants.set_constant_value_at_index(
- &query_transposed_value as *const bool as *const std::ffi::c_void,
- MTLDataType::Bool,
- 21,
- ); // query_transposed
- function_constants.set_constant_value_at_index(
- &do_causal_value as *const bool as *const std::ffi::c_void,
- MTLDataType::Bool,
- 22,
- ); // do_causal
- function_constants.set_constant_value_at_index(
- &bool_mask_value as *const bool as *const std::ffi::c_void,
- MTLDataType::Bool,
- 23,
- ); // bool_mask
- function_constants.set_constant_value_at_index(
- &float_mask_value as *const bool as *const std::ffi::c_void,
- MTLDataType::Bool,
- 24,
- ); // float_mask
-
let supported_head_dims = [64, 128, 256];
let mut single_pass = HashMap::new();
let mut two_pass_1 = HashMap::new();
let mut two_pass_2 = HashMap::new();
- // Pre-generate all supported variants
- for &head_dim in &supported_head_dims {
- if let Ok((pipeline, _)) = context
- .compute_pipeline_state_with_reflection(
- &format!(
- "attention_single_pass_{}_{}",
- data_suffix, head_dim
- ),
- Some(&function_constants),
- )
- {
- single_pass.insert(head_dim, pipeline);
- }
+ // Pre-generate all supported variants for both sink configurations
+ for &has_sinks_value in &[false, true] {
+ let function_constants = make_function_constants(has_sinks_value);
+
+ for &head_dim in &supported_head_dims {
+ if let Ok((pipeline, _)) = context
+ .compute_pipeline_state_with_reflection(
+ &format!(
+ "attention_single_pass_{}_{}",
+ data_suffix, head_dim
+ ),
+ Some(&function_constants),
+ )
+ {
+ single_pass.insert((head_dim, has_sinks_value), pipeline);
+ }
- if let Ok((pipeline, _)) = context
- .compute_pipeline_state_with_reflection(
- &format!("attention_2pass_1_{}_{}", data_suffix, head_dim),
- Some(&function_constants),
- )
- {
- two_pass_1.insert(head_dim, pipeline);
- }
+ if let Ok((pipeline, _)) = context
+ .compute_pipeline_state_with_reflection(
+ &format!(
+ "attention_2pass_1_{}_{}",
+ data_suffix, head_dim
+ ),
+ Some(&function_constants),
+ )
+ {
+ two_pass_1.insert((head_dim, has_sinks_value), pipeline);
+ }
- if let Ok((pipeline, _)) = context
- .compute_pipeline_state_with_reflection(
- &format!("attention_2pass_2_{}_{}", data_suffix, head_dim),
- Some(&function_constants),
- )
- {
- two_pass_2.insert(head_dim, pipeline);
+ if !two_pass_2.contains_key(&head_dim) {
+ if let Ok((pipeline, _)) = context
+ .compute_pipeline_state_with_reflection(
+ &format!(
+ "attention_2pass_2_{}_{}",
+ data_suffix, head_dim
+ ),
+ Some(&function_constants),
+ )
+ {
+ two_pass_2.insert(head_dim, pipeline);
+ }
+ }
}
}
@@ -205,14 +230,14 @@ impl AttentionKernel {
&self,
head_dim: usize,
) -> bool {
- self.pipelines.single_pass.contains_key(&head_dim)
+ self.pipelines.single_pass.contains_key(&(head_dim, false))
}
pub fn supports_two_pass(
&self,
head_dim: usize,
) -> bool {
- self.pipelines.two_pass_1.contains_key(&head_dim)
+ self.pipelines.two_pass_1.contains_key(&(head_dim, false))
&& self.pipelines.two_pass_2.contains_key(&head_dim)
}
@@ -233,10 +258,12 @@ impl AttentionKernel {
compute_encoder: &ComputeCommandEncoderRef,
args: AttentionSinglePassArguments,
) -> Result<(), AttentionError> {
- let pipeline =
- self.pipelines.single_pass.get(&args.head_dim).ok_or_else(
- || AttentionError::UnsupportedHeadDim(args.head_dim),
- )?;
+ let has_sinks = args.sinks_buffer.is_some();
+ let pipeline = self
+ .pipelines
+ .single_pass
+ .get(&(args.head_dim, has_sinks))
+ .ok_or_else(|| AttentionError::UnsupportedHeadDim(args.head_dim))?;
compute_encoder.set_compute_pipeline_state(pipeline);
@@ -300,6 +327,10 @@ impl AttentionKernel {
);
}
+ if let Some(sinks_buffer) = args.sinks_buffer {
+ compute_encoder.set_buffer(16, Some(sinks_buffer), 0);
+ }
+
let threads_per_threadgroup = MTLSize {
width: 32 * 32, // sequence_block_size * head_block_size
height: 1,
@@ -324,10 +355,12 @@ impl AttentionKernel {
compute_encoder: &ComputeCommandEncoderRef,
args: AttentionTwoPassArguments,
) -> Result<(), AttentionError> {
- let pass1_pipeline =
- self.pipelines.two_pass_1.get(&args.head_dim).ok_or_else(|| {
- AttentionError::UnsupportedHeadDim(args.head_dim)
- })?;
+ let has_sinks = args.sinks_buffer.is_some();
+ let pass1_pipeline = self
+ .pipelines
+ .two_pass_1
+ .get(&(args.head_dim, has_sinks))
+ .ok_or_else(|| AttentionError::UnsupportedHeadDim(args.head_dim))?;
let pass2_pipeline =
self.pipelines.two_pass_2.get(&args.head_dim).ok_or_else(|| {
@@ -399,6 +432,10 @@ impl AttentionKernel {
);
}
+ if let Some(sinks_buffer) = args.sinks_buffer {
+ compute_encoder.set_buffer(18, Some(sinks_buffer), 0);
+ }
+
let total_blocks_count = 32u64;
let pass1_threads_per_threadgroup = MTLSize {
width: 8 * 32, // sequence_block_size * head_block_size
@@ -516,6 +553,7 @@ pub struct AttentionKernelEncodable {
kernel: AttentionKernel,
layer_index: usize,
attention_scale: Option<f32>,
+ has_sinks: bool,
}
impl AttentionKernelEncodable {
@@ -524,12 +562,14 @@ impl AttentionKernelEncodable {
data_type: KernelDataType,
layer_index: usize,
attention_scale: Option<f32>,
+ has_sinks: bool,
) -> Result<Self, AttentionError> {
let kernel = AttentionKernel::new(context, data_type)?;
Ok(Self {
kernel,
layer_index,
attention_scale,
+ has_sinks,
})
}
}
@@ -602,6 +642,16 @@ impl EncodableWithState for AttentionKernelEncodable {
let attention_output_binding =
state.arrays(&[ArrayId::AttentionOutput]);
+ let attention_bias_map = attention_bias_binding[0].clone();
+ let mask_kv_seq_stride = 1;
+ let mask_q_seq_stride = sequence_length as i32;
+ let mask_head_stride = 0;
+ let sinks_binding = if self.has_sinks {
+ Some(state.arrays(&[ArrayId::AttentionSinks(self.layer_index)]))
+ } else {
+ None
+ };
+
let mut rotated_keys_array = rotated_keys_binding[0].borrow_mut();
let rotated_keys_buffer = unsafe { rotated_keys_array.mtl_buffer() };
@@ -622,7 +672,6 @@ impl EncodableWithState for AttentionKernelEncodable {
let attention_output_buffer =
unsafe { attention_output_array.mtl_buffer() };
- let attention_bias_map = attention_bias_binding[0].clone();
let attention_bias_buffer = attention_bias_map
.get(&window_length)
.map(|array| {
@@ -649,6 +698,10 @@ impl EncodableWithState for AttentionKernelEncodable {
let mut maxs_array = maxs_binding[0].borrow_mut();
let maxs_buffer = unsafe { maxs_array.mtl_buffer() };
+ let sinks_buffer = sinks_binding.as_ref().map(|binding| unsafe {
+ binding[0].borrow_mut().mtl_buffer().clone()
+ });
+
let mtl_command_buffer =
command_buffer.root_command_buffer().to_owned();
@@ -679,10 +732,6 @@ impl EncodableWithState for AttentionKernelEncodable {
let v_head_stride = (max_sequence_length * head_dim) as i32;
let v_seq_stride = head_dim as i32;
- let mask_kv_seq_stride = 1;
- let mask_q_seq_stride = sequence_length as i32;
- let mask_head_stride = 0;
-
match variant {
AttentionKernelVariant::SinglePass => {
if let Err(e) = self.kernel.encode_single_pass(
@@ -703,6 +752,7 @@ impl EncodableWithState for AttentionKernelEncodable {
mask_kv_seq_stride,
mask_q_seq_stride,
mask_head_stride,
+ sinks_buffer: sinks_buffer.as_ref(),
num_heads,
suffix_length,
head_dim,
@@ -736,6 +786,7 @@ impl EncodableWithState for AttentionKernelEncodable {
mask_kv_seq_stride,
mask_q_seq_stride,
mask_head_stride,
+ sinks_buffer: sinks_buffer.as_ref(),
num_heads,
suffix_length,
head_dim,
diff --git a/crates/uzu/src/backends/metal/kernel/linear/mod.rs b/crates/uzu/src/backends/metal/kernel/linear/mod.rs
index d4efc2b57..bc736dcd2 100644
--- a/crates/uzu/src/backends/metal/kernel/linear/mod.rs
+++ b/crates/uzu/src/backends/metal/kernel/linear/mod.rs
@@ -3,8 +3,10 @@ use std::rc::Rc;
use metal::Buffer as MTLBuffer;
use mpsgraph::CommandBuffer as MPSCommandBuffer;
-use super::quant_matmul::{QuantizedMatmulArguments, QuantizedMatmulKernel};
-use super::{KernelDataType, TensorAddBias};
+use super::{
+ KernelDataType, TensorAddBias,
+ quant_matmul::{QuantizedMatmulArguments, QuantizedMatmulKernel},
+};
use crate::{
Array, DataType,
backends::metal::{
@@ -112,29 +114,33 @@ impl QuantizedLinearKernelBlock {
unsafe { weights.mtl_buffer() }.to_owned();
// Optional trainable bias support
- let (bias_add_kernel, biases_buffer) = match parameter_tree.leaf("biases") {
- Ok(mut biases) => {
- if biases.shape() != [output_dim] {
- return Err(MTLError::Generic(format!(
- "Bias shape mismatch: got {:?}, expected [{:?}]",
- biases.shape(), output_dim
- )));
- }
- if biases.data_type() != kernel_data_type {
- return Err(MTLError::Generic(format!(
- "Bias dtype mismatch: got {:?}, expected {:?}",
- biases.data_type(), kernel_data_type
- )));
- }
- let bias_add_kernel = Some(TensorAddBias::new(
- mtl_context,
- KernelDataType::from(kernel_data_type),
- )?);
- let biases_buffer: MTLBuffer = unsafe { biases.mtl_buffer() }.to_owned();
- (bias_add_kernel, Some(biases_buffer))
- },
- Err(_) => (None, None),
- };
+ let (bias_add_kernel, biases_buffer) =
+ match parameter_tree.leaf("biases") {
+ Ok(mut biases) => {
+ if biases.shape() != [output_dim] {
+ return Err(MTLError::Generic(format!(
+ "Bias shape mismatch: got {:?}, expected [{:?}]",
+ biases.shape(),
+ output_dim
+ )));
+ }
+ if biases.data_type() != kernel_data_type {
+ return Err(MTLError::Generic(format!(
+ "Bias dtype mismatch: got {:?}, expected {:?}",
+ biases.data_type(),
+ kernel_data_type
+ )));
+ }
+ let bias_add_kernel = Some(TensorAddBias::new(
+ mtl_context,
+ KernelDataType::from(kernel_data_type),
+ )?);
+ let biases_buffer: MTLBuffer =
+ unsafe { biases.mtl_buffer() }.to_owned();
+ (bias_add_kernel, Some(biases_buffer))
+ },
+ Err(_) => (None, None),
+ };
let g = config.group_size;
let (kernel_name_mm, kernel_name_mv) = match (kernel_data_type, g) {
@@ -246,7 +252,9 @@ impl EncodableWithState for QuantizedLinearKernelBlock {
encoder.end_encoding();
- if let (Some(bias_add), Some(bias_buf)) = (&self.bias_add_kernel, &self.biases_buffer) {
+ if let (Some(bias_add), Some(bias_buf)) =
+ (&self.bias_add_kernel, &self.biases_buffer)
+ {
let total_len = batch_size * self.output_dim;
let retained_cb = root_command_buffer.to_owned();
bias_add.encode_into_command_buffer(
diff --git a/crates/uzu/src/backends/metal/kernel/mlp/mod.rs b/crates/uzu/src/backends/metal/kernel/mlp/mod.rs
index 3d39c4f99..61af0f929 100644
--- a/crates/uzu/src/backends/metal/kernel/mlp/mod.rs
+++ b/crates/uzu/src/backends/metal/kernel/mlp/mod.rs
@@ -89,7 +89,9 @@ impl MlpGateActMulKernel {
fn act_code(act: &Activation) -> u16 {
match act {
- Activation::SILU => 0,
+ Activation::SILU {
+ ..
+ } => 0,
Activation::GELU => 1,
}
}
diff --git a/crates/uzu/src/backends/metal/kernel/mod.rs b/crates/uzu/src/backends/metal/kernel/mod.rs
index b20c740da..e68739bf1 100644
--- a/crates/uzu/src/backends/metal/kernel/mod.rs
+++ b/crates/uzu/src/backends/metal/kernel/mod.rs
@@ -4,25 +4,35 @@ pub mod kv_cache_update;
pub mod linear;
pub mod media_kernels;
pub mod mlp;
+pub mod moe;
pub mod quant_matmul;
pub mod rms_norm;
pub mod rope;
pub mod sampling;
-mod tensor_add_swap;
mod tensor_add_bias;
+mod tensor_add_swap;
mod tensor_copy;
pub use attention::{AttentionKernel, AttentionKernelEncodable};
pub use data_type::KernelDataType;
pub use kv_cache_update::KVCacheUpdate;
+pub use moe::{
+ MoeBlockBasesArguments, MoeBlockEncodable, MoeCountsOffsetsFusedArguments,
+ MoeCountsOffsetsFusedError, MoeCountsOffsetsFusedKernel,
+ MoeExpertsArguments, MoeExpertsError, MoeExpertsTwoPassArguments,
+ MoeExpertsTwoPassDecodeKernel, MoeExpertsTwoPassPrefillKernel,
+ MoeFinalizeArguments, MoeFinalizeError, MoeFinalizeKernel,
+ MoeScatterArguments, MoeScatterError, MoeScatterKernels,
+ MoeScatterWithMapArguments,
+};
pub use rms_norm::{
QKNormArguments, QKNormKernelEncodable, RMSNormArguments, RMSNormKernel,
RMSNormKernelEncodable, RMSNormKernelType,
};
pub use rope::{RopeKernel, RopeKernelEncodable};
pub use sampling::{SamplingKernel, SamplingKernelEncodable};
-pub use tensor_add_swap::TensorAddSwap;
pub use tensor_add_bias::TensorAddBias;
+pub use tensor_add_swap::TensorAddSwap;
pub use tensor_copy::TensorCopy;
use super::{MTLContext, metal_extensions};
diff --git a/crates/uzu/src/backends/metal/kernel/moe/counts_offsets_fused.metal b/crates/uzu/src/backends/metal/kernel/moe/counts_offsets_fused.metal
new file mode 100644
index 000000000..d8d5a9aca
--- /dev/null
+++ b/crates/uzu/src/backends/metal/kernel/moe/counts_offsets_fused.metal
@@ -0,0 +1,103 @@
+#include <metal_stdlib>
+#include <metal_atomic>
+using namespace metal;
+
+#include "../definitions.metal"
+
+#define BLOCK_SIZE 128
+#define TILE_E 512
+
+// Single-kernel fused: count all experts + scan to offsets
+// This kernel is launched with SINGLE threadgroup
+kernel void moe_counts_offsets_fused(
+ device const int* topk_ids [[buffer(0)]],
+ device uint* offsets [[buffer(1)]], // output: exclusive scan [E+1]
+ device uint* sum_k_out [[buffer(2)]], // output: total count [1]
+ device uint* partials [[buffer(3)]], // output: partials [num_tiles * TILE_E] (for block_bases)
+ constant uint& T [[buffer(4)]],
+ constant uint& E [[buffer(5)]],
+ constant uint& K [[buffer(6)]],
+ uint lid [[thread_index_in_threadgroup]])
+{
+ if (E == 0) {
+ if (lid == 0) {
+ offsets[0] = 0u;
+ sum_k_out[0] = 0u;
+ }
+ return;
+ }
+
+ threadgroup _atomic<uint> tg_hist[TILE_E];
+ threadgroup uint scan_shared[BLOCK_SIZE];
+ threadgroup uint reduce_shared[BLOCK_SIZE];
+ threadgroup uint counts_shared[BLOCK_SIZE]; // Cache counts in threadgroup memory
+
+ // ═══════════════════════════════════════════════════════════
+ // PHASE 1: Count tokens per expert using tiled histogram
+ // ═══════════════════════════════════════════════════════════
+ // Tile over E dimension
+ for (uint e0 = 0; e0 < E; e0 += TILE_E) {
+ const uint tile_e = (e0 + TILE_E <= E) ? TILE_E : (E - e0);
+
+ // Zero threadgroup histogram
+ for (uint e = lid; e < tile_e; e += BLOCK_SIZE) {
+ atomic_store_explicit(&tg_hist[e], 0u, memory_order_relaxed);
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ // Process all tokens in strided fashion
+ // Since we have only 1 threadgroup, we need to cover all T tokens
+ for (uint t = lid; t < T; t += BLOCK_SIZE) {
+ const uint base = t * K;
+ for (uint k = 0; k < K; ++k) {
+ int eid = topk_ids[base + k];
+ if (eid >= 0) {
+ uint ue = uint(eid);
+ if (ue >= e0 && ue < e0 + tile_e) {
+ uint te = ue - e0;
+ atomic_fetch_add_explicit(&tg_hist[te], 1u, memory_order_relaxed);
+ }
+ }
+ }
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ // Write final counts and partials for this tile
+ for (uint e = lid; e < tile_e; e += BLOCK_SIZE) {
+ const uint count_val = atomic_load_explicit(&tg_hist[e], memory_order_relaxed);
+ counts_shared[e0 + e] = count_val;
+ partials[e0 + e] = count_val;
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ }
+
+ // ═══════════════════════════════════════════════════════════
+ // PHASE 2: Compute exclusive prefix scan on counts
+ // ═══════════════════════════════════════════════════════════
+ threadgroup uint carry;
+ if (lid == 0) { carry = 0u; }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ for (uint base = 0; base < E; base += BLOCK_SIZE) {
+ uint remaining = E - base;
+ uint chunk_n = remaining < BLOCK_SIZE ? remaining : BLOCK_SIZE;
+
+ uint v = (lid < chunk_n) ? counts_shared[lid] : 0u;
+
+ uint prefix_local = threadgroup_raking_prefix_exclusive_sum<BLOCK_SIZE>(v, scan_shared, (ushort)lid);
+ uint prefix_global = prefix_local + carry;
+ if (lid < chunk_n) {
+ offsets[base + lid] = prefix_global;
+ }
+
+ uint block_sum = threadgroup_cooperative_reduce_sum<BLOCK_SIZE>(v, reduce_shared, (ushort)lid);
+ if (lid == 0) { carry += block_sum; }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ }
+
+ // Write final offset and total
+ if (lid == 0) {
+ offsets[E] = carry;
+ sum_k_out[0] = carry;
+ }
+}
diff --git a/crates/uzu/src/backends/metal/kernel/moe/counts_offsets_fused.rs b/crates/uzu/src/backends/metal/kernel/moe/counts_offsets_fused.rs
new file mode 100644
index 000000000..b5bd0776e
--- /dev/null
+++ b/crates/uzu/src/backends/metal/kernel/moe/counts_offsets_fused.rs
@@ -0,0 +1,104 @@
+use std::mem::size_of;
+
+use metal::{
+ Buffer as MTLBuffer, CommandBufferRef,
+ ComputePipelineState as MTLComputePipelineState, MTLSize,
+};
+
+use crate::backends::metal::{MTLContext, MTLError};
+
+// ---- Fused Counts + Offsets Kernel ----
+
+#[derive(Debug, thiserror::Error)]
+pub enum MoeCountsOffsetsFusedError {
+ #[error("Metal error: {0}")]
+ MetalError(#[from] MTLError),
+ #[error("Invalid dimensions: T={t}, E={e}, K={k}")]
+ InvalidDimensions {
+ t: usize,
+ e: usize,
+ k: usize,
+ },
+}
+
+pub struct MoeCountsOffsetsFusedKernel {
+ pipeline: MTLComputePipelineState,
+}
+
+#[derive(Debug)]
+pub struct MoeCountsOffsetsFusedArguments<'a> {
+ pub topk_ids_buffer: &'a MTLBuffer,
+ pub offsets_buffer: &'a MTLBuffer, // output [E+1]
+ pub sum_k_buffer: &'a MTLBuffer, // output [1]
+ pub partials_buffer: &'a MTLBuffer, // output [num_tiles * 512] (for block_bases)
+ pub t: usize,
+ pub e: usize,
+ pub k: usize,
+}
+
+impl MoeCountsOffsetsFusedKernel {
+ pub fn new(
+ mtl_context: &MTLContext
+ ) -> Result<Self, MoeCountsOffsetsFusedError> {
+ let pipeline = mtl_context
+ .compute_pipeline_state("moe_counts_offsets_fused", None)?;
+ Ok(Self {
+ pipeline,
+ })
+ }
+
+ pub fn encode(
+ &self,
+ command_buffer: &CommandBufferRef,
+ args: MoeCountsOffsetsFusedArguments,
+ ) -> Result<(), MoeCountsOffsetsFusedError> {
+ if args.k == 0 || args.e == 0 {
+ return Ok(());
+ }
+ if args.t == 0 {
+ return Ok(());
+ }
+ if args.e < 1 {
+ return Err(MoeCountsOffsetsFusedError::InvalidDimensions {
+ t: args.t,
+ e: args.e,
+ k: args.k,
+ });
+ }
+
+ let encoder = command_buffer.new_compute_command_encoder();
+ encoder.set_compute_pipeline_state(&self.pipeline);
+
+ encoder.set_buffer(0, Some(args.topk_ids_buffer), 0);
+ encoder.set_buffer(1, Some(args.offsets_buffer), 0);
+ encoder.set_buffer(2, Some(args.sum_k_buffer), 0);
+ encoder.set_buffer(3, Some(args.partials_buffer), 0);
+
+ let t_u32 = args.t as u32;
+ let e_u32 = args.e as u32;
+ let k_u32 = args.k as u32;
+
+ encoder.set_bytes(
+ 4,
+ size_of::<u32>() as u64,
+ &t_u32 as *const u32 as *const std::ffi::c_void,
+ );
+ encoder.set_bytes(
+ 5,
+ size_of::<u32>() as u64,
+ &e_u32 as *const u32 as *const std::ffi::c_void,
+ );
+ encoder.set_bytes(
+ 6,
+ size_of::<u32>() as u64,
+ &k_u32 as *const u32 as *const std::ffi::c_void,
+ );
+
+ let threads_per_threadgroup = MTLSize::new(128, 1, 1);
+ let tg = MTLSize::new(1, 1, 1);
+ encoder.dispatch_thread_groups(tg, threads_per_threadgroup);
+
+ encoder.end_encoding();
+ Ok(())
+ }
+}
diff --git a/crates/uzu/src/backends/metal/kernel/moe/encodable.rs b/crates/uzu/src/backends/metal/kernel/moe/encodable.rs
new file mode 100644
index 000000000..3a8bf1b93
--- /dev/null
+++ b/crates/uzu/src/backends/metal/kernel/moe/encodable.rs
@@ -0,0 +1,632 @@
+use std::{cell::RefCell, rc::Rc};
+
+use mpsgraph::CommandBuffer as MPSCommandBuffer;
+
+use super::{
+ MoeCountsOffsetsFusedArguments, MoeCountsOffsetsFusedKernel,
+ MoeExpertsTwoPassArguments, MoeExpertsTwoPassDecodeKernel,
+ MoeExpertsTwoPassPrefillKernel, MoeFinalizeKernel, MoeGatherArguments,
+ MoeGatherKernel, MoeRouterTopKArguments, MoeRouterTopKKernel,
+ MoeScatterKernels, MoeScatterWithMapArguments,
+};
+use crate::{
+ DataType,
+ backends::metal::{
+ KernelDataType, MTLContext, MetalArray,
+ forward_pass::{
+ ArrayId, ForwardPassState,
+ encodable_with_state::{EncodableWithState, EncodingParameters},
+ },
+ },
+ config::{
+ Activation, LinearConfig, MixtureOfExpertsConfig,
+ mlp::RoutingFunctionConfig,
+ },
+ parameters::ParameterTree,
+};
+
+enum RouterBlock {
+ Metal {
+ weights_buf: metal::Buffer,
+ biases_buf: metal::Buffer,
+ },
+}
+
+#[derive(Clone)]
+pub struct SharedMoeWeights {
+ pub w13_buf: Rc<metal::Buffer>,
+ pub w2_buf: Rc<metal::Buffer>,
+ pub up_biases_buf: Rc<metal::Buffer>,
+ pub down_biases_buf: Rc<metal::Buffer>,
+}
+
+pub struct MoeBlockEncodable {
+ router: RouterBlock,
+ router_data_type: KernelDataType,
+ router_renorm: bool,
+ router_topk_kernel: MoeRouterTopKKernel,
+ counts_offsets_kernel: MoeCountsOffsetsFusedKernel,
+ scatter_kernels: MoeScatterKernels,
+ gather_kernel: MoeGatherKernel,
+ experts_two_pass_decode_kernel: MoeExpertsTwoPassDecodeKernel,
+ experts_two_pass_prefill_kernel: MoeExpertsTwoPassPrefillKernel,
+ finalize_kernel: MoeFinalizeKernel,
+ moe_config: MixtureOfExpertsConfig,
+ model_dim: usize,
+ hidden_dim: usize,
+ data_type: KernelDataType,
+ shared_weights: SharedMoeWeights,
+}
+
+impl MoeBlockEncodable {
+ pub fn new(
+ context: &MTLContext,
+ moe_config: &MixtureOfExpertsConfig,
+ model_dim: usize,
+ hidden_dim: usize,
+ parameter_tree: &ParameterTree<Rc<MTLContext>>,
+ ) -> Result<Self, crate::backends::metal::MTLError> {
+ let activation_data_type: DataType = moe_config
+ .expert_config
+ .linear_config
+ .activation_precision()
+ .into();
+ let data_type: KernelDataType = activation_data_type.into();
+
+ let router_data_type: DataType =
+ moe_config.router_config.activation_precision().into();
+ let router_kernel_data_type: KernelDataType = router_data_type.into();
+
+ let router_renorm = matches!(
+ moe_config.routing_function,
+ RoutingFunctionConfig::SoftmaxRouting
+ );
+
+ let router_tree = parameter_tree.subtree("router").map_err(|e| {
+ crate::backends::metal::MTLError::Generic(format!(
+ "Router subtree error: {:?}",
+ e
+ ))
+ })?;
+
+ let router = match &moe_config.router_config {
+ LinearConfig::Quantized(_) => {
+ unimplemented!(
+ "Quantized router with fused router+topk not yet supported"
+ );
+ },
+ LinearConfig::FullPrecision {
+ ..
+ } => {
+ let mut weights_arr =
+ router_tree.leaf("weights").map_err(|e| {
+ crate::backends::metal::MTLError::Generic(format!(
+ "Router weights error: {:?}",
+ e
+ ))
+ })?;
+ let weights_buf = unsafe { weights_arr.mtl_buffer().clone() };
+
+ let mut biases_arr =
+ router_tree.leaf("biases").map_err(|e| {
+ crate::backends::metal::MTLError::Generic(format!(
+ "Router biases error: {:?}",
+ e
+ ))
+ })?;
+ let biases_buf = unsafe { biases_arr.mtl_buffer().clone() };
+
+ RouterBlock::Metal {
+ weights_buf,
+ biases_buf,
+ }
+ },
+ LinearConfig::QLoRA {
+ ..
+ } => {
+ unimplemented!("QLoRA router not yet supported for MoE");
+ },
+ };
+
+ let router_topk_kernel =
+ MoeRouterTopKKernel::new(context).map_err(|e| {
+ crate::backends::metal::MTLError::Generic(format!(
+ "RouterTopK fused kernel error: {:?}",
+ e
+ ))
+ })?;
+ let counts_offsets_kernel = MoeCountsOffsetsFusedKernel::new(context)
+ .map_err(|e| {
+ crate::backends::metal::MTLError::Generic(format!(
+ "Counts+offsets kernel error: {:?}",
+ e
+ ))
+ })?;
+ let scatter_kernels = MoeScatterKernels::new(context).map_err(|e| {
+ crate::backends::metal::MTLError::Generic(format!(
+ "Scatter kernels error: {:?}",
+ e
+ ))
+ })?;
+ let gather_kernel = MoeGatherKernel::new(context).map_err(|e| {
+ crate::backends::metal::MTLError::Generic(format!(
+ "Gather kernel error: {:?}",
+ e
+ ))
+ })?;
+ let experts_two_pass_decode_kernel =
+ MoeExpertsTwoPassDecodeKernel::new(context).map_err(|e| {
+ crate::backends::metal::MTLError::Generic(format!(
+ "Experts two-pass decode kernel error: {:?}",
+ e
+ ))
+ })?;
+ let experts_two_pass_prefill_kernel =
+ MoeExpertsTwoPassPrefillKernel::new(context).map_err(|e| {
+ crate::backends::metal::MTLError::Generic(format!(
+ "Experts two-pass prefill kernel error: {:?}",
+ e
+ ))
+ })?;
+ let finalize_kernel = MoeFinalizeKernel::new(context).map_err(|e| {
+ crate::backends::metal::MTLError::Generic(format!(
+ "Finalize kernel error: {:?}",
+ e
+ ))
+ })?;
+
+ let experts_tree = parameter_tree.subtree("experts").map_err(|e| {
+ crate::backends::metal::MTLError::Generic(format!(
+ "experts subtree error: {:?}",
+ e
+ ))
+ })?;
+
+ let mut w13_arr = experts_tree
+ .subtree("up_projection")
+ .map_err(|e| {
+ crate::backends::metal::MTLError::Generic(format!(
+ "up_projection error: {:?}",
+ e
+ ))
+ })?
+ .leaf("weights")
+ .map_err(|e| {
+ crate::backends::metal::MTLError::Generic(format!(
+ "up weights error: {:?}",
+ e
+ ))
+ })?;
+ let w13_buf = unsafe { w13_arr.mtl_buffer().clone() };
+
+ let mut w2_arr = experts_tree
+ .subtree("down_projection")
+ .map_err(|e| {
+ crate::backends::metal::MTLError::Generic(format!(
+ "down_projection error: {:?}",
+ e
+ ))
+ })?
+ .leaf("weights")
+ .map_err(|e| {
+ crate::backends::metal::MTLError::Generic(format!(
+ "down weights error: {:?}",
+ e
+ ))
+ })?;
+ let w2_buf = unsafe { w2_arr.mtl_buffer().clone() };
+
+ let mut up_biases_arr = experts_tree
+ .subtree("up_projection")
+ .map_err(|e| {
+ crate::backends::metal::MTLError::Generic(format!(
+ "up_projection biases error: {:?}",
+ e
+ ))
+ })?
+ .leaf("biases")
+ .map_err(|e| {
+ crate::backends::metal::MTLError::Generic(format!(
+ "up biases error: {:?}",
+ e
+ ))
+ })?;
+ let up_biases_buf = unsafe { up_biases_arr.mtl_buffer().clone() };
+
+ let mut down_biases_arr = experts_tree
+ .subtree("down_projection")
+ .map_err(|e| {
+ crate::backends::metal::MTLError::Generic(format!(
+ "down_projection biases error: {:?}",
+ e
+ ))
+ })?
+ .leaf("biases")
+ .map_err(|e| {
+ crate::backends::metal::MTLError::Generic(format!(
+ "down biases error: {:?}",
+ e
+ ))
+ })?;
+ let down_biases_buf = unsafe { down_biases_arr.mtl_buffer().clone() };
+
+ let shared_weights = SharedMoeWeights {
+ w13_buf: Rc::new(w13_buf),
+ w2_buf: Rc::new(w2_buf),
+ up_biases_buf: Rc::new(up_biases_buf),
+ down_biases_buf: Rc::new(down_biases_buf),
+ };
+
+ Ok(Self {
+ router,
+ router_data_type: router_kernel_data_type,
+ router_renorm,
+ router_topk_kernel,
+ counts_offsets_kernel,
+ scatter_kernels,
+ gather_kernel,
+ experts_two_pass_decode_kernel,
+ experts_two_pass_prefill_kernel,
+ finalize_kernel,
+ moe_config: moe_config.clone(),
+ model_dim,
+ hidden_dim,
+ data_type,
+ shared_weights,
+ })
+ }
+
+ fn gating_code_from_activation(activation: &Activation) -> u32 {
+ match activation {
+ Activation::GELU => 3,
+ Activation::SILU {
+ ..
+ } => 2,
+ }
+ }
+}
+
+impl EncodableWithState for MoeBlockEncodable {
+ fn encode(
+ &self,
+ state: &mut ForwardPassState,
+ command_buffer: &MPSCommandBuffer,
+ parameters: &EncodingParameters,
+ ) {
+ let suffix_length = state.aux_buffers_suffix_length();
+ let arrays = state.arrays(&[
+ ArrayId::Main,
+ ArrayId::MoeTopkIds,
+ ArrayId::MoeTopkProbs,
+ ArrayId::MoeOffsets,
+ ArrayId::MoeSumK,
+ ArrayId::MoeBucketedTokenIds,
+ ArrayId::MoeBucketedProbs,
+ ArrayId::MoeXPerm,
+ ArrayId::MoeTok2Row,
+ ArrayId::MoeYPartial,
+ ArrayId::MoeTileCounts,
+ ArrayId::MoeTileOffsets,
+ ArrayId::MoeTileMap,
+ ArrayId::MoeTotalTiles,
+ ArrayId::MoeDispatchArgs,
+ ArrayId::MoeScatterPartials,
+ ArrayId::MoeScatterBlockBases,
+ ArrayId::MoeBlockAlloc,
+ ArrayId::MoeHidden,
+ ArrayId::MoeTwoPassRowExpertMap,
+ ]);
+
+ let clone_buffer = |array: &RefCell<MetalArray>| -> metal::Buffer {
+ let mut borrow = array.borrow_mut();
+ let buffer = unsafe { borrow.mtl_buffer().clone() };
+ buffer
+ };
+
+ let mut array_iter = arrays.iter();
+ let main_buf = clone_buffer(array_iter.next().unwrap());
+ let topk_ids_buf = clone_buffer(array_iter.next().unwrap());
+ let topk_probs_buf = clone_buffer(array_iter.next().unwrap());
+ let offsets_buf = clone_buffer(array_iter.next().unwrap());
+ let sumk_buf = clone_buffer(array_iter.next().unwrap());
+ let bucketed_ids_buf = clone_buffer(array_iter.next().unwrap());
+ let bucketed_probs_buf = clone_buffer(array_iter.next().unwrap());
+ let x_perm_buf = clone_buffer(array_iter.next().unwrap());
+ let tok2row_buf = clone_buffer(array_iter.next().unwrap());
+ let y_partial_buf = clone_buffer(array_iter.next().unwrap());
+ let tile_counts_buf = clone_buffer(array_iter.next().unwrap());
+ let tile_offsets_buf = clone_buffer(array_iter.next().unwrap());
+ let tile_map_buf = clone_buffer(array_iter.next().unwrap());
+ let total_tiles_buf = clone_buffer(array_iter.next().unwrap());
+ let dispatch_args_buf = clone_buffer(array_iter.next().unwrap());
+ let partials_buf = clone_buffer(array_iter.next().unwrap());
+ let block_bases_buf = clone_buffer(array_iter.next().unwrap());
+ let block_alloc_buf = clone_buffer(array_iter.next().unwrap());
+ let hidden_buf = clone_buffer(array_iter.next().unwrap());
+ let row_expert_map_buf = clone_buffer(array_iter.next().unwrap());
+ debug_assert!(array_iter.next().is_none());
+
+ let e = self.moe_config.mixture_size;
+ let k = self.moe_config.num_experts_per_token;
+
+ let mtl_command_buffer =
+ command_buffer.root_command_buffer().to_owned();
+ let root = &*mtl_command_buffer;
+ let k_tile = 128;
+
+ // Clear internal MoE buffers
+ let dtype_size = match self.data_type {
+ KernelDataType::BFloat16 | KernelDataType::Float16 => 2,
+ KernelDataType::Float32 => 4,
+ };
+
+ let blit_encoder = root.new_blit_command_encoder();
+
+ if suffix_length > 0 && k > 0 {
+ let entries = suffix_length * k;
+ let topk_bytes = entries * std::mem::size_of::<u32>();
+ let tok2row_bytes = entries * std::mem::size_of::<i32>();
+
+ // Clear topk_ids and tok2row buffers
+ if topk_bytes > 0 {
+ blit_encoder.fill_buffer(
+ &topk_ids_buf,
+ metal::NSRange::new(0, topk_bytes as u64),
+ 0xFF,
+ );
+ }
+ if tok2row_bytes > 0 {
+ blit_encoder.fill_buffer(
+ &tok2row_buf,
+ metal::NSRange::new(0, tok2row_bytes as u64),
+ 0xFF,
+ );
+ }
+
+ // Clear hidden buffer
+ let hidden_bytes =
+ (suffix_length * k * self.hidden_dim * dtype_size) as u64;
+ if hidden_bytes > 0 {
+ blit_encoder.fill_buffer(
+ &hidden_buf,
+ metal::NSRange::new(0, hidden_bytes),
+ 0,
+ );
+ }
+
+ // Clear y_partial buffer
+ let y_partial_bytes =
+ (suffix_length * k * self.model_dim * dtype_size) as u64;
+ if y_partial_bytes > 0 {
+ blit_encoder.fill_buffer(
+ &y_partial_buf,
+ metal::NSRange::new(0, y_partial_bytes),
+ 0,
+ );
+ }
+
+ // Clear x_perm buffer
+ let x_perm_bytes =
+ (suffix_length * k * self.model_dim * dtype_size) as u64;
+ if x_perm_bytes > 0 {
+ blit_encoder.fill_buffer(
+ &x_perm_buf,
+ metal::NSRange::new(0, x_perm_bytes),
+ 0,
+ );
+ }
+ }
+
+ blit_encoder.end_encoding();
+
+ // Use fused Router+TopK kernel for non-quantized routers
+ match &self.router {
+ RouterBlock::Metal {
+ weights_buf,
+ biases_buf,
+ } => {
+ // Use the fused router+topk kernel
+ self.router_topk_kernel
+ .encode(
+ root,
+ self.router_data_type,
+ MoeRouterTopKArguments {
+ input_buffer: &main_buf,
+ weight_buffer: weights_buf,
+ bias_buffer: biases_buf,
+ topk_ids_buffer: &topk_ids_buf,
+ topk_probs_buffer: &topk_probs_buf,
+ t: suffix_length,
+ d_model: self.model_dim,
+ e,
+ k,
+ renorm: self.router_renorm,
+ },
+ )
+ .expect("MoE fused router+topk failed");
+ },
+ }
+
+ self.counts_offsets_kernel
+ .encode(
+ root,
+ MoeCountsOffsetsFusedArguments {
+ topk_ids_buffer: &topk_ids_buf,
+ offsets_buffer: &offsets_buf,
+ sum_k_buffer: &sumk_buf,
+ partials_buffer: &partials_buf,
+ t: suffix_length,
+ e,
+ k,
+ },
+ )
+ .expect("MoE counts+offsets failed");
+
+ let num_blocks = ((suffix_length + 255) / 256).max(1);
+ let num_tiles = ((e + 512 - 1) / 512).max(1);
+
+ self.scatter_kernels
+ .encode_block_bases(
+ root,
+ super::MoeBlockBasesArguments {
+ partials_buffer: &partials_buf,
+ block_bases_buffer: &block_bases_buf,
+ block_alloc_buffer: &block_alloc_buf,
+ e,
+ num_blocks,
+ num_tiles,
+ },
+ )
+ .expect("MoE block bases failed");
+
+ self.scatter_kernels
+ .encode_scatter_with_map(
+ root,
+ MoeScatterWithMapArguments {
+ base: super::MoeScatterArguments {
+ topk_ids_buffer: &topk_ids_buf,
+ topk_probs_buffer: &topk_probs_buf,
+ offsets_buffer: &offsets_buf,
+ block_bases_buffer: &block_bases_buf,
+ block_alloc_buffer: &block_alloc_buf,
+ out_ids_buffer: &bucketed_ids_buf,
+ out_probs_buffer: &bucketed_probs_buf,
+ t: suffix_length,
+ e,
+ k,
+ num_blocks,
+ num_tiles,
+ },
+ tok2row_buffer: &tok2row_buf,
+ },
+ self.data_type,
+ )
+ .expect("MoE scatter failed");
+
+ self.gather_kernel
+ .encode(
+ root,
+ self.data_type,
+ MoeGatherArguments {
+ x_buffer: &main_buf,
+ bucketed_ids_buffer: &bucketed_ids_buf,
+ x_perm_buffer: &x_perm_buf,
+ sumk_buffer: &sumk_buf,
+ t: suffix_length,
+ k,
+ d_model: self.model_dim,
+ },
+ )
+ .expect("MoE gather failed");
+
+ let gating_code = Self::gating_code_from_activation(
+ &self.moe_config.expert_config.activation,
+ );
+
+ // Compute clipping values and alpha for expert kernels
+ let gate_clip_min = self.moe_config.expert_config.gate_clipping[0]
+ .unwrap_or(f32::NEG_INFINITY);
+ let gate_clip_max = self.moe_config.expert_config.gate_clipping[1]
+ .unwrap_or(f32::INFINITY);
+ let up_clip_min = self.moe_config.expert_config.up_clipping[0];
+ let up_clip_max = self.moe_config.expert_config.up_clipping[1];
+ let silu_alpha = self.moe_config.expert_config.activation.alpha();
+
+ if suffix_length == 1 {
+ let total_rows = suffix_length * k;
+ let num_tiles_k = ((self.hidden_dim + k_tile - 1) / k_tile) as u32;
+
+ self.experts_two_pass_decode_kernel
+ .encode(
+ root,
+ MoeExpertsTwoPassArguments {
+ x_perm_buffer: &x_perm_buf,
+ expert_offsets: &offsets_buf,
+ row_expert_map: &row_expert_map_buf,
+ hidden_buffer: &hidden_buf,
+ output_buffer: &y_partial_buf,
+ w13_all: &self.shared_weights.w13_buf,
+ w2_all: &self.shared_weights.w2_buf,
+ up_biases: &self.shared_weights.up_biases_buf,
+ down_biases: &self.shared_weights.down_biases_buf,
+ tile_counts: &tile_counts_buf,
+ tile_offsets: &tile_offsets_buf,
+ tile_map: &tile_map_buf,
+ total_tiles: &total_tiles_buf,
+ dispatch_args: &dispatch_args_buf,
+ total_rows,
+ d_model: self.model_dim,
+ d_ff: self.hidden_dim,
+ e,
+ num_tiles_k,
+ gating_code,
+ gate_clip_min,
+ gate_clip_max,
+ up_clip_min,
+ up_clip_max,
+ silu_alpha,
+ data_type: self.data_type,
+ },
+ )
+ .expect("MoE experts two-pass failed");
+ } else {
+ let total_rows = suffix_length * k;
+ let num_tiles_k = ((self.hidden_dim + k_tile - 1) / k_tile) as u32;
+
+ self.experts_two_pass_prefill_kernel
+ .encode(
+ root,
+ MoeExpertsTwoPassArguments {
+ x_perm_buffer: &x_perm_buf,
+ expert_offsets: &offsets_buf,
+ row_expert_map: &row_expert_map_buf,
+ hidden_buffer: &hidden_buf,
+ output_buffer: &y_partial_buf,
+ w13_all: &self.shared_weights.w13_buf,
+ w2_all: &self.shared_weights.w2_buf,
+ up_biases: &self.shared_weights.up_biases_buf,
+ down_biases: &self.shared_weights.down_biases_buf,
+ tile_counts: &tile_counts_buf,
+ tile_offsets: &tile_offsets_buf,
+ tile_map: &tile_map_buf,
+ total_tiles: &total_tiles_buf,
+ dispatch_args: &dispatch_args_buf,
+ total_rows,
+ d_model: self.model_dim,
+ d_ff: self.hidden_dim,
+ e,
+ num_tiles_k,
+ gating_code,
+ gate_clip_min,
+ gate_clip_max,
+ up_clip_min,
+ up_clip_max,
+ silu_alpha,
+ data_type: self.data_type,
+ },
+ )
+ .expect("MoE experts two-pass prefill failed");
+ }
+
+ self.finalize_kernel
+ .encode(
+ root,
+ super::MoeFinalizeArguments {
+ tok2row_buffer: &tok2row_buf,
+ probs_buffer: &topk_probs_buf,
+ y_partial_buffer: &y_partial_buf,
+ y_out_buffer: &main_buf,
+ t: suffix_length,
+ d_model: self.model_dim,
+ k,
+ },
+ self.data_type,
+ )
+ .expect("MoE finalize failed");
+
+ if parameters.wait_until_completed {
+ command_buffer.commit_and_continue();
+ mtl_command_buffer.wait_until_completed();
+ }
+ }
+}
diff --git a/crates/uzu/src/backends/metal/kernel/moe/experts.rs b/crates/uzu/src/backends/metal/kernel/moe/experts.rs
new file mode 100644
index 000000000..3769c7eca
--- /dev/null
+++ b/crates/uzu/src/backends/metal/kernel/moe/experts.rs
@@ -0,0 +1,529 @@
+use std::mem::size_of;
+
+use metal::{
+ Buffer as MTLBuffer, CommandBufferRef,
+ ComputePipelineState as MTLComputePipelineState, FunctionConstantValues,
+ MTLDataType, MTLSize,
+};
+
+use super::{
+ MoePassARowMapArguments, MoePassATileBuildArguments,
+ MoePassATileCountsArguments, MoePassATileDispatchArguments,
+ MoePassATileKernel, MoePassATileScanArguments, MoeTileCountsArguments,
+ MoeTileDispatchArguments, MoeTileError, MoeTileMapBuildArguments,
+ MoeTileMapKernel, MoeTileScanArguments, dtype_index, dtype_suffix,
+};
+use crate::backends::metal::{KernelDataType, MTLContext, MTLError};
+
+#[derive(Debug, thiserror::Error)]
+pub enum MoeScatterError {
+ #[error("Metal error: {0}")]
+ MetalError(#[from] MTLError),
+}
+#[derive(Debug, thiserror::Error)]
+pub enum MoeExpertsError {
+ #[error("Metal error: {0}")]
+ MetalError(#[from] MTLError),
+ #[error("{0}")]
+ Generic(String),
+}
+
+impl From<MoeTileError> for MoeExpertsError {
+ fn from(err: MoeTileError) -> Self {
+ match err {
+ MoeTileError::MetalError(inner) => {
+ MoeExpertsError::MetalError(inner)
+ },
+ }
+ }
+}
+
+#[derive(Debug)]
+pub struct MoeExpertsArguments<'a> {
+ pub x_perm_buffer: &'a MTLBuffer, // [sum_k, d_model] - permuted input
+ pub expert_offsets: &'a MTLBuffer, // [E+1] - expert segment offsets
+ pub w13_all: &'a MTLBuffer, // [E, 2*d_ff, d_model] - transposed up projection weights
+ pub w2_all: &'a MTLBuffer, // [E, d_model, d_ff] - transposed down projection weights
+ pub y_partial: &'a MTLBuffer, // [sum_k, d_model] - output buffer
+ pub up_biases: &'a MTLBuffer, // [E, 2*d_ff] - up projection biases
+ pub down_biases: &'a MTLBuffer, // [E, d_model] - down projection biases
+ pub tile_counts: &'a MTLBuffer, // [E]
+ pub tile_row_offsets: &'a MTLBuffer, // [E+1]
+ pub tile_map: &'a MTLBuffer, // [max_tiles * 3]
+ pub total_tiles: &'a MTLBuffer, // [2]
+ pub dispatch_args: &'a MTLBuffer, // [3]
+ pub num_tiles_n: usize,
+ pub t: usize,
+ pub d_model: usize,
+ pub d_ff: usize,
+ pub e: usize,
+ pub k: usize,
+ pub gating_code: u32,
+ 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: KernelDataType,
+}
+
+pub struct MoeExpertsTwoPassDecodeKernel {
+ pass_a_tile: MoePassATileKernel,
+ pass_a_indirect: Vec<Vec<MTLComputePipelineState>>, // [gate][dtype]
+ fused_down: Vec<MTLComputePipelineState>, // [dtype]
+}
+
+pub struct MoeExpertsTwoPassPrefillKernel {
+ tile_map: MoeTileMapKernel,
+ pass_a_indirect: Vec<Vec<MTLComputePipelineState>>, // [gate][dtype]
+ pass_b_indirect: Vec<MTLComputePipelineState>, // [dtype]
+}
+
+#[derive(Debug)]
+pub struct MoeExpertsTwoPassArguments<'a> {
+ pub x_perm_buffer: &'a MTLBuffer,
+ pub expert_offsets: &'a MTLBuffer,
+ pub row_expert_map: &'a MTLBuffer,
+ pub hidden_buffer: &'a MTLBuffer,
+ pub output_buffer: &'a MTLBuffer,
+ pub w13_all: &'a MTLBuffer,
+ pub w2_all: &'a MTLBuffer,
+ pub up_biases: &'a MTLBuffer,
+ pub down_biases: &'a MTLBuffer,
+ pub tile_counts: &'a MTLBuffer,
+ pub tile_offsets: &'a MTLBuffer,
+ pub tile_map: &'a MTLBuffer,
+ pub total_tiles: &'a MTLBuffer,
+ pub dispatch_args: &'a MTLBuffer,
+ pub total_rows: usize,
+ pub d_model: usize,
+ pub d_ff: usize,
+ pub e: usize,
+ pub num_tiles_k: u32,
+ pub gating_code: u32,
+ 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: KernelDataType,
+}
+
+impl MoeExpertsTwoPassDecodeKernel {
+ pub fn new(ctx: &MTLContext) -> Result<Self, MoeExpertsError> {
+ let dtypes = [
+ KernelDataType::Float16,
+ KernelDataType::BFloat16,
+ KernelDataType::Float32,
+ ];
+ let mut pass_a_indirect = vec![Vec::with_capacity(dtypes.len()); 4];
+ for gate in 0u32..4u32 {
+ for dtype in &dtypes {
+ let dtype_suffix = dtype_suffix(*dtype);
+ let fcv = FunctionConstantValues::new();
+ fcv.set_constant_value_at_index(
+ &gate as *const u32 as *const std::ffi::c_void,
+ MTLDataType::UInt,
+ 30,
+ );
+ let tile_h: u32 = 512;
+ fcv.set_constant_value_at_index(
+ &tile_h as *const u32 as *const std::ffi::c_void,
+ MTLDataType::UInt,
+ 32,
+ );
+ let kernel_name = format!(
+ "moe_experts_decode_pass_a_indirect_{}",
+ dtype_suffix
+ );
+ pass_a_indirect[gate as usize].push(
+ ctx.compute_pipeline_state(&kernel_name, Some(&fcv))?,
+ );
+ }
+ }
+ let mut fused_down = Vec::with_capacity(dtypes.len());
+ for dtype in &dtypes {
+ let dtype_suffix = dtype_suffix(*dtype);
+ let kernel_name =
+ format!("moe_experts_decode_down_fused_2d_{}", dtype_suffix);
+ fused_down.push(ctx.compute_pipeline_state(&kernel_name, None)?);
+ }
+ Ok(Self {
+ pass_a_tile: MoePassATileKernel::new(ctx)?,
+ pass_a_indirect,
+ fused_down,
+ })
+ }
+
+ pub fn encode(
+ &self,
+ command_buffer: &CommandBufferRef,
+ args: MoeExpertsTwoPassArguments,
+ ) -> Result<(), MoeExpertsError> {
+ if args.total_rows == 0 {
+ return Ok(());
+ }
+ let gate_idx = (args.gating_code.min(3)) as usize;
+ let dtype_idx = dtype_index(args.data_type);
+ const BLOCK_M: u32 = 4;
+ let h_blocks = (args.d_ff as u32 + BLOCK_M - 1) / BLOCK_M;
+ self.pass_a_tile.encode_counts(
+ command_buffer,
+ &MoePassATileCountsArguments {
+ expert_offsets: args.expert_offsets,
+ tile_counts: args.tile_counts,
+ e: args.e,
+ h_blocks,
+ },
+ )?;
+ self.pass_a_tile.encode_scan(
+ command_buffer,
+ &MoePassATileScanArguments {
+ tile_counts: args.tile_counts,
+ tile_offsets: args.tile_offsets,
+ total_tiles: args.total_tiles,
+ e: args.e,
+ },
+ )?;
+ self.pass_a_tile.encode_row_map(
+ command_buffer,
+ &MoePassARowMapArguments {
+ expert_offsets: args.expert_offsets,
+ row_expert_map: args.row_expert_map,
+ total_rows: args.total_rows,
+ e: args.e,
+ },
+ )?;
+ self.pass_a_tile.encode_build_map(
+ command_buffer,
+ &MoePassATileBuildArguments {
+ expert_offsets: args.expert_offsets,
+ tile_offsets: args.tile_offsets,
+ row_expert_map: args.row_expert_map,
+ tile_map: args.tile_map,
+ total_rows: args.total_rows,
+ h_blocks,
+ },
+ )?;
+ self.pass_a_tile.encode_dispatch_args(
+ command_buffer,
+ &MoePassATileDispatchArguments {
+ total_tiles: args.total_tiles,
+ dispatch_args: args.dispatch_args,
+ num_tiles_y: 1,
+ },
+ )?;
+ let d_model_u32 = args.d_model as u32;
+ let d_ff_u32 = args.d_ff as u32;
+ let e_u32 = args.e as u32;
+ let pass_a_pipeline = &self.pass_a_indirect[gate_idx][dtype_idx];
+ let encoder_a = command_buffer.new_compute_command_encoder();
+ encoder_a.set_compute_pipeline_state(pass_a_pipeline);
+ encoder_a.set_buffer(0, Some(args.x_perm_buffer), 0);
+ encoder_a.set_buffer(1, Some(args.expert_offsets), 0);
+ encoder_a.set_buffer(2, Some(args.w13_all), 0);
+ encoder_a.set_buffer(3, Some(args.hidden_buffer), 0);
+ encoder_a.set_buffer(4, Some(args.up_biases), 0);
+ encoder_a.set_bytes(
+ 5,
+ size_of::<u32>() as u64,
+ &d_model_u32 as *const u32 as *const _,
+ );
+ encoder_a.set_bytes(
+ 6,
+ size_of::<u32>() as u64,
+ &d_ff_u32 as *const u32 as *const _,
+ );
+ encoder_a.set_bytes(
+ 7,
+ size_of::<u32>() as u64,
+ &e_u32 as *const u32 as *const _,
+ );
+ encoder_a.set_bytes(
+ 8,
+ size_of::<f32>() as u64,
+ &args.gate_clip_min as *const f32 as *const _,
+ );
+ encoder_a.set_bytes(
+ 9,
+ size_of::<f32>() as u64,
+ &args.gate_clip_max as *const f32 as *const _,
+ );
+ encoder_a.set_bytes(
+ 10,
+ size_of::<f32>() as u64,
+ &args.up_clip_min as *const f32 as *const _,
+ );
+ encoder_a.set_bytes(
+ 11,
+ size_of::<f32>() as u64,
+ &args.up_clip_max as *const f32 as *const _,
+ );
+ encoder_a.set_bytes(
+ 12,
+ size_of::<f32>() as u64,
+ &args.silu_alpha as *const f32 as *const _,
+ );
+ encoder_a.set_buffer(13, Some(args.tile_map), 0);
+ encoder_a.dispatch_thread_groups_indirect(
+ args.dispatch_args,
+ 0,
+ MTLSize::new(128, 1, 1),
+ );
+ encoder_a.end_encoding();
+ let total_rows_u32 = args.total_rows as u32;
+ let pass_b_pipeline = &self.fused_down[dtype_idx];
+ let encoder_b = command_buffer.new_compute_command_encoder();
+ encoder_b.set_compute_pipeline_state(pass_b_pipeline);
+ encoder_b.set_buffer(0, Some(args.hidden_buffer), 0);
+ encoder_b.set_buffer(1, Some(args.row_expert_map), 0);
+ encoder_b.set_buffer(2, Some(args.w2_all), 0);
+ encoder_b.set_buffer(3, Some(args.down_biases), 0);
+ encoder_b.set_buffer(4, Some(args.output_buffer), 0);
+ encoder_b.set_bytes(
+ 5,
+ size_of::<u32>() as u64,
+ &total_rows_u32 as *const u32 as *const _,
+ );
+ encoder_b.set_bytes(
+ 6,
+ size_of::<u32>() as u64,
+ &d_model_u32 as *const u32 as *const _,
+ );
+ encoder_b.set_bytes(
+ 7,
+ size_of::<u32>() as u64,
+ &d_ff_u32 as *const u32 as *const _,
+ );
+ encoder_b.set_bytes(
+ 8,
+ size_of::<u32>() as u64,
+ &e_u32 as *const u32 as *const _,
+ );
+ const SIMDGROUPS_PER_TG: u32 = 8;
+ const THREADS_PER_TG: u32 = 256;
+ let col_blocks =
+ (args.d_model as u32 + SIMDGROUPS_PER_TG - 1) / SIMDGROUPS_PER_TG;
+ encoder_b.dispatch_thread_groups(
+ MTLSize::new(col_blocks as u64, args.total_rows as u64, 1),
+ MTLSize::new(THREADS_PER_TG as u64, 1, 1),
+ );
+ encoder_b.end_encoding();
+ Ok(())
+ }
+}
+
+impl MoeExpertsTwoPassPrefillKernel {
+ pub fn new(ctx: &MTLContext) -> Result<Self, MoeExpertsError> {
+ let dtypes = [
+ KernelDataType::Float16,
+ KernelDataType::BFloat16,
+ KernelDataType::Float32,
+ ];
+ let mut pass_a_indirect = vec![Vec::with_capacity(dtypes.len()); 4];
+ for gate in 0u32..4u32 {
+ for dtype in &dtypes {
+ let dtype_suffix = dtype_suffix(*dtype);
+ let fcv = FunctionConstantValues::new();
+ fcv.set_constant_value_at_index(
+ &gate as *const u32 as *const std::ffi::c_void,
+ MTLDataType::UInt,
+ 30,
+ );
+ let kernel_name = format!(
+ "moe_two_pass_prefill_pass_a_indirect_{}",
+ dtype_suffix
+ );
+ pass_a_indirect[gate as usize].push(
+ ctx.compute_pipeline_state(&kernel_name, Some(&fcv))?,
+ );
+ }
+ }
+ let mut pass_b_indirect = Vec::with_capacity(dtypes.len());
+ for dtype in &dtypes {
+ let dtype_suffix = dtype_suffix(*dtype);
+ let kernel_name = format!(
+ "moe_two_pass_prefill_pass_b_indirect_{}",
+ dtype_suffix
+ );
+ pass_b_indirect
+ .push(ctx.compute_pipeline_state(&kernel_name, None)?);
+ }
+ Ok(Self {
+ tile_map: MoeTileMapKernel::new(ctx)?,
+ pass_a_indirect,
+ pass_b_indirect,
+ })
+ }
+
+ pub fn encode(
+ &self,
+ command_buffer: &CommandBufferRef,
+ args: MoeExpertsTwoPassArguments,
+ ) -> Result<(), MoeExpertsError> {
+ if args.total_rows == 0 {
+ return Ok(());
+ }
+ let gate_idx = (args.gating_code.min(3)) as usize;
+ let dtype_idx = dtype_index(args.data_type);
+ let dtype_size = match args.data_type {
+ KernelDataType::BFloat16 | KernelDataType::Float16 => 2,
+ KernelDataType::Float32 => 4,
+ };
+ let hidden_bytes = (args.total_rows * args.d_ff * dtype_size) as u64;
+ let blit_encoder = command_buffer.new_blit_command_encoder();
+ blit_encoder.fill_buffer(
+ args.hidden_buffer,
+ metal::NSRange::new(0, hidden_bytes),
+ 0,
+ );
+ blit_encoder.end_encoding();
+ self.tile_map.encode_counts(
+ command_buffer,
+ &MoeTileCountsArguments {
+ offsets_buffer: args.expert_offsets,
+ tile_counts_buffer: args.tile_counts,
+ e: args.e,
+ },
+ )?;
+ self.tile_map.encode_scan(
+ command_buffer,
+ &MoeTileScanArguments {
+ tile_counts_buffer: args.tile_counts,
+ tile_offsets_buffer: args.tile_offsets,
+ total_tiles_buffer: args.total_tiles,
+ e: args.e,
+ },
+ )?;
+ self.tile_map.encode_build_map(
+ command_buffer,
+ &MoeTileMapBuildArguments {
+ expert_offsets: args.expert_offsets,
+ tile_offsets: args.tile_offsets,
+ tile_counts: args.tile_counts,
+ tile_map: args.tile_map,
+ e: args.e,
+ },
+ )?;
+ let d_model_u32 = args.d_model as u32;
+ let d_ff_u32 = args.d_ff as u32;
+ let e_u32 = args.e as u32;
+ const COL_TILE_FF: u32 = 32; // Must match PASSA_BN in Metal 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
+ };
+ self.tile_map.encode_dispatch_args(
+ command_buffer,
+ &MoeTileDispatchArguments {
+ total_tiles: args.total_tiles,
+ dispatch_args: args.dispatch_args,
+ num_tiles_x: n_tiles_ff,
+ },
+ )?;
+ let pass_a_pipeline = &self.pass_a_indirect[gate_idx][dtype_idx];
+ let encoder_a = command_buffer.new_compute_command_encoder();
+ encoder_a.set_compute_pipeline_state(pass_a_pipeline);
+ encoder_a.set_buffer(0, Some(args.x_perm_buffer), 0);
+ encoder_a.set_buffer(1, Some(args.expert_offsets), 0);
+ encoder_a.set_buffer(2, Some(args.w13_all), 0);
+ encoder_a.set_buffer(3, Some(args.up_biases), 0);
+ encoder_a.set_buffer(4, Some(args.hidden_buffer), 0);
+ encoder_a.set_bytes(
+ 5,
+ size_of::<u32>() as u64,
+ &d_model_u32 as *const u32 as *const _,
+ );
+ encoder_a.set_bytes(
+ 6,
+ size_of::<u32>() as u64,
+ &d_ff_u32 as *const u32 as *const _,
+ );
+ encoder_a.set_bytes(
+ 7,
+ size_of::<u32>() as u64,
+ &e_u32 as *const u32 as *const _,
+ );
+ encoder_a.set_bytes(
+ 8,
+ size_of::<f32>() as u64,
+ &args.gate_clip_min as *const f32 as *const _,
+ );
+ encoder_a.set_bytes(
+ 9,
+ size_of::<f32>() as u64,
+ &args.gate_clip_max as *const f32 as *const _,
+ );
+ encoder_a.set_bytes(
+ 10,
+ size_of::<f32>() as u64,
+ &args.up_clip_min as *const f32 as *const _,
+ );
+ encoder_a.set_bytes(
+ 11,
+ size_of::<f32>() as u64,
+ &args.up_clip_max as *const f32 as *const _,
+ );
+ encoder_a.set_bytes(
+ 12,
+ size_of::<f32>() as u64,
+ &args.silu_alpha as *const f32 as *const _,
+ );
+ encoder_a.set_buffer(13, Some(args.tile_map), 0);
+ // Match kernel config: WM=2, WN=2 => 4 SIMDgroups => 128 threads
+ const SIMDGROUPS_PER_TG: u32 = 4;
+ const THREADS_PER_TG: u32 = SIMDGROUPS_PER_TG * 32;
+ encoder_a.dispatch_thread_groups_indirect(
+ args.dispatch_args,
+ 0,
+ MTLSize::new(THREADS_PER_TG as u64, 1, 1),
+ );
+ encoder_a.end_encoding();
+ self.tile_map.encode_dispatch_args(
+ command_buffer,
+ &MoeTileDispatchArguments {
+ total_tiles: args.total_tiles,
+ dispatch_args: args.dispatch_args,
+ num_tiles_x: n_tiles_model,
+ },
+ )?;
+ let pass_b_pipeline = &self.pass_b_indirect[dtype_idx];
+ let encoder_b = command_buffer.new_compute_command_encoder();
+ encoder_b.set_compute_pipeline_state(pass_b_pipeline);
+ encoder_b.set_buffer(0, Some(args.hidden_buffer), 0);
+ encoder_b.set_buffer(1, Some(args.expert_offsets), 0);
+ encoder_b.set_buffer(2, Some(args.w2_all), 0);
+ encoder_b.set_buffer(3, Some(args.down_biases), 0);
+ encoder_b.set_buffer(4, Some(args.output_buffer), 0);
+ encoder_b.set_bytes(
+ 5,
+ size_of::<u32>() as u64,
+ &d_model_u32 as *const u32 as *const _,
+ );
+ encoder_b.set_bytes(
+ 6,
+ size_of::<u32>() as u64,
+ &d_ff_u32 as *const u32 as *const _,
+ );
+ encoder_b.set_bytes(
+ 7,
+ size_of::<u32>() as u64,
+ &e_u32 as *const u32 as *const _,
+ );
+ encoder_b.set_buffer(8, Some(args.tile_map), 0);
+ encoder_b.dispatch_thread_groups_indirect(
+ args.dispatch_args,
+ 0,
+ MTLSize::new(THREADS_PER_TG as u64, 1, 1),
+ );
+ encoder_b.end_encoding();
+ Ok(())
+ }
+}
diff --git a/crates/uzu/src/backends/metal/kernel/moe/experts_two_pass_decode.metal b/crates/uzu/src/backends/metal/kernel/moe/experts_two_pass_decode.metal
new file mode 100644
index 000000000..edf485ceb
--- /dev/null
+++ b/crates/uzu/src/backends/metal/kernel/moe/experts_two_pass_decode.metal
@@ -0,0 +1,626 @@
+#include <metal_stdlib>
+#include <metal_simdgroup>
+using namespace metal;
+
+constant uint GATING_SEL [[function_constant(30)]]; // 0=GELU,1=SiLU,2=SwiGLU,3=GEGLU
+constant uint TILE_H [[function_constant(32)]]; // tile size for hidden dimension in Pass A
+
+static inline float gelu_approx(float x) {
+ const float k0 = 0.7978845608f;
+ const float k1 = 0.044715f;
+ if (x > 10.0f) return x;
+ if (x < -10.0f) return 0.0f;
+ return 0.5f * x * (1.0f + tanh(clamp(k0 * (x + k1 * x * x * x), -10.0f, 10.0f)));
+}
+
+static inline float silu(float x, float alpha) {
+ return x / (1.0f + exp(-alpha * x));
+}
+
+#define MTL_CONST static constant constexpr const
+#define MTL_PRAGMA_UNROLL _Pragma("clang loop unroll(full)")
+
+// Tiling configuration (tunable)
+MTL_CONST uint BM = 1; // Simdgroups in M dimension within threadgroup
+MTL_CONST uint BN = 4; // Simdgroups in N dimension within threadgroup
+MTL_CONST uint SM = 1; // Thread rows per simdgroup
+MTL_CONST uint SN = 32; // Thread cols per simdgroup (full warp width)
+MTL_CONST uint TM = 4; // Output elements per thread in M
+MTL_CONST uint TN = 4; // Input elements per thread in N (per iteration)
+
+MTL_CONST uint THREADS_M = BM * SM;
+MTL_CONST uint THREADS_N = BN * SN;
+MTL_CONST uint BLOCK_M = THREADS_M * TM;
+MTL_CONST uint BLOCK_N = THREADS_N * TN;
+
+static_assert(SM * SN == 32, "simdgroup must have 32 threads");
+static_assert(SN == 4 || SN == 8 || SN == 16 || SN == 32, "SN must be 4, 8, 16, or 32");
+
+// === Pass A: Optimized GEMV with hierarchical tiling ===
+// Computes: hidden[row, h] = activation(x[row, d] @ W13[d, 2*h])
+// AccumT is used for internal accumulations, output still stored as T
+template<typename T, typename AccumT>
+void moe_experts_decode_pass_a_impl(
+ device const T* X_perm, // [total_rows, d_model]
+ device const uint* expert_offsets, // [E + 1]
+ device const T* W13_all, // weights in layout [E, 2*d_ff, d_model]
+ device const T* up_biases, // [E, 2*d_ff]
+ device float* hidden_out, // [total_rows, d_ff] - f32 for activation precision
+ uint d_model,
+ uint d_ff,
+ uint E,
+ float gate_clip_min,
+ float gate_clip_max,
+ float up_clip_min,
+ float up_clip_max,
+ float silu_alpha,
+ uint expert_idx,
+ uint row_in_expert,
+ uint h_block_idx,
+ uint simd_gid,
+ uint simd_lid,
+ threadgroup float* tgp_memory
+) {
+ // Thread position within simdgroup
+ const uint thrM = SN != 32 ? simd_lid / SN : 0;
+ const uint thrN = SN != 32 ? simd_lid % SN : uint(simd_lid);
+
+ // Simdgroup position within threadgroup
+ const uint sgN = BN != 1 ? (simd_gid % BN) : 0;
+ const uint simdM = BN != 1 ? SM * (simd_gid / BN) : uint(SM * simd_gid);
+ const uint simdN = BN != 1 ? SN * (simd_gid % BN) : 0;
+
+ // Thread's work block
+ int bm = (simdM + thrM) * TM;
+ int bn = (simdN + thrN) * TN;
+
+ // Output row position
+ const uint seg_start = expert_offsets[expert_idx];
+ const uint seg_end = expert_offsets[expert_idx + 1];
+ uint global_row = seg_start + row_in_expert;
+
+ if (global_row >= seg_end) return;
+
+ // Calculate output h index
+ int h_row = h_block_idx * BLOCK_M + bm;
+
+ // Adjust tail block to ensure in-bounds reads
+ if (h_row + TM > d_ff) {
+ h_row = d_ff > TM ? int(d_ff - TM) : 0;
+ bm = h_row - int(h_block_idx * BLOCK_M);
+ }
+
+ if (h_row >= int(d_ff)) return;
+
+ // Accumulation arrays for up and gate projections
+ thread AccumT result_up[TM] = {0};
+ thread AccumT result_gate[TM] = {0};
+ thread T weights_up[TN];
+ thread T weights_gate[TN];
+ thread AccumT x_vals[TN];
+
+ // Expert weight base addresses
+ const ulong w13_base = (ulong)expert_idx * (ulong)d_model * (ulong)(2 * d_ff);
+ const ulong bias_base = (ulong)expert_idx * (ulong)(2 * d_ff);
+ const ulong x_row_base = (ulong)global_row * (ulong)d_model;
+
+ // Main accumulation loop over d_model in blocks of BLOCK_N
+ const uint n_iter = d_model / BLOCK_N;
+ const uint leftover = d_model - (n_iter * BLOCK_N);
+
+ for (uint i = 0; i < n_iter; ++i) {
+ // Load x values for this block
+ MTL_PRAGMA_UNROLL
+ for (uint tn = 0; tn < TN; tn++) {
+ uint d_idx = bn + tn;
+ x_vals[tn] = AccumT(X_perm[x_row_base + d_idx]);
+ }
+
+ // Accumulate for each output row
+ MTL_PRAGMA_UNROLL
+ for (uint tm = 0; tm < TM; tm++) {
+ uint h_idx = h_row + tm;
+
+ // Load weights for up projection
+ MTL_PRAGMA_UNROLL
+ for (uint tn = 0; tn < TN; tn++) {
+ uint d_idx = bn + tn;
+ ulong w_idx = w13_base + (ulong)h_idx * (ulong)d_model + (ulong)d_idx;
+ weights_up[tn] = W13_all[w_idx];
+ }
+
+ // Accumulate up projection
+ MTL_PRAGMA_UNROLL
+ for (uint tn = 0; tn < TN; tn++) {
+ result_up[tm] += x_vals[tn] * AccumT(weights_up[tn]);
+ }
+
+ // Load and accumulate gate projection if needed
+ if (GATING_SEL > 1) {
+ MTL_PRAGMA_UNROLL
+ for (uint tn = 0; tn < TN; tn++) {
+ uint d_idx = bn + tn;
+ ulong w_gate_idx = w13_base + (ulong)(d_ff + h_idx) * (ulong)d_model + (ulong)d_idx;
+ weights_gate[tn] = W13_all[w_gate_idx];
+ }
+
+ MTL_PRAGMA_UNROLL
+ for (uint tn = 0; tn < TN; tn++) {
+ result_gate[tm] += x_vals[tn] * AccumT(weights_gate[tn]);
+ }
+ }
+ }
+
+ bn += BLOCK_N;
+ }
+
+ // Handle leftover elements
+ if (leftover > 0) {
+ MTL_PRAGMA_UNROLL
+ for (uint tn = 0; tn < TN; tn++) {
+ uint d_idx = bn + tn;
+ x_vals[tn] = (d_idx < d_model) ? AccumT(X_perm[x_row_base + d_idx]) : AccumT(0.0);
+ }
+
+ MTL_PRAGMA_UNROLL
+ for (uint tm = 0; tm < TM; tm++) {
+ uint h_idx = h_row + tm;
+
+ MTL_PRAGMA_UNROLL
+ for (uint tn = 0; tn < TN; tn++) {
+ uint d_idx = bn + tn;
+ if (d_idx < d_model) {
+ ulong w_idx = w13_base + (ulong)h_idx * (ulong)d_model + (ulong)d_idx;
+ weights_up[tn] = W13_all[w_idx];
+ result_up[tm] += x_vals[tn] * AccumT(weights_up[tn]);
+
+ if (GATING_SEL > 1) {
+ ulong w_gate_idx = w13_base + (ulong)(d_ff + h_idx) * (ulong)d_model + (ulong)d_idx;
+ weights_gate[tn] = W13_all[w_gate_idx];
+ result_gate[tm] += x_vals[tn] * AccumT(weights_gate[tn]);
+ }
+ }
+ }
+ }
+ }
+
+ // Simdgroup reduction across thrN dimension
+ MTL_PRAGMA_UNROLL
+ for (uint tm = 0; tm < TM; tm++) {
+ result_up[tm] = simd_sum(result_up[tm]);
+ if (GATING_SEL > 1) {
+ result_gate[tm] = simd_sum(result_gate[tm]);
+ }
+ }
+
+ // Threadgroup reduction if BN > 1
+ if (BN > 1) {
+ threadgroup float* tgp_up = tgp_memory;
+ threadgroup float* tgp_gate = tgp_memory + BN * (BLOCK_M + TM);
+
+ if (thrN == 0) {
+ MTL_PRAGMA_UNROLL
+ for (uint tm = 0; tm < TM; tm++) {
+ tgp_up[sgN * (BLOCK_M + TM) + bm + tm] = float(result_up[tm]);
+ if (GATING_SEL > 1) {
+ tgp_gate[sgN * (BLOCK_M + TM) + bm + tm] = float(result_gate[tm]);
+ }
+ }
+
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ if (sgN == 0) {
+ MTL_PRAGMA_UNROLL
+ for (uint sgn = 1; sgn < BN; sgn++) {
+ MTL_PRAGMA_UNROLL
+ for (uint tm = 0; tm < TM; tm++) {
+ result_up[tm] += AccumT(tgp_up[sgn * (BLOCK_M + TM) + bm + tm]);
+ if (GATING_SEL > 1) {
+ result_gate[tm] += AccumT(tgp_gate[sgn * (BLOCK_M + TM) + bm + tm]);
+ }
+ }
+ }
+ }
+ }
+ }
+
+ // Apply activation and write output (only first thread in simdgroup width)
+ if (simdN == 0 && thrN == 0) {
+ MTL_PRAGMA_UNROLL
+ for (uint tm = 0; tm < TM; tm++) {
+ uint h_idx = h_row + tm;
+ if (h_idx < d_ff) {
+ // Add bias and clip
+ AccumT up_val = result_up[tm] + AccumT(up_biases[bias_base + h_idx]);
+ up_val = AccumT(clamp(float(up_val), up_clip_min, up_clip_max));
+
+ AccumT activated_val;
+ if (GATING_SEL <= 1) {
+ activated_val = (GATING_SEL == 0) ? AccumT(gelu_approx(float(up_val))) : AccumT(silu(float(up_val), silu_alpha));
+ } else {
+ AccumT gate_val = result_gate[tm] + AccumT(up_biases[bias_base + d_ff + h_idx]);
+ gate_val = AccumT(clamp(float(gate_val), gate_clip_min, gate_clip_max));
+ AccumT gate_activated = (GATING_SEL == 2) ? AccumT(silu(float(gate_val), silu_alpha)) : AccumT(gelu_approx(float(gate_val)));
+ activated_val = gate_activated * up_val;
+ }
+
+ ulong hidden_idx = (ulong)global_row * (ulong)d_ff + (ulong)h_idx;
+ hidden_out[hidden_idx] = float(activated_val);
+ }
+ }
+ }
+}
+
+#define MOE_PASS_A_KERNEL(DTYPE, SUFFIX) \
+kernel void moe_experts_decode_pass_a_##SUFFIX( \
+ device const DTYPE* X_perm [[buffer(0)]], \
+ device const uint* expert_offsets [[buffer(1)]], \
+ device const DTYPE* W13_all [[buffer(2)]], \
+ device float* hidden_out [[buffer(3)]], \
+ device const DTYPE* up_biases [[buffer(4)]], \
+ constant uint& d_model [[buffer(5)]], \
+ constant uint& d_ff [[buffer(6)]], \
+ constant uint& E [[buffer(7)]], \
+ constant float& gate_clip_min [[buffer(8)]], \
+ constant float& gate_clip_max [[buffer(9)]], \
+ constant float& up_clip_min [[buffer(10)]], \
+ constant float& up_clip_max [[buffer(11)]], \
+ constant float& silu_alpha [[buffer(12)]], \
+ uint3 tgpig [[threadgroup_position_in_grid]], \
+ uint simd_gid [[simdgroup_index_in_threadgroup]], \
+ uint simd_lid [[thread_index_in_simdgroup]]) \
+{ \
+ constexpr uint tgp_mem_size = (BN > 1) ? 2 * BN * (BLOCK_M + TM) : 1; \
+ threadgroup float tgp_memory[tgp_mem_size]; \
+ \
+ moe_experts_decode_pass_a_impl<DTYPE, float>( \
+ X_perm, expert_offsets, W13_all, up_biases, hidden_out, \
+ d_model, d_ff, E, gate_clip_min, gate_clip_max, \
+ up_clip_min, up_clip_max, silu_alpha, \
+ tgpig.y, tgpig.z, tgpig.x, \
+ simd_gid, simd_lid, \
+ (BN > 1) ? tgp_memory : nullptr); \
+}
+
+MOE_PASS_A_KERNEL(bfloat, bf16)
+MOE_PASS_A_KERNEL(half, f16)
+MOE_PASS_A_KERNEL(float, f32)
+
+// === Helper kernels for indirect dispatch of Pass A ===
+
+// Count tiles per expert: tiles = (num_rows > 0) ? num_rows * h_blocks : 0
+kernel void moe_pass_a_tile_counts(
+ device const uint* expert_offsets [[buffer(0)]], // [E+1]
+ device uint* tile_counts [[buffer(1)]], // [E]
+ constant uint& E [[buffer(2)]],
+ constant uint& h_blocks [[buffer(3)]],
+ uint tid [[thread_position_in_grid]]
+) {
+ if (tid >= E) return;
+ const uint start = expert_offsets[tid];
+ const uint end = expert_offsets[tid + 1];
+ const uint num_rows = end - start;
+ tile_counts[tid] = (num_rows > 0) ? (num_rows * h_blocks) : 0;
+}
+
+// Exclusive scan of tile_counts to get tile_offsets and total_tiles
+kernel void moe_pass_a_tile_scan(
+ device const uint* tile_counts [[buffer(0)]], // [E]
+ device uint* tile_offsets [[buffer(1)]], // [E+1]
+ device uint* total_tiles [[buffer(2)]], // [1]
+ constant uint& E [[buffer(3)]],
+ uint lid [[thread_index_in_threadgroup]],
+ threadgroup uint* scratch [[threadgroup(0)]]
+) {
+ // Simple single-threadgroup scan (works for E <= 1024)
+ const uint idx = lid;
+
+ // Load into threadgroup memory
+ if (idx < E) {
+ scratch[idx] = tile_counts[idx];
+ } else {
+ scratch[idx] = 0;
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ // Kogge-Stone scan
+ uint val = scratch[idx];
+ MTL_PRAGMA_UNROLL
+ for (uint offset = 1; offset < 1024; offset *= 2) {
+ uint temp = 0;
+ if (idx >= offset && idx < E) {
+ temp = scratch[idx - offset];
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ if (idx >= offset && idx < E) {
+ val += temp;
+ scratch[idx] = val;
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ }
+
+ // Write exclusive scan (shift right by 1)
+ if (idx == 0) {
+ tile_offsets[0] = 0;
+ }
+ if (idx < E) {
+ tile_offsets[idx + 1] = scratch[idx];
+ if (idx == E - 1) {
+ total_tiles[0] = scratch[idx];
+ }
+ }
+}
+
+// Build row→expert map: one thread per routed row
+kernel void moe_pass_a_build_row_map(
+ device const uint* expert_offsets [[buffer(0)]] , // [E+1]
+ device uint* row_expert_map [[buffer(1)]] , // [total_rows]
+ constant uint& total_rows [[buffer(2)]],
+ constant uint& E [[buffer(3)]],
+ uint tid [[thread_position_in_grid]]
+) {
+ if (tid >= total_rows) return;
+
+ uint left = 0u;
+ uint right = E;
+ const uint row = tid;
+
+ while (left + 1u < right) {
+ const uint mid = (left + right) >> 1;
+ if (row < expert_offsets[mid]) {
+ right = mid;
+ } else {
+ left = mid;
+ }
+ }
+
+ row_expert_map[row] = left;
+}
+
+// Build tile map entries from row→expert map
+kernel void moe_pass_a_build_tile_map(
+ device const uint* expert_offsets [[buffer(0)]], // [E+1]
+ device const uint* tile_offsets [[buffer(1)]], // [E+1]
+ device const uint* row_expert_map [[buffer(2)]], // [total_rows]
+ device uint* tile_map [[buffer(3)]], // [total_tiles * 3]
+ constant uint& total_rows [[buffer(4)]],
+ constant uint& h_blocks [[buffer(5)]],
+ uint tid [[thread_position_in_grid]]
+) {
+ const uint total_tiles = total_rows * h_blocks;
+ if (tid >= total_tiles) return;
+
+ const uint row_idx = tid / h_blocks;
+ const uint h_block = tid % h_blocks;
+
+ if (row_idx >= total_rows) return;
+
+ const uint expert_idx = row_expert_map[row_idx];
+ const uint row_start = expert_offsets[expert_idx];
+ const uint row_in_expert = row_idx - row_start;
+ const uint tile_base = tile_offsets[expert_idx] + row_in_expert * h_blocks + h_block;
+
+ tile_map[tile_base * 3 + 0] = h_block;
+ tile_map[tile_base * 3 + 1] = expert_idx;
+ tile_map[tile_base * 3 + 2] = row_in_expert;
+}
+
+// Write dispatch args for indirect dispatch (reusable from tiled version)
+kernel void moe_pass_a_write_dispatch_args(
+ device const uint* total_tiles [[buffer(0)]], // [1]
+ device uint* dispatch_args [[buffer(1)]], // [3] - MTLDispatchThreadgroupsIndirectArguments
+ constant uint& num_tiles_y [[buffer(2)]], // usually 1 for Pass A
+ uint tid [[thread_position_in_grid]]
+) {
+ if (tid > 0) return;
+ dispatch_args[0] = total_tiles[0]; // x dimension = total tiles
+ dispatch_args[1] = num_tiles_y; // y dimension
+ dispatch_args[2] = 1; // z dimension
+}
+
+// Modified Pass A that reads from tile map for indirect dispatch
+template<typename T>
+void moe_experts_decode_pass_a_indirect_impl(
+ device const T* X_perm,
+ device const uint* expert_offsets,
+ device const T* W13_all,
+ device const T* up_biases,
+ device float* hidden_out,
+ device const uint* tile_map, // [total_tiles * 3]
+ uint d_model,
+ uint d_ff,
+ uint E,
+ float gate_clip_min,
+ float gate_clip_max,
+ float up_clip_min,
+ float up_clip_max,
+ float silu_alpha,
+ uint tile_idx, // flat threadgroup index
+ uint simd_gid,
+ uint simd_lid,
+ threadgroup float* tgp_memory
+) {
+ // Read tile descriptor
+ const uint h_block_idx = tile_map[tile_idx * 3 + 0];
+ const uint expert_idx = tile_map[tile_idx * 3 + 1];
+ const uint row_in_expert = tile_map[tile_idx * 3 + 2];
+
+ // Call original implementation
+ moe_experts_decode_pass_a_impl<T, float>(
+ X_perm, expert_offsets, W13_all, up_biases, hidden_out,
+ d_model, d_ff, E,
+ gate_clip_min, gate_clip_max,
+ up_clip_min, up_clip_max, silu_alpha,
+ expert_idx, row_in_expert, h_block_idx,
+ simd_gid, simd_lid, tgp_memory
+ );
+}
+
+#define MOE_PASS_A_INDIRECT_KERNEL(DTYPE, SUFFIX) \
+kernel void moe_experts_decode_pass_a_indirect_##SUFFIX( \
+ device const DTYPE* X_perm [[buffer(0)]], \
+ device const uint* expert_offsets [[buffer(1)]], \
+ device const DTYPE* W13_all [[buffer(2)]], \
+ device float* hidden_out [[buffer(3)]], \
+ device const DTYPE* up_biases [[buffer(4)]], \
+ constant uint& d_model [[buffer(5)]], \
+ constant uint& d_ff [[buffer(6)]], \
+ constant uint& E [[buffer(7)]], \
+ constant float& gate_clip_min [[buffer(8)]], \
+ constant float& gate_clip_max [[buffer(9)]], \
+ constant float& up_clip_min [[buffer(10)]], \
+ constant float& up_clip_max [[buffer(11)]], \
+ constant float& silu_alpha [[buffer(12)]], \
+ device const uint* tile_map [[buffer(13)]], \
+ uint3 tgpig [[threadgroup_position_in_grid]], \
+ uint simd_gid [[simdgroup_index_in_threadgroup]], \
+ uint simd_lid [[thread_index_in_simdgroup]]) \
+{ \
+ constexpr uint tgp_mem_size = (BN > 1) ? 2 * BN * (BLOCK_M + TM) : 1; \
+ threadgroup float tgp_memory[tgp_mem_size]; \
+ \
+ moe_experts_decode_pass_a_indirect_impl<DTYPE>( \
+ X_perm, expert_offsets, W13_all, up_biases, hidden_out, tile_map, \
+ d_model, d_ff, E, gate_clip_min, gate_clip_max, \
+ up_clip_min, up_clip_max, silu_alpha, \
+ tgpig.x, simd_gid, simd_lid, \
+ (BN > 1) ? tgp_memory : nullptr); \
+}
+
+MOE_PASS_A_INDIRECT_KERNEL(bfloat, bf16)
+MOE_PASS_A_INDIRECT_KERNEL(half, f16)
+MOE_PASS_A_INDIRECT_KERNEL(float, f32)
+
+
+// === Pass B: Simdgroup cooperation along K for coalescing ===
+// W2 layout [E, d_model, d_ff] - 32 threads cooperate on one output, reading consecutive K elements
+
+template<typename T, typename AccumT>
+void moe_experts_decode_down_fused_2d_impl(
+ device const float* hidden, // [total_rows, d_ff] - f32 from Pass A
+ device const uint* row_expert_map, // [total_rows] - direct row->expert lookup
+ device const T* w2_all, // [E, d_model, d_ff] - layout
+ device const T* down_biases, // [E, d_model]
+ device T* y_out, // [total_rows, d_model]
+ uint total_rows,
+ uint d_model,
+ uint d_ff,
+ uint E,
+ uint2 tgpig,
+ uint simd_gid,
+ uint simd_lid
+) {
+ constexpr uint THREADS_PER_SIMD = 32;
+ constexpr uint SIMDGROUPS_PER_TG = 8;
+
+ const uint row_idx = tgpig.y;
+ if (row_idx >= total_rows) return;
+
+ // Each simdgroup computes one output column
+ const uint my_col = tgpig.x * SIMDGROUPS_PER_TG + simd_gid;
+ if (my_col >= d_model) return;
+
+ const uint expert_idx = row_expert_map[row_idx];
+
+ // Base addresses for this output column
+ const ulong hidden_base = (ulong)row_idx * (ulong)d_ff;
+ const ulong w2_col_base = (ulong)expert_idx * (ulong)d_model * (ulong)d_ff + (ulong)my_col * (ulong)d_ff;
+
+ // Dual accumulators for ILP: breaks FMA dependency chains
+ AccumT acc0 = AccumT(0.0);
+ AccumT acc1 = AccumT(0.0);
+ AccumT acc = AccumT(0.0);
+
+ // Main loop: stride-32 with vec8 loads for ILP
+ const uint k_iters = d_ff / THREADS_PER_SIMD;
+ const uint k_vec_iters = k_iters / 8;
+
+ MTL_PRAGMA_UNROLL
+ for (uint iter = 0; iter < k_vec_iters; ++iter) {
+ const uint k_base = iter * (8 * THREADS_PER_SIMD) + simd_lid;
+
+ // hidden: stride-32 per lane, already f32 from Pass A
+ const AccumT h0 = hidden[hidden_base + k_base + 0 * THREADS_PER_SIMD];
+ const AccumT h1 = hidden[hidden_base + k_base + 1 * THREADS_PER_SIMD];
+ const AccumT h2 = hidden[hidden_base + k_base + 2 * THREADS_PER_SIMD];
+ const AccumT h3 = hidden[hidden_base + k_base + 3 * THREADS_PER_SIMD];
+ const AccumT h4 = hidden[hidden_base + k_base + 4 * THREADS_PER_SIMD];
+ const AccumT h5 = hidden[hidden_base + k_base + 5 * THREADS_PER_SIMD];
+ const AccumT h6 = hidden[hidden_base + k_base + 6 * THREADS_PER_SIMD];
+ const AccumT h7 = hidden[hidden_base + k_base + 7 * THREADS_PER_SIMD];
+
+ // W2: lane-coalesced
+ const AccumT w0 = AccumT(w2_all[w2_col_base + k_base + 0 * THREADS_PER_SIMD]);
+ const AccumT w1 = AccumT(w2_all[w2_col_base + k_base + 1 * THREADS_PER_SIMD]);
+ const AccumT w2 = AccumT(w2_all[w2_col_base + k_base + 2 * THREADS_PER_SIMD]);
+ const AccumT w3 = AccumT(w2_all[w2_col_base + k_base + 3 * THREADS_PER_SIMD]);
+ const AccumT w4 = AccumT(w2_all[w2_col_base + k_base + 4 * THREADS_PER_SIMD]);
+ const AccumT w5 = AccumT(w2_all[w2_col_base + k_base + 5 * THREADS_PER_SIMD]);
+ const AccumT w6 = AccumT(w2_all[w2_col_base + k_base + 6 * THREADS_PER_SIMD]);
+ const AccumT w7 = AccumT(w2_all[w2_col_base + k_base + 7 * THREADS_PER_SIMD]);
+
+ // dual trees for ILP
+ acc0 = fma(h0, w0, acc0);
+ acc1 = fma(h1, w1, acc1);
+ acc0 = fma(h2, w2, acc0);
+ acc1 = fma(h3, w3, acc1);
+ acc0 = fma(h4, w4, acc0);
+ acc1 = fma(h5, w5, acc1);
+ acc0 = fma(h6, w6, acc0);
+ acc1 = fma(h7, w7, acc1);
+ }
+
+ // fold the vectorized contribution once
+ acc += (acc0 + acc1);
+
+ // Handle remaining full iterations
+ MTL_PRAGMA_UNROLL
+ for (uint iter = k_vec_iters * 8; iter < k_iters; ++iter) {
+ const uint k = iter * THREADS_PER_SIMD + simd_lid;
+ acc = fma(AccumT(hidden[hidden_base + k]), AccumT(w2_all[w2_col_base + k]), acc);
+ }
+
+ // Handle leftover elements (d_ff % 32)
+ const uint leftover_start = k_iters * THREADS_PER_SIMD;
+ if (leftover_start + simd_lid < d_ff) {
+ const uint k = leftover_start + simd_lid;
+ acc = fma(AccumT(hidden[hidden_base + k]), AccumT(w2_all[w2_col_base + k]), acc);
+ }
+
+ // Simdgroup reduction
+ AccumT result = simd_sum(acc);
+
+ // Lane 0 writes result
+ if (simd_lid == 0) {
+ const ulong bias_idx = (ulong)expert_idx * (ulong)d_model + (ulong)my_col;
+ result += AccumT(down_biases[bias_idx]);
+
+ const ulong out_idx = (ulong)row_idx * (ulong)d_model + (ulong)my_col;
+ y_out[out_idx] = T(result);
+ }
+}
+
+#define MOE_PASS_B_FUSED_2D_KERNEL(DTYPE, SUFFIX) \
+kernel void moe_experts_decode_down_fused_2d_##SUFFIX( \
+ device const float* hidden [[buffer(0)]], \
+ device const uint* row_expert_map [[buffer(1)]], \
+ device const DTYPE* w2_all [[buffer(2)]], \
+ device const DTYPE* down_biases [[buffer(3)]], \
+ device DTYPE* y_out [[buffer(4)]], \
+ constant uint& total_rows [[buffer(5)]], \
+ constant uint& d_model [[buffer(6)]], \
+ constant uint& d_ff [[buffer(7)]], \
+ constant uint& E [[buffer(8)]], \
+ uint2 tgpig [[threadgroup_position_in_grid]], \
+ uint simd_gid [[simdgroup_index_in_threadgroup]], \
+ uint simd_lid [[thread_index_in_simdgroup]]) \
+{ \
+ moe_experts_decode_down_fused_2d_impl<DTYPE, float>( \
+ hidden, row_expert_map, w2_all, down_biases, y_out, \
+ total_rows, d_model, d_ff, E, \
+ tgpig, simd_gid, simd_lid); \
+}
+
+MOE_PASS_B_FUSED_2D_KERNEL(bfloat, bf16)
+MOE_PASS_B_FUSED_2D_KERNEL(half, f16)
+MOE_PASS_B_FUSED_2D_KERNEL(float, f32)
diff --git a/crates/uzu/src/backends/metal/kernel/moe/experts_two_pass_prefill.metal b/crates/uzu/src/backends/metal/kernel/moe/experts_two_pass_prefill.metal
new file mode 100644
index 000000000..db64af685
--- /dev/null
+++ b/crates/uzu/src/backends/metal/kernel/moe/experts_two_pass_prefill.metal
@@ -0,0 +1,777 @@
+// UZU MoE Two-Pass Prefill
+// - Pass A: X @ W13 → hidden (f32) with gating
+// - Pass B: hidden @ W2 → output (T)
+//
+// X_perm : [total_rows, D]
+// W13_all : [E, 2*FF, D] // first FF = up, second FF = gate
+// up_biases : [E, 2*FF] // [up | gate]
+// hidden_out (f32): [total_rows, FF]
+// W2_all : [E, D, FF] // FF contiguous (col-major-ish use below)
+// down_biases : [E, D]
+// output (T) : [total_rows, D]
+//
+// Notes:
+// - 8x8 simdgroup MMA tiles; threadgroup staging is float.
+// - Vectorized float4 cooperative loads.
+// - Linearized thread id covers both 1-D and 2/3-D TGs safely.
+// - We guard tails; K/N can be non-multiples.
+
+#include <metal_stdlib>
+#include <metal_simdgroup>
+#include <metal_simdgroup_matrix>
+#include "../quant_matmul/mma.h"
+
+using namespace metal;
+
+// ------------------------ helpers ------------------------
+static inline uint ceil_div(uint a, uint b) { return (a + b - 1u) / b; }
+
+static inline uint linear_tid(uint3 tid, uint3 tpg) {
+ return tid.z * (tpg.x * tpg.y) + tid.y * tpg.x + tid.x;
+}
+
+static inline float gelu_approx(float x) {
+ const float k0 = 0.7978845608f; // sqrt(2/pi)
+ const float k1 = 0.044715f;
+ if (x > 10.0f) return x;
+ if (x < -10.0f) return 0.0f;
+ float x3 = x * x * x;
+ float t = clamp(k0 * (x + k1 * x3), -10.0f, 10.0f);
+ return 0.5f * x * (1.0f + tanh(t));
+}
+
+static inline float silu(float x, float alpha) {
+ // alpha=1 gives standard SiLU; keep alpha param for parity with your API
+ return x / (1.0f + exp(-alpha * x));
+}
+
+template<typename T>
+inline void store_vec4(device T* dst, ulong base, float4 vals) {
+ dst[base + 0] = T(vals.x);
+ dst[base + 1] = T(vals.y);
+ dst[base + 2] = T(vals.z);
+ dst[base + 3] = T(vals.w);
+}
+
+template<>
+inline void store_vec4<float>(device float* dst, ulong base, float4 vals) {
+ *reinterpret_cast<device float4*>(dst + base) = vals;
+}
+
+template<typename T>
+struct StageStorage {
+ using type = float;
+};
+
+template<>
+struct StageStorage<half> {
+ using type = half;
+};
+
+template<>
+struct StageStorage<bfloat> {
+ using type = bfloat;
+};
+
+// 0=GELU(up), 1=SiLU(up), 2=SwiGLU(gate)*up, 3=GEGLU(gate)*up
+constant uint GATING_SEL [[function_constant(30)]];
+
+// ------------------------ Pass A (X @ W13 → hidden) ------------------------
+// Tile config (tuned for A-series; matches your prior defaults)
+constant uint PASSA_BM = 16;
+constant uint PASSA_BN = 32;
+constant uint PASSA_BK = 64;
+constant uint PASSA_SG_BM = 8;
+constant uint PASSA_SG_BN = 16;
+
+template<typename T>
+inline void pass_a_impl(
+ device const T* X_perm, // [total_rows, D]
+ device const uint* expert_offsets, // [E+1]
+ device const T* W13_all, // [E, 2*FF, D]
+ device const T* up_biases, // [E, 2*FF] (up | gate)
+ device float* hidden_out, // [total_rows, FF]
+ uint d_model, uint d_ff, uint E,
+ float gate_clip_min, float gate_clip_max,
+ float up_clip_min, float up_clip_max,
+ float silu_alpha,
+ // work partition
+ uint tile_seg_start, uint expert_idx, uint tile_m, uint tile_n,
+ // per-thread info
+ uint sg_id, uint3 threads_per_tg, uint3 local_tid,
+ // TG storage
+ threadgroup typename StageStorage<T>::type* Xs, // [BM,BK]
+ threadgroup typename StageStorage<T>::type* Wk_up, // [BN,BK]
+ threadgroup typename StageStorage<T>::type* Wk_gate, // [BN,BK]
+ threadgroup float* bias_up, // [BN]
+ threadgroup float* bias_gate // [BN]
+) {
+ using StageT = typename StageStorage<T>::type;
+ using StageVec4 = metal::vec<StageT, 4>;
+
+ const uint Bm = PASSA_BM, Bn = PASSA_BN, Bk = PASSA_BK;
+ const uint SgBm = PASSA_SG_BM, SgBn = PASSA_SG_BN;
+
+ if (expert_idx >= E) return;
+
+ const uint seg_start = expert_offsets[expert_idx];
+ const uint seg_end = expert_offsets[expert_idx + 1];
+ const uint seg_len = (seg_end > seg_start) ? (seg_end - seg_start) : 0u;
+ if (seg_len == 0) return;
+
+ const uint row_tg_off = tile_m * Bm;
+ const uint col_tg_off = tile_n * Bn;
+ if (row_tg_off >= seg_len || col_tg_off >= d_ff) return;
+
+ const uint m_rows = min(Bm, seg_len - row_tg_off);
+ const uint n_cols = min(Bn, d_ff - col_tg_off);
+
+ const ulong x_base = ((ulong)tile_seg_start + (ulong)row_tg_off) * (ulong)d_model;
+ const ulong w13_expert_base = (ulong)expert_idx * (ulong)(2 * d_ff) * (ulong)d_model;
+ const ulong bias_base = (ulong)expert_idx * (ulong)(2 * d_ff);
+
+ // simdgroup tile mapping
+ const uint sg_col_count = Bn / SgBn;
+ const uint row_sg = sg_id / sg_col_count;
+ const uint col_sg = sg_id % sg_col_count;
+ const uint row_sg_off = row_sg * SgBm;
+ const uint col_sg_off = col_sg * SgBn;
+
+ // Guard against misconfigured TG sizes
+ constexpr uint SG_TILE = 8; // simdgroup fragment dimension (8x8)
+ constexpr uint SG_EXPECTED = (PASSA_BM / SG_TILE) * (PASSA_BN / SG_TILE);
+ if (sg_id >= SG_EXPECTED) return;
+
+ // partial accumulators (8x8 tiles per simdgroup)
+ constexpr uint TEMP = (PASSA_SG_BM / SG_TILE) * (PASSA_SG_BN / SG_TILE);
+ metal::simdgroup_float8x8 OutUp[TEMP];
+ metal::simdgroup_float8x8 OutGate[TEMP];
+ for (uint i = 0; i < TEMP; ++i) {
+ OutUp[i] = metal::make_filled_simdgroup_matrix<float, 8, 8>(0.0f);
+ if (GATING_SEL > 1u) {
+ OutGate[i] = metal::make_filled_simdgroup_matrix<float, 8, 8>(0.0f);
+ }
+ }
+
+ const uint threads_total = threads_per_tg.x * threads_per_tg.y * threads_per_tg.z;
+ const uint lin = linear_tid(local_tid, threads_per_tg);
+
+ // K-loop (tile along D)
+ for (uint k_off = 0; k_off < d_model; k_off += Bk) {
+ const uint valid_k = min(Bk, d_model - k_off);
+
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ // ---- Stage LHS: Xs [Bm,Bk] as float, vectorized 4 ----
+ {
+ constexpr uint row_stride = PASSA_BK;
+ constexpr uint vec_cols = PASSA_BK / 4;
+ const uint total_vecs = PASSA_BM * vec_cols;
+ const uint iters = ceil_div(total_vecs, threads_total);
+
+UZU_PRAGMA_UNROLL
+ for (uint t = 0; t < iters; ++t) {
+ const uint i = t * threads_total + lin;
+ if (i < total_vecs) {
+ const uint r = i / vec_cols;
+ const uint c4 = i % vec_cols;
+
+ threadgroup StageVec4* dst4 =
+ reinterpret_cast<threadgroup StageVec4*>(Xs + r * row_stride + (c4 << 2));
+
+ StageVec4 packed = StageVec4(StageT(0.0f));
+ if (r < m_rows) {
+ const ulong base = x_base + (ulong)r * (ulong)d_model + (ulong)(k_off + (c4 << 2));
+ const uint base_vec = (c4 << 2);
+ float v0 = 0.0f, v1 = 0.0f, v2 = 0.0f, v3 = 0.0f;
+ if (base_vec + 0 < valid_k) v0 = float(X_perm[base + 0]);
+ if (base_vec + 1 < valid_k) v1 = float(X_perm[base + 1]);
+ if (base_vec + 2 < valid_k) v2 = float(X_perm[base + 2]);
+ if (base_vec + 3 < valid_k) v3 = float(X_perm[base + 3]);
+ packed = StageVec4(StageT(v0), StageT(v1), StageT(v2), StageT(v3));
+ }
+ *dst4 = packed;
+ }
+ }
+ }
+
+ // ---- Stage RHS: W_up [Bn,Bk], W_gate [Bn,Bk], vectorized 4 ----
+ {
+ constexpr uint row_stride = PASSA_BK;
+ constexpr uint vec_cols = PASSA_BK / 4;
+ const uint total_vecs = PASSA_BN * vec_cols;
+ const uint iters = ceil_div(total_vecs, threads_total);
+
+UZU_PRAGMA_UNROLL
+ for (uint t = 0; t < iters; ++t) {
+ const uint i = t * threads_total + lin;
+ if (i < total_vecs) {
+ const uint n = i / vec_cols; // column within the BN tile
+ const uint c4 = i % vec_cols;
+
+ threadgroup StageVec4* up4 =
+ reinterpret_cast<threadgroup StageVec4*>(Wk_up + n * row_stride + (c4 << 2));
+ StageVec4 upv = StageVec4(StageT(0.0f));
+
+ threadgroup StageVec4* gt4 =
+ reinterpret_cast<threadgroup StageVec4*>(Wk_gate + n * row_stride + (c4 << 2));
+ StageVec4 gtv = StageVec4(StageT(0.0f));
+
+ if (n < n_cols) {
+ const uint gcol = col_tg_off + n;
+ const ulong up_base = w13_expert_base + (ulong)gcol * (ulong)d_model + (ulong)(k_off + (c4 << 2));
+ const ulong gate_base = w13_expert_base + (ulong)(d_ff + gcol) * (ulong)d_model + (ulong)(k_off + (c4 << 2));
+ const uint base_vec = (c4 << 2);
+ float up0 = 0.0f, up1 = 0.0f, up2 = 0.0f, up3 = 0.0f;
+ float gt0 = 0.0f, gt1 = 0.0f, gt2 = 0.0f, gt3 = 0.0f;
+ if (base_vec + 0 < valid_k) { up0 = float(W13_all[up_base + 0]); gt0 = float(W13_all[gate_base + 0]); }
+ if (base_vec + 1 < valid_k) { up1 = float(W13_all[up_base + 1]); gt1 = float(W13_all[gate_base + 1]); }
+ if (base_vec + 2 < valid_k) { up2 = float(W13_all[up_base + 2]); gt2 = float(W13_all[gate_base + 2]); }
+ if (base_vec + 3 < valid_k) { up3 = float(W13_all[up_base + 3]); gt3 = float(W13_all[gate_base + 3]); }
+ upv = StageVec4(StageT(up0), StageT(up1), StageT(up2), StageT(up3));
+ gtv = StageVec4(StageT(gt0), StageT(gt1), StageT(gt2), StageT(gt3));
+ }
+
+ *up4 = upv;
+ if (GATING_SEL > 1u) *gt4 = gtv;
+ }
+ }
+ }
+
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ // ---- MMA across the BK tile (in simdgroup-sized chunks) ----
+UZU_PRAGMA_UNROLL
+ for (uint kk = 0; kk < PASSA_BK; kk += SG_TILE) {
+UZU_PRAGMA_UNROLL
+ for (uint m_sub = 0; m_sub < PASSA_SG_BM; m_sub += SG_TILE) {
+ const uint r_idx = m_sub / SG_TILE;
+ metal::simdgroup_matrix<StageT, 8, 8> lhs_frag;
+ simdgroup_load(lhs_frag, Xs, PASSA_BK, ulong2(kk, row_sg_off + m_sub));
+
+UZU_PRAGMA_UNROLL
+ for (uint n_sub = 0; n_sub < PASSA_SG_BN; n_sub += SG_TILE) {
+ const uint c_idx = n_sub / SG_TILE;
+ const uint tile = r_idx * (PASSA_SG_BN / SG_TILE) + c_idx;
+ metal::simdgroup_matrix<StageT, 8, 8> rhs_up;
+ simdgroup_load(rhs_up, Wk_up, PASSA_BK, ulong2(kk, col_sg_off + n_sub), true);
+ simdgroup_multiply_accumulate(OutUp[tile], lhs_frag, rhs_up, OutUp[tile]);
+
+ if (GATING_SEL > 1u) {
+ metal::simdgroup_matrix<StageT, 8, 8> rhs_gate;
+ simdgroup_load(rhs_gate, Wk_gate, PASSA_BK, ulong2(kk, col_sg_off + n_sub), true);
+ simdgroup_multiply_accumulate(OutGate[tile], lhs_frag, rhs_gate, OutGate[tile]);
+ }
+ }
+ }
+ }
+ } // K loop
+
+ // ---- Bias tile [Bn] ----
+ // Note: bias layout is [up | gate] in contiguous FF chunks.
+ for (uint c_local = lin; c_local < Bn; c_local += threads_total) {
+ const uint c_global = col_tg_off + c_local;
+ bias_up[c_local] = (c_global < d_ff) ? float(up_biases[bias_base + c_global]) : 0.0f;
+ if (GATING_SEL > 1u) {
+ bias_gate[c_local] = (c_global < d_ff) ? float(up_biases[bias_base + d_ff + c_global]) : 0.0f;
+ }
+ }
+
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ // ---- Epilogue: activation/gating → hidden_out (f32) ----
+ const uint sg_lane_start = sg_id * 32;
+ const uint sg_lane_end = sg_lane_start + 32;
+ if (lin < sg_lane_start || lin >= sg_lane_end) return;
+ const uint sg_lin = lin - sg_lane_start;
+ // Lane→(row,col) mapping for 8x8 simdgroup fragments, matches the fragment layout used above.
+ const uint lane_qid = sg_lin >> 2;
+ const uint lane_row = (lane_qid & 4u) + ((sg_lin >> 1) & 3u);
+ const uint lane_col_base = ((lane_qid & 2u) << 1) + ((sg_lin & 1u) << 1);
+
+UZU_PRAGMA_UNROLL
+ for (uint n_sub = 0; n_sub < PASSA_SG_BN; n_sub += SG_TILE) {
+ const uint c_idx = n_sub / SG_TILE;
+UZU_PRAGMA_UNROLL
+ for (uint m_sub = 0; m_sub < PASSA_SG_BM; m_sub += SG_TILE) {
+ const uint r_idx = m_sub / SG_TILE;
+ const uint tile = r_idx * (PASSA_SG_BN / SG_TILE) + c_idx;
+
+ const uint tile_row_base = row_sg_off + m_sub;
+ const uint tile_col_base = col_sg_off + n_sub;
+ const uint local_row = tile_row_base + lane_row;
+ if (local_row >= m_rows || tile_col_base >= n_cols) {
+ continue;
+ }
+
+ const auto up_frag = OutUp[tile].thread_elements();
+ float gate_frag_0 = 0.0f;
+ float gate_frag_1 = 0.0f;
+ if (GATING_SEL > 1u) {
+ const auto gate_frag = OutGate[tile].thread_elements();
+ gate_frag_0 = gate_frag[0];
+ gate_frag_1 = gate_frag[1];
+ }
+
+ const uint col0 = tile_col_base + lane_col_base;
+ const uint col1 = col0 + 1;
+ const ulong out_row = seg_start + row_tg_off + local_row;
+
+ if (col0 < n_cols) {
+ float up_v = clamp(up_frag[0] + bias_up[col0], up_clip_min, up_clip_max);
+ float out_val;
+ if (GATING_SEL <= 1u) {
+ out_val =
+ (GATING_SEL == 0u) ? gelu_approx(up_v) : silu(up_v, silu_alpha);
+ } else {
+ float gate_v =
+ clamp(gate_frag_0 + bias_gate[col0], gate_clip_min, gate_clip_max);
+ const float gate_act =
+ (GATING_SEL == 2u) ? silu(gate_v, silu_alpha) : gelu_approx(gate_v);
+ out_val = gate_act * up_v;
+ }
+ const ulong out_col = col_tg_off + col0;
+ hidden_out[out_row * (ulong)d_ff + out_col] = out_val;
+ }
+
+ if (col1 < n_cols) {
+ float up_v = clamp(up_frag[1] + bias_up[col1], up_clip_min, up_clip_max);
+ float out_val;
+ if (GATING_SEL <= 1u) {
+ out_val =
+ (GATING_SEL == 0u) ? gelu_approx(up_v) : silu(up_v, silu_alpha);
+ } else {
+ float gate_v =
+ clamp(gate_frag_1 + bias_gate[col1], gate_clip_min, gate_clip_max);
+ const float gate_act =
+ (GATING_SEL == 2u) ? silu(gate_v, silu_alpha) : gelu_approx(gate_v);
+ out_val = gate_act * up_v;
+ }
+ const ulong out_col = col_tg_off + col1;
+ hidden_out[out_row * (ulong)d_ff + out_col] = out_val;
+ }
+ }
+ }
+}
+
+// ----- Kernel entry points (Pass A) -----
+#define MOE_PASS_A_KERNEL(DTYPE, SUFFIX) \
+kernel void moe_two_pass_prefill_pass_a_##SUFFIX( \
+ device const DTYPE* X_perm [[buffer(0)]], \
+ device const uint* expert_offsets [[buffer(1)]], \
+ device const DTYPE* W13_all [[buffer(2)]], \
+ device const DTYPE* up_biases [[buffer(3)]], \
+ device float* hidden_out [[buffer(4)]], \
+ constant uint& d_model [[buffer(5)]], \
+ constant uint& d_ff [[buffer(6)]], \
+ constant uint& E [[buffer(7)]], \
+ constant float& gate_clip_min [[buffer(8)]], \
+ constant float& gate_clip_max [[buffer(9)]], \
+ constant float& up_clip_min [[buffer(10)]], \
+ constant float& up_clip_max [[buffer(11)]], \
+ constant float& silu_alpha [[buffer(12)]], \
+ uint sg_id [[simdgroup_index_in_threadgroup]], \
+ uint3 threads_per_tg [[threads_per_threadgroup]], \
+ uint3 tg_pos [[threadgroup_position_in_grid]], \
+ uint3 local_tid [[thread_position_in_threadgroup]] ) \
+{ \
+ using StageT = typename StageStorage<DTYPE>::type; \
+ threadgroup StageT Xs [PASSA_BM * PASSA_BK]; \
+ threadgroup StageT Wk_up [PASSA_BN * PASSA_BK]; \
+ threadgroup StageT Wk_gate [PASSA_BN * PASSA_BK]; \
+ threadgroup float bias_up [PASSA_BN]; \
+ threadgroup float bias_gate [PASSA_BN]; \
+ pass_a_impl<DTYPE>( \
+ X_perm, expert_offsets, W13_all, up_biases, hidden_out, \
+ d_model, d_ff, E, \
+ gate_clip_min, gate_clip_max, up_clip_min, up_clip_max, silu_alpha, \
+ /*tile_seg_start*/ expert_offsets[tg_pos.z], /*expert*/ tg_pos.z, /*tile_m*/ tg_pos.y, /*tile_n*/ tg_pos.x, \
+ sg_id, threads_per_tg, local_tid, \
+ Xs, Wk_up, Wk_gate, bias_up, bias_gate); \
+}
+
+MOE_PASS_A_KERNEL(bfloat, bf16)
+MOE_PASS_A_KERNEL(half, f16)
+MOE_PASS_A_KERNEL(float, f32)
+
+// Indirect variant (consumes [expert, seg_start, tile_row_offset] triples)
+template<typename T>
+inline void pass_a_indirect_impl(
+ device const T* X_perm,
+ device const uint* expert_offsets,
+ device const T* W13_all,
+ device const T* up_biases,
+ device float* hidden_out,
+ device const uint* tile_map, // [tiles * 3]: (expert, seg_start, row_offset_elems)
+ uint d_model, uint d_ff, uint E,
+ float gate_clip_min, float gate_clip_max,
+ float up_clip_min, float up_clip_max,
+ float silu_alpha,
+ uint row_tile_idx, uint n_tile_idx,
+ uint sg_id, uint3 threads_per_tg, uint3 local_tid,
+ threadgroup typename StageStorage<T>::type* Xs,
+ threadgroup typename StageStorage<T>::type* Wk_up,
+ threadgroup typename StageStorage<T>::type* Wk_gate,
+ threadgroup float* bias_up,
+ threadgroup float* bias_gate)
+{
+ constexpr uint ROW_TILE = PASSA_BM;
+ const uint base = row_tile_idx * 3u;
+ const uint expert_idx = tile_map[base + 0u];
+ if (expert_idx >= E) return;
+ const uint tile_seg_start = tile_map[base + 1u];
+ const uint row_off_elems = tile_map[base + 2u];
+ const uint tile_m = row_off_elems / ROW_TILE;
+
+ pass_a_impl<T>(
+ X_perm, expert_offsets, W13_all, up_biases, hidden_out,
+ d_model, d_ff, E,
+ gate_clip_min, gate_clip_max, up_clip_min, up_clip_max, silu_alpha,
+ tile_seg_start, expert_idx, tile_m, n_tile_idx,
+ sg_id, threads_per_tg, local_tid,
+ Xs, Wk_up, Wk_gate, bias_up, bias_gate);
+}
+
+#define MOE_PASS_A_INDIRECT_KERNEL(DTYPE, SUFFIX) \
+kernel void moe_two_pass_prefill_pass_a_indirect_##SUFFIX( \
+ device const DTYPE* X_perm [[buffer(0)]], \
+ device const uint* expert_offsets [[buffer(1)]], \
+ device const DTYPE* W13_all [[buffer(2)]], \
+ device const DTYPE* up_biases [[buffer(3)]], \
+ device float* hidden_out [[buffer(4)]], \
+ constant uint& d_model [[buffer(5)]], \
+ constant uint& d_ff [[buffer(6)]], \
+ constant uint& E [[buffer(7)]], \
+ constant float& gate_clip_min [[buffer(8)]], \
+ constant float& gate_clip_max [[buffer(9)]], \
+ constant float& up_clip_min [[buffer(10)]], \
+ constant float& up_clip_max [[buffer(11)]], \
+ constant float& silu_alpha [[buffer(12)]], \
+ device const uint* tile_map [[buffer(13)]], \
+ uint sg_id [[simdgroup_index_in_threadgroup]], \
+ uint3 threads_per_tg [[threads_per_threadgroup]], \
+ uint3 tg_pos [[threadgroup_position_in_grid]], \
+ uint3 local_tid [[thread_position_in_threadgroup]]) \
+{ \
+ using StageT = typename StageStorage<DTYPE>::type; \
+ threadgroup StageT Xs [PASSA_BM * PASSA_BK]; \
+ threadgroup StageT Wk_up [PASSA_BN * PASSA_BK]; \
+ threadgroup StageT Wk_gate [PASSA_BN * PASSA_BK]; \
+ threadgroup float bias_up [PASSA_BN]; \
+ threadgroup float bias_gate [PASSA_BN]; \
+ pass_a_indirect_impl<DTYPE>( \
+ X_perm, expert_offsets, W13_all, up_biases, hidden_out, tile_map, \
+ d_model, d_ff, E, \
+ gate_clip_min, gate_clip_max, up_clip_min, up_clip_max, silu_alpha, \
+ /*row_tile_idx*/ tg_pos.y, /*n_tile_idx*/ tg_pos.x, \
+ sg_id, threads_per_tg, local_tid, \
+ Xs, Wk_up, Wk_gate, bias_up, bias_gate); \
+}
+
+MOE_PASS_A_INDIRECT_KERNEL(bfloat, bf16)
+MOE_PASS_A_INDIRECT_KERNEL(half, f16)
+MOE_PASS_A_INDIRECT_KERNEL(float, f32)
+
+// ------------------------ Pass B (hidden @ W2 → output) ------------------------
+constant uint PASSB_BM = 16;
+constant uint PASSB_BN = 64;
+constant uint PASSB_BK = 64;
+constant uint PASSB_SG_BM = 8;
+constant uint PASSB_SG_BN = 32;
+
+template<typename T>
+inline void pass_b_impl(
+ device const float* hidden, // [total_rows, FF]
+ device const uint* expert_offsets, // [E+1]
+ device const T* W2_all, // [E, D, FF] (FF contiguous)
+ device const T* down_biases, // [E, D]
+ device T* output, // [total_rows, D]
+ uint d_model, uint d_ff, uint E,
+ uint expert_idx, uint tile_m, uint tile_n,
+ uint sg_id, uint3 threads_per_tg, uint3 local_tid,
+ threadgroup float* Hs, // [BM,BK]
+ threadgroup typename StageStorage<T>::type* Wk, // [BN,BK]
+ threadgroup float* bias_tile // [BN]
+) {
+ using StageT = typename StageStorage<T>::type;
+ using StageVec4 = metal::vec<StageT, 4>;
+
+ const uint Bm = PASSB_BM, Bn = PASSB_BN, Bk = PASSB_BK;
+ const uint SgBm = PASSB_SG_BM, SgBn = PASSB_SG_BN;
+
+ if (expert_idx >= E) return;
+
+ const uint seg_start = expert_offsets[expert_idx];
+ const uint seg_end = expert_offsets[expert_idx + 1];
+ const uint seg_len = (seg_end > seg_start) ? (seg_end - seg_start) : 0u;
+ if (seg_len == 0) return;
+
+ const uint row_tg_off = tile_m * Bm;
+ const uint col_tg_off = tile_n * Bn;
+ if (row_tg_off >= seg_len || col_tg_off >= d_model) return;
+
+ const uint m_rows = min(Bm, seg_len - row_tg_off);
+ const uint n_cols = min(Bn, d_model - col_tg_off);
+
+ const ulong h_base = (ulong)(seg_start + row_tg_off) * (ulong)d_ff;
+ const ulong w2_expert_base = (ulong)expert_idx * (ulong)d_model * (ulong)d_ff;
+ const ulong bias_base = (ulong)expert_idx * (ulong)d_model;
+
+ const uint sg_col_count = Bn / SgBn;
+ const uint row_sg = sg_id / sg_col_count;
+ const uint col_sg = sg_id % sg_col_count;
+ const uint row_sg_off = row_sg * SgBm;
+ const uint col_sg_off = col_sg * SgBn;
+
+ constexpr uint SG_TILE = 8;
+ constexpr uint TEMP = (PASSB_SG_BM / SG_TILE) * (PASSB_SG_BN / SG_TILE);
+ metal::simdgroup_float8x8 Out[TEMP];
+ for (uint i = 0; i < TEMP; ++i) {
+ Out[i] = metal::make_filled_simdgroup_matrix<float, 8, 8>(0.0f);
+ }
+
+ const uint threads_total = threads_per_tg.x * threads_per_tg.y * threads_per_tg.z;
+ const uint lin = linear_tid(local_tid, threads_per_tg);
+
+ // K-loop across FF
+ for (uint k_off = 0; k_off < d_ff; k_off += Bk) {
+ const uint valid_k = min(Bk, d_ff - k_off);
+
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ // ---- Stage hidden [Bm,Bk] as float4 ----
+ {
+ constexpr uint row_stride = PASSB_BK;
+ constexpr uint vec_cols = PASSB_BK / 4;
+ const uint total_vecs = PASSB_BM * vec_cols;
+ const uint iters = ceil_div(total_vecs, threads_total);
+
+UZU_PRAGMA_UNROLL
+ for (uint t = 0; t < iters; ++t) {
+ const uint i = t * threads_total + lin;
+ if (i < total_vecs) {
+ const uint r = i / vec_cols;
+ const uint c4 = i % vec_cols;
+
+ threadgroup float4* dst4 =
+ reinterpret_cast<threadgroup float4*>(Hs + r * row_stride + (c4 << 2));
+
+ float4 v = float4(0.0f);
+ if (r < m_rows) {
+ const uint base_vec = (c4 << 2);
+ const ulong base = h_base + (ulong)r * (ulong)d_ff + (ulong)(k_off + base_vec);
+ if (base_vec + 0u < valid_k) v.x = hidden[base + 0];
+ if (base_vec + 1u < valid_k) v.y = hidden[base + 1];
+ if (base_vec + 2u < valid_k) v.z = hidden[base + 2];
+ if (base_vec + 3u < valid_k) v.w = hidden[base + 3];
+ }
+ *dst4 = v;
+ }
+ }
+ }
+
+ // ---- Stage W2 [Bn,Bk] as StageT (column-major for simd transpose) ----
+ {
+ constexpr uint row_stride = PASSB_BK;
+ constexpr uint vec_cols = PASSB_BK / 4;
+ const uint total_vecs = PASSB_BN * vec_cols;
+ const uint iters = ceil_div(total_vecs, threads_total);
+
+UZU_PRAGMA_UNROLL
+ for (uint t = 0; t < iters; ++t) {
+ const uint i = t * threads_total + lin;
+ if (i < total_vecs) {
+ const uint n = i / vec_cols;
+ const uint c4 = i % vec_cols;
+
+ threadgroup StageVec4* dst4 =
+ reinterpret_cast<threadgroup StageVec4*>(Wk + n * row_stride + (c4 << 2));
+
+ StageVec4 packed = StageVec4(StageT(0.0f));
+ if (n < n_cols) {
+ const uint gcol = col_tg_off + n;
+ const ulong base = w2_expert_base + (ulong)gcol * (ulong)d_ff + (ulong)(k_off + (c4 << 2));
+ const uint base_vec = (c4 << 2);
+ float v0 = 0.0f, v1 = 0.0f, v2 = 0.0f, v3 = 0.0f;
+ if (base_vec + 0u < valid_k) v0 = float(W2_all[base + 0]);
+ if (base_vec + 1u < valid_k) v1 = float(W2_all[base + 1]);
+ if (base_vec + 2u < valid_k) v2 = float(W2_all[base + 2]);
+ if (base_vec + 3u < valid_k) v3 = float(W2_all[base + 3]);
+ packed = StageVec4(StageT(v0), StageT(v1), StageT(v2), StageT(v3));
+ }
+ *dst4 = packed;
+ }
+ }
+ }
+
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ // ---- MMA ----
+UZU_PRAGMA_UNROLL
+ for (uint kk = 0; kk < PASSB_BK; kk += SG_TILE) {
+UZU_PRAGMA_UNROLL
+ for (uint m_sub = 0; m_sub < PASSB_SG_BM; m_sub += SG_TILE) {
+ const uint r_idx = m_sub / SG_TILE;
+ metal::simdgroup_float8x8 lhs;
+ simdgroup_load(lhs, Hs, PASSB_BK, ulong2(kk, row_sg_off + m_sub));
+UZU_PRAGMA_UNROLL
+ for (uint n_sub = 0; n_sub < PASSB_SG_BN; n_sub += SG_TILE) {
+ const uint c_idx = n_sub / SG_TILE;
+ const uint tile = r_idx * (PASSB_SG_BN / SG_TILE) + c_idx;
+ metal::simdgroup_matrix<StageT, 8, 8> rhs;
+ simdgroup_load(rhs, Wk, PASSB_BK, ulong2(kk, col_sg_off + n_sub), true);
+ simdgroup_multiply_accumulate(Out[tile], lhs, rhs, Out[tile]);
+ }
+ }
+ }
+ }
+
+ // ---- Bias tile ----
+ for (uint c_local = lin; c_local < Bn; c_local += threads_total) {
+ const uint c_global = col_tg_off + c_local;
+ bias_tile[c_local] = (c_global < d_model) ? float(down_biases[bias_base + c_global]) : 0.0f;
+ }
+
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ // ---- Writeout ----
+ const uint sg_lane_start = sg_id * 32;
+ const uint sg_lane_end = sg_lane_start + 32;
+ if (lin < sg_lane_start || lin >= sg_lane_end) return;
+ const uint sg_lin = lin - sg_lane_start;
+
+ // Lane→(row,col) mapping for 8x8 simdgroup fragments, matches PASSB fragment packing.
+ const uint lane_qid = sg_lin >> 2;
+ const uint lane_row = (lane_qid & 4u) + ((sg_lin >> 1) & 3u);
+ const uint lane_col_base = ((lane_qid & 2u) << 1) + ((sg_lin & 1u) << 1);
+
+UZU_PRAGMA_UNROLL
+ for (uint n_sub = 0; n_sub < PASSB_SG_BN; n_sub += SG_TILE) {
+ const uint c_idx = n_sub / SG_TILE;
+UZU_PRAGMA_UNROLL
+ for (uint m_sub = 0; m_sub < PASSB_SG_BM; m_sub += SG_TILE) {
+ const uint r_idx = m_sub / SG_TILE;
+ const uint tile = r_idx * (PASSB_SG_BN / SG_TILE) + c_idx;
+
+ const uint tile_row_base = row_sg_off + m_sub;
+ const uint tile_col_base = col_sg_off + n_sub;
+ const uint local_row = tile_row_base + lane_row;
+ if (local_row >= m_rows || tile_col_base >= n_cols) {
+ continue;
+ }
+
+ const auto accum = Out[tile].thread_elements();
+
+ const uint col0 = tile_col_base + lane_col_base;
+ const uint col1 = col0 + 1u;
+ const ulong out_row = seg_start + row_tg_off + local_row;
+
+ if (col0 < n_cols) {
+ const ulong out_col = col_tg_off + col0;
+ const float val = accum[0] + bias_tile[col0];
+ output[out_row * (ulong)d_model + out_col] = T(val);
+ }
+
+ if (col1 < n_cols) {
+ const ulong out_col = col_tg_off + col1;
+ const float val = accum[1] + bias_tile[col1];
+ output[out_row * (ulong)d_model + out_col] = T(val);
+ }
+ }
+ }
+}
+
+// ----- Kernel entry points (Pass B) -----
+#define MOE_PASS_B_KERNEL(DTYPE, SUFFIX) \
+kernel void moe_two_pass_prefill_pass_b_##SUFFIX( \
+ device const float* hidden [[buffer(0)]], \
+ device const uint* expert_offsets [[buffer(1)]], \
+ device const DTYPE* W2_all [[buffer(2)]], \
+ device const DTYPE* down_biases [[buffer(3)]], \
+ device DTYPE* output [[buffer(4)]], \
+ constant uint& d_model [[buffer(5)]], \
+ constant uint& d_ff [[buffer(6)]], \
+ constant uint& E [[buffer(7)]], \
+ uint sg_id [[simdgroup_index_in_threadgroup]], \
+ uint3 threads_per_tg [[threads_per_threadgroup]], \
+ uint3 tg_pos [[threadgroup_position_in_grid]], \
+ uint3 local_tid [[thread_position_in_threadgroup]]) \
+{ \
+ using StageT = typename StageStorage<DTYPE>::type; \
+ threadgroup float Hs [PASSB_BM * PASSB_BK]; \
+ threadgroup StageT Wk [PASSB_BN * PASSB_BK]; \
+ threadgroup float bias [PASSB_BN]; \
+ pass_b_impl<DTYPE>( \
+ hidden, expert_offsets, W2_all, down_biases, output, \
+ d_model, d_ff, E, \
+ /*expert*/ tg_pos.z, /*tile_m*/ tg_pos.y, /*tile_n*/ tg_pos.x, \
+ sg_id, threads_per_tg, local_tid, \
+ Hs, Wk, bias); \
+}
+
+MOE_PASS_B_KERNEL(bfloat, bf16)
+MOE_PASS_B_KERNEL(half, f16)
+MOE_PASS_B_KERNEL(float, f32)
+
+// Indirect variant
+template<typename T>
+inline void pass_b_indirect_impl(
+ device const float* hidden,
+ device const uint* expert_offsets,
+ device const T* W2_all,
+ device const T* down_biases,
+ device T* output,
+ device const uint* tile_map, // [tiles * 3]
+ uint d_model, uint d_ff, uint E,
+ uint row_tile_idx, uint n_tile_idx,
+ uint sg_id, uint3 threads_per_tg, uint3 local_tid,
+ threadgroup float* Hs,
+ threadgroup typename StageStorage<T>::type* Wk,
+ threadgroup float* bias_tile)
+{
+ constexpr uint ROW_TILE = PASSB_BM;
+ const uint base = row_tile_idx * 3u;
+ const uint expert_idx = tile_map[base + 0u];
+ if (expert_idx >= E) return;
+ const uint row_off_elems = tile_map[base + 2u];
+ const uint tile_m = row_off_elems / ROW_TILE;
+
+ pass_b_impl<T>(
+ hidden, expert_offsets, W2_all, down_biases, output,
+ d_model, d_ff, E,
+ expert_idx, tile_m, n_tile_idx,
+ sg_id, threads_per_tg, local_tid,
+ Hs, Wk, bias_tile);
+}
+
+#define MOE_PASS_B_INDIRECT_KERNEL(DTYPE, SUFFIX) \
+kernel void moe_two_pass_prefill_pass_b_indirect_##SUFFIX( \
+ device const float* hidden [[buffer(0)]], \
+ device const uint* expert_offsets [[buffer(1)]], \
+ device const DTYPE* W2_all [[buffer(2)]], \
+ device const DTYPE* down_biases [[buffer(3)]], \
+ device DTYPE* output [[buffer(4)]], \
+ constant uint& d_model [[buffer(5)]], \
+ constant uint& d_ff [[buffer(6)]], \
+ constant uint& E [[buffer(7)]], \
+ device const uint* tile_map [[buffer(8)]], \
+ uint sg_id [[simdgroup_index_in_threadgroup]], \
+ uint3 threads_per_tg [[threads_per_threadgroup]], \
+ uint3 tg_pos [[threadgroup_position_in_grid]], \
+ uint3 local_tid [[thread_position_in_threadgroup]]) \
+{ \
+ using StageT = typename StageStorage<DTYPE>::type; \
+ threadgroup float Hs [PASSB_BM * PASSB_BK]; \
+ threadgroup StageT Wk [PASSB_BN * PASSB_BK]; \
+ threadgroup float bias [PASSB_BN]; \
+ pass_b_indirect_impl<DTYPE>( \
+ hidden, expert_offsets, W2_all, down_biases, output, tile_map, \
+ d_model, d_ff, E, \
+ /*row_tile_idx*/ tg_pos.y, /*n_tile_idx*/ tg_pos.x, \
+ sg_id, threads_per_tg, local_tid, \
+ Hs, Wk, bias); \
+}
+
+MOE_PASS_B_INDIRECT_KERNEL(bfloat, bf16)
+MOE_PASS_B_INDIRECT_KERNEL(half, f16)
+MOE_PASS_B_INDIRECT_KERNEL(float, f32)
diff --git a/crates/uzu/src/backends/metal/kernel/moe/finalize.metal b/crates/uzu/src/backends/metal/kernel/moe/finalize.metal
new file mode 100644
index 000000000..978cec9ba
--- /dev/null
+++ b/crates/uzu/src/backends/metal/kernel/moe/finalize.metal
@@ -0,0 +1,74 @@
+#include <metal_stdlib>
+using namespace metal;
+
+// Defaults must match Rust launcher
+#define BM 32
+#define BN 64
+
+template<typename T>
+inline void moe_finalize_impl(
+ device const int* tok2row, // [T*K], -1 if dropped
+ device const T* probs, // [T*K]
+ device const T* Y_partial, // [sum_k, d_model]
+ device T* Y, // [T, d_model]
+ constant uint& T_count,
+ constant uint& d_model,
+ constant uint& K,
+ uint lid,
+ uint3 tgpig)
+{
+ if (T_count == 0u || d_model == 0u) return;
+ const uint tile_m0 = tgpig.y * BM;
+ const uint tile_n0 = tgpig.x * BN;
+ if (tile_m0 >= T_count || tile_n0 >= d_model) return;
+ const uint m_rows = min((uint)BM, T_count - tile_m0);
+ const uint n_cols = min((uint)BN, d_model - tile_n0);
+
+ // 128 threads per TG expected
+ for (uint idx = lid; idx < m_rows * n_cols; idx += 128u) {
+ const uint mi = idx / n_cols;
+ const uint nj = idx % n_cols;
+ const uint t = tile_m0 + mi;
+ const uint f = tile_n0 + nj;
+ float acc = 0.0f;
+ const uint base = t * K;
+ for (uint k = 0; k < K; ++k) {
+ const int row = tok2row[base + k];
+ if (row >= 0) {
+ const ulong yidx = (ulong)(uint)row * (ulong)d_model + (ulong)f;
+ float prob = (float)probs[base + k];
+ if (!isfinite(prob)) {
+ prob = 0.0f;
+ }
+ float val = (float)Y_partial[yidx];
+ if (!isfinite(val)) {
+ val = 0.0f;
+ }
+ acc = fma(prob, val, acc);
+ }
+ }
+ if (!isfinite(acc)) {
+ acc = 0.0f;
+ }
+ Y[t * d_model + f] = T(acc);
+ }
+}
+
+#define DEFINE_MOE_FINALIZE_KERNEL(SUFFIX, T) \
+kernel void moe_finalize_##SUFFIX( \
+ device const int* tok2row [[buffer(0)]], \
+ device const T* probs [[buffer(1)]], \
+ device const T* Y_partial [[buffer(2)]], \
+ device T* Y [[buffer(3)]], \
+ constant uint& T_count [[buffer(4)]], \
+ constant uint& d_model [[buffer(5)]], \
+ constant uint& K [[buffer(6)]], \
+ uint lid [[thread_index_in_threadgroup]], \
+ uint3 tgpig [[threadgroup_position_in_grid]]) \
+{ \
+ moe_finalize_impl<T>(tok2row, probs, Y_partial, Y, T_count, d_model, K, lid, tgpig); \
+}
+
+DEFINE_MOE_FINALIZE_KERNEL(f16, half)
+DEFINE_MOE_FINALIZE_KERNEL(bf16, bfloat)
+DEFINE_MOE_FINALIZE_KERNEL(f32, float)
diff --git a/crates/uzu/src/backends/metal/kernel/moe/finalize.rs b/crates/uzu/src/backends/metal/kernel/moe/finalize.rs
new file mode 100644
index 000000000..176991b89
--- /dev/null
+++ b/crates/uzu/src/backends/metal/kernel/moe/finalize.rs
@@ -0,0 +1,106 @@
+use std::mem::size_of;
+
+use metal::{
+ Buffer as MTLBuffer, CommandBufferRef,
+ ComputePipelineState as MTLComputePipelineState, MTLSize,
+};
+
+use crate::backends::metal::{KernelDataType, MTLContext, MTLError};
+
+// ---- Finalize Kernel ----
+
+#[derive(Debug, thiserror::Error)]
+pub enum MoeFinalizeError {
+ #[error("Metal error: {0}")]
+ MetalError(#[from] MTLError),
+}
+
+pub struct MoeFinalizeKernel {
+ pipeline_f16: MTLComputePipelineState,
+ pipeline_bf16: MTLComputePipelineState,
+ pipeline_f32: MTLComputePipelineState,
+}
+
+#[derive(Debug)]
+pub struct MoeFinalizeArguments<'a> {
+ pub tok2row_buffer: &'a MTLBuffer, // [T*K] i32
+ pub probs_buffer: &'a MTLBuffer, // [T*K] f16/bf16
+ pub y_partial_buffer: &'a MTLBuffer, // [sum_k, d_model] f16
+ pub y_out_buffer: &'a MTLBuffer, // [T, d_model] f16
+ pub t: usize,
+ pub d_model: usize,
+ pub k: usize,
+}
+
+impl MoeFinalizeKernel {
+ pub fn new(ctx: &MTLContext) -> Result<Self, MoeFinalizeError> {
+ let pipeline_f16 =
+ ctx.compute_pipeline_state("moe_finalize_f16", None)?;
+ let pipeline_bf16 =
+ ctx.compute_pipeline_state("moe_finalize_bf16", None)?;
+ let pipeline_f32 =
+ ctx.compute_pipeline_state("moe_finalize_f32", None)?;
+ Ok(Self {
+ pipeline_f16,
+ pipeline_bf16,
+ pipeline_f32,
+ })
+ }
+
+ pub fn encode(
+ &self,
+ command_buffer: &CommandBufferRef,
+ args: MoeFinalizeArguments,
+ dtype: KernelDataType,
+ ) -> Result<(), MoeFinalizeError> {
+ let encoder = command_buffer.new_compute_command_encoder();
+ match dtype {
+ KernelDataType::Float16 => {
+ encoder.set_compute_pipeline_state(&self.pipeline_f16);
+ },
+ KernelDataType::BFloat16 => {
+ encoder.set_compute_pipeline_state(&self.pipeline_bf16);
+ },
+ KernelDataType::Float32 => {
+ encoder.set_compute_pipeline_state(&self.pipeline_f32);
+ },
+ }
+ encoder.set_buffer(0, Some(args.tok2row_buffer), 0);
+ encoder.set_buffer(1, Some(args.probs_buffer), 0);
+ encoder.set_buffer(2, Some(args.y_partial_buffer), 0);
+ encoder.set_buffer(3, Some(args.y_out_buffer), 0);
+ let t_u = args.t as u32;
+ let dm_u = args.d_model as u32;
+ let k_u = args.k as u32;
+ encoder.set_bytes(
+ 4,
+ size_of::<u32>() as u64,
+ &t_u as *const u32 as *const _,
+ );
+ encoder.set_bytes(
+ 5,
+ size_of::<u32>() as u64,
+ &dm_u as *const u32 as *const _,
+ );
+ encoder.set_bytes(
+ 6,
+ size_of::<u32>() as u64,
+ &k_u as *const u32 as *const _,
+ );
+
+ // Launch tiles over (N tiles, M tiles)
+ const BM: usize = 32;
+ const BN: usize = 64;
+ let num_tiles_n = (args.d_model + BN - 1) / BN;
+ let num_tiles_m = (args.t + BM - 1) / BM;
+ let threads_per_threadgroup = MTLSize::new(128, 1, 1); // BM * BN * 32 = 1 * 4 * 32
+ if num_tiles_m > 0 && num_tiles_n > 0 {
+ let threadgroups =
+ MTLSize::new(num_tiles_n as u64, num_tiles_m as u64, 1);
+ encoder
+ .dispatch_thread_groups(threadgroups, threads_per_threadgroup);
+ }
+ encoder.end_encoding();
+ Ok(())
+ }
+}
diff --git a/crates/uzu/src/backends/metal/kernel/moe/gather.rs b/crates/uzu/src/backends/metal/kernel/moe/gather.rs
new file mode 100644
index 000000000..0538518ac
--- /dev/null
+++ b/crates/uzu/src/backends/metal/kernel/moe/gather.rs
@@ -0,0 +1,102 @@
+use std::mem::size_of;
+
+use metal::{
+ Buffer as MTLBuffer, CommandBufferRef,
+ ComputePipelineState as MTLComputePipelineState, MTLSize,
+};
+
+use crate::backends::metal::{KernelDataType, MTLContext, MTLError};
+
+// ---- Gather Permuted Activations Kernel ----
+
+#[derive(Debug, thiserror::Error)]
+pub enum MoeGatherError {
+ #[error("Metal error: {0}")]
+ MetalError(#[from] MTLError),
+}
+
+pub struct MoeGatherKernel {
+ pipeline_f16: MTLComputePipelineState,
+ pipeline_f32: MTLComputePipelineState,
+ pipeline_bf16: MTLComputePipelineState,
+}
+
+#[derive(Debug)]
+pub struct MoeGatherArguments<'a> {
+ pub x_buffer: &'a MTLBuffer,
+ pub bucketed_ids_buffer: &'a MTLBuffer,
+ pub x_perm_buffer: &'a MTLBuffer,
+ pub sumk_buffer: &'a MTLBuffer,
+ pub t: usize,
+ pub k: usize,
+ pub d_model: usize,
+}
+
+impl MoeGatherKernel {
+ pub fn new(ctx: &MTLContext) -> Result<Self, MoeGatherError> {
+ let pipeline_f16 =
+ ctx.compute_pipeline_state("moe_gather_x_perm_f16", None)?;
+ let pipeline_f32 =
+ ctx.compute_pipeline_state("moe_gather_x_perm_f32", None)?;
+ let pipeline_bf16 =
+ ctx.compute_pipeline_state("moe_gather_x_perm_bf16_2d", None)?;
+ Ok(Self {
+ pipeline_f16,
+ pipeline_f32,
+ pipeline_bf16,
+ })
+ }
+
+ pub fn encode(
+ &self,
+ command_buffer: &CommandBufferRef,
+ dtype: KernelDataType,
+ args: MoeGatherArguments,
+ ) -> Result<(), MoeGatherError> {
+ let encoder = command_buffer.new_compute_command_encoder();
+ match dtype {
+ KernelDataType::Float16 => {
+ encoder.set_compute_pipeline_state(&self.pipeline_f16);
+ },
+ KernelDataType::Float32 => {
+ encoder.set_compute_pipeline_state(&self.pipeline_f32);
+ },
+ KernelDataType::BFloat16 => {
+ encoder.set_compute_pipeline_state(&self.pipeline_bf16);
+ },
+ }
+
+ encoder.set_buffer(0, Some(args.x_buffer), 0);
+ encoder.set_buffer(1, Some(args.bucketed_ids_buffer), 0);
+ encoder.set_buffer(2, Some(args.x_perm_buffer), 0);
+ encoder.set_buffer(3, Some(args.sumk_buffer), 0);
+ let d_model_u32 = args.d_model as u32;
+ encoder.set_bytes(
+ 4,
+ size_of::<u32>() as u64,
+ &d_model_u32 as *const u32 as *const _,
+ );
+
+ let max_rows = args.t * args.k;
+ if max_rows == 0 {
+ encoder.end_encoding();
+ return Ok(());
+ }
+ let threads_per_threadgroup = MTLSize::new(256, 1, 1);
+ let threadgroups = match dtype {
+ KernelDataType::BFloat16 => {
+ const BF16_ROWS_PER_TG: usize = 8;
+ MTLSize::new(
+ ((max_rows + BF16_ROWS_PER_TG - 1) / BF16_ROWS_PER_TG)
+ as u64,
+ 1,
+ 1,
+ )
+ },
+ _ => MTLSize::new(((max_rows + 255) / 256) as u64, 1, 1),
+ };
+ encoder.dispatch_thread_groups(threadgroups, threads_per_threadgroup);
+ encoder.end_encoding();
+ Ok(())
+ }
+}
diff --git a/crates/uzu/src/backends/metal/kernel/moe/mod.rs b/crates/uzu/src/backends/metal/kernel/moe/mod.rs
new file mode 100644
index 000000000..1fb3fd783
--- /dev/null
+++ b/crates/uzu/src/backends/metal/kernel/moe/mod.rs
@@ -0,0 +1,57 @@
+use crate::backends::metal::KernelDataType;
+
+mod encodable;
+pub use encodable::{MoeBlockEncodable, SharedMoeWeights};
+
+// Submodules
+mod counts_offsets_fused;
+mod experts;
+mod finalize;
+mod gather;
+mod router_topk;
+mod scatter;
+mod tiles;
+
+// Re-export public items from submodules
+pub use counts_offsets_fused::{
+ MoeCountsOffsetsFusedArguments, MoeCountsOffsetsFusedError,
+ MoeCountsOffsetsFusedKernel,
+};
+pub use experts::{
+ MoeExpertsArguments, MoeExpertsError, MoeExpertsTwoPassArguments,
+ MoeExpertsTwoPassDecodeKernel, MoeExpertsTwoPassPrefillKernel,
+ MoeScatterError,
+};
+pub use finalize::{MoeFinalizeArguments, MoeFinalizeError, MoeFinalizeKernel};
+pub use gather::{MoeGatherArguments, MoeGatherError, MoeGatherKernel};
+pub use router_topk::{
+ MoeRouterTopKArguments, MoeRouterTopKError, MoeRouterTopKKernel,
+};
+pub use scatter::{
+ MoeBlockBasesArguments, MoeScatterArguments, MoeScatterKernels,
+ MoeScatterWithMapArguments,
+};
+pub use tiles::{
+ MoePassARowMapArguments, MoePassATileBuildArguments,
+ MoePassATileCountsArguments, MoePassATileDispatchArguments,
+ MoePassATileKernel, MoePassATileScanArguments, MoeTileCountsArguments,
+ MoeTileDispatchArguments, MoeTileError, MoeTileMapBuildArguments,
+ MoeTileMapKernel, MoeTileScanArguments,
+};
+
+// Common utility functions
+pub(crate) fn dtype_suffix(dtype: KernelDataType) -> &'static str {
+ match dtype {
+ KernelDataType::Float16 => "f16",
+ KernelDataType::BFloat16 => "bf16",
+ KernelDataType::Float32 => "f32",
+ }
+}
+
+pub(crate) fn dtype_index(dtype: KernelDataType) -> usize {
+ match dtype {
+ KernelDataType::Float16 => 0,
+ KernelDataType::BFloat16 => 1,
+ KernelDataType::Float32 => 2,
+ }
+}
diff --git a/crates/uzu/src/backends/metal/kernel/moe/prepare.metal b/crates/uzu/src/backends/metal/kernel/moe/prepare.metal
new file mode 100644
index 000000000..2499930b2
--- /dev/null
+++ b/crates/uzu/src/backends/metal/kernel/moe/prepare.metal
@@ -0,0 +1,139 @@
+#include <metal_stdlib>
+using namespace metal;
+
+// Tiling config for 2D gather
+constant uint ROWS_PER_TG = 8u;
+constant uint COL_VECS = 32u; // 256 threads = 8×32
+constant uint ELEMS_PER_THREAD = 8u; // each thread copies 8 elements (2× vec4)
+
+// ========== 2D Tiled Gather Template ==========
+template<typename T>
+void moe_gather_x_perm_2d_impl(
+ device const T* X,
+ device const int* bucketed_ids,
+ device T* x_perm,
+ device const uint* sumk_buf,
+ uint d_model,
+ uint3 tgid,
+ uint lid)
+{
+ const uint total_rows = sumk_buf[0];
+ if (total_rows == 0u || d_model == 0u) return;
+
+ // Thread organization: lid = row_in_tg * COL_VECS + col_vec
+ const uint row_in_tg = lid / COL_VECS;
+ const uint col_vec = lid % COL_VECS;
+
+ // Global row assignment
+ const uint base_row = tgid.x * ROWS_PER_TG;
+ const uint row = base_row + row_in_tg;
+
+ if (row >= total_rows) return;
+
+ int token = bucketed_ids[row];
+ if (token < 0) return;
+
+ const device T* src = X + (ulong)(uint)token * (ulong)d_model;
+ device T* dst = x_perm + (ulong)row * (ulong)d_model;
+
+ // Each thread copies ELEMS_PER_THREAD elements
+ // Thread i processes: col_vec*8, col_vec*8+256, col_vec*8+512, ...
+ uint col = col_vec * ELEMS_PER_THREAD;
+ const uint stride = COL_VECS * ELEMS_PER_THREAD;
+
+ // Vectorized copy: 8 elements = 2× vec4
+ using Vec4 = typename metal::vec<T, 4>;
+ while (col + 7u < d_model) {
+ Vec4 v0 = *(reinterpret_cast<const device Vec4*>(src + col));
+ Vec4 v1 = *(reinterpret_cast<const device Vec4*>(src + col + 4u));
+ *(reinterpret_cast<device Vec4*>(dst + col)) = v0;
+ *(reinterpret_cast<device Vec4*>(dst + col + 4u)) = v1;
+ col += stride;
+ }
+
+ // Scalar remainder
+ if (col < d_model) {
+ const uint limit = min(d_model, col + ELEMS_PER_THREAD);
+ for (uint tail = col; tail < limit; ++tail) {
+ dst[tail] = src[tail];
+ }
+ }
+}
+
+// ========== 1D Gather Template ==========
+template<typename T>
+void moe_gather_x_perm_1d_impl(
+ device const T* X,
+ device const int* bucketed_ids,
+ device T* x_perm,
+ device const uint* sumk_buf,
+ uint d_model,
+ uint lid,
+ uint threads_x)
+{
+ const uint total_rows = sumk_buf[0];
+ if (total_rows == 0u || d_model == 0u) return;
+
+ const uint num_vec4 = d_model / 4u;
+
+ // Each thread processes multiple rows sequentially
+ for (uint row = lid; row < total_rows; row += threads_x) {
+ int token = bucketed_ids[row];
+ if (token < 0) continue;
+
+ const device T* src = X + (ulong)(uint)token * (ulong)d_model;
+ device T* dst = x_perm + (ulong)row * (ulong)d_model;
+
+ // Vectorized copy: 4 elements at a time
+ using Vec4 = typename metal::vec<T, 4>;
+ for (uint vec_idx = 0u; vec_idx < num_vec4; vec_idx++) {
+ uint col = vec_idx * 4u;
+ Vec4 v = *(reinterpret_cast<const device Vec4*>(src + col));
+ *(reinterpret_cast<device Vec4*>(dst + col)) = v;
+ }
+
+ // Scalar remainder
+ for (uint col = num_vec4 * 4u; col < d_model; col++) {
+ dst[col] = src[col];
+ }
+ }
+}
+
+// ========== Kernel Entry Points ==========
+
+// 2D Tiled kernels
+#define GATHER_2D_KERNEL(DTYPE, SUFFIX) \
+kernel void moe_gather_x_perm_##SUFFIX##_2d( \
+ device const DTYPE* X [[buffer(0)]], \
+ device const int* bucketed_ids [[buffer(1)]], \
+ device DTYPE* x_perm [[buffer(2)]], \
+ device const uint* sumk_buf [[buffer(3)]], \
+ constant uint& d_model [[buffer(4)]], \
+ uint3 tgid [[threadgroup_position_in_grid]], \
+ uint lid [[thread_index_in_threadgroup]]) \
+{ \
+ moe_gather_x_perm_2d_impl<DTYPE>(X, bucketed_ids, x_perm, sumk_buf, d_model, tgid, lid); \
+}
+
+// 1D kernels
+#define GATHER_1D_KERNEL(DTYPE, SUFFIX) \
+kernel void moe_gather_x_perm_##SUFFIX( \
+ device const DTYPE* X [[buffer(0)]], \
+ device const int* bucketed_ids [[buffer(1)]], \
+ device DTYPE* x_perm [[buffer(2)]], \
+ device const uint* sumk_buf [[buffer(3)]], \
+ constant uint& d_model [[buffer(4)]], \
+ uint lid [[thread_index_in_threadgroup]], \
+ uint3 threads_per_threadgroup [[threads_per_threadgroup]]) \
+{ \
+ moe_gather_x_perm_1d_impl<DTYPE>(X, bucketed_ids, x_perm, sumk_buf, d_model, lid, threads_per_threadgroup.x); \
+}
+
+// Instantiate for all types
+GATHER_2D_KERNEL(bfloat, bf16)
+GATHER_2D_KERNEL(half, f16)
+GATHER_2D_KERNEL(float, f32)
+
+GATHER_1D_KERNEL(bfloat, bf16)
+GATHER_1D_KERNEL(half, f16)
+GATHER_1D_KERNEL(float, f32)
diff --git a/crates/uzu/src/backends/metal/kernel/moe/router_topk.metal b/crates/uzu/src/backends/metal/kernel/moe/router_topk.metal
new file mode 100644
index 000000000..25b41db03
--- /dev/null
+++ b/crates/uzu/src/backends/metal/kernel/moe/router_topk.metal
@@ -0,0 +1,182 @@
+#include <metal_stdlib>
+#include <metal_simdgroup>
+#include "../definitions.metal"
+using namespace metal;
+
+constant uint THREADS_PER_TG = 256; // 8 simdgroups
+constant uint MAX_EXPERTS = 512;
+constant uint MAX_TOPK = 128;
+constant float NEG_INF = -INFINITY;
+
+template <typename Vec4T, typename ScalarT, typename ProbT>
+inline void moe_router_topk_impl(
+ const device Vec4T* input, // [T, d_model/4]
+ const device Vec4T* weight, // [E, d_model/4]
+ const device ScalarT* bias, // [E]
+ device int* topk_ids, // [T, K]
+ device ProbT* topk_probs, // [T, K]
+ uint T,
+ uint d_model,
+ uint E,
+ uint K,
+ uint renorm,
+ uint2 tgpig,
+ ushort lid,
+ ushort simd_lane,
+ ushort simdgroup_idx,
+ ushort simdgroups_per_tg,
+ threadgroup float4* x_cache,
+ threadgroup float* logits_shared,
+ threadgroup uint* idx_shared,
+ threadgroup float* reduce_tmp,
+ threadgroup uint* reduce_tmp_u,
+ threadgroup uint* shared_best_idx,
+ threadgroup float* shared_best_val)
+{
+ const uint token_idx = tgpig.y;
+ if (token_idx >= T || d_model == 0 || E == 0 || K == 0) {
+ return;
+ }
+
+ const uint vecs = d_model / 4u;
+ const device Vec4T* x_vec =
+ input + (ulong)token_idx * (ulong)vecs;
+
+ for (uint c = lid; c < vecs; c += THREADS_PER_TG) {
+ x_cache[c] = float4(x_vec[c]);
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ for (uint row = simdgroup_idx; row < E; row += simdgroups_per_tg) {
+ const device Vec4T* w_vec =
+ weight + (ulong)row * (ulong)vecs;
+
+ float4 accum4 = float4(0.0f);
+ for (uint c = simd_lane; c < vecs; c += 32u) {
+ const float4 wv = float4(w_vec[c]);
+ const float4 xv = x_cache[c];
+ accum4 = fma(wv, xv, accum4);
+ }
+ float sum = (accum4.x + accum4.y) + (accum4.z + accum4.w);
+ sum = simd_sum(sum);
+ if (simd_is_first()) {
+ sum += float(bias[row]);
+ logits_shared[row] = sum;
+ idx_shared[row] = row;
+ }
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ for (uint row = lid + E; row < MAX_EXPERTS; row += THREADS_PER_TG) {
+ logits_shared[row] = NEG_INF;
+ idx_shared[row] = row;
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ const uint effective_k = min(K, MAX_TOPK);
+ for (uint sel = 0; sel < effective_k; ++sel) {
+ float local_best = NEG_INF;
+ uint local_idx = 0xFFFFFFFFu;
+ for (uint row = lid; row < E; row += THREADS_PER_TG) {
+ float candidate = logits_shared[row];
+ if (candidate > local_best ||
+ (candidate == local_best && row < local_idx)) {
+ local_best = candidate;
+ local_idx = row;
+ }
+ }
+
+ float max_val =
+ threadgroup_cooperative_reduce_max<THREADS_PER_TG>(
+ local_best,
+ reduce_tmp,
+ lid);
+
+ uint candidate_id =
+ (local_best == max_val) ? local_idx : 0xFFFFFFFFu;
+ uint best_idx =
+ threadgroup_cooperative_reduce_min<THREADS_PER_TG>(
+ candidate_id,
+ reduce_tmp_u,
+ lid);
+
+ if (lid == 0) {
+ *shared_best_idx = best_idx;
+ *shared_best_val = max_val;
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ uint winner_idx = *shared_best_idx;
+ float winner_val = *shared_best_val;
+ if (winner_idx < MAX_EXPERTS) {
+ if (lid == 0) {
+ logits_shared[winner_idx] = NEG_INF;
+ idx_shared[winner_idx] = 0xFFFFFFFFu;
+ device int* out_ids = topk_ids + token_idx * K;
+ device ProbT* out_probs = topk_probs + token_idx * K;
+ out_ids[sel] = int(winner_idx);
+ out_probs[sel] = ProbT(winner_val);
+ }
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ }
+
+ if (lid == 0 && renorm != 0 && effective_k > 0) {
+ device ProbT* out_probs = topk_probs + token_idx * K;
+ float max_logit = -INFINITY;
+ for (uint i = 0; i < effective_k; ++i) {
+ max_logit = fmax(max_logit, float(out_probs[i]));
+ }
+ float sum_exp = 0.0f;
+ for (uint i = 0; i < effective_k; ++i) {
+ sum_exp += exp(float(out_probs[i]) - max_logit);
+ }
+ float default_prob = 1.0f / float(effective_k);
+ float inv_sum = (sum_exp > 0.0f) ? (1.0f / sum_exp) : default_prob;
+ for (uint i = 0; i < effective_k; ++i) {
+ float prob = (sum_exp > 0.0f)
+ ? exp(float(out_probs[i]) - max_logit) * inv_sum
+ : default_prob;
+ out_probs[i] = ProbT(prob);
+ }
+ for (uint i = effective_k; i < K; ++i) {
+ out_probs[i] = ProbT(0.0f);
+ }
+ }
+}
+
+#define DEFINE_ROUTER_TOPK_KERNEL(SUFFIX, VEC4, SCALAR, PROB) \
+kernel void moe_router_topk_##SUFFIX( \
+ const device VEC4* input [[buffer(0)]], \
+ const device VEC4* weight [[buffer(1)]], \
+ const device SCALAR* bias [[buffer(2)]], \
+ device int* topk_ids [[buffer(3)]], \
+ device PROB* topk_probs [[buffer(4)]], \
+ constant uint& T [[buffer(5)]], \
+ constant uint& d_model [[buffer(6)]], \
+ constant uint& E [[buffer(7)]], \
+ constant uint& K [[buffer(8)]], \
+ constant uint& renorm [[buffer(9)]], \
+ uint2 tgpig [[threadgroup_position_in_grid]], \
+ ushort lid [[thread_index_in_threadgroup]], \
+ ushort simd_lane [[thread_index_in_simdgroup]], \
+ ushort simdgroup_idx [[simdgroup_index_in_threadgroup]], \
+ ushort simdgroups_per_tg [[simdgroups_per_threadgroup]]) \
+{ \
+ threadgroup float4 x_cache[1024]; \
+ threadgroup float logits_shared[MAX_EXPERTS]; \
+ threadgroup uint idx_shared[MAX_EXPERTS]; \
+ threadgroup float reduce_tmp[THREADS_PER_TG]; \
+ threadgroup uint reduce_tmp_u[THREADS_PER_TG]; \
+ threadgroup uint shared_best_idx_mem; \
+ threadgroup float shared_best_val_mem; \
+ moe_router_topk_impl<VEC4, SCALAR, PROB>( \
+ input, weight, bias, topk_ids, topk_probs, \
+ T, d_model, E, K, renorm, tgpig, lid, simd_lane, simdgroup_idx, simdgroups_per_tg, \
+ x_cache, logits_shared, idx_shared, reduce_tmp, reduce_tmp_u, \
+ &shared_best_idx_mem, &shared_best_val_mem); \
+}
+
+DEFINE_ROUTER_TOPK_KERNEL(f16, half4, half, half)
+DEFINE_ROUTER_TOPK_KERNEL(bf16, bfloat4, bfloat, bfloat)
+DEFINE_ROUTER_TOPK_KERNEL(f32, float4, float, float)
diff --git a/crates/uzu/src/backends/metal/kernel/moe/router_topk.rs b/crates/uzu/src/backends/metal/kernel/moe/router_topk.rs
new file mode 100644
index 000000000..a1e2495bd
--- /dev/null
+++ b/crates/uzu/src/backends/metal/kernel/moe/router_topk.rs
@@ -0,0 +1,151 @@
+use std::mem::size_of;
+
+use metal::{
+ Buffer as MTLBuffer, CommandBufferRef,
+ ComputePipelineState as MTLComputePipelineState, MTLSize,
+};
+
+use crate::backends::metal::{KernelDataType, MTLContext, MTLError};
+
+const THREADS_PER_THREADGROUP: usize = 256;
+const MAX_EXPERTS: usize = 512;
+const MAX_TOPK: usize = 128;
+
+#[derive(Debug, thiserror::Error)]
+pub enum MoeRouterTopKError {
+ #[error("Metal error: {0}")]
+ MetalError(#[from] MTLError),
+ #[error("Invalid configuration: T={t}, d_model={d_model}, E={e}, K={k}")]
+ InvalidConfig {
+ t: usize,
+ d_model: usize,
+ e: usize,
+ k: usize,
+ },
+}
+
+pub struct MoeRouterTopKKernel {
+ pipeline_f16: MTLComputePipelineState,
+ pipeline_f32: MTLComputePipelineState,
+ pipeline_bf16: MTLComputePipelineState,
+}
+
+#[derive(Debug)]
+pub struct MoeRouterTopKArguments<'a> {
+ pub input_buffer: &'a MTLBuffer, // [T, d_model]
+ pub weight_buffer: &'a MTLBuffer, // [E, d_model]
+ pub bias_buffer: &'a MTLBuffer, // [E]
+ pub topk_ids_buffer: &'a MTLBuffer, // [T, K]
+ pub topk_probs_buffer: &'a MTLBuffer, // [T, K]
+ pub t: usize,
+ pub d_model: usize,
+ pub e: usize,
+ pub k: usize,
+ pub renorm: bool,
+}
+
+impl MoeRouterTopKKernel {
+ pub fn new(mtl_context: &MTLContext) -> Result<Self, MoeRouterTopKError> {
+ let pipeline_f16 =
+ mtl_context.compute_pipeline_state("moe_router_topk_f16", None)?;
+ let pipeline_f32 =
+ mtl_context.compute_pipeline_state("moe_router_topk_f32", None)?;
+ let pipeline_bf16 =
+ mtl_context.compute_pipeline_state("moe_router_topk_bf16", None)?;
+ Ok(Self {
+ pipeline_f16,
+ pipeline_f32,
+ pipeline_bf16,
+ })
+ }
+
+ pub fn encode(
+ &self,
+ command_buffer: &CommandBufferRef,
+ dtype: KernelDataType,
+ args: MoeRouterTopKArguments,
+ ) -> Result<(), MoeRouterTopKError> {
+ if args.t == 0 || args.e == 0 || args.k == 0 {
+ return Ok(());
+ }
+ if args.d_model % 4 != 0 {
+ return Err(MoeRouterTopKError::InvalidConfig {
+ t: args.t,
+ d_model: args.d_model,
+ e: args.e,
+ k: args.k,
+ });
+ }
+ if args.e > MAX_EXPERTS || args.k > MAX_TOPK {
+ return Err(MoeRouterTopKError::InvalidConfig {
+ t: args.t,
+ d_model: args.d_model,
+ e: args.e,
+ k: args.k,
+ });
+ }
+
+ let compute_encoder = command_buffer.new_compute_command_encoder();
+ match dtype {
+ KernelDataType::Float16 => {
+ compute_encoder.set_compute_pipeline_state(&self.pipeline_f16)
+ },
+ KernelDataType::Float32 => {
+ compute_encoder.set_compute_pipeline_state(&self.pipeline_f32)
+ },
+ KernelDataType::BFloat16 => {
+ compute_encoder.set_compute_pipeline_state(&self.pipeline_bf16)
+ },
+ }
+
+ compute_encoder.set_buffer(0, Some(args.input_buffer), 0);
+ compute_encoder.set_buffer(1, Some(args.weight_buffer), 0);
+ compute_encoder.set_buffer(2, Some(args.bias_buffer), 0);
+ compute_encoder.set_buffer(3, Some(args.topk_ids_buffer), 0);
+ compute_encoder.set_buffer(4, Some(args.topk_probs_buffer), 0);
+
+ let t_u32 = args.t as u32;
+ let d_u32 = args.d_model as u32;
+ let e_u32 = args.e as u32;
+ let k_u32 = args.k as u32;
+ let renorm_u32: u32 = if args.renorm {
+ 1
+ } else {
+ 0
+ };
+
+ compute_encoder.set_bytes(
+ 5,
+ size_of::<u32>() as u64,
+ &t_u32 as *const u32 as *const _,
+ );
+ compute_encoder.set_bytes(
+ 6,
+ size_of::<u32>() as u64,
+ &d_u32 as *const u32 as *const _,
+ );
+ compute_encoder.set_bytes(
+ 7,
+ size_of::<u32>() as u64,
+ &e_u32 as *const u32 as *const _,
+ );
+ compute_encoder.set_bytes(
+ 8,
+ size_of::<u32>() as u64,
+ &k_u32 as *const u32 as *const _,
+ );
+ compute_encoder.set_bytes(
+ 9,
+ size_of::<u32>() as u64,
+ &renorm_u32 as *const u32 as *const _,
+ );
+
+ let threadgroups = MTLSize::new(1, args.t as u64, 1);
+ let threads_per_tg = MTLSize::new(THREADS_PER_THREADGROUP as u64, 1, 1);
+
+ compute_encoder.dispatch_thread_groups(threadgroups, threads_per_tg);
+ compute_encoder.end_encoding();
+
+ Ok(())
+ }
+}
diff --git a/crates/uzu/src/backends/metal/kernel/moe/scatter.rs b/crates/uzu/src/backends/metal/kernel/moe/scatter.rs
new file mode 100644
index 000000000..b476242f2
--- /dev/null
+++ b/crates/uzu/src/backends/metal/kernel/moe/scatter.rs
@@ -0,0 +1,265 @@
+use std::mem::size_of;
+
+use metal::{
+ Buffer as MTLBuffer, CommandBufferRef,
+ ComputePipelineState as MTLComputePipelineState, MTLSize,
+};
+
+use crate::backends::metal::{KernelDataType, MTLContext};
+
+// ---- Scatter Buckets Kernels ----
+
+#[derive(Debug, thiserror::Error)]
+pub enum MoeScatterError {
+ #[error("Metal error: {0}")]
+ MetalError(#[from] crate::backends::metal::MTLError),
+}
+
+pub struct MoeScatterKernels {
+ pipeline_bases: MTLComputePipelineState,
+ pipeline_scatter_f16: MTLComputePipelineState,
+ pipeline_scatter_f32: MTLComputePipelineState,
+ pipeline_scatter_bf16: MTLComputePipelineState,
+ // map variants
+ pipeline_scatter_map_f16: MTLComputePipelineState,
+ pipeline_scatter_map_f32: MTLComputePipelineState,
+ pipeline_scatter_map_bf16: MTLComputePipelineState,
+}
+
+#[derive(Debug)]
+pub struct MoeBlockBasesArguments<'a> {
+ pub partials_buffer: &'a MTLBuffer, // [num_blocks * num_tiles * 512]
+ pub block_bases_buffer: &'a MTLBuffer, // same shape as partials
+ pub block_alloc_buffer: &'a MTLBuffer, // [num_blocks * num_tiles * 512]
+ pub e: usize,
+ pub num_blocks: usize,
+ pub num_tiles: usize,
+}
+
+#[derive(Debug)]
+pub struct MoeScatterArguments<'a> {
+ pub topk_ids_buffer: &'a MTLBuffer,
+ pub topk_probs_buffer: &'a MTLBuffer,
+ pub offsets_buffer: &'a MTLBuffer,
+ pub block_bases_buffer: &'a MTLBuffer,
+ pub block_alloc_buffer: &'a MTLBuffer,
+ pub out_ids_buffer: &'a MTLBuffer,
+ pub out_probs_buffer: &'a MTLBuffer,
+ pub t: usize,
+ pub e: usize,
+ pub k: usize,
+ pub num_blocks: usize,
+ pub num_tiles: usize,
+}
+
+#[derive(Debug)]
+pub struct MoeScatterWithMapArguments<'a> {
+ pub base: MoeScatterArguments<'a>,
+ pub tok2row_buffer: &'a MTLBuffer, // [T*K] int32, initialized to -1
+}
+
+impl MoeScatterKernels {
+ pub fn new(mtl_context: &MTLContext) -> Result<Self, MoeScatterError> {
+ let pipeline_bases = mtl_context
+ .compute_pipeline_state("moe_block_bases_from_partials", None)?;
+ let pipeline_scatter_f16 = mtl_context
+ .compute_pipeline_state("moe_scatter_buckets_f16", None)?;
+ let pipeline_scatter_f32 = mtl_context
+ .compute_pipeline_state("moe_scatter_buckets_f32", None)?;
+ let pipeline_scatter_bf16 = mtl_context
+ .compute_pipeline_state("moe_scatter_buckets_bf16", None)?;
+ let pipeline_scatter_map_f16 = mtl_context
+ .compute_pipeline_state("moe_scatter_buckets_map_f16", None)?;
+ let pipeline_scatter_map_f32 = mtl_context
+ .compute_pipeline_state("moe_scatter_buckets_map_f32", None)?;
+ let pipeline_scatter_map_bf16 = mtl_context
+ .compute_pipeline_state("moe_scatter_buckets_map_bf16", None)?;
+
+ Ok(Self {
+ pipeline_bases,
+ pipeline_scatter_f16,
+ pipeline_scatter_f32,
+ pipeline_scatter_bf16,
+ pipeline_scatter_map_f16,
+ pipeline_scatter_map_f32,
+ pipeline_scatter_map_bf16,
+ })
+ }
+
+ pub fn encode_block_bases(
+ &self,
+ command_buffer: &CommandBufferRef,
+ args: MoeBlockBasesArguments,
+ ) -> Result<(), MoeScatterError> {
+ let compute_encoder = command_buffer.new_compute_command_encoder();
+ compute_encoder.set_compute_pipeline_state(&self.pipeline_bases);
+ compute_encoder.set_buffer(0, Some(args.partials_buffer), 0);
+ compute_encoder.set_buffer(1, Some(args.block_bases_buffer), 0);
+ compute_encoder.set_buffer(2, Some(args.block_alloc_buffer), 0);
+
+ let e_u32 = args.e as u32;
+ let nb_u32 = args.num_blocks as u32;
+ let nt_u32 = args.num_tiles as u32;
+ let cap_u32: u32 = 0;
+ compute_encoder.set_bytes(
+ 3,
+ size_of::<u32>() as u64,
+ &e_u32 as *const u32 as *const std::ffi::c_void,
+ );
+ compute_encoder.set_bytes(
+ 4,
+ size_of::<u32>() as u64,
+ &nb_u32 as *const u32 as *const std::ffi::c_void,
+ );
+ compute_encoder.set_bytes(
+ 5,
+ size_of::<u32>() as u64,
+ &nt_u32 as *const u32 as *const std::ffi::c_void,
+ );
+ compute_encoder.set_bytes(
+ 6,
+ size_of::<u32>() as u64,
+ &cap_u32 as *const u32 as *const std::ffi::c_void,
+ );
+
+ let total_entries = args.num_tiles * 512usize;
+ let threads_per_threadgroup = MTLSize::new(256, 1, 1);
+ let tg = MTLSize::new(((total_entries + 255) / 256) as u64, 1, 1);
+ if total_entries > 0 {
+ compute_encoder.dispatch_thread_groups(tg, threads_per_threadgroup);
+ }
+ compute_encoder.end_encoding();
+ Ok(())
+ }
+
+ pub fn encode_scatter(
+ &self,
+ command_buffer: &CommandBufferRef,
+ args: MoeScatterArguments,
+ dtype: KernelDataType,
+ ) -> Result<(), MoeScatterError> {
+ let compute_encoder = command_buffer.new_compute_command_encoder();
+ // Select pipeline based on dtype
+ match dtype {
+ KernelDataType::Float16 => {
+ compute_encoder
+ .set_compute_pipeline_state(&self.pipeline_scatter_f16);
+ },
+ KernelDataType::Float32 => {
+ compute_encoder
+ .set_compute_pipeline_state(&self.pipeline_scatter_f32);
+ },
+ KernelDataType::BFloat16 => {
+ compute_encoder
+ .set_compute_pipeline_state(&self.pipeline_scatter_bf16);
+ },
+ }
+ compute_encoder.set_buffer(0, Some(args.topk_ids_buffer), 0);
+ compute_encoder.set_buffer(1, Some(args.topk_probs_buffer), 0);
+ compute_encoder.set_buffer(2, Some(args.offsets_buffer), 0);
+ compute_encoder.set_buffer(3, Some(args.block_bases_buffer), 0);
+ compute_encoder.set_buffer(4, Some(args.block_alloc_buffer), 0);
+ compute_encoder.set_buffer(5, Some(args.out_ids_buffer), 0);
+ compute_encoder.set_buffer(6, Some(args.out_probs_buffer), 0);
+ let t_u32 = args.t as u32;
+ let e_u32 = args.e as u32;
+ let k_u32 = args.k as u32;
+ let nb_u32 = args.num_blocks as u32;
+ let nt_u32 = args.num_tiles as u32;
+ compute_encoder.set_bytes(
+ 7,
+ size_of::<u32>() as u64,
+ &t_u32 as *const u32 as *const std::ffi::c_void,
+ );
+ compute_encoder.set_bytes(
+ 8,
+ size_of::<u32>() as u64,
+ &e_u32 as *const u32 as *const std::ffi::c_void,
+ );
+ compute_encoder.set_bytes(
+ 9,
+ size_of::<u32>() as u64,
+ &k_u32 as *const u32 as *const std::ffi::c_void,
+ );
+ compute_encoder.set_bytes(
+ 10,
+ size_of::<u32>() as u64,
+ &nb_u32 as *const u32 as *const std::ffi::c_void,
+ );
+ compute_encoder.set_bytes(
+ 11,
+ size_of::<u32>() as u64,
+ &nt_u32 as *const u32 as *const std::ffi::c_void,
+ );
+
+ let threads_per_threadgroup = MTLSize::new(256, 1, 1);
+ let tg = MTLSize::new(args.num_blocks as u64, 1, 1);
+ if args.num_blocks > 0 {
+ compute_encoder.dispatch_thread_groups(tg, threads_per_threadgroup);
+ }
+ compute_encoder.end_encoding();
+ Ok(())
+ }
+
+ pub fn encode_scatter_with_map(
+ &self,
+ command_buffer: &CommandBufferRef,
+ args: MoeScatterWithMapArguments,
+ dtype: KernelDataType,
+ ) -> Result<(), MoeScatterError> {
+ let compute_encoder = command_buffer.new_compute_command_encoder();
+ let pipeline = match dtype {
+ KernelDataType::Float16 => &self.pipeline_scatter_map_f16,
+ KernelDataType::Float32 => &self.pipeline_scatter_map_f32,
+ KernelDataType::BFloat16 => &self.pipeline_scatter_map_bf16,
+ };
+ compute_encoder.set_compute_pipeline_state(pipeline);
+ let base = &args.base;
+ compute_encoder.set_buffer(0, Some(base.topk_ids_buffer), 0);
+ compute_encoder.set_buffer(1, Some(base.topk_probs_buffer), 0);
+ compute_encoder.set_buffer(2, Some(base.offsets_buffer), 0);
+ compute_encoder.set_buffer(3, Some(base.block_bases_buffer), 0);
+ compute_encoder.set_buffer(4, Some(base.block_alloc_buffer), 0);
+ compute_encoder.set_buffer(5, Some(base.out_ids_buffer), 0);
+ compute_encoder.set_buffer(6, Some(base.out_probs_buffer), 0);
+ let t_u32 = base.t as u32;
+ let e_u32 = base.e as u32;
+ let k_u32 = base.k as u32;
+ let nb_u32 = base.num_blocks as u32;
+ let nt_u32 = base.num_tiles as u32;
+ compute_encoder.set_bytes(
+ 7,
+ size_of::<u32>() as u64,
+ &t_u32 as *const u32 as *const std::ffi::c_void,
+ );
+ compute_encoder.set_bytes(
+ 8,
+ size_of::<u32>() as u64,
+ &e_u32 as *const u32 as *const std::ffi::c_void,
+ );
+ compute_encoder.set_bytes(
+ 9,
+ size_of::<u32>() as u64,
+ &k_u32 as *const u32 as *const std::ffi::c_void,
+ );
+ compute_encoder.set_bytes(
+ 10,
+ size_of::<u32>() as u64,
+ &nb_u32 as *const u32 as *const std::ffi::c_void,
+ );
+ compute_encoder.set_bytes(
+ 11,
+ size_of::<u32>() as u64,
+ &nt_u32 as *const u32 as *const std::ffi::c_void,
+ );
+ compute_encoder.set_buffer(12, Some(args.tok2row_buffer), 0);
+
+ let threads_per_threadgroup = MTLSize::new(256, 1, 1);
+ let tg = MTLSize::new(base.num_blocks as u64, 1, 1);
+ if base.num_blocks > 0 {
+ compute_encoder.dispatch_thread_groups(tg, threads_per_threadgroup);
+ }
+ compute_encoder.end_encoding();
+ Ok(())
+ }
+}
diff --git a/crates/uzu/src/backends/metal/kernel/moe/scatter_buckets.metal b/crates/uzu/src/backends/metal/kernel/moe/scatter_buckets.metal
new file mode 100644
index 000000000..d55ca893b
--- /dev/null
+++ b/crates/uzu/src/backends/metal/kernel/moe/scatter_buckets.metal
@@ -0,0 +1,213 @@
+#include <metal_stdlib>
+#include <metal_atomic>
+using namespace metal;
+
+#define BLOCK_SIZE 256
+#define TILE_E 512
+#define SIMD_WIDTH 32
+#define NUM_SG (BLOCK_SIZE / SIMD_WIDTH)
+
+// 4A: Compute per-block base offsets from partials
+// partials layout: index = (block_id * num_tiles + tile_id) * TILE_E + te
+kernel void moe_block_bases_from_partials(
+ device const uint* partials [[buffer(0)]],
+ device uint* block_bases [[buffer(1)]],
+ device uint* block_alloc [[buffer(2)]],
+ constant uint& E [[buffer(3)]],
+ constant uint& num_blocks [[buffer(4)]],
+ constant uint& num_tiles [[buffer(5)]],
+ constant uint& capacity_per_expert [[buffer(6)]], // 0 => no clamp
+ uint gid [[thread_position_in_grid]])
+{
+ const uint entries = num_tiles * TILE_E;
+ if (gid >= entries) return;
+ const uint tile_id = gid / TILE_E;
+ const uint te = gid % TILE_E;
+ const uint e = tile_id * TILE_E + te;
+ if (e >= E) return;
+
+ uint running = 0u;
+ const bool clamp = (capacity_per_expert > 0u);
+ for (uint b = 0; b < num_blocks; ++b) {
+ const uint idx = (b * num_tiles + tile_id) * TILE_E + te;
+ const uint p = partials[idx];
+ const uint alloc = clamp ? (running < capacity_per_expert ? min(p, capacity_per_expert - running) : 0u) : p;
+ block_bases[idx] = running;
+ block_alloc[idx] = alloc;
+ running += alloc;
+ if (clamp && running >= capacity_per_expert) {
+ // Remainder allocate zero and base stays at capacity
+ for (uint bb = b + 1; bb < num_blocks; ++bb) {
+ const uint idx2 = (bb * num_tiles + tile_id) * TILE_E + te;
+ block_bases[idx2] = running;
+ block_alloc[idx2] = 0u;
+ }
+ break;
+ }
+ }
+}
+
+// 4B: Scatter into expert-major buckets using atomic-free device writes
+template <typename ProbT>
+inline void moe_scatter_buckets_impl(
+ device const int* topk_ids,
+ device const ProbT* topk_probs,
+ device const uint* offsets,
+ device const uint* block_bases,
+ device const uint* block_alloc,
+ device int* out_ids,
+ device ProbT* out_probs,
+ device int* tok2row_opt,
+ uint T, uint E, uint K,
+ uint num_blocks, uint num_tiles,
+ uint3 tid3, uint lid, uint3 tgpig,
+ threadgroup _atomic<uint>* sg_counts,
+ threadgroup uint* sg_base)
+{
+ if (E == 0 || T == 0 || K == 0) return;
+ const uint block_id = tgpig.x;
+ const uint t_start = block_id * BLOCK_SIZE;
+ const uint t_end = min(t_start + BLOCK_SIZE, T);
+ const uint sg_id = lid / SIMD_WIDTH;
+ const uint lane = lid % SIMD_WIDTH;
+
+ // Per-tile processing
+ for (uint e0 = 0; e0 < E; e0 += TILE_E) {
+ const uint tile_e = (e0 + TILE_E <= E) ? TILE_E : (E - e0);
+
+ // Zero counts and bases for active tile
+ for (uint te = lid; te < tile_e; te += BLOCK_SIZE) {
+ for (uint sg = 0; sg < NUM_SG; ++sg) {
+ atomic_store_explicit(&sg_counts[sg * TILE_E + te], 0u, memory_order_relaxed);
+ sg_base[sg * TILE_E + te] = 0u;
+ }
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ // Phase 1: per-sg counting using threadgroup atomics (order-independent)
+ for (uint t = t_start + lid; t < t_end; t += BLOCK_SIZE) {
+ const uint base = t * K;
+ for (uint k = 0; k < K; ++k) {
+ int eid = topk_ids[base + k];
+ if (eid >= 0) {
+ const uint ue = (uint)eid;
+ if (ue >= e0 && ue < e0 + tile_e) {
+ const uint te = ue - e0;
+ atomic_fetch_add_explicit(&sg_counts[sg_id * TILE_E + te], 1u, memory_order_relaxed);
+ }
+ }
+ }
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ // Phase 2: compute per-sg bases via prefix across sgs with capacity clamp
+ for (uint te = lid; te < tile_e; te += BLOCK_SIZE) {
+ const uint tile_id = e0 / TILE_E;
+ const uint base_idx_block = (block_id * num_tiles + tile_id) * TILE_E + te;
+ const uint alloc_total = block_alloc[base_idx_block];
+ uint prefix = 0u;
+ for (uint sg = 0; sg < NUM_SG; ++sg) {
+ const uint idx = sg * TILE_E + te;
+ const uint c = atomic_load_explicit(&sg_counts[idx], memory_order_relaxed);
+ const uint room = (prefix < alloc_total) ? (alloc_total - prefix) : 0u;
+ const uint take = min(c, room);
+ sg_base[idx] = prefix;
+ prefix += take;
+ }
+ // Reuse sg_counts as write indices: reset to zero
+ for (uint sg = 0; sg < NUM_SG; ++sg) {
+ atomic_store_explicit(&sg_counts[sg * TILE_E + te], 0u, memory_order_relaxed);
+ }
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ // Phase 3: deterministic write with 32-lane sequencing, no device atomics
+ for (uint step = 0; step < SIMD_WIDTH; ++step) {
+ if (lane == step) {
+ const uint t = t_start + lid;
+ if (t < t_end) {
+ const uint base = t * K;
+ for (uint k = 0; k < K; ++k) {
+ int eid = topk_ids[base + k];
+ if (eid >= 0) {
+ const uint ue = (uint)eid;
+ if (ue >= e0 && ue < e0 + tile_e) {
+ const uint te = ue - e0;
+ const uint tile_id = e0 / TILE_E;
+ const uint base_idx_block = (block_id * num_tiles + tile_id) * TILE_E + te;
+ const uint idx_sg_te = sg_id * TILE_E + te;
+ const uint local = atomic_fetch_add_explicit(&sg_counts[idx_sg_te], 1u, memory_order_relaxed);
+ const uint base_s = sg_base[idx_sg_te];
+
+ const uint slot = offsets[ue] + block_bases[base_idx_block] + base_s + local;
+ out_ids[slot] = (int)t;
+ out_probs[slot] = topk_probs[base + k];
+ if (tok2row_opt != nullptr) {
+ tok2row_opt[base + k] = (int)slot;
+ }
+ }
+ }
+ }
+ }
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ }
+}
+
+#define DEFINE_MOE_SCATTER_BUCKETS_KERNEL(SUFFIX, ProbT) \
+kernel void moe_scatter_buckets_##SUFFIX( \
+ device const int* topk_ids [[buffer(0)]], \
+ device const ProbT* topk_probs [[buffer(1)]], \
+ device const uint* offsets [[buffer(2)]], \
+ device const uint* block_bases [[buffer(3)]], \
+ device const uint* block_alloc [[buffer(4)]], \
+ device int* out_ids [[buffer(5)]], \
+ device ProbT* out_probs [[buffer(6)]], \
+ constant uint& T [[buffer(7)]], \
+ constant uint& E [[buffer(8)]], \
+ constant uint& K [[buffer(9)]], \
+ constant uint& num_blocks [[buffer(10)]], \
+ constant uint& num_tiles [[buffer(11)]], \
+ uint3 tid3 [[thread_position_in_grid]], \
+ uint lid [[thread_index_in_threadgroup]], \
+ uint3 tgpig [[threadgroup_position_in_grid]]) \
+{ \
+ threadgroup _atomic<uint> sg_counts[NUM_SG * TILE_E]; \
+ threadgroup uint sg_base [NUM_SG * TILE_E]; \
+ moe_scatter_buckets_impl<ProbT>(topk_ids, topk_probs, offsets, block_bases, block_alloc, out_ids, out_probs, (device int*)nullptr, T, E, K, num_blocks, num_tiles, tid3, lid, tgpig, sg_counts, sg_base); \
+}
+
+DEFINE_MOE_SCATTER_BUCKETS_KERNEL(f16, half)
+DEFINE_MOE_SCATTER_BUCKETS_KERNEL(f32, float)
+DEFINE_MOE_SCATTER_BUCKETS_KERNEL(bf16, bfloat)
+
+// Map variants
+#define DEFINE_MOE_SCATTER_BUCKETS_MAP_KERNEL(SUFFIX, ProbT) \
+kernel void moe_scatter_buckets_map_##SUFFIX( \
+ device const int* topk_ids [[buffer(0)]], \
+ device const ProbT* topk_probs [[buffer(1)]], \
+ device const uint* offsets [[buffer(2)]], \
+ device const uint* block_bases [[buffer(3)]], \
+ device const uint* block_alloc [[buffer(4)]], \
+ device int* out_ids [[buffer(5)]], \
+ device ProbT* out_probs [[buffer(6)]], \
+ constant uint& T [[buffer(7)]], \
+ constant uint& E [[buffer(8)]], \
+ constant uint& K [[buffer(9)]], \
+ constant uint& num_blocks [[buffer(10)]], \
+ constant uint& num_tiles [[buffer(11)]], \
+ device int* tok2row [[buffer(12)]], \
+ uint3 tid3 [[thread_position_in_grid]], \
+ uint lid [[thread_index_in_threadgroup]], \
+ uint3 tgpig [[threadgroup_position_in_grid]]) \
+{ \
+ threadgroup _atomic<uint> sg_counts[NUM_SG * TILE_E]; \
+ threadgroup uint sg_base [NUM_SG * TILE_E]; \
+ moe_scatter_buckets_impl<ProbT>(topk_ids, topk_probs, offsets, block_bases, block_alloc, out_ids, out_probs, tok2row, T, E, K, num_blocks, num_tiles, tid3, lid, tgpig, sg_counts, sg_base); \
+}
+
+DEFINE_MOE_SCATTER_BUCKETS_MAP_KERNEL(f16, half)
+DEFINE_MOE_SCATTER_BUCKETS_MAP_KERNEL(f32, float)
+DEFINE_MOE_SCATTER_BUCKETS_MAP_KERNEL(bf16, bfloat)
diff --git a/crates/uzu/src/backends/metal/kernel/moe/tiles.metal b/crates/uzu/src/backends/metal/kernel/moe/tiles.metal
new file mode 100644
index 000000000..f57eff6f8
--- /dev/null
+++ b/crates/uzu/src/backends/metal/kernel/moe/tiles.metal
@@ -0,0 +1,109 @@
+#include <metal_stdlib>
+#include <metal_atomic>
+using namespace metal;
+
+#define BM 16
+
+// Compute per-expert tile counts: tiles_e = ceil((seg_len)/BM)
+kernel void moe_tile_counts(
+ device const uint* offsets [[buffer(0)]], // [E+1]
+ device uint* tile_counts [[buffer(1)]], // [E]
+ constant uint& E [[buffer(2)]],
+ uint gid [[thread_position_in_grid]])
+{
+ if (gid >= E) return;
+ const uint start = offsets[gid];
+ const uint end = offsets[gid + 1];
+ const uint seg_len = (end > start) ? (end - start) : 0u;
+ const uint tiles = (seg_len == 0u) ? 0u : ((seg_len + BM - 1u) / BM);
+ tile_counts[gid] = tiles;
+}
+
+// Single-threadgroup exclusive scan over tile_counts -> tile_row_offsets, also writes total_tiles
+kernel void moe_tile_scan(
+ device const uint* tile_counts [[buffer(0)]], // [E]
+ device uint* tile_row_offsets [[buffer(1)]], // [E+1]
+ device uint* total_tiles_buf [[buffer(2)]], // [>=2]
+ constant uint& E [[buffer(3)]],
+ uint tid [[thread_index_in_threadgroup]])
+{
+ threadgroup uint scratch[1024]; // supports up to E<=1023
+ if (tid < E) {
+ scratch[tid] = tile_counts[tid];
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ // Inclusive scan in-place over scratch
+ // Simple O(log E) scan; E is small
+ for (uint offset = 1u; offset < E; offset <<= 1u) {
+ uint val = 0u;
+ if (tid < E) {
+ val = scratch[tid];
+ if (tid >= offset) {
+ val += scratch[tid - offset];
+ }
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ if (tid < E) {
+ scratch[tid] = val;
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ }
+
+ if (tid == 0u) {
+ tile_row_offsets[0] = 0u;
+ }
+ if (tid < E) {
+ // exclusive: shift right by one
+ const uint prefix = (tid == 0u) ? 0u : scratch[tid - 1u];
+ tile_row_offsets[tid] = prefix;
+ }
+ if (tid == 0u) {
+ tile_row_offsets[E] = (E == 0u) ? 0u : scratch[E - 1u];
+ total_tiles_buf[0] = tile_row_offsets[E];
+ total_tiles_buf[1] = 0u;
+ total_tiles_buf[2] = 0u;
+ total_tiles_buf[3] = 0u;
+ total_tiles_buf[4] = 0u;
+ total_tiles_buf[5] = 0u;
+ total_tiles_buf[6] = 0u;
+ total_tiles_buf[7] = 0u;
+ }
+}
+
+// Build flattened tile_map of length total_tiles; each entry is 3 uints:
+// [3*i+0]=expert_idx, [3*i+1]=seg_start, [3*i+2]=tile_m0
+kernel void moe_build_tile_map(
+ device const uint* offsets [[buffer(0)]], // [E+1]
+ device const uint* tile_row_offsets [[buffer(1)]], // [E+1]
+ device const uint* tile_counts [[buffer(2)]], // [E]
+ device uint* tile_map [[buffer(3)]], // [3*total_tiles]
+ constant uint& E [[buffer(4)]],
+ uint gid [[thread_position_in_grid]])
+{
+ if (gid >= E) return;
+ const uint start = offsets[gid];
+ const uint tiles = tile_counts[gid];
+ const uint base = tile_row_offsets[gid];
+ for (uint t = 0u; t < tiles; ++t) {
+ const uint idx = base + t;
+ tile_map[3u * idx + 0u] = gid;
+ tile_map[3u * idx + 1u] = start;
+ tile_map[3u * idx + 2u] = t * BM;
+ }
+}
+
+// Write MTLDispatchThreadgroupsIndirectArguments {x, y, z} where:
+// x = num_tiles_n (computed on CPU and passed in), y = total_tiles, z = 1
+kernel void moe_write_dispatch_args(
+ device const uint* total_tiles_buf [[buffer(0)]], // [>=1], total_tiles_buf[0] = total_rows
+ device uint* dispatch_args [[buffer(1)]], // [3] u32
+ constant uint& num_tiles_n [[buffer(2)]], // x dimension
+ uint gid [[thread_position_in_grid]])
+{
+ if (gid > 0u) return;
+ const uint total_rows = total_tiles_buf[0];
+ dispatch_args[0] = num_tiles_n; // x
+ dispatch_args[1] = total_rows; // y
+ dispatch_args[2] = 1u; // z
+}
diff --git a/crates/uzu/src/backends/metal/kernel/moe/tiles.rs b/crates/uzu/src/backends/metal/kernel/moe/tiles.rs
new file mode 100644
index 000000000..fa33deb1d
--- /dev/null
+++ b/crates/uzu/src/backends/metal/kernel/moe/tiles.rs
@@ -0,0 +1,367 @@
+use std::mem::size_of;
+
+use metal::{
+ Buffer as MTLBuffer, CommandBufferRef,
+ ComputePipelineState as MTLComputePipelineState, MTLSize,
+};
+
+use crate::backends::metal::{MTLContext, MTLError};
+
+// ---- Tile Kernels ----
+
+#[derive(Debug, thiserror::Error)]
+pub enum MoeTileError {
+ #[error("Metal error: {0}")]
+ MetalError(#[from] MTLError),
+}
+
+/// Arguments for tile counts encoder
+pub struct MoeTileCountsArguments<'a> {
+ pub offsets_buffer: &'a MTLBuffer, // [E+1]
+ pub tile_counts_buffer: &'a MTLBuffer, // [E]
+ pub e: usize,
+}
+
+/// Arguments for tile scan encoder
+pub struct MoeTileScanArguments<'a> {
+ pub tile_counts_buffer: &'a MTLBuffer, // [E]
+ pub tile_offsets_buffer: &'a MTLBuffer, // [E+1]
+ pub total_tiles_buffer: &'a MTLBuffer, // [>=2]
+ pub e: usize,
+}
+
+#[derive(Debug)]
+pub struct MoeTileMapBuildArguments<'a> {
+ pub expert_offsets: &'a MTLBuffer, // [E+1]
+ pub tile_offsets: &'a MTLBuffer, // [E+1]
+ pub tile_counts: &'a MTLBuffer, // [E]
+ pub tile_map: &'a MTLBuffer, // [total_tiles * 3]
+ pub e: usize,
+}
+
+#[derive(Debug)]
+pub struct MoeTileDispatchArguments<'a> {
+ pub total_tiles: &'a MTLBuffer, // [>=1]
+ pub dispatch_args: &'a MTLBuffer, // [3]
+ pub num_tiles_x: u32, // x dimension for indirect dispatch
+}
+
+pub struct MoeTileMapKernel {
+ counts_pipeline: MTLComputePipelineState,
+ scan_pipeline: MTLComputePipelineState,
+ build_pipeline: MTLComputePipelineState,
+ dispatch_pipeline: MTLComputePipelineState,
+}
+
+#[derive(Debug)]
+pub struct MoePassATileCountsArguments<'a> {
+ pub expert_offsets: &'a MTLBuffer, // [E+1]
+ pub tile_counts: &'a MTLBuffer, // [E]
+ pub e: usize,
+ pub h_blocks: u32,
+}
+
+#[derive(Debug)]
+pub struct MoePassATileScanArguments<'a> {
+ pub tile_counts: &'a MTLBuffer, // [E]
+ pub tile_offsets: &'a MTLBuffer, // [E+1]
+ pub total_tiles: &'a MTLBuffer, // [>=1]
+ pub e: usize,
+}
+
+#[derive(Debug)]
+pub struct MoePassARowMapArguments<'a> {
+ pub expert_offsets: &'a MTLBuffer, // [E+1]
+ pub row_expert_map: &'a MTLBuffer, // [total_rows]
+ pub total_rows: usize,
+ pub e: usize,
+}
+
+#[derive(Debug)]
+pub struct MoePassATileBuildArguments<'a> {
+ pub expert_offsets: &'a MTLBuffer, // [E+1]
+ pub tile_offsets: &'a MTLBuffer, // [E+1]
+ pub row_expert_map: &'a MTLBuffer, // [total_rows]
+ pub tile_map: &'a MTLBuffer, // [total_tiles * 3]
+ pub total_rows: usize,
+ pub h_blocks: u32,
+}
+
+#[derive(Debug)]
+pub struct MoePassATileDispatchArguments<'a> {
+ pub total_tiles: &'a MTLBuffer, // [>=1]
+ pub dispatch_args: &'a MTLBuffer, // [3]
+ pub num_tiles_y: u32,
+}
+
+pub struct MoePassATileKernel {
+ counts_pipeline: MTLComputePipelineState,
+ scan_pipeline: MTLComputePipelineState,
+ row_map_pipeline: MTLComputePipelineState,
+ build_pipeline: MTLComputePipelineState,
+ dispatch_pipeline: MTLComputePipelineState,
+}
+
+impl MoePassATileKernel {
+ pub fn new(ctx: &MTLContext) -> Result<Self, MoeTileError> {
+ Ok(Self {
+ counts_pipeline: ctx
+ .compute_pipeline_state("moe_pass_a_tile_counts", None)?,
+ scan_pipeline: ctx
+ .compute_pipeline_state("moe_pass_a_tile_scan", None)?,
+ row_map_pipeline: ctx
+ .compute_pipeline_state("moe_pass_a_build_row_map", None)?,
+ build_pipeline: ctx
+ .compute_pipeline_state("moe_pass_a_build_tile_map", None)?,
+ dispatch_pipeline: ctx.compute_pipeline_state(
+ "moe_pass_a_write_dispatch_args",
+ None,
+ )?,
+ })
+ }
+
+ pub fn encode_counts(
+ &self,
+ command_buffer: &CommandBufferRef,
+ args: &MoePassATileCountsArguments,
+ ) -> Result<(), MoeTileError> {
+ let encoder = command_buffer.new_compute_command_encoder();
+ encoder.set_compute_pipeline_state(&self.counts_pipeline);
+ encoder.set_buffer(0, Some(args.expert_offsets), 0);
+ encoder.set_buffer(1, Some(args.tile_counts), 0);
+ let e_u32 = args.e as u32;
+ encoder.set_bytes(
+ 2,
+ size_of::<u32>() as u64,
+ &e_u32 as *const u32 as *const _,
+ );
+ encoder.set_bytes(
+ 3,
+ size_of::<u32>() as u64,
+ &args.h_blocks as *const u32 as *const _,
+ );
+ encoder.dispatch_thread_groups(
+ MTLSize::new(((args.e + 255) / 256) as u64, 1, 1),
+ MTLSize::new(256, 1, 1),
+ );
+ encoder.end_encoding();
+ Ok(())
+ }
+
+ pub fn encode_scan(
+ &self,
+ command_buffer: &CommandBufferRef,
+ args: &MoePassATileScanArguments,
+ ) -> Result<(), MoeTileError> {
+ let encoder = command_buffer.new_compute_command_encoder();
+ encoder.set_compute_pipeline_state(&self.scan_pipeline);
+ encoder.set_buffer(0, Some(args.tile_counts), 0);
+ encoder.set_buffer(1, Some(args.tile_offsets), 0);
+ encoder.set_buffer(2, Some(args.total_tiles), 0);
+ let e_u32 = args.e as u32;
+ encoder.set_bytes(
+ 3,
+ size_of::<u32>() as u64,
+ &e_u32 as *const u32 as *const _,
+ );
+ encoder
+ .set_threadgroup_memory_length(0, (1024 * size_of::<u32>()) as u64);
+ encoder.dispatch_thread_groups(
+ MTLSize::new(1, 1, 1),
+ MTLSize::new(1024, 1, 1),
+ );
+ encoder.end_encoding();
+ Ok(())
+ }
+
+ pub fn encode_row_map(
+ &self,
+ command_buffer: &CommandBufferRef,
+ args: &MoePassARowMapArguments,
+ ) -> Result<(), MoeTileError> {
+ let encoder = command_buffer.new_compute_command_encoder();
+ encoder.set_compute_pipeline_state(&self.row_map_pipeline);
+ encoder.set_buffer(0, Some(args.expert_offsets), 0);
+ encoder.set_buffer(1, Some(args.row_expert_map), 0);
+ let total_rows_u32 = args.total_rows as u32;
+ let e_u32 = args.e as u32;
+ encoder.set_bytes(
+ 2,
+ size_of::<u32>() as u64,
+ &total_rows_u32 as *const u32 as *const _,
+ );
+ encoder.set_bytes(
+ 3,
+ size_of::<u32>() as u64,
+ &e_u32 as *const u32 as *const _,
+ );
+ encoder.dispatch_thread_groups(
+ MTLSize::new(((args.total_rows + 255) / 256) as u64, 1, 1),
+ MTLSize::new(256, 1, 1),
+ );
+ encoder.end_encoding();
+ Ok(())
+ }
+
+ pub fn encode_build_map(
+ &self,
+ command_buffer: &CommandBufferRef,
+ args: &MoePassATileBuildArguments,
+ ) -> Result<(), MoeTileError> {
+ let encoder = command_buffer.new_compute_command_encoder();
+ encoder.set_compute_pipeline_state(&self.build_pipeline);
+ encoder.set_buffer(0, Some(args.expert_offsets), 0);
+ encoder.set_buffer(1, Some(args.tile_offsets), 0);
+ encoder.set_buffer(2, Some(args.row_expert_map), 0);
+ encoder.set_buffer(3, Some(args.tile_map), 0);
+ let total_rows_u32 = args.total_rows as u32;
+ encoder.set_bytes(
+ 4,
+ size_of::<u32>() as u64,
+ &total_rows_u32 as *const u32 as *const _,
+ );
+ encoder.set_bytes(
+ 5,
+ size_of::<u32>() as u64,
+ &args.h_blocks as *const u32 as *const _,
+ );
+ let total_tiles_linear =
+ (total_rows_u32 as u64).saturating_mul(args.h_blocks as u64);
+ encoder.dispatch_thread_groups(
+ MTLSize::new(((total_tiles_linear + 255) / 256) as u64, 1, 1),
+ MTLSize::new(256, 1, 1),
+ );
+ encoder.end_encoding();
+ Ok(())
+ }
+
+ pub fn encode_dispatch_args(
+ &self,
+ command_buffer: &CommandBufferRef,
+ args: &MoePassATileDispatchArguments,
+ ) -> Result<(), MoeTileError> {
+ let encoder = command_buffer.new_compute_command_encoder();
+ encoder.set_compute_pipeline_state(&self.dispatch_pipeline);
+ encoder.set_buffer(0, Some(args.total_tiles), 0);
+ encoder.set_buffer(1, Some(args.dispatch_args), 0);
+ encoder.set_bytes(
+ 2,
+ size_of::<u32>() as u64,
+ &args.num_tiles_y as *const u32 as *const _,
+ );
+ encoder.dispatch_thread_groups(
+ MTLSize::new(1, 1, 1),
+ MTLSize::new(1, 1, 1),
+ );
+ encoder.end_encoding();
+ Ok(())
+ }
+}
+
+impl MoeTileMapKernel {
+ pub fn new(ctx: &MTLContext) -> Result<Self, MoeTileError> {
+ Ok(Self {
+ counts_pipeline: ctx
+ .compute_pipeline_state("moe_tile_counts", None)?,
+ scan_pipeline: ctx.compute_pipeline_state("moe_tile_scan", None)?,
+ build_pipeline: ctx
+ .compute_pipeline_state("moe_build_tile_map", None)?,
+ dispatch_pipeline: ctx
+ .compute_pipeline_state("moe_write_dispatch_args", None)?,
+ })
+ }
+
+ pub fn encode_counts(
+ &self,
+ command_buffer: &CommandBufferRef,
+ args: &MoeTileCountsArguments,
+ ) -> Result<(), MoeTileError> {
+ let encoder = command_buffer.new_compute_command_encoder();
+ encoder.set_compute_pipeline_state(&self.counts_pipeline);
+ encoder.set_buffer(0, Some(args.offsets_buffer), 0);
+ encoder.set_buffer(1, Some(args.tile_counts_buffer), 0);
+ let e_u32 = args.e as u32;
+ encoder.set_bytes(
+ 2,
+ size_of::<u32>() as u64,
+ &e_u32 as *const u32 as *const _,
+ );
+ encoder.dispatch_thread_groups(
+ MTLSize::new(((args.e + 255) / 256) as u64, 1, 1),
+ MTLSize::new(256, 1, 1),
+ );
+ encoder.end_encoding();
+ Ok(())
+ }
+
+ pub fn encode_scan(
+ &self,
+ command_buffer: &CommandBufferRef,
+ args: &MoeTileScanArguments,
+ ) -> Result<(), MoeTileError> {
+ let encoder = command_buffer.new_compute_command_encoder();
+ encoder.set_compute_pipeline_state(&self.scan_pipeline);
+ encoder.set_buffer(0, Some(args.tile_counts_buffer), 0);
+ encoder.set_buffer(1, Some(args.tile_offsets_buffer), 0);
+ encoder.set_buffer(2, Some(args.total_tiles_buffer), 0);
+ let e_u32 = args.e as u32;
+ encoder.set_bytes(
+ 3,
+ size_of::<u32>() as u64,
+ &e_u32 as *const u32 as *const _,
+ );
+ encoder.dispatch_thread_groups(
+ MTLSize::new(1, 1, 1),
+ MTLSize::new(256, 1, 1),
+ );
+ encoder.end_encoding();
+ Ok(())
+ }
+
+ pub fn encode_build_map(
+ &self,
+ command_buffer: &CommandBufferRef,
+ args: &MoeTileMapBuildArguments,
+ ) -> Result<(), MoeTileError> {
+ let encoder = command_buffer.new_compute_command_encoder();
+ encoder.set_compute_pipeline_state(&self.build_pipeline);
+ encoder.set_buffer(0, Some(args.expert_offsets), 0);
+ encoder.set_buffer(1, Some(args.tile_offsets), 0);
+ encoder.set_buffer(2, Some(args.tile_counts), 0);
+ encoder.set_buffer(3, Some(args.tile_map), 0);
+ let e_u32 = args.e as u32;
+ encoder.set_bytes(
+ 4,
+ size_of::<u32>() as u64,
+ &e_u32 as *const u32 as *const _,
+ );
+ encoder.dispatch_thread_groups(
+ MTLSize::new(((args.e + 255) / 256) as u64, 1, 1),
+ MTLSize::new(256, 1, 1),
+ );
+ encoder.end_encoding();
+ Ok(())
+ }
+
+ pub fn encode_dispatch_args(
+ &self,
+ command_buffer: &CommandBufferRef,
+ args: &MoeTileDispatchArguments,
+ ) -> Result<(), MoeTileError> {
+ let encoder = command_buffer.new_compute_command_encoder();
+ encoder.set_compute_pipeline_state(&self.dispatch_pipeline);
+ encoder.set_buffer(0, Some(args.total_tiles), 0);
+ encoder.set_buffer(1, Some(args.dispatch_args), 0);
+ encoder.set_bytes(
+ 2,
+ size_of::<u32>() as u64,
+ &args.num_tiles_x as *const u32 as *const _,
+ );
+ encoder.dispatch_thread_groups(
+ MTLSize::new(1, 1, 1),
+ MTLSize::new(1, 1, 1),
+ );
+ encoder.end_encoding();
+ Ok(())
+ }
+}
diff --git a/crates/uzu/src/backends/metal/kernel/moe/topk_select.metal b/crates/uzu/src/backends/metal/kernel/moe/topk_select.metal
new file mode 100644
index 000000000..a0f1c85f6
--- /dev/null
+++ b/crates/uzu/src/backends/metal/kernel/moe/topk_select.metal
@@ -0,0 +1,155 @@
+#include <metal_stdlib>
+#include "../definitions.metal"
+using namespace metal;
+
+constant uint THREADS_PER_TG = 128;
+constant uint MAX_EXPERTS = 512;
+constant uint MAX_TOPK = 128;
+constant float NEG_INF = -INFINITY;
+
+template<typename LogitT, typename ProbT>
+inline void moe_topk_select_impl(
+ device const LogitT* logits,
+ device int* topk_ids,
+ device ProbT* topk_probs,
+ uint T,
+ uint E,
+ uint K,
+ uint renorm,
+ ushort lid,
+ uint token,
+ threadgroup float* tg_logits,
+ threadgroup uint* tg_indices,
+ threadgroup float* reduce_tmp,
+ threadgroup uint* reduce_tmp_u,
+ threadgroup float* selected_vals,
+ threadgroup uint* selected_ids)
+{
+ if (token >= T || K == 0) {
+ return;
+ }
+
+ const uint effective_k = min(K, MAX_TOPK);
+
+ for (uint i = lid; i < MAX_EXPERTS; i += THREADS_PER_TG) {
+ if (i < E) {
+ tg_logits[i] = float(logits[token * E + i]);
+ } else {
+ tg_logits[i] = NEG_INF;
+ }
+ tg_indices[i] = i;
+ }
+
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ const uint selections = min(effective_k, E);
+ for (uint sel = 0; sel < selections; ++sel) {
+ float local_best_val = NEG_INF;
+ uint local_best_idx = 0xFFFFFFFFu;
+
+ for (uint i = lid; i < E; i += THREADS_PER_TG) {
+ float candidate = tg_logits[i];
+ if (candidate > local_best_val ||
+ (candidate == local_best_val && i < local_best_idx)) {
+ local_best_val = candidate;
+ local_best_idx = i;
+ }
+ }
+
+ float max_val = threadgroup_cooperative_reduce_max<THREADS_PER_TG>(
+ local_best_val,
+ reduce_tmp,
+ lid);
+
+ uint candidate_id =
+ (local_best_val == max_val) ? local_best_idx : 0xFFFFFFFFu;
+ uint best_idx = threadgroup_cooperative_reduce_min<THREADS_PER_TG>(
+ candidate_id,
+ reduce_tmp_u,
+ lid);
+
+ if (lid == 0) {
+ selected_vals[sel] = max_val;
+ selected_ids[sel] = best_idx;
+ tg_logits[best_idx] = NEG_INF;
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ }
+
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ if (lid == 0) {
+ device int* out_ids = topk_ids + token * K;
+ device ProbT* out_probs = topk_probs + token * K;
+
+ const uint written = selections;
+ for (uint i = 0; i < written; ++i) {
+ out_ids[i] = int(selected_ids[i]);
+ }
+ for (uint i = written; i < K; ++i) {
+ out_ids[i] = 0;
+ }
+
+ if (renorm != 0 && written > 0) {
+ float max_logit = -INFINITY;
+ for (uint i = 0; i < written; ++i) {
+ max_logit = fmax(max_logit, selected_vals[i]);
+ }
+
+ float exp_values[MAX_TOPK];
+ float sum_exp = 0.0f;
+ for (uint i = 0; i < written; ++i) {
+ float e_val = exp(selected_vals[i] - max_logit);
+ exp_values[i] = e_val;
+ sum_exp += e_val;
+ }
+
+ float default_prob = 1.0f / float(written);
+ float inv_sum =
+ (sum_exp > 0.0f) ? (1.0f / sum_exp) : default_prob;
+
+ for (uint i = 0; i < written; ++i) {
+ float prob = (sum_exp > 0.0f) ? (exp_values[i] * inv_sum)
+ : default_prob;
+ out_probs[i] = ProbT(prob);
+ }
+ for (uint i = written; i < K; ++i) {
+ out_probs[i] = ProbT(0.0f);
+ }
+ } else {
+ for (uint i = 0; i < written; ++i) {
+ out_probs[i] = ProbT(selected_vals[i]);
+ }
+ for (uint i = written; i < K; ++i) {
+ out_probs[i] = ProbT(0.0f);
+ }
+ }
+ }
+}
+
+#define DEFINE_MOE_TOPK_KERNEL(LOGIT_T, PROB_T, SUFFIX) \
+kernel void moe_topk_select_##SUFFIX( \
+ device const LOGIT_T* logits [[buffer(0)]], \
+ device int* topk_ids [[buffer(1)]], \
+ device PROB_T* topk_probs [[buffer(2)]], \
+ constant uint& T [[buffer(3)]], \
+ constant uint& E [[buffer(4)]], \
+ constant uint& K [[buffer(5)]], \
+ constant uint& renorm [[buffer(6)]], \
+ ushort lid [[thread_index_in_threadgroup]], \
+ uint3 tgpig [[threadgroup_position_in_grid]]) \
+{ \
+ threadgroup float tg_logits[MAX_EXPERTS]; \
+ threadgroup uint tg_indices[MAX_EXPERTS]; \
+ threadgroup float reduce_tmp[THREADS_PER_TG]; \
+ threadgroup uint reduce_tmp_u[THREADS_PER_TG]; \
+ threadgroup float selected_vals[MAX_TOPK]; \
+ threadgroup uint selected_ids[MAX_TOPK]; \
+ moe_topk_select_impl<LOGIT_T, PROB_T>( \
+ logits, topk_ids, topk_probs, T, E, K, renorm, lid, tgpig.x, \
+ tg_logits, tg_indices, reduce_tmp, reduce_tmp_u, selected_vals, selected_ids); \
+}
+
+DEFINE_MOE_TOPK_KERNEL(half, half, f16)
+DEFINE_MOE_TOPK_KERNEL(float, half, f32)
+DEFINE_MOE_TOPK_KERNEL(bfloat, bfloat, bf16)
diff --git a/crates/uzu/src/backends/metal/kernel/quant_matmul/mma.h b/crates/uzu/src/backends/metal/kernel/quant_matmul/mma.h
index 9be4dee9b..b75b3241c 100644
--- a/crates/uzu/src/backends/metal/kernel/quant_matmul/mma.h
+++ b/crates/uzu/src/backends/metal/kernel/quant_matmul/mma.h
@@ -21,6 +21,11 @@ struct pointer_element_t_impl<device T*> {
using type = T;
};
template<typename T>
+struct pointer_element_t_impl<threadgroup T*> {
+ using type = T;
+};
+template<typename T>
+
using pointer_element_t = typename pointer_element_t_impl<T>::type;
template <typename T, typename U = T>
@@ -237,6 +242,21 @@ struct MMATile {
}
}
+ // Store results into threadgroup memory (same layout as device variant)
+ template <typename U, int w_x, int w_y>
+ METAL_FUNC void store_tg(threadgroup U* dst, const int ld) const {
+ UZU_PRAGMA_UNROLL
+ for (short i = 0; i < kTileRows; ++i) {
+ UZU_PRAGMA_UNROLL
+ for (short j = 0; j < kTileCols; ++j) {
+ MMAFrag_t::store(
+ frag_at(i, j),
+ &(dst[(i * kFragRows) * w_x * ld + (j * kFragCols) * w_y]),
+ ld,
+ 1);
+ }
+ }
+ }
template <typename U, int w_x, int w_y>
METAL_FUNC void
@@ -397,6 +417,20 @@ struct BlockMMA {
Ctile.template store<U, WM, WN>(D, ldd);
}
+ /* Store results into threadgroup memory */
+ METAL_FUNC void store_result_tg(threadgroup U* D, const int ldd) {
+ // Apply epilogue
+ UZU_PRAGMA_UNROLL
+ for (short i = 0; i < decltype(Ctile)::kElemsPerTile; i++) {
+ Ctile.elems()[i] = Epilogue::apply(Ctile.elems()[i]);
+ }
+
+ // Adjust for simdgroup and thread location
+ D += sm * ldd + sn;
+
+ Ctile.template store_tg<U, WM, WN>(D, ldd);
+ }
+
METAL_FUNC void
store_result_safe(device U* D, const int ldd, short2 dst_tile_dims) {
diff --git a/crates/uzu/src/backends/metal/kernel/tensor_add_bias/mod.rs b/crates/uzu/src/backends/metal/kernel/tensor_add_bias/mod.rs
index 7c41f9bee..61838092b 100644
--- a/crates/uzu/src/backends/metal/kernel/tensor_add_bias/mod.rs
+++ b/crates/uzu/src/backends/metal/kernel/tensor_add_bias/mod.rs
@@ -1,8 +1,13 @@
use std::mem::size_of;
-use metal::{Buffer as MTLBuffer, CommandBuffer as MTLCommandBuffer, ComputePipelineState as MTLComputePipelineState};
+use metal::{
+ Buffer as MTLBuffer, CommandBuffer as MTLCommandBuffer,
+ ComputePipelineState as MTLComputePipelineState,
+};
-use super::{KernelDataType, MTLContext, metal_extensions::ComputeEncoderDispatch};
+use super::{
+ KernelDataType, MTLContext, metal_extensions::ComputeEncoderDispatch,
+};
use crate::backends::metal::error::MTLError;
#[derive(Debug)]
@@ -15,10 +20,13 @@ impl TensorAddBias {
context: &MTLContext,
data_type: KernelDataType,
) -> Result<Self, MTLError> {
- let function_name = format!("tensorAddBias_{}", data_type.function_name_suffix());
- let (pipeline_state, _reflection) =
- context.compute_pipeline_state_with_reflection(&function_name, None)?;
- Ok(Self { pipeline_state })
+ let function_name =
+ format!("tensorAddBias_{}", data_type.function_name_suffix());
+ let (pipeline_state, _reflection) = context
+ .compute_pipeline_state_with_reflection(&function_name, None)?;
+ Ok(Self {
+ pipeline_state,
+ })
}
pub fn encode_into_command_buffer(
@@ -36,11 +44,17 @@ impl TensorAddBias {
encoder.set_buffer(0, Some(input), 0);
encoder.set_buffer(1, Some(bias), 0);
encoder.set_buffer(2, Some(output), 0);
- encoder.set_bytes(3, size_of::<i32>() as u64, &(num_cols as i32) as *const _ as *const _);
- encoder.set_bytes(4, size_of::<i32>() as u64, &(total_len as i32) as *const _ as *const _);
+ encoder.set_bytes(
+ 3,
+ size_of::<i32>() as u64,
+ &(num_cols as i32) as *const _ as *const _,
+ );
+ encoder.set_bytes(
+ 4,
+ size_of::<i32>() as u64,
+ &(total_len as i32) as *const _ as *const _,
+ );
encoder.dispatch_1d_exactly(&self.pipeline_state, total_len, None);
encoder.end_encoding();
}
}
-
-
diff --git a/crates/uzu/src/config/attention.rs b/crates/uzu/src/config/attention.rs
index 485f0a3da..a6245dedf 100644
--- a/crates/uzu/src/config/attention.rs
+++ b/crates/uzu/src/config/attention.rs
@@ -11,6 +11,8 @@ pub struct AttentionConfig {
pub key_norm_config: Option<RMSNormConfig>,
pub logit_soft_cap: Option<f32>,
+ #[serde(default)]
+ pub has_sinks: bool,
pub has_qkv_biases: bool,
pub has_out_biases: bool,
}
@@ -81,6 +83,7 @@ mod tests {
query_norm_config: None,
key_norm_config: None,
logit_soft_cap: None,
+ has_sinks: false,
has_qkv_biases: false,
has_out_biases: false,
};
diff --git a/crates/uzu/src/config/common.rs b/crates/uzu/src/config/common.rs
index f2f1896ce..228345efb 100644
--- a/crates/uzu/src/config/common.rs
+++ b/crates/uzu/src/config/common.rs
@@ -56,9 +56,29 @@ impl Into<DataType> for QuantizationMode {
}
}
-#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Copy, Clone)]
-#[serde(rename_all = "lowercase")]
+#[derive(Debug, Serialize, Deserialize, PartialEq, Copy, Clone)]
+#[serde(tag = "type")]
pub enum Activation {
- SILU,
+ #[serde(rename = "SiLU")]
+ SILU {
+ #[serde(default = "default_silu_alpha")]
+ alpha: f32,
+ },
+ #[serde(rename = "GELU")]
GELU,
}
+
+fn default_silu_alpha() -> f32 {
+ 1.0
+}
+
+impl Activation {
+ pub fn alpha(&self) -> f32 {
+ match self {
+ Activation::SILU {
+ alpha,
+ } => *alpha,
+ Activation::GELU => 1.0,
+ }
+ }
+}
diff --git a/crates/uzu/src/config/decoder.rs b/crates/uzu/src/config/decoder.rs
index 750ee83a2..34b0f36ec 100644
--- a/crates/uzu/src/config/decoder.rs
+++ b/crates/uzu/src/config/decoder.rs
@@ -41,7 +41,7 @@ mod tests {
common::{Activation, ConfigDataType, QuantizationMode},
embedding::{EmbeddingConfig, EmbeddingConfigCommon},
linear::{LinearConfig, QuantizationConfig},
- mlp::MLPConfig,
+ mlp::{DenseMLPConfig, MLPConfig},
normalization::UpcastMode,
rope::RopeConfigCommon,
},
@@ -55,7 +55,7 @@ mod tests {
"embedding_config": {
"type": "QuantizedTiedEmbeddingConfig",
"input_scale": null,
- "logits_soft_cap": null,
+ "logit_soft_cap": null,
"embedding_quantization_mode": "int8",
"activation_quantization_mode": "int8",
"activation_precision": "bfloat16"
@@ -99,6 +99,7 @@ mod tests {
"lora_scale": 2.0,
},
"logit_soft_cap": null,
+ "has_sinks": false,
"has_qkv_biases": false,
"has_out_biases": false
},
@@ -111,6 +112,7 @@ mod tests {
"upcast_mode": "only_normalization"
},
"mlp_config": {
+ "type": "DenseMLPConfig",
"linear_config": {
"type": "QLoRALinearConfig",
"group_size": 32,
@@ -118,9 +120,9 @@ mod tests {
"activation_quantization_mode": "int8",
"activation_precision": "bfloat16",
"lora_rank": 16,
- "lora_scale": 2.0,
+ "lora_scale": 2.0
},
- "activation": "silu"
+ "activation": {"type": "SiLU"}
},
"post_mlp_norm_config": null
},
@@ -209,10 +211,11 @@ mod tests {
query_norm_config: None,
key_norm_config: None,
logit_soft_cap: None,
+ has_sinks: false,
has_qkv_biases: false,
has_out_biases: false,
},
- mlp_config: MLPConfig {
+ mlp_config: MLPConfig::Dense(DenseMLPConfig {
linear_config: LinearConfig::QLoRA {
quantization: QuantizationConfig {
group_size: 32,
@@ -225,8 +228,10 @@ mod tests {
lora_rank: 16,
lora_scale: 2.0,
},
- activation: Activation::SILU,
- },
+ activation: Activation::SILU {
+ alpha: 1.0,
+ },
+ }),
post_attention_norm_config: None,
post_mlp_norm_config: None,
},
diff --git a/crates/uzu/src/config/decoder_layer.rs b/crates/uzu/src/config/decoder_layer.rs
index ea67665bb..2f65467d8 100644
--- a/crates/uzu/src/config/decoder_layer.rs
+++ b/crates/uzu/src/config/decoder_layer.rs
@@ -26,6 +26,7 @@ mod tests {
},
*,
};
+ use crate::config::mlp;
#[test]
fn test_decoder_layer_config() {
@@ -58,6 +59,7 @@ mod tests {
"lora_scale": 2.0
},
"logit_soft_cap": null,
+ "has_sinks": false,
"has_qkv_biases": false,
"has_out_biases": false
},
@@ -70,6 +72,7 @@ mod tests {
"upcast_mode": "only_normalization"
},
"mlp_config": {
+ "type": "DenseMLPConfig",
"linear_config": {
"type": "QLoRALinearConfig",
"group_size": 32,
@@ -79,7 +82,7 @@ mod tests {
"lora_rank": 16,
"lora_scale": 2.0
},
- "activation": "silu"
+ "activation": {"type": "SiLU"}
},
"post_mlp_norm_config": null
}
@@ -128,10 +131,11 @@ mod tests {
query_norm_config: None,
key_norm_config: None,
logit_soft_cap: None,
+ has_sinks: false,
has_qkv_biases: false,
has_out_biases: false,
},
- mlp_config: MLPConfig {
+ mlp_config: MLPConfig::Dense(mlp::DenseMLPConfig {
linear_config: LinearConfig::QLoRA {
quantization: QuantizationConfig {
group_size: 32,
@@ -144,8 +148,10 @@ mod tests {
lora_rank: 16,
lora_scale: 2.0,
},
- activation: Activation::SILU,
- },
+ activation: Activation::SILU {
+ alpha: 1.0,
+ },
+ }),
post_attention_norm_config: None,
post_mlp_norm_config: None,
};
diff --git a/crates/uzu/src/config/embedding.rs b/crates/uzu/src/config/embedding.rs
index 4587903d9..092ecc276 100644
--- a/crates/uzu/src/config/embedding.rs
+++ b/crates/uzu/src/config/embedding.rs
@@ -64,7 +64,7 @@ mod tests {
{
"type": "QuantizedTiedEmbeddingConfig",
"input_scale": null,
- "logits_soft_cap": null,
+ "logit_soft_cap": null,
"embedding_quantization_mode": "int8",
"activation_quantization_mode": "int8",
"activation_precision": "bfloat16"
diff --git a/crates/uzu/src/config/mlp.rs b/crates/uzu/src/config/mlp.rs
index ec0bc7833..637e625dc 100644
--- a/crates/uzu/src/config/mlp.rs
+++ b/crates/uzu/src/config/mlp.rs
@@ -3,27 +3,59 @@ use serde::{Deserialize, Serialize};
use super::{common::Activation, linear::LinearConfig};
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
-pub struct MLPConfig {
+#[serde(tag = "type")]
+pub enum MLPConfig {
+ #[serde(rename = "DenseMLPConfig")]
+ Dense(DenseMLPConfig),
+ #[serde(rename = "MixtureOfExpertsConfig")]
+ MixtureOfExperts(MixtureOfExpertsConfig),
+}
+
+#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
+pub struct DenseMLPConfig {
+ pub linear_config: LinearConfig,
+ pub activation: Activation,
+}
+
+#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
+pub struct MixtureOfExpertsConfig {
+ pub mixture_size: usize,
+ pub num_experts_per_token: usize,
+ pub routing_function: RoutingFunctionConfig,
+ pub router_config: LinearConfig,
+ pub router_has_biases: bool,
+ pub expert_config: MoeExpertConfig,
+}
+
+#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
+#[serde(tag = "type")]
+pub enum RoutingFunctionConfig {
+ #[serde(rename = "SoftmaxRouting")]
+ SoftmaxRouting,
+}
+
+#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
+pub struct MoeExpertConfig {
pub linear_config: LinearConfig,
pub activation: Activation,
+ pub has_up_biases: bool,
+ pub has_down_biases: bool,
+ pub gate_clipping: [Option<f32>; 2],
+ pub up_clipping: [f32; 2],
}
#[cfg(test)]
mod tests {
use serde_json::from_str;
- use super::{
- super::{
- common::{ConfigDataType, QuantizationMode},
- linear::QuantizationConfig,
- },
- *,
- };
+ use super::{super::linear::QuantizationConfig, *};
+ use crate::config::{Activation, ConfigDataType, QuantizationMode};
#[test]
- fn test_mlp_config() {
+ fn test_dense_mlp_config() {
let config_str = r#"
{
+ "type": "DenseMLPConfig",
"linear_config": {
"type": "QLoRALinearConfig",
"group_size": 32,
@@ -33,11 +65,11 @@ mod tests {
"lora_rank": 16,
"lora_scale": 2.0
},
- "activation": "silu"
+ "activation": {"type": "SiLU"}
}
"#;
- let ground_truth_config = MLPConfig {
+ let ground_truth_config = MLPConfig::Dense(DenseMLPConfig {
linear_config: LinearConfig::QLoRA {
quantization: QuantizationConfig {
group_size: 32,
@@ -48,8 +80,75 @@ mod tests {
lora_rank: 16,
lora_scale: 2.0,
},
- activation: Activation::SILU,
- };
+ activation: Activation::SILU {
+ alpha: 1.0,
+ },
+ });
+
+ let deserialized_config: MLPConfig = from_str(config_str).unwrap();
+ assert_eq!(deserialized_config, ground_truth_config);
+ }
+
+ #[test]
+ fn test_moe_mlp_config() {
+ let config_str = r#"
+ {
+ "type": "MixtureOfExpertsConfig",
+ "mixture_size": 32,
+ "num_experts_per_token": 4,
+ "routing_function": {"type": "SoftmaxRouting"},
+ "router_config": {"type": "FullPrecisionLinearConfig", "precision": "bfloat16"},
+ "router_has_biases": true,
+ "expert_config": {
+ "linear_config": {
+ "type": "QLoRALinearConfig",
+ "group_size": 32,
+ "weight_quantization_mode": "uint4",
+ "activation_quantization_mode": "int8",
+ "activation_precision": "bfloat16",
+ "lora_rank": 16,
+ "lora_scale": 2.0
+ },
+ "activation": {"type": "SiLU"},
+ "has_up_biases": true,
+ "has_down_biases": true,
+ "gate_clipping": [null, 7.0],
+ "up_clipping": [-6.0, 8.0]
+ }
+ }
+ "#;
+
+ let ground_truth_config =
+ MLPConfig::MixtureOfExperts(MixtureOfExpertsConfig {
+ mixture_size: 32,
+ num_experts_per_token: 4,
+ routing_function: RoutingFunctionConfig::SoftmaxRouting,
+ router_config: LinearConfig::FullPrecision {
+ precision: ConfigDataType::BFloat16,
+ },
+ router_has_biases: true,
+ expert_config: MoeExpertConfig {
+ linear_config: LinearConfig::QLoRA {
+ quantization: QuantizationConfig {
+ group_size: 32,
+ weight_quantization_mode: QuantizationMode::UInt4,
+ activation_quantization_mode: Some(
+ QuantizationMode::Int8,
+ ),
+ activation_precision: ConfigDataType::BFloat16,
+ },
+ lora_rank: 16,
+ lora_scale: 2.0,
+ },
+ activation: Activation::SILU {
+ alpha: 1.0,
+ },
+ has_up_biases: true,
+ has_down_biases: true,
+ gate_clipping: [None, Some(7.0)],
+ up_clipping: [-6.0, 8.0],
+ },
+ });
let deserialized_config: MLPConfig = from_str(config_str).unwrap();
assert_eq!(deserialized_config, ground_truth_config);
diff --git a/crates/uzu/src/config/rope.rs b/crates/uzu/src/config/rope.rs
index 93d3f675d..0b9d56abd 100644
--- a/crates/uzu/src/config/rope.rs
+++ b/crates/uzu/src/config/rope.rs
@@ -29,8 +29,9 @@ pub enum RoPEConfig {
common: RopeConfigCommon,
scaling_factor: f32,
original_context_length: usize,
- low_frequency_factor: f32,
- high_frequency_factor: f32,
+ beta_fast: f32,
+ beta_slow: f32,
+ truncate: bool,
},
LinearScalingRoPEConfig {
#[serde(flatten)]
diff --git a/crates/uzu/src/generator/context.rs b/crates/uzu/src/generator/context.rs
index b44d65b94..8f1033ae6 100644
--- a/crates/uzu/src/generator/context.rs
+++ b/crates/uzu/src/generator/context.rs
@@ -100,6 +100,7 @@ impl GeneratorContext {
let scratch_buffers = ForwardPassBuffers::new(
&mtl_context,
+ &decoder_config,
&model_shape,
max_prefix_length,
max_suffix_length,
diff --git a/crates/uzu/src/generator/generator.rs b/crates/uzu/src/generator/generator.rs
index 5cfc3773c..2e0e4bfd5 100644
--- a/crates/uzu/src/generator/generator.rs
+++ b/crates/uzu/src/generator/generator.rs
@@ -4,6 +4,7 @@ use mpsgraph::CommandBuffer;
use super::{
context::GeneratorContext,
+ gpu_capture::GpuCaptureManager,
result::{GenerateResult, PrefillResult},
tasks::{GeneratorEncodedTask, GeneratorRunTask},
};
@@ -31,6 +32,7 @@ pub struct Generator {
encoded_tasks: HashMap<String, GeneratorEncodedTask>,
registered_prefix_len: usize,
pending_kv_update: Option<u64>,
+ gpu_capture: GpuCaptureManager,
}
impl Generator {
@@ -38,6 +40,8 @@ impl Generator {
model_path: &Path,
decoding_config: DecodingConfig,
) -> Result<Self, Error> {
+ let gpu_capture = GpuCaptureManager::new();
+
let context = GeneratorContext::new(model_path, &decoding_config)?;
let prefill_step_size =
@@ -45,19 +49,20 @@ impl Generator {
let generate_suffix_length = decoding_config.generate_suffix_length();
let mut generator = Self {
- decoding_config: decoding_config,
+ decoding_config,
tokens: Vec::new(),
context,
encoded_tasks: HashMap::new(),
registered_prefix_len: 0,
pending_kv_update: None,
+ gpu_capture,
};
//Warmup
generator.warmup(prefill_step_size);
generator.warmup(generate_suffix_length);
- return Ok(generator);
+ Ok(generator)
}
pub fn prefill(
@@ -127,6 +132,16 @@ impl Generator {
let positions_for_step =
&padded_positions[tokens_start_index..tokens_end_index];
+ let is_first_prefill = step == 0;
+ let should_capture =
+ self.gpu_capture.should_capture_prefill(is_first_prefill);
+
+ if should_capture {
+ let _ = self
+ .gpu_capture
+ .start_capture(&self.context.mtl_context, "prefill");
+ }
+
objc2::rc::autoreleasepool(|_pool| {
let _ = last_state.take();
});
@@ -144,6 +159,10 @@ impl Generator {
sampling_method,
);
+ if should_capture {
+ self.gpu_capture.stop_capture("prefill");
+ }
+
// Register the *accepted* real tokens from this step (exclude the
// padding token at the very end of the overall prefill).
let step_end_token_index =
@@ -314,6 +333,7 @@ impl Generator {
self.registered_prefix_len = 0;
self.encoded_tasks.clear();
self.pending_kv_update = None;
+ self.gpu_capture.reset();
}
pub fn prefix_len(&self) -> usize {
@@ -346,8 +366,22 @@ impl Generator {
let mut state = task.create_state(&mut self.context, None);
state.sampling_method = Some(sampling_method);
+ let is_first_decode = !warmup && task.token_ids.len() == 1;
+ let should_capture =
+ self.gpu_capture.should_capture_decode(is_first_decode);
+
+ if should_capture {
+ let _ = self
+ .gpu_capture
+ .start_capture(&self.context.mtl_context, "decode");
+ }
+
let encoded_task_key = task.encoded_task_key(self.tokens.len());
+ if should_capture {
+ self.encoded_tasks.remove(&encoded_task_key);
+ }
+
if let Some(_) = self.encoded_tasks.remove(&encoded_task_key) {
//Nothing
} else {
@@ -400,6 +434,10 @@ impl Generator {
root_command_buffer.wait_until_completed();
let run_time = run_start.elapsed().as_secs_f64();
+ if should_capture {
+ self.gpu_capture.stop_capture("decode");
+ }
+
(state, run_time)
})
}
diff --git a/crates/uzu/src/generator/gpu_capture.rs b/crates/uzu/src/generator/gpu_capture.rs
new file mode 100644
index 000000000..4d2665d69
--- /dev/null
+++ b/crates/uzu/src/generator/gpu_capture.rs
@@ -0,0 +1,111 @@
+use std::{
+ path::PathBuf,
+ time::{SystemTime, UNIX_EPOCH},
+};
+
+use metal::{CaptureDescriptor, CaptureManager, MTLCaptureDestination};
+
+use crate::{backends::metal::MTLContext, utils::env_utils::MetalEnvVar};
+
+pub struct GpuCaptureManager {
+ capture_prefill_enabled: bool,
+ capture_decode_enabled: bool,
+ first_prefill_captured: bool,
+ first_decode_captured: bool,
+}
+
+impl GpuCaptureManager {
+ pub fn new() -> Self {
+ let capture_prefill_enabled =
+ MetalEnvVar::CaptureFirstPrefill.is_enabled();
+ let capture_decode_enabled =
+ MetalEnvVar::CaptureFirstDecode.is_enabled();
+
+ // Enable Metal capture layer BEFORE device creation if any capture is requested
+ if capture_prefill_enabled || capture_decode_enabled {
+ unsafe {
+ std::env::set_var("METAL_CAPTURE_ENABLED", "1");
+ }
+ }
+
+ Self {
+ capture_prefill_enabled,
+ capture_decode_enabled,
+ first_prefill_captured: false,
+ first_decode_captured: false,
+ }
+ }
+
+ pub fn should_capture_prefill(
+ &self,
+ is_first_prefill: bool,
+ ) -> bool {
+ self.capture_prefill_enabled
+ && is_first_prefill
+ && !self.first_prefill_captured
+ }
+
+ pub fn should_capture_decode(
+ &self,
+ is_first_decode: bool,
+ ) -> bool {
+ self.capture_decode_enabled
+ && is_first_decode
+ && !self.first_decode_captured
+ }
+
+ pub fn start_capture(
+ &self,
+ mtl_context: &MTLContext,
+ capture_type: &str,
+ ) -> Result<PathBuf, String> {
+ let timestamp = SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .map_err(|e| format!("Time error: {}", e))?
+ .as_secs();
+
+ let trace_path = std::env::current_dir()
+ .unwrap_or_else(|_| PathBuf::from("."))
+ .join(format!("uzu_first_{}-{}.gputrace", capture_type, timestamp));
+
+ let capture_manager = CaptureManager::shared();
+ let capture_descriptor = CaptureDescriptor::new();
+ capture_descriptor
+ .set_destination(MTLCaptureDestination::GpuTraceDocument);
+ capture_descriptor.set_output_url(&trace_path);
+
+ mtl_context.command_queue.set_label("uzu_command_queue");
+ capture_descriptor
+ .set_capture_command_queue(&mtl_context.command_queue);
+
+ capture_manager
+ .start_capture(&capture_descriptor)
+ .map_err(|e| format!("Failed to start GPU capture: {}", e))?;
+
+ println!(
+ "🔍 GPU capture started for first {}: {:?}",
+ capture_type, trace_path
+ );
+
+ Ok(trace_path)
+ }
+
+ pub fn stop_capture(
+ &mut self,
+ capture_type: &str,
+ ) {
+ CaptureManager::shared().stop_capture();
+ println!("✅ GPU capture stopped for {}", capture_type);
+
+ match capture_type {
+ "prefill" => self.first_prefill_captured = true,
+ "decode" => self.first_decode_captured = true,
+ _ => {},
+ }
+ }
+
+ pub fn reset(&mut self) {
+ self.first_prefill_captured = false;
+ self.first_decode_captured = false;
+ }
+}
diff --git a/crates/uzu/src/generator/mod.rs b/crates/uzu/src/generator/mod.rs
index c6e6e1c90..7f2575f42 100644
--- a/crates/uzu/src/generator/mod.rs
+++ b/crates/uzu/src/generator/mod.rs
@@ -1,5 +1,6 @@
pub mod context;
pub mod generator;
+pub mod gpu_capture;
pub mod result;
pub mod sampler;
pub mod tasks;
diff --git a/crates/uzu/src/generator/tasks.rs b/crates/uzu/src/generator/tasks.rs
index 728398089..89b685d54 100644
--- a/crates/uzu/src/generator/tasks.rs
+++ b/crates/uzu/src/generator/tasks.rs
@@ -43,6 +43,7 @@ impl GeneratorRunTask {
) -> ForwardPassState {
let state = ForwardPassState::new(
context.mtl_context.clone(),
+ &context.model_config.decoder_config,
&context.model_shape,
&context.scratch_buffers,
context.kv_cache.clone(),
diff --git a/crates/uzu/src/runners/decoder_runner.rs b/crates/uzu/src/runners/decoder_runner.rs
index 0cd844a42..3de9f4042 100644
--- a/crates/uzu/src/runners/decoder_runner.rs
+++ b/crates/uzu/src/runners/decoder_runner.rs
@@ -110,6 +110,7 @@ impl DecoderTestContext {
// Scratch buffers sized for the maximum prefix/suffix lengths in this test
let scratch_buffers = ForwardPassBuffers::new(
&mtl_context,
+ &decoder_config,
&model_shape,
max_prefix_length,
max_suffix_length,
@@ -117,6 +118,7 @@ impl DecoderTestContext {
let state = ForwardPassState::new(
mtl_context.clone(),
+ &decoder_config,
&model_shape,
&scratch_buffers,
kv_cache.clone(),
diff --git a/crates/uzu/src/session/helpers/input_processor.rs b/crates/uzu/src/session/helpers/input_processor.rs
index 3172fb4f7..cb79abf0d 100644
--- a/crates/uzu/src/session/helpers/input_processor.rs
+++ b/crates/uzu/src/session/helpers/input_processor.rs
@@ -1,3 +1,5 @@
+use std::{ffi::CString, mem::MaybeUninit};
+
use minijinja::{Environment, context};
use minijinja_contrib::pycompat::unknown_method_callback;
@@ -29,6 +31,49 @@ impl InputProcessorDefault {
}
}
+/// Formats the current local time according to the provided `strftime` pattern.
+fn strftime_now(format_string: String) -> String {
+ let Ok(c_format) = CString::new(format_string) else {
+ return String::new();
+ };
+
+ unsafe {
+ let now = libc::time(std::ptr::null_mut());
+ if now == -1 {
+ return String::new();
+ }
+
+ let mut tm = MaybeUninit::<libc::tm>::uninit();
+ if libc::localtime_r(&now, tm.as_mut_ptr()).is_null() {
+ return String::new();
+ }
+
+ let tm = tm.assume_init();
+ let mut buf_len = 128_usize;
+
+ loop {
+ let mut buffer = vec![0u8; buf_len];
+ let written = libc::strftime(
+ buffer.as_mut_ptr() as *mut libc::c_char,
+ buffer.len(),
+ c_format.as_ptr(),
+ &tm,
+ );
+
+ if written > 0 {
+ buffer.truncate(written as usize);
+ return String::from_utf8_lossy(&buffer).into_owned();
+ }
+
+ if buf_len >= 4096 {
+ return String::new();
+ }
+
+ buf_len *= 2;
+ }
+ }
+}
+
impl InputProcessor for InputProcessorDefault {
fn process(
&self,
@@ -54,12 +99,14 @@ impl InputProcessor for InputProcessorDefault {
let template_name = "chat_template";
let mut environment = Environment::new();
environment.set_unknown_method_callback(unknown_method_callback);
+ environment.add_function("strftime_now", strftime_now);
environment
.add_template(template_name, template.as_str())
.map_err(|_| Error::UnableToLoadPromptTemplate)?;
let template = environment
.get_template(template_name)
.map_err(|_| Error::UnableToLoadPromptTemplate)?;
+
let result = template
.render(context!(
messages => messages,
diff --git a/crates/uzu/src/session/helpers/memory_checker.rs b/crates/uzu/src/session/helpers/memory_checker.rs
index 3da918246..e561710b2 100644
--- a/crates/uzu/src/session/helpers/memory_checker.rs
+++ b/crates/uzu/src/session/helpers/memory_checker.rs
@@ -22,6 +22,6 @@ pub fn is_directory_fits_ram(path: &Path) -> bool {
let mut sys = System::new();
sys.refresh_memory();
- let allowed_bytes = sys.total_memory() * 60 / 100;
- return model_size_bytes <= allowed_bytes;
+ let allowed_bytes = sys.total_memory() * 100 / 100;
+ model_size_bytes <= allowed_bytes
}
diff --git a/crates/uzu/src/session/parameter/prefill_step_size.rs b/crates/uzu/src/session/parameter/prefill_step_size.rs
index 62d2e5d38..9f75489da 100644
--- a/crates/uzu/src/session/parameter/prefill_step_size.rs
+++ b/crates/uzu/src/session/parameter/prefill_step_size.rs
@@ -43,7 +43,7 @@ impl ConfigResolvableValue<LanguageModelConfig, usize> for PrefillStepSize {
if cfg!(target_os = "ios") {
64
} else {
- 256
+ 64
}
},
PrefillStepSize::Maximal => maximal_value,
diff --git a/crates/uzu/src/session/session.rs b/crates/uzu/src/session/session.rs
index 0adfb6410..08596b5e4 100644
--- a/crates/uzu/src/session/session.rs
+++ b/crates/uzu/src/session/session.rs
@@ -400,6 +400,9 @@ impl Session {
let prefill_stats = {
let tokens_count = prefill_result.tokens.len();
let tokens_per_second = tokens_count as f64 / prefill_duration;
+ let processed_tokens = tokens_count_input + tokens_count;
+ let processed_tokens_per_second =
+ processed_tokens as f64 / prefill_duration;
let model_run_count = prefill_result.forwardpass_durations.len();
let model_run_average_duration =
@@ -411,6 +414,7 @@ impl Session {
suffix_length: prefill_suffix_length as u64,
tokens_count: tokens_count as u64,
tokens_per_second,
+ processed_tokens_per_second,
model_run: RunStats {
count: model_run_count as u64,
average_duration: model_run_average_duration,
@@ -445,6 +449,7 @@ impl Session {
suffix_length: generate_suffix_length as u64,
tokens_count: tokens_count as u64,
tokens_per_second,
+ processed_tokens_per_second: tokens_per_second,
model_run: RunStats {
count: model_run_count as u64,
average_duration: model_run_average_duration,
diff --git a/crates/uzu/src/session/types/stats.rs b/crates/uzu/src/session/types/stats.rs
index 74d75b7b8..31368e2e7 100644
--- a/crates/uzu/src/session/types/stats.rs
+++ b/crates/uzu/src/session/types/stats.rs
@@ -12,6 +12,7 @@ pub struct StepStats {
pub suffix_length: u64,
pub tokens_count: u64,
pub tokens_per_second: f64,
+ pub processed_tokens_per_second: f64,
pub model_run: RunStats,
pub run: Option<RunStats>,
}
diff --git a/crates/uzu/src/tracer/tracer.rs b/crates/uzu/src/tracer/tracer.rs
index 2d44cfc21..7c5d9e5d1 100644
--- a/crates/uzu/src/tracer/tracer.rs
+++ b/crates/uzu/src/tracer/tracer.rs
@@ -12,21 +12,26 @@ use num_traits::NumCast;
use crate::{
Array, ArrayElement, DataType,
backends::metal::{
- ForwardPassState, MTLContext, MetalArray,
+ ForwardPassState, KVCache, KVCacheUpdate, KernelDataType, MTLContext,
+ MetalArray,
forward_pass::{
- ArrayId,
+ ArrayId, ForwardPassBuffers,
encodable_with_state::{EncodableWithState, EncodingParameters},
traces::DecoderActivationTrace,
},
+ kernel::SamplingKernelEncodable,
},
generator::{
context::GeneratorContext,
sampler::{ArgmaxSampler, LogitsSampler},
},
- parameters::{ParameterLoader, ParameterTree},
+ parameters::{ParameterLoader, ParameterTree, read_safetensors_metadata},
session::{
config::{DecodingConfig, SpeculatorConfig},
- parameter::{ContextLength, PrefillStepSize, SamplingSeed},
+ parameter::{
+ ConfigResolvableValue, ContextLength, PrefillStepSize,
+ ResolvableValue, SamplingSeed,
+ },
},
};
@@ -140,15 +145,23 @@ pub struct Tracer {
impl Tracer {
pub fn new(model_path: &Path) -> Self {
+ let prefill_step_size = Self::determine_prefill_step_size(model_path);
let decoding_config = DecodingConfig::new(
- PrefillStepSize::Custom(1024),
+ PrefillStepSize::Custom(prefill_step_size),
ContextLength::default(),
SpeculatorConfig::default(),
SamplingSeed::default(),
false,
);
- let generator_context =
+ let mut generator_context =
GeneratorContext::new(model_path, &decoding_config).unwrap();
+ let desired_suffix_length =
+ prefill_step_size.max(decoding_config.generate_suffix_length());
+ Self::ensure_context_capacity(
+ &decoding_config,
+ desired_suffix_length,
+ &mut generator_context,
+ );
Self {
model_path: model_path.to_path_buf(),
@@ -161,15 +174,23 @@ impl Tracer {
sampling_seed: SamplingSeed,
max_prefix_length: ContextLength,
) -> Self {
+ let prefill_step_size = Self::determine_prefill_step_size(model_path);
let decoding_config = DecodingConfig::new(
- PrefillStepSize::Custom(1024),
+ PrefillStepSize::Custom(prefill_step_size),
max_prefix_length,
SpeculatorConfig::default(),
sampling_seed,
false,
);
- let generator_context =
+ let mut generator_context =
GeneratorContext::new(model_path, &decoding_config).unwrap();
+ let desired_suffix_length =
+ prefill_step_size.max(decoding_config.generate_suffix_length());
+ Self::ensure_context_capacity(
+ &decoding_config,
+ desired_suffix_length,
+ &mut generator_context,
+ );
Self {
model_path: model_path.to_path_buf(),
@@ -177,6 +198,86 @@ impl Tracer {
}
}
+ fn determine_prefill_step_size(model_path: &Path) -> usize {
+ let traces_path = model_path.join("traces.safetensors");
+ if let Ok(file) = File::open(&traces_path) {
+ if let Ok((_header_len, metadata)) =
+ read_safetensors_metadata(&file)
+ {
+ if let Some(tensor) =
+ metadata.tensors.get("activation_trace.token_ids")
+ {
+ if let Some(&length) = tensor.shape.first() {
+ return tensor
+ .shape
+ .iter()
+ .copied()
+ .max()
+ .unwrap_or(length)
+ .max(1);
+ }
+ }
+ }
+ }
+ 1
+ }
+
+ fn ensure_context_capacity(
+ decoding_config: &DecodingConfig,
+ desired_suffix_length: usize,
+ context: &mut GeneratorContext,
+ ) {
+ let resolved_prefix_length =
+ decoding_config.context_length.resolve(&context.model_config);
+ let current_suffix_length = std::cmp::max(
+ decoding_config.prefill_step_size.resolve(&context.model_config),
+ decoding_config.generate_suffix_length(),
+ );
+
+ if desired_suffix_length <= current_suffix_length {
+ return;
+ }
+
+ let decoder_config = &context.model_config.decoder_config;
+ context.scratch_buffers = ForwardPassBuffers::new(
+ &context.mtl_context,
+ decoder_config,
+ &context.model_shape,
+ resolved_prefix_length,
+ desired_suffix_length,
+ );
+
+ context.kv_cache = Rc::new(RefCell::new(KVCache::new(
+ &context.mtl_context,
+ &context.model_shape,
+ resolved_prefix_length,
+ desired_suffix_length,
+ )));
+
+ let intermediate_dtype: DataType =
+ decoder_config.output_norm_config.scale_precision.into();
+ let kernel_dtype: KernelDataType = intermediate_dtype.into();
+
+ context.kv_cache_update = Box::new(
+ KVCacheUpdate::new(
+ &context.mtl_context,
+ kernel_dtype,
+ resolved_prefix_length,
+ )
+ .expect("Failed to create KV cache update kernel"),
+ );
+
+ let sampling_seed = decoding_config.sampling_seed.resolve();
+ context.gpu_sampler = SamplingKernelEncodable::new(
+ &context.mtl_context,
+ kernel_dtype,
+ desired_suffix_length,
+ decoder_config.vocab_size,
+ sampling_seed,
+ )
+ .expect("Failed to create sampling kernel");
+ }
+
pub fn run(&self) -> TracerValidationResults {
let traces_path = self.model_path.join("traces.safetensors");
if !traces_path.exists() {
@@ -202,6 +303,7 @@ impl Tracer {
let mut state = ForwardPassState::new(
self.generator_context.mtl_context.clone(),
+ &self.generator_context.model_config.decoder_config,
&self.generator_context.model_shape,
&self.generator_context.scratch_buffers,
self.generator_context.kv_cache.clone(),
@@ -440,20 +542,60 @@ impl Tracer {
let expected_view = expected_array.as_view::<Precision>().unwrap();
let produced_view = produced_array.as_view::<Precision>().unwrap();
- let (expected_data, produced_data) = match produced_transform {
+ let (mut expected_data, mut produced_data) = match produced_transform {
Some(transform) => match transform {
Transform::KVCacheSlice => {
- let transformed_data = produced_view
- .permuted_axes(IxDyn(&[1, 0, 2]))
- .slice(s![0..expected_view.shape()[0], .., ..])
- .into_dyn()
+ let permuted =
+ produced_view.permuted_axes(IxDyn(&[1, 0, 2]));
+ let total_tokens = permuted.shape()[0];
+ let expected_tokens = expected_view.shape()[1];
+ let start = total_tokens.saturating_sub(expected_tokens);
+ let sliced = permuted.slice(s![start.., .., ..]);
+ let reshaped = sliced
+ .into_owned()
+ .to_shape(IxDyn(&[
+ 1,
+ expected_tokens,
+ permuted.shape()[1],
+ permuted.shape()[2],
+ ]))
+ .expect("Failed to reshape KV cache slice")
.to_owned();
- (expected_view.to_owned(), transformed_data)
+ (expected_view.to_owned(), reshaped)
},
},
None => (expected_view.to_owned(), produced_view.to_owned()),
};
- assert_eq!(expected_data.shape(), produced_data.shape());
+ let expected_shape = expected_data.shape().to_vec();
+ let produced_shape = produced_data.shape().to_vec();
+
+ if expected_shape != produced_shape {
+ if expected_shape.len() == produced_shape.len() + 1
+ && expected_shape.get(0) == Some(&1)
+ && expected_shape[1..] == produced_shape[..]
+ {
+ expected_data = expected_data
+ .to_shape(IxDyn(&produced_shape))
+ .expect("Failed to reshape expected data")
+ .to_owned();
+ } else if produced_shape.len() == expected_shape.len() + 1
+ && produced_shape.get(0) == Some(&1)
+ && produced_shape[1..] == expected_shape[..]
+ {
+ produced_data = produced_data
+ .to_shape(IxDyn(&expected_shape))
+ .expect("Failed to reshape produced data")
+ .to_owned();
+ }
+ }
+
+ if expected_data.shape() != produced_data.shape() {
+ panic!(
+ "Shape mismatch after alignment: expected {:?}, produced {:?}",
+ expected_data.shape(),
+ produced_data.shape()
+ );
+ }
let reference = expected_data
.iter()
diff --git a/crates/uzu/src/utils/env_utils.rs b/crates/uzu/src/utils/env_utils.rs
index adfdaf65f..27593aef8 100644
--- a/crates/uzu/src/utils/env_utils.rs
+++ b/crates/uzu/src/utils/env_utils.rs
@@ -1,12 +1,16 @@
#[derive(Copy, Clone, Debug)]
pub enum MetalEnvVar {
DeviceWrapperType,
+ CaptureFirstDecode,
+ CaptureFirstPrefill,
}
impl MetalEnvVar {
pub fn key(&self) -> &'static str {
match self {
MetalEnvVar::DeviceWrapperType => "METAL_DEVICE_WRAPPER_TYPE",
+ MetalEnvVar::CaptureFirstDecode => "UZU_CAPTURE_FIRST_DECODE",
+ MetalEnvVar::CaptureFirstPrefill => "UZU_CAPTURE_FIRST_PREFILL",
}
}
diff --git a/crates/uzu/tests/attention_kernel_test.rs b/crates/uzu/tests/attention_kernel_test.rs
index eca876e62..818e357ee 100644
--- a/crates/uzu/tests/attention_kernel_test.rs
+++ b/crates/uzu/tests/attention_kernel_test.rs
@@ -20,6 +20,7 @@ fn reference_attention(
keys: &Array4<f32>, // [batch, num_kv_heads, seq_len, head_dim]
values: &Array4<f32>, // [batch, num_kv_heads, seq_len, head_dim]
mask: Option<&Array3<f32>>, // [batch, seq_len, seq_len] or None
+ sinks: Option<&[f32]>,
scale: f32,
) -> Array4<f32> {
let (batch_size, num_heads, seq_len, head_dim) = queries.dim();
@@ -60,12 +61,16 @@ fn reference_attention(
}
for i in 0..seq_len {
- let mut max_score = f32::NEG_INFINITY;
+ let sink_logit = sinks.map(|s| s[q_head]);
+ let mut max_score =
+ sink_logit.unwrap_or(f32::NEG_INFINITY);
for j in 0..kv_seq_len {
max_score = max_score.max(scores[[i, j]]);
}
- let mut sum_exp = 0.0;
+ let mut sum_exp = sink_logit
+ .map(|sink| (sink - max_score).exp())
+ .unwrap_or(0.0);
for j in 0..kv_seq_len {
scores[[i, j]] = (scores[[i, j]] - max_score).exp();
sum_exp += scores[[i, j]];
@@ -113,12 +118,15 @@ fn reference_attention(
}
for i in 0..seq_len {
- let mut max_score = f32::NEG_INFINITY;
+ let sink_logit = sinks.map(|s| s[h]);
+ let mut max_score = sink_logit.unwrap_or(f32::NEG_INFINITY);
for j in 0..kv_seq_len {
max_score = max_score.max(scores[[i, j]]);
}
- let mut sum_exp = 0.0;
+ let mut sum_exp = sink_logit
+ .map(|sink| (sink - max_score).exp())
+ .unwrap_or(0.0);
for j in 0..kv_seq_len {
scores[[i, j]] = (scores[[i, j]] - max_score).exp();
sum_exp += scores[[i, j]];
@@ -289,6 +297,17 @@ fn create_mask_buffer(
)
}
+fn create_sinks_buffer(
+ sinks: &[f32],
+ context: &MTLContext,
+) -> metal::Buffer {
+ context.device.new_buffer_with_data(
+ sinks.as_ptr() as *const _,
+ (sinks.len() * size_of::<f32>()) as u64,
+ MTLResourceOptions::StorageModeShared,
+ )
+}
+
fn convert_kernel_output(
output_slice: &[f32],
batch_size: usize,
@@ -318,6 +337,7 @@ fn run_single_pass_attention(
keys: &Array4<f32>,
values: &Array4<f32>,
mask: Option<&Array3<f32>>,
+ sinks: Option<&[f32]>,
scale: f32,
) -> Result<Array4<f32>, Box<dyn std::error::Error>> {
let (batch_size, num_heads, seq_len, head_dim) = queries.dim();
@@ -329,6 +349,7 @@ fn run_single_pass_attention(
create_value_cache_buffer(values, seq_len, context);
let mask_buffer = mask.map(|m| create_mask_buffer(m, num_heads, context));
+ let sinks_buffer = sinks.map(|s| create_sinks_buffer(s, context));
let output_buffer = context.device.new_buffer(
(num_heads * seq_len * head_dim * size_of::<f32>()) as u64,
@@ -354,6 +375,7 @@ fn run_single_pass_attention(
mask_kv_seq_stride: 1,
mask_q_seq_stride: seq_len as i32,
mask_head_stride: 0,
+ sinks_buffer: sinks_buffer.as_ref(),
num_heads,
suffix_length: seq_len,
head_dim,
@@ -476,7 +498,7 @@ fn test_single_pass_attention_basic() {
println!("Testing reference implementation without mask...");
let reference_output =
- reference_attention(&queries, &keys, &values, None, scale);
+ reference_attention(&queries, &keys, &values, None, None, scale);
let ref_max = reference_output.iter().fold(0.0f32, |a, &b| a.max(b.abs()));
let ref_min =
@@ -512,7 +534,7 @@ fn test_single_pass_attention_basic() {
}
let kernel_output = match run_single_pass_attention(
- &kernel, &context, &queries, &keys, &values, None, scale,
+ &kernel, &context, &queries, &keys, &values, None, None, scale,
) {
Ok(output) => output,
Err(e) => {
@@ -576,6 +598,7 @@ fn test_single_pass_attention_with_mask() {
&keys,
&values,
Some(&mask),
+ None,
scale,
) {
Ok(output) => output,
@@ -585,7 +608,7 @@ fn test_single_pass_attention_with_mask() {
};
let reference_output =
- reference_attention(&queries, &keys, &values, Some(&mask), scale);
+ reference_attention(&queries, &keys, &values, Some(&mask), None, scale);
println!("Mask values:");
for i in 0..seq_len.min(4) {
@@ -606,6 +629,166 @@ fn test_single_pass_attention_with_mask() {
}
}
+#[test]
+fn test_single_pass_attention_with_sinks() {
+ let device = Device::system_default().expect("No Metal device found");
+ let command_queue = device.new_command_queue();
+ let context = match MTLContext::new(device, command_queue) {
+ Ok(ctx) => ctx,
+ Err(e) => {
+ panic!("Failed to create MTLContext: {:?}", e);
+ },
+ };
+
+ let batch_size = 1;
+ let num_heads = 4;
+ let num_kv_heads = 4;
+ let seq_len = 8;
+ let head_dim = 64;
+ let scale = 1.0 / (head_dim as f32).sqrt();
+
+ let (queries, keys, values, _mask) = create_test_data(
+ batch_size,
+ num_heads,
+ num_kv_heads,
+ seq_len,
+ head_dim,
+ 444,
+ );
+
+ let sinks: Vec<f32> = (0..num_heads)
+ .map(|h| (h as f32 - (num_heads as f32 / 2.0)) * 0.25)
+ .collect();
+ println!("Using sinks: {:?}", sinks);
+
+ let kernel = match AttentionKernel::new(&context, KernelDataType::Float32) {
+ Ok(k) => k,
+ Err(e) => {
+ panic!("Failed to create AttentionKernel: {:?}", e);
+ },
+ };
+
+ if !kernel.supports_single_pass(head_dim) {
+ panic!("Single-pass kernel not supported for head_dim={}", head_dim);
+ }
+
+ let reference_output = reference_attention(
+ &queries,
+ &keys,
+ &values,
+ None,
+ Some(&sinks),
+ scale,
+ );
+
+ let kernel_output = match run_single_pass_attention(
+ &kernel,
+ &context,
+ &queries,
+ &keys,
+ &values,
+ None,
+ Some(&sinks),
+ scale,
+ ) {
+ Ok(output) => output,
+ Err(e) => {
+ panic!("Failed to run single-pass attention with sinks: {:?}", e);
+ },
+ };
+
+ let tolerance = 1e-2;
+ if let Err(e) = compare_results(
+ &kernel_output,
+ &reference_output,
+ tolerance,
+ "Single-pass attention with sinks",
+ ) {
+ panic!("{}", e);
+ }
+}
+
+#[test]
+fn test_single_pass_attention_with_sinks_long_sequence() {
+ let device = Device::system_default().expect("No Metal device found");
+ let command_queue = device.new_command_queue();
+ let context = match MTLContext::new(device, command_queue) {
+ Ok(ctx) => ctx,
+ Err(e) => {
+ panic!("Failed to create MTLContext: {:?}", e);
+ },
+ };
+
+ let batch_size = 1;
+ let num_heads = 4;
+ let num_kv_heads = 4;
+ let seq_len = 64;
+ let head_dim = 64;
+ let scale = 1.0 / (head_dim as f32).sqrt();
+
+ let (queries, keys, values, _mask) = create_test_data(
+ batch_size,
+ num_heads,
+ num_kv_heads,
+ seq_len,
+ head_dim,
+ 777,
+ );
+
+ let sinks: Vec<f32> =
+ (0..num_heads).map(|h| (h as f32 * 0.1) - 0.15).collect();
+ println!("Long sequence sinks: {:?}", sinks);
+
+ let kernel = match AttentionKernel::new(&context, KernelDataType::Float32) {
+ Ok(k) => k,
+ Err(e) => {
+ panic!("Failed to create AttentionKernel: {:?}", e);
+ },
+ };
+
+ if !kernel.supports_single_pass(head_dim) {
+ panic!("Single-pass kernel not supported for head_dim={}", head_dim);
+ }
+
+ let reference_output = reference_attention(
+ &queries,
+ &keys,
+ &values,
+ None,
+ Some(&sinks),
+ scale,
+ );
+
+ let kernel_output = match run_single_pass_attention(
+ &kernel,
+ &context,
+ &queries,
+ &keys,
+ &values,
+ None,
+ Some(&sinks),
+ scale,
+ ) {
+ Ok(output) => output,
+ Err(e) => {
+ panic!(
+ "Failed to run single-pass attention long sequence with sinks: {:?}",
+ e
+ );
+ },
+ };
+
+ let tolerance = 5e-2;
+ if let Err(e) = compare_results(
+ &kernel_output,
+ &reference_output,
+ tolerance,
+ "Single-pass attention with sinks (long sequence)",
+ ) {
+ panic!("{}", e);
+ }
+}
+
#[test]
fn test_single_pass_attention_gqa() {
let device = Device::system_default().expect("No Metal device found");
@@ -648,7 +831,7 @@ fn test_single_pass_attention_gqa() {
}
let kernel_output = match run_single_pass_attention(
- &kernel, &context, &queries, &keys, &values, None, scale,
+ &kernel, &context, &queries, &keys, &values, None, None, scale,
) {
Ok(output) => output,
Err(e) => {
@@ -657,7 +840,7 @@ fn test_single_pass_attention_gqa() {
};
let reference_output =
- reference_attention(&queries, &keys, &values, None, scale);
+ reference_attention(&queries, &keys, &values, None, None, scale);
let tolerance = 1e-1;
if let Err(e) = compare_results(
@@ -677,6 +860,7 @@ fn run_two_pass_attention(
keys: &Array4<f32>,
values: &Array4<f32>,
mask: Option<&Array3<f32>>,
+ sinks: Option<&[f32]>,
scale: f32,
) -> Result<Array4<f32>, Box<dyn std::error::Error>> {
let (batch_size, num_heads, seq_len, head_dim) = queries.dim();
@@ -686,6 +870,7 @@ fn run_two_pass_attention(
let keys_buffer = create_key_cache_buffer(keys, seq_len, context);
let values_buffer = create_value_cache_buffer(values, seq_len, context);
let mask_buffer = mask.map(|m| create_mask_buffer(m, num_heads, context));
+ let sinks_buffer = sinks.map(|s| create_sinks_buffer(s, context));
let total_blocks_count = 32;
let partials_size = num_heads * seq_len * total_blocks_count * head_dim;
@@ -733,6 +918,7 @@ fn run_two_pass_attention(
mask_kv_seq_stride: 1,
mask_q_seq_stride: seq_len as i32,
mask_head_stride: 0,
+ sinks_buffer: sinks_buffer.as_ref(),
num_heads,
suffix_length: seq_len,
head_dim,
@@ -807,10 +993,10 @@ fn test_two_pass_attention() {
);
let reference_output =
- reference_attention(&queries, &keys, &values, None, scale);
+ reference_attention(&queries, &keys, &values, None, None, scale);
let kernel_output = match run_two_pass_attention(
- &kernel, &context, &queries, &keys, &values, None, scale,
+ &kernel, &context, &queries, &keys, &values, None, None, scale,
) {
Ok(output) => output,
Err(e) => {
@@ -876,10 +1062,10 @@ fn test_two_pass_attention_gqa() {
);
let reference_output =
- reference_attention(&queries, &keys, &values, None, scale);
+ reference_attention(&queries, &keys, &values, None, None, scale);
let kernel_output = match run_two_pass_attention(
- &kernel, &context, &queries, &keys, &values, None, scale,
+ &kernel, &context, &queries, &keys, &values, None, None, scale,
) {
Ok(output) => output,
Err(e) => {
@@ -1013,6 +1199,7 @@ fn perf_two_pass_attention() {
mask_kv_seq_stride: 1,
mask_q_seq_stride: suffix_length as i32,
mask_head_stride: 0,
+ sinks_buffer: None,
num_heads,
suffix_length, // Use actual suffix_length, not seq_len
head_dim,
diff --git a/crates/uzu/tests/moe/counts_offsets_fused_test.rs b/crates/uzu/tests/moe/counts_offsets_fused_test.rs
new file mode 100644
index 000000000..cf031770b
--- /dev/null
+++ b/crates/uzu/tests/moe/counts_offsets_fused_test.rs
@@ -0,0 +1,240 @@
+#![cfg(any(target_os = "macos", target_os = "ios"))]
+
+use half::bf16;
+use rand::{Rng, SeedableRng, rngs::StdRng};
+use uzu::backends::metal::{
+ MTLContext,
+ kernel::{
+ KernelDataType, MoeCountsOffsetsFusedArguments,
+ MoeCountsOffsetsFusedKernel,
+ moe::{MoeRouterTopKArguments, MoeRouterTopKKernel},
+ },
+};
+
+use super::test_utils::{alloc_buffer, alloc_buffer_with_data, create_ctx};
+
+fn cpu_bucket_counts(
+ topk_ids: &[i32],
+ t: usize,
+ k: usize,
+ e: usize,
+) -> Vec<u32> {
+ let mut counts = vec![0u32; e];
+ for ti in 0..t {
+ for kk in 0..k {
+ let id = topk_ids[ti * k + kk];
+ if id >= 0 {
+ let ue = id as usize;
+ if ue < e {
+ counts[ue] += 1;
+ }
+ }
+ }
+ }
+ counts
+}
+
+fn cpu_offsets_from_counts(counts: &[u32]) -> (Vec<u32>, u32) {
+ let mut offsets = vec![0u32; counts.len() + 1];
+ let mut sum = 0u32;
+ for (i, &c) in counts.iter().enumerate() {
+ offsets[i] = sum;
+ sum += c;
+ }
+ offsets[counts.len()] = sum;
+ (offsets, sum)
+}
+
+fn gen_topk_ids_from_logits(
+ ctx: &MTLContext,
+ t: usize,
+ e: usize,
+ k: usize,
+) -> (Vec<i32>, metal::Buffer) {
+ let mut rng = StdRng::seed_from_u64(1234);
+
+ // Generate random input and router weights
+ let d_model = 64; // arbitrary model dimension for test
+ let input_f32: Vec<f32> =
+ (0..t * d_model).map(|_| rng.random_range(-1.0..1.0)).collect();
+ let weight_f32: Vec<f32> =
+ (0..e * d_model).map(|_| rng.random_range(-1.0..1.0)).collect();
+ let bias_f32: Vec<f32> =
+ (0..e).map(|_| rng.random_range(-0.5..0.5)).collect();
+
+ // Convert to bf16
+ let input: Vec<bf16> =
+ input_f32.iter().map(|&x| bf16::from_f32(x)).collect();
+ let weight: Vec<bf16> =
+ weight_f32.iter().map(|&x| bf16::from_f32(x)).collect();
+ let bias: Vec<bf16> = bias_f32.iter().map(|&x| bf16::from_f32(x)).collect();
+
+ let input_buf = alloc_buffer_with_data(ctx, &input);
+ let weight_buf = alloc_buffer_with_data(ctx, &weight);
+ let bias_buf = alloc_buffer_with_data(ctx, &bias);
+ let topk_ids_buf = alloc_buffer::<i32>(ctx, t * k);
+ let topk_probs_buf = alloc_buffer::<bf16>(ctx, t * k);
+
+ // Use fused router+topk kernel
+ let router_topk =
+ MoeRouterTopKKernel::new(ctx).expect("router_topk kernel");
+ let cb = ctx.command_queue.new_command_buffer();
+ let args = MoeRouterTopKArguments {
+ input_buffer: &input_buf,
+ weight_buffer: &weight_buf,
+ bias_buffer: &bias_buf,
+ topk_ids_buffer: &topk_ids_buf,
+ topk_probs_buffer: &topk_probs_buf,
+ t,
+ d_model,
+ e,
+ k,
+ renorm: true,
+ };
+ router_topk
+ .encode(&cb, KernelDataType::BFloat16, args)
+ .expect("encode router_topk");
+ cb.commit();
+ cb.wait_until_completed();
+
+ let ids_ptr = topk_ids_buf.contents() as *const i32;
+ let ids = unsafe { std::slice::from_raw_parts(ids_ptr, t * k) };
+ (ids.to_vec(), topk_ids_buf)
+}
+
+#[test]
+fn test_counts_offsets_fused_parity_random() {
+ let ctx = create_ctx();
+ let shapes = vec![(1usize, 4usize), (7, 16), (64, 64), (1024, 128)];
+ let ks = vec![1usize, 2usize, 4usize];
+
+ for &(t, e) in &shapes {
+ for &k in &ks {
+ if k > e {
+ continue;
+ }
+ let (topk_ids, topk_ids_buf) =
+ gen_topk_ids_from_logits(&ctx, t, e, k);
+
+ // CPU reference
+ let counts_cpu = cpu_bucket_counts(&topk_ids, t, k, e);
+ let (offsets_cpu, sum_cpu) = cpu_offsets_from_counts(&counts_cpu);
+
+ // GPU fused kernel
+ let offsets_buf = alloc_buffer::<u32>(&ctx, e + 1);
+ let sum_k_buf = alloc_buffer::<u32>(&ctx, 1);
+ let num_tiles = ((e + 511) / 512).max(1);
+ let partials_buf = alloc_buffer::<u32>(&ctx, num_tiles * 512);
+
+ let kernel =
+ MoeCountsOffsetsFusedKernel::new(&ctx).expect("fused kernel");
+ let cb = ctx.command_queue.new_command_buffer();
+ let args = MoeCountsOffsetsFusedArguments {
+ topk_ids_buffer: &topk_ids_buf,
+ offsets_buffer: &offsets_buf,
+ sum_k_buffer: &sum_k_buf,
+ partials_buffer: &partials_buf,
+ t,
+ e,
+ k,
+ };
+ kernel.encode(&cb, args).expect("encode fused");
+ cb.commit();
+ cb.wait_until_completed();
+
+ // Verify offsets
+ let offsets_ptr = offsets_buf.contents() as *const u32;
+ let offsets_gpu =
+ unsafe { std::slice::from_raw_parts(offsets_ptr, e + 1) };
+ assert_eq!(
+ offsets_gpu,
+ &offsets_cpu[..],
+ "offsets mismatch T={} E={} K={}",
+ t,
+ e,
+ k
+ );
+
+ // Verify sum
+ let sum_ptr = sum_k_buf.contents() as *const u32;
+ let sum_gpu = unsafe { *sum_ptr };
+ assert_eq!(
+ sum_gpu, sum_cpu,
+ "sum mismatch T={} E={} K={}",
+ t, e, k
+ );
+ }
+ }
+}
+
+#[test]
+fn test_counts_offsets_fused_edge_cases() {
+ let ctx = create_ctx();
+
+ // Case 1: All tokens to one expert
+ let (t, e, k) = (16usize, 8usize, 2usize);
+ let mut topk_ids = vec![-1i32; t * k];
+ for ti in 0..t {
+ for kk in 0..k {
+ topk_ids[ti * k + kk] = 3;
+ }
+ }
+ let topk_ids_buf = alloc_buffer_with_data(&ctx, &topk_ids);
+
+ let offsets_buf = alloc_buffer::<u32>(&ctx, e + 1);
+ let sum_k_buf = alloc_buffer::<u32>(&ctx, 1);
+ let num_tiles = ((e + 511) / 512).max(1);
+ let partials_buf = alloc_buffer::<u32>(&ctx, num_tiles * 512);
+
+ let kernel = MoeCountsOffsetsFusedKernel::new(&ctx).expect("fused kernel");
+ let cb = ctx.command_queue.new_command_buffer();
+ let args = MoeCountsOffsetsFusedArguments {
+ topk_ids_buffer: &topk_ids_buf,
+ offsets_buffer: &offsets_buf,
+ sum_k_buffer: &sum_k_buf,
+ partials_buffer: &partials_buf,
+ t,
+ e,
+ k,
+ };
+ kernel.encode(&cb, args).expect("encode fused");
+ cb.commit();
+ cb.wait_until_completed();
+
+ let offsets_gpu = unsafe {
+ std::slice::from_raw_parts(offsets_buf.contents() as *const u32, e + 1)
+ };
+
+ let mut expected_offsets = vec![0u32; e + 1];
+ expected_offsets[4..].fill((t * k) as u32);
+ assert_eq!(offsets_gpu, &expected_offsets[..]);
+
+ // Case 2: T=0
+ let (t, e, k) = (0usize, 8usize, 2usize);
+ let topk_ids: Vec<i32> = vec![];
+ let topk_ids_buf = alloc_buffer_with_data(&ctx, &topk_ids);
+ let offsets_buf = alloc_buffer::<u32>(&ctx, e + 1);
+ let sum_k_buf = alloc_buffer::<u32>(&ctx, 1);
+ let num_tiles = ((e + 511) / 512).max(1);
+ let partials_buf = alloc_buffer::<u32>(&ctx, num_tiles * 512);
+
+ let kernel = MoeCountsOffsetsFusedKernel::new(&ctx).expect("fused kernel");
+ let cb = ctx.command_queue.new_command_buffer();
+ let args = MoeCountsOffsetsFusedArguments {
+ topk_ids_buffer: &topk_ids_buf,
+ offsets_buffer: &offsets_buf,
+ sum_k_buffer: &sum_k_buf,
+ partials_buffer: &partials_buf,
+ t,
+ e,
+ k,
+ };
+ kernel.encode(&cb, args).expect("encode fused");
+ cb.commit();
+ cb.wait_until_completed();
+
+ let offsets_gpu = unsafe {
+ std::slice::from_raw_parts(offsets_buf.contents() as *const u32, e + 1)
+ };
+ assert!(offsets_gpu.iter().all(|&v| v == 0));
+}
diff --git a/crates/uzu/tests/moe/mod.rs b/crates/uzu/tests/moe/mod.rs
new file mode 100644
index 000000000..38680d043
--- /dev/null
+++ b/crates/uzu/tests/moe/mod.rs
@@ -0,0 +1,25 @@
+// Shared test utilities
+#[path = "moe_test_utils.rs"]
+mod test_utils;
+
+// Unit tests for individual kernels
+#[path = "moe_block_e2e_test.rs"]
+mod block_e2e_test;
+#[path = "counts_offsets_fused_test.rs"]
+mod counts_offsets_fused_test;
+#[path = "moe_experts_perf_test.rs"]
+mod experts_perf_test;
+#[path = "moe_experts_test.rs"]
+mod experts_test;
+#[path = "moe_finalize_test.rs"]
+mod finalize_test;
+#[path = "moe_gather_test.rs"]
+mod gather_test;
+#[path = "moe_perf_test.rs"]
+mod perf_test;
+#[path = "moe_router_topk_test.rs"]
+mod router_topk_test;
+#[path = "moe_scatter_test.rs"]
+mod scatter_test;
+#[path = "moe_tiles_test.rs"]
+mod tiles_test;
diff --git a/crates/uzu/tests/moe/moe_block_e2e_test.rs b/crates/uzu/tests/moe/moe_block_e2e_test.rs
new file mode 100644
index 000000000..f43c9949e
--- /dev/null
+++ b/crates/uzu/tests/moe/moe_block_e2e_test.rs
@@ -0,0 +1,1256 @@
+use half::bf16;
+use rand::{Rng, SeedableRng, rngs::StdRng};
+use uzu::backends::metal::{
+ MTLContext,
+ kernel::{
+ KernelDataType, MoeBlockBasesArguments, MoeCountsOffsetsFusedArguments,
+ MoeCountsOffsetsFusedKernel, MoeFinalizeArguments, MoeFinalizeKernel,
+ MoeScatterKernels, MoeScatterWithMapArguments,
+ moe::{
+ MoeExpertsTwoPassArguments, MoeExpertsTwoPassPrefillKernel,
+ MoeGatherArguments, MoeGatherKernel, MoeRouterTopKArguments,
+ MoeRouterTopKKernel,
+ },
+ },
+};
+
+use super::test_utils::{alloc_buffer, alloc_buffer_with_data, create_ctx};
+
+fn silu(
+ x: f32,
+ alpha: f32,
+) -> f32 {
+ x / (1.0 + (-alpha * x).exp())
+}
+
+fn gelu(x: f32) -> f32 {
+ const K0: f32 = 0.7978845608f32;
+ const K1: f32 = 0.044715f32;
+ if x > 10.0 {
+ return x;
+ }
+ if x < -10.0 {
+ return 0.0;
+ }
+ let x3 = x * x * x;
+ let inner = x + K1 * x3;
+ let tanh_arg = (K0 * inner).clamp(-10.0, 10.0);
+ 0.5 * x * (1.0 + tanh_arg.tanh())
+}
+
+fn moe_cpu_reference(
+ x: &[bf16],
+ router_weight: &[f32], // [E, d_model] - kept as F32 for router (computed before BF16 conversion)
+ router_bias: &[f32], // [E]
+ w13: &[bf16], // source layout [E, d_model, 2*d_ff] (GPU transposes to [E, 2*d_ff, d_model])
+ w2: &[bf16], // [E, d_ff, d_model]
+ up_biases: &[bf16], // [E, 2*d_ff]
+ down_biases: &[bf16], // [E, d_model]
+ t: usize,
+ e: usize,
+ k: usize,
+ d_model: usize,
+ d_ff: usize,
+ gating_code: u32, // 0=GELU, 1=SiLU, 2=SwiGLU, 3=GEGLU
+ silu_alpha: f32,
+ gate_clip: (f32, f32),
+ up_clip: (f32, f32),
+) -> Vec<f32> {
+ let mut output = vec![0.0f32; t * d_model];
+
+ for token_idx in 0..t {
+ let x_start = token_idx * d_model;
+
+ // Router: compute logits = x @ W_r^T + b_r
+ // Router uses F32 precision (router_weight/router_bias are F32)
+ let mut token_logits = vec![0.0f32; e];
+ for expert_idx in 0..e {
+ let mut logit = router_bias[expert_idx];
+ for d in 0..d_model {
+ let x_val = f32::from(x[x_start + d]);
+ logit += x_val * router_weight[expert_idx * d_model + d];
+ }
+ token_logits[expert_idx] = logit;
+ }
+
+ // TopK selection
+ let mut indices_and_logits: Vec<(usize, f32)> =
+ token_logits.iter().enumerate().map(|(i, &v)| (i, v)).collect();
+ indices_and_logits.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap());
+ let top_k_indices: Vec<usize> =
+ indices_and_logits[..k].iter().map(|&(i, _)| i).collect();
+ let top_k_logits: Vec<f32> =
+ indices_and_logits[..k].iter().map(|&(_, v)| v).collect();
+
+ // Softmax normalization (matching Python: jax.nn.softmax)
+ let max_logit =
+ top_k_logits.iter().copied().fold(f32::NEG_INFINITY, f32::max);
+ let exp_sum: f32 =
+ top_k_logits.iter().map(|&v| (v - max_logit).exp()).sum();
+ let weights: Vec<f32> = top_k_logits
+ .iter()
+ .map(|&v| (v - max_logit).exp() / exp_sum)
+ .collect();
+
+ // Process each selected expert (matching Python: vmap(run_expert))
+ for (expert_idx, &weight) in top_k_indices.iter().zip(weights.iter()) {
+ let x_start = token_idx * d_model;
+
+ // Expert MLP weights layout: CPU uses W13[E, d_model, 2*d_ff], GPU stores as [E, 2*d_ff, d_model]; W2[E, d_ff, d_model]
+ let w13_offset = expert_idx * d_model * 2 * d_ff;
+ let w2_offset = expert_idx * d_ff * d_model;
+ let bias_up_offset = expert_idx * 2 * d_ff;
+ let bias_down_offset = expert_idx * d_model;
+
+ // Up projection: W13[expert, input, output] where output=[up, gate]
+ // Convert BF16→F32 on each access to match GPU precision
+ let mut up_out = vec![0.0f32; d_ff];
+ let mut gate_out = vec![0.0f32; d_ff];
+
+ for ff_idx in 0..d_ff {
+ let mut up_sum = f32::from(up_biases[bias_up_offset + ff_idx]);
+ let mut gate_sum =
+ f32::from(up_biases[bias_up_offset + d_ff + ff_idx]);
+
+ for input_idx in 0..d_model {
+ let w_base = w13_offset + input_idx * 2 * d_ff;
+ let x_val = f32::from(x[x_start + input_idx]);
+ let w_up = f32::from(w13[w_base + ff_idx]);
+ let w_gate = f32::from(w13[w_base + d_ff + ff_idx]);
+ up_sum += x_val * w_up;
+ gate_sum += x_val * w_gate;
+ }
+
+ up_out[ff_idx] = up_sum;
+ gate_out[ff_idx] = gate_sum;
+ }
+
+ // Apply clipping
+ for i in 0..d_ff {
+ gate_out[i] = gate_out[i].clamp(gate_clip.0, gate_clip.1);
+ up_out[i] = up_out[i].clamp(up_clip.0, up_clip.1);
+ }
+
+ // Activation: depends on gating_code
+ // 0=GELU(up), 1=SiLU(up), 2=SwiGLU(gate)*up, 3=GEGLU(gate)*up
+ let mut hidden = vec![0.0f32; d_ff];
+ for i in 0..d_ff {
+ hidden[i] = match gating_code {
+ 0 => gelu(up_out[i]),
+ 1 => silu(up_out[i], silu_alpha),
+ 2 => silu(gate_out[i], silu_alpha) * up_out[i],
+ 3 => gelu(gate_out[i]) * up_out[i],
+ _ => silu(gate_out[i], silu_alpha) * up_out[i], // fallback to SwiGLU
+ };
+ }
+
+ // Down projection: W2[expert, ff, output]
+ // Convert BF16→F32 on each access to match GPU precision
+ // CRITICAL: Two-pass kernel accumulates in F32, only quantizes at the very end
+ for out_idx in 0..d_model {
+ let mut fc2_sum = 0.0f32;
+ for ff_idx in 0..d_ff {
+ let w2_val =
+ f32::from(w2[w2_offset + ff_idx * d_model + out_idx]);
+ fc2_sum += hidden[ff_idx] * w2_val;
+ }
+ // Two-pass: keep in F32 (no intermediate quantization)
+
+ // Add down bias in F32
+ let down_bias_val =
+ f32::from(down_biases[bias_down_offset + out_idx]);
+ let with_bias = fc2_sum + down_bias_val;
+
+ // Only quantize to BF16 once at the end (matches two-pass final write)
+ let with_bias_bf16 = bf16::from_f32(with_bias);
+ let final_val = f32::from(with_bias_bf16);
+
+ output[x_start + out_idx] += weight * final_val;
+ }
+ }
+ }
+
+ output
+}
+
+// Main entry point - automatically tests both modes for T>1
+fn run_moe_parity_test(
+ ctx: &MTLContext,
+ t: usize,
+ e: usize,
+ k: usize,
+ d_model: usize,
+ d_ff: usize,
+ gating_code: u32,
+ silu_alpha: f32,
+ gate_clip: (f32, f32),
+ up_clip: (f32, f32),
+ seed: u64,
+ test_name: &str,
+) {
+ if t > 1 {
+ // Test 1-pass prefill (default, stable)
+ run_moe_parity_test_internal(
+ ctx,
+ t,
+ e,
+ k,
+ d_model,
+ d_ff,
+ gating_code,
+ silu_alpha,
+ gate_clip,
+ up_clip,
+ seed,
+ &format!("{}_decode", test_name),
+ );
+ // Test 2-pass prefill (experimental)
+ run_moe_parity_test_internal(
+ ctx,
+ t,
+ e,
+ k,
+ d_model,
+ d_ff,
+ gating_code,
+ silu_alpha,
+ gate_clip,
+ up_clip,
+ seed,
+ &format!("{}_prefill", test_name),
+ );
+ } else {
+ // Decode mode (T=1) - no prefill variants
+ run_moe_parity_test_internal(
+ ctx,
+ t,
+ e,
+ k,
+ d_model,
+ d_ff,
+ gating_code,
+ silu_alpha,
+ gate_clip,
+ up_clip,
+ seed,
+ test_name,
+ );
+ }
+}
+
+fn run_moe_parity_test_internal(
+ ctx: &MTLContext,
+ t: usize,
+ e: usize,
+ k: usize,
+ d_model: usize,
+ d_ff: usize,
+ gating_code: u32, // 0=GELU, 1=SiLU, 2=SwiGLU, 3=GEGLU
+ silu_alpha: f32,
+ gate_clip: (f32, f32),
+ up_clip: (f32, f32),
+ seed: u64,
+ test_name: &str,
+) {
+ let mut rng = StdRng::seed_from_u64(seed);
+
+ let prefill_mode = if t > 1 {
+ "2-pass"
+ } else {
+ "decode"
+ };
+
+ eprintln!(
+ "\n[{}] T={}, E={}, K={}, d_model={}, d_ff={}, alpha={}, gate_clip={:?}, up_clip={:?}, mode={}",
+ test_name,
+ t,
+ e,
+ k,
+ d_model,
+ d_ff,
+ silu_alpha,
+ gate_clip,
+ up_clip,
+ prefill_mode
+ );
+
+ // Random BF16 inputs
+ let x: Vec<bf16> = (0..t * d_model)
+ .map(|_| bf16::from_f32(rng.random_range(-1.0..1.0)))
+ .collect();
+
+ // Generate random router weights and biases for CPU reference
+ let router_weight_f32: Vec<f32> =
+ (0..e * d_model).map(|_| rng.random_range(-0.5..0.5)).collect();
+ let router_bias_f32: Vec<f32> =
+ (0..e).map(|_| rng.random_range(-0.1..0.1)).collect();
+
+ // Convert router weights/bias to BF16 for GPU
+ let router_weight_bf16: Vec<bf16> =
+ router_weight_f32.iter().map(|&v| bf16::from_f32(v)).collect();
+ let router_bias_bf16: Vec<bf16> =
+ router_bias_f32.iter().map(|&v| bf16::from_f32(v)).collect();
+
+ // Generate random expert weights and biases
+ let w13_len = e * d_model * 2 * d_ff;
+ let w2_len = e * d_ff * d_model;
+
+ // Generate W13 in original layout [E, d_model, 2*d_ff] for CPU reference
+ let w13_cpu: Vec<bf16> = (0..w13_len)
+ .map(|_| bf16::from_f32(rng.random_range(-0.5..0.5)))
+ .collect();
+
+ // Transpose to GPU layout [E, 2*d_ff, d_model]
+ let mut w13_gpu = vec![bf16::from_f32(0.0); w13_len];
+ 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_gpu[dst_idx] = w13_cpu[src_idx];
+ }
+ }
+ }
+
+ // Generate W2 in original layout [E, d_ff, d_model] for CPU reference
+ let w2_cpu: Vec<bf16> = (0..w2_len)
+ .map(|_| bf16::from_f32(rng.random_range(-0.5..0.5)))
+ .collect();
+
+ // Transpose W2 to GPU layout [E, d_model, d_ff]
+ let mut w2_gpu = vec![bf16::from_f32(0.0); w2_len];
+ for expert in 0..e {
+ let expert_offset = expert * d_ff * d_model;
+ for ff in 0..d_ff {
+ for dm in 0..d_model {
+ // src: [E, d_ff, d_model] -> index: expert_offset + ff * d_model + dm
+ // dst: [E, d_model, d_ff] -> index: expert_offset + dm * d_ff + ff
+ w2_gpu[expert_offset + dm * d_ff + ff] =
+ w2_cpu[expert_offset + ff * d_model + dm];
+ }
+ }
+ }
+ let up_biases: Vec<bf16> = (0..e * 2 * d_ff)
+ .map(|_| bf16::from_f32(rng.random_range(-0.1..0.1)))
+ .collect();
+ let down_biases: Vec<bf16> = (0..e * d_model)
+ .map(|_| bf16::from_f32(rng.random_range(-0.1..0.1)))
+ .collect();
+
+ // Create Metal buffers
+ let x_buf = alloc_buffer_with_data(&ctx, &x);
+ let router_w_buf = alloc_buffer_with_data(&ctx, &router_weight_bf16);
+ let router_b_buf = alloc_buffer_with_data(&ctx, &router_bias_bf16);
+ let w13_buf = alloc_buffer_with_data(&ctx, &w13_gpu);
+ let w2_buf = alloc_buffer_with_data(&ctx, &w2_gpu);
+ let up_biases_buf = alloc_buffer_with_data(&ctx, &up_biases);
+ let down_biases_buf = alloc_buffer_with_data(&ctx, &down_biases);
+
+ // Allocate intermediate buffers (max capacity)
+ let max_sumk = t * k;
+ let topk_ids_buf = alloc_buffer::<i32>(&ctx, t * k);
+ let topk_probs_buf = alloc_buffer::<bf16>(&ctx, t * k);
+ let offsets_buf = alloc_buffer::<u32>(&ctx, e + 1);
+ let sumk_buf = alloc_buffer::<u32>(&ctx, 1);
+ let num_blocks = ((t + 255) / 256).max(1);
+ let num_tiles = ((e + 512 - 1) / 512).max(1);
+ let entries = num_blocks * num_tiles * 512usize;
+ let partials_buf = alloc_buffer::<u32>(&ctx, entries);
+ let block_bases_buf = alloc_buffer::<u32>(&ctx, entries);
+ let block_alloc_buf = alloc_buffer::<u32>(&ctx, entries);
+ let bucketed_ids_buf = alloc_buffer::<i32>(&ctx, max_sumk);
+ let bucketed_probs_buf = alloc_buffer::<bf16>(&ctx, max_sumk);
+ let tok2row_buf = alloc_buffer::<i32>(&ctx, t * k);
+ let x_perm_buf = alloc_buffer::<bf16>(&ctx, max_sumk * d_model);
+ let y_partial_buf = alloc_buffer::<bf16>(&ctx, max_sumk * d_model);
+ let y_out_buf = alloc_buffer::<bf16>(&ctx, t * d_model);
+ const BLOCK_M_DECODE: usize = 4; // matches two-pass decode kernel configuration
+ let h_blocks_decode = (d_ff + BLOCK_M_DECODE - 1) / BLOCK_M_DECODE;
+ let max_tiles = max_sumk * h_blocks_decode;
+ let tile_counts_buf = alloc_buffer::<u32>(&ctx, e);
+ let tile_offsets_buf = alloc_buffer::<u32>(&ctx, e + 1);
+ let tile_map_buf = alloc_buffer::<u32>(&ctx, max_tiles * 3);
+ let total_tiles_buf = alloc_buffer::<u32>(&ctx, 8);
+ let dispatch_args_buf = alloc_buffer::<u32>(&ctx, 3);
+
+ // Encode ALL kernels in one command buffer
+ eprintln!("[E2E] Encoding entire MoE pipeline in single command buffer...");
+ let cb = ctx.command_queue.new_command_buffer();
+
+ // Router + TopK (fused kernel)
+ let router_topk = MoeRouterTopKKernel::new(&ctx).expect("router+topk");
+ router_topk
+ .encode(
+ &cb,
+ KernelDataType::BFloat16,
+ MoeRouterTopKArguments {
+ input_buffer: &x_buf,
+ weight_buffer: &router_w_buf,
+ bias_buffer: &router_b_buf,
+ topk_ids_buffer: &topk_ids_buf,
+ topk_probs_buffer: &topk_probs_buf,
+ t,
+ d_model,
+ e,
+ k,
+ renorm: true,
+ },
+ )
+ .expect("router+topk encode");
+
+ let fused_kernel =
+ MoeCountsOffsetsFusedKernel::new(&ctx).expect("fused kernel");
+ fused_kernel
+ .encode(
+ &cb,
+ MoeCountsOffsetsFusedArguments {
+ topk_ids_buffer: &topk_ids_buf,
+ offsets_buffer: &offsets_buf,
+ sum_k_buffer: &sumk_buf,
+ partials_buffer: &partials_buf,
+ t,
+ e,
+ k,
+ },
+ )
+ .expect("fused encode");
+
+ let scatter = MoeScatterKernels::new(&ctx).expect("scatter");
+ scatter
+ .encode_block_bases(
+ &cb,
+ MoeBlockBasesArguments {
+ partials_buffer: &partials_buf,
+ block_bases_buffer: &block_bases_buf,
+ block_alloc_buffer: &block_alloc_buf,
+ e,
+ num_blocks,
+ num_tiles,
+ },
+ )
+ .expect("block bases");
+
+ scatter
+ .encode_scatter_with_map(
+ &cb,
+ MoeScatterWithMapArguments {
+ base: uzu::backends::metal::kernel::MoeScatterArguments {
+ topk_ids_buffer: &topk_ids_buf,
+ topk_probs_buffer: &topk_probs_buf,
+ offsets_buffer: &offsets_buf,
+ block_bases_buffer: &block_bases_buf,
+ block_alloc_buffer: &block_alloc_buf,
+ out_ids_buffer: &bucketed_ids_buf,
+ out_probs_buffer: &bucketed_probs_buf,
+ t,
+ e,
+ k,
+ num_blocks,
+ num_tiles,
+ },
+ tok2row_buffer: &tok2row_buf,
+ },
+ KernelDataType::BFloat16,
+ )
+ .expect("scatter");
+
+ let gather = MoeGatherKernel::new(&ctx).expect("gather");
+ gather
+ .encode(
+ &cb,
+ KernelDataType::BFloat16,
+ MoeGatherArguments {
+ x_buffer: &x_buf,
+ bucketed_ids_buffer: &bucketed_ids_buf,
+ x_perm_buffer: &x_perm_buf,
+ sumk_buffer: &sumk_buf,
+ t,
+ k,
+ d_model,
+ },
+ )
+ .expect("gather");
+
+ // Additional buffers for 2-pass
+ let total_rows = t * k;
+ let hidden_buf = alloc_buffer::<f32>(&ctx, total_rows * d_ff);
+ let row_expert_map_buf = alloc_buffer::<u32>(&ctx, total_rows);
+
+ let experts = MoeExpertsTwoPassPrefillKernel::new(&ctx).expect("experts");
+ let num_tiles_k = ((d_ff + 64 - 1) / 64) as u32;
+ experts
+ .encode(
+ &cb,
+ MoeExpertsTwoPassArguments {
+ x_perm_buffer: &x_perm_buf,
+ expert_offsets: &offsets_buf,
+ row_expert_map: &row_expert_map_buf,
+ hidden_buffer: &hidden_buf,
+ output_buffer: &y_partial_buf,
+ w13_all: &w13_buf,
+ w2_all: &w2_buf,
+ up_biases: &up_biases_buf,
+ down_biases: &down_biases_buf,
+ tile_counts: &tile_counts_buf,
+ tile_offsets: &tile_offsets_buf,
+ tile_map: &tile_map_buf,
+ total_tiles: &total_tiles_buf,
+ dispatch_args: &dispatch_args_buf,
+ total_rows,
+ d_model,
+ d_ff,
+ e,
+ num_tiles_k,
+ gating_code,
+ 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: KernelDataType::BFloat16,
+ },
+ )
+ .expect("experts encode");
+
+ let finalize = MoeFinalizeKernel::new(&ctx).expect("finalize");
+ finalize
+ .encode(
+ &cb,
+ MoeFinalizeArguments {
+ tok2row_buffer: &tok2row_buf,
+ probs_buffer: &topk_probs_buf,
+ y_partial_buffer: &y_partial_buf,
+ y_out_buffer: &y_out_buf,
+ t,
+ d_model,
+ k,
+ },
+ KernelDataType::BFloat16,
+ )
+ .expect("finalize");
+
+ eprintln!("[E2E] All kernels encoded. Committing ONCE and waiting...");
+ cb.commit();
+ cb.wait_until_completed();
+ eprintln!("[E2E] GPU execution completed");
+
+ // Read GPU output
+ let y_out_bf16 = unsafe {
+ std::slice::from_raw_parts(
+ y_out_buf.contents() as *const bf16,
+ t * d_model,
+ )
+ };
+ let y_out_gpu: Vec<f32> =
+ y_out_bf16.iter().map(|&v| f32::from(v)).collect();
+
+ // Validate GPU output is finite
+ let nan_count = y_out_gpu.iter().filter(|v| v.is_nan()).count();
+ let inf_count = y_out_gpu.iter().filter(|v| v.is_infinite()).count();
+
+ eprintln!("[E2E] GPU output stats: nan={}, inf={}", nan_count, inf_count);
+ assert_eq!(nan_count, 0, "GPU output contains {} NaN values", nan_count);
+ assert_eq!(inf_count, 0, "GPU output contains {} Inf values", inf_count);
+
+ // Run CPU reference (router logits already computed above)
+ // NOTE: Keep weights as BF16 and convert per-access to match GPU precision
+ eprintln!("[{}] Running CPU reference implementation...", test_name);
+
+ // Debug: Verify data consistency and tile bookkeeping for large-scale tests
+ if d_model >= 512 {
+ eprintln!(
+ "[E2E] Large-scale debug: x[0]={:.6}, w13[0]={:.6}, w2[0]={:.6}",
+ f32::from(x[0]),
+ f32::from(w13_cpu[0]),
+ f32::from(w2_cpu[0])
+ );
+
+ // Probe tile bookkeeping
+ let total_tiles_cpu = unsafe {
+ std::slice::from_raw_parts(
+ total_tiles_buf.contents() as *const u32,
+ 2,
+ )
+ };
+ let dispatch_args_cpu = unsafe {
+ std::slice::from_raw_parts(
+ dispatch_args_buf.contents() as *const u32,
+ 3,
+ )
+ };
+ let tile_offsets_cpu = unsafe {
+ std::slice::from_raw_parts(
+ tile_offsets_buf.contents() as *const u32,
+ (e + 1).min(8),
+ )
+ };
+ let sumk_val = unsafe { *(sumk_buf.contents() as *const u32) } as usize;
+ eprintln!("[E2E] Tile bookkeeping:");
+ eprintln!(
+ "[E2E] total_tiles={}, dispatch_args=({}, {}, {})",
+ total_tiles_cpu[0],
+ dispatch_args_cpu[0],
+ dispatch_args_cpu[1],
+ dispatch_args_cpu[2]
+ );
+ eprintln!(
+ "[E2E] tile_offsets[0..{}]={:?}",
+ (e + 1).min(8),
+ &tile_offsets_cpu
+ );
+ eprintln!("[E2E] sumk={}, num_tiles_k={}", sumk_val, num_tiles_k);
+
+ // For multi-token tests with large d_ff, verify gather output (x_perm)
+ if t > 1 && d_ff >= 256 {
+ let x_perm_cpu = unsafe {
+ std::slice::from_raw_parts(
+ x_perm_buf.contents() as *const bf16,
+ sumk_val * d_model,
+ )
+ };
+ eprintln!("[E2E] x_perm diagnostics (sumk={}):", sumk_val);
+ eprintln!(
+ "[E2E] Row 0 [0:8]: {:?}",
+ &x_perm_cpu[0..8]
+ .iter()
+ .map(|&v| f32::from(v))
+ .collect::<Vec<_>>()
+ );
+ if sumk_val > 1 {
+ eprintln!(
+ "[E2E] Row 1 [{}:{}]: {:?}",
+ d_model,
+ d_model + 8,
+ &x_perm_cpu[d_model..d_model + 8]
+ .iter()
+ .map(|&v| f32::from(v))
+ .collect::<Vec<_>>()
+ );
+ }
+
+ // Check tile_map for first few tiles
+ let tile_map_cpu = unsafe {
+ std::slice::from_raw_parts(
+ tile_map_buf.contents() as *const u32,
+ 12.min(max_tiles * 3),
+ )
+ };
+ eprintln!("[E2E] tile_map (first 4 tiles): {:?}", &tile_map_cpu);
+
+ // CRITICAL: Check tok2row mapping for multi-token tests
+ let tok2row_cpu = unsafe {
+ std::slice::from_raw_parts(
+ tok2row_buf.contents() as *const i32,
+ t * k,
+ )
+ };
+ eprintln!("[E2E] tok2row[0..{}]: {:?}", t * k, &tok2row_cpu);
+ eprintln!(
+ "[E2E] Expected: token 0→row {}, token 1→row {}",
+ 0,
+ if sumk_val > 1 {
+ 1
+ } else {
+ -1
+ }
+ );
+
+ // Check y_partial at specific indices where finalize reads for token 1
+ let y_partial_full = unsafe {
+ std::slice::from_raw_parts(
+ y_partial_buf.contents() as *const bf16,
+ sumk_val * d_model,
+ )
+ };
+ eprintln!("[E2E] y_partial spot check:");
+ eprintln!(
+ "[E2E] y_partial[48] (row 0, col 48) = {:.6}",
+ f32::from(y_partial_full[48])
+ );
+ if sumk_val > 1 {
+ // Check positions where mismatches occur (odd indices near tile boundaries)
+ eprintln!(
+ "[E2E] Row 1 positions (even=working, odd=corrupted?):"
+ );
+ for &pos in &[
+ 48, 56, 57, 58, 59, 60, 61, 62, 63, 64, 120, 121, 122, 123,
+ 124, 125, 126, 127, 128,
+ ] {
+ let idx = 1 * d_model + pos;
+ if idx < y_partial_full.len() {
+ eprintln!(
+ "[E2E] y_partial[row1, col {}] = {:.3}",
+ pos,
+ f32::from(y_partial_full[idx])
+ );
+ }
+ }
+ }
+ }
+ }
+
+ let y_cpu = moe_cpu_reference(
+ &x,
+ &router_weight_f32,
+ &router_bias_f32,
+ &w13_cpu,
+ &w2_cpu,
+ &up_biases,
+ &down_biases,
+ t,
+ e,
+ k,
+ d_model,
+ d_ff,
+ gating_code,
+ silu_alpha,
+ gate_clip,
+ up_clip,
+ );
+
+ // Compare GPU vs CPU
+ eprintln!("[E2E] Comparing GPU vs CPU outputs...");
+ let mut max_abs_diff = 0.0f32;
+ let mut max_rel_diff = 0.0f32;
+ let mut total_abs_error = 0.0f32;
+ let mut mismatches = 0;
+
+ for i in 0..(t * d_model) {
+ let gpu_val = y_out_gpu[i];
+ let cpu_val = y_cpu[i];
+ let abs_diff = (gpu_val - cpu_val).abs();
+ let rel_diff = if cpu_val.abs() > 1e-6 {
+ abs_diff / cpu_val.abs()
+ } else {
+ abs_diff
+ };
+
+ max_abs_diff = max_abs_diff.max(abs_diff);
+ max_rel_diff = max_rel_diff.max(rel_diff);
+ total_abs_error += abs_diff;
+
+ let threshold_rel = 0.1;
+ let threshold_abs = 1e-3;
+
+ if rel_diff > threshold_rel && abs_diff > threshold_abs {
+ let print_limit =
+ if test_name.contains("BoundarySweep_D1024_FF256_T2") {
+ usize::MAX // Print ALL for debugging
+ } else {
+ 10
+ };
+ if mismatches < print_limit {
+ eprintln!(
+ "[{}] Mismatch idx {}: GPU={:.6}, CPU={:.6}, abs={:.6}, rel={:.6}",
+ test_name, i, gpu_val, cpu_val, abs_diff, rel_diff
+ );
+ }
+ mismatches += 1;
+ }
+ }
+
+ let mean_abs_error = total_abs_error / (t * d_model) as f32;
+
+ eprintln!(
+ "[E2E] Error metrics: max_abs={:.6}, max_rel={:.6}, mean_abs={:.6}, mismatches={}",
+ max_abs_diff, max_rel_diff, mean_abs_error, mismatches
+ );
+
+ // Debug: print some sample values from intermediate buffers
+ eprintln!("[E2E] === DEBUG: Intermediate values ===");
+ let topk_ids_gpu = unsafe {
+ std::slice::from_raw_parts(topk_ids_buf.contents() as *const i32, t * k)
+ };
+ let topk_probs_gpu = unsafe {
+ std::slice::from_raw_parts(
+ topk_probs_buf.contents() as *const bf16,
+ t * k,
+ )
+ };
+ eprintln!("[E2E] TopK IDs: {:?}", topk_ids_gpu);
+ eprintln!(
+ "[E2E] TopK Probs: {:?}",
+ topk_probs_gpu.iter().map(|&v| f32::from(v)).collect::<Vec<_>>()
+ );
+
+ let y_partial_gpu = unsafe {
+ std::slice::from_raw_parts(
+ y_partial_buf.contents() as *const bf16,
+ max_sumk * d_model,
+ )
+ };
+ let sumk_actual = unsafe { *(sumk_buf.contents() as *const u32) } as usize;
+ eprintln!("[E2E] sumk={}", sumk_actual);
+ let sample_size = 16.min(sumk_actual * d_model);
+ eprintln!(
+ "[E2E] y_partial sample (first {}): {:?}",
+ sample_size,
+ &y_partial_gpu[..sample_size]
+ .iter()
+ .map(|&v| f32::from(v))
+ .collect::<Vec<_>>()
+ );
+
+ // For multi-row debugging: print both rows
+ if sumk_actual > 1 && d_ff >= 256 {
+ eprintln!(
+ "[E2E] y_partial row 1 [{}-{}]: {:?}",
+ d_model,
+ d_model + 16,
+ &y_partial_gpu[d_model..d_model + 16]
+ .iter()
+ .map(|&v| f32::from(v))
+ .collect::<Vec<_>>()
+ );
+ }
+ let out_sample_size = 16.min(t * d_model);
+ eprintln!(
+ "[E2E] y_out sample (token 0): {:?}",
+ &y_out_gpu[..out_sample_size]
+ );
+ if t > 1 && d_model >= 512 {
+ eprintln!(
+ "[E2E] y_out sample (token 1, first 32): {:?}",
+ &y_out_gpu[d_model..d_model + 32]
+ .iter()
+ .map(|&v| f32::from(v))
+ .collect::<Vec<_>>()
+ );
+ }
+ eprintln!(
+ "[E2E] CPU ref sample (token 0): {:?}",
+ &y_cpu[..out_sample_size]
+ );
+ if t > 1 && d_model >= 512 {
+ eprintln!(
+ "[E2E] CPU ref sample (token 1): {:?}",
+ &y_cpu[d_model..d_model + 16]
+ );
+
+ // Compare token 1 outputs element-wise (more positions to find pattern)
+ let gpu_t1 = &y_out_gpu[d_model..];
+ let cpu_t1 = &y_cpu[d_model..];
+ eprintln!("[E2E] Token 1 detailed comparison:");
+ for i in
+ [0, 1, 2, 3, 4, 5, 6, 7, 15, 16, 17, 18, 48, 64, 121, 128].iter()
+ {
+ if *i < d_model {
+ let diff = (f32::from(gpu_t1[*i]) - cpu_t1[*i]).abs();
+ eprintln!(
+ "[E2E] [{}]: GPU={:.6}, CPU={:.6}, diff={:.6}",
+ i,
+ f32::from(gpu_t1[*i]),
+ cpu_t1[*i],
+ diff
+ );
+ }
+ }
+ }
+
+ let k0_iters = (d_model + 31) / 32;
+ let ff0_iters = (d_ff + 31) / 32;
+ let product = k0_iters * ff0_iters;
+ let sqrt_product = (product as f32).sqrt();
+
+ let multi_expert_drift = 0.03 * sqrt_product * (k as f32 / 2.0);
+ let mean_abs_threshold = 0.1f32.max(multi_expert_drift);
+
+ if mean_abs_error >= mean_abs_threshold {
+ panic!(
+ "[{}] Mean absolute error {:.6} exceeds threshold {:.6}",
+ test_name, mean_abs_error, mean_abs_threshold
+ );
+ }
+
+ // Warn on high max_rel but don't fail (can be inflated by near-zero values)
+ if max_rel_diff > 1.0 && mismatches > (t * d_model / 4) {
+ eprintln!(
+ "[{}] WARNING: High max_rel={:.2} with {} mismatches, but mean_abs={:.6} is acceptable",
+ test_name, max_rel_diff, mismatches, mean_abs_error
+ );
+ }
+
+ eprintln!("[{}] ✓ PASSED (GPU matches CPU reference)", test_name);
+}
+
+#[test]
+fn test_moe_basic() {
+ let ctx = create_ctx();
+
+ // Test 1: Minimal (K=1, small dims, no clipping, alpha=1.0)
+ run_moe_parity_test(
+ &ctx,
+ 1, // t
+ 2, // e
+ 1, // k
+ 4, // d_model
+ 4, // d_ff
+ 2, // gating_code (SwiGLU)
+ 1.0, // silu_alpha
+ (f32::NEG_INFINITY, f32::INFINITY), // gate_clip
+ (f32::NEG_INFINITY, f32::INFINITY), // up_clip
+ 0xE2E_0001,
+ "Minimal_K1_SwiGLU",
+ );
+
+ // Test 2: Multi-expert (K=2, tests finalize weighted sum)
+ run_moe_parity_test(
+ &ctx,
+ 2, // t
+ 4, // e
+ 2, // k
+ 8, // d_model
+ 8, // d_ff
+ 2, // gating_code (SwiGLU)
+ 1.702, // silu_alpha (GPT-OSS value)
+ (f32::NEG_INFINITY, 7.0), // gate_clip (GPT-OSS config)
+ (-6.0, 8.0), // up_clip (GPT-OSS config)
+ 0xE2E_0002,
+ "Multi_K2_SwiGLU",
+ );
+
+ // Test 3: Large d_model only (K=1 to isolate from finalize complexity)
+ run_moe_parity_test(
+ &ctx,
+ 1, // t
+ 2, // e
+ 1, // k
+ 64, // d_model (tests k0 chunking)
+ 8, // d_ff (single ff0 chunk)
+ 2, // gating_code (SwiGLU)
+ 1.0,
+ (f32::NEG_INFINITY, f32::INFINITY),
+ (f32::NEG_INFINITY, f32::INFINITY),
+ 0xE2E_0003,
+ "LargeDModel64",
+ );
+
+ // Test 4a: d_ff=32 (exactly 1 full chunk - baseline for multi-chunk)
+ run_moe_parity_test(
+ &ctx,
+ 1, // t
+ 2, // e
+ 1, // k
+ 8, // d_model
+ 32, // d_ff (exactly 1 full chunk)
+ 2, // gating_code (SwiGLU)
+ 1.0,
+ (f32::NEG_INFINITY, f32::INFINITY),
+ (f32::NEG_INFINITY, f32::INFINITY),
+ 0xE2E_0004,
+ "LargeFF32_SingleChunk",
+ );
+
+ // Test 4b: d_ff=48 (1.5 chunks - tests partial second chunk)
+ run_moe_parity_test(
+ &ctx,
+ 1, // t
+ 2, // e
+ 1, // k
+ 8, // d_model
+ 48, // d_ff (1 full + 1 partial chunk)
+ 2, // gating_code (SwiGLU)
+ 1.0,
+ (f32::NEG_INFINITY, f32::INFINITY),
+ (f32::NEG_INFINITY, f32::INFINITY),
+ 0xE2E_0005,
+ "LargeFF48_Partial",
+ );
+
+ // Test 4c: d_ff=64 (exactly 2 full chunks)
+ run_moe_parity_test(
+ &ctx,
+ 1, // t
+ 2, // e
+ 1, // k
+ 8, // d_model
+ 64, // d_ff (exactly 2 full chunks)
+ 2, // gating_code (SwiGLU)
+ 1.0,
+ (f32::NEG_INFINITY, f32::INFINITY),
+ (f32::NEG_INFINITY, f32::INFINITY),
+ 0xE2E_0006,
+ "LargeFF64_TwoChunks",
+ );
+
+ // Test 5: GELU activation (gating_code=0)
+ run_moe_parity_test(
+ &ctx,
+ 1, // t
+ 2, // e
+ 1, // k
+ 8, // d_model
+ 16, // d_ff
+ 0, // gating_code (GELU)
+ 1.0, // silu_alpha (unused for GELU)
+ (f32::NEG_INFINITY, f32::INFINITY),
+ (f32::NEG_INFINITY, f32::INFINITY),
+ 0xE2E_0007,
+ "GELU_Activation",
+ );
+
+ // Test 6: SiLU activation (gating_code=1)
+ run_moe_parity_test(
+ &ctx,
+ 1, // t
+ 2, // e
+ 1, // k
+ 8, // d_model
+ 16, // d_ff
+ 1, // gating_code (SiLU)
+ 1.702,
+ (f32::NEG_INFINITY, f32::INFINITY),
+ (f32::NEG_INFINITY, f32::INFINITY),
+ 0xE2E_0008,
+ "SiLU_Activation",
+ );
+
+ // Test 7: GEGLU activation (gating_code=3)
+ run_moe_parity_test(
+ &ctx,
+ 1, // t
+ 2, // e
+ 1, // k
+ 8, // d_model
+ 16, // d_ff
+ 3, // gating_code (GEGLU)
+ 1.0, // silu_alpha (unused for GEGLU)
+ (f32::NEG_INFINITY, f32::INFINITY),
+ (f32::NEG_INFINITY, f32::INFINITY),
+ 0xE2E_0009,
+ "GEGLU_Activation",
+ );
+
+ // Test 8: Bucket stress - multiple tokens, larger E, stress scatter/gather
+ run_moe_parity_test(
+ &ctx,
+ 8, // t (8 tokens)
+ 8, // e (8 experts)
+ 2, // k (each token picks 2 experts)
+ 16, // d_model
+ 32, // d_ff
+ 2, // gating_code (SwiGLU)
+ 1.0,
+ (f32::NEG_INFINITY, f32::INFINITY),
+ (f32::NEG_INFINITY, f32::INFINITY),
+ 0xE2E_0010,
+ "BucketStress_T8_E8_K2",
+ );
+
+ // Test 9a: K=4 small-scale to verify multi-expert accumulation
+ run_moe_parity_test(
+ &ctx,
+ 2, // t
+ 4, // e
+ 4, // k (all experts)
+ 8, // d_model
+ 16, // d_ff
+ 2, // gating_code (SwiGLU)
+ 1.0,
+ (f32::NEG_INFINITY, f32::INFINITY),
+ (f32::NEG_INFINITY, f32::INFINITY),
+ 0xE2E_0011,
+ "Multi_K4_Small",
+ );
+
+ // Test 9a: d_model=128 (4 k0 chunks, 2 n-tiles)
+ run_moe_parity_test(
+ &ctx,
+ 2, // t
+ 4, // e
+ 1, // k
+ 128, // d_model (4 k0 chunks, 2 n-tiles)
+ 32, // d_ff
+ 2, // gating_code (SwiGLU)
+ 1.0,
+ (f32::NEG_INFINITY, f32::INFINITY),
+ (f32::NEG_INFINITY, f32::INFINITY),
+ 0xE2E_0012,
+ "MultiNTile_D128",
+ );
+
+ // Test 9b: d_model=192 (6 k0 chunks, 3 n-tiles - test threshold)
+ run_moe_parity_test(
+ &ctx,
+ 2, // t
+ 4, // e
+ 1, // k
+ 192, // d_model (6 k0 chunks, 3 n-tiles)
+ 32, // d_ff
+ 2, // gating_code (SwiGLU)
+ 1.0,
+ (f32::NEG_INFINITY, f32::INFINITY),
+ (f32::NEG_INFINITY, f32::INFINITY),
+ 0xE2E_0013,
+ "MultiNTile_D192_3tiles",
+ );
+
+ // Test 9c: d_model=256 (8 k0 chunks, 4 n-tiles)
+ run_moe_parity_test(
+ &ctx,
+ 2, // t
+ 4, // e
+ 1, // k
+ 256, // d_model (8 k0 chunks, 4 n-tiles)
+ 32, // d_ff
+ 2, // gating_code (SwiGLU)
+ 1.0,
+ (f32::NEG_INFINITY, f32::INFINITY),
+ (f32::NEG_INFINITY, f32::INFINITY),
+ 0xE2E_0014,
+ "MultiNTile_D256_4tiles",
+ );
+
+ // Test 10a: Isolate large d_ff with small d_model (FF accumulation test)
+ run_moe_parity_test(
+ &ctx,
+ 2, // t
+ 4, // e
+ 1, // k
+ 64, // d_model (small, 1 n-tile, 2 k0 chunks)
+ 14336, // d_ff (448 ff0 chunks!) - production scale
+ 2, // gating_code (SwiGLU)
+ 1.0,
+ (f32::NEG_INFINITY, f32::INFINITY),
+ (f32::NEG_INFINITY, f32::INFINITY),
+ 0xE2E_0016,
+ "IsolateFF_D64_FF14336_K1",
+ );
+
+ // Test 10b: d_model=1024 (16 n-tiles)
+ run_moe_parity_test(
+ &ctx,
+ 2, // t
+ 4, // e
+ 1, // k
+ 1024, // d_model (32 k0 chunks, 16 n-tiles)
+ 64, // d_ff (small)
+ 2, // gating_code (SwiGLU)
+ 1.0,
+ (f32::NEG_INFINITY, f32::INFINITY),
+ (f32::NEG_INFINITY, f32::INFINITY),
+ 0xE2E_0017,
+ "IsolateD_D1024_FF64_K1",
+ );
+
+ // Test 10c: Verify layout with d_model=96, d_ff=96 (3 chunks each)
+ // This tests non-power-of-2 to catch stride bugs
+ run_moe_parity_test(
+ &ctx,
+ 1, // t (single token)
+ 2, // e
+ 1, // k
+ 96, // d_model (3 k0 chunks - odd number)
+ 96, // d_ff (3 ff0 chunks - odd number)
+ 2, // gating_code (SwiGLU)
+ 1.0,
+ (f32::NEG_INFINITY, f32::INFINITY),
+ (f32::NEG_INFINITY, f32::INFINITY),
+ 0xE2E_0018,
+ "VerifyLayout_D96_FF96",
+ );
+
+ // Test 10d: d_model=1536
+ run_moe_parity_test(
+ &ctx,
+ 2, // t
+ 4, // e
+ 1, // k
+ 1536, // d_model (48 k0 chunks, 24 n-tiles)
+ 64, // d_ff (small)
+ 2, // gating_code (SwiGLU)
+ 1.0,
+ (f32::NEG_INFINITY, f32::INFINITY),
+ (f32::NEG_INFINITY, f32::INFINITY),
+ 0xE2E_0019,
+ "IsolateD_D1536_FF64_K1",
+ );
+
+ // Test 10e: 2 n-tiles
+ run_moe_parity_test(
+ &ctx,
+ 1, // t
+ 2, // e
+ 1, // k
+ 128, // d_model (2 n-tiles)
+ 256, // d_ff
+ 2, // gating_code (SwiGLU)
+ 1.0,
+ (f32::NEG_INFINITY, f32::INFINITY),
+ (f32::NEG_INFINITY, f32::INFINITY),
+ 0xE2E_0020,
+ "NTileTest_D128_2tiles",
+ );
+
+ // Test 10g: 8 n-tiles - find threshold
+ run_moe_parity_test(
+ &ctx,
+ 1, // t
+ 2, // e
+ 1, // k
+ 512, // d_model (8 n-tiles)
+ 256, // d_ff
+ 2, // gating_code (SwiGLU)
+ 1.0,
+ (f32::NEG_INFINITY, f32::INFINITY),
+ (f32::NEG_INFINITY, f32::INFINITY),
+ 0xE2E_0021,
+ "NTileTest_D512_8tiles",
+ );
+}
+
+#[test]
+#[ignore]
+fn test_moe_production_scale() {
+ let ctx = create_ctx();
+
+ // Test 11b: Production scale with clipping but K=1
+ run_moe_parity_test(
+ &ctx,
+ 2, // t
+ 8, // e
+ 1, // k
+ 4096, // d_model
+ 14336, // d_ff
+ 2, // gating_code (SwiGLU)
+ 1.702, // silu_alpha (GPT-OSS value)
+ (f32::NEG_INFINITY, 20.0), // gate_clip_max
+ (-19.0, 21.0), // up_clip
+ 0xE2E_0029,
+ "ProductionScale_D4096_H14336_E8_K1",
+ );
+
+ // Test 11c: PRODUCTION SCALE T=1 decode (triggers GEMV v2)
+ run_moe_parity_test(
+ &ctx,
+ 1, // t (single token decode)
+ 16, // e (16 experts)
+ 2, // k (2 experts per token)
+ 4096, // d_model
+ 14336, // d_ff
+ 2, // gating_code (SwiGLU)
+ 1.702, // silu_alpha (GPT-OSS value)
+ (f32::NEG_INFINITY, 20.0), // gate_clip_max (GPT-OSS config)
+ (-19.0, 21.0), // up_clip (GPT-OSS config)
+ 0xE2E_0030,
+ "ProductionScale_T1_D4096_H14336_E16_K2",
+ );
+
+ // Test 11d: FULL PRODUCTION SCALE with K=2, T=4 (uses tiled MMA)
+ run_moe_parity_test(
+ &ctx,
+ 4, // t (4 tokens)
+ 16, // e (16 experts)
+ 2, // k (2 experts per token)
+ 4096, // d_model (128 k0 chunks, 64 n-tiles!)
+ 14336, // d_ff (448 ff0 chunks!)
+ 2, // gating_code (SwiGLU)
+ 1.702, // silu_alpha (GPT-OSS value)
+ (f32::NEG_INFINITY, 20.0), // gate_clip_max (GPT-OSS config)
+ (-19.0, 21.0), // up_clip (GPT-OSS config)
+ 0xE2E_0031,
+ "ProductionScale_D4096_H14336_E16_K2",
+ );
+}
diff --git a/crates/uzu/tests/moe/moe_experts_perf_test.rs b/crates/uzu/tests/moe/moe_experts_perf_test.rs
new file mode 100644
index 000000000..8f705b296
--- /dev/null
+++ b/crates/uzu/tests/moe/moe_experts_perf_test.rs
@@ -0,0 +1,356 @@
+use std::time::Instant;
+
+use half::bf16;
+use rand::{Rng, SeedableRng, rngs::StdRng};
+use uzu::backends::metal::{
+ KernelDataType, MTLContext,
+ kernel::moe::{
+ MoeExpertsTwoPassArguments, MoeExpertsTwoPassDecodeKernel,
+ MoeExpertsTwoPassPrefillKernel,
+ },
+};
+
+use super::test_utils::{alloc_buffer, alloc_buffer_with_data, create_ctx};
+
+fn build_offsets(
+ e: usize,
+ sum_k: usize,
+) -> Vec<u32> {
+ let mut offsets = vec![0u32; e + 1];
+ let mut running = 0u32;
+ let mut remaining = sum_k;
+ for expert in 0..e {
+ offsets[expert] = running;
+ if remaining > 0 {
+ running += 1;
+ remaining -= 1;
+ }
+ }
+ offsets[e] = running;
+ offsets
+}
+
+fn run_decode_case(
+ ctx: &MTLContext,
+ name: &str,
+ t: usize,
+ d_model: usize,
+ d_ff: usize,
+ e: usize,
+ k: usize,
+ warmup: usize,
+ iters: usize,
+) {
+ const K_TILE: usize = 64;
+
+ let mut rng = StdRng::seed_from_u64(0xDEC0DE1234567890);
+ let sum_k = t * k;
+
+ eprintln!(
+ "\n[decode/two-pass] {} => T={}, D={}, FF={}, E={}, K={}, sum_k={}",
+ name, t, d_model, d_ff, e, k, sum_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);
+
+ // Generate W13 in original layout [E, d_model, 2*d_ff]
+ let w13_original: Vec<bf16> = (0..e * d_model * 2 * d_ff)
+ .map(|_| bf16::from_f32(rng.random_range(-0.05..0.05)))
+ .collect();
+
+ // Transpose to GPU layout [E, 2*d_ff, d_model]
+ 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 =
+ MoeExpertsTwoPassDecodeKernel::new(ctx).expect("experts decode kernel");
+
+ let x_perm_buf = alloc_buffer_with_data(&ctx, &x_perm);
+ let offsets_buf = alloc_buffer_with_data(&ctx, &offsets);
+
+ let w13_buf = alloc_buffer_with_data(&ctx, &w13);
+
+ let w2_buf = alloc_buffer_with_data(&ctx, &w2);
+
+ let up_biases_buf = alloc_buffer_with_data(&ctx, &up_biases);
+ let down_biases_buf = alloc_buffer_with_data(&ctx, &down_biases);
+
+ let num_tiles_k = ((d_ff + K_TILE - 1) / K_TILE) as usize;
+
+ let hidden_buf = alloc_buffer::<f32>(&ctx, sum_k * d_ff);
+ let output_buf = alloc_buffer::<bf16>(&ctx, sum_k * d_model);
+
+ // Buffers for indirect dispatch
+ let tile_counts_buf = alloc_buffer::<u32>(&ctx, e);
+ let tile_offsets_buf = alloc_buffer::<u32>(&ctx, e + 1);
+ let max_tiles = e * sum_k * 16384; // Conservative upper bound
+ let tile_map_buf = alloc_buffer::<u32>(&ctx, max_tiles * 3);
+ let total_tiles_buf = alloc_buffer::<u32>(&ctx, 1);
+ let dispatch_args_buf = alloc_buffer::<u32>(&ctx, 3);
+ let row_expert_map_buf = alloc_buffer::<u32>(&ctx, sum_k);
+
+ let make_two_pass_args = || MoeExpertsTwoPassArguments {
+ x_perm_buffer: &x_perm_buf,
+ expert_offsets: &offsets_buf,
+ row_expert_map: &row_expert_map_buf,
+ hidden_buffer: &hidden_buf,
+ output_buffer: &output_buf,
+ w13_all: &w13_buf,
+ w2_all: &w2_buf,
+ up_biases: &up_biases_buf,
+ down_biases: &down_biases_buf,
+ tile_counts: &tile_counts_buf,
+ tile_offsets: &tile_offsets_buf,
+ tile_map: &tile_map_buf,
+ total_tiles: &total_tiles_buf,
+ dispatch_args: &dispatch_args_buf,
+ total_rows: sum_k,
+ d_model,
+ d_ff,
+ e,
+ num_tiles_k: num_tiles_k as u32,
+ gating_code: 2,
+ 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: KernelDataType::BFloat16,
+ };
+
+ for _ in 0..warmup {
+ let cb = ctx.command_queue.new_command_buffer();
+ experts_kernel
+ .encode(&cb, make_two_pass_args())
+ .expect("two-pass encode");
+ cb.commit();
+ cb.wait_until_completed();
+ }
+
+ let mut times = Vec::with_capacity(iters);
+ for _ in 0..iters {
+ let start = Instant::now();
+ let cb = ctx.command_queue.new_command_buffer();
+ experts_kernel
+ .encode(&cb, make_two_pass_args())
+ .expect("two-pass encode");
+ cb.commit();
+ cb.wait_until_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 / t as f64) * 1000.0);
+}
+
+#[test]
+#[ignore]
+fn test_two_pass_decode_speed() {
+ let ctx = create_ctx();
+
+ let cases = vec![
+ ("T1_E16_D1024_F4096", 1, 1024, 4096, 16, 4, 3, 20),
+ ("T1_E8_D2048_F8192", 1, 2048, 8192, 8, 4, 3, 20),
+ ];
+
+ for (name, t, d_model, d_ff, e, k, warmup, iters) in &cases {
+ run_decode_case(
+ &ctx, name, *t, *d_model, *d_ff, *e, *k, *warmup, *iters,
+ );
+ }
+}
+
+fn run_two_pass_prefill_case(
+ ctx: &MTLContext,
+ name: &str,
+ t: usize,
+ d_model: usize,
+ d_ff: usize,
+ e: usize,
+ k: usize,
+ warmup: usize,
+ iters: usize,
+) {
+ const K_TILE: usize = 64;
+
+ let mut rng = StdRng::seed_from_u64(0xDEC0DE1234567890);
+ let sum_k = t * k;
+
+ eprintln!(
+ "\n[2-pass prefill] {} => T={}, D={}, FF={}, E={}, K={}, sum_k={}",
+ name, t, d_model, d_ff, e, k, sum_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 = MoeExpertsTwoPassPrefillKernel::new(ctx)
+ .expect("experts prefill kernel");
+
+ let x_perm_buf = alloc_buffer_with_data(&ctx, &x_perm);
+ let offsets_buf = alloc_buffer_with_data(&ctx, &offsets);
+ let w13_buf = alloc_buffer_with_data(&ctx, &w13);
+ let w2_buf = alloc_buffer_with_data(&ctx, &w2);
+ let up_biases_buf = alloc_buffer_with_data(&ctx, &up_biases);
+ let down_biases_buf = alloc_buffer_with_data(&ctx, &down_biases);
+
+ let num_tiles_k = ((d_ff + K_TILE - 1) / K_TILE) as usize;
+
+ let hidden_buf = alloc_buffer::<f32>(&ctx, sum_k * d_ff);
+ let output_buf = alloc_buffer::<bf16>(&ctx, sum_k * d_model);
+
+ let tile_counts_buf = alloc_buffer::<u32>(&ctx, e);
+ let tile_offsets_buf = alloc_buffer::<u32>(&ctx, e + 1);
+ let max_tiles = e * sum_k * 16384;
+ let tile_map_buf = alloc_buffer::<u32>(&ctx, max_tiles * 3);
+ let total_tiles_buf = alloc_buffer::<u32>(&ctx, 1);
+ let dispatch_args_buf = alloc_buffer::<u32>(&ctx, 3);
+ let row_expert_map_buf = alloc_buffer::<u32>(&ctx, sum_k);
+
+ let make_two_pass_args = || MoeExpertsTwoPassArguments {
+ x_perm_buffer: &x_perm_buf,
+ expert_offsets: &offsets_buf,
+ row_expert_map: &row_expert_map_buf,
+ hidden_buffer: &hidden_buf,
+ output_buffer: &output_buf,
+ w13_all: &w13_buf,
+ w2_all: &w2_buf,
+ up_biases: &up_biases_buf,
+ down_biases: &down_biases_buf,
+ tile_counts: &tile_counts_buf,
+ tile_offsets: &tile_offsets_buf,
+ tile_map: &tile_map_buf,
+ total_tiles: &total_tiles_buf,
+ dispatch_args: &dispatch_args_buf,
+ total_rows: sum_k,
+ d_model,
+ d_ff,
+ e,
+ num_tiles_k: num_tiles_k as u32,
+ gating_code: 2,
+ 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: KernelDataType::BFloat16,
+ };
+
+ for _ in 0..warmup {
+ let cb = ctx.command_queue.new_command_buffer();
+ experts_kernel
+ .encode(&cb, make_two_pass_args())
+ .expect("two-pass prefill encode");
+ cb.commit();
+ cb.wait_until_completed();
+ }
+
+ let mut times = Vec::with_capacity(iters);
+ for _ in 0..iters {
+ let start = Instant::now();
+ let cb = ctx.command_queue.new_command_buffer();
+ experts_kernel
+ .encode(&cb, make_two_pass_args())
+ .expect("two-pass prefill encode");
+ cb.commit();
+ cb.wait_until_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!(
+ " → Throughput: {:.1} µs/token (mean / sum_k)",
+ (mean / sum_k as f64) * 1000.0
+ );
+}
+
+#[test]
+#[ignore]
+fn test_two_pass_prefill_speed() {
+ let ctx = create_ctx();
+
+ let cases = vec![
+ ("T32_E16_D1024_F4096", 32, 1024, 4096, 16, 4, 2, 10),
+ ("T64_E16_D2048_F6144", 64, 2048, 6144, 16, 4, 2, 10),
+ ];
+
+ for (name, t, d_model, d_ff, e, k, warmup, iters) in cases {
+ run_two_pass_prefill_case(
+ &ctx, name, t, d_model, d_ff, e, k, warmup, iters,
+ );
+ }
+}
diff --git a/crates/uzu/tests/moe/moe_experts_test.rs b/crates/uzu/tests/moe/moe_experts_test.rs
new file mode 100644
index 000000000..7aab2d2fe
--- /dev/null
+++ b/crates/uzu/tests/moe/moe_experts_test.rs
@@ -0,0 +1,616 @@
+//! Unit correctness tests for MoE Expert kernels (both 1-pass and 2-pass variants)
+//!
+//! Tests verify:
+//! - Decode (suffix_length=1) with 2-pass tiled implementation
+//! - Prefill (suffix_length>1) with 2-pass tiled implementation
+//! - Intermediate buffer correctness (row maps, tiles, dispatch args)
+//! - Numerical correctness against CPU reference
+
+#![cfg(any(target_os = "macos", target_os = "ios"))]
+
+use half::bf16;
+use rand::{Rng, SeedableRng, rngs::StdRng};
+use uzu::backends::metal::{
+ KernelDataType,
+ kernel::moe::{
+ MoeExpertsTwoPassArguments, MoeExpertsTwoPassDecodeKernel,
+ MoeExpertsTwoPassPrefillKernel,
+ },
+};
+
+#[path = "moe_test_utils.rs"]
+mod test_utils;
+use test_utils::{
+ alloc_buffer, alloc_buffer_with_data, assert_bf16_close, cpu_tile_counts,
+ cpu_tile_scan, create_ctx,
+};
+
+/// Build expert segment offsets - distributes sum_k rows across e experts
+fn build_offsets(
+ e: usize,
+ sum_k: usize,
+) -> Vec<u32> {
+ let mut offsets = vec![0u32; e + 1];
+ let base_rows = sum_k / e;
+ let extra = sum_k % e;
+
+ for i in 0..=e {
+ offsets[i] = (base_rows * i + extra.min(i)) as u32;
+ }
+ offsets
+}
+
+/// Build row-expert map: maps each row to its expert index
+fn build_row_expert_map(
+ offsets: &[u32],
+ sum_k: usize,
+) -> Vec<u32> {
+ let e = offsets.len() - 1;
+ let mut row_map = vec![0u32; sum_k];
+
+ for expert in 0..e {
+ let start = offsets[expert] as usize;
+ let end = offsets[expert + 1] as usize;
+ for row in start..end {
+ row_map[row] = expert as u32;
+ }
+ }
+ row_map
+}
+
+/// CPU reference for full expert computation matching GPU implementation
+///
+/// Supports 4 gating modes:
+/// - 0: GELU(up)
+/// - 1: SiLU(up)
+/// - 2: SwiGLU = SiLU(gate) * up
+/// - 3: GEGLU = GELU(gate) * up
+fn cpu_expert_ffn_full(
+ x_perm: &[bf16], // [sum_k, d_model]
+ offsets: &[u32], // [E+1]
+ w13: &[bf16], // [E, 2*d_ff, d_model] transposed
+ w2: &[bf16], // [E, d_model, d_ff] transposed
+ up_biases: &[bf16], // [E, 2*d_ff]
+ down_biases: &[bf16], // [E, d_model]
+ d_model: usize,
+ d_ff: usize,
+ gating_code: u32,
+ silu_alpha: f32,
+) -> (Vec<f32>, Vec<bf16>) {
+ let e = offsets.len() - 1;
+ let sum_k = x_perm.len() / d_model;
+ let mut hidden_full = vec![0.0f32; sum_k * d_ff];
+ let mut output = vec![bf16::from_f32(0.0); sum_k * d_model];
+
+ // Helper functions matching Metal kernels
+ let gelu_approx = |x: f32| -> f32 {
+ const K0: f32 = 0.7978845608;
+ const K1: f32 = 0.044715;
+ if x > 10.0 {
+ return x;
+ }
+ if x < -10.0 {
+ return 0.0;
+ }
+ let x3 = x * x * x;
+ let inner = x + K1 * x3;
+ let tanh_arg = (K0 * inner).clamp(-10.0, 10.0);
+ 0.5 * x * (1.0 + tanh_arg.tanh())
+ };
+
+ let silu = |x: f32, alpha: f32| -> f32 { x / (1.0 + (-alpha * x).exp()) };
+
+ for expert in 0..e {
+ let row_start = offsets[expert] as usize;
+ let row_end = offsets[expert + 1] as usize;
+ let expert_rows = row_end - row_start;
+
+ if expert_rows == 0 {
+ continue;
+ }
+
+ let w1_offset = expert * 2 * d_ff * d_model;
+ let w2_offset = expert * d_model * d_ff;
+
+ // FC1: [expert_rows, d_model] @ [d_model, 2*d_ff] -> [expert_rows, 2*d_ff]
+ let mut hidden = vec![bf16::from_f32(0.0); expert_rows * 2 * d_ff];
+ for row in 0..expert_rows {
+ for ff in 0..(2 * d_ff) {
+ let mut acc = f32::from(up_biases[expert * 2 * d_ff + ff]);
+ for dm in 0..d_model {
+ let x_val =
+ f32::from(x_perm[(row_start + row) * d_model + dm]);
+ // w13 transposed: [2*d_ff, d_model]
+ let w_val = f32::from(w13[w1_offset + ff * d_model + dm]);
+ acc += x_val * w_val;
+ }
+ hidden[row * 2 * d_ff + ff] = bf16::from_f32(acc);
+ }
+ }
+
+ // Apply activation based on gating_code
+ for row in 0..expert_rows {
+ for ff in 0..d_ff {
+ let up = f32::from(hidden[row * 2 * d_ff + ff]);
+
+ let result = if gating_code <= 1 {
+ // GELU(up) or SiLU(up) - no gating
+ if gating_code == 0 {
+ gelu_approx(up)
+ } else {
+ silu(up, silu_alpha)
+ }
+ } else {
+ // SwiGLU or GEGLU - gate * up
+ let gate = f32::from(hidden[row * 2 * d_ff + d_ff + ff]);
+ let activated_gate = if gating_code == 2 {
+ silu(gate, silu_alpha)
+ } else {
+ gelu_approx(gate)
+ };
+ activated_gate * up
+ };
+
+ hidden[row * 2 * d_ff + ff] = bf16::from_f32(result);
+ hidden_full[(row_start + row) * d_ff + ff] = result;
+ }
+ }
+
+ // FC2: [expert_rows, d_ff] @ [d_ff, d_model] -> [expert_rows, d_model]
+ for row in 0..expert_rows {
+ for dm in 0..d_model {
+ let mut acc = f32::from(down_biases[expert * d_model + dm]);
+ for ff in 0..d_ff {
+ let h_val = f32::from(hidden[row * 2 * d_ff + ff]);
+ // w2 transposed: [d_model, d_ff]
+ let w_val = f32::from(w2[w2_offset + dm * d_ff + ff]);
+ acc += h_val * w_val;
+ }
+ output[(row_start + row) * d_model + dm] = bf16::from_f32(acc);
+ }
+ }
+ }
+
+ (hidden_full, output)
+}
+
+#[test]
+fn test_two_pass_decode_correctness() {
+ let ctx = create_ctx();
+ let mut rng = StdRng::seed_from_u64(0xDEC0DE42);
+
+ // Realistic decode test case: single token, K=2
+ let t = 1;
+ let k = 2;
+ let sum_k = t * k;
+ let d_model = 512;
+ let d_ff = 2048;
+ let e = 8;
+
+ eprintln!(
+ "[2-pass decode] T={}, K={}, sum_k={}, d_model={}, d_ff={}, E={}",
+ t, k, sum_k, d_model, d_ff, e
+ );
+
+ // Generate test data
+ 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 row_expert_map = build_row_expert_map(&offsets, sum_k);
+
+ // Generate weights (W13 in GPU transposed layout [E, 2*d_ff, d_model])
+ let w13: Vec<bf16> = (0..e * 2 * d_ff * d_model)
+ .map(|_| bf16::from_f32(rng.random_range(-0.05..0.05)))
+ .collect();
+ 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();
+
+ // CPU reference (gating_code=0 means GELU)
+ let (_hidden_expected, expected) = cpu_expert_ffn_full(
+ &x_perm,
+ &offsets,
+ &w13,
+ &w2,
+ &up_biases,
+ &down_biases,
+ d_model,
+ d_ff,
+ 0,
+ 1.0,
+ );
+
+ // Prepare GPU buffers
+ let x_perm_buf = alloc_buffer_with_data(&ctx, &x_perm);
+ let offsets_buf = alloc_buffer_with_data(&ctx, &offsets);
+ let row_expert_map_buf = alloc_buffer_with_data(&ctx, &row_expert_map);
+ let w13_buf = alloc_buffer_with_data(&ctx, &w13);
+ let w2_buf = alloc_buffer_with_data(&ctx, &w2);
+ let up_biases_buf = alloc_buffer_with_data(&ctx, &up_biases);
+ let down_biases_buf = alloc_buffer_with_data(&ctx, &down_biases);
+
+ // Intermediate buffers - hidden is f32 for activation precision
+ let hidden_buf = alloc_buffer::<f32>(&ctx, sum_k * d_ff);
+ let output_buf = alloc_buffer::<bf16>(&ctx, sum_k * d_model);
+
+ // Tile infrastructure
+ let h_blocks_decode = (d_ff + 3) / 4;
+ let max_total_tiles = sum_k * h_blocks_decode;
+
+ let tile_counts_buf = alloc_buffer::<u32>(&ctx, e);
+ let tile_offsets_buf = alloc_buffer::<u32>(&ctx, e + 1);
+ let total_tiles_buf = alloc_buffer::<u32>(&ctx, 8);
+ let tile_map_buf = alloc_buffer::<u32>(&ctx, max_total_tiles * 3);
+ let dispatch_args_buf = alloc_buffer::<u32>(&ctx, 3);
+
+ // Execute 2-pass decode kernel
+ let experts_kernel = MoeExpertsTwoPassDecodeKernel::new(&ctx)
+ .expect("MoeExpertsTwoPassDecodeKernel::new");
+ let cb = ctx.command_queue.new_command_buffer();
+
+ const K_TILE: usize = 64;
+ let num_tiles_k = ((d_ff + K_TILE - 1) / K_TILE) as u32;
+
+ experts_kernel
+ .encode(
+ &cb,
+ MoeExpertsTwoPassArguments {
+ x_perm_buffer: &x_perm_buf,
+ expert_offsets: &offsets_buf,
+ row_expert_map: &row_expert_map_buf,
+ hidden_buffer: &hidden_buf,
+ output_buffer: &output_buf,
+ w13_all: &w13_buf,
+ w2_all: &w2_buf,
+ up_biases: &up_biases_buf,
+ down_biases: &down_biases_buf,
+ tile_counts: &tile_counts_buf,
+ tile_offsets: &tile_offsets_buf,
+ tile_map: &tile_map_buf,
+ total_tiles: &total_tiles_buf,
+ dispatch_args: &dispatch_args_buf,
+ total_rows: sum_k,
+ d_model,
+ d_ff,
+ e,
+ num_tiles_k,
+ gating_code: 0, // GELU activation
+ gate_clip_min: -1e6,
+ gate_clip_max: 1e6,
+ up_clip_min: -1e6,
+ up_clip_max: 1e6,
+ silu_alpha: 1.0,
+ data_type: KernelDataType::BFloat16,
+ },
+ )
+ .expect("encode_two_pass_decode");
+
+ cb.commit();
+ cb.wait_until_completed();
+
+ // Read GPU output
+ let output_gpu = unsafe {
+ std::slice::from_raw_parts(
+ output_buf.contents() as *const bf16,
+ sum_k * d_model,
+ )
+ };
+
+ // Compute error metrics
+ let mut max_abs_error = 0.0f32;
+ let mut max_rel_error = 0.0f32;
+ let mut max_abs_idx = 0;
+ let mut max_rel_idx = 0;
+
+ for (i, (&gpu_val, &cpu_val)) in
+ output_gpu.iter().zip(expected.iter()).enumerate()
+ {
+ let gpu_f = f32::from(gpu_val);
+ let cpu_f = f32::from(cpu_val);
+ let abs_error = (gpu_f - cpu_f).abs();
+ let rel_error = if cpu_f.abs() > 1e-6 {
+ abs_error / cpu_f.abs()
+ } else {
+ 0.0
+ };
+
+ if abs_error > max_abs_error {
+ max_abs_error = abs_error;
+ max_abs_idx = i;
+ }
+ if rel_error > max_rel_error {
+ max_rel_error = rel_error;
+ max_rel_idx = i;
+ }
+ }
+
+ eprintln!(
+ "[2-pass decode] Max absolute error: {:.6} at index {} (GPU={:.6}, CPU={:.6})",
+ max_abs_error,
+ max_abs_idx,
+ f32::from(output_gpu[max_abs_idx]),
+ f32::from(expected[max_abs_idx])
+ );
+ eprintln!(
+ "[2-pass decode] Max relative error: {:.6} ({:.2}%) at index {} (GPU={:.6}, CPU={:.6})",
+ max_rel_error,
+ max_rel_error * 100.0,
+ max_rel_idx,
+ f32::from(output_gpu[max_rel_idx]),
+ f32::from(expected[max_rel_idx])
+ );
+
+ let tolerance = 0.01;
+
+ assert_bf16_close(output_gpu, &expected, tolerance, "2-pass decode output");
+
+ eprintln!("[2-pass decode] ✓ PASSED (tolerance={:.4})", tolerance);
+}
+
+#[test]
+fn test_two_pass_prefill_correctness() {
+ let ctx = create_ctx();
+ let mut rng = StdRng::seed_from_u64(0xFE1111);
+
+ // Realistic prefill case: 8 tokens, K=2
+ let t = 8;
+ let k = 2;
+ let sum_k = t * k;
+ let d_model = 512;
+ let d_ff = 2048;
+ let e = 8;
+
+ eprintln!(
+ "[2-pass prefill] T={}, K={}, sum_k={}, d_model={}, d_ff={}, E={}",
+ t, k, sum_k, d_model, d_ff, e
+ );
+
+ // Generate test data
+ 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 row_expert_map = build_row_expert_map(&offsets, sum_k);
+
+ // Generate weights
+ let w13: Vec<bf16> = (0..e * 2 * d_ff * d_model)
+ .map(|_| bf16::from_f32(rng.random_range(-0.05..0.05)))
+ .collect();
+ 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();
+
+ // CPU reference (gating_code=0 means GELU)
+ let (hidden_expected, expected) = cpu_expert_ffn_full(
+ &x_perm,
+ &offsets,
+ &w13,
+ &w2,
+ &up_biases,
+ &down_biases,
+ d_model,
+ d_ff,
+ 0,
+ 1.0,
+ );
+
+ // Prepare GPU buffers
+ let x_perm_buf = alloc_buffer_with_data(&ctx, &x_perm);
+ let offsets_buf = alloc_buffer_with_data(&ctx, &offsets);
+ let row_expert_map_buf = alloc_buffer_with_data(&ctx, &row_expert_map);
+ let w13_buf = alloc_buffer_with_data(&ctx, &w13);
+ let w2_buf = alloc_buffer_with_data(&ctx, &w2);
+ let up_biases_buf = alloc_buffer_with_data(&ctx, &up_biases);
+ let down_biases_buf = alloc_buffer_with_data(&ctx, &down_biases);
+
+ // Intermediate buffers - hidden is f32 for activation precision
+ let hidden_buf = alloc_buffer::<f32>(&ctx, sum_k * d_ff);
+ let output_buf = alloc_buffer::<bf16>(&ctx, sum_k * d_model);
+
+ // Tile infrastructure
+ let h_blocks_decode = (d_ff + 3) / 4;
+ let max_total_tiles = sum_k * h_blocks_decode;
+
+ let tile_counts_buf = alloc_buffer::<u32>(&ctx, e);
+ let tile_offsets_buf = alloc_buffer::<u32>(&ctx, e + 1);
+ let total_tiles_buf = alloc_buffer::<u32>(&ctx, 8);
+ let tile_map_buf = alloc_buffer::<u32>(&ctx, max_total_tiles * 3);
+ let dispatch_args_buf = alloc_buffer::<u32>(&ctx, 3);
+
+ // Execute 2-pass prefill kernel
+ let experts_kernel = MoeExpertsTwoPassPrefillKernel::new(&ctx)
+ .expect("MoeExpertsTwoPassPrefillKernel::new");
+ let cb = ctx.command_queue.new_command_buffer();
+
+ const K_TILE: usize = 64;
+ let num_tiles_k = ((d_ff + K_TILE - 1) / K_TILE) as u32;
+
+ experts_kernel
+ .encode(
+ &cb,
+ MoeExpertsTwoPassArguments {
+ x_perm_buffer: &x_perm_buf,
+ expert_offsets: &offsets_buf,
+ row_expert_map: &row_expert_map_buf,
+ hidden_buffer: &hidden_buf,
+ output_buffer: &output_buf,
+ w13_all: &w13_buf,
+ w2_all: &w2_buf,
+ up_biases: &up_biases_buf,
+ down_biases: &down_biases_buf,
+ tile_counts: &tile_counts_buf,
+ tile_offsets: &tile_offsets_buf,
+ tile_map: &tile_map_buf,
+ total_tiles: &total_tiles_buf,
+ dispatch_args: &dispatch_args_buf,
+ total_rows: sum_k,
+ d_model,
+ d_ff,
+ e,
+ num_tiles_k,
+ gating_code: 0, // GELU activation
+ gate_clip_min: -1e6,
+ gate_clip_max: 1e6,
+ up_clip_min: -1e6,
+ up_clip_max: 1e6,
+ silu_alpha: 1.0,
+ data_type: KernelDataType::BFloat16,
+ },
+ )
+ .expect("encode_two_pass_prefill");
+
+ cb.commit();
+ cb.wait_until_completed();
+
+ // Read GPU output
+ let output_gpu = unsafe {
+ std::slice::from_raw_parts(
+ output_buf.contents() as *const bf16,
+ sum_k * d_model,
+ )
+ };
+
+ // Compute error metrics
+ let mut max_abs_error = 0.0f32;
+ let mut max_rel_error = 0.0f32;
+ let mut max_abs_idx = 0;
+ let mut max_rel_idx = 0;
+
+ for (i, (&gpu_val, &cpu_val)) in
+ output_gpu.iter().zip(expected.iter()).enumerate()
+ {
+ let gpu_f = f32::from(gpu_val);
+ let cpu_f = f32::from(cpu_val);
+ let abs_error = (gpu_f - cpu_f).abs();
+ let rel_error = if cpu_f.abs() > 1e-6 {
+ abs_error / cpu_f.abs()
+ } else {
+ 0.0
+ };
+
+ if abs_error > max_abs_error {
+ max_abs_error = abs_error;
+ max_abs_idx = i;
+ }
+ if rel_error > max_rel_error {
+ max_rel_error = rel_error;
+ max_rel_idx = i;
+ }
+ }
+
+ eprintln!(
+ "[2-pass prefill] Max absolute error: {:.6} at index {} (GPU={:.6}, CPU={:.6})",
+ max_abs_error,
+ max_abs_idx,
+ f32::from(output_gpu[max_abs_idx]),
+ f32::from(expected[max_abs_idx])
+ );
+ eprintln!(
+ "[2-pass prefill] Max relative error: {:.6} ({:.2}%) at index {} (GPU={:.6}, CPU={:.6})",
+ max_rel_error,
+ max_rel_error * 100.0,
+ max_rel_idx,
+ f32::from(output_gpu[max_rel_idx]),
+ f32::from(expected[max_rel_idx])
+ );
+
+ // Verify correctness with tight tolerance
+ let tolerance = 0.01;
+
+ let hidden_gpu = unsafe {
+ std::slice::from_raw_parts(
+ hidden_buf.contents() as *const f32,
+ sum_k * d_ff,
+ )
+ };
+
+ let mut hidden_max_diff = 0.0f32;
+ let mut hidden_max_idx = 0usize;
+ for (idx, (&gpu, &cpu)) in
+ hidden_gpu.iter().zip(hidden_expected.iter()).enumerate()
+ {
+ let diff = (gpu - cpu).abs();
+ if diff > hidden_max_diff {
+ hidden_max_diff = diff;
+ hidden_max_idx = idx;
+ }
+ }
+
+ if hidden_max_diff > tolerance {
+ let row = hidden_max_idx / d_ff;
+ let col = hidden_max_idx % d_ff;
+ eprintln!(
+ "[2-pass prefill] hidden mismatch row={} col={} gpu={} cpu={} diff={}",
+ row,
+ col,
+ hidden_gpu[hidden_max_idx],
+ hidden_expected[hidden_max_idx],
+ hidden_max_diff
+ );
+
+ for offset in 0..8 {
+ let idx = row * d_ff + (col + offset).min(d_ff - 1);
+ let g = hidden_gpu[idx];
+ let c = hidden_expected[idx];
+ eprintln!(
+ " col {} -> gpu {:.6} cpu {:.6} diff {:.6}",
+ (col + offset).min(d_ff - 1),
+ g,
+ c,
+ (g - c).abs()
+ );
+ }
+ } else {
+ eprintln!(
+ "[2-pass prefill] hidden max diff {:.6} within tolerance",
+ hidden_max_diff
+ );
+ }
+
+ assert_bf16_close(
+ output_gpu,
+ &expected,
+ tolerance,
+ "2-pass prefill output",
+ );
+
+ eprintln!("[2-pass prefill] ✓ PASSED (tolerance={:.4})", tolerance);
+}
+
+#[test]
+fn test_tile_infrastructure() {
+ // Test that tile counts/scan/map are computed correctly
+ // This is already tested in moe_tiles_test.rs, but we verify here
+ // that the tiles match our expectations for expert workload distribution
+
+ let offsets = vec![0, 5, 20, 35, 40];
+ const BM: usize = 16;
+
+ let tile_counts = cpu_tile_counts(&offsets, BM);
+ let (tile_offsets, total_tiles) = cpu_tile_scan(&tile_counts);
+
+ // Expert 0: 5 rows -> 1 tile
+ // Expert 1: 15 rows -> 1 tile
+ // Expert 2: 15 rows -> 1 tile
+ // Expert 3: 5 rows -> 1 tile
+ assert_eq!(tile_counts, vec![1, 1, 1, 1]);
+ assert_eq!(tile_offsets, vec![0, 1, 2, 3, 4]);
+ assert_eq!(total_tiles, 4);
+
+ eprintln!("[tile infrastructure] ✓ PASSED");
+}
diff --git a/crates/uzu/tests/moe/moe_finalize_test.rs b/crates/uzu/tests/moe/moe_finalize_test.rs
new file mode 100644
index 000000000..b0420dae9
--- /dev/null
+++ b/crates/uzu/tests/moe/moe_finalize_test.rs
@@ -0,0 +1,129 @@
+#![cfg(any(target_os = "macos", target_os = "ios"))]
+
+use half::bf16;
+use rand::{Rng, SeedableRng, rngs::StdRng};
+use uzu::backends::metal::kernel::{
+ KernelDataType, MoeFinalizeArguments, MoeFinalizeKernel,
+};
+
+use super::test_utils::{
+ alloc_buffer, alloc_buffer_with_data, assert_bf16_close, create_ctx,
+};
+
+fn cpu_finalize(
+ tok2row: &[i32],
+ probs: &[bf16],
+ y_partial: &[bf16],
+ t: usize,
+ d_model: usize,
+ k: usize,
+) -> Vec<bf16> {
+ let mut y = vec![bf16::from_f32(0.0); t * d_model];
+ for ti in 0..t {
+ for f in 0..d_model {
+ let mut acc = 0f32;
+ for kk in 0..k {
+ let idx = ti * k + kk;
+ let row = tok2row[idx];
+ if row >= 0 {
+ let rowu = row as usize;
+ acc += f32::from(probs[idx])
+ * f32::from(y_partial[rowu * d_model + f]);
+ }
+ }
+ y[ti * d_model + f] = bf16::from_f32(acc);
+ }
+ }
+ y
+}
+
+#[test]
+fn test_finalize_correctness() {
+ let ctx = create_ctx();
+ let mut rng = StdRng::seed_from_u64(2026);
+
+ // Test multiple shapes: (T, K, d_model, sum_k)
+ let shapes = vec![
+ (1, 2, 64, 2), // Single token, K=2
+ (4, 2, 128, 8), // Small batch
+ (8, 4, 256, 32), // Medium
+ (16, 2, 512, 32), // Large d_model
+ ];
+
+ for (t, k, d_model, sum_k) in shapes {
+ eprintln!(
+ "[FinalizeTest] T={}, K={}, d_model={}, sum_k={}",
+ t, k, d_model, sum_k
+ );
+
+ // Generate random tok2row mapping: maps (token, k_idx) → row in y_partial
+ // Some entries can be -1 (no expert selected)
+ let mut tok2row: Vec<i32> = (0..t * k)
+ .map(|_| {
+ if rng.random_bool(0.9) {
+ rng.random_range(0..sum_k as i32)
+ } else {
+ -1 // No expert selected
+ }
+ })
+ .collect();
+
+ // Ensure we use all rows in sum_k (avoid unused rows)
+ for row in 0..sum_k.min(t * k) {
+ tok2row[row] = row as i32;
+ }
+
+ // Generate random probabilities (should sum to 1 per token, but not critical for unit test)
+ let probs: Vec<bf16> = (0..t * k)
+ .map(|_| bf16::from_f32(rng.random_range(0.0..1.0)))
+ .collect();
+
+ // Generate random y_partial (expert outputs)
+ let y_partial: Vec<bf16> = (0..sum_k * d_model)
+ .map(|_| bf16::from_f32(rng.random_range(-2.0..2.0)))
+ .collect();
+
+ // CPU reference
+ let y_cpu = cpu_finalize(&tok2row, &probs, &y_partial, t, d_model, k);
+
+ // GPU buffers
+ let tok2row_buf = alloc_buffer_with_data(&ctx, &tok2row);
+ let probs_buf = alloc_buffer_with_data(&ctx, &probs);
+ let y_partial_buf = alloc_buffer_with_data(&ctx, &y_partial);
+ let y_out_buf = alloc_buffer::<bf16>(&ctx, t * d_model);
+
+ // Execute finalize kernel
+ let finalize = MoeFinalizeKernel::new(&ctx).expect("finalize kernel");
+ let cb = ctx.command_queue.new_command_buffer();
+ finalize
+ .encode(
+ &cb,
+ MoeFinalizeArguments {
+ tok2row_buffer: &tok2row_buf,
+ probs_buffer: &probs_buf,
+ y_partial_buffer: &y_partial_buf,
+ y_out_buffer: &y_out_buf,
+ t,
+ d_model,
+ k,
+ },
+ KernelDataType::BFloat16,
+ )
+ .expect("encode finalize");
+ cb.commit();
+ cb.wait_until_completed();
+
+ // Compare
+ let y_gpu = unsafe {
+ std::slice::from_raw_parts(
+ y_out_buf.contents() as *const bf16,
+ t * d_model,
+ )
+ };
+
+ // BF16 has limited precision, especially for weighted sums
+ assert_bf16_close(y_gpu, &y_cpu, 1e-2, "finalize output");
+
+ eprintln!("[FinalizeTest] ✓ PASSED");
+ }
+}
diff --git a/crates/uzu/tests/moe/moe_gather_test.rs b/crates/uzu/tests/moe/moe_gather_test.rs
new file mode 100644
index 000000000..2a0c8a26f
--- /dev/null
+++ b/crates/uzu/tests/moe/moe_gather_test.rs
@@ -0,0 +1,114 @@
+#![cfg(any(target_os = "macos", target_os = "ios"))]
+
+use half::bf16;
+use rand::{Rng, SeedableRng, rngs::StdRng};
+use uzu::backends::metal::kernel::{
+ KernelDataType,
+ moe::{MoeGatherArguments, MoeGatherKernel},
+};
+
+use super::test_utils::{
+ alloc_buffer, alloc_buffer_with_data, assert_bf16_close, create_ctx,
+};
+
+/// CPU reference for gather operation: x_perm[i] = x[bucketed_ids[i]]
+///
+/// # Arguments
+/// * `x` - Input tensor [T, d_model]
+/// * `bucketed_ids` - Index mapping [sum_k], values in range [0, T)
+/// * `t` - Number of tokens
+/// * `d_model` - Model dimension
+/// * `sum_k` - Number of output rows
+///
+/// # Returns
+/// Gathered tensor [sum_k, d_model]
+pub fn cpu_gather(
+ x: &[bf16],
+ bucketed_ids: &[i32],
+ t: usize,
+ d_model: usize,
+ sum_k: usize,
+) -> Vec<bf16> {
+ let mut x_perm = vec![bf16::from_f32(0.0); sum_k * d_model];
+ for row in 0..sum_k {
+ let token_id = bucketed_ids[row];
+ if token_id >= 0 && (token_id as usize) < t {
+ let src_offset = (token_id as usize) * d_model;
+ let dst_offset = row * d_model;
+ x_perm[dst_offset..dst_offset + d_model]
+ .copy_from_slice(&x[src_offset..src_offset + d_model]);
+ }
+ }
+ x_perm
+}
+
+#[test]
+fn test_gather_correctness() {
+ let ctx = create_ctx();
+ let mut rng = StdRng::seed_from_u64(2027);
+
+ // Test multiple shapes: (T, sum_k, d_model)
+ let shapes = vec![
+ (1, 2, 64), // Single token, K=2
+ (4, 8, 128), // Small batch
+ (16, 32, 256), // Medium
+ (64, 128, 512), // Large
+ ];
+
+ for (t, sum_k, d_model) in shapes {
+ eprintln!("[GatherTest] T={}, sum_k={}, d_model={}", t, sum_k, d_model);
+
+ // Random input
+ let x: Vec<bf16> = (0..t * d_model)
+ .map(|_| bf16::from_f32(rng.random_range(-2.0..2.0)))
+ .collect();
+
+ // Random bucketed_ids with valid token indices
+ let bucketed_ids: Vec<i32> =
+ (0..sum_k).map(|_| rng.random_range(0..t as i32)).collect();
+
+ let x_cpu = cpu_gather(&x, &bucketed_ids, t, d_model, sum_k);
+
+ // GPU buffers
+ let x_buf = alloc_buffer_with_data(&ctx, &x);
+ let ids_buf = alloc_buffer_with_data(&ctx, &bucketed_ids);
+ let x_perm_buf = alloc_buffer::<bf16>(&ctx, sum_k * d_model);
+
+ // Create sumk_buffer for API (kernel reads sumk_buf[0])
+ let sum_k_u32 = vec![sum_k as u32];
+ let sumk_buf = alloc_buffer_with_data(&ctx, &sum_k_u32);
+
+ // Execute gather kernel using kernel struct
+ let gather = MoeGatherKernel::new(&ctx).expect("MoeGatherKernel::new");
+ let cb = ctx.command_queue.new_command_buffer();
+ gather
+ .encode(
+ &cb,
+ KernelDataType::BFloat16,
+ MoeGatherArguments {
+ x_buffer: &x_buf,
+ bucketed_ids_buffer: &ids_buf,
+ x_perm_buffer: &x_perm_buf,
+ sumk_buffer: &sumk_buf,
+ t: t,
+ k: sum_k / t, // Decompose sum_k into k per token
+ d_model,
+ },
+ )
+ .expect("encode gather");
+ cb.commit();
+ cb.wait_until_completed();
+
+ // Compare
+ let x_gpu = unsafe {
+ std::slice::from_raw_parts(
+ x_perm_buf.contents() as *const bf16,
+ sum_k * d_model,
+ )
+ };
+
+ assert_bf16_close(x_gpu, &x_cpu, 1e-6, "gather output");
+
+ eprintln!("[GatherTest] ✓ PASSED");
+ }
+}
diff --git a/crates/uzu/tests/moe/moe_perf_test.rs b/crates/uzu/tests/moe/moe_perf_test.rs
new file mode 100644
index 000000000..4e2aec78f
--- /dev/null
+++ b/crates/uzu/tests/moe/moe_perf_test.rs
@@ -0,0 +1,578 @@
+use std::time::Instant;
+
+use half::bf16;
+use rand::{Rng, SeedableRng, rngs::StdRng};
+use uzu::backends::metal::{
+ KernelDataType,
+ kernel::moe::{
+ MoeCountsOffsetsFusedArguments, MoeCountsOffsetsFusedKernel,
+ MoeExpertsTwoPassArguments, MoeExpertsTwoPassDecodeKernel,
+ MoeFinalizeArguments, MoeFinalizeKernel, MoeGatherArguments,
+ MoeGatherKernel, MoeRouterTopKArguments, MoeRouterTopKKernel,
+ MoeScatterKernels, MoeScatterWithMapArguments,
+ },
+};
+
+use super::test_utils::{alloc_buffer, alloc_buffer_with_data, create_ctx};
+
+struct PerfResult {
+ name: String,
+ mean_ms: f64,
+ median_ms: f64,
+ min_ms: f64,
+ max_ms: f64,
+ std_dev_ms: f64,
+}
+
+impl PerfResult {
+ fn new(
+ name: String,
+ times_ms: &[f64],
+ ) -> Self {
+ let mut sorted = times_ms.to_vec();
+ sorted.sort_by(|a, b| a.partial_cmp(b).unwrap());
+
+ let mean = sorted.iter().sum::<f64>() / sorted.len() as f64;
+ let median = sorted[sorted.len() / 2];
+ let min = sorted[0];
+ let max = sorted[sorted.len() - 1];
+
+ let variance = sorted.iter().map(|t| (t - mean).powi(2)).sum::<f64>()
+ / sorted.len() as f64;
+ let std_dev = variance.sqrt();
+
+ Self {
+ name,
+ mean_ms: mean,
+ median_ms: median,
+ min_ms: min,
+ max_ms: max,
+ std_dev_ms: std_dev,
+ }
+ }
+
+ fn print(&self) {
+ eprintln!(
+ " {:<30} mean={:8.3}ms median={:8.3}ms min={:8.3}ms max={:8.3}ms std={:6.3}ms",
+ self.name,
+ self.mean_ms,
+ self.median_ms,
+ self.min_ms,
+ self.max_ms,
+ self.std_dev_ms
+ );
+ }
+}
+
+fn time_kernel<F>(
+ name: &str,
+ warmup: usize,
+ iterations: usize,
+ mut f: F,
+) -> PerfResult
+where
+ F: FnMut(),
+{
+ // Warmup
+ for _ in 0..warmup {
+ f();
+ }
+
+ // Measure
+ let mut times_ms = Vec::new();
+ for _ in 0..iterations {
+ let start = Instant::now();
+ f();
+ let elapsed = start.elapsed();
+ times_ms.push(elapsed.as_secs_f64() * 1000.0);
+ }
+
+ PerfResult::new(name.to_string(), &times_ms)
+}
+
+// Test E2E MoE performance with timing breakdown (decode mode, T=1)
+#[test]
+#[ignore]
+fn test_moe_e2e_decode_perf() {
+ let ctx = create_ctx();
+ let mut rng = StdRng::seed_from_u64(0xA0075);
+
+ let configs = vec![
+ ("Small", 1, 1024, 256, 8, 2),
+ ("Medium", 1, 2048, 1024, 16, 2),
+ ("Production", 1, 4096, 14336, 16, 2),
+ ];
+
+ eprintln!("\n=== End-to-End MoE Performance (DECODE, T=1) ===");
+
+ for (config_name, t, d_model, d_ff, e, k) in configs {
+ eprintln!(
+ "\n{} T={}, D={}, H={}, E={}, K={}",
+ config_name, t, d_model, d_ff, e, k
+ );
+
+ // Generate data
+ let x: Vec<bf16> = (0..t * d_model)
+ .map(|_| bf16::from_f32(rng.random_range(-1.0..1.0)))
+ .collect();
+ let router_w: Vec<bf16> = (0..e * d_model)
+ .map(|_| bf16::from_f32(rng.random_range(-0.5..0.5)))
+ .collect();
+ let router_b: Vec<bf16> = (0..e)
+ .map(|_| bf16::from_f32(rng.random_range(-0.1..0.1)))
+ .collect();
+
+ // Buffers (simplified - just key buffers for timing)
+ let x_buf = alloc_buffer_with_data(&ctx, &x);
+ let router_w_buf = alloc_buffer_with_data(&ctx, &router_w);
+ let router_b_buf = alloc_buffer_with_data(&ctx, &router_b);
+ let topk_ids_buf = alloc_buffer::<i32>(&ctx, t * k);
+ let topk_probs_buf = alloc_buffer::<bf16>(&ctx, t * k);
+
+ let router_topk =
+ MoeRouterTopKKernel::new(&ctx).expect("router+topk fused kernel");
+
+ // Time fused Router+TopK
+ let fused_perf = time_kernel("Router+TopK (FUSED)", 5, 20, || {
+ let cb = ctx.command_queue.new_command_buffer();
+ router_topk
+ .encode(
+ &cb,
+ KernelDataType::BFloat16,
+ MoeRouterTopKArguments {
+ input_buffer: &x_buf,
+ weight_buffer: &router_w_buf,
+ bias_buffer: &router_b_buf,
+ topk_ids_buffer: &topk_ids_buf,
+ topk_probs_buffer: &topk_probs_buf,
+ t,
+ d_model,
+ e,
+ k,
+ renorm: true,
+ },
+ )
+ .expect("encode fused router+topk");
+ cb.commit();
+ cb.wait_until_completed();
+ });
+
+ fused_perf.print();
+ eprintln!(" Total: {:8.1} µs/token", fused_perf.mean_ms * 1000.0);
+ }
+}
+
+// Test E2E MoE performance with timing breakdown (prefill mode, T>1)
+#[test]
+#[ignore]
+fn test_moe_e2e_prefill_perf() {
+ let ctx = create_ctx();
+ let mut rng = StdRng::seed_from_u64(0xA0076);
+
+ let configs = vec![
+ ("Batch4", 4, 4096, 14336, 16, 2),
+ ("Batch16", 16, 4096, 14336, 16, 2),
+ ("Batch32", 32, 4096, 14336, 16, 2),
+ ("Batch64", 64, 4096, 14336, 16, 2),
+ ];
+
+ eprintln!("\n=== End-to-End MoE Performance (PREFILL, T>1) ===");
+
+ for (config_name, t, d_model, d_ff, e, k) in configs {
+ eprintln!(
+ "\n{} T={}, D={}, H={}, E={}, K={}",
+ config_name, t, d_model, d_ff, e, k
+ );
+
+ // Generate data
+ let x: Vec<bf16> = (0..t * d_model)
+ .map(|_| bf16::from_f32(rng.random_range(-1.0..1.0)))
+ .collect();
+ let router_w: Vec<bf16> = (0..e * d_model)
+ .map(|_| bf16::from_f32(rng.random_range(-0.5..0.5)))
+ .collect();
+ let router_b: Vec<bf16> = (0..e)
+ .map(|_| bf16::from_f32(rng.random_range(-0.1..0.1)))
+ .collect();
+
+ // Buffers (simplified - just key buffers for timing)
+ let x_buf = alloc_buffer_with_data(&ctx, &x);
+ let router_w_buf = alloc_buffer_with_data(&ctx, &router_w);
+ let router_b_buf = alloc_buffer_with_data(&ctx, &router_b);
+ let topk_ids_buf = alloc_buffer::<i32>(&ctx, t * k);
+ let topk_probs_buf = alloc_buffer::<bf16>(&ctx, t * k);
+
+ let router_topk =
+ MoeRouterTopKKernel::new(&ctx).expect("router+topk fused kernel");
+
+ // Time fused Router+TopK
+ let fused_perf = time_kernel("Router+TopK (FUSED)", 5, 20, || {
+ let cb = ctx.command_queue.new_command_buffer();
+ router_topk
+ .encode(
+ &cb,
+ KernelDataType::BFloat16,
+ MoeRouterTopKArguments {
+ input_buffer: &x_buf,
+ weight_buffer: &router_w_buf,
+ bias_buffer: &router_b_buf,
+ topk_ids_buffer: &topk_ids_buf,
+ topk_probs_buffer: &topk_probs_buf,
+ t,
+ d_model,
+ e,
+ k,
+ renorm: true,
+ },
+ )
+ .expect("encode fused router+topk");
+ cb.commit();
+ cb.wait_until_completed();
+ });
+
+ fused_perf.print();
+ eprintln!(" Total: {:8.3} ms", fused_perf.mean_ms);
+ eprintln!(
+ " Throughput: {:.1} tokens/sec, {:.3} ms/token",
+ (t as f64 / fused_perf.mean_ms) * 1000.0,
+ fused_perf.mean_ms / t as f64
+ );
+ }
+}
+
+// Test complete MoE pipeline timing breakdown (decode mode, T=1)
+#[test]
+#[ignore]
+fn test_moe_pipeline_breakdown_decode() {
+ let ctx = create_ctx();
+ let mut rng = StdRng::seed_from_u64(0xDECADE);
+
+ eprintln!("\n=== MoE Pipeline Breakdown (DECODE, T=1) ===");
+ eprintln!(
+ "Measures ALL MoE kernels: Router→TopK→Counts→Offsets→Scatter→Gather→Experts→Finalize\n"
+ );
+
+ let (t, d_model, d_ff, e, k) = (1, 4096, 14336, 16, 2);
+
+ // Allocate buffers
+ let x: Vec<bf16> = (0..t * d_model)
+ .map(|_| bf16::from_f32(rng.random_range(-1.0..1.0)))
+ .collect();
+ let router_w: Vec<bf16> = (0..e * d_model)
+ .map(|_| bf16::from_f32(rng.random_range(-0.5..0.5)))
+ .collect();
+ let router_b: Vec<bf16> =
+ (0..e).map(|_| bf16::from_f32(rng.random_range(-0.1..0.1))).collect();
+
+ let x_buf = alloc_buffer_with_data(&ctx, &x);
+ let router_w_buf = alloc_buffer_with_data(&ctx, &router_w);
+ let router_b_buf = alloc_buffer_with_data(&ctx, &router_b);
+ let topk_ids_buf = alloc_buffer::<i32>(&ctx, t * k);
+ let topk_probs_buf = alloc_buffer::<bf16>(&ctx, t * k);
+ let num_blocks = ((t + 255) / 256).max(1);
+ let num_tiles = ((e + 512 - 1) / 512).max(1);
+ let partials_buf = alloc_buffer::<i32>(&ctx, num_blocks * num_tiles * e);
+ let offsets_buf = alloc_buffer::<u32>(&ctx, e + 1);
+ let sumk_buf = alloc_buffer::<u32>(&ctx, 1);
+ let bucketed_ids_buf = alloc_buffer::<i32>(&ctx, t * k);
+ let x_perm_buf = alloc_buffer::<bf16>(&ctx, t * k * d_model);
+ let y_partial_buf = alloc_buffer::<bf16>(&ctx, t * k * d_model);
+ let tok2row_buf = alloc_buffer::<i32>(&ctx, t * k);
+ let y_out_buf = alloc_buffer::<bf16>(&ctx, t * d_model);
+
+ // Expert weights buffers
+ // Generate W13 in original layout [E, d_model, 2*d_ff]
+ let w13_original: Vec<bf16> = (0..e * d_model * 2 * d_ff)
+ .map(|_| bf16::from_f32(rng.random_range(-0.5..0.5)))
+ .collect();
+
+ // Transpose to GPU layout [E, 2*d_ff, d_model]
+ 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.5..0.5)))
+ .collect();
+ let up_biases: Vec<bf16> = (0..e * 2 * d_ff)
+ .map(|_| bf16::from_f32(rng.random_range(-0.1..0.1)))
+ .collect();
+ let down_biases: Vec<bf16> = (0..e * d_model)
+ .map(|_| bf16::from_f32(rng.random_range(-0.1..0.1)))
+ .collect();
+
+ let w13_buf = alloc_buffer_with_data(&ctx, &w13);
+ let w2_buf = alloc_buffer_with_data(&ctx, &w2);
+ let up_biases_buf = alloc_buffer_with_data(&ctx, &up_biases);
+ let down_biases_buf = alloc_buffer_with_data(&ctx, &down_biases);
+
+ // Experts tiling buffers for two-pass
+ const K_TILE: usize = 64;
+ let sum_k = t * k;
+ let num_tiles_k = (d_ff + K_TILE - 1) / K_TILE;
+ let max_tiles = t * k * e * num_tiles_k;
+ let tile_counts_buf = alloc_buffer::<u32>(&ctx, e);
+ let tile_offsets_buf = alloc_buffer::<u32>(&ctx, e + 1);
+ let tile_map_buf = alloc_buffer::<u32>(&ctx, max_tiles * 3);
+ let total_tiles_buf = alloc_buffer::<u32>(&ctx, 1);
+ let dispatch_args_buf = alloc_buffer::<u32>(&ctx, 3);
+
+ // Two-pass specific buffers
+ let hidden_buf = alloc_buffer::<f32>(&ctx, sum_k * d_ff);
+ let row_expert_map_buf = alloc_buffer::<u32>(&ctx, sum_k);
+
+ // Scatter block bases buffers
+ let block_bases_buf = alloc_buffer::<u32>(&ctx, num_blocks * num_tiles);
+ let block_alloc_buf = alloc_buffer::<u32>(&ctx, num_blocks * num_tiles);
+ let bucketed_probs_buf = alloc_buffer::<bf16>(&ctx, t * k);
+
+ // Create kernel structs (use production-validated encoding logic)
+ let counts_offsets_kernel =
+ MoeCountsOffsetsFusedKernel::new(&ctx).expect("counts+offsets fused");
+ let scatter_kernel = MoeScatterKernels::new(&ctx).expect("scatter");
+ let gather_kernel = MoeGatherKernel::new(&ctx).expect("gather");
+ let experts_kernel = MoeExpertsTwoPassDecodeKernel::new(&ctx)
+ .expect("experts two-pass decode");
+ let finalize_kernel = MoeFinalizeKernel::new(&ctx).expect("finalize");
+ let router_topk_fused_kernel =
+ MoeRouterTopKKernel::new(&ctx).expect("router+topk fused");
+
+ // Testing: Router + TopK + Counts+Offsets (FUSED)
+ let router_topk_fused_perf =
+ time_kernel("Router+TopK (FUSED)", 2, 5, || {
+ let cb = ctx.command_queue.new_command_buffer();
+ router_topk_fused_kernel
+ .encode(
+ &cb,
+ KernelDataType::BFloat16,
+ MoeRouterTopKArguments {
+ input_buffer: &x_buf,
+ weight_buffer: &router_w_buf,
+ bias_buffer: &router_b_buf,
+ topk_ids_buffer: &topk_ids_buf,
+ topk_probs_buffer: &topk_probs_buf,
+ t,
+ d_model,
+ e,
+ k,
+ renorm: true,
+ },
+ )
+ .expect("router_topk_fused");
+ cb.commit();
+ cb.wait_until_completed();
+ });
+
+ let counts_offsets_perf =
+ time_kernel("Counts+Offsets (FUSED)", 2, 5, || {
+ let cb = ctx.command_queue.new_command_buffer();
+ counts_offsets_kernel
+ .encode(
+ &cb,
+ MoeCountsOffsetsFusedArguments {
+ topk_ids_buffer: &topk_ids_buf,
+ offsets_buffer: &offsets_buf,
+ sum_k_buffer: &sumk_buf,
+ partials_buffer: &partials_buf,
+ t,
+ e,
+ k,
+ },
+ )
+ .expect("counts+offsets fused");
+ cb.commit();
+ cb.wait_until_completed();
+ });
+
+ let scatter_perf = time_kernel("Scatter", 2, 5, || {
+ let cb = ctx.command_queue.new_command_buffer();
+ scatter_kernel
+ .encode_block_bases(
+ &cb,
+ uzu::backends::metal::kernel::moe::MoeBlockBasesArguments {
+ partials_buffer: &partials_buf,
+ block_bases_buffer: &block_bases_buf,
+ block_alloc_buffer: &block_alloc_buf,
+ e,
+ num_blocks,
+ num_tiles,
+ },
+ )
+ .expect("block bases");
+ scatter_kernel
+ .encode_scatter_with_map(
+ &cb,
+ MoeScatterWithMapArguments {
+ base:
+ uzu::backends::metal::kernel::moe::MoeScatterArguments {
+ topk_ids_buffer: &topk_ids_buf,
+ topk_probs_buffer: &topk_probs_buf,
+ offsets_buffer: &offsets_buf,
+ block_bases_buffer: &block_bases_buf,
+ block_alloc_buffer: &block_alloc_buf,
+ out_ids_buffer: &bucketed_ids_buf,
+ out_probs_buffer: &bucketed_probs_buf,
+ t,
+ e,
+ k,
+ num_blocks,
+ num_tiles,
+ },
+ tok2row_buffer: &tok2row_buf,
+ },
+ KernelDataType::BFloat16,
+ )
+ .expect("scatter");
+ cb.commit();
+ cb.wait_until_completed();
+ });
+
+ let gather_perf = time_kernel("Gather", 2, 5, || {
+ let cb = ctx.command_queue.new_command_buffer();
+ gather_kernel
+ .encode(
+ &cb,
+ KernelDataType::BFloat16,
+ MoeGatherArguments {
+ x_buffer: &x_buf,
+ bucketed_ids_buffer: &bucketed_ids_buf,
+ x_perm_buffer: &x_perm_buf,
+ sumk_buffer: &sumk_buf,
+ t,
+ k,
+ d_model,
+ },
+ )
+ .expect("gather");
+ cb.commit();
+ cb.wait_until_completed();
+ });
+
+ let experts_perf = time_kernel("Experts (MAIN COMPUTE)", 2, 5, || {
+ let cb = ctx.command_queue.new_command_buffer();
+ experts_kernel
+ .encode(
+ &cb,
+ MoeExpertsTwoPassArguments {
+ x_perm_buffer: &x_perm_buf,
+ expert_offsets: &offsets_buf,
+ row_expert_map: &row_expert_map_buf,
+ hidden_buffer: &hidden_buf,
+ output_buffer: &y_partial_buf,
+ w13_all: &w13_buf,
+ w2_all: &w2_buf,
+ up_biases: &up_biases_buf,
+ down_biases: &down_biases_buf,
+ tile_counts: &tile_counts_buf,
+ tile_offsets: &tile_offsets_buf,
+ tile_map: &tile_map_buf,
+ total_tiles: &total_tiles_buf,
+ dispatch_args: &dispatch_args_buf,
+ total_rows: sum_k,
+ d_model,
+ d_ff,
+ e,
+ num_tiles_k: num_tiles_k as u32,
+ gating_code: 2, // SILU
+ 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: KernelDataType::BFloat16,
+ },
+ )
+ .expect("experts");
+ cb.commit();
+ cb.wait_until_completed();
+ });
+
+ let finalize_perf = time_kernel("Finalize", 2, 5, || {
+ let cb = ctx.command_queue.new_command_buffer();
+ finalize_kernel
+ .encode(
+ &cb,
+ MoeFinalizeArguments {
+ tok2row_buffer: &tok2row_buf,
+ probs_buffer: &topk_probs_buf,
+ y_partial_buffer: &y_partial_buf,
+ y_out_buffer: &y_out_buf,
+ t,
+ d_model,
+ k,
+ },
+ KernelDataType::BFloat16,
+ )
+ .expect("finalize");
+ cb.commit();
+ cb.wait_until_completed();
+ });
+
+ // Print results
+ router_topk_fused_perf.print();
+ counts_offsets_perf.print();
+ scatter_perf.print();
+ gather_perf.print();
+ experts_perf.print();
+ finalize_perf.print();
+
+ // Calculate breakdown
+ let total_us = (router_topk_fused_perf.mean_ms
+ + counts_offsets_perf.mean_ms
+ + scatter_perf.mean_ms
+ + gather_perf.mean_ms
+ + experts_perf.mean_ms
+ + finalize_perf.mean_ms)
+ * 1000.0;
+
+ eprintln!(
+ "\n ═══ Per-Kernel Latency (Production D=4096, H=14336, E=16, K=2, T=1) ═══"
+ );
+ eprintln!(
+ " Router+TopK (FUSED): {:8.1} us ({:5.1}%)",
+ router_topk_fused_perf.mean_ms * 1000.0,
+ (router_topk_fused_perf.mean_ms / (total_us / 1000.0)) * 100.0
+ );
+ eprintln!(
+ " Counts+Offsets: {:8.1} us ({:5.1}%)",
+ counts_offsets_perf.mean_ms * 1000.0,
+ (counts_offsets_perf.mean_ms / (total_us / 1000.0)) * 100.0
+ );
+ eprintln!(
+ " Scatter: {:8.1} us ({:5.1}%)",
+ scatter_perf.mean_ms * 1000.0,
+ (scatter_perf.mean_ms / (total_us / 1000.0)) * 100.0
+ );
+ eprintln!(
+ " Gather: {:8.1} us ({:5.1}%)",
+ gather_perf.mean_ms * 1000.0,
+ (gather_perf.mean_ms / (total_us / 1000.0)) * 100.0
+ );
+ eprintln!(
+ " Experts: {:8.1} us ({:5.1}%) ← MAIN COMPUTE",
+ experts_perf.mean_ms * 1000.0,
+ (experts_perf.mean_ms / (total_us / 1000.0)) * 100.0
+ );
+ eprintln!(
+ " Finalize: {:8.1} us ({:5.1}%)",
+ finalize_perf.mean_ms * 1000.0,
+ (finalize_perf.mean_ms / (total_us / 1000.0)) * 100.0
+ );
+ eprintln!(" ═══════════════════════════════════════════");
+ eprintln!(" TOTAL: {:8.1} us (100.0%)", total_us);
+ eprintln!(
+ "\n Note: Times include Metal CB overhead (~10-50ms per kernel)."
+ );
+ eprintln!(
+ " Real GPU compute is much faster, but relative % shows bottleneck."
+ );
+}
diff --git a/crates/uzu/tests/moe/moe_router_topk_test.rs b/crates/uzu/tests/moe/moe_router_topk_test.rs
new file mode 100644
index 000000000..05138069f
--- /dev/null
+++ b/crates/uzu/tests/moe/moe_router_topk_test.rs
@@ -0,0 +1,251 @@
+#![cfg(any(target_os = "macos", target_os = "ios"))]
+
+use half::bf16;
+use rand::{Rng, SeedableRng, rngs::StdRng};
+use uzu::backends::metal::{
+ KernelDataType, MTLContext,
+ kernel::moe::{MoeRouterTopKArguments, MoeRouterTopKKernel},
+};
+
+use super::test_utils::{alloc_buffer, alloc_buffer_with_data, create_ctx};
+
+/// CPU reference for router logits (bf16 precision, f32 accumulation).
+pub fn cpu_router_logits_bf16(
+ input: &[bf16],
+ weight: &[bf16],
+ bias: &[bf16],
+ t: usize,
+ e: usize,
+ d_model: usize,
+) -> Vec<f32> {
+ assert_eq!(input.len(), t * d_model);
+ assert_eq!(weight.len(), e * d_model);
+ assert_eq!(bias.len(), e);
+ assert_eq!(d_model % 4, 0, "d_model must be multiple of 4");
+
+ let mut out = vec![0.0f32; t * e];
+ for token in 0..t {
+ let x_row = &input[token * d_model..(token + 1) * d_model];
+ for expert in 0..e {
+ let w_row = &weight[expert * d_model..(expert + 1) * d_model];
+
+ // Simulate GPU vec4 processing: accumulate in 4-element chunks
+ let mut accum = [0.0f32; 4];
+ for chunk in (0..d_model).step_by(4) {
+ // Load vec4
+ let xv = [
+ f32::from(x_row[chunk]),
+ f32::from(x_row[chunk + 1]),
+ f32::from(x_row[chunk + 2]),
+ f32::from(x_row[chunk + 3]),
+ ];
+ let wv = [
+ f32::from(w_row[chunk]),
+ f32::from(w_row[chunk + 1]),
+ f32::from(w_row[chunk + 2]),
+ f32::from(w_row[chunk + 3]),
+ ];
+ // FMA: accum = wv * xv + accum
+ for i in 0..4 {
+ accum[i] = wv[i].mul_add(xv[i], accum[i]);
+ }
+ }
+
+ // Sum the 4-vector: (a.x + a.y) + (a.z + a.w) - matches Metal shader line 60
+ let sum = (accum[0] + accum[1]) + (accum[2] + accum[3]);
+ out[token * e + expert] = sum + f32::from(bias[expert]);
+ }
+ }
+ out
+}
+
+/// CPU reference for Top-K selection over float32 logits.
+pub fn cpu_topk_select_f32(
+ logits: &[f32],
+ t: usize,
+ e: usize,
+ k: usize,
+ renorm: bool,
+) -> (Vec<i32>, Vec<f32>) {
+ assert_eq!(logits.len(), t * e);
+ assert!(k >= 1 && e >= k);
+ let mut ids = vec![0i32; t * k];
+ let mut probs = vec![0f32; t * k];
+ for token in 0..t {
+ let row = &logits[token * e..(token + 1) * e];
+ let mut best_vals = vec![f32::NEG_INFINITY; k];
+ let mut best_ids = vec![-1i32; k];
+ for expert in 0..e {
+ let v = row[expert];
+ let mut insert_pos = None;
+ for j in (0..k).rev() {
+ if v > best_vals[j]
+ || (v == best_vals[j] && (expert as i32) < best_ids[j])
+ {
+ insert_pos = Some(j);
+ }
+ }
+ if let Some(pos) = insert_pos {
+ for s in (pos + 1..k).rev() {
+ best_vals[s] = best_vals[s - 1];
+ best_ids[s] = best_ids[s - 1];
+ }
+ best_vals[pos] = v;
+ best_ids[pos] = expert as i32;
+ }
+ }
+ let base = token * k;
+ for kk in 0..k {
+ ids[base + kk] = best_ids[kk];
+ }
+ if renorm {
+ let max_v =
+ best_vals.iter().copied().fold(f32::NEG_INFINITY, f32::max);
+ let mut exps = vec![0.0f32; k];
+ let mut sum = 0.0f32;
+ for kk in 0..k {
+ exps[kk] = (best_vals[kk] - max_v).exp();
+ sum += exps[kk];
+ }
+ if sum > 0.0 {
+ for kk in 0..k {
+ probs[base + kk] = exps[kk] / sum;
+ }
+ } else {
+ let uniform = 1.0f32 / k as f32;
+ for kk in 0..k {
+ probs[base + kk] = uniform;
+ }
+ }
+ } else {
+ for kk in 0..k {
+ probs[base + kk] = f32::from(bf16::from_f32(best_vals[kk]));
+ }
+ }
+ }
+ (ids, probs)
+}
+
+fn run_router_topk_once(
+ ctx: &MTLContext,
+ kernel: &MoeRouterTopKKernel,
+ t: usize,
+ d_model: usize,
+ e: usize,
+ k: usize,
+ renorm: bool,
+) {
+ let mut rng = StdRng::seed_from_u64(1234);
+ let input_f32: Vec<f32> =
+ (0..t * d_model).map(|_| rng.random_range(-1.0..1.0)).collect();
+ let weight_f32: Vec<f32> =
+ (0..e * d_model).map(|_| rng.random_range(-1.0..1.0)).collect();
+ let bias_f32: Vec<f32> =
+ (0..e).map(|_| rng.random_range(-0.5..0.5)).collect();
+
+ // Convert to bf16
+ let input: Vec<bf16> =
+ input_f32.iter().map(|&x| bf16::from_f32(x)).collect();
+ let weight: Vec<bf16> =
+ weight_f32.iter().map(|&x| bf16::from_f32(x)).collect();
+ let bias: Vec<bf16> = bias_f32.iter().map(|&x| bf16::from_f32(x)).collect();
+
+ // Compute CPU reference using bf16 inputs (with f32 accumulation)
+ let logits_ref =
+ cpu_router_logits_bf16(&input, &weight, &bias, t, e, d_model);
+ let (ids_ref, probs_ref) =
+ cpu_topk_select_f32(&logits_ref, t, e, k, renorm);
+
+ let input_buf = alloc_buffer_with_data(ctx, &input);
+ let weight_buf = alloc_buffer_with_data(ctx, &weight);
+ let bias_buf = alloc_buffer_with_data(ctx, &bias);
+ let ids_buf = alloc_buffer::<i32>(ctx, t * k);
+ // For BFloat16 kernel, probs buffer must be bf16, not f32
+ let probs_buf = alloc_buffer::<bf16>(ctx, t * k);
+
+ let cb = ctx.command_queue.new_command_buffer();
+ let args = MoeRouterTopKArguments {
+ input_buffer: &input_buf,
+ weight_buffer: &weight_buf,
+ bias_buffer: &bias_buf,
+ topk_ids_buffer: &ids_buf,
+ topk_probs_buffer: &probs_buf,
+ t,
+ d_model,
+ e,
+ k,
+ renorm,
+ };
+ kernel
+ .encode(&cb, KernelDataType::BFloat16, args)
+ .expect("encode fused router+topk");
+ cb.commit();
+ cb.wait_until_completed();
+
+ let ids_ptr = ids_buf.contents() as *const i32;
+ let probs_ptr = probs_buf.contents() as *const bf16;
+ let ids_gpu =
+ unsafe { std::slice::from_raw_parts(ids_ptr, t * k) }.to_vec();
+ let probs_bf16_gpu =
+ unsafe { std::slice::from_raw_parts(probs_ptr, t * k) }.to_vec();
+ // Convert bf16 to f32 for comparison
+ let probs_gpu: Vec<f32> =
+ probs_bf16_gpu.iter().map(|&h| f32::from(h)).collect();
+
+ assert_eq!(
+ ids_gpu, ids_ref,
+ "Top-k ids mismatch for T={}, d_model={}, E={}, K={}, renorm={}",
+ t, d_model, e, k, renorm
+ );
+
+ for i in 0..(t * k) {
+ let diff = (probs_gpu[i] - probs_ref[i]).abs();
+
+ // Tolerance accounts for numerical differences in:
+ // 1. Router matmul: GPU uses vec4 FMA + SIMD reductions, CPU uses scalar loops
+ // With bf16 inputs and f32 accumulation, minor differences expected
+ // 2. bf16 quantization on probs output buffer
+ // 3. TopK selection (minor)
+ // 4. Softmax computation when renorm=true (exp/div operations)
+ let atol = if renorm {
+ 2e-2 // Normalized probabilities with bf16: softmax + bf16 quantization
+ } else {
+ 5e-2 // Raw logits with bf16: vec4 accumulation + bf16 output quantization
+ };
+ assert!(
+ diff <= atol,
+ "Top-k prob mismatch at {}: gpu={} ref={} (diff={}, atol={}) with T={}, d_model={}, E={}, K={}, renorm={}",
+ i,
+ probs_gpu[i],
+ probs_ref[i],
+ diff,
+ atol,
+ t,
+ d_model,
+ e,
+ k,
+ renorm
+ );
+ }
+}
+
+#[test]
+fn test_router_topk_fused_matches_reference() {
+ let ctx = create_ctx();
+ let kernel = MoeRouterTopKKernel::new(&ctx).expect("kernel");
+
+ let configs = [
+ (1usize, 64usize, 32usize, 4usize),
+ (2, 128, 64, 8),
+ (4, 256, 128, 16),
+ (8, 256, 256, 32),
+ (1, 512, 512, 64),
+ ];
+ let renorm_options = [false, true];
+
+ for &(t, d_model, e, k) in &configs {
+ for &renorm in &renorm_options {
+ run_router_topk_once(&ctx, &kernel, t, d_model, e, k, renorm);
+ }
+ }
+}
diff --git a/crates/uzu/tests/moe/moe_scatter_test.rs b/crates/uzu/tests/moe/moe_scatter_test.rs
new file mode 100644
index 000000000..3ff34f756
--- /dev/null
+++ b/crates/uzu/tests/moe/moe_scatter_test.rs
@@ -0,0 +1,238 @@
+#![cfg(any(target_os = "macos", target_os = "ios"))]
+
+use half::bf16;
+use rand::{Rng, SeedableRng, rngs::StdRng};
+use uzu::backends::metal::kernel::{
+ KernelDataType, MoeBlockBasesArguments, MoeCountsOffsetsFusedArguments,
+ MoeCountsOffsetsFusedKernel, MoeScatterArguments, MoeScatterKernels,
+ moe::{MoeRouterTopKArguments, MoeRouterTopKKernel},
+};
+
+use super::test_utils::{alloc_buffer, alloc_buffer_with_data, create_ctx};
+
+fn cpu_expert_buckets(
+ topk_ids: &[i32],
+ topk_probs: &[f32],
+ t: usize,
+ e: usize,
+ k: usize,
+) -> (Vec<i32>, Vec<f32>, Vec<u32>) {
+ let mut per_e: Vec<Vec<(i32, f32)>> = vec![Vec::new(); e];
+ for ti in 0..t {
+ for kk in 0..k {
+ let id = topk_ids[ti * k + kk];
+ if id >= 0 {
+ let ue = id as usize;
+ if ue < e {
+ per_e[ue].push((ti as i32, topk_probs[ti * k + kk]));
+ }
+ }
+ }
+ }
+ let mut offsets = Vec::with_capacity(e + 1);
+ offsets.push(0u32);
+ for ei in 0..e {
+ offsets.push(offsets[ei] + per_e[ei].len() as u32);
+ }
+ let sumk = *offsets.last().unwrap() as usize;
+ let mut ids = vec![0i32; sumk];
+ let mut probs = vec![0f32; sumk];
+ for ei in 0..e {
+ let mut entries = per_e[ei].clone();
+ entries.sort_by_key(|&(id, _)| id);
+ let start = offsets[ei] as usize;
+ for (i, (id, p)) in entries.into_iter().enumerate() {
+ ids[start + i] = id;
+ probs[start + i] = p;
+ }
+ }
+ (ids, probs, offsets)
+}
+
+#[test]
+fn test_scatter_buckets_parity() {
+ let ctx = create_ctx();
+ let shapes = vec![(1usize, 4usize, 1usize), (7, 16, 2), (128, 64, 2)];
+ for (t, e, k) in shapes {
+ let mut rng = StdRng::seed_from_u64(7);
+
+ // Generate random input and router weights for fused kernel
+ let d_model = 64;
+ let input_f32: Vec<f32> =
+ (0..t * d_model).map(|_| rng.random_range(-1.0..1.0)).collect();
+ let weight_f32: Vec<f32> =
+ (0..e * d_model).map(|_| rng.random_range(-1.0..1.0)).collect();
+ let bias_f32: Vec<f32> =
+ (0..e).map(|_| rng.random_range(-0.5..0.5)).collect();
+
+ let input: Vec<bf16> =
+ input_f32.iter().map(|&x| bf16::from_f32(x)).collect();
+ let weight: Vec<bf16> =
+ weight_f32.iter().map(|&x| bf16::from_f32(x)).collect();
+ let bias: Vec<bf16> =
+ bias_f32.iter().map(|&x| bf16::from_f32(x)).collect();
+
+ let input_buf = alloc_buffer_with_data(&ctx, &input);
+ let weight_buf = alloc_buffer_with_data(&ctx, &weight);
+ let bias_buf = alloc_buffer_with_data(&ctx, &bias);
+ let topk_ids_buf = alloc_buffer::<i32>(&ctx, t * k);
+ let topk_probs_buf = alloc_buffer::<bf16>(&ctx, t * k);
+
+ // Use fused router+topk kernel
+ let router_topk = MoeRouterTopKKernel::new(&ctx).expect("router_topk");
+ let cb = ctx.command_queue.new_command_buffer();
+ router_topk
+ .encode(
+ &cb,
+ KernelDataType::BFloat16,
+ MoeRouterTopKArguments {
+ input_buffer: &input_buf,
+ weight_buffer: &weight_buf,
+ bias_buffer: &bias_buf,
+ topk_ids_buffer: &topk_ids_buf,
+ topk_probs_buffer: &topk_probs_buf,
+ t,
+ d_model,
+ e,
+ k,
+ renorm: true,
+ },
+ )
+ .expect("encode router_topk");
+ cb.commit();
+ cb.wait_until_completed();
+
+ // Read back CPU probs for reference compare
+ let probs_bf16 = unsafe {
+ std::slice::from_raw_parts(
+ topk_probs_buf.contents() as *const bf16,
+ t * k,
+ )
+ };
+ let topk_probs_cpu: Vec<f32> =
+ probs_bf16.iter().map(|&h| f32::from(h)).collect();
+ let topk_ids_cpu = unsafe {
+ std::slice::from_raw_parts(
+ topk_ids_buf.contents() as *const i32,
+ t * k,
+ )
+ };
+
+ let offsets_buf = alloc_buffer::<u32>(&ctx, e + 1);
+ let sumk_buf = alloc_buffer::<u32>(&ctx, 1);
+ let num_tiles = ((e + 511) / 512).max(1);
+ let partials_buf = alloc_buffer::<u32>(&ctx, num_tiles * 512);
+
+ let fused_kernel =
+ MoeCountsOffsetsFusedKernel::new(&ctx).expect("fused kernel");
+ let cb = ctx.command_queue.new_command_buffer();
+ fused_kernel
+ .encode(
+ &cb,
+ MoeCountsOffsetsFusedArguments {
+ topk_ids_buffer: &topk_ids_buf,
+ offsets_buffer: &offsets_buf,
+ sum_k_buffer: &sumk_buf,
+ partials_buffer: &partials_buf,
+ t,
+ e,
+ k,
+ },
+ )
+ .expect("encode fused");
+ cb.commit();
+ cb.wait_until_completed();
+
+ // Partials already created by fused kernel above
+ let num_blocks = 1; // Fused kernel uses single block
+ let num_tiles = ((e + 511) / 512).max(1);
+ let entries = num_blocks * num_tiles * 512usize;
+ let block_bases_buf = alloc_buffer::<u32>(&ctx, entries);
+
+ let scatter = MoeScatterKernels::new(&ctx).expect("scatter kernels");
+ let cb = ctx.command_queue.new_command_buffer();
+ let block_alloc_buf = alloc_buffer::<u32>(&ctx, entries);
+ scatter
+ .encode_block_bases(
+ &cb,
+ MoeBlockBasesArguments {
+ partials_buffer: &partials_buf,
+ block_bases_buffer: &block_bases_buf,
+ block_alloc_buffer: &block_alloc_buf,
+ e,
+ num_blocks,
+ num_tiles,
+ },
+ )
+ .expect("encode bases");
+ cb.commit();
+ cb.wait_until_completed();
+
+ let sumk = unsafe {
+ std::slice::from_raw_parts(sumk_buf.contents() as *const u32, 1)
+ }[0] as usize;
+ let out_ids_buf = alloc_buffer::<i32>(&ctx, sumk);
+ let out_probs_buf = alloc_buffer::<bf16>(&ctx, sumk);
+
+ let cb = ctx.command_queue.new_command_buffer();
+ scatter
+ .encode_scatter(
+ &cb,
+ MoeScatterArguments {
+ topk_ids_buffer: &topk_ids_buf,
+ topk_probs_buffer: &topk_probs_buf,
+ offsets_buffer: &offsets_buf,
+ block_bases_buffer: &block_bases_buf,
+ block_alloc_buffer: &block_alloc_buf,
+ out_ids_buffer: &out_ids_buf,
+ out_probs_buffer: &out_probs_buf,
+ t,
+ e,
+ k,
+ num_blocks,
+ num_tiles,
+ },
+ KernelDataType::BFloat16,
+ )
+ .expect("encode scatter");
+ cb.commit();
+ cb.wait_until_completed();
+
+ let out_ids = unsafe {
+ std::slice::from_raw_parts(
+ out_ids_buf.contents() as *const i32,
+ sumk,
+ )
+ };
+ let out_probs_h = unsafe {
+ std::slice::from_raw_parts(
+ out_probs_buf.contents() as *const bf16,
+ sumk,
+ )
+ };
+ let _out_probs: Vec<f32> =
+ out_probs_h.iter().map(|&h| f32::from(h)).collect();
+
+ // CPU reference
+ let (cpu_ids, _cpu_probs, offsets_cpu) =
+ cpu_expert_buckets(topk_ids_cpu, &topk_probs_cpu, t, e, k);
+ let offsets_gpu = unsafe {
+ std::slice::from_raw_parts(
+ offsets_buf.contents() as *const u32,
+ e + 1,
+ )
+ };
+ assert_eq!(offsets_gpu, &offsets_cpu[..]);
+
+ // Compare per-expert multisets of ids
+ for ei in 0..e {
+ let s = offsets_cpu[ei] as usize;
+ let epos = offsets_cpu[ei + 1] as usize;
+ let mut a = out_ids[s..epos].to_vec();
+ a.sort();
+ let mut b = cpu_ids[s..epos].to_vec();
+ b.sort();
+ assert_eq!(a, b, "ids multiset mismatch for expert {}", ei);
+ }
+ }
+}
diff --git a/crates/uzu/tests/moe/moe_test_utils.rs b/crates/uzu/tests/moe/moe_test_utils.rs
new file mode 100644
index 000000000..5164bf052
--- /dev/null
+++ b/crates/uzu/tests/moe/moe_test_utils.rs
@@ -0,0 +1,125 @@
+//! Shared test utilities for MoE tests
+//!
+//! Contains common helper functions, CPU ground truth implementations,
+//! buffer allocation helpers, and test fixtures used across all MoE test files.
+
+#![cfg(any(target_os = "macos", target_os = "ios"))]
+
+use half::bf16;
+use metal::{Buffer as MTLBuffer, Device, MTLResourceOptions};
+use uzu::backends::metal::MTLContext;
+
+/// Create Metal context for testing
+pub fn create_ctx() -> MTLContext {
+ let device = Device::system_default().expect("No Metal device");
+ let queue = device.new_command_queue();
+ MTLContext::new(device, queue).expect("Failed to create MTLContext")
+}
+
+/// Helper to allocate buffer with data
+pub fn alloc_buffer_with_data<T>(
+ ctx: &MTLContext,
+ data: &[T],
+) -> MTLBuffer {
+ ctx.device.new_buffer_with_data(
+ data.as_ptr() as *const _,
+ (data.len() * std::mem::size_of::<T>()) as u64,
+ MTLResourceOptions::StorageModeShared,
+ )
+}
+
+/// Helper to allocate empty buffer
+pub fn alloc_buffer<T>(
+ ctx: &MTLContext,
+ count: usize,
+) -> MTLBuffer {
+ ctx.device.new_buffer(
+ (count * std::mem::size_of::<T>()) as u64,
+ MTLResourceOptions::StorageModeShared,
+ )
+}
+
+/// Compare two bf16 slices with tolerance
+///
+/// # Arguments
+/// * `a` - First slice
+/// * `b` - Second slice
+/// * `tolerance` - Maximum absolute difference allowed
+/// * `name` - Name for error messages
+///
+/// # Panics
+/// Panics if any element differs by more than tolerance
+pub fn assert_bf16_close(
+ a: &[bf16],
+ b: &[bf16],
+ tolerance: f32,
+ name: &str,
+) {
+ assert_eq!(a.len(), b.len(), "{}: length mismatch", name);
+
+ let mut max_diff = 0.0f32;
+ let mut max_idx = 0;
+
+ for (i, (&a_val, &b_val)) in a.iter().zip(b.iter()).enumerate() {
+ let diff = (f32::from(a_val) - f32::from(b_val)).abs();
+ if diff > max_diff {
+ max_diff = diff;
+ max_idx = i;
+ }
+ }
+
+ assert!(
+ max_diff <= tolerance,
+ "{}: max difference {:.6} at index {} exceeds tolerance {:.6} (a={:.6}, b={:.6})",
+ name,
+ max_diff,
+ max_idx,
+ tolerance,
+ f32::from(a[max_idx]),
+ f32::from(b[max_idx])
+ );
+}
+
+/// CPU reference for tile counts: count number of BM-sized tiles per expert
+///
+/// # Arguments
+/// * `offsets` - Expert segment offsets [E+1]
+/// * `bm` - Tile size (must match kernel BM constant)
+///
+/// # Returns
+/// Tile counts per expert [E]
+pub fn cpu_tile_counts(
+ offsets: &[u32],
+ bm: usize,
+) -> Vec<u32> {
+ let e = offsets.len() - 1;
+ let mut tile_counts = vec![0u32; e];
+ for expert in 0..e {
+ let seg_len = offsets[expert + 1] - offsets[expert];
+ tile_counts[expert] = if seg_len == 0 {
+ 0
+ } else {
+ ((seg_len as usize + bm - 1) / bm) as u32
+ };
+ }
+ tile_counts
+}
+
+/// CPU reference for tile scan: exclusive prefix sum of tile counts
+///
+/// # Arguments
+/// * `tile_counts` - Tile counts per expert [E]
+///
+/// # Returns
+/// * Tile offsets [E+1] (exclusive prefix sum)
+/// * Total number of tiles
+pub fn cpu_tile_scan(tile_counts: &[u32]) -> (Vec<u32>, u32) {
+ let e = tile_counts.len();
+ let mut tile_offsets = Vec::with_capacity(e + 1);
+ tile_offsets.push(0);
+ for i in 0..e {
+ tile_offsets.push(tile_offsets[i] + tile_counts[i]);
+ }
+ let total_tiles = *tile_offsets.last().unwrap();
+ (tile_offsets, total_tiles)
+}
diff --git a/crates/uzu/tests/moe/moe_tiles_test.rs b/crates/uzu/tests/moe/moe_tiles_test.rs
new file mode 100644
index 000000000..853aafdf0
--- /dev/null
+++ b/crates/uzu/tests/moe/moe_tiles_test.rs
@@ -0,0 +1,219 @@
+#![cfg(any(target_os = "macos", target_os = "ios"))]
+
+use rand::{Rng, SeedableRng, rngs::StdRng};
+use uzu::backends::metal::kernel::moe::{
+ MoeTileCountsArguments, MoeTileMapKernel, MoeTileScanArguments,
+};
+
+use super::test_utils::{
+ alloc_buffer, alloc_buffer_with_data, cpu_tile_counts, cpu_tile_scan,
+ create_ctx,
+};
+
+#[test]
+fn test_tile_counts_correctness() {
+ let ctx = create_ctx();
+ let mut rng = StdRng::seed_from_u64(2028);
+
+ // Test multiple expert counts
+ let expert_counts = vec![4, 8, 16, 64];
+
+ for e in expert_counts {
+ eprintln!("[TileCountsTest] E={}", e);
+
+ // Generate random offsets (simulating expert segment sizes)
+ let mut offsets = vec![0u32];
+ for _ in 0..e {
+ let seg_len = rng.random_range(0..200);
+ offsets.push(offsets.last().unwrap() + seg_len);
+ }
+
+ let tile_counts_cpu = cpu_tile_counts(&offsets, 16);
+
+ // GPU buffers
+ let offsets_buf = alloc_buffer_with_data(&ctx, &offsets);
+ let tile_counts_buf = alloc_buffer::<u32>(&ctx, e);
+
+ // Execute kernel using kernel struct
+ let tile_kernel =
+ MoeTileMapKernel::new(&ctx).expect("MoeTileMapKernel::new");
+ let cb = ctx.command_queue.new_command_buffer();
+ tile_kernel
+ .encode_counts(
+ &cb,
+ &MoeTileCountsArguments {
+ offsets_buffer: &offsets_buf,
+ tile_counts_buffer: &tile_counts_buf,
+ e,
+ },
+ )
+ .expect("encode tile counts");
+ cb.commit();
+ cb.wait_until_completed();
+
+ // Compare
+ let tile_counts_gpu = unsafe {
+ std::slice::from_raw_parts(
+ tile_counts_buf.contents() as *const u32,
+ e,
+ )
+ };
+
+ assert_eq!(
+ tile_counts_gpu,
+ &tile_counts_cpu[..],
+ "Tile counts mismatch for E={}",
+ e
+ );
+
+ eprintln!("[TileCountsTest] ✓ PASSED");
+ }
+}
+
+#[test]
+fn test_tile_scan_correctness() {
+ let ctx = create_ctx();
+ let mut rng = StdRng::seed_from_u64(2029);
+
+ // Test multiple expert counts
+ let expert_counts = vec![4, 8, 16, 64];
+
+ for e in expert_counts {
+ eprintln!("[TileScanTest] E={}", e);
+
+ // Generate random tile counts
+ let tile_counts: Vec<u32> =
+ (0..e).map(|_| rng.random_range(0..20)).collect();
+
+ let (tile_offsets_cpu, total_tiles_cpu) = cpu_tile_scan(&tile_counts);
+
+ // GPU buffers
+ let tile_counts_buf = alloc_buffer_with_data(&ctx, &tile_counts);
+ let tile_offsets_buf = alloc_buffer::<u32>(&ctx, e + 1);
+ let total_tiles_buf = alloc_buffer::<u32>(&ctx, 1);
+
+ // Execute kernel using kernel struct
+ let tile_kernel =
+ MoeTileMapKernel::new(&ctx).expect("MoeTileMapKernel::new");
+ let cb = ctx.command_queue.new_command_buffer();
+ tile_kernel
+ .encode_scan(
+ &cb,
+ &MoeTileScanArguments {
+ tile_counts_buffer: &tile_counts_buf,
+ tile_offsets_buffer: &tile_offsets_buf,
+ total_tiles_buffer: &total_tiles_buf,
+ e,
+ },
+ )
+ .expect("encode tile scan");
+ cb.commit();
+ cb.wait_until_completed();
+
+ // Compare
+ let tile_offsets_gpu = unsafe {
+ std::slice::from_raw_parts(
+ tile_offsets_buf.contents() as *const u32,
+ e + 1,
+ )
+ };
+ let total_tiles_gpu =
+ unsafe { *(total_tiles_buf.contents() as *const u32) };
+
+ assert_eq!(
+ tile_offsets_gpu,
+ &tile_offsets_cpu[..],
+ "Tile offsets mismatch for E={}",
+ e
+ );
+ assert_eq!(
+ total_tiles_gpu, total_tiles_cpu,
+ "Total tiles mismatch for E={}",
+ e
+ );
+
+ eprintln!("[TileScanTest] ✓ PASSED");
+ }
+}
+
+#[test]
+fn test_tile_edge_cases() {
+ let ctx = create_ctx();
+
+ // Test with all empty experts (seg_len=0)
+ {
+ let e = 8;
+ let offsets = vec![0u32; e + 1]; // All zeros
+
+ let tile_counts_cpu = cpu_tile_counts(&offsets, 16);
+
+ let offsets_buf = alloc_buffer_with_data(&ctx, &offsets);
+ let tile_counts_buf = alloc_buffer::<u32>(&ctx, e);
+
+ let tile_kernel =
+ MoeTileMapKernel::new(&ctx).expect("MoeTileMapKernel::new");
+ let cb = ctx.command_queue.new_command_buffer();
+ tile_kernel
+ .encode_counts(
+ &cb,
+ &MoeTileCountsArguments {
+ offsets_buffer: &offsets_buf,
+ tile_counts_buffer: &tile_counts_buf,
+ e,
+ },
+ )
+ .expect("encode tile counts");
+ cb.commit();
+ cb.wait_until_completed();
+
+ let tile_counts_gpu = unsafe {
+ std::slice::from_raw_parts(
+ tile_counts_buf.contents() as *const u32,
+ e,
+ )
+ };
+
+ assert_eq!(tile_counts_gpu, &tile_counts_cpu[..]);
+ assert!(tile_counts_gpu.iter().all(|&c| c == 0));
+ eprintln!("[TileEdgeCases] ✓ Empty experts PASSED");
+ }
+
+ // Test with single tile per expert (seg_len < BM=16)
+ {
+ let e = 4;
+ let offsets = vec![0, 10, 15, 30, 50]; // Small segments
+
+ let tile_counts_cpu = cpu_tile_counts(&offsets, 16);
+
+ let offsets_buf = alloc_buffer_with_data(&ctx, &offsets);
+ let tile_counts_buf = alloc_buffer::<u32>(&ctx, e);
+
+ let tile_kernel =
+ MoeTileMapKernel::new(&ctx).expect("MoeTileMapKernel::new");
+ let cb = ctx.command_queue.new_command_buffer();
+ tile_kernel
+ .encode_counts(
+ &cb,
+ &MoeTileCountsArguments {
+ offsets_buffer: &offsets_buf,
+ tile_counts_buffer: &tile_counts_buf,
+ e,
+ },
+ )
+ .expect("encode tile counts");
+ cb.commit();
+ cb.wait_until_completed();
+
+ let tile_counts_gpu = unsafe {
+ std::slice::from_raw_parts(
+ tile_counts_buf.contents() as *const u32,
+ e,
+ )
+ };
+
+ assert_eq!(tile_counts_gpu, &tile_counts_cpu[..]);
+ // With BM=16: seg_lens=[10, 5, 15, 20] -> tile_counts=[1, 1, 1, 2]
+ assert_eq!(tile_counts_gpu, &[1, 1, 1, 2]);
+ eprintln!("[TileEdgeCases] ✓ Small segments PASSED");
+ }
+}
diff --git a/crates/uzu/tests/text_session_test.rs b/crates/uzu/tests/text_session_test.rs
index 6fafb2aaa..268c948c9 100644
--- a/crates/uzu/tests/text_session_test.rs
+++ b/crates/uzu/tests/text_session_test.rs
@@ -80,6 +80,9 @@ fn run_scenario(
system_prompt: Option<String>,
user_prompts: Vec<String>,
) {
+ unsafe {
+ std::env::set_var("UZU_SKIP_RAM_CHECK", "1");
+ }
let mut session =
Session::new(build_model_path(), build_decoding_config()).unwrap();