A high-performance inference engine for AI models
format
Eugene Bokhane22049dc99e7
diff --git a/crates/uzu/src/backends/metal/kernel/activation/activation.metal b/crates/uzu/src/backends/metal/kernel/activation/activation.metalindex fb5e88d00..283f342ee 100644--- a/crates/uzu/src/backends/metal/kernel/activation/activation.metal+++ b/crates/uzu/src/backends/metal/kernel/activation/activation.metal@@ -43,8 +43,7 @@ template <typename T>}// Explicit instantiations-template [[host_name("activation_f16")]] [[kernel]] void-activation<half>(+template [[host_name("activation_f16")]] [[kernel]] void activation<half>(const device half* input [[buffer(0)]],device half* output [[buffer(1)]],const constant int& N [[buffer(2)]],@@ -52,8 +51,7 @@ activation<half>(uint tid [[thread_position_in_grid]]);-template [[host_name("activation_f32")]] [[kernel]] void-activation<float>(+template [[host_name("activation_f32")]] [[kernel]] void activation<float>(const device float* input [[buffer(0)]],device float* output [[buffer(1)]],const constant int& N [[buffer(2)]],@@ -61,8 +59,7 @@ activation<float>(uint tid [[thread_position_in_grid]]);-template [[host_name("activation_bf16")]] [[kernel]] void-activation<bfloat>(+template [[host_name("activation_bf16")]] [[kernel]] void activation<bfloat>(const device bfloat* input [[buffer(0)]],device bfloat* output [[buffer(1)]],const constant int& N [[buffer(2)]],diff --git a/crates/uzu/src/backends/metal/kernel/embedding/full_precision_embedding.metal b/crates/uzu/src/backends/metal/kernel/embedding/full_precision_embedding.metalindex 96ffb2c13..f1602f8ca 100644--- a/crates/uzu/src/backends/metal/kernel/embedding/full_precision_embedding.metal+++ b/crates/uzu/src/backends/metal/kernel/embedding/full_precision_embedding.metal@@ -3,28 +3,29 @@ using namespace metal;template <typename T>[[kernel]] void full_precision_embedding_lookup(- const device uint64_t* token_ids [[buffer(0)]], // [batch_size]- const device T* weights [[buffer(1)]], // [vocab_size, model_dim]- device T* output [[buffer(2)]], // [batch_size, model_dim]+ const device uint64_t* token_ids [[buffer(0)]], // [batch_size]+ const device T* weights [[buffer(1)]], // [vocab_size, model_dim]+ device T* output [[buffer(2)]], // [batch_size, model_dim]constant uint32_t& batch_size [[buffer(3)]],constant uint32_t& vocab_size [[buffer(4)]],constant uint32_t& model_dim [[buffer(5)]],constant float& input_scale [[buffer(6)]],uint thread_position_in_grid [[thread_position_in_grid]]) {- const uint batch_idx = thread_position_in_grid / model_dim;- const uint dim_idx = thread_position_in_grid % model_dim;+ const uint batch_idx = thread_position_in_grid / model_dim;+ const uint dim_idx = thread_position_in_grid % model_dim;- if (batch_idx >= batch_size) return;+ if (batch_idx >= batch_size)+ return;- const uint64_t token_id = token_ids[batch_idx];- if (token_id >= vocab_size) {- output[thread_position_in_grid] = T(0);- return;- }+ const uint64_t token_id = token_ids[batch_idx];+ if (token_id >= vocab_size) {+ output[thread_position_in_grid] = T(0);+ return;+ }- T value = weights[token_id * model_dim + dim_idx];- output[thread_position_in_grid] = value * T(input_scale);+ T value = weights[token_id * model_dim + dim_idx];+ output[thread_position_in_grid] = value * T(input_scale);}template [[host_name("full_precision_embedding_lookup_f32")]] [[kernel]] void@@ -62,4 +63,3 @@ full_precision_embedding_lookup<bfloat>(constant float& input_scale [[buffer(6)]],uint thread_position_in_grid [[thread_position_in_grid]]);-diff --git a/crates/uzu/src/backends/metal/kernel/mask_update/mask_update.metal b/crates/uzu/src/backends/metal/kernel/mask_update/mask_update.metalindex babdccb16..7898db785 100644--- a/crates/uzu/src/backends/metal/kernel/mask_update/mask_update.metal+++ b/crates/uzu/src/backends/metal/kernel/mask_update/mask_update.metal@@ -8,25 +8,26 @@ kernel void update_attention_mask(constant int& mask_col [[buffer(2)]],uint tid [[thread_position_in_grid]]) {- if (tid == 0) {- if (unmask_col >= 0) {- mask[unmask_col] = T(0);- }- if (mask_col >= 0) {- mask[mask_col] = -numeric_limits<T>::infinity();- }+ if (tid == 0) {+ if (unmask_col >= 0) {+ mask[unmask_col] = T(0);}+ if (mask_col >= 0) {+ mask[mask_col] = -numeric_limits<T>::infinity();+ }+ }}-#define instantiate_mask_update(name, type) \- template [[host_name("update_attention_mask_" #name)]] \- kernel void update_attention_mask<type>( \- device type* mask [[buffer(0)]], \- constant int& unmask_col [[buffer(1)]], \- constant int& mask_col [[buffer(2)]], \- uint tid [[thread_position_in_grid]] \- );+#define instantiate_mask_update(name, type) \+ template [[host_name("update_attention_mask_" #name)]] \+ kernel void update_attention_mask<type>( \+ device type * mask [[buffer(0)]], \+ constant int& unmask_col [[buffer(1)]], \+ constant int& mask_col [[buffer(2)]], \+ uint tid [[thread_position_in_grid]] \+ );-instantiate_mask_update(float, float)-instantiate_mask_update(half, half)-instantiate_mask_update(bfloat, bfloat)+instantiate_mask_update(float, float) instantiate_mask_update(+ half,+ half+) instantiate_mask_update(bfloat, bfloat)diff --git a/crates/uzu/src/backends/metal/kernel/matmul/gemv.metal b/crates/uzu/src/backends/metal/kernel/matmul/gemv.metalindex 5ba80b972..70d310cef 100644--- a/crates/uzu/src/backends/metal/kernel/matmul/gemv.metal+++ b/crates/uzu/src/backends/metal/kernel/matmul/gemv.metal@@ -3,7 +3,11 @@#include <metal_stdlib>using namespace metal;-template <typename T, typename AccT, int ROWS_PER_SIMDGROUP, int ELEMS_PER_THREAD>+template <+ typename T,+ typename AccT,+ int ROWS_PER_SIMDGROUP,+ int ELEMS_PER_THREAD>METAL_FUNC void gemv_multirow(const device T* __restrict weights,const device T* __restrict input,@@ -15,109 +19,125 @@ METAL_FUNC void gemv_multirow(const int input_batch_stride,const int output_batch_stride,uint row_base,- uint simd_lid) {+ uint simd_lid+) {- constexpr int BLOCK_K = 32 * ELEMS_PER_THREAD;+ constexpr int BLOCK_K = 32 * ELEMS_PER_THREAD;- input += batch_idx * input_batch_stride;- output += batch_idx * output_batch_stride;+ input += batch_idx * input_batch_stride;+ output += batch_idx * output_batch_stride;- if (row_base >= static_cast<uint>(output_dim)) {- return;- }-- const int rows_to_compute = min(ROWS_PER_SIMDGROUP, output_dim - static_cast<int>(row_base));+ if (row_base >= static_cast<uint>(output_dim)) {+ return;+ }- AccT accumulators[ROWS_PER_SIMDGROUP];- #pragma unroll(ROWS_PER_SIMDGROUP)- for (int r = 0; r < ROWS_PER_SIMDGROUP; ++r) {- accumulators[r] = AccT(0);- }+ const int rows_to_compute =+ min(ROWS_PER_SIMDGROUP, output_dim - static_cast<int>(row_base));- AccT input_cache[ELEMS_PER_THREAD];+ AccT accumulators[ROWS_PER_SIMDGROUP];+#pragma unroll(ROWS_PER_SIMDGROUP)+ for (int r = 0; r < ROWS_PER_SIMDGROUP; ++r) {+ accumulators[r] = AccT(0);+ }- const device T* weight_row_ptrs[ROWS_PER_SIMDGROUP];- #pragma unroll(ROWS_PER_SIMDGROUP)- for (int r = 0; r < ROWS_PER_SIMDGROUP; ++r) {- weight_row_ptrs[r] = weights + (row_base + r) * weight_stride;- }+ AccT input_cache[ELEMS_PER_THREAD];- int k = 0;- for (; k + BLOCK_K <= input_dim; k += BLOCK_K) {- const int thread_k = k + simd_lid * ELEMS_PER_THREAD;+ const device T* weight_row_ptrs[ROWS_PER_SIMDGROUP];+#pragma unroll(ROWS_PER_SIMDGROUP)+ for (int r = 0; r < ROWS_PER_SIMDGROUP; ++r) {+ weight_row_ptrs[r] = weights + (row_base + r) * weight_stride;+ }- #pragma unroll(ELEMS_PER_THREAD)- for (int e = 0; e < ELEMS_PER_THREAD; ++e) {- input_cache[e] = static_cast<AccT>(input[thread_k + e]);- }+ int k = 0;+ for (; k + BLOCK_K <= input_dim; k += BLOCK_K) {+ const int thread_k = k + simd_lid * ELEMS_PER_THREAD;- #pragma unroll(ROWS_PER_SIMDGROUP)- for (int r = 0; r < ROWS_PER_SIMDGROUP; ++r) {- AccT dot = 0;- #pragma unroll(ELEMS_PER_THREAD)- for (int e = 0; e < ELEMS_PER_THREAD; ++e) {- dot += input_cache[e] * static_cast<AccT>(weight_row_ptrs[r][thread_k + e]);- }- accumulators[r] += dot;- }+#pragma unroll(ELEMS_PER_THREAD)+ for (int e = 0; e < ELEMS_PER_THREAD; ++e) {+ input_cache[e] = static_cast<AccT>(input[thread_k + e]);}- if (k < input_dim) {- const int thread_k = k + simd_lid * ELEMS_PER_THREAD;- const int remaining = input_dim - k;+#pragma unroll(ROWS_PER_SIMDGROUP)+ for (int r = 0; r < ROWS_PER_SIMDGROUP; ++r) {+ AccT dot = 0;+#pragma unroll(ELEMS_PER_THREAD)+ for (int e = 0; e < ELEMS_PER_THREAD; ++e) {+ dot += input_cache[e] *+ static_cast<AccT>(weight_row_ptrs[r][thread_k + e]);+ }+ accumulators[r] += dot;+ }+ }- #pragma unroll(ELEMS_PER_THREAD)- for (int e = 0; e < ELEMS_PER_THREAD; ++e) {- const int idx = simd_lid * ELEMS_PER_THREAD + e;- input_cache[e] = (idx < remaining) ? static_cast<AccT>(input[thread_k + e]) : AccT(0);- }+ if (k < input_dim) {+ const int thread_k = k + simd_lid * ELEMS_PER_THREAD;+ const int remaining = input_dim - k;- #pragma unroll(ROWS_PER_SIMDGROUP)- for (int r = 0; r < ROWS_PER_SIMDGROUP; ++r) {- AccT dot = 0;- #pragma unroll(ELEMS_PER_THREAD)- for (int e = 0; e < ELEMS_PER_THREAD; ++e) {- const int idx = simd_lid * ELEMS_PER_THREAD + e;- if (idx < remaining) {- dot += input_cache[e] * static_cast<AccT>(weight_row_ptrs[r][thread_k + e]);- }- }- accumulators[r] += dot;- }+#pragma unroll(ELEMS_PER_THREAD)+ for (int e = 0; e < ELEMS_PER_THREAD; ++e) {+ const int idx = simd_lid * ELEMS_PER_THREAD + e;+ input_cache[e] =+ (idx < remaining) ? static_cast<AccT>(input[thread_k + e]) : AccT(0);}- #pragma unroll(ROWS_PER_SIMDGROUP)+#pragma unroll(ROWS_PER_SIMDGROUP)for (int r = 0; r < ROWS_PER_SIMDGROUP; ++r) {- accumulators[r] = simd_sum(accumulators[r]);+ AccT dot = 0;+#pragma unroll(ELEMS_PER_THREAD)+ for (int e = 0; e < ELEMS_PER_THREAD; ++e) {+ const int idx = simd_lid * ELEMS_PER_THREAD + e;+ if (idx < remaining) {+ dot += input_cache[e] *+ static_cast<AccT>(weight_row_ptrs[r][thread_k + e]);+ }+ }+ accumulators[r] += dot;}+ }- if (simd_lid == 0) {- #pragma unroll(ROWS_PER_SIMDGROUP)- for (int r = 0; r < rows_to_compute; ++r) {- output[row_base + r] = static_cast<T>(accumulators[r]);- }+#pragma unroll(ROWS_PER_SIMDGROUP)+ for (int r = 0; r < ROWS_PER_SIMDGROUP; ++r) {+ accumulators[r] = simd_sum(accumulators[r]);+ }++ if (simd_lid == 0) {+#pragma unroll(ROWS_PER_SIMDGROUP)+ for (int r = 0; r < rows_to_compute; ++r) {+ output[row_base + r] = static_cast<T>(accumulators[r]);}+ }}-#define DECL_GEMV_FAST(NAME, TYPE, ACC) \- [[kernel]] void NAME( \- const device TYPE* weights [[buffer(0)]], \- const device TYPE* input [[buffer(1)]], \- device TYPE* output [[buffer(2)]], \- constant int& input_dim [[buffer(3)]], \- constant int& output_dim [[buffer(4)]], \- constant int& weight_stride [[buffer(5)]], \- constant int& input_batch_stride [[buffer(6)]], \- constant int& output_batch_stride [[buffer(7)]], \- uint3 tgid [[threadgroup_position_in_grid]], \- uint simd_lid [[thread_index_in_simdgroup]]) { \- constexpr int ROWS_PER_SIMDGROUP = 4; \- constexpr int ELEMS_PER_THREAD = 4; \- const uint row_base = tgid.x * ROWS_PER_SIMDGROUP; \- gemv_multirow<TYPE, ACC, ROWS_PER_SIMDGROUP, ELEMS_PER_THREAD>( \- weights, input, output, input_dim, output_dim, weight_stride, \- tgid.z, input_batch_stride, output_batch_stride, row_base, simd_lid); \- }+#define DECL_GEMV_FAST(NAME, TYPE, ACC) \+ [[kernel]] void NAME( \+ const device TYPE* weights [[buffer(0)]], \+ const device TYPE* input [[buffer(1)]], \+ device TYPE* output [[buffer(2)]], \+ constant int& input_dim [[buffer(3)]], \+ constant int& output_dim [[buffer(4)]], \+ constant int& weight_stride [[buffer(5)]], \+ constant int& input_batch_stride [[buffer(6)]], \+ constant int& output_batch_stride [[buffer(7)]], \+ uint3 tgid [[threadgroup_position_in_grid]], \+ uint simd_lid [[thread_index_in_simdgroup]] \+ ) { \+ constexpr int ROWS_PER_SIMDGROUP = 4; \+ constexpr int ELEMS_PER_THREAD = 4; \+ const uint row_base = tgid.x * ROWS_PER_SIMDGROUP; \+ gemv_multirow<TYPE, ACC, ROWS_PER_SIMDGROUP, ELEMS_PER_THREAD>( \+ weights, \+ input, \+ output, \+ input_dim, \+ output_dim, \+ weight_stride, \+ tgid.z, \+ input_batch_stride, \+ output_batch_stride, \+ row_base, \+ simd_lid \+ ); \+ }DECL_GEMV_FAST(gemv_fast_f16, half, float)DECL_GEMV_FAST(gemv_fast_bf16, bfloat, float)@@ -137,68 +157,83 @@ METAL_FUNC void gemv_tiled(uint simd_gid,uint simd_lid,uint tid,- threadgroup AccT* input_tile) {-- const ushort THREADS_PER_THREADGROUP = ROWS_PER_THREADGROUP * 32;- if (simd_gid >= ROWS_PER_THREADGROUP) {- return;- }+ threadgroup AccT* input_tile+) {- const uint row = tgid.x * ROWS_PER_THREADGROUP + simd_gid;- if (row >= output_dim) {- return;- }+ const ushort THREADS_PER_THREADGROUP = ROWS_PER_THREADGROUP * 32;+ if (simd_gid >= ROWS_PER_THREADGROUP) {+ return;+ }- const uint batch = tgid.z;- const device T* weight_row = weights + row * weight_stride;- const device T* input_ptr = input + batch * input_stride;- device T* output_ptr = output + batch * output_stride;+ const uint row = tgid.x * ROWS_PER_THREADGROUP + simd_gid;+ if (row >= output_dim) {+ return;+ }- AccT accumulator = AccT(0);+ const uint batch = tgid.z;+ const device T* weight_row = weights + row * weight_stride;+ const device T* input_ptr = input + batch * input_stride;+ device T* output_ptr = output + batch * output_stride;- for (uint k_block = 0; k_block < input_dim; k_block += TILE_K) {- const uint remaining = input_dim - k_block;- const uint tile_size = remaining < TILE_K ? remaining : TILE_K;+ AccT accumulator = AccT(0);- if (tid < tile_size && tid < THREADS_PER_THREADGROUP) {- input_tile[tid] = static_cast<AccT>(input_ptr[k_block + tid]);- }- threadgroup_barrier(mem_flags::mem_threadgroup);+ for (uint k_block = 0; k_block < input_dim; k_block += TILE_K) {+ const uint remaining = input_dim - k_block;+ const uint tile_size = remaining < TILE_K ? remaining : TILE_K;- for (uint idx = simd_lid; idx < tile_size; idx += 32) {- accumulator += static_cast<AccT>(weight_row[k_block + idx]) * input_tile[idx];- }- threadgroup_barrier(mem_flags::mem_threadgroup);+ if (tid < tile_size && tid < THREADS_PER_THREADGROUP) {+ input_tile[tid] = static_cast<AccT>(input_ptr[k_block + tid]);}+ threadgroup_barrier(mem_flags::mem_threadgroup);- for (ushort offset = 16; offset > 0; offset >>= 1) {- accumulator += simd_shuffle_down(accumulator, offset);+ for (uint idx = simd_lid; idx < tile_size; idx += 32) {+ accumulator +=+ static_cast<AccT>(weight_row[k_block + idx]) * input_tile[idx];}+ threadgroup_barrier(mem_flags::mem_threadgroup);+ }- if (simd_lid == 0) {- output_ptr[row] = static_cast<T>(accumulator);- }+ for (ushort offset = 16; offset > 0; offset >>= 1) {+ accumulator += simd_shuffle_down(accumulator, offset);+ }++ if (simd_lid == 0) {+ output_ptr[row] = static_cast<T>(accumulator);+ }}-#define DECL_GEMV_TILED(NAME, TYPE, ACC, ROWS, TILE_K) \- [[kernel, max_total_threads_per_threadgroup(ROWS * 32)]] void NAME( \- const device TYPE* weights [[buffer(0)]], \- const device TYPE* input [[buffer(1)]], \- device TYPE* output [[buffer(2)]], \- constant uint& input_dim [[buffer(3)]], \- constant uint& output_dim [[buffer(4)]], \- constant uint& weight_stride [[buffer(5)]], \- constant uint& input_stride [[buffer(6)]], \- constant uint& output_stride [[buffer(7)]], \- uint3 tgid [[threadgroup_position_in_grid]], \- uint simd_gid [[simdgroup_index_in_threadgroup]], \- uint simd_lid [[thread_index_in_simdgroup]], \- uint tid [[thread_index_in_threadgroup]]) { \- threadgroup ACC input_tile[TILE_K]; \- gemv_tiled<TYPE, ACC, ROWS, TILE_K>( \- weights, input, output, input_dim, output_dim, weight_stride, \- input_stride, output_stride, tgid, simd_gid, simd_lid, tid, input_tile); \- }+#define DECL_GEMV_TILED(NAME, TYPE, ACC, ROWS, TILE_K) \+ [[kernel, max_total_threads_per_threadgroup(ROWS * 32)]] void NAME( \+ const device TYPE* weights [[buffer(0)]], \+ const device TYPE* input [[buffer(1)]], \+ device TYPE* output [[buffer(2)]], \+ constant uint& input_dim [[buffer(3)]], \+ constant uint& output_dim [[buffer(4)]], \+ constant uint& weight_stride [[buffer(5)]], \+ constant uint& input_stride [[buffer(6)]], \+ constant uint& output_stride [[buffer(7)]], \+ uint3 tgid [[threadgroup_position_in_grid]], \+ uint simd_gid [[simdgroup_index_in_threadgroup]], \+ uint simd_lid [[thread_index_in_simdgroup]], \+ uint tid [[thread_index_in_threadgroup]] \+ ) { \+ threadgroup ACC input_tile[TILE_K]; \+ gemv_tiled<TYPE, ACC, ROWS, TILE_K>( \+ weights, \+ input, \+ output, \+ input_dim, \+ output_dim, \+ weight_stride, \+ input_stride, \+ output_stride, \+ tgid, \+ simd_gid, \+ simd_lid, \+ tid, \+ input_tile \+ ); \+ }DECL_GEMV_TILED(gemv_f16_rows2, half, float, 2, 128)DECL_GEMV_TILED(gemv_f16_rows4, half, float, 4, 128)diff --git a/crates/uzu/src/backends/metal/kernel/matmul/gemv_masked.metal b/crates/uzu/src/backends/metal/kernel/matmul/gemv_masked.metalindex e36180018..622969fde 100644--- a/crates/uzu/src/backends/metal/kernel/matmul/gemv_masked.metal+++ b/crates/uzu/src/backends/metal/kernel/matmul/gemv_masked.metal@@ -18,38 +18,38 @@ METAL_FUNC void gemv_masked_impl(constant uint& ldd [[buffer(9)]],uint3 tgid [[threadgroup_position_in_grid]],uint simd_gid [[simdgroup_index_in_threadgroup]],- uint simd_lid [[thread_index_in_simdgroup]]) {- if (simd_gid >= ROWS) {- return;- }- const uint row = tgid.x * ROWS + simd_gid;- if (row >= n) {- return;- }- const uint batch = tgid.z;- const device T* row_ptr = matrix + row * ldb;- const device T* vec_ptr = vector + batch * lda;- device T* out_ptr = output + batch * ldd;+ uint simd_lid [[thread_index_in_simdgroup]]+) {+ if (simd_gid >= ROWS) {+ return;+ }+ const uint row = tgid.x * ROWS + simd_gid;+ if (row >= n) {+ return;+ }+ const uint batch = tgid.z;+ const device T* row_ptr = matrix + row * ldb;+ const device T* vec_ptr = vector + batch * lda;+ device T* out_ptr = output + batch * ldd;- AccT acc = static_cast<AccT>(0);- for (uint idx = simd_lid; idx < k; idx += 32) {- // If op_mask provided, zero out masked elements- const bool op_on = (op_mask == nullptr) || (op_mask[row] != 0);- if (op_on) {- acc += static_cast<AccT>(row_ptr[idx]) *- static_cast<AccT>(vec_ptr[idx]);- }+ AccT acc = static_cast<AccT>(0);+ for (uint idx = simd_lid; idx < k; idx += 32) {+ // If op_mask provided, zero out masked elements+ const bool op_on = (op_mask == nullptr) || (op_mask[row] != 0);+ if (op_on) {+ acc += static_cast<AccT>(row_ptr[idx]) * static_cast<AccT>(vec_ptr[idx]);}+ }- for (ushort offset = 16; offset > 0; offset >>= 1) {- acc += simd_shuffle_down(acc, offset);- }+ for (ushort offset = 16; offset > 0; offset >>= 1) {+ acc += simd_shuffle_down(acc, offset);+ }- if (simd_lid == 0) {- if (out_mask == nullptr || out_mask[row] != 0) {- out_ptr[row] = static_cast<T>(acc);- }+ if (simd_lid == 0) {+ if (out_mask == nullptr || out_mask[row] != 0) {+ out_ptr[row] = static_cast<T>(acc);}+ }}template <typename T, typename AccT, ushort ROWS>@@ -66,74 +66,101 @@ METAL_FUNC void gemv_gather_impl(constant uint& ldd [[buffer(9)]],uint3 tgid [[threadgroup_position_in_grid]],uint simd_gid [[simdgroup_index_in_threadgroup]],- uint simd_lid [[thread_index_in_simdgroup]]) {- if (simd_gid >= ROWS) {- return;- }- const uint row = tgid.x * ROWS + simd_gid;- if (row >= n) {- return;- }- const uint batch = tgid.z;- const device T* base_row = matrix + row * ldb;- device T* out_ptr = output + batch * ldd;+ uint simd_lid [[thread_index_in_simdgroup]]+) {+ if (simd_gid >= ROWS) {+ return;+ }+ const uint row = tgid.x * ROWS + simd_gid;+ if (row >= n) {+ return;+ }+ const uint batch = tgid.z;+ const device T* base_row = matrix + row * ldb;+ device T* out_ptr = output + batch * ldd;- AccT acc = static_cast<AccT>(0);- for (uint idx = simd_lid; idx < k; idx += 32) {- const uint col = mat_indices ? mat_indices[idx] : idx;- const uint vec_idx = vec_indices ? vec_indices[idx] : idx;- acc += static_cast<AccT>(base_row[col]) *- static_cast<AccT>(vector[batch * lda + vec_idx]);- }+ AccT acc = static_cast<AccT>(0);+ for (uint idx = simd_lid; idx < k; idx += 32) {+ const uint col = mat_indices ? mat_indices[idx] : idx;+ const uint vec_idx = vec_indices ? vec_indices[idx] : idx;+ acc += static_cast<AccT>(base_row[col]) *+ static_cast<AccT>(vector[batch * lda + vec_idx]);+ }- for (ushort offset = 16; offset > 0; offset >>= 1) {- acc += simd_shuffle_down(acc, offset);- }+ for (ushort offset = 16; offset > 0; offset >>= 1) {+ acc += simd_shuffle_down(acc, offset);+ }- if (simd_lid == 0) {- out_ptr[row] = static_cast<T>(acc);- }+ if (simd_lid == 0) {+ out_ptr[row] = static_cast<T>(acc);+ }}-#define DECL_GEMV_MASKED(NAME, TYPE, ACC, ROWS) \- [[kernel, max_total_threads_per_threadgroup(ROWS * 32)]] void NAME( \- const device TYPE* matrix [[buffer(0)]], \- const device TYPE* vector [[buffer(1)]], \- const device uchar* out_mask [[buffer(2)]], \- const device uchar* op_mask [[buffer(3)]], \- device TYPE* output [[buffer(4)]], \- constant uint& k [[buffer(5)]], \- constant uint& n [[buffer(6)]], \- constant uint& ldb [[buffer(7)]], \- constant uint& lda [[buffer(8)]], \- constant uint& ldd [[buffer(9)]], \- uint3 tgid [[threadgroup_position_in_grid]], \- uint simd_gid [[simdgroup_index_in_threadgroup]], \- uint simd_lid [[thread_index_in_simdgroup]]) { \- gemv_masked_impl<TYPE, ACC, ROWS>( \- matrix, vector, out_mask, op_mask, output, \- k, n, ldb, lda, ldd, tgid, simd_gid, simd_lid); \- }+#define DECL_GEMV_MASKED(NAME, TYPE, ACC, ROWS) \+ [[kernel, max_total_threads_per_threadgroup(ROWS * 32)]] void NAME( \+ const device TYPE* matrix [[buffer(0)]], \+ const device TYPE* vector [[buffer(1)]], \+ const device uchar* out_mask [[buffer(2)]], \+ const device uchar* op_mask [[buffer(3)]], \+ device TYPE* output [[buffer(4)]], \+ constant uint& k [[buffer(5)]], \+ constant uint& n [[buffer(6)]], \+ constant uint& ldb [[buffer(7)]], \+ constant uint& lda [[buffer(8)]], \+ constant uint& ldd [[buffer(9)]], \+ uint3 tgid [[threadgroup_position_in_grid]], \+ uint simd_gid [[simdgroup_index_in_threadgroup]], \+ uint simd_lid [[thread_index_in_simdgroup]] \+ ) { \+ gemv_masked_impl<TYPE, ACC, ROWS>( \+ matrix, \+ vector, \+ out_mask, \+ op_mask, \+ output, \+ k, \+ n, \+ ldb, \+ lda, \+ ldd, \+ tgid, \+ simd_gid, \+ simd_lid \+ ); \+ }-#define DECL_GEMV_GATHER(NAME, TYPE, ACC, ROWS) \- [[kernel, max_total_threads_per_threadgroup(ROWS * 32)]] void NAME( \- const device TYPE* matrix [[buffer(0)]], \- const device TYPE* vector [[buffer(1)]], \- const device uint* vec_indices [[buffer(2)]], \- const device uint* mat_indices [[buffer(3)]], \- device TYPE* output [[buffer(4)]], \- constant uint& k [[buffer(5)]], \- constant uint& n [[buffer(6)]], \- constant uint& ldb [[buffer(7)]], \- constant uint& lda [[buffer(8)]], \- constant uint& ldd [[buffer(9)]], \- uint3 tgid [[threadgroup_position_in_grid]], \- uint simd_gid [[simdgroup_index_in_threadgroup]], \- uint simd_lid [[thread_index_in_simdgroup]]) { \- gemv_gather_impl<TYPE, ACC, ROWS>( \- matrix, vector, vec_indices, mat_indices, output, \- k, n, ldb, lda, ldd, tgid, simd_gid, simd_lid); \- }+#define DECL_GEMV_GATHER(NAME, TYPE, ACC, ROWS) \+ [[kernel, max_total_threads_per_threadgroup(ROWS * 32)]] void NAME( \+ const device TYPE* matrix [[buffer(0)]], \+ const device TYPE* vector [[buffer(1)]], \+ const device uint* vec_indices [[buffer(2)]], \+ const device uint* mat_indices [[buffer(3)]], \+ device TYPE* output [[buffer(4)]], \+ constant uint& k [[buffer(5)]], \+ constant uint& n [[buffer(6)]], \+ constant uint& ldb [[buffer(7)]], \+ constant uint& lda [[buffer(8)]], \+ constant uint& ldd [[buffer(9)]], \+ uint3 tgid [[threadgroup_position_in_grid]], \+ uint simd_gid [[simdgroup_index_in_threadgroup]], \+ uint simd_lid [[thread_index_in_simdgroup]] \+ ) { \+ gemv_gather_impl<TYPE, ACC, ROWS>( \+ matrix, \+ vector, \+ vec_indices, \+ mat_indices, \+ output, \+ k, \+ n, \+ ldb, \+ lda, \+ ldd, \+ tgid, \+ simd_gid, \+ simd_lid \+ ); \+ }// Masked instantiationsDECL_GEMV_MASKED(gemv_masked_f16_rows4, half, float, 4)@@ -146,4 +173,5 @@ DECL_GEMV_GATHER(gemv_gather_f16_rows4, half, float, 4)DECL_GEMV_GATHER(gemv_gather_f16_rows8, half, float, 8)DECL_GEMV_GATHER(gemv_gather_bf16_rows4, bfloat, float, 4)DECL_GEMV_GATHER(gemv_gather_bf16_rows8, bfloat, float, 8)-// Masked/gather GEMV kernels are stubbed out (not used). Keeping file empty to avoid shader compilation errors.+// Masked/gather GEMV kernels are stubbed out (not used). Keeping file empty to+// avoid shader compilation errors.diff --git a/crates/uzu/src/backends/metal/kernel/matmul/splitk.metal b/crates/uzu/src/backends/metal/kernel/matmul/splitk.metalindex 0b2a48247..d79061915 100644--- a/crates/uzu/src/backends/metal/kernel/matmul/splitk.metal+++ b/crates/uzu/src/backends/metal/kernel/matmul/splitk.metal@@ -32,7 +32,8 @@ void splitk_partial_gemm(uint simd_lane_id [[thread_index_in_simdgroup]],uint simd_group_id [[simdgroup_index_in_threadgroup]],uint3 threadgroup_id [[threadgroup_position_in_grid]],- uint3 thread_id [[thread_position_in_threadgroup]]) {+ uint3 thread_id [[thread_position_in_threadgroup]]+) {(void)thread_id;using gemm_kernel = GEMMKernel<@@ -66,7 +67,8 @@ void splitk_partial_gemm(const int output_row = tile_y * TileRows;const int output_col = tile_x * TileCols;- const int k_partition_start = params->k_elements_per_partition * partition_index;+ const int k_partition_start =+ params->k_elements_per_partition * partition_index;const size_t output_row_long = size_t(output_row);const size_t output_col_long = size_t(output_col);@@ -76,18 +78,31 @@ void splitk_partial_gemm(const device InputType* b_ptr = input_b;a_ptr += TransposeA- ? (output_row_long + k_start_long * params->leading_dim_a)- : (k_start_long + output_row_long * params->leading_dim_a);+ ? (output_row_long + k_start_long * params->leading_dim_a)+ : (k_start_long + output_row_long * params->leading_dim_a);b_ptr += TransposeB- ? (k_start_long + output_col_long * params->leading_dim_b)- : (output_col_long + k_start_long * params->leading_dim_b);+ ? (k_start_long + output_col_long * params->leading_dim_b)+ : (output_col_long + k_start_long * params->leading_dim_b);- device AccumulatorType* output_ptr = accumulator ++ device AccumulatorType* output_ptr =+ accumulator +(size_t(params->output_elements_per_partition) * partition_index) +(output_row_long * params->leading_dim_accumulator + output_col_long);- thread loader_a_t loader_a(a_ptr, params->leading_dim_a, shared_a, simd_group_id, simd_lane_id);- thread loader_b_t loader_b(b_ptr, params->leading_dim_b, shared_b, simd_group_id, simd_lane_id);+ thread loader_a_t loader_a(+ a_ptr,+ params->leading_dim_a,+ shared_a,+ simd_group_id,+ simd_lane_id+ );+ thread loader_b_t loader_b(+ b_ptr,+ params->leading_dim_b,+ shared_b,+ simd_group_id,+ simd_lane_id+ );thread mma_t mma_op(simd_group_id, simd_lane_id);int gemm_k_iterations = params->gemm_k_iterations_aligned;@@ -96,57 +111,93 @@ void splitk_partial_gemm(short tile_bound_n = min(TileCols, params->n - output_col);short leftover_k = params->k % TileDepth;- const bool is_last_partition = (partition_index + 1) == params->partition_count;+ const bool is_last_partition =+ (partition_index + 1) == params->partition_count;if (MNAligned || (tile_bound_m == TileRows && tile_bound_n == TileCols)) {gemm_kernel::gemm_loop(- shared_a, shared_b,+ shared_a,+ shared_b,gemm_k_iterations,- loader_a, loader_b, mma_op,- tile_bound_m, tile_bound_n, leftover_k,- LoopAlignment<true, true, true>{});+ loader_a,+ loader_b,+ mma_op,+ tile_bound_m,+ tile_bound_n,+ leftover_k,+ LoopAlignment<true, true, true>{}+ );} else if (tile_bound_n == TileCols) {gemm_kernel::gemm_loop(- shared_a, shared_b,+ shared_a,+ shared_b,gemm_k_iterations,- loader_a, loader_b, mma_op,- tile_bound_m, tile_bound_n, leftover_k,- LoopAlignment<false, true, true>{});+ loader_a,+ loader_b,+ mma_op,+ tile_bound_m,+ tile_bound_n,+ leftover_k,+ LoopAlignment<false, true, true>{}+ );} else if (tile_bound_m == TileRows) {gemm_kernel::gemm_loop(- shared_a, shared_b,+ shared_a,+ shared_b,gemm_k_iterations,- loader_a, loader_b, mma_op,- tile_bound_m, tile_bound_n, leftover_k,- LoopAlignment<true, false, true>{});+ loader_a,+ loader_b,+ mma_op,+ tile_bound_m,+ tile_bound_n,+ leftover_k,+ LoopAlignment<true, false, true>{}+ );} else {gemm_kernel::gemm_loop(- shared_a, shared_b,+ shared_a,+ shared_b,gemm_k_iterations,- loader_a, loader_b, mma_op,- tile_bound_m, tile_bound_n, leftover_k,- LoopAlignment<false, false, true>{});+ loader_a,+ loader_b,+ mma_op,+ tile_bound_m,+ tile_bound_n,+ leftover_k,+ LoopAlignment<false, false, true>{}+ );}threadgroup_barrier(mem_flags::mem_threadgroup);if (is_last_partition) {int remaining_k_iterations =- (params->k - (k_partition_start + params->k_elements_per_partition)) / TileDepth;+ (params->k - (k_partition_start + params->k_elements_per_partition)) /+ TileDepth;if (!KAligned || remaining_k_iterations > 0) {gemm_kernel::gemm_loop(- shared_a, shared_b,+ shared_a,+ shared_b,remaining_k_iterations,- loader_a, loader_b, mma_op,- tile_bound_m, tile_bound_n, leftover_k,- LoopAlignment<false, false, KAligned>{});+ loader_a,+ loader_b,+ mma_op,+ tile_bound_m,+ tile_bound_n,+ leftover_k,+ LoopAlignment<false, false, KAligned>{}+ );}}if (MNAligned || (tile_bound_m == TileRows && tile_bound_n == TileCols)) {mma_op.store_result(output_ptr, params->leading_dim_accumulator);} else {- mma_op.store_result_safe(output_ptr, params->leading_dim_accumulator, short2(tile_bound_n, tile_bound_m));+ mma_op.store_result_safe(+ output_ptr,+ params->leading_dim_accumulator,+ short2(tile_bound_n, tile_bound_m)+ );}}@@ -161,7 +212,8 @@ template <typename OutputType, typename AccumulatorType>constant int& partition_count [[buffer(2)]],constant int& output_elements_per_partition [[buffer(3)]],constant int& leading_dim_output [[buffer(4)]],- uint2 thread_position [[thread_position_in_grid]]) {+ uint2 thread_position [[thread_position_in_grid]]+) {const size_t col = thread_position.x;const size_t row = thread_position.y;@@ -184,18 +236,33 @@ template <typename OutputType, typename AccumulatorType>///////////////////////////////////////////////////////////////////////////////#define INSTANTIATE_SPLITK_PARTIAL( \- transpose_name, transpose_a, transpose_b, \- type_name, input_type, \- tile_rows, tile_cols, tile_depth, warps_row, warps_col) \+ transpose_name, \+ transpose_a, \+ transpose_b, \+ type_name, \+ input_type, \+ tile_rows, \+ tile_cols, \+ tile_depth, \+ warps_row, \+ warps_col \+) \template [[host_name( \- "splitk_partial_" #transpose_name "_" #type_name \- "_tm" #tile_rows "_tn" #tile_cols "_tk" #tile_depth \- "_wm" #warps_row "_wn" #warps_col \+ "splitk_partial_" #transpose_name "_" #type_name "_tm" #tile_rows \+ "_tn" #tile_cols "_tk" #tile_depth "_wm" #warps_row "_wn" #warps_col \)]] [[kernel]] void \splitk_partial_gemm< \- input_type, float, \- tile_rows, tile_cols, tile_depth, warps_row, warps_col, \- transpose_a, transpose_b, false, false>( \+ input_type, \+ float, \+ tile_rows, \+ tile_cols, \+ tile_depth, \+ warps_row, \+ warps_col, \+ transpose_a, \+ transpose_b, \+ false, \+ false>( \const device input_type* input_a [[buffer(0)]], \const device input_type* input_b [[buffer(1)]], \device float* accumulator [[buffer(2)]], \@@ -203,18 +270,66 @@ template <typename OutputType, typename AccumulatorType>uint simd_lane_id [[thread_index_in_simdgroup]], \uint simd_group_id [[simdgroup_index_in_threadgroup]], \uint3 threadgroup_id [[threadgroup_position_in_grid]], \- uint3 thread_id [[thread_position_in_threadgroup]]);+ uint3 thread_id [[thread_position_in_threadgroup]] \+ );#define INSTANTIATE_SPLITK_TRANSPOSE_HELPER( \- type_name, input_type, tile_rows, tile_cols, tile_depth, warps_row, warps_col) \- INSTANTIATE_SPLITK_PARTIAL(nn, false, false, type_name, input_type, \- tile_rows, tile_cols, tile_depth, warps_row, warps_col) \- INSTANTIATE_SPLITK_PARTIAL(nt, false, true, type_name, input_type, \- tile_rows, tile_cols, tile_depth, warps_row, warps_col) \- INSTANTIATE_SPLITK_PARTIAL(tn, true, false, type_name, input_type, \- tile_rows, tile_cols, tile_depth, warps_row, warps_col) \- INSTANTIATE_SPLITK_PARTIAL(tt, true, true, type_name, input_type, \- tile_rows, tile_cols, tile_depth, warps_row, warps_col)+ type_name, \+ input_type, \+ tile_rows, \+ tile_cols, \+ tile_depth, \+ warps_row, \+ warps_col \+) \+ INSTANTIATE_SPLITK_PARTIAL( \+ nn, \+ false, \+ false, \+ type_name, \+ input_type, \+ tile_rows, \+ tile_cols, \+ tile_depth, \+ warps_row, \+ warps_col \+ ) \+ INSTANTIATE_SPLITK_PARTIAL( \+ nt, \+ false, \+ true, \+ type_name, \+ input_type, \+ tile_rows, \+ tile_cols, \+ tile_depth, \+ warps_row, \+ warps_col \+ ) \+ INSTANTIATE_SPLITK_PARTIAL( \+ tn, \+ true, \+ false, \+ type_name, \+ input_type, \+ tile_rows, \+ tile_cols, \+ tile_depth, \+ warps_row, \+ warps_col \+ ) \+ INSTANTIATE_SPLITK_PARTIAL( \+ tt, \+ true, \+ true, \+ type_name, \+ input_type, \+ tile_rows, \+ tile_cols, \+ tile_depth, \+ warps_row, \+ warps_col \+ )#define INSTANTIATE_SPLITK_SHAPES_HELPER(type_name, input_type) \INSTANTIATE_SPLITK_TRANSPOSE_HELPER(type_name, input_type, 16, 16, 16, 2, 2) \@@ -234,7 +349,8 @@ INSTANTIATE_SPLITK_SHAPES_HELPER(f32, float)constant int& partition_count [[buffer(2)]], \constant int& output_elements_per_partition [[buffer(3)]], \constant int& leading_dim_output [[buffer(4)]], \- uint2 thread_position [[thread_position_in_grid]]);+ uint2 thread_position [[thread_position_in_grid]] \+ );INSTANTIATE_SPLITK_ACCUM(f16, half)INSTANTIATE_SPLITK_ACCUM(bf16, bfloat)diff --git a/crates/uzu/src/backends/metal/kernel/sampling/bitmask.metal b/crates/uzu/src/backends/metal/kernel/sampling/bitmask.metalindex c1571bc2f..8165d45f4 100644--- a/crates/uzu/src/backends/metal/kernel/sampling/bitmask.metal+++ b/crates/uzu/src/backends/metal/kernel/sampling/bitmask.metal@@ -27,9 +27,8 @@ void batched_bitmask(if (global_idx < batch_end) {uint token_idx = global_idx - batch_idx * vocab_size;uint bitmask_idx = batch_idx * bitmask_size + (token_idx / BITS_IN_U32);- bool mask = (bitmask_data[bitmask_idx] >>- (token_idx % BITS_IN_U32)) &- 0b1;+ bool mask =+ (bitmask_data[bitmask_idx] >> (token_idx % BITS_IN_U32)) & 0b1;processed_logits[global_idx] =select(T(-INFINITY), logits_data[global_idx], mask);}diff --git a/crates/uzu/src/backends/metal/kernel/sampling/min_p.metal b/crates/uzu/src/backends/metal/kernel/sampling/min_p.metalindex 94e9e2d47..a5fb3797d 100644--- a/crates/uzu/src/backends/metal/kernel/sampling/min_p.metal+++ b/crates/uzu/src/backends/metal/kernel/sampling/min_p.metal@@ -29,7 +29,8 @@ void batched_minp(thread_idx);- // Then the threshold is just max_logit + log(min_p), mask everything strictly below it+ // Then the threshold is just max_logit + log(min_p), mask everything strictly+ // below itT t_threshold = T(max_logit + log(min_p));#pragma unroll(4)for (uint i = thread_idx; i < vocab_size; i += BLOCK_SIZE) {diff --git a/crates/uzu/src/backends/metal/kernel/short_conv/short_conv.metal b/crates/uzu/src/backends/metal/kernel/short_conv/short_conv.metalindex a9bbb2b86..bdb7e0edb 100644--- a/crates/uzu/src/backends/metal/kernel/short_conv/short_conv.metal+++ b/crates/uzu/src/backends/metal/kernel/short_conv/short_conv.metal@@ -14,32 +14,34 @@ kernel void short_conv_pack_kernel(constant const uint& model_dim [[buffer(6)]],uint2 grid_idx [[thread_position_in_grid]]) {- const uint channel_idx = grid_idx.x;- const uint row_idx = grid_idx.y;- const size_t padded_rows = state_stride + suffix_len;-- if (channel_idx >= model_dim || row_idx >= padded_rows) {- return;- }-- const size_t padded_offset =- size_t(row_idx) * model_dim + size_t(channel_idx);-- if (row_idx < state_stride) {- // Copy from state- const size_t state_idx = size_t(channel_idx) * state_stride + size_t(row_idx);- padded[padded_offset] = state_in[state_idx];- } else {- // Compute gated input from in_proj- const size_t token = row_idx - state_stride;- const size_t in_proj_idx = size_t(token) * in_proj_stride + size_t(channel_idx);-- float pre_gate = float(in_proj[in_proj_idx]);- float x_in = float(in_proj[in_proj_idx + 2 * model_dim]);- float x = x_in * pre_gate;+ const uint channel_idx = grid_idx.x;+ const uint row_idx = grid_idx.y;+ const size_t padded_rows = state_stride + suffix_len;++ if (channel_idx >= model_dim || row_idx >= padded_rows) {+ return;+ }++ const size_t padded_offset =+ size_t(row_idx) * model_dim + size_t(channel_idx);++ if (row_idx < state_stride) {+ // Copy from state+ const size_t state_idx =+ size_t(channel_idx) * state_stride + size_t(row_idx);+ padded[padded_offset] = state_in[state_idx];+ } else {+ // Compute gated input from in_proj+ const size_t token = row_idx - state_stride;+ const size_t in_proj_idx =+ size_t(token) * in_proj_stride + size_t(channel_idx);++ float pre_gate = float(in_proj[in_proj_idx]);+ float x_in = float(in_proj[in_proj_idx + 2 * model_dim]);+ float x = x_in * pre_gate;- padded[padded_offset] = static_cast<T>(x);- }+ padded[padded_offset] = static_cast<T>(x);+ }}template <typename T>@@ -57,54 +59,55 @@ kernel void short_conv_prefill_kernel(constant const uint& model_dim [[buffer(10)]],uint2 grid_idx [[thread_position_in_grid]]) {- const int tap_count = max(kernel_size - 1, 0);- const size_t work_len = suffix_len + size_t(tap_count);+ const int tap_count = max(kernel_size - 1, 0);+ const size_t work_len = suffix_len + size_t(tap_count);- const uint token_idx = grid_idx.x;- const uint channel_idx = grid_idx.y;+ const uint token_idx = grid_idx.x;+ const uint channel_idx = grid_idx.y;- if (channel_idx >= model_dim || token_idx >= work_len) {- return;- }+ if (channel_idx >= model_dim || token_idx >= work_len) {+ return;+ }++ const device T* w_row = w + size_t(channel_idx) * size_t(kernel_size);+ const bool has_bias = b != nullptr;++ // Threads [0..suffix_len-1]: Compute outputs+ if (token_idx < suffix_len) {+ float acc = has_bias ? float(b[channel_idx]) : 0.0f;- const device T* w_row = w + size_t(channel_idx) * size_t(kernel_size);- const bool has_bias = b != nullptr;-- // Threads [0..suffix_len-1]: Compute outputs- if (token_idx < suffix_len) {- float acc = has_bias ? float(b[channel_idx]) : 0.0f;-- // Convolve using padded buffer- for (int tap = 0; tap < kernel_size; ++tap) {- const size_t padded_row = size_t(token_idx + tap);- const size_t padded_offset = padded_row * model_dim + channel_idx;- float sample = float(padded[padded_offset]);- acc += float(w_row[tap]) * sample;- }-- // Apply post-gate from in_proj- const size_t in_proj_idx = size_t(token_idx) * in_proj_stride + size_t(channel_idx);- float post_conv_gate = float(in_proj[in_proj_idx + model_dim]);- float gated_output = acc * post_conv_gate;-- // Write output- const size_t out_idx = size_t(token_idx) * model_dim + size_t(channel_idx);- out[out_idx] = static_cast<T>(gated_output);+ // Convolve using padded buffer+ for (int tap = 0; tap < kernel_size; ++tap) {+ const size_t padded_row = size_t(token_idx + tap);+ const size_t padded_offset = padded_row * model_dim + channel_idx;+ float sample = float(padded[padded_offset]);+ acc += float(w_row[tap]) * sample;}- // Threads [suffix_len..work_len-1]: Write state- else if (tap_count > 0) {- const size_t tap = size_t(token_idx - suffix_len);- if (tap >= size_t(tap_count)) {- return;- }-- // Copy last tap_count values from padded to state_out- const size_t padded_row = suffix_len + tap;- const size_t padded_offset = padded_row * model_dim + channel_idx;- const size_t state_idx = size_t(channel_idx) * state_stride + tap;-- state_out[state_idx] = padded[padded_offset];++ // Apply post-gate from in_proj+ const size_t in_proj_idx =+ size_t(token_idx) * in_proj_stride + size_t(channel_idx);+ float post_conv_gate = float(in_proj[in_proj_idx + model_dim]);+ float gated_output = acc * post_conv_gate;++ // Write output+ const size_t out_idx = size_t(token_idx) * model_dim + size_t(channel_idx);+ out[out_idx] = static_cast<T>(gated_output);+ }+ // Threads [suffix_len..work_len-1]: Write state+ else if (tap_count > 0) {+ const size_t tap = size_t(token_idx - suffix_len);+ if (tap >= size_t(tap_count)) {+ return;}++ // Copy last tap_count values from padded to state_out+ const size_t padded_row = suffix_len + tap;+ const size_t padded_offset = padded_row * model_dim + channel_idx;+ const size_t state_idx = size_t(channel_idx) * state_stride + tap;++ state_out[state_idx] = padded[padded_offset];+ }}template <typename T>@@ -122,96 +125,97 @@ kernel void short_conv_decode_kernel(constant const uint& model_dim [[buffer(10)]],uint2 grid_idx [[thread_position_in_grid]]) {- const uint token_idx = grid_idx.x;- const uint channel_idx = grid_idx.y;+ const uint token_idx = grid_idx.x;+ const uint channel_idx = grid_idx.y;- if (channel_idx >= model_dim || token_idx >= suffix_len) {- return;- }+ if (channel_idx >= model_dim || token_idx >= suffix_len) {+ return;+ }- const int tap_count = max(kernel_size - 1, 0);- const size_t state_offset = size_t(channel_idx) * state_stride;- const device T* w_row = w + size_t(channel_idx) * size_t(kernel_size);- const bool has_bias = b != nullptr;+ const int tap_count = max(kernel_size - 1, 0);+ const size_t state_offset = size_t(channel_idx) * state_stride;+ const device T* w_row = w + size_t(channel_idx) * size_t(kernel_size);+ const bool has_bias = b != nullptr;- size_t in_proj_idx = size_t(token_idx) * in_proj_stride + size_t(channel_idx);- float pre_conv_gate = float(in_proj[in_proj_idx]);- float post_conv_gate = float(in_proj[in_proj_idx + model_dim]);- float x_in = float(in_proj[in_proj_idx + 2 * model_dim]);+ size_t in_proj_idx = size_t(token_idx) * in_proj_stride + size_t(channel_idx);+ float pre_conv_gate = float(in_proj[in_proj_idx]);+ float post_conv_gate = float(in_proj[in_proj_idx + model_dim]);+ float x_in = float(in_proj[in_proj_idx + 2 * model_dim]);- float x = x_in * pre_conv_gate;+ float x = x_in * pre_conv_gate;- float acc = has_bias ? float(b[channel_idx]) : 0.0f;+ float acc = has_bias ? float(b[channel_idx]) : 0.0f;- for (int tap = 0; tap < tap_count; ++tap) {- float sample = float(state[state_offset + size_t(tap)]);- acc += float(w_row[tap]) * sample;- }+ for (int tap = 0; tap < tap_count; ++tap) {+ float sample = float(state[state_offset + size_t(tap)]);+ acc += float(w_row[tap]) * sample;+ }- acc += float(w_row[tap_count]) * x;+ acc += float(w_row[tap_count]) * x;- float gated_output = acc * post_conv_gate;+ float gated_output = acc * post_conv_gate;- size_t out_idx = size_t(token_idx) * model_dim + size_t(channel_idx);- out[out_idx] = static_cast<T>(gated_output);+ size_t out_idx = size_t(token_idx) * model_dim + size_t(channel_idx);+ out[out_idx] = static_cast<T>(gated_output);- if (tap_count > 0) {- for (int tap = 0; tap < tap_count - 1; ++tap) {- next_state[state_offset + size_t(tap)] = state[state_offset + size_t(tap + 1)];- }- next_state[state_offset + size_t(tap_count - 1)] = static_cast<T>(x);+ if (tap_count > 0) {+ for (int tap = 0; tap < tap_count - 1; ++tap) {+ next_state[state_offset + size_t(tap)] =+ state[state_offset + size_t(tap + 1)];}+ next_state[state_offset + size_t(tap_count - 1)] = static_cast<T>(x);+ }}// ============================================================================// Template instantiations// ============================================================================#define instantiate_short_conv_pack_kernel(type_name, type) \- template [[host_name("short_conv_pack_kernel_" #type_name)]] \- kernel void short_conv_pack_kernel<type>( \- device const type* state_in [[buffer(0)]], \- device const type* in_proj [[buffer(1)]], \- device type* padded [[buffer(2)]], \- constant const size_t& state_stride [[buffer(3)]], \- constant const size_t& suffix_len [[buffer(4)]], \- constant const size_t& in_proj_stride [[buffer(5)]], \- constant const uint& model_dim [[buffer(6)]], \- uint2 grid_idx [[thread_position_in_grid]] \- );+ template [[host_name("short_conv_pack_kernel_" #type_name)]] \+ kernel void short_conv_pack_kernel<type>( \+ device const type* state_in [[buffer(0)]], \+ device const type* in_proj [[buffer(1)]], \+ device type* padded [[buffer(2)]], \+ constant const size_t& state_stride [[buffer(3)]], \+ constant const size_t& suffix_len [[buffer(4)]], \+ constant const size_t& in_proj_stride [[buffer(5)]], \+ constant const uint& model_dim [[buffer(6)]], \+ uint2 grid_idx [[thread_position_in_grid]] \+ );#define instantiate_short_conv_prefill_kernel(type_name, type) \- template [[host_name("short_conv_prefill_kernel_" #type_name)]] \- kernel void short_conv_prefill_kernel<type>( \- device const type* padded [[buffer(0)]], \- device const type* in_proj [[buffer(1)]], \- device const type* w [[buffer(2)]], \- device const type* b [[buffer(3)]], \- device type* out [[buffer(4)]], \- device type* state_out [[buffer(5)]], \- constant const size_t& suffix_len [[buffer(6)]], \- constant const int& kernel_size [[buffer(7)]], \- constant const size_t& in_proj_stride [[buffer(8)]], \- constant const size_t& state_stride [[buffer(9)]], \- constant const uint& model_dim [[buffer(10)]], \- uint2 grid_idx [[thread_position_in_grid]] \- );+ template [[host_name("short_conv_prefill_kernel_" #type_name)]] \+ kernel void short_conv_prefill_kernel<type>( \+ device const type* padded [[buffer(0)]], \+ device const type* in_proj [[buffer(1)]], \+ device const type* w [[buffer(2)]], \+ device const type* b [[buffer(3)]], \+ device type* out [[buffer(4)]], \+ device type* state_out [[buffer(5)]], \+ constant const size_t& suffix_len [[buffer(6)]], \+ constant const int& kernel_size [[buffer(7)]], \+ constant const size_t& in_proj_stride [[buffer(8)]], \+ constant const size_t& state_stride [[buffer(9)]], \+ constant const uint& model_dim [[buffer(10)]], \+ uint2 grid_idx [[thread_position_in_grid]] \+ );#define instantiate_short_conv_decode_kernel(type_name, type) \- template [[host_name("short_conv_decode_kernel_" #type_name)]] \- kernel void short_conv_decode_kernel<type>( \- device const type* x [[buffer(0)]], \- device const type* w [[buffer(1)]], \- device const type* b [[buffer(2)]], \- device const type* state [[buffer(3)]], \- device type* out [[buffer(4)]], \- device type* next_state [[buffer(5)]], \- constant const size_t& suffix_len [[buffer(6)]], \- constant const int& kernel_size [[buffer(7)]], \- constant const size_t& row_stride [[buffer(8)]], \- constant const size_t& state_stride [[buffer(9)]], \- constant const uint& num_channels [[buffer(10)]], \- uint2 grid_idx [[thread_position_in_grid]] \- );+ template [[host_name("short_conv_decode_kernel_" #type_name)]] \+ kernel void short_conv_decode_kernel<type>( \+ device const type* x [[buffer(0)]], \+ device const type* w [[buffer(1)]], \+ device const type* b [[buffer(2)]], \+ device const type* state [[buffer(3)]], \+ device type* out [[buffer(4)]], \+ device type* next_state [[buffer(5)]], \+ constant const size_t& suffix_len [[buffer(6)]], \+ constant const int& kernel_size [[buffer(7)]], \+ constant const size_t& row_stride [[buffer(8)]], \+ constant const size_t& state_stride [[buffer(9)]], \+ constant const uint& num_channels [[buffer(10)]], \+ uint2 grid_idx [[thread_position_in_grid]] \+ );instantiate_short_conv_pack_kernel(float, float);instantiate_short_conv_pack_kernel(bfloat, bfloat);