A high-performance inference engine for AI models
delete device profile
eugene344b78031b23
diff --git a/Cargo.lock b/Cargo.lockindex 2aefeaa2a..93d25dad2 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -3650,9 +3650,9 @@ dependencies = [[[package]]name = "mtl-rs"-version = "0.1.14"+version = "0.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "6365d3a49e40c611ee28aa0f1bc90abc69b3b3a38172f63b1fdb0061809cba91"+checksum = "bf8b377d6cc3233c580332bf4aba1c3c1b93d72dadf5af30bc1b7414c39fccb8"dependencies = ["bitflags 2.13.0","block2",diff --git a/Cargo.toml b/Cargo.tomlindex 6a394e1e0..db9f8c110 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -79,7 +79,7 @@ objc2-io-kit = { version = "0.3.2", default-features = false, features = ["libc"objc2-security = "0.3.2"obfstr = "0.4.4"zstd = "0.13.3"-metal = { package = "mtl-rs", version = "0.1.14" }+metal = { package = "mtl-rs", version = "0.2.0" }block2 = "0.6"bytemuck = "1.23"bytesize = "2"diff --git a/crates/uzu-engine/src/backends/metal/context.rs b/crates/uzu-engine/src/backends/metal/context.rsindex a81773318..f86583644 100644--- a/crates/uzu-engine/src/backends/metal/context.rs+++ b/crates/uzu-engine/src/backends/metal/context.rs@@ -11,15 +11,14 @@ use std::{use metal::MTLSharedEvent;use metal::{MTL4CommandQueue, MTL4CommandQueueExt, MTLBuffer, MTLCaptureDescriptor, MTLCaptureDestination, MTLCaptureManager,- MTLCommandBufferExt, MTLCommandQueue, MTLCommandQueueExt, MTLComputePipelineState, MTLDevice, MTLDeviceExt,- MTLEvent, MTLFunctionConstantValues, MTLLibrary, MTLResourceOptions, MTLSparsePageSize,+ MTLCaptureTarget, MTLCommandBufferExt, MTLCommandQueue, MTLCommandQueueExt, MTLComputePipelineState, MTLDevice,+ MTLDeviceExt, MTLEvent, MTLFunctionConstantValues, MTLGPUFamily, MTLLibrary, MTLResourceOptions, MTLSparsePageSize,};use objc2::{rc::Retained, runtime::ProtocolObject};use parking_lot::{Mutex, MutexGuard};use super::{Metal,- device_profile::{DeviceProfile, classify_device},error::MetalError,metal_extensions::{DeviceExt, LibraryPipelineExtensions},};@@ -31,9 +30,14 @@ use crate::backends::{},};+pub(super) const LARGE_MIN_GPU_CORES: u32 = 30;+pub struct MetalContext {pub device: Retained<ProtocolObject<dyn MTLDevice>>,- device_name: String,+ pub gpu_core_count: u32,+ pub apple_gpu_family: MTLGPUFamily,+ pub supports_mxu: bool,+ pub device_name: String,pub command_queue: Retained<ProtocolObject<dyn MTLCommandQueue>>,pub command_queue4: Retained<ProtocolObject<dyn MTL4CommandQueue>>,timeline_event: Retained<ProtocolObject<dyn MTLEvent>>,@@ -43,21 +47,12 @@ pub struct MetalContext {library_cache: Mutex<HashMap<usize, Retained<ProtocolObject<dyn MTLLibrary>>>>,pipeline_cache: Mutex<HashMap<String, Retained<ProtocolObject<dyn MTLComputePipelineState>>>>,sparse_heap_pool: Mutex<MetalSparseHeapPool>,- device_profile: DeviceProfile,weak_self: Weak<MetalContext>,#[cfg(test)]timeline_shared_event: Retained<ProtocolObject<dyn MTLSharedEvent>>,}impl MetalContext {- pub fn supports_mxu(&self) -> bool {- self.device_profile.supports_mxu()- }-- pub(super) fn device_profile(&self) -> DeviceProfile {- self.device_profile- }-pub(super) fn update_peak_memory_usage(&self) {self.peak_memory_usage.fetch_max(self.device.current_allocated_size(), Ordering::Relaxed);}@@ -150,14 +145,15 @@ impl Context for MetalContext {let device: Retained<ProtocolObject<dyn MTLDevice>> =<dyn MTLDevice>::system_default().ok_or(MetalError::CannotOpenDevice)?;let device_name = device.name();+ let gpu_core_count = device.gpu_core_count();+ let apple_gpu_family = device.newest_supported_apple_gpu_family();+ let supports_mxu = device.supports_mxu();let command_queue =device.new_command_queue_with_max_command_buffer_count(1024).ok_or(MetalError::CannotCreateCommandQueue)?;let command_queue4 = device.new_mtl4_command_queue().ok_or(MetalError::CannotCreateCommandQueueMtl4)?;- let gpu_core_count = device.gpu_core_count();- let device_profile = classify_device(&device.name(), gpu_core_count, device.supports_mxu());let page_size = MTLSparsePageSize::KB256;let heap_capacity = Metal::ALLOCATION_GRANULARITY;let sparse_pool = MetalSparseHeapPool::new(page_size, heap_capacity);@@ -167,6 +163,9 @@ impl Context for MetalContext {Ok(Arc::new_cyclic(|weak_self| Self {device,+ gpu_core_count,+ apple_gpu_family,+ supports_mxu,device_name,command_queue,command_queue4,@@ -177,7 +176,6 @@ impl Context for MetalContext {library_cache: Mutex::new(HashMap::new()),pipeline_cache: Mutex::new(HashMap::new()),sparse_heap_pool: Mutex::new(sparse_pool),- device_profile,weak_self: weak_self.clone(),#[cfg(test)]timeline_shared_event,@@ -256,11 +254,12 @@ impl Context for MetalContext {capture_descriptor.set_output_path(Some(&trace_path.with_added_extension("gputrace")));self.command_queue.set_label(Some("uzu_command_queue"));- capture_descriptor.set_capture_object(Some(self.command_queue.as_ref()));+ let capture_target = MTLCaptureTarget::CommandQueue(self.command_queue.clone());+ capture_descriptor.set_capture_object(Some(&capture_target));capture_manager- .start_capture_with_descriptor_error(&capture_descriptor)- .map_err(|nserror| MetalError::CannotStartGpuCapture(nserror.to_string()))?;+ .start_capture_with_descriptor(&capture_descriptor)+ .map_err(|error| MetalError::CannotStartGpuCapture(error.to_string()))?;Ok(())}diff --git a/crates/uzu-engine/src/backends/metal/device_profile.rs b/crates/uzu-engine/src/backends/metal/device_profile.rsdeleted file mode 100644index 81f68fd7e..000000000--- a/crates/uzu-engine/src/backends/metal/device_profile.rs+++ /dev/null@@ -1,173 +0,0 @@-#[derive(Debug, Clone, Copy, PartialEq, Eq)]-pub(super) enum DeviceIdentity {- A14,- A15,- A16,- A17Pro,- A18,- A18Pro,- A19,- A19Pro,- M1,- M1Pro,- M1Max,- M1Ultra,- M2,- M2Pro,- M2Max,- M2Ultra,- M3,- M3Pro,- M3Max,- M3Ultra,- M4,- M4Pro,- M4Max,- M5,- M5Pro,- M5Max,- M5Ultra,-}--impl DeviceIdentity {- fn from_name(device_name: &str) -> Self {- let Some(chip) = device_name.strip_prefix("Apple ") else {- panic!("unsupported Metal device {device_name:?}; add its DeviceIdentity mapping");- };- let chip = chip.strip_suffix(" GPU").unwrap_or(chip);- match chip {- "A14" => Self::A14,- "A15" => Self::A15,- "A16" => Self::A16,- "A17 Pro" => Self::A17Pro,- "A18" => Self::A18,- "A18 Pro" => Self::A18Pro,- "A19" => Self::A19,- "A19 Pro" => Self::A19Pro,- "M1" => Self::M1,- "M1 Pro" => Self::M1Pro,- "M1 Max" => Self::M1Max,- "M1 Ultra" => Self::M1Ultra,- "M2" => Self::M2,- "M2 Pro" => Self::M2Pro,- "M2 Max" => Self::M2Max,- "M2 Ultra" => Self::M2Ultra,- "M3" => Self::M3,- "M3 Pro" => Self::M3Pro,- "M3 Max" => Self::M3Max,- "M3 Ultra" => Self::M3Ultra,- "M4" => Self::M4,- "M4 Pro" => Self::M4Pro,- "M4 Max" => Self::M4Max,- "M5" => Self::M5,- "M5 Pro" => Self::M5Pro,- "M5 Max" => Self::M5Max,- "M5 Ultra" => Self::M5Ultra,- _ => panic!("unsupported Metal device {device_name:?}; add its DeviceIdentity mapping"),- }- }-- const fn gpu_family(self) -> GpuFamily {- match self {- Self::A14 | Self::M1 | Self::M1Pro | Self::M1Max | Self::M1Ultra => GpuFamily::Legacy,- Self::A15 | Self::A16 | Self::M2 | Self::M2Pro | Self::M2Max | Self::M2Ultra => GpuFamily::Apple8,- Self::A17Pro- | Self::A18- | Self::A18Pro- | Self::M3- | Self::M3Pro- | Self::M3Max- | Self::M3Ultra- | Self::M4- | Self::M4Pro- | Self::M4Max => GpuFamily::Apple9,- Self::A19 | Self::A19Pro | Self::M5 | Self::M5Pro | Self::M5Max | Self::M5Ultra => GpuFamily::M5Plus,- }- }-}--#[derive(Debug, Clone, Copy, PartialEq, Eq)]-pub(super) enum GpuFamily {- Legacy,- Apple8,- Apple9,- M5Plus,-}--impl GpuFamily {- pub(super) fn contains(- self,- identity: DeviceIdentity,- ) -> bool {- identity.gpu_family() == self- }-}--#[derive(Debug, Clone, Copy, PartialEq, Eq)]-pub(super) enum DeviceSize {- Small,- Large,-}--impl DeviceSize {- fn from_gpu_core_count(gpu_core_count: u32) -> Self {- if gpu_core_count >= 30 {- Self::Large- } else {- Self::Small- }- }-}--#[derive(Debug, Clone, Copy, PartialEq, Eq)]-pub(super) struct DeviceProfile {- identity: DeviceIdentity,- size: DeviceSize,- supports_mxu: bool,-}--impl DeviceProfile {- pub(super) const fn new(- identity: DeviceIdentity,- size: DeviceSize,- supports_mxu: bool,- ) -> Self {- Self {- identity,- size,- supports_mxu,- }- }-- pub(super) const fn identity(self) -> DeviceIdentity {- self.identity- }-- pub(super) const fn gpu_family(self) -> GpuFamily {- self.identity.gpu_family()- }-- pub(super) const fn size(self) -> DeviceSize {- self.size- }-- pub(super) const fn supports_mxu(self) -> bool {- self.supports_mxu- }-}--pub(super) fn classify_device(- device_name: &str,- gpu_core_count: u32,- supports_mxu: bool,-) -> DeviceProfile {- DeviceProfile::new(- DeviceIdentity::from_name(device_name),- DeviceSize::from_gpu_core_count(gpu_core_count),- supports_mxu,- )-}--#[cfg(test)]-#[path = "../../../unit/backends/metal/device_profile_test.rs"]-mod tests;diff --git a/crates/uzu-engine/src/backends/metal/kernel/attention/gemm.rs b/crates/uzu-engine/src/backends/metal/kernel/attention/gemm.rsindex 3501e1a6d..cecf5fe2b 100644--- a/crates/uzu-engine/src/backends/metal/kernel/attention/gemm.rs+++ b/crates/uzu-engine/src/backends/metal/kernel/attention/gemm.rs@@ -117,9 +117,9 @@ impl AttentionGemm {.allocate_constant_for_shape(&[arguments.suffix_length, self.num_q_heads, self.head_dim], self.data_type)?;let use_mxu = arguments.suffix_length >= 64- && encoder.context().supports_mxu()&& matches!(self.data_type, DataType::BF16)- && matches!(self.head_dim, 64 | 128);+ && matches!(self.head_dim, 64 | 128)+ && encoder.context().supports_mxu;let (bq, bk) = if use_mxu {(64, 32)} else {diff --git a/crates/uzu-engine/src/backends/metal/kernel/attention/gemm_grouped/mod.rs b/crates/uzu-engine/src/backends/metal/kernel/attention/gemm_grouped/mod.rsindex 53455bfe0..efe870e83 100644--- a/crates/uzu-engine/src/backends/metal/kernel/attention/gemm_grouped/mod.rs+++ b/crates/uzu-engine/src/backends/metal/kernel/attention/gemm_grouped/mod.rs@@ -12,7 +12,6 @@ use crate::{context::MetalContext,error::MetalError,kernel::{AttentionGemmGroupedCombineMetalKernel, AttentionGemmGroupedMetalKernel},- metal_extensions::DeviceExt,},},data_type::DataType,@@ -38,7 +37,6 @@ struct AttentionGemmGroupedMetal {scale: Option<f32>,block_rows: u32,mask: MaskKind,- gpu_core_count: u32,}impl AttentionGemmGroupedMetal {@@ -77,7 +75,6 @@ impl AttentionGemmGroupedMetal {scale,block_rows,mask,- gpu_core_count: context.device.gpu_core_count(),})}@@ -264,6 +261,7 @@ impl AttentionGemmGrouped {let kv_length = arguments.cache.prefix_len() + suffix_length;let mut output =encoder.allocate_constant_for_shape(&[suffix_length, self.num_q_heads, self.head_dim], DataType::BF16)?;+ let gpu_core_count = encoder.context().gpu_core_count;let core = self.get_or_create(encoder.context(), mask)?;let num_splits = choose_splits(core.head_dim,@@ -271,7 +269,7 @@ impl AttentionGemmGrouped {kv_length,(core.num_q_heads / core.num_groups * suffix_length).div_ceil(core.block_rows) * core.num_groups,BLOCK_K,- core.gpu_core_count,+ gpu_core_count,);core.encode(arguments.queries,diff --git a/crates/uzu-engine/src/backends/metal/kernel/attention/gemm_grouped/policy.rs b/crates/uzu-engine/src/backends/metal/kernel/attention/gemm_grouped/policy.rsindex b759f5964..762f36e7e 100644--- a/crates/uzu-engine/src/backends/metal/kernel/attention/gemm_grouped/policy.rs+++ b/crates/uzu-engine/src/backends/metal/kernel/attention/gemm_grouped/policy.rs@@ -17,7 +17,7 @@ pub fn is_supported() -> bool {GEMM_GROUPED_HEAD_DIMS.contains(&arguments.head_dim)&& arguments.data_type == DataType::BF16- && context.supports_mxu()+ && context.supports_mxu&& !arguments.has_sinks&& !arguments.is_kv_cache_ring&& arguments.sliding_window_size.is_none()diff --git a/crates/uzu-engine/src/backends/metal/kernel/gdn/chunked/mod.rs b/crates/uzu-engine/src/backends/metal/kernel/gdn/chunked/mod.rsindex be76ae7ef..c71e1cbcd 100644--- a/crates/uzu-engine/src/backends/metal/kernel/gdn/chunked/mod.rs+++ b/crates/uzu-engine/src/backends/metal/kernel/gdn/chunked/mod.rs@@ -44,7 +44,7 @@ impl DeltaNetChunkedPrefill for MetalDeltaNetChunkedPrefill {return Ok(None);}- if !context.supports_mxu() {+ if !context.supports_mxu {return Ok(None);}diff --git a/crates/uzu-engine/src/backends/metal/kernel/gdn/tree_verify.rs b/crates/uzu-engine/src/backends/metal/kernel/gdn/tree_verify.rsindex 5ee51c0e5..44f7044ca 100644--- a/crates/uzu-engine/src/backends/metal/kernel/gdn/tree_verify.rs+++ b/crates/uzu-engine/src/backends/metal/kernel/gdn/tree_verify.rs@@ -1,3 +1,5 @@+use metal::MTLGPUFamily;+use crate::{backends::{common::{@@ -7,12 +9,7 @@ use crate::{delta_net_tree_verify::DeltaNetTreeVerify,},},- metal::{- Metal, MetalContext,- device_profile::{DeviceSize, GpuFamily},- error::MetalError,- kernel::MetalKernels,- },+ metal::{Metal, MetalContext, context::LARGE_MIN_GPU_CORES, error::MetalError, kernel::MetalKernels},},data_type::DataType,encodable_block::mixer::delta_net::tree_verify::{TreeVerifyEncodeArguments, TreeVerifyNewArguments},@@ -73,10 +70,10 @@ impl DeltaNetTreeVerify for MetalDeltaNetTreeVerify {context: &MetalContext,arguments: &TreeVerifyNewArguments,) -> Result<Self, MetalError> {- let use_mxu = arguments.data_type == DataType::BF16 && context.supports_mxu();+ let use_mxu = arguments.data_type == DataType::BF16 && context.supports_mxu;let transposed_h0 = !use_mxu- && context.device_profile().size() == DeviceSize::Small- && matches!(context.device_profile().gpu_family(), GpuFamily::Legacy | GpuFamily::Apple8);+ && context.gpu_core_count < LARGE_MIN_GPU_CORES+ && context.apple_gpu_family <= MTLGPUFamily::Apple8;Ok(Self {arguments: *arguments,prefix: <MetalKernels as Kernels>::BuildTreePrefixKernel::new(context)?,diff --git a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/kernel.rs b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/kernel.rsindex eb69e31b5..3b27f7299 100644--- a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/kernel.rs+++ b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/kernel.rs@@ -21,7 +21,6 @@ use crate::{metal::{Metal,context::MetalContext,- device_profile::DeviceProfile,error::MetalError,kernel::{GemmMetalKernel, GemmSplitKReduceMetalKernel, TensorAddBiasMetalKernel},},@@ -109,10 +108,15 @@ impl GemmKernel {fn problem(&self,shape: MatmulShape,- supports_mxu: bool,- profile: DeviceProfile,+ context: &MetalContext,) -> GemmProblem {- GemmProblem::new(shape, self.weights_data_type, self.output_data_type, supports_mxu, profile)+ GemmProblem::new(+ shape,+ self.weights_data_type,+ self.output_data_type,+ context.supports_mxu,+ context.apple_gpu_family,+ )}#[cfg(test)]@@ -122,7 +126,7 @@ impl GemmKernel {engine: GemmEngine,context: &MetalContext,) -> Result<GemmPlan, MetalError> {- self.problem(*shape, context.supports_mxu(), context.device_profile())+ self.problem(*shape, context).select_plan_for_engine(engine).map_err(|error| MetalError::KernelDispatchFailed(Box::new(error)))}@@ -146,7 +150,7 @@ impl GemmKernel {encoder: &mut Encoder<Metal>,) -> Result<(), MetalError> {let shape = MatmulShape::from_arguments(&arguments);- self.problem(shape, encoder.context().supports_mxu(), encoder.context().device_profile())+ self.problem(shape, encoder.context()).validate_engine(plan.engine).map_err(|error| MetalError::KernelDispatchFailed(Box::new(error)))?;diff --git a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/policy.rs b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/policy.rsindex fffdc926d..7a439b16e 100644--- a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/policy.rs+++ b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/policy.rs@@ -4,10 +4,9 @@//! features to choices. Eligibility, fallbacks, and legality stay in//! `selection.rs`.-use crate::backends::{- common::gpu_types::gemm::GemmTiling,- metal::device_profile::{DeviceProfile, GpuFamily},-};+use metal::MTLGPUFamily;++use crate::backends::common::gpu_types::gemm::GemmTiling;pub(super) const MXU_DEFAULT_TILE: GemmTiling = GemmTiling::Tile64x64x256_Simdgroups2x2;@@ -102,20 +101,20 @@ pub(super) fn simdgroup_fp_tile(/// A partial trailing M block costs a second pass over the weights. Older GPUs are bound by that;/// Apple9 and newer would rather keep the narrow tile's parallelism.-fn prefers_wide_partial_m_tile(profile: DeviceProfile) -> bool {- matches!(profile.gpu_family(), GpuFamily::Legacy | GpuFamily::Apple8)+fn prefers_wide_partial_m_tile(apple_gpu_family: MTLGPUFamily) -> bool {+ apple_gpu_family <= MTLGPUFamily::Apple8}pub(super) fn simdgroup_quant_tile(m: u32,n: u32,group_size: u32,- profile: DeviceProfile,+ apple_gpu_family: MTLGPUFamily,) -> GemmTiling {if group_size < 32 {GemmTiling::Tile64x64x16_Simdgroups2x2} else if m < SIMDGROUP_QUANT_SMALL_M_MAX {- if !prefers_wide_partial_m_tile(profile)+ if !prefers_wide_partial_m_tile(apple_gpu_family)|| m <= SIMDGROUP_QUANT_NARROW_BLOCK_M|| m.is_multiple_of(SIMDGROUP_QUANT_NARROW_BLOCK_M){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 8c3676138..6e5c0c8ae 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@@ -1,13 +1,11 @@+use metal::MTLGPUFamily;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},- },- metal::device_profile::DeviceProfile,+ backends::common::{+ gpu_types::gemm::{GemmBPrologueKind, GemmTiling},+ kernel::{activation_transform::ACTIVATION_SCALE_GROUP_SIZE, matmul::MatmulShape},},data_type::DataType,};@@ -18,7 +16,7 @@ pub struct GemmProblem {weights_data_type: DataType,output_data_type: DataType,supports_mxu: bool,- profile: DeviceProfile,+ apple_gpu_family: MTLGPUFamily,}#[derive(Debug, Clone, Copy, PartialEq, Error)]@@ -35,14 +33,14 @@ impl GemmProblem {weights_data_type: DataType,output_data_type: DataType,supports_mxu: bool,- profile: DeviceProfile,+ apple_gpu_family: MTLGPUFamily,) -> Self {Self {shape,weights_data_type,output_data_type,supports_mxu,- profile,+ apple_gpu_family,}}@@ -52,7 +50,7 @@ impl GemmProblem {} else {GemmEngine::Simdgroup};- self.finish_plan(engine, select_tiling(self.shape, engine, self.profile))+ self.finish_plan(engine, select_tiling(self.shape, engine, self.apple_gpu_family))}#[cfg(test)]@@ -61,7 +59,7 @@ impl GemmProblem {engine: GemmEngine,) -> Result<GemmPlan, GemmPlanError> {self.validate_engine(engine)?;- Ok(self.finish_plan(engine, select_tiling(self.shape, engine, self.profile)))+ Ok(self.finish_plan(engine, select_tiling(self.shape, engine, self.apple_gpu_family)))}pub(super) fn validate_engine(@@ -77,39 +75,6 @@ impl GemmProblem {Ok(())}- #[cfg(test)]- pub fn plan_is_legal(- self,- plan: GemmPlan,- ) -> bool {- use super::specialization::GemmSpecialization;- use crate::backends::common::gpu_types::gemm::{GemmAPrologueKind, GemmAlignment};-- if self.validate_engine(plan.engine).is_err()- || plan.engine == GemmEngine::Mxu && !plan.tiling.is_mxu_variant()- || plan.engine == GemmEngine::Simdgroup && plan.tiling.is_mxu_variant()- || plan.split_k == 0- || !self.shape.k.is_multiple_of(plan.split_k)- {- return false;- }- let alignment = GemmAlignment::new(- self.shape.m.is_multiple_of(plan.tiling.block_m()),- self.shape.n.is_multiple_of(plan.tiling.block_n()),- self.shape.k.is_multiple_of(plan.tiling.block_k()),- );- GemmSpecialization::from_plan(- plan,- self.shape,- self.weights_data_type,- self.shape.d_transform,- alignment,- GemmAPrologueKind::FullPrecision,- None,- )- .is_ok()- }-fn finish_plan(&self,engine: GemmEngine,@@ -199,11 +164,11 @@ fn mxu_is_eligible(shape: MatmulShape) -> bool {fn select_tiling(shape: MatmulShape,engine: GemmEngine,- profile: DeviceProfile,+ apple_gpu_family: MTLGPUFamily,) -> GemmTiling {match engine {GemmEngine::Simdgroup if shape.is_quant() => {- policy::simdgroup_quant_tile(shape.m, shape.n, shape.b_group_size.unwrap_or(0), profile)+ policy::simdgroup_quant_tile(shape.m, shape.n, shape.b_group_size.unwrap_or(0), apple_gpu_family)},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),diff --git a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemv/kernel.rs b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemv/kernel.rsindex 56ceb4e6a..a78ae14ed 100644--- a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemv/kernel.rs+++ b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemv/kernel.rs@@ -1,3 +1,5 @@+use metal::MTLGPUFamily;+use super::policy::{self, DEFAULT_RESULTS_PER_SIMDGROUP, FP_K_BLOCK};use crate::{backends::{@@ -8,7 +10,7 @@ use crate::{},kernel::matmul::MatmulShape,},- metal::{context::MetalContext, device_profile::DeviceProfile, error::MetalError, kernel::GemvMetalKernel},+ metal::{context::MetalContext, error::MetalError, kernel::GemvMetalKernel},},data_type::DataType,};@@ -34,24 +36,13 @@ pub struct GemvSpecialization {}impl GemvSpecialization {- #[cfg(test)]- pub fn tile(self) -> policy::GemvTile {- policy::GemvTile {- num_simdgroups: self.num_simdgroups,- k_split: self.k_split,- results_per_simdgroup: self.output_row_tile / (self.num_simdgroups / self.k_split),- input_row_tile: self.input_row_tile,- reduction_lanes: self.reduction_lanes,- group_lanes: self.group_lanes,- }- }-pub fn select_shape(shape: &MatmulShape,weights_data_type: DataType,input_data_type: DataType,output_data_type: DataType,- device_profile: DeviceProfile,+ gpu_core_count: u32,+ apple_gpu_family: MTLGPUFamily,) -> Option<Self> {let is_quant = shape.is_quant();let bits = shape.b_bits.unwrap_or(0);@@ -60,7 +51,8 @@ impl GemvSpecialization {policy::gathered_tile(bits, shape.b_group_size.unwrap_or(0), shape.m, shape.n)} else if is_quant {policy::quantized_tile(- device_profile,+ gpu_core_count,+ apple_gpu_family,bits,shape.b_group_size.unwrap_or(0),shape.m,@@ -79,7 +71,7 @@ impl GemvSpecialization {if shape.d_transform.contains(GemmDTransform::RHT) {Some(policy::DEFAULT_TILE)} else {- Some(policy::fp_tile(shape.m, shape.n, shape.k, input_aligned, device_profile))+ Some(policy::fp_tile(gpu_core_count, apple_gpu_family, shape.m, shape.n, shape.k, input_aligned))}};Self::select_tile(shape, weights_data_type, input_data_type, output_data_type, tile?)diff --git a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemv/policy.rs b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemv/policy.rsindex c410c67ed..c8d7e98d2 100644--- a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemv/policy.rs+++ b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemv/policy.rs@@ -1,4 +1,6 @@-use crate::backends::metal::device_profile::{DeviceProfile, DeviceSize, GpuFamily};+use metal::MTLGPUFamily;++use crate::backends::metal::context::LARGE_MIN_GPU_CORES;mod quantized;@@ -142,18 +144,18 @@ fn preferred_fp_k_split(/// Selects the full-precision GEMV tile. `m` is the input-vector count,/// `n` is the output row count, and `k` is the reduction depth.pub(super) fn fp_tile(+ gpu_core_count: u32,+ apple_gpu_family: MTLGPUFamily,m: u32,n: u32,k: u32,input_aligned: bool,- profile: DeviceProfile,) -> GemvTile {- let size = profile.size();- let gpu_family = profile.gpu_family();- let is_small_legacy = size == DeviceSize::Small && gpu_family == GpuFamily::Legacy;+ let is_large_gpu = gpu_core_count >= LARGE_MIN_GPU_CORES;+ let is_small_legacy = !is_large_gpu && apple_gpu_family < MTLGPUFamily::Apple8;// SG8 is the portable full-precision geometry.let should_disable_k_split = !input_aligned- || (m == 1 && size == DeviceSize::Large && k < FP_LARGE_SPLIT_K_MIN_DEPTH)+ || (m == 1 && is_large_gpu && k < FP_LARGE_SPLIT_K_MIN_DEPTH)|| (m == 1 && is_small_legacy && n >= SMALL_G13_HUGE_N);let k_split = if should_disable_k_split {@@ -164,7 +166,7 @@ pub(super) fn fp_tile(let results_per_simdgroup = if is_small_legacy && m == 1 && n >= SMALL_G13_BROAD_ROW_N {DEFAULT_RESULTS_PER_SIMDGROUP- } else if m == 1 && (k <= DEEP_K || size != DeviceSize::Large) {+ } else if m == 1 && (k <= DEEP_K || !is_large_gpu) {1} else {DEFAULT_RESULTS_PER_SIMDGROUPdiff --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 56bafba17..49876973f 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@@ -1,8 +1,7 @@+use metal::MTLGPUFamily;+use super::{DEFAULT_RESULTS_PER_SIMDGROUP, GemvTile};-use crate::backends::{- common::gpu_types::gemm::GemmDTransform,- metal::device_profile::{DeviceProfile, DeviceSize, GpuFamily},-};+use crate::backends::{common::gpu_types::gemm::GemmDTransform, metal::context::LARGE_MIN_GPU_CORES};const QUANT_N_BUCKET_MAXES: [u32; 6] = [512, 2048, 4096, 8192, 16384, 32768];const QUANT_K_BUCKET_MAXES: [u32; 3] = [512, 2048, 8192];@@ -54,21 +53,21 @@ fn table_bucket_index(}fn lane_policy(+ gpu_core_count: u32,+ apple_gpu_family: MTLGPUFamily,m: u32,n: u32,k: u32,bits: u32,group: u32,has_rht: bool,- profile: DeviceProfile,) -> GemvTile {- let size = profile.size();- let gpu_family = profile.gpu_family();+ let is_large_gpu = gpu_core_count >= LARGE_MIN_GPU_CORES;if m != 1 || bits != 4 {return lane_default(bits, group);}if has_rht {- return if size == DeviceSize::Large+ return if is_large_gpu&& n > QUANT_RHT_TUNED_N_MIN_EXCLUSIVE&& n <= QUANT_RHT_TUNED_N_MAX&& k >= QUANT_RHT_TUNED_K_MIN@@ -81,26 +80,26 @@ fn lane_policy(let k_bucket = table_bucket_index(k, &QUANT_K_BUCKET_MAXES);let n_bucket = table_bucket_index(n, &QUANT_N_BUCKET_MAXES);- let (num_simdgroups, results_per_simdgroup) = match (size, gpu_family, k_bucket, n_bucket) {- (DeviceSize::Large, _, 0, 1) => (4, 2),- (DeviceSize::Large, _, 1, 0) => (2, 1),- (DeviceSize::Large, _, 1, 1..=3) => (2, 2),- (DeviceSize::Large, _, 1, 4) => (2, 1),- (DeviceSize::Large, _, 1, 5) => (2, 4),- (DeviceSize::Large, _, 2, 1) => (4, 2),- (DeviceSize::Large, _, 3, 1) => (2, 2),- (DeviceSize::Small, GpuFamily::Apple9, 0, 1) => (4, 4),- (DeviceSize::Small, GpuFamily::Apple9, 1, 0) => (4, 2),- (DeviceSize::Small, GpuFamily::Apple9, 1, 1) => (2, 2),- (DeviceSize::Small, GpuFamily::Apple9, 1, 2) => (4, 2),- (DeviceSize::Small, GpuFamily::Apple9, 1, 4) => (2, 2),- (DeviceSize::Small, GpuFamily::Apple9, 1, 5) => (4, 2),- (DeviceSize::Small, GpuFamily::Apple9, 2, 1) => (4, 2),- (DeviceSize::Small, GpuFamily::Apple9, 3, 1) => (2, 2),- (DeviceSize::Small, GpuFamily::Apple8, 0, 1) => (4, 4),- (DeviceSize::Small, GpuFamily::Apple8, 1, _) | (DeviceSize::Small, GpuFamily::Apple8, 2, 1) => (8, 2),- (DeviceSize::Small, GpuFamily::Legacy, 0, 1) => (4, 8),- (DeviceSize::Small, GpuFamily::Legacy, 1, 0..=3) => (8, 2),+ let (num_simdgroups, results_per_simdgroup) = match (is_large_gpu, apple_gpu_family, k_bucket, n_bucket) {+ (true, _, 0, 1) => (4, 2),+ (true, _, 1, 0) => (2, 1),+ (true, _, 1, 1..=3) => (2, 2),+ (true, _, 1, 4) => (2, 1),+ (true, _, 1, 5) => (2, 4),+ (true, _, 2, 1) => (4, 2),+ (true, _, 3, 1) => (2, 2),+ (false, MTLGPUFamily::Apple9, 0, 1) => (4, 4),+ (false, MTLGPUFamily::Apple9, 1, 0) => (4, 2),+ (false, MTLGPUFamily::Apple9, 1, 1) => (2, 2),+ (false, MTLGPUFamily::Apple9, 1, 2) => (4, 2),+ (false, MTLGPUFamily::Apple9, 1, 4) => (2, 2),+ (false, MTLGPUFamily::Apple9, 1, 5) => (4, 2),+ (false, MTLGPUFamily::Apple9, 2, 1) => (4, 2),+ (false, MTLGPUFamily::Apple9, 3, 1) => (2, 2),+ (false, MTLGPUFamily::Apple8, 0, 1) => (4, 4),+ (false, MTLGPUFamily::Apple8, 1, _) | (false, MTLGPUFamily::Apple8, 2, 1) => (8, 2),+ (false, family, 0, 1) if family < MTLGPUFamily::Apple8 => (4, 8),+ (false, family, 1, 0..=3) if family < MTLGPUFamily::Apple8 => (8, 2),_ => (8, 4),};let selected = lane_tile(num_simdgroups, results_per_simdgroup, bits, group);@@ -112,7 +111,8 @@ fn lane_policy(}pub fn select(- profile: DeviceProfile,+ gpu_core_count: u32,+ apple_gpu_family: MTLGPUFamily,bits: u32,group: u32,m: u32,@@ -132,7 +132,7 @@ pub fn select(let has_rht = d_transform.contains(GemmDTransform::RHT);let tile = match m {- 1..=4 => lane_policy(m, n, k, bits, group, has_rht, profile),+ 1..=4 => lane_policy(gpu_core_count, apple_gpu_family, m, n, k, bits, group, has_rht),5..=8 if n <= 64 => lane_default(bits, group),_ => return None,};diff --git a/crates/uzu-engine/src/backends/metal/kernel/matmul/mod.rs b/crates/uzu-engine/src/backends/metal/kernel/matmul/mod.rsindex 2139f6cca..14fa5a4c1 100644--- a/crates/uzu-engine/src/backends/metal/kernel/matmul/mod.rs+++ b/crates/uzu-engine/src/backends/metal/kernel/matmul/mod.rs@@ -2,6 +2,8 @@ pub mod gemm;mod gemv;mod qmv;+use metal::MTLGPUFamily;+pub use self::gemm::GemmKernel;use self::{gemm::{GemmPlan, GemmProblem},@@ -68,7 +70,9 @@ impl MatmulMetalKernel {fn choose_dispatch(shape: &MatmulShape,- profile: crate::backends::metal::device_profile::DeviceProfile,+ device_name: &str,+ gpu_core_count: u32,+ apple_gpu_family: MTLGPUFamily,supports_mxu: bool,weights_data_type: DataType,input_data_type: DataType,@@ -77,7 +81,7 @@ impl MatmulMetalKernel {let all_bf16 = weights_data_type == DataType::BF16&& input_data_type == DataType::BF16&& output_data_type == DataType::BF16;- if let Some(route) = qmv::route(profile, shape, all_bf16) {+ if let Some(route) = qmv::route(device_name, apple_gpu_family, supports_mxu, shape, all_bf16) {return match route {QmvRoute::Tuned(tile) | QmvRoute::MainGemv(tile) => MatmulDispatch::Gemv(GemvSpecialization::select_tile(shape, weights_data_type, input_data_type, output_data_type, tile)@@ -86,9 +90,15 @@ impl MatmulMetalKernel {QmvRoute::MainGemm(plan) => MatmulDispatch::Gemm(plan),};}- let gemv =- GemvSpecialization::select_shape(shape, weights_data_type, input_data_type, output_data_type, profile);- let problem = GemmProblem::new(*shape, weights_data_type, output_data_type, supports_mxu, profile);+ let gemv = GemvSpecialization::select_shape(+ shape,+ weights_data_type,+ input_data_type,+ output_data_type,+ gpu_core_count,+ apple_gpu_family,+ );+ let problem = GemmProblem::new(*shape, weights_data_type, output_data_type, supports_mxu, apple_gpu_family);let plan = problem.select_plan();match gemv {None => MatmulDispatch::Gemm(plan),@@ -108,8 +118,10 @@ impl MatmulMetalKernel {) -> MatmulDispatch {Self::choose_dispatch(shape,- context.device_profile(),- context.supports_mxu(),+ &context.device_name,+ context.gpu_core_count,+ context.apple_gpu_family,+ context.supports_mxu,self.weights_data_type,self.input_data_type,self.output_data_type,@@ -150,7 +162,10 @@ impl MatmulKernel for MatmulMetalKernel {context: &MetalContext,) -> Option<A8ActivationPlan> {let activation_group_size = ACTIVATION_SCALE_GROUP_SIZE;- if !context.supports_mxu()+ let Some(weight_group_size @ (32 | 64 | 128)) = shape.b_group_size else {+ return None;+ };+ if !context.supports_mxu|| self.input_data_type != DataType::BF16|| self.output_data_type != DataType::BF16|| shape.a_full_precision@@ -159,9 +174,8 @@ impl MatmulKernel for MatmulMetalKernel {|| !shape.b_transpose|| shape.b_leading_dimension.is_some()|| !matches!(shape.b_bits, Some(4 | 8))- || !matches!(shape.b_group_size, Some(32 | 64 | 128))|| !shape.k.is_multiple_of(activation_group_size)- || !shape.k.is_multiple_of(shape.b_group_size.unwrap())+ || !shape.k.is_multiple_of(weight_group_size){return None;}@@ -169,7 +183,7 @@ impl MatmulKernel for MatmulMetalKernel {let sum_group_size = match shape.b_prologue {GemmBPrologueKind::ScaleSymmetricDequant => None,GemmBPrologueKind::ScaleBiasDequant | GemmBPrologueKind::ScaleZeroPointDequant => {- Some(shape.b_group_size.unwrap().min(activation_group_size))+ Some(weight_group_size.min(activation_group_size))},GemmBPrologueKind::FullPrecision => return None,};diff --git a/crates/uzu-engine/src/backends/metal/kernel/matmul/qmv/routes.rs b/crates/uzu-engine/src/backends/metal/kernel/matmul/qmv/routes.rsindex 2ace699b2..d9f42d111 100644--- a/crates/uzu-engine/src/backends/metal/kernel/matmul/qmv/routes.rs+++ b/crates/uzu-engine/src/backends/metal/kernel/matmul/qmv/routes.rs@@ -1,5 +1,7 @@// Qwen3.6-27B W4/ZP and W8/Symmetric, G32/G64.// Tuned on M1, M2, M2 Pro, M3 Max, M4, M4 Pro, M5 Max.+use metal::MTLGPUFamily;+use super::{super::{gemm::{GemmEngine, GemmPlan},@@ -7,12 +9,9 @@ use super::{},QmvRoute,};-use crate::backends::{- common::{- gpu_types::gemm::{GemmBPrologueKind, GemmTiling},- kernel::matmul::MatmulShape,- },- metal::device_profile::{DeviceIdentity, DeviceProfile},+use crate::backends::common::{+ gpu_types::gemm::{GemmBPrologueKind, GemmTiling},+ kernel::matmul::MatmulShape,};const DOWN: u8 = 1 << 0;@@ -25,7 +24,8 @@ const READOUT: u8 = 1 << 6;#[derive(Clone, Copy)]struct RouteRow {- identity: DeviceIdentity,+ device_name: &'static str,+ apple_gpu_family: MTLGPUFamily,bits: u32,group: u32,m: u32,@@ -58,7 +58,11 @@ macro_rules! main_gemm { ($engine:ident, $tiling:ident, $split:literal) => { Qmv#[rustfmt::skip]macro_rules! qmv_format { (w4_zp_g32) => { (4, 32) }; (w4_zp_g64) => { (4, 64) }; (w8_sym_g32) => { (8, 32) }; (w8_sym_g64) => { (8, 64) }; }#[rustfmt::skip]-macro_rules! row { ($identity:ident, $format:ident, $m:literal, $shapes:expr, $route:expr) => { RouteRow { identity: DeviceIdentity::$identity, bits: qmv_format!($format).0, group: qmv_format!($format).1, m: $m, shapes: $shapes, route: $route } }; }+macro_rules! measured_device_name { (M1) => { "Apple M1" }; (M2) => { "Apple M2" }; (M2Pro) => { "Apple M2 Pro" }; (M3Max) => { "Apple M3 Max" }; (M4) => { "Apple M4" }; (M4Pro) => { "Apple M4 Pro" }; (M5Max) => { "Apple M5 Max" }; }+#[rustfmt::skip]+macro_rules! measured_apple_gpu_family { (M1) => { MTLGPUFamily::Apple7 }; (M2) => { MTLGPUFamily::Apple8 }; (M2Pro) => { MTLGPUFamily::Apple8 }; (M3Max) => { MTLGPUFamily::Apple9 }; (M4) => { MTLGPUFamily::Apple9 }; (M4Pro) => { MTLGPUFamily::Apple9 }; (M5Max) => { MTLGPUFamily::Apple10 }; }+#[rustfmt::skip]+macro_rules! row { ($device:ident, $format:ident, $m:literal, $shapes:expr, $route:expr) => { RouteRow { device_name: measured_device_name!($device), apple_gpu_family: measured_apple_gpu_family!($device), bits: qmv_format!($format).0, group: qmv_format!($format).1, m: $m, shapes: $shapes, route: $route } }; }#[rustfmt::skip]const ROWS: &[RouteRow] = &[@@ -371,7 +375,9 @@ fn qmv_format(shape: &MatmulShape) -> Option<(u32, u32)> {}pub fn route(- device: DeviceProfile,+ device_name: &str,+ apple_gpu_family: MTLGPUFamily,+ supports_mxu: bool,shape: &MatmulShape,all_bf16: bool,) -> Option<QmvRoute> {@@ -393,8 +399,8 @@ pub fn route(let matches =|row: &&RouteRow| row.bits == bits && row.group == group && row.m == shape.m && row.shapes & mask != 0;let route =- ROWS.iter().filter(matches).find(|row| row.identity == device.identity()).map(|row| row.route).or_else(|| {- let same_family = |row: &&RouteRow| device.gpu_family().contains(row.identity);+ ROWS.iter().filter(matches).find(|row| row.device_name == device_name).map(|row| row.route).or_else(|| {+ let same_family = |row: &&RouteRow| row.apple_gpu_family == apple_gpu_family;let mut routes = ROWS.iter().filter(matches).filter(same_family).map(|row| row.route);let route = routes.next()?;routes.all(|candidate| candidate == route).then_some(route)@@ -406,7 +412,7 @@ pub fn route(engine: GemmEngine::Mxu,..})- ) || device.supports_mxu()+ ) || supports_mxu})}diff --git a/crates/uzu-engine/src/backends/metal/metal_extensions/device_extensions.rs b/crates/uzu-engine/src/backends/metal/metal_extensions/device_extensions.rsindex 1fbdec746..02bd38d86 100644--- a/crates/uzu-engine/src/backends/metal/metal_extensions/device_extensions.rs+++ b/crates/uzu-engine/src/backends/metal/metal_extensions/device_extensions.rs@@ -1,7 +1,7 @@use core::mem::transmute;use std::ffi::CString;-use metal::MTLDevice;+use metal::{MTLDevice, MTLGPUFamily};use obfstr::obfstr;use objc2::{Message,@@ -9,6 +9,8 @@ use objc2::{runtime::{NSObjectProtocol, ProtocolObject, Sel},};+use super::GpuFamilyExt;+// Used to bypass objc2's debug-mode class validation for proxy objects like// `CaptureMTLDevice` which forward messages at the ObjC runtime level (via// `forwardingTargetForSelector:`) but don't have the methods in their own class@@ -70,6 +72,15 @@ pub trait DeviceExt: MTLDevice + Message + NSObjectProtocol + Sized {fn supports_placement_sparse_resources(&self) -> bool {optional_selector_value(self, obfstr!("supportsPlacementSparse"), false)}++ /// Newest Apple GPU family the device supports.+ fn newest_supported_apple_gpu_family(&self) -> MTLGPUFamily {+ MTLGPUFamily::all_cases()+ .into_iter()+ .rev()+ .find(|family| self.supports_family(*family))+ .expect("unsupported Metal device: uzu requires an Apple GPU")+ }}impl DeviceExt for ProtocolObject<dyn MTLDevice> {}diff --git a/crates/uzu-engine/src/backends/metal/metal_extensions/gpu_family_extensions.rs b/crates/uzu-engine/src/backends/metal/metal_extensions/gpu_family_extensions.rsnew file mode 100644index 000000000..a376ad86c--- /dev/null+++ b/crates/uzu-engine/src/backends/metal/metal_extensions/gpu_family_extensions.rs@@ -0,0 +1,23 @@+use metal::MTLGPUFamily;++pub trait GpuFamilyExt: Sized {+ /// All Apple GPU family cases, oldest to newest.+ fn all_cases() -> [Self; 10];+}++impl GpuFamilyExt for MTLGPUFamily {+ fn all_cases() -> [Self; 10] {+ [+ Self::Apple1,+ Self::Apple2,+ Self::Apple3,+ Self::Apple4,+ Self::Apple5,+ Self::Apple6,+ Self::Apple7,+ Self::Apple8,+ Self::Apple9,+ Self::Apple10,+ ]+ }+}diff --git a/crates/uzu-engine/src/backends/metal/metal_extensions/library_extensions_pipeline.rs b/crates/uzu-engine/src/backends/metal/metal_extensions/library_extensions_pipeline.rsindex d57731d2c..887383597 100644--- a/crates/uzu-engine/src/backends/metal/metal_extensions/library_extensions_pipeline.rs+++ b/crates/uzu-engine/src/backends/metal/metal_extensions/library_extensions_pipeline.rs@@ -21,12 +21,13 @@ impl LibraryPipelineExtensions for ProtocolObject<dyn MTLLibrary> {constants: Option<&MTLFunctionConstantValues>,) -> Result<Retained<ProtocolObject<dyn MTLComputePipelineState>>, MetalError> {let function = match constants {- Some(const_values) => {- self.new_function_with_name_constant_values_error(function_name, const_values, std::ptr::null_mut())- },- None => self.new_function_with_name(function_name),- }- .ok_or_else(|| MetalError::CannotCreateFunction(function_name.to_owned()))?;+ Some(const_values) => self+ .new_function_with_name_constant_values(function_name, const_values)+ .map_err(|error| MetalError::CannotCreateFunction(format!("{function_name}: {error}")))?,+ None => self+ .new_function_with_name(function_name)+ .ok_or_else(|| MetalError::CannotCreateFunction(function_name.to_owned()))?,+ };let device = self.device();diff --git a/crates/uzu-engine/src/backends/metal/metal_extensions/mod.rs b/crates/uzu-engine/src/backends/metal/metal_extensions/mod.rsindex 3476c3a4f..67889fcfb 100644--- a/crates/uzu-engine/src/backends/metal/metal_extensions/mod.rs+++ b/crates/uzu-engine/src/backends/metal/metal_extensions/mod.rs@@ -2,6 +2,7 @@ mod compute_command_encoder_extensions_set_value;mod data_type;mod device_extensions;mod function_constant_values_extensions_set_value;+mod gpu_family_extensions;mod library_extensions_pipeline;mod sparse_page_size_extensions;@@ -9,5 +10,6 @@ pub use compute_command_encoder_extensions_set_value::ComputeEncoderSetValue;pub use data_type::MetalDataTypeExt;pub use device_extensions::DeviceExt;pub use function_constant_values_extensions_set_value::FunctionConstantValuesSetValue;+pub use gpu_family_extensions::GpuFamilyExt;pub use library_extensions_pipeline::LibraryPipelineExtensions;pub use sparse_page_size_extensions::SparsePageSizeExt;diff --git a/crates/uzu-engine/src/backends/metal/mod.rs b/crates/uzu-engine/src/backends/metal/mod.rsindex d03f39fce..428aec8e5 100644--- a/crates/uzu-engine/src/backends/metal/mod.rs+++ b/crates/uzu-engine/src/backends/metal/mod.rs@@ -3,7 +3,6 @@ mod buffer;mod command_buffer;mod context;mod dense_buffer;-mod device_profile;mod error;mod kernel;mod metal_extensions;diff --git a/crates/uzu-engine/unit/backends/common/kernel/gdn/tree_verify/out_bench.rs b/crates/uzu-engine/unit/backends/common/kernel/gdn/tree_verify/out_bench.rsindex 9a6b64456..54c6a5679 100644--- a/crates/uzu-engine/unit/backends/common/kernel/gdn/tree_verify/out_bench.rs+++ b/crates/uzu-engine/unit/backends/common/kernel/gdn/tree_verify/out_bench.rs@@ -88,7 +88,7 @@ fn bench_build_tree_out_type<T: ArrayElement + Float>(data_type_name: &str,) {for &(path, use_mxu, transposed_h0, tile_rows) in BUILD_TREE_OUT_PATHS {- if use_mxu && !context.supports_mxu() {+ if use_mxu && !context.supports_mxu {continue;}let tile_name = format!("Rows{tile_rows}_VCols{TREE_OUT_VALUE_COLS}_SG{TREE_OUT_SIMDGROUPS_PER_TG}");diff --git a/crates/uzu-engine/unit/backends/common/kernel/gdn/tree_verify/out_test.rs b/crates/uzu-engine/unit/backends/common/kernel/gdn/tree_verify/out_test.rsindex 256a1787e..75889593f 100644--- a/crates/uzu-engine/unit/backends/common/kernel/gdn/tree_verify/out_test.rs+++ b/crates/uzu-engine/unit/backends/common/kernel/gdn/tree_verify/out_test.rs@@ -146,7 +146,7 @@ fn check_shape<T: ArrayElement + Float + std::fmt::Display>(}});- if <Metal as Backend>::Context::new().expect("Failed to create Context").supports_mxu() {+ if <Metal as Backend>::Context::new().expect("Failed to create Context").supports_mxu {for &(path, use_mxu, transposed_h0) in BUILD_TREE_OUT_PATHS {if !use_mxu || transposed_h0 && !use_h0 {continue;diff --git a/crates/uzu-engine/unit/backends/common/kernel/gdn/tree_verify/tree_gram_bench.rs b/crates/uzu-engine/unit/backends/common/kernel/gdn/tree_verify/tree_gram_bench.rsindex be3d7eaf0..d4461df34 100644--- a/crates/uzu-engine/unit/backends/common/kernel/gdn/tree_verify/tree_gram_bench.rs+++ b/crates/uzu-engine/unit/backends/common/kernel/gdn/tree_verify/tree_gram_bench.rs@@ -148,7 +148,7 @@ fn buffers_bytes(#[uzu_bench]fn bench_build_tree_gram(c: &mut Criterion) {let context = <Metal as Backend>::Context::new().expect("metal context");- let kernel_paths = if context.supports_mxu() {+ let kernel_paths = if context.supports_mxu {&[("Simdgroup", false), ("MXU", true)][..]} else {&[("Simdgroup", false)][..]diff --git a/crates/uzu-engine/unit/backends/common/kernel/gdn/tree_verify/tree_gram_test.rs b/crates/uzu-engine/unit/backends/common/kernel/gdn/tree_verify/tree_gram_test.rsindex 31cb98683..6359fed74 100644--- a/crates/uzu-engine/unit/backends/common/kernel/gdn/tree_verify/tree_gram_test.rs+++ b/crates/uzu-engine/unit/backends/common/kernel/gdn/tree_verify/tree_gram_test.rs@@ -158,7 +158,7 @@ fn check_type<T: ArrayElement + Float>(assert_eq_float::<f32>(&expected.3, &actual.3, 2e-4, &format!("kh0 {msg}"));});- if <Metal as Backend>::Context::new().expect("Failed to create Context").supports_mxu() {+ if <Metal as Backend>::Context::new().expect("Failed to create Context").supports_mxu {let actual = get_output::<Metal, T>(&q,&k,diff --git a/crates/uzu-engine/unit/backends/common/kernel/matmul/a8w_bench.rs b/crates/uzu-engine/unit/backends/common/kernel/matmul/a8w_bench.rsindex ae7a6de50..21131ac60 100644--- a/crates/uzu-engine/unit/backends/common/kernel/matmul/a8w_bench.rs+++ b/crates/uzu-engine/unit/backends/common/kernel/matmul/a8w_bench.rs@@ -249,7 +249,7 @@ fn bench_bits(#[uzu_bench]fn bench_a8w(c: &mut Criterion) {let context = shared_metal_context();- if !context.supports_mxu() {+ if !context.supports_mxu {return;}let prepare = ActivationTransform::<Metal>::quantize(&context, DataType::BF16, 128, None).expect("prepare kernel");diff --git a/crates/uzu-engine/unit/backends/common/kernel/matmul/dispatch_paths_test.rs b/crates/uzu-engine/unit/backends/common/kernel/matmul/dispatch_paths_test.rsindex ea357815a..59f13f8a7 100644--- a/crates/uzu-engine/unit/backends/common/kernel/matmul/dispatch_paths_test.rs+++ b/crates/uzu-engine/unit/backends/common/kernel/matmul/dispatch_paths_test.rs@@ -27,7 +27,7 @@ use crate::{fn gemm_engines_for_hw(context: &MetalContext) -> Vec<GemmEngine> {let mut engines = vec![GemmEngine::Simdgroup];- if context.supports_mxu() {+ if context.supports_mxu {engines.push(GemmEngine::Mxu);}enginesdiff --git a/crates/uzu-engine/unit/backends/common/kernel/matmul/gemm_bench.rs b/crates/uzu-engine/unit/backends/common/kernel/matmul/gemm_bench.rsindex 58ef6912b..3d49bc736 100644--- a/crates/uzu-engine/unit/backends/common/kernel/matmul/gemm_bench.rs+++ b/crates/uzu-engine/unit/backends/common/kernel/matmul/gemm_bench.rs@@ -34,7 +34,7 @@ fn bench_gemm(c: &mut Criterion) {).expect("MatmulKernel");- let engines: &[(&str, GemmEngine)] = if context.supports_mxu() {+ let engines: &[(&str, GemmEngine)] = if context.supports_mxu {&[("GEMM", GemmEngine::Simdgroup), ("GEMM_MXU", GemmEngine::Mxu)]} else {&[("GEMM", GemmEngine::Simdgroup)]diff --git a/crates/uzu-engine/unit/backends/common/kernel/matmul/quant_dispatch_test.rs b/crates/uzu-engine/unit/backends/common/kernel/matmul/quant_dispatch_test.rsindex 6f8197bfd..77d510c6b 100644--- a/crates/uzu-engine/unit/backends/common/kernel/matmul/quant_dispatch_test.rs+++ b/crates/uzu-engine/unit/backends/common/kernel/matmul/quant_dispatch_test.rs@@ -467,7 +467,7 @@ fn mxu_quant_parity_bf16(#[case] method: QuantizationMethod,) {let context = MetalContext::new().expect("Metal context");- if !context.supports_mxu() {+ if !context.supports_mxu {return;}let input = QuantInput::<bf16>::new(m, k, n, gs, bits, method, 0);@@ -503,7 +503,7 @@ fn a8w_mxu_parity_bf16(#[case] method: QuantizationMethod,) {let context = MetalContext::new().expect("Metal context");- if !context.supports_mxu() {+ if !context.supports_mxu {return;}let (k, n) = (256u32, 128u32);@@ -529,7 +529,7 @@ fn a8w_mxu_parity_bf16(#[case::m33(33u32)]fn a8w_independent_activation_group_parity_bf16(#[case] m: u32) {let context = MetalContext::new().expect("Metal context");- if !context.supports_mxu() {+ if !context.supports_mxu {return;}@@ -566,7 +566,7 @@ fn a8w_independent_activation_group_parity_bf16(#[case] m: u32) {#[case::m33(33)]fn a8w4_zero_point_tail_parity(#[case] m: u32) {let context = MetalContext::new().expect("Metal context");- if !context.supports_mxu() {+ if !context.supports_mxu {return;}let input = QuantInput::<bf16>::new(m, 256, 72, 32, 4, QuantizationMethod::ScaleZeroPoint, 0)@@ -579,7 +579,7 @@ fn a8w4_zero_point_tail_parity(#[case] m: u32) {#[uzu_test]fn a8w4_zero_point_tail_signed_codes_parity() {let context = MetalContext::new().expect("Metal context");- if !context.supports_mxu() {+ if !context.supports_mxu {return;}let input = QuantInput::<bf16>::new(33, 256, 72, 32, 4, QuantizationMethod::ScaleZeroPoint, 0)@@ -633,7 +633,7 @@ fn a8w_mxu_output_bias_parity_bf16(#[case] with_output_hadamard: bool,) {let context = MetalContext::new().expect("Metal context");- if !context.supports_mxu() {+ if !context.supports_mxu {return;}diff --git a/crates/uzu-engine/unit/backends/common/kernel/matmul/quant_gemm_bench.rs b/crates/uzu-engine/unit/backends/common/kernel/matmul/quant_gemm_bench.rsindex e3f463551..265599eb8 100644--- a/crates/uzu-engine/unit/backends/common/kernel/matmul/quant_gemm_bench.rs+++ b/crates/uzu-engine/unit/backends/common/kernel/matmul/quant_gemm_bench.rs@@ -29,7 +29,7 @@ fn bench_unified_quant_typed<T: ArrayElement + Float>(bits: u32,quant_method: QuantizationMethod,) {- let supports_mxu = context.supports_mxu();+ let supports_mxu = context.supports_mxu;let engines: &[(&str, GemmEngine)] = if supports_mxu {&[("Simdgroup", GemmEngine::Simdgroup), ("Mxu", GemmEngine::Mxu)]} else {diff --git a/crates/uzu-engine/unit/backends/metal/device_profile_test.rs b/crates/uzu-engine/unit/backends/metal/device_profile_test.rsdeleted file mode 100644index a2749db57..000000000--- a/crates/uzu-engine/unit/backends/metal/device_profile_test.rs+++ /dev/null@@ -1,100 +0,0 @@-use uzu_engine_macros::uzu_test;--use super::*;--#[uzu_test]-fn device_profile_detection() {- let cases = [- ("Apple A18 Pro", 6, false, DeviceIdentity::A18Pro, GpuFamily::Apple9, DeviceSize::Small),- ("Apple M3 Ultra", 80, false, DeviceIdentity::M3Ultra, GpuFamily::Apple9, DeviceSize::Large),- ("Apple M4 Max", 40, false, DeviceIdentity::M4Max, GpuFamily::Apple9, DeviceSize::Large),- ("Apple M5 Max", 40, true, DeviceIdentity::M5Max, GpuFamily::M5Plus, DeviceSize::Large),- ("Apple M5 Ultra", 80, true, DeviceIdentity::M5Ultra, GpuFamily::M5Plus, DeviceSize::Large),- ("Apple M3 Pro", 20, false, DeviceIdentity::M3Pro, GpuFamily::Apple9, DeviceSize::Small),- ("Apple M2", 10, false, DeviceIdentity::M2, GpuFamily::Apple8, DeviceSize::Small),- ("Apple M1", 8, false, DeviceIdentity::M1, GpuFamily::Legacy, DeviceSize::Small),- ];- for (name, cores, mxu, identity, family, size) in cases {- let profile = classify_device(name, cores, mxu);- assert_eq!(profile.identity(), identity);- assert_eq!(profile.gpu_family(), family);- assert_eq!(profile.size(), size);- assert_eq!(profile.supports_mxu(), mxu);- }-}--#[uzu_test]-fn family_detection_does_not_use_mxu_as_generation_proxy() {- let m5_without_mxu = classify_device("Apple M5", 12, false);- let m4_with_mxu = classify_device("Apple M4", 10, true);-- assert_eq!(m5_without_mxu.gpu_family(), GpuFamily::M5Plus);- assert!(!m5_without_mxu.supports_mxu());- assert_eq!(m4_with_mxu.gpu_family(), GpuFamily::Apple9);- assert!(m4_with_mxu.supports_mxu());-}--#[uzu_test]-fn phone_device_profiles_follow_apple_gpu_families() {- let cases = [- ("Apple A14 GPU", DeviceIdentity::A14, GpuFamily::Legacy),- ("Apple A15 GPU", DeviceIdentity::A15, GpuFamily::Apple8),- ("Apple A16 GPU", DeviceIdentity::A16, GpuFamily::Apple8),- ("Apple A17 Pro GPU", DeviceIdentity::A17Pro, GpuFamily::Apple9),- ("Apple A18 GPU", DeviceIdentity::A18, GpuFamily::Apple9),- ("Apple A18 Pro GPU", DeviceIdentity::A18Pro, GpuFamily::Apple9),- ("Apple A19 GPU", DeviceIdentity::A19, GpuFamily::M5Plus),- ("Apple A19 Pro GPU", DeviceIdentity::A19Pro, GpuFamily::M5Plus),- ];- for (name, identity, family) in cases {- let profile = classify_device(name, 6, false);- assert_eq!(profile.identity(), identity);- assert_eq!(profile.gpu_family(), family);- }-}--#[uzu_test]-fn mac_device_identities_remain_distinct() {- let cases = [- ("Apple M1", DeviceIdentity::M1),- ("Apple M1 Pro", DeviceIdentity::M1Pro),- ("Apple M1 Max", DeviceIdentity::M1Max),- ("Apple M1 Ultra", DeviceIdentity::M1Ultra),- ("Apple M2", DeviceIdentity::M2),- ("Apple M2 Pro", DeviceIdentity::M2Pro),- ("Apple M2 Max", DeviceIdentity::M2Max),- ("Apple M2 Ultra", DeviceIdentity::M2Ultra),- ("Apple M3", DeviceIdentity::M3),- ("Apple M3 Pro", DeviceIdentity::M3Pro),- ("Apple M3 Max", DeviceIdentity::M3Max),- ("Apple M3 Ultra", DeviceIdentity::M3Ultra),- ("Apple M4", DeviceIdentity::M4),- ("Apple M4 Pro", DeviceIdentity::M4Pro),- ("Apple M4 Max", DeviceIdentity::M4Max),- ("Apple M5", DeviceIdentity::M5),- ("Apple M5 Pro", DeviceIdentity::M5Pro),- ("Apple M5 Max", DeviceIdentity::M5Max),- ("Apple M5 Ultra", DeviceIdentity::M5Ultra),- ];- for (name, expected) in cases {- assert_eq!(classify_device(name, 16, false).identity(), expected);- }-}--#[uzu_test]-fn mobile_m_series_names_accept_the_gpu_suffix() {- assert_eq!(classify_device("Apple M1 GPU", 8, false).identity(), DeviceIdentity::M1);-}--#[uzu_test]-fn untuned_devices_keep_their_identity_and_family() {- let m1_ultra = classify_device("Apple M1 Ultra", 64, false);- assert_eq!(m1_ultra.identity(), DeviceIdentity::M1Ultra);- assert_eq!(m1_ultra.gpu_family(), GpuFamily::Legacy);-}--#[uzu_test]-fn core_count_is_reduced_to_device_size() {- assert_eq!(classify_device("Apple M1 Max", 24, false).size(), DeviceSize::Small);- assert_eq!(classify_device("Apple M1 Max", 32, false).size(), DeviceSize::Large);-}diff --git a/crates/uzu-engine/unit/backends/metal/kernel/matmul/gemm/selection_test.rs b/crates/uzu-engine/unit/backends/metal/kernel/matmul/gemm/selection_test.rsindex 018f92f72..6ab2041a4 100644--- a/crates/uzu-engine/unit/backends/metal/kernel/matmul/gemm/selection_test.rs+++ b/crates/uzu-engine/unit/backends/metal/kernel/matmul/gemm/selection_test.rs@@ -1,17 +1,12 @@+use metal::MTLGPUFamily;use uzu_engine_macros::uzu_test;use super::{super::specialization::GemmSpecialization, *};use crate::backends::{common::gpu_types::gemm::{GemmAPrologueKind, GemmAlignment, GemmDTransform},- metal::{- device_profile::{DeviceIdentity, DeviceProfile, DeviceSize},- kernel::matmul::MatmulMetalKernel,- },+ metal::kernel::matmul::MatmulMetalKernel,};-const LEGACY_PROFILE: DeviceProfile = DeviceProfile::new(DeviceIdentity::M1, DeviceSize::Small, false);-const APPLE9_PROFILE: DeviceProfile = DeviceProfile::new(DeviceIdentity::M4, DeviceSize::Small, false);-fn shape(m: u32,n: u32,@@ -45,7 +40,7 @@ fn problem(shape: MatmulShape,output_data_type: DataType,) -> GemmProblem {- GemmProblem::new(shape, DataType::BF16, output_data_type, true, LEGACY_PROFILE)+ GemmProblem::new(shape, DataType::BF16, output_data_type, true, MTLGPUFamily::Apple7)}fn plan(split_k: u32) -> GemmPlan {@@ -96,12 +91,19 @@ fn policy_boundaries_are_preserved() {(64, 6143, 32, Tile32x32x32_Simdgroups2x2),(64, 6144, 32, Tile64x64x32_Simdgroups2x2),] {- assert_eq!(policy::simdgroup_quant_tile(m, n, group_size, LEGACY_PROFILE), expected);+ assert_eq!(policy::simdgroup_quant_tile(m, n, group_size, MTLGPUFamily::Apple7), expected);}- // Apple9 and newer keep the narrow tile regardless.- for m in [9, 15, 31] {- assert_eq!(policy::simdgroup_quant_tile(m, 4096, 32, APPLE9_PROFILE), Tile8x32x32_Simdgroups1x1);+ // Apple8 retains the older wide-tile policy; Apple9 and newer keep the narrow tile.+ for apple_gpu_family in [MTLGPUFamily::Apple7, MTLGPUFamily::Apple8] {+ for m in [9, 15, 31] {+ assert_eq!(policy::simdgroup_quant_tile(m, 4096, 32, apple_gpu_family), Tile32x32x32_Simdgroups2x2);+ }+ }+ for apple_gpu_family in [MTLGPUFamily::Apple9, MTLGPUFamily::Apple10] {+ for m in [9, 15, 31] {+ assert_eq!(policy::simdgroup_quant_tile(m, 4096, 32, apple_gpu_family), Tile8x32x32_Simdgroups1x1);+ }}}@@ -137,7 +139,10 @@ fn selection_fallbacks_and_split_k_are_preserved() {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, LEGACY_PROFILE).select_plan().split_k, 1);+ assert_eq!(+ GemmProblem::new(biased, DataType::BF16, DataType::F32, true, MTLGPUFamily::Apple7).select_plan().split_k,+ 1+ );let mut zero = quant(shape(0, 1, 1));zero.b_prologue = GemmBPrologueKind::ScaleZeroPointDequant;@@ -149,7 +154,7 @@ fn selection_fallbacks_and_split_k_are_preserved() {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, LEGACY_PROFILE)+ GemmProblem::new(huge, DataType::BF16, DataType::BF16, false, MTLGPUFamily::Apple7).select_plan_for_engine(GemmEngine::Mxu),Err(GemmPlanError::MxuUnavailable));@@ -195,7 +200,7 @@ fn gemv_gemm_route_boundaries_are_preserved() {(shape(3, 4096, 8192), DataType::BF16, false),(shape(5, 4096, 8192), DataType::BF16, false),] {- let plan = GemmProblem::new(shape, data_type, data_type, true, LEGACY_PROFILE).select_plan();+ let plan = GemmProblem::new(shape, data_type, data_type, true, MTLGPUFamily::Apple7).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);diff --git a/crates/uzu-engine/unit/backends/metal/kernel/matmul/gemv/policy_test.rs b/crates/uzu-engine/unit/backends/metal/kernel/matmul/gemv/policy_test.rsindex df438a596..48ac8e849 100644--- a/crates/uzu-engine/unit/backends/metal/kernel/matmul/gemv/policy_test.rs+++ b/crates/uzu-engine/unit/backends/metal/kernel/matmul/gemv/policy_test.rs@@ -1,27 +1,17 @@+use metal::MTLGPUFamily;use uzu_engine_macros::uzu_test;use super::*;use crate::{- backends::{- common::{- gpu_types::gemm::{GemmBPrologueKind, GemmDTransform},- kernel::matmul::MatmulShape,- },- metal::device_profile::{DeviceIdentity, DeviceProfile, DeviceSize},+ backends::common::{+ gpu_types::gemm::{GemmBPrologueKind, GemmDTransform},+ kernel::matmul::MatmulShape,},data_type::DataType,};-fn profile(- size: DeviceSize,- identity: DeviceIdentity,-) -> DeviceProfile {- DeviceProfile::new(- identity,- size,- matches!(identity, DeviceIdentity::M5 | DeviceIdentity::M5Pro | DeviceIdentity::M5Max),- )-}+const SMALL_GPU_CORE_COUNT: u32 = 29;+const LARGE_GPU_CORE_COUNT: u32 = 30;fn qtile(num_simdgroups: u32,@@ -33,46 +23,40 @@ fn qtile(#[uzu_test]fn fp_policy_cases() {let cases = [- (profile(DeviceSize::Large, DeviceIdentity::M3Max), 1, 12288, 1536, true, tile(8, 8, 1)),- (profile(DeviceSize::Large, DeviceIdentity::M3Max), 1, 12288, 1536, false, tile(8, 1, 1)),- (profile(DeviceSize::Large, DeviceIdentity::M3Max), 1, 1536, 256, true, tile(8, 1, 1)),- (profile(DeviceSize::Small, DeviceIdentity::M3), 1, 1536, 256, true, tile(8, 2, 1)),- (profile(DeviceSize::Large, DeviceIdentity::M3Max), 8, 12288, 1536, true, tile(8, 1, 4)),- (profile(DeviceSize::Large, DeviceIdentity::M3Max), 1, 1536, 12288, true, tile(8, 8, 4)),- (profile(DeviceSize::Small, DeviceIdentity::M1), 1, 262144, 1536, true, tile(8, 1, 4)),+ (LARGE_GPU_CORE_COUNT, MTLGPUFamily::Apple9, 1, 12288, 1536, true, tile(8, 8, 1)),+ (LARGE_GPU_CORE_COUNT, MTLGPUFamily::Apple9, 1, 12288, 1536, false, tile(8, 1, 1)),+ (LARGE_GPU_CORE_COUNT, MTLGPUFamily::Apple9, 1, 1536, 256, true, tile(8, 1, 1)),+ (SMALL_GPU_CORE_COUNT, MTLGPUFamily::Apple9, 1, 1536, 256, true, tile(8, 2, 1)),+ (LARGE_GPU_CORE_COUNT, MTLGPUFamily::Apple9, 8, 12288, 1536, true, tile(8, 1, 4)),+ (LARGE_GPU_CORE_COUNT, MTLGPUFamily::Apple9, 1, 1536, 12288, true, tile(8, 8, 4)),+ (SMALL_GPU_CORE_COUNT, MTLGPUFamily::Apple7, 1, 262144, 1536, true, tile(8, 1, 4)),];- for (profile, m, n, k, aligned, expected) in cases {- assert_eq!(fp_tile(m, n, k, aligned, profile), expected);+ for (gpu_core_count, apple_gpu_family, m, n, k, aligned, expected) in cases {+ assert_eq!(fp_tile(gpu_core_count, apple_gpu_family, m, n, k, aligned), expected);}}#[uzu_test]fn quant_policy_cases() {let cases = [- (profile(DeviceSize::Large, DeviceIdentity::M3Max), 1, 256, 1536, 4, false, qtile(2, 1)),- (profile(DeviceSize::Large, DeviceIdentity::M3Max), 1, 262144, 1536, 4, false, qtile(8, 4)),- (profile(DeviceSize::Small, DeviceIdentity::M3), 1, 1536, 256, 4, false, qtile(4, 4)),- (profile(DeviceSize::Small, DeviceIdentity::M2), 1, 2048, 1536, 4, false, qtile(8, 2)),- (profile(DeviceSize::Small, DeviceIdentity::M1), 1, 256, 1536, 4, false, qtile(8, 2)),- (profile(DeviceSize::Small, DeviceIdentity::M1), 1, 1536, 256, 4, false, qtile(4, 8)),- (profile(DeviceSize::Large, DeviceIdentity::M3Max), 2, 2048, 1536, 4, false, qtile(8, 4)),- (profile(DeviceSize::Large, DeviceIdentity::M3Max), 4, 5120, 5120, 4, false, qtile(8, 4)),- (- profile(DeviceSize::Large, DeviceIdentity::M3Max),- 1,- 2048,- 1536,- 8,- false,- GemvTile::quantized(8, 4, 1, 32, 4),- ),- (profile(DeviceSize::Large, DeviceIdentity::M3Max), 1, 2560, 9216, 4, true, qtile(4, 8)),+ (LARGE_GPU_CORE_COUNT, MTLGPUFamily::Apple9, 1, 256, 1536, 4, false, qtile(2, 1)),+ (LARGE_GPU_CORE_COUNT, MTLGPUFamily::Apple9, 1, 262144, 1536, 4, false, qtile(8, 4)),+ (SMALL_GPU_CORE_COUNT, MTLGPUFamily::Apple9, 1, 1536, 256, 4, false, qtile(4, 4)),+ (SMALL_GPU_CORE_COUNT, MTLGPUFamily::Apple10, 1, 1536, 256, 4, false, qtile(8, 4)),+ (SMALL_GPU_CORE_COUNT, MTLGPUFamily::Apple8, 1, 2048, 1536, 4, false, qtile(8, 2)),+ (SMALL_GPU_CORE_COUNT, MTLGPUFamily::Apple7, 1, 256, 1536, 4, false, qtile(8, 2)),+ (SMALL_GPU_CORE_COUNT, MTLGPUFamily::Apple7, 1, 1536, 256, 4, false, qtile(4, 8)),+ (LARGE_GPU_CORE_COUNT, MTLGPUFamily::Apple9, 2, 2048, 1536, 4, false, qtile(8, 4)),+ (LARGE_GPU_CORE_COUNT, MTLGPUFamily::Apple9, 4, 5120, 5120, 4, false, qtile(8, 4)),+ (LARGE_GPU_CORE_COUNT, MTLGPUFamily::Apple9, 1, 2048, 1536, 8, false, GemvTile::quantized(8, 4, 1, 32, 4)),+ (LARGE_GPU_CORE_COUNT, MTLGPUFamily::Apple9, 1, 2560, 9216, 4, true, qtile(4, 8)),];- for (profile, m, n, k, bits, has_rht, expected) in cases {+ for (gpu_core_count, apple_gpu_family, m, n, k, bits, has_rht, expected) in cases {let actual = quantized_tile(- profile,+ gpu_core_count,+ apple_gpu_family,bits,32,m,@@ -86,12 +70,28 @@ fn quant_policy_cases() {true,).expect("quantized route");- assert_eq!(actual, expected, "m={m} n={n} k={k} bits={bits} profile={profile:?}");+ assert_eq!(+ actual, expected,+ "m={m} n={n} k={k} bits={bits} gpu_core_count={gpu_core_count} apple_gpu_family={apple_gpu_family:?}"+ );}}+#[uzu_test]+fn gpu_core_count_boundary_selects_large_policy() {+ let transform = GemmDTransform::empty();+ let small =+ quantized(SMALL_GPU_CORE_COUNT, MTLGPUFamily::Apple9, 4, 32, 1, 256, 1536, transform).expect("small GPU route");+ let large =+ quantized(LARGE_GPU_CORE_COUNT, MTLGPUFamily::Apple9, 4, 32, 1, 256, 1536, transform).expect("large GPU route");++ assert_eq!(small, qtile(4, 2));+ assert_eq!(large, qtile(2, 1));+}+fn quantized(- profile: DeviceProfile,+ gpu_core_count: u32,+ apple_gpu_family: MTLGPUFamily,bits: u32,group: u32,m: u32,@@ -99,35 +99,68 @@ fn quantized(k: u32,d_transform: GemmDTransform,) -> Option<GemvTile> {- quantized_tile(profile, bits, group, m, n, k, d_transform, true)+ quantized_tile(gpu_core_count, apple_gpu_family, bits, group, m, n, k, d_transform, true)}#[uzu_test]fn quantized_policy_edges() {- for (profile, m, group, expected) in [- (profile(DeviceSize::Large, DeviceIdentity::M5Max), 2, 32, GemvTile::quantized(8, 4, 1, 32, 4)),- (profile(DeviceSize::Large, DeviceIdentity::M5Max), 3, 32, GemvTile::quantized(8, 4, 1, 32, 4)),- (profile(DeviceSize::Small, DeviceIdentity::M2), 4, 64, GemvTile::quantized(8, 4, 1, 32, 8)),+ for (gpu_core_count, apple_gpu_family, m, group, expected) in [+ (LARGE_GPU_CORE_COUNT, MTLGPUFamily::Apple10, 2, 32, GemvTile::quantized(8, 4, 1, 32, 4)),+ (LARGE_GPU_CORE_COUNT, MTLGPUFamily::Apple10, 3, 32, GemvTile::quantized(8, 4, 1, 32, 4)),+ (SMALL_GPU_CORE_COUNT, MTLGPUFamily::Apple8, 4, 64, GemvTile::quantized(8, 4, 1, 32, 8)),] {- assert_eq!(quantized(profile, 8, group, m, 4096, 4096, GemmDTransform::RHT), Some(expected));+ assert_eq!(+ quantized(gpu_core_count, apple_gpu_family, 8, group, m, 4096, 4096, GemmDTransform::RHT),+ Some(expected)+ );}- let profile = profile(DeviceSize::Large, DeviceIdentity::M5Max);let none = GemmDTransform::empty();- assert_eq!(quantized(profile, 4, 64, 4, 8192, 4100, none), Some(GemvTile::quantized(8, 4, 1, 32, 4)));- assert!(quantized(profile, 4, 32, 4, 8, 4096, none).is_some());- assert!(quantized(profile, 4, 32, 1, 8192, 4096, none).is_some());- assert_eq!(quantized(profile, 4, 32, 9, 8192, 4096, none), None);- assert_eq!(quantized_tile(profile, 4, 32, 4, 8192, 4096, none, true), Some(GemvTile::quantized(8, 4, 1, 32, 2)));+ assert_eq!(+ quantized(LARGE_GPU_CORE_COUNT, MTLGPUFamily::Apple10, 4, 64, 4, 8192, 4100, none),+ Some(GemvTile::quantized(8, 4, 1, 32, 4))+ );+ assert!(quantized(LARGE_GPU_CORE_COUNT, MTLGPUFamily::Apple10, 4, 32, 4, 8, 4096, none).is_some());+ assert!(quantized(LARGE_GPU_CORE_COUNT, MTLGPUFamily::Apple10, 4, 32, 1, 8192, 4096, none).is_some());+ assert_eq!(quantized(LARGE_GPU_CORE_COUNT, MTLGPUFamily::Apple10, 4, 32, 9, 8192, 4096, none), None);+ assert_eq!(+ quantized_tile(LARGE_GPU_CORE_COUNT, MTLGPUFamily::Apple10, 4, 32, 4, 8192, 4096, none, true),+ Some(GemvTile::quantized(8, 4, 1, 32, 2))+ );}#[uzu_test]fn untuned_quantized_io_uses_only_the_generated_fallback() {- let profile = profile(DeviceSize::Large, DeviceIdentity::M5Max);- assert_eq!(quantized_tile(profile, 4, 32, 4, 3, 4096, GemmDTransform::empty(), false), None);- let tile =- quantized_tile(profile, 4, 32, 4, 4096, 4096, GemmDTransform::empty(), false).expect("mixed-IO fallback");+ assert_eq!(+ quantized_tile(LARGE_GPU_CORE_COUNT, MTLGPUFamily::Apple10, 4, 32, 4, 3, 4096, GemmDTransform::empty(), false,),+ None+ );+ let tile = quantized_tile(+ LARGE_GPU_CORE_COUNT,+ MTLGPUFamily::Apple10,+ 4,+ 32,+ 4,+ 4096,+ 4096,+ GemmDTransform::empty(),+ false,+ )+ .expect("mixed-IO fallback");assert_eq!(tile, GemvTile::quantized(8, 4, 1, 32, 2));- assert_eq!(quantized_tile(profile, 4, 32, 5, 4096, 4096, GemmDTransform::empty(), false), None);+ assert_eq!(+ quantized_tile(+ LARGE_GPU_CORE_COUNT,+ MTLGPUFamily::Apple10,+ 4,+ 32,+ 5,+ 4096,+ 4096,+ GemmDTransform::empty(),+ false,+ ),+ None+ );}fn quant_shape(@@ -153,7 +186,6 @@ fn quant_shape(#[uzu_test]fn block_unaligned_quantized_k_stays_on_gemv() {- let profile = profile(DeviceSize::Large, DeviceIdentity::M5Max);let shape = MatmulShape {m: 1,n: 64,@@ -174,7 +206,8 @@ fn block_unaligned_quantized_k_stays_on_gemv() {DataType::BF16,DataType::BF16,DataType::BF16,- profile,+ LARGE_GPU_CORE_COUNT,+ MTLGPUFamily::Apple10,).is_some());@@ -182,14 +215,14 @@ fn block_unaligned_quantized_k_stays_on_gemv() {#[uzu_test]fn specialization_preserves_quantized_route_and_accumulate_tail() {- let profile = profile(DeviceSize::Large, DeviceIdentity::M5Max);let select = |n, transform| {super::super::kernel::GemvSpecialization::select_shape(&quant_shape(4, n, transform),DataType::BF16,DataType::BF16,DataType::BF16,- profile,+ LARGE_GPU_CORE_COUNT,+ MTLGPUFamily::Apple10,)};let clean = select(8192, GemmDTransform::empty()).expect("quantized specialization");diff --git a/crates/uzu-engine/unit/backends/metal/kernel/matmul/qmv/routes_test.rs b/crates/uzu-engine/unit/backends/metal/kernel/matmul/qmv/routes_test.rsindex 7e016371c..b4944350e 100644--- a/crates/uzu-engine/unit/backends/metal/kernel/matmul/qmv/routes_test.rs+++ b/crates/uzu-engine/unit/backends/metal/kernel/matmul/qmv/routes_test.rs@@ -1,5 +1,6 @@use std::fmt::Write;+use metal::MTLGPUFamily;use uzu_engine_macros::uzu_test;use xxhash_rust::xxh3::xxh3_64;@@ -10,24 +11,20 @@ use crate::{gpu_types::gemm::{GemmBPrologueKind, GemmDTransform},kernel::matmul::MatmulShape,},- metal::{- device_profile::{DeviceIdentity, DeviceProfile, DeviceSize},- kernel::matmul::{MatmulDispatch, MatmulMetalKernel, gemm::GemmProblem, gemv::GemvSpecialization},- },+ metal::kernel::matmul::{MatmulDispatch, MatmulMetalKernel, gemv::GemvSpecialization},},data_type::DataType,};const FROZEN_PLAN_FINGERPRINT: u64 = 5_839_212_743_558_880_136;--const DEVICES: [(&str, DeviceIdentity); 7] = [- ("m1", DeviceIdentity::M1),- ("m2", DeviceIdentity::M2),- ("m2-pro", DeviceIdentity::M2Pro),- ("m3-max", DeviceIdentity::M3Max),- ("m4", DeviceIdentity::M4),- ("m4-pro", DeviceIdentity::M4Pro),- ("m5-max", DeviceIdentity::M5Max),+const DEVICES: [(&str, &str, u32, MTLGPUFamily, bool); 7] = [+ ("m1", "Apple M1", 8, MTLGPUFamily::Apple7, false),+ ("m2", "Apple M2", 10, MTLGPUFamily::Apple8, false),+ ("m2-pro", "Apple M2 Pro", 19, MTLGPUFamily::Apple8, false),+ ("m3-max", "Apple M3 Max", 40, MTLGPUFamily::Apple9, false),+ ("m4", "Apple M4", 10, MTLGPUFamily::Apple9, false),+ ("m4-pro", "Apple M4 Pro", 20, MTLGPUFamily::Apple9, false),+ ("m5-max", "Apple M5 Max", 40, MTLGPUFamily::Apple10, true),];const FORMATS: [(&str, u32, u32, GemmBPrologueKind); 4] = [("W4/ZP G32", 4, 32, GemmBPrologueKind::ScaleZeroPointDequant),@@ -76,7 +73,7 @@ fn table_is_complete_and_fingerprint_is_stable() {let mut tuned = 0;let mut main_gemv = 0;let mut main_gemm = 0;- for &(device_name, identity) in &DEVICES {+ for &(device_label, device_name, gpu_core_count, apple_gpu_family, supports_mxu) in &DEVICES {for &(format_name, bits, group, prologue) in &FORMATS {for m in 2..=7 {for &(shape_name, n, k) in &SHAPES {@@ -85,14 +82,15 @@ fn table_is_complete_and_fingerprint_is_stable() {.iter().enumerate().filter(|row| {- row.1.identity == identity+ row.1.device_name == device_name+ && row.1.apple_gpu_family == apple_gpu_family&& row.1.bits == bits&& row.1.group == group&& row.1.m == m&& row.1.shapes & mask != 0}).collect();- assert_eq!(matches.len(), 1, "route coverage for {device_name} {format_name} M={m} {shape_name}");+ assert_eq!(matches.len(), 1, "route coverage for {device_label} {format_name} M={m} {shape_name}");let (row_index, row) = matches[0];matched_rows[row_index] = true;let selected = row.route;@@ -101,14 +99,15 @@ fn table_is_complete_and_fingerprint_is_stable() {QmvRoute::MainGemv(_) => main_gemv += 1,QmvRoute::MainGemm(_) => main_gemm += 1,}- canonical.push(format!("{device_name}|{format_name}|{shape_name}|{m}|{n}|{k}|{selected:?}"));- let profile = device_profile(identity);+ canonical.push(format!("{device_label}|{format_name}|{shape_name}|{m}|{n}|{k}|{selected:?}"));let problem = problem(m, n, k, bits, group, prologue);- assert_eq!(route(profile, &problem, true), Some(selected));+ assert_eq!(route(device_name, apple_gpu_family, supports_mxu, &problem, true), Some(selected));let runtime = MatmulMetalKernel::choose_dispatch(&problem,- profile,- profile.supports_mxu(),+ device_name,+ gpu_core_count,+ apple_gpu_family,+ supports_mxu,DataType::BF16,DataType::BF16,DataType::BF16,@@ -122,12 +121,8 @@ fn table_is_complete_and_fingerprint_is_stable() {tile,).expect("stored GEMV tile must be legal");- assert_eq!(specialization.tile(), tile);assert!(matches!(runtime, MatmulDispatch::Gemv(actual) if actual == specialization));} else if let QmvRoute::MainGemm(plan) = selected {- let problem =- GemmProblem::new(problem, DataType::BF16, DataType::BF16, profile.supports_mxu(), profile);- assert!(problem.plan_is_legal(plan), "stored GEMM plan must be legal");assert!(matches!(runtime, MatmulDispatch::Gemm(actual) if actual == plan));}}@@ -139,7 +134,7 @@ fn table_is_complete_and_fingerprint_is_stable() {assert_eq!(canonical.len(), 1176);let mut expanded = String::new();for line in canonical {- writeln!(&mut expanded, "{line}").unwrap();+ writeln!(&mut expanded, "{line}").expect("writing to a String must succeed");}assert_eq!(tuned, 864);assert_eq!(main_gemv, 221);@@ -147,24 +142,10 @@ fn table_is_complete_and_fingerprint_is_stable() {assert_eq!(xxh3_64(expanded.trim_end().as_bytes()), FROZEN_PLAN_FINGERPRINT);}-fn device_profile(identity: DeviceIdentity) -> DeviceProfile {- let large = matches!(identity, DeviceIdentity::M3Max | DeviceIdentity::M5Max);- DeviceProfile::new(- identity,- if large {- DeviceSize::Large- } else {- DeviceSize::Small- },- matches!(identity, DeviceIdentity::M5Max),- )-}-#[uzu_test]fn exact_lookup_rejects_non_matrix_inputs() {- let profile = device_profile(DeviceIdentity::M1);let p = problem(2, 5120, 17408, 4, 64, GemmBPrologueKind::ScaleZeroPointDequant);- assert!(route(profile, &p, true).is_some());+ assert!(route("Apple M1", MTLGPUFamily::Apple7, false, &p, true).is_some());for mutate in [|p: &mut MatmulShape| p.m = 1,|p: &mut MatmulShape| p.n = 1,@@ -173,14 +154,15 @@ fn exact_lookup_rejects_non_matrix_inputs() {] {let mut rejected = p;mutate(&mut rejected);- assert!(route(profile, &rejected, true).is_none());+ assert!(route("Apple M1", MTLGPUFamily::Apple7, false, &rejected, true).is_none());}- assert!(route(profile, &p, false).is_none());+ assert!(route("Apple M1", MTLGPUFamily::Apple7, false, &p, false).is_none());let mut rht = p;rht.d_transform = GemmDTransform::RHT;rht.signed_codes = true;- let selected = route(profile, &rht, true).expect("RHT must preserve the exact route");+ let selected =+ route("Apple M1", MTLGPUFamily::Apple7, false, &rht, true).expect("RHT must preserve the exact route");let QmvRoute::Tuned(tile) = selected else {panic!("test anchor must use a tuned tile");};@@ -188,25 +170,31 @@ fn exact_lookup_rejects_non_matrix_inputs() {rht.n -= 1;assert!(GemvSpecialization::select_tile(&rht, DataType::BF16, DataType::BF16, DataType::BF16, tile).is_none());- let m5_without_mxu = DeviceProfile::new(DeviceIdentity::M5Max, DeviceSize::Large, false);let p = problem(7, 6144, 5120, 8, 64, GemmBPrologueKind::ScaleSymmetricDequant);- assert!(matches!(route(device_profile(DeviceIdentity::M5Max), &p, true), Some(QmvRoute::MainGemm(_))));- assert_eq!(route(m5_without_mxu, &p, true), None);+ assert!(matches!(route("Apple M5 Max", MTLGPUFamily::Apple10, true, &p, true), Some(QmvRoute::MainGemm(_))));+ assert_eq!(route("Apple M5 Max", MTLGPUFamily::Apple10, false, &p, true), None);}#[uzu_test]fn normal_routing_handles_inputs_outside_the_frozen_matrix() {- let profile = device_profile(DeviceIdentity::M1);for (m, n, k) in [(1, 5120, 17408), (2, 4096, 5120)] {let problem = problem(m, n, k, 4, 64, GemmBPrologueKind::ScaleZeroPointDequant);- assert_eq!(route(profile, &problem, true), None);- let specialization =- GemvSpecialization::select_shape(&problem, DataType::BF16, DataType::BF16, DataType::BF16, profile)- .expect("normal M1 policy should select GEMV for this anchor");+ assert_eq!(route("Apple M1", MTLGPUFamily::Apple7, false, &problem, true), None);+ let specialization = GemvSpecialization::select_shape(+ &problem,+ DataType::BF16,+ DataType::BF16,+ DataType::BF16,+ 8,+ MTLGPUFamily::Apple7,+ )+ .expect("normal M1 policy should select GEMV for this anchor");assert!(matches!(MatmulMetalKernel::choose_dispatch(&problem,- profile,+ "Apple M1",+ 8,+ MTLGPUFamily::Apple7,false,DataType::BF16,DataType::BF16,@@ -219,15 +207,28 @@ fn normal_routing_handles_inputs_outside_the_frozen_matrix() {#[uzu_test]fn family_lookup_requires_one_unanimous_route() {- let m1_max = DeviceProfile::new(DeviceIdentity::M1Max, DeviceSize::Large, false);let m1_route = problem(4, 8192, 5120, 4, 64, GemmBPrologueKind::ScaleZeroPointDequant);- assert_eq!(route(m1_max, &m1_route, true), route(device_profile(DeviceIdentity::M1), &m1_route, true));+ let measured_m1 = route("Apple M1", MTLGPUFamily::Apple7, false, &m1_route, true);+ for device_name in ["Apple M1 Pro", "Apple M1 Max", "Apple M1 Ultra"] {+ assert_eq!(route(device_name, MTLGPUFamily::Apple7, false, &m1_route, true), measured_m1);+ }- let family = DeviceProfile::new(DeviceIdentity::M2Max, DeviceSize::Small, false);let unanimous = problem(6, 5120, 17408, 4, 64, GemmBPrologueKind::ScaleZeroPointDequant);- assert_eq!(route(family, &unanimous, true), route(device_profile(DeviceIdentity::M2), &unanimous, true));+ let measured_m2 = route("Apple M2", MTLGPUFamily::Apple8, false, &unanimous, true);+ for device_name in ["Apple M2 Max", "Apple M2 Ultra"] {+ assert_eq!(route(device_name, MTLGPUFamily::Apple8, false, &unanimous, true), measured_m2);+ }+ let measured_m3_max = route("Apple M3 Max", MTLGPUFamily::Apple9, false, &unanimous, true);+ for device_name in ["Apple M3", "Apple M3 Pro", "Apple M4 Max"] {+ assert_eq!(route(device_name, MTLGPUFamily::Apple9, false, &unanimous, true), measured_m3_max);+ }+ let measured_m5_max = route("Apple M5 Max", MTLGPUFamily::Apple10, true, &unanimous, true);+ for device_name in ["Apple M5", "Apple M5 Pro"] {+ assert_eq!(route(device_name, MTLGPUFamily::Apple10, true, &unanimous, true), measured_m5_max);+ }let disagreement = problem(3, 5120, 6144, 4, 64, GemmBPrologueKind::ScaleZeroPointDequant);- assert_eq!(route(family, &disagreement, true), None);- assert!(route(device_profile(DeviceIdentity::M2), &disagreement, true).is_some());+ assert_eq!(route("Apple M2 Max", MTLGPUFamily::Apple8, false, &disagreement, true), None);+ assert!(route("Apple M2", MTLGPUFamily::Apple8, false, &disagreement, true).is_some());+ assert_eq!(route("Apple A11 GPU", MTLGPUFamily::Apple4, false, &m1_route, true), None);}