A high-performance inference engine for AI models
Support Trellis GEMM for preM5 chips (#900)
CCYeh6d06d36a68b3
diff --git a/crates/uzu-engine/src/backends/metal/gpu_types/gemm.rs b/crates/uzu-engine/src/backends/metal/gpu_types/gemm.rsindex 8b536d3e4..55bca59a2 100644--- a/crates/uzu-engine/src/backends/metal/gpu_types/gemm.rs+++ b/crates/uzu-engine/src/backends/metal/gpu_types/gemm.rs@@ -34,6 +34,7 @@ pub enum GemmTiling {Tile128x128x256_Simdgroups4x4,Tile8x32x64_Simdgroups1x2x4,Tile8x32x128_Simdgroups1x2x4,+ Tile16x32x32_Simdgroups2x1,}pub const MXU_SIMDGROUP_BLOCK_K: u32 = 32;@@ -57,6 +58,7 @@ impl GemmTiling {Self::Tile64x64x256_Simdgroups2x2 => 64,Self::Tile128x128x256_Simdgroups4x4 => 128,Self::Tile8x32x64_Simdgroups1x2x4 | Self::Tile8x32x128_Simdgroups1x2x4 => 8,+ Self::Tile16x32x32_Simdgroups2x1 => 16,}}@@ -74,6 +76,7 @@ impl GemmTiling {Self::Tile64x64x256_Simdgroups2x2 => 64,Self::Tile128x128x256_Simdgroups4x4 => 128,Self::Tile8x32x64_Simdgroups1x2x4 | Self::Tile8x32x128_Simdgroups1x2x4 => 32,+ Self::Tile16x32x32_Simdgroups2x1 => 32,}}@@ -92,6 +95,7 @@ impl GemmTiling {Self::Tile128x128x256_Simdgroups4x4 => 256,Self::Tile8x32x64_Simdgroups1x2x4 => 64,Self::Tile8x32x128_Simdgroups1x2x4 => 128,+ Self::Tile16x32x32_Simdgroups2x1 => 32,}}@@ -109,6 +113,7 @@ impl GemmTiling {Self::Tile64x64x256_Simdgroups2x2 => 2,Self::Tile128x128x256_Simdgroups4x4 => 4,Self::Tile8x32x64_Simdgroups1x2x4 | Self::Tile8x32x128_Simdgroups1x2x4 => 1,+ Self::Tile16x32x32_Simdgroups2x1 => 2,}}@@ -126,6 +131,7 @@ impl GemmTiling {Self::Tile64x64x256_Simdgroups2x2 => 2,Self::Tile128x128x256_Simdgroups4x4 => 4,Self::Tile8x32x64_Simdgroups1x2x4 | Self::Tile8x32x128_Simdgroups1x2x4 => 2,+ Self::Tile16x32x32_Simdgroups2x1 => 1,}}diff --git a/crates/uzu-engine/src/backends/metal/kernel/generated/gemm.h b/crates/uzu-engine/src/backends/metal/kernel/generated/gemm.hindex e46959984..16b699a07 100644--- a/crates/uzu-engine/src/backends/metal/kernel/generated/gemm.h+++ b/crates/uzu-engine/src/backends/metal/kernel/generated/gemm.h@@ -51,6 +51,7 @@ enum class GemmTiling : uint32_t {Tile128x128x256_Simdgroups4x4 = 10,Tile8x32x64_Simdgroups1x2x4 = 11,Tile8x32x128_Simdgroups1x2x4 = 12,+ Tile16x32x32_Simdgroups2x1 = 13,};static constant constexpr uint32_t MXU_SIMDGROUP_BLOCK_K = 32;diff --git a/crates/uzu-engine/src/backends/metal/kernel/matmul/common/loader.h b/crates/uzu-engine/src/backends/metal/kernel/matmul/common/loader.hindex 03b8ee587..22ad3f0b1 100644--- a/crates/uzu-engine/src/backends/metal/kernel/matmul/common/loader.h+++ b/crates/uzu-engine/src/backends/metal/kernel/matmul/common/loader.h@@ -19,7 +19,8 @@ template <ushort ALIGNMENT = 1,ushort READS_PER_THREAD = (THREADGROUP_TILE_COLS * THREADGROUP_TILE_ROWS) / (THREADGROUP_SIZE),ushort THREAD_COLS = THREADGROUP_TILE_COLS / READS_PER_THREAD,- ushort THREAD_ROWS = THREADGROUP_SIZE / THREAD_COLS>+ ushort THREAD_ROWS = THREADGROUP_SIZE / THREAD_COLS,+ typename StageT = T>struct ThreadgroupLoader {const int source_leading_dimension;const int tile_stride;@@ -28,7 +29,7 @@ struct ThreadgroupLoader {const ushort tile_row_index;const ushort tile_col_index;- threadgroup T* destination;+ threadgroup StageT* destination;const device T* source;struct alignas(ALIGNMENT * sizeof(T)) ReadVector {@@ -38,7 +39,7 @@ struct ThreadgroupLoader {METAL_FUNC ThreadgroupLoader(const device T* source_ptr,const int source_leading_dim,- threadgroup T* destination_ptr,+ threadgroup StageT* destination_ptr,const thread ThreadContext& thread_context): source_leading_dimension(source_leading_dim),@@ -63,8 +64,16 @@ struct ThreadgroupLoader {METAL_FUNC void load_unsafe() const {METAL_PRAGMA_UNROLLfor (ushort i = 0; i < THREADGROUP_TILE_ROWS; i += THREAD_ROWS) {- *reinterpret_cast<threadgroup ReadVector*>(&destination[i * DESTINATION_LEADING_DIMENSION]) =- *reinterpret_cast<const device ReadVector*>(&source[i * source_leading_dimension]);+ if constexpr (is_same_v<T, StageT>) {+ *reinterpret_cast<threadgroup ReadVector*>(&destination[i * DESTINATION_LEADING_DIMENSION]) =+ *reinterpret_cast<const device ReadVector*>(&source[i * source_leading_dimension]);+ } else {+ const ReadVector values = *reinterpret_cast<const device ReadVector*>(&source[i * source_leading_dimension]);+ METAL_PRAGMA_UNROLL+ for (ushort j = 0; j < READS_PER_THREAD; j++) {+ destination[i * DESTINATION_LEADING_DIMENSION + j] = StageT(reinterpret_cast<const thread T*>(&values)[j]);+ }+ }}}diff --git a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/common/gemm_tiling.h b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/common/gemm_tiling.hindex 7c70a5186..5460dcac1 100644--- a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/common/gemm_tiling.h+++ b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/common/gemm_tiling.h@@ -19,6 +19,7 @@ constexpr uint gemm_tiling_block_m(GemmTiling t) {: t == GemmTiling::Tile128x128x256_Simdgroups4x4 ? 128: t == GemmTiling::Tile8x32x64_Simdgroups1x2x4 ? 8: t == GemmTiling::Tile8x32x128_Simdgroups1x2x4 ? 8+ : t == GemmTiling::Tile16x32x32_Simdgroups2x1 ? 16: 0;}@@ -36,6 +37,7 @@ constexpr uint gemm_tiling_block_n(GemmTiling t) {: t == GemmTiling::Tile128x128x256_Simdgroups4x4 ? 128: t == GemmTiling::Tile8x32x64_Simdgroups1x2x4 ? 32: t == GemmTiling::Tile8x32x128_Simdgroups1x2x4 ? 32+ : t == GemmTiling::Tile16x32x32_Simdgroups2x1 ? 32: 0;}@@ -53,6 +55,7 @@ constexpr uint gemm_tiling_block_k(GemmTiling t) {: t == GemmTiling::Tile128x128x256_Simdgroups4x4 ? 256: t == GemmTiling::Tile8x32x64_Simdgroups1x2x4 ? 64: t == GemmTiling::Tile8x32x128_Simdgroups1x2x4 ? 128+ : t == GemmTiling::Tile16x32x32_Simdgroups2x1 ? 32: 0;}@@ -70,6 +73,7 @@ constexpr uint gemm_tiling_simdgroups_per_row(GemmTiling t) {: t == GemmTiling::Tile128x128x256_Simdgroups4x4 ? 4: t == GemmTiling::Tile8x32x64_Simdgroups1x2x4 ? 1: t == GemmTiling::Tile8x32x128_Simdgroups1x2x4 ? 1+ : t == GemmTiling::Tile16x32x32_Simdgroups2x1 ? 2: 0;}@@ -87,6 +91,7 @@ constexpr uint gemm_tiling_simdgroups_per_column(GemmTiling t) {: t == GemmTiling::Tile128x128x256_Simdgroups4x4 ? 4: t == GemmTiling::Tile8x32x64_Simdgroups1x2x4 ? 2: t == GemmTiling::Tile8x32x128_Simdgroups1x2x4 ? 2+ : t == GemmTiling::Tile16x32x32_Simdgroups2x1 ? 1: 0;}diff --git a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/common/simdgroup_mma_core.h b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/common/simdgroup_mma_core.hindex 022ee3501..696ad443e 100644--- a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/common/simdgroup_mma_core.h+++ b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/common/simdgroup_mma_core.h@@ -88,12 +88,12 @@ struct SimdgroupMmaCore {float,uzu::matmul::TransformNone<OutputElementType, float>>;- template <uint GEMM_ALIGNMENT_RAW, typename BLoader>+ template <uint GEMM_ALIGNMENT_RAW, typename ALoaderType, typename BLoader>static METAL_FUNC void k_loop(threadgroup LeftElementType* a_shared,threadgroup RightStageType* b_shared,const int aligned_k_iterations,- thread ALoader& loader_a,+ thread ALoaderType& loader_a,thread BLoader& loader_b,thread TileAccumulator& accumulator,thread const ushort& tile_block_rows,diff --git a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/gemm_trellis.metal b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/gemm_trellis.metalindex 630898183..0134dc35e 100644--- a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/gemm_trellis.metal+++ b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/gemm_trellis.metal@@ -7,12 +7,19 @@#include "common/mxu_mma_core.h"#include "common/quantized/cursor.h"#include "common/quantized/trellis.h"+#include "common/simdgroup_mma_core.h"+#include "../common/simdgroup_fragment_ops.h"using namespace metal;using namespace uzu::gemm;#define REDUCE_THREADS 256#define REDUCE_VECTOR_WIDTH 4+// Pre-M5 stages both operands as half in threadgroup memory, each row padded by 16 bytes.+#define TRELLIS_STAGE_ELEMENTS \+ (USE_MXU ? 1 \+ : (gemm_tiling_block_m(GEMM_TILING) + gemm_tiling_block_n(GEMM_TILING)) * \+ (gemm_tiling_block_k(GEMM_TILING) + 8))namespace {@@ -36,15 +43,51 @@ struct TrellisEpilogue {}};+struct TrellisWeightLoader {+ trellis::GemmTrellisFormat format;+ const device uint8_t* codes;+ uint row_columns;+ uint column;+ uint row;+ uint block_n;+ threadgroup half* destination;+ uint block_k;++ METAL_FUNC void load_unsafe() const { load(true); }++ METAL_FUNC void load_safe(const short2 valid) const { load(row < uint(valid.y)); }++ METAL_FUNC void next() { column += block_k; }++ METAL_FUNC void load(const bool live) const {+ if (row >= block_n) {+ return;+ }+ const uint4 weights = live ? trellis::decode_biased_weight_quad(format, codes, 0, column, row_columns) : uint4(0u);+ METAL_PRAGMA_UNROLL+ for (ushort index = 0; index < 4; ++index) {+ *reinterpret_cast<threadgroup half4*>(destination + 4 * index) = half4(as_type<uchar4>(weights[index]));+ }+ }+};+} // namespace-template <GemmTiling GEMM_TILING>+template <GemmTiling GEMM_TILING, bool USE_MXU>VARIANTS(GEMM_TILING,+ GemmTiling::Tile16x32x32_Simdgroups2x1,+ GemmTiling::Tile32x32x32_Simdgroups2x2,+ GemmTiling::Tile64x64x32_Simdgroups2x2,GemmTiling::Tile16x32x256_Simdgroups1x1,GemmTiling::Tile32x64x256_Simdgroups2x2,GemmTiling::Tile64x64x256_Simdgroups2x2,GemmTiling::Tile128x128x256_Simdgroups4x4)+VARIANTS(USE_MXU, false, true)+CONSTRAINT(+ USE_MXU ==+ (GEMM_TILING == GemmTiling::Tile16x32x256_Simdgroups1x1 || GEMM_TILING == GemmTiling::Tile32x64x256_Simdgroups2x2 ||+ GEMM_TILING == GemmTiling::Tile64x64x256_Simdgroups2x2 || GEMM_TILING == GemmTiling::Tile128x128x256_Simdgroups4x4))KERNEL(GemmTrellis)(const device int8_t* activations,const device float4* column_group_sums,@@ -54,6 +97,7 @@ KERNEL(GemmTrellis)(const device float* scale_and_offsets,device bfloat* output,const constant uzu::matmul::GemmParams* params,+ threadgroup half stage[TRELLIS_STAGE_ELEMENTS],const constant uint& group_count_x,const constant uint& group_count_y,const constant uint& group_count_z,@@ -73,15 +117,15 @@ KERNEL(GemmTrellis)((void)thread_y;(void)thread_z;- using LeftOperand =- operands::LeftOperandFor<GemmAPrologueKind::Int8Symmetric, bfloat, ushort(trellis::K_STEP), false>;- // A stock int8 right operand, only for the tile constants of `Core`.- using RightOperand =- operands::RightOperandFor<GemmBPrologueKind::ScaleSymmetricDequant, ushort(8), ushort(trellis::K_STEP), bfloat>;- using Core = MxuMmaCore<bfloat, GEMM_TILING, true, LeftOperand, RightOperand>;- using Ops = typename Core::FragmentOps;- using Products = uzu::matmul::Fragment<int, Core::TILES_M, Core::TILES_N, Ops>;- using RightFragment = uzu::matmul::Fragment<int8_t, Core::TILES_N, Core::TILES_K, Ops, uzu::matmul::ReadDirect, true>;+ using Ops = metal::conditional_t<USE_MXU, uzu::matmul::MxuFragmentOps<>, uzu::matmul::SimdgroupFragmentOps>;+ constexpr ushort BLOCK_M = gemm_tiling_block_m(GEMM_TILING);+ constexpr ushort BLOCK_N = gemm_tiling_block_n(GEMM_TILING);+ constexpr ushort SIMDGROUPS_PER_COLUMN = gemm_tiling_simdgroups_per_column(GEMM_TILING);+ constexpr ushort SIMDGROUP_BLOCK_M = BLOCK_M / gemm_tiling_simdgroups_per_row(GEMM_TILING);+ constexpr ushort SIMDGROUP_BLOCK_N = BLOCK_N / SIMDGROUPS_PER_COLUMN;+ constexpr ushort TILES_M = SIMDGROUP_BLOCK_M / Ops::FRAGMENT_ROWS;+ constexpr ushort TILES_N = SIMDGROUP_BLOCK_N / Ops::FRAGMENT_COLS;+ using Products = uzu::matmul::Fragment<int, TILES_M, TILES_N, Ops>;const trellis::GemmTrellisFormat trellis_format{trellis_vector_width,trellis_transition_bits,@@ -89,73 +133,141 @@ KERNEL(GemmTrellis)(};const uint simdgroup = thread_context.simdgroup_index;- const uint token_base =- group_y * Core::THREADGROUP_BLOCK_M + Core::SIMDGROUP_BLOCK_M * (simdgroup / Core::SIMDGROUPS_PER_COLUMN);- const uint row_base =- group_x * Core::THREADGROUP_BLOCK_N + Core::SIMDGROUP_BLOCK_N * (simdgroup % Core::SIMDGROUPS_PER_COLUMN);- const short token_end = short(min(int(Core::SIMDGROUP_BLOCK_M), int(params->M) - int(token_base)));- const short row_end = short(min(int(Core::SIMDGROUP_BLOCK_N), int(params->N) - int(row_base)));- const schedules::TileContext tile_context{- .simdgroup_limit_m = token_end,- .simdgroup_limit_n = row_end,- .k_offset = group_z * params->aligned_inner_iterations * trellis::K_STEP,- .abs_row_base = token_base,- };+ const uint token_base = group_y * BLOCK_M + SIMDGROUP_BLOCK_M * (simdgroup / SIMDGROUPS_PER_COLUMN);+ const uint row_base = group_x * BLOCK_N + SIMDGROUP_BLOCK_N * (simdgroup % SIMDGROUPS_PER_COLUMN);+ const short token_end = short(min(int(SIMDGROUP_BLOCK_M), int(params->M) - int(token_base)));+ const short row_end = short(min(int(SIMDGROUP_BLOCK_N), int(params->N) - int(row_base)));+ const uint k_offset = group_z * params->aligned_inner_iterations * trellis::K_STEP;const uint code_row_bytes = trellis::row_bytes(trellis_format, params->K);const short2 position = Ops::get_position(thread_context.simd_lane_id);Products products;products.clear();- // Each lane decodes 16 consecutive K columns: chunk 0 takes columns 0..7, chunk 1 takes 8..15- using LeftFragment = uzu::matmul::Fragment<int8_t, Core::TILES_M, Core::TILES_K, Ops>;- const uint lane_column = 4 * uint(position.x);- const uint k_steps = token_end > 0 && row_end > 0 ? params->aligned_inner_iterations : 0;- const device int8_t* lane_activations = activations + size_t(token_base + position.y) * params->leading_dimension_a;- // Rows past M re-read the last row; the store drops them- const bool aligned_m = alignment.contains(GemmAlignment::M);- const device int8_t* tile_activations = activations + size_t(token_base) * params->leading_dimension_a;- const short last_tile_row = token_end - 1;- const uint lane_row_byte = (row_base + position.y) * code_row_bytes;- uzu::dispatch_bool(alignment.contains(GemmAlignment::N) || row_end == Core::SIMDGROUP_BLOCK_N, [&](auto aligned_n) {- METAL_PRAGMA_NO_UNROLL- for (uint step = 0; step < k_steps; ++step) {- const uint k = tile_context.k_offset + step * trellis::K_STEP + lane_column;- LeftFragment left[2];- RightFragment right[2];- quantized::for_each_fragment_row<LeftFragment>([&](ushort fragment_row, ushort row_slot, short row_offset) {- const device int8_t* row = aligned_m ? lane_activations + row_offset * params->leading_dimension_a- : tile_activations + min(short(position.y + row_offset), last_tile_row) *- params->leading_dimension_a;- const uint4 values = *reinterpret_cast<const device uint4*>(row + k);- METAL_PRAGMA_UNROLL- for (uint index = 0; index < 4; ++index) {- reinterpret_cast<thread uint*>(&left[index / 2].fragment_at(fragment_row, index % 2))[row_slot] =- values[index];- }- });- quantized::for_each_fragment_row<RightFragment>([&](ushort fragment_row, ushort row_slot, short row_offset) {- const bool live = aligned_n.value || position.y + row_offset < row_end;- const uint4 weights = live ? trellis::decode_biased_weight_quad(- trellis_format,- codes,- lane_row_byte + row_offset * code_row_bytes,- k,- params->K- )- : uint4(0u);+ if constexpr (USE_MXU) {+ constexpr ushort TILES_K = MXU_SIMDGROUP_BLOCK_K / Ops::FRAGMENT_ROWS;+ using RightFragment = uzu::matmul::Fragment<int8_t, TILES_N, TILES_K, Ops, uzu::matmul::ReadDirect, true>;+ // Each lane decodes 16 consecutive K columns: chunk 0 takes columns 0..7, chunk 1 takes 8..15+ using LeftFragment = uzu::matmul::Fragment<int8_t, TILES_M, TILES_K, Ops>;+ const uint k_steps = token_end > 0 && row_end > 0 ? params->aligned_inner_iterations : 0;+ const device int8_t* lane_activations = activations + size_t(token_base + position.y) * params->leading_dimension_a;+ // Rows past M re-read the last row; the store drops them+ const bool aligned_m = alignment.contains(GemmAlignment::M);+ const device int8_t* tile_activations = activations + size_t(token_base) * params->leading_dimension_a;+ const short last_tile_row = token_end - 1;+ const uint lane_row_byte = (row_base + position.y) * code_row_bytes;+ const auto fill = [](thread auto& fragments, ushort fragment_row, ushort row_slot, const uint4 values) {+ METAL_PRAGMA_UNROLL+ for (uint index = 0; index < 4; ++index) {+ reinterpret_cast<thread uint*>(&fragments[index / 2].fragment_at(fragment_row, index % 2))[row_slot] =+ values[index];+ }+ };+ uzu::dispatch_bool(alignment.contains(GemmAlignment::N) || row_end == SIMDGROUP_BLOCK_N, [&](auto aligned_n) {+ METAL_PRAGMA_NO_UNROLL+ for (uint step = 0; step < k_steps; ++step) {+ const uint k = k_offset + step * trellis::K_STEP + 4 * uint(position.x);+ LeftFragment left[2];+ RightFragment right[2];+ quantized::for_each_fragment_row<LeftFragment>([&](ushort fragment_row, ushort row_slot, short row_offset) {+ const device int8_t* row = aligned_m ? lane_activations + row_offset * params->leading_dimension_a+ : tile_activations + min(short(position.y + row_offset), last_tile_row) *+ params->leading_dimension_a;+ fill(left, fragment_row, row_slot, *reinterpret_cast<const device uint4*>(row + k));+ });+ quantized::for_each_fragment_row<RightFragment>([&](ushort fragment_row, ushort row_slot, short row_offset) {+ const bool live = aligned_n.value || position.y + row_offset < row_end;+ const uint4 weights = live ? trellis::decode_biased_weight_quad(+ trellis_format,+ codes,+ lane_row_byte + row_offset * code_row_bytes,+ k,+ params->K+ )+ : uint4(0u);+ fill(right, fragment_row, row_slot, weights);+ });METAL_PRAGMA_UNROLL- for (uint index = 0; index < 4; ++index) {- reinterpret_cast<thread uint*>(&right[index / 2].fragment_at(fragment_row, index % 2))[row_slot] =- weights[index];+ for (uint chunk = 0; chunk < 2; ++chunk) {+ uzu::matmul::fragment_mma(products, left[chunk], right[chunk]);}- });- METAL_PRAGMA_UNROLL- for (uint chunk = 0; chunk < 2; ++chunk) {- uzu::matmul::fragment_mma(products, left[chunk], right[chunk]);}- }- });+ });+ } else {+ using LeftOperand = operands::LeftOperandFor<GemmAPrologueKind::FullPrecision, half, ushort(0), false>;+ using RightOperand = operands::RightOperandFor<GemmBPrologueKind::FullPrecision, ushort(0), ushort(0), half>;+ using Core = SimdgroupMmaCore<float, GEMM_TILING, true, LeftOperand, RightOperand>;+ constexpr ushort BLOCK_K = Core::THREADGROUP_BLOCK_K;+ constexpr ushort A_READS = BLOCK_M * BLOCK_K / Core::THREADGROUP_THREADS;+ constexpr ushort A_COLS = BLOCK_K / A_READS;+ constexpr uint SLAB_ITERATIONS = 1024 / BLOCK_K;+ static_assert(SLAB_ITERATIONS * BLOCK_K * 128 * 111 < (1 << 24), "a slab must sum exactly in float");+ using ALoader = uzu::matmul::ThreadgroupLoader<+ int8_t,+ BLOCK_M,+ BLOCK_K,+ Core::SHARED_STRIDE_A,+ true,+ Core::THREADGROUP_THREADS,+ 8,+ A_READS,+ A_COLS,+ Core::THREADGROUP_THREADS / A_COLS,+ half>;+ const uint block_row = group_y * BLOCK_M;+ const uint block_col = group_x * BLOCK_N;+ const ushort tile_block_rows = ushort(min(uint(BLOCK_M), params->M - block_row));+ const ushort tile_block_cols = ushort(min(uint(BLOCK_N), params->N - block_col));+ const ushort leftover_block_depth = 0;+ threadgroup half* a_shared = stage;+ threadgroup half* b_shared = stage + BLOCK_M * Core::SHARED_STRIDE_A;+ ALoader a_loader(+ activations + size_t(block_row) * params->leading_dimension_a + k_offset,+ params->leading_dimension_a,+ a_shared,+ thread_context+ );+ // One decode pass covers the tile: every thread owns a 16-column window of one weight row+ constexpr ushort B_WINDOWS = BLOCK_K / trellis::LANE_COLUMNS;+ static_assert(Core::THREADGROUP_THREADS / B_WINDOWS >= BLOCK_N, "one decode pass covers the tile");+ const ushort thread_index = simdgroup * METAL_SIMD_SIZE + thread_context.simd_lane_id;+ const uint b_row = thread_index / B_WINDOWS;+ const uint b_window = thread_index % B_WINDOWS * trellis::LANE_COLUMNS;+ TrellisWeightLoader b_loader{+ trellis_format,+ codes + size_t(block_col + b_row) * code_row_bytes,+ params->K,+ k_offset + b_window,+ b_row,+ BLOCK_N,+ b_shared + b_row * Core::SHARED_STRIDE_B + b_window,+ BLOCK_K+ };+ typename Core::TileAccumulator slab(thread_context);+ const uint iterations = params->aligned_inner_iterations * (trellis::K_STEP / BLOCK_K);+ dispatch_gemm_alignment(alignment.raw_value | uint(GemmAlignment::K), [&](auto gemm_alignment_mask) {+ for (uint done = 0; done < iterations; done += SLAB_ITERATIONS) {+ slab.c_fragment.clear();+ Core::template k_loop<gemm_alignment_mask.value>(+ a_shared,+ b_shared,+ int(min(SLAB_ITERATIONS, iterations - done)),+ a_loader,+ b_loader,+ slab,+ tile_block_rows,+ tile_block_cols,+ leftover_block_depth+ );+ slab.c_fragment.zip_for_each_coord(+ thread_context.simd_lane_id,+ [&](short, short, thread float& sum, thread int& exact) { exact += int(sum); },+ slab.c_fragment,+ products+ );+ }+ });+ }const bool write_split_k_partials = params->aligned_inner_iterations * trellis::K_STEP < params->K;const size_t partial_sum_offset = size_t(group_z) * params->M * params->N;diff --git a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/policy.rs b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/policy.rsindex 7b5fe1b1e..b0bd39bbe 100644--- a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/policy.rs+++ b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/policy.rs@@ -25,6 +25,8 @@ const SIMDGROUP_QUANT_WIDE_BLOCK_M: u32 = 64;const SPLIT_K_TARGET_TILES_FP: u32 = 512;pub(super) const SPLIT_K_TARGET_TILES_A8: u32 = 256;+pub(super) const SPLIT_K_TARGET_TILES_TRELLIS_SIMDGROUP: u32 = 384;+pub(super) const SPLIT_K_TARGET_TILES_TRELLIS_TILE16: u32 = 768;pub(super) const SPLIT_K_TARGET_TILES_A8_TILE16X32: u32 = 4 * SPLIT_K_TARGET_TILES_A8;const SPLIT_K_TARGET_TILES_A8_TILE16X32_K_SPLIT: u32 = 2 * SPLIT_K_TARGET_TILES_A8;pub(super) const SPLIT_K_TARGET_TILES_A8_TILE32_W4: u32 = 512;diff --git a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/selection.rs b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/selection.rsindex 0e0958b1b..157747cad 100644--- a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/selection.rs+++ b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/selection.rs@@ -88,14 +88,14 @@ impl GemmProblem {}pub fn select_plan(self) -> GemmPlan {- if self.shape.b_is_trellis {- return select_trellis_plan(self.shape.m, self.shape.n, self.shape.k);- }let engine = if self.supports_mxu && mxu_is_eligible(self.shape) {GemmEngine::Mxu} else {GemmEngine::Simdgroup};+ if self.shape.b_is_trellis {+ return select_trellis_plan(self.shape.m, self.shape.n, self.shape.k, engine);+ }self.finish_plan(engine, select_tiling(self.shape, engine))}@@ -122,9 +122,7 @@ impl GemmProblem {engine: GemmEngine,) -> Result<GemmPlan, GemmPlanError> {if self.shape.b_is_trellis {- let mut plan = select_trellis_plan(self.shape.m, self.shape.n, self.shape.k);- plan.engine = engine;- return Ok(plan);+ return Ok(select_trellis_plan(self.shape.m, self.shape.n, self.shape.k, engine));}self.validate_engine(engine)?;Ok(self.finish_plan(engine, select_tiling(self.shape, engine)))@@ -204,33 +202,42 @@ fn select_trellis_plan(m: u32,n: u32,k: u32,+ engine: GemmEngine,) -> GemmPlan {- // The M16 wide finalist favored a 32x64 tile and a 256-workgroup target.- let (tiling, target_workgroups) =- if m == 16 && n >= 4096 && (2048..=5120).contains(&k) && k.is_multiple_of(TRELLIS_K_STEP) {+ let (tiling, target_workgroups) = match engine {+ GemmEngine::Simdgroup if m <= 16 => {+ (GemmTiling::Tile16x32x32_Simdgroups2x1, policy::SPLIT_K_TARGET_TILES_TRELLIS_TILE16)+ },+ GemmEngine::Simdgroup => (policy::simdgroup_quant_tile(m), policy::SPLIT_K_TARGET_TILES_TRELLIS_SIMDGROUP),+ // The M16 wide finalist favored a 32x64 tile and a 256-workgroup target.+ GemmEngine::Mxu if m == 16 && n >= 4096 && (2048..=5120).contains(&k) && k.is_multiple_of(TRELLIS_K_STEP) => {(GemmTiling::Tile32x64x256_Simdgroups2x2, 256)- } else {- match policy::mxu_mn_tile(true, m, n) {- GemmTiling::Tile16x32x256_Simdgroups1x1 => {- (GemmTiling::Tile16x32x256_Simdgroups1x1, policy::SPLIT_K_TARGET_TILES_A8_TILE16X32)- },- GemmTiling::Tile32x64x256_Simdgroups2x2 => {- (GemmTiling::Tile64x64x256_Simdgroups2x2, policy::SPLIT_K_TARGET_TILES_A8_TILE32_W4)- },- GemmTiling::Tile128x128x256_Simdgroups4x4 => {- (GemmTiling::Tile128x128x256_Simdgroups4x4, policy::SPLIT_K_TARGET_TILES_A8)- },- _ => (GemmTiling::Tile64x64x256_Simdgroups2x2, policy::SPLIT_K_TARGET_TILES_A8),- }- };+ },+ GemmEngine::Mxu => match policy::mxu_mn_tile(true, m, n) {+ GemmTiling::Tile16x32x256_Simdgroups1x1 => {+ (GemmTiling::Tile16x32x256_Simdgroups1x1, policy::SPLIT_K_TARGET_TILES_A8_TILE16X32)+ },+ GemmTiling::Tile32x64x256_Simdgroups2x2 => {+ (GemmTiling::Tile64x64x256_Simdgroups2x2, policy::SPLIT_K_TARGET_TILES_A8_TILE32_W4)+ },+ GemmTiling::Tile128x128x256_Simdgroups4x4 => {+ (GemmTiling::Tile128x128x256_Simdgroups4x4, policy::SPLIT_K_TARGET_TILES_A8)+ },+ _ => (GemmTiling::Tile64x64x256_Simdgroups2x2, policy::SPLIT_K_TARGET_TILES_A8),+ },+ };let output_workgroups = (n.div_ceil(tiling.block_n()) * m.div_ceil(tiling.block_m())).max(1);let k_steps = (k / TRELLIS_K_STEP).max(1);let mut split_k = (target_workgroups / output_workgroups).clamp(1, k_steps);+ // The split-K reduce reads four partial sums at a time.+ if !n.is_multiple_of(4) {+ split_k = 1;+ }while !k_steps.is_multiple_of(split_k) {split_k -= 1;}GemmPlan {- engine: GemmEngine::Mxu,+ engine,tiling,split_k,}diff --git a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/trellis.rs b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/trellis.rsindex 6b6fa5333..d536dee8f 100644--- a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/trellis.rs+++ b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/trellis.rs@@ -64,8 +64,7 @@ impl TrellisGemm {let (m, n, k) = (arguments.m, arguments.n, arguments.k);let output_stride = arguments.output.row_stride.unwrap_or(n);let (tiling, split_k) = (plan.tiling, plan.split_k);- if plan.engine != GemmEngine::Mxu- || !arguments.output.ops.mask().is_empty()+ if !arguments.output.ops.mask().is_empty()|| !arguments.b_transpose|| arguments.b_leading_dimension.is_some()|| output_stride < n@@ -94,6 +93,7 @@ impl TrellisGemm {Entry::Vacant(entry) => entry.insert(GemmTrellisMetalKernel::new(command_buffer.context(),tiling,+ plan.engine == GemmEngine::Mxu,alignment,format.vector_width,format.transition_bits,diff --git a/crates/uzu-engine/unit/backends/metal/kernel/matmul/trellis_gemm_test.rs b/crates/uzu-engine/unit/backends/metal/kernel/matmul/trellis_gemm_test.rsindex eac7a88d8..f1f9d56ba 100644--- a/crates/uzu-engine/unit/backends/metal/kernel/matmul/trellis_gemm_test.rs+++ b/crates/uzu-engine/unit/backends/metal/kernel/matmul/trellis_gemm_test.rs@@ -181,7 +181,12 @@ fn run_projection(if let Some((tiling, split_k)) = forced_plan {let shape = MatmulShape::from_arguments(&arguments);let mut gemm = GemmKernel::new(DataType::BF16, DataType::BF16, DataType::BF16);- let mut plan = gemm.select_plan_for_engine(&shape, GemmEngine::Mxu, context).unwrap();+ let engine = if tiling.is_mxu_variant() {+ GemmEngine::Mxu+ } else {+ GemmEngine::Simdgroup+ };+ let mut plan = gemm.select_plan_for_engine(&shape, engine, context).unwrap();plan.tiling = tiling;plan.split_k = split_k;let output_work = MatmulOutputWork::new(context, DataType::BF16, DataType::BF16).unwrap();@@ -233,20 +238,21 @@ fn run_projection(#[case::v4_t8_no_restart(V4_T8_NO_RESTART)]fn trellis_projection_matches_cpu_reference(#[case] format: TrellisFormat) {let context = shared_metal_context();- if !context.supports_mxu {- return;- }// A projection's K is a whole number of restart blocks.let whole_blocks = |k: usize| k.is_multiple_of(format.restart_columns.unwrap_or(1) as usize);for dimensions in CASES.into_iter().filter(|&(_, _, k)| whole_blocks(k)) {run_projection(&context, format, dimensions, None);}// The forced plans' K are whole 64-column blocks.- if whole_blocks(64) {+ if whole_blocks(64) && context.supports_mxu {run_projection(&context, format, (129, 132, 1024), Some((GemmTiling::Tile128x128x256_Simdgroups4x4, 1)));run_projection(&context, format, (129, 132, 64), Some((GemmTiling::Tile128x128x256_Simdgroups4x4, 1)));run_projection(&context, format, (17, 80, 192), Some((GemmTiling::Tile32x64x256_Simdgroups2x2, 1)));run_projection(&context, format, (17, 80, 192), Some((GemmTiling::Tile16x32x256_Simdgroups1x1, 1)));run_projection(&context, format, (7, 80, 192), Some((GemmTiling::Tile16x32x256_Simdgroups1x1, 1)));+ } else if whole_blocks(64) {+ run_projection(&context, format, (7, 68, 6144), Some((GemmTiling::Tile16x32x32_Simdgroups2x1, 4)));+ run_projection(&context, format, (33, 68, 6144), Some((GemmTiling::Tile32x32x32_Simdgroups2x2, 4)));+ run_projection(&context, format, (65, 68, 6144), Some((GemmTiling::Tile64x64x32_Simdgroups2x2, 4)));}}