Skip to content

armgit / uzu

Public Imported from GitHub
0

A high-performance inference engine for AI models

more heuristics and tiling decisions

Eugene Bokhan4b402645b321
diff --git a/crates/uzu/src/backends/metal/encodable_block/embedding/full_precision_readout.rs b/crates/uzu/src/backends/metal/encodable_block/embedding/full_precision_readout.rs
index c0e3eb5a2..0b0ce7f34 100644
--- a/crates/uzu/src/backends/metal/encodable_block/embedding/full_precision_readout.rs
+++ b/crates/uzu/src/backends/metal/encodable_block/embedding/full_precision_readout.rs
@@ -121,6 +121,7 @@ impl EncodableBlock for FullPrecisionEmbeddingReadout {
let args = MatmulArguments {
a: input_buffer,
b: &self.weights_buffer,
+ c: None,
d: output_buffer,
batch: batch_size as i32,
input_dim: self.model_dim as i32,
@@ -129,6 +130,8 @@ impl EncodableBlock for FullPrecisionEmbeddingReadout {
ldb: self.model_dim as i32,
ldd: self.vocab_size as i32,
batch_count: 1,
+ alpha: 1.0,
+ beta: 0.0,
};
self.kernel
diff --git a/crates/uzu/src/backends/metal/encodable_block/linear/full_precision.rs b/crates/uzu/src/backends/metal/encodable_block/linear/full_precision.rs
index 03ce41159..a39340dd7 100644
--- a/crates/uzu/src/backends/metal/encodable_block/linear/full_precision.rs
+++ b/crates/uzu/src/backends/metal/encodable_block/linear/full_precision.rs
@@ -8,9 +8,7 @@ use crate::{
MTLContext, MTLError,
encodable_block::{EncodableBlock, EncodingParameters},
forward_pass::{ArrayId, ForwardPassState},
- kernel::{
- matmul::{MatmulArguments, MatmulKernel},
- },
+ kernel::matmul::{MatmulArguments, MatmulKernel},
},
device::array::Array,
parameters::ParameterTree,
@@ -125,6 +123,7 @@ impl EncodableBlock for FullPrecisionLinear {
let args = MatmulArguments {
a: input_buffer,
b: &self.weights_buffer,
+ c: None,
d: output_buffer,
batch: batch_size as i32,
input_dim: self.input_dim as i32,
@@ -133,6 +132,8 @@ impl EncodableBlock for FullPrecisionLinear {
ldb: self.input_dim as i32,
ldd: self.output_dim as i32,
batch_count: 1,
+ alpha: 1.0,
+ beta: 0.0,
};
let mut kernel = self.kernel.borrow_mut();
@@ -176,6 +177,7 @@ impl EncodableBlock for FullPrecisionLinear {
let args = MatmulArguments {
a: input_buffer,
b: &self.weights_buffer,
+ c: None,
d: output_buffer,
batch: batch_size as i32,
input_dim: self.input_dim as i32,
@@ -184,6 +186,8 @@ impl EncodableBlock for FullPrecisionLinear {
ldb: self.input_dim as i32,
ldd: self.output_dim as i32,
batch_count: 1,
+ alpha: 1.0,
+ beta: 0.0,
};
let mut kernel = self.kernel.borrow_mut();
diff --git a/crates/uzu/src/backends/metal/encodable_block/normalization/mod.rs b/crates/uzu/src/backends/metal/encodable_block/normalization/mod.rs
index 1e2806e44..bd7444b3f 100644
--- a/crates/uzu/src/backends/metal/encodable_block/normalization/mod.rs
+++ b/crates/uzu/src/backends/metal/encodable_block/normalization/mod.rs
@@ -7,8 +7,7 @@ mod rms_norm;
use std::rc::Rc;
pub use layer_norm::LayerNorm;
-use metal::CommandBufferRef;
-use metal::ComputeCommandEncoderRef;
+use metal::{CommandBufferRef, ComputeCommandEncoderRef};
pub use qk_norm::QKNorm;
pub use rms_norm::RMSNorm;
diff --git a/crates/uzu/src/backends/metal/kernel/matmul/arguments.rs b/crates/uzu/src/backends/metal/kernel/matmul/arguments.rs
index 65b8ba5e3..72fbea9ef 100644
--- a/crates/uzu/src/backends/metal/kernel/matmul/arguments.rs
+++ b/crates/uzu/src/backends/metal/kernel/matmul/arguments.rs
@@ -1,9 +1,10 @@
use metal::Buffer as MTLBuffer;
-#[derive(Debug, Clone, Copy)]
+#[derive(Debug, Clone)]
pub struct MatmulArguments<'a> {
pub a: &'a MTLBuffer,
pub b: &'a MTLBuffer,
+ pub c: Option<&'a MTLBuffer>,
pub d: &'a MTLBuffer,
/// M dimension - batch/number of tokens (rows of A, rows of D)
pub batch: i32,
@@ -16,4 +17,7 @@ pub struct MatmulArguments<'a> {
pub ldd: i32,
/// Number of batched matrix multiplications (z-dimension)
pub batch_count: i32,
+ /// Scaling factors for fused addmm (alpha * A @ B + beta * C)
+ pub alpha: f32,
+ pub beta: f32,
}
diff --git a/crates/uzu/src/backends/metal/kernel/matmul/gemv.metal b/crates/uzu/src/backends/metal/kernel/matmul/gemv.metal
index 032c8f1bd..41c829f50 100644
--- a/crates/uzu/src/backends/metal/kernel/matmul/gemv.metal
+++ b/crates/uzu/src/backends/metal/kernel/matmul/gemv.metal
@@ -2,341 +2,700 @@
#include <metal_simdgroup>
#include <metal_stdlib>
+
using namespace metal;
-template <typename DataType>
-struct VectorType4 {};
+#define UZU_MTL_CONST static constant constexpr const
-template <>
-struct VectorType4<half> {
- using type = half4;
+template <typename T>
+struct DefaultAccumulator {
+ using type = float;
};
-template <>
-struct VectorType4<bfloat> {
- using type = vec<bfloat, 4>;
-};
+template <typename T>
+using AccumulatorType = typename DefaultAccumulator<T>::type;
+
+static METAL_FUNC int64_t linear_offset_for_batch(
+ uint batch_index,
+ const constant int* batch_shape,
+ const constant int64_t* batch_strides,
+ int batch_ndim
+) {
+ if (batch_ndim <= 1) {
+ return static_cast<int64_t>(batch_index) * batch_strides[0];
+ }
-template <>
-struct VectorType4<float> {
- using type = float4;
-};
+ int64_t offset = 0;
+ uint remaining = batch_index;
+ for (int dim = batch_ndim - 1; dim >= 0; --dim) {
+ int dim_size = batch_shape[dim];
+ if (dim_size <= 0) {
+ continue;
+ }
+ uint coord = remaining % static_cast<uint>(dim_size);
+ remaining /= static_cast<uint>(dim_size);
+ offset += coord * batch_strides[dim];
+ }
+ return offset;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+/// Matrix vector multiplication
+///////////////////////////////////////////////////////////////////////////////
template <
- typename DataType,
- typename AccumulatorType,
- ushort SIMDGROUPS_PER_ROW,
- ushort SIMDGROUPS_PER_REDUCTION,
- ushort THREADS_PER_SIMDGROUP_ROW,
- ushort THREADS_PER_SIMDGROUP_COL,
- ushort ELEMENTS_PER_THREAD_ROW,
- ushort ELEMENTS_PER_THREAD_COL,
- bool HAS_BIAS>
-struct GemvKernel {
-
- using Vector4 = typename VectorType4<DataType>::type;
-
- static constant constexpr ushort TOTAL_THREADS_ROW = SIMDGROUPS_PER_ROW * THREADS_PER_SIMDGROUP_ROW;
- static constant constexpr ushort TOTAL_THREADS_COL = SIMDGROUPS_PER_REDUCTION * THREADS_PER_SIMDGROUP_COL;
- static constant constexpr ushort OUTPUT_ELEMENTS_PER_THREADGROUP = TOTAL_THREADS_ROW * ELEMENTS_PER_THREAD_ROW;
- static constant constexpr ushort INPUT_ELEMENTS_PER_ITERATION = TOTAL_THREADS_COL * ELEMENTS_PER_THREAD_COL;
- static constant constexpr bool NEEDS_THREADGROUP_REDUCTION = SIMDGROUPS_PER_REDUCTION > 1;
- static constant constexpr ushort THREADGROUP_MEMORY_SIZE = NEEDS_THREADGROUP_REDUCTION
- ? SIMDGROUPS_PER_REDUCTION * (OUTPUT_ELEMENTS_PER_THREADGROUP + ELEMENTS_PER_THREAD_ROW)
- : 0;
- static constant constexpr bool CAN_USE_VECTOR_LOADS = (ELEMENTS_PER_THREAD_COL == 4);
-
- static_assert(THREADS_PER_SIMDGROUP_ROW * THREADS_PER_SIMDGROUP_COL == 32,
- "simdgroup must have exactly 32 threads");
-
- static METAL_FUNC float4 load_as_float4(const device DataType* source, int offset) {
- const device Vector4* vector_ptr = reinterpret_cast<const device Vector4*>(source + offset);
- return float4(*vector_ptr);
+ typename T,
+ const int BM, /* Threadgroup rows (in simdgroups) */
+ const int BN, /* Threadgroup cols (in simdgroups) */
+ const int SM, /* Simdgroup rows (in threads) */
+ const int SN, /* Simdgroup cols (in threads) */
+ const int TM, /* Thread rows (in elements) */
+ const int TN, /* Thread cols (in elements) */
+ const bool kDoAxpby, /* Do out = alpha * out + beta * bias */
+ typename AccT = AccumulatorType<T>>
+struct GEMVKernel {
+ using acc_type = AccT;
+
+ UZU_MTL_CONST int threadsM = BM * SM;
+ UZU_MTL_CONST int threadsN = BN * SN;
+
+ UZU_MTL_CONST int blockM = threadsM * TM;
+ UZU_MTL_CONST int blockN = threadsN * TN;
+
+ static_assert(SM * SN == 32, "simdgroup can only have 32 threads");
+ static_assert(
+ SN == 4 || SN == 8 || SN == 16 || SN == 32,
+ "gemv block must have a width of 4, 8, 16, or 32"
+ );
+
+ UZU_MTL_CONST short tgp_mem_size = BN > 1 ? BN * (blockM + TM) : 0;
+ UZU_MTL_CONST bool needs_tgp_reduction = BN > 1;
+
+ template <typename U = T>
+ static METAL_FUNC void load_unsafe(
+ const device T* src,
+ thread U dst[TN],
+ const int src_offset = 0
+ ) {
+ #pragma unroll
+ for (int tn = 0; tn < TN; tn++) {
+ dst[tn] = static_cast<U>(src[src_offset + tn]);
+ }
}
- static METAL_FUNC float4 load_as_float4_checked(const device DataType* source, int offset, int source_size) {
- float4 result = float4(0.0f);
- if (offset + 4 <= source_size) {
- const device Vector4* vector_ptr = reinterpret_cast<const device Vector4*>(source + offset);
- result = float4(*vector_ptr);
+ template <typename U = T>
+ static METAL_FUNC void load_safe(
+ const device T* src,
+ thread U dst[TN],
+ const int src_offset = 0,
+ const int src_size = TN
+ ) {
+ if (src_offset + TN <= src_size) {
+ #pragma unroll
+ for (int tn = 0; tn < TN; tn++) {
+ dst[tn] = static_cast<U>(src[src_offset + tn]);
+ }
} else {
- if (offset + 0 < source_size) result.x = static_cast<float>(source[offset + 0]);
- if (offset + 1 < source_size) result.y = static_cast<float>(source[offset + 1]);
- if (offset + 2 < source_size) result.z = static_cast<float>(source[offset + 2]);
- if (offset + 3 < source_size) result.w = static_cast<float>(source[offset + 3]);
+ #pragma unroll
+ for (int tn = 0; tn < TN; tn++) {
+ dst[tn] = (src_offset + tn) < src_size
+ ? static_cast<U>(src[src_offset + tn])
+ : U(0);
+ }
}
- return result;
- }
-
- static METAL_FUNC AccumulatorType dot_product(float4 a, float4 b) {
- return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w;
}
- static METAL_FUNC void execute(
- const device DataType* weight_matrix,
- const device DataType* input_vector,
- const device DataType* bias_vector,
- device DataType* output_vector,
- constant int& input_dimension,
- constant int& output_dimension,
- constant int& weight_row_stride,
- constant int& input_batch_stride,
- constant int& output_batch_stride,
- threadgroup AccumulatorType* shared_memory,
- uint3 threadgroup_position,
- uint simdgroup_index,
- uint thread_index_in_simdgroup
+ static METAL_FUNC void run(
+ const device T* mat [[buffer(0)]],
+ const device T* in_vec [[buffer(1)]],
+ const device T* bias [[buffer(2)]],
+ device T* out_vec [[buffer(3)]],
+ const constant int& in_vec_size [[buffer(4)]],
+ const constant int& out_vec_size [[buffer(5)]],
+ const constant int& matrix_ld [[buffer(6)]],
+ const constant float& alpha [[buffer(7)]],
+ const constant float& beta [[buffer(8)]],
+ const constant int& bias_stride [[buffer(14)]],
+ threadgroup AccT* tgp_memory [[threadgroup(0)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint3 lid [[thread_position_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]
) {
- thread AccumulatorType accumulated_results[ELEMENTS_PER_THREAD_ROW] = {0};
+ (void)lid;
- int thread_row_in_simdgroup = (THREADS_PER_SIMDGROUP_COL != 32)
- ? (thread_index_in_simdgroup / THREADS_PER_SIMDGROUP_COL)
- : 0;
- int thread_col_in_simdgroup = (THREADS_PER_SIMDGROUP_COL != 32)
- ? (thread_index_in_simdgroup % THREADS_PER_SIMDGROUP_COL)
- : int(thread_index_in_simdgroup);
+ thread AccT result[TM] = {0};
+ thread T inter[TN];
+ thread AccT v_coeff[TN];
- int simdgroup_reduction_index = NEEDS_THREADGROUP_REDUCTION
- ? (simdgroup_index % SIMDGROUPS_PER_REDUCTION)
- : 0;
+ const int thrM = SN != 32 ? simd_lid / SN : 0;
+ const int thrN = SN != 32 ? simd_lid % SN : int(simd_lid);
- int simdgroup_row_offset = NEEDS_THREADGROUP_REDUCTION
- ? THREADS_PER_SIMDGROUP_ROW * (simdgroup_index / SIMDGROUPS_PER_REDUCTION)
- : int(THREADS_PER_SIMDGROUP_ROW * simdgroup_index);
+ const int sgN = BN != 1 ? (simd_gid % BN) : 0;
- int simdgroup_col_offset = NEEDS_THREADGROUP_REDUCTION
- ? THREADS_PER_SIMDGROUP_COL * simdgroup_reduction_index
- : 0;
+ const int simdM = BN != 1 ? SM * (simd_gid / BN) : int(SM * simd_gid);
+ const int simdN = BN != 1 ? SN * (simd_gid % BN) : 0;
- int thread_output_offset = (simdgroup_row_offset + thread_row_in_simdgroup) * ELEMENTS_PER_THREAD_ROW;
- int thread_input_offset = (simdgroup_col_offset + thread_col_in_simdgroup) * ELEMENTS_PER_THREAD_COL;
+ int bm = (simdM + thrM) * TM;
+ int bn = (simdN + thrN) * TN;
- int batch_index = threadgroup_position.z;
- int output_row_start = threadgroup_position.x * OUTPUT_ELEMENTS_PER_THREADGROUP + thread_output_offset;
+ int out_row = tid.x * blockM + bm;
- if (output_row_start >= output_dimension) {
- return;
- }
+ if (out_row >= out_vec_size) {
+ return;
+ }
- output_row_start = (output_row_start + ELEMENTS_PER_THREAD_ROW <= output_dimension)
- ? output_row_start
- : (output_dimension - ELEMENTS_PER_THREAD_ROW);
+ out_row = (out_row + TM <= out_vec_size)
+ ? out_row
+ : (out_vec_size - TM);
- const device DataType* batch_input = input_vector + batch_index * input_batch_stride;
- device DataType* batch_output = output_vector + batch_index * output_batch_stride;
+ mat += out_row * matrix_ld;
- int full_iterations = input_dimension / INPUT_ELEMENTS_PER_ITERATION;
- int remaining_elements = input_dimension - (full_iterations * INPUT_ELEMENTS_PER_ITERATION);
+ constexpr const uniform<int> loop_stride = make_uniform(blockN);
+ const uniform<int> in_size = make_uniform(in_vec_size);
+ const uniform<int> n_iter = in_size / loop_stride;
+ const uniform<int> last_iter = loop_stride * n_iter;
+ const uniform<int> leftover = in_size - last_iter;
- int current_input_offset = thread_input_offset;
+ for (int i = 0; i < n_iter; ++i) {
+ load_unsafe<AccT>(in_vec, v_coeff, bn);
- if (CAN_USE_VECTOR_LOADS) {
- const device Vector4* input_vectors = reinterpret_cast<const device Vector4*>(batch_input);
- const device Vector4* weight_row_vectors[ELEMENTS_PER_THREAD_ROW];
+ int mat_offset = 0;
+ #pragma unroll
+ for (int tm = 0; tm < TM; tm++) {
+ load_unsafe(mat, inter, mat_offset + bn);
+
+ #pragma unroll
+ for (int tn = 0; tn < TN; tn++) {
+ result[tm] += inter[tn] * v_coeff[tn];
+ }
- #pragma unroll(ELEMENTS_PER_THREAD_ROW)
- for (ushort row = 0; row < ELEMENTS_PER_THREAD_ROW; ++row) {
- weight_row_vectors[row] = reinterpret_cast<const device Vector4*>(
- weight_matrix + (output_row_start + row) * weight_row_stride
- );
+ mat_offset += matrix_ld;
}
- for (int iteration = 0; iteration < full_iterations; ++iteration) {
- int vector_index = current_input_offset / ELEMENTS_PER_THREAD_COL;
- float4 input_float4 = float4(input_vectors[vector_index]);
+ bn += blockN;
+ }
+
+ if (leftover > 0) {
+ load_safe<AccT>(in_vec, v_coeff, bn, in_size);
+
+ #pragma unroll
+ for (int tm = 0; tm < TM; tm++) {
+ load_safe(&mat[tm * matrix_ld], inter, bn, in_size);
- #pragma unroll(ELEMENTS_PER_THREAD_ROW)
- for (ushort row = 0; row < ELEMENTS_PER_THREAD_ROW; ++row) {
- float4 weight_float4 = float4(weight_row_vectors[row][vector_index]);
- accumulated_results[row] += dot_product(input_float4, weight_float4);
+ #pragma unroll
+ for (int tn = 0; tn < TN; tn++) {
+ result[tm] += inter[tn] * v_coeff[tn];
}
+ }
+ }
- current_input_offset += INPUT_ELEMENTS_PER_ITERATION;
+ #pragma unroll
+ for (int tm = 0; tm < TM; tm++) {
+ #pragma unroll
+ for (ushort sn = (SN / 2); sn >= 1; sn >>= 1) {
+ result[tm] += simd_shuffle_down(result[tm], sn);
}
+ }
- if (remaining_elements > 0) {
- float4 input_float4 = load_as_float4_checked(batch_input, current_input_offset, input_dimension);
+ if (needs_tgp_reduction) {
+ threadgroup AccT* tgp_results =
+ tgp_memory + sgN * (blockM + TM) + bm;
+ if (thrN == 0) {
+ #pragma unroll
+ for (int tm = 0; tm < TM; tm++) {
+ tgp_results[tm] = result[tm];
+ }
+
+ threadgroup_barrier(mem_flags::mem_none);
- #pragma unroll(ELEMENTS_PER_THREAD_ROW)
- for (ushort row = 0; row < ELEMENTS_PER_THREAD_ROW; ++row) {
- const device DataType* weight_row = weight_matrix + (output_row_start + row) * weight_row_stride;
- float4 weight_float4 = load_as_float4_checked(weight_row, current_input_offset, input_dimension);
- accumulated_results[row] += dot_product(input_float4, weight_float4);
+ if (sgN == 0) {
+ #pragma unroll
+ for (int sgn = 1; sgn < BN; sgn++) {
+ #pragma unroll
+ for (int tm = 0; tm < TM; tm++) {
+ result[tm] +=
+ tgp_results[sgn * (blockM + TM) + tm];
+ }
+ }
}
}
- } else {
- thread DataType weight_elements[ELEMENTS_PER_THREAD_COL];
- thread AccumulatorType input_elements[ELEMENTS_PER_THREAD_COL];
- const device DataType* weight_rows = weight_matrix + output_row_start * weight_row_stride;
-
- for (int iteration = 0; iteration < full_iterations; ++iteration) {
- #pragma unroll(ELEMENTS_PER_THREAD_COL)
- for (ushort col = 0; col < ELEMENTS_PER_THREAD_COL; ++col) {
- input_elements[col] = static_cast<AccumulatorType>(batch_input[current_input_offset + col]);
+ }
+
+ if (simdN == 0 && thrN == 0) {
+ #pragma unroll
+ for (int tm = 0; tm < TM; tm++) {
+ if (kDoAxpby) {
+ out_vec[out_row + tm] =
+ static_cast<T>(alpha) * static_cast<T>(result[tm]) +
+ static_cast<T>(beta)
+ * bias[(out_row + tm) * bias_stride];
+ } else {
+ out_vec[out_row + tm] = static_cast<T>(result[tm]);
}
+ }
+ }
+ }
+};
- int weight_offset = 0;
- #pragma unroll(ELEMENTS_PER_THREAD_ROW)
- for (ushort row = 0; row < ELEMENTS_PER_THREAD_ROW; ++row) {
- #pragma unroll(ELEMENTS_PER_THREAD_COL)
- for (ushort col = 0; col < ELEMENTS_PER_THREAD_COL; ++col) {
- weight_elements[col] = weight_rows[weight_offset + current_input_offset + col];
- }
+///////////////////////////////////////////////////////////////////////////////
+/// Vector matrix multiplication (transposed GEMV)
+///////////////////////////////////////////////////////////////////////////////
- #pragma unroll(ELEMENTS_PER_THREAD_COL)
- for (ushort col = 0; col < ELEMENTS_PER_THREAD_COL; ++col) {
- accumulated_results[row] += static_cast<AccumulatorType>(weight_elements[col]) * input_elements[col];
- }
+template <
+ typename T,
+ const int BM, /* Threadgroup rows (in simdgroups) */
+ const int BN, /* Threadgroup cols (in simdgroups) */
+ const int SM, /* Simdgroup rows (in threads) */
+ const int SN, /* Simdgroup cols (in threads) */
+ const int TM, /* Thread rows (in elements) */
+ const int TN, /* Thread cols (in elements) */
+ const bool kDoAxpby, /* Do out = alpha * out + beta * bias */
+ typename AccT = AccumulatorType<T>>
+struct GEMVTKernel {
+ using acc_type = AccT;
+
+ UZU_MTL_CONST int threadsM = BM * SM;
+ UZU_MTL_CONST int threadsN = BN * SN;
+
+ UZU_MTL_CONST int blockM = threadsM * TM;
+ UZU_MTL_CONST int blockN = threadsN * TN;
+
+ static_assert(SM * SN == 32, "simdgroup can only have 32 threads");
+
+ UZU_MTL_CONST short tgp_mem_size = BM > 1 ? BM * (blockN + TN) : 0;
+ UZU_MTL_CONST bool needs_tgp_reduction = BM > 1;
+
+ static METAL_FUNC void run(
+ const device T* mat [[buffer(0)]],
+ const device T* in_vec [[buffer(1)]],
+ const device T* bias [[buffer(2)]],
+ device T* out_vec [[buffer(3)]],
+ const constant int& in_vec_size [[buffer(4)]],
+ const constant int& out_vec_size [[buffer(5)]],
+ const constant int& matrix_ld [[buffer(6)]],
+ const constant float& alpha [[buffer(7)]],
+ const constant float& beta [[buffer(8)]],
+ const constant int& bias_stride [[buffer(14)]],
+ threadgroup AccT* tgp_memory [[threadgroup(0)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint3 lid [[thread_position_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]
+ ) {
+ (void)lid;
- weight_offset += weight_row_stride;
- }
+ AccT result[TN] = {0};
+ T inter[TN];
+ AccT v_coeff[TM];
+ const int thrM = SN != 32 ? simd_lid / SN : 0;
+ const int thrN = SN != 32 ? simd_lid % SN : int(simd_lid);
- current_input_offset += INPUT_ELEMENTS_PER_ITERATION;
- }
+ const int sgM = BN != 1 ? (simd_gid / BN) : int(simd_gid);
+ const int sgN = BN != 1 ? (simd_gid % BN) : 0;
+
+ const int simdM = SM * sgM;
+ const int simdN = SN * sgN;
+
+ int cm = (simdM + thrM);
+ int cn = (simdN + thrN);
+
+ int bm = cm * TM;
+ int bn = cn * TN;
- if (remaining_elements > 0) {
- #pragma unroll(ELEMENTS_PER_THREAD_COL)
- for (ushort col = 0; col < ELEMENTS_PER_THREAD_COL; ++col) {
- int idx = current_input_offset + col;
- input_elements[col] = (idx < input_dimension)
- ? static_cast<AccumulatorType>(batch_input[idx])
- : AccumulatorType(0);
+ int out_col = tid.x * blockN + bn;
+
+ constexpr const uniform<int> loop_stride = make_uniform(blockM);
+ const uniform<int> in_size = make_uniform(in_vec_size);
+ const uniform<int> n_iter = in_size / loop_stride;
+ const uniform<int> last_iter = loop_stride * n_iter;
+ const uniform<int> leftover = in_size - last_iter;
+
+ if (out_col < out_vec_size) {
+ out_col = (out_col + TN < out_vec_size)
+ ? out_col
+ : (out_vec_size - TN);
+
+ for (int i = 0; i < n_iter; ++i) {
+ threadgroup_barrier(mem_flags::mem_none);
+
+ #pragma unroll
+ for (int tm = 0; tm < TM; tm++) {
+ v_coeff[tm] = static_cast<AccT>(in_vec[bm + tm]);
}
- #pragma unroll(ELEMENTS_PER_THREAD_ROW)
- for (ushort row = 0; row < ELEMENTS_PER_THREAD_ROW; ++row) {
- const device DataType* weight_row = weight_rows + row * weight_row_stride;
+ #pragma unroll
+ for (int tm = 0; tm < TM; tm++) {
+ auto vc = static_cast<AccT>(v_coeff[tm]);
+ for (int tn = 0; tn < TN; tn++) {
+ inter[tn] = mat[(bm + tm) * matrix_ld + out_col + tn];
+ }
+ for (int tn = 0; tn < TN; tn++) {
+ result[tn] += vc * inter[tn];
+ }
+ }
+
+ bm += blockM;
+ }
+
+ if (leftover > 0) {
+ for (int tm = 0; tm < TM && bm + tm < in_vec_size; tm++) {
+ v_coeff[tm] = static_cast<AccT>(in_vec[bm + tm]);
- #pragma unroll(ELEMENTS_PER_THREAD_COL)
- for (ushort col = 0; col < ELEMENTS_PER_THREAD_COL; ++col) {
- int idx = current_input_offset + col;
- weight_elements[col] = (idx < input_dimension) ? weight_row[idx] : DataType(0);
+ #pragma unroll
+ for (int tn = 0; tn < TN; tn++) {
+ inter[tn] =
+ mat[(bm + tm) * matrix_ld + out_col + tn];
}
- #pragma unroll(ELEMENTS_PER_THREAD_COL)
- for (ushort col = 0; col < ELEMENTS_PER_THREAD_COL; ++col) {
- accumulated_results[row] += static_cast<AccumulatorType>(weight_elements[col]) * input_elements[col];
+ #pragma unroll
+ for (int tn = 0; tn < TN; tn++) {
+ result[tn] += v_coeff[tm] * inter[tn];
}
}
}
}
- #pragma unroll(ELEMENTS_PER_THREAD_ROW)
- for (ushort row = 0; row < ELEMENTS_PER_THREAD_ROW; ++row) {
+ #pragma unroll
+ for (int tn = 0; tn < TN; tn++) {
#pragma unroll
- for (ushort shuffle_offset = (THREADS_PER_SIMDGROUP_COL / 2); shuffle_offset >= 1; shuffle_offset >>= 1) {
- accumulated_results[row] += simd_shuffle_down(accumulated_results[row], shuffle_offset);
+ for (ushort sm = (SM / 2); sm >= 1; sm >>= 1) {
+ result[tn] += simd_shuffle_down(result[tn], SN * sm);
}
}
- if (NEEDS_THREADGROUP_REDUCTION) {
- threadgroup AccumulatorType* reduction_memory =
- shared_memory + simdgroup_reduction_index * (OUTPUT_ELEMENTS_PER_THREADGROUP + ELEMENTS_PER_THREAD_ROW)
- + thread_output_offset;
-
- if (thread_col_in_simdgroup == 0) {
- #pragma unroll(ELEMENTS_PER_THREAD_ROW)
- for (ushort row = 0; row < ELEMENTS_PER_THREAD_ROW; ++row) {
- reduction_memory[row] = accumulated_results[row];
+ if (needs_tgp_reduction) {
+ threadgroup AccT* tgp_results =
+ tgp_memory + sgM * (blockN + TN) + bn;
+ if (thrM == 0) {
+ #pragma unroll
+ for (int tn = 0; tn < TN; tn++) {
+ tgp_results[tn] = result[tn];
}
threadgroup_barrier(mem_flags::mem_none);
- if (simdgroup_reduction_index == 0) {
+ if (sgM == 0) {
#pragma unroll
- for (ushort other_simdgroup = 1; other_simdgroup < SIMDGROUPS_PER_REDUCTION; ++other_simdgroup) {
- #pragma unroll(ELEMENTS_PER_THREAD_ROW)
- for (ushort row = 0; row < ELEMENTS_PER_THREAD_ROW; ++row) {
- accumulated_results[row] +=
- reduction_memory[other_simdgroup * (OUTPUT_ELEMENTS_PER_THREADGROUP + ELEMENTS_PER_THREAD_ROW) + row];
+ for (int sgm = 1; sgm < BM; sgm++) {
+ #pragma unroll
+ for (int tn = 0; tn < TN; tn++) {
+ result[tn] +=
+ tgp_results[sgm * (blockN + TN) + tn];
}
}
}
}
}
- bool is_first_thread_in_reduction = (simdgroup_col_offset == 0) && (thread_col_in_simdgroup == 0);
-
- if (is_first_thread_in_reduction) {
- #pragma unroll(ELEMENTS_PER_THREAD_ROW)
- for (ushort row = 0; row < ELEMENTS_PER_THREAD_ROW; ++row) {
- int output_index = output_row_start + row;
- if (HAS_BIAS) {
- batch_output[output_index] =
- static_cast<DataType>(accumulated_results[row]) + bias_vector[output_index];
+ if (cm == 0 && out_col < out_vec_size) {
+ #pragma unroll
+ for (int j = 0; j < TN; j++) {
+ if (kDoAxpby) {
+ out_vec[out_col + j] =
+ static_cast<T>(alpha) * static_cast<T>(result[j]) +
+ static_cast<T>(beta)
+ * bias[(out_col + j) * bias_stride];
} else {
- batch_output[output_index] = static_cast<DataType>(accumulated_results[row]);
+ out_vec[out_col + j] = static_cast<T>(result[j]);
}
}
}
}
};
-#define INSTANTIATE_GEMV_KERNEL( \
- kernel_name, data_type, accumulator_type, \
- simdgroups_per_row, simdgroups_per_reduction, \
- threads_per_simdgroup_row, threads_per_simdgroup_col, \
- elements_per_thread_row, elements_per_thread_col, has_bias) \
- \
-[[kernel, max_total_threads_per_threadgroup( \
- simdgroups_per_row * simdgroups_per_reduction * 32)]] \
-void kernel_name( \
- const device data_type* weight_matrix [[buffer(0)]], \
- const device data_type* input_vector [[buffer(1)]], \
- const device data_type* bias_vector [[buffer(2)]], \
- device data_type* output_vector [[buffer(3)]], \
- constant int& input_dimension [[buffer(4)]], \
- constant int& output_dimension [[buffer(5)]], \
- constant int& weight_row_stride [[buffer(6)]], \
- constant int& input_batch_stride [[buffer(7)]], \
- constant int& output_batch_stride [[buffer(8)]], \
- uint3 threadgroup_position [[threadgroup_position_in_grid]], \
- uint simdgroup_index [[simdgroup_index_in_threadgroup]], \
- uint thread_index_in_simdgroup [[thread_index_in_simdgroup]] \
-) { \
- using Kernel = GemvKernel< \
- data_type, accumulator_type, \
- simdgroups_per_row, simdgroups_per_reduction, \
- threads_per_simdgroup_row, threads_per_simdgroup_col, \
- elements_per_thread_row, elements_per_thread_col, has_bias>; \
- \
- threadgroup accumulator_type shared_memory[ \
- Kernel::THREADGROUP_MEMORY_SIZE == 0 ? 1 : Kernel::THREADGROUP_MEMORY_SIZE]; \
- \
- Kernel::execute( \
- weight_matrix, \
- input_vector, \
- bias_vector, \
- output_vector, \
- input_dimension, \
- output_dimension, \
- weight_row_stride, \
- input_batch_stride, \
- output_batch_stride, \
- shared_memory, \
- threadgroup_position, \
- simdgroup_index, \
- thread_index_in_simdgroup \
- ); \
+///////////////////////////////////////////////////////////////////////////////
+/// Kernel entry points
+///////////////////////////////////////////////////////////////////////////////
+
+template <
+ typename T,
+ const int BM, /* Threadgroup rows (in simdgroups) */
+ const int BN, /* Threadgroup cols (in simdgroups) */
+ const int SM, /* Simdgroup rows (in threads) */
+ const int SN, /* Simdgroup cols (in threads) */
+ const int TM, /* Thread rows (in elements) */
+ const int TN, /* Thread cols (in elements) */
+ const bool kDoNCBatch, /* Batch ndim > 1 */
+ const bool kDoAxpby> /* Do out = alpha * out + beta * bias */
+METAL_FUNC void gemv_entry(
+ const device T* mat [[buffer(0)]],
+ const device T* in_vec [[buffer(1)]],
+ const device T* bias [[buffer(2)]],
+ device T* out_vec [[buffer(3)]],
+ const constant int& in_vec_size [[buffer(4)]],
+ const constant int& out_vec_size [[buffer(5)]],
+ const constant int& matrix_ld [[buffer(6)]],
+ const constant float& alpha [[buffer(7)]],
+ const constant float& beta [[buffer(8)]],
+ const constant int& batch_ndim [[buffer(9)]],
+ const constant int* batch_shape [[buffer(10)]],
+ const constant int64_t* vector_batch_stride [[buffer(11)]],
+ const constant int64_t* matrix_batch_stride [[buffer(12)]],
+ const constant int64_t* bias_batch_stride [[buffer(13)]],
+ const constant int& bias_stride [[buffer(14)]],
+ threadgroup typename GEMVKernel<T, BM, BN, SM, SN, TM, TN, kDoAxpby>::acc_type* tgp_memory,
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint3 lid [[thread_position_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]
+) {
+ using gemv_kernel = GEMVKernel<T, BM, BN, SM, SN, TM, TN, kDoAxpby>;
+
+ if (kDoNCBatch) {
+ in_vec += linear_offset_for_batch(
+ tid.z, batch_shape, vector_batch_stride, batch_ndim
+ );
+ mat += linear_offset_for_batch(
+ tid.z, batch_shape, matrix_batch_stride, batch_ndim
+ );
+ if (kDoAxpby) {
+ bias += linear_offset_for_batch(
+ tid.z, batch_shape, bias_batch_stride, batch_ndim
+ );
+ }
+ } else {
+ in_vec += tid.z * vector_batch_stride[0];
+ mat += tid.z * matrix_batch_stride[0];
+ if (kDoAxpby) {
+ bias += tid.z * bias_batch_stride[0];
+ }
+ }
+
+ out_vec += tid.z * out_vec_size;
+
+ gemv_kernel::run(
+ mat,
+ in_vec,
+ bias,
+ out_vec,
+ in_vec_size,
+ out_vec_size,
+ matrix_ld,
+ alpha,
+ beta,
+ bias_stride,
+ tgp_memory,
+ tid,
+ lid,
+ simd_gid,
+ simd_lid
+ );
+}
+
+template <
+ typename T,
+ const int BM, /* Threadgroup rows (in simdgroups) */
+ const int BN, /* Threadgroup cols (in simdgroups) */
+ const int SM, /* Simdgroup rows (in threads) */
+ const int SN, /* Simdgroup cols (in threads) */
+ const int TM, /* Thread rows (in elements) */
+ const int TN, /* Thread cols (in elements) */
+ const bool kDoNCBatch, /* Batch ndim > 1 */
+ const bool kDoAxpby> /* Do out = alpha * out + beta * bias */
+METAL_FUNC void gemv_t_entry(
+ const device T* mat [[buffer(0)]],
+ const device T* in_vec [[buffer(1)]],
+ const device T* bias [[buffer(2)]],
+ device T* out_vec [[buffer(3)]],
+ const constant int& in_vec_size [[buffer(4)]],
+ const constant int& out_vec_size [[buffer(5)]],
+ const constant int& matrix_ld [[buffer(6)]],
+ const constant float& alpha [[buffer(7)]],
+ const constant float& beta [[buffer(8)]],
+ const constant int& batch_ndim [[buffer(9)]],
+ const constant int* batch_shape [[buffer(10)]],
+ const constant int64_t* vector_batch_stride [[buffer(11)]],
+ const constant int64_t* matrix_batch_stride [[buffer(12)]],
+ const constant int64_t* bias_batch_stride [[buffer(13)]],
+ const constant int& bias_stride [[buffer(14)]],
+ threadgroup typename GEMVTKernel<T, BM, BN, SM, SN, TM, TN, kDoAxpby>::acc_type* tgp_memory,
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint3 lid [[thread_position_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]
+) {
+ using gemv_kernel = GEMVTKernel<T, BM, BN, SM, SN, TM, TN, kDoAxpby>;
+
+ if (kDoNCBatch) {
+ in_vec += linear_offset_for_batch(
+ tid.z, batch_shape, vector_batch_stride, batch_ndim
+ );
+ mat += linear_offset_for_batch(
+ tid.z, batch_shape, matrix_batch_stride, batch_ndim
+ );
+ if (kDoAxpby) {
+ bias += linear_offset_for_batch(
+ tid.z, batch_shape, bias_batch_stride, batch_ndim
+ );
+ }
+ } else {
+ in_vec += tid.z * vector_batch_stride[0];
+ mat += tid.z * matrix_batch_stride[0];
+ if (kDoAxpby) {
+ bias += tid.z * bias_batch_stride[0];
+ }
+ }
+
+ out_vec += tid.z * out_vec_size;
+
+ gemv_kernel::run(
+ mat,
+ in_vec,
+ bias,
+ out_vec,
+ in_vec_size,
+ out_vec_size,
+ matrix_ld,
+ alpha,
+ beta,
+ bias_stride,
+ tgp_memory,
+ tid,
+ lid,
+ simd_gid,
+ simd_lid);
}
-#define INSTANTIATE_GEMV_CONFIG(dtype, acc_type, rows, reduction, thr_row, thr_col, elem_row, elem_col) \
- INSTANTIATE_GEMV_KERNEL( \
- gemv_##dtype##_rows##rows##_reduction##reduction##_elements##elem_row, \
- dtype, acc_type, rows, reduction, thr_row, thr_col, elem_row, elem_col, false) \
- INSTANTIATE_GEMV_KERNEL( \
- gemv_##dtype##_rows##rows##_reduction##reduction##_elements##elem_row##_bias, \
- dtype, acc_type, rows, reduction, thr_row, thr_col, elem_row, elem_col, true)
-
-#define INSTANTIATE_ALL_CONFIGS_FOR_DTYPE(dtype, acc_type) \
- INSTANTIATE_GEMV_CONFIG(dtype, acc_type, 1, 8, 1, 32, 4, 4) \
- INSTANTIATE_GEMV_CONFIG(dtype, acc_type, 1, 8, 1, 32, 1, 4) \
- INSTANTIATE_GEMV_CONFIG(dtype, acc_type, 1, 1, 8, 4, 4, 4) \
- INSTANTIATE_GEMV_CONFIG(dtype, acc_type, 1, 1, 8, 4, 1, 4) \
- INSTANTIATE_GEMV_CONFIG(dtype, acc_type, 4, 1, 1, 32, 1, 4) \
- INSTANTIATE_GEMV_CONFIG(dtype, acc_type, 4, 1, 1, 32, 4, 4) \
- INSTANTIATE_GEMV_CONFIG(dtype, acc_type, 8, 1, 1, 32, 4, 4)
-
-INSTANTIATE_ALL_CONFIGS_FOR_DTYPE(half, float)
-INSTANTIATE_ALL_CONFIGS_FOR_DTYPE(bfloat, float)
-INSTANTIATE_ALL_CONFIGS_FOR_DTYPE(float, float)
+///////////////////////////////////////////////////////////////////////////////
+/// Instantiation helpers
+///////////////////////////////////////////////////////////////////////////////
+
+#define instantiate_gemv_helper( \
+ name, itype, bm, bn, sm, sn, tm, tn, nc, axpby) \
+ [[host_name( \
+ "gemv_" #name "_bm" #bm "_bn" #bn "_sm" #sm "_sn" #sn "_tm" #tm \
+ "_tn" #tn "_nc" #nc "_axpby" #axpby)]] \
+ [[kernel, max_total_threads_per_threadgroup(bm * bn * 32)]] \
+ void gemv_inst_##name##_bm##bm##_bn##bn##_sm##sm##_sn##sn##_tm##tm##_tn##tn##_nc##nc##_axpby##axpby( \
+ const device itype* mat [[buffer(0)]], \
+ const device itype* in_vec [[buffer(1)]], \
+ const device itype* bias [[buffer(2)]], \
+ device itype* out_vec [[buffer(3)]], \
+ const constant int& in_vec_size [[buffer(4)]], \
+ const constant int& out_vec_size [[buffer(5)]], \
+ const constant int& matrix_ld [[buffer(6)]], \
+ const constant float& alpha [[buffer(7)]], \
+ const constant float& beta [[buffer(8)]], \
+ const constant int& batch_ndim [[buffer(9)]], \
+ const constant int* batch_shape [[buffer(10)]], \
+ const constant int64_t* vector_batch_stride [[buffer(11)]], \
+ const constant int64_t* matrix_batch_stride [[buffer(12)]], \
+ const constant int64_t* bias_batch_stride [[buffer(13)]], \
+ const constant int& bias_stride [[buffer(14)]], \
+ uint3 tid [[threadgroup_position_in_grid]], \
+ uint3 lid [[thread_position_in_threadgroup]], \
+ uint simd_gid [[simdgroup_index_in_threadgroup]], \
+ uint simd_lid [[thread_index_in_simdgroup]]) { \
+ using gemv_kernel = GEMVKernel<itype, bm, bn, sm, sn, tm, tn, axpby>; \
+ threadgroup typename gemv_kernel::acc_type tgp_memory[ \
+ gemv_kernel::tgp_mem_size == 0 ? 1 : gemv_kernel::tgp_mem_size]; \
+ gemv_entry<itype, bm, bn, sm, sn, tm, tn, nc, axpby>( \
+ mat, \
+ in_vec, \
+ bias, \
+ out_vec, \
+ in_vec_size, \
+ out_vec_size, \
+ matrix_ld, \
+ alpha, \
+ beta, \
+ batch_ndim, \
+ batch_shape, \
+ vector_batch_stride, \
+ matrix_batch_stride, \
+ bias_batch_stride, \
+ bias_stride, \
+ gemv_kernel::tgp_mem_size == 0 ? nullptr : tgp_memory, \
+ tid, \
+ lid, \
+ simd_gid, \
+ simd_lid); \
+ } \
+ [[host_name( \
+ "gemv_t_" #name "_bm" #bm "_bn" #bn "_sm" #sm "_sn" #sn "_tm" \
+ #tm "_tn" #tn "_nc" #nc "_axpby" #axpby)]] \
+ [[kernel, max_total_threads_per_threadgroup(bm * bn * 32)]] \
+ void gemv_t_inst_##name##_bm##bm##_bn##bn##_sm##sm##_sn##sn##_tm##tm##_tn##tn##_nc##nc##_axpby##axpby( \
+ const device itype* mat [[buffer(0)]], \
+ const device itype* in_vec [[buffer(1)]], \
+ const device itype* bias [[buffer(2)]], \
+ device itype* out_vec [[buffer(3)]], \
+ const constant int& in_vec_size [[buffer(4)]], \
+ const constant int& out_vec_size [[buffer(5)]], \
+ const constant int& matrix_ld [[buffer(6)]], \
+ const constant float& alpha [[buffer(7)]], \
+ const constant float& beta [[buffer(8)]], \
+ const constant int& batch_ndim [[buffer(9)]], \
+ const constant int* batch_shape [[buffer(10)]], \
+ const constant int64_t* vector_batch_stride [[buffer(11)]], \
+ const constant int64_t* matrix_batch_stride [[buffer(12)]], \
+ const constant int64_t* bias_batch_stride [[buffer(13)]], \
+ const constant int& bias_stride [[buffer(14)]], \
+ uint3 tid [[threadgroup_position_in_grid]], \
+ uint3 lid [[thread_position_in_threadgroup]], \
+ uint simd_gid [[simdgroup_index_in_threadgroup]], \
+ uint simd_lid [[thread_index_in_simdgroup]]) { \
+ using gemv_kernel = GEMVTKernel<itype, bm, bn, sm, sn, tm, tn, axpby>; \
+ threadgroup typename gemv_kernel::acc_type tgp_memory[ \
+ gemv_kernel::tgp_mem_size == 0 ? 1 : gemv_kernel::tgp_mem_size]; \
+ gemv_t_entry<itype, bm, bn, sm, sn, tm, tn, nc, axpby>( \
+ mat, \
+ in_vec, \
+ bias, \
+ out_vec, \
+ in_vec_size, \
+ out_vec_size, \
+ matrix_ld, \
+ alpha, \
+ beta, \
+ batch_ndim, \
+ batch_shape, \
+ vector_batch_stride, \
+ matrix_batch_stride, \
+ bias_batch_stride, \
+ bias_stride, \
+ gemv_kernel::tgp_mem_size == 0 ? nullptr : tgp_memory, \
+ tid, \
+ lid, \
+ simd_gid, \
+ simd_lid); \
+ }
+
+// clang-format off
+#define instantiate_gemv(name, itype, bm, bn, sm, sn, tm, tn) \
+ instantiate_gemv_helper(name, itype, bm, bn, sm, sn, tm, tn, 0, 0) \
+ instantiate_gemv_helper(name, itype, bm, bn, sm, sn, tm, tn, 0, 1) \
+ instantiate_gemv_helper(name, itype, bm, bn, sm, sn, tm, tn, 1, 0) \
+ instantiate_gemv_helper(name, itype, bm, bn, sm, sn, tm, tn, 1, 1)
+
+#define instantiate_gemv_blocks(name, itype) \
+ instantiate_gemv(name, itype, 1, 8, 1, 32, 4, 4) \
+ instantiate_gemv(name, itype, 1, 8, 1, 32, 1, 4) \
+ instantiate_gemv(name, itype, 1, 1, 8, 4, 4, 4) \
+ instantiate_gemv(name, itype, 1, 1, 8, 4, 1, 4) \
+ instantiate_gemv(name, itype, 4, 1, 1, 32, 1, 4) \
+ instantiate_gemv(name, itype, 4, 1, 1, 32, 4, 4) \
+ instantiate_gemv(name, itype, 8, 1, 1, 32, 4, 4)
+
+instantiate_gemv_blocks(float32, float);
+instantiate_gemv_blocks(float16, half);
+instantiate_gemv_blocks(bfloat16, bfloat);
+
+#define instantiate_gemv_t(name, itype, bm, bn, sm, sn, tm, tn) \
+ instantiate_gemv_helper(name, itype, bm, bn, sm, sn, tm, tn, 0, 0) \
+ instantiate_gemv_helper(name, itype, bm, bn, sm, sn, tm, tn, 0, 1) \
+ instantiate_gemv_helper(name, itype, bm, bn, sm, sn, tm, tn, 1, 0) \
+ instantiate_gemv_helper(name, itype, bm, bn, sm, sn, tm, tn, 1, 1)
+
+#define instantiate_gemv_t_blocks(name, itype) \
+ instantiate_gemv_t(name, itype, 1, 2, 8, 4, 4, 1) \
+ instantiate_gemv_t(name, itype, 1, 2, 8, 4, 4, 4) \
+ instantiate_gemv_t(name, itype, 1, 4, 8, 4, 4, 4) \
+ instantiate_gemv_t(name, itype, 1, 16, 8, 4, 4, 4) \
+ instantiate_gemv_t(name, itype, 1, 16, 4, 8, 4, 4)
+
+instantiate_gemv_t_blocks(float32, float);
+instantiate_gemv_t_blocks(float16, half);
+instantiate_gemv_t_blocks(bfloat16, bfloat);
+// clang-format on
diff --git a/crates/uzu/src/backends/metal/kernel/matmul/gemv.rs b/crates/uzu/src/backends/metal/kernel/matmul/gemv.rs
index bb1e473ff..df810d944 100644
--- a/crates/uzu/src/backends/metal/kernel/matmul/gemv.rs
+++ b/crates/uzu/src/backends/metal/kernel/matmul/gemv.rs
@@ -1,6 +1,9 @@
use std::collections::HashMap;
-use metal::{Buffer as MTLBuffer, ComputeCommandEncoderRef, ComputePipelineState, MTLSize};
+use metal::{
+ Buffer as MTLBuffer, ComputeCommandEncoderRef, ComputePipelineState,
+ MTLSize,
+};
use super::arguments::MatmulArguments;
use crate::{
@@ -10,102 +13,179 @@ use crate::{
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct GemvConfiguration {
- simdgroups_per_row: u32,
- simdgroups_per_reduction: u32,
+ transpose_matrix: bool,
+ 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,
- has_bias: bool,
+ non_contiguous_batch: bool,
+ do_axpby: bool,
}
impl GemvConfiguration {
fn output_elements_per_threadgroup(&self) -> u32 {
- let total_threads_row = self.simdgroups_per_row * self.threads_per_simdgroup_row;
- total_threads_row * self.elements_per_thread_row
- }
-
- fn total_threads_per_threadgroup(&self) -> u32 {
- self.simdgroups_per_row * self.simdgroups_per_reduction * 32
+ if self.transpose_matrix {
+ self.threadgroup_cols
+ * self.threads_per_simdgroup_col
+ * self.elements_per_thread_col
+ } else {
+ self.threadgroup_rows
+ * self.threads_per_simdgroup_row
+ * self.elements_per_thread_row
+ }
}
-}
-fn select_gemv_configuration(input_dimension: i32, output_dimension: i32, has_bias: bool) -> GemvConfiguration {
- let is_small_input_dimension = input_dimension <= 64;
- let is_large_input_relative_to_output = input_dimension >= 16 * output_dimension;
- let is_large_output_dimension = output_dimension >= 4096;
- let is_very_small_output_dimension = output_dimension < 4;
-
- if is_small_input_dimension {
- GemvConfiguration {
- simdgroups_per_row: 1,
- simdgroups_per_reduction: 1,
- threads_per_simdgroup_row: 8,
- threads_per_simdgroup_col: 4,
- elements_per_thread_row: if is_very_small_output_dimension { 1 } else { 4 },
- elements_per_thread_col: 4,
- has_bias,
- }
- } else if is_large_input_relative_to_output {
- GemvConfiguration {
- simdgroups_per_row: 1,
- simdgroups_per_reduction: 8,
- threads_per_simdgroup_row: 1,
- threads_per_simdgroup_col: 32,
- elements_per_thread_row: if is_very_small_output_dimension { 1 } else { 4 },
- elements_per_thread_col: 4,
- has_bias,
- }
- } else {
- GemvConfiguration {
- simdgroups_per_row: if is_large_output_dimension { 8 } else { 4 },
- simdgroups_per_reduction: 1,
- threads_per_simdgroup_row: 1,
- threads_per_simdgroup_col: 32,
- elements_per_thread_row: if is_very_small_output_dimension { 1 } else { 4 },
- elements_per_thread_col: 4,
- has_bias,
- }
+ fn threads_per_threadgroup(&self) -> MTLSize {
+ // 32 threads per simdgroup, arranged (x=32, y=BN, z=BM)
+ MTLSize::new(
+ 32,
+ self.threadgroup_cols as u64,
+ self.threadgroup_rows as u64,
+ )
}
}
-fn kernel_name_for_configuration(data_type: DataType, configuration: &GemvConfiguration) -> Result<String, MTLError> {
- let type_name = match data_type {
- DataType::F16 => "half",
- DataType::BF16 => "bfloat",
- DataType::F32 => "float",
+fn gemv_kernel_name(
+ data_type: DataType,
+ configuration: &GemvConfiguration,
+) -> 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 GEMV: {:?}",
data_type
)));
- }
+ },
+ };
+
+ let prefix = if configuration.transpose_matrix {
+ "gemv_t"
+ } else {
+ "gemv"
};
- let base_name = format!(
- "gemv_{}_rows{}_reduction{}_elements{}",
- type_name,
- configuration.simdgroups_per_row,
- configuration.simdgroups_per_reduction,
- configuration.elements_per_thread_row
- );
+ Ok(format!(
+ "{prefix}_{dtype_name}_bm{}_bn{}_sm{}_sn{}_tm{}_tn{}_nc{}_axpby{}",
+ 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,
+ configuration.non_contiguous_batch as u8,
+ configuration.do_axpby as u8,
+ ))
+}
+
+fn select_gemv_configuration(
+ transpose_matrix: bool,
+ input_dimension: i32,
+ output_dimension: i32,
+ non_contiguous_batch: bool,
+ do_axpby: bool,
+) -> GemvConfiguration {
+ // GEMV tuning surface for axpby kernel selection.
+ let (threadgroup_rows, threadgroup_cols);
+ let (threads_per_simdgroup_row, threads_per_simdgroup_col);
+ let (elements_per_thread_row, elements_per_thread_col);
+
+ if transpose_matrix {
+ let mut sm = 8;
+ let mut sn = 4;
+ if input_dimension >= 8192 && output_dimension >= 2048 {
+ sm = 4;
+ sn = 8;
+ }
+
+ let bn = if output_dimension >= 2048 {
+ 16
+ } else if output_dimension >= 512 {
+ 4
+ } else {
+ 2
+ };
+
+ let tn = if output_dimension < 4 {
+ 1
+ } else {
+ 4
+ };
- Ok(if configuration.has_bias {
- format!("{}_bias", base_name)
+ threadgroup_rows = 1;
+ threadgroup_cols = bn;
+ threads_per_simdgroup_row = sm;
+ threads_per_simdgroup_col = sn;
+ elements_per_thread_row = 4;
+ elements_per_thread_col = tn;
} else {
- base_name
- })
+ let mut bm = if output_dimension >= 4096 {
+ 8
+ } else {
+ 4
+ };
+ let mut sm = 1;
+ let mut sn = 32;
+ let mut bn = 1;
+
+ if input_dimension <= 64 {
+ bm = 1;
+ sm = 8;
+ sn = 4;
+ } else if input_dimension >= 16 * output_dimension {
+ bm = 1;
+ bn = 8;
+ }
+
+ let tm = if output_dimension < 4 {
+ 1
+ } else {
+ 4
+ };
+
+ threadgroup_rows = bm;
+ threadgroup_cols = bn;
+ threads_per_simdgroup_row = sm;
+ threads_per_simdgroup_col = sn;
+ elements_per_thread_row = tm;
+ elements_per_thread_col = 4;
+ }
+
+ GemvConfiguration {
+ transpose_matrix,
+ threadgroup_rows,
+ threadgroup_cols,
+ threads_per_simdgroup_row,
+ threads_per_simdgroup_col,
+ elements_per_thread_row,
+ elements_per_thread_col,
+ non_contiguous_batch,
+ do_axpby,
+ }
}
+
pub struct GemvKernel {
data_type: DataType,
+ lhs_is_transposed: bool,
+ rhs_is_transposed: bool,
pipelines: HashMap<GemvConfiguration, ComputePipelineState>,
}
impl GemvKernel {
- pub fn new(data_type: DataType) -> Self {
+ pub fn new(
+ data_type: DataType,
+ lhs_is_transposed: bool,
+ rhs_is_transposed: bool,
+ ) -> Self {
Self {
data_type,
+ lhs_is_transposed,
+ rhs_is_transposed,
pipelines: HashMap::new(),
}
}
@@ -116,36 +196,69 @@ impl GemvKernel {
configuration: GemvConfiguration,
) -> Result<&ComputePipelineState, MTLError> {
if !self.pipelines.contains_key(&configuration) {
- let kernel_name = kernel_name_for_configuration(self.data_type, &configuration)?;
- let pipeline = context.compute_pipeline_state(&kernel_name, None)?;
+ let kernel_name = gemv_kernel_name(self.data_type, &configuration)?;
+ let pipeline =
+ context.compute_pipeline_state(&kernel_name, None)?;
self.pipelines.insert(configuration, pipeline);
}
Ok(self.pipelines.get(&configuration).unwrap())
}
+ #[allow(clippy::too_many_arguments)]
fn encode_with_configuration(
&mut self,
context: &MTLContext,
encoder: &ComputeCommandEncoderRef,
- arguments: MatmulArguments,
+ arguments: &MatmulArguments,
configuration: GemvConfiguration,
- bias: Option<&MTLBuffer>,
+ matrix_is_rhs: bool,
+ bias_buffer: Option<&MTLBuffer>,
+ alpha: f32,
+ beta: f32,
+ bias_stride: i32,
) -> Result<(), MTLError> {
let pipeline = self.get_pipeline(context, configuration)?;
encoder.set_compute_pipeline_state(pipeline);
- encoder.set_buffer(0, Some(arguments.b), 0);
- encoder.set_buffer(1, Some(arguments.a), 0);
- if let Some(bias_buffer) = bias {
- encoder.set_buffer(2, Some(bias_buffer), 0);
+ encoder.set_buffer(
+ 0,
+ Some(if matrix_is_rhs {
+ arguments.b
+ } else {
+ arguments.a
+ }),
+ 0,
+ );
+
+ encoder.set_buffer(
+ 1,
+ Some(if matrix_is_rhs {
+ arguments.a
+ } else {
+ arguments.b
+ }),
+ 0,
+ );
+
+ if configuration.do_axpby {
+ if let Some(bias) = bias_buffer {
+ encoder.set_buffer(2, Some(bias), 0);
+ }
}
+
encoder.set_buffer(3, Some(arguments.d), 0);
let input_dimension = arguments.input_dim;
- let output_dimension = arguments.output_dim;
- let weight_row_stride = arguments.ldb;
- let input_batch_stride = arguments.lda;
- let output_batch_stride = arguments.ldd;
+ let output_dimension = if matrix_is_rhs {
+ arguments.output_dim
+ } else {
+ arguments.batch
+ };
+ let matrix_leading_dim = if matrix_is_rhs {
+ arguments.ldb
+ } else {
+ arguments.lda
+ };
encoder.set_bytes(
4,
@@ -160,28 +273,99 @@ impl GemvKernel {
encoder.set_bytes(
6,
std::mem::size_of::<i32>() as u64,
- &weight_row_stride as *const i32 as *const std::ffi::c_void,
+ &matrix_leading_dim as *const i32 as *const std::ffi::c_void,
);
+
encoder.set_bytes(
7,
- std::mem::size_of::<i32>() as u64,
- &input_batch_stride as *const i32 as *const std::ffi::c_void,
+ std::mem::size_of::<f32>() as u64,
+ &alpha as *const f32 as *const std::ffi::c_void,
);
encoder.set_bytes(
8,
+ std::mem::size_of::<f32>() as u64,
+ &beta as *const f32 as *const std::ffi::c_void,
+ );
+
+ let has_batch = arguments.batch_count > 1;
+ let batch_shape = if has_batch {
+ vec![arguments.batch_count]
+ } else {
+ vec![1]
+ };
+ let batch_ndim = 1i32;
+ let batch_groups = arguments.batch_count.max(1);
+
+ let elements_per_matrix_a =
+ (arguments.batch as i64) * (arguments.lda as i64);
+ let elements_per_matrix_b = if self.rhs_is_transposed {
+ (arguments.output_dim as i64) * (arguments.ldb as i64)
+ } else {
+ (arguments.input_dim as i64) * (arguments.ldb as i64)
+ };
+
+ let vector_batch_stride = if matrix_is_rhs {
+ vec![elements_per_matrix_a]
+ } else {
+ vec![elements_per_matrix_b]
+ };
+
+ let matrix_batch_stride = if matrix_is_rhs {
+ vec![elements_per_matrix_b]
+ } else {
+ vec![elements_per_matrix_a]
+ };
+
+ let bias_batch_stride = if arguments.batch_count > 1 {
+ vec![(output_dimension as i64) * (arguments.ldd as i64)]
+ } else {
+ vec![0]
+ };
+
+ encoder.set_bytes(
+ 9,
std::mem::size_of::<i32>() as u64,
- &output_batch_stride as *const i32 as *const std::ffi::c_void,
+ &batch_ndim as *const i32 as *const std::ffi::c_void,
+ );
+ encoder.set_bytes(
+ 10,
+ (std::mem::size_of::<i32>() * batch_shape.len()) as u64,
+ batch_shape.as_ptr() as *const std::ffi::c_void,
+ );
+ encoder.set_bytes(
+ 11,
+ (std::mem::size_of::<i64>() * vector_batch_stride.len()) as u64,
+ vector_batch_stride.as_ptr() as *const std::ffi::c_void,
+ );
+ encoder.set_bytes(
+ 12,
+ (std::mem::size_of::<i64>() * matrix_batch_stride.len()) as u64,
+ matrix_batch_stride.as_ptr() as *const std::ffi::c_void,
+ );
+ encoder.set_bytes(
+ 13,
+ (std::mem::size_of::<i64>() * bias_batch_stride.len()) as u64,
+ bias_batch_stride.as_ptr() as *const std::ffi::c_void,
+ );
+ encoder.set_bytes(
+ 14,
+ std::mem::size_of::<i32>() as u64,
+ &bias_stride as *const i32 as *const std::ffi::c_void,
);
- let output_elements_per_threadgroup = configuration.output_elements_per_threadgroup();
+ let output_elements_per_threadgroup =
+ configuration.output_elements_per_threadgroup();
let threadgroup_count_x =
- ((output_dimension as u32 + output_elements_per_threadgroup - 1) / output_elements_per_threadgroup) as u64;
- let threadgroup_count_z = arguments.batch_count as u64;
+ ((output_dimension as u32 + output_elements_per_threadgroup - 1)
+ / output_elements_per_threadgroup) as u64;
+ let threadgroup_count_z = batch_groups.max(1) as u64;
- let threadgroup_count = MTLSize::new(threadgroup_count_x, 1, threadgroup_count_z);
- let threads_per_threadgroup = MTLSize::new(configuration.total_threads_per_threadgroup() as u64, 1, 1);
+ let threadgroup_count =
+ MTLSize::new(threadgroup_count_x, 1, threadgroup_count_z);
+ let threads_per_threadgroup = configuration.threads_per_threadgroup();
- encoder.dispatch_thread_groups(threadgroup_count, threads_per_threadgroup);
+ encoder
+ .dispatch_thread_groups(threadgroup_count, threads_per_threadgroup);
Ok(())
}
@@ -189,30 +373,80 @@ impl GemvKernel {
&mut self,
context: &MTLContext,
encoder: &ComputeCommandEncoderRef,
- arguments: MatmulArguments,
- _rows_per_threadgroup: u32,
+ arguments: &MatmulArguments,
) -> Result<(), MTLError> {
- let configuration = select_gemv_configuration(
- arguments.input_dim,
- arguments.output_dim,
- false,
- );
- self.encode_with_configuration(context, encoder, arguments, configuration, None)
+ self.encode_internal(context, encoder, arguments, None)
}
pub fn encode_with_bias(
&mut self,
context: &MTLContext,
encoder: &ComputeCommandEncoderRef,
- arguments: MatmulArguments,
- _rows_per_threadgroup: u32,
+ arguments: &MatmulArguments,
bias: &MTLBuffer,
) -> Result<(), MTLError> {
+ self.encode_internal(context, encoder, arguments, Some(bias))
+ }
+
+ fn encode_internal(
+ &mut self,
+ context: &MTLContext,
+ encoder: &ComputeCommandEncoderRef,
+ arguments: &MatmulArguments,
+ bias: Option<&MTLBuffer>,
+ ) -> Result<(), MTLError> {
+ let m = arguments.batch;
+ let n = arguments.output_dim;
+ if m != 1 && n != 1 {
+ return Ok(());
+ }
+
+ let matrix_is_rhs = n != 1;
+ let transpose_matrix = if matrix_is_rhs {
+ !self.rhs_is_transposed
+ } else {
+ self.lhs_is_transposed
+ };
+
+ let has_non_contiguous_batch = false;
+
+ let (do_axpby, bias_buffer, alpha, beta, bias_stride) =
+ if let Some(bias_buf) = bias {
+ (true, Some(bias_buf), 1.0f32, 1.0f32, 1)
+ } else if let Some(c_buf) = arguments.c {
+ (
+ true,
+ Some(c_buf),
+ arguments.alpha,
+ arguments.beta,
+ arguments.ldd,
+ )
+ } else {
+ (false, None, 1.0f32, 0.0f32, 0)
+ };
+
let configuration = select_gemv_configuration(
+ transpose_matrix,
arguments.input_dim,
- arguments.output_dim,
- true,
+ if matrix_is_rhs {
+ arguments.output_dim
+ } else {
+ arguments.batch
+ },
+ has_non_contiguous_batch,
+ do_axpby,
);
- self.encode_with_configuration(context, encoder, arguments, configuration, Some(bias))
+
+ self.encode_with_configuration(
+ context,
+ encoder,
+ arguments,
+ configuration,
+ matrix_is_rhs,
+ bias_buffer,
+ alpha,
+ beta,
+ bias_stride,
+ )
}
}
diff --git a/crates/uzu/src/backends/metal/kernel/matmul/kernel.rs b/crates/uzu/src/backends/metal/kernel/matmul/kernel.rs
index e9913698e..0f99c03cb 100644
--- a/crates/uzu/src/backends/metal/kernel/matmul/kernel.rs
+++ b/crates/uzu/src/backends/metal/kernel/matmul/kernel.rs
@@ -1,26 +1,58 @@
use std::collections::HashMap;
use metal::{
- Buffer as MTLBuffer,
- ComputeCommandEncoderRef, ComputePipelineState as MTLComputePipelineState,
- MTLSize,
+ Buffer as MTLBuffer, ComputeCommandEncoderRef,
+ ComputePipelineState as MTLComputePipelineState, MTLSize,
};
use super::{
- arguments::MatmulArguments, gemv::GemvKernel, pipeline::PipelineKey,
- shared_types::GEMMParams, splitk::SplitKGemm,
+ super::{KernelDataType, TensorAddBias},
+ arguments::MatmulArguments,
+ gemv::GemvKernel,
+ pipeline::PipelineKey,
+ shared_types::{GEMMAddMMParams, GEMMParams},
+ splitk::SplitKGemm,
transpose::transpose_configuration,
};
-use super::super::{KernelDataType, TensorAddBias};
use crate::{
DataType,
backends::metal::{MTLContext, MTLError},
};
+#[derive(Debug, Clone, Copy)]
+struct TileSelection {
+ block_rows: i32,
+ block_cols: i32,
+ block_depth: i32,
+ warps_per_row: u64,
+ warps_per_col: u64,
+ swizzle_log2: i32,
+}
+
+impl TileSelection {
+ fn new(
+ block_rows: i32,
+ block_cols: i32,
+ block_depth: i32,
+ warps_per_row: u64,
+ warps_per_col: u64,
+ swizzle_log2: i32,
+ ) -> Self {
+ Self {
+ block_rows,
+ block_cols,
+ block_depth,
+ warps_per_row,
+ warps_per_col,
+ swizzle_log2,
+ }
+ }
+}
+
pub struct MatmulKernel {
- dt: DataType,
- transpose_a: bool,
- transpose_b: bool,
+ data_type: DataType,
+ lhs_is_transposed: bool,
+ rhs_is_transposed: bool,
gemv: Option<GemvKernel>,
splitk: Option<SplitKGemm>,
bias_add: Option<TensorAddBias>,
@@ -39,37 +71,42 @@ impl MatmulKernel {
fn kernel_name(
&self,
- bm: i32,
- bn: i32,
- bk: i32,
- wm: u64,
- wn: u64,
+ tile: &TileSelection,
) -> String {
- let t = Self::dtype_suffix(self.dt);
- let cfg = transpose_configuration(self.transpose_a, self.transpose_b);
- let tcfg = cfg.as_str();
+ let dtype_suffix = Self::dtype_suffix(self.data_type);
+ let transpose_suffix = transpose_configuration(
+ self.lhs_is_transposed,
+ self.rhs_is_transposed,
+ );
format!(
"gemm_{}_{}_bm{}_bn{}_bk{}_wm{}_wn{}",
- tcfg, t, bm, bn, bk, wm, wn
+ transpose_suffix.as_str(),
+ dtype_suffix,
+ tile.block_rows,
+ tile.block_cols,
+ tile.block_depth,
+ tile.warps_per_row,
+ tile.warps_per_col
)
}
pub fn new(
_mtl: &MTLContext,
- dt: DataType,
- transpose_a: bool,
- transpose_b: bool,
+ data_type: DataType,
+ lhs_is_transposed: bool,
+ rhs_is_transposed: bool,
) -> Result<Self, MTLError> {
- if !matches!(dt, DataType::F16 | DataType::BF16 | DataType::F32) {
+ if !matches!(data_type, DataType::F16 | DataType::BF16 | DataType::F32)
+ {
return Err(MTLError::Generic(format!(
- "Unsupported dtype for MatmulKernel: {dt:?}"
+ "Unsupported dtype for MatmulKernel: {data_type:?}"
)));
}
Ok(Self {
- dt,
- transpose_a,
- transpose_b,
+ data_type,
+ lhs_is_transposed,
+ rhs_is_transposed,
gemv: None,
splitk: None,
bias_add: None,
@@ -81,7 +118,7 @@ impl MatmulKernel {
&mut self,
mtl: &MTLContext,
enc: &ComputeCommandEncoderRef,
- args: MatmulArguments,
+ args: &MatmulArguments,
bias: Option<&MTLBuffer>,
) -> Result<bool, MTLError> {
// GEMV kernel requires:
@@ -90,45 +127,24 @@ impl MatmulKernel {
// Without transpose_b, B is [K, N] and columns are not contiguous
let m = args.batch;
let n = args.output_dim;
- if self.transpose_a || !self.transpose_b {
+ if self.lhs_is_transposed || !self.rhs_is_transposed {
return Ok(false);
}
- // For small M (≤ 8), treat as M independent GEMV operations in batch dimension
- // This is more efficient than using GEMM with mostly empty tiles
- let use_batched_gemv =
- m > 1 && m <= 8 && n > 1 && args.batch_count == 1;
- if use_batched_gemv {
- let batched_args = MatmulArguments {
- a: args.a,
- b: args.b,
- d: args.d,
- batch: 1,
- input_dim: args.input_dim,
- output_dim: args.output_dim,
- lda: args.lda,
- ldb: args.ldb,
- ldd: args.ldd,
- batch_count: m,
- };
- let gemv =
- self.gemv.get_or_insert_with(|| GemvKernel::new(self.dt));
- if let Some(bias) = bias {
- gemv.encode_with_bias(mtl, enc, batched_args, 0, bias)?;
- } else {
- gemv.encode(mtl, enc, batched_args, 0)?;
- }
- return Ok(true);
- }
-
if m != 1 && n != 1 {
return Ok(false);
}
- let gemv = self.gemv.get_or_insert_with(|| GemvKernel::new(self.dt));
+ let gemv = self.gemv.get_or_insert_with(|| {
+ GemvKernel::new(
+ self.data_type,
+ self.lhs_is_transposed,
+ self.rhs_is_transposed,
+ )
+ });
if let Some(bias) = bias {
- gemv.encode_with_bias(mtl, enc, args, 0, bias)?;
+ gemv.encode_with_bias(mtl, enc, args, bias)?;
} else {
- gemv.encode(mtl, enc, args, 0)?;
+ gemv.encode(mtl, enc, args)?;
}
Ok(true)
}
@@ -137,7 +153,7 @@ impl MatmulKernel {
&mut self,
mtl: &MTLContext,
enc: &ComputeCommandEncoderRef,
- args: MatmulArguments,
+ args: &MatmulArguments,
) -> Result<bool, MTLError> {
self.maybe_use_gemv_impl(mtl, enc, args, None)
}
@@ -146,7 +162,7 @@ impl MatmulKernel {
&mut self,
mtl: &MTLContext,
enc: &ComputeCommandEncoderRef,
- args: MatmulArguments,
+ args: &MatmulArguments,
bias: &MTLBuffer,
) -> Result<bool, MTLError> {
self.maybe_use_gemv_impl(mtl, enc, args, Some(bias))
@@ -156,7 +172,7 @@ impl MatmulKernel {
&mut self,
mtl: &MTLContext,
enc: &ComputeCommandEncoderRef,
- args: MatmulArguments,
+ args: &MatmulArguments,
) -> Result<bool, MTLError> {
let m = args.batch;
let n = args.output_dim;
@@ -168,153 +184,105 @@ impl MatmulKernel {
}
let splitk = self.splitk.get_or_insert_with(|| {
- SplitKGemm::new(self.dt, self.transpose_a, self.transpose_b)
+ SplitKGemm::new(
+ self.data_type,
+ self.lhs_is_transposed,
+ self.rhs_is_transposed,
+ )
});
splitk.encode(mtl, enc, args)?;
Ok(true)
}
- fn select_tiles(
+ fn select_tile_configuration(
&self,
mtl: &MTLContext,
args: &MatmulArguments,
- ) -> (i32, i32, i32, u64, u64) {
+ ) -> TileSelection {
use crate::backends::metal::DeviceClass;
- let mut bm = 64;
- let mut bn = 64;
- let mut bk = 16;
- let mut wm = 2;
- let mut wn = 2;
- let m = args.batch;
- let n = args.output_dim;
- let k = args.input_dim;
- let batch_size_out = args.batch_count;
- let large_mat =
- (batch_size_out as i64) * (m as i64) * (n as i64) >= (1_i64 << 20);
-
- // Small M optimization: use smaller BM tiles to avoid wasted computation
- // For M <= 32, use 32×32 tiles for better efficiency
- let small_m = m <= 32;
- if small_m && !self.transpose_a {
- // 32×32×16 tiles with 2×2 warp config work well for small M
- return (32, 32, 16, 2, 2);
- }
+ let overall_work_elements = (args.batch_count as i64)
+ * (args.batch as i64)
+ * (args.output_dim as i64);
+ let is_float32 = matches!(self.data_type, DataType::F32);
+ let prefer_half_or_tf32 = !is_float32 || mtl.tf32_enabled();
- // Prefer NAX tiles when available on M4+ hardware.
- if mtl.is_nax_available()
- && (!matches!(self.dt, DataType::F32) || mtl.tf32_enabled())
- {
- if large_mat {
- return (128, 128, 32, 2, 2);
- }
- return (64, 64, 32, 2, 2);
+ // NAX path: prefer deeper K tiles on NAX-capable devices.
+ if mtl.is_nax_available() && prefer_half_or_tf32 {
+ let base_tile = TileSelection::new(
+ 128, 128, 32, 2, 2, /*swizzle_log2=*/ 0,
+ );
+ let tile_rows =
+ (args.batch + base_tile.block_rows - 1) / base_tile.block_rows;
+ let swizzle_log2 = if tile_rows <= 3 {
+ 0
+ } else {
+ 1
+ };
+ return TileSelection {
+ swizzle_log2,
+ ..base_tile
+ };
}
- let devc = match mtl.architecture.device_class {
+
+ let device_class_code = match mtl.architecture.device_class {
DeviceClass::Desktop => 'd',
DeviceClass::Integrated => 'g',
DeviceClass::Phone => 'p',
DeviceClass::Unknown(_) => 'g',
};
- let is_float = matches!(self.dt, DataType::F32);
- let prefer_halfish = !is_float || mtl.tf32_enabled();
-
- if devc == 'g' || devc == 'p' {
- if prefer_halfish {
- if !self.transpose_a && self.transpose_b {
- bm = 64;
- bn = 32;
- bk = 32;
- wm = 2;
- wn = 2;
- } else {
- bm = 64;
- bn = 64;
- bk = 16;
- wm = 1;
- wn = 2;
- }
- } else if !self.transpose_a && self.transpose_b {
- bm = 32;
- bn = 64;
- bk = 16;
- wm = 1;
- wn = 2;
- } else {
- bm = 64;
- bn = 32;
- bk = 32;
- wm = 2;
- wn = 2;
- }
- } else if devc == 'd' {
- if large_mat {
- if prefer_halfish {
- if 2 * std::cmp::max(m, n) > k {
- bm = 64;
- bn = 64;
- bk = 16;
- wm = 1;
- wn = 2;
- } else if !self.transpose_a && self.transpose_b {
- bm = 64;
- bn = 32;
- bk = 32;
- wm = 2;
- wn = 2;
+ // Default steel matmul heuristics (non-NAX), matching observed
+ // choices on M2 Max: prefer 64x64x16 wm2/wn2 for large shapes and
+ // fall back to 64x32x32 when transpose_b=true and not N-aligned.
+ match device_class_code {
+ 'g' | 'p' => {
+ if prefer_half_or_tf32 {
+ if !self.lhs_is_transposed && self.rhs_is_transposed {
+ TileSelection::new(64, 32, 32, 2, 2, 0)
} else {
- bm = 32;
- bn = 64;
- bk = 16;
- wm = 1;
- wn = 2;
+ TileSelection::new(64, 64, 16, 1, 2, 0)
}
- } else if !self.transpose_a && self.transpose_b {
- bm = 32;
- bn = 64;
- bk = 16;
- wm = 1;
- wn = 2;
+ } else if !self.lhs_is_transposed && self.rhs_is_transposed {
+ TileSelection::new(32, 64, 16, 1, 2, 0)
} else {
- bm = 64;
- bn = 32;
- bk = 32;
- wm = 2;
- wn = 2;
+ TileSelection::new(64, 32, 32, 2, 2, 0)
}
- } else {
- if prefer_halfish {
- if !self.transpose_a && self.transpose_b {
- bm = 64;
- bn = 32;
- bk = 32;
- wm = 2;
- wn = 2;
+ },
+ 'd' => {
+ if overall_work_elements >= (1_i64 << 20) {
+ if prefer_half_or_tf32 {
+ if 2 * std::cmp::max(args.batch, args.output_dim)
+ > args.input_dim
+ {
+ TileSelection::new(64, 64, 16, 2, 2, 0)
+ } else if !self.lhs_is_transposed
+ && self.rhs_is_transposed
+ {
+ TileSelection::new(64, 32, 32, 2, 2, 0)
+ } else {
+ TileSelection::new(32, 64, 16, 1, 2, 0)
+ }
+ } else if !self.lhs_is_transposed && self.rhs_is_transposed
+ {
+ TileSelection::new(32, 64, 16, 1, 2, 0)
+ } else {
+ TileSelection::new(64, 32, 32, 2, 2, 0)
+ }
+ } else if prefer_half_or_tf32 {
+ if !self.lhs_is_transposed && self.rhs_is_transposed {
+ TileSelection::new(64, 32, 32, 2, 2, 0)
} else {
- bm = 64;
- bn = 64;
- bk = 16;
- wm = 1;
- wn = 2;
+ TileSelection::new(64, 64, 16, 1, 2, 0)
}
- } else if !self.transpose_a && self.transpose_b {
- bm = 32;
- bn = 64;
- bk = 16;
- wm = 1;
- wn = 2;
+ } else if !self.lhs_is_transposed && self.rhs_is_transposed {
+ TileSelection::new(32, 64, 16, 1, 2, 0)
} else {
- bm = 64;
- bn = 32;
- bk = 32;
- wm = 2;
- wn = 2;
+ TileSelection::new(64, 32, 32, 2, 2, 0)
}
- }
+ },
+ _ => TileSelection::new(64, 64, 16, 2, 2, 0),
}
-
- (bm, bn, bk, wm, wn)
}
fn get_or_compile_pipeline(
@@ -324,19 +292,22 @@ impl MatmulKernel {
align_m: bool,
align_n: bool,
align_k: bool,
+ has_batch: bool,
+ use_out_source: bool,
+ do_axpby: bool,
) -> Result<&MTLComputePipelineState, MTLError> {
let key = PipelineKey {
name: name.to_string(),
align_m,
align_n,
align_k,
+ has_batch,
+ use_out_source,
+ do_axpby,
};
if !self.pipelines.contains_key(&key) {
let fcv = metal::FunctionConstantValues::new();
// Base specializations
- let has_batch = false;
- let use_out_source = false;
- let do_axpby = false;
fcv.set_constant_value_at_index(
&has_batch as *const bool as *const _,
metal::MTLDataType::Bool,
@@ -369,8 +340,14 @@ impl MatmulKernel {
);
let cache_key = format!(
- "{}_am{}_an{}_ak{}",
- name, align_m as u8, align_n as u8, align_k as u8
+ "{}_am{}_an{}_ak{}_hb{}_uo{}_ax{}",
+ name,
+ align_m as u8,
+ align_n as u8,
+ align_k as u8,
+ has_batch as u8,
+ use_out_source as u8,
+ do_axpby as u8
);
let (ps, _) = mtl.compute_pipeline_state_with_reflection_cached(
&cache_key,
@@ -386,37 +363,62 @@ impl MatmulKernel {
&mut self,
mtl: &MTLContext,
enc: &ComputeCommandEncoderRef,
- args: MatmulArguments,
+ args: &MatmulArguments,
) -> Result<(), MTLError> {
- let (bm, bn, bk, wm, wn) = self.select_tiles(mtl, &args);
- let kname = self.kernel_name(bm, bn, bk, wm, wn);
+ let tile = self.select_tile_configuration(mtl, &args);
+ let kname = self.kernel_name(&tile);
// M = batch, N = output_dim, K = input_dim
let m = args.batch;
let n = args.output_dim;
let k = args.input_dim;
- let am = (m % bm) == 0;
- let an = (n % bn) == 0;
- let ak = (k % bk) == 0;
- let ps = self.get_or_compile_pipeline(mtl, &kname, am, an, ak)?;
+ let align_m = (m % tile.block_rows) == 0;
+ let align_n = (n % tile.block_cols) == 0;
+ let align_k = (k % tile.block_depth) == 0;
+ let has_batch = args.batch_count > 1;
+ let use_out_source = args.c.is_some();
+ let do_axpby =
+ use_out_source && (args.alpha != 1.0 || args.beta != 0.0);
+ let ps = self.get_or_compile_pipeline(
+ mtl,
+ &kname,
+ align_m,
+ align_n,
+ align_k,
+ has_batch,
+ use_out_source,
+ do_axpby,
+ )?;
enc.set_compute_pipeline_state(ps);
- // Set buffers (C is elided since use_out_source=false)
+ // Set buffers
enc.set_buffer(0, Some(args.a), 0);
enc.set_buffer(1, Some(args.b), 0);
+ if use_out_source {
+ if let Some(c_buf) = args.c {
+ enc.set_buffer(2, Some(c_buf), 0);
+ }
+ }
enc.set_buffer(3, Some(args.d), 0);
// Params
- let tiles_n = (n + bn - 1) / bn;
- let tiles_m = (m + bm - 1) / bm;
- // Swizzle: small tm -> no swizzle, otherwise simple 2-way.
- let swizzle_log = if tiles_m <= 3 { 0 } else { 1 };
-
- let tile = 1 << swizzle_log;
- let tm_swizzled = (tiles_m + tile - 1) / tile;
- let tn_swizzled = tiles_n * tile;
+ let tiles_n = (n + tile.block_cols - 1) / tile.block_cols;
+ let tiles_m = (m + tile.block_rows - 1) / tile.block_rows;
+ let swizzle_log = tile.swizzle_log2;
+
+ let tile_swizzle = 1 << swizzle_log;
+ let tm_swizzled = (tiles_m + tile_swizzle - 1) / tile_swizzle;
+ let tn_swizzled = tiles_n * tile_swizzle;
+ let elements_per_matrix_a = (args.batch as i64) * (args.lda as i64);
+ let elements_per_matrix_b = if self.rhs_is_transposed {
+ (args.output_dim as i64) * (args.ldb as i64)
+ } else {
+ (args.input_dim as i64) * (args.ldb as i64)
+ };
+ let elements_per_matrix_d = (args.batch as i64) * (args.ldd as i64);
+ let batch_ndim = 1;
let params = GEMMParams {
batch: m,
output_dim: n,
@@ -429,11 +431,12 @@ impl MatmulKernel {
// swizzled separately via tn_swizzled/tm_swizzled.
tiles_n,
tiles_m,
- batch_stride_a: (args.lda as i64) * (k as i64),
- batch_stride_b: (args.ldb as i64) * (n as i64),
- batch_stride_d: (args.ldd as i64) * (n as i64),
+ batch_stride_a: elements_per_matrix_a,
+ batch_stride_b: elements_per_matrix_b,
+ batch_stride_d: elements_per_matrix_d,
swizzle_log,
- gemm_k_iterations_aligned: k / bk,
+ gemm_k_iterations_aligned: k / tile.block_depth,
+ batch_ndim,
};
enc.set_bytes(
4,
@@ -441,8 +444,31 @@ impl MatmulKernel {
&params as *const GEMMParams as *const _,
);
+ if use_out_source {
+ let ldc = args.ldd;
+ let fdc = 1;
+ let batch_stride_c = if args.batch_count > 1 {
+ (args.ldd as i64) * (args.output_dim as i64)
+ } else {
+ 0
+ };
+ let addmm_params = GEMMAddMMParams {
+ ldc,
+ fdc,
+ batch_stride_c,
+ alpha: args.alpha,
+ beta: args.beta,
+ };
+ enc.set_bytes(
+ 5,
+ std::mem::size_of::<GEMMAddMMParams>() as u64,
+ &addmm_params as *const GEMMAddMMParams as *const _,
+ );
+ }
+
// Threadgroup sizing
- let threads_per_tg = MTLSize::new(32, wn, wm);
+ let threads_per_tg =
+ MTLSize::new(32, tile.warps_per_col, tile.warps_per_row);
let tg_x = tn_swizzled as u64;
let tg_y = tm_swizzled as u64;
let tg_z = args.batch_count as u64;
@@ -460,15 +486,15 @@ impl MatmulKernel {
self.apply_batch_collapse(&mut args);
// Try GEMV fast path for decode shapes.
- if self.maybe_use_gemv(mtl, enc, args)? {
+ if self.maybe_use_gemv(mtl, enc, &args)? {
return Ok(());
}
// Try Split-K for small M*N and large K.
- if self.maybe_use_splitk(mtl, enc, args)? {
+ if self.maybe_use_splitk(mtl, enc, &args)? {
return Ok(());
}
- self.encode_gemm(mtl, enc, args)
+ self.encode_gemm(mtl, enc, &args)
}
pub fn encode_with_bias(
@@ -480,17 +506,17 @@ impl MatmulKernel {
) -> Result<(), MTLError> {
self.apply_batch_collapse(&mut args);
- if self.maybe_use_gemv_with_bias(mtl, enc, args, bias)? {
+ if self.maybe_use_gemv_with_bias(mtl, enc, &args, bias)? {
return Ok(());
}
- if self.maybe_use_splitk(mtl, enc, args)? {
- self.apply_bias_add(mtl, enc, args, bias)?;
+ if self.maybe_use_splitk(mtl, enc, &args)? {
+ self.apply_bias_add(mtl, enc, &args, bias)?;
return Ok(());
}
- self.encode_gemm(mtl, enc, args)?;
- self.apply_bias_add(mtl, enc, args, bias)?;
+ self.encode_gemm(mtl, enc, &args)?;
+ self.apply_bias_add(mtl, enc, &args, bias)?;
Ok(())
}
@@ -498,7 +524,7 @@ impl MatmulKernel {
&mut self,
mtl: &MTLContext,
enc: &ComputeCommandEncoderRef,
- args: MatmulArguments,
+ args: &MatmulArguments,
bias: &MTLBuffer,
) -> Result<(), MTLError> {
let m = args.batch as usize;
@@ -512,19 +538,12 @@ impl MatmulKernel {
if self.bias_add.is_none() {
self.bias_add = Some(TensorAddBias::new(
mtl,
- KernelDataType::from(self.dt),
+ KernelDataType::from(self.data_type),
)?);
}
let bias_add = self.bias_add.as_ref().unwrap();
- bias_add.encode_with_encoder(
- args.d,
- bias,
- args.d,
- n,
- total_len,
- enc,
- None,
- );
+ bias_add
+ .encode_with_encoder(args.d, bias, args.d, n, total_len, enc, None);
Ok(())
}
@@ -532,14 +551,14 @@ impl MatmulKernel {
&self,
args: &mut MatmulArguments,
) {
- if self.transpose_a {
+ if self.lhs_is_transposed {
return;
}
if args.batch_count <= 1 {
return;
}
// Collapse batch_count into M when A is contiguous and B is broadcast.
- if args.lda == args.input_dim && self.transpose_b {
+ if args.lda == args.input_dim && self.rhs_is_transposed {
args.batch *= args.batch_count;
args.batch_count = 1;
}
diff --git a/crates/uzu/src/backends/metal/kernel/matmul/matmul.metal b/crates/uzu/src/backends/metal/kernel/matmul/matmul.metal
index aea205633..68226ae56 100644
--- a/crates/uzu/src/backends/metal/kernel/matmul/matmul.metal
+++ b/crates/uzu/src/backends/metal/kernel/matmul/matmul.metal
@@ -477,13 +477,15 @@ template <
// 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, 32, 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) \
- /* 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)
+ instantiate_gemm_transpose_helper(type_name, element_type, 128, 128, 32, 2, 2) \
+ /* Small-gemm variant for complex/float32 */ \
+ instantiate_gemm_transpose_helper(type_name, element_type, 64, 32, 8, 4, 1)
// clang-format on
// Instantiate for float16, bfloat16, and float32
diff --git a/crates/uzu/src/backends/metal/kernel/matmul/pipeline.rs b/crates/uzu/src/backends/metal/kernel/matmul/pipeline.rs
index 801ce989d..26c0062ad 100644
--- a/crates/uzu/src/backends/metal/kernel/matmul/pipeline.rs
+++ b/crates/uzu/src/backends/metal/kernel/matmul/pipeline.rs
@@ -4,4 +4,7 @@ pub(super) struct PipelineKey {
pub align_m: bool,
pub align_n: bool,
pub align_k: bool,
+ pub has_batch: bool,
+ pub use_out_source: bool,
+ pub do_axpby: bool,
}
diff --git a/crates/uzu/src/backends/metal/kernel/matmul/shared_types.h b/crates/uzu/src/backends/metal/kernel/matmul/shared_types.h
index aea7226cc..1cb70950d 100644
--- a/crates/uzu/src/backends/metal/kernel/matmul/shared_types.h
+++ b/crates/uzu/src/backends/metal/kernel/matmul/shared_types.h
@@ -46,6 +46,8 @@ struct GEMMParams {
int swizzle_log;
int gemm_k_iterations_aligned;
+
+ int batch_ndim;
};
/// Parameters for addmm (alpha * A @ B + beta * C) operations
diff --git a/crates/uzu/src/backends/metal/kernel/matmul/shared_types.rs b/crates/uzu/src/backends/metal/kernel/matmul/shared_types.rs
index 6b420fc0f..4dddb9938 100644
--- a/crates/uzu/src/backends/metal/kernel/matmul/shared_types.rs
+++ b/crates/uzu/src/backends/metal/kernel/matmul/shared_types.rs
@@ -20,10 +20,11 @@ pub struct GEMMParams {
pub batch_stride_d: i64,
pub swizzle_log: ::core::ffi::c_int,
pub gemm_k_iterations_aligned: ::core::ffi::c_int,
+ pub batch_ndim: ::core::ffi::c_int,
}
#[allow(clippy::unnecessary_operation, clippy::identity_op)]
const _: () = {
- ["Size of GEMMParams"][::core::mem::size_of::<GEMMParams>() - 64usize];
+ ["Size of GEMMParams"][::core::mem::size_of::<GEMMParams>() - 72usize];
["Alignment of GEMMParams"][::core::mem::align_of::<GEMMParams>() - 8usize];
["Offset of field: GEMMParams::batch"]
[::core::mem::offset_of!(GEMMParams, batch) - 0usize];
@@ -53,6 +54,8 @@ const _: () = {
GEMMParams,
gemm_k_iterations_aligned
) - 60usize];
+ ["Offset of field: GEMMParams::batch_ndim"]
+ [::core::mem::offset_of!(GEMMParams, batch_ndim) - 64usize];
};
#[doc = " Parameters for addmm (alpha * A @ B + beta * C) operations"]
#[repr(C)]
diff --git a/crates/uzu/src/backends/metal/kernel/matmul/splitk.metal b/crates/uzu/src/backends/metal/kernel/matmul/splitk.metal
index d79061915..3a2de4d52 100644
--- a/crates/uzu/src/backends/metal/kernel/matmul/splitk.metal
+++ b/crates/uzu/src/backends/metal/kernel/matmul/splitk.metal
@@ -231,11 +231,43 @@ template <typename OutputType, typename AccumulatorType>
output[0] = OutputType(sum);
}
+template <typename OutputType, typename AccumulatorType>
+[[kernel]] void splitk_accumulate_axpby(
+ 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)]],
+ const device OutputType* bias_source [[buffer(5)]],
+ constant int& ldc [[buffer(6)]],
+ constant int& fdc [[buffer(7)]],
+ constant float& alpha [[buffer(8)]],
+ constant float& beta [[buffer(9)]],
+ uint2 thread_position [[thread_position_in_grid]]
+) {
+ const size_t col = thread_position.x;
+ const size_t row = thread_position.y;
+
+ bias_source += col * size_t(fdc) + row * size_t(ldc);
+ output += col + row * size_t(leading_dim_output);
+ partitioned_accumulator += col + row * size_t(leading_dim_output);
+
+ 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(alpha * sum + beta * AccumulatorType(*bias_source));
+}
+
///////////////////////////////////////////////////////////////////////////////
// Kernel Instantiation
///////////////////////////////////////////////////////////////////////////////
-#define INSTANTIATE_SPLITK_PARTIAL( \
+#define INSTANTIATE_SPLITK_PARTIAL_ALIGNED( \
transpose_name, \
transpose_a, \
transpose_b, \
@@ -245,12 +277,14 @@ template <typename OutputType, typename AccumulatorType>
tile_cols, \
tile_depth, \
warps_row, \
- warps_col \
+ warps_col, \
+ mn_aligned, \
+ k_aligned \
) \
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 \
+ "_mn" #mn_aligned "_k" #k_aligned)]][[kernel]] void \
splitk_partial_gemm< \
input_type, \
float, \
@@ -261,8 +295,8 @@ template <typename OutputType, typename AccumulatorType>
warps_col, \
transpose_a, \
transpose_b, \
- false, \
- false>( \
+ mn_aligned, \
+ k_aligned>( \
const device input_type* input_a [[buffer(0)]], \
const device input_type* input_b [[buffer(1)]], \
device float* accumulator [[buffer(2)]], \
@@ -273,6 +307,71 @@ template <typename OutputType, typename AccumulatorType>
uint3 thread_id [[thread_position_in_threadgroup]] \
);
+#define INSTANTIATE_SPLITK_PARTIAL( \
+ transpose_name, \
+ transpose_a, \
+ transpose_b, \
+ type_name, \
+ input_type, \
+ tile_rows, \
+ tile_cols, \
+ tile_depth, \
+ warps_row, \
+ warps_col \
+) \
+ INSTANTIATE_SPLITK_PARTIAL_ALIGNED( \
+ transpose_name, \
+ transpose_a, \
+ transpose_b, \
+ type_name, \
+ input_type, \
+ tile_rows, \
+ tile_cols, \
+ tile_depth, \
+ warps_row, \
+ warps_col, \
+ 0, \
+ 0) \
+ INSTANTIATE_SPLITK_PARTIAL_ALIGNED( \
+ transpose_name, \
+ transpose_a, \
+ transpose_b, \
+ type_name, \
+ input_type, \
+ tile_rows, \
+ tile_cols, \
+ tile_depth, \
+ warps_row, \
+ warps_col, \
+ 1, \
+ 0) \
+ INSTANTIATE_SPLITK_PARTIAL_ALIGNED( \
+ transpose_name, \
+ transpose_a, \
+ transpose_b, \
+ type_name, \
+ input_type, \
+ tile_rows, \
+ tile_cols, \
+ tile_depth, \
+ warps_row, \
+ warps_col, \
+ 0, \
+ 1) \
+ INSTANTIATE_SPLITK_PARTIAL_ALIGNED( \
+ transpose_name, \
+ transpose_a, \
+ transpose_b, \
+ type_name, \
+ input_type, \
+ tile_rows, \
+ tile_cols, \
+ tile_depth, \
+ warps_row, \
+ warps_col, \
+ 1, \
+ 1)
+
#define INSTANTIATE_SPLITK_TRANSPOSE_HELPER( \
type_name, \
input_type, \
@@ -350,6 +449,20 @@ INSTANTIATE_SPLITK_SHAPES_HELPER(f32, float)
constant int& output_elements_per_partition [[buffer(3)]], \
constant int& leading_dim_output [[buffer(4)]], \
uint2 thread_position [[thread_position_in_grid]] \
+ ); \
+ template [[host_name("splitk_accum_" #type_name "_axpby")]] [[kernel]] void \
+ splitk_accumulate_axpby<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)]], \
+ const device output_type* bias_source [[buffer(5)]], \
+ constant int& ldc [[buffer(6)]], \
+ constant int& fdc [[buffer(7)]], \
+ constant float& alpha [[buffer(8)]], \
+ constant float& beta [[buffer(9)]], \
+ uint2 thread_position [[thread_position_in_grid]] \
);
INSTANTIATE_SPLITK_ACCUM(f16, half)
diff --git a/crates/uzu/src/backends/metal/kernel/matmul/splitk.rs b/crates/uzu/src/backends/metal/kernel/matmul/splitk.rs
index 39858dc25..13aecacba 100644
--- a/crates/uzu/src/backends/metal/kernel/matmul/splitk.rs
+++ b/crates/uzu/src/backends/metal/kernel/matmul/splitk.rs
@@ -5,8 +5,7 @@ use metal::{
MTLSize,
};
-use super::arguments::MatmulArguments;
-use super::shared_types::SplitKGEMMParams;
+use super::{arguments::MatmulArguments, shared_types::SplitKGEMMParams};
use crate::{
DataType,
backends::metal::{MTLContext, MTLError},
@@ -24,6 +23,8 @@ struct TileConfig {
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct PartialKernelKey {
tile_config: TileConfig,
+ mn_aligned: bool,
+ k_aligned: bool,
}
pub struct SplitKGemm {
@@ -73,18 +74,22 @@ impl SplitKGemm {
fn partial_kernel_name(
&self,
config: &TileConfig,
+ mn_aligned: bool,
+ k_aligned: bool,
) -> Result<String, MTLError> {
let type_suffix = self.type_suffix()?;
let transpose_suffix = self.transpose_suffix();
Ok(format!(
- "splitk_partial_{}_{}_tm{}_tn{}_tk{}_wm{}_wn{}",
+ "splitk_partial_{}_{}_tm{}_tn{}_tk{}_wm{}_wn{}_mn{}_k{}",
transpose_suffix,
type_suffix,
config.tile_rows,
config.tile_cols,
config.tile_depth,
config.warps_per_row,
- config.warps_per_col
+ config.warps_per_col,
+ mn_aligned as u8,
+ k_aligned as u8,
))
}
@@ -97,12 +102,17 @@ impl SplitKGemm {
&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)?;
+ 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);
}
@@ -125,8 +135,16 @@ impl SplitKGemm {
m: i32,
n: i32,
) -> TileConfig {
- let tile_rows = if m < 40 { 16 } else { 32 };
- let tile_cols = if n < 40 { 16 } else { 32 };
+ let tile_rows = if m < 40 {
+ 16
+ } else {
+ 32
+ };
+ let tile_cols = if n < 40 {
+ 16
+ } else {
+ 32
+ };
TileConfig {
tile_rows,
tile_cols,
@@ -171,7 +189,7 @@ impl SplitKGemm {
&mut self,
mtl: &MTLContext,
enc: &ComputeCommandEncoderRef,
- args: MatmulArguments,
+ args: &MatmulArguments,
) -> Result<(), MTLError> {
let m = args.batch;
let n = args.output_dim;
@@ -179,12 +197,18 @@ impl SplitKGemm {
let tile_config = Self::select_tile_config(m, n);
let partition_count = Self::compute_partition_count(k);
+ let mn_aligned = (m % tile_config.tile_rows) == 0
+ && (n % 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 = (n + tile_config.tile_cols - 1) / tile_config.tile_cols;
+ 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 k_elements_per_partition =
+ gemm_k_iterations * tile_config.tile_depth;
let output_elements_per_partition = m * n;
let accumulator_element_count =
@@ -211,7 +235,8 @@ impl SplitKGemm {
gemm_k_iterations_aligned: gemm_k_iterations,
};
- let partial_ps = self.get_partial_pipeline(mtl, tile_config)?;
+ 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.a), 0);
@@ -247,7 +272,8 @@ impl SplitKGemm {
enc.set_bytes(
3,
4,
- &output_elements_per_partition as *const i32 as *const std::ffi::c_void,
+ &output_elements_per_partition as *const i32
+ as *const std::ffi::c_void,
);
enc.set_bytes(
4,
@@ -256,12 +282,12 @@ impl SplitKGemm {
);
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,
+ 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_threads(accum_total_threads, accum_threads_per_threadgroup);
Ok(())
}
diff --git a/crates/uzu/src/backends/metal/kernel/ssm/split_inproj.rs b/crates/uzu/src/backends/metal/kernel/ssm/split_inproj.rs
index 37ad2baf3..28ae18483 100644
--- a/crates/uzu/src/backends/metal/kernel/ssm/split_inproj.rs
+++ b/crates/uzu/src/backends/metal/kernel/ssm/split_inproj.rs
@@ -1,8 +1,7 @@
use metal::{Buffer as MTLBuffer, ComputeCommandEncoderRef, MTLSize};
-use crate::backends::metal::{KernelDataType, MTLContext};
-
use super::{SSMKernelError, fn_suffix};
+use crate::backends::metal::{KernelDataType, MTLContext};
pub struct SplitInProjKernel {
pipeline: metal::ComputePipelineState,
diff --git a/crates/uzu/src/language_model/mod.rs b/crates/uzu/src/language_model/mod.rs
index 9a1fcc735..2366b34de 100644
--- a/crates/uzu/src/language_model/mod.rs
+++ b/crates/uzu/src/language_model/mod.rs
@@ -8,5 +8,6 @@ pub mod sampler;
pub mod tasks;
// Re-export main types
-pub use crate::backends::metal::LanguageModelGeneratorContext;
pub use language_model_generator::LanguageModelGenerator;
+
+pub use crate::backends::metal::LanguageModelGeneratorContext;
diff --git a/crates/uzu/src/prelude.rs b/crates/uzu/src/prelude.rs
index c9ce4126a..405d00400 100644
--- a/crates/uzu/src/prelude.rs
+++ b/crates/uzu/src/prelude.rs
@@ -5,7 +5,6 @@
// Constants & Utilities
// Session Core
-pub use crate::session::ChatSession;
// Session Config
pub use crate::session::config::{DecodingConfig, RunConfig, SpeculatorConfig};
// Session Parameters
@@ -21,6 +20,8 @@ pub use crate::session::types::{
// Speculators
pub use crate::speculators::speculator::Speculator;
pub use crate::{
- VERSION, session::ClassificationSession,
- speculators::empty_speculator::EmptySpeculator, storage_path,
+ VERSION,
+ session::{ChatSession, ClassificationSession},
+ speculators::empty_speculator::EmptySpeculator,
+ storage_path,
};
diff --git a/crates/uzu/src/speculators/empty_speculator.rs b/crates/uzu/src/speculators/empty_speculator.rs
index cc680a085..bc3d74d43 100644
--- a/crates/uzu/src/speculators/empty_speculator.rs
+++ b/crates/uzu/src/speculators/empty_speculator.rs
@@ -1,6 +1,7 @@
-use super::speculator::Speculator;
use std::collections::HashMap;
+use super::speculator::Speculator;
+
#[derive(Default, Debug, Clone, Copy)]
pub struct EmptySpeculator;
diff --git a/crates/uzu/tests/safetensors_metadata_test.rs b/crates/uzu/tests/safetensors_metadata_test.rs
index 60f5361f2..289c85261 100644
--- a/crates/uzu/tests/safetensors_metadata_test.rs
+++ b/crates/uzu/tests/safetensors_metadata_test.rs
@@ -1,6 +1,7 @@
mod common;
use std::fs::File;
+
use uzu::parameters::read_safetensors_metadata as read_metadata;
#[test]