A high-performance inference engine for AI models
update split k
Eugene Bokhane25addba360f
diff --git a/crates/uzu/src/backends/metal/kernel/matmul/kernel.rs b/crates/uzu/src/backends/metal/kernel/matmul/kernel.rsindex 9f6e81742..39d1c62f1 100644--- a/crates/uzu/src/backends/metal/kernel/matmul/kernel.rs+++ b/crates/uzu/src/backends/metal/kernel/matmul/kernel.rs@@ -148,13 +148,15 @@ impl MatmulKernel {let k = args.input_dim;let batch_count = args.batch_count;- let splitk =- self.splitk.get_or_insert_with(|| SplitKGemm::new(self.dt));- if splitk.should_use_splitk(m, n, k, batch_count) {- splitk.encode(mtl, enc, args)?;- return Ok(true);+ if !SplitKGemm::should_use_splitk(m, n, k, batch_count) {+ return Ok(false);}- Ok(false)++ let splitk = self.splitk.get_or_insert_with(|| {+ SplitKGemm::new(self.dt, self.transpose_a, self.transpose_b)+ });+ splitk.encode(mtl, enc, args)?;+ Ok(true)}fn select_tiles(diff --git a/crates/uzu/src/backends/metal/kernel/matmul/matmul.metal b/crates/uzu/src/backends/metal/kernel/matmul/matmul.metalindex f1b70c726..aea205633 100644--- a/crates/uzu/src/backends/metal/kernel/matmul/matmul.metal+++ b/crates/uzu/src/backends/metal/kernel/matmul/matmul.metal@@ -476,14 +476,12 @@ template <// clang-format on// clang-format off-#define instantiate_gemm_shapes_helper(type_name, element_type) \- instantiate_gemm_transpose_helper(type_name, element_type, 64, 64, 16, 2, 2) \- instantiate_gemm_transpose_helper(type_name, element_type, 64, 64, 16, 1, 2) \- instantiate_gemm_transpose_helper(type_name, element_type, 64, 32, 32, 2, 2) \- instantiate_gemm_transpose_helper(type_name, element_type, 32, 64, 16, 1, 2) \- instantiate_gemm_transpose_helper(type_name, element_type, 32, 32, 16, 2, 2) \- instantiate_gemm_transpose_helper(type_name, element_type, 64, 32, 8, 4, 1) \- /* NAX-oriented larger tiles (safe BK=32) */ \+#define instantiate_gemm_shapes_helper(type_name, element_type) \+ instantiate_gemm_transpose_helper(type_name, element_type, 64, 64, 16, 1, 2) \+ instantiate_gemm_transpose_helper(type_name, element_type, 64, 32, 32, 2, 2) \+ instantiate_gemm_transpose_helper(type_name, element_type, 32, 64, 16, 1, 2) \+ instantiate_gemm_transpose_helper(type_name, element_type, 32, 32, 16, 2, 2) \+ /* NAX-oriented larger tiles (safe BK=32) */ \instantiate_gemm_transpose_helper(type_name, element_type, 64, 64, 32, 2, 2) \instantiate_gemm_transpose_helper(type_name, element_type, 128, 128, 32, 2, 2)// clang-format ondiff --git a/crates/uzu/src/backends/metal/kernel/matmul/shared_types.h b/crates/uzu/src/backends/metal/kernel/matmul/shared_types.hindex 4a9b28047..aea7226cc 100644--- a/crates/uzu/src/backends/metal/kernel/matmul/shared_types.h+++ b/crates/uzu/src/backends/metal/kernel/matmul/shared_types.h@@ -59,6 +59,24 @@ struct GEMMAddMMParams {float beta;};+struct SplitKGEMMParams {+ int m;+ int n;+ int k;++ int leading_dim_a;+ int leading_dim_b;+ int leading_dim_accumulator;++ int tile_count_n;+ int tile_count_m;++ int partition_count;+ int output_elements_per_partition;+ int k_elements_per_partition;+ int gemm_k_iterations_aligned;+};+// Close Metal namespace#ifdef __METAL_VERSION__} // namespace matmuldiff --git a/crates/uzu/src/backends/metal/kernel/matmul/splitk.metal b/crates/uzu/src/backends/metal/kernel/matmul/splitk.metalindex bdfec8f94..0b2a48247 100644--- a/crates/uzu/src/backends/metal/kernel/matmul/splitk.metal+++ b/crates/uzu/src/backends/metal/kernel/matmul/splitk.metal@@ -1,125 +1,241 @@-// Split-K GEMM partial accumulation kernels (simplified).-// Partial products are accumulated into a float buffer; a second kernel-// converts to the target type.+// Split-K GEMM: partitions K dimension across threadgroups for better+// parallelism on small M*N with large K.#include <metal_stdlib>+#include "gemm.h"+using namespace metal;+using namespace uzu::matmul;-template <typename T, typename AccT>-METAL_FUNC void splitk_partial_impl(- const device T* __restrict a [[buffer(0)]],- const device T* __restrict b [[buffer(1)]],- device atomic_float* __restrict accum [[buffer(2)]],- constant uint& m [[buffer(3)]],- constant uint& n [[buffer(4)]],- constant uint& k [[buffer(5)]],- constant uint& lda [[buffer(6)]],- constant uint& ldb [[buffer(7)]],- constant uint& ldd [[buffer(8)]],- constant uint& k_start [[buffer(9)]],- constant uint& k_end [[buffer(10)]],- uint3 tgid [[threadgroup_position_in_grid]],- uint3 tid [[thread_position_in_threadgroup]]) {- const uint col = tgid.x * 8 + tid.x;- const uint row = tgid.y * 8 + tid.y;- const uint batch = tgid.z;-- if (row >= m || col >= n) {- return;- }+///////////////////////////////////////////////////////////////////////////////+// Split-K Partial GEMM Kernel+///////////////////////////////////////////////////////////////////////////////- const device T* a_row = a + batch * (lda * m) + row * lda;- const device T* b_col = b + col * ldb;+template <+ typename InputType,+ typename AccumulatorType,+ int TileRows,+ int TileCols,+ int TileDepth,+ int WarpsPerRow,+ int WarpsPerCol,+ bool TransposeA,+ bool TransposeB,+ bool MNAligned,+ bool KAligned>+[[kernel, max_total_threads_per_threadgroup(WarpsPerRow * WarpsPerCol * 32)]]+void splitk_partial_gemm(+ const device InputType* input_a [[buffer(0)]],+ const device InputType* input_b [[buffer(1)]],+ device AccumulatorType* accumulator [[buffer(2)]],+ const constant SplitKGEMMParams* params [[buffer(3)]],+ uint simd_lane_id [[thread_index_in_simdgroup]],+ uint simd_group_id [[simdgroup_index_in_threadgroup]],+ uint3 threadgroup_id [[threadgroup_position_in_grid]],+ uint3 thread_id [[thread_position_in_threadgroup]]) {+ (void)thread_id;- AccT acc = static_cast<AccT>(0);- for (uint kk = k_start; kk < k_end; kk++) {- acc += static_cast<AccT>(a_row[kk]) *- static_cast<AccT>(b_col[kk]);- }+ using gemm_kernel = GEMMKernel<+ InputType,+ AccumulatorType,+ TileRows,+ TileCols,+ TileDepth,+ WarpsPerRow,+ WarpsPerCol,+ TransposeA,+ TransposeB,+ MNAligned,+ KAligned,+ AccumulatorType>;- const uint out_index = batch * (ldd * m) + row * ldd + col;- atomic_fetch_add_explicit(&accum[out_index], acc, memory_order_relaxed);-}+ using loader_a_t = typename gemm_kernel::loader_a_t;+ using loader_b_t = typename gemm_kernel::loader_b_t;+ using mma_t = typename gemm_kernel::mma_t;++ threadgroup InputType shared_a[gemm_kernel::tgp_mem_size_a];+ threadgroup InputType shared_b[gemm_kernel::tgp_mem_size_b];++ const int tile_x = threadgroup_id.x;+ const int tile_y = threadgroup_id.y;+ const int partition_index = threadgroup_id.z;++ if (params->tile_count_n <= tile_x || params->tile_count_m <= tile_y) {+ return;+ }++ const int output_row = tile_y * TileRows;+ const int output_col = tile_x * TileCols;+ const int k_partition_start = params->k_elements_per_partition * partition_index;++ const size_t output_row_long = size_t(output_row);+ const size_t output_col_long = size_t(output_col);+ const size_t k_start_long = size_t(k_partition_start);++ const device InputType* a_ptr = input_a;+ const device InputType* b_ptr = input_b;++ a_ptr += TransposeA+ ? (output_row_long + k_start_long * params->leading_dim_a)+ : (k_start_long + output_row_long * params->leading_dim_a);+ b_ptr += TransposeB+ ? (k_start_long + output_col_long * params->leading_dim_b)+ : (output_col_long + k_start_long * params->leading_dim_b);++ device AccumulatorType* output_ptr = accumulator ++ (size_t(params->output_elements_per_partition) * partition_index) ++ (output_row_long * params->leading_dim_accumulator + output_col_long);++ thread loader_a_t loader_a(a_ptr, params->leading_dim_a, shared_a, simd_group_id, simd_lane_id);+ thread loader_b_t loader_b(b_ptr, params->leading_dim_b, shared_b, simd_group_id, simd_lane_id);+ thread mma_t mma_op(simd_group_id, simd_lane_id);++ int gemm_k_iterations = params->gemm_k_iterations_aligned;-template <typename T>-METAL_FUNC void splitk_convert_impl(- const device atomic_float* __restrict accum [[buffer(0)]],- device T* __restrict out [[buffer(1)]],- constant uint& m [[buffer(2)]],- constant uint& n [[buffer(3)]],- constant uint& ldd [[buffer(4)]],- uint3 tgid [[threadgroup_position_in_grid]],- uint3 tid [[thread_position_in_threadgroup]]) {- const uint col = tgid.x * 8 + tid.x;- const uint row = tgid.y * 8 + tid.y;- const uint batch = tgid.z;-- if (row >= m || col >= n) {- return;+ short tile_bound_m = min(TileRows, params->m - output_row);+ short tile_bound_n = min(TileCols, params->n - output_col);+ short leftover_k = params->k % TileDepth;++ const bool is_last_partition = (partition_index + 1) == params->partition_count;++ if (MNAligned || (tile_bound_m == TileRows && tile_bound_n == TileCols)) {+ gemm_kernel::gemm_loop(+ shared_a, shared_b,+ gemm_k_iterations,+ loader_a, loader_b, mma_op,+ tile_bound_m, tile_bound_n, leftover_k,+ LoopAlignment<true, true, true>{});+ } else if (tile_bound_n == TileCols) {+ gemm_kernel::gemm_loop(+ shared_a, shared_b,+ gemm_k_iterations,+ loader_a, loader_b, mma_op,+ tile_bound_m, tile_bound_n, leftover_k,+ LoopAlignment<false, true, true>{});+ } else if (tile_bound_m == TileRows) {+ gemm_kernel::gemm_loop(+ shared_a, shared_b,+ gemm_k_iterations,+ loader_a, loader_b, mma_op,+ tile_bound_m, tile_bound_n, leftover_k,+ LoopAlignment<true, false, true>{});+ } else {+ gemm_kernel::gemm_loop(+ shared_a, shared_b,+ gemm_k_iterations,+ loader_a, loader_b, mma_op,+ tile_bound_m, tile_bound_n, leftover_k,+ LoopAlignment<false, false, true>{});+ }++ threadgroup_barrier(mem_flags::mem_threadgroup);++ if (is_last_partition) {+ int remaining_k_iterations =+ (params->k - (k_partition_start + params->k_elements_per_partition)) / TileDepth;+ if (!KAligned || remaining_k_iterations > 0) {+ gemm_kernel::gemm_loop(+ shared_a, shared_b,+ remaining_k_iterations,+ loader_a, loader_b, mma_op,+ tile_bound_m, tile_bound_n, leftover_k,+ LoopAlignment<false, false, KAligned>{});}+ }- const uint idx = batch * (ldd * m) + row * ldd + col;- const float v = atomic_load_explicit(&accum[idx], memory_order_relaxed);- out[idx] = static_cast<T>(v);+ if (MNAligned || (tile_bound_m == TileRows && tile_bound_n == TileCols)) {+ mma_op.store_result(output_ptr, params->leading_dim_accumulator);+ } else {+ mma_op.store_result_safe(output_ptr, params->leading_dim_accumulator, short2(tile_bound_n, tile_bound_m));+ }}-// Kernel entry points-[[kernel, max_total_threads_per_threadgroup(256)]] void splitk_partial_f16(- const device half* a [[buffer(0)]],- const device half* b [[buffer(1)]],- device atomic_float* accum [[buffer(2)]],- constant uint& m [[buffer(3)]],- constant uint& n [[buffer(4)]],- constant uint& k [[buffer(5)]],- constant uint& lda [[buffer(6)]],- constant uint& ldb [[buffer(7)]],- constant uint& ldd [[buffer(8)]],- constant uint& k_start [[buffer(9)]],- constant uint& k_end [[buffer(10)]],- uint3 tgid [[threadgroup_position_in_grid]],- uint3 tid [[thread_position_in_threadgroup]]) {- splitk_partial_impl<half, float>(- a, b, accum, m, n, k, lda, ldb, ldd, k_start, k_end, tgid, tid);-}+///////////////////////////////////////////////////////////////////////////////+// Split-K Accumulation Kernel+///////////////////////////////////////////////////////////////////////////////-[[kernel, max_total_threads_per_threadgroup(256)]] void splitk_partial_bf16(- const device bfloat* a [[buffer(0)]],- const device bfloat* b [[buffer(1)]],- device atomic_float* accum [[buffer(2)]],- constant uint& m [[buffer(3)]],- constant uint& n [[buffer(4)]],- constant uint& k [[buffer(5)]],- constant uint& lda [[buffer(6)]],- constant uint& ldb [[buffer(7)]],- constant uint& ldd [[buffer(8)]],- constant uint& k_start [[buffer(9)]],- constant uint& k_end [[buffer(10)]],- uint3 tgid [[threadgroup_position_in_grid]],- uint3 tid [[thread_position_in_threadgroup]]) {- splitk_partial_impl<bfloat, float>(- a, b, accum, m, n, k, lda, ldb, ldd, k_start, k_end, tgid, tid);-}+template <typename OutputType, typename AccumulatorType>+[[kernel]] void splitk_accumulate(+ const device AccumulatorType* partitioned_accumulator [[buffer(0)]],+ device OutputType* output [[buffer(1)]],+ constant int& partition_count [[buffer(2)]],+ constant int& output_elements_per_partition [[buffer(3)]],+ constant int& leading_dim_output [[buffer(4)]],+ uint2 thread_position [[thread_position_in_grid]]) {+ const size_t col = thread_position.x;+ const size_t row = thread_position.y;-[[kernel, max_total_threads_per_threadgroup(256)]] void splitk_convert_f16(- const device atomic_float* accum [[buffer(0)]],- device half* out [[buffer(1)]],- constant uint& m [[buffer(2)]],- constant uint& n [[buffer(3)]],- constant uint& ldd [[buffer(4)]],- uint3 tgid [[threadgroup_position_in_grid]],- uint3 tid [[thread_position_in_threadgroup]]) {- splitk_convert_impl<half>(accum, out, m, n, ldd, tgid, tid);-}+ output += col + row * size_t(leading_dim_output);+ partitioned_accumulator += col + row * size_t(leading_dim_output);-[[kernel, max_total_threads_per_threadgroup(256)]] void splitk_convert_bf16(- const device atomic_float* accum [[buffer(0)]],- device bfloat* out [[buffer(1)]],- constant uint& m [[buffer(2)]],- constant uint& n [[buffer(3)]],- constant uint& ldd [[buffer(4)]],- uint3 tgid [[threadgroup_position_in_grid]],- uint3 tid [[thread_position_in_threadgroup]]) {- splitk_convert_impl<bfloat>(accum, out, m, n, ldd, tgid, tid);+ AccumulatorType sum = AccumulatorType(0);+ size_t partition_offset = 0;++ for (int i = 0; i < partition_count; i++) {+ sum += partitioned_accumulator[partition_offset];+ partition_offset += output_elements_per_partition;+ }++ output[0] = OutputType(sum);}+///////////////////////////////////////////////////////////////////////////////+// Kernel Instantiation+///////////////////////////////////////////////////////////////////////////////++#define INSTANTIATE_SPLITK_PARTIAL( \+ transpose_name, transpose_a, transpose_b, \+ type_name, input_type, \+ tile_rows, tile_cols, tile_depth, warps_row, warps_col) \+ template [[host_name( \+ "splitk_partial_" #transpose_name "_" #type_name \+ "_tm" #tile_rows "_tn" #tile_cols "_tk" #tile_depth \+ "_wm" #warps_row "_wn" #warps_col \+ )]] [[kernel]] void \+ splitk_partial_gemm< \+ input_type, float, \+ tile_rows, tile_cols, tile_depth, warps_row, warps_col, \+ transpose_a, transpose_b, false, false>( \+ const device input_type* input_a [[buffer(0)]], \+ const device input_type* input_b [[buffer(1)]], \+ device float* accumulator [[buffer(2)]], \+ const constant SplitKGEMMParams* params [[buffer(3)]], \+ uint simd_lane_id [[thread_index_in_simdgroup]], \+ uint simd_group_id [[simdgroup_index_in_threadgroup]], \+ uint3 threadgroup_id [[threadgroup_position_in_grid]], \+ uint3 thread_id [[thread_position_in_threadgroup]]);++#define INSTANTIATE_SPLITK_TRANSPOSE_HELPER( \+ type_name, input_type, tile_rows, tile_cols, tile_depth, warps_row, warps_col) \+ INSTANTIATE_SPLITK_PARTIAL(nn, false, false, type_name, input_type, \+ tile_rows, tile_cols, tile_depth, warps_row, warps_col) \+ INSTANTIATE_SPLITK_PARTIAL(nt, false, true, type_name, input_type, \+ tile_rows, tile_cols, tile_depth, warps_row, warps_col) \+ INSTANTIATE_SPLITK_PARTIAL(tn, true, false, type_name, input_type, \+ tile_rows, tile_cols, tile_depth, warps_row, warps_col) \+ INSTANTIATE_SPLITK_PARTIAL(tt, true, true, type_name, input_type, \+ tile_rows, tile_cols, tile_depth, warps_row, warps_col)++#define INSTANTIATE_SPLITK_SHAPES_HELPER(type_name, input_type) \+ INSTANTIATE_SPLITK_TRANSPOSE_HELPER(type_name, input_type, 16, 16, 16, 2, 2) \+ INSTANTIATE_SPLITK_TRANSPOSE_HELPER(type_name, input_type, 16, 32, 16, 2, 2) \+ INSTANTIATE_SPLITK_TRANSPOSE_HELPER(type_name, input_type, 32, 16, 16, 2, 2) \+ INSTANTIATE_SPLITK_TRANSPOSE_HELPER(type_name, input_type, 32, 32, 16, 2, 2)++INSTANTIATE_SPLITK_SHAPES_HELPER(f16, half)+INSTANTIATE_SPLITK_SHAPES_HELPER(bf16, bfloat)+INSTANTIATE_SPLITK_SHAPES_HELPER(f32, float)++#define INSTANTIATE_SPLITK_ACCUM(type_name, output_type) \+ template [[host_name("splitk_accum_" #type_name)]] [[kernel]] void \+ splitk_accumulate<output_type, float>( \+ const device float* partitioned_accumulator [[buffer(0)]], \+ device output_type* output [[buffer(1)]], \+ constant int& partition_count [[buffer(2)]], \+ constant int& output_elements_per_partition [[buffer(3)]], \+ constant int& leading_dim_output [[buffer(4)]], \+ uint2 thread_position [[thread_position_in_grid]]);+INSTANTIATE_SPLITK_ACCUM(f16, half)+INSTANTIATE_SPLITK_ACCUM(bf16, bfloat)+INSTANTIATE_SPLITK_ACCUM(f32, float)diff --git a/crates/uzu/src/backends/metal/kernel/matmul/splitk.rs b/crates/uzu/src/backends/metal/kernel/matmul/splitk.rsindex 3601567b5..346d4a499 100644--- a/crates/uzu/src/backends/metal/kernel/matmul/splitk.rs+++ b/crates/uzu/src/backends/metal/kernel/matmul/splitk.rs@@ -11,65 +11,161 @@ use crate::{backends::metal::{MTLContext, MTLError},};+#[repr(C)]+#[derive(Debug, Default, Copy, Clone)]+struct SplitKGEMMParams {+ m: i32,+ n: i32,+ k: i32,+ leading_dim_a: i32,+ leading_dim_b: i32,+ leading_dim_accumulator: i32,+ tile_count_n: i32,+ tile_count_m: i32,+ partition_count: i32,+ output_elements_per_partition: i32,+ k_elements_per_partition: i32,+ gemm_k_iterations_aligned: i32,+}+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]-enum SplitKKernelKind {- Partial,- Convert,+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,}pub struct SplitKGemm {- dt: DataType,- pipelines: HashMap<SplitKKernelKind, MTLComputePipelineState>,+ data_type: DataType,+ transpose_a: bool,+ transpose_b: bool,+ partial_pipelines: HashMap<PartialKernelKey, MTLComputePipelineState>,+ accum_pipeline: Option<MTLComputePipelineState>,}impl SplitKGemm {- pub fn new(dt: DataType) -> Self {+ pub fn new(+ data_type: DataType,+ transpose_a: bool,+ transpose_b: bool,+ ) -> Self {Self {- dt,- pipelines: HashMap::new(),+ data_type,+ transpose_a,+ transpose_b,+ partial_pipelines: HashMap::new(),+ accum_pipeline: None,}}- fn kernel_name(- &self,- kind: SplitKKernelKind,- ) -> Result<&'static str, MTLError> {- match (self.dt, kind) {- (DataType::F16, SplitKKernelKind::Partial) => {- Ok("splitk_partial_f16")- },- (DataType::F16, SplitKKernelKind::Convert) => {- Ok("splitk_convert_f16")- },- (DataType::BF16, SplitKKernelKind::Partial) => {- Ok("splitk_partial_bf16")- },- (DataType::BF16, SplitKKernelKind::Convert) => {- Ok("splitk_convert_bf16")- },+ fn type_suffix(&self) -> Result<&'static str, MTLError> {+ match self.data_type {+ DataType::F16 => Ok("f16"),+ DataType::BF16 => Ok("bf16"),+ DataType::F32 => Ok("f32"),_ => Err(MTLError::Generic(format!("Unsupported dtype for Split-K: {:?}",- self.dt+ self.data_type))),}}- fn pipeline(+ fn transpose_suffix(&self) -> &'static str {+ match (self.transpose_a, self.transpose_b) {+ (false, false) => "nn",+ (false, true) => "nt",+ (true, false) => "tn",+ (true, true) => "tt",+ }+ }++ fn partial_kernel_name(+ &self,+ config: &TileConfig,+ ) -> Result<String, MTLError> {+ let type_suffix = self.type_suffix()?;+ let transpose_suffix = self.transpose_suffix();+ Ok(format!(+ "splitk_partial_{}_{}_tm{}_tn{}_tk{}_wm{}_wn{}",+ transpose_suffix,+ type_suffix,+ config.tile_rows,+ config.tile_cols,+ config.tile_depth,+ config.warps_per_row,+ config.warps_per_col+ ))+ }++ fn accum_kernel_name(&self) -> Result<String, MTLError> {+ let type_suffix = self.type_suffix()?;+ Ok(format!("splitk_accum_{}", type_suffix))+ }++ fn get_partial_pipeline(&mut self,mtl: &MTLContext,- kind: SplitKKernelKind,+ config: TileConfig,) -> Result<&MTLComputePipelineState, MTLError> {- if !self.pipelines.contains_key(&kind) {- let name = self.kernel_name(kind)?;- let ps = mtl.compute_pipeline_state(name, None)?;- self.pipelines.insert(kind, ps);+ let key = PartialKernelKey {+ tile_config: config,+ };+ if !self.partial_pipelines.contains_key(&key) {+ let name = self.partial_kernel_name(&config)?;+ 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,+ ) -> Result<&MTLComputePipelineState, MTLError> {+ if self.accum_pipeline.is_none() {+ let name = self.accum_kernel_name()?;+ let ps = mtl.compute_pipeline_state(&name, None)?;+ self.accum_pipeline = Some(ps);+ }+ Ok(self.accum_pipeline.as_ref().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}- Ok(self.pipelines.get(&kind).unwrap())}- /// Heuristic from plan: use Split-K when batch_size == 1, small M*N but large K.pub fn should_use_splitk(- &self,m: i32,n: i32,k: i32,@@ -81,10 +177,10 @@ impl SplitKGemm {if m <= 0 || n <= 0 || k <= 0 {return false;}- let tm = m / 16;- let tn = n / 16;- let tk = k / 16;- (tm * tn) <= 32 && tk >= 8+ let m_tiles = m / 16;+ let n_tiles = n / 16;+ let k_tiles = k / 16;+ (m_tiles * n_tiles) <= 32 && k_tiles >= 8}pub fn encode(@@ -93,94 +189,96 @@ impl SplitKGemm {enc: &ComputeCommandEncoderRef,args: MatmulArguments,) -> Result<(), MTLError> {- let m = args.batch as u32;- let n = args.output_dim as u32;- let k = args.input_dim as u32;-- // Choose split count (fixed 4-way)- let split_k = 4u32;- let chunk = (k + split_k - 1) / split_k;-- // Temporary accumulation buffer (float)- let output_len = (args.batch_count as u32) * m * (args.ldd as u32);- let accum_bytes = (output_len as usize) * std::mem::size_of::<f32>();- let accum_buf = mtl.device.new_buffer(- accum_bytes as u64,- metal::MTLResourceOptions::StorageModeShared,+ let m = args.batch;+ let n = args.output_dim;+ let k = args.input_dim;++ let tile_config = Self::select_tile_config(m, n);+ let partition_count = Self::compute_partition_count(k);++ let tile_count_m = (m + tile_config.tile_rows - 1) / tile_config.tile_rows;+ let tile_count_n = (n + 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 * n;++ let accumulator_element_count =+ partition_count * output_elements_per_partition * args.batch_count;+ let accumulator_bytes =+ (accumulator_element_count as usize) * std::mem::size_of::<f32>();+ let accumulator_buffer = mtl.device.new_buffer(+ accumulator_bytes as u64,+ metal::MTLResourceOptions::StorageModePrivate,);- unsafe {- // Zero initialize- std::ptr::write_bytes(- accum_buf.contents() as *mut u8,- 0,- accum_bytes,- );- }- let partial_ps = self.pipeline(mtl, SplitKKernelKind::Partial)?;-- let threads = MTLSize::new(8, 8, 1);- let tg_x = (n as u64 + 7) / 8;- let tg_y = (m as u64 + 7) / 8;- let tg_z = args.batch_count as u64;- let grid = MTLSize::new(tg_x, tg_y, tg_z);-- for split in 0..split_k {- let k_start = split * chunk;- let k_end = ((split + 1) * chunk).min(k);-- enc.set_compute_pipeline_state(partial_ps);- enc.set_buffer(0, Some(args.a), 0);- enc.set_buffer(1, Some(args.b), 0);- enc.set_buffer(2, Some(&accum_buf), 0);-- enc.set_bytes(3, 4, &m as *const u32 as *const std::ffi::c_void);- enc.set_bytes(4, 4, &n as *const u32 as *const std::ffi::c_void);- enc.set_bytes(5, 4, &k as *const u32 as *const std::ffi::c_void);- enc.set_bytes(- 6,- 4,- &(args.lda as u32) as *const u32 as *const std::ffi::c_void,- );- enc.set_bytes(- 7,- 4,- &(args.ldb as u32) as *const u32 as *const std::ffi::c_void,- );- enc.set_bytes(- 8,- 4,- &(args.ldd as u32) as *const u32 as *const std::ffi::c_void,- );- enc.set_bytes(- 9,- 4,- &k_start as *const u32 as *const std::ffi::c_void,- );- enc.set_bytes(- 10,- 4,- &k_end as *const u32 as *const std::ffi::c_void,- );-- enc.dispatch_thread_groups(grid, threads);- }+ let params = SplitKGEMMParams {+ m,+ n,+ k,+ leading_dim_a: args.lda,+ leading_dim_b: args.ldb,+ leading_dim_accumulator: n,+ tile_count_n,+ tile_count_m,+ partition_count,+ output_elements_per_partition,+ k_elements_per_partition,+ gemm_k_iterations_aligned: gemm_k_iterations,+ };- // Convert to target type- let convert_ps = self.pipeline(mtl, SplitKKernelKind::Convert)?;- enc.set_compute_pipeline_state(convert_ps);- enc.set_buffer(0, Some(&accum_buf), 0);- enc.set_buffer(1, Some(args.d), 0);+ let partial_ps = self.get_partial_pipeline(mtl, tile_config)?;- enc.set_bytes(2, 4, &m as *const u32 as *const std::ffi::c_void);- enc.set_bytes(3, 4, &n as *const u32 as *const std::ffi::c_void);+ enc.set_compute_pipeline_state(partial_ps);+ enc.set_buffer(0, Some(args.a), 0);+ enc.set_buffer(1, Some(args.b), 0);+ enc.set_buffer(2, Some(&accumulator_buffer), 0);+ enc.set_bytes(+ 3,+ std::mem::size_of::<SplitKGEMMParams>() as u64,+ ¶ms as *const SplitKGEMMParams 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)?;+ enc.set_compute_pipeline_state(accum_ps);+ enc.set_buffer(0, Some(&accumulator_buffer), 0);+ enc.set_buffer(1, Some(args.d), 0);+ enc.set_bytes(+ 2,+ 4,+ &partition_count as *const i32 as *const std::ffi::c_void,+ );+ enc.set_bytes(+ 3,+ 4,+ &output_elements_per_partition as *const i32 as *const std::ffi::c_void,+ );enc.set_bytes(4,4,- &(args.ldd as u32) as *const u32 as *const std::ffi::c_void,+ &(args.ldd) as *const i32 as *const std::ffi::c_void,+ );++ let accum_total_threads = MTLSize::new(n as u64, m as u64, 1);+ let accum_threads_per_threadgroup = MTLSize::new(+ 16.min(n as u64),+ 16.min(m as u64),+ 1,);+ enc.dispatch_threads(accum_total_threads, accum_threads_per_threadgroup);- enc.dispatch_thread_groups(grid, threads);Ok(())}}