A high-performance inference engine for AI models
pre M5 2bit for dash (#1090)
CCYehc2afb5b0538f
diff --git a/crates/uzu-engine/src/backends/common/kernel/activation_transform.rs b/crates/uzu-engine/src/backends/common/kernel/activation_transform.rsindex 462d291e1..74dcb1074 100644--- a/crates/uzu-engine/src/backends/common/kernel/activation_transform.rs+++ b/crates/uzu-engine/src/backends/common/kernel/activation_transform.rs@@ -72,17 +72,19 @@ impl<B: Backend> ActivationTransform<B> {format: ActivationFormat,) -> Result<Self, B::Error> {let has_bias = bias_data_type.is_some();- let (codes_grouped_by_nibble, scale_group_size, sum_group_size) = match format {+ let (codes_grouped_by_nibble, scale_group_size, sum_group_size, weight_bits) = match format {ActivationFormat::Int8(q) => (q.code_layout().is_grouped_by_nibble(),q.scale_group_size(),q.sum_group_size().unwrap_or(q.scale_group_size()),+ 0,),ActivationFormat::PackedHalf {- group_size,- } => (false, HADAMARD_TRANSFORM_BLOCK_SIZE, group_size),+ block_k,+ bits,+ } => (false, HADAMARD_TRANSFORM_BLOCK_SIZE, block_k, bits),ActivationFormat::Bf16 | ActivationFormat::Trellis => {- (false, HADAMARD_TRANSFORM_BLOCK_SIZE, HADAMARD_TRANSFORM_BLOCK_SIZE)+ (false, HADAMARD_TRANSFORM_BLOCK_SIZE, HADAMARD_TRANSFORM_BLOCK_SIZE, 0)},};let kernel = <B::Kernels as Kernels>::ActivationTransformKernel::new(@@ -94,6 +96,7 @@ impl<B: Backend> ActivationTransform<B> {in_place,scale_group_size,sum_group_size,+ weight_bits,has_bias,)?;Ok(Self {diff --git a/crates/uzu-engine/src/backends/common/kernel/gated_act_mul.rs b/crates/uzu-engine/src/backends/common/kernel/gated_act_mul.rsindex 9a4a6610a..13bf900d3 100644--- a/crates/uzu-engine/src/backends/common/kernel/gated_act_mul.rs+++ b/crates/uzu-engine/src/backends/common/kernel/gated_act_mul.rs@@ -67,7 +67,7 @@ impl<B: Backend> GatedActMul<B> {settings: GatedActMulSettings,format: ActivationFormat,) -> Result<Self, B::Error> {- let (ops, codes_grouped_by_nibble, scale_group_size, sum_group_size) = match format {+ let (ops, codes_grouped_by_nibble, scale_group_size, sum_group_size, weight_bits) = match format {ActivationFormat::Int8(quantization) => (if quantization.sum_group_size().is_some() {GatedActMulOp::QuantizeWithGroupSums@@ -77,12 +77,14 @@ impl<B: Backend> GatedActMul<B> {quantization.code_layout().is_grouped_by_nibble(),quantization.scale_group_size(),quantization.sum_group_size().unwrap_or(quantization.scale_group_size()),+ 0,),ActivationFormat::PackedHalf {- group_size,- } => (GatedActMulOp::PackHalf, false, HADAMARD_TRANSFORM_BLOCK_SIZE, group_size),+ block_k,+ bits,+ } => (GatedActMulOp::PackHalf, false, HADAMARD_TRANSFORM_BLOCK_SIZE, block_k, bits),ActivationFormat::Bf16 | ActivationFormat::Trellis => {- (GatedActMulOp::FullPrecision, false, HADAMARD_TRANSFORM_BLOCK_SIZE, HADAMARD_TRANSFORM_BLOCK_SIZE)+ (GatedActMulOp::FullPrecision, false, HADAMARD_TRANSFORM_BLOCK_SIZE, HADAMARD_TRANSFORM_BLOCK_SIZE, 0)},};let kernel = <B::Kernels as Kernels>::GatedActMulKernel::new(@@ -94,6 +96,7 @@ impl<B: Backend> GatedActMul<B> {options.contains(GatedActMulOptions::HADAMARD),scale_group_size,sum_group_size,+ weight_bits,settings.activation_alpha.is_some(),settings.gate_clipping.into_pair().is_some(),settings.value_clipping.into_pair().is_some(),diff --git a/crates/uzu-engine/src/backends/common/kernel/matmul/matmul_a.rs b/crates/uzu-engine/src/backends/common/kernel/matmul/matmul_a.rsindex 14462b617..8c2515f13 100644--- a/crates/uzu-engine/src/backends/common/kernel/matmul/matmul_a.rs+++ b/crates/uzu-engine/src/backends/common/kernel/matmul/matmul_a.rs@@ -54,7 +54,8 @@ pub enum MatmulA<T> {},PackedHalf {values: T,- group_size: u32,+ block_k: u32,+ bits: u32,},Int8Symmetric {values: T,@@ -88,10 +89,12 @@ impl<T> MatmulA<T> {},Self::PackedHalf {values,- group_size,+ block_k,+ bits,} => MatmulA::PackedHalf {values,- group_size: *group_size,+ block_k: *block_k,+ bits: *bits,},Self::Int8Symmetric {values,@@ -120,8 +123,9 @@ impl<T> MatmulA<T> {/// Matches `PackedHalfLayout` in `packed_half_layout.h`.pub fn packed_half_bytes(k: u32,- group_size: u32,+ block_k: u32,+ bits: u32,) -> usize {- assert!(matches!(group_size, 32 | 64) && k.is_multiple_of(group_size));- (k / group_size) as usize * (32 * (group_size as usize / 8) + 16) * size_of::<u32>()+ assert!(matches!((bits, block_k), (4, 32 | 64) | (2, 128)) && k.is_multiple_of(block_k));+ (k / block_k) as usize * (32 * (block_k as usize / 8) + 16) * size_of::<u32>()}diff --git a/crates/uzu-engine/src/backends/common/kernel/matmul/routing.rs b/crates/uzu-engine/src/backends/common/kernel/matmul/routing.rsindex 83518b514..d0f9cedeb 100644--- a/crates/uzu-engine/src/backends/common/kernel/matmul/routing.rs+++ b/crates/uzu-engine/src/backends/common/kernel/matmul/routing.rs@@ -10,7 +10,8 @@ pub enum ActivationFormat {Bf16,Int8(ActivationQuantization),PackedHalf {- group_size: u32,+ block_k: u32,+ bits: u32,},Trellis,}@@ -60,10 +61,12 @@ impl MatmulShape {..} => ActivationFormat::Bf16,MatmulA::PackedHalf {- group_size,+ block_k,+ bits,..} => ActivationFormat::PackedHalf {- group_size: *group_size,+ block_k: *block_k,+ bits: *bits,},MatmulA::Int8Symmetric {quantization,diff --git a/crates/uzu-engine/src/backends/cpu/kernel/activation_transform/activation_transform.rs b/crates/uzu-engine/src/backends/cpu/kernel/activation_transform/activation_transform.rsindex a501ae16b..0658bf1e3 100644--- a/crates/uzu-engine/src/backends/cpu/kernel/activation_transform/activation_transform.rs+++ b/crates/uzu-engine/src/backends/cpu/kernel/activation_transform/activation_transform.rs@@ -64,12 +64,17 @@ pub fn activation_transform<T: DataTypeRepr + Float, BiasT: DataTypeRepr + Floatrht_factors: *const i32,batch_size: u32,element_count: u32,- #[optional(ops == ActivationTransformOp::PackHalf)] packed_half_out: Option<*mut u32>,+ #[expect(unused_variables)]+ #[optional(ops == ActivationTransformOp::PackHalf)]+ packed_half_out: Option<*mut u32>,#[specialize] ops: ActivationTransformOp,#[specialize] grouped_by_weight_nibble: bool,#[specialize] in_place: bool,#[specialize] activation_scale_group_size: u32,#[specialize] sum_group_size: u32,+ #[expect(unused_variables)]+ #[specialize]+ weight_bits: u32,#[specialize] has_bias: bool,) {let input = match in_place {@@ -80,7 +85,6 @@ pub fn activation_transform<T: DataTypeRepr + Float, BiasT: DataTypeRepr + Floatlet columns = element_count as usize;let input_rht = ops != ActivationTransformOp::OutputRht;let quantize = matches!(ops, ActivationTransformOp::Quantize | ActivationTransformOp::QuantizeWithGroupSums);- assert!(packed_half_out.is_none(), "CPU packed-half activation is not selected");assert_eq!(bias.is_some(), has_bias);let mut transformed = vec![0.0f32; columns];diff --git a/crates/uzu-engine/src/backends/cpu/kernel/gated_act_mul/gated_act_mul.rs b/crates/uzu-engine/src/backends/cpu/kernel/gated_act_mul/gated_act_mul.rsindex 15f41254a..9d719608b 100644--- a/crates/uzu-engine/src/backends/cpu/kernel/gated_act_mul/gated_act_mul.rs+++ b/crates/uzu-engine/src/backends/cpu/kernel/gated_act_mul/gated_act_mul.rs@@ -41,13 +41,18 @@ pub fn gated_act_mul<T: DataTypeRepr + Float>(#[optional(clip_gate)] gate_clip_max: Option<f32>,#[optional(clip_value)] value_clip_min: Option<f32>,#[optional(clip_value)] value_clip_max: Option<f32>,- #[optional(ops == GatedActMulOp::PackHalf)] packed_half_out: Option<*mut u32>,+ #[expect(unused_variables)]+ #[optional(ops == GatedActMulOp::PackHalf)]+ packed_half_out: Option<*mut u32>,#[specialize] ops: GatedActMulOp,#[specialize] grouped_by_weight_nibble: bool,#[specialize] interleaved: bool,#[specialize] use_hadamard: bool,#[specialize] activation_scale_group_size: u32,#[specialize] sum_group_size: u32,+ #[expect(unused_variables)]+ #[specialize]+ weight_bits: u32,#[specialize] custom_activation_alpha: bool,#[specialize] clip_gate: bool,#[specialize] clip_value: bool,@@ -55,7 +60,6 @@ pub fn gated_act_mul<T: DataTypeRepr + Float>(assert_eq!(hadamard_factors.is_some(), use_hadamard);let quantize = matches!(ops, GatedActMulOp::Quantize | GatedActMulOp::QuantizeWithGroupSums);let emit_group_sums = ops == GatedActMulOp::QuantizeWithGroupSums;- assert!(packed_half_out.is_none(), "CPU packed-half gate is not selected");assert!(!quantize || use_hadamard, "quantized gate activation requires RHT");assert!(!quantize || gated_dim.is_multiple_of(activation_scale_group_size));assert!(!emit_group_sums || gated_dim.is_multiple_of(sum_group_size));diff --git a/crates/uzu-engine/src/backends/metal/gpu_types/gemm.rs b/crates/uzu-engine/src/backends/metal/gpu_types/gemm.rsindex 637e75054..39e94d78c 100644--- a/crates/uzu-engine/src/backends/metal/gpu_types/gemm.rs+++ b/crates/uzu-engine/src/backends/metal/gpu_types/gemm.rs@@ -41,10 +41,6 @@ pub const MXU_SIMDGROUP_BLOCK_K: u32 = 32;pub const TRELLIS_DECODE_MAX_BATCH: u32 = 8;impl GemmTiling {- pub const fn is_packed_w4(self) -> bool {- matches!(self, Self::Tile8x32x64_Simdgroups1x2x4)- }-pub const fn block_m(self) -> u32 {match self {Self::Tile8x32x32_Simdgroups1x1 => 8,diff --git a/crates/uzu-engine/src/backends/metal/kernel/activation_transform/activation_transform.metal b/crates/uzu-engine/src/backends/metal/kernel/activation_transform/activation_transform.metalindex 2dc3e562d..0b96e0dfc 100644--- a/crates/uzu-engine/src/backends/metal/kernel/activation_transform/activation_transform.metal+++ b/crates/uzu-engine/src/backends/metal/kernel/activation_transform/activation_transform.metal@@ -38,6 +38,7 @@ PUBLIC KERNEL(ActivationTransform)(const bool in_place SPECIALIZE,const uint activation_scale_group_size SPECIALIZE,const uint sum_group_size SPECIALIZE,+ const uint weight_bits SPECIALIZE,const bool has_bias SPECIALIZE,uint activation_tile_index GROUPS(element_count.div_ceil(TILE_ELEMENTS)),uint batch_index GROUPS(batch_size),@@ -83,7 +84,7 @@ PUBLIC KERNEL(ActivationTransform)(if (PACKED_HALF) {if (in_bounds) {- store_packed_half(values, lane_index, first_index, batch_index, sum_group_size, packed_half_out);+ store_packed_half(values, lane_index, first_index, batch_index, sum_group_size, weight_bits, packed_half_out);}return;}diff --git a/crates/uzu-engine/src/backends/metal/kernel/common/packed_half_activation.h b/crates/uzu-engine/src/backends/metal/kernel/common/packed_half_activation.hindex f60fa6407..e21410ff0 100644--- a/crates/uzu-engine/src/backends/metal/kernel/common/packed_half_activation.h+++ b/crates/uzu-engine/src/backends/metal/kernel/common/packed_half_activation.h@@ -15,28 +15,33 @@ static METAL_FUNC void store_packed_half(const uint lane,const uint first_index,const uint row,- const uint group_size,+ const uint block_k,+ const uint weight_bits,device uint* packed) {- using Layout32 = uzu::gemm::PackedHalfLayout<32>;- using Layout64 = uzu::gemm::PackedHalfLayout<64>;- const uint group = first_index / group_size;- const uint k = first_index % group_size;- const uint group_words = group_size == 32 ? Layout32::GROUP_WORDS : Layout64::GROUP_WORDS;- const uint word =- group * group_words + (group_size == 32 ? Layout32::word_offset(k, row) : Layout64::word_offset(k, row));+ using Layout32 = uzu::gemm::PackedHalfLayout<32, 4>;+ using Layout64 = uzu::gemm::PackedHalfLayout<64, 4>;+ using Layout128 = uzu::gemm::PackedHalfLayout<128, 2>;+ const uint group = first_index / block_k;+ const uint k = first_index % block_k;+ const uint sums_offset = METAL_SIMD_SIZE * (block_k / Layout32::MMA_WIDTH);+ const uint group_words =+ sums_offset + (METAL_SIMD_SIZE / Layout32::MMA_WIDTH) * Layout32::ROWS_PER_PAIR * Layout32::SUMS_PER_ROW;+ const uint word = group * group_words + (weight_bits == 2 ? Layout128::word_offset(k, row)+ : block_k == 32 ? Layout32::word_offset(k, row)+ : Layout64::word_offset(k, row));device half* halves = reinterpret_cast<device half*>(packed);float2 sums = 0.0f;for (uint i = 0; i < Layout32::VALUES_PER_VECTOR; ++i) {const half value = half(clamp(values[i], -PACKED_HALF_MAX_FINITE, PACKED_HALF_MAX_FINITE));halves[Layout32::ROWS_PER_PAIR * (word + i) + row % Layout32::ROWS_PER_PAIR] = value;- sums += float2(float(value), uzu::gemm::w4_pair_bias_value(i) * float(value));+ const float bias = weight_bits == 2 ? uzu::gemm::w2_pair_bias_value((k + i) % 8) : uzu::gemm::w4_pair_bias_value(i);+ sums += float2(float(value), bias * float(value));}- const uint lane_count = group_size / Layout32::VALUES_PER_VECTOR;+ const uint lane_count = block_k / Layout32::VALUES_PER_VECTOR;sums.x = reduce_adjacent_lanes(sums.x, lane_count, [](float x, float y) { return x + y; });sums.y = reduce_adjacent_lanes(sums.y, lane_count, [](float x, float y) { return x + y; });if (lane % lane_count == 0) {- const uint sums_offset = group_size == 32 ? Layout32::sums_offset() : Layout64::sums_offset();device float* output = reinterpret_cast<device float*>(packed + group * group_words + sums_offset);output[row * Layout32::SUMS_PER_ROW] = sums.x;output[row * Layout32::SUMS_PER_ROW + 1] = sums.y;diff --git a/crates/uzu-engine/src/backends/metal/kernel/gated_act_mul/gated_act_mul.metal b/crates/uzu-engine/src/backends/metal/kernel/gated_act_mul/gated_act_mul.metalindex f3ae5f572..2d49d3d99 100644--- a/crates/uzu-engine/src/backends/metal/kernel/gated_act_mul/gated_act_mul.metal+++ b/crates/uzu-engine/src/backends/metal/kernel/gated_act_mul/gated_act_mul.metal@@ -46,6 +46,7 @@ PUBLIC KERNEL(GatedActMul) (const bool use_hadamard SPECIALIZE,const uint activation_scale_group_size SPECIALIZE,const uint sum_group_size SPECIALIZE,+ const uint weight_bits SPECIALIZE,const bool custom_activation_alpha SPECIALIZE,const bool clip_gate SPECIALIZE,const bool clip_value SPECIALIZE,@@ -126,7 +127,7 @@ PUBLIC KERNEL(GatedActMul) (if (PACKED_HALF) {if (valid_count > 0) {- store_packed_half(results, lane_index, first_index, batch_idx, sum_group_size, packed_half_out);+ store_packed_half(results, lane_index, first_index, batch_idx, sum_group_size, weight_bits, packed_half_out);}return;}diff --git a/crates/uzu-engine/src/backends/metal/kernel/matmul/common/packed_half_layout.h b/crates/uzu-engine/src/backends/metal/kernel/matmul/common/packed_half_layout.hindex 40fc02d49..37ed94369 100644--- a/crates/uzu-engine/src/backends/metal/kernel/matmul/common/packed_half_layout.h+++ b/crates/uzu-engine/src/backends/metal/kernel/matmul/common/packed_half_layout.h@@ -7,7 +7,7 @@ using namespace metal;namespace uzu::gemm {-template <uint GROUP_SIZE>+template <uint BLOCK_K, uint BITS>struct PackedHalfLayout {UZU_CONST uint MMA_WIDTH = 8;UZU_CONST uint VALUES_PER_VECTOR = 4;@@ -15,20 +15,26 @@ struct PackedHalfLayout {UZU_CONST uint SUMS_PER_ROW = 2;UZU_CONST uint G64_K_INTERLEAVE = 2;UZU_CONST uint G64_K_CHUNK = G64_K_INTERLEAVE * MMA_WIDTH;- UZU_CONST uint STEPS = GROUP_SIZE / MMA_WIDTH;+ UZU_CONST uint STEPS = BLOCK_K / MMA_WIDTH;UZU_CONST uint GROUP_WORDS = METAL_SIMD_SIZE * STEPS + (METAL_SIMD_SIZE / MMA_WIDTH) * ROWS_PER_PAIR * SUMS_PER_ROW;static METAL_FUNC uint pair_offset(uint slot, uint fm) { return (slot * MMA_WIDTH + fm) * STEPS; }static METAL_FUNC uint codes_offset(uint group, uint slot) {- return group * (GROUP_SIZE / 2) + slot * (GROUP_SIZE / 8);+ return group * (BLOCK_K * BITS / 8) + slot * (BLOCK_K * BITS / 32);}static METAL_FUNC uint sums_offset() { return METAL_SIMD_SIZE * STEPS; }static METAL_FUNC uint word_offset(uint k, uint row) {+ if constexpr (BITS == 2) {+ const uint octet = k / MMA_WIDTH;+ const uint fm = 2 * (octet / 4) + octet % 2;+ const uint step = (octet / 2 % 2) * MMA_WIDTH + k % MMA_WIDTH;+ return pair_offset(row / ROWS_PER_PAIR, fm) + step;+ }const uint chunk = (k % G64_K_CHUNK) / VALUES_PER_VECTOR;const uint fm =- GROUP_SIZE == 32 ? k / VALUES_PER_VECTOR : (k / G64_K_CHUNK) * G64_K_INTERLEAVE + chunk % G64_K_INTERLEAVE;- const uint step = GROUP_SIZE == 32 ? k % VALUES_PER_VECTOR- : (chunk / G64_K_INTERLEAVE) * VALUES_PER_VECTOR + k % VALUES_PER_VECTOR;+ BLOCK_K == 32 ? k / VALUES_PER_VECTOR : (k / G64_K_CHUNK) * G64_K_INTERLEAVE + chunk % G64_K_INTERLEAVE;+ const uint step =+ BLOCK_K == 32 ? k % VALUES_PER_VECTOR : (chunk / G64_K_INTERLEAVE) * VALUES_PER_VECTOR + k % VALUES_PER_VECTOR;return pair_offset(row / ROWS_PER_PAIR, fm) + step;}};diff --git a/crates/uzu-engine/src/backends/metal/kernel/matmul/common/quant_unpack.h b/crates/uzu-engine/src/backends/metal/kernel/matmul/common/quant_unpack.hindex 15e4d921c..bcc86d4a0 100644--- a/crates/uzu-engine/src/backends/metal/kernel/matmul/common/quant_unpack.h+++ b/crates/uzu-engine/src/backends/metal/kernel/matmul/common/quant_unpack.h@@ -92,8 +92,8 @@ inline void dequantize(threadgroup StageT* w_local,const bool signed_codes) {- static_assert(bits == 4 || bits == 8, "Only int4 and int8 supported");- static_assert(bits == 8 || N % 2 == 0, "int4 values are unpacked in pairs");+ static_assert(bits == 2 || bits == 4 || bits == 8, "Only int2, int4 and int8 supported");+ static_assert(bits == 8 || N % 2 == 0, "int2 and int4 values are unpacked in pairs");constexpr bool IS_16_BIT_COMPUTE = sizeof(ComputeT) == 2;constexpr bool READ_CODE_WORDS = bits == 4 && N % 8 == 0 && IS_16_BIT_COMPUTE;threadgroup vec<StageT, 2>* pairs = reinterpret_cast<threadgroup vec<StageT, 2>*>(w_local);@@ -110,6 +110,11 @@ inline void dequantize();}}+ } else if constexpr (bits == 2) {+ for (int i = 0; i < (N / 2); i++) {+ const uint code = uint(w[i / 2]) >> (4 * (i % 2));+ pairs[i] = vec<StageT, 2>(vec<ComputeT, 2>(dequantize_code(code & 0x3u), dequantize_code((code >> 2) & 0x3u)));+ }} else if constexpr (bits == 4) {const uint sign_flip = signed_codes ? 0x88u : 0u;for (int i = 0; i < (N / 2); i++) {@@ -129,6 +134,23 @@ inline void dequantize(}}+UZU_CONST uint HALF_MANTISSA_BITS = 10;+UZU_CONST uint HALF_EXPONENT_BIAS = 15;++static METAL_FUNC constexpr uint w2_mantissa_bit(uint t) { return t < 5 ? 2 * t : 2 * t - 6; }++static METAL_FUNC half2 w2_pair(uint word, uint t) {+ const uint mantissa_bit = w2_mantissa_bit(t);+ const uint code_mask = 3u << mantissa_bit;+ const uint exponent = (HALF_EXPONENT_BIAS + HALF_MANTISSA_BITS - mantissa_bit) << HALF_MANTISSA_BITS;+ const uint codes = (word >> (2 * t - mantissa_bit)) & (code_mask | (code_mask << 16));+ return as_type<half2>(codes | exponent | (exponent << 16));+}++static METAL_FUNC constexpr float w2_pair_bias_value(uint t) {+ return float(1u << (HALF_MANTISSA_BITS - w2_mantissa_bit(t)));+}+// A byte ored with 0x6400 is the half 1024 plus the byte, so the subtraction is exact.METAL_FUNC float4 bytes_to_float(const uint word, const float offset) {const half2 bias = half2(half(1024.0f + offset));diff --git a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/common/quant_scale_bias.h b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/common/quant_scale_bias.hindex c15d00022..ec9d94221 100644--- a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/common/quant_scale_bias.h+++ b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/common/quant_scale_bias.h@@ -25,7 +25,7 @@ template <struct QuantizedBlockLoaderScaleBias {static_assert(THREADGROUP_TILE_COLS <= GROUP_SIZE, "Group size should be larger than columns");static_assert(GROUP_SIZE % THREADGROUP_TILE_COLS == 0, "Group size should be divisible by columns");- static_assert(BITS == 4 || BITS == 8, "Only int4 and int8 supported");+ static_assert(BITS == 2 || BITS == 4 || BITS == 8, "Only int2, int4 and int8 supported");UZU_CONST short PACK_FACTOR = get_pack_factor<BITS, 8>();UZU_CONST short BYTES_PER_PACK = get_bytes_per_pack<BITS>();diff --git a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/common/schedules/small_batch/packed.h b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/common/schedules/small_batch/packed.hindex 3f6df944c..70c359ed5 100644--- a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/common/schedules/small_batch/packed.h+++ b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/common/schedules/small_batch/packed.h@@ -17,12 +17,16 @@ namespace schedules {struct PackedSchedule {UZU_CONST bool TRANSPOSED_OUTPUT = true;- template <ushort WORDS_PER_LANE>+ template <ushort BITS, ushort WORDS_PER_LANE>struct WeightDecoder {thread const uint* packed_words;METAL_FUNC half2 operator()(const ushort row, const ushort k) const thread {- return w4_pair(packed_words[row * WORDS_PER_LANE + k / 4], k % 4);+ if constexpr (BITS == 2) {+ return w2_pair(packed_words[row * WORDS_PER_LANE + k / 8], k % 8);+ } else {+ return w4_pair(packed_words[row * WORDS_PER_LANE + k / 4], k % 4);+ }}};@@ -36,13 +40,14 @@ struct PackedSchedule {using RightOperand = typename Core::Right;constexpr bool HAS_BIAS = RightOperand::SCHEME == GemmBPrologueKind::ScaleBiasDequant;constexpr ushort WEIGHT_GROUP_SIZE = RightOperand::GROUP_SIZE;- constexpr ushort K_STEPS_PER_GROUP = PackedHalfLayout<WEIGHT_GROUP_SIZE>::STEPS;- constexpr ushort WORDS_PER_LANE = WEIGHT_GROUP_SIZE / 32;- constexpr ushort WORDS_PER_GROUP = PackedHalfLayout<WEIGHT_GROUP_SIZE>::GROUP_WORDS;+ constexpr ushort WEIGHT_BITS = RightOperand::BITS;+ constexpr ushort K_STEPS_PER_GROUP = PackedHalfLayout<WEIGHT_GROUP_SIZE, WEIGHT_BITS>::STEPS;+ constexpr ushort WORDS_PER_LANE = WEIGHT_GROUP_SIZE * WEIGHT_BITS / (8 * sizeof(uint4));+ constexpr ushort WORDS_PER_GROUP = PackedHalfLayout<WEIGHT_GROUP_SIZE, WEIGHT_BITS>::GROUP_WORDS;constexpr ushort GROUPS_PER_K_BLOCK = Core::THREADGROUP_BLOCK_K / WEIGHT_GROUP_SIZE;using Ops = typename Core::FragmentOps;- using WeightFragment =- uzu::matmul::GeneratedFragment<half, Core::TILES_M, K_STEPS_PER_GROUP, Ops, WeightDecoder<WORDS_PER_LANE>>;+ using WeightFragment = uzu::matmul::+ GeneratedFragment<half, Core::TILES_M, K_STEPS_PER_GROUP, Ops, WeightDecoder<WEIGHT_BITS, WORDS_PER_LANE>>;using ActivationFragment = uzu::matmul::Fragment<half, K_STEPS_PER_GROUP, Core::TILES_N, Ops>;const device uint* packed_activations = left.packed_half;@@ -50,8 +55,12 @@ struct PackedSchedule {const uint lane_row = uint(tile_context.lane_position.y);const uint weight_sign_mask = right.sign_mask();+ const bool row_scaled = right.hoist_row_metadata;typename Core::AccumFragment accumulator;accumulator.clear();+ typename Core::AccumFragment group_product;+ group_product.clear();+ float4 total_sums = 0.0f;const uint k_block_end = tile_context.k_block_end;for (uint k_block = tile_context.k_block_begin + tile_context.simdgroup_k_slice; k_block < k_block_end;k_block += Core::SIMDGROUPS_PER_K) {@@ -60,7 +69,8 @@ struct PackedSchedule {const uint weight_group_index = first_weight_group + group_in_block;const device uint* packed_group = packed_activations + weight_group_index * WORDS_PER_GROUP;const device uint* activation_pairs =- packed_group + PackedHalfLayout<WEIGHT_GROUP_SIZE>::pair_offset(fragment_column_pair, lane_row);+ packed_group ++ PackedHalfLayout<WEIGHT_GROUP_SIZE, WEIGHT_BITS>::pair_offset(fragment_column_pair, lane_row);ActivationFragment activation_fragment;METAL_PRAGMA_UNROLLfor (ushort vector = 0; vector < K_STEPS_PER_GROUP / 4; ++vector) {@@ -71,7 +81,7 @@ struct PackedSchedule {activation_fragment.fragment_at(4 * vector + 3, 0) = as_type<half2>(raw.w);}const float4 activation_sums = reinterpret_cast<const device float4*>(- packed_group + PackedHalfLayout<WEIGHT_GROUP_SIZE>::sums_offset()+ packed_group + PackedHalfLayout<WEIGHT_GROUP_SIZE, WEIGHT_BITS>::sums_offset())[fragment_column_pair];uint weight_rows[Core::TILES_M];@@ -84,24 +94,30 @@ struct PackedSchedule {min(tile_context.simdgroup_column_base + Ops::FRAGMENT_ROWS * tile_m + lane_row, params->N - 1);const device uint* weight_source = reinterpret_cast<const device uint*>(right.row_codes(weight_rows[tile_m], params) +- PackedHalfLayout<WEIGHT_GROUP_SIZE>::codes_offset(weight_group_index, fragment_column_pair)+ PackedHalfLayout<WEIGHT_GROUP_SIZE, WEIGHT_BITS>::codes_offset(weight_group_index, fragment_column_pair));METAL_PRAGMA_UNROLLfor (ushort word_index = 0; word_index < WORDS_PER_LANE; ++word_index) {packed_weight_words[tile_m * WORDS_PER_LANE + word_index] = weight_source[word_index] ^ weight_sign_mask;}- weight_scales[tile_m] = float(right.scale(weight_rows[tile_m], weight_group_index, params));- if constexpr (HAS_BIAS) {- weight_offsets[tile_m] =- float(right.bias()[right.scale_index(weight_rows[tile_m], weight_group_index, params)]);- } else {- weight_offsets[tile_m] = float(right.zero_point(weight_rows[tile_m], weight_group_index, params));+ if (!row_scaled) {+ weight_scales[tile_m] = float(right.scale(weight_rows[tile_m], weight_group_index, params));+ if constexpr (HAS_BIAS) {+ weight_offsets[tile_m] =+ float(right.bias()[right.scale_index(weight_rows[tile_m], weight_group_index, params)]);+ } else {+ weight_offsets[tile_m] = float(right.zero_point(weight_rows[tile_m], weight_group_index, params));+ }}}- WeightDecoder<WORDS_PER_LANE> weight_decoder{packed_weight_words};+ WeightDecoder<WEIGHT_BITS, WORDS_PER_LANE> weight_decoder{packed_weight_words};WeightFragment weight_fragment{weight_decoder};- typename Core::AccumFragment group_product;+ if (row_scaled) {+ uzu::matmul::fragment_mma(group_product, weight_fragment, activation_fragment);+ total_sums += activation_sums;+ continue;+ }group_product.clear();uzu::matmul::fragment_mma(group_product, weight_fragment, activation_fragment);accumulator.for_each_lane(@@ -122,6 +138,22 @@ struct PackedSchedule {}}+ if constexpr (HAS_BIAS) {+ if (row_scaled) {+ accumulator.for_each_lane(+ [&](ushort tile_m, ushort input_index, thread float& accumulator_value, thread float& product_value) {+ const uint row =+ min(tile_context.simdgroup_column_base + Ops::FRAGMENT_ROWS * tile_m + lane_row, params->N - 1);+ accumulator_value =+ fma(product_value - total_sums[2 * input_index + 1],+ float(right.scale(row, 0, params)),+ float(right.bias()[right.scale_index(row, 0u, params)]) * total_sums[2 * input_index]);+ },+ group_product+ );+ }+ }+return accumulator;}};diff --git a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/gemm.metal b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/gemm.metalindex 3ece65d3e..2af9b7c13 100644--- a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/gemm.metal+++ b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/gemm.metal@@ -12,9 +12,9 @@ using namespace metal;using namespace uzu::gemm;#define A_IS_INT8 (A_PROLOGUE == GemmAPrologueKind::Int8Symmetric)-#define GEMM_PACKED_HALF_TILING (GEMM_TILING == GemmTiling::Tile8x32x64_Simdgroups1x2x4)-#define GEMM_SMALL_BATCH (GEMM_PACKED_HALF_TILING || GEMM_TILING == GemmTiling::Tile8x32x128_Simdgroups1x2x4)-#define GEMM_SMALL_BATCH_W8 (GEMM_SMALL_BATCH && !GEMM_PACKED_HALF_TILING)+#define GEMM_SMALL_BATCH \+ (GEMM_TILING == GemmTiling::Tile8x32x64_Simdgroups1x2x4 || GEMM_TILING == GemmTiling::Tile8x32x128_Simdgroups1x2x4)+#define GEMM_SMALL_BATCH_W8 (GEMM_SMALL_BATCH && A_PROLOGUE != GemmAPrologueKind::PackedHalf)#define NEEDS_ASYMMETRIC_WEIGHT_CORRECTION (A_IS_INT8 && B_PROLOGUE == GemmBPrologueKind::ScaleBiasDequant)#define GEMM_MXU_QUANT (USE_MXU && B_PROLOGUE != GemmBPrologueKind::FullPrecision && !A_IS_INT8)#define GEMM_TGA_ELEMENTS \@@ -95,7 +95,11 @@ CONSTRAINT((BITS == 0) == (GROUP_SIZE == 0))CONSTRAINT(B_PROLOGUE != GemmBPrologueKind::ScaleZeroPointDequant || BITS == 4)CONSTRAINT(B_PROLOGUE != GemmBPrologueKind::ScaleSymmetricDequant || BITS == 8)CONSTRAINT(B_PROLOGUE != GemmBPrologueKind::ScaleBiasDequant || BITS == 2 || BITS == 4)-CONSTRAINT((BITS == 2) == (GROUP_SIZE == 128) && (BITS != 2 || A_IS_INT8))+CONSTRAINT(+ (BITS == 2) == (GROUP_SIZE == 128) &&+ (BITS != 2 || A_IS_INT8 ||+ (DT == "bfloat" &&+ (A_PROLOGUE == GemmAPrologueKind::PackedHalf || (!USE_MXU && !GEMM_SMALL_BATCH)))))CONSTRAINT(B_PROLOGUE == GemmBPrologueKind::FullPrecision ||(TRANSPOSE_B && GEMM_TILING != GemmTiling::Tile64x32x32_Simdgroups2x2))@@ -113,8 +117,12 @@ CONSTRAINT(GEMM_TILING != GemmTiling::Tile16x128x256_Simdgroups1x4 ||(TRANSPOSE_B && B_PROLOGUE == GemmBPrologueKind::FullPrecision))CONSTRAINT(A_PROLOGUE == GemmAPrologueKind::FullPrecision || A_PROLOGUE == GemmAPrologueKind::PackedHalf || USE_MXU)-CONSTRAINT(GEMM_PACKED_HALF_TILING == (A_PROLOGUE == GemmAPrologueKind::PackedHalf))-CONSTRAINT(!GEMM_PACKED_HALF_TILING || (!USE_MXU && TRANSPOSE_B && BITS == 4))+CONSTRAINT(GEMM_TILING != GemmTiling::Tile8x32x64_Simdgroups1x2x4 || A_PROLOGUE == GemmAPrologueKind::PackedHalf)+CONSTRAINT(+ A_PROLOGUE != GemmAPrologueKind::PackedHalf ||+ (GEMM_SMALL_BATCH && !USE_MXU && TRANSPOSE_B &&+ ((GEMM_TILING == GemmTiling::Tile8x32x64_Simdgroups1x2x4 && BITS == 4) ||+ (GEMM_TILING == GemmTiling::Tile8x32x128_Simdgroups1x2x4 && BITS == 2))))CONSTRAINT(!GEMM_SMALL_BATCH_W8 ||(!USE_MXU && TRANSPOSE_B && A_PROLOGUE == GemmAPrologueKind::FullPrecision &&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 34370b0a4..16b6a68fb 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@@ -38,19 +38,22 @@ pub enum GemmPlanError {UnsupportedLayout(&'static str),}-/// The weight formats with small-M kernels (batched GEMV and register GEMM): W4 zero-point or scale-bias, and W8-/// symmetric, at group size 32 or 64. Returns the GEMM's activation format, tiling and K alignment.+/// Activation format, tiling and K alignment of the small-M GEMM for W4 and W8 (group 32 or 64) and W2 (group 128).pub fn small_m_weights(shape: &MatmulShape) -> Option<(ActivationFormat, GemmTiling, u32)> {- let group_size = shape.b_group_size.filter(|group_size| matches!(group_size, 32 | 64))?;- match (shape.b_prologue, shape.b_bits) {- (GemmBPrologueKind::ScaleZeroPointDequant | GemmBPrologueKind::ScaleBiasDequant, Some(4)) => Some((- ActivationFormat::PackedHalf {- group_size,- },- GemmTiling::Tile8x32x64_Simdgroups1x2x4,- 512,- )),- (GemmBPrologueKind::ScaleSymmetricDequant, Some(8)) => {+ let bits = shape.b_bits?;+ let group_size = shape.b_group_size?;+ let packed_half = ActivationFormat::PackedHalf {+ block_k: group_size,+ bits,+ };+ match (shape.b_prologue, bits, group_size) {+ (GemmBPrologueKind::ScaleBiasDequant, 2, 128) => {+ Some((packed_half, GemmTiling::Tile8x32x128_Simdgroups1x2x4, 512))+ },+ (GemmBPrologueKind::ScaleZeroPointDequant | GemmBPrologueKind::ScaleBiasDequant, 4, 32 | 64) => {+ Some((packed_half, GemmTiling::Tile8x32x64_Simdgroups1x2x4, 512))+ },+ (GemmBPrologueKind::ScaleSymmetricDequant, 8, 32 | 64) => {Some((ActivationFormat::Bf16, GemmTiling::Tile8x32x128_Simdgroups1x2x4, 256))},_ => None,@@ -105,13 +108,14 @@ impl GemmProblem {) -> Option<GemmPlan> {let (activation, tiling) = small_batch_format(self.shape, layout)?;let plan = self.finish_plan(GemmEngine::Simdgroup, tiling);- let partition_alignment = if tiling.is_packed_w4() || plan.split_k == 1 {+ let partition_alignment = if plan.split_k == 1 {256} else {- 512+ tiling.simdgroups_k() * tiling.block_k()};(self.shape.a == activation- && (4..=8).contains(&self.shape.m)+ && (2..=8).contains(&self.shape.m)+ && (self.shape.m >= 4 || self.shape.b_bits == Some(2))&& self.shape.k.is_multiple_of(partition_alignment * plan.split_k)).then_some(plan)}@@ -163,7 +167,10 @@ impl GemmProblem {) -> u32 {let shape = self.shape;let splittable = shape.is_quant() || (shape.b_transpose && shape.b_leading_dimension.is_none());- if !splittable || !self.split_k_output_supported() {+ if !splittable+ || !self.split_k_output_supported()+ || (shape.b_bits == Some(2) && tiling == GemmTiling::Tile8x32x128_Simdgroups1x2x4)+ {return 1;}let base_tiles = shape.n.div_ceil(tiling.block_n()).saturating_mul(shape.m.div_ceil(tiling.block_m()));diff --git a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/specialization.rs b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/specialization.rsindex 5a69d25c8..7eafc463a 100644--- a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/specialization.rs+++ b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/specialization.rs@@ -54,7 +54,7 @@ impl GemmSpecialization {signed_codes: shape.signed_codes,gemm_b_layout,hoist_row_metadata: row_scaled_weights- && a_prologue == GemmAPrologueKind::Int8Symmetric+ && matches!(a_prologue, GemmAPrologueKind::Int8Symmetric | GemmAPrologueKind::PackedHalf)&& shape.b_prologue == GemmBPrologueKind::ScaleBiasDequant,a_group_size,};diff --git a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemv/policy/quantized.rs b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemv/policy/quantized.rsindex 3d113d869..7d790efc1 100644--- a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemv/policy/quantized.rs+++ b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemv/policy/quantized.rs@@ -40,7 +40,7 @@ pub fn select(bf16_io: bool,) -> Option<GemvTile> {// The GEMV pipelines exist for BF16 I/O only. Rows 5..=8 stay on GEMV for tiny N only.- if !bf16_io || bits == 2 || (m > 4 && n > 64) {+ if !bf16_io || (m > 4 && n > 64) {return None;}gathered_tile(bits, group, m, n)diff --git a/crates/uzu-engine/src/backends/metal/kernel/matmul/matmul_metal_kernel.rs b/crates/uzu-engine/src/backends/metal/kernel/matmul/matmul_metal_kernel.rsindex ee33dbfa4..7a4604178 100644--- a/crates/uzu-engine/src/backends/metal/kernel/matmul/matmul_metal_kernel.rs+++ b/crates/uzu-engine/src/backends/metal/kernel/matmul/matmul_metal_kernel.rs@@ -97,6 +97,7 @@ impl MatmulMetalKernel {return MatmulDispatch::Gemm(plan);}let tile = match (supports_mxu, shape.m) {+ (_, 2..=8) if shape.b_bits == Some(2) => None,(false, 2..=8) => Some(GemvTile::quantized_output_tile(4, 32, shape.m.min(4), 8, 1)),(true, 2..=4) => Some(GemvTile::quantized_output_tile(2, 16, shape.m, 8, 1)),_ => None,diff --git a/crates/uzu-engine/src/backends/slang/kernel/activation_transform/activation_transform.slang b/crates/uzu-engine/src/backends/slang/kernel/activation_transform/activation_transform.slangindex b45a250b8..30f3f7f83 100644--- a/crates/uzu-engine/src/backends/slang/kernel/activation_transform/activation_transform.slang+++ b/crates/uzu-engine/src/backends/slang/kernel/activation_transform/activation_transform.slang@@ -20,6 +20,7 @@ import generated.activation_transform;[[Specialize]] bool in_place,[[Specialize]] uint32_t activation_scale_group_size,[[Specialize]] uint32_t sum_group_size,+ [[Specialize]] uint32_t weight_bits,[[Specialize]] bool has_bias,[[Groups("element_count.div_ceil(4* 32* 4)")]] uint32_t activation_tile_index,[[Groups("batch_size")]] uint32_t batch_index,diff --git a/crates/uzu-engine/src/backends/slang/kernel/gated_act_mul/gated_act_mul.slang b/crates/uzu-engine/src/backends/slang/kernel/gated_act_mul/gated_act_mul.slangindex afc64b6ee..60de9999a 100644--- a/crates/uzu-engine/src/backends/slang/kernel/gated_act_mul/gated_act_mul.slang+++ b/crates/uzu-engine/src/backends/slang/kernel/gated_act_mul/gated_act_mul.slang@@ -29,6 +29,7 @@ import generated.gated_act_mul;[[Specialize]] bool use_hadamard,[[Specialize]] uint32_t activation_scale_group_size,[[Specialize]] uint32_t sum_group_size,+ [[Specialize]] uint32_t weight_bits,[[Specialize]] bool custom_activation_alpha,[[Specialize]] bool clip_gate,[[Specialize]] bool clip_value,diff --git a/crates/uzu-engine/src/encodable_block/linear/input_rht.rs b/crates/uzu-engine/src/encodable_block/linear/input_rht.rsindex 6ccb1a82f..286380555 100644--- a/crates/uzu-engine/src/encodable_block/linear/input_rht.rs+++ b/crates/uzu-engine/src/encodable_block/linear/input_rht.rs@@ -51,14 +51,16 @@ impl<B: Backend> InputRht<B> {if let Some(quantizer) = self.quantizer.as_ref().filter(|quantizer| quantizer.format() == format) {let input_dim = self.input_dim();if let ActivationFormat::PackedHalf {- group_size,+ block_k,+ bits,} = format{- let mut values = command_buffer.allocate_scratch(packed_half_bytes(input_dim, group_size))?;+ let mut values = command_buffer.allocate_scratch(packed_half_bytes(input_dim, block_k, bits))?;quantizer.encode_pack_half(input, &mut values, &self.rht_signs, batch_dim, input_dim, command_buffer);return Ok(MatmulA::PackedHalf {values,- group_size,+ block_k,+ bits,});}let ActivationFormat::Int8(quantization) = format else {diff --git a/crates/uzu-engine/src/encodable_block/mlp/gate_act_mul.rs b/crates/uzu-engine/src/encodable_block/mlp/gate_act_mul.rsindex 2a7847bc0..383110450 100644--- a/crates/uzu-engine/src/encodable_block/mlp/gate_act_mul.rs+++ b/crates/uzu-engine/src/encodable_block/mlp/gate_act_mul.rs@@ -67,10 +67,11 @@ impl<B: Backend> MlpGateActMulEncodable<B> {if let Some(kernel) = self.quantized_kernel.as_ref().filter(|kernel| kernel.format() == act_format) {let hadamard_factors = self.hadamard_factors.as_ref().expect("quantized input requires RHT factors");if let ActivationFormat::PackedHalf {- group_size,+ block_k,+ bits,} = act_format{- let mut values = command_buffer.allocate_scratch(packed_half_bytes(self.hidden_dim, group_size))?;+ let mut values = command_buffer.allocate_scratch(packed_half_bytes(self.hidden_dim, block_k, bits))?;kernel.encode_pack_half(fused_up,&mut values,@@ -82,7 +83,8 @@ impl<B: Backend> MlpGateActMulEncodable<B> {);return Ok(MatmulA::PackedHalf {values,- group_size,+ block_k,+ bits,});}let ActivationFormat::Int8(quantization) = act_format else {diff --git a/crates/uzu-engine/unit/backends/metal/kernel/matmul/quant_dispatch_test.rs b/crates/uzu-engine/unit/backends/metal/kernel/matmul/quant_dispatch_test.rsindex be35ca155..fa64a3a9a 100644--- a/crates/uzu-engine/unit/backends/metal/kernel/matmul/quant_dispatch_test.rs+++ b/crates/uzu-engine/unit/backends/metal/kernel/matmul/quant_dispatch_test.rs@@ -166,6 +166,11 @@ fn run_parity<T: DataTypeRepr + Float + Debug + Display>() {let context = block_on(MetalContext::new()).expect("Metal context");let input = QuantInput::<T>::new(m, k, n, group_size, bits, quant_method, 0);+ let input = if bits == 2 {+ input.with_one_group_per_row()+ } else {+ input+ };let unified = run_quant_metal::<T>(&context, &input, GemmBLayout::RowMajor, dispatch);let reference = run_quant_cpu::<T>(&input);@@ -191,6 +196,9 @@ fn run_parity<T: DataTypeRepr + Float + Debug + Display>(#[case::gs32_narrow_n_tail_zp(64, 256, 72, 32, 4, QuantizationMethod::ScaleZeroPoint)]#[case::gs32_narrow_n_tail_mlx(64, 256, 72, 32, 4, QuantizationMethod::ScaleBias)]#[case::gs32_narrow_n_tail_sym(64, 256, 40, 32, 8, QuantizationMethod::ScaleSymmetric)]+#[case::w2_tile8(16, 4096, 160, 128, 2, QuantizationMethod::ScaleBias)]+#[case::w2_tile32_m_tail(65, 1024, 200, 128, 2, QuantizationMethod::ScaleBias)]+#[case::w2_prefill(512, 4096, 256, 128, 2, QuantizationMethod::ScaleBias)]fn parity_bf16(#[case] m: u32,#[case] k: u32,@@ -229,6 +237,7 @@ fn parity_bf16_8bit_splitk(#[case::m8_gs32_4bit_mlx(8, 256, 64, 32, 4, QuantizationMethod::ScaleBias)]#[case::m3_w4_g32_zp_k1024(3, 1024, 72, 32, 4, QuantizationMethod::ScaleZeroPoint)]#[case::m3_w8_g32_sym_k1024(3, 1024, 72, 32, 8, QuantizationMethod::ScaleSymmetric)]+#[case::m1_w2(1, 1024, 96, 128, 2, QuantizationMethod::ScaleBias)]fn parity_gemv_bf16(#[case] m: u32,#[case] k: u32,@@ -757,6 +766,7 @@ fn gathered_gemv_reads_weight_layout_bf16(fn run_packed_half_pipeline(group_size: u32,+ bits: u32,gated: bool,(batch, n): (u32, u32),with_bias: bool,@@ -771,9 +781,13 @@ fn run_packed_half_pipeline(let signs = |len: u32| (0..len).map(|i| 1 - 2 * (i % 3 == 0) as i32).collect::<Vec<_>>();let factors = signs(k);let format = ActivationFormat::PackedHalf {- group_size,+ block_k: group_size,+ bits,};- let mut input = QuantInput::<bf16>::new(batch, k, n, group_size, 4, method, 19).with_group_output();+ let mut input = QuantInput::<bf16>::new(batch, k, n, group_size, bits, method, 19).with_group_output();+ if bits == 2 {+ input = input.with_one_group_per_row();+ }input.ab_scale = 0.75;input.output_bias = with_bias.then(|| (0..n).map(|i| bf16::from_f32(1.0 + 0.5 * (i % 3) as f32)).collect());input.output_rht_factors = with_rht.then(|| signs(n));@@ -785,7 +799,7 @@ fn run_packed_half_pipeline(let mut reference_a = create_buffer::<Metal, bf16>(&context, (batch * k) as usize);let mut gemm = GemmKernel::new(DataType::BF16, DataType::BF16, DataType::BF16);let output_work = MatmulOutputWork::new(&context, DataType::BF16, DataType::BF16).unwrap();- let mut packed = create_buffer::<Metal, u32>(&context, packed_half_bytes(k, group_size) / size_of::<u32>());+ let mut packed = create_buffer::<Metal, u32>(&context, packed_half_bytes(k, group_size, bits) / size_of::<u32>());let mut command_buffer = context.create_command_buffer(None, None).expect("Metal command buffer");if !gated {ActivationTransform::<Metal>::input_rht(&context, DataType::BF16, false).expect("RHT reference").encode_fp(@@ -830,7 +844,8 @@ fn run_packed_half_pipeline(let arguments = MatmulArguments {a: MatmulA::PackedHalf {values: &packed,- group_size,+ block_k: group_size,+ bits,},b: arguments.b,b_leading_dimension: arguments.b_leading_dimension,@@ -843,7 +858,11 @@ fn run_packed_half_pipeline(};let plan = GemmPlan {engine: GemmEngine::Simdgroup,- tiling: GemmTiling::Tile8x32x64_Simdgroups1x2x4,+ tiling: if bits == 2 {+ GemmTiling::Tile8x32x128_Simdgroups1x2x4+ } else {+ GemmTiling::Tile8x32x64_Simdgroups1x2x4+ },split_k,};gemm.encode_plan(arguments, plan, &output_work, &mut command_buffer).expect("prepared W4 GEMM");@@ -857,12 +876,14 @@ fn run_packed_half_pipeline(#[uzu_test]fn packed_half_producers_match_bf16_reference() {// Fused RHT rounds directly to half; the standalone reference stores BF16 first.- for (group, gated, n, bias, rht, cap, method, splits) in [- (32, false, (4, 72), false, false, None, ScaleZeroPoint, 2),- (64, false, (5, 64), true, false, None, ScaleBias, 1),- (32, true, (8, 64), true, true, None, ScaleZeroPoint, 1),- (64, true, (5, 64), true, false, Some(0.5), ScaleBias, 2),+ for (group, bits, gated, n, bias, rht, cap, method, splits) in [+ (32, 4, false, (4, 72), false, false, None, ScaleZeroPoint, 2),+ (64, 4, false, (5, 64), true, false, None, ScaleBias, 1),+ (32, 4, true, (8, 64), true, true, None, ScaleZeroPoint, 1),+ (64, 4, true, (5, 64), true, false, Some(0.5), ScaleBias, 2),+ (128, 2, false, (6, 64), true, true, None, ScaleBias, 1),+ (128, 2, true, (8, 64), true, false, Some(0.5), ScaleBias, 1),] {- run_packed_half_pipeline(group, gated, n, bias, rht, cap, method, splits);+ run_packed_half_pipeline(group, bits, gated, n, bias, rht, cap, method, splits);}}