Skip to content

armgit / uzu

Public Imported from GitHub
0

A high-performance inference engine for AI models

Cleanup matmul dispatch (1/n) (#688)

CCYehb7c757f6b9f6
diff --git a/crates/backend-uzu/src/backends/metal/kernel/matmul/gemm/kernel.rs b/crates/backend-uzu/src/backends/metal/kernel/matmul/gemm/kernel.rs
index b7a41f24b..2700cad70 100644
--- a/crates/backend-uzu/src/backends/metal/kernel/matmul/gemm/kernel.rs
+++ b/crates/backend-uzu/src/backends/metal/kernel/matmul/gemm/kernel.rs
@@ -1,17 +1,20 @@
use std::collections::{HashMap, hash_map::Entry};
-use super::specialization::GemmSpecialization;
+use super::{
+ GemmEngine, GemmPlan,
+ selection::{GemmProblem, outer_block_k},
+ specialization::GemmSpecialization,
+};
use crate::{
backends::{
common::{
Allocation, BufferArg, Encoder,
gpu_types::{
GemmParams,
- gemm::{GemmAPrologueKind, GemmAlignment, GemmBPrologueKind, GemmDTransform, GemmTiling},
+ gemm::{GemmAPrologueKind, GemmAlignment, GemmBPrologueKind, GemmDTransform},
},
kernel::{
ActivationTransform, TensorAddBiasKernel,
- activation_transform::ACTIVATION_SCALE_GROUP_SIZE,
matmul::{MatmulA, MatmulArguments, MatmulB, MatmulError, MatmulShape},
},
},
@@ -20,55 +23,11 @@ use crate::{
context::MetalContext,
error::MetalError,
kernel::{GemmMetalKernel, GemmSplitKReduceMetalKernel, TensorAddBiasMetalKernel},
- metal_extensions::DeviceExt,
},
},
data_type::DataType,
};
-fn split_k_target(
- a_is_int8: bool,
- tiling: GemmTiling,
- bits_per_b: Option<u32>,
-) -> u32 {
- match (a_is_int8, tiling, bits_per_b) {
- (true, GemmTiling::Tile32x64x256_Simdgroups2x2, Some(4)) => 512,
- (true, GemmTiling::Tile32x64x256_Simdgroups2x2, _) => 1024,
- (true, _, _) => 256,
- (false, _, _) => 512,
- }
-}
-
-const STAGE_WEIGHT_SCALE_MIN_GROUPS: u32 = 6;
-
-fn should_stage_weight_scales(
- tiling: GemmTiling,
- dispatch_k: u32,
- group_size: Option<u32>,
- bits_per_b: Option<u32>,
-) -> bool {
- if bits_per_b == Some(4) && group_size == Some(32) && tiling.block_m() <= 32 {
- return false;
- }
- tiling != GemmTiling::Tile32x64x256_Simdgroups2x2
- || group_size.is_none_or(|group_size| dispatch_k / group_size >= STAGE_WEIGHT_SCALE_MIN_GROUPS)
-}
-
-fn should_hoist_operand_addressing(
- tiling: GemmTiling,
- b_prologue: GemmBPrologueKind,
-) -> bool {
- let needs_correction =
- matches!(b_prologue, GemmBPrologueKind::ScaleBiasDequant | GemmBPrologueKind::ScaleZeroPointDequant);
- needs_correction || tiling != GemmTiling::Tile128x128x256_Simdgroups4x4
-}
-
-#[derive(Debug, Clone, Copy)]
-pub enum GemmDispatchPath {
- Simdgroup,
- Mxu,
-}
-
pub struct GemmKernel {
weights_data_type: DataType,
input_data_type: DataType,
@@ -80,7 +39,7 @@ pub struct GemmKernel {
}
impl GemmKernel {
- pub(crate) fn new(
+ pub fn new(
context: &MetalContext,
weights_data_type: DataType,
input_data_type: DataType,
@@ -146,105 +105,48 @@ impl GemmKernel {
}
}
- pub(crate) fn should_skip_gemv_for_mxu(
+ fn problem(
&self,
- shape: &MatmulShape,
- ) -> bool {
- if shape.gathered {
- // TODO: gathered GEMM
- return false;
- }
- match (shape.m, shape.n == shape.k, (self.weights_data_type, self.input_data_type, self.output_data_type)) {
- (4, true, (DataType::F32, DataType::F32, DataType::F32))
- | (5, _, (DataType::BF16, DataType::BF16, DataType::BF16)) => return false,
- _ => {},
- }
- match shape.m {
- 0..=3 => return false,
- 4 => {
- // The M4 MXU tile only uses a quarter of its rows; avoid it for wide-N shapes.
- let small_enough_for_mxu = shape.n <= 6144 && shape.k <= 9728;
- let k_dominates = shape.k > 3_u32.saturating_mul(shape.n);
- if !(small_enough_for_mxu || k_dominates) {
- return false;
- }
- },
- _ => {},
- }
- matches!(
- self.mxu_tiling_for(shape),
- Some(GemmTiling::Tile16x32x256_Simdgroups1x1 | GemmTiling::Tile16x128x256_Simdgroups1x4)
- )
+ shape: MatmulShape,
+ supports_mxu: bool,
+ ) -> GemmProblem {
+ GemmProblem::new(shape, self.weights_data_type, self.output_data_type, supports_mxu)
}
- /// Int8 activations always have an MXU tiling, so callers short-circuit before asking.
- fn mxu_tiling_for(
+ #[cfg(test)]
+ fn select_plan_for_engine(
&self,
shape: &MatmulShape,
- ) -> Option<GemmTiling> {
- if !shape.a_full_precision {
- return None;
- }
- if ![self.weights_data_type, self.input_data_type, self.output_data_type]
- .into_iter()
- .all(|data_type| matches!(data_type, DataType::BF16 | DataType::F32))
- {
- return None;
- }
-
- match shape.b_prologue {
- GemmBPrologueKind::FullPrecision => Some(if shape.b_transpose {
- mxu_tiling(shape.m, shape.n, shape.k)
- } else {
- mxu_tiling_by_mn(shape.m, shape.n)
- }),
- _ => {
- if !shape.b_transpose || shape.b_leading_dimension.is_some() {
- return None;
- }
- let tiling = mxu_quant_tiling(shape.m, shape.n, shape.b_group_size.unwrap_or(0), false);
- shape.k.is_multiple_of(tiling.block_k()).then_some(tiling)
- },
- }
+ engine: GemmEngine,
+ context: &MetalContext,
+ ) -> Result<GemmPlan, MetalError> {
+ self.problem(*shape, context.supports_mxu())
+ .select_plan_for_engine(engine)
+ .map_err(|error| MetalError::KernelDispatchFailed(Box::new(error)))
}
- pub fn encode<'a, 'b, 'd, TB: BufferArg<'b, Metal>>(
+ #[cfg(test)]
+ pub fn encode_with_engine<'a, 'b, 'd, TB: BufferArg<'b, Metal>>(
&mut self,
arguments: MatmulArguments<'a, 'b, 'd, Metal, TB>,
+ engine: GemmEngine,
encoder: &mut Encoder<Metal>,
) -> Result<(), MetalError> {
- let int8_activations = arguments.a.prologue_kind() == GemmAPrologueKind::Int8Symmetric;
- let path = if encoder.context().device.supports_mxu()
- && (int8_activations || self.mxu_tiling_for(&MatmulShape::from_arguments(&arguments)).is_some())
- {
- GemmDispatchPath::Mxu
- } else {
- GemmDispatchPath::Simdgroup
- };
- self.encode_dispatch_path(arguments, path, encoder)
+ let shape = MatmulShape::from_arguments(&arguments);
+ let plan = self.select_plan_for_engine(&shape, engine, encoder.context())?;
+ self.encode_plan(arguments, plan, encoder)
}
- pub fn encode_dispatch_path<'a, 'b, 'd, TB: BufferArg<'b, Metal>>(
+ pub fn encode_plan<'a, 'b, 'd, TB: BufferArg<'b, Metal>>(
&mut self,
arguments: MatmulArguments<'a, 'b, 'd, Metal, TB>,
- path: GemmDispatchPath,
+ plan: GemmPlan,
encoder: &mut Encoder<Metal>,
) -> Result<(), MetalError> {
- if matches!(path, GemmDispatchPath::Mxu) {
- assert!(
- encoder.context().device.supports_mxu(),
- "GemmDispatchPath::Mxu requested on hardware without MXU support",
- );
- assert!(
- [self.weights_data_type, self.input_data_type, self.output_data_type]
- .into_iter()
- .all(|data_type| matches!(data_type, DataType::BF16 | DataType::F32)),
- "GemmDispatchPath::Mxu requires BF16 or F32 data types, got weights {:?}, input {:?}, output {:?}",
- self.weights_data_type,
- self.input_data_type,
- self.output_data_type,
- );
- }
+ let shape = MatmulShape::from_arguments(&arguments);
+ self.problem(shape, encoder.context().supports_mxu())
+ .validate_engine(plan.engine)
+ .map_err(|error| MetalError::KernelDispatchFailed(Box::new(error)))?;
let is_quant = !matches!(arguments.b, MatmulB::FullPrecision { .. });
if is_quant {
@@ -256,12 +158,6 @@ impl GemmKernel {
}
.into());
}
- if !arguments.b_transpose || arguments.b_leading_dimension.is_some() {
- return Err(MatmulError::UnsupportedLayout {
- path: "QuantGemm",
- }
- .into());
- }
}
let ab_scale = arguments.d_transform.ab_scale;
@@ -286,7 +182,7 @@ impl GemmKernel {
..
} = arguments;
- let use_mxu = matches!(path, GemmDispatchPath::Mxu);
+ let use_mxu = plan.engine == GemmEngine::Mxu;
match b {
MatmulB::FullPrecision {
@@ -304,15 +200,7 @@ impl GemmKernel {
.into());
};
- let tiling = if use_mxu {
- if b_transpose {
- mxu_tiling(m, n, k)
- } else {
- mxu_tiling_by_mn(m, n)
- }
- } else {
- simdgroup_tiling(m, n, k)
- };
+ let tiling = plan.tiling;
let threadgroups_per_row = n.div_ceil(tiling.block_n());
let threadgroups_per_column = m.div_ceil(tiling.block_m());
@@ -336,51 +224,25 @@ impl GemmKernel {
let alignment =
GemmAlignment::new(m % tiling.block_m() == 0, n % tiling.block_n() == 0, k % tiling.block_k() == 0);
- if b_transpose && b_leading_dimension.is_none() {
- let split_k = select_split_k(
- m,
- n,
- k,
- tiling,
- use_mxu,
- false,
- 0,
- true,
- false,
- split_k_target(false, tiling, None),
+ if plan.split_k > 1 {
+ return self.encode_split_k(
+ MatmulA::FullPrecision {
+ values: a,
+ offset: a_offset,
+ },
+ weights,
+ None,
+ None,
+ None,
+ &mut *d,
+ ab_scale,
+ shape,
+ plan,
+ output_transform,
+ output_bias,
+ rht_factors,
+ encoder,
);
- if split_k > 1
- && split_k_output_supported(output_transform, n, self.weights_data_type, self.output_data_type)
- {
- return self.encode_split_k(
- Some((a, a_offset)),
- None,
- None,
- None,
- GemmAPrologueKind::FullPrecision,
- weights,
- None,
- None,
- None,
- &mut *d,
- m,
- n,
- k,
- ab_scale,
- use_mxu,
- tiling,
- b_prologue,
- bits_per_b,
- group_size,
- false,
- None,
- split_k,
- output_transform,
- output_bias,
- rht_factors,
- encoder,
- );
- }
}
let default_ldb = if b_transpose {
@@ -402,23 +264,15 @@ impl GemmKernel {
ab_scale,
};
- let specialization = GemmSpecialization {
- weights_data_type: self.weights_data_type,
- tiling,
- use_mxu,
+ let specialization = GemmSpecialization::from_plan(
+ plan,
+ shape,
+ self.weights_data_type,
output_transform,
alignment,
- transpose_b: b_transpose,
- b_prologue,
- bits_per_b,
- b_group_size: group_size,
- a_prologue: GemmAPrologueKind::FullPrecision,
- signed_codes: false,
- a_group_size: None,
- stage_weight_scales: true,
- hoist_operand_addressing: false,
- };
- specialization.validate()?;
+ GemmAPrologueKind::FullPrecision,
+ None,
+ )?;
let kernel = self.get_or_create(encoder.context(), specialization)?;
kernel.encode(
Some((a, a_offset)),
@@ -470,12 +324,11 @@ impl GemmKernel {
};
let a_prologue = a.prologue_kind();
- let a_is_int8 = a_prologue == GemmAPrologueKind::Int8Symmetric;
- let (a_full_precision, a_int8, a_scales, a_group_sums, a_group_size) = match a {
+ let (a_full_precision, a_int8, a_scales, a_group_sums, a_group_size) = match &a {
MatmulA::FullPrecision {
values,
offset,
- } => (Some((values, offset)), None, None, None, None),
+ } => (Some((*values, *offset)), None, None, None, None),
MatmulA::Int8Symmetric {
values,
scales: activation_scales,
@@ -489,7 +342,7 @@ impl GemmKernel {
b_prologue,
bits_per_b,
group_size,
- a_group_size,
+ *a_group_size,
)?;
if output_transform.contains(GemmDTransform::SOFT_CAP) {
return Err(MatmulError::UnsupportedDOp {
@@ -498,7 +351,7 @@ impl GemmKernel {
}
.into());
}
- (None, Some(values), Some(activation_scales), activation_group_sums, Some(a_group_size))
+ (None, Some(*values), Some(*activation_scales), *activation_group_sums, Some(*a_group_size))
},
};
@@ -509,80 +362,39 @@ impl GemmKernel {
(output_bias, None, output_transform)
};
- let tiling = if use_mxu {
- mxu_quant_tiling(m, n, group_size.unwrap_or(0), a_is_int8)
- } else {
- simdgroup_quant_tiling(m, n, group_size.unwrap_or(0))
- };
+ let tiling = plan.tiling;
let alignment =
GemmAlignment::new(m % tiling.block_m() == 0, n % tiling.block_n() == 0, k % tiling.block_k() == 0);
- let params = quant_params(m, n, k, tiling, use_mxu, group_size.unwrap_or(0), ab_scale);
+ let params = quant_params(shape, plan, ab_scale);
let group_count_x = n.div_ceil(tiling.block_n());
let group_count_y = m.div_ceil(tiling.block_m());
- let zero_point_4bit = zero_points.is_some() && bits_per_b == Some(4);
- let split_k_target = split_k_target(a_is_int8, tiling, bits_per_b);
- let split_k = select_split_k(
- m,
- n,
- k,
- tiling,
- use_mxu,
- a_is_int8 && use_mxu,
- group_size.unwrap_or(0),
- false,
- zero_point_4bit,
- split_k_target,
- );
- if split_k > 1
- && split_k_output_supported(output_transform, n, self.weights_data_type, self.output_data_type)
- {
+ if plan.split_k > 1 {
self.encode_split_k(
- a_full_precision,
- a_int8,
- a_scales,
- a_group_sums,
- a_prologue,
+ a,
weights,
scales,
biases,
zero_points,
&mut *d,
- m,
- n,
- k,
ab_scale,
- use_mxu,
- tiling,
- b_prologue,
- bits_per_b,
- group_size,
- weights_signed_codes,
- a_group_size,
- split_k,
+ shape,
+ plan,
output_transform,
output_bias,
rht_factors,
encoder,
)?;
} else {
- let specialization = GemmSpecialization {
- weights_data_type: self.weights_data_type,
- tiling,
- use_mxu,
+ let specialization = GemmSpecialization::from_plan(
+ plan,
+ shape,
+ self.weights_data_type,
output_transform,
alignment,
- transpose_b: true,
- b_prologue,
- bits_per_b,
- b_group_size: group_size,
a_prologue,
- signed_codes: weights_signed_codes,
a_group_size,
- stage_weight_scales: should_stage_weight_scales(tiling, k, group_size, bits_per_b),
- hoist_operand_addressing: should_hoist_operand_addressing(tiling, b_prologue),
- };
- specialization.validate()?;
+ )?;
let kernel = self.get_or_create(encoder.context(), specialization)?;
kernel.encode(
a_full_precision,
@@ -617,57 +429,55 @@ impl GemmKernel {
#[allow(clippy::too_many_arguments)]
fn encode_split_k<'a, 'b, WB: BufferArg<'b, Metal>>(
&mut self,
- a_full_precision: Option<(&Allocation<Metal>, usize)>,
- a_int8: Option<&Allocation<Metal>>,
- a_scales: Option<&Allocation<Metal>>,
- a_group_sums: Option<&Allocation<Metal>>,
- a_prologue: GemmAPrologueKind,
+ a: MatmulA<'a, Metal>,
weights: WB,
scales: Option<&Allocation<Metal>>,
biases: Option<&Allocation<Metal>>,
zero_points: Option<&Allocation<Metal>>,
d: &mut Allocation<Metal>,
- m: u32,
- n: u32,
- k: u32,
ab_scale: f32,
- use_mxu: bool,
- tiling: GemmTiling,
- b_prologue: GemmBPrologueKind,
- bits_per_b: Option<u32>,
- group_size: Option<u32>,
- signed_codes: bool,
- a_group_size: Option<u32>,
- split_k: u32,
+ shape: MatmulShape,
+ plan: GemmPlan,
output_transform: GemmDTransform,
output_bias: Option<&Allocation<Metal>>,
rht_factors: Option<&Allocation<Metal>>,
encoder: &mut Encoder<Metal>,
) -> Result<(), MetalError> {
- let full_precision = matches!(b_prologue, GemmBPrologueKind::FullPrecision);
+ let MatmulShape {
+ m,
+ n,
+ k,
+ ..
+ } = shape;
+ let (a_full_precision, a_int8, a_scales, a_group_sums, a_prologue, a_group_size) = match a {
+ MatmulA::FullPrecision {
+ values,
+ offset,
+ } => (Some((values, offset)), None, None, None, GemmAPrologueKind::FullPrecision, None),
+ MatmulA::Int8Symmetric {
+ values,
+ scales,
+ group_sums,
+ group_size,
+ } => (None, Some(values), Some(scales), group_sums, GemmAPrologueKind::Int8Symmetric, Some(group_size)),
+ };
+ let tiling = plan.tiling;
+ let split_k = plan.split_k;
let kp = k / split_k;
- let k_step = split_k_step(tiling, use_mxu, group_size.unwrap_or(0), full_precision).unwrap_or(1);
+ let k_step = outer_block_k(shape, plan.engine, plan.tiling).unwrap_or(1);
let base_gx = n.div_ceil(tiling.block_n());
let base_gy = m.div_ceil(tiling.block_m());
let alignment =
GemmAlignment::new(m.is_multiple_of(tiling.block_m()), n.is_multiple_of(tiling.block_n()), true);
- let part_spec = GemmSpecialization {
- weights_data_type: self.weights_data_type,
- tiling,
- use_mxu,
- output_transform: GemmDTransform::empty(),
+ let part_spec = GemmSpecialization::from_plan(
+ plan,
+ shape,
+ self.weights_data_type,
+ GemmDTransform::empty(),
alignment,
- transpose_b: true,
- b_prologue,
- bits_per_b,
- b_group_size: group_size,
a_prologue,
- signed_codes,
a_group_size,
- stage_weight_scales: should_stage_weight_scales(tiling, kp, group_size, bits_per_b),
- hoist_operand_addressing: should_hoist_operand_addressing(tiling, b_prologue),
- };
- part_spec.validate()?;
+ )?;
let elem = (m as usize) * (n as usize);
let slice_bytes = elem * self.output_data_type.size_in_bytes();
@@ -764,14 +574,17 @@ fn validate_int8_activation_arguments(
}
fn quant_params(
- m: u32,
- n: u32,
- k: u32,
- tiling: GemmTiling,
- use_mxu: bool,
- group_size: u32,
+ shape: MatmulShape,
+ plan: GemmPlan,
ab_scale: f32,
) -> GemmParams {
+ let MatmulShape {
+ m,
+ n,
+ k,
+ ..
+ } = shape;
+ let tiling = plan.tiling;
GemmParams {
M: m,
N: n,
@@ -781,197 +594,8 @@ fn quant_params(
leading_dimension_d: n,
threadgroups_per_row: n.div_ceil(tiling.block_n()),
threadgroups_per_column: m.div_ceil(tiling.block_m()),
- aligned_inner_iterations: split_k_step(tiling, use_mxu, group_size, false).map_or(0, |step| k / step),
+ aligned_inner_iterations: outer_block_k(shape, plan.engine, plan.tiling).map_or(0, |step| k / step),
use_morton: false,
ab_scale,
}
}
-
-fn split_k_step(
- tiling: GemmTiling,
- use_mxu: bool,
- group_size: u32,
- full_precision: bool,
-) -> Option<u32> {
- let step = if use_mxu && !full_precision {
- group_size
- } else {
- tiling.block_k()
- };
- (step != 0).then_some(step)
-}
-
-fn split_k_output_supported(
- output_transform: GemmDTransform,
- n: u32,
- weights_data_type: DataType,
- output_data_type: DataType,
-) -> bool {
- if !output_transform.contains(GemmDTransform::BIAS) {
- return true;
- }
- n.is_multiple_of(4) && weights_data_type == output_data_type
-}
-
-fn select_split_k(
- m: u32,
- n: u32,
- k: u32,
- tiling: GemmTiling,
- use_mxu: bool,
- floor_split_k_to_tile_block: bool,
- group_size: u32,
- full_precision: bool,
- zero_point_4bit: bool,
- target_tiles: u32,
-) -> u32 {
- let base_tiles = n.div_ceil(tiling.block_n()) * m.div_ceil(tiling.block_m());
- if base_tiles == 0 {
- return 1;
- }
- if !((m as u64) * (n as u64)).is_multiple_of(4) {
- return 1;
- }
- let mut split_k = (target_tiles / base_tiles).max(1);
- let step = match split_k_step(tiling, use_mxu, group_size, full_precision) {
- Some(s) => s,
- None => return 1,
- };
- let mut align = if use_mxu || full_precision {
- step
- } else {
- step.max(group_size)
- };
- if zero_point_4bit {
- align = align.max(2 * group_size);
- }
- align = align.max(ACTIVATION_SCALE_GROUP_SIZE).max(group_size);
- split_k = split_k.min((k / align).max(1));
- if floor_split_k_to_tile_block && tiling.block_k() != 0 {
- split_k = split_k.min((k / tiling.block_k()).max(1));
- }
- while split_k > 1 && !k.is_multiple_of(split_k * align) {
- split_k -= 1;
- }
- split_k
-}
-
-pub(crate) fn simdgroup_tiling(
- m: u32,
- n: u32,
- k: u32,
-) -> GemmTiling {
- if 2 * m.max(n) > k {
- GemmTiling::Tile64x64x16_Simdgroups2x2
- } else {
- GemmTiling::Tile64x32x32_Simdgroups2x2
- }
-}
-
-pub(crate) fn mxu_tiling(
- m: u32,
- n: u32,
- k: u32,
-) -> GemmTiling {
- if m < 64 && n >= 64 {
- if n == k {
- return if m < 16 && k <= 2560 {
- GemmTiling::Tile16x32x256_Simdgroups1x1
- } else {
- GemmTiling::Tile32x64x256_Simdgroups2x2
- };
- }
- return if m < 16 {
- mxu_tiling_small_m(n, k)
- } else {
- mxu_tiling_by_mn(m, n)
- };
- }
- mxu_tiling_by_mn(m, n)
-}
-
-fn mxu_tiling_by_mn(
- m: u32,
- n: u32,
-) -> GemmTiling {
- if m >= 256 && n >= 128 {
- GemmTiling::Tile128x128x256_Simdgroups4x4
- } else if n < 64 {
- GemmTiling::Tile64x32x256_Simdgroups4x1
- } else if m < 64 {
- GemmTiling::Tile32x64x256_Simdgroups2x2
- } else {
- GemmTiling::Tile64x64x256_Simdgroups2x2
- }
-}
-
-fn mxu_tiling_small_m(
- n: u32,
- k: u32,
-) -> GemmTiling {
- if k > n {
- return GemmTiling::Tile16x128x256_Simdgroups1x4;
- }
- if n > 32_u32.saturating_mul(k) {
- return GemmTiling::Tile16x32x256_Simdgroups1x1;
- }
- if (k >= 4096 && n >= 4_u32.saturating_mul(k)) || (k == 2560 && n >= 6_u32.saturating_mul(k)) {
- return GemmTiling::Tile16x128x256_Simdgroups1x4;
- }
- GemmTiling::Tile32x64x256_Simdgroups2x2
-}
-
-fn int8_mxu_tiling(
- m: u32,
- n: u32,
-) -> GemmTiling {
- if n < 64 {
- return GemmTiling::Tile64x32x256_Simdgroups4x1;
- }
- if m <= 16 {
- return GemmTiling::Tile16x128x256_Simdgroups1x4;
- }
- if m < 64 {
- return GemmTiling::Tile32x64x256_Simdgroups2x2;
- }
- if m >= 512 {
- return GemmTiling::Tile128x128x256_Simdgroups4x4;
- }
- GemmTiling::Tile64x64x256_Simdgroups2x2
-}
-
-pub(crate) fn mxu_quant_tiling(
- m: u32,
- n: u32,
- group_size: u32,
- int8_activations: bool,
-) -> GemmTiling {
- let tiling = if int8_activations {
- int8_mxu_tiling(m, n)
- } else {
- mxu_tiling_by_mn(m, n)
- };
- if tiling.fits_quant_group_size(group_size) {
- tiling
- } else {
- GemmTiling::Tile64x64x256_Simdgroups2x2
- }
-}
-
-pub(crate) fn simdgroup_quant_tiling(
- m: u32,
- n: u32,
- group_size: u32,
-) -> GemmTiling {
- if group_size < 32 {
- GemmTiling::Tile64x64x16_Simdgroups2x2
- } else if m < 32 {
- GemmTiling::Tile8x32x32_Simdgroups1x1
- } else if m >= 64 && n <= 2048 {
- GemmTiling::Tile32x32x32_Simdgroups2x2
- } else if m >= 64 && n >= 6144 && n.is_multiple_of(64) {
- GemmTiling::Tile64x64x32_Simdgroups2x2
- } else {
- GemmTiling::Tile32x32x32_Simdgroups2x2
- }
-}
diff --git a/crates/backend-uzu/src/backends/metal/kernel/matmul/gemm/mod.rs b/crates/backend-uzu/src/backends/metal/kernel/matmul/gemm/mod.rs
index 3841e73d9..1e5091984 100644
--- a/crates/backend-uzu/src/backends/metal/kernel/matmul/gemm/mod.rs
+++ b/crates/backend-uzu/src/backends/metal/kernel/matmul/gemm/mod.rs
@@ -1,6 +1,24 @@
mod error;
mod kernel;
+mod policy;
+mod selection;
mod specialization;
pub use error::GemmSpecializationError;
-pub use kernel::{GemmDispatchPath, GemmKernel};
+pub use kernel::GemmKernel;
+pub(super) use selection::GemmProblem;
+
+use crate::backends::common::gpu_types::gemm::GemmTiling;
+
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub enum GemmEngine {
+ Simdgroup,
+ Mxu,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub struct GemmPlan {
+ pub(super) engine: GemmEngine,
+ pub(super) tiling: GemmTiling,
+ pub(super) split_k: u32,
+}
diff --git a/crates/backend-uzu/src/backends/metal/kernel/matmul/gemm/policy.rs b/crates/backend-uzu/src/backends/metal/kernel/matmul/gemm/policy.rs
new file mode 100644
index 000000000..45ee8aa2f
--- /dev/null
+++ b/crates/backend-uzu/src/backends/metal/kernel/matmul/gemm/policy.rs
@@ -0,0 +1,125 @@
+//! Tuned GEMM tile and split-K policy.
+//!
+//! These functions are the retunable part of GEMM dispatch: they map shape
+//! features to choices. Eligibility, fallbacks, and legality stay in
+//! `selection.rs`.
+
+use crate::backends::common::gpu_types::gemm::GemmTiling;
+
+pub(super) const MXU_DEFAULT_TILE: GemmTiling = GemmTiling::Tile64x64x256_Simdgroups2x2;
+
+const MXU_SKINNY_M_MAX: u32 = 16;
+const SKINNY_SQUARE_K_MAX: u32 = 2560;
+const READOUT_N_TO_K_RATIO: u32 = 32;
+const WIDE_N_DEEP_K_MIN: u32 = 4096;
+const WIDE_N_DEEP_K_RATIO: u32 = 4;
+const WIDE_N_MODERATE_K: u32 = 2560;
+const WIDE_N_MODERATE_K_RATIO: u32 = 6;
+
+const MXU_M_BUCKET_MAXES: [u32; 4] = [16, 63, 255, 511];
+const MXU_N_BUCKET_MAXES: [u32; 2] = [63, 127];
+
+const SIMDGROUP_QUANT_SMALL_M_MAX: u32 = 32;
+const SIMDGROUP_QUANT_LARGE_M_MIN: u32 = 64;
+const SIMDGROUP_QUANT_WIDE_N_MIN: u32 = 6144;
+
+const SPLIT_K_TARGET_TILES_FP: u32 = 512;
+const SPLIT_K_TARGET_TILES_A8: u32 = 256;
+const SPLIT_K_TARGET_TILES_A8_TILE32_W4: u32 = 512;
+const SPLIT_K_TARGET_TILES_A8_TILE32_W8: u32 = 1024;
+
+fn bucket(
+ value: u32,
+ bucket_maxes: &[u32],
+) -> usize {
+ bucket_maxes.partition_point(|&max| value > max)
+}
+
+pub(super) fn mxu_mn_tile(
+ is_a_int8: bool,
+ m: u32,
+ n: u32,
+) -> GemmTiling {
+ match (is_a_int8, bucket(m, &MXU_M_BUCKET_MAXES), bucket(n, &MXU_N_BUCKET_MAXES)) {
+ (_, _, 0) => GemmTiling::Tile64x32x256_Simdgroups4x1,
+ (false, 0..=1, _) => GemmTiling::Tile32x64x256_Simdgroups2x2,
+ (false, 3..=4, 2) => GemmTiling::Tile128x128x256_Simdgroups4x4,
+ (true, 0, _) => GemmTiling::Tile16x128x256_Simdgroups1x4,
+ (true, 1, _) => GemmTiling::Tile32x64x256_Simdgroups2x2,
+ (true, 4, _) => GemmTiling::Tile128x128x256_Simdgroups4x4,
+ _ => MXU_DEFAULT_TILE,
+ }
+}
+
+pub(super) fn mxu_fp_tile(
+ m: u32,
+ n: u32,
+ k: u32,
+) -> GemmTiling {
+ if m >= 64 || n < 64 {
+ return mxu_mn_tile(false, m, n);
+ }
+ if n == k {
+ return if m < MXU_SKINNY_M_MAX && k <= SKINNY_SQUARE_K_MAX {
+ GemmTiling::Tile16x32x256_Simdgroups1x1
+ } else {
+ GemmTiling::Tile32x64x256_Simdgroups2x2
+ };
+ }
+ if m >= MXU_SKINNY_M_MAX {
+ return mxu_mn_tile(false, m, n);
+ }
+ if k > n {
+ return GemmTiling::Tile16x128x256_Simdgroups1x4;
+ }
+ if n > READOUT_N_TO_K_RATIO.saturating_mul(k) {
+ return GemmTiling::Tile16x32x256_Simdgroups1x1;
+ }
+ if (k >= WIDE_N_DEEP_K_MIN && n >= WIDE_N_DEEP_K_RATIO.saturating_mul(k))
+ || (k == WIDE_N_MODERATE_K && n >= WIDE_N_MODERATE_K_RATIO.saturating_mul(k))
+ {
+ return GemmTiling::Tile16x128x256_Simdgroups1x4;
+ }
+ GemmTiling::Tile32x64x256_Simdgroups2x2
+}
+
+pub(super) fn simdgroup_fp_tile(
+ m: u32,
+ n: u32,
+ k: u32,
+) -> GemmTiling {
+ if 2_u32.saturating_mul(m.max(n)) > k {
+ GemmTiling::Tile64x64x16_Simdgroups2x2
+ } else {
+ GemmTiling::Tile64x32x32_Simdgroups2x2
+ }
+}
+
+pub(super) fn simdgroup_quant_tile(
+ m: u32,
+ n: u32,
+ group_size: u32,
+) -> GemmTiling {
+ if group_size < 32 {
+ GemmTiling::Tile64x64x16_Simdgroups2x2
+ } else if m < SIMDGROUP_QUANT_SMALL_M_MAX {
+ GemmTiling::Tile8x32x32_Simdgroups1x1
+ } else if m >= SIMDGROUP_QUANT_LARGE_M_MIN && n >= SIMDGROUP_QUANT_WIDE_N_MIN && n.is_multiple_of(64) {
+ GemmTiling::Tile64x64x32_Simdgroups2x2
+ } else {
+ GemmTiling::Tile32x32x32_Simdgroups2x2
+ }
+}
+
+pub(super) fn split_k_target_tiles(
+ is_a_int8: bool,
+ tiling: GemmTiling,
+ b_bits: Option<u32>,
+) -> u32 {
+ match (is_a_int8, tiling, b_bits) {
+ (true, GemmTiling::Tile32x64x256_Simdgroups2x2, Some(4)) => SPLIT_K_TARGET_TILES_A8_TILE32_W4,
+ (true, GemmTiling::Tile32x64x256_Simdgroups2x2, _) => SPLIT_K_TARGET_TILES_A8_TILE32_W8,
+ (true, _, _) => SPLIT_K_TARGET_TILES_A8,
+ (false, _, _) => SPLIT_K_TARGET_TILES_FP,
+ }
+}
diff --git a/crates/backend-uzu/src/backends/metal/kernel/matmul/gemm/selection.rs b/crates/backend-uzu/src/backends/metal/kernel/matmul/gemm/selection.rs
new file mode 100644
index 000000000..8c341ac44
--- /dev/null
+++ b/crates/backend-uzu/src/backends/metal/kernel/matmul/gemm/selection.rs
@@ -0,0 +1,185 @@
+use thiserror::Error;
+
+use super::{GemmEngine, GemmPlan, policy};
+use crate::{
+ backends::common::{
+ gpu_types::gemm::{GemmBPrologueKind, GemmTiling},
+ kernel::{activation_transform::ACTIVATION_SCALE_GROUP_SIZE, matmul::MatmulShape},
+ },
+ data_type::DataType,
+};
+
+#[derive(Clone, Copy)]
+pub struct GemmProblem {
+ shape: MatmulShape,
+ weights_data_type: DataType,
+ output_data_type: DataType,
+ supports_mxu: bool,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Error)]
+pub(super) enum GemmPlanError {
+ #[error("MXU engine is not available for this GEMM")]
+ MxuUnavailable,
+ #[error("quantized GEMM requires transposed contiguous B")]
+ UnsupportedQuantLayout,
+}
+
+impl GemmProblem {
+ pub fn new(
+ shape: MatmulShape,
+ weights_data_type: DataType,
+ output_data_type: DataType,
+ supports_mxu: bool,
+ ) -> Self {
+ Self {
+ shape,
+ weights_data_type,
+ output_data_type,
+ supports_mxu,
+ }
+ }
+
+ pub fn select_plan(self) -> GemmPlan {
+ let engine = if self.supports_mxu && mxu_is_eligible(self.shape) {
+ GemmEngine::Mxu
+ } else {
+ GemmEngine::Simdgroup
+ };
+ self.finish_plan(engine, select_tiling(self.shape, engine))
+ }
+
+ #[cfg(test)]
+ pub(super) fn select_plan_for_engine(
+ self,
+ engine: GemmEngine,
+ ) -> Result<GemmPlan, GemmPlanError> {
+ self.validate_engine(engine)?;
+ Ok(self.finish_plan(engine, select_tiling(self.shape, engine)))
+ }
+
+ pub(super) fn validate_engine(
+ &self,
+ engine: GemmEngine,
+ ) -> Result<(), GemmPlanError> {
+ if engine == GemmEngine::Mxu && !self.supports_mxu {
+ return Err(GemmPlanError::MxuUnavailable);
+ }
+ if self.shape.is_quant() && (!self.shape.b_transpose || self.shape.b_leading_dimension.is_some()) {
+ return Err(GemmPlanError::UnsupportedQuantLayout);
+ }
+ Ok(())
+ }
+
+ fn finish_plan(
+ &self,
+ engine: GemmEngine,
+ tiling: GemmTiling,
+ ) -> GemmPlan {
+ GemmPlan {
+ engine,
+ tiling,
+ split_k: self.select_split_k(engine, tiling),
+ }
+ }
+
+ fn select_split_k(
+ &self,
+ engine: GemmEngine,
+ tiling: GemmTiling,
+ ) -> 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() {
+ return 1;
+ }
+ let base_tiles = shape.n.div_ceil(tiling.block_n()).saturating_mul(shape.m.div_ceil(tiling.block_m()));
+ if base_tiles == 0 || !((shape.m as u64) * (shape.n as u64)).is_multiple_of(4) {
+ return 1;
+ }
+ let Some(step) = outer_block_k(shape, engine, tiling) else {
+ return 1;
+ };
+ let group_size = shape.b_group_size.unwrap_or(0);
+ let mut align = if engine == GemmEngine::Mxu || !shape.is_quant() {
+ step
+ } else {
+ step.max(group_size)
+ };
+ if shape.b_prologue == GemmBPrologueKind::ScaleZeroPointDequant && shape.b_bits == Some(4) {
+ align = align.max(2_u32.saturating_mul(group_size));
+ }
+ let align = align.max(ACTIVATION_SCALE_GROUP_SIZE).max(group_size);
+ let target_tiles = policy::split_k_target_tiles(!shape.a_full_precision, tiling, shape.b_bits);
+ let mut split_k = (target_tiles / base_tiles).max(1).min((shape.k / align).max(1));
+ if !shape.a_full_precision && engine == GemmEngine::Mxu && tiling.block_k() != 0 {
+ split_k = split_k.min((shape.k / tiling.block_k()).max(1));
+ }
+ while split_k > 1 && !shape.k.is_multiple_of(split_k * align) {
+ split_k -= 1;
+ }
+ split_k
+ }
+
+ fn split_k_output_supported(&self) -> bool {
+ use crate::backends::common::gpu_types::gemm::GemmDTransform;
+
+ let mut output_transform = self.shape.d_transform;
+ if self.shape.is_quant()
+ && output_transform.contains(GemmDTransform::RHT)
+ && output_transform.contains(GemmDTransform::BIAS)
+ {
+ output_transform.remove(GemmDTransform::BIAS);
+ }
+ !output_transform.contains(GemmDTransform::BIAS)
+ || (self.shape.n.is_multiple_of(4) && self.weights_data_type == self.output_data_type)
+ }
+}
+
+pub(super) fn outer_block_k(
+ shape: MatmulShape,
+ engine: GemmEngine,
+ tiling: GemmTiling,
+) -> Option<u32> {
+ if engine == GemmEngine::Mxu && shape.is_quant() {
+ shape.b_group_size.filter(|&group_size| group_size != 0)
+ } else {
+ Some(tiling.block_k()).filter(|&block_k| block_k != 0)
+ }
+}
+
+fn mxu_is_eligible(shape: MatmulShape) -> bool {
+ if !shape.a_full_precision || shape.b_prologue == GemmBPrologueKind::FullPrecision {
+ return true;
+ }
+ shape.b_transpose
+ && shape.b_leading_dimension.is_none()
+ && shape.k.is_multiple_of(select_mxu_quant_tiling(shape).block_k())
+}
+
+fn select_tiling(
+ shape: MatmulShape,
+ engine: GemmEngine,
+) -> GemmTiling {
+ match engine {
+ GemmEngine::Simdgroup if shape.is_quant() => {
+ policy::simdgroup_quant_tile(shape.m, shape.n, shape.b_group_size.unwrap_or(0))
+ },
+ GemmEngine::Simdgroup => policy::simdgroup_fp_tile(shape.m, shape.n, shape.k),
+ GemmEngine::Mxu if !shape.a_full_precision || shape.is_quant() => select_mxu_quant_tiling(shape),
+ GemmEngine::Mxu if shape.b_transpose => policy::mxu_fp_tile(shape.m, shape.n, shape.k),
+ GemmEngine::Mxu => policy::mxu_mn_tile(false, shape.m, shape.n),
+ }
+}
+
+fn select_mxu_quant_tiling(shape: MatmulShape) -> GemmTiling {
+ let tiling = policy::mxu_mn_tile(!shape.a_full_precision, shape.m, shape.n);
+ if tiling.fits_quant_group_size(shape.b_group_size.unwrap_or(0)) {
+ tiling
+ } else {
+ policy::MXU_DEFAULT_TILE
+ }
+}
+#[cfg(test)]
+#[path = "../../../../../../tests/unit/backends/metal/kernel/matmul/gemm/selection_test.rs"]
+mod tests;
diff --git a/crates/backend-uzu/src/backends/metal/kernel/matmul/gemm/specialization.rs b/crates/backend-uzu/src/backends/metal/kernel/matmul/gemm/specialization.rs
index 8d889b3d4..ad6514ac5 100644
--- a/crates/backend-uzu/src/backends/metal/kernel/matmul/gemm/specialization.rs
+++ b/crates/backend-uzu/src/backends/metal/kernel/matmul/gemm/specialization.rs
@@ -1,11 +1,14 @@
-use super::error::GemmSpecializationError;
+use super::{GemmEngine, GemmPlan, error::GemmSpecializationError};
use crate::{
- backends::common::gpu_types::gemm::{
- GemmAPrologueKind, GemmAlignment, GemmBPrologueKind, GemmDTransform, GemmTiling,
+ backends::common::{
+ gpu_types::gemm::{GemmAPrologueKind, GemmAlignment, GemmBPrologueKind, GemmDTransform, GemmTiling},
+ kernel::matmul::MatmulShape,
},
data_type::DataType,
};
+const STAGE_WEIGHT_SCALE_MIN_GROUPS: u32 = 6;
+
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(super) struct GemmSpecialization {
pub(super) weights_data_type: DataType,
@@ -25,6 +28,40 @@ pub(super) struct GemmSpecialization {
}
impl GemmSpecialization {
+ pub(super) fn from_plan(
+ plan: GemmPlan,
+ shape: MatmulShape,
+ weights_data_type: DataType,
+ output_transform: GemmDTransform,
+ alignment: GemmAlignment,
+ a_prologue: GemmAPrologueKind,
+ a_group_size: Option<u32>,
+ ) -> Result<Self, GemmSpecializationError> {
+ let use_tuned_addressing = shape.is_quant() || plan.split_k > 1;
+ let specialization = Self {
+ weights_data_type,
+ tiling: plan.tiling,
+ use_mxu: plan.engine == GemmEngine::Mxu,
+ output_transform,
+ alignment,
+ transpose_b: shape.b_transpose,
+ a_prologue,
+ b_prologue: shape.b_prologue,
+ bits_per_b: shape.b_bits,
+ b_group_size: shape.b_group_size,
+ signed_codes: shape.signed_codes,
+ a_group_size,
+ stage_weight_scales: if use_tuned_addressing {
+ plan.should_stage_weight_scales(shape)
+ } else {
+ true
+ },
+ hoist_operand_addressing: use_tuned_addressing && plan.should_hoist_operand_addressing(shape),
+ };
+ specialization.validate()?;
+ Ok(specialization)
+ }
+
pub(super) fn validate(&self) -> Result<(), GemmSpecializationError> {
let valid_activation_group = match self.a_prologue {
GemmAPrologueKind::FullPrecision => self.a_group_size.is_none(),
@@ -68,3 +105,30 @@ impl GemmSpecialization {
Ok(())
}
}
+
+impl GemmPlan {
+ pub(super) fn should_stage_weight_scales(
+ self,
+ shape: MatmulShape,
+ ) -> bool {
+ if shape.b_bits == Some(4) && shape.b_group_size == Some(32) && self.tiling.block_m() <= 32 {
+ return false;
+ }
+ if self.tiling == GemmTiling::Tile32x64x256_Simdgroups2x2 {
+ return shape
+ .b_group_size
+ .is_none_or(|group_size| shape.k / self.split_k / group_size >= STAGE_WEIGHT_SCALE_MIN_GROUPS);
+ }
+ true
+ }
+
+ pub(super) fn should_hoist_operand_addressing(
+ self,
+ shape: MatmulShape,
+ ) -> bool {
+ if matches!(shape.b_prologue, GemmBPrologueKind::ScaleBiasDequant | GemmBPrologueKind::ScaleZeroPointDequant) {
+ return true;
+ }
+ self.tiling != GemmTiling::Tile128x128x256_Simdgroups4x4
+ }
+}
diff --git a/crates/backend-uzu/src/backends/metal/kernel/matmul/mod.rs b/crates/backend-uzu/src/backends/metal/kernel/matmul/mod.rs
index 8d9f05d9d..03ade8771 100644
--- a/crates/backend-uzu/src/backends/metal/kernel/matmul/mod.rs
+++ b/crates/backend-uzu/src/backends/metal/kernel/matmul/mod.rs
@@ -1,15 +1,19 @@
pub mod gemm;
pub mod gemv;
-pub use self::gemm::{GemmDispatchPath, GemmKernel};
-use self::gemv::{GemvDispatch, GemvSpecialization};
+pub use self::gemm::GemmKernel;
+use self::{
+ gemm::{GemmPlan, GemmProblem},
+ gemv::{GemvDispatch, GemvSpecialization},
+};
use crate::{
backends::{
common::{
BufferArg, Encoder,
+ gpu_types::gemm::GemmTiling,
kernel::matmul::{MatmulArguments, MatmulError, MatmulKernel, MatmulPath, MatmulShape},
},
- metal::{Metal, context::MetalContext, error::MetalError, metal_extensions::DeviceExt},
+ metal::{Metal, context::MetalContext, error::MetalError},
},
data_type::DataType,
};
@@ -22,22 +26,70 @@ pub struct MatmulMetalKernel {
output_data_type: DataType,
}
+enum MatmulDispatch {
+ Gemv(GemvSpecialization),
+ Gemm(GemmPlan),
+}
+
impl MatmulMetalKernel {
- fn gemv_specialization(
+ fn prefer_gemm_over_gemv(
+ shape: MatmulShape,
+ plan: GemmPlan,
+ weights_data_type: DataType,
+ input_data_type: DataType,
+ output_data_type: DataType,
+ ) -> bool {
+ if shape.gathered || plan.engine != gemm::GemmEngine::Mxu {
+ return false;
+ }
+ match (shape.m, shape.n == shape.k, (weights_data_type, input_data_type, output_data_type)) {
+ (4, true, (DataType::F32, DataType::F32, DataType::F32))
+ | (5, _, (DataType::BF16, DataType::BF16, DataType::BF16)) => return false,
+ _ => {},
+ }
+ match shape.m {
+ 0..=3 => return false,
+ 4 => {
+ let small_enough_for_mxu = shape.n <= 6144 && shape.k <= 9728;
+ let k_dominates = shape.k > 3_u32.saturating_mul(shape.n);
+ if !(small_enough_for_mxu || k_dominates) {
+ return false;
+ }
+ },
+ _ => {},
+ }
+ matches!(plan.tiling, GemmTiling::Tile16x32x256_Simdgroups1x1 | GemmTiling::Tile16x128x256_Simdgroups1x4)
+ }
+
+ fn select_dispatch(
&self,
shape: &MatmulShape,
context: &MetalContext,
- ) -> Option<GemvSpecialization> {
- if context.device.supports_mxu() && self.gemm.should_skip_gemv_for_mxu(shape) {
- return None;
- }
- GemvSpecialization::select_shape(
+ ) -> MatmulDispatch {
+ let gemv = GemvSpecialization::select_shape(
shape,
self.weights_data_type,
self.input_data_type,
self.output_data_type,
context.device_tier(),
- )
+ );
+ let problem = GemmProblem::new(*shape, self.weights_data_type, self.output_data_type, context.supports_mxu());
+ let plan = problem.select_plan();
+ match gemv {
+ None => MatmulDispatch::Gemm(plan),
+ Some(_)
+ if Self::prefer_gemm_over_gemv(
+ *shape,
+ plan,
+ self.weights_data_type,
+ self.input_data_type,
+ self.output_data_type,
+ ) =>
+ {
+ MatmulDispatch::Gemm(plan)
+ },
+ Some(gemv) => MatmulDispatch::Gemv(gemv),
+ }
}
}
@@ -73,10 +125,9 @@ impl MatmulKernel for MatmulMetalKernel {
shape: &MatmulShape,
context: &MetalContext,
) -> MatmulPath {
- if self.gemv_specialization(shape, context).is_some() {
- MatmulPath::Gemv
- } else {
- MatmulPath::Gemm
+ match self.select_dispatch(shape, context) {
+ MatmulDispatch::Gemv(_) => MatmulPath::Gemv,
+ MatmulDispatch::Gemm(_) => MatmulPath::Gemm,
}
}
@@ -86,9 +137,12 @@ impl MatmulKernel for MatmulMetalKernel {
encoder: &mut Encoder<Metal>,
) -> Result<(), MetalError> {
let shape = MatmulShape::from_arguments(&arguments);
- if let Some(gemv) = self.gemv_specialization(&shape, encoder.context()) {
- return self.gemv.encode(arguments, gemv, encoder).map_err(MetalError::from);
- }
+ let plan = match self.select_dispatch(&shape, encoder.context()) {
+ MatmulDispatch::Gemv(gemv) => {
+ return self.gemv.encode(arguments, gemv, encoder).map_err(MetalError::from);
+ },
+ MatmulDispatch::Gemm(plan) => plan,
+ };
// TODO: remove after GatherGEMM is supported
if arguments.gather_indices.is_some() {
@@ -100,6 +154,6 @@ impl MatmulKernel for MatmulMetalKernel {
.into(),
));
}
- self.gemm.encode(arguments, encoder)
+ self.gemm.encode_plan(arguments, plan, encoder)
}
}
diff --git a/crates/backend-uzu/src/backends/metal/mod.rs b/crates/backend-uzu/src/backends/metal/mod.rs
index 045b68c00..a8917c48a 100644
--- a/crates/backend-uzu/src/backends/metal/mod.rs
+++ b/crates/backend-uzu/src/backends/metal/mod.rs
@@ -21,6 +21,7 @@ pub use backend::Metal;
pub use context::MetalContext;
#[cfg(test)]
pub(crate) use device_tier::DeviceTier;
-pub use kernel::matmul::GemmDispatchPath;
+#[cfg(test)]
+pub use kernel::matmul::gemm::GemmEngine;
#[cfg(test)]
pub(crate) use kernel::matmul::gemv::{GemvDispatch, GemvSpecialization};
diff --git a/crates/backend-uzu/src/tests/matmul/harness.rs b/crates/backend-uzu/src/tests/matmul/harness.rs
index d491ac229..8dd541ab7 100644
--- a/crates/backend-uzu/src/tests/matmul/harness.rs
+++ b/crates/backend-uzu/src/tests/matmul/harness.rs
@@ -2,7 +2,7 @@ use num_traits::Float;
use super::Shape;
#[cfg(backend = "metal")]
-use crate::backends::metal::{GemmDispatchPath, Metal, MetalContext};
+use crate::backends::metal::{GemmEngine, Metal, MetalContext};
use crate::{
array::ArrayElement,
backends::{
@@ -21,6 +21,9 @@ use crate::{
#[cfg(backend = "metal")]
pub type MetalMatmulKernel = <<Metal as Backend>::Kernels as Kernels>::MatmulKernel;
+#[cfg(backend = "metal")]
+pub type TestDispatch = Option<GemmEngine>;
+
#[derive(Debug, Clone, Copy)]
pub struct Case {
pub shape: Shape,
@@ -198,12 +201,13 @@ pub fn run_metal<T: ArrayElement + Float>(
context: &MetalContext,
kernel: &mut MetalMatmulKernel,
input: &Input<T>,
- path: Option<GemmDispatchPath>,
+ dispatch: TestDispatch,
) -> Vec<T> {
- run::<Metal, T>(context, kernel, input, |kernel, args, encoder| match path {
- None => kernel.encode(args, encoder).expect("matmul encode failed"),
- Some(gemm_path) => {
- kernel.gemm.encode_dispatch_path(args, gemm_path, encoder).expect("gemm encode_dispatch_path failed")
- },
+ run::<Metal, T>(context, kernel, input, |kernel, args, encoder| {
+ if let Some(engine) = dispatch {
+ kernel.gemm.encode_with_engine(args, engine, encoder).expect("forced GEMM engine encode failed");
+ } else {
+ kernel.encode(args, encoder).expect("matmul encode failed");
+ }
})
}
diff --git a/crates/backend-uzu/src/tests/matmul/mod.rs b/crates/backend-uzu/src/tests/matmul/mod.rs
index 18c9c7a53..34de4a92d 100644
--- a/crates/backend-uzu/src/tests/matmul/mod.rs
+++ b/crates/backend-uzu/src/tests/matmul/mod.rs
@@ -4,11 +4,7 @@ pub mod quant;
pub mod shape;
pub use bench::{iter_encode_loop, iter_encode_loop_named};
-#[cfg(backend = "metal")]
-pub use harness::run_metal;
pub use harness::{Case, cpu_reference, deterministic_input};
-#[cfg(backend = "metal")]
-pub use quant::run_quant_metal;
pub use quant::{QuantBuffers, QuantInput, quant_arguments, quant_b_variant, run_quant_cpu};
pub use shape::{
Shape, all_correctness_shapes, bench_fp_gemm_shapes, bench_quant_gemm_shapes, bench_quant_gemv_shapes,
diff --git a/crates/backend-uzu/src/tests/matmul/quant.rs b/crates/backend-uzu/src/tests/matmul/quant.rs
index ef15115d4..8d81940d4 100644
--- a/crates/backend-uzu/src/tests/matmul/quant.rs
+++ b/crates/backend-uzu/src/tests/matmul/quant.rs
@@ -4,7 +4,9 @@ use num_traits::Float;
use rand::{RngExt, SeedableRng, rngs::SmallRng};
#[cfg(backend = "metal")]
-use crate::backends::metal::{GemmDispatchPath, Metal, MetalContext};
+use super::harness::TestDispatch;
+#[cfg(backend = "metal")]
+use crate::backends::metal::{Metal, MetalContext};
use crate::{
array::ArrayElement,
backends::{
@@ -318,7 +320,7 @@ pub fn run_quant_cpu<T: ArrayElement + Float>(input: &QuantInput<T>) -> Vec<T> {
pub fn run_quant_metal<T: ArrayElement + Float>(
context: &MetalContext,
input: &QuantInput<T>,
- path: Option<GemmDispatchPath>,
+ dispatch: TestDispatch,
) -> Vec<T> {
let mut buffers = QuantBuffers::<Metal, T>::allocate(context, input);
let mut matmul = <<Metal as Backend>::Kernels as Kernels>::MatmulKernel::new(
@@ -330,11 +332,10 @@ pub fn run_quant_metal<T: ArrayElement + Float>(
.expect("MatmulMetalKernel");
let mut encoder = Encoder::<Metal>::new(context).expect("encoder");
let args = quant_arguments(&mut buffers, input);
- match path {
- None => matmul.encode(args, &mut encoder).expect("matmul encode failed"),
- Some(gemm_path) => {
- matmul.gemm.encode_dispatch_path(args, gemm_path, &mut encoder).expect("gemm encode_dispatch_path failed")
- },
+ if let Some(engine) = dispatch {
+ matmul.gemm.encode_with_engine(args, engine, &mut encoder).expect("forced GEMM engine encode failed");
+ } else {
+ matmul.encode(args, &mut encoder).expect("matmul encode failed");
}
encoder.end_encoding().submit().wait_until_completed().unwrap();
allocation_to_vec::<Metal, T>(&buffers.y)
diff --git a/crates/backend-uzu/tests/unit/backends/common/kernel/matmul/a8w_bench.rs b/crates/backend-uzu/tests/unit/backends/common/kernel/matmul/a8w_bench.rs
index 6b6ed1377..df0a7678c 100644
--- a/crates/backend-uzu/tests/unit/backends/common/kernel/matmul/a8w_bench.rs
+++ b/crates/backend-uzu/tests/unit/backends/common/kernel/matmul/a8w_bench.rs
@@ -17,7 +17,7 @@ use crate::{
matmul::{MatmulA, MatmulArguments, MatmulB, MatmulDOps, MatmulKernel, MatmulShape},
},
},
- metal::{DeviceTier, GemmDispatchPath, GemvDispatch, GemvSpecialization, Metal, MetalContext},
+ metal::{DeviceTier, GemmEngine, GemvDispatch, GemvSpecialization, Metal, MetalContext},
},
data_type::DataType,
tests::{
@@ -187,13 +187,13 @@ fn encode_step(
n: data.n,
k: data.k,
};
- matmul.gemm.encode_dispatch_path(args, GemmDispatchPath::Mxu, encoder).expect("a8 gemm mxu encode");
+ matmul.gemm.encode_with_engine(args, GemmEngine::Mxu, encoder).expect("a8 gemm mxu encode");
},
BenchPath::Bf16GemmMxu => {
encoder.encode_copy(&data.activations, .., &mut data.a_working, ..);
hadamard.encode_fp_in_place(&mut data.a_working, &data.rht_factors, data.m, data.k, encoder);
let args = data.bf16_arguments(output);
- matmul.gemm.encode_dispatch_path(args, GemmDispatchPath::Mxu, encoder).expect("bf16 gemm mxu encode");
+ matmul.gemm.encode_with_engine(args, GemmEngine::Mxu, encoder).expect("bf16 gemm mxu encode");
},
BenchPath::Bf16Gemv => {
encoder.encode_copy(&data.activations, .., &mut data.a_working, ..);
diff --git a/crates/backend-uzu/tests/unit/backends/common/kernel/matmul/dispatch_paths_test.rs b/crates/backend-uzu/tests/unit/backends/common/kernel/matmul/dispatch_paths_test.rs
index 0b942b2c2..645a635f8 100644
--- a/crates/backend-uzu/tests/unit/backends/common/kernel/matmul/dispatch_paths_test.rs
+++ b/crates/backend-uzu/tests/unit/backends/common/kernel/matmul/dispatch_paths_test.rs
@@ -14,33 +14,41 @@ use crate::{
Backend, Context,
kernel::{Kernels, matmul::MatmulKernel},
},
- metal::{GemmDispatchPath, Metal, MetalContext},
+ metal::{GemmEngine, Metal, MetalContext},
},
tests::{
assert::assert_eq_float,
- matmul::{Case, all_correctness_shapes, cpu_reference, deterministic_input, run_metal},
+ matmul::{
+ Case, Shape, all_correctness_shapes, cpu_reference, deterministic_input,
+ harness::{TestDispatch, run_metal},
+ },
},
};
-fn gemm_paths_for_hw(context: &MetalContext) -> Vec<GemmDispatchPath> {
- let mut paths = vec![GemmDispatchPath::Simdgroup];
+fn gemm_engines_for_hw(context: &MetalContext) -> Vec<GemmEngine> {
+ let mut engines = vec![GemmEngine::Simdgroup];
if context.supports_mxu() {
- paths.push(GemmDispatchPath::Mxu);
+ engines.push(GemmEngine::Mxu);
}
- paths
+ engines
}
fn check_case<T: ArrayElement + Float + Debug + Display>(
context: &MetalContext,
kernel: &mut <<Metal as Backend>::Kernels as Kernels>::MatmulKernel,
- path: Option<GemmDispatchPath>,
+ dispatch: TestDispatch,
case: Case,
tolerance: f32,
) {
let input = deterministic_input::<T>(case);
let expected = cpu_reference::<T>(&input);
- let actual = run_metal::<T>(context, kernel, &input, path);
- assert_eq_float(&expected, &actual, tolerance, &format!("{path:?} dtype={} {case:?}", std::any::type_name::<T>()));
+ let actual = run_metal::<T>(context, kernel, &input, dispatch);
+ assert_eq_float(
+ &expected,
+ &actual,
+ tolerance,
+ &format!("{dispatch:?} dtype={} {case:?}", std::any::type_name::<T>()),
+ );
}
fn run_matrix<T: ArrayElement + Float + Debug + Display>(
@@ -55,10 +63,10 @@ fn run_matrix<T: ArrayElement + Float + Debug + Display>(
T::data_type(),
)
.expect("MatmulKernel");
- for path in gemm_paths_for_hw(&context) {
+ for engine in gemm_engines_for_hw(&context) {
for shape in all_correctness_shapes() {
let case = case_for_shape(shape);
- check_case::<T>(&context, &mut kernel, Some(path), case, tolerance);
+ check_case::<T>(&context, &mut kernel, Some(engine), case, tolerance);
}
}
}
@@ -107,10 +115,10 @@ fn rht_parity_bf16() {
bf16::data_type(),
)
.expect("MatmulKernel");
- for path in gemm_paths_for_hw(&context) {
+ for engine in gemm_engines_for_hw(&context) {
for shape in rht_shapes() {
let case = Case::new(shape).with_rht(true);
- check_case::<bf16>(&context, &mut kernel, Some(path), case, 1.0);
+ check_case::<bf16>(&context, &mut kernel, Some(engine), case, 1.0);
}
}
}
@@ -127,17 +135,16 @@ fn bias_parity_bf16() {
)
.expect("MatmulKernel");
let shapes = [Shape::new(64, 128, 64), Shape::new(128, 2048, 128), Shape::new(33, 128, 64)];
- for path in gemm_paths_for_hw(&context) {
+ for engine in gemm_engines_for_hw(&context) {
for shape in shapes {
let case = Case::new(shape).with_bias(true);
- check_case::<bf16>(&context, &mut kernel, Some(path), case, 1.0);
+ check_case::<bf16>(&context, &mut kernel, Some(engine), case, 1.0);
}
}
}
#[uzu_test]
fn gemv_fp_partial_output_block_bf16() {
- use crate::tests::matmul::Shape;
let context = MetalContext::new().expect("Metal context");
let mut kernel = <<Metal as Backend>::Kernels as Kernels>::MatmulKernel::new(
&context,
@@ -146,8 +153,6 @@ fn gemv_fp_partial_output_block_bf16() {
bf16::data_type(),
)
.expect("MatmulKernel");
- // Small m routes to GEMV; n that is not a multiple of the 32-row threadgroup
- // block exercises the tail-row clamp (must not read weight rows past B).
let shapes = [Shape::new(1, 128, 33), Shape::new(2, 256, 65), Shape::new(4, 384, 100)];
for shape in shapes {
check_case::<bf16>(&context, &mut kernel, None, Case::new(shape), 1.0);
@@ -179,7 +184,7 @@ fn gemv_fp_output_transforms_bf16() {
}
#[uzu_test]
-fn small_m_tiles_parity() {
+fn small_m_square_tile_parity() {
use crate::tests::matmul::Shape;
let context = MetalContext::new().expect("Metal context");
let mut bf16_kernel = <<Metal as Backend>::Kernels as Kernels>::MatmulKernel::new(
@@ -197,10 +202,10 @@ fn small_m_tiles_parity() {
)
.expect("MatmulKernel");
- for path in gemm_paths_for_hw(&context) {
- for shape in [Shape::new(8, 256, 256), Shape::new(8, 512, 256)] {
- check_case::<bf16>(&context, &mut bf16_kernel, Some(path), Case::new(shape), 1.0);
- check_case::<f32>(&context, &mut f32_kernel, Some(path), Case::new(shape), 0.01);
+ for shape in [Shape::new(8, 256, 256), Shape::new(8, 512, 256)] {
+ for engine in gemm_engines_for_hw(&context) {
+ check_case::<bf16>(&context, &mut bf16_kernel, Some(engine), Case::new(shape), 1.0);
+ check_case::<f32>(&context, &mut f32_kernel, Some(engine), Case::new(shape), 0.01);
}
}
}
diff --git a/crates/backend-uzu/tests/unit/backends/common/kernel/matmul/gemm_bench.rs b/crates/backend-uzu/tests/unit/backends/common/kernel/matmul/gemm_bench.rs
index 41f6422c4..7159bbd31 100644
--- a/crates/backend-uzu/tests/unit/backends/common/kernel/matmul/gemm_bench.rs
+++ b/crates/backend-uzu/tests/unit/backends/common/kernel/matmul/gemm_bench.rs
@@ -14,7 +14,7 @@ use crate::{
matmul::{MatmulA, MatmulArguments, MatmulB, MatmulDOps, MatmulKernel},
},
},
- metal::{GemmDispatchPath, Metal},
+ metal::{GemmEngine, Metal},
},
tests::{
helpers::alloc_allocation,
@@ -34,13 +34,13 @@ fn bench_gemm(c: &mut Criterion) {
)
.expect("MatmulKernel");
- let paths: &[(&str, GemmDispatchPath)] = if context.supports_mxu() {
- &[("GEMM", GemmDispatchPath::Simdgroup), ("GEMM_MXU", GemmDispatchPath::Mxu)]
+ let engines: &[(&str, GemmEngine)] = if context.supports_mxu() {
+ &[("GEMM", GemmEngine::Simdgroup), ("GEMM_MXU", GemmEngine::Mxu)]
} else {
- &[("GEMM", GemmDispatchPath::Simdgroup)]
+ &[("GEMM", GemmEngine::Simdgroup)]
};
- for &(group_label, path) in paths {
+ for &(group_label, engine) in engines {
let mut group = c.benchmark_group(format!("{}/Kernel/Matmul/{}", type_short_name::<Metal>(), group_label));
for shape in bench_fp_gemm_shapes() {
@@ -48,13 +48,12 @@ fn bench_gemm(c: &mut Criterion) {
let a = alloc_allocation::<Metal, bf16>(&context, m * k);
let b_weights = alloc_allocation::<Metal, bf16>(&context, n * k);
let mut d = alloc_allocation::<Metal, bf16>(&context, m * n);
-
group.throughput(Throughput::Elements((2 * m * k * n) as u64));
group.bench_function(BenchmarkId::new("BF16", shape.to_string()), |b| {
iter_encode_loop::<Metal, _>(&context, b, |encoder| {
kernel
.gemm
- .encode_dispatch_path(
+ .encode_with_engine(
MatmulArguments {
a: MatmulA::FullPrecision {
values: &a,
@@ -72,10 +71,10 @@ fn bench_gemm(c: &mut Criterion) {
n: n as u32,
k: k as u32,
},
- path,
+ engine,
encoder,
)
- .expect("encode_dispatch_path failed");
+ .expect("encode_plan failed");
});
});
}
diff --git a/crates/backend-uzu/tests/unit/backends/common/kernel/matmul/quant_dispatch_test.rs b/crates/backend-uzu/tests/unit/backends/common/kernel/matmul/quant_dispatch_test.rs
index d3a944172..28c4eaf5e 100644
--- a/crates/backend-uzu/tests/unit/backends/common/kernel/matmul/quant_dispatch_test.rs
+++ b/crates/backend-uzu/tests/unit/backends/common/kernel/matmul/quant_dispatch_test.rs
@@ -23,11 +23,16 @@ use crate::{
},
},
cpu::Cpu,
- metal::{GemmDispatchPath, Metal, MetalContext},
+ metal::{GemmEngine, Metal, MetalContext},
},
tests::{
helpers::allocation_to_vec,
- matmul::{QuantBuffers, QuantInput, quant_arguments, quant_b_variant, run_quant_cpu, run_quant_metal},
+ matmul::{
+ QuantBuffers, QuantInput,
+ harness::TestDispatch,
+ quant::{run_quant_cpu, run_quant_metal},
+ quant_arguments, quant_b_variant,
+ },
},
};
@@ -71,17 +76,19 @@ fn run_parity<T: ArrayElement + Float + Debug + Display>(
group_size: u32,
bits: u32,
quant_method: QuantizationMethod,
+ dispatch: TestDispatch,
+ label: &str,
rel_tol: f64,
abs_tol: f64,
) {
let context = MetalContext::new().expect("Metal context");
let input = QuantInput::<T>::new(m, k, n, group_size, bits, quant_method, 0);
- let unified = run_quant_metal::<T>(&context, &input, Some(GemmDispatchPath::Simdgroup));
+ let unified = run_quant_metal::<T>(&context, &input, dispatch);
let reference = run_quant_cpu::<T>(&input);
assert_parity::<T>(
&format!(
- "m={m} k={k} n={n} gs={group_size} bits={bits} method={quant_method:?} dtype={}",
+ "{label} m={m} k={k} n={n} gs={group_size} bits={bits} method={quant_method:?} dtype={}",
std::any::type_name::<T>()
),
&reference,
@@ -114,7 +121,7 @@ fn parity_bf16(
#[case] bits: u32,
#[case] method: QuantizationMethod,
) {
- run_parity::<bf16>(m, k, n, gs, bits, method, 0.05, 0.4);
+ run_parity::<bf16>(m, k, n, gs, bits, method, Some(GemmEngine::Simdgroup), "gemm", 0.05, 0.4);
}
#[rstest]
@@ -131,33 +138,7 @@ fn parity_bf16_8bit_splitk(
#[case] bits: u32,
#[case] method: QuantizationMethod,
) {
- run_parity::<bf16>(m, k, n, gs, bits, method, 0.05, 1.0);
-}
-
-fn run_parity_gemv<T: ArrayElement + Float + Debug + Display>(
- m: usize,
- k: usize,
- n: usize,
- group_size: u32,
- bits: u32,
- quant_method: QuantizationMethod,
- rel_tol: f64,
- abs_tol: f64,
-) {
- let context = MetalContext::new().expect("Metal context");
- let input = QuantInput::<T>::new(m, k, n, group_size, bits, quant_method, 0);
- let gemv = run_quant_metal::<T>(&context, &input, None);
- let reference = run_quant_cpu::<T>(&input);
- assert_parity::<T>(
- &format!(
- "gemv m={m} k={k} n={n} gs={group_size} bits={bits} method={quant_method:?} dtype={}",
- std::any::type_name::<T>()
- ),
- &reference,
- &gemv,
- rel_tol,
- abs_tol,
- );
+ run_parity::<bf16>(m, k, n, gs, bits, method, Some(GemmEngine::Simdgroup), "gemm", 0.05, 1.0);
}
#[rstest]
@@ -180,7 +161,7 @@ fn parity_gemv_bf16(
#[case] bits: u32,
#[case] method: QuantizationMethod,
) {
- run_parity_gemv::<bf16>(m, k, n, gs, bits, method, 0.05, 0.4);
+ run_parity::<bf16>(m, k, n, gs, bits, method, None, "gemv", 0.05, 0.4);
}
#[uzu_test]
@@ -207,7 +188,7 @@ fn parity_bf16_gs32_4bit_mlx_with_bias() {
bias: Some(&bias_pp_buf),
..MatmulDOps::none()
};
- matmul.gemm.encode_dispatch_path(args, GemmDispatchPath::Simdgroup, &mut encoder).expect("encode quant with bias");
+ matmul.gemm.encode_with_engine(args, GemmEngine::Simdgroup, &mut encoder).expect("encode quant with bias");
encoder.end_encoding().submit().wait_until_completed().unwrap();
let actual = allocation_to_vec::<Metal, bf16>(&buffers.y);
@@ -280,7 +261,7 @@ fn parity_gemv_partial_group_bf16(
) {
// k is not a multiple of group_size, so the per-row scale/zp stride must use
// ceil(k / group_size) groups.
- run_parity_gemv::<bf16>(m, k, n, gs, bits, method, 0.05, 0.6);
+ run_parity::<bf16>(m, k, n, gs, bits, method, None, "gemv", 0.05, 0.6);
}
#[rstest]
@@ -297,7 +278,7 @@ fn parity_gemv_unaligned_width_bf16(
#[case] method: QuantizationMethod,
) {
// n is not a multiple of 8; the output-tail clamp must cover the partial block.
- run_parity_gemv::<bf16>(m, k, n, gs, bits, method, 0.05, 0.6);
+ run_parity::<bf16>(m, k, n, gs, bits, method, None, "gemv", 0.05, 0.6);
}
#[uzu_test]
@@ -481,7 +462,7 @@ fn mxu_quant_parity_bf16(
return;
}
let input = QuantInput::<bf16>::new(m, k, n, gs, bits, method, 0);
- let actual = run_quant_metal::<bf16>(&context, &input, Some(GemmDispatchPath::Mxu));
+ let actual = run_quant_metal::<bf16>(&context, &input, Some(GemmEngine::Mxu));
let reference = run_quant_cpu::<bf16>(&input);
assert_parity::<bf16>(
&format!("MXU m={m} k={k} n={n} gs={gs} bits={bits} method={method:?}"),
@@ -521,7 +502,7 @@ fn a8w_mxu_parity_bf16(
ACTIVATION_SCALE_GROUP_SIZE as usize,
(method != QuantizationMethod::ScaleSymmetric).then_some(weight_gs),
);
- let actual = run_quant_metal::<bf16>(&context, &input, Some(GemmDispatchPath::Mxu));
+ let actual = run_quant_metal::<bf16>(&context, &input, Some(GemmEngine::Mxu));
let reference = run_quant_cpu::<bf16>(&input);
assert_parity::<bf16>(
&format!("A8W{bits} MXU m={m} weight_gs={weight_gs} method={method:?}"),
@@ -557,7 +538,7 @@ fn a8w_independent_activation_group_parity_bf16(#[case] m: usize) {
(method != QuantizationMethod::ScaleSymmetric)
.then_some((activation_group_size as u32).min(weight_group_size)),
);
- let actual = run_quant_metal::<bf16>(&context, &input, Some(GemmDispatchPath::Mxu));
+ let actual = run_quant_metal::<bf16>(&context, &input, Some(GemmEngine::Mxu));
let reference = run_quant_cpu::<bf16>(&input);
assert_parity::<bf16>(
&format!("A8W{bits} act{activation_group_size} weight{weight_group_size} m={m} method={method:?}"),
@@ -582,7 +563,7 @@ fn a8w4_zero_point_tail_parity(#[case] m: usize) {
}
let input = QuantInput::<bf16>::new(m, 256, 72, 32, 4, QuantizationMethod::ScaleZeroPoint, 0)
.with_prepared_a(ACTIVATION_SCALE_GROUP_SIZE as usize, Some(32));
- let actual = run_quant_metal::<bf16>(&context, &input, Some(GemmDispatchPath::Mxu));
+ let actual = run_quant_metal::<bf16>(&context, &input, Some(GemmEngine::Mxu));
let reference = run_quant_cpu::<bf16>(&input);
assert_parity::<bf16>(&format!("A8W4 ZP N-tail m={m}"), &reference, &actual, 0.08, 0.8);
}
@@ -596,7 +577,7 @@ fn a8w4_zero_point_tail_signed_codes_parity() {
let input = QuantInput::<bf16>::new(33, 256, 72, 32, 4, QuantizationMethod::ScaleZeroPoint, 0)
.with_prepared_a(ACTIVATION_SCALE_GROUP_SIZE as usize, Some(32))
.with_signed_weight_codes();
- let actual = run_quant_metal::<bf16>(&context, &input, Some(GemmDispatchPath::Mxu));
+ let actual = run_quant_metal::<bf16>(&context, &input, Some(GemmEngine::Mxu));
let reference = run_quant_cpu::<bf16>(&input);
assert_parity::<bf16>("A8W4 ZP signed-code N-tail", &reference, &actual, 0.08, 0.8);
}
@@ -621,8 +602,8 @@ fn signed_weights_full_precision_activations_parity_bf16(
let reference_input = QuantInput::<bf16>::new(m, k, n, group_size, bits, method, 0);
let reference = run_quant_cpu::<bf16>(&reference_input);
- for (label, path) in [("gemv", None), ("simdgroup", Some(GemmDispatchPath::Simdgroup))] {
- let actual = run_quant_metal::<bf16>(&context, &input, path);
+ for (label, dispatch) in [("gemv", None), ("simdgroup", Some(GemmEngine::Simdgroup))] {
+ let actual = run_quant_metal::<bf16>(&context, &input, dispatch);
assert_parity::<bf16>(
&format!("signed weights FP-A {label} bits={bits} method={method:?}"),
&reference,
@@ -720,7 +701,7 @@ fn a8w_mxu_output_bias_parity_bf16(
};
metal_matmul
.gemm
- .encode_dispatch_path(metal_arguments, GemmDispatchPath::Mxu, &mut metal_encoder)
+ .encode_with_engine(metal_arguments, GemmEngine::Mxu, &mut metal_encoder)
.expect("Metal A8W MXU matmul with output bias");
metal_encoder.end_encoding().submit().wait_until_completed().unwrap();
let actual = allocation_to_vec::<Metal, bf16>(&metal_buffers.y);
diff --git a/crates/backend-uzu/tests/unit/backends/common/kernel/matmul/quant_gemm_bench.rs b/crates/backend-uzu/tests/unit/backends/common/kernel/matmul/quant_gemm_bench.rs
index 7ea4422e4..d41fa2a8a 100644
--- a/crates/backend-uzu/tests/unit/backends/common/kernel/matmul/quant_gemm_bench.rs
+++ b/crates/backend-uzu/tests/unit/backends/common/kernel/matmul/quant_gemm_bench.rs
@@ -13,7 +13,7 @@ use crate::{
gpu_types::QuantizationMethod,
kernel::{Kernels, matmul::MatmulKernel},
},
- metal::{GemmDispatchPath, Metal, MetalContext},
+ metal::{GemmEngine, Metal, MetalContext},
},
tests::{
matmul::{QuantBuffers, QuantInput, bench_quant_gemm_shapes, iter_encode_loop, quant_arguments},
@@ -30,10 +30,10 @@ fn bench_unified_quant_typed<T: ArrayElement + Float>(
quant_method: QuantizationMethod,
) {
let supports_mxu = context.supports_mxu();
- let paths: &[(&str, GemmDispatchPath)] = if supports_mxu {
- &[("Simdgroup", GemmDispatchPath::Simdgroup), ("Mxu", GemmDispatchPath::Mxu)]
+ let engines: &[(&str, GemmEngine)] = if supports_mxu {
+ &[("Simdgroup", GemmEngine::Simdgroup), ("Mxu", GemmEngine::Mxu)]
} else {
- &[("Simdgroup", GemmDispatchPath::Simdgroup)]
+ &[("Simdgroup", GemmEngine::Simdgroup)]
};
for shape in bench_quant_gemm_shapes(bits) {
@@ -48,7 +48,7 @@ fn bench_unified_quant_typed<T: ArrayElement + Float>(
)
.unwrap();
- for &(path_label, path) in paths {
+ for &(path_label, engine) in engines {
let mut group = c.benchmark_group(format!(
"{}/Kernel/UnifiedQuantizedGemm/{}/{}",
type_short_name::<Metal>(),
@@ -60,7 +60,7 @@ fn bench_unified_quant_typed<T: ArrayElement + Float>(
iter_encode_loop::<Metal, _>(context, b, |encoder| {
matmul
.gemm
- .encode_dispatch_path(quant_arguments(&mut buffers, &input), path, encoder)
+ .encode_with_engine(quant_arguments(&mut buffers, &input), engine, encoder)
.expect("encode unified quant matmul");
});
});
diff --git a/crates/backend-uzu/tests/unit/backends/metal/kernel/matmul/gemm/selection_test.rs b/crates/backend-uzu/tests/unit/backends/metal/kernel/matmul/gemm/selection_test.rs
new file mode 100644
index 000000000..ed59d14d3
--- /dev/null
+++ b/crates/backend-uzu/tests/unit/backends/metal/kernel/matmul/gemm/selection_test.rs
@@ -0,0 +1,177 @@
+use proc_macros::uzu_test;
+
+use super::{super::specialization::GemmSpecialization, *};
+use crate::backends::{
+ common::gpu_types::gemm::{GemmAPrologueKind, GemmAlignment, GemmDTransform},
+ metal::kernel::matmul::MatmulMetalKernel,
+};
+
+fn shape(
+ m: u32,
+ n: u32,
+ k: u32,
+) -> MatmulShape {
+ MatmulShape {
+ m,
+ n,
+ k,
+ b_transpose: true,
+ b_leading_dimension: None,
+ b_prologue: GemmBPrologueKind::FullPrecision,
+ b_bits: None,
+ b_group_size: None,
+ signed_codes: false,
+ a_full_precision: true,
+ gathered: false,
+ d_transform: GemmDTransform::empty(),
+ }
+}
+
+fn quant(mut shape: MatmulShape) -> MatmulShape {
+ shape.b_prologue = GemmBPrologueKind::ScaleSymmetricDequant;
+ shape.b_bits = Some(4);
+ shape.b_group_size = Some(64);
+ shape.signed_codes = true;
+ shape
+}
+
+fn problem(
+ shape: MatmulShape,
+ output_data_type: DataType,
+) -> GemmProblem {
+ GemmProblem::new(shape, DataType::BF16, output_data_type, true)
+}
+
+fn plan(split_k: u32) -> GemmPlan {
+ GemmPlan {
+ engine: GemmEngine::Mxu,
+ tiling: GemmTiling::Tile64x64x256_Simdgroups2x2,
+ split_k,
+ }
+}
+
+#[uzu_test]
+fn policy_boundaries_are_preserved() {
+ use GemmTiling::*;
+
+ for (is_a_int8, m, n, expected) in [
+ (true, 16, 4096, Tile16x128x256_Simdgroups1x4),
+ (true, 17, 4096, Tile32x64x256_Simdgroups2x2),
+ (true, 64, 63, Tile64x32x256_Simdgroups4x1),
+ (true, 512, 4096, Tile128x128x256_Simdgroups4x4),
+ (false, 16, 4096, Tile32x64x256_Simdgroups2x2),
+ (false, 64, 4096, Tile64x64x256_Simdgroups2x2),
+ (false, 256, 4096, Tile128x128x256_Simdgroups4x4),
+ ] {
+ assert_eq!(policy::mxu_mn_tile(is_a_int8, m, n), expected);
+ }
+
+ for (m, n, k, expected) in [
+ (15, 2560, 2560, Tile16x32x256_Simdgroups1x1),
+ (15, 4096, 8192, Tile16x128x256_Simdgroups1x4),
+ (15, 131_073, 4096, Tile16x32x256_Simdgroups1x1),
+ (64, 4096, 2048, Tile64x64x256_Simdgroups2x2),
+ (256, 4096, 2048, Tile128x128x256_Simdgroups4x4),
+ ] {
+ assert_eq!(policy::mxu_fp_tile(m, n, k), expected);
+ }
+
+ for (m, n, group_size, expected) in [
+ (16, 4096, 31, Tile64x64x16_Simdgroups2x2),
+ (31, 4096, 32, Tile8x32x32_Simdgroups1x1),
+ (64, 6143, 32, Tile32x32x32_Simdgroups2x2),
+ (64, 6144, 32, Tile64x64x32_Simdgroups2x2),
+ ] {
+ assert_eq!(policy::simdgroup_quant_tile(m, n, group_size), expected);
+ }
+}
+
+#[uzu_test]
+fn selection_fallbacks_and_split_k_are_preserved() {
+ use GemmEngine::*;
+ use GemmTiling::*;
+
+ let mut invalid_layout = quant(shape(64, 4096, 4096));
+ invalid_layout.b_transpose = false;
+ assert_eq!(problem(invalid_layout, DataType::BF16).select_plan().engine, Simdgroup);
+ invalid_layout.a_full_precision = false;
+ assert_eq!(problem(invalid_layout, DataType::BF16).select_plan().engine, Mxu);
+ assert_eq!(problem(quant(shape(64, 4096, 4095)), DataType::BF16).select_plan().engine, Simdgroup);
+
+ let mut large_group = quant(shape(512, 4096, 4096));
+ large_group.a_full_precision = false;
+ large_group.b_group_size = Some(128);
+ assert_eq!(problem(large_group, DataType::BF16).select_plan().tiling, Tile64x64x256_Simdgroups2x2);
+
+ let mut a8 = quant(shape(16, 4096, 4096));
+ a8.a_full_precision = false;
+ assert_eq!(problem(a8, DataType::BF16).select_plan().split_k, 8);
+
+ let mut biased = quant(shape(16, 4096, 4096));
+ biased.a_full_precision = false;
+ biased.d_transform = GemmDTransform::BIAS;
+ assert_eq!(GemmProblem::new(biased, DataType::BF16, DataType::F32, true).select_plan().split_k, 1);
+
+ let mut zero = quant(shape(0, 1, 1));
+ zero.b_prologue = GemmBPrologueKind::ScaleZeroPointDequant;
+ zero.b_group_size = Some(u32::MAX);
+ assert_eq!(problem(zero, DataType::BF16).select_plan().split_k, 1);
+}
+
+#[uzu_test]
+fn forced_engine_errors_are_preserved() {
+ let huge = shape(u32::MAX, u32::MAX, u32::MAX);
+ assert_eq!(
+ GemmProblem::new(huge, DataType::BF16, DataType::BF16, false).select_plan_for_engine(GemmEngine::Mxu),
+ Err(GemmPlanError::MxuUnavailable)
+ );
+
+ let mut invalid_layout = quant(huge);
+ invalid_layout.b_transpose = false;
+ assert_eq!(
+ problem(invalid_layout, DataType::BF16).select_plan_for_engine(GemmEngine::Mxu),
+ Err(GemmPlanError::UnsupportedQuantLayout)
+ );
+}
+
+#[uzu_test]
+fn specialization_flags_are_preserved() {
+ let specialization = |shape, split_k| {
+ GemmSpecialization::from_plan(
+ plan(split_k),
+ shape,
+ DataType::BF16,
+ GemmDTransform::empty(),
+ GemmAlignment::new(true, true, true),
+ GemmAPrologueKind::FullPrecision,
+ None,
+ )
+ .unwrap()
+ };
+ for (split_k, hoist) in [(1, false), (2, true)] {
+ let spec = specialization(shape(64, 4096, 4096), split_k);
+ assert!(spec.stage_weight_scales);
+ assert_eq!(spec.hoist_operand_addressing, hoist);
+ }
+ let spec = specialization(quant(shape(64, 4096, 4096)), 1);
+ assert!(spec.stage_weight_scales);
+ assert!(spec.hoist_operand_addressing);
+}
+
+#[uzu_test]
+fn gemv_gemm_route_boundaries_are_preserved() {
+ for (shape, data_type, prefer_gemm) in [
+ (shape(4, 4096, 8192), DataType::BF16, true),
+ (shape(4, 8192, 4096), DataType::BF16, false),
+ (shape(4, 4096, 4096), DataType::F32, false),
+ (shape(3, 4096, 8192), DataType::BF16, false),
+ (shape(5, 4096, 8192), DataType::BF16, false),
+ ] {
+ let plan = GemmProblem::new(shape, data_type, data_type, true).select_plan();
+ assert_eq!(MatmulMetalKernel::prefer_gemm_over_gemv(shape, plan, data_type, data_type, data_type), prefer_gemm);
+ }
+ let mut gathered = shape(4, 4096, 8192);
+ gathered.gathered = true;
+ let plan = problem(gathered, DataType::BF16).select_plan();
+ assert!(!MatmulMetalKernel::prefer_gemm_over_gemv(gathered, plan, DataType::BF16, DataType::BF16, DataType::BF16,));
+}