A high-performance inference engine for AI models
format (#76)
uuuvn0fba842eea5c
diff --git a/crates/matmul-benchmark/src/cxx_utils/matmul.hpp b/crates/matmul-benchmark/src/cxx_utils/matmul.hppindex 4a0cef9d0..c6ec4cfcf 100644--- a/crates/matmul-benchmark/src/cxx_utils/matmul.hpp+++ b/crates/matmul-benchmark/src/cxx_utils/matmul.hpp@@ -11,188 +11,207 @@ namespace cxx_utils {namespace mx = mlx::core;struct BenchmarkResult {- double avg_time_ms;- double gflops;+ double avg_time_ms;+ double gflops;};// Compute matmul and copy result to output buffer for accuracy testing-// Input: A[M,K] row-major, B[K,N] row-major (but we'll transpose B for consistency with UZU)-// UZU expects: A[M,K], B^T[N,K] (transpose_b=true means B is stored as [N,K])-// So we need to pass B as [N,K] to MLX too, then transpose it+// Input: A[M,K] row-major, B[K,N] row-major (but we'll transpose B for+// consistency with UZU) UZU expects: A[M,K], B^T[N,K] (transpose_b=true means B+// is stored as [N,K]) So we need to pass B as [N,K] to MLX too, then transpose+// itinline void matmul_bf16_with_output(const uint16_t* a_data, // [M, K] row-major bf16 as raw bytesconst uint16_t* b_data, // [N, K] row-major bf16 (transposed storage)uint16_t* output_data, // [M, N] output- int M, int K, int N+ int M,+ int K,+ int N) {- // Create MLX arrays from raw data- // A is [M, K], B is stored as [N, K] (transposed)- mx::Shape a_shape = {M, K};- mx::Shape b_shape = {N, K};-- auto a = mx::array(- reinterpret_cast<const mx::bfloat16_t*>(a_data),- a_shape,- mx::bfloat16- );-- auto b_transposed = mx::array(- reinterpret_cast<const mx::bfloat16_t*>(b_data),- b_shape,- mx::bfloat16- );-- // Transpose B back to [K, N] for standard matmul- auto b = mx::transpose(b_transposed);- mx::eval(a, b);-- // Compute matmul: [M, K] @ [K, N] -> [M, N]- auto result = mx::matmul(a, b);- mx::eval(result);-- // Copy result to output buffer- const auto* result_ptr = result.data<mx::bfloat16_t>();- std::memcpy(output_data, result_ptr, M * N * sizeof(uint16_t));+ // Create MLX arrays from raw data+ // A is [M, K], B is stored as [N, K] (transposed)+ mx::Shape a_shape = {M, K};+ mx::Shape b_shape = {N, K};++ auto a = mx::array(+ reinterpret_cast<const mx::bfloat16_t*>(a_data),+ a_shape,+ mx::bfloat16+ );++ auto b_transposed = mx::array(+ reinterpret_cast<const mx::bfloat16_t*>(b_data),+ b_shape,+ mx::bfloat16+ );++ // Transpose B back to [K, N] for standard matmul+ auto b = mx::transpose(b_transposed);+ mx::eval(a, b);++ // Compute matmul: [M, K] @ [K, N] -> [M, N]+ auto result = mx::matmul(a, b);+ mx::eval(result);++ // Copy result to output buffer+ const auto* result_ptr = result.data<mx::bfloat16_t>();+ std::memcpy(output_data, result_ptr, M * N * sizeof(uint16_t));}inline void matmul_f16_with_output(const uint16_t* a_data,const uint16_t* b_data,uint16_t* output_data,- int M, int K, int N+ int M,+ int K,+ int N) {- mx::Shape a_shape = {M, K};- mx::Shape b_shape = {N, K};+ mx::Shape a_shape = {M, K};+ mx::Shape b_shape = {N, K};- auto a = mx::array(- reinterpret_cast<const mx::float16_t*>(a_data),- a_shape,- mx::float16- );+ auto a = mx::array(+ reinterpret_cast<const mx::float16_t*>(a_data),+ a_shape,+ mx::float16+ );- auto b_transposed = mx::array(- reinterpret_cast<const mx::float16_t*>(b_data),- b_shape,- mx::float16- );+ auto b_transposed = mx::array(+ reinterpret_cast<const mx::float16_t*>(b_data),+ b_shape,+ mx::float16+ );- auto b = mx::transpose(b_transposed);- mx::eval(a, b);+ auto b = mx::transpose(b_transposed);+ mx::eval(a, b);- auto result = mx::matmul(a, b);- mx::eval(result);+ auto result = mx::matmul(a, b);+ mx::eval(result);- const auto* result_ptr = result.data<mx::float16_t>();- std::memcpy(output_data, result_ptr, M * N * sizeof(uint16_t));+ const auto* result_ptr = result.data<mx::float16_t>();+ std::memcpy(output_data, result_ptr, M * N * sizeof(uint16_t));}inline void matmul_f32_with_output(const float* a_data,const float* b_data,float* output_data,- int M, int K, int N+ int M,+ int K,+ int N) {- mx::Shape a_shape = {M, K};- mx::Shape b_shape = {N, K};+ mx::Shape a_shape = {M, K};+ mx::Shape b_shape = {N, K};- auto a = mx::array(a_data, a_shape, mx::float32);- auto b_transposed = mx::array(b_data, b_shape, mx::float32);+ auto a = mx::array(a_data, a_shape, mx::float32);+ auto b_transposed = mx::array(b_data, b_shape, mx::float32);- auto b = mx::transpose(b_transposed);- mx::eval(a, b);+ auto b = mx::transpose(b_transposed);+ mx::eval(a, b);- auto result = mx::matmul(a, b);- mx::eval(result);+ auto result = mx::matmul(a, b);+ mx::eval(result);- const auto* result_ptr = result.data<float>();- std::memcpy(output_data, result_ptr, M * N * sizeof(float));+ const auto* result_ptr = result.data<float>();+ std::memcpy(output_data, result_ptr, M * N * sizeof(float));}inline BenchmarkResult benchmark_matmul_f16(- int M, int N, int K,+ int M,+ int N,+ int K,int warmup_iters,int bench_iters) {- auto a = mx::random::uniform({M, K}, mx::float16);- // Match UZU weight layout: B is stored as [N, K] and viewed as [K, N] via transpose- auto b_transposed = mx::random::uniform({N, K}, mx::float16);- auto b = mx::transpose(b_transposed);- mx::eval(a, b);-- for (int i = 0; i < warmup_iters; ++i) {- mx::eval(mx::matmul(a, b));- }-- auto start = std::chrono::high_resolution_clock::now();- for (int i = 0; i < bench_iters; ++i) {- mx::eval(mx::matmul(a, b));- }- auto end = std::chrono::high_resolution_clock::now();-- double total_ms = std::chrono::duration<double, std::milli>(end - start).count();- double avg_ms = total_ms / bench_iters;- double flops = 2.0 * M * N * K;- double gflops = (flops / (avg_ms / 1000.0)) / 1e9;-- return BenchmarkResult{avg_ms, gflops};+ auto a = mx::random::uniform({M, K}, mx::float16);+ // Match UZU weight layout: B is stored as [N, K] and viewed as [K, N] via+ // transpose+ auto b_transposed = mx::random::uniform({N, K}, mx::float16);+ auto b = mx::transpose(b_transposed);+ mx::eval(a, b);++ for (int i = 0; i < warmup_iters; ++i) {+ mx::eval(mx::matmul(a, b));+ }++ auto start = std::chrono::high_resolution_clock::now();+ for (int i = 0; i < bench_iters; ++i) {+ mx::eval(mx::matmul(a, b));+ }+ auto end = std::chrono::high_resolution_clock::now();++ double total_ms =+ std::chrono::duration<double, std::milli>(end - start).count();+ double avg_ms = total_ms / bench_iters;+ double flops = 2.0 * M * N * K;+ double gflops = (flops / (avg_ms / 1000.0)) / 1e9;++ return BenchmarkResult{avg_ms, gflops};}inline BenchmarkResult benchmark_matmul_f32(- int M, int N, int K,+ int M,+ int N,+ int K,int warmup_iters,int bench_iters) {- auto a = mx::random::uniform({M, K}, mx::float32);- // Match UZU weight layout: B is stored as [N, K] and viewed as [K, N] via transpose- auto b_transposed = mx::random::uniform({N, K}, mx::float32);- auto b = mx::transpose(b_transposed);- mx::eval(a, b);-- for (int i = 0; i < warmup_iters; ++i) {- mx::eval(mx::matmul(a, b));- }-- auto start = std::chrono::high_resolution_clock::now();- for (int i = 0; i < bench_iters; ++i) {- mx::eval(mx::matmul(a, b));- }- auto end = std::chrono::high_resolution_clock::now();-- double total_ms = std::chrono::duration<double, std::milli>(end - start).count();- double avg_ms = total_ms / bench_iters;- double flops = 2.0 * M * N * K;- double gflops = (flops / (avg_ms / 1000.0)) / 1e9;-- return BenchmarkResult{avg_ms, gflops};+ auto a = mx::random::uniform({M, K}, mx::float32);+ // Match UZU weight layout: B is stored as [N, K] and viewed as [K, N] via+ // transpose+ auto b_transposed = mx::random::uniform({N, K}, mx::float32);+ auto b = mx::transpose(b_transposed);+ mx::eval(a, b);++ for (int i = 0; i < warmup_iters; ++i) {+ mx::eval(mx::matmul(a, b));+ }++ auto start = std::chrono::high_resolution_clock::now();+ for (int i = 0; i < bench_iters; ++i) {+ mx::eval(mx::matmul(a, b));+ }+ auto end = std::chrono::high_resolution_clock::now();++ double total_ms =+ std::chrono::duration<double, std::milli>(end - start).count();+ double avg_ms = total_ms / bench_iters;+ double flops = 2.0 * M * N * K;+ double gflops = (flops / (avg_ms / 1000.0)) / 1e9;++ return BenchmarkResult{avg_ms, gflops};}inline BenchmarkResult benchmark_matmul_bf16(- int M, int N, int K,+ int M,+ int N,+ int K,int warmup_iters,int bench_iters) {- auto a = mx::random::uniform({M, K}, mx::bfloat16);- // Match UZU weight layout: B is stored as [N, K] and viewed as [K, N] via transpose- auto b_transposed = mx::random::uniform({N, K}, mx::bfloat16);- auto b = mx::transpose(b_transposed);- mx::eval(a, b);-- for (int i = 0; i < warmup_iters; ++i) {- mx::eval(mx::matmul(a, b));- }-- auto start = std::chrono::high_resolution_clock::now();- for (int i = 0; i < bench_iters; ++i) {- mx::eval(mx::matmul(a, b));- }- auto end = std::chrono::high_resolution_clock::now();-- double total_ms = std::chrono::duration<double, std::milli>(end - start).count();- double avg_ms = total_ms / bench_iters;- double flops = 2.0 * M * N * K;- double gflops = (flops / (avg_ms / 1000.0)) / 1e9;-- return BenchmarkResult{avg_ms, gflops};+ auto a = mx::random::uniform({M, K}, mx::bfloat16);+ // Match UZU weight layout: B is stored as [N, K] and viewed as [K, N] via+ // transpose+ auto b_transposed = mx::random::uniform({N, K}, mx::bfloat16);+ auto b = mx::transpose(b_transposed);+ mx::eval(a, b);++ for (int i = 0; i < warmup_iters; ++i) {+ mx::eval(mx::matmul(a, b));+ }++ auto start = std::chrono::high_resolution_clock::now();+ for (int i = 0; i < bench_iters; ++i) {+ mx::eval(mx::matmul(a, b));+ }+ auto end = std::chrono::high_resolution_clock::now();++ double total_ms =+ std::chrono::duration<double, std::milli>(end - start).count();+ double avg_ms = total_ms / bench_iters;+ double flops = 2.0 * M * N * K;+ double gflops = (flops / (avg_ms / 1000.0)) / 1e9;++ return BenchmarkResult{avg_ms, gflops};}} // namespace cxx_utilsdiff --git a/crates/uzu/src/backends/metal/encodable_block/normalization/rms_norm.rs b/crates/uzu/src/backends/metal/encodable_block/normalization/rms_norm.rsindex e24c95130..23b65ef3c 100644--- a/crates/uzu/src/backends/metal/encodable_block/normalization/rms_norm.rs+++ b/crates/uzu/src/backends/metal/encodable_block/normalization/rms_norm.rs@@ -146,7 +146,8 @@ impl EncodableBlock for RMSNorm {} else {(0, state.active_suffix_length())};- let batch_len = batch_len.min(suffix_length.saturating_sub(batch_start));+ let batch_len =+ batch_len.min(suffix_length.saturating_sub(batch_start));if batch_len == 0 {return;}diff --git a/crates/uzu/src/backends/metal/kernel/attention/gemm_attention.metal b/crates/uzu/src/backends/metal/kernel/attention/gemm_attention.metalindex bcff92b15..07470e915 100644--- a/crates/uzu/src/backends/metal/kernel/attention/gemm_attention.metal+++ b/crates/uzu/src/backends/metal/kernel/attention/gemm_attention.metal@@ -171,7 +171,8 @@ template <constexpr int kNWarps = WM * WN;static_assert(BQ >= (kNWarps * kFragSize) && BQ % (kNWarps * kFragSize) == 0,- "Each simdgroup must host at least 1 simdgroup matrix along Q sequence.");+ "Each simdgroup must host at least 1 simdgroup matrix along Q sequence."+ );// Q seq frags per warp (we keep TQ == 1 for the 32-row block layout)constexpr int TQ = BQ / (kNWarps * kFragSize);@@ -205,7 +206,8 @@ template <// Ks is row-major [BK, BD] but we load K^T by swapping strides:// B_str_k = 1, B_str_n = LDK_tgp => offset = sn * LDK_tgp + smconst short Ks_offset = sn * LDK_tgp + sm;- constexpr short Ks_tile_stride = kFragSize; // advance along head-dim (contiguous)+ constexpr short Ks_tile_stride =+ kFragSize; // advance along head-dim (contiguous)// Vs is row-major [BK, BD]const short Vs_offset = sm * LDV_tgp + sn;@@ -262,8 +264,12 @@ template <for (short dd = 0; dd < TD; dd++) {simdgroup_barrier(mem_flags::mem_none);- Qtile.template load<T, 1, 1, LDQ_tgp, 1>(&Qs[Qs_offset + dd * Qs_tile_stride]);- Ktile.template load<T, 1, 1, 1, LDK_tgp>(&Ks[Ks_offset + dd * Ks_tile_stride]);+ Qtile.template load<T, 1, 1, LDQ_tgp, 1>(+ &Qs[Qs_offset + dd * Qs_tile_stride]+ );+ Ktile.template load<T, 1, 1, 1, LDK_tgp>(+ &Ks[Ks_offset + dd * Ks_tile_stride]+ );simdgroup_barrier(mem_flags::mem_none);tile_matmad(Stile, Qtile, Ktile, Stile);@@ -318,14 +324,12 @@ template <const int k1 = col_base + 1;if (k0 < params->k_len) {- AccumType mv =- static_cast<AccumType>(mask[row_base + int64_t(k0)]);+ AccumType mv = static_cast<AccumType>(mask[row_base + int64_t(k0)]);mv = metal::max(mv, static_cast<AccumType>(-1e9f));frag[0] += M_LOG2E_F * mv;}if (k1 < params->k_len) {- AccumType mv =- static_cast<AccumType>(mask[row_base + int64_t(k1)]);+ AccumType mv = static_cast<AccumType>(mask[row_base + int64_t(k1)]);mv = metal::max(mv, static_cast<AccumType>(-1e9f));frag[1] += M_LOG2E_F * mv;}@@ -393,7 +397,9 @@ template <const short kk = ik * kFragSize;const short dd = id * kFragSize;- Vtile.template load<T, 1, 1, LDV_tgp, 1>(&Vs[Vs_offset + kk * LDV_tgp + dd]);+ Vtile.template load<T, 1, 1, LDV_tgp, 1>(+ &Vs[Vs_offset + kk * LDV_tgp + dd]+ );if constexpr (BD == 128) {simdgroup_barrier(mem_flags::mem_none);@@ -403,7 +409,8 @@ template <Otile.frag_at(0, id),Stile.frag_at(0, ik),Vtile.frag_at(0, 0),- Otile.frag_at(0, id));+ Otile.frag_at(0, id)+ );}}@@ -435,7 +442,10 @@ template <}Otile.template store_safe<T, 1, 1>(- O, int(params->o_strides[2]), dst_tile_dims);+ O,+ int(params->o_strides[2]),+ dst_tile_dims+ );} else {Otile.template store<T, 1, 1>(O, int(params->o_strides[2]));}@@ -445,16 +455,16 @@ template <// Kernel instantiations (BQ=32, BK in {32,16}, WM=2, WN=2)///////////////////////////////////////////////////////////////////////////////-#define instantiate_attention_gemm(type_name, element_type, head_dim_value, bk_value) \- template [[host_name("attention_gemm_" #type_name "_" #head_dim_value "_bk" #bk_value)]] \- [[kernel]] void attention_gemm< \- element_type, \- 32, \- bk_value, \- head_dim_value, \- 4, \- 1, \- float>( \+#define instantiate_attention_gemm( \+ type_name, \+ element_type, \+ head_dim_value, \+ bk_value \+) \+ template [[host_name( \+ "attention_gemm_" #type_name "_" #head_dim_value "_bk" #bk_value \+ )]] [[kernel]] void \+ attention_gemm<element_type, 32, bk_value, head_dim_value, 4, 1, float>( \const device element_type* Q [[buffer(0)]], \const device element_type* K [[buffer(1)]], \const device element_type* V [[buffer(2)]], \@@ -462,25 +472,34 @@ template <const constant AttnParams* params [[buffer(4)]], \const constant AttnMaskParams* mask_params \[[buffer(5), function_constant(has_mask)]], \- const device element_type* mask [[buffer(6), function_constant(has_mask)]], \+ const device element_type* mask \+ [[buffer(6), function_constant(has_mask)]], \const device float* sinks [[buffer(7), function_constant(has_sinks)]], \uint simd_lane_id [[thread_index_in_simdgroup]], \uint simd_group_id [[simdgroup_index_in_threadgroup]], \uint3 tid [[threadgroup_position_in_grid]], \- uint3 lid [[thread_position_in_threadgroup]]);--instantiate_attention_gemm(f16, half, 64, 32)-instantiate_attention_gemm(f16, half, 128, 16)-instantiate_attention_gemm(f16, half, 256, 16)--instantiate_attention_gemm(bf16, bfloat, 64, 32)-instantiate_attention_gemm(bf16, bfloat, 128, 16)-instantiate_attention_gemm(bf16, bfloat, 256, 16)--instantiate_attention_gemm(f32, float, 64, 32)-instantiate_attention_gemm(f32, float, 128, 16)-instantiate_attention_gemm(f32, float, 256, 16)+ uint3 lid [[thread_position_in_threadgroup]] \+ );++instantiate_attention_gemm(f16, half, 64, 32) instantiate_attention_gemm(+ f16,+ half,+ 128,+ 16+) instantiate_attention_gemm(f16, half, 256, 16)++ instantiate_attention_gemm(bf16, bfloat, 64, 32) instantiate_attention_gemm(+ bf16,+ bfloat,+ 128,+ 16+ ) instantiate_attention_gemm(bf16, bfloat, 256, 16)++ instantiate_attention_gemm(f32, float, 64, 32) instantiate_attention_gemm(+ f32,+ float,+ 128,+ 16+ ) instantiate_attention_gemm(f32, float, 256, 16)#undef instantiate_attention_gemm--diff --git a/crates/uzu/src/backends/metal/kernel/attention/gemm_types.h b/crates/uzu/src/backends/metal/kernel/attention/gemm_types.hindex 2b634d5d3..fada4ef99 100644--- a/crates/uzu/src/backends/metal/kernel/attention/gemm_types.h+++ b/crates/uzu/src/backends/metal/kernel/attention/gemm_types.h@@ -75,5 +75,3 @@ struct AttnMaskParams {} // namespace attention} // namespace uzu#endif--diff --git a/crates/uzu/src/backends/metal/kernel/common/bf16_math.h b/crates/uzu/src/backends/metal/kernel/common/bf16_math.hindex 23e3291c3..639e04eed 100644--- a/crates/uzu/src/backends/metal/kernel/common/bf16_math.h+++ b/crates/uzu/src/backends/metal/kernel/common/bf16_math.h@@ -47,11 +47,13 @@ functions to accordingly automatically handle the casting} \METAL_FUNC otype atan(itype y_over_x) { \return static_cast<otype>( \- __metal_atan(static_cast<ctype>(y_over_x), mfast)); \+ __metal_atan(static_cast<ctype>(y_over_x), mfast) \+ ); \} \METAL_FUNC otype atan2(itype y, itype x) { \return static_cast<otype>( \- __metal_atan2(static_cast<ctype>(y), static_cast<ctype>(x), mfast)); \+ __metal_atan2(static_cast<ctype>(y), static_cast<ctype>(x), mfast) \+ ); \} \METAL_FUNC otype atanh(itype x) { \return static_cast<otype>(__metal_atanh(static_cast<ctype>(x), mfast)); \@@ -70,7 +72,8 @@ functions to accordingly automatically handle the casting} \METAL_FUNC otype divide(itype x, itype y) { \return static_cast<otype>( \- __metal_divide(static_cast<ctype>(x), static_cast<ctype>(y), mfast)); \+ __metal_divide(static_cast<ctype>(x), static_cast<ctype>(y), mfast) \+ ); \} \METAL_FUNC otype exp(itype x) { \return static_cast<otype>(__metal_exp(static_cast<ctype>(x), mfast)); \@@ -93,40 +96,49 @@ functions to accordingly automatically handle the casting} \METAL_FUNC otype fma(itype x, itype y, itype z) { \return static_cast<otype>(__metal_fma( \- static_cast<ctype>(x), static_cast<ctype>(y), static_cast<ctype>(z))); \+ static_cast<ctype>(x), \+ static_cast<ctype>(y), \+ static_cast<ctype>(z) \+ )); \} \METAL_FUNC otype fmax(itype x, itype y) { \return static_cast<otype>( \- __metal_fmax(static_cast<ctype>(x), static_cast<ctype>(y), mfast)); \+ __metal_fmax(static_cast<ctype>(x), static_cast<ctype>(y), mfast) \+ ); \} \METAL_FUNC otype fmax3(itype x, itype y, itype z) { \return static_cast<otype>(__metal_fmax3( \static_cast<ctype>(x), \static_cast<ctype>(y), \static_cast<ctype>(z), \- mfast)); \+ mfast \+ )); \} \METAL_FUNC otype fmedian3(itype x, itype y, itype z) { \return static_cast<otype>(__metal_fmedian3( \static_cast<ctype>(x), \static_cast<ctype>(y), \static_cast<ctype>(z), \- mfast)); \+ mfast \+ )); \} \METAL_FUNC otype fmin(itype x, itype y) { \return static_cast<otype>( \- __metal_fmin(static_cast<ctype>(x), static_cast<ctype>(y), mfast)); \+ __metal_fmin(static_cast<ctype>(x), static_cast<ctype>(y), mfast) \+ ); \} \METAL_FUNC otype fmin3(itype x, itype y, itype z) { \return static_cast<otype>(__metal_fmin3( \static_cast<ctype>(x), \static_cast<ctype>(y), \static_cast<ctype>(z), \- mfast)); \+ mfast \+ )); \} \METAL_FUNC otype fmod(itype x, itype y) { \return static_cast<otype>( \- __metal_fmod(static_cast<ctype>(x), static_cast<ctype>(y), mfast)); \+ __metal_fmod(static_cast<ctype>(x), static_cast<ctype>(y), mfast) \+ ); \} \METAL_FUNC otype fract(itype x) { \return static_cast<otype>(__metal_fract(static_cast<ctype>(x), mfast)); \@@ -148,44 +160,52 @@ functions to accordingly automatically handle the casting} \METAL_FUNC otype max(itype x, itype y) { \return static_cast<otype>( \- __metal_fmax(static_cast<ctype>(x), static_cast<ctype>(y), mfast)); \+ __metal_fmax(static_cast<ctype>(x), static_cast<ctype>(y), mfast) \+ ); \} \METAL_FUNC otype max3(itype x, itype y, itype z) { \return static_cast<otype>(__metal_fmax3( \static_cast<ctype>(x), \static_cast<ctype>(y), \static_cast<ctype>(z), \- mfast)); \+ mfast \+ )); \} \METAL_FUNC otype median3(itype x, itype y, itype z) { \return static_cast<otype>(__metal_fmedian3( \static_cast<ctype>(x), \static_cast<ctype>(y), \static_cast<ctype>(z), \- mfast)); \+ mfast \+ )); \} \METAL_FUNC otype min(itype x, itype y) { \return static_cast<otype>( \- __metal_fmin(static_cast<ctype>(x), static_cast<ctype>(y), mfast)); \+ __metal_fmin(static_cast<ctype>(x), static_cast<ctype>(y), mfast) \+ ); \} \METAL_FUNC otype min3(itype x, itype y, itype z) { \return static_cast<otype>(__metal_fmin3( \static_cast<ctype>(x), \static_cast<ctype>(y), \static_cast<ctype>(z), \- mfast)); \+ mfast \+ )); \} \METAL_FUNC otype nextafter(itype x, itype y) { \return static_cast<otype>( \- __metal_nextafter(static_cast<ctype>(x), static_cast<ctype>(y))); \+ __metal_nextafter(static_cast<ctype>(x), static_cast<ctype>(y)) \+ ); \} \METAL_FUNC otype pow(itype x, itype y) { \return static_cast<otype>( \- __metal_pow(static_cast<ctype>(x), static_cast<ctype>(y), mfast)); \+ __metal_pow(static_cast<ctype>(x), static_cast<ctype>(y), mfast) \+ ); \} \METAL_FUNC otype powr(itype x, itype y) { \return static_cast<otype>( \- __metal_powr(static_cast<ctype>(x), static_cast<ctype>(y), mfast)); \+ __metal_powr(static_cast<ctype>(x), static_cast<ctype>(y), mfast) \+ ); \} \METAL_FUNC otype rint(itype x) { \return static_cast<otype>(__metal_rint(static_cast<ctype>(x), mfast)); \@@ -227,7 +247,8 @@ instantiate_metal_math_funcs(bfloat16_t,bfloat16_t,float,- __METAL_MAYBE_FAST_MATH__);+ __METAL_MAYBE_FAST_MATH__+);namespace fast {@@ -235,7 +256,8 @@ instantiate_metal_math_funcs(bfloat16_t,bfloat16_t,float,- __METAL_FAST_MATH__);+ __METAL_FAST_MATH__+);} // namespace fast@@ -245,7 +267,8 @@ instantiate_metal_math_funcs(bfloat16_t,bfloat16_t,float,- __METAL_PRECISE_MATH__);+ __METAL_PRECISE_MATH__+);} // namespace precise@@ -255,72 +278,102 @@ instantiate_metal_math_funcs(// Metal simd for bfloat16///////////////////////////////////////////////////////////////////////////////-#define instantiate_metal_simd_comm_funcs( \- itype, otype, ctype, itype_to_ctype, ctype_to_otype) \- \- METAL_FUNC otype simd_broadcast(itype data, ushort broadcast_lane_id) { \- return ctype_to_otype( \- __metal_simd_broadcast(itype_to_ctype(data), broadcast_lane_id)); \- } \- \- METAL_FUNC otype simd_shuffle(itype data, ushort simd_lane_id) { \- return ctype_to_otype( \- __metal_simd_shuffle(itype_to_ctype(data), simd_lane_id)); \- } \- \- METAL_FUNC otype simd_shuffle_and_fill_down( \- itype data, itype filling_data, ushort delta, ushort modulo) { \- return ctype_to_otype(__metal_simd_shuffle_and_fill_down( \- itype_to_ctype(data), itype_to_ctype(filling_data), delta, modulo)); \- } \- \- METAL_FUNC otype simd_shuffle_and_fill_down( \- itype data, itype filling_data, ushort delta) { \- return ctype_to_otype(__metal_simd_shuffle_and_fill_down( \- itype_to_ctype(data), \- itype_to_ctype(filling_data), \- delta, \- __metal_get_simdgroup_size(ushort()))); \- } \- \- METAL_FUNC otype simd_shuffle_and_fill_up( \- itype data, itype filling_data, ushort delta, ushort modulo) { \- return ctype_to_otype(__metal_simd_shuffle_and_fill_up( \- itype_to_ctype(data), itype_to_ctype(filling_data), delta, modulo)); \- } \- \- METAL_FUNC otype simd_shuffle_and_fill_up( \- itype data, itype filling_data, ushort delta) { \- return ctype_to_otype(__metal_simd_shuffle_and_fill_up( \- itype_to_ctype(data), \- itype_to_ctype(filling_data), \- delta, \- __metal_get_simdgroup_size(ushort()))); \- } \- \- METAL_FUNC otype simd_shuffle_down(itype data, ushort delta) { \- return ctype_to_otype( \- __metal_simd_shuffle_down(itype_to_ctype(data), delta)); \- } \- \- METAL_FUNC otype simd_shuffle_rotate_down(itype data, ushort delta) { \- return ctype_to_otype( \- __metal_simd_shuffle_rotate_down(itype_to_ctype(data), delta)); \- } \- \- METAL_FUNC otype simd_shuffle_rotate_up(itype data, ushort delta) { \- return ctype_to_otype( \- __metal_simd_shuffle_rotate_up(itype_to_ctype(data), delta)); \- } \- \- METAL_FUNC otype simd_shuffle_up(itype data, ushort delta) { \- return ctype_to_otype( \- __metal_simd_shuffle_up(itype_to_ctype(data), delta)); \- } \- \- METAL_FUNC otype simd_shuffle_xor(itype data, ushort mask) { \- return ctype_to_otype( \- __metal_simd_shuffle_xor(itype_to_ctype(data), mask)); \+#define instantiate_metal_simd_comm_funcs( \+ itype, \+ otype, \+ ctype, \+ itype_to_ctype, \+ ctype_to_otype \+) \+ \+ METAL_FUNC otype simd_broadcast(itype data, ushort broadcast_lane_id) { \+ return ctype_to_otype( \+ __metal_simd_broadcast(itype_to_ctype(data), broadcast_lane_id) \+ ); \+ } \+ \+ METAL_FUNC otype simd_shuffle(itype data, ushort simd_lane_id) { \+ return ctype_to_otype( \+ __metal_simd_shuffle(itype_to_ctype(data), simd_lane_id) \+ ); \+ } \+ \+ METAL_FUNC otype simd_shuffle_and_fill_down( \+ itype data, \+ itype filling_data, \+ ushort delta, \+ ushort modulo \+ ) { \+ return ctype_to_otype(__metal_simd_shuffle_and_fill_down( \+ itype_to_ctype(data), \+ itype_to_ctype(filling_data), \+ delta, \+ modulo \+ )); \+ } \+ \+ METAL_FUNC otype \+ simd_shuffle_and_fill_down(itype data, itype filling_data, ushort delta) { \+ return ctype_to_otype(__metal_simd_shuffle_and_fill_down( \+ itype_to_ctype(data), \+ itype_to_ctype(filling_data), \+ delta, \+ __metal_get_simdgroup_size(ushort()) \+ )); \+ } \+ \+ METAL_FUNC otype simd_shuffle_and_fill_up( \+ itype data, \+ itype filling_data, \+ ushort delta, \+ ushort modulo \+ ) { \+ return ctype_to_otype(__metal_simd_shuffle_and_fill_up( \+ itype_to_ctype(data), \+ itype_to_ctype(filling_data), \+ delta, \+ modulo \+ )); \+ } \+ \+ METAL_FUNC otype \+ simd_shuffle_and_fill_up(itype data, itype filling_data, ushort delta) { \+ return ctype_to_otype(__metal_simd_shuffle_and_fill_up( \+ itype_to_ctype(data), \+ itype_to_ctype(filling_data), \+ delta, \+ __metal_get_simdgroup_size(ushort()) \+ )); \+ } \+ \+ METAL_FUNC otype simd_shuffle_down(itype data, ushort delta) { \+ return ctype_to_otype( \+ __metal_simd_shuffle_down(itype_to_ctype(data), delta) \+ ); \+ } \+ \+ METAL_FUNC otype simd_shuffle_rotate_down(itype data, ushort delta) { \+ return ctype_to_otype( \+ __metal_simd_shuffle_rotate_down(itype_to_ctype(data), delta) \+ ); \+ } \+ \+ METAL_FUNC otype simd_shuffle_rotate_up(itype data, ushort delta) { \+ return ctype_to_otype( \+ __metal_simd_shuffle_rotate_up(itype_to_ctype(data), delta) \+ ); \+ } \+ \+ METAL_FUNC otype simd_shuffle_up(itype data, ushort delta) { \+ return ctype_to_otype( \+ __metal_simd_shuffle_up(itype_to_ctype(data), delta) \+ ); \+ } \+ \+ METAL_FUNC otype simd_shuffle_xor(itype data, ushort mask) { \+ return ctype_to_otype( \+ __metal_simd_shuffle_xor(itype_to_ctype(data), mask) \+ ); \}#define instantiate_metal_simd_reduction_funcs(itype, otype, ctype) \@@ -335,22 +388,26 @@ instantiate_metal_math_funcs(\METAL_FUNC otype simd_prefix_exclusive_product(itype data) { \return static_cast<otype>( \- __metal_simd_prefix_exclusive_product(static_cast<ctype>(data))); \+ __metal_simd_prefix_exclusive_product(static_cast<ctype>(data)) \+ ); \} \\METAL_FUNC otype simd_prefix_exclusive_sum(itype data) { \return static_cast<otype>( \- __metal_simd_prefix_exclusive_sum(static_cast<ctype>(data))); \+ __metal_simd_prefix_exclusive_sum(static_cast<ctype>(data)) \+ ); \} \\METAL_FUNC otype simd_prefix_inclusive_product(itype data) { \return static_cast<otype>( \- __metal_simd_prefix_inclusive_product(static_cast<ctype>(data))); \+ __metal_simd_prefix_inclusive_product(static_cast<ctype>(data)) \+ ); \} \\METAL_FUNC otype simd_prefix_inclusive_sum(itype data) { \return static_cast<otype>( \- __metal_simd_prefix_inclusive_sum(static_cast<ctype>(data))); \+ __metal_simd_prefix_inclusive_sum(static_cast<ctype>(data)) \+ ); \} \\METAL_FUNC otype simd_product(itype data) { \@@ -372,7 +429,8 @@ instantiate_metal_simd_comm_funcs(bfloat16_t,uint16_t,bfloat16_to_uint16,- uint16_to_bfloat16);+ uint16_to_bfloat16+);instantiate_metal_simd_reduction_funcs(bfloat16_t, bfloat16_t, float);} // namespace metaldiff --git a/crates/uzu/src/backends/metal/kernel/common/complex.h b/crates/uzu/src/backends/metal/kernel/common/complex.hindex 858ecd9e0..84bbbeb11 100644--- a/crates/uzu/src/backends/metal/kernel/common/complex.h+++ b/crates/uzu/src/backends/metal/kernel/common/complex.h@@ -75,9 +75,7 @@ struct complex64_t {}};-constexpr complex64_t operator-(complex64_t x) {- return {-x.real, -x.imag};-}+constexpr complex64_t operator-(complex64_t x) { return {-x.real, -x.imag}; }constexpr bool operator>=(complex64_t a, complex64_t b) {return (a.real > b.real) || (a.real == b.real && a.imag >= b.imag);@@ -111,7 +109,8 @@ constexpr thread complex64_t& operator+=(thread complex64_t& a, complex64_t b) {constexpr threadgroup complex64_t& operator+=(threadgroup complex64_t& a,- complex64_t b) {+ complex64_t b+) {a.real += b.real;a.imag += b.imag;return a;diff --git a/crates/uzu/src/backends/metal/kernel/common/defines.h b/crates/uzu/src/backends/metal/kernel/common/defines.hindex e77c28855..4ea67c43f 100644--- a/crates/uzu/src/backends/metal/kernel/common/defines.h+++ b/crates/uzu/src/backends/metal/kernel/common/defines.h@@ -17,6 +17,7 @@ static MTL_CONST constexpr int RMS_LOOPED_LIMIT = 4096;// Extra args are used as template parameters:// e.g. instantiate_kernel(binary_int, binary, a, b) ->// [[host_name(binary_int)]] [kernel] binary<a, b>-#define instantiate_kernel(name, func, ...) \- template [[host_name( \- name)]] [[kernel]] decltype(func<__VA_ARGS__>) func<__VA_ARGS__>;+#define instantiate_kernel(name, func, ...) \+ template [[host_name( \+ name \+ )]] [[kernel]] decltype(func<__VA_ARGS__>) func<__VA_ARGS__>;diff --git a/crates/uzu/src/backends/metal/kernel/common/mlp_epilogue.h b/crates/uzu/src/backends/metal/kernel/common/mlp_epilogue.hindex f7cc9376b..936a01fe8 100644--- a/crates/uzu/src/backends/metal/kernel/common/mlp_epilogue.h+++ b/crates/uzu/src/backends/metal/kernel/common/mlp_epilogue.h@@ -18,59 +18,59 @@ constant uint MLP_ACTIVATION [[function_constant(52)]];// Activation type enum for readabilityenum MlpActivationType : uint {- MLP_ACT_SILU = 0,- MLP_ACT_GELU = 1,+ MLP_ACT_SILU = 0,+ MLP_ACT_GELU = 1,};// SiLU activation: x * sigmoid(x)template <typename T>inline T mlp_silu(T x) {- float xf = float(x);- float result = xf / (1.0f + exp(-xf));- return T(result);+ float xf = float(x);+ float result = xf / (1.0f + exp(-xf));+ return T(result);}// GELU approximation (tanh-based)template <typename T>inline T mlp_gelu(T x) {- constexpr float k0 = 0.044715f;- constexpr float k1 = 0.7978845608f; // sqrt(2/pi)- float xf = float(x);- float t = k1 * (xf + k0 * xf * xf * xf);- float result = 0.5f * xf * (1.0f + metal::precise::tanh(t));- return T(result);+ constexpr float k0 = 0.044715f;+ constexpr float k1 = 0.7978845608f; // sqrt(2/pi)+ float xf = float(x);+ float t = k1 * (xf + k0 * xf * xf * xf);+ float result = 0.5f * xf * (1.0f + metal::precise::tanh(t));+ return T(result);}// Apply activation based on MLP_ACTIVATION constanttemplate <typename T>inline T mlp_activate(T x) {- if (MLP_ACTIVATION == MLP_ACT_SILU) {- return mlp_silu(x);- }- return mlp_gelu(x);+ if (MLP_ACTIVATION == MLP_ACT_SILU) {+ return mlp_silu(x);+ }+ return mlp_gelu(x);}// Fused MLP epilogue: up * activation(gate)// Used in SwiGLU (SiLU) and GeGLU (GELU) style MLPstemplate <typename T>inline T mlp_fused_epilogue(T up, T gate) {- T activated_gate = mlp_activate(gate);- return T(float(up) * float(activated_gate));+ T activated_gate = mlp_activate(gate);+ return T(float(up) * float(activated_gate));}// Fused MLP epilogue with float accumulatorsinline float mlp_fused_epilogue_f32(float up, float gate) {- float activated_gate;- if (MLP_ACTIVATION == MLP_ACT_SILU) {- activated_gate = up / (1.0f + exp(-gate));- // Note: SwiGLU is gate_act * up, not up_act * gate- // Correcting: activated_gate = gate / (1.0f + exp(-gate))- activated_gate = gate / (1.0f + exp(-gate));- } else {- constexpr float k0 = 0.044715f;- constexpr float k1 = 0.7978845608f;- float t = k1 * (gate + k0 * gate * gate * gate);- activated_gate = 0.5f * gate * (1.0f + metal::precise::tanh(t));- }- return up * activated_gate;+ float activated_gate;+ if (MLP_ACTIVATION == MLP_ACT_SILU) {+ activated_gate = up / (1.0f + exp(-gate));+ // Note: SwiGLU is gate_act * up, not up_act * gate+ // Correcting: activated_gate = gate / (1.0f + exp(-gate))+ activated_gate = gate / (1.0f + exp(-gate));+ } else {+ constexpr float k0 = 0.044715f;+ constexpr float k1 = 0.7978845608f;+ float t = k1 * (gate + k0 * gate * gate * gate);+ activated_gate = 0.5f * gate * (1.0f + metal::precise::tanh(t));+ }+ return up * activated_gate;}diff --git a/crates/uzu/src/backends/metal/kernel/common/utils.h b/crates/uzu/src/backends/metal/kernel/common/utils.hindex 05ff74458..c4e853f4c 100644--- a/crates/uzu/src/backends/metal/kernel/common/utils.h+++ b/crates/uzu/src/backends/metal/kernel/common/utils.h@@ -29,15 +29,15 @@ struct Limits {static const constant U finite_min = metal::numeric_limits<U>::min();};-#define instantiate_default_limit(type) \- template <> \- struct Limits<type> { \- static constexpr constant type max = metal::numeric_limits<type>::max(); \- static constexpr constant type min = metal::numeric_limits<type>::min(); \- static constexpr constant type finite_max = \- metal::numeric_limits<type>::max(); \- static constexpr constant type finite_min = \- metal::numeric_limits<type>::min(); \+#define instantiate_default_limit(type) \+ template <> \+ struct Limits<type> { \+ static constexpr constant type max = metal::numeric_limits<type>::max(); \+ static constexpr constant type min = metal::numeric_limits<type>::min(); \+ static constexpr constant type finite_max = \+ metal::numeric_limits<type>::max(); \+ static constexpr constant type finite_min = \+ metal::numeric_limits<type>::min(); \};instantiate_default_limit(uint8_t);@@ -49,17 +49,17 @@ instantiate_default_limit(int16_t);instantiate_default_limit(int32_t);instantiate_default_limit(int64_t);-#define instantiate_float_limit(type) \- template <> \- struct Limits<type> { \- static constexpr constant type max = \- metal::numeric_limits<type>::infinity(); \- static constexpr constant type min = \- -metal::numeric_limits<type>::infinity(); \- static constexpr constant type finite_max = \- metal::numeric_limits<type>::max(); \- static constexpr constant type finite_min = \- -metal::numeric_limits<type>::max(); \+#define instantiate_float_limit(type) \+ template <> \+ struct Limits<type> { \+ static constexpr constant type max = \+ metal::numeric_limits<type>::infinity(); \+ static constexpr constant type min = \+ -metal::numeric_limits<type>::infinity(); \+ static constexpr constant type finite_max = \+ metal::numeric_limits<type>::max(); \+ static constexpr constant type finite_min = \+ -metal::numeric_limits<type>::max(); \};instantiate_float_limit(half);@@ -76,10 +76,12 @@ template <>struct Limits<complex64_t> {static constexpr constant complex64_t max = complex64_t(metal::numeric_limits<float>::infinity(),- metal::numeric_limits<float>::infinity());+ metal::numeric_limits<float>::infinity()+ );static constexpr constant complex64_t min = complex64_t(-metal::numeric_limits<float>::infinity(),- -metal::numeric_limits<float>::infinity());+ -metal::numeric_limits<float>::infinity()+ );};///////////////////////////////////////////////////////////////////////////////@@ -96,7 +98,8 @@ METAL_FUNC IdxT elem_to_loc(IdxT elem,constant const int* shape,constant const int64_t* strides,- int ndim) {+ int ndim+) {IdxT loc = 0;for (int i = ndim - 1; i >= 0 && elem > 0; --i) {loc += (elem % shape[i]) * IdxT(strides[i]);@@ -111,7 +114,8 @@ METAL_FUNC IdxT elem_to_loc(uint3 elem,constant const int* shape,constant const int64_t* strides,- int ndim) {+ int ndim+) {IdxT loc =elem.x * IdxT(strides[ndim - 1]) + elem.y * IdxT(strides[ndim - 2]);for (int d = ndim - 3; d >= 0; --d) {@@ -137,7 +141,7 @@ METAL_FUNC IdxT elem_to_loc_2(uint2 elem, constant const int64_t strides[2]) {template <typename IdxT = int64_t>METAL_FUNC IdxT elem_to_loc_3(uint3 elem, constant const int64_t strides[3]) {return elem.x * IdxT(strides[2]) + elem.y * IdxT(strides[1]) +- elem.z * IdxT(strides[0]);+ elem.z * IdxT(strides[0]);}///////////////////////////////////////////////////////////////////////////////@@ -149,14 +153,18 @@ METAL_FUNC vec<IdxT, 2> elem_to_loc_2_nd(constant const int* shape,constant const int64_t* a_strides,constant const int64_t* b_strides,- int ndim) {+ int ndim+) {vec<IdxT, 2> loc = {IdxT(elem.x * IdxT(a_strides[ndim - 1]) +- IdxT(elem.y) * IdxT(a_strides[ndim - 2])),+ IdxT(elem.y) * IdxT(a_strides[ndim - 2])+ ),IdxT(elem.x * IdxT(b_strides[ndim - 1]) +- elem.y * IdxT(b_strides[ndim - 2]))};+ elem.y * IdxT(b_strides[ndim - 2])+ )+ };for (int d = ndim - 3; d >= 0; --d) {uint l = elem.z % shape[d];loc.x += l * IdxT(a_strides[d]);@@ -173,14 +181,16 @@ METAL_FUNC vec<IdxT, 3> elem_to_loc_3_nd(constant const int64_t* a_strides,constant const int64_t* b_strides,constant const int64_t* c_strides,- int ndim) {+ int ndim+) {vec<IdxT, 3> loc = {IdxT(elem.x * IdxT(a_strides[ndim - 1])) +IdxT(elem.y * IdxT(a_strides[ndim - 2])),IdxT(elem.x * IdxT(b_strides[ndim - 1])) +IdxT(elem.y * IdxT(b_strides[ndim - 2])),IdxT(elem.x * IdxT(c_strides[ndim - 1])) +- IdxT(elem.y * IdxT(c_strides[ndim - 2]))};+ IdxT(elem.y * IdxT(c_strides[ndim - 2]))+ };for (int d = ndim - 3; d >= 0; --d) {uint l = elem.z % shape[d];loc.x += l * IdxT(a_strides[d]);@@ -240,9 +250,7 @@ struct LoopedElemToLoc {}}- OffsetT location() {- return offset;- }+ OffsetT location() { return offset; }};template <typename OffsetT>@@ -271,9 +279,7 @@ struct LoopedElemToLoc<1, OffsetT, true> {}}- OffsetT location() {- return offset;- }+ OffsetT location() { return offset; }};template <typename OffsetT>@@ -290,9 +296,7 @@ struct LoopedElemToLoc<1, OffsetT, false> {offset += n * OffsetT(strides[0]);}- OffsetT location() {- return offset;- }+ OffsetT location() { return offset; }};///////////////////////////////////////////////////////////////////////////////@@ -353,12 +357,14 @@ inline complex64_t log1p(complex64_t in) {inline uint64_t simd_shuffle_down(uint64_t data, uint16_t delta) {return as_type<uint64_t>(- metal::simd_shuffle_down(as_type<uint2>(data), delta));+ metal::simd_shuffle_down(as_type<uint2>(data), delta)+ );}inline int64_t simd_shuffle_down(int64_t data, uint16_t delta) {return as_type<int64_t>(- metal::simd_shuffle_down(as_type<uint2>(data), delta));+ metal::simd_shuffle_down(as_type<uint2>(data), delta)+ );}inline bool simd_shuffle_down(bool data, uint16_t delta) {@@ -367,7 +373,9 @@ inline bool simd_shuffle_down(bool data, uint16_t delta) {inline complex64_t simd_shuffle_down(complex64_t data, uint16_t delta) {return complex64_t(- simd_shuffle_down(data.real, delta), simd_shuffle_down(data.imag, delta));+ simd_shuffle_down(data.real, delta),+ simd_shuffle_down(data.imag, delta)+ );}inline uint64_t simd_shuffle_up(uint64_t data, uint16_t delta) {@@ -384,33 +392,52 @@ inline bool simd_shuffle_up(bool data, uint16_t delta) {inline complex64_t simd_shuffle_up(complex64_t data, uint16_t delta) {return complex64_t(- simd_shuffle_up(data.real, delta), simd_shuffle_up(data.imag, delta));+ simd_shuffle_up(data.real, delta),+ simd_shuffle_up(data.imag, delta)+ );}-inline uint64_t-simd_shuffle_and_fill_up(uint64_t data, uint64_t filling, uint16_t delta) {+inline uint64_t simd_shuffle_and_fill_up(+ uint64_t data,+ uint64_t filling,+ uint16_t delta+) {return as_type<uint64_t>(metal::simd_shuffle_and_fill_up(- as_type<uint2>(data), as_type<uint2>(filling), delta));+ as_type<uint2>(data),+ as_type<uint2>(filling),+ delta+ ));}-inline int64_t-simd_shuffle_and_fill_up(int64_t data, int64_t filling, uint16_t delta) {+inline int64_t simd_shuffle_and_fill_up(+ int64_t data,+ int64_t filling,+ uint16_t delta+) {return as_type<int64_t>(metal::simd_shuffle_and_fill_up(- as_type<uint2>(data), as_type<uint2>(filling), delta));+ as_type<uint2>(data),+ as_type<uint2>(filling),+ delta+ ));}inline bool simd_shuffle_and_fill_up(bool data, bool filling, uint16_t delta) {return simd_shuffle_and_fill_up(- static_cast<uint32_t>(data), static_cast<uint32_t>(filling), delta);+ static_cast<uint32_t>(data),+ static_cast<uint32_t>(filling),+ delta+ );}inline complex64_t simd_shuffle_and_fill_up(complex64_t data,complex64_t filling,- uint16_t delta) {+ uint16_t delta+) {return complex64_t(simd_shuffle_and_fill_up(data.real, filling.real, delta),- simd_shuffle_and_fill_up(data.imag, filling.imag, delta));+ simd_shuffle_and_fill_up(data.imag, filling.imag, delta)+ );}inline uint64_t simd_shuffle(uint64_t data, uint16_t lane) {@@ -427,7 +454,9 @@ inline bool simd_shuffle(bool data, uint16_t lane) {inline complex64_t simd_shuffle(complex64_t data, uint16_t lane) {return complex64_t(- simd_shuffle(data.real, lane), simd_shuffle(data.imag, lane));+ simd_shuffle(data.real, lane),+ simd_shuffle(data.imag, lane)+ );}// std::conditional is not included with Metaldiff --git a/crates/uzu/src/backends/metal/kernel/matmul/common/steel/gemm/gemm.h b/crates/uzu/src/backends/metal/kernel/matmul/common/steel/gemm/gemm.hindex 52c46c46e..82a0d3ede 100644--- a/crates/uzu/src/backends/metal/kernel/matmul/common/steel/gemm/gemm.h+++ b/crates/uzu/src/backends/metal/kernel/matmul/common/steel/gemm/gemm.h@@ -85,7 +85,8 @@ struct GEMMKernel {thread const short& tgp_bm,thread const short& tgp_bn,thread const short& lbk,- LoopAlignment<M_aligned, N_aligned, K_aligned_> l = {}) {+ LoopAlignment<M_aligned, N_aligned, K_aligned_> l = {}+ ) {// Appease the compiler(void)l;@@ -146,12 +147,13 @@ struct GEMMKernel {uint simd_lane_id [[thread_index_in_simdgroup]],uint simd_group_id [[simdgroup_index_in_threadgroup]],uint3 tid [[threadgroup_position_in_grid]],- uint3 lid [[thread_position_in_threadgroup]]) {+ uint3 lid [[thread_position_in_threadgroup]]+ ) {// Pacifying compiler(void)lid;const int tid_y = ((tid.y) << params->swizzle_log) +- ((tid.x) & ((1 << params->swizzle_log) - 1));+ ((tid.x) & ((1 << params->swizzle_log) - 1));const int tid_x = (tid.x) >> params->swizzle_log;if (params->tiles_n <= tid_x || params->tiles_m <= tid_y) {@@ -236,7 +238,8 @@ struct GEMMKernel {mma_op,tgp_bm,tgp_bn,- leftover_bk);+ leftover_bk+ );mma_op.store_result(D, params->ldd);return;@@ -251,7 +254,8 @@ struct GEMMKernel {mma_op,tgp_bm,tgp_bn,- leftover_bk);+ leftover_bk+ );mma_op.store_result_safe(D, params->ldd, short2(tgp_bn, tgp_bm));return;@@ -266,7 +270,8 @@ struct GEMMKernel {mma_op,tgp_bm,tgp_bn,- leftover_bk);+ leftover_bk+ );mma_op.store_result_safe(D, params->ldd, short2(tgp_bn, tgp_bm));return;@@ -281,7 +286,8 @@ struct GEMMKernel {mma_op,tgp_bm,tgp_bn,- leftover_bk);+ leftover_bk+ );mma_op.store_result_safe(D, params->ldd, short2(tgp_bn, tgp_bm));return;diff --git a/crates/uzu/src/backends/metal/kernel/matmul/common/steel/gemm/gemm_nax.h b/crates/uzu/src/backends/metal/kernel/matmul/common/steel/gemm/gemm_nax.hindex cb836ac78..39f560249 100644--- a/crates/uzu/src/backends/metal/kernel/matmul/common/steel/gemm/gemm_nax.h+++ b/crates/uzu/src/backends/metal/kernel/matmul/common/steel/gemm/gemm_nax.h@@ -31,7 +31,8 @@ auto gemm_loop(const device T* B,const constant GEMMParams* params [[buffer(4)]],const short sgp_sm,- const short sgp_sn) {+ const short sgp_sn+) {constexpr short TM = SM / UM;constexpr short TN = SN / UN;constexpr short TK = SK / UK;@@ -89,7 +90,8 @@ auto gemm_loop(Atile,metal::bool_constant<transpose_a>{},Btile,- metal::bool_constant<transpose_b>{});+ metal::bool_constant<transpose_b>{}+ );(void)compiler_barrier;}@@ -143,7 +145,8 @@ auto gemm_loop(Atile.subtile_at(0, 0),metal::bool_constant<transpose_a>{},Btile.subtile_at(0, 0),- metal::bool_constant<transpose_b>{});+ metal::bool_constant<transpose_b>{}+ );}}}diff --git a/crates/uzu/src/backends/metal/kernel/matmul/common/steel/gemm/loader.h b/crates/uzu/src/backends/metal/kernel/matmul/common/steel/gemm/loader.hindex 1d03c83f8..7aab96e78 100644--- a/crates/uzu/src/backends/metal/kernel/matmul/common/steel/gemm/loader.h+++ b/crates/uzu/src/backends/metal/kernel/matmul/common/steel/gemm/loader.h@@ -48,13 +48,11 @@ struct BlockLoader {const int src_ld_,threadgroup T* dst_,ushort simd_group_id [[simdgroup_index_in_threadgroup]],- ushort simd_lane_id [[thread_index_in_simdgroup]])- : src_ld(src_ld_),- tile_stride(reduction_dim ? BCOLS : BROWS * src_ld),- thread_idx(simd_group_id * 32 + simd_lane_id),- bi(thread_idx / TCOLS),- bj(vec_size * (thread_idx % TCOLS)),- dst(dst_ + bi * dst_ld + bj),+ ushort simd_lane_id [[thread_index_in_simdgroup]]+ )+ : src_ld(src_ld_), tile_stride(reduction_dim ? BCOLS : BROWS * src_ld),+ thread_idx(simd_group_id * 32 + simd_lane_id), bi(thread_idx / TCOLS),+ bj(vec_size * (thread_idx % TCOLS)), dst(dst_ + bi * dst_ld + bj),src(src_ + bi * src_ld + bj) {}/* Apply operation to threadgroup without bound checking */@@ -127,9 +125,7 @@ struct BlockLoader {}/* Iteration helper */- METAL_FUNC void next() {- src += tile_stride;- }+ METAL_FUNC void next() { src += tile_stride; }};} // namespace steeldiff --git a/crates/uzu/src/backends/metal/kernel/matmul/common/steel/gemm/mma.h b/crates/uzu/src/backends/metal/kernel/matmul/common/steel/gemm/mma.hindex 38f4eec24..252e8ad5b 100644--- a/crates/uzu/src/backends/metal/kernel/matmul/common/steel/gemm/mma.h+++ b/crates/uzu/src/backends/metal/kernel/matmul/common/steel/gemm/mma.h@@ -22,10 +22,12 @@ template <typename T, int kFragRows_, int kFragCols_>struct BaseMMAFrag {static_assert(kFragRows_ == 8,- "Only 8 x 8 fragment matrices are currently supported");+ "Only 8 x 8 fragment matrices are currently supported"+ );static_assert(kFragCols_ == 8,- "Only 8 x 8 fragment matrices are currently supported");+ "Only 8 x 8 fragment matrices are currently supported"+ );};template <typename T>@@ -40,13 +42,15 @@ struct BaseMMAFrag<T, 8, 8> {static_assert(kElemRows * kElemCols == kElemsPerFrag,- "MMAFrag shape is not consistent with MMAFrag size");+ "MMAFrag shape is not consistent with MMAFrag size"+ );typedef metal::simdgroup_matrix<T, kFragRows, kFragCols> mat_type;typedef metal::vec<T, kElemsPerFrag> frag_type;- METAL_FUNC static constexpr short2 get_coord(ushort simd_lane_id- [[thread_index_in_simdgroup]]) {+ METAL_FUNC static constexpr short2 get_coord(+ ushort simd_lane_id [[thread_index_in_simdgroup]]+ ) {const short qid = simd_lane_id / 4;const short fm = (qid & 4) + ((simd_lane_id / 2) % 4);const short fn = (qid & 2) * 2 + (simd_lane_id % 2) * 2;@@ -54,8 +58,12 @@ struct BaseMMAFrag<T, 8, 8> {}template <typename SrcPtrType, typename StrX, typename StrY>- METAL_FUNC static constexpr void- load(thread frag_type& dst, SrcPtrType src, StrX str_x, StrY str_y) {+ METAL_FUNC static constexpr void load(+ thread frag_type& dst,+ SrcPtrType src,+ StrX str_x,+ StrY str_y+ ) {STEEL_PRAGMA_UNROLLfor (short i = 0; i < kElemRows; i++) {STEEL_PRAGMA_UNROLL@@ -81,7 +89,8 @@ struct BaseMMAFrag<T, 8, 8> {LimX lim_x,LimY lim_y,OffX off_x = Int<0>{},- OffY off_y = Int<0>{}) {+ OffY off_y = Int<0>{}+ ) {STEEL_PRAGMA_UNROLLfor (short i = 0; i < kElemRows; i++) {STEEL_PRAGMA_UNROLL@@ -97,8 +106,12 @@ struct BaseMMAFrag<T, 8, 8> {}template <typename DstPtrType, typename StrX, typename StrY>- METAL_FUNC static constexpr void- store(const thread frag_type& src, DstPtrType dst, StrX str_x, StrY str_y) {+ METAL_FUNC static constexpr void store(+ const thread frag_type& src,+ DstPtrType dst,+ StrX str_x,+ StrY str_y+ ) {using U = pointer_element_t<DstPtrType>;STEEL_PRAGMA_UNROLL@@ -126,7 +139,8 @@ struct BaseMMAFrag<T, 8, 8> {LimX lim_x,LimY lim_y,OffX off_x = Int<0>{},- OffY off_y = Int<0>{}) {+ OffY off_y = Int<0>{}+ ) {using U = pointer_element_t<DstPtrType>;STEEL_PRAGMA_UNROLL@@ -161,7 +175,8 @@ struct BaseMMAFrag<T, 8, 8> {StartY start_y,StopY stop_y,OffX off_x = Int<0>{},- OffY off_y = Int<0>{}) {+ OffY off_y = Int<0>{}+ ) {using U = pointer_element_t<DstPtrType>;STEEL_PRAGMA_UNROLL@@ -181,7 +196,8 @@ struct BaseMMAFrag<T, 8, 8> {thread frag_type& D,thread frag_type& A,thread frag_type& B,- thread frag_type& C) {+ thread frag_type& C+ ) {mat_type D_mat;mat_type A_mat;mat_type B_mat;@@ -200,7 +216,8 @@ struct BaseMMAFrag<T, 8, 8> {thread mat_type& D,thread mat_type& A,thread mat_type& B,- thread mat_type& C) {+ thread mat_type& C+ ) {simdgroup_multiply_accumulate(D, A, B, C);}};@@ -246,7 +263,8 @@ struct MMATile {METAL_FUNC constexpr const thread frag_type& frag_at(const short i,- const short j) const {+ const short j+ ) const {return val_frags[i * kTileCols + j];}@@ -277,9 +295,11 @@ struct MMATile {frag_at(i, j),&(src[(i * kFragRows) * w_x * str_x +- (j * kFragCols) * w_y * str_y]),+ (j * kFragCols) * w_y * str_y]+ ),Int<str_x>{},- Int<str_y>{});+ Int<str_y>{}+ );}}}@@ -294,9 +314,11 @@ struct MMATile {frag_at(i, j),&(dst[(i * kFragRows) * w_x * str_x +- (j * kFragCols) * w_y * str_y]),+ (j * kFragCols) * w_y * str_y]+ ),Int<str_x>{},- Int<str_y>{});+ Int<str_y>{}+ );}}}@@ -311,7 +333,8 @@ struct MMATile {frag_at(i, j),&(src[(i * kFragRows) * w_x * ld + (j * kFragCols) * w_y]),ld,- Int<1>{});+ Int<1>{}+ );}}}@@ -326,14 +349,18 @@ struct MMATile {frag_at(i, j),&(dst[(i * kFragRows) * w_x * ld + (j * kFragCols) * w_y]),ld,- Int<1>{});+ Int<1>{}+ );}}}template <typename U, int w_x, int w_y>- METAL_FUNC void- load_safe(const device U* src, const int ld, const short2 src_tile_dims) {+ METAL_FUNC void load_safe(+ const device U* src,+ const int ld,+ const short2 src_tile_dims+ ) {STEEL_PRAGMA_UNROLLfor (int i = 0; i < kTileRows; ++i) {STEEL_PRAGMA_UNROLL@@ -346,14 +373,18 @@ struct MMATile {src_tile_dims.y,src_tile_dims.x,(i * kFragRows) * w_x,- (j * kFragCols) * w_y);+ (j * kFragCols) * w_y+ );}}}template <typename U, int w_x, int w_y>- METAL_FUNC void- store_safe(device U* dst, const int ld, const short2 dst_tile_dims) const {+ METAL_FUNC void store_safe(+ device U* dst,+ const int ld,+ const short2 dst_tile_dims+ ) const {STEEL_PRAGMA_UNROLLfor (int i = 0; i < kTileRows; ++i) {STEEL_PRAGMA_UNROLL@@ -366,7 +397,8 @@ struct MMATile {dst_tile_dims.y,dst_tile_dims.x,(i * kFragRows) * w_x,- (j * kFragCols) * w_y);+ (j * kFragCols) * w_y+ );}}}@@ -376,7 +408,8 @@ struct MMATile {device U* dst,const int ld,const short2 start,- const short2 stop) const {+ const short2 stop+ ) const {STEEL_PRAGMA_UNROLLfor (int i = 0; i < kTileRows; ++i) {STEEL_PRAGMA_UNROLL@@ -391,7 +424,8 @@ struct MMATile {start.x,stop.x,(i * kFragRows) * w_x,- (j * kFragCols) * w_y);+ (j * kFragCols) * w_y+ );}}}@@ -402,7 +436,8 @@ METAL_FUNC void tile_matmad(thread MMATile<T, M, N>& D,thread MMATile<U, M, K>& A,thread MMATile<U, K, N>& B,- thread MMATile<T, M, N>& C) {+ thread MMATile<T, M, N>& C+) {STEEL_PRAGMA_UNROLLfor (short m = 0; m < M; ++m) {STEEL_PRAGMA_UNROLL@@ -414,7 +449,8 @@ METAL_FUNC void tile_matmad(D.frag_at(m, n_serp),A.frag_at(m, k),B.frag_at(k, n_serp),- C.frag_at(m, n_serp));+ C.frag_at(m, n_serp)+ );}}}@@ -422,12 +458,8 @@ METAL_FUNC void tile_matmad(template <typename InT>struct TransformNone<complex64_t, InT> {- static METAL_FUNC complex64_t apply(complex64_t x) {- return x;- }- static METAL_FUNC complex64_t apply(complex64_t x, complex64_t) {- return x;- }+ static METAL_FUNC complex64_t apply(complex64_t x) { return x; }+ static METAL_FUNC complex64_t apply(complex64_t x, complex64_t) { return x; }};template <@@ -486,7 +518,8 @@ struct BlockMMA {/* Constructor */METAL_FUNC BlockMMA(ushort simd_group_id [[simdgroup_index_in_threadgroup]],- ushort simd_lane_id [[thread_index_in_simdgroup]]) {+ ushort simd_lane_id [[thread_index_in_simdgroup]]+ ) {// Determine thread position in simdgroup matrixshort tm = kFragSize * (simd_group_id / WN);short tn = kFragSize * (simd_group_id % WN);@@ -544,8 +577,12 @@ struct BlockMMA {Ctile.template store<U, WM, WN>(D, ldd);}- METAL_FUNC void- store_result_slice(device U* D, const int ldd, short2 start, short2 stop) {+ METAL_FUNC void store_result_slice(+ device U* D,+ const int ldd,+ short2 start,+ short2 stop+ ) {// Apply epilogueSTEEL_PRAGMA_UNROLLfor (short i = 0; i < decltype(Ctile)::kElemsPerTile; i++) {@@ -564,8 +601,11 @@ struct BlockMMA {Ctile.template store_slice<U, WM, WN>(D, ldd, start, stop);}- METAL_FUNC void- store_result_safe(device U* D, const int ldd, short2 dst_tile_dims) {+ METAL_FUNC void store_result_safe(+ device U* D,+ const int ldd,+ short2 dst_tile_dims+ ) {// Apply epilogueSTEEL_PRAGMA_UNROLLfor (short i = 0; i < decltype(Ctile)::kElemsPerTile; i++) {@@ -598,7 +638,8 @@ struct BlockMMA {const device U* C,const int ldc,const int fdc,- thread const BinaryEpilogue& epilogue_op) {+ thread const BinaryEpilogue& epilogue_op+ ) {// Adjust for simdgroup and thread locationC += (sm)*ldc + (sn)*fdc;@@ -627,7 +668,8 @@ struct BlockMMA {const int ldc,const int fdc,short2 dst_tile_dims,- thread const BinaryEpilogue& epilogue_op) {+ thread const BinaryEpilogue& epilogue_op+ ) {// Adjust for simdgroup and thread locationC += (sm)*ldc + (sn)*fdc;dst_tile_dims -= short2(sn, sm);@@ -672,7 +714,8 @@ struct BlockMMA {const device U* C,const int ldc,const int fdc,- thread const Epilogue& epilogue_op) const {+ thread const Epilogue& epilogue_op+ ) const {// Adjust for simdgroup and thread locationC += (sm)*ldc + (sn)*fdc;D += (sm)*ldd + sn;@@ -705,7 +748,8 @@ struct BlockMMA {const int ldc,const int fdc,short2 dst_tile_dims,- thread const Epilogue& epilogue_op) const {+ thread const Epilogue& epilogue_op+ ) const {// Adjust for simdgroup and thread locationC += (sm)*ldc + (sn)*fdc;D += (sm)*ldd + sn;@@ -769,10 +813,13 @@ struct BlockMMA<Epilogue> {static_assert(metal::is_same_v<AccumType, float>,- "BlockMMA<complex64_t,...> expects float accumulators");+ "BlockMMA<complex64_t,...> expects float accumulators"+ );static_assert(metal::is_same_v<U, complex64_t>,- "For complex BlockMMA, U must be complex64_t; use a different epilogue for projections");+ "For complex BlockMMA, U must be complex64_t; use a different epilogue "+ "for projections"+ );// MMAFrag sizeSTEEL_CONST short kFragSize = 8;using MMAFrag_acc_t = BaseMMAFrag<AccumType, kFragSize, kFragSize>;@@ -818,7 +865,8 @@ struct BlockMMA</* Constructor */METAL_FUNC BlockMMA(ushort simd_group_id [[simdgroup_index_in_threadgroup]],- ushort simd_lane_id [[thread_index_in_simdgroup]]) {+ ushort simd_lane_id [[thread_index_in_simdgroup]]+ ) {// Determine thread position in simdgroup matrixshort tm = kFragSize * (simd_group_id / WN);short tn = kFragSize * (simd_group_id % WN);@@ -838,7 +886,8 @@ struct BlockMMA</* Karatsuba MMA: 3 real MMAs per K-chunk */METAL_FUNC void mma(const threadgroup complex64_t* As,- const threadgroup complex64_t* Bs) {+ const threadgroup complex64_t* Bs+ ) {// Adjust for simdgroup and thread locationAs += As_offset;Bs += Bs_offset;@@ -915,8 +964,12 @@ struct BlockMMA<}}- METAL_FUNC void- store_result_slice(device U* D, const int ldd, short2 start, short2 stop) {+ METAL_FUNC void store_result_slice(+ device U* D,+ const int ldd,+ short2 start,+ short2 stop+ ) {D += sm * ldd + sn;start -= short2(sn, sm);stop -= short2(sn, sm);@@ -946,8 +999,11 @@ struct BlockMMA<}}- METAL_FUNC void- store_result_safe(device U* D, const int ldd, short2 dst_tile_dims) {+ METAL_FUNC void store_result_safe(+ device U* D,+ const int ldd,+ short2 dst_tile_dims+ ) {D += sm * ldd + sn;dst_tile_dims -= short2(sn, sm);if (dst_tile_dims.x <= 0 || dst_tile_dims.y <= 0)@@ -977,7 +1033,8 @@ struct BlockMMA<STEEL_PRAGMA_UNROLLfor (short i = 0; i < decltype(Ctile_r)::kElemsPerTile; i++) {complex64_t out = epilogue_op.apply(- complex64_t(Ctile_r.elems()[i], Ctile_i.elems()[i]));+ complex64_t(Ctile_r.elems()[i], Ctile_i.elems()[i])+ );Ctile_r.elems()[i] = out.real;Ctile_i.elems()[i] = out.imag;}@@ -989,7 +1046,8 @@ struct BlockMMA<const device U* C,const int ldc,const int fdc,- thread const BinaryEpilogue& epilogue_op) {+ thread const BinaryEpilogue& epilogue_op+ ) {// Adjust for simdgroup and thread locationC += (sm)*ldc + (sn)*fdc;@@ -1006,7 +1064,9 @@ struct BlockMMA<STEEL_PRAGMA_UNROLLfor (short k = 0; k < decltype(Ctile_r)::kElemsPerFrag; k++) {complex64_t out = epilogue_op.apply(- complex64_t(r[k], im[k]), C[offset_c + k * fdc]);+ complex64_t(r[k], im[k]),+ C[offset_c + k * fdc]+ );r[k] = out.real;im[k] = out.imag;}@@ -1021,7 +1081,8 @@ struct BlockMMA<const int ldc,const int fdc,short2 dst_tile_dims,- thread const BinaryEpilogue& epilogue_op) {+ thread const BinaryEpilogue& epilogue_op+ ) {// Adjust for simdgroup and thread locationC += (sm)*ldc + (sn)*fdc;dst_tile_dims -= short2(sn, sm);@@ -1070,7 +1131,8 @@ struct BlockMMA<const device U* C,const int ldc,const int fdc,- thread const Epilogue& epilogue_op) const {+ thread const Epilogue& epilogue_op+ ) const {// Adjust for simdgroup and thread locationC += (sm)*ldc + (sn)*fdc;D += (sm)*ldd + sn;@@ -1105,7 +1167,8 @@ struct BlockMMA<const int ldc,const int fdc,short2 dst_tile_dims,- thread const Epilogue& epilogue_op) const {+ thread const Epilogue& epilogue_op+ ) const {// Adjust for simdgroup and thread locationC += (sm)*ldc + (sn)*fdc;D += (sm)*ldd + sn;@@ -1132,7 +1195,9 @@ struct BlockMMA<for (short k = 0; k < kelems; k++) {if ((j * TN_stride + k) < dst_tile_dims.x) {D[off_d + k] = epilogue_op.apply(- complex64_t(r[k], im[k]), C[off_c + k * fdc]);+ complex64_t(r[k], im[k]),+ C[off_c + k * fdc]+ );}}}diff --git a/crates/uzu/src/backends/metal/kernel/matmul/common/steel/gemm/nax.h b/crates/uzu/src/backends/metal/kernel/matmul/common/steel/gemm/nax.hindex 738ce48f8..e1d665fc5 100644--- a/crates/uzu/src/backends/metal/kernel/matmul/common/steel/gemm/nax.h+++ b/crates/uzu/src/backends/metal/kernel/matmul/common/steel/gemm/nax.h@@ -37,7 +37,8 @@ struct BaseNAXFrag {static_assert(kElemRows * kElemCols == kElemsPerFrag,- "MMAFrag shape is not consistent with MMAFrag size");+ "MMAFrag shape is not consistent with MMAFrag size"+ );template <typename U>using dtype_frag_t = typename metal::vec<U, kElemsPerFrag>;@@ -71,7 +72,8 @@ struct BaseNAXFrag {StrX str_x,StrY str_y,OffX off_x = {},- OffY off_y = {}) {+ OffY off_y = {}+ ) {const short2 sc = get_coord();STEEL_PRAGMA_UNROLLfor (short i = 0; i < kElemRows; i++) {@@ -108,7 +110,8 @@ struct BaseNAXFrag {StrY str_y,LimX lim_x,OffX off_x = {},- OffY off_y = {}) {+ OffY off_y = {}+ ) {const short2 sc = get_coord();STEEL_PRAGMA_UNROLLfor (short i = 0; i < kElemRows; i++) {@@ -152,7 +155,8 @@ struct BaseNAXFrag {LimX lim_x,LimY lim_y,OffX off_x = {},- OffY off_y = {}) {+ OffY off_y = {}+ ) {const short2 sc = get_coord();STEEL_PRAGMA_UNROLLfor (short i = 0; i < kElemRows; i++) {@@ -183,7 +187,8 @@ struct BaseNAXFrag {StrX str_x,StrY str_y,OffX off_x = {},- OffY off_y = {}) {+ OffY off_y = {}+ ) {using U = pointer_element_t<DstPtrType>;const short2 sc = get_coord();@@ -222,7 +227,8 @@ struct BaseNAXFrag {StrY str_y,LimX lim_x,OffX off_x = {},- OffY off_y = {}) {+ OffY off_y = {}+ ) {using U = pointer_element_t<DstPtrType>;const short2 sc = get_coord();@@ -265,7 +271,8 @@ struct BaseNAXFrag {LimX lim_x,LimY lim_y,OffX off_x = {},- OffY off_y = {}) {+ OffY off_y = {}+ ) {using U = pointer_element_t<DstPtrType>;const short2 sc = get_coord();@@ -305,7 +312,8 @@ struct BaseNAXFrag {StartY start_y,StopY stop_y,OffX off_x = Int<0>{},- OffY off_y = Int<0>{}) {+ OffY off_y = Int<0>{}+ ) {using U = pointer_element_t<DstPtrType>;const short2 sc = get_coord();@@ -332,12 +340,14 @@ struct BaseNAXFrag {template <typename Op, typename T>METAL_FUNC static constexpr void row_reduce(thread const dtype_frag_t<T>& inp_vals,- thread T* reduced_vals) {+ thread T* reduced_vals+ ) {STEEL_PRAGMA_UNROLLfor (short i = 0; i < kElemRows; i++) {T thr_reduce = Op::apply(Op::apply(inp_vals[i * kElemCols + 0], inp_vals[i * kElemCols + 1]),- Op::apply(inp_vals[i * kElemCols + 2], inp_vals[i * kElemCols + 3]));+ Op::apply(inp_vals[i * kElemCols + 2], inp_vals[i * kElemCols + 3])+ );T qgr_reduce = simd_shuffle_xor(thr_reduce, ushort(1));qgr_reduce = Op::apply(thr_reduce, qgr_reduce);@@ -352,7 +362,8 @@ struct BaseNAXFrag {template <typename Op, typename T>METAL_FUNC static constexpr void row_bin_op(thread dtype_frag_t<T>& inp_vals,- thread T* row_vals) {+ thread T* row_vals+ ) {STEEL_PRAGMA_UNROLLfor (short i = 0; i < kElemRows; i++) {STEEL_PRAGMA_UNROLL@@ -407,7 +418,8 @@ struct NAXSubTile {METAL_FUNC constexpr const thread frag_type& frag_at(const short i,- const short j) const {+ const short j+ ) const {return val_frags[i * kSubTileCols + j];}@@ -436,7 +448,9 @@ struct NAXSubTile {STEEL_PRAGMA_UNROLLfor (short j = 0; j < kSubTileCols; ++j) {NAXFrag_t::template row_reduce<Op>(- frag_at(i, j), &vals[i * kFragThrRows]);+ frag_at(i, j),+ &vals[i * kFragThrRows]+ );}}}@@ -448,7 +462,9 @@ struct NAXSubTile {STEEL_PRAGMA_UNROLLfor (short j = 0; j < kSubTileCols; ++j) {NAXFrag_t::template row_bin_op<Op>(- frag_at(i, j), &vals[i * kFragThrRows]);+ frag_at(i, j),+ &vals[i * kFragThrRows]+ );}}}@@ -464,7 +480,8 @@ struct NAXSubTile {StrX str_x,StrY str_y,OffX off_x = {},- OffY off_y = {}) {+ OffY off_y = {}+ ) {STEEL_PRAGMA_UNROLLfor (short i = 0; i < kSubTileRows; ++i) {STEEL_PRAGMA_UNROLL@@ -475,7 +492,8 @@ struct NAXSubTile {str_x,str_y,off_x + i * kFragRows,- off_y + j * kFragCols);+ off_y + j * kFragCols+ );}}}@@ -491,7 +509,8 @@ struct NAXSubTile {StrX str_x,StrY str_y,OffX off_x = {},- OffY off_y = {}) const {+ OffY off_y = {}+ ) const {STEEL_PRAGMA_UNROLLfor (short i = 0; i < kSubTileRows; ++i) {STEEL_PRAGMA_UNROLL@@ -502,7 +521,8 @@ struct NAXSubTile {str_x,str_y,off_x + i * kFragRows,- off_y + j * kFragCols);+ off_y + j * kFragCols+ );}}}@@ -520,7 +540,8 @@ struct NAXSubTile {StrY str_y,LimX lim_x,OffX off_x = {},- OffY off_y = {}) {+ OffY off_y = {}+ ) {STEEL_PRAGMA_UNROLLfor (int i = 0; i < kSubTileRows; ++i) {STEEL_PRAGMA_UNROLL@@ -532,7 +553,8 @@ struct NAXSubTile {str_y,lim_x,off_x + (i * kFragRows),- off_y + (j * kFragCols));+ off_y + (j * kFragCols)+ );}}}@@ -552,7 +574,8 @@ struct NAXSubTile {LimX lim_x,LimY lim_y,OffX off_x = {},- OffY off_y = {}) {+ OffY off_y = {}+ ) {STEEL_PRAGMA_UNROLLfor (int i = 0; i < kSubTileRows; ++i) {STEEL_PRAGMA_UNROLL@@ -565,7 +588,8 @@ struct NAXSubTile {lim_x,lim_y,off_x + (i * kFragRows),- off_y + (j * kFragCols));+ off_y + (j * kFragCols)+ );}}}@@ -585,7 +609,8 @@ struct NAXSubTile {LimX lim_x,LimY lim_y,OffX off_x = {},- OffY off_y = {}) const {+ OffY off_y = {}+ ) const {STEEL_PRAGMA_UNROLLfor (int i = 0; i < kSubTileRows; ++i) {STEEL_PRAGMA_UNROLL@@ -598,7 +623,8 @@ struct NAXSubTile {lim_x,lim_y,off_x + (i * kFragRows),- off_y + (j * kFragCols));+ off_y + (j * kFragCols)+ );}}}@@ -616,7 +642,8 @@ struct NAXSubTile {StrY str_y,LimX lim_x,OffX off_x = {},- OffY off_y = {}) const {+ OffY off_y = {}+ ) const {STEEL_PRAGMA_UNROLLfor (int i = 0; i < kSubTileRows; ++i) {STEEL_PRAGMA_UNROLL@@ -628,7 +655,8 @@ struct NAXSubTile {str_y,lim_x,off_x + (i * kFragRows),- off_y + (j * kFragCols));+ off_y + (j * kFragCols)+ );}}}@@ -652,7 +680,8 @@ struct NAXSubTile {StartY start_y,StopY stop_y,OffX off_x = Int<0>{},- OffY off_y = Int<0>{}) const {+ OffY off_y = Int<0>{}+ ) const {const_for_loop<0, kSubTileRows, 1>([&](auto idx_row) {const_for_loop<0, kSubTileCols, 1>([&](auto idx_col) {NAXFrag_t::store_slice(@@ -665,7 +694,8 @@ struct NAXSubTile {start_y,stop_y,off_x + idx_row * Int<kFragRows>{},- off_y + idx_col * Int<kFragCols>{});+ off_y + idx_col * Int<kFragCols>{}+ );});});}@@ -689,7 +719,8 @@ METAL_FUNC void subtile_matmad_nax(thread NAXSubTile<AType, RA, CA, NAXFrag_t>& A,metal::bool_constant<transpose_a>,thread NAXSubTile<BType, RB, CB, NAXFrag_t>& B,- metal::bool_constant<transpose_b>) {+ metal::bool_constant<transpose_b>+) {// Static checksconstexpr short FMa = transpose_a ? CA : RA;constexpr short FMc = RC;@@ -719,7 +750,8 @@ METAL_FUNC void subtile_matmad_nax(transpose_a,transpose_b,true,- mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate);+ mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate+ );// Create matmul opmpp::tensor_ops::matmul2d<desc, metal::execution_simdgroup> gemm_op;@@ -819,13 +851,15 @@ struct NAXTile {METAL_FUNC constexpr thread NAXSubTile_t& subtile_at(const short i,- const short j) {+ const short j+ ) {return val_subtiles[i * kTileCols + j];}METAL_FUNC constexpr const thread NAXSubTile_t& subtile_at(const short i,- const short j) const {+ const short j+ ) const {return val_subtiles[i * kTileCols + j];}@@ -877,7 +911,8 @@ struct NAXTile {Int<str_x>{},Int<str_y>{},i * kSubTileRows,- j * kSubTileCols);+ j * kSubTileCols+ );}}}@@ -893,7 +928,8 @@ struct NAXTile {Int<str_x>{},Int<str_y>{},i * kSubTileRows,- j * kSubTileCols);+ j * kSubTileCols+ );}}}@@ -905,7 +941,10 @@ struct NAXTile {STEEL_PRAGMA_UNROLLfor (short j = 0; j < kTileCols; ++j) {subtile_at(i, j).load(- &src[(i * kSubTileRows * ld + j * kSubTileCols)], ld, Int<1>{});+ &src[(i * kSubTileRows * ld + j * kSubTileCols)],+ ld,+ Int<1>{}+ );}}}@@ -917,14 +956,20 @@ struct NAXTile {STEEL_PRAGMA_UNROLLfor (short j = 0; j < kTileCols; ++j) {subtile_at(i, j).store(- &dst[(i * kSubTileRows * ld + j * kSubTileCols)], ld, Int<1>{});+ &dst[(i * kSubTileRows * ld + j * kSubTileCols)],+ ld,+ Int<1>{}+ );}}}template <typename U>- METAL_FUNC void- load_rows(const device U* src, const int ld, const short n_rows) {+ METAL_FUNC void load_rows(+ const device U* src,+ const int ld,+ const short n_rows+ ) {STEEL_PRAGMA_UNROLLfor (int i = 0; i < kTileRows; ++i) {STEEL_PRAGMA_UNROLL@@ -933,14 +978,18 @@ struct NAXTile {&src[(i * kSubTileRows) * ld + (j * kSubTileCols)],ld,Int<1>{},- n_rows - i * kSubTileRows);+ n_rows - i * kSubTileRows+ );}}}template <typename U>- METAL_FUNC void- load_safe(const device U* src, const int ld, const short2 src_tile_dims) {+ METAL_FUNC void load_safe(+ const device U* src,+ const int ld,+ const short2 src_tile_dims+ ) {STEEL_PRAGMA_UNROLLfor (int i = 0; i < kTileRows; ++i) {STEEL_PRAGMA_UNROLL@@ -952,14 +1001,18 @@ struct NAXTile {src_tile_dims.y,src_tile_dims.x,i * kSubTileRows,- j * kSubTileCols);+ j * kSubTileCols+ );}}}template <typename U>- METAL_FUNC void store_rows(device U* dst, const int ld, const short n_rows)- const {+ METAL_FUNC void store_rows(+ device U* dst,+ const int ld,+ const short n_rows+ ) const {STEEL_PRAGMA_UNROLLfor (int i = 0; i < kTileRows; ++i) {STEEL_PRAGMA_UNROLL@@ -968,14 +1021,18 @@ struct NAXTile {&dst[(i * kSubTileRows) * ld + (j * kSubTileCols)],ld,Int<1>{},- n_rows - i * kSubTileRows);+ n_rows - i * kSubTileRows+ );}}}template <typename U>- METAL_FUNC void- store_safe(device U* dst, const int ld, const short2 dst_tile_dims) const {+ METAL_FUNC void store_safe(+ device U* dst,+ const int ld,+ const short2 dst_tile_dims+ ) const {STEEL_PRAGMA_UNROLLfor (int i = 0; i < kTileRows; ++i) {STEEL_PRAGMA_UNROLL@@ -987,7 +1044,8 @@ struct NAXTile {dst_tile_dims.y,dst_tile_dims.x,i * kSubTileRows,- j * kSubTileCols);+ j * kSubTileCols+ );}}}@@ -997,7 +1055,8 @@ struct NAXTile {device U* dst,const int ld,const short2 start,- const short2 stop) const {+ const short2 stop+ ) const {const_for_loop<0, kTileRows, 1>([&](auto idx_row) {const_for_loop<0, kTileCols, 1>([&](auto idx_col) {subtile_at<idx_row.value, idx_col.value>().store_slice(@@ -1009,7 +1068,8 @@ struct NAXTile {start.x,stop.x,idx_row * Int<kSubTileRows>{},- idx_col * Int<kSubTileCols>{});+ idx_col * Int<kSubTileCols>{}+ );});});}@@ -1026,7 +1086,8 @@ METAL_FUNC void tile_matmad_nax(thread ATile& A,metal::bool_constant<transpose_a>,thread BTile& B,- metal::bool_constant<transpose_b>) {+ metal::bool_constant<transpose_b>+) {// Static checksconstexpr short TMa = transpose_a ? ATile::kTileCols : ATile::kTileRows;constexpr short TMc = CTile::kTileRows;@@ -1073,7 +1134,8 @@ METAL_FUNC void tile_matmad_nax(A.subtile_at(ra, ca),metal::bool_constant<transpose_a>{},B.subtile_at(rb, cb),- metal::bool_constant<transpose_b>{});+ metal::bool_constant<transpose_b>{}+ );}}}diff --git a/crates/uzu/src/backends/metal/kernel/matmul/common/steel/gemm/transforms.h b/crates/uzu/src/backends/metal/kernel/matmul/common/steel/gemm/transforms.hindex 8dd550212..87246822c 100644--- a/crates/uzu/src/backends/metal/kernel/matmul/common/steel/gemm/transforms.h+++ b/crates/uzu/src/backends/metal/kernel/matmul/common/steel/gemm/transforms.h@@ -12,22 +12,16 @@ namespace steel {template <typename OutT, typename InT>struct TransformNone {- static METAL_FUNC OutT apply(InT x) {- return static_cast<OutT>(x);- }+ static METAL_FUNC OutT apply(InT x) { return static_cast<OutT>(x); }- static METAL_FUNC OutT apply(InT x, OutT) {- return static_cast<OutT>(x);- }+ static METAL_FUNC OutT apply(InT x, OutT) { return static_cast<OutT>(x); }};template <typename OutT, typename InT>struct TransformAdd {TransformAdd(const float, const float) {}- static METAL_FUNC OutT apply(InT x) {- return static_cast<OutT>(x);- }+ static METAL_FUNC OutT apply(InT x) { return static_cast<OutT>(x); }static METAL_FUNC OutT apply(InT x, OutT c) {return static_cast<OutT>(x) + c;@@ -42,13 +36,12 @@ struct TransformAxpby {TransformAxpby(const float alpha_, const float beta_): alpha(alpha_), beta(beta_) {}- static METAL_FUNC OutT apply(InT x) {- return static_cast<OutT>(x);- }+ static METAL_FUNC OutT apply(InT x) { return static_cast<OutT>(x); }METAL_FUNC OutT apply(InT x, OutT c) const {return static_cast<OutT>(- x * static_cast<InT>(alpha) + (static_cast<OutT>(beta) * c));+ x * static_cast<InT>(alpha) + (static_cast<OutT>(beta) * c)+ );}};diff --git a/crates/uzu/src/backends/metal/kernel/matmul/common/steel/utils.h b/crates/uzu/src/backends/metal/kernel/matmul/common/steel/utils.hindex 2241b7f6e..0f01377d9 100644--- a/crates/uzu/src/backends/metal/kernel/matmul/common/steel/utils.h+++ b/crates/uzu/src/backends/metal/kernel/matmul/common/steel/utils.h@@ -9,7 +9,8 @@ METAL_FUNC ulong2 elem_to_loc_broadcast(constant const int* shape,constant const int64_t* a_strides,constant const int64_t* b_strides,- int ndim) {+ int ndim+) {ulong loc_a{0};ulong loc_b{0};for (int i = ndim - 1; i >= 0 && elem > 0; --i) {@@ -27,7 +28,8 @@ METAL_FUNC ulong3 elem_to_loc_broadcast(constant const int64_t* a_strides,constant const int64_t* b_strides,constant const int64_t* c_strides,- int ndim) {+ int ndim+) {ulong loc_a{0};ulong loc_b{0};ulong loc_c{0};diff --git a/crates/uzu/src/backends/metal/kernel/matmul/common/steel/utils/integral_constant.h b/crates/uzu/src/backends/metal/kernel/matmul/common/steel/utils/integral_constant.hindex 7fc91a29a..1ad59d9a7 100644--- a/crates/uzu/src/backends/metal/kernel/matmul/common/steel/utils/integral_constant.h+++ b/crates/uzu/src/backends/metal/kernel/matmul/common/steel/utils/integral_constant.h@@ -19,9 +19,7 @@ struct integral_constant {using value_type = T;using type = integral_constant;- METAL_FUNC constexpr operator value_type() const noexcept {- return value;- }+ METAL_FUNC constexpr operator value_type() const noexcept { return value; }// METAL_FUNC constexpr value_type operator()() const noexcept {// return value;@@ -50,12 +48,14 @@ using Int = integral_constant<int, val>;// Binary Operators on Integral constants///////////////////////////////////////////////////////////////////////////////-#define integral_const_binop(__op__, __operator__) \- template <typename T, T tv, typename U, U uv> \- METAL_FUNC constexpr auto __operator__( \- integral_constant<T, tv>, integral_constant<U, uv>) { \- constexpr auto res = tv __op__ uv; \- return integral_constant<decltype(res), res>{}; \+#define integral_const_binop(__op__, __operator__) \+ template <typename T, T tv, typename U, U uv> \+ METAL_FUNC constexpr auto __operator__( \+ integral_constant<T, tv>, \+ integral_constant<U, uv> \+ ) { \+ constexpr auto res = tv __op__ uv; \+ return integral_constant<decltype(res), res>{}; \}integral_const_binop(+, operator+);diff --git a/crates/uzu/src/backends/metal/kernel/matmul/gemm/mod.rs b/crates/uzu/src/backends/metal/kernel/matmul/gemm/mod.rsindex b8eda5d5d..6b041d0fc 100644--- a/crates/uzu/src/backends/metal/kernel/matmul/gemm/mod.rs+++ b/crates/uzu/src/backends/metal/kernel/matmul/gemm/mod.rs@@ -3,5 +3,5 @@ mod kernel;mod pipeline_configuration;mod tile_configuration;-pub use kernel::Kernel as GemmKernel;pub(crate) use dispatch_descriptor::DispatchDescriptor;+pub use kernel::Kernel as GemmKernel;diff --git a/crates/uzu/src/backends/metal/kernel/matmul/gemm/shaders/steel_gemm.h b/crates/uzu/src/backends/metal/kernel/matmul/gemm/shaders/steel_gemm.hindex 4c7189378..f201ef4af 100644--- a/crates/uzu/src/backends/metal/kernel/matmul/gemm/shaders/steel_gemm.h+++ b/crates/uzu/src/backends/metal/kernel/matmul/gemm/shaders/steel_gemm.h@@ -62,7 +62,7 @@ template <// Find blockconst int tid_y = ((tid.y) << params->swizzle_log) +- ((tid.x) & ((1 << params->swizzle_log) - 1));+ ((tid.x) & ((1 << params->swizzle_log) - 1));const int tid_x = (tid.x) >> params->swizzle_log;// Exit early if out of bounds@@ -76,7 +76,12 @@ template <const constant auto* B_bstrides = batch_strides + params->batch_ndim;ulong2 batch_offsets = elem_to_loc_broadcast(- tid.z, batch_shape, A_bstrides, B_bstrides, params->batch_ndim);+ tid.z,+ batch_shape,+ A_bstrides,+ B_bstrides,+ params->batch_ndim+ );A += batch_offsets.x;B += batch_offsets.y;@@ -163,9 +168,13 @@ template <}const TransformAdd<AccumType, AccumType> epilogue_op_add(- addmm_params->alpha, addmm_params->beta);+ addmm_params->alpha,+ addmm_params->beta+ );const TransformAxpby<AccumType, AccumType> epilogue_op_axpby(- addmm_params->alpha, addmm_params->beta);+ addmm_params->alpha,+ addmm_params->beta+ );///////////////////////////////////////////////////////////////////////////////// MNK aligned loop@@ -193,10 +202,18 @@ template <if (use_out_source) {if (do_axpby) {mma_op.apply_epilogue(- C, addmm_params->ldc, addmm_params->fdc, epilogue_op_axpby);+ C,+ addmm_params->ldc,+ addmm_params->fdc,+ epilogue_op_axpby+ );} else {mma_op.apply_epilogue(- C, addmm_params->ldc, addmm_params->fdc, epilogue_op_add);+ C,+ addmm_params->ldc,+ addmm_params->fdc,+ epilogue_op_add+ );}}@@ -221,16 +238,25 @@ template <tgp_bm,tgp_bn,leftover_bk,- LoopAlignment<true, true, true>{});+ LoopAlignment<true, true, true>{}+ );// Do epilogueif (use_out_source) {if (do_axpby) {mma_op.apply_epilogue(- C, addmm_params->ldc, addmm_params->fdc, epilogue_op_axpby);+ C,+ addmm_params->ldc,+ addmm_params->fdc,+ epilogue_op_axpby+ );} else {mma_op.apply_epilogue(- C, addmm_params->ldc, addmm_params->fdc, epilogue_op_add);+ C,+ addmm_params->ldc,+ addmm_params->fdc,+ epilogue_op_add+ );}}@@ -248,7 +274,8 @@ template <tgp_bm,tgp_bn,leftover_bk,- LoopAlignment<false, true, true>{});+ LoopAlignment<false, true, true>{}+ );// Do epilogueif (use_out_source) {@@ -258,14 +285,16 @@ template <addmm_params->ldc,addmm_params->fdc,short2(tgp_bn, tgp_bm),- epilogue_op_axpby);+ epilogue_op_axpby+ );} else {mma_op.apply_epilogue_safe(C,addmm_params->ldc,addmm_params->fdc,short2(tgp_bn, tgp_bm),- epilogue_op_add);+ epilogue_op_add+ );}}@@ -283,7 +312,8 @@ template <tgp_bm,tgp_bn,leftover_bk,- LoopAlignment<true, false, true>{});+ LoopAlignment<true, false, true>{}+ );// Do epilogueif (use_out_source) {@@ -293,14 +323,16 @@ template <addmm_params->ldc,addmm_params->fdc,short2(tgp_bn, tgp_bm),- epilogue_op_axpby);+ epilogue_op_axpby+ );} else {mma_op.apply_epilogue_safe(C,addmm_params->ldc,addmm_params->fdc,short2(tgp_bn, tgp_bm),- epilogue_op_add);+ epilogue_op_add+ );}}@@ -318,7 +350,8 @@ template <tgp_bm,tgp_bn,leftover_bk,- LoopAlignment<false, false, true>{});+ LoopAlignment<false, false, true>{}+ );// Do epilogueif (use_out_source) {@@ -328,14 +361,16 @@ template <addmm_params->ldc,addmm_params->fdc,short2(tgp_bn, tgp_bm),- epilogue_op_axpby);+ epilogue_op_axpby+ );} else {mma_op.apply_epilogue_safe(C,addmm_params->ldc,addmm_params->fdc,short2(tgp_bn, tgp_bm),- epilogue_op_add);+ epilogue_op_add+ );}}diff --git a/crates/uzu/src/backends/metal/kernel/matmul/gemm/shaders/steel_gemm.metal b/crates/uzu/src/backends/metal/kernel/matmul/gemm/shaders/steel_gemm.metalindex 928e3f97f..34c164aa3 100644--- a/crates/uzu/src/backends/metal/kernel/matmul/gemm/shaders/steel_gemm.metal+++ b/crates/uzu/src/backends/metal/kernel/matmul/gemm/shaders/steel_gemm.metal@@ -1,7 +1,7 @@// clang-format off-#include "../../common/utils.h"+#include "../../../common/utils.h"#include "../../common/steel/gemm/gemm.h"#include "steel_gemm.h"diff --git a/crates/uzu/src/backends/metal/kernel/matmul/gemm/shaders/steel_gemm_nax.h b/crates/uzu/src/backends/metal/kernel/matmul/gemm/shaders/steel_gemm_nax.hindex 0a7593ec8..18338aa1a 100644--- a/crates/uzu/src/backends/metal/kernel/matmul/gemm/shaders/steel_gemm_nax.h+++ b/crates/uzu/src/backends/metal/kernel/matmul/gemm/shaders/steel_gemm_nax.h@@ -50,7 +50,14 @@ void gemm_epilogue(CTile.load(C, addmm_params->ldc, addmm_params->fdc, m, n);} else {CTile.load_safe(- C, addmm_params->ldc, addmm_params->fdc, sgp_sm, sgp_sn, m, n);+ C,+ addmm_params->ldc,+ addmm_params->fdc,+ sgp_sm,+ sgp_sn,+ m,+ n+ );}auto delems = Dtile.subtile_at(mm, nn).elems();@@ -60,7 +67,7 @@ void gemm_epilogue(for (short i = 0; i < kElemsPerSubTile; i++) {if (do_axpby) {delems[i] = addmm_params->alpha * delems[i] +- addmm_params->beta * static_cast<V>(celems[i]);+ addmm_params->beta * static_cast<V>(celems[i]);} else {delems[i] += static_cast<V>(celems[i]);}@@ -93,7 +100,7 @@ template <uint3 tid [[threadgroup_position_in_grid]]) { // clang-format on// Find blockconst int tid_y = ((tid.y) << params->swizzle_log) +- ((tid.x) & ((1 << params->swizzle_log) - 1));+ ((tid.x) & ((1 << params->swizzle_log) - 1));const int tid_x = (tid.x) >> params->swizzle_log;// Exit early if out of bounds@@ -107,7 +114,12 @@ template <const constant auto* B_bstrides = batch_strides + params->batch_ndim;ulong2 batch_offsets = elem_to_loc_broadcast(- tid.z, batch_shape, A_bstrides, B_bstrides, params->batch_ndim);+ tid.z,+ batch_shape,+ A_bstrides,+ B_bstrides,+ params->batch_ndim+ );A += batch_offsets.x;B += batch_offsets.y;@@ -194,7 +206,13 @@ template <AccumType>(A, B, params, sgp_sm, sgp_sn);if (use_out_source) {gemm_epilogue<kAlignedM.value, kAlignedN.value>(- Dtile, C, params, addmm_params, sgp_sm, sgp_sn);+ Dtile,+ C,+ params,+ addmm_params,+ sgp_sm,+ sgp_sn+ );}if constexpr (kAlignedM && kAlignedN) {Dtile.store(D, int(params->ldd));diff --git a/crates/uzu/src/backends/metal/kernel/matmul/gemm/shaders/steel_gemm_nax.metal b/crates/uzu/src/backends/metal/kernel/matmul/gemm/shaders/steel_gemm_nax.metalindex 8a3070c0d..286b81152 100644--- a/crates/uzu/src/backends/metal/kernel/matmul/gemm/shaders/steel_gemm_nax.metal+++ b/crates/uzu/src/backends/metal/kernel/matmul/gemm/shaders/steel_gemm_nax.metal@@ -2,7 +2,7 @@#include <metal_stdlib>-#include "../../common/utils.h"+#include "../../../common/utils.h"#include "../../common/steel/gemm/gemm_nax.h"#include "steel_gemm_nax.h"diff --git a/crates/uzu/src/backends/metal/kernel/matmul/gemv/dispatch_descriptor.rs b/crates/uzu/src/backends/metal/kernel/matmul/gemv/dispatch_descriptor.rsindex 94344f824..a004d8361 100644--- a/crates/uzu/src/backends/metal/kernel/matmul/gemv/dispatch_descriptor.rs+++ b/crates/uzu/src/backends/metal/kernel/matmul/gemv/dispatch_descriptor.rs@@ -78,7 +78,9 @@ impl DispatchDescriptor {let (do_axpby, alpha, beta, bias_stride) = match axpby_source {AxpbySource::None => (false, 1.0f32, 0.0f32, 0),AxpbySource::Bias => (true, 1.0f32, 1.0f32, 1),- AxpbySource::C => (true, arguments.alpha, arguments.beta, arguments.ldd),+ AxpbySource::C => {+ (true, arguments.alpha, arguments.beta, arguments.ldd)+ },};let output_dimension = if matrix_is_rhs {diff --git a/crates/uzu/src/backends/metal/kernel/matmul/gemv/mod.rs b/crates/uzu/src/backends/metal/kernel/matmul/gemv/mod.rsindex ca3ea07c9..5ee340249 100644--- a/crates/uzu/src/backends/metal/kernel/matmul/gemv/mod.rs+++ b/crates/uzu/src/backends/metal/kernel/matmul/gemv/mod.rs@@ -2,5 +2,5 @@ mod dispatch_descriptor;mod kernel;mod pipeline_configuration;-pub use kernel::Kernel as GemvKernel;pub(crate) use dispatch_descriptor::DispatchDescriptor;+pub use kernel::Kernel as GemvKernel;diff --git a/crates/uzu/src/backends/metal/kernel/matmul/gemv/shaders/gemv.metal b/crates/uzu/src/backends/metal/kernel/matmul/gemv/shaders/gemv.metalindex ff714458a..9d5538a0e 100644--- a/crates/uzu/src/backends/metal/kernel/matmul/gemv/shaders/gemv.metal+++ b/crates/uzu/src/backends/metal/kernel/matmul/gemv/shaders/gemv.metal@@ -1,7 +1,7 @@#include <metal_simdgroup>#include <metal_stdlib>-#include "../../common/utils.h"+#include "../../../common/utils.h"#include "../../common/steel/utils.h"@@ -24,12 +24,12 @@ struct DefaultAccT<complex64_t> {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 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 = typename DefaultAccT<T>::type>struct GEMVKernel {@@ -45,7 +45,8 @@ struct GEMVKernel {static_assert(SN == 4 || SN == 8 || SN == 16 || SN == 32,- "gemv block must have a width of 4, 8, 16, or 32");+ "gemv block must have a width of 4, 8, 16, or 32"+ );// - The matrix of size (M = out_vec_size, K = in_vec_size) is divided up// into blocks of (blockM, blockN) divided among threadgroups@@ -71,8 +72,11 @@ struct GEMVKernel {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) {+ static METAL_FUNC void load_unsafe(+ const device T* src,+ thread U dst[TN],+ const int src_offset = 0+ ) {MTL_PRAGMA_UNROLLfor (int tn = 0; tn < TN; tn++) {dst[tn] = static_cast<U>(src[src_offset + tn]);@@ -84,7 +88,8 @@ struct GEMVKernel {const device T* src,thread U dst[TN],const int src_offset = 0,- const int src_size = TN) {+ const int src_size = TN+ ) {if (src_offset + TN <= src_size) {MTL_PRAGMA_UNROLLfor (int tn = 0; tn < TN; tn++) {@@ -94,8 +99,8 @@ struct GEMVKernel {MTL_PRAGMA_UNROLLfor (int tn = 0; tn < TN; tn++) {dst[tn] = src_offset + tn < src_size- ? static_cast<U>(src[src_offset + tn])- : U(0);+ ? static_cast<U>(src[src_offset + tn])+ : U(0);}}}@@ -115,7 +120,8 @@ struct GEMVKernel {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]]) {+ uint simd_lid [[thread_index_in_simdgroup]]+ ) {// Appease compiler(void)lid;@@ -248,12 +254,12 @@ struct GEMVKernel {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 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 = typename DefaultAccT<T>::type>struct GEMVTKernel {@@ -304,7 +310,8 @@ struct GEMVTKernel {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]]) {+ uint simd_lid [[thread_index_in_simdgroup]]+ ) {// Appease compiler(void)lid;@@ -435,15 +442,15 @@ struct GEMVTKernel {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 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 */-[[kernel, max_total_threads_per_threadgroup(BM* BN * 32)]] void gemv(+ const bool kDoAxpby> /* Do out = alpha * out + beta * bias */+[[kernel, max_total_threads_per_threadgroup(BM * BN * 32)]] void gemv(const device T* mat [[buffer(0)]],const device T* in_vec [[buffer(1)]],const device T* bias [[buffer(2)]],@@ -462,7 +469,8 @@ template <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]]) {+ uint simd_lid [[thread_index_in_simdgroup]]+) {using gemv_kernel = GEMVKernel<T, BM, BN, SM, SN, TM, TN, kDoAxpby>;threadgroup typename gemv_kernel::acc_type tgp_memory[gemv_kernel::tgp_mem_size == 0 ? 1 : gemv_kernel::tgp_mem_size];@@ -502,24 +510,36 @@ template <tid,lid,simd_gid,- simd_lid);+ simd_lid+ );}-#define instantiate_gemv_helper( \- name, itype, bm, bn, sm, sn, tm, tn, nc, axpby) \- instantiate_kernel( \- "gemv_" #name "_bm" #bm "_bn" #bn "_sm" #sm "_sn" #sn "_tm" #tm \- "_tn" #tn "_nc" #nc "_axpby" #axpby, \- gemv, \- itype, \- bm, \- bn, \- sm, \- sn, \- tm, \- tn, \- nc, \- axpby)+#define instantiate_gemv_helper( \+ name, \+ itype, \+ bm, \+ bn, \+ sm, \+ sn, \+ tm, \+ tn, \+ nc, \+ axpby \+) \+ instantiate_kernel( \+ "gemv_" #name "_bm" #bm "_bn" #bn "_sm" #sm "_sn" #sn "_tm" #tm \+ "_tn" #tn "_nc" #nc "_axpby" #axpby, \+ gemv, \+ itype, \+ bm, \+ bn, \+ sm, \+ sn, \+ tm, \+ tn, \+ nc, \+ axpby \+ )// clang-format off#define instantiate_gemv(name, itype, bm, bn, sm, sn, tm, tn) \@@ -551,7 +571,7 @@ template <const int SN, /* Simdgroup cols (in threads) */const int TM, /* Thread rows (in elements) */const int TN> /* Thread cols (in elements) */-[[kernel, max_total_threads_per_threadgroup(BM* BN * 32)]] void gemv_gather(+[[kernel, max_total_threads_per_threadgroup(BM * BN * 32)]] void gemv_gather(const device T* mat [[buffer(0)]],const device T* in_vec [[buffer(1)]],const device T* bias [[buffer(2)]],@@ -575,7 +595,8 @@ template <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]]) {+ uint simd_lid [[thread_index_in_simdgroup]]+) {using gemv_kernel = GEMVKernel<T, BM, BN, SM, SN, TM, TN, false>;threadgroup typename gemv_kernel::acc_type tgp_memory[gemv_kernel::tgp_mem_size == 0 ? 1 : gemv_kernel::tgp_mem_size];@@ -589,7 +610,12 @@ template <const constant auto* mati_bstrides = index_batch_strides + batch_ndim;ulong2 batch_offsets = elem_to_loc_broadcast(- tid.z, batch_shape, veci_bstrides, mati_bstrides, batch_ndim);+ tid.z,+ batch_shape,+ veci_bstrides,+ mati_bstrides,+ batch_ndim+ );indx_vec = vec_indices[batch_offsets.x];indx_mat = mat_indices[batch_offsets.y];@@ -601,14 +627,22 @@ template <if (vector_batch_ndim > 1) {in_vec += elem_to_loc(- indx_vec, vector_batch_shape, vector_batch_stride, vector_batch_ndim);+ indx_vec,+ vector_batch_shape,+ vector_batch_stride,+ vector_batch_ndim+ );} else {in_vec += indx_vec * vector_batch_stride[0];}if (matrix_batch_ndim > 1) {mat += elem_to_loc(- indx_mat, matrix_batch_shape, matrix_batch_stride, matrix_batch_ndim);+ indx_mat,+ matrix_batch_shape,+ matrix_batch_stride,+ matrix_batch_ndim+ );} else {mat += indx_mat * matrix_batch_stride[0];}@@ -630,7 +664,8 @@ template <tid,lid,simd_gid,- simd_lid);+ simd_lid+ );}// clang-format off@@ -656,15 +691,15 @@ instantiate_gemv_bs_blocks(complex64, complex64_t);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 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 */-[[kernel, max_total_threads_per_threadgroup(BM* BN * 32)]] void gemv_t(+ const bool kDoAxpby> /* Do out = alpha * out + beta * bias */+[[kernel, max_total_threads_per_threadgroup(BM * BN * 32)]] void gemv_t(const device T* mat [[buffer(0)]],const device T* in_vec [[buffer(1)]],const device T* bias [[buffer(2)]],@@ -683,7 +718,8 @@ template <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]]) {+ uint simd_lid [[thread_index_in_simdgroup]]+) {using gemv_kernel = GEMVTKernel<T, BM, BN, SM, SN, TM, TN, kDoAxpby>;threadgroup typename gemv_kernel::acc_type tgp_memory[gemv_kernel::tgp_mem_size == 0 ? 1 : gemv_kernel::tgp_mem_size];@@ -723,7 +759,8 @@ template <tid,lid,simd_gid,- simd_lid);+ simd_lid+ );}// clang-format off@@ -762,7 +799,7 @@ template <const int SN, /* Simdgroup cols (in threads) */const int TM, /* Thread rows (in elements) */const int TN> /* Thread cols (in elements) */-[[kernel, max_total_threads_per_threadgroup(BM* BN * 32)]] void gemv_t_gather(+[[kernel, max_total_threads_per_threadgroup(BM * BN * 32)]] void gemv_t_gather(const device T* mat [[buffer(0)]],const device T* in_vec [[buffer(1)]],const device T* bias [[buffer(2)]],@@ -786,7 +823,8 @@ template <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]]) {+ uint simd_lid [[thread_index_in_simdgroup]]+) {using gemv_kernel = GEMVTKernel<T, BM, BN, SM, SN, TM, TN, false>;threadgroup typename gemv_kernel::acc_type tgp_memory[gemv_kernel::tgp_mem_size == 0 ? 1 : gemv_kernel::tgp_mem_size];@@ -800,7 +838,12 @@ template <const constant auto* mati_bstrides = index_batch_strides + batch_ndim;ulong2 batch_offsets = elem_to_loc_broadcast(- tid.z, batch_shape, veci_bstrides, mati_bstrides, batch_ndim);+ tid.z,+ batch_shape,+ veci_bstrides,+ mati_bstrides,+ batch_ndim+ );indx_vec = vec_indices[batch_offsets.x];indx_mat = mat_indices[batch_offsets.y];@@ -812,14 +855,22 @@ template <if (vector_batch_ndim > 1) {in_vec += elem_to_loc(- indx_vec, vector_batch_shape, vector_batch_stride, vector_batch_ndim);+ indx_vec,+ vector_batch_shape,+ vector_batch_stride,+ vector_batch_ndim+ );} else {in_vec += indx_vec * vector_batch_stride[0];}if (matrix_batch_ndim > 1) {mat += elem_to_loc(- indx_mat, matrix_batch_shape, matrix_batch_stride, matrix_batch_ndim);+ indx_mat,+ matrix_batch_shape,+ matrix_batch_stride,+ matrix_batch_ndim+ );} else {mat += indx_mat * matrix_batch_stride[0];}@@ -841,7 +892,8 @@ template <tid,lid,simd_gid,- simd_lid);+ simd_lid+ );}// clang-format offdiff --git a/crates/uzu/src/backends/metal/kernel/matmul/split_k/dispatch_descriptor.rs b/crates/uzu/src/backends/metal/kernel/matmul/split_k/dispatch_descriptor.rsindex a052e8d66..8f5a0723e 100644--- a/crates/uzu/src/backends/metal/kernel/matmul/split_k/dispatch_descriptor.rs+++ b/crates/uzu/src/backends/metal/kernel/matmul/split_k/dispatch_descriptor.rs@@ -56,8 +56,7 @@ impl DispatchDescriptor {let tile = select_tile_configuration(m, n);let partition_count = compute_partition_count(k);- let mn_aligned =- (m % tile.tile_rows) == 0 && (n % tile.tile_cols) == 0;+ let mn_aligned = (m % tile.tile_rows) == 0 && (n % tile.tile_cols) == 0;let k_aligned = (k % tile.tile_depth) == 0;let pipeline_configuration = PipelineConfiguration {@@ -138,7 +137,12 @@ fn compute_partition_count(k: i32) -> i32 {}}-fn should_use_splitk(m: i32, n: i32, k: i32, batch_count: i32) -> bool {+fn should_use_splitk(+ m: i32,+ n: i32,+ k: i32,+ batch_count: i32,+) -> bool {if batch_count != 1 {return false;}diff --git a/crates/uzu/src/backends/metal/kernel/matmul/split_k/mod.rs b/crates/uzu/src/backends/metal/kernel/matmul/split_k/mod.rsindex 22383d1f8..029fa0f90 100644--- a/crates/uzu/src/backends/metal/kernel/matmul/split_k/mod.rs+++ b/crates/uzu/src/backends/metal/kernel/matmul/split_k/mod.rs@@ -3,5 +3,5 @@ mod kernel;mod pipeline_configuration;mod tile_configuration;-pub use kernel::Kernel as SplitKGemm;pub(crate) use dispatch_descriptor::DispatchDescriptor;+pub use kernel::Kernel as SplitKGemm;diff --git a/crates/uzu/src/backends/metal/kernel/matmul/split_k/shaders/steel_gemm_splitk.h b/crates/uzu/src/backends/metal/kernel/matmul/split_k/shaders/steel_gemm_splitk.hindex 4d1203149..24302129b 100644--- a/crates/uzu/src/backends/metal/kernel/matmul/split_k/shaders/steel_gemm_splitk.h+++ b/crates/uzu/src/backends/metal/kernel/matmul/split_k/shaders/steel_gemm_splitk.h@@ -18,7 +18,7 @@ template <bool transpose_b,bool MN_aligned,bool K_aligned>-[[kernel, max_total_threads_per_threadgroup(WM* WN * 32)]] void gemm_splitk(+[[kernel, max_total_threads_per_threadgroup(WM * WN * 32)]] void gemm_splitk(const device T* A [[buffer(0)]],const device T* B [[buffer(1)]],device U* C [[buffer(2)]],@@ -26,7 +26,8 @@ template <uint simd_lane_id [[thread_index_in_simdgroup]],uint simd_group_id [[simdgroup_index_in_threadgroup]],uint3 tid [[threadgroup_position_in_grid]],- uint3 lid [[thread_position_in_threadgroup]]) {+ uint3 lid [[thread_position_in_threadgroup]]+) {(void)lid;using gemm_kernel = GEMMKernel<@@ -70,7 +71,7 @@ template <B += transpose_b ? (k_start_long + c_col_long * params->ldb): (c_col_long + k_start_long * params->ldb);C += (size_t(params->split_k_partition_stride) * tid_z) +- (c_row_long * params->ldc + c_col_long);+ (c_row_long * params->ldc + c_col_long);// Prepare threadgroup loading operationsthread loader_a_t loader_a(A, params->lda, As, simd_group_id, simd_lane_id);@@ -96,7 +97,8 @@ template <tgp_bm,tgp_bn,leftover_bk,- LoopAlignment<true, true, true>{});+ LoopAlignment<true, true, true>{}+ );} else if (tgp_bn == BN) {gemm_kernel::gemm_loop(As,@@ -108,7 +110,8 @@ template <tgp_bm,tgp_bn,leftover_bk,- LoopAlignment<false, true, true>{});+ LoopAlignment<false, true, true>{}+ );} else if (tgp_bm == BM) {gemm_kernel::gemm_loop(As,@@ -120,7 +123,8 @@ template <tgp_bm,tgp_bn,leftover_bk,- LoopAlignment<true, false, true>{});+ LoopAlignment<true, false, true>{}+ );} else {gemm_kernel::gemm_loop(As,@@ -132,7 +136,8 @@ template <tgp_bm,tgp_bn,leftover_bk,- LoopAlignment<false, false, true>{});+ LoopAlignment<false, false, true>{}+ );}threadgroup_barrier(mem_flags::mem_threadgroup);@@ -151,7 +156,8 @@ template <tgp_bm,tgp_bn,leftover_bk,- LoopAlignment<false, false, K_aligned>{});+ LoopAlignment<false, false, K_aligned>{}+ );}if (MN_aligned || (tgp_bm == BM && tgp_bn == BN)) {@@ -175,7 +181,8 @@ template <const constant int& k_partitions [[buffer(2)]],const constant int& partition_stride [[buffer(3)]],const constant int& ldd [[buffer(4)]],- uint2 gid [[thread_position_in_grid]]) {+ uint2 gid [[thread_position_in_grid]]+) {// Ajust D and CD += gid.x + gid.y * size_t(ldd);C_split += gid.x + gid.y * size_t(ldd);@@ -207,7 +214,8 @@ template <const constant int& fdc [[buffer(7)]],const constant float& alpha [[buffer(8)]],const constant float& beta [[buffer(9)]],- uint2 gid [[thread_position_in_grid]]) {+ uint2 gid [[thread_position_in_grid]]+) {// Ajust D and CC += gid.x * size_t(fdc) + gid.y * size_t(ldc);D += gid.x + gid.y * size_t(ldd);diff --git a/crates/uzu/src/backends/metal/kernel/matmul/split_k/shaders/steel_gemm_splitk.metal b/crates/uzu/src/backends/metal/kernel/matmul/split_k/shaders/steel_gemm_splitk.metalindex 07cf0b530..34c61e201 100644--- a/crates/uzu/src/backends/metal/kernel/matmul/split_k/shaders/steel_gemm_splitk.metal+++ b/crates/uzu/src/backends/metal/kernel/matmul/split_k/shaders/steel_gemm_splitk.metal@@ -1,7 +1,7 @@// clang-format off-#include "../../common/utils.h"+#include "../../../common/utils.h"#include "../../common/steel/gemm/gemm.h"#include "steel_gemm_splitk.h"diff --git a/crates/uzu/src/backends/metal/kernel/matmul/split_k/tile_configuration.rs b/crates/uzu/src/backends/metal/kernel/matmul/split_k/tile_configuration.rsindex d2abe25d8..d8f86ecf5 100644--- a/crates/uzu/src/backends/metal/kernel/matmul/split_k/tile_configuration.rs+++ b/crates/uzu/src/backends/metal/kernel/matmul/split_k/tile_configuration.rs@@ -7,9 +7,20 @@ pub struct TileConfiguration {pub warps_per_col: i32,}-pub fn select_tile_configuration(m: i32, n: i32) -> TileConfiguration {- let tile_rows = if m < 40 { 16 } else { 32 };- let tile_cols = if n < 40 { 16 } else { 32 };+pub fn select_tile_configuration(+ m: i32,+ n: i32,+) -> TileConfiguration {+ let tile_rows = if m < 40 {+ 16+ } else {+ 32+ };+ let tile_cols = if n < 40 {+ 16+ } else {+ 32+ };TileConfiguration {tile_rows,tile_cols,diff --git a/crates/uzu/src/backends/metal/kernel/mlp_fused/gemm/steel_gemm_mlp_fused.h b/crates/uzu/src/backends/metal/kernel/mlp_fused/gemm/steel_gemm_mlp_fused.hindex 6b945428b..6f914713f 100644--- a/crates/uzu/src/backends/metal/kernel/mlp_fused/gemm/steel_gemm_mlp_fused.h+++ b/crates/uzu/src/backends/metal/kernel/mlp_fused/gemm/steel_gemm_mlp_fused.h@@ -15,8 +15,8 @@ namespace steel {///////////////////////////////////////////////////////////////////////////////// MLP Fused GEMM Kernel// Computes paired up/gate projections with fused activation for prefill path.-// Weight layout: B = [up_weights (hidden_dim cols), gate_weights (hidden_dim cols)]-// Output = up * activation(gate), written to first hidden_dim columns+// Weight layout: B = [up_weights (hidden_dim cols), gate_weights (hidden_dim+// cols)] Output = up * activation(gate), written to first hidden_dim columns///////////////////////////////////////////////////////////////////////////////template <@@ -84,11 +84,12 @@ struct GEMMMlpFusedKernel {uint simd_lane_id [[thread_index_in_simdgroup]],uint simd_group_id [[simdgroup_index_in_threadgroup]],uint3 tid [[threadgroup_position_in_grid]],- uint3 lid [[thread_position_in_threadgroup]]) {+ uint3 lid [[thread_position_in_threadgroup]]+ ) {(void)lid;const int tid_y = ((tid.y) << params->swizzle_log) +- ((tid.x) & ((1 << params->swizzle_log) - 1));+ ((tid.x) & ((1 << params->swizzle_log) - 1));const int tid_x = (tid.x) >> params->swizzle_log;// Only process tiles within hidden_dim columns (output size)@@ -105,12 +106,15 @@ struct GEMMMlpFusedKernel {const size_t c_col_long = size_t(c_col);// Pointer to A (input activations)- const device T* A_ptr = A + (transpose_a ? c_row_long : c_row_long * params->lda);+ const device T* A_ptr =+ A + (transpose_a ? c_row_long : c_row_long * params->lda);// Pointers to up and gate weights in B// B layout: [up_weights | gate_weights] where each is hidden_dim columns- const device T* B_up = B + (transpose_b ? c_col_long * params->ldb : c_col_long);- const device T* B_gate = B_up + (transpose_b ? hidden_dim * params->ldb : hidden_dim);+ const device T* B_up =+ B + (transpose_b ? c_col_long * params->ldb : c_col_long);+ const device T* B_gate =+ B_up + (transpose_b ? hidden_dim * params->ldb : hidden_dim);device U* D_ptr = D + c_row_long * params->ldd + c_col_long;@@ -118,9 +122,17 @@ struct GEMMMlpFusedKernel {threadgroup T* Bs_gate = Bs_up + (tgp_mem_size_b / 2);// Loaders for A (shared) and B (up and gate)- thread loader_a_t loader_a(A_ptr, params->lda, As, simd_group_id, simd_lane_id);- thread loader_b_t loader_b_up(B_up, params->ldb, Bs_up, simd_group_id, simd_lane_id);- thread loader_b_t loader_b_gate(B_gate, params->ldb, Bs_gate, simd_group_id, simd_lane_id);+ thread loader_a_t+ loader_a(A_ptr, params->lda, As, simd_group_id, simd_lane_id);+ thread loader_b_t+ loader_b_up(B_up, params->ldb, Bs_up, simd_group_id, simd_lane_id);+ thread loader_b_t loader_b_gate(+ B_gate,+ params->ldb,+ Bs_gate,+ simd_group_id,+ simd_lane_id+ );// MMA operations for up and gatethread mma_t mma_up(simd_group_id, simd_lane_id);@@ -137,7 +149,8 @@ struct GEMMMlpFusedKernel {loader_a.load_unsafe();} else {short tgp_bm = min(short(BM), short(params->M - c_row));- short2 tile_dims_A = transpose_a ? short2(tgp_bm, BK) : short2(BK, tgp_bm);+ short2 tile_dims_A =+ transpose_a ? short2(tgp_bm, BK) : short2(BK, tgp_bm);loader_a.load_safe(tile_dims_A);}@@ -147,7 +160,8 @@ struct GEMMMlpFusedKernel {loader_b_gate.load_unsafe();} else {short tgp_bn = min(short(BN), short(hidden_dim - c_col));- short2 tile_dims_B = transpose_b ? short2(BK, tgp_bn) : short2(tgp_bn, BK);+ short2 tile_dims_B =+ transpose_b ? short2(BK, tgp_bn) : short2(tgp_bn, BK);loader_b_up.load_safe(tile_dims_B);loader_b_gate.load_safe(tile_dims_B);}@@ -185,7 +199,7 @@ struct GEMMMlpFusedKernel {// Access the Ctile elements and apply fusionconstexpr int kElemsPerTile = decltype(mma_up.Ctile)::kElemsPerTile;- #pragma unroll+#pragma unrollfor (short i = 0; i < kElemsPerTile; i++) {float up_val = static_cast<float>(mma_up.Ctile.elems()[i]);float gate_val = static_cast<float>(mma_gate.Ctile.elems()[i]);diff --git a/crates/uzu/src/backends/metal/kernel/mlp_fused/gemm/steel_gemm_mlp_fused.metal b/crates/uzu/src/backends/metal/kernel/mlp_fused/gemm/steel_gemm_mlp_fused.metalindex 35ffc4949..850b63b6c 100644--- a/crates/uzu/src/backends/metal/kernel/mlp_fused/gemm/steel_gemm_mlp_fused.metal+++ b/crates/uzu/src/backends/metal/kernel/mlp_fused/gemm/steel_gemm_mlp_fused.metal@@ -10,22 +10,47 @@ using namespace metal;// For prefill path: computes up * activation(gate) in a single pass///////////////////////////////////////////////////////////////////////////////-#define instantiate_mlp_fused_gemm( \- tname, trans_a, trans_b, itype, otype, bm, bn, bk, wm, wn, aname, mn, k) \- template [[host_name("steel_gemm_mlp_fused_" #tname "_" #itype "_" #otype \- "_bm" #bm "_bn" #bn "_bk" #bk "_wm" #wm "_wn" #wn \- "_" #aname "_MN_" #mn "_K_" #k)]] [[kernel]] void \- steel_gemm_mlp_fused< \- itype, otype, bm, bn, bk, wm, wn, trans_a, trans_b, mn, k>( \- const device itype* A [[buffer(0)]], \- const device itype* B [[buffer(1)]], \- device otype* D [[buffer(2)]], \- const constant steel::GEMMParams* params [[buffer(3)]], \- const constant int& hidden_dim [[buffer(10)]], \- uint simd_lane_id [[thread_index_in_simdgroup]], \- uint simd_group_id [[simdgroup_index_in_threadgroup]], \- uint3 tid [[threadgroup_position_in_grid]], \- uint3 lid [[thread_position_in_threadgroup]])+#define instantiate_mlp_fused_gemm( \+ tname, \+ trans_a, \+ trans_b, \+ itype, \+ otype, \+ bm, \+ bn, \+ bk, \+ wm, \+ wn, \+ aname, \+ mn, \+ k \+) \+ template [[host_name( \+ "steel_gemm_mlp_fused_" #tname "_" #itype "_" #otype "_bm" #bm "_bn" #bn \+ "_bk" #bk "_wm" #wm "_wn" #wn "_" #aname "_MN_" #mn "_K_" #k \+ )]] [[kernel]] void \+ steel_gemm_mlp_fused< \+ itype, \+ otype, \+ bm, \+ bn, \+ bk, \+ wm, \+ wn, \+ trans_a, \+ trans_b, \+ mn, \+ k>( \+ const device itype* A [[buffer(0)]], \+ const device itype* B [[buffer(1)]], \+ device otype* D [[buffer(2)]], \+ const constant steel::GEMMParams* params [[buffer(3)]], \+ const constant int& hidden_dim [[buffer(10)]], \+ uint simd_lane_id [[thread_index_in_simdgroup]], \+ uint simd_group_id [[simdgroup_index_in_threadgroup]], \+ uint3 tid [[threadgroup_position_in_grid]], \+ uint3 lid [[thread_position_in_threadgroup]] \+ )template <typename T,@@ -39,7 +64,7 @@ template <bool transpose_b,bool MN_aligned,bool K_aligned>-[[kernel, max_total_threads_per_threadgroup(WM* WN * 32)]] void+[[kernel, max_total_threads_per_threadgroup(WM * WN * 32)]] voidsteel_gemm_mlp_fused(const device T* A [[buffer(0)]],const device T* B [[buffer(1)]],@@ -49,61 +74,532 @@ steel_gemm_mlp_fused(uint simd_lane_id [[thread_index_in_simdgroup]],uint simd_group_id [[simdgroup_index_in_threadgroup]],uint3 tid [[threadgroup_position_in_grid]],- uint3 lid [[thread_position_in_threadgroup]]) {- using kernel_t =- steel::GEMMMlpFusedKernel<T, U, BM, BN, BK, WM, WN, transpose_a, transpose_b, MN_aligned, K_aligned>;+ uint3 lid [[thread_position_in_threadgroup]]+) {+ using kernel_t = steel::GEMMMlpFusedKernel<+ T,+ U,+ BM,+ BN,+ BK,+ WM,+ WN,+ transpose_a,+ transpose_b,+ MN_aligned,+ K_aligned>;// Allocate threadgroup memorythreadgroup T As[kernel_t::tgp_mem_size_a];threadgroup T Bs[kernel_t::tgp_mem_size_b];kernel_t::run(- A, B, D, params, hidden_dim, As, Bs, simd_lane_id, simd_group_id, tid, lid);+ A,+ B,+ D,+ params,+ hidden_dim,+ As,+ Bs,+ simd_lane_id,+ simd_group_id,+ tid,+ lid+ );}// Instantiate for common configurations-// transpose_a = false, transpose_b = true (weights are [K, 2*H], accessed as transposed)+// transpose_a = false, transpose_b = true (weights are [K, 2*H], accessed as+// transposed)// float16 configurations-instantiate_mlp_fused_gemm(t, false, true, half, half, 32, 32, 16, 2, 2, align, true, true);-instantiate_mlp_fused_gemm(t, false, true, half, half, 32, 32, 16, 2, 2, align, true, false);-instantiate_mlp_fused_gemm(t, false, true, half, half, 32, 32, 16, 2, 2, align, false, true);-instantiate_mlp_fused_gemm(t, false, true, half, half, 32, 32, 16, 2, 2, align, false, false);+instantiate_mlp_fused_gemm(+ t,+ false,+ true,+ half,+ half,+ 32,+ 32,+ 16,+ 2,+ 2,+ align,+ true,+ true+);+instantiate_mlp_fused_gemm(+ t,+ false,+ true,+ half,+ half,+ 32,+ 32,+ 16,+ 2,+ 2,+ align,+ true,+ false+);+instantiate_mlp_fused_gemm(+ t,+ false,+ true,+ half,+ half,+ 32,+ 32,+ 16,+ 2,+ 2,+ align,+ false,+ true+);+instantiate_mlp_fused_gemm(+ t,+ false,+ true,+ half,+ half,+ 32,+ 32,+ 16,+ 2,+ 2,+ align,+ false,+ false+);-instantiate_mlp_fused_gemm(t, false, true, half, half, 64, 64, 16, 2, 2, align, true, true);-instantiate_mlp_fused_gemm(t, false, true, half, half, 64, 64, 16, 2, 2, align, true, false);-instantiate_mlp_fused_gemm(t, false, true, half, half, 64, 64, 16, 2, 2, align, false, true);-instantiate_mlp_fused_gemm(t, false, true, half, half, 64, 64, 16, 2, 2, align, false, false);+instantiate_mlp_fused_gemm(+ t,+ false,+ true,+ half,+ half,+ 64,+ 64,+ 16,+ 2,+ 2,+ align,+ true,+ true+);+instantiate_mlp_fused_gemm(+ t,+ false,+ true,+ half,+ half,+ 64,+ 64,+ 16,+ 2,+ 2,+ align,+ true,+ false+);+instantiate_mlp_fused_gemm(+ t,+ false,+ true,+ half,+ half,+ 64,+ 64,+ 16,+ 2,+ 2,+ align,+ false,+ true+);+instantiate_mlp_fused_gemm(+ t,+ false,+ true,+ half,+ half,+ 64,+ 64,+ 16,+ 2,+ 2,+ align,+ false,+ false+);// bfloat16 configurations-instantiate_mlp_fused_gemm(t, false, true, bfloat, bfloat, 32, 32, 16, 2, 2, align, true, true);-instantiate_mlp_fused_gemm(t, false, true, bfloat, bfloat, 32, 32, 16, 2, 2, align, true, false);-instantiate_mlp_fused_gemm(t, false, true, bfloat, bfloat, 32, 32, 16, 2, 2, align, false, true);-instantiate_mlp_fused_gemm(t, false, true, bfloat, bfloat, 32, 32, 16, 2, 2, align, false, false);+instantiate_mlp_fused_gemm(+ t,+ false,+ true,+ bfloat,+ bfloat,+ 32,+ 32,+ 16,+ 2,+ 2,+ align,+ true,+ true+);+instantiate_mlp_fused_gemm(+ t,+ false,+ true,+ bfloat,+ bfloat,+ 32,+ 32,+ 16,+ 2,+ 2,+ align,+ true,+ false+);+instantiate_mlp_fused_gemm(+ t,+ false,+ true,+ bfloat,+ bfloat,+ 32,+ 32,+ 16,+ 2,+ 2,+ align,+ false,+ true+);+instantiate_mlp_fused_gemm(+ t,+ false,+ true,+ bfloat,+ bfloat,+ 32,+ 32,+ 16,+ 2,+ 2,+ align,+ false,+ false+);-instantiate_mlp_fused_gemm(t, false, true, bfloat, bfloat, 64, 64, 16, 2, 2, align, true, true);-instantiate_mlp_fused_gemm(t, false, true, bfloat, bfloat, 64, 64, 16, 2, 2, align, true, false);-instantiate_mlp_fused_gemm(t, false, true, bfloat, bfloat, 64, 64, 16, 2, 2, align, false, true);-instantiate_mlp_fused_gemm(t, false, true, bfloat, bfloat, 64, 64, 16, 2, 2, align, false, false);+instantiate_mlp_fused_gemm(+ t,+ false,+ true,+ bfloat,+ bfloat,+ 64,+ 64,+ 16,+ 2,+ 2,+ align,+ true,+ true+);+instantiate_mlp_fused_gemm(+ t,+ false,+ true,+ bfloat,+ bfloat,+ 64,+ 64,+ 16,+ 2,+ 2,+ align,+ true,+ false+);+instantiate_mlp_fused_gemm(+ t,+ false,+ true,+ bfloat,+ bfloat,+ 64,+ 64,+ 16,+ 2,+ 2,+ align,+ false,+ true+);+instantiate_mlp_fused_gemm(+ t,+ false,+ true,+ bfloat,+ bfloat,+ 64,+ 64,+ 16,+ 2,+ 2,+ align,+ false,+ false+);// float32 configurations-instantiate_mlp_fused_gemm(t, false, true, float, float, 32, 32, 16, 2, 2, align, true, true);-instantiate_mlp_fused_gemm(t, false, true, float, float, 32, 32, 16, 2, 2, align, true, false);-instantiate_mlp_fused_gemm(t, false, true, float, float, 32, 32, 16, 2, 2, align, false, true);-instantiate_mlp_fused_gemm(t, false, true, float, float, 32, 32, 16, 2, 2, align, false, false);+instantiate_mlp_fused_gemm(+ t,+ false,+ true,+ float,+ float,+ 32,+ 32,+ 16,+ 2,+ 2,+ align,+ true,+ true+);+instantiate_mlp_fused_gemm(+ t,+ false,+ true,+ float,+ float,+ 32,+ 32,+ 16,+ 2,+ 2,+ align,+ true,+ false+);+instantiate_mlp_fused_gemm(+ t,+ false,+ true,+ float,+ float,+ 32,+ 32,+ 16,+ 2,+ 2,+ align,+ false,+ true+);+instantiate_mlp_fused_gemm(+ t,+ false,+ true,+ float,+ float,+ 32,+ 32,+ 16,+ 2,+ 2,+ align,+ false,+ false+);// Non-transposed B (weights are [2*H, K])-instantiate_mlp_fused_gemm(n, false, false, half, half, 32, 32, 16, 2, 2, align, true, true);-instantiate_mlp_fused_gemm(n, false, false, half, half, 32, 32, 16, 2, 2, align, true, false);-instantiate_mlp_fused_gemm(n, false, false, half, half, 32, 32, 16, 2, 2, align, false, true);-instantiate_mlp_fused_gemm(n, false, false, half, half, 32, 32, 16, 2, 2, align, false, false);--instantiate_mlp_fused_gemm(n, false, false, bfloat, bfloat, 32, 32, 16, 2, 2, align, true, true);-instantiate_mlp_fused_gemm(n, false, false, bfloat, bfloat, 32, 32, 16, 2, 2, align, true, false);-instantiate_mlp_fused_gemm(n, false, false, bfloat, bfloat, 32, 32, 16, 2, 2, align, false, true);-instantiate_mlp_fused_gemm(n, false, false, bfloat, bfloat, 32, 32, 16, 2, 2, align, false, false);--instantiate_mlp_fused_gemm(n, false, false, float, float, 32, 32, 16, 2, 2, align, true, true);-instantiate_mlp_fused_gemm(n, false, false, float, float, 32, 32, 16, 2, 2, align, true, false);-instantiate_mlp_fused_gemm(n, false, false, float, float, 32, 32, 16, 2, 2, align, false, true);-instantiate_mlp_fused_gemm(n, false, false, float, float, 32, 32, 16, 2, 2, align, false, false);+instantiate_mlp_fused_gemm(+ n,+ false,+ false,+ half,+ half,+ 32,+ 32,+ 16,+ 2,+ 2,+ align,+ true,+ true+);+instantiate_mlp_fused_gemm(+ n,+ false,+ false,+ half,+ half,+ 32,+ 32,+ 16,+ 2,+ 2,+ align,+ true,+ false+);+instantiate_mlp_fused_gemm(+ n,+ false,+ false,+ half,+ half,+ 32,+ 32,+ 16,+ 2,+ 2,+ align,+ false,+ true+);+instantiate_mlp_fused_gemm(+ n,+ false,+ false,+ half,+ half,+ 32,+ 32,+ 16,+ 2,+ 2,+ align,+ false,+ false+);++instantiate_mlp_fused_gemm(+ n,+ false,+ false,+ bfloat,+ bfloat,+ 32,+ 32,+ 16,+ 2,+ 2,+ align,+ true,+ true+);+instantiate_mlp_fused_gemm(+ n,+ false,+ false,+ bfloat,+ bfloat,+ 32,+ 32,+ 16,+ 2,+ 2,+ align,+ true,+ false+);+instantiate_mlp_fused_gemm(+ n,+ false,+ false,+ bfloat,+ bfloat,+ 32,+ 32,+ 16,+ 2,+ 2,+ align,+ false,+ true+);+instantiate_mlp_fused_gemm(+ n,+ false,+ false,+ bfloat,+ bfloat,+ 32,+ 32,+ 16,+ 2,+ 2,+ align,+ false,+ false+);++instantiate_mlp_fused_gemm(+ n,+ false,+ false,+ float,+ float,+ 32,+ 32,+ 16,+ 2,+ 2,+ align,+ true,+ true+);+instantiate_mlp_fused_gemm(+ n,+ false,+ false,+ float,+ float,+ 32,+ 32,+ 16,+ 2,+ 2,+ align,+ true,+ false+);+instantiate_mlp_fused_gemm(+ n,+ false,+ false,+ float,+ float,+ 32,+ 32,+ 16,+ 2,+ 2,+ align,+ false,+ true+);+instantiate_mlp_fused_gemm(+ n,+ false,+ false,+ float,+ float,+ 32,+ 32,+ 16,+ 2,+ 2,+ align,+ false,+ false+);diff --git a/crates/uzu/src/backends/metal/kernel/mlp_fused/gemv/gemv_mlp_fused.metal b/crates/uzu/src/backends/metal/kernel/mlp_fused/gemv/gemv_mlp_fused.metalindex 789063231..a7a13fee1 100644--- a/crates/uzu/src/backends/metal/kernel/mlp_fused/gemv/gemv_mlp_fused.metal+++ b/crates/uzu/src/backends/metal/kernel/mlp_fused/gemv/gemv_mlp_fused.metal@@ -4,7 +4,7 @@#include "../../common/utils.h"#include "../../common/mlp_epilogue.h"-#include "../matmul/common/steel/utils.h"+#include "../../matmul/common/steel/utils.h"using namespace metal;@@ -15,8 +15,9 @@ using namespace metal;#define MTL_CONST static constant constexpr const// MLP fused GEMV kernel for decode path (M=1).-// Computes paired up and gate projections, then applies: out = up * activation(gate)-// Output size is hidden_dim (half of the weight matrix columns).+// Computes paired up and gate projections, then applies: out = up *+// activation(gate) Output size is hidden_dim (half of the weight matrix+// columns).template <typename T,const int BM, /* Threadgroup rows (in simdgroups) */@@ -35,12 +36,15 @@ struct GEMVMlpFusedKernel {static_assert(SM * SN == 32, "simdgroup can only have 32 threads");- MTL_CONST short tgp_mem_size = BN > 1 ? 2 * BN * (blockM + TM) : 0;+ MTL_CONST short tgp_mem_size = BN > 1 ? 2 * BN*(blockM + TM) : 0;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) {+ static METAL_FUNC void load_unsafe(+ const device T* src,+ thread U dst[TN],+ const int src_offset = 0+ ) {MTL_PRAGMA_UNROLLfor (int tn = 0; tn < TN; tn++) {dst[tn] = static_cast<U>(src[src_offset + tn]);@@ -52,7 +56,8 @@ struct GEMVMlpFusedKernel {const device T* src,thread U dst[TN],const int src_offset = 0,- const int src_size = TN) {+ const int src_size = TN+ ) {if (src_offset + TN <= src_size) {MTL_PRAGMA_UNROLLfor (int tn = 0; tn < TN; tn++) {@@ -62,8 +67,8 @@ struct GEMVMlpFusedKernel {MTL_PRAGMA_UNROLLfor (int tn = 0; tn < TN; tn++) {dst[tn] = src_offset + tn < src_size- ? static_cast<U>(src[src_offset + tn])- : U(0);+ ? static_cast<U>(src[src_offset + tn])+ : U(0);}}}@@ -73,13 +78,14 @@ struct GEMVMlpFusedKernel {const device T* in_vec [[buffer(1)]],device T* out_vec [[buffer(3)]],const int in_vec_size,- const int hidden_dim, // Output size (half of weight matrix rows)+ const int hidden_dim, // Output size (half of weight matrix rows)const int matrix_ld,threadgroup AccT* 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]]) {+ uint simd_lid [[thread_index_in_simdgroup]]+ ) {(void)lid;// Thread local accumulation results for up and gate@@ -170,7 +176,8 @@ struct GEMVMlpFusedKernel {// Threadgroup reduction if neededif (needs_tgp_reduction) {threadgroup AccT* tgp_results_up = tgp_memory + sgN * (blockM + TM) + bm;- threadgroup AccT* tgp_results_gate = tgp_memory + BN * (blockM + TM) + sgN * (blockM + TM) + bm;+ threadgroup AccT* tgp_results_gate =+ tgp_memory + BN * (blockM + TM) + sgN * (blockM + TM) + bm;if (thrN == 0) {MTL_PRAGMA_UNROLL@@ -198,7 +205,8 @@ struct GEMVMlpFusedKernel {if (simdN == 0 && thrN == 0) {MTL_PRAGMA_UNROLLfor (int tm = 0; tm < TM; tm++) {- float fused_result = mlp_fused_epilogue_f32(result_up[tm], result_gate[tm]);+ float fused_result =+ mlp_fused_epilogue_f32(result_up[tm], result_gate[tm]);out_vec[out_row + tm] = static_cast<T>(fused_result);}}@@ -213,19 +221,21 @@ template <const int SN,const int TM,const int TN>-[[kernel, max_total_threads_per_threadgroup(BM* BN * 32)]] void gemv_mlp_fused(+[[kernel, max_total_threads_per_threadgroup(BM * BN * 32)]] void gemv_mlp_fused(const device T* mat [[buffer(0)]],const device T* in_vec [[buffer(1)]],device T* out_vec [[buffer(3)]],const constant int& in_vec_size [[buffer(4)]],- const constant int& hidden_dim [[buffer(5)]], // Output dimension (half of weight rows)+ const constant int& hidden_dim+ [[buffer(5)]], // Output dimension (half of weight rows)const constant int& matrix_ld [[buffer(6)]],const constant int64_t& vector_batch_stride [[buffer(11)]],const constant int64_t& matrix_batch_stride [[buffer(12)]],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]]) {+ uint simd_lid [[thread_index_in_simdgroup]]+) {using gemv_kernel = GEMVMlpFusedKernel<T, BM, BN, SM, SN, TM, TN>;threadgroup typename gemv_kernel::AccT tgp_memory[gemv_kernel::tgp_mem_size == 0 ? 1 : gemv_kernel::tgp_mem_size];@@ -246,13 +256,14 @@ template <tid,lid,simd_gid,- simd_lid);+ simd_lid+ );}#define instantiate_gemv_mlp_fused_helper(name, itype, bm, bn, sm, sn, tm, tn) \instantiate_kernel( \- "gemv_mlp_fused_" #name "_bm" #bm "_bn" #bn "_sm" #sm "_sn" #sn "_tm" #tm \- "_tn" #tn, \+ "gemv_mlp_fused_" #name "_bm" #bm "_bn" #bn "_sm" #sm "_sn" #sn \+ "_tm" #tm "_tn" #tn, \gemv_mlp_fused, \itype, \bm, \@@ -260,7 +271,8 @@ template <sm, \sn, \tm, \- tn)+ tn \+ )// clang-format off#define instantiate_gemv_mlp_fused_blocks(name, itype) \diff --git a/crates/uzu/src/backends/metal/kernel/mlp_fused/split_k/steel_gemm_splitk_mlp_fused.h b/crates/uzu/src/backends/metal/kernel/mlp_fused/split_k/steel_gemm_splitk_mlp_fused.hindex 15d59cfef..3d36c9e9e 100644--- a/crates/uzu/src/backends/metal/kernel/mlp_fused/split_k/steel_gemm_splitk_mlp_fused.h+++ b/crates/uzu/src/backends/metal/kernel/mlp_fused/split_k/steel_gemm_splitk_mlp_fused.h@@ -28,7 +28,8 @@ template <bool transpose_b,bool MN_aligned,bool K_aligned>-[[kernel, max_total_threads_per_threadgroup(WM* WN * 32)]] void gemm_splitk_mlp_fused(+[[kernel, max_total_threads_per_threadgroup(WM * WN * 32)]] void+gemm_splitk_mlp_fused(const device T* A [[buffer(0)]],const device T* B [[buffer(1)]],device U* C [[buffer(2)]],@@ -36,7 +37,8 @@ template <uint simd_lane_id [[thread_index_in_simdgroup]],uint simd_group_id [[simdgroup_index_in_threadgroup]],uint3 tid [[threadgroup_position_in_grid]],- uint3 lid [[thread_position_in_threadgroup]]) {+ uint3 lid [[thread_position_in_threadgroup]]+) {(void)lid;using gemm_kernel = GEMMKernel<@@ -79,25 +81,33 @@ template <const size_t k_start_long = size_t(k_start);// Pointers to A (input)- const device T* A_ptr = A + (transpose_a ? (c_row_long + k_start_long * params->lda)- : (k_start_long + c_row_long * params->lda));+ const device T* A_ptr =+ A + (transpose_a ? (c_row_long + k_start_long * params->lda)+ : (k_start_long + c_row_long * params->lda));// Pointers to B (up and gate weights)// B layout: [up_weights | gate_weights] where each is hidden_dim columns- const device T* B_up = B + (transpose_b ? (k_start_long + c_col_long * params->ldb)- : (c_col_long + k_start_long * params->ldb));- const device T* B_gate = B_up + (transpose_b ? params->hidden_dim * params->ldb : params->hidden_dim);+ const device T* B_up =+ B + (transpose_b ? (k_start_long + c_col_long * params->ldb)+ : (c_col_long + k_start_long * params->ldb));+ const device T* B_gate =+ B_up ++ (transpose_b ? params->hidden_dim * params->ldb : params->hidden_dim);// C output for partial sums (up and gate interleaved in split_k dimension)// Layout: [up_partitions, gate_partitions] in the partition stridedevice U* C_up = C + (size_t(params->split_k_partition_stride) * tid_z) +- (c_row_long * params->ldc + c_col_long);- device U* C_gate = C_up + (size_t(params->split_k_partition_stride) * params->split_k_partitions);+ (c_row_long * params->ldc + c_col_long);+ device U* C_gate = C_up + (size_t(params->split_k_partition_stride) *+ params->split_k_partitions);// Loaders- thread loader_a_t loader_a(A_ptr, params->lda, As, simd_group_id, simd_lane_id);- thread loader_b_t loader_b_up(B_up, params->ldb, Bs_up, simd_group_id, simd_lane_id);- thread loader_b_t loader_b_gate(B_gate, params->ldb, Bs_gate, simd_group_id, simd_lane_id);+ thread loader_a_t+ loader_a(A_ptr, params->lda, As, simd_group_id, simd_lane_id);+ thread loader_b_t+ loader_b_up(B_up, params->ldb, Bs_up, simd_group_id, simd_lane_id);+ thread loader_b_t+ loader_b_gate(B_gate, params->ldb, Bs_gate, simd_group_id, simd_lane_id);// MMA operationsthread mma_t mma_up(simd_group_id, simd_lane_id);@@ -122,8 +132,10 @@ template <loader_b_up.load_unsafe();loader_b_gate.load_unsafe();} else {- short2 tile_dims_A = transpose_a ? short2(tgp_bm, BK) : short2(BK, tgp_bm);- short2 tile_dims_B = transpose_b ? short2(BK, tgp_bn) : short2(tgp_bn, BK);+ short2 tile_dims_A =+ transpose_a ? short2(tgp_bm, BK) : short2(BK, tgp_bm);+ short2 tile_dims_B =+ transpose_b ? short2(BK, tgp_bn) : short2(tgp_bn, BK);loader_a.load_safe(tile_dims_A);loader_b_up.load_safe(tile_dims_B);loader_b_gate.load_safe(tile_dims_B);@@ -149,8 +161,10 @@ template <threadgroup_barrier(mem_flags::mem_threadgroup);if (!K_aligned) {- short2 tile_dims_A = transpose_a ? short2(tgp_bm, leftover_bk) : short2(leftover_bk, tgp_bm);- short2 tile_dims_B = transpose_b ? short2(leftover_bk, tgp_bn) : short2(tgp_bn, leftover_bk);+ short2 tile_dims_A = transpose_a ? short2(tgp_bm, leftover_bk)+ : short2(leftover_bk, tgp_bm);+ short2 tile_dims_B = transpose_b ? short2(leftover_bk, tgp_bn)+ : short2(tgp_bn, leftover_bk);loader_a.load_safe(tile_dims_A);loader_b_up.load_safe(tile_dims_B);loader_b_gate.load_safe(tile_dims_B);@@ -193,7 +207,8 @@ template <typename AccT, typename OutT>const constant int& k_partitions [[buffer(2)]],const constant int& partition_stride [[buffer(3)]],const constant int& ldd [[buffer(4)]],- uint2 gid [[thread_position_in_grid]]) {+ uint2 gid [[thread_position_in_grid]]+) {// Adjust pointersD += gid.x + gid.y * size_t(ldd);const device AccT* C_up = C_split + gid.x + gid.y * size_t(ldd);@@ -211,6 +226,9 @@ template <typename AccT, typename OutT>}// Apply MLP fused epilogue: out = up * activation(gate)- float fused = mlp_fused_epilogue_f32(static_cast<float>(out_up), static_cast<float>(out_gate));+ float fused = mlp_fused_epilogue_f32(+ static_cast<float>(out_up),+ static_cast<float>(out_gate)+ );D[0] = static_cast<OutT>(fused);}diff --git a/crates/uzu/src/backends/metal/kernel/quant_matmul/quant_matmul.metal b/crates/uzu/src/backends/metal/kernel/quant_matmul/quant_matmul.metalindex 58872d428..999a8c2d6 100644--- a/crates/uzu/src/backends/metal/kernel/quant_matmul/quant_matmul.metal+++ b/crates/uzu/src/backends/metal/kernel/quant_matmul/quant_matmul.metal@@ -4144,9 +4144,9 @@ qmm_transposed<bfloat, 128, 4, true, 128, 32, 64>(///////////////////////////////////////////////////////////////////////////////// MLP fused QMV kernel for decode path (M=1).-// Computes paired up and gate projections, then applies: out = up * activation(gate)-// Weight layout: [up_weights (hidden_dim rows), gate_weights (hidden_dim rows)]-// Output size is hidden_dim.+// Computes paired up and gate projections, then applies: out = up *+// activation(gate) Weight layout: [up_weights (hidden_dim rows), gate_weights+// (hidden_dim rows)] Output size is hidden_dim.template <typename T, int group_size, int bits>void qmv_mlp_fused_impl(const device uint32_t* w,@@ -4156,14 +4156,14 @@ void qmv_mlp_fused_impl(const device T* x,device T* y,const constant int& in_vec_size,- const constant int& hidden_dim, // Output size (half of weight rows)+ const constant int& hidden_dim, // Output size (half of weight rows)uint3 tid [[threadgroup_position_in_grid]],uint simd_gid [[simdgroup_index_in_threadgroup]],uint simd_lid [[thread_index_in_simdgroup]]) {constexpr int packs_per_thread = bits == 2 ? 1 : 2;constexpr int num_simdgroups = 2;- constexpr int results_per_simdgroup = 4; // Compute 4 paired rows at a time+ constexpr int results_per_simdgroup = 4; // Compute 4 paired rows at a timeconstexpr int pack_factor = get_pack_factor<bits, 32>();constexpr int bytes_per_pack = get_bytes_per_pack<bits, 32>();constexpr int values_per_thread = pack_factor * packs_per_thread;@@ -4186,15 +4186,20 @@ void qmv_mlp_fused_impl(const int out_row_gate = out_row_up + hidden_dim;// Check bounds - only process if up row is within hidden_dim- if (out_row_up >= hidden_dim) return;+ if (out_row_up >= hidden_dim)+ return;// Pointer setup for up weights- const device uint8_t* ws_up = ws + out_row_up * in_vec_size_w + simd_lid * packs_per_thread * bytes_per_pack;- const device T* scales_up = scales + out_row_up * in_vec_size_g + simd_lid / scale_step_per_thread;+ const device uint8_t* ws_up = ws + out_row_up * in_vec_size_w ++ simd_lid * packs_per_thread * bytes_per_pack;+ const device T* scales_up =+ scales + out_row_up * in_vec_size_g + simd_lid / scale_step_per_thread;// Pointer setup for gate weights- const device uint8_t* ws_gate = ws + out_row_gate * in_vec_size_w + simd_lid * packs_per_thread * bytes_per_pack;- const device T* scales_gate = scales + out_row_gate * in_vec_size_g + simd_lid / scale_step_per_thread;+ const device uint8_t* ws_gate = ws + out_row_gate * in_vec_size_w ++ simd_lid * packs_per_thread * bytes_per_pack;+ const device T* scales_gate =+ scales + out_row_gate * in_vec_size_g + simd_lid / scale_step_per_thread;const device T* biases_up = nullptr;const device T* biases_gate = nullptr;@@ -4204,8 +4209,10 @@ void qmv_mlp_fused_impl(bool high_nibble = false;if (kUseMlxQuant) {- biases_up = biases + out_row_up * in_vec_size_g + simd_lid / scale_step_per_thread;- biases_gate = biases + out_row_gate * in_vec_size_g + simd_lid / scale_step_per_thread;+ biases_up =+ biases + out_row_up * in_vec_size_g + simd_lid / scale_step_per_thread;+ biases_gate = biases + out_row_gate * in_vec_size_g ++ simd_lid / scale_step_per_thread;} else {if (bits == 4) {zp_stride = (in_vec_size_g + 1) / 2;@@ -4217,8 +4224,10 @@ void qmv_mlp_fused_impl(high_nibble = (g_offset & 1);} else {zp_stride = in_vec_size_g;- zps_up = zero_points + out_row_up * zp_stride + simd_lid / scale_step_per_thread;- zps_gate = zero_points + out_row_gate * zp_stride + simd_lid / scale_step_per_thread;+ zps_up = zero_points + out_row_up * zp_stride ++ simd_lid / scale_step_per_thread;+ zps_gate = zero_points + out_row_gate * zp_stride ++ simd_lid / scale_step_per_thread;}}@@ -4261,20 +4270,70 @@ void qmv_mlp_fused_impl(U b_gate2 = static_cast<U>(biases_gate[2 * in_vec_size_g]);U b_gate3 = static_cast<U>(biases_gate[3 * in_vec_size_g]);- result_up[0] += qdot<U, values_per_thread, bits>(wl_up0, x_thread, s_up0, b_up0, sum);- result_up[1] += qdot<U, values_per_thread, bits>(wl_up1, x_thread, s_up1, b_up1, sum);- result_up[2] += qdot<U, values_per_thread, bits>(wl_up2, x_thread, s_up2, b_up2, sum);- result_up[3] += qdot<U, values_per_thread, bits>(wl_up3, x_thread, s_up3, b_up3, sum);+ result_up[0] += qdot<U, values_per_thread, bits>(+ wl_up0,+ x_thread,+ s_up0,+ b_up0,+ sum+ );+ result_up[1] += qdot<U, values_per_thread, bits>(+ wl_up1,+ x_thread,+ s_up1,+ b_up1,+ sum+ );+ result_up[2] += qdot<U, values_per_thread, bits>(+ wl_up2,+ x_thread,+ s_up2,+ b_up2,+ sum+ );+ result_up[3] += qdot<U, values_per_thread, bits>(+ wl_up3,+ x_thread,+ s_up3,+ b_up3,+ sum+ );- result_gate[0] += qdot<U, values_per_thread, bits>(wl_gate0, x_thread, s_gate0, b_gate0, sum);- result_gate[1] += qdot<U, values_per_thread, bits>(wl_gate1, x_thread, s_gate1, b_gate1, sum);- result_gate[2] += qdot<U, values_per_thread, bits>(wl_gate2, x_thread, s_gate2, b_gate2, sum);- result_gate[3] += qdot<U, values_per_thread, bits>(wl_gate3, x_thread, s_gate3, b_gate3, sum);+ result_gate[0] += qdot<U, values_per_thread, bits>(+ wl_gate0,+ x_thread,+ s_gate0,+ b_gate0,+ sum+ );+ result_gate[1] += qdot<U, values_per_thread, bits>(+ wl_gate1,+ x_thread,+ s_gate1,+ b_gate1,+ sum+ );+ result_gate[2] += qdot<U, values_per_thread, bits>(+ wl_gate2,+ x_thread,+ s_gate2,+ b_gate2,+ sum+ );+ result_gate[3] += qdot<U, values_per_thread, bits>(+ wl_gate3,+ x_thread,+ s_gate3,+ b_gate3,+ sum+ );} else {auto extract_zp = [&](const device uint8_t* zps, int row_offset) -> U {uint8_t zp_byte = zps[row_offset * zp_stride];if (bits == 4) {- return static_cast<U>(high_nibble ? (zp_byte >> 4) : (zp_byte & 0x0F));+ return static_cast<U>(+ high_nibble ? (zp_byte >> 4) : (zp_byte & 0x0F)+ );} else {return static_cast<U>(zp_byte);}@@ -4290,15 +4349,55 @@ void qmv_mlp_fused_impl(U zp_gate2 = extract_zp(zps_gate, 2);U zp_gate3 = extract_zp(zps_gate, 3);- result_up[0] += qdot_zero_point<U, values_per_thread, bits>(wl_up0, x_thread, s_up0, zp_up0);- result_up[1] += qdot_zero_point<U, values_per_thread, bits>(wl_up1, x_thread, s_up1, zp_up1);- result_up[2] += qdot_zero_point<U, values_per_thread, bits>(wl_up2, x_thread, s_up2, zp_up2);- result_up[3] += qdot_zero_point<U, values_per_thread, bits>(wl_up3, x_thread, s_up3, zp_up3);+ result_up[0] += qdot_zero_point<U, values_per_thread, bits>(+ wl_up0,+ x_thread,+ s_up0,+ zp_up0+ );+ result_up[1] += qdot_zero_point<U, values_per_thread, bits>(+ wl_up1,+ x_thread,+ s_up1,+ zp_up1+ );+ result_up[2] += qdot_zero_point<U, values_per_thread, bits>(+ wl_up2,+ x_thread,+ s_up2,+ zp_up2+ );+ result_up[3] += qdot_zero_point<U, values_per_thread, bits>(+ wl_up3,+ x_thread,+ s_up3,+ zp_up3+ );- result_gate[0] += qdot_zero_point<U, values_per_thread, bits>(wl_gate0, x_thread, s_gate0, zp_gate0);- result_gate[1] += qdot_zero_point<U, values_per_thread, bits>(wl_gate1, x_thread, s_gate1, zp_gate1);- result_gate[2] += qdot_zero_point<U, values_per_thread, bits>(wl_gate2, x_thread, s_gate2, zp_gate2);- result_gate[3] += qdot_zero_point<U, values_per_thread, bits>(wl_gate3, x_thread, s_gate3, zp_gate3);+ result_gate[0] += qdot_zero_point<U, values_per_thread, bits>(+ wl_gate0,+ x_thread,+ s_gate0,+ zp_gate0+ );+ result_gate[1] += qdot_zero_point<U, values_per_thread, bits>(+ wl_gate1,+ x_thread,+ s_gate1,+ zp_gate1+ );+ result_gate[2] += qdot_zero_point<U, values_per_thread, bits>(+ wl_gate2,+ x_thread,+ s_gate2,+ zp_gate2+ );+ result_gate[3] += qdot_zero_point<U, values_per_thread, bits>(+ wl_gate3,+ x_thread,+ s_gate3,+ zp_gate3+ );}}@@ -4337,7 +4436,8 @@ template <typename T, int group_size, int bits>[[kernel]] void qmv_mlp_fused(const device uint32_t* w [[buffer(0)]],const device T* scales [[buffer(1)]],- const device uint8_t* zero_points [[buffer(2), function_constant(kUseZeroPoints)]],+ const device uint8_t* zero_points+ [[buffer(2), function_constant(kUseZeroPoints)]],const device T* biases [[buffer(2), function_constant(kUseMlxQuant)]],const device T* x [[buffer(3)]],device T* y [[buffer(4)]],@@ -4363,8 +4463,8 @@ template <typename T, int group_size, int bits>}// Instantiate MLP fused QMV kernels for common configurations-template [[host_name("qmv_mlp_fused_f16_g32_b4")]] [[kernel]] void qmv_mlp_fused<- half, 32, 4>(+template [[host_name("qmv_mlp_fused_f16_g32_b4")]] [[kernel]] void+qmv_mlp_fused<half, 32, 4>(const device uint32_t* w [[buffer(0)]],const device half* scales [[buffer(1)]],const device uint8_t* zero_points [[buffer(2)]],@@ -4378,8 +4478,8 @@ template [[host_name("qmv_mlp_fused_f16_g32_b4")]] [[kernel]] void qmv_mlp_fuseduint simd_lid [[thread_index_in_simdgroup]]);-template [[host_name("qmv_mlp_fused_f16_g64_b4")]] [[kernel]] void qmv_mlp_fused<- half, 64, 4>(+template [[host_name("qmv_mlp_fused_f16_g64_b4")]] [[kernel]] void+qmv_mlp_fused<half, 64, 4>(const device uint32_t* w [[buffer(0)]],const device half* scales [[buffer(1)]],const device uint8_t* zero_points [[buffer(2)]],@@ -4393,8 +4493,8 @@ template [[host_name("qmv_mlp_fused_f16_g64_b4")]] [[kernel]] void qmv_mlp_fuseduint simd_lid [[thread_index_in_simdgroup]]);-template [[host_name("qmv_mlp_fused_f16_g128_b4")]] [[kernel]] void qmv_mlp_fused<- half, 128, 4>(+template [[host_name("qmv_mlp_fused_f16_g128_b4")]] [[kernel]] void+qmv_mlp_fused<half, 128, 4>(const device uint32_t* w [[buffer(0)]],const device half* scales [[buffer(1)]],const device uint8_t* zero_points [[buffer(2)]],@@ -4408,8 +4508,8 @@ template [[host_name("qmv_mlp_fused_f16_g128_b4")]] [[kernel]] void qmv_mlp_fuseuint simd_lid [[thread_index_in_simdgroup]]);-template [[host_name("qmv_mlp_fused_bf16_g32_b4")]] [[kernel]] void qmv_mlp_fused<- bfloat, 32, 4>(+template [[host_name("qmv_mlp_fused_bf16_g32_b4")]] [[kernel]] void+qmv_mlp_fused<bfloat, 32, 4>(const device uint32_t* w [[buffer(0)]],const device bfloat* scales [[buffer(1)]],const device uint8_t* zero_points [[buffer(2)]],@@ -4423,8 +4523,8 @@ template [[host_name("qmv_mlp_fused_bf16_g32_b4")]] [[kernel]] void qmv_mlp_fuseuint simd_lid [[thread_index_in_simdgroup]]);-template [[host_name("qmv_mlp_fused_bf16_g64_b4")]] [[kernel]] void qmv_mlp_fused<- bfloat, 64, 4>(+template [[host_name("qmv_mlp_fused_bf16_g64_b4")]] [[kernel]] void+qmv_mlp_fused<bfloat, 64, 4>(const device uint32_t* w [[buffer(0)]],const device bfloat* scales [[buffer(1)]],const device uint8_t* zero_points [[buffer(2)]],@@ -4438,8 +4538,8 @@ template [[host_name("qmv_mlp_fused_bf16_g64_b4")]] [[kernel]] void qmv_mlp_fuseuint simd_lid [[thread_index_in_simdgroup]]);-template [[host_name("qmv_mlp_fused_bf16_g128_b4")]] [[kernel]] void qmv_mlp_fused<- bfloat, 128, 4>(+template [[host_name("qmv_mlp_fused_bf16_g128_b4")]] [[kernel]] void+qmv_mlp_fused<bfloat, 128, 4>(const device uint32_t* w [[buffer(0)]],const device bfloat* scales [[buffer(1)]],const device uint8_t* zero_points [[buffer(2)]],@@ -4458,10 +4558,17 @@ template [[host_name("qmv_mlp_fused_bf16_g128_b4")]] [[kernel]] void qmv_mlp_fus///////////////////////////////////////////////////////////////////////////////// MLP fused QMM kernel for prefill path (M>1).-// Computes paired up and gate projections, then applies: out = up * activation(gate)-// Weight layout: [up_weights (hidden_dim cols), gate_weights (hidden_dim cols)]-// Output size is [M, hidden_dim].-template <typename T, int group_size, int bits, bool aligned_K, int BM = 32, int BK = 32, int BN = 32>+// Computes paired up and gate projections, then applies: out = up *+// activation(gate) Weight layout: [up_weights (hidden_dim cols), gate_weights+// (hidden_dim cols)] Output size is [M, hidden_dim].+template <+ typename T,+ int group_size,+ int bits,+ bool aligned_K,+ int BM = 32,+ int BK = 32,+ int BN = 32>void qmm_mlp_fused_impl(const device uint32_t* w,const device T* scales,@@ -4472,7 +4579,8 @@ void qmm_mlp_fused_impl(threadgroup T* Xs,threadgroup T* Ws_up,const constant int& K,- const constant int& hidden_dim, // Output columns (half of total weight columns)+ const constant int&+ hidden_dim, // Output columns (half of total weight columns)const constant int& M,uint3 tid [[threadgroup_position_in_grid]],uint lid [[thread_index_in_threadgroup]],@@ -4492,16 +4600,19 @@ void qmm_mlp_fused_impl(constexpr int BK_padded = (BK + 16 / sizeof(T));constexpr int BN_padded = (BN + 16 / sizeof(T));- using mma_t = matmul_utils::BlockMMA<T, T, BM, BN, BK, WM, WN, false, false, BK_padded, BN_padded>;- using loader_x_t = matmul_utils::BlockLoader<T, BM, BK, BK_padded, 1, WM * WN * 32, 1, 4>;+ using mma_t = matmul_utils::+ BlockMMA<T, T, BM, BN, BK, WM, WN, false, false, BK_padded, BN_padded>;+ using loader_x_t =+ matmul_utils::BlockLoader<T, BM, BK, BK_padded, 1, WM * WN * 32, 1, 4>;auto wl_up = (const device uint8_t*)w;const int y_row = tid.y * BM;- const int y_col = tid.x * BN; // Column in output (within hidden_dim)+ const int y_col = tid.x * BN; // Column in output (within hidden_dim)// Only process tiles within hidden_dim- if (y_col >= hidden_dim) return;+ if (y_col >= hidden_dim)+ return;x += y_row * static_cast<int64_t>(K);@@ -4532,15 +4643,41 @@ void qmm_mlp_fused_impl(const int N_total = hidden_dim * 2;if (kUseMlxQuant) {- using loader_w_t = QuantizedBlockLoaderMlx<T, BK, BN, BN_padded, 0, WM * WN * 32, group_size, bits>;+ using loader_w_t = QuantizedBlockLoaderMlx<+ T,+ BK,+ BN,+ BN_padded,+ 0,+ WM * WN * 32,+ group_size,+ bits>;const device T* scales_up = scales_base + (y_col / group_size);const device T* biases_up = biases_base + (y_col / group_size);- const device T* scales_gate = scales_base + ((y_col + hidden_dim) / group_size);- const device T* biases_gate = biases_base + ((y_col + hidden_dim) / group_size);+ const device T* scales_gate =+ scales_base + ((y_col + hidden_dim) / group_size);+ const device T* biases_gate =+ biases_base + ((y_col + hidden_dim) / group_size);- loader_w_t loader_w_up(wl_up, scales_up, biases_up, N_total, Ws_up, simd_gid, simd_lid);- loader_w_t loader_w_gate(wl_gate, scales_gate, biases_gate, N_total, Ws_gate, simd_gid, simd_lid);+ loader_w_t loader_w_up(+ wl_up,+ scales_up,+ biases_up,+ N_total,+ Ws_up,+ simd_gid,+ simd_lid+ );+ loader_w_t loader_w_gate(+ wl_gate,+ scales_gate,+ biases_gate,+ N_total,+ Ws_gate,+ simd_gid,+ simd_lid+ );for (int k = 0; k < full_iterations; k++) {threadgroup_barrier(mem_flags::mem_threadgroup);@@ -4572,21 +4709,47 @@ void qmm_mlp_fused_impl(const int groups_per_row = out_groups_total;const int out_group_up = y_col / group_size;const int out_group_gate = (y_col + hidden_dim) / group_size;- const int zp_stride_out = (bits == 4) ? ((out_groups_total + 1) / 2) : out_groups_total;+ const int zp_stride_out =+ (bits == 4) ? ((out_groups_total + 1) / 2) : out_groups_total;- using loader_w_t = QuantizedBlockLoaderZp<T, BK, BN, BN_padded, 0, WM * WN * 32, group_size, bits, true>;+ using loader_w_t = QuantizedBlockLoaderZp<+ T,+ BK,+ BN,+ BN_padded,+ 0,+ WM * WN * 32,+ group_size,+ bits,+ true>;loader_w_t loader_w_up(- wl_up, scales_base, zero_points,- N_total, groups_per_row, Ws_up,- simd_gid, simd_lid,- out_group_up, out_groups_total, zp_stride_out);+ wl_up,+ scales_base,+ zero_points,+ N_total,+ groups_per_row,+ Ws_up,+ simd_gid,+ simd_lid,+ out_group_up,+ out_groups_total,+ zp_stride_out+ );loader_w_t loader_w_gate(- wl_gate, scales_base, zero_points,- N_total, groups_per_row, Ws_gate,- simd_gid, simd_lid,- out_group_gate, out_groups_total, zp_stride_out);+ wl_gate,+ scales_base,+ zero_points,+ N_total,+ groups_per_row,+ Ws_gate,+ simd_gid,+ simd_lid,+ out_group_gate,+ out_groups_total,+ zp_stride_out+ );for (int k = 0; k < full_iterations; k++) {threadgroup_barrier(mem_flags::mem_threadgroup);@@ -4618,7 +4781,7 @@ void qmm_mlp_fused_impl(// Apply MLP fused epilogue: out = up * activation(gate)// Access Ctile elements and apply fusionconstexpr int kElemsPerTile = decltype(mma_up.Ctile)::kElemsPerTile;- #pragma unroll+#pragma unrollfor (short i = 0; i < kElemsPerTile; i++) {float up_val = static_cast<float>(mma_up.Ctile.elems()[i]);float gate_val = static_cast<float>(mma_gate.Ctile.elems()[i]);@@ -4634,7 +4797,8 @@ template <typename T, int group_size, int bits>[[kernel]] void qmm_mlp_fused(const device uint32_t* w [[buffer(0)]],const device T* scales [[buffer(1)]],- const device uint8_t* zero_points [[buffer(2), function_constant(kUseZeroPoints)]],+ const device uint8_t* zero_points+ [[buffer(2), function_constant(kUseZeroPoints)]],const device T* biases [[buffer(2), function_constant(kUseMlxQuant)]],const device T* x [[buffer(3)]],device T* y [[buffer(4)]],@@ -4653,23 +4817,51 @@ template <typename T, int group_size, int bits>constexpr int BN_padded = (BN + 16 / sizeof(T));threadgroup T Xs[BM * BK_padded];- threadgroup T Ws[2 * BK * BN_padded]; // Double for up and gate+ threadgroup T Ws[2 * BK * BN_padded]; // Double for up and gatebool aligned_K = (K % BK) == 0;if (aligned_K) {qmm_mlp_fused_impl<T, group_size, bits, true, BM, BK, BN>(- w, scales, zero_points, biases, x, y, Xs, Ws,- K, hidden_dim, M, tid, lid, simd_gid, simd_lid);+ w,+ scales,+ zero_points,+ biases,+ x,+ y,+ Xs,+ Ws,+ K,+ hidden_dim,+ M,+ tid,+ lid,+ simd_gid,+ simd_lid+ );} else {qmm_mlp_fused_impl<T, group_size, bits, false, BM, BK, BN>(- w, scales, zero_points, biases, x, y, Xs, Ws,- K, hidden_dim, M, tid, lid, simd_gid, simd_lid);+ w,+ scales,+ zero_points,+ biases,+ x,+ y,+ Xs,+ Ws,+ K,+ hidden_dim,+ M,+ tid,+ lid,+ simd_gid,+ simd_lid+ );}}// Instantiate MLP fused QMM kernels-template [[host_name("qmm_mlp_fused_f16_g32_b4")]] [[kernel]] void qmm_mlp_fused<- half, 32, 4>(+template [[host_name("qmm_mlp_fused_f16_g32_b4")]] [[kernel]] void+qmm_mlp_fused<half, 32, 4>(const device uint32_t* w [[buffer(0)]],const device half* scales [[buffer(1)]],const device uint8_t* zero_points [[buffer(2)]],@@ -4685,8 +4877,8 @@ template [[host_name("qmm_mlp_fused_f16_g32_b4")]] [[kernel]] void qmm_mlp_fuseduint simd_lid [[thread_index_in_simdgroup]]);-template [[host_name("qmm_mlp_fused_f16_g64_b4")]] [[kernel]] void qmm_mlp_fused<- half, 64, 4>(+template [[host_name("qmm_mlp_fused_f16_g64_b4")]] [[kernel]] void+qmm_mlp_fused<half, 64, 4>(const device uint32_t* w [[buffer(0)]],const device half* scales [[buffer(1)]],const device uint8_t* zero_points [[buffer(2)]],@@ -4702,8 +4894,8 @@ template [[host_name("qmm_mlp_fused_f16_g64_b4")]] [[kernel]] void qmm_mlp_fuseduint simd_lid [[thread_index_in_simdgroup]]);-template [[host_name("qmm_mlp_fused_f16_g128_b4")]] [[kernel]] void qmm_mlp_fused<- half, 128, 4>(+template [[host_name("qmm_mlp_fused_f16_g128_b4")]] [[kernel]] void+qmm_mlp_fused<half, 128, 4>(const device uint32_t* w [[buffer(0)]],const device half* scales [[buffer(1)]],const device uint8_t* zero_points [[buffer(2)]],@@ -4719,8 +4911,8 @@ template [[host_name("qmm_mlp_fused_f16_g128_b4")]] [[kernel]] void qmm_mlp_fuseuint simd_lid [[thread_index_in_simdgroup]]);-template [[host_name("qmm_mlp_fused_bf16_g32_b4")]] [[kernel]] void qmm_mlp_fused<- bfloat, 32, 4>(+template [[host_name("qmm_mlp_fused_bf16_g32_b4")]] [[kernel]] void+qmm_mlp_fused<bfloat, 32, 4>(const device uint32_t* w [[buffer(0)]],const device bfloat* scales [[buffer(1)]],const device uint8_t* zero_points [[buffer(2)]],@@ -4736,8 +4928,8 @@ template [[host_name("qmm_mlp_fused_bf16_g32_b4")]] [[kernel]] void qmm_mlp_fuseuint simd_lid [[thread_index_in_simdgroup]]);-template [[host_name("qmm_mlp_fused_bf16_g64_b4")]] [[kernel]] void qmm_mlp_fused<- bfloat, 64, 4>(+template [[host_name("qmm_mlp_fused_bf16_g64_b4")]] [[kernel]] void+qmm_mlp_fused<bfloat, 64, 4>(const device uint32_t* w [[buffer(0)]],const device bfloat* scales [[buffer(1)]],const device uint8_t* zero_points [[buffer(2)]],@@ -4753,8 +4945,8 @@ template [[host_name("qmm_mlp_fused_bf16_g64_b4")]] [[kernel]] void qmm_mlp_fuseuint simd_lid [[thread_index_in_simdgroup]]);-template [[host_name("qmm_mlp_fused_bf16_g128_b4")]] [[kernel]] void qmm_mlp_fused<- bfloat, 128, 4>(+template [[host_name("qmm_mlp_fused_bf16_g128_b4")]] [[kernel]] void+qmm_mlp_fused<bfloat, 128, 4>(const device uint32_t* w [[buffer(0)]],const device bfloat* scales [[buffer(1)]],const device uint8_t* zero_points [[buffer(2)]],diff --git a/crates/uzu/src/backends/metal/kernel/rms_norm/mod.rs b/crates/uzu/src/backends/metal/kernel/rms_norm/mod.rsindex 961af1179..0d77b7dbd 100644--- a/crates/uzu/src/backends/metal/kernel/rms_norm/mod.rs+++ b/crates/uzu/src/backends/metal/kernel/rms_norm/mod.rs@@ -209,10 +209,17 @@ impl RMSNormKernel {compute_encoder.set_compute_pipeline_state(&self.pipeline);// Set buffers- compute_encoder.set_buffer(0, Some(args.input_buffer), args.input_offset);+ compute_encoder.set_buffer(+ 0,+ Some(args.input_buffer),+ args.input_offset,+ );compute_encoder.set_buffer(1, Some(args.scales_buffer), 0);- compute_encoder- .set_buffer(2, Some(args.output_buffer), args.output_offset);+ compute_encoder.set_buffer(+ 2,+ Some(args.output_buffer),+ args.output_offset,+ );// Set parameterscompute_encoder.set_bytes(diff --git a/crates/uzu/src/backends/metal/kernel/sampling/top_k.metal b/crates/uzu/src/backends/metal/kernel/sampling/top_k.metalindex cdee11a50..dff9f782c 100644--- a/crates/uzu/src/backends/metal/kernel/sampling/top_k.metal+++ b/crates/uzu/src/backends/metal/kernel/sampling/top_k.metal@@ -39,7 +39,7 @@ void batched_topk(local_min,shared_reduce_buffer,thread_idx- );+ );// Do the binary search on the thresholdfloat low = min_logit;float high = max_logit;@@ -102,7 +102,7 @@ void batched_topk([[max_total_threads_per_threadgroup( \1024 \)]] kernel void functionName##_##scalarType outerArgs { \- threadgroup float shared_reduce_buffer[BLOCK_SIZE_IN_SIMDS]; \+ threadgroup float shared_reduce_buffer[BLOCK_SIZE_IN_SIMDS]; \functionName innerArgs; \}diff --git a/crates/uzu/tests/mlp_fused_correctness_test.rs b/crates/uzu/tests/mlp_fused_correctness_test.rsindex 70a9d85ac..8e6397e7a 100644--- a/crates/uzu/tests/mlp_fused_correctness_test.rs+++ b/crates/uzu/tests/mlp_fused_correctness_test.rs@@ -93,8 +93,7 @@ fn run_fused_gemv(MTLResourceOptions::StorageModeShared,);- let mut kernel =- MlpFusedKernel::new(DataType::F16, true).expect("kernel");+ let mut kernel = MlpFusedKernel::new(DataType::F16, true).expect("kernel");let cb = ctx.command_queue.new_command_buffer().to_owned();let enc = cb.new_compute_command_encoder();@@ -150,8 +149,7 @@ fn run_fused_gemm(MTLResourceOptions::StorageModeShared,);- let mut kernel =- MlpFusedKernel::new(DataType::F16, true).expect("kernel");+ let mut kernel = MlpFusedKernel::new(DataType::F16, true).expect("kernel");let cb = ctx.command_queue.new_command_buffer().to_owned();let enc = cb.new_compute_command_encoder();