A high-performance inference engine for AI models
wip
eugene1429d539ae9c
diff --git a/crates/uzu/examples/matmul_benchmark.rs b/crates/uzu/examples/matmul_benchmark.rsindex 671c5de27..9790c354f 100644--- a/crates/uzu/examples/matmul_benchmark.rs+++ b/crates/uzu/examples/matmul_benchmark.rs@@ -370,8 +370,9 @@ fn main() {let _ = std::io::stdout().flush();let result = run_benchmark(&ctx, name, *m, *k, *n, warmup, iters);- let speedup = result.metal_ms / result.mpsgraph_ms;- let speedup_str = if speedup > 1.0 {+ // Speedup = MPS time / Metal time. >1.0 means Metal is faster.+ let speedup = result.mpsgraph_ms / result.metal_ms;+ let speedup_str = if speedup >= 1.0 {format!("{:.2}x ✓", speedup)} else {format!("{:.2}x", speedup)@@ -395,6 +396,7 @@ fn main() {}println!("\n=== Summary ===");- println!("Speedup > 1.0 means MPSGraph is faster");- println!("Speedup < 1.0 means Metal GEMM is faster");+ println!("Speedup = MPS time / Metal time");+ println!("Speedup > 1.0 means Metal is faster ✓");+ println!("Speedup < 1.0 means MPS is faster");}diff --git a/crates/uzu/src/backends/metal/kernel/matmul/gemv.metal b/crates/uzu/src/backends/metal/kernel/matmul/gemv.metalindex 1b2ff8cc5..d1ee2ea1f 100644--- a/crates/uzu/src/backends/metal/kernel/matmul/gemv.metal+++ b/crates/uzu/src/backends/metal/kernel/matmul/gemv.metal@@ -1,8 +1,263 @@+// SPDX-License-Identifier: MIT+// Optimized GEMV kernels:+// - Multi-row output per simdgroup with input vector reuse+// - Vectorized loads (4 elements per thread)+// - simd_sum for fast K-dimension reduction+// - Register-only (no threadgroup memory)+//+// Two variants:+// - gemv_fast_*: 4 rows per simdgroup, best for large K (≥4096)+// - gemv_wide_*: 16 rows per simdgroup, best for small K with large N (MLP up pattern)+#include <metal_stdlib>using namespace metal;-// Tiled GEMV with vector blocking in threadgroup memory.-// Signature matches existing Rust dispatch (no bias/axpby).+// Elements loaded per thread per K iteration (4 elements vectorized)+#define ELEMS_PER_THREAD 4++// Templated GEMV implementation with configurable rows per simdgroup+// y = A * x where A is [N, K] row-major+template <typename T, typename AccT, int ROWS>+METAL_FUNC void gemv_impl(+ const device T* __restrict A,+ const device T* __restrict x,+ device T* __restrict y,+ const int K,+ const int N,+ const int lda,+ const int batch_idx,+ const int batch_stride_x,+ const int batch_stride_y,+ uint row_base,+ uint simd_lid) {++ // Block size in K dimension: 32 threads * 4 elements = 128+ constexpr int BLOCK_K = 32 * ELEMS_PER_THREAD;++ // Position pointers for this batch+ x += batch_idx * batch_stride_x;+ y += batch_idx * batch_stride_y;++ // Bounds check+ if (row_base >= static_cast<uint>(N)) {+ return;+ }++ const int rows_to_compute = min(ROWS, N - static_cast<int>(row_base));++ // Accumulators in registers+ AccT result[ROWS];+ #pragma unroll(ROWS)+ for (int r = 0; r < ROWS; ++r) {+ result[r] = AccT(0);+ }++ // Input vector cache+ AccT x_cache[ELEMS_PER_THREAD];++ // Weight row pointers+ const device T* row_ptrs[ROWS];+ #pragma unroll(ROWS)+ for (int r = 0; r < ROWS; ++r) {+ row_ptrs[r] = A + (row_base + r) * lda;+ }++ // Main K loop+ int k = 0;+ for (; k + BLOCK_K <= K; k += BLOCK_K) {+ const int thread_k = k + simd_lid * ELEMS_PER_THREAD;++ // Load input vector chunk+ #pragma unroll(ELEMS_PER_THREAD)+ for (int e = 0; e < ELEMS_PER_THREAD; ++e) {+ x_cache[e] = static_cast<AccT>(x[thread_k + e]);+ }++ // Dot product for each row+ #pragma unroll(ROWS)+ for (int r = 0; r < ROWS; ++r) {+ AccT dot = 0;+ #pragma unroll(ELEMS_PER_THREAD)+ for (int e = 0; e < ELEMS_PER_THREAD; ++e) {+ dot += x_cache[e] * static_cast<AccT>(row_ptrs[r][thread_k + e]);+ }+ result[r] += dot;+ }+ }++ // Handle leftover K elements+ if (k < K) {+ const int thread_k = k + simd_lid * ELEMS_PER_THREAD;+ const int remaining = K - k;++ #pragma unroll(ELEMS_PER_THREAD)+ for (int e = 0; e < ELEMS_PER_THREAD; ++e) {+ const int idx = simd_lid * ELEMS_PER_THREAD + e;+ x_cache[e] = (idx < remaining) ? static_cast<AccT>(x[thread_k + e]) : AccT(0);+ }++ #pragma unroll(ROWS)+ for (int r = 0; r < ROWS; ++r) {+ AccT dot = 0;+ #pragma unroll(ELEMS_PER_THREAD)+ for (int e = 0; e < ELEMS_PER_THREAD; ++e) {+ const int idx = simd_lid * ELEMS_PER_THREAD + e;+ if (idx < remaining) {+ dot += x_cache[e] * static_cast<AccT>(row_ptrs[r][thread_k + e]);+ }+ }+ result[r] += dot;+ }+ }++ // Reduce across simdgroup+ #pragma unroll(ROWS)+ for (int r = 0; r < ROWS; ++r) {+ result[r] = simd_sum(result[r]);+ }++ // Write output+ if (simd_lid == 0) {+ #pragma unroll(ROWS)+ for (int r = 0; r < rows_to_compute; ++r) {+ y[row_base + r] = static_cast<T>(result[r]);+ }+ }+}++// Standard GEMV: 4 rows per simdgroup (best for large K)+#define DECL_GEMV_FAST(NAME, TYPE, ACC) \+ [[kernel]] void NAME( \+ const device TYPE* A [[buffer(0)]], \+ const device TYPE* x [[buffer(1)]], \+ device TYPE* y [[buffer(2)]], \+ constant int& K [[buffer(3)]], \+ constant int& N [[buffer(4)]], \+ constant int& lda [[buffer(5)]], \+ constant int& batch_stride_x [[buffer(6)]], \+ constant int& batch_stride_y [[buffer(7)]], \+ uint3 tgid [[threadgroup_position_in_grid]], \+ uint simd_lid [[thread_index_in_simdgroup]]) { \+ constexpr int ROWS = 4; \+ const uint row_base = tgid.x * ROWS; \+ gemv_impl<TYPE, ACC, ROWS>( \+ A, x, y, K, N, lda, tgid.z, batch_stride_x, batch_stride_y, \+ row_base, simd_lid); \+ }++// Wide GEMV: 8 rows per simdgroup (balanced for small K, large N)+#define DECL_GEMV_WIDE(NAME, TYPE, ACC) \+ [[kernel]] void NAME( \+ const device TYPE* A [[buffer(0)]], \+ const device TYPE* x [[buffer(1)]], \+ device TYPE* y [[buffer(2)]], \+ constant int& K [[buffer(3)]], \+ constant int& N [[buffer(4)]], \+ constant int& lda [[buffer(5)]], \+ constant int& batch_stride_x [[buffer(6)]], \+ constant int& batch_stride_y [[buffer(7)]], \+ uint3 tgid [[threadgroup_position_in_grid]], \+ uint simd_lid [[thread_index_in_simdgroup]]) { \+ constexpr int ROWS = 8; \+ const uint row_base = tgid.x * ROWS; \+ gemv_impl<TYPE, ACC, ROWS>( \+ A, x, y, K, N, lda, tgid.z, batch_stride_x, batch_stride_y, \+ row_base, simd_lid); \+ }++// Instantiate standard (4-row) kernels+DECL_GEMV_FAST(gemv_fast_f16, half, float)+DECL_GEMV_FAST(gemv_fast_bf16, bfloat, float)+DECL_GEMV_FAST(gemv_fast_f32, float, float)++// Instantiate wide (8-row) kernels+DECL_GEMV_WIDE(gemv_wide_f16, half, float)+DECL_GEMV_WIDE(gemv_wide_bf16, bfloat, float)+DECL_GEMV_WIDE(gemv_wide_f32, float, float)++// =============================================================================+// Parallel GEMV: Multiple simdgroups per threadgroup with shared input vector+// Best for small K with large N (reduces threadgroup count, amortizes overhead)+// =============================================================================++template <typename T, typename AccT, int SIMDGROUPS_PER_TG, int BK>+[[kernel, max_total_threads_per_threadgroup(SIMDGROUPS_PER_TG * 32)]]+void gemv_parallel_impl(+ const device T* __restrict A [[buffer(0)]],+ const device T* __restrict x [[buffer(1)]],+ device T* __restrict y [[buffer(2)]],+ constant int& K [[buffer(3)]],+ constant int& N [[buffer(4)]],+ constant int& lda [[buffer(5)]],+ constant int& batch_stride_x [[buffer(6)]],+ constant int& batch_stride_y [[buffer(7)]],+ uint3 tgid [[threadgroup_position_in_grid]],+ uint simd_gid [[simdgroup_index_in_threadgroup]],+ uint simd_lid [[thread_index_in_simdgroup]],+ uint tid [[thread_index_in_threadgroup]]) {++ // Shared memory for input vector tile+ threadgroup AccT x_shared[BK];++ // Position pointers for this batch+ const int batch_idx = tgid.z;+ x += batch_idx * batch_stride_x;+ y += batch_idx * batch_stride_y;++ // Each simdgroup computes one output row+ const uint row = tgid.x * SIMDGROUPS_PER_TG + simd_gid;+ if (row >= static_cast<uint>(N)) {+ return;+ }++ const device T* row_ptr = A + row * lda;+ AccT acc = AccT(0);++ // Process K in tiles+ for (int k_start = 0; k_start < K; k_start += BK) {+ const int remaining = K - k_start;+ const int tile_k = remaining < BK ? remaining : BK;++ // Cooperative load of input vector tile into shared memory+ for (int idx = tid; idx < tile_k; idx += SIMDGROUPS_PER_TG * 32) {+ x_shared[idx] = static_cast<AccT>(x[k_start + idx]);+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);++ // Each thread in simdgroup processes part of the tile+ for (int idx = simd_lid; idx < tile_k; idx += 32) {+ acc += static_cast<AccT>(row_ptr[k_start + idx]) * x_shared[idx];+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);+ }++ // Reduce within simdgroup+ acc = simd_sum(acc);++ // Write output+ if (simd_lid == 0) {+ y[row] = static_cast<T>(acc);+ }+}++// Parallel kernels: 32 simdgroups per threadgroup, BK=1024 for maximum occupancy+template [[host_name("gemv_parallel_f16")]] kernel void gemv_parallel_impl<half, float, 32, 1024>(+ const device half*, const device half*, device half*,+ constant int&, constant int&, constant int&, constant int&, constant int&,+ uint3, uint, uint, uint);+template [[host_name("gemv_parallel_bf16")]] kernel void gemv_parallel_impl<bfloat, float, 32, 1024>(+ const device bfloat*, const device bfloat*, device bfloat*,+ constant int&, constant int&, constant int&, constant int&, constant int&,+ uint3, uint, uint, uint);+template [[host_name("gemv_parallel_f32")]] kernel void gemv_parallel_impl<float, float, 32, 1024>(+ const device float*, const device float*, device float*,+ constant int&, constant int&, constant int&, constant int&, constant int&,+ uint3, uint, uint, uint);++// =============================================================================+// Legacy kernels for backwards compatibility (used by existing Rust dispatcher)+// =============================================================================+template <typename T, typename AccT, ushort ROWS_PER_TG, ushort BK>METAL_FUNC void gemv_impl_tiled(const device T* __restrict matrix [[buffer(0)]],@@ -34,25 +289,21 @@ METAL_FUNC void gemv_impl_tiled(AccT acc = static_cast<AccT>(0);- // Cooperative load of vector tile into threadgroup memory.for (uint k_block = 0; k_block < k; k_block += BK) {const uint remaining = k - k_block;const uint tile_elems = remaining < BK ? remaining : BK;- // Each thread loads at most one element of the vector tile.if (tid < tile_elems && tid < TG_THREADS) {vec_tile[tid] = static_cast<AccT>(vec_ptr[k_block + tid]);}threadgroup_barrier(mem_flags::mem_threadgroup);- // Accumulate over this tile.for (uint idx = simd_lid; idx < tile_elems; idx += 32) {acc += static_cast<AccT>(row_ptr[k_block + idx]) * vec_tile[idx];}threadgroup_barrier(mem_flags::mem_threadgroup);}- // Reduce within simdgroup.for (ushort offset = 16; offset > 0; offset >>= 1) {acc += simd_shuffle_down(acc, offset);}@@ -62,219 +313,32 @@ METAL_FUNC void gemv_impl_tiled(}}-#define DECL_GEMV(NAME, TYPE, ACC, ROWS, BK) \- [[kernel, max_total_threads_per_threadgroup(ROWS * 32)]] void NAME( \- const device TYPE* matrix [[buffer(0)]], \- const device TYPE* vector [[buffer(1)]], \- device TYPE* output [[buffer(2)]], \- constant uint& k [[buffer(3)]], \- constant uint& n [[buffer(4)]], \- constant uint& ldb [[buffer(5)]], \- constant uint& lda [[buffer(6)]], \- constant uint& ldd [[buffer(7)]], \- uint3 tgid [[threadgroup_position_in_grid]], \- uint simd_gid [[simdgroup_index_in_threadgroup]], \- uint simd_lid [[thread_index_in_simdgroup]], \- uint tid [[thread_index_in_threadgroup]]) { \- threadgroup ACC vec_tile[BK]; \- gemv_impl_tiled<TYPE, ACC, ROWS, BK>( \- matrix, vector, output, k, n, ldb, lda, ldd, \- tgid, simd_gid, simd_lid, tid, vec_tile); \+#define DECL_GEMV_LEGACY(NAME, TYPE, ACC, ROWS, BK) \+ [[kernel, max_total_threads_per_threadgroup(ROWS * 32)]] void NAME( \+ const device TYPE* matrix [[buffer(0)]], \+ const device TYPE* vector [[buffer(1)]], \+ device TYPE* output [[buffer(2)]], \+ constant uint& k [[buffer(3)]], \+ constant uint& n [[buffer(4)]], \+ constant uint& ldb [[buffer(5)]], \+ constant uint& lda [[buffer(6)]], \+ constant uint& ldd [[buffer(7)]], \+ uint3 tgid [[threadgroup_position_in_grid]], \+ uint simd_gid [[simdgroup_index_in_threadgroup]], \+ uint simd_lid [[thread_index_in_simdgroup]], \+ uint tid [[thread_index_in_threadgroup]]) { \+ threadgroup ACC vec_tile[BK]; \+ gemv_impl_tiled<TYPE, ACC, ROWS, BK>( \+ matrix, vector, output, k, n, ldb, lda, ldd, \+ tgid, simd_gid, simd_lid, tid, vec_tile); \}-// half variants-DECL_GEMV(gemv_f16_rows2, half, float, 2, 128)-DECL_GEMV(gemv_f16_rows4, half, float, 4, 128)-DECL_GEMV(gemv_f16_rows8, half, float, 8, 128)--// bfloat16 variants-DECL_GEMV(gemv_bf16_rows2, bfloat, float, 2, 128)-DECL_GEMV(gemv_bf16_rows4, bfloat, float, 4, 128)-DECL_GEMV(gemv_bf16_rows8, bfloat, float, 8, 128)-#include <metal_stdlib>-using namespace metal;--#define UZU_PRAGMA_UNROLL _Pragma("unroll")--// Vectorized GEMV without bias/axpby; compact signature.-template <- typename T,- const int BM,- const int BN,- const int SM,- const int SN,- const int TM,- const int TN>-struct GEMVKernel {- enum : int {- threadsM = BM * SM,- threadsN = BN * SN,- blockM = threadsM * TM,- blockN = threadsN * TN,- };-- static_assert(SM * SN == 32, "simdgroup must be 32 threads");- static_assert(SN == 4 || SN == 8 || SN == 16 || SN == 32, "SN must divide 32");-- template <typename U = T>- static METAL_FUNC void load_safe(- const device T* src,- thread U dst[TN],- const int src_offset,- const int src_size) {- if (src_offset + TN <= src_size) {- UZU_PRAGMA_UNROLL- for (int tn = 0; tn < TN; tn++) {- dst[tn] = static_cast<U>(src[src_offset + tn]);- }- } else {- UZU_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);- }- }- }-- static METAL_FUNC void run(- const device T* mat [[buffer(0)]],- const device T* in_vec [[buffer(1)]],- device T* out_vec [[buffer(2)]],- const constant int& in_vec_size [[buffer(3)]],- const constant int& out_vec_size [[buffer(4)]],- const constant int& matrix_ld [[buffer(5)]],- threadgroup float* 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;-- thread float result[TM] = {0};- thread T inter[TN];- thread float v_coeff[TN];-- const int thrM = SN != 32 ? simd_lid / SN : 0;- const int thrN = SN != 32 ? simd_lid % SN : int(simd_lid);-- const int sgN = BN != 1 ? (simd_gid % BN) : 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 bm = (simdM + thrM) * TM;- int bn = (simdN + thrN) * TN;-- int out_row = tid.x * blockM + bm;- if (out_row >= out_vec_size) {- return;- }- out_row = out_row + TM <= out_vec_size ? out_row : out_vec_size - TM;+// Legacy half variants+DECL_GEMV_LEGACY(gemv_f16_rows2, half, float, 2, 128)+DECL_GEMV_LEGACY(gemv_f16_rows4, half, float, 4, 128)+DECL_GEMV_LEGACY(gemv_f16_rows8, half, float, 8, 128)- mat += out_row * matrix_ld;-- const int loop_stride = blockN;- const int in_size = in_vec_size;- const int n_iter = in_size / loop_stride;- const int leftover = in_size - loop_stride * n_iter;-- for (int i = 0; i < n_iter; ++i) {- load_safe<float>(in_vec, v_coeff, bn, TN);-- int mat_offset = 0;- UZU_PRAGMA_UNROLL- for (int tm = 0; tm < TM; tm++) {- load_safe(mat, inter, mat_offset + bn, TN);- UZU_PRAGMA_UNROLL- for (int tn = 0; tn < TN; tn++) {- result[tm] += inter[tn] * v_coeff[tn];- }- mat_offset += matrix_ld;- }-- bn += blockN;- }-- if (leftover > 0) {- load_safe<float>(in_vec, v_coeff, bn, in_size);-- UZU_PRAGMA_UNROLL- for (int tm = 0; tm < TM; tm++) {- load_safe(&mat[tm * matrix_ld], inter, bn, in_size);- UZU_PRAGMA_UNROLL- for (int tn = 0; tn < TN; tn++) {- result[tm] += inter[tn] * v_coeff[tn];- }- }- }-- UZU_PRAGMA_UNROLL- for (int tm = 0; tm < TM; tm++) {- UZU_PRAGMA_UNROLL- for (ushort sn = (SN / 2); sn >= 1; sn >>= 1) {- result[tm] += simd_shuffle_down(result[tm], sn);- }- }-- if (BN > 1) {- threadgroup float* tgp_results = tgp_memory + sgN * (blockM + TM) + bm;- if (thrN == 0) {- UZU_PRAGMA_UNROLL- for (int tm = 0; tm < TM; tm++) {- tgp_results[tm] = result[tm];- }-- threadgroup_barrier(mem_flags::mem_none);-- if (sgN == 0) {- UZU_PRAGMA_UNROLL- for (int sgn = 1; sgn < BN; sgn++) {- UZU_PRAGMA_UNROLL- for (int tm = 0; tm < TM; tm++) {- result[tm] += tgp_results[sgn * (blockM + TM) + tm];- }- }- }- }- }-- if (simdN == 0 && thrN == 0) {- UZU_PRAGMA_UNROLL- for (int tm = 0; tm < TM; tm++) {- out_vec[out_row + tm] = static_cast<T>(result[tm]);- }- }- }-};--#define DECL_GEMV(name, itype, bm, bn, sm, sn, tm, tn) \- [[kernel, max_total_threads_per_threadgroup(bm * sm * bn * sn)]] void \- name( \- const device itype* mat [[buffer(0)]], \- const device itype* in_vec [[buffer(1)]], \- device itype* out_vec [[buffer(2)]], \- const constant int& in_vec_size [[buffer(3)]], \- const constant int& out_vec_size [[buffer(4)]], \- const constant int& matrix_ld [[buffer(5)]], \- 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]], \- threadgroup float* tgp_memory [[threadgroup(0)]]) { \- GEMVKernel<itype, bm, bn, sm, sn, tm, tn>::run( \- mat, in_vec, out_vec, in_vec_size, out_vec_size, \- matrix_ld, tgp_memory, \- tid, lid, simd_gid, simd_lid); \- }--#define DECL_GEMV_BLOCKS(name, itype) \- DECL_GEMV(name##_bm2_bn1_sm4_sn8_tm1_tn4, itype, 2, 1, 4, 8, 1, 4) \- DECL_GEMV(name##_bm2_bn1_sm4_sn8_tm4_tn4, itype, 2, 1, 4, 8, 4, 4) \- DECL_GEMV(name##_bm2_bn1_sm2_sn16_tm1_tn4, itype, 2, 1, 2, 16, 1, 4) \- DECL_GEMV(name##_bm2_bn1_sm2_sn16_tm4_tn4, itype, 2, 1, 2, 16, 4, 4) \- DECL_GEMV(name##_bm4_bn1_sm2_sn16_tm4_tn4, itype, 4, 1, 2, 16, 4, 4)--DECL_GEMV_BLOCKS(gemv_f32, float)-DECL_GEMV_BLOCKS(gemv_f16, half)-DECL_GEMV_BLOCKS(gemv_bf16, bfloat)+// Legacy bfloat16 variants+DECL_GEMV_LEGACY(gemv_bf16_rows2, bfloat, float, 2, 128)+DECL_GEMV_LEGACY(gemv_bf16_rows4, bfloat, float, 4, 128)+DECL_GEMV_LEGACY(gemv_bf16_rows8, bfloat, float, 8, 128)diff --git a/crates/uzu/src/backends/metal/kernel/matmul/gemv.rs b/crates/uzu/src/backends/metal/kernel/matmul/gemv.rsindex abcea511c..f3ed8f0b1 100644--- a/crates/uzu/src/backends/metal/kernel/matmul/gemv.rs+++ b/crates/uzu/src/backends/metal/kernel/matmul/gemv.rs@@ -12,13 +12,18 @@ use crate::{};#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]-struct PipelineKey {- rows_per_group: u32,+enum PipelineKind {+ Legacy {+ rows_per_group: u32,+ },+ Fast,+ Wide,+ Parallel,}pub struct GemvKernel {dt: DataType,- pipelines: HashMap<PipelineKey, MTLComputePipelineState>,+ pipelines: HashMap<PipelineKind, MTLComputePipelineState>,}impl GemvKernel {@@ -29,7 +34,43 @@ impl GemvKernel {}}- fn kernel_name(+ fn fast_kernel_name(&self) -> Result<String, MTLError> {+ match self.dt {+ DataType::F16 => Ok("gemv_fast_f16".to_string()),+ DataType::BF16 => Ok("gemv_fast_bf16".to_string()),+ DataType::F32 => Ok("gemv_fast_f32".to_string()),+ _ => Err(MTLError::Generic(format!(+ "Unsupported dtype for fast GEMV: {:?}",+ self.dt+ ))),+ }+ }++ fn wide_kernel_name(&self) -> Result<String, MTLError> {+ match self.dt {+ DataType::F16 => Ok("gemv_wide_f16".to_string()),+ DataType::BF16 => Ok("gemv_wide_bf16".to_string()),+ DataType::F32 => Ok("gemv_wide_f32".to_string()),+ _ => Err(MTLError::Generic(format!(+ "Unsupported dtype for wide GEMV: {:?}",+ self.dt+ ))),+ }+ }++ fn parallel_kernel_name(&self) -> Result<String, MTLError> {+ match self.dt {+ DataType::F16 => Ok("gemv_parallel_f16".to_string()),+ DataType::BF16 => Ok("gemv_parallel_bf16".to_string()),+ DataType::F32 => Ok("gemv_parallel_f32".to_string()),+ _ => Err(MTLError::Generic(format!(+ "Unsupported dtype for parallel GEMV: {:?}",+ self.dt+ ))),+ }+ }++ fn legacy_kernel_name(&self,rows: u32,) -> Result<String, MTLError> {@@ -38,7 +79,7 @@ impl GemvKernel {DataType::BF16 => "gemv_bf16",_ => {return Err(MTLError::Generic(format!(- "Unsupported dtype for GEMV: {:?}",+ "Unsupported dtype for legacy GEMV: {:?}",self.dt)));},@@ -46,23 +87,280 @@ impl GemvKernel {Ok(format!("{base}_rows{rows}"))}- fn get_or_compile_pipeline(+ fn get_fast_pipeline(+ &mut self,+ mtl: &MTLContext,+ ) -> Result<&MTLComputePipelineState, MTLError> {+ let key = PipelineKind::Fast;+ if !self.pipelines.contains_key(&key) {+ let name = self.fast_kernel_name()?;+ let ps = mtl.compute_pipeline_state(&name, None)?;+ self.pipelines.insert(key, ps);+ }+ Ok(self.pipelines.get(&key).unwrap())+ }++ fn get_wide_pipeline(+ &mut self,+ mtl: &MTLContext,+ ) -> Result<&MTLComputePipelineState, MTLError> {+ let key = PipelineKind::Wide;+ if !self.pipelines.contains_key(&key) {+ let name = self.wide_kernel_name()?;+ let ps = mtl.compute_pipeline_state(&name, None)?;+ self.pipelines.insert(key, ps);+ }+ Ok(self.pipelines.get(&key).unwrap())+ }++ fn get_parallel_pipeline(+ &mut self,+ mtl: &MTLContext,+ ) -> Result<&MTLComputePipelineState, MTLError> {+ let key = PipelineKind::Parallel;+ if !self.pipelines.contains_key(&key) {+ let name = self.parallel_kernel_name()?;+ let ps = mtl.compute_pipeline_state(&name, None)?;+ self.pipelines.insert(key, ps);+ }+ Ok(self.pipelines.get(&key).unwrap())+ }++ fn get_legacy_pipeline(&mut self,mtl: &MTLContext,rows: u32,) -> Result<&MTLComputePipelineState, MTLError> {- let key = PipelineKey {+ let key = PipelineKind::Legacy {rows_per_group: rows,};if !self.pipelines.contains_key(&key) {- let name = self.kernel_name(rows)?;+ let name = self.legacy_kernel_name(rows)?;let ps = mtl.compute_pipeline_state(&name, None)?;self.pipelines.insert(key, ps);}Ok(self.pipelines.get(&key).unwrap())}- pub fn encode(+ /// Check if wide GEMV is applicable.+ /// Currently disabled as it doesn't improve MLP up pattern.+ fn should_use_wide(+ &self,+ _args: &MatmulArguments,+ ) -> bool {+ false+ }++ /// Check if parallel GEMV is applicable.+ /// Parallel kernel (8 simdgroups/TG) is best for small K with large N.+ fn should_use_parallel(+ &self,+ args: &MatmulArguments,+ ) -> bool {+ let k = args.input_dim;+ let n = args.output_dim;+ // Use parallel kernel when:+ // - K is small (< 4096) so threadgroup memory can hold a good chunk+ // - N is large (≥ 4096) so we benefit from reduced TG count+ // - K is aligned for vectorized loads+ k < 4096 && n >= 4096 && k % 4 == 0 && k >= 128+ }++ /// Check if fast GEMV is applicable.+ /// Fast kernel works best when K is large enough for vectorized loads.+ fn can_use_fast(+ &self,+ args: &MatmulArguments,+ ) -> bool {+ // Fast kernel uses BLOCK_K = 128 (32 threads * 4 elements)+ // Works well when K >= 128 and is reasonably aligned+ args.input_dim >= 128 && args.input_dim % 4 == 0+ }++ /// Encode using the fast optimized GEMV kernel.+ pub fn encode_fast(+ &mut self,+ mtl: &MTLContext,+ enc: &ComputeCommandEncoderRef,+ args: MatmulArguments,+ ) -> Result<(), MTLError> {+ let ps = self.get_fast_pipeline(mtl)?;+ enc.set_compute_pipeline_state(ps);++ // Bind buffers: A (weights/matrix), x (input vector), y (output)+ enc.set_buffer(0, Some(args.b), 0); // A = weights+ enc.set_buffer(1, Some(args.a), 0); // x = input+ enc.set_buffer(2, Some(args.d), 0); // y = output++ // Scalars (as i32 to match Metal kernel)+ let k = args.input_dim;+ let n = args.output_dim;+ let lda = args.ldb; // Weight matrix leading dimension+ // For batched GEMV: stride between input/output vectors is the leading dimension+ let batch_stride_x = args.lda; // stride between rows of A (input vectors)+ let batch_stride_y = args.ldd; // stride between rows of D (output vectors)++ enc.set_bytes(+ 3,+ std::mem::size_of::<i32>() as u64,+ &k as *const i32 as *const std::ffi::c_void,+ );+ enc.set_bytes(+ 4,+ std::mem::size_of::<i32>() as u64,+ &n as *const i32 as *const std::ffi::c_void,+ );+ enc.set_bytes(+ 5,+ std::mem::size_of::<i32>() as u64,+ &lda as *const i32 as *const std::ffi::c_void,+ );+ enc.set_bytes(+ 6,+ std::mem::size_of::<i32>() as u64,+ &batch_stride_x as *const i32 as *const std::ffi::c_void,+ );+ enc.set_bytes(+ 7,+ std::mem::size_of::<i32>() as u64,+ &batch_stride_y as *const i32 as *const std::ffi::c_void,+ );++ // Fast kernel: 4 rows per simdgroup, 1 simdgroup per threadgroup+ const ROWS_PER_SIMDGROUP: i32 = 4;+ let tg_x = ((n + ROWS_PER_SIMDGROUP - 1) / ROWS_PER_SIMDGROUP) as u64;+ let tg_z = args.batch_count as u64;++ let tgs = MTLSize::new(tg_x, 1, tg_z);+ let threads_per_tg = MTLSize::new(32, 1, 1); // Single simdgroup++ enc.dispatch_thread_groups(tgs, threads_per_tg);+ Ok(())+ }++ /// Encode using the wide GEMV kernel (16 rows per simdgroup).+ /// Best for small K with large N (MLP up pattern).+ pub fn encode_wide(+ &mut self,+ mtl: &MTLContext,+ enc: &ComputeCommandEncoderRef,+ args: MatmulArguments,+ ) -> Result<(), MTLError> {+ let ps = self.get_wide_pipeline(mtl)?;+ enc.set_compute_pipeline_state(ps);++ // Same buffer layout as fast kernel+ enc.set_buffer(0, Some(args.b), 0); // A = weights+ enc.set_buffer(1, Some(args.a), 0); // x = input+ enc.set_buffer(2, Some(args.d), 0); // y = output++ let k = args.input_dim;+ let n = args.output_dim;+ let lda = args.ldb;+ let batch_stride_x = args.lda; // stride between rows of A+ let batch_stride_y = args.ldd; // stride between rows of D++ enc.set_bytes(+ 3,+ std::mem::size_of::<i32>() as u64,+ &k as *const i32 as *const std::ffi::c_void,+ );+ enc.set_bytes(+ 4,+ std::mem::size_of::<i32>() as u64,+ &n as *const i32 as *const std::ffi::c_void,+ );+ enc.set_bytes(+ 5,+ std::mem::size_of::<i32>() as u64,+ &lda as *const i32 as *const std::ffi::c_void,+ );+ enc.set_bytes(+ 6,+ std::mem::size_of::<i32>() as u64,+ &batch_stride_x as *const i32 as *const std::ffi::c_void,+ );+ enc.set_bytes(+ 7,+ std::mem::size_of::<i32>() as u64,+ &batch_stride_y as *const i32 as *const std::ffi::c_void,+ );++ // Wide kernel: 8 rows per simdgroup+ const ROWS_PER_SIMDGROUP: i32 = 8;+ let tg_x = ((n + ROWS_PER_SIMDGROUP - 1) / ROWS_PER_SIMDGROUP) as u64;+ let tg_z = args.batch_count as u64;++ let tgs = MTLSize::new(tg_x, 1, tg_z);+ let threads_per_tg = MTLSize::new(32, 1, 1); // Single simdgroup++ enc.dispatch_thread_groups(tgs, threads_per_tg);+ Ok(())+ }++ /// Encode using the parallel GEMV kernel (8 simdgroups per threadgroup).+ /// Best for small K with large N (reduces threadgroup count).+ pub fn encode_parallel(+ &mut self,+ mtl: &MTLContext,+ enc: &ComputeCommandEncoderRef,+ args: MatmulArguments,+ ) -> Result<(), MTLError> {+ let ps = self.get_parallel_pipeline(mtl)?;+ enc.set_compute_pipeline_state(ps);++ // Same buffer layout as other kernels+ enc.set_buffer(0, Some(args.b), 0); // A = weights+ enc.set_buffer(1, Some(args.a), 0); // x = input+ enc.set_buffer(2, Some(args.d), 0); // y = output++ let k = args.input_dim;+ let n = args.output_dim;+ let lda = args.ldb;+ let batch_stride_x = args.lda; // stride between rows of A+ let batch_stride_y = args.ldd; // stride between rows of D++ enc.set_bytes(+ 3,+ std::mem::size_of::<i32>() as u64,+ &k as *const i32 as *const std::ffi::c_void,+ );+ enc.set_bytes(+ 4,+ std::mem::size_of::<i32>() as u64,+ &n as *const i32 as *const std::ffi::c_void,+ );+ enc.set_bytes(+ 5,+ std::mem::size_of::<i32>() as u64,+ &lda as *const i32 as *const std::ffi::c_void,+ );+ enc.set_bytes(+ 6,+ std::mem::size_of::<i32>() as u64,+ &batch_stride_x as *const i32 as *const std::ffi::c_void,+ );+ enc.set_bytes(+ 7,+ std::mem::size_of::<i32>() as u64,+ &batch_stride_y as *const i32 as *const std::ffi::c_void,+ );++ // Parallel kernel: 32 simdgroups per TG, each computes 1 row+ const SIMDGROUPS_PER_TG: i32 = 32;+ let tg_x = ((n + SIMDGROUPS_PER_TG - 1) / SIMDGROUPS_PER_TG) as u64;+ let tg_z = args.batch_count as u64;++ let tgs = MTLSize::new(tg_x, 1, tg_z);+ let threads_per_tg =+ MTLSize::new((SIMDGROUPS_PER_TG * 32) as u64, 1, 1);++ enc.dispatch_thread_groups(tgs, threads_per_tg);+ Ok(())+ }++ /// Encode using the legacy GEMV kernel (for fallback).+ pub fn encode_legacy(&mut self,mtl: &MTLContext,enc: &ComputeCommandEncoderRef,@@ -70,7 +368,7 @@ impl GemvKernel {rows_per_group: u32,) -> Result<(), MTLError> {let rows_per_group = rows_per_group.max(1);- let ps = self.get_or_compile_pipeline(mtl, rows_per_group)?;+ let ps = self.get_legacy_pipeline(mtl, rows_per_group)?;enc.set_compute_pipeline_state(ps);// Bind buffers: matrix (B), vector (A), output (D)@@ -114,11 +412,30 @@ impl GemvKernel {// Threadgroup sizinglet threads_per_tg = MTLSize::new((rows_per_group * 32) as u64, 1, 1);let tg_x = ((n + rows_per_group - 1) / rows_per_group) as u64;- let tg_y = 1;let tg_z = args.batch_count as u64;- let tgs = MTLSize::new(tg_x, tg_y, tg_z);+ let tgs = MTLSize::new(tg_x, 1, tg_z);enc.dispatch_thread_groups(tgs, threads_per_tg);Ok(())}++ /// Main encode entry point - automatically selects best kernel variant.+ pub fn encode(+ &mut self,+ mtl: &MTLContext,+ enc: &ComputeCommandEncoderRef,+ args: MatmulArguments,+ rows_per_group: u32,+ ) -> Result<(), MTLError> {+ // Priority: parallel > wide > fast > legacy+ if self.should_use_parallel(&args) {+ self.encode_parallel(mtl, enc, args)+ } else if self.should_use_wide(&args) {+ self.encode_wide(mtl, enc, args)+ } else if self.can_use_fast(&args) {+ self.encode_fast(mtl, enc, args)+ } else {+ self.encode_legacy(mtl, enc, args, rows_per_group)+ }+ }}diff --git a/crates/uzu/src/backends/metal/kernel/matmul/kernel.rs b/crates/uzu/src/backends/metal/kernel/matmul/kernel.rsindex 76a7a03b6..1c7663734 100644--- a/crates/uzu/src/backends/metal/kernel/matmul/kernel.rs+++ b/crates/uzu/src/backends/metal/kernel/matmul/kernel.rs@@ -92,12 +92,39 @@ impl MatmulKernel {enc: &ComputeCommandEncoderRef,args: MatmulArguments,) -> Result<bool, MTLError> {- // Apply GEMV when batch (M) is 1 or output_dim (N) is 1, and when A is not transposed.+ // Apply GEMV when batch (M) is small or output_dim (N) is 1, and A is not transposed.let m = args.batch;let n = args.output_dim;if self.transpose_a {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 {+ // Reshape: treat M rows as M batches of 1-row 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, // stride between input vectors+ ldb: args.ldb,+ ldd: args.ldd, // stride between output vectors+ batch_count: m, // M becomes batch count+ };+ let rows = self.select_gemv_rows(n);+ let gemv =+ self.gemv.get_or_insert_with(|| GemvKernel::new(self.dt));+ gemv.encode(mtl, enc, batched_args, rows)?;+ return Ok(true);+ }++ // Standard GEMV for M=1 or N=1if m != 1 && n != 1 {return Ok(false);}@@ -146,6 +173,14 @@ impl MatmulKernel {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);+ }+// Prefer NAX tiles when available on M4+ hardware.if mtl.is_nax_available()&& (!matches!(self.dt, DataType::F32) || mtl.tf32_enabled())