A high-performance inference engine for AI models
mlp_fused
Eugene Bokhanced56b30534e
diff --git a/crates/uzu/src/backends/metal/encodable_block/mlp.rs b/crates/uzu/src/backends/metal/encodable_block/mlp.rsindex 3393dbde5..48be9a197 100644--- a/crates/uzu/src/backends/metal/encodable_block/mlp.rs+++ b/crates/uzu/src/backends/metal/encodable_block/mlp.rs@@ -12,10 +12,7 @@ use crate::{forward_pass::{ArrayId, ForwardPassState},kernel::{mlp::{MlpActivationType, MlpGateActMulEncodable},- mlp_fused::{- GemmArguments as MlpFusedGemmArguments, GemmKernel as MlpFusedGemmKernel,- GemvArguments as MlpFusedGemvArguments, GemvKernel as MlpFusedGemvKernel,- },+ mlp_fused::{MlpFusedArguments, MlpFusedKernel},quant_matmul::{MlpFusedQmmArguments, MlpFusedQmmKernel, MlpFusedQmvArguments,MlpFusedQmvKernel,@@ -122,8 +119,7 @@ impl EncodableBlock for MlpBlock {/// Selects between full precision and quantized fused kernelspub enum MlpFusedUpKernel {FullPrecision {- gemv: RefCell<MlpFusedGemvKernel>,- gemm: RefCell<MlpFusedGemmKernel>,+ kernel: RefCell<MlpFusedKernel>,},Quantized {qmv: MlpFusedQmvKernel,@@ -160,14 +156,12 @@ impl MlpFusedBlock {input_array_id: ArrayId,hidden_array_id: ArrayId,) -> Result<Self, crate::backends::metal::MTLError> {- let gemv = MlpFusedGemvKernel::new(data_type)?;- let gemm = MlpFusedGemmKernel::new(data_type, true)?; // Weights transposed+ let kernel = MlpFusedKernel::new(data_type, true)?; // Weights transposedOk(Self {context,fused_up: MlpFusedUpKernel::FullPrecision {- gemv: RefCell::new(gemv),- gemm: RefCell::new(gemm),+ kernel: RefCell::new(kernel),},down,weights_buffer,@@ -246,46 +240,28 @@ impl MlpFusedBlock {output: &MTLBuffer,batch: i32,) {- let is_decode = batch == 1;-match &self.fused_up {MlpFusedUpKernel::FullPrecision {- gemv,- gemm,+ kernel,} => {- if is_decode {- let args = MlpFusedGemvArguments {- weights: &self.weights_buffer,- input,- input_offset,- output,- input_dim: self.input_dim as i32,- hidden_dim: self.hidden_dim as i32,- weights_ld: self.input_dim as i32,- batch_count: batch,- activation: self.activation,- };- gemv.borrow_mut()- .encode(&self.context, encoder, &args)- .expect("Failed to encode MLP fused GEMV");- } else {- let args = MlpFusedGemmArguments {- input,- input_offset,- weights: &self.weights_buffer,- output,- batch,- input_dim: self.input_dim as i32,- hidden_dim: self.hidden_dim as i32,- lda: self.input_dim as i32,- ldb: self.input_dim as i32,- ldd: self.hidden_dim as i32,- activation: self.activation,- };- gemm.borrow_mut()- .encode(&self.context, encoder, &args)- .expect("Failed to encode MLP fused GEMM");- }+ let args = MlpFusedArguments {+ input,+ input_offset,+ weights: &self.weights_buffer,+ output,+ batch,+ input_dim: self.input_dim as i32,+ hidden_dim: self.hidden_dim as i32,+ lda: self.input_dim as i32,+ ldb: self.input_dim as i32,+ ldd: self.hidden_dim as i32,+ batch_count: batch,+ activation: self.activation,+ };+ kernel+ .borrow_mut()+ .encode(&self.context, encoder, &args)+ .expect("Failed to encode MLP fused kernel");},MlpFusedUpKernel::Quantized {qmv,@@ -295,6 +271,7 @@ impl MlpFusedBlock {let zp_or_biases =self.zero_points_or_biases_buffer.as_ref().unwrap();+ let is_decode = batch == 1;if is_decode {let args = MlpFusedQmvArguments {weights: &self.weights_buffer,diff --git a/crates/uzu/src/backends/metal/kernel/mlp_fused/common/mlp_fused_arguments.rs b/crates/uzu/src/backends/metal/kernel/mlp_fused/common/mlp_fused_arguments.rsnew file mode 100644index 000000000..2d05a64e7--- /dev/null+++ b/crates/uzu/src/backends/metal/kernel/mlp_fused/common/mlp_fused_arguments.rs@@ -0,0 +1,19 @@+use metal::Buffer as MTLBuffer;++use crate::backends::metal::kernel::mlp::MlpActivationType;++#[derive(Debug)]+pub struct MlpFusedArguments<'a> {+ pub input: &'a MTLBuffer,+ pub input_offset: u64,+ pub weights: &'a MTLBuffer,+ pub output: &'a MTLBuffer,+ pub batch: i32,+ pub input_dim: i32,+ pub hidden_dim: i32,+ pub lda: i32,+ pub ldb: i32,+ pub ldd: i32,+ pub batch_count: i32,+ pub activation: MlpActivationType,+}diff --git a/crates/uzu/src/backends/metal/kernel/mlp_fused/common/mod.rs b/crates/uzu/src/backends/metal/kernel/mlp_fused/common/mod.rsnew file mode 100644index 000000000..8816071bd--- /dev/null+++ b/crates/uzu/src/backends/metal/kernel/mlp_fused/common/mod.rs@@ -0,0 +1,3 @@+mod mlp_fused_arguments;++pub use mlp_fused_arguments::MlpFusedArguments;diff --git a/crates/uzu/src/backends/metal/kernel/mlp_fused/dispatch_descriptor.rs b/crates/uzu/src/backends/metal/kernel/mlp_fused/dispatch_descriptor.rsnew file mode 100644index 000000000..43fed2155--- /dev/null+++ b/crates/uzu/src/backends/metal/kernel/mlp_fused/dispatch_descriptor.rs@@ -0,0 +1,40 @@+use super::{common::MlpFusedArguments, gemm, gemv, split_k};+use crate::{+ DataType,+ backends::metal::{MTLContext, MTLError},+};++#[derive(Debug, Clone)]+pub(crate) enum MlpFusedDispatchDescriptor {+ Gemv(gemv::DispatchDescriptor),+ SplitK(split_k::DispatchDescriptor),+ Gemm(gemm::DispatchDescriptor),+}++pub(crate) fn choose_dispatch_descriptor(+ context: &MTLContext,+ data_type: DataType,+ weights_transposed: bool,+ arguments: &MlpFusedArguments,+) -> Result<MlpFusedDispatchDescriptor, MTLError> {+ if weights_transposed {+ if let Some(descriptor) =+ gemv::DispatchDescriptor::try_new(context, data_type, arguments)?+ {+ return Ok(MlpFusedDispatchDescriptor::Gemv(descriptor));+ }++ if let Some(descriptor) =+ split_k::DispatchDescriptor::try_new(context, data_type, arguments)?+ {+ return Ok(MlpFusedDispatchDescriptor::SplitK(descriptor));+ }+ }++ Ok(MlpFusedDispatchDescriptor::Gemm(gemm::DispatchDescriptor::new(+ context,+ data_type,+ weights_transposed,+ arguments,+ )?))+}diff --git a/crates/uzu/src/backends/metal/kernel/mlp_fused/gemm/dispatch_descriptor.rs b/crates/uzu/src/backends/metal/kernel/mlp_fused/gemm/dispatch_descriptor.rsnew file mode 100644index 000000000..6a37e8944--- /dev/null+++ b/crates/uzu/src/backends/metal/kernel/mlp_fused/gemm/dispatch_descriptor.rs@@ -0,0 +1,93 @@+use metal::MTLSize;++use super::{+ pipeline_configuration::PipelineConfiguration,+ tile_configuration::select_tile_configuration,+};+use crate::{+ DataType,+ backends::metal::{+ MTLContext, MTLError,+ kernel::{+ matmul::common::GEMMParams, mlp_fused::common::MlpFusedArguments,+ },+ },+};++#[derive(Debug, Clone)]+pub struct DispatchDescriptor {+ pub(crate) pipeline_configuration: PipelineConfiguration,+ pub(crate) params: GEMMParams,+ pub(crate) hidden_dim: i32,+ pub(crate) threadgroups: MTLSize,+ pub(crate) threads_per_threadgroup: MTLSize,+}++impl DispatchDescriptor {+ pub(crate) fn new(+ _context: &MTLContext,+ data_type: DataType,+ weights_transposed: bool,+ arguments: &MlpFusedArguments,+ ) -> Result<Self, MTLError> {+ if !matches!(data_type, DataType::F16 | DataType::BF16 | DataType::F32)+ {+ return Err(MTLError::Generic(format!(+ "Unsupported dtype for MLP fused GEMM: {data_type:?}"+ )));+ }++ let tile =+ select_tile_configuration(arguments.batch, arguments.hidden_dim);++ let mn_aligned = arguments.batch % tile.block_rows == 0+ && arguments.hidden_dim % tile.block_cols == 0;+ let k_aligned = arguments.input_dim % tile.block_depth == 0;++ let pipeline_configuration = PipelineConfiguration {+ tile,+ weights_transposed,+ mn_aligned,+ k_aligned,+ activation: arguments.activation,+ };++ let tiles_m = (arguments.batch + tile.block_rows - 1) / tile.block_rows;+ let tiles_n =+ (arguments.hidden_dim + tile.block_cols - 1) / tile.block_cols;+ let gemm_k_iterations =+ (arguments.input_dim + tile.block_depth - 1) / tile.block_depth;++ let params = GEMMParams {+ M: arguments.batch,+ N: arguments.hidden_dim * 2,+ K: arguments.input_dim,+ lda: arguments.lda,+ ldb: arguments.ldb,+ ldd: arguments.ldd,+ tiles_n,+ tiles_m,+ batch_stride_a: 0,+ batch_stride_b: 0,+ batch_stride_d: 0,+ swizzle_log: 0,+ gemm_k_iterations_aligned: if k_aligned {+ gemm_k_iterations+ } else {+ gemm_k_iterations - 1+ },+ batch_ndim: 0,+ };++ let threadgroups = MTLSize::new(tiles_n as u64, tiles_m as u64, 1);+ let threads_per_threadgroup = MTLSize::new(32, 2, 2);++ Ok(Self {+ pipeline_configuration,+ params,+ hidden_dim: arguments.hidden_dim,+ threadgroups,+ threads_per_threadgroup,+ })+ }+}diff --git a/crates/uzu/src/backends/metal/kernel/mlp_fused/gemm/kernel.rs b/crates/uzu/src/backends/metal/kernel/mlp_fused/gemm/kernel.rsnew file mode 100644index 000000000..923804394--- /dev/null+++ b/crates/uzu/src/backends/metal/kernel/mlp_fused/gemm/kernel.rs@@ -0,0 +1,145 @@+use std::collections::HashMap;++use metal::{+ ComputeCommandEncoderRef, ComputePipelineState as MTLComputePipelineState,+};++use super::{+ DispatchDescriptor, pipeline_configuration::PipelineConfiguration,+};+use crate::{+ DataType,+ backends::metal::{+ MTLContext, MTLError,+ kernel::{+ matmul::common::GEMMParams, mlp_fused::common::MlpFusedArguments,+ },+ },+};++pub struct Kernel {+ data_type: DataType,+ weights_transposed: bool,+ pipelines: HashMap<PipelineConfiguration, MTLComputePipelineState>,+}++impl Kernel {+ pub fn new(+ data_type: DataType,+ weights_transposed: bool,+ ) -> Result<Self, MTLError> {+ if !matches!(data_type, DataType::F16 | DataType::BF16 | DataType::F32)+ {+ return Err(MTLError::Generic(format!(+ "Unsupported dtype for MLP fused GEMM: {data_type:?}"+ )));+ }+ Ok(Self {+ data_type,+ weights_transposed,+ pipelines: HashMap::new(),+ })+ }++ pub fn weights_transposed(&self) -> bool {+ self.weights_transposed+ }++ fn kernel_name(+ &self,+ configuration: &PipelineConfiguration,+ ) -> String {+ let type_name = match self.data_type {+ DataType::F16 => "half",+ DataType::BF16 => "bfloat",+ DataType::F32 => "float",+ _ => unreachable!(),+ };+ let transpose_char = if configuration.weights_transposed {+ "t"+ } else {+ "n"+ };+ let mn_str = if configuration.mn_aligned {+ "true"+ } else {+ "false"+ };+ let k_str = if configuration.k_aligned {+ "true"+ } else {+ "false"+ };++ format!(+ "steel_gemm_mlp_fused_{}_{}_{}_bm{}_bn{}_bk16_wm2_wn2_align_MN_{}_K_{}",+ transpose_char,+ type_name,+ type_name,+ configuration.tile.block_rows,+ configuration.tile.block_cols,+ mn_str,+ k_str+ )+ }++ fn get_or_compile_pipeline(+ &mut self,+ context: &MTLContext,+ configuration: &PipelineConfiguration,+ ) -> Result<&MTLComputePipelineState, MTLError> {+ if !self.pipelines.contains_key(configuration) {+ let kernel_name = self.kernel_name(configuration);++ let function_constants = metal::FunctionConstantValues::new();+ let activation_val = configuration.activation as u32;+ function_constants.set_constant_value_at_index(+ &activation_val as *const u32 as *const _,+ metal::MTLDataType::UInt,+ 52,+ );++ let pipeline_state = context.compute_pipeline_state(+ &kernel_name,+ Some(&function_constants),+ )?;+ self.pipelines.insert(configuration.clone(), pipeline_state);+ }+ Ok(self.pipelines.get(configuration).unwrap())+ }++ pub(crate) fn encode_descriptor(+ &mut self,+ context: &MTLContext,+ encoder: &ComputeCommandEncoderRef,+ arguments: &MlpFusedArguments,+ descriptor: &DispatchDescriptor,+ ) -> Result<(), MTLError> {+ let pipeline_state = self.get_or_compile_pipeline(+ context,+ &descriptor.pipeline_configuration,+ )?;+ encoder.set_compute_pipeline_state(pipeline_state);++ encoder.set_buffer(0, Some(arguments.input), arguments.input_offset);+ encoder.set_buffer(1, Some(arguments.weights), 0);+ encoder.set_buffer(2, Some(arguments.output), 0);++ encoder.set_bytes(+ 3,+ std::mem::size_of::<GEMMParams>() as u64,+ &descriptor.params as *const GEMMParams as *const std::ffi::c_void,+ );+ encoder.set_bytes(+ 10,+ std::mem::size_of::<i32>() as u64,+ &descriptor.hidden_dim as *const i32 as *const std::ffi::c_void,+ );++ encoder.dispatch_thread_groups(+ descriptor.threadgroups,+ descriptor.threads_per_threadgroup,+ );+ Ok(())+ }+}diff --git a/crates/uzu/src/backends/metal/kernel/mlp_fused/gemm/mod.rs b/crates/uzu/src/backends/metal/kernel/mlp_fused/gemm/mod.rsindex 05b66ce46..6b041d0fc 100644--- a/crates/uzu/src/backends/metal/kernel/mlp_fused/gemm/mod.rs+++ b/crates/uzu/src/backends/metal/kernel/mlp_fused/gemm/mod.rs@@ -1,237 +1,7 @@-use std::collections::HashMap;+mod dispatch_descriptor;+mod kernel;+mod pipeline_configuration;+mod tile_configuration;-use metal::{- Buffer as MTLBuffer, ComputeCommandEncoderRef,- ComputePipelineState as MTLComputePipelineState, MTLSize,-};--use super::split_k;-use crate::{- DataType,- backends::metal::{- MTLContext, MTLError,- kernel::{matmul::common::GEMMParams, mlp::MlpActivationType},- },-};--#[derive(Debug)]-pub struct Arguments<'a> {- pub input: &'a MTLBuffer,- pub input_offset: u64,- pub weights: &'a MTLBuffer,- pub output: &'a MTLBuffer,- pub batch: i32,- pub input_dim: i32,- pub hidden_dim: i32,- pub lda: i32,- pub ldb: i32,- pub ldd: i32,- pub activation: MlpActivationType,-}--pub struct Kernel {- data_type: DataType,- weights_transposed: bool,- pipelines: HashMap<- (i32, i32, bool, bool, MlpActivationType),- MTLComputePipelineState,- >,- splitk_kernel: Option<split_k::Kernel>,-}--impl Kernel {- pub fn new(- data_type: DataType,- weights_transposed: bool,- ) -> Result<Self, MTLError> {- if !matches!(data_type, DataType::F16 | DataType::BF16 | DataType::F32)- {- return Err(MTLError::Generic(format!(- "Unsupported dtype for MLP fused GEMM: {:?}",- data_type- )));- }- let splitk_kernel = if weights_transposed- && matches!(data_type, DataType::F16 | DataType::BF16)- {- Some(split_k::Kernel::new(data_type))- } else {- None- };- Ok(Self {- data_type,- weights_transposed,- pipelines: HashMap::new(),- splitk_kernel,- })- }-- fn kernel_name(- &self,- bm: i32,- bn: i32,- mn_aligned: bool,- k_aligned: bool,- ) -> String {- let type_name = match self.data_type {- DataType::F16 => "half",- DataType::BF16 => "bfloat",- DataType::F32 => "float",- _ => unreachable!(),- };- let transpose_char = if self.weights_transposed {- "t"- } else {- "n"- };- let mn_str = if mn_aligned {- "true"- } else {- "false"- };- let k_str = if k_aligned {- "true"- } else {- "false"- };-- format!(- "steel_gemm_mlp_fused_{}_{}_{}_bm{}_bn{}_bk16_wm2_wn2_align_MN_{}_K_{}",- transpose_char, type_name, type_name, bm, bn, mn_str, k_str- )- }-- fn get_pipeline(- &mut self,- context: &MTLContext,- bm: i32,- bn: i32,- mn_aligned: bool,- k_aligned: bool,- activation: MlpActivationType,- ) -> Result<&MTLComputePipelineState, MTLError> {- let key = (bm, bn, mn_aligned, k_aligned, activation);- if !self.pipelines.contains_key(&key) {- let name = self.kernel_name(bm, bn, mn_aligned, k_aligned);-- let fcv = metal::FunctionConstantValues::new();- let activation_val = activation as u32;- fcv.set_constant_value_at_index(- &activation_val as *const u32 as *const _,- metal::MTLDataType::UInt,- 52,- );-- let pipeline = context.compute_pipeline_state(&name, Some(&fcv))?;- self.pipelines.insert(key, pipeline);- }- Ok(self.pipelines.get(&key).unwrap())- }-- fn select_tile_size(- &self,- m: i32,- hidden_dim: i32,- _k: i32,- ) -> (i32, i32) {- if m >= 64 && hidden_dim >= 64 {- (64, 64)- } else {- (32, 32)- }- }-- pub fn encode(- &mut self,- context: &MTLContext,- encoder: &ComputeCommandEncoderRef,- args: &Arguments,- ) -> Result<(), MTLError> {- if let Some(ref mut splitk) = self.splitk_kernel {- if split_k::Kernel::should_use_splitk(- args.batch,- args.hidden_dim,- args.input_dim,- ) {- let splitk_args = split_k::Arguments {- input: args.input,- input_offset: args.input_offset,- weights: args.weights,- output: args.output,- batch: args.batch,- input_dim: args.input_dim,- hidden_dim: args.hidden_dim,- lda: args.lda,- ldb: args.ldb,- ldd: args.ldd,- activation: args.activation,- };- return splitk.encode(context, encoder, &splitk_args);- }- }-- let (bm, bn) =- self.select_tile_size(args.batch, args.hidden_dim, args.input_dim);- let bk = 16;-- let mn_aligned = args.batch % bm == 0 && args.hidden_dim % bn == 0;- let k_aligned = args.input_dim % bk == 0;-- let pipeline = self.get_pipeline(- context,- bm,- bn,- mn_aligned,- k_aligned,- args.activation,- )?;- encoder.set_compute_pipeline_state(pipeline);-- encoder.set_buffer(0, Some(args.input), args.input_offset);- encoder.set_buffer(1, Some(args.weights), 0);- encoder.set_buffer(2, Some(args.output), 0);-- let tiles_m = (args.batch + bm - 1) / bm;- let tiles_n = (args.hidden_dim + bn - 1) / bn;- let gemm_k_iterations = (args.input_dim + bk - 1) / bk;-- let params = GEMMParams {- M: args.batch,- N: args.hidden_dim * 2,- K: args.input_dim,- lda: args.lda,- ldb: args.ldb,- ldd: args.ldd,- tiles_n,- tiles_m,- batch_stride_a: 0,- batch_stride_b: 0,- batch_stride_d: 0,- swizzle_log: 0,- gemm_k_iterations_aligned: if k_aligned {- gemm_k_iterations- } else {- gemm_k_iterations - 1- },- batch_ndim: 0,- };-- encoder.set_bytes(- 3,- std::mem::size_of::<GEMMParams>() as u64,- ¶ms as *const GEMMParams as *const std::ffi::c_void,- );- encoder.set_bytes(- 10,- std::mem::size_of::<i32>() as u64,- &args.hidden_dim as *const i32 as *const std::ffi::c_void,- );-- let threadgroup_count = MTLSize::new(tiles_n as u64, tiles_m as u64, 1);- let threads_per_threadgroup = MTLSize::new(32, 2, 2);-- encoder- .dispatch_thread_groups(threadgroup_count, threads_per_threadgroup);- Ok(())- }-}+pub(crate) use dispatch_descriptor::DispatchDescriptor;+pub use kernel::Kernel as GemmKernel;diff --git a/crates/uzu/src/backends/metal/kernel/mlp_fused/gemm/pipeline_configuration.rs b/crates/uzu/src/backends/metal/kernel/mlp_fused/gemm/pipeline_configuration.rsnew file mode 100644index 000000000..fdf5fa36b--- /dev/null+++ b/crates/uzu/src/backends/metal/kernel/mlp_fused/gemm/pipeline_configuration.rs@@ -0,0 +1,11 @@+use super::tile_configuration::TileConfiguration;+use crate::backends::metal::kernel::mlp::MlpActivationType;++#[derive(Debug, Clone, PartialEq, Eq, Hash)]+pub struct PipelineConfiguration {+ pub tile: TileConfiguration,+ pub weights_transposed: bool,+ pub mn_aligned: bool,+ pub k_aligned: bool,+ pub activation: MlpActivationType,+}diff --git a/crates/uzu/src/backends/metal/kernel/mlp_fused/gemm/tile_configuration.rs b/crates/uzu/src/backends/metal/kernel/mlp_fused/gemm/tile_configuration.rsnew file mode 100644index 000000000..408008478--- /dev/null+++ b/crates/uzu/src/backends/metal/kernel/mlp_fused/gemm/tile_configuration.rs@@ -0,0 +1,31 @@+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]+pub struct TileConfiguration {+ pub block_rows: i32,+ pub block_cols: i32,+ pub block_depth: i32,+}++impl TileConfiguration {+ pub fn new(+ block_rows: i32,+ block_cols: i32,+ block_depth: i32,+ ) -> Self {+ Self {+ block_rows,+ block_cols,+ block_depth,+ }+ }+}++pub fn select_tile_configuration(+ batch: i32,+ hidden_dim: i32,+) -> TileConfiguration {+ if batch >= 64 && hidden_dim >= 64 {+ TileConfiguration::new(64, 64, 16)+ } else {+ TileConfiguration::new(32, 32, 16)+ }+}diff --git a/crates/uzu/src/backends/metal/kernel/mlp_fused/gemv/dispatch_descriptor.rs b/crates/uzu/src/backends/metal/kernel/mlp_fused/gemv/dispatch_descriptor.rsnew file mode 100644index 000000000..b0b690839--- /dev/null+++ b/crates/uzu/src/backends/metal/kernel/mlp_fused/gemv/dispatch_descriptor.rs@@ -0,0 +1,69 @@+use metal::MTLSize;++use super::pipeline_configuration::{+ PipelineConfiguration, select_configuration,+};+use crate::{+ DataType,+ backends::metal::{+ MTLContext, MTLError, kernel::mlp_fused::common::MlpFusedArguments,+ },+};++#[derive(Debug, Clone)]+pub struct DispatchDescriptor {+ pub(crate) pipeline_configuration: PipelineConfiguration,+ pub(crate) input_dim: i32,+ pub(crate) hidden_dim: i32,+ pub(crate) weights_ld: i32,+ pub(crate) vector_batch_stride: i64,+ pub(crate) matrix_batch_stride: i64,+ pub(crate) threadgroups: MTLSize,+ pub(crate) threads_per_threadgroup: MTLSize,+}++impl DispatchDescriptor {+ pub(crate) fn try_new(+ _context: &MTLContext,+ data_type: DataType,+ arguments: &MlpFusedArguments,+ ) -> Result<Option<Self>, MTLError> {+ if !matches!(data_type, DataType::F16 | DataType::BF16 | DataType::F32)+ {+ return Err(MTLError::Generic(format!(+ "Unsupported dtype for MLP fused GEMV: {data_type:?}"+ )));+ }++ if arguments.batch != 1 {+ return Ok(None);+ }++ let pipeline_configuration =+ select_configuration(arguments.hidden_dim, arguments.activation);++ let output_elements_per_threadgroup =+ pipeline_configuration.output_elements_per_threadgroup();+ let threadgroup_count_x =+ ((arguments.hidden_dim as u32 + output_elements_per_threadgroup+ - 1)+ / output_elements_per_threadgroup) as u64;+ let threadgroup_count_z = arguments.batch_count.max(1) as u64;++ let threadgroups =+ MTLSize::new(threadgroup_count_x, 1, threadgroup_count_z);+ let threads_per_threadgroup =+ pipeline_configuration.threads_per_threadgroup();++ Ok(Some(Self {+ pipeline_configuration,+ input_dim: arguments.input_dim,+ hidden_dim: arguments.hidden_dim,+ weights_ld: arguments.ldb,+ vector_batch_stride: arguments.input_dim as i64,+ matrix_batch_stride: 0,+ threadgroups,+ threads_per_threadgroup,+ }))+ }+}diff --git a/crates/uzu/src/backends/metal/kernel/mlp_fused/gemv/kernel.rs b/crates/uzu/src/backends/metal/kernel/mlp_fused/gemv/kernel.rsnew file mode 100644index 000000000..c911d8abb--- /dev/null+++ b/crates/uzu/src/backends/metal/kernel/mlp_fused/gemv/kernel.rs@@ -0,0 +1,138 @@+use std::collections::HashMap;++use metal::{ComputeCommandEncoderRef, ComputePipelineState};++use super::{+ DispatchDescriptor, pipeline_configuration::PipelineConfiguration,+};+use crate::{+ DataType,+ backends::metal::{+ MTLContext, MTLError, kernel::mlp_fused::common::MlpFusedArguments,+ },+};++fn kernel_name(+ data_type: DataType,+ configuration: &PipelineConfiguration,+) -> Result<String, MTLError> {+ let dtype_name = match data_type {+ DataType::F16 => "float16",+ DataType::BF16 => "bfloat16",+ DataType::F32 => "float32",+ _ => {+ return Err(MTLError::Generic(format!(+ "Unsupported data type for MLP fused GEMV: {data_type:?}"+ )));+ },+ };++ Ok(format!(+ "gemv_mlp_fused_{}_bm{}_bn{}_sm{}_sn{}_tm{}_tn{}",+ dtype_name,+ configuration.threadgroup_rows,+ configuration.threadgroup_cols,+ configuration.threads_per_simdgroup_row,+ configuration.threads_per_simdgroup_col,+ configuration.elements_per_thread_row,+ configuration.elements_per_thread_col,+ ))+}++pub struct Kernel {+ data_type: DataType,+ pipelines: HashMap<PipelineConfiguration, ComputePipelineState>,+}++impl Kernel {+ pub fn new(data_type: DataType) -> Result<Self, MTLError> {+ if !matches!(data_type, DataType::F16 | DataType::BF16 | DataType::F32)+ {+ return Err(MTLError::Generic(format!(+ "Unsupported dtype for MLP fused GEMV: {data_type:?}"+ )));+ }+ Ok(Self {+ data_type,+ pipelines: HashMap::new(),+ })+ }++ fn get_or_compile_pipeline(+ &mut self,+ context: &MTLContext,+ configuration: &PipelineConfiguration,+ ) -> Result<&ComputePipelineState, MTLError> {+ if !self.pipelines.contains_key(configuration) {+ let kernel_name = kernel_name(self.data_type, configuration)?;++ let function_constants = metal::FunctionConstantValues::new();+ let activation_val = configuration.activation as u32;+ function_constants.set_constant_value_at_index(+ &activation_val as *const u32 as *const _,+ metal::MTLDataType::UInt,+ 52,+ );++ let pipeline_state = context.compute_pipeline_state(+ &kernel_name,+ Some(&function_constants),+ )?;+ self.pipelines.insert(*configuration, pipeline_state);+ }+ Ok(self.pipelines.get(configuration).unwrap())+ }++ pub(crate) fn encode_descriptor(+ &mut self,+ context: &MTLContext,+ encoder: &ComputeCommandEncoderRef,+ arguments: &MlpFusedArguments,+ descriptor: &DispatchDescriptor,+ ) -> Result<(), MTLError> {+ let pipeline_state = self.get_or_compile_pipeline(+ context,+ &descriptor.pipeline_configuration,+ )?;+ encoder.set_compute_pipeline_state(pipeline_state);++ encoder.set_buffer(0, Some(arguments.weights), 0);+ encoder.set_buffer(1, Some(arguments.input), arguments.input_offset);+ encoder.set_buffer(3, Some(arguments.output), 0);++ encoder.set_bytes(+ 4,+ std::mem::size_of::<i32>() as u64,+ &descriptor.input_dim as *const i32 as *const std::ffi::c_void,+ );+ encoder.set_bytes(+ 5,+ std::mem::size_of::<i32>() as u64,+ &descriptor.hidden_dim as *const i32 as *const std::ffi::c_void,+ );+ encoder.set_bytes(+ 6,+ std::mem::size_of::<i32>() as u64,+ &descriptor.weights_ld as *const i32 as *const std::ffi::c_void,+ );++ encoder.set_bytes(+ 11,+ std::mem::size_of::<i64>() as u64,+ &descriptor.vector_batch_stride as *const i64+ as *const std::ffi::c_void,+ );+ encoder.set_bytes(+ 12,+ std::mem::size_of::<i64>() as u64,+ &descriptor.matrix_batch_stride as *const i64+ as *const std::ffi::c_void,+ );++ encoder.dispatch_thread_groups(+ descriptor.threadgroups,+ descriptor.threads_per_threadgroup,+ );+ Ok(())+ }+}diff --git a/crates/uzu/src/backends/metal/kernel/mlp_fused/gemv/mod.rs b/crates/uzu/src/backends/metal/kernel/mlp_fused/gemv/mod.rsindex 0fc92d97b..5ee340249 100644--- a/crates/uzu/src/backends/metal/kernel/mlp_fused/gemv/mod.rs+++ b/crates/uzu/src/backends/metal/kernel/mlp_fused/gemv/mod.rs@@ -1,202 +1,6 @@-use std::collections::HashMap;+mod dispatch_descriptor;+mod kernel;+mod pipeline_configuration;-use metal::{- Buffer as MTLBuffer, ComputeCommandEncoderRef, ComputePipelineState,- MTLSize,-};--use crate::{- DataType,- backends::metal::{MTLContext, MTLError, kernel::mlp::MlpActivationType},-};--#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]-struct Configuration {- threadgroup_rows: u32,- threadgroup_cols: u32,- threads_per_simdgroup_row: u32,- threads_per_simdgroup_col: u32,- elements_per_thread_row: u32,- elements_per_thread_col: u32,- activation: MlpActivationType,-}--impl Configuration {- fn output_elements_per_threadgroup(&self) -> u32 {- self.threadgroup_rows- * self.threads_per_simdgroup_row- * self.elements_per_thread_row- }-- fn threads_per_threadgroup(&self) -> MTLSize {- MTLSize::new(- 32,- self.threadgroup_cols as u64,- self.threadgroup_rows as u64,- )- }-}--fn kernel_name(- data_type: DataType,- config: &Configuration,-) -> Result<String, MTLError> {- let dtype_name = match data_type {- DataType::F16 => "float16",- DataType::BF16 => "bfloat16",- DataType::F32 => "float32",- _ => {- return Err(MTLError::Generic(format!(- "Unsupported data type for MLP fused GEMV: {:?}",- data_type- )));- },- };-- Ok(format!(- "gemv_mlp_fused_{}_bm{}_bn{}_sm{}_sn{}_tm{}_tn{}",- dtype_name,- config.threadgroup_rows,- config.threadgroup_cols,- config.threads_per_simdgroup_row,- config.threads_per_simdgroup_col,- config.elements_per_thread_row,- config.elements_per_thread_col,- ))-}--fn select_configuration(- hidden_dim: i32,- activation: MlpActivationType,-) -> Configuration {- let threadgroup_rows = if hidden_dim >= 4096 {- 8- } else {- 4- };-- Configuration {- threadgroup_rows,- threadgroup_cols: 1,- threads_per_simdgroup_row: 1,- threads_per_simdgroup_col: 32,- elements_per_thread_row: 4,- elements_per_thread_col: 4,- activation,- }-}--#[derive(Debug)]-pub struct Arguments<'a> {- pub weights: &'a MTLBuffer,- pub input: &'a MTLBuffer,- pub input_offset: u64,- pub output: &'a MTLBuffer,- pub input_dim: i32,- pub hidden_dim: i32,- pub weights_ld: i32,- pub batch_count: i32,- pub activation: MlpActivationType,-}--pub struct Kernel {- data_type: DataType,- pipelines: HashMap<Configuration, ComputePipelineState>,-}--impl Kernel {- pub fn new(data_type: DataType) -> Result<Self, MTLError> {- if !matches!(data_type, DataType::F16 | DataType::BF16 | DataType::F32)- {- return Err(MTLError::Generic(format!(- "Unsupported dtype for MLP fused GEMV: {:?}",- data_type- )));- }- Ok(Self {- data_type,- pipelines: HashMap::new(),- })- }-- fn get_pipeline(- &mut self,- context: &MTLContext,- config: Configuration,- ) -> Result<&ComputePipelineState, MTLError> {- if !self.pipelines.contains_key(&config) {- let name = kernel_name(self.data_type, &config)?;-- let fcv = metal::FunctionConstantValues::new();- let activation_val = config.activation as u32;- fcv.set_constant_value_at_index(- &activation_val as *const u32 as *const _,- metal::MTLDataType::UInt,- 52,- );-- let pipeline = context.compute_pipeline_state(&name, Some(&fcv))?;- self.pipelines.insert(config, pipeline);- }- Ok(self.pipelines.get(&config).unwrap())- }-- pub fn encode(- &mut self,- context: &MTLContext,- encoder: &ComputeCommandEncoderRef,- args: &Arguments,- ) -> Result<(), MTLError> {- let config = select_configuration(args.hidden_dim, args.activation);- let pipeline = self.get_pipeline(context, config)?;-- encoder.set_compute_pipeline_state(pipeline);- encoder.set_buffer(0, Some(args.weights), 0);- encoder.set_buffer(1, Some(args.input), args.input_offset);- encoder.set_buffer(3, Some(args.output), 0);-- encoder.set_bytes(- 4,- std::mem::size_of::<i32>() as u64,- &args.input_dim as *const i32 as *const std::ffi::c_void,- );- encoder.set_bytes(- 5,- std::mem::size_of::<i32>() as u64,- &args.hidden_dim as *const i32 as *const std::ffi::c_void,- );- encoder.set_bytes(- 6,- std::mem::size_of::<i32>() as u64,- &args.weights_ld as *const i32 as *const std::ffi::c_void,- );-- let vector_batch_stride = args.input_dim as i64;- let matrix_batch_stride = 0i64;- encoder.set_bytes(- 11,- std::mem::size_of::<i64>() as u64,- &vector_batch_stride as *const i64 as *const std::ffi::c_void,- );- encoder.set_bytes(- 12,- std::mem::size_of::<i64>() as u64,- &matrix_batch_stride as *const i64 as *const std::ffi::c_void,- );-- let output_elements_per_threadgroup =- config.output_elements_per_threadgroup();- let threadgroup_count_x =- ((args.hidden_dim as u32 + output_elements_per_threadgroup - 1)- / output_elements_per_threadgroup) as u64;- let threadgroup_count_z = args.batch_count.max(1) as u64;-- let threadgroup_count =- MTLSize::new(threadgroup_count_x, 1, threadgroup_count_z);- let threads_per_threadgroup = config.threads_per_threadgroup();-- encoder- .dispatch_thread_groups(threadgroup_count, threads_per_threadgroup);- Ok(())- }-}+pub(crate) use dispatch_descriptor::DispatchDescriptor;+pub use kernel::Kernel as GemvKernel;diff --git a/crates/uzu/src/backends/metal/kernel/mlp_fused/gemv/pipeline_configuration.rs b/crates/uzu/src/backends/metal/kernel/mlp_fused/gemv/pipeline_configuration.rsnew file mode 100644index 000000000..9b310a2df--- /dev/null+++ b/crates/uzu/src/backends/metal/kernel/mlp_fused/gemv/pipeline_configuration.rs@@ -0,0 +1,51 @@+use metal::MTLSize;++use crate::backends::metal::kernel::mlp::MlpActivationType;++#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]+pub struct PipelineConfiguration {+ pub threadgroup_rows: u32,+ pub threadgroup_cols: u32,+ pub threads_per_simdgroup_row: u32,+ pub threads_per_simdgroup_col: u32,+ pub elements_per_thread_row: u32,+ pub elements_per_thread_col: u32,+ pub activation: MlpActivationType,+}++impl PipelineConfiguration {+ pub fn output_elements_per_threadgroup(&self) -> u32 {+ self.threadgroup_rows+ * self.threads_per_simdgroup_row+ * self.elements_per_thread_row+ }++ pub fn threads_per_threadgroup(&self) -> MTLSize {+ MTLSize::new(+ 32,+ self.threadgroup_cols as u64,+ self.threadgroup_rows as u64,+ )+ }+}++pub fn select_configuration(+ hidden_dim: i32,+ activation: MlpActivationType,+) -> PipelineConfiguration {+ let threadgroup_rows = if hidden_dim >= 4096 {+ 8+ } else {+ 4+ };++ PipelineConfiguration {+ threadgroup_rows,+ threadgroup_cols: 1,+ threads_per_simdgroup_row: 1,+ threads_per_simdgroup_col: 32,+ elements_per_thread_row: 4,+ elements_per_thread_col: 4,+ activation,+ }+}diff --git a/crates/uzu/src/backends/metal/kernel/mlp_fused/kernel.rs b/crates/uzu/src/backends/metal/kernel/mlp_fused/kernel.rsnew file mode 100644index 000000000..6f4bc0695--- /dev/null+++ b/crates/uzu/src/backends/metal/kernel/mlp_fused/kernel.rs@@ -0,0 +1,112 @@+use metal::ComputeCommandEncoderRef;++use super::{+ common::MlpFusedArguments,+ dispatch_descriptor::{+ MlpFusedDispatchDescriptor, choose_dispatch_descriptor,+ },+ gemm::GemmKernel,+ gemv::GemvKernel,+ split_k::SplitKKernel,+};+use crate::{+ DataType,+ backends::metal::{MTLContext, MTLError},+};++pub struct MlpFusedKernel {+ data_type: DataType,+ weights_transposed: bool,+ gemm: Option<GemmKernel>,+ gemv: Option<GemvKernel>,+ splitk: Option<SplitKKernel>,+}++impl MlpFusedKernel {+ pub fn new(+ data_type: DataType,+ weights_transposed: bool,+ ) -> Result<Self, MTLError> {+ if !matches!(data_type, DataType::F16 | DataType::BF16 | DataType::F32)+ {+ return Err(MTLError::Generic(format!(+ "Unsupported dtype for MlpFusedKernel: {data_type:?}"+ )));+ }++ Ok(Self {+ data_type,+ weights_transposed,+ gemm: None,+ gemv: None,+ splitk: None,+ })+ }++ fn get_or_create_gemm(&mut self) -> Result<&mut GemmKernel, MTLError> {+ if self.gemm.is_none() {+ self.gemm =+ Some(GemmKernel::new(self.data_type, self.weights_transposed)?);+ }+ Ok(self.gemm.as_mut().unwrap())+ }++ fn get_or_create_gemv(&mut self) -> Result<&mut GemvKernel, MTLError> {+ if self.gemv.is_none() {+ self.gemv = Some(GemvKernel::new(self.data_type)?);+ }+ Ok(self.gemv.as_mut().unwrap())+ }++ fn get_or_create_splitk(&mut self) -> Result<&mut SplitKKernel, MTLError> {+ if self.splitk.is_none() {+ self.splitk = Some(SplitKKernel::new(self.data_type)?);+ }+ Ok(self.splitk.as_mut().unwrap())+ }++ fn encode_dispatch_descriptor(+ &mut self,+ context: &MTLContext,+ encoder: &ComputeCommandEncoderRef,+ arguments: &MlpFusedArguments,+ descriptor: &MlpFusedDispatchDescriptor,+ ) -> Result<(), MTLError> {+ match descriptor {+ MlpFusedDispatchDescriptor::Gemv(descriptor) => {+ let gemv = self.get_or_create_gemv()?;+ gemv.encode_descriptor(context, encoder, arguments, descriptor)+ },+ MlpFusedDispatchDescriptor::SplitK(descriptor) => {+ let splitk = self.get_or_create_splitk()?;+ splitk+ .encode_descriptor(context, encoder, arguments, descriptor)+ },+ MlpFusedDispatchDescriptor::Gemm(descriptor) => {+ let gemm = self.get_or_create_gemm()?;+ gemm.encode_descriptor(context, encoder, arguments, descriptor)+ },+ }+ }++ pub fn encode(+ &mut self,+ context: &MTLContext,+ encoder: &ComputeCommandEncoderRef,+ arguments: &MlpFusedArguments,+ ) -> Result<(), MTLError> {+ let descriptor = choose_dispatch_descriptor(+ context,+ self.data_type,+ self.weights_transposed,+ arguments,+ )?;++ self.encode_dispatch_descriptor(+ context,+ encoder,+ arguments,+ &descriptor,+ )+ }+}diff --git a/crates/uzu/src/backends/metal/kernel/mlp_fused/mod.rs b/crates/uzu/src/backends/metal/kernel/mlp_fused/mod.rsindex bbbf615c1..53118d819 100644--- a/crates/uzu/src/backends/metal/kernel/mlp_fused/mod.rs+++ b/crates/uzu/src/backends/metal/kernel/mlp_fused/mod.rs@@ -1,7 +1,12 @@-pub mod gemm;-pub mod gemv;-pub mod split_k;+pub mod common;+mod dispatch_descriptor;+mod gemm;+mod gemv;+mod kernel;+mod split_k;-pub use gemm::{Arguments as GemmArguments, Kernel as GemmKernel};-pub use gemv::{Arguments as GemvArguments, Kernel as GemvKernel};-pub use split_k::{Arguments as SplitKArguments, Kernel as SplitKKernel};+pub use common::MlpFusedArguments;+pub use gemm::GemmKernel;+pub use gemv::GemvKernel;+pub use kernel::MlpFusedKernel;+pub use split_k::SplitKKernel;diff --git a/crates/uzu/src/backends/metal/kernel/mlp_fused/split_k/dispatch_descriptor.rs b/crates/uzu/src/backends/metal/kernel/mlp_fused/split_k/dispatch_descriptor.rsnew file mode 100644index 000000000..604d332d5--- /dev/null+++ b/crates/uzu/src/backends/metal/kernel/mlp_fused/split_k/dispatch_descriptor.rs@@ -0,0 +1,153 @@+use metal::MTLSize;++use super::{+ pipeline_configuration::PipelineConfiguration,+ tile_configuration::select_tile_configuration,+};+use crate::{+ DataType,+ backends::metal::{+ MTLContext, MTLError,+ kernel::{+ matmul::common::GEMMSpiltKMlpFusedParams,+ mlp_fused::common::MlpFusedArguments,+ },+ },+};++#[derive(Debug, Clone)]+pub struct DispatchDescriptor {+ pub(crate) pipeline_configuration: PipelineConfiguration,+ pub(crate) params: GEMMSpiltKMlpFusedParams,+ pub(crate) partition_count: i32,+ pub(crate) output_elements_per_partition: i32,+ pub(crate) accumulator_bytes: usize,+ pub(crate) ldd: i32,+ pub(crate) partial_threadgroups: MTLSize,+ pub(crate) partial_threads_per_threadgroup: MTLSize,+ pub(crate) accum_total_threads: MTLSize,+ pub(crate) accum_threads_per_threadgroup: MTLSize,+}++impl DispatchDescriptor {+ pub(crate) fn try_new(+ _context: &MTLContext,+ data_type: DataType,+ arguments: &MlpFusedArguments,+ ) -> Result<Option<Self>, MTLError> {+ if !matches!(data_type, DataType::F16 | DataType::BF16) {+ return Ok(None);+ }++ if !should_use_splitk(+ arguments.batch,+ arguments.hidden_dim,+ arguments.input_dim,+ ) {+ return Ok(None);+ }++ let batch = arguments.batch;+ let hidden_dim = arguments.hidden_dim;+ let input_dim = arguments.input_dim;++ let tile = select_tile_configuration(batch, hidden_dim);+ let partition_count = compute_partition_count(input_dim);+ let mn_aligned =+ (batch % tile.tile_rows) == 0 && (hidden_dim % tile.tile_cols) == 0;+ let k_aligned = (input_dim % tile.tile_depth) == 0;++ let pipeline_configuration = PipelineConfiguration {+ tile,+ mn_aligned,+ k_aligned,+ activation: arguments.activation,+ };++ let tile_count_m = (batch + tile.tile_rows - 1) / tile.tile_rows;+ let tile_count_n = (hidden_dim + tile.tile_cols - 1) / tile.tile_cols;++ let gemm_k_iterations = (input_dim / tile.tile_depth) / partition_count;+ let k_elements_per_partition = gemm_k_iterations * tile.tile_depth;+ let output_elements_per_partition = batch * hidden_dim;++ let accumulator_element_count =+ partition_count * output_elements_per_partition;+ let accumulator_bytes =+ (accumulator_element_count as usize) * std::mem::size_of::<f32>();++ let params = GEMMSpiltKMlpFusedParams {+ M: batch,+ N: hidden_dim,+ K: input_dim,+ lda: arguments.lda,+ ldb: arguments.ldb,+ ldc: hidden_dim,+ tiles_n: tile_count_n,+ tiles_m: tile_count_m,+ split_k_partitions: partition_count,+ split_k_partition_stride: output_elements_per_partition,+ split_k_partition_size: k_elements_per_partition,+ gemm_k_iterations_aligned: gemm_k_iterations,+ hidden_dim,+ };++ let partial_threads_per_threadgroup = MTLSize::new(+ 32,+ tile.warps_per_col as u64,+ tile.warps_per_row as u64,+ );+ let partial_threadgroups = MTLSize::new(+ tile_count_n as u64,+ tile_count_m as u64,+ partition_count as u64,+ );++ let accum_total_threads =+ MTLSize::new(hidden_dim as u64, batch as u64, 1);+ let accum_threads_per_threadgroup =+ MTLSize::new(16.min(hidden_dim as u64), 16.min(batch as u64), 1);++ Ok(Some(Self {+ pipeline_configuration,+ params,+ partition_count,+ output_elements_per_partition,+ accumulator_bytes,+ ldd: arguments.ldd,+ partial_threadgroups,+ partial_threads_per_threadgroup,+ accum_total_threads,+ accum_threads_per_threadgroup,+ }))+ }+}++fn compute_partition_count(k: i32) -> i32 {+ let k_tiles = k / 16;+ if k_tiles < 16 {+ 2+ } else if k_tiles < 32 {+ 4+ } else if k_tiles < 64 {+ 8+ } else {+ 16+ }+}++pub fn should_use_splitk(+ batch: i32,+ hidden_dim: i32,+ input_dim: i32,+) -> bool {+ if batch != 1 {+ return false;+ }+ if hidden_dim <= 0 || input_dim <= 0 {+ return false;+ }+ let n_tiles = hidden_dim / 16;+ let k_tiles = input_dim / 16;+ n_tiles <= 32 && k_tiles >= 8+}diff --git a/crates/uzu/src/backends/metal/kernel/mlp_fused/split_k/kernel.rs b/crates/uzu/src/backends/metal/kernel/mlp_fused/split_k/kernel.rsnew file mode 100644index 000000000..007f0640d--- /dev/null+++ b/crates/uzu/src/backends/metal/kernel/mlp_fused/split_k/kernel.rs@@ -0,0 +1,203 @@+use std::collections::HashMap;++use metal::{+ Buffer as MTLBuffer, ComputeCommandEncoderRef,+ ComputePipelineState as MTLComputePipelineState,+};++use super::{+ DispatchDescriptor, pipeline_configuration::PipelineConfiguration,+};+use crate::{+ DataType,+ backends::metal::{+ MTLContext, MTLError,+ kernel::{+ matmul::common::GEMMSpiltKMlpFusedParams, mlp::MlpActivationType,+ mlp_fused::common::MlpFusedArguments,+ },+ },+};++pub struct Kernel {+ data_type: DataType,+ partial_pipelines: HashMap<PipelineConfiguration, MTLComputePipelineState>,+ accum_pipelines: HashMap<MlpActivationType, MTLComputePipelineState>,+}++impl Kernel {+ pub fn new(data_type: DataType) -> Result<Self, MTLError> {+ if !matches!(data_type, DataType::F16 | DataType::BF16) {+ return Err(MTLError::Generic(format!(+ "Unsupported dtype for MLP fused Split-K: {data_type:?}"+ )));+ }+ Ok(Self {+ data_type,+ partial_pipelines: HashMap::new(),+ accum_pipelines: HashMap::new(),+ })+ }++ fn steel_type_name(&self) -> Result<&'static str, MTLError> {+ match self.data_type {+ DataType::F16 => Ok("float16"),+ DataType::BF16 => Ok("bfloat16"),+ _ => Err(MTLError::Generic(format!(+ "Unsupported dtype for MLP Fused Split-K: {:?}",+ self.data_type+ ))),+ }+ }++ fn partial_kernel_name(+ &self,+ configuration: &PipelineConfiguration,+ ) -> Result<String, MTLError> {+ let in_name = self.steel_type_name()?;+ let mn_tag = if configuration.mn_aligned {+ "taligned"+ } else {+ "naligned"+ };+ let k_tag = if configuration.k_aligned {+ "taligned"+ } else {+ "naligned"+ };+ Ok(format!(+ "steel_gemm_splitk_mlp_fused_nt_{}_float32_bm{}_bn{}_bk{}_wm{}_wn{}_MN_{}_K_{}",+ in_name,+ configuration.tile.tile_rows,+ configuration.tile.tile_cols,+ configuration.tile.tile_depth,+ configuration.tile.warps_per_row,+ configuration.tile.warps_per_col,+ mn_tag,+ k_tag,+ ))+ }++ fn accum_kernel_name(&self) -> Result<String, MTLError> {+ let out_name = self.steel_type_name()?;+ Ok(format!("steel_gemm_splitk_mlp_fused_accum_{}_float32", out_name))+ }++ fn get_partial_pipeline(+ &mut self,+ context: &MTLContext,+ configuration: &PipelineConfiguration,+ ) -> Result<&MTLComputePipelineState, MTLError> {+ if !self.partial_pipelines.contains_key(configuration) {+ let kernel_name = self.partial_kernel_name(configuration)?;+ let pipeline_state =+ context.compute_pipeline_state(&kernel_name, None)?;+ self.partial_pipelines+ .insert(configuration.clone(), pipeline_state);+ }+ Ok(self.partial_pipelines.get(configuration).unwrap())+ }++ fn get_accum_pipeline(+ &mut self,+ context: &MTLContext,+ activation: MlpActivationType,+ ) -> Result<&MTLComputePipelineState, MTLError> {+ if !self.accum_pipelines.contains_key(&activation) {+ let kernel_name = self.accum_kernel_name()?;+ let function_constants = metal::FunctionConstantValues::new();+ let activation_val = activation as u32;+ function_constants.set_constant_value_at_index(+ &activation_val as *const u32 as *const _,+ metal::MTLDataType::UInt,+ 52,+ );+ let pipeline_state = context.compute_pipeline_state(+ &kernel_name,+ Some(&function_constants),+ )?;+ self.accum_pipelines.insert(activation, pipeline_state);+ }+ Ok(self.accum_pipelines.get(&activation).unwrap())+ }++ fn ensure_accumulator_buffers(+ &self,+ context: &MTLContext,+ required_bytes: usize,+ ) -> (MTLBuffer, MTLBuffer) {+ let up_buffer = context.device.new_buffer(+ required_bytes as u64,+ metal::MTLResourceOptions::StorageModePrivate,+ );+ let gate_buffer = context.device.new_buffer(+ required_bytes as u64,+ metal::MTLResourceOptions::StorageModePrivate,+ );+ (up_buffer, gate_buffer)+ }++ pub(crate) fn encode_descriptor(+ &mut self,+ context: &MTLContext,+ encoder: &ComputeCommandEncoderRef,+ arguments: &MlpFusedArguments,+ descriptor: &DispatchDescriptor,+ ) -> Result<(), MTLError> {+ let (up_accumulator_buffer, gate_accumulator_buffer) = self+ .ensure_accumulator_buffers(context, descriptor.accumulator_bytes);++ let partial_pipeline_state = self.get_partial_pipeline(+ context,+ &descriptor.pipeline_configuration,+ )?;++ encoder.set_compute_pipeline_state(partial_pipeline_state);+ encoder.set_buffer(0, Some(arguments.input), arguments.input_offset);+ encoder.set_buffer(1, Some(arguments.weights), 0);+ encoder.set_buffer(2, Some(&up_accumulator_buffer), 0);+ encoder.set_buffer(3, Some(&gate_accumulator_buffer), 0);+ encoder.set_bytes(+ 4,+ std::mem::size_of::<GEMMSpiltKMlpFusedParams>() as u64,+ &descriptor.params as *const GEMMSpiltKMlpFusedParams as *const _,+ );+ encoder.dispatch_thread_groups(+ descriptor.partial_threadgroups,+ descriptor.partial_threads_per_threadgroup,+ );++ let accum_pipeline_state = self.get_accum_pipeline(+ context,+ descriptor.pipeline_configuration.activation,+ )?;+ encoder.set_compute_pipeline_state(accum_pipeline_state);+ encoder.set_buffer(0, Some(&up_accumulator_buffer), 0);+ encoder.set_buffer(1, Some(&gate_accumulator_buffer), 0);+ encoder.set_buffer(2, Some(arguments.output), 0);+ encoder.set_bytes(+ 3,+ 4,+ &descriptor.partition_count as *const i32+ as *const std::ffi::c_void,+ );+ encoder.set_bytes(+ 4,+ 4,+ &descriptor.output_elements_per_partition as *const i32+ as *const std::ffi::c_void,+ );+ encoder.set_bytes(+ 5,+ 4,+ &descriptor.ldd as *const i32 as *const std::ffi::c_void,+ );++ encoder.dispatch_threads(+ descriptor.accum_total_threads,+ descriptor.accum_threads_per_threadgroup,+ );++ Ok(())+ }+}diff --git a/crates/uzu/src/backends/metal/kernel/mlp_fused/split_k/mod.rs b/crates/uzu/src/backends/metal/kernel/mlp_fused/split_k/mod.rsindex 191d42704..efefcd2bd 100644--- a/crates/uzu/src/backends/metal/kernel/mlp_fused/split_k/mod.rs+++ b/crates/uzu/src/backends/metal/kernel/mlp_fused/split_k/mod.rs@@ -1,313 +1,7 @@-use std::collections::HashMap;+mod dispatch_descriptor;+mod kernel;+mod pipeline_configuration;+mod tile_configuration;-use metal::{- Buffer as MTLBuffer, ComputeCommandEncoderRef,- ComputePipelineState as MTLComputePipelineState, MTLSize,-};--use crate::{- DataType,- backends::metal::{- MTLContext, MTLError,- kernel::{- matmul::common::GEMMSpiltKMlpFusedParams, mlp::MlpActivationType,- },- },-};--#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]-struct TileConfig {- tile_rows: i32,- tile_cols: i32,- tile_depth: i32,- warps_per_row: i32,- warps_per_col: i32,-}--#[derive(Debug, Clone, PartialEq, Eq, Hash)]-struct PartialKernelKey {- tile_config: TileConfig,- mn_aligned: bool,- k_aligned: bool,-}--#[derive(Debug)]-pub struct Arguments<'a> {- pub input: &'a MTLBuffer,- pub input_offset: u64,- pub weights: &'a MTLBuffer,- pub output: &'a MTLBuffer,- pub batch: i32,- pub input_dim: i32,- pub hidden_dim: i32,- pub lda: i32,- pub ldb: i32,- pub ldd: i32,- pub activation: MlpActivationType,-}--pub struct Kernel {- data_type: DataType,- partial_pipelines: HashMap<PartialKernelKey, MTLComputePipelineState>,- accum_pipelines: HashMap<MlpActivationType, MTLComputePipelineState>,-}--impl Kernel {- pub fn new(data_type: DataType) -> Self {- Self {- data_type,- partial_pipelines: HashMap::new(),- accum_pipelines: HashMap::new(),- }- }-- fn steel_type_name(&self) -> Result<&'static str, MTLError> {- match self.data_type {- DataType::F16 => Ok("float16"),- DataType::BF16 => Ok("bfloat16"),- _ => Err(MTLError::Generic(format!(- "Unsupported dtype for MLP Fused Split-K: {:?}",- self.data_type- ))),- }- }-- fn partial_kernel_name(- &self,- config: &TileConfig,- mn_aligned: bool,- k_aligned: bool,- ) -> Result<String, MTLError> {- let in_name = self.steel_type_name()?;- let mn_tag = if mn_aligned {- "taligned"- } else {- "naligned"- };- let k_tag = if k_aligned {- "taligned"- } else {- "naligned"- };- Ok(format!(- "steel_gemm_splitk_mlp_fused_nt_{}_float32_bm{}_bn{}_bk{}_wm{}_wn{}_MN_{}_K_{}",- in_name,- config.tile_rows,- config.tile_cols,- config.tile_depth,- config.warps_per_row,- config.warps_per_col,- mn_tag,- k_tag,- ))- }-- fn accum_kernel_name(&self) -> Result<String, MTLError> {- let out_name = self.steel_type_name()?;- Ok(format!("steel_gemm_splitk_mlp_fused_accum_{}_float32", out_name))- }-- fn get_partial_pipeline(- &mut self,- mtl: &MTLContext,- config: TileConfig,- mn_aligned: bool,- k_aligned: bool,- ) -> Result<&MTLComputePipelineState, MTLError> {- let key = PartialKernelKey {- tile_config: config,- mn_aligned,- k_aligned,- };- if !self.partial_pipelines.contains_key(&key) {- let name =- self.partial_kernel_name(&config, mn_aligned, k_aligned)?;- let ps = mtl.compute_pipeline_state(&name, None)?;- self.partial_pipelines.insert(key.clone(), ps);- }- Ok(self.partial_pipelines.get(&key).unwrap())- }-- fn get_accum_pipeline(- &mut self,- mtl: &MTLContext,- activation: MlpActivationType,- ) -> Result<&MTLComputePipelineState, MTLError> {- if !self.accum_pipelines.contains_key(&activation) {- let name = self.accum_kernel_name()?;- let fcv = metal::FunctionConstantValues::new();- let activation_val = activation as u32;- fcv.set_constant_value_at_index(- &activation_val as *const u32 as *const _,- metal::MTLDataType::UInt,- 52,- );- let ps = mtl.compute_pipeline_state(&name, Some(&fcv))?;- self.accum_pipelines.insert(activation, ps);- }- Ok(self.accum_pipelines.get(&activation).unwrap())- }-- fn select_tile_config(- m: i32,- n: i32,- ) -> TileConfig {- let tile_rows = if m < 40 {- 16- } else {- 32- };- let tile_cols = if n < 40 {- 16- } else {- 32- };- TileConfig {- tile_rows,- tile_cols,- tile_depth: 16,- warps_per_row: 2,- warps_per_col: 2,- }- }-- fn compute_partition_count(k: i32) -> i32 {- let k_tiles = k / 16;- if k_tiles < 16 {- 2- } else if k_tiles < 32 {- 4- } else if k_tiles < 64 {- 8- } else {- 16- }- }-- pub fn should_use_splitk(- m: i32,- hidden_dim: i32,- k: i32,- ) -> bool {- if m != 1 {- return false;- }- if hidden_dim <= 0 || k <= 0 {- return false;- }- let n_tiles = hidden_dim / 16;- let k_tiles = k / 16;- n_tiles <= 32 && k_tiles >= 8- }-- pub fn encode(- &mut self,- mtl: &MTLContext,- enc: &ComputeCommandEncoderRef,- args: &Arguments,- ) -> Result<(), MTLError> {- let m = args.batch;- let hidden_dim = args.hidden_dim;- let k = args.input_dim;-- let tile_config = Self::select_tile_config(m, hidden_dim);- let partition_count = Self::compute_partition_count(k);- let mn_aligned = (m % tile_config.tile_rows) == 0- && (hidden_dim % tile_config.tile_cols) == 0;- let k_aligned = (k % tile_config.tile_depth) == 0;-- let tile_count_m =- (m + tile_config.tile_rows - 1) / tile_config.tile_rows;- let tile_count_n =- (hidden_dim + tile_config.tile_cols - 1) / tile_config.tile_cols;-- let gemm_k_iterations = (k / tile_config.tile_depth) / partition_count;- let k_elements_per_partition =- gemm_k_iterations * tile_config.tile_depth;- let output_elements_per_partition = m * hidden_dim;-- let accumulator_element_count =- partition_count * output_elements_per_partition;- let accumulator_bytes =- (accumulator_element_count as usize) * std::mem::size_of::<f32>();-- let up_accumulator_buffer = mtl.device.new_buffer(- accumulator_bytes as u64,- metal::MTLResourceOptions::StorageModePrivate,- );- let gate_accumulator_buffer = mtl.device.new_buffer(- accumulator_bytes as u64,- metal::MTLResourceOptions::StorageModePrivate,- );-- let params = GEMMSpiltKMlpFusedParams {- M: m,- N: hidden_dim,- K: k,- lda: args.lda,- ldb: args.ldb,- ldc: hidden_dim,- tiles_n: tile_count_n,- tiles_m: tile_count_m,- split_k_partitions: partition_count,- split_k_partition_stride: output_elements_per_partition,- split_k_partition_size: k_elements_per_partition,- gemm_k_iterations_aligned: gemm_k_iterations,- hidden_dim,- };-- let partial_ps =- self.get_partial_pipeline(mtl, tile_config, mn_aligned, k_aligned)?;-- enc.set_compute_pipeline_state(partial_ps);- enc.set_buffer(0, Some(args.input), args.input_offset);- enc.set_buffer(1, Some(args.weights), 0);- enc.set_buffer(2, Some(&up_accumulator_buffer), 0);- enc.set_buffer(3, Some(&gate_accumulator_buffer), 0);- enc.set_bytes(- 4,- std::mem::size_of::<GEMMSpiltKMlpFusedParams>() as u64,- ¶ms as *const GEMMSpiltKMlpFusedParams as *const _,- );-- let threads_per_threadgroup = MTLSize::new(- 32,- tile_config.warps_per_col as u64,- tile_config.warps_per_row as u64,- );- let threadgroups = MTLSize::new(- tile_count_n as u64,- tile_count_m as u64,- partition_count as u64,- );- enc.dispatch_thread_groups(threadgroups, threads_per_threadgroup);-- let accum_ps = self.get_accum_pipeline(mtl, args.activation)?;- enc.set_compute_pipeline_state(accum_ps);- enc.set_buffer(0, Some(&up_accumulator_buffer), 0);- enc.set_buffer(1, Some(&gate_accumulator_buffer), 0);- enc.set_buffer(2, Some(args.output), 0);- enc.set_bytes(- 3,- 4,- &partition_count as *const i32 as *const std::ffi::c_void,- );- enc.set_bytes(- 4,- 4,- &output_elements_per_partition as *const i32- as *const std::ffi::c_void,- );- enc.set_bytes(5, 4, &args.ldd as *const i32 as *const std::ffi::c_void);-- let accum_total_threads = MTLSize::new(hidden_dim as u64, m as u64, 1);- let accum_threads_per_threadgroup =- MTLSize::new(16.min(hidden_dim as u64), 16.min(m as u64), 1);- enc.dispatch_threads(- accum_total_threads,- accum_threads_per_threadgroup,- );-- Ok(())- }-}+pub(crate) use dispatch_descriptor::DispatchDescriptor;+pub use kernel::Kernel as SplitKKernel;diff --git a/crates/uzu/src/backends/metal/kernel/mlp_fused/split_k/pipeline_configuration.rs b/crates/uzu/src/backends/metal/kernel/mlp_fused/split_k/pipeline_configuration.rsnew file mode 100644index 000000000..4f21c8f5e--- /dev/null+++ b/crates/uzu/src/backends/metal/kernel/mlp_fused/split_k/pipeline_configuration.rs@@ -0,0 +1,10 @@+use super::tile_configuration::TileConfiguration;+use crate::backends::metal::kernel::mlp::MlpActivationType;++#[derive(Debug, Clone, PartialEq, Eq, Hash)]+pub struct PipelineConfiguration {+ pub tile: TileConfiguration,+ pub mn_aligned: bool,+ pub k_aligned: bool,+ pub activation: MlpActivationType,+}diff --git a/crates/uzu/src/backends/metal/kernel/mlp_fused/split_k/tile_configuration.rs b/crates/uzu/src/backends/metal/kernel/mlp_fused/split_k/tile_configuration.rsnew file mode 100644index 000000000..c1de7141a--- /dev/null+++ b/crates/uzu/src/backends/metal/kernel/mlp_fused/split_k/tile_configuration.rs@@ -0,0 +1,31 @@+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]+pub struct TileConfiguration {+ pub tile_rows: i32,+ pub tile_cols: i32,+ pub tile_depth: i32,+ pub warps_per_row: i32,+ pub warps_per_col: i32,+}++pub fn select_tile_configuration(+ batch: i32,+ hidden_dim: i32,+) -> TileConfiguration {+ let tile_rows = if batch < 40 {+ 16+ } else {+ 32+ };+ let tile_cols = if hidden_dim < 40 {+ 16+ } else {+ 32+ };+ TileConfiguration {+ tile_rows,+ tile_cols,+ tile_depth: 16,+ warps_per_row: 2,+ warps_per_col: 2,+ }+}diff --git a/crates/uzu/tests/matmul_correctness_test.rs b/crates/uzu/tests/matmul_correctness_test.rsindex 98ff7029d..1d119306d 100644--- a/crates/uzu/tests/matmul_correctness_test.rs+++ b/crates/uzu/tests/matmul_correctness_test.rs@@ -47,8 +47,7 @@ fn run_metal_matmul(n};- let mut kernel = MatmulKernel::new(ctx, DataType::BF16, false, transpose_b)- .expect("kernel");+ let mut kernel = MatmulKernel::new(DataType::BF16).expect("kernel");let cb = ctx.command_queue.new_command_buffer().to_owned();let enc = cb.new_compute_command_encoder();@@ -62,6 +61,7 @@ fn run_metal_matmul(b: &b_buf,c: None,d: &d_buf,+ bias: None,batch: m as i32,input_dim: k as i32,output_dim: n as i32,@@ -71,8 +71,9 @@ fn run_metal_matmul(batch_count: 1,alpha: 1.0,beta: 0.0,+ transpose_a: false,+ transpose_b,},- None,).expect("encode");enc.end_encoding();diff --git a/crates/uzu/tests/mlp_fused_correctness_test.rs b/crates/uzu/tests/mlp_fused_correctness_test.rsindex 04de27d08..70a9d85ac 100644--- a/crates/uzu/tests/mlp_fused_correctness_test.rs+++ b/crates/uzu/tests/mlp_fused_correctness_test.rs@@ -10,12 +10,7 @@ use uzu::{MTLContext,kernel::{mlp::MlpActivationType,- mlp_fused::{- GemmArguments as MlpFusedGemmArguments,- GemmKernel as MlpFusedGemmKernel,- GemvArguments as MlpFusedGemvArguments,- GemvKernel as MlpFusedGemvKernel,- },+ mlp_fused::{MlpFusedArguments, MlpFusedKernel},},},};@@ -74,7 +69,7 @@ fn mlp_fused_reference(result}-/// Run MLP fused GEMV kernel (decode path, M=1)+/// Run MLP fused kernel (decode path, M=1)fn run_fused_gemv(ctx: &MTLContext,input: &[f16],@@ -98,19 +93,23 @@ fn run_fused_gemv(MTLResourceOptions::StorageModeShared,);- let mut kernel = MlpFusedGemvKernel::new(DataType::F16).expect("kernel");+ let mut kernel =+ MlpFusedKernel::new(DataType::F16, true).expect("kernel");let cb = ctx.command_queue.new_command_buffer().to_owned();let enc = cb.new_compute_command_encoder();- let args = MlpFusedGemvArguments {- weights: &weights_buf,+ let args = MlpFusedArguments {input: &input_buf,input_offset: 0,+ weights: &weights_buf,output: &output_buf,+ batch: 1,input_dim: k as i32,hidden_dim: hidden_dim as i32,- weights_ld: k as i32,+ lda: k as i32,+ ldb: k as i32,+ ldd: hidden_dim as i32,batch_count: 1,activation,};@@ -126,7 +125,7 @@ fn run_fused_gemv(}}-/// Run MLP fused GEMM kernel (prefill path, M>1)+/// Run MLP fused kernel (prefill path, M>1)fn run_fused_gemm(ctx: &MTLContext,input: &[f16],@@ -152,12 +151,12 @@ fn run_fused_gemm();let mut kernel =- MlpFusedGemmKernel::new(DataType::F16, true).expect("kernel");+ MlpFusedKernel::new(DataType::F16, true).expect("kernel");let cb = ctx.command_queue.new_command_buffer().to_owned();let enc = cb.new_compute_command_encoder();- let args = MlpFusedGemmArguments {+ let args = MlpFusedArguments {input: &input_buf,input_offset: 0,weights: &weights_buf,@@ -168,6 +167,7 @@ fn run_fused_gemm(lda: k as i32,ldb: k as i32,ldd: hidden_dim as i32,+ batch_count: 1,activation,};diff --git a/crates/uzu/tests/mlp_fused_performance_test.rs b/crates/uzu/tests/mlp_fused_performance_test.rsindex 317fa812e..efa02eb14 100644--- a/crates/uzu/tests/mlp_fused_performance_test.rs+++ b/crates/uzu/tests/mlp_fused_performance_test.rs@@ -13,12 +13,7 @@ use uzu::{kernel::{matmul::{MatmulArguments, MatmulKernel},mlp::MlpActivationType,- mlp_fused::{- GemmArguments as MlpFusedGemmArguments,- GemmKernel as MlpFusedGemmKernel,- GemvArguments as MlpFusedGemvArguments,- GemvKernel as MlpFusedGemvKernel,- },+ mlp_fused::{MlpFusedArguments, MlpFusedKernel},},},};@@ -76,27 +71,32 @@ fn benchmark_gemv_fused();let mut fused_kernel =- MlpFusedGemvKernel::new(DataType::F16).expect("fused kernel");- let mut matmul_kernel =- MatmulKernel::new(context, DataType::F16, false, true).expect("matmul");+ MlpFusedKernel::new(DataType::F16, true).expect("fused kernel");+ let mut matmul_kernel = MatmulKernel::new(DataType::F16).expect("matmul");++ let fused_args = MlpFusedArguments {+ input: &input_buffer,+ input_offset: 0,+ weights: &weights_buffer,+ output: &output_buffer,+ batch: 1,+ input_dim: input_dimension as i32,+ hidden_dim: hidden_dimension as i32,+ lda: input_dimension as i32,+ ldb: input_dimension as i32,+ ldd: hidden_dimension as i32,+ batch_count: 1,+ activation: MlpActivationType::SiLU,+ };// Warmup fusedfor _ in 0..warmup_count {let command_buffer =context.command_queue.new_command_buffer().to_owned();let encoder = command_buffer.new_compute_command_encoder();- let arguments = MlpFusedGemvArguments {- weights: &weights_buffer,- input: &input_buffer,- input_offset: 0,- output: &output_buffer,- input_dim: input_dimension as i32,- hidden_dim: hidden_dimension as i32,- weights_ld: input_dimension as i32,- batch_count: 1,- activation: MlpActivationType::SiLU,- };- fused_kernel.encode(context, &encoder, &arguments).unwrap();+ fused_kernel+ .encode(context, &encoder, &fused_args)+ .unwrap();encoder.end_encoding();command_buffer.commit();command_buffer.wait_until_completed();@@ -108,51 +108,42 @@ fn benchmark_gemv_fused(let command_buffer =context.command_queue.new_command_buffer().to_owned();let encoder = command_buffer.new_compute_command_encoder();- let arguments = MlpFusedGemvArguments {- weights: &weights_buffer,- input: &input_buffer,- input_offset: 0,- output: &output_buffer,- input_dim: input_dimension as i32,- hidden_dim: hidden_dimension as i32,- weights_ld: input_dimension as i32,- batch_count: 1,- activation: MlpActivationType::SiLU,- };- fused_kernel.encode(context, &encoder, &arguments).unwrap();+ fused_kernel+ .encode(context, &encoder, &fused_args)+ .unwrap();encoder.end_encoding();command_buffer.commit();command_buffer.wait_until_completed();}let fused_duration = fused_start.elapsed() / iteration_count as u32;+ let matmul_args = MatmulArguments {+ a: &input_buffer,+ a_offset: 0,+ b: &weights_buffer,+ c: None,+ d: &fused_up_buffer,+ bias: None,+ batch: 1,+ input_dim: input_dimension as i32,+ output_dim: (2 * hidden_dimension) as i32,+ lda: input_dimension as i32,+ ldb: input_dimension as i32,+ ldd: (2 * hidden_dimension) as i32,+ batch_count: 1,+ alpha: 1.0,+ beta: 0.0,+ transpose_a: false,+ transpose_b: true,+ };+// Warmup unfusedfor _ in 0..warmup_count {let command_buffer =context.command_queue.new_command_buffer().to_owned();let encoder = command_buffer.new_compute_command_encoder();matmul_kernel- .encode(- context,- &encoder,- MatmulArguments {- a: &input_buffer,- a_offset: 0,- b: &weights_buffer,- c: None,- d: &fused_up_buffer,- batch: 1,- input_dim: input_dimension as i32,- output_dim: (2 * hidden_dimension) as i32,- lda: input_dimension as i32,- ldb: input_dimension as i32,- ldd: (2 * hidden_dimension) as i32,- batch_count: 1,- alpha: 1.0,- beta: 0.0,- },- None,- )+ .encode(context, &encoder, matmul_args.clone()).unwrap();encoder.end_encoding();command_buffer.commit();@@ -166,27 +157,7 @@ fn benchmark_gemv_fused(context.command_queue.new_command_buffer().to_owned();let encoder = command_buffer.new_compute_command_encoder();matmul_kernel- .encode(- context,- &encoder,- MatmulArguments {- a: &input_buffer,- a_offset: 0,- b: &weights_buffer,- c: None,- d: &fused_up_buffer,- batch: 1,- input_dim: input_dimension as i32,- output_dim: (2 * hidden_dimension) as i32,- lda: input_dimension as i32,- ldb: input_dimension as i32,- ldd: (2 * hidden_dimension) as i32,- batch_count: 1,- alpha: 1.0,- beta: 0.0,- },- None,- )+ .encode(context, &encoder, matmul_args.clone()).unwrap();encoder.end_encoding();command_buffer.commit();@@ -224,29 +195,32 @@ fn benchmark_gemm_fused();let mut fused_kernel =- MlpFusedGemmKernel::new(DataType::F16, true).expect("fused kernel");- let mut matmul_kernel =- MatmulKernel::new(context, DataType::F16, false, true).expect("matmul");+ MlpFusedKernel::new(DataType::F16, true).expect("fused kernel");+ let mut matmul_kernel = MatmulKernel::new(DataType::F16).expect("matmul");++ let fused_args = MlpFusedArguments {+ input: &input_buffer,+ input_offset: 0,+ weights: &weights_buffer,+ output: &output_buffer,+ batch: batch_size as i32,+ input_dim: input_dimension as i32,+ hidden_dim: hidden_dimension as i32,+ lda: input_dimension as i32,+ ldb: input_dimension as i32,+ ldd: hidden_dimension as i32,+ batch_count: 1,+ activation: MlpActivationType::SiLU,+ };// Warmup fusedfor _ in 0..warmup_count {let command_buffer =context.command_queue.new_command_buffer().to_owned();let encoder = command_buffer.new_compute_command_encoder();- let arguments = MlpFusedGemmArguments {- input: &input_buffer,- input_offset: 0,- weights: &weights_buffer,- output: &output_buffer,- batch: batch_size as i32,- input_dim: input_dimension as i32,- hidden_dim: hidden_dimension as i32,- lda: input_dimension as i32,- ldb: input_dimension as i32,- ldd: hidden_dimension as i32,- activation: MlpActivationType::SiLU,- };- fused_kernel.encode(context, &encoder, &arguments).unwrap();+ fused_kernel+ .encode(context, &encoder, &fused_args)+ .unwrap();encoder.end_encoding();command_buffer.commit();command_buffer.wait_until_completed();@@ -257,53 +231,42 @@ fn benchmark_gemm_fused(let command_buffer =context.command_queue.new_command_buffer().to_owned();let encoder = command_buffer.new_compute_command_encoder();- let arguments = MlpFusedGemmArguments {- input: &input_buffer,- input_offset: 0,- weights: &weights_buffer,- output: &output_buffer,- batch: batch_size as i32,- input_dim: input_dimension as i32,- hidden_dim: hidden_dimension as i32,- lda: input_dimension as i32,- ldb: input_dimension as i32,- ldd: hidden_dimension as i32,- activation: MlpActivationType::SiLU,- };- fused_kernel.encode(context, &encoder, &arguments).unwrap();+ fused_kernel+ .encode(context, &encoder, &fused_args)+ .unwrap();encoder.end_encoding();command_buffer.commit();command_buffer.wait_until_completed();}let fused_duration = fused_start.elapsed() / iteration_count as u32;+ let matmul_args = MatmulArguments {+ a: &input_buffer,+ a_offset: 0,+ b: &weights_buffer,+ c: None,+ d: &fused_up_buffer,+ bias: None,+ batch: batch_size as i32,+ input_dim: input_dimension as i32,+ output_dim: (2 * hidden_dimension) as i32,+ lda: input_dimension as i32,+ ldb: input_dimension as i32,+ ldd: (2 * hidden_dimension) as i32,+ batch_count: 1,+ alpha: 1.0,+ beta: 0.0,+ transpose_a: false,+ transpose_b: true,+ };+// Warmup unfusedfor _ in 0..warmup_count {let command_buffer =context.command_queue.new_command_buffer().to_owned();let encoder = command_buffer.new_compute_command_encoder();matmul_kernel- .encode(- context,- &encoder,- MatmulArguments {- a: &input_buffer,- a_offset: 0,- b: &weights_buffer,- c: None,- d: &fused_up_buffer,- batch: batch_size as i32,- input_dim: input_dimension as i32,- output_dim: (2 * hidden_dimension) as i32,- lda: input_dimension as i32,- ldb: input_dimension as i32,- ldd: (2 * hidden_dimension) as i32,- batch_count: 1,- alpha: 1.0,- beta: 0.0,- },- None,- )+ .encode(context, &encoder, matmul_args.clone()).unwrap();encoder.end_encoding();command_buffer.commit();@@ -316,27 +279,7 @@ fn benchmark_gemm_fused(context.command_queue.new_command_buffer().to_owned();let encoder = command_buffer.new_compute_command_encoder();matmul_kernel- .encode(- context,- &encoder,- MatmulArguments {- a: &input_buffer,- a_offset: 0,- b: &weights_buffer,- c: None,- d: &fused_up_buffer,- batch: batch_size as i32,- input_dim: input_dimension as i32,- output_dim: (2 * hidden_dimension) as i32,- lda: input_dimension as i32,- ldb: input_dimension as i32,- ldd: (2 * hidden_dimension) as i32,- batch_count: 1,- alpha: 1.0,- beta: 0.0,- },- None,- )+ .encode(context, &encoder, matmul_args.clone()).unwrap();encoder.end_encoding();command_buffer.commit();