Skip to content

armgit / uzu

Public Imported from GitHub
0

A high-performance inference engine for AI models

Decode all trellis formats from one reversed little-endian tape (#1004)

CCYeh333c5f2b6125
diff --git a/crates/uzu-engine/src/backends/common/kernel/matmul/matmul_b.rs b/crates/uzu-engine/src/backends/common/kernel/matmul/matmul_b.rs
index f0519ce3e..adf77560c 100644
--- a/crates/uzu-engine/src/backends/common/kernel/matmul/matmul_b.rs
+++ b/crates/uzu-engine/src/backends/common/kernel/matmul/matmul_b.rs
@@ -14,6 +14,27 @@ pub struct TrellisFormat {
pub restart_columns: Option<u32>,
}
+/// Readable bytes past the last code row (the GEMM loads whole words).
+#[cfg(backend = "metal")]
+pub const TRELLIS_CODES_TAIL_BYTES: usize = 16;
+
+impl TrellisFormat {
+ /// Bytes per code row: restart rows pad to 16 bytes, connected rows to a byte.
+ pub fn code_row_bytes(
+ self,
+ columns: u32,
+ ) -> u32 {
+ let block_columns = self.restart_columns.unwrap_or(columns);
+ let block_bits = 16 + (block_columns / self.vector_width - 1) * self.transition_bits;
+ let bytes = (columns / block_columns * block_bits).div_ceil(8);
+ if self.restart_columns.is_some() {
+ bytes.next_multiple_of(16)
+ } else {
+ bytes
+ }
+ }
+}
+
pub enum MatmulB<TB: BufferRef> {
FullPrecision {
b: TB,
diff --git a/crates/uzu-engine/src/backends/common/kernel/matmul/mod.rs b/crates/uzu-engine/src/backends/common/kernel/matmul/mod.rs
index 7d2640125..84df3422b 100644
--- a/crates/uzu-engine/src/backends/common/kernel/matmul/mod.rs
+++ b/crates/uzu-engine/src/backends/common/kernel/matmul/mod.rs
@@ -10,9 +10,9 @@ pub use arguments::MatmulArguments;
pub use d_ops::MatmulDOps;
pub use kernel::MatmulKernel;
pub use matmul_a::{Int8CodeLayout, MatmulA};
-#[cfg(backend = "metal")]
-pub use matmul_b::TrellisFormat;
pub use matmul_b::{MatmulB, QuantizedB, QuantizedCorrection};
+#[cfg(backend = "metal")]
+pub use matmul_b::{TRELLIS_CODES_TAIL_BYTES, TrellisFormat};
pub use output::{MatmulOutput, MatmulOutputError};
pub use routing::{ActivationFormat, MatmulShape};
diff --git a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/common/quantized/trellis.h b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/common/quantized/trellis.h
index 443f847e6..f027c62a2 100644
--- a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/common/quantized/trellis.h
+++ b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/common/quantized/trellis.h
@@ -4,7 +4,6 @@
#include "../../../../common/defines.h"
#include "../../../../generated/gemm.h"
-#include "cursor.h"
using namespace metal;
@@ -20,7 +19,7 @@ struct GemmTrellisFormat {
};
UZU_CONST uint K_STEP = 64, WEIGHT_BIAS = 54;
-UZU_CONST uint STATE_BITS = 16, BYTE_BITS = 8, V4_VECTOR_WIDTH = 4, V2T6_TRANSITION_BITS = 6;
+UZU_CONST uint STATE_BITS = 16, BYTE_BITS = 8, WORD_BYTES = 4, WORD_BITS = 32, LANE_COLUMNS = 16, ROW_ALIGNMENT = 16;
UZU_CONST uint HASH_MULTIPLIER = 0xCFCCB83Fu, HASH_INCREMENT = 0x584B4AA3u;
UZU_CONST uint HASH_AVALANCHE_MULTIPLIER = 0x85EBCA6Bu, HASH_FOLD_BITS = 16;
@@ -29,40 +28,52 @@ UZU_CONST uint TWO_BIT_FIELD_SHIFT = 2, NIBBLE_SHIFT = 4, FIELD_SUM_SHIFT = 3;
UZU_CONST uint TWO_BIT_FIELDS_MASK = 0x33333333u, BYTE_NIBBLES_MASK = 0x0F0F0F0Fu;
UZU_CONST uint FIELD_PAIR_SUM_MULTIPLIER = 3, DITHER_MULTIPLIER = 3;
-// Row layout
-static METAL_FUNC uint block_bytes(const GemmTrellisFormat format, const uint block_columns) {
+// Row layout: restart rows pad to ROW_ALIGNMENT bytes, connected rows to a byte
+static METAL_FUNC uint block_bits(const GemmTrellisFormat format, const uint block_columns) {
const uint state_count = block_columns / format.vector_width;
const uint transition_count = state_count - 1;
- return (STATE_BITS + transition_count * format.transition_bits + BYTE_BITS - 1) / BYTE_BITS;
+ return STATE_BITS + transition_count * format.transition_bits;
}
static METAL_FUNC uint row_bytes(const GemmTrellisFormat format, const uint code_columns) {
- const uint block_columns = format.restart_columns == 0 ? code_columns : format.restart_columns;
- return code_columns / block_columns * block_bytes(format, block_columns);
+ if (format.restart_columns == 0) {
+ return (block_bits(format, code_columns) + BYTE_BITS - 1) / BYTE_BITS;
+ }
+ const uint stream_bits = code_columns / format.restart_columns * block_bits(format, format.restart_columns);
+ const uint stream_bytes = (stream_bits + BYTE_BITS - 1) / BYTE_BITS;
+ return (stream_bytes + ROW_ALIGNMENT - 1) / ROW_ALIGNMENT * ROW_ALIGNMENT;
}
-// MSB-first codes. code_column must be a multiple of 4.
-static METAL_FUNC uint2
-states_at(const GemmTrellisFormat format, const device uchar* code_row, const uint code_column) {
- if (format.vector_width == V4_VECTOR_WIDTH) {
- const device uchar* block_codes = code_row;
- uint block_column = code_column;
- if (format.restart_columns != 0) {
- block_codes += code_column / format.restart_columns * block_bytes(format, format.restart_columns);
- block_column %= format.restart_columns;
- }
- const device uchar* state_bytes = block_codes + block_column / V4_VECTOR_WIDTH;
- return uint2(uint(state_bytes[0]) << BYTE_BITS | state_bytes[1], 0);
+// Tape 2: each block's bits reversed, LSB first; state i is the LE 16-bit field at bit B - 16 - i*T
+static METAL_FUNC uint states_per_lane(const GemmTrellisFormat format) { return LANE_COLUMNS / format.vector_width; }
+
+static METAL_FUNC uint states_per_window(const GemmTrellisFormat format) {
+ const uint block_states = format.restart_columns / format.vector_width;
+ return format.restart_columns == 0 ? states_per_lane(format) : min(states_per_lane(format), 1u << ctz(block_states));
+}
+
+static METAL_FUNC uint window_bits(const GemmTrellisFormat format) {
+ return STATE_BITS + (states_per_window(format) - 1) * format.transition_bits;
+}
+
+// Window starts are multiples of a power of two bits, at least a byte (row starts are only byte aligned)
+static METAL_FUNC uint max_window_bit_offset(const GemmTrellisFormat format) {
+ const uint spacing = states_per_window(format) * format.transition_bits;
+ uint unit = spacing;
+ if (format.restart_columns != 0) {
+ unit |= block_bits(format, format.restart_columns) | (spacing - format.transition_bits);
}
- const uint first_bit = code_column / format.vector_width * format.transition_bits;
- const device uchar* bytes = code_row + first_bit / BYTE_BITS;
- const uint shift = first_bit % BYTE_BITS;
- const uint fourth_byte = format.transition_bits == V2T6_TRANSITION_BITS ? uint(bytes[3]) : 0;
- const uint window = uint(bytes[0]) << 24 | uint(bytes[1]) << 16 | uint(bytes[2]) << 8 | fourth_byte;
- const uint state_mask = (1u << STATE_BITS) - 1;
- const uint first_state = (window >> (16 - shift)) & state_mask;
- const uint second_state = (window >> (16 - format.transition_bits - shift)) & state_mask;
- return uint2(first_state, second_state);
+ return WORD_BITS - min(BYTE_BITS, 1u << ctz(unit));
+}
+
+static METAL_FUNC uint state_field(const uint word0, const uint word1, const uint word2, const uint first_bit) {
+ const uint word = first_bit / WORD_BITS, bit = first_bit % WORD_BITS;
+ const uint low = word == 0 ? word0 : (word == 1 ? word1 : word2);
+ uint value = low >> bit;
+ if (bit + STATE_BITS > WORD_BITS) {
+ value |= (word == 0 ? word1 : word2) << (WORD_BITS - bit);
+ }
+ return value & ((1u << STATE_BITS) - 1);
}
// State -> hash -> biased weights
@@ -83,58 +94,59 @@ static METAL_FUNC uint biased_weights(const uint hash_bytes) {
return (byte_field_sums << FIELD_SUM_SHIFT) + low_nibble_dither;
}
-static METAL_FUNC uint
-decode_biased_weights(const GemmTrellisFormat format, const device uchar* code_row, const uint code_column) {
- const uint2 code_states = states_at(format, code_row, code_column);
- const uint first_hash = hash_without_final_fold(code_states.x);
- if (format.vector_width == V4_VECTOR_WIDTH) {
- return biased_weights(final_fold(first_hash));
- }
- const uint second_hash = hash_without_final_fold(code_states.y);
+static METAL_FUNC uint state_pair_weights(const uint first_state, const uint second_state) {
+ const uint first_hash = hash_without_final_fold(first_state);
+ const uint second_hash = hash_without_final_fold(second_state);
const uint low_halves = insert_bits(first_hash, second_hash, HASH_FOLD_BITS, HASH_FOLD_BITS);
const uint high_halves = insert_bits(second_hash, first_hash >> HASH_FOLD_BITS, 0, HASH_FOLD_BITS);
return biased_weights(low_halves ^ high_halves);
}
-} // namespace trellis
-
-namespace quantized {
-
-template <typename Fragment, bool ALIGNED>
-struct TrellisCursor {
- using Ops = typename Fragment::FragmentOpsType;
- UZU_CONST short BLOCK_K = short(Fragment::COL_FRAGMENTS * Ops::FRAGMENT_ROWS);
-
- const device uint8_t* code_rows;
- uint code_row_stride_bytes;
- short tile_row_limit;
- short2 position;
- uint k_offset;
- trellis::GemmTrellisFormat format;
-
- METAL_FUNC Fragment load(const uint) const thread {
- const short row_limit = tile_row_limit - position.y;
- Fragment tile;
- for_each_fragment_row<Fragment>([&](ushort fragment_row, ushort row_slot, short row_offset) {
- const bool live = ALIGNED || row_offset < row_limit;
- const device uint8_t* code_row = code_rows + int(row_offset) * int(code_row_stride_bytes);
- METAL_PRAGMA_UNROLL
- for (ushort k_fragment = 0; k_fragment < Fragment::COL_FRAGMENTS; ++k_fragment) {
- reinterpret_cast<thread uint*>(&tile.fragment_at(fragment_row, k_fragment))[row_slot] =
- live ? trellis::decode_biased_weights(
- format,
- code_row,
- k_offset + uint(k_fragment * Ops::FRAGMENT_ROWS) + uint(position.x)
- )
- : 0u;
- }
- });
- return tile;
+// Biased weights of the 16 columns from code_column, four per word
+static METAL_FUNC uint4 decode_biased_weight_quad(
+ const GemmTrellisFormat format,
+ const device uchar* codes,
+ const uint row_start_byte,
+ const uint code_column,
+ const uint row_columns
+) {
+ const uint transition_bits = format.transition_bits;
+ const uint window_states = states_per_window(format);
+ const uint states_per_weight_word = WORD_BYTES / format.vector_width;
+ const uint block_columns = format.restart_columns != 0 ? format.restart_columns : row_columns;
+ const uint block_size = block_bits(format, block_columns);
+ const uint bits_in_window = window_bits(format);
+ const bool third_word_possible = max_window_bit_offset(format) + bits_in_window > 2 * WORD_BITS;
+ uint4 weights;
+ METAL_PRAGMA_UNROLL
+ for (uint window = 0; window < states_per_lane(format) / window_states; ++window) {
+ const uint column = code_column + window * window_states * format.vector_width;
+ const uint block = format.restart_columns != 0 ? column / block_columns : 0;
+ const uint state_in_block = column % block_columns / format.vector_width;
+ const uint first_bit =
+ block * block_size + block_size - STATE_BITS - (state_in_block + window_states - 1) * transition_bits;
+ const uint byte = row_start_byte + first_bit / BYTE_BITS;
+ const uint shift = byte % WORD_BYTES * BYTE_BITS + first_bit % BYTE_BITS;
+ const device uint* words = reinterpret_cast<const device uint*>(codes) + byte / WORD_BYTES;
+ const uint first = words[0], second = words[1];
+ const uint third = third_word_possible ? words[1 + uint(shift + bits_in_window > 2 * WORD_BITS)] : 0u;
+ const uint word0 = (first >> shift) | ((second << 1) << (WORD_BITS - 1 - shift));
+ const uint word1 = (second >> shift) | ((third << 1) << (WORD_BITS - 1 - shift));
+ const uint word2 = third >> shift;
+ METAL_PRAGMA_UNROLL
+ for (uint output = 0; output < window_states / states_per_weight_word; ++output) {
+ const uint first_state_bit = (window_states - 1 - output * states_per_weight_word) * transition_bits;
+ const uint first_state = state_field(word0, word1, word2, first_state_bit);
+ weights[window * (window_states / states_per_weight_word) + output] =
+ format.vector_width == 4
+ ? biased_weights(final_fold(hash_without_final_fold(first_state)))
+ : state_pair_weights(first_state, state_field(word0, word1, word2, first_state_bit - transition_bits));
+ }
}
+ return weights;
+}
- METAL_FUNC void advance() thread { k_offset += uint(BLOCK_K); }
-};
+} // namespace trellis
-} // namespace quantized
} // namespace gemm
} // namespace uzu
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.metal
index 83855456b..630898183 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
@@ -5,6 +5,7 @@
#include "common/gemm_tiling.h"
#include "common/mxu_mma_core.h"
+#include "common/quantized/cursor.h"
#include "common/quantized/trellis.h"
using namespace metal;
@@ -103,66 +104,57 @@ KERNEL(GemmTrellis)(
const uint code_row_bytes = trellis::row_bytes(trellis_format, params->K);
const short2 position = Ops::get_position(thread_context.simd_lane_id);
- const auto left_storage = operands::pack_left<LeftOperand, bfloat>(nullptr, activations, nullptr, nullptr);
Products products;
products.clear();
- uzu::dispatch_bool(alignment.contains(GemmAlignment::M) || token_end == Core::SIMDGROUP_BLOCK_M, [&](auto aligned_m) {
- uzu::dispatch_bool(alignment.contains(GemmAlignment::N) || row_end == Core::SIMDGROUP_BLOCK_N, [&](auto aligned_n) {
- auto left = quantized::make_left_cursor<Core, LeftOperand, aligned_m.value>(
- left_storage,
- params,
- tile_context,
- thread_context
- );
- quantized::TrellisCursor<RightFragment, aligned_n.value> trellis_cursor{
- codes + size_t(row_base + position.y) * code_row_bytes,
- code_row_bytes,
- row_end,
- position,
- tile_context.k_offset,
- trellis_format
- };
- const int k_chunks = token_end > 0 && row_end > 0
- ? int(params->aligned_inner_iterations) * int(trellis::K_STEP / Core::SIMDGROUP_BLOCK_K)
- : 0;
- if constexpr (GEMM_TILING == GemmTiling::Tile128x128x256_Simdgroups4x4) {
- if (trellis_vector_width == trellis::V4_VECTOR_WIDTH && trellis_transition_bits == 8 &&
- trellis_restart_columns == 64 && params->aligned_inner_iterations > 1) {
- static_assert(trellis::K_STEP % (2 * Core::SIMDGROUP_BLOCK_K) == 0, "paired K chunks must be complete");
- auto run_chunk = [&]() {
- auto left_tile = left.load(0u);
- auto right_tile = trellis_cursor.load(0u);
- uzu::matmul::fragment_mma(products, left_tile, right_tile);
- left.advance();
- trellis_cursor.advance();
- };
- METAL_PRAGMA_NO_UNROLL
- for (int chunk = 0; chunk < k_chunks; chunk += 2) {
- run_chunk();
- run_chunk();
- }
- } else {
- METAL_PRAGMA_NO_UNROLL
- for (int chunk = 0; chunk < k_chunks; ++chunk) {
- auto left_tile = left.load(0u);
- auto right_tile = trellis_cursor.load(0u);
- uzu::matmul::fragment_mma(products, left_tile, right_tile);
- left.advance();
- trellis_cursor.advance();
- }
+ // 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];
}
- } else {
- METAL_PRAGMA_NO_UNROLL
- for (int chunk = 0; chunk < k_chunks; ++chunk) {
- auto left_tile = left.load(0u);
- auto right_tile = trellis_cursor.load(0u);
- uzu::matmul::fragment_mma(products, left_tile, right_tile);
- left.advance();
- trellis_cursor.advance();
+ });
+ 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);
+ 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];
}
+ });
+ METAL_PRAGMA_UNROLL
+ for (uint chunk = 0; chunk < 2; ++chunk) {
+ uzu::matmul::fragment_mma(products, left[chunk], right[chunk]);
}
- });
+ }
});
const bool write_split_k_partials = params->aligned_inner_iterations * trellis::K_STEP < params->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.rs
index fdfe28a11..6b6fa5333 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
@@ -3,7 +3,7 @@ use std::collections::{HashMap, hash_map::Entry};
use crate::backends::{
common::{
BufferMut, BufferRef, CommandBufferEncoding,
- kernel::matmul::{MatmulA, MatmulArguments, MatmulB, TrellisFormat},
+ kernel::matmul::{MatmulA, MatmulArguments, MatmulB, TRELLIS_CODES_TAIL_BYTES, TrellisFormat},
},
metal::{
Metal,
@@ -70,6 +70,7 @@ impl TrellisGemm {
|| arguments.b_leading_dimension.is_some()
|| output_stride < n
|| (split_k > 1 && !n.is_multiple_of(4))
+ || codes.size() < (n * format.code_row_bytes(k)) as usize + TRELLIS_CODES_TAIL_BYTES
{
return Err(unsupported());
}
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.rs
index e3654dc8b..bbeeec47d 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
@@ -8,7 +8,8 @@ use crate::{
common::{
Backend, Context, Kernels,
kernel::matmul::{
- MatmulA, MatmulArguments, MatmulB, MatmulDOps, MatmulKernel, MatmulOutput, MatmulShape, TrellisFormat,
+ MatmulA, MatmulArguments, MatmulB, MatmulDOps, MatmulKernel, MatmulOutput, MatmulShape,
+ TRELLIS_CODES_TAIL_BYTES, TrellisFormat,
},
},
metal::{
@@ -40,37 +41,49 @@ const V2_T4: TrellisFormat = TrellisFormat {
transition_bits: 4,
restart_columns: None,
};
+const V4_T6: TrellisFormat = TrellisFormat {
+ vector_width: 4,
+ transition_bits: 6,
+ restart_columns: Some(64),
+};
+const V4_T7: TrellisFormat = TrellisFormat {
+ vector_width: 4,
+ transition_bits: 7,
+ restart_columns: Some(64),
+};
+const V4_T6_R40: TrellisFormat = TrellisFormat {
+ vector_width: 4,
+ transition_bits: 6,
+ restart_columns: Some(40),
+};
+const V4_T8_NO_RESTART: TrellisFormat = TrellisFormat {
+ vector_width: 4,
+ transition_bits: 8,
+ restart_columns: None,
+};
+// Tape 2: each block's bits reversed, LSB first; state i is the LE 16-bit field at bit B - 16 - i*T.
fn decode_state(
format: TrellisFormat,
row: &[u8],
+ columns: usize,
column: usize,
) -> u16 {
- let width = format.vector_width as usize;
- let (block, local) =
- format.restart_columns.map_or((0, column), |restart| (column / restart as usize, column % restart as usize));
- let block_bytes = format.restart_columns.map_or(0, |restart| row_bytes(format, restart as usize));
- let start_bit = block * block_bytes * 8 + local / width * format.transition_bits as usize;
- (start_bit..start_bit + 16).fold(0u32, |state, bit| (state << 1) | u32::from(row[bit / 8] >> (7 - bit % 8) & 1))
- as u16
-}
-
-fn row_bytes(
- format: TrellisFormat,
- columns: usize,
-) -> usize {
+ let (width, transition_bits) = (format.vector_width as usize, format.transition_bits as usize);
let block_columns = format.restart_columns.map_or(columns, |restart| restart as usize);
- let transitions = block_columns / format.vector_width as usize - 1;
- let bytes_per_block = (16 + transitions * format.transition_bits as usize).div_ceil(8);
- columns.div_ceil(block_columns) * bytes_per_block
+ let block_bits = 16 + (block_columns / width - 1) * transition_bits;
+ let start_bit = (column / block_columns + 1) * block_bits - 16 - column % block_columns / width * transition_bits;
+ (start_bit..start_bit + 16).rev().fold(0u32, |state, bit| (state << 1) | u32::from(row[bit / 8] >> (bit % 8) & 1))
+ as u16
}
fn decode_level(
format: TrellisFormat,
row: &[u8],
+ columns: usize,
column: usize,
) -> i32 {
- let state = u32::from(decode_state(format, row, column));
+ let state = u32::from(decode_state(format, row, columns, column));
let hash = state.wrapping_mul(0xCFCC_B83F).wrapping_add(0x584B_4AA3);
let hash = (hash ^ hash >> 16).wrapping_mul(0x85EB_CA6B);
let hash_byte = ((hash ^ hash >> 16) >> (8 * (column % format.vector_width as usize))) & 0xFF;
@@ -86,8 +99,9 @@ const PADDING: usize = 24;
const SENTINEL: u16 = 0x7F7F;
const RELATIVE_TOLERANCE: f32 = 1e-2;
// Cases are ordered as (m, n, k).
-const CASES: [(usize, usize, usize); 8] = [
+const CASES: [(usize, usize, usize); 9] = [
(1, 80, 5120),
+ (7, 80, 5120),
(17, 80, 5120),
(512, 80, 5120),
(16, 4096, 2048),
@@ -105,7 +119,8 @@ fn run_projection(
) {
let (m, n, k) = dimensions;
let mut rng = SmallRng::seed_from_u64((m * k + n) as u64);
- let stored: Vec<u8> = (0..n * row_bytes(format, k)).map(|_| rng.random()).collect();
+ let row_bytes = format.code_row_bytes(k as u32) as usize;
+ let stored: Vec<u8> = (0..n * row_bytes).map(|_| rng.random()).collect();
let row_scales: Vec<f32> = (0..n).map(|_| rng.random_range(0.001..0.01)).collect();
let mut values: Vec<i8> = (0..m * k).map(|_| rng.random_range(-127..=127)).collect();
if m > 1 {
@@ -131,7 +146,10 @@ fn run_projection(
let activations = create_buffer_with_data::<Metal, i8>(context, &values);
let group_sums = create_buffer_with_data::<Metal, f32>(context, &group_sums_host);
let activation_scales = create_buffer_with_data::<Metal, f32>(context, &activation_scales_host);
- let codes = create_buffer_with_data::<Metal, u8>(context, &stored);
+ // The GEMM may read a word past the last row's codes; the tail must not change the result.
+ let mut codes_with_tail = stored.clone();
+ codes_with_tail.resize(stored.len() + TRELLIS_CODES_TAIL_BYTES, 0xA5);
+ let codes = create_buffer_with_data::<Metal, u8>(context, &codes_with_tail);
let row_scales_buffer = create_buffer_with_data::<Metal, f32>(context, &row_scales);
let codebook = create_buffer_with_data::<Metal, f32>(context, &CODEBOOK);
let mut output = create_buffer_with_data::<Metal, u16>(context, &vec![SENTINEL; m * (n + PADDING)]);
@@ -175,8 +193,8 @@ fn run_projection(
}
submit_command_buffer(command_buffer);
let decoded_levels: Vec<i32> = stored
- .chunks_exact(row_bytes(format, k))
- .flat_map(|codes| (0..k).map(|column| decode_level(format, codes, column)))
+ .chunks_exact(row_bytes)
+ .flat_map(|codes| (0..k).map(|column| decode_level(format, codes, k, column)))
.collect();
let actual = buffer_to_vec::<Metal, u16>(&output);
let stride = n + PADDING;
@@ -209,15 +227,26 @@ fn run_projection(
#[case::v4_t8(V4_T8)]
#[case::v2_t6(V2_T6)]
#[case::v2_t4(V2_T4)]
+#[case::v4_t6(V4_T6)]
+#[case::v4_t7(V4_T7)]
+#[case::v4_t6_r40(V4_T6_R40)]
+#[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;
}
- for dimensions in CASES {
+ // 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);
}
- 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)));
+ // The forced plans' K are whole 64-column blocks.
+ if whole_blocks(64) {
+ 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)));
+ }
}