A high-performance inference engine for AI models
small import cleanup (#195)
uuuvn6f05da5cceab
diff --git a/crates/uzu/build/metal/bindgen.rs b/crates/uzu/build/metal/bindgen.rsindex e16857e28..92ff957d9 100644--- a/crates/uzu/build/metal/bindgen.rs+++ b/crates/uzu/build/metal/bindgen.rs@@ -304,7 +304,7 @@ pub fn bindgen(impl crate::backends::common::kernel::#trait_name for #struct_name {type Backend = crate::backends::metal::Metal;- fn new(context: &MTLContext #(, #variants_extra_arguments)* #(, #specialize_args)*) -> Result<Self, MTLError> {+ fn new(context: &MetalContext #(, #variants_extra_arguments)* #(, #specialize_args)*) -> Result<Self, MetalError> {#function_constants_initlet pipeline = context.compute_pipeline_state(&#entry_name, #function_constants_arg)?;Ok(Self { pipeline #(, #conditional_buffer_sets)* })diff --git a/crates/uzu/build/metal/compiler.rs b/crates/uzu/build/metal/compiler.rsindex 08ef2e71b..d2c16efd8 100644--- a/crates/uzu/build/metal/compiler.rs+++ b/crates/uzu/build/metal/compiler.rs@@ -283,19 +283,17 @@ impl MetalCompiler {.collect::<anyhow::Result<(Vec<TokenStream>, Vec<TokenStream>)>>()?;let tokens = quote! {+ use objc2::{runtime::ProtocolObject, rc::Retained};+ use metal::{MTLFunctionConstantValues, MTLSize, MTLBuffer, MTLComputeCommandEncoder, MTLComputePipelineState};+use crate::backends::metal::{ComputeEncoderSetValue,FunctionConstantValuesSetValue,data_type::MetalDataTypeExt,- MTLContext,- MTLError,- MTLFunctionConstantValues,- MTLSize,- ProtocolObject,- Retained,+ MetalContext,+ MetalError,metal_extensions::ComputeEncoderConditional,};- use metal::{MTLBuffer, MTLComputeCommandEncoder, MTLComputePipelineState};#(#bindings)*diff --git a/crates/uzu/src/backends/metal/backend.rs b/crates/uzu/src/backends/metal/backend.rsindex 559046842..349ad9151 100644--- a/crates/uzu/src/backends/metal/backend.rs+++ b/crates/uzu/src/backends/metal/backend.rs@@ -1,18 +1,18 @@use metal::{MTLBlitCommandEncoder, MTLBuffer, MTLCommandBuffer, MTLComputeCommandEncoder};use objc2::{rc::Retained, runtime::ProtocolObject};-use super::{MTLContext, MTLError, MetalKernels};+use super::{MetalContext, MetalError, MetalKernels};use crate::backends::common::Backend;#[derive(Debug, Clone)]pub struct Metal;impl Backend for Metal {- type Context = MTLContext;+ type Context = MetalContext;type NativeBuffer = Retained<ProtocolObject<dyn MTLBuffer>>;type CommandBuffer = Retained<ProtocolObject<dyn MTLCommandBuffer>>;type ComputeEncoder = ProtocolObject<dyn MTLComputeCommandEncoder>;type CopyEncoder = ProtocolObject<dyn MTLBlitCommandEncoder>;type Kernels = MetalKernels;- type Error = MTLError;+ type Error = MetalError;}diff --git a/crates/uzu/src/backends/metal/classifier_context.rs b/crates/uzu/src/backends/metal/classifier_context.rsindex dcdbf7f0a..296a1ea3f 100644--- a/crates/uzu/src/backends/metal/classifier_context.rs+++ b/crates/uzu/src/backends/metal/classifier_context.rs@@ -1,9 +1,12 @@use std::{cell::RefCell, fs::File, io::BufReader, path::Path, rc::Rc};+use metal::MTLCommandBuffer;+use objc2::{rc::Retained, runtime::ProtocolObject};+use super::{- MTLCommandBuffer, MTLContext, ProtocolObject, Retained,+ MetalContext,encodable_block::{- Activation, ClassifierLayer, ClassifierPredictionHead, Normalization, Pooling, Rope,+ ClassifierLayer, ClassifierPredictionHead,transformer_layer::{embed_block, linear_block},},kernel::dsl::SigmoidMetalKernel,@@ -15,7 +18,7 @@ use crate::{metal::{Metal, error::ClassifierError},},config::{ClassifierModelConfig, ModelMetadata},- encodable_block::EncodableBlock,+ encodable_block::{Activation, EncodableBlock, Normalization, Pooling, Rope},forward_pass::{model_shape::ModelShape,scratch_buffers::ScratchBuffers,@@ -26,7 +29,7 @@ use crate::{};pub struct ClassifierContext {- pub mtl_context: Rc<MTLContext>,+ pub mtl_context: Rc<MetalContext>,pub command_buffer: Retained<ProtocolObject<dyn MTLCommandBuffer>>,pub shared_buffers: Rc<RefCell<SharedBuffers<Metal>>>,@@ -36,9 +39,9 @@ pub struct ClassifierContext {pub model_shape: ModelShape,pub embed: Box<dyn EncodableBlock<Metal>>,- pub embedding_norm: Normalization,+ pub embedding_norm: Normalization<Metal>,pub layers: Box<[ClassifierLayer]>,- pub output_norm: Normalization,+ pub output_norm: Normalization<Metal>,pub global_rope: Rc<Box<dyn EncodableBlock<Metal>>>,pub local_rope: Option<Rc<Box<dyn EncodableBlock<Metal>>>>,@@ -50,7 +53,7 @@ pub struct ClassifierContext {impl ClassifierContext {pub fn new(model_path: &Path) -> Result<Self, Error> {- let context = MTLContext::new().map_err(|_| Error::UnableToCreateMetalContext)?;+ let context = MetalContext::new().map_err(|_| Error::UnableToCreateMetalContext)?;let command_buffer = context.create_command_buffer().map_err(|_| Error::UnableToCreateMetalContext)?;@@ -164,7 +167,7 @@ impl ClassifierContext {.subtree("output_norm").map_err(|_| Error::Classifier(ClassifierError::WeightSubtreeNotFound("output_norm".to_string())))?;let output_norm = Normalization::new(- &context,+ context.as_ref(),data_type,classifier_model_config.model_config.transformer_config.output_norm_config.clone(),ArrayId::Main,@@ -181,7 +184,7 @@ impl ClassifierContext {.subtree("embedding_norm").map_err(|_| Error::Classifier(ClassifierError::WeightSubtreeNotFound("embedding_norm".to_string())))?;let embedding_norm = Normalization::new(- &context,+ context.as_ref(),data_type,classifier_model_config.model_config.embedding_norm_config.clone(),ArrayId::Main,@@ -230,7 +233,7 @@ impl ClassifierContext {Error::Classifier(ClassifierError::WeightSubtreeNotFound("prediction_head.norm".to_string()))})?;let prediction_head_norm = Normalization::new(- &context,+ context.as_ref(),prediction_head_data_type,prediction_head_config.normalization_config.clone(),ArrayId::ClassifierPredictionHeadDense,@@ -306,7 +309,7 @@ impl ClassifierContext {}fn create_rope_block(- mtl_context: &MTLContext,+ mtl_context: &MetalContext,data_type: DataType,rope_type: RopeType,) -> Result<Rc<Box<dyn EncodableBlock<Metal>>>, ClassifierError> {diff --git a/crates/uzu/src/backends/metal/context.rs b/crates/uzu/src/backends/metal/context.rsindex 18b22e98f..e653ad5cc 100644--- a/crates/uzu/src/backends/metal/context.rs+++ b/crates/uzu/src/backends/metal/context.rs@@ -1,16 +1,13 @@use std::{cell::RefCell, collections::HashMap, env, rc::Rc};-use metal::{MTLBuffer, MTLCommandBuffer};+use metal::{+ MTLBuffer, MTLCommandBuffer, MTLCommandQueue, MTLComputePipelineState, MTLDevice, MTLDeviceExt,+ MTLFunctionConstantValues, MTLLibrary, MTLResourceOptions,+};use objc2::{rc::Retained, runtime::ProtocolObject};-use super::{Metal, error::MTLError, kernel, metal_extensions::LibraryPipelineExtensions};-use crate::backends::{- common::{Allocator, Context},- metal::{- MTLCommandQueue, MTLComputePipelineState, MTLDevice, MTLDeviceExt, MTLFunctionConstantValues, MTLLibrary,- MTLResourceOptions,- },-};+use super::{Metal, error::MetalError, kernel, metal_extensions::LibraryPipelineExtensions};+use crate::backends::common::{Allocator, Context};/// Apple GPU architecture generation./// Based on Apple GPU family naming convention (e.g., "applegpu_g13p").@@ -122,7 +119,7 @@ impl DeviceArchitecture {}}-pub struct MTLContext {+pub struct MetalContext {pub device: Retained<ProtocolObject<dyn MTLDevice>>,pub command_queue: Retained<ProtocolObject<dyn MTLCommandQueue>>,architecture: DeviceArchitecture,@@ -131,7 +128,7 @@ pub struct MTLContext {allocator: Allocator<Metal>,}-impl MTLContext {+impl MetalContext {/// Returns true if NAX kernels are available on this device.pub fn is_nax_available(&self) -> bool {cfg!(feature = "metal-nax") && self.architecture.is_nax_available()@@ -161,7 +158,7 @@ impl MTLContext {&self,function_name: &str,constants: Option<&MTLFunctionConstantValues>,- ) -> Result<Retained<ProtocolObject<dyn MTLComputePipelineState>>, MTLError> {+ ) -> Result<Retained<ProtocolObject<dyn MTLComputePipelineState>>, MetalError> {// Only cache pipelines without constantsif constants.is_some() {return self.library.compute_pipeline_state(function_name, constants);@@ -174,7 +171,7 @@ impl MTLContext {cache_key: &str,function_name: &str,constants: Option<&MTLFunctionConstantValues>,- ) -> Result<Retained<ProtocolObject<dyn MTLComputePipelineState>>, MTLError> {+ ) -> Result<Retained<ProtocolObject<dyn MTLComputePipelineState>>, MetalError> {if let Some(pipeline) = self.pipeline_cache.borrow().get(cache_key) {return Ok(pipeline.clone());}@@ -187,20 +184,20 @@ impl MTLContext {}}-impl Context for MTLContext {+impl Context for MetalContext {type Backend = Metal;- fn new() -> Result<Rc<Self>, MTLError> {+ fn new() -> Result<Rc<Self>, MetalError> {let device: Retained<ProtocolObject<dyn MTLDevice>> = <dyn metal::MTLDevice>::system_default()- .ok_or(MTLError::Generic("cannot open system default device".into()))?;+ .ok_or(MetalError::Generic("cannot open system default device".into()))?;let command_queue = device.new_command_queue_with_max_command_buffer_count(1024)- .ok_or(MTLError::Generic("cannot create command queue".into()))?;+ .ok_or(MetalError::Generic("cannot create command queue".into()))?;let library = device.new_library_with_data(kernel::MTLB)- .map_err(|nserror| MTLError::Generic(format!("Failed to create Metal library: {}", nserror)))?;+ .map_err(|nserror| MetalError::Generic(format!("Failed to create Metal library: {}", nserror)))?;let architecture = DeviceArchitecture::from_device(&device);@@ -221,13 +218,13 @@ impl Context for MTLContext {fn create_buffer(&self,size: usize,- ) -> Result<Retained<ProtocolObject<dyn MTLBuffer>>, MTLError> {+ ) -> Result<Retained<ProtocolObject<dyn MTLBuffer>>, MetalError> {self.device.new_buffer(size, MTLResourceOptions::STORAGE_MODE_SHARED)- .ok_or(MTLError::Generic("cannot create buffer".into()))+ .ok_or(MetalError::Generic("cannot create buffer".into()))}- fn create_command_buffer(&self) -> Result<Retained<ProtocolObject<dyn MTLCommandBuffer>>, MTLError> {- self.command_queue.command_buffer().ok_or(MTLError::Generic("cannot create command buffer".into()))+ fn create_command_buffer(&self) -> Result<Retained<ProtocolObject<dyn MTLCommandBuffer>>, MetalError> {+ self.command_queue.command_buffer().ok_or(MetalError::Generic("cannot create command buffer".into()))}}diff --git a/crates/uzu/src/backends/metal/encodable_block/attention.rs b/crates/uzu/src/backends/metal/encodable_block/attention.rsindex b37c35821..532afecfc 100644--- a/crates/uzu/src/backends/metal/encodable_block/attention.rs+++ b/crates/uzu/src/backends/metal/encodable_block/attention.rs@@ -1,16 +1,18 @@//! Attention kernel encodable.-use super::{EncodableBlock, Metal};+use metal::{MTLCommandBuffer, MTLCommandEncoder, MTLComputeCommandEncoder};+use objc2::{rc::Retained, runtime::ProtocolObject};+use crate::{DataType,backends::metal::{- MTLCommandBuffer, MTLCommandEncoder, MTLComputeCommandEncoder, MTLContext, ProtocolObject, Retained,+ Metal, MetalContext,kernel::attention::{AttentionError, AttentionGemmArguments, AttentionKernel, AttentionKernelVariant,AttentionSinglePassArguments, AttentionTwoPassArguments, KVCacheUpdateArguments,},},- encodable_block::EncodingParameters,+ encodable_block::{EncodableBlock, EncodingParameters},forward_pass::state::{ArrayId, ForwardPassState, HashMapId},};@@ -41,7 +43,7 @@ pub struct Attention {impl Attention {pub fn new(- context: &MTLContext,+ context: &MetalContext,data_type: DataType,layer_index: usize,attention_scale: Option<f32>,diff --git a/crates/uzu/src/backends/metal/encodable_block/classifier_layer.rs b/crates/uzu/src/backends/metal/encodable_block/classifier_layer.rsindex 5d9c7990b..7684e4728 100644--- a/crates/uzu/src/backends/metal/encodable_block/classifier_layer.rs+++ b/crates/uzu/src/backends/metal/encodable_block/classifier_layer.rs@@ -1,15 +1,19 @@use std::rc::Rc;-use objc2::rc::autoreleasepool;--use super::{Attention, EncodableBlock, Normalization, QKNorm, TensorAddSwap, TensorCopy, transformer_layer};#[cfg(not(feature = "tracing"))]-use crate::backends::metal::MTLCommandEncoder;+use metal::MTLCommandEncoder;+use metal::{MTLCommandBuffer, MTLComputeCommandEncoder};+use objc2::{+ rc::{Retained, autoreleasepool},+ runtime::ProtocolObject,+};++use super::{Attention, transformer_layer};use crate::{DataType,- backends::metal::{MTLCommandBuffer, MTLComputeCommandEncoder, MTLContext, Metal, ProtocolObject, Retained},+ backends::metal::{Metal, MetalContext},config::TransformerLayerConfig,- encodable_block::EncodingParameters,+ encodable_block::{EncodableBlock, EncodingParameters, Normalization, QKNorm, TensorAddSwap, TensorCopy},forward_pass::state::{ArrayId, ForwardPassState},parameters::ParameterTree,};@@ -35,7 +39,7 @@ pub struct ClassifierLayer {impl ClassifierLayer {pub fn new(- mtl_context: Rc<MTLContext>,+ mtl_context: Rc<MetalContext>,layer_config: &TransformerLayerConfig,layer_index: usize,model_dim: usize,@@ -44,11 +48,11 @@ impl ClassifierLayer {head_dim: usize,num_groups: usize,attention_scale: Option<f32>,- layer_loader: &ParameterTree<MTLContext>,+ layer_loader: &ParameterTree<MetalContext>,rope: Rc<Box<dyn EncodableBlock<Metal>>>,) -> Self {autoreleasepool(|_| {- let ctx = &*mtl_context; // Reference for functions expecting &MTLContext+ let ctx = mtl_context.as_ref(); // Reference for functions expecting &MetalContextlet attention_config =layer_config.mixer_config.as_attention().expect("Classifier layers must use attention");let intermediate_data_type: DataType = attention_config.qkv_projection_config.activation_precision().into();diff --git a/crates/uzu/src/backends/metal/encodable_block/decoder.rs b/crates/uzu/src/backends/metal/encodable_block/decoder.rsindex 9f816e00c..03ddee61b 100644--- a/crates/uzu/src/backends/metal/encodable_block/decoder.rs+++ b/crates/uzu/src/backends/metal/encodable_block/decoder.rs@@ -2,15 +2,18 @@use std::rc::Rc;-use super::{EncodableBlock, LayerExecutables, RMSNorm, Rope};+use metal::{MTLCommandBuffer, MTLComputeCommandEncoder};+use objc2::{rc::Retained, runtime::ProtocolObject};++use super::LayerExecutables;use crate::{DataType, DecoderConfig,backends::metal::{- MTLCommandBuffer, MTLComputeCommandEncoder, MTLContext, Metal, ProtocolObject, Retained,+ Metal, MetalContext,encodable_block::transformer_layer::{embed_block, readout_block},},config::{DecoderLayerType, MixerConfig},- encodable_block::EncodingParameters,+ encodable_block::{EncodableBlock, EncodingParameters, RMSNorm, Rope},forward_pass::{model_shape::ModelShape,state::{ArrayId, ForwardPassState, RopeType},@@ -30,9 +33,9 @@ pub struct Decoder {impl Decoder {pub fn new(- mtl_context: Rc<MTLContext>,+ mtl_context: Rc<MetalContext>,decoder_config: Rc<DecoderConfig>,- root_weight_loader: &ParameterTree<MTLContext>,+ root_weight_loader: &ParameterTree<MetalContext>,) -> Self {let decoder_weight_loader = root_weight_loader.subtree("transformer").expect("transformer subtree not found");@@ -119,7 +122,7 @@ impl Decoder {let norm_block: Box<dyn EncodableBlock<Metal>> = Box::new(RMSNorm::new(- &mtl_context,+ mtl_context.as_ref(),norm_data_type,decoder_config.output_norm_config.clone(),ArrayId::Main,@@ -141,7 +144,7 @@ impl Decoder {}fn create_rope_block(- mtl_context: &MTLContext,+ mtl_context: &MetalContext,data_type: DataType,rope_type: RopeType,) -> Rc<Box<dyn EncodableBlock<Metal>>> {diff --git a/crates/uzu/src/backends/metal/encodable_block/embedding/error.rs b/crates/uzu/src/backends/metal/encodable_block/embedding/error.rsindex da85f713d..34f566354 100644--- a/crates/uzu/src/backends/metal/encodable_block/embedding/error.rs+++ b/crates/uzu/src/backends/metal/encodable_block/embedding/error.rs@@ -1,9 +1,9 @@-use crate::{DataType, backends::metal::MTLError};+use crate::{DataType, backends::metal::MetalError};#[derive(Debug, thiserror::Error)]pub enum EmbeddingError {#[error("Metal error: {0}")]- MetalError(#[from] MTLError),+ MetalError(#[from] MetalError),#[error("Unsupported data type: {0:?}")]UnsupportedDataType(DataType),}diff --git a/crates/uzu/src/backends/metal/encodable_block/embedding/quantized_readout.rs b/crates/uzu/src/backends/metal/encodable_block/embedding/quantized_readout.rsindex f1c8ddfa1..ad92a5179 100644--- a/crates/uzu/src/backends/metal/encodable_block/embedding/quantized_readout.rs+++ b/crates/uzu/src/backends/metal/encodable_block/embedding/quantized_readout.rs@@ -1,19 +1,18 @@-use super::{- super::{EncodableBlock, Metal},- EmbeddingError,-};+use metal::{MTLBuffer, MTLCommandBuffer, MTLCommandEncoder, MTLComputeCommandEncoder};+use objc2::{rc::Retained, runtime::ProtocolObject};++use super::EmbeddingError;use crate::{DataType,backends::{common::Context,metal::{- MTLBuffer, MTLCommandBuffer, MTLCommandEncoder, MTLComputeCommandEncoder, MTLContext, MTLError,- ProtocolObject, Retained,+ Metal, MetalContext, MetalError,kernel::quant_matmul::{QuantizationType, QuantizedMatmulArguments, QuantizedMatmulKernel},},},config::QuantizationMode,- encodable_block::EncodingParameters,+ encodable_block::{EncodableBlock, EncodingParameters},forward_pass::state::{ArrayId, ForwardPassState},parameters::ParameterTree,};@@ -29,13 +28,13 @@ pub struct QuantizedEmbeddingReadout {impl QuantizedEmbeddingReadout {pub fn new_tied(- mtl_context: &MTLContext,+ mtl_context: &MetalContext,data_type: DataType,vocab_size: usize,model_dim: usize,group_size: usize,mode: QuantizationMode,- parameter_tree: &ParameterTree<MTLContext>,+ parameter_tree: &ParameterTree<MetalContext>,) -> Result<Self, EmbeddingError> {Self::new_with_names(mtl_context,@@ -52,13 +51,13 @@ impl QuantizedEmbeddingReadout {}pub fn new_untied_output(- mtl_context: &MTLContext,+ mtl_context: &MetalContext,data_type: DataType,vocab_size: usize,model_dim: usize,group_size: usize,mode: QuantizationMode,- parameter_tree: &ParameterTree<MTLContext>,+ parameter_tree: &ParameterTree<MetalContext>,) -> Result<Self, EmbeddingError> {Self::new_with_names(mtl_context,@@ -75,7 +74,7 @@ impl QuantizedEmbeddingReadout {}fn new_with_names(- mtl_context: &MTLContext,+ mtl_context: &MetalContext,data_type: DataType,vocab_size: usize,model_dim: usize,@@ -84,17 +83,17 @@ impl QuantizedEmbeddingReadout {weights_name: &str,scales_name: &str,biases_name: &str,- parameter_tree: &ParameterTree<MTLContext>,+ parameter_tree: &ParameterTree<MetalContext>,) -> Result<Self, EmbeddingError> {// Load weights [vocab_size, model_dim/2] as U8let weights = parameter_tree.leaf(weights_name)- .map_err(|e| EmbeddingError::MetalError(MTLError::Generic(format!("Failed to load weights: {:?}", e))))?;+ .map_err(|e| EmbeddingError::MetalError(MetalError::Generic(format!("Failed to load weights: {:?}", e))))?;// Load scales [vocab_size, num_groups]let scales = parameter_tree.leaf(scales_name)- .map_err(|e| EmbeddingError::MetalError(MTLError::Generic(format!("Failed to load scales: {:?}", e))))?;+ .map_err(|e| EmbeddingError::MetalError(MetalError::Generic(format!("Failed to load scales: {:?}", e))))?;// Validate shapeslet num_groups = (model_dim + group_size - 1) / group_size;@@ -104,7 +103,7 @@ impl QuantizedEmbeddingReadout {let weights_transposed = weights.shape()[0] == vocab_size;if weights.shape() != [vocab_size, model_dim / packing_divisor] {- return Err(EmbeddingError::MetalError(MTLError::Generic(format!(+ return Err(EmbeddingError::MetalError(MetalError::Generic(format!("Embedding readout weights shape mismatch: got {:?}, expected [{}, {}]",weights.shape(),vocab_size,@@ -112,7 +111,7 @@ impl QuantizedEmbeddingReadout {))));}if scales.shape() != [vocab_size, num_groups] {- return Err(EmbeddingError::MetalError(MTLError::Generic(format!(+ return Err(EmbeddingError::MetalError(MetalError::Generic(format!("Embedding readout scales shape mismatch: got {:?}, expected [{}, {}]",scales.shape(),vocab_size,@@ -127,7 +126,7 @@ impl QuantizedEmbeddingReadout {let biases_buffer: Retained<ProtocolObject<dyn MTLBuffer>> = match parameter_tree.leaf(biases_name) {Ok(deq_biases) => {if deq_biases.shape() != [vocab_size, num_groups] {- return Err(EmbeddingError::MetalError(MTLError::Generic(format!(+ return Err(EmbeddingError::MetalError(MetalError::Generic(format!("Embedding readout deq_biases shape mismatch: got {:?}, expected [{}, {}]",deq_biases.shape(),vocab_size,@@ -170,7 +169,7 @@ impl QuantizedEmbeddingReadout {QuantizationType::Mlx,weights_transposed,)- .map_err(|e| EmbeddingError::MetalError(MTLError::Generic(format!("Failed to create kernel: {:?}", e))))?;+ .map_err(|e| EmbeddingError::MetalError(MetalError::Generic(format!("Failed to create kernel: {:?}", e))))?;Ok(Self {kernel,diff --git a/crates/uzu/src/backends/metal/encodable_block/layer/executables.rs b/crates/uzu/src/backends/metal/encodable_block/layer/executables.rsindex eed7deb01..a847f842c 100644--- a/crates/uzu/src/backends/metal/encodable_block/layer/executables.rs+++ b/crates/uzu/src/backends/metal/encodable_block/layer/executables.rs@@ -2,22 +2,23 @@use std::rc::Rc;-use objc2::rc::autoreleasepool;+#[cfg(not(feature = "tracing"))]+use metal::MTLCommandEncoder;+use metal::{MTLCommandBuffer, MTLComputeCommandEncoder};+use objc2::{+ rc::{Retained, autoreleasepool},+ runtime::ProtocolObject,+};use super::{- super::{- Attention, EncodableBlock, MambaMixer, QKNorm, RMSNorm, ShortConvMixer, TensorAddSwap, TensorCopy,- transformer_layer,- },+ super::{Attention, MambaMixer, ShortConvMixer, transformer_layer},MixerExecutables,};-#[cfg(not(feature = "tracing"))]-use crate::backends::metal::MTLCommandEncoder;use crate::{DataType, DecoderLayerConfig,- backends::metal::{MTLCommandBuffer, MTLComputeCommandEncoder, MTLContext, Metal, ProtocolObject, Retained},+ backends::metal::{Metal, MetalContext},config::{DecoderLayerType, MixerConfig},- encodable_block::EncodingParameters,+ encodable_block::{EncodableBlock, EncodingParameters, QKNorm, RMSNorm, TensorAddSwap, TensorCopy},forward_pass::state::{ArrayId, ForwardPassState},parameters::ParameterTree,};@@ -38,7 +39,7 @@ pub struct LayerExecutables {impl LayerExecutables {#[allow(clippy::too_many_arguments)]pub fn new(- mtl_context: Rc<MTLContext>,+ mtl_context: Rc<MetalContext>,layer_config: &DecoderLayerConfig,layer_type: &DecoderLayerType,layer_index: usize,@@ -48,11 +49,11 @@ impl LayerExecutables {head_dim: usize,num_groups: usize,attention_scale: Option<f32>,- decoder_layer_loader: &ParameterTree<MTLContext>,+ decoder_layer_loader: &ParameterTree<MetalContext>,rope: Option<Rc<Box<dyn EncodableBlock<Metal>>>>,) -> Self {autoreleasepool(|_| {- let ctx = &*mtl_context; // Reference for functions expecting &MTLContext+ let ctx = mtl_context.as_ref(); // Reference for functions expecting &MetalContextlet intermediate_data_type: DataType = match &layer_config.mixer_config {MixerConfig::Attention(attention) => attention.qkv_projection_config.activation_precision().into(),MixerConfig::Mamba(mamba) => mamba.in_projection_config.activation_precision().into(),diff --git a/crates/uzu/src/backends/metal/encodable_block/layer/mixer.rs b/crates/uzu/src/backends/metal/encodable_block/layer/mixer.rsindex 16b9eea8d..0ac31a7b4 100644--- a/crates/uzu/src/backends/metal/encodable_block/layer/mixer.rs+++ b/crates/uzu/src/backends/metal/encodable_block/layer/mixer.rs@@ -2,8 +2,7 @@use std::rc::Rc;-use super::super::EncodableBlock;-use crate::backends::metal::Metal;+use crate::{backends::metal::Metal, encodable_block::EncodableBlock};/// Mixer component - either attention, state space, or short conv.pub(crate) enum MixerExecutables {diff --git a/crates/uzu/src/backends/metal/encodable_block/mamba_mixer.rs b/crates/uzu/src/backends/metal/encodable_block/mamba_mixer.rsindex 290f34405..7ffb9ea8f 100644--- a/crates/uzu/src/backends/metal/encodable_block/mamba_mixer.rs+++ b/crates/uzu/src/backends/metal/encodable_block/mamba_mixer.rs@@ -2,16 +2,16 @@use std::env;-use objc2::Message;+use metal::{MTLCommandBuffer, MTLCommandEncoder, MTLComputeCommandEncoder};+use objc2::{Message, rc::Retained, runtime::ProtocolObject};-use super::{EncodableBlock, Metal, transformer_layer};+use super::transformer_layer;use crate::{Activation, DataType,backends::{common::kernel::{Conv1dDecodeKernel, Conv1dPackKernel, Conv1dScanKernel, SSDUpdateKernel, SplitInProjKernel},metal::{- MTLCommandBuffer, MTLCommandEncoder, MTLComputeCommandEncoder, MTLContext, MetalArray, ProtocolObject,- Retained,+ Metal, MetalArray, MetalContext,kernel::{dsl::{Conv1dDecodeMetalKernel, Conv1dPackMetalKernel, Conv1dScanMetalKernel, SSDUpdateMetalKernel,@@ -22,7 +22,7 @@ use crate::{},},config::{DecoderLayerType, Mamba2Config},- encodable_block::EncodingParameters,+ encodable_block::{EncodableBlock, EncodingParameters},forward_pass::state::{ArrayId, ForwardPassState},parameters::ParameterTree,};@@ -48,7 +48,7 @@ pub(crate) struct MambaMixer {impl MambaMixer {#[allow(clippy::too_many_arguments)]pub(crate) fn new(- mtl_context: &MTLContext,+ mtl_context: &MetalContext,layer_type: DecoderLayerType,mamba_config: Mamba2Config,layer_index: usize,@@ -56,7 +56,7 @@ impl MambaMixer {num_heads: usize,head_dim: usize,num_groups: usize,- decoder_layer_loader: &ParameterTree<MTLContext>,+ decoder_layer_loader: &ParameterTree<MetalContext>,) -> Self {let _ = (num_heads, head_dim, num_groups);if !matches!(layer_type, DecoderLayerType::StateSpace { .. }) {@@ -530,9 +530,9 @@ impl EncodableBlock<Metal> for MambaMixer {}fn resolve_subtree<'tree>(- loader: &'tree ParameterTree<MTLContext>,+ loader: &'tree ParameterTree<MetalContext>,candidates: &[&str],-) -> ParameterTree<'tree, MTLContext> {+) -> ParameterTree<'tree, MetalContext> {for candidate in candidates {if let Ok(tree) = loader.subtree(candidate) {return tree;diff --git a/crates/uzu/src/backends/metal/encodable_block/mlp.rs b/crates/uzu/src/backends/metal/encodable_block/mlp.rsindex 70298c6e8..6cfcd4bc0 100644--- a/crates/uzu/src/backends/metal/encodable_block/mlp.rs+++ b/crates/uzu/src/backends/metal/encodable_block/mlp.rs@@ -1,12 +1,11 @@//! MLP block encodable.-use super::{EncodableBlock, Metal};+use metal::{MTLCommandBuffer, MTLCommandEncoder, MTLComputeCommandEncoder};+use objc2::{rc::Retained, runtime::ProtocolObject};+use crate::{- backends::metal::{- MTLCommandBuffer, MTLCommandEncoder, MTLComputeCommandEncoder, ProtocolObject, Retained,- kernel::mlp::MlpGateActMulEncodable,- },- encodable_block::EncodingParameters,+ backends::metal::{Metal, kernel::mlp::MlpGateActMulEncodable},+ encodable_block::{EncodableBlock, EncodingParameters},forward_pass::state::{ArrayId, ForwardPassState},};diff --git a/crates/uzu/src/backends/metal/encodable_block/mod.rs b/crates/uzu/src/backends/metal/encodable_block/mod.rsindex 275846b7b..7c704bc60 100644--- a/crates/uzu/src/backends/metal/encodable_block/mod.rs+++ b/crates/uzu/src/backends/metal/encodable_block/mod.rs@@ -6,9 +6,6 @@//! Encodables implement `EncodableBlock` and orchestrate one or more//! kernels to perform operations on `ForwardPassState`.-pub use super::Metal;-pub use crate::encodable_block::{Activation, EncodableBlock, Pooling, Rope, TensorAddSwap, TensorCopy};-mod attention;mod classifier_layer;mod decoder;@@ -18,7 +15,6 @@ mod linear;mod mamba_mixer;mod mlp;mod moe_block;-mod normalization;mod prediction_head;mod short_conv_mixer;pub mod transformer_layer;@@ -35,6 +31,5 @@ pub use linear::{FullPrecisionLinear, QuantizedLinear};pub(crate) use mamba_mixer::MambaMixer;pub use mlp::MlpBlock;pub use moe_block::{MoeBlock, SharedMoeWeights};-pub use normalization::{LayerNorm, Normalization, QKNorm, RMSNorm};pub use prediction_head::ClassifierPredictionHead;pub(crate) use short_conv_mixer::ShortConvMixer;diff --git a/crates/uzu/src/backends/metal/encodable_block/moe_block/moe_block.rs b/crates/uzu/src/backends/metal/encodable_block/moe_block/moe_block.rsindex d18725db8..aa7c07d87 100644--- a/crates/uzu/src/backends/metal/encodable_block/moe_block/moe_block.rs+++ b/crates/uzu/src/backends/metal/encodable_block/moe_block/moe_block.rs@@ -2,17 +2,16 @@use std::{cell::RefCell, rc::Rc};-use super::{- super::{EncodableBlock, Metal},- SharedMoeWeights,-};+use metal::{MTLBlitCommandEncoderExt, MTLBuffer, MTLCommandBuffer, MTLCommandEncoder, MTLComputeCommandEncoder};+use objc2::{rc::Retained, runtime::ProtocolObject};++use super::SharedMoeWeights;use crate::{Activation, DataType, LinearConfig, MixtureOfExpertsConfig, RoutingFunctionConfig,backends::{common::kernel::{MoeCountsOffsetsFusedKernel, MoeFinalizeKernel},metal::{- MTLBlitCommandEncoderExt, MTLBuffer, MTLCommandBuffer, MTLCommandEncoder, MTLComputeCommandEncoder,- MTLContext, MetalArray, ProtocolObject, Retained,+ Metal, MetalArray, MetalContext,kernel::{MoeGatherKernels,dsl::{MoeCountsOffsetsFusedMetalKernel, MoeFinalizeMetalKernel},@@ -24,7 +23,7 @@ use crate::{},},},- encodable_block::EncodingParameters,+ encodable_block::{EncodableBlock, EncodingParameters},forward_pass::state::{ArrayId, ForwardPassState},parameters::ParameterTree,};@@ -56,12 +55,12 @@ pub struct MoeBlock {impl MoeBlock {pub fn new(- context: &MTLContext,+ context: &MetalContext,moe_config: &MixtureOfExpertsConfig,model_dim: usize,hidden_dim: usize,- parameter_tree: &ParameterTree<MTLContext>,- ) -> Result<Self, crate::backends::metal::MTLError> {+ parameter_tree: &ParameterTree<MetalContext>,+ ) -> Result<Self, crate::backends::metal::MetalError> {let data_type: DataType = moe_config.expert_config.linear_config.activation_precision().into();let router_data_type: DataType = moe_config.router_config.activation_precision().into();@@ -70,7 +69,7 @@ impl MoeBlock {let router_tree = parameter_tree.subtree("router")- .map_err(|e| crate::backends::metal::MTLError::Generic(format!("Router subtree error: {:?}", e)))?;+ .map_err(|e| crate::backends::metal::MetalError::Generic(format!("Router subtree error: {:?}", e)))?;let router = match &moe_config.router_config {LinearConfig::Quantized(_) => {@@ -82,14 +81,14 @@ impl MoeBlock {LinearConfig::FullPrecision {..} => {- let weights_arr = router_tree- .leaf("weights")- .map_err(|e| crate::backends::metal::MTLError::Generic(format!("Router weights error: {:?}", e)))?;+ let weights_arr = router_tree.leaf("weights").map_err(|e| {+ crate::backends::metal::MetalError::Generic(format!("Router weights error: {:?}", e))+ })?;let weights_buf = weights_arr.buffer();- let biases_arr = router_tree- .leaf("biases")- .map_err(|e| crate::backends::metal::MTLError::Generic(format!("Router biases error: {:?}", e)))?;+ let biases_arr = router_tree.leaf("biases").map_err(|e| {+ crate::backends::metal::MetalError::Generic(format!("Router biases error: {:?}", e))+ })?;let biases_buf = biases_arr.buffer();RouterBlock::Metal {@@ -105,53 +104,54 @@ impl MoeBlock {};let router_topk_kernel = MoeRouterTopKKernel::new(context).map_err(|e| {- crate::backends::metal::MTLError::Generic(format!("RouterTopK fused kernel error: {:?}", e))+ crate::backends::metal::MetalError::Generic(format!("RouterTopK fused kernel error: {:?}", e))+ })?;+ let counts_offsets_kernel = MoeCountsOffsetsFusedKernel::new(context).map_err(|e| {+ crate::backends::metal::MetalError::Generic(format!("Counts+offsets kernel error: {:?}", e))})?;- let counts_offsets_kernel = MoeCountsOffsetsFusedKernel::new(context)- .map_err(|e| crate::backends::metal::MTLError::Generic(format!("Counts+offsets kernel error: {:?}", e)))?;let scatter_kernels = MoeScatterKernels::new(context)- .map_err(|e| crate::backends::metal::MTLError::Generic(format!("Scatter kernels error: {:?}", e)))?;+ .map_err(|e| crate::backends::metal::MetalError::Generic(format!("Scatter kernels error: {:?}", e)))?;let gather_kernel = MoeGatherKernels::new(context)- .map_err(|e| crate::backends::metal::MTLError::Generic(format!("Gather kernel error: {:?}", e)))?;+ .map_err(|e| crate::backends::metal::MetalError::Generic(format!("Gather kernel error: {:?}", e)))?;let experts_two_pass_decode_kernel = MoeExpertsTwoPassDecodeKernels::new(context).map_err(|e| {- crate::backends::metal::MTLError::Generic(format!("Experts two-pass decode kernel error: {:?}", e))+ crate::backends::metal::MetalError::Generic(format!("Experts two-pass decode kernel error: {:?}", e))})?;let experts_two_pass_prefill_kernel = MoeExpertsTwoPassPrefillKernel::new(context).map_err(|e| {- crate::backends::metal::MTLError::Generic(format!("Experts two-pass prefill kernel error: {:?}", e))+ crate::backends::metal::MetalError::Generic(format!("Experts two-pass prefill kernel error: {:?}", e))})?;let finalize_kernel = MoeFinalizeMetalKernel::new(context, data_type)- .map_err(|e| crate::backends::metal::MTLError::Generic(format!("Finalize kernel error: {:?}", e)))?;+ .map_err(|e| crate::backends::metal::MetalError::Generic(format!("Finalize kernel error: {:?}", e)))?;let experts_tree = parameter_tree.subtree("experts")- .map_err(|e| crate::backends::metal::MTLError::Generic(format!("experts subtree error: {:?}", e)))?;+ .map_err(|e| crate::backends::metal::MetalError::Generic(format!("experts subtree error: {:?}", e)))?;let w13_arr = experts_tree.subtree("up_projection")- .map_err(|e| crate::backends::metal::MTLError::Generic(format!("up_projection error: {:?}", e)))?+ .map_err(|e| crate::backends::metal::MetalError::Generic(format!("up_projection error: {:?}", e)))?.leaf("weights")- .map_err(|e| crate::backends::metal::MTLError::Generic(format!("up weights error: {:?}", e)))?;+ .map_err(|e| crate::backends::metal::MetalError::Generic(format!("up weights error: {:?}", e)))?;let w13_buf = w13_arr.buffer().clone();let w2_arr = experts_tree.subtree("down_projection")- .map_err(|e| crate::backends::metal::MTLError::Generic(format!("down_projection error: {:?}", e)))?+ .map_err(|e| crate::backends::metal::MetalError::Generic(format!("down_projection error: {:?}", e)))?.leaf("weights")- .map_err(|e| crate::backends::metal::MTLError::Generic(format!("down weights error: {:?}", e)))?;+ .map_err(|e| crate::backends::metal::MetalError::Generic(format!("down weights error: {:?}", e)))?;let w2_buf = w2_arr.buffer().clone();let up_biases_arr = experts_tree.subtree("up_projection")- .map_err(|e| crate::backends::metal::MTLError::Generic(format!("up_projection biases error: {:?}", e)))?+ .map_err(|e| crate::backends::metal::MetalError::Generic(format!("up_projection biases error: {:?}", e)))?.leaf("biases")- .map_err(|e| crate::backends::metal::MTLError::Generic(format!("up biases error: {:?}", e)))?;+ .map_err(|e| crate::backends::metal::MetalError::Generic(format!("up biases error: {:?}", e)))?;let up_biases_buf = up_biases_arr.buffer().clone();let down_biases_arr = experts_tree.subtree("down_projection")- .map_err(|e| crate::backends::metal::MTLError::Generic(format!("down_projection biases error: {:?}", e)))?+ .map_err(|e| crate::backends::metal::MetalError::Generic(format!("down_projection biases error: {:?}", e)))?.leaf("biases")- .map_err(|e| crate::backends::metal::MTLError::Generic(format!("down biases error: {:?}", e)))?;+ .map_err(|e| crate::backends::metal::MetalError::Generic(format!("down biases error: {:?}", e)))?;let down_biases_buf = down_biases_arr.buffer().clone();let shared_weights = SharedMoeWeights {diff --git a/crates/uzu/src/backends/metal/encodable_block/moe_block/shared_weights.rs b/crates/uzu/src/backends/metal/encodable_block/moe_block/shared_weights.rsindex a7a948335..bc51a10bd 100644--- a/crates/uzu/src/backends/metal/encodable_block/moe_block/shared_weights.rs+++ b/crates/uzu/src/backends/metal/encodable_block/moe_block/shared_weights.rs@@ -2,7 +2,8 @@use std::rc::Rc;-use crate::backends::metal::{MTLBuffer, ProtocolObject, Retained};+use metal::MTLBuffer;+use objc2::{rc::Retained, runtime::ProtocolObject};#[derive(Clone)]pub struct SharedMoeWeights {diff --git a/crates/uzu/src/backends/metal/encodable_block/normalization/mod.rs b/crates/uzu/src/backends/metal/encodable_block/normalization/mod.rsdeleted file mode 100644index 583158542..000000000--- a/crates/uzu/src/backends/metal/encodable_block/normalization/mod.rs+++ /dev/null@@ -1,12 +0,0 @@-//! Unified normalization encodables: LayerNorm, RMSNorm, QKNorm.--use super::Metal;-use crate::encodable_block::{- LayerNorm as GenericLayerNorm, Normalization as GenericNormalization, QKNorm as GenericQKNorm,- RMSNorm as GenericRMSNorm,-};--pub type LayerNorm = GenericLayerNorm<Metal>;-pub type RMSNorm = GenericRMSNorm<Metal>;-pub type Normalization = GenericNormalization<Metal>;-pub type QKNorm = GenericQKNorm<Metal>;diff --git a/crates/uzu/src/backends/metal/encodable_block/prediction_head.rs b/crates/uzu/src/backends/metal/encodable_block/prediction_head.rsindex 041280f4f..71154dbc1 100644--- a/crates/uzu/src/backends/metal/encodable_block/prediction_head.rs+++ b/crates/uzu/src/backends/metal/encodable_block/prediction_head.rs@@ -1,13 +1,15 @@//! Prediction head encodable for classification output.-use super::{EncodableBlock, Metal};#[cfg(feature = "tracing")]-use crate::backends::metal::MTLBlitCommandEncoder;+use metal::MTLBlitCommandEncoder;+use metal::{MTLCommandBuffer, MTLCommandEncoder, MTLComputeCommandEncoder};+use objc2::{rc::Retained, runtime::ProtocolObject};+#[cfg(feature = "tracing")]use crate::forward_pass::state::ArrayId;use crate::{- backends::metal::{MTLCommandBuffer, MTLCommandEncoder, MTLComputeCommandEncoder, ProtocolObject, Retained},- encodable_block::EncodingParameters,+ backends::metal::Metal,+ encodable_block::{EncodableBlock, EncodingParameters},forward_pass::state::ForwardPassState,};diff --git a/crates/uzu/src/backends/metal/encodable_block/short_conv_mixer.rs b/crates/uzu/src/backends/metal/encodable_block/short_conv_mixer.rsindex b443231d1..336e837e2 100644--- a/crates/uzu/src/backends/metal/encodable_block/short_conv_mixer.rs+++ b/crates/uzu/src/backends/metal/encodable_block/short_conv_mixer.rs@@ -1,4 +1,7 @@-use super::{EncodableBlock, Metal, transformer_layer};+use metal::{MTLCommandBuffer, MTLCommandEncoder, MTLComputeCommandEncoder};+use objc2::{rc::Retained, runtime::ProtocolObject};++use super::transformer_layer;use crate::{DataType,backends::{@@ -7,8 +10,7 @@ use crate::{kernel::{ShortConvDecodeKernel, ShortConvPackKernel, ShortConvPrefillKernel, ShortConvTrieKernel},},metal::{- MTLCommandBuffer, MTLCommandEncoder, MTLComputeCommandEncoder, MTLContext, MetalArray, ProtocolObject,- Retained,+ Metal, MetalArray, MetalContext,kernel::dsl::{ShortConvDecodeMetalKernel, ShortConvPackMetalKernel, ShortConvPrefillMetalKernel,ShortConvTrieMetalKernel,@@ -16,7 +18,7 @@ use crate::{},},config::{DecoderLayerType, ShortConvConfig},- encodable_block::EncodingParameters,+ encodable_block::{EncodableBlock, EncodingParameters},forward_pass::state::{ArrayId, ForwardPassState},parameters::ParameterTree,};@@ -36,9 +38,9 @@ pub(crate) struct ShortConvMixer {}fn resolve_subtree<'tree>(- tree: &'tree ParameterTree<MTLContext>,+ tree: &'tree ParameterTree<MetalContext>,candidates: &[&str],-) -> ParameterTree<'tree, MTLContext> {+) -> ParameterTree<'tree, MetalContext> {for candidate in candidates {if let Ok(subtree) = tree.subtree(candidate) {return subtree;@@ -50,12 +52,12 @@ fn resolve_subtree<'tree>(impl ShortConvMixer {#[allow(clippy::too_many_arguments)]pub(crate) fn new(- mtl_context: &MTLContext,+ mtl_context: &MetalContext,layer_type: DecoderLayerType,short_conv_config: ShortConvConfig,layer_index: usize,model_dim: usize,- decoder_layer_loader: &ParameterTree<MTLContext>,+ decoder_layer_loader: &ParameterTree<MetalContext>,) -> Self {if !matches!(layer_type, DecoderLayerType::ShortConv { .. }) {panic!("Layer {} marked as non-ShortConv but ShortConv config provided", layer_index);diff --git a/crates/uzu/src/backends/metal/encodable_block/transformer_layer.rs b/crates/uzu/src/backends/metal/encodable_block/transformer_layer.rsindex d8891e29f..8bee2f346 100644--- a/crates/uzu/src/backends/metal/encodable_block/transformer_layer.rs+++ b/crates/uzu/src/backends/metal/encodable_block/transformer_layer.rs@@ -1,11 +1,12 @@use super::{- EncodableBlock, FullPrecisionEmbeddingLookup, FullPrecisionEmbeddingReadout, FullPrecisionLinear, Metal, MlpBlock,- MoeBlock, QuantizedEmbeddingLookup, QuantizedEmbeddingReadout, QuantizedLinear,+ FullPrecisionEmbeddingLookup, FullPrecisionEmbeddingReadout, FullPrecisionLinear, MlpBlock, MoeBlock,+ QuantizedEmbeddingLookup, QuantizedEmbeddingReadout, QuantizedLinear,};use crate::{DataType,- backends::metal::{MTLContext, MTLError, kernel::mlp::MlpGateActMulEncodable},+ backends::metal::{Metal, MetalContext, MetalError, kernel::mlp::MlpGateActMulEncodable},config::{DecoderConfig, EmbeddingConfig, LinearConfig, MLPConfig},+ encodable_block::EncodableBlock,forward_pass::state::ArrayId,parameters::ParameterTree,};@@ -15,11 +16,11 @@ pub fn linear_block<const N: usize>(_has_biases: bool,input_dimension: usize,output_dimensions: [usize; N],- context: &MTLContext,- parameter_tree: &ParameterTree<MTLContext>,+ context: &MetalContext,+ parameter_tree: &ParameterTree<MetalContext>,input_array_id: ArrayId,output_array_id: ArrayId,-) -> Result<Box<dyn EncodableBlock<Metal>>, MTLError> {+) -> Result<Box<dyn EncodableBlock<Metal>>, MetalError> {let output_dimension_sum: usize = output_dimensions.iter().sum();match config {LinearConfig::Quantized(quantization_config) | LinearConfig::MLXQuantized(quantization_config) => {@@ -32,7 +33,7 @@ pub fn linear_block<const N: usize>(input_array_id,output_array_id,)- .map_err(|error| MTLError::Generic(format!("{:?}", error)))?;+ .map_err(|error| MetalError::Generic(format!("{:?}", error)))?;Ok(Box::new(block))},LinearConfig::FullPrecision {@@ -47,12 +48,12 @@ pub fn linear_block<const N: usize>(input_array_id,output_array_id,)- .map_err(|error| MTLError::Generic(format!("{:?}", error)))?;+ .map_err(|error| MetalError::Generic(format!("{:?}", error)))?;Ok(Box::new(block))},LinearConfig::QLoRA {..- } => Err(MTLError::Generic("QLoRA linear layer not supported".to_string())),+ } => Err(MetalError::Generic("QLoRA linear layer not supported".to_string())),}}@@ -61,9 +62,9 @@ pub fn mlp_block(config: &MLPConfig,model_dimension: usize,hidden_dimension: usize,- context: &MTLContext,- parameter_tree: &ParameterTree<MTLContext>,-) -> Result<Box<dyn EncodableBlock<Metal>>, MTLError> {+ context: &MetalContext,+ parameter_tree: &ParameterTree<MetalContext>,+) -> Result<Box<dyn EncodableBlock<Metal>>, MetalError> {if let crate::config::MLPConfig::Dense(dense_config) = config {let data_type: DataType = dense_config.linear_config.activation_precision().into();@@ -74,7 +75,7 @@ pub fn mlp_block(model_dimension,[2 * hidden_dimension],context,- ¶meter_tree.subtree("up_projection").map_err(|error| MTLError::Generic(format!("{:?}", error)))?,+ ¶meter_tree.subtree("up_projection").map_err(|error| MetalError::Generic(format!("{:?}", error)))?,ArrayId::Main,ArrayId::MlpFusedUp,)?;@@ -90,7 +91,7 @@ pub fn mlp_block(hidden_dimension,[model_dimension],context,- ¶meter_tree.subtree("down_projection").map_err(|error| MTLError::Generic(format!("{:?}", error)))?,+ ¶meter_tree.subtree("down_projection").map_err(|error| MetalError::Generic(format!("{:?}", error)))?,ArrayId::MlpHidden,ArrayId::Main,)?;@@ -109,8 +110,8 @@ pub fn mlp_block(pub fn embed_block(config: &DecoderConfig,- context: &MTLContext,- parameter_tree: &ParameterTree<MTLContext>,+ context: &MetalContext,+ parameter_tree: &ParameterTree<MetalContext>,) -> Box<dyn EncodableBlock<Metal>> {match &config.embedding_config {EmbeddingConfig::Tied {@@ -249,8 +250,8 @@ pub fn embed_block(pub fn readout_block(config: &DecoderConfig,- context: &MTLContext,- parameter_tree: &ParameterTree<MTLContext>,+ context: &MetalContext,+ parameter_tree: &ParameterTree<MetalContext>,) -> Box<dyn EncodableBlock<Metal>> {match &config.embedding_config {EmbeddingConfig::Tied {diff --git a/crates/uzu/src/backends/metal/error.rs b/crates/uzu/src/backends/metal/error.rsindex 34164f418..620b39be8 100644--- a/crates/uzu/src/backends/metal/error.rs+++ b/crates/uzu/src/backends/metal/error.rs@@ -1,8 +1,8 @@use thiserror::Error;#[derive(Debug, Error)]-pub enum MTLError {- #[error("MTLContext error: {0}")]+pub enum MetalError {+ #[error("MetalContext error: {0}")]Context(#[from] ContextError),#[error("MTLDevice error: {0}")]Device(#[from] DeviceError),@@ -28,15 +28,15 @@ pub enum MTLError {Generic(String),}-impl From<&str> for MTLError {+impl From<&str> for MetalError {fn from(error: &str) -> Self {- MTLError::Generic(error.to_string())+ MetalError::Generic(error.to_string())}}-impl From<String> for MTLError {+impl From<String> for MetalError {fn from(error: String) -> Self {- MTLError::Generic(error)+ MetalError::Generic(error)}}diff --git a/crates/uzu/src/backends/metal/kernel/attention/mod.rs b/crates/uzu/src/backends/metal/kernel/attention/mod.rsindex 51a48d9d4..241747e35 100644--- a/crates/uzu/src/backends/metal/kernel/attention/mod.rs+++ b/crates/uzu/src/backends/metal/kernel/attention/mod.rs@@ -1,6 +1,7 @@use std::{collections::HashMap, mem::size_of, ptr::NonNull};-use objc2::rc::Retained;+use metal::{MTLBuffer, MTLComputeCommandEncoder, MTLComputePipelineState, MTLFunctionConstantValues, MTLSize};+use objc2::{rc::Retained, runtime::ProtocolObject};use thiserror::Error;use crate::{@@ -8,8 +9,7 @@ use crate::{backends::{common::gpu_types::{AttnMaskParams, AttnParams},metal::{- FunctionConstantValuesSetValue, MTLBuffer, MTLComputeCommandEncoder, MTLComputePipelineState, MTLContext,- MTLError, MTLFunctionConstantValues, MTLSize, ProtocolObject, data_type::MetalDataTypeExt,+ FunctionConstantValuesSetValue, MetalContext, MetalError, data_type::MetalDataTypeExt,kernel::moe::dtype_suffix,},},@@ -38,7 +38,7 @@ pub struct AttentionKernel {#[derive(Debug, Error)]pub enum AttentionError {#[error("Metal error: {0}")]- MetalError(#[from] MTLError),+ MetalError(#[from] MetalError),#[error("Function not found: {0}")]FunctionNotFound(String),#[error("Unsupported head dimension: {0}")]@@ -148,7 +148,7 @@ fn make_function_constants(impl AttentionKernel {pub fn new(- context: &MTLContext,+ context: &MetalContext,data_type: DataType,) -> Result<Self, AttentionError> {let data_suffix = data_type.metal_type();@@ -551,7 +551,7 @@ impl AttentionKernel {pub fn encode_gemm(&self,- context: &MTLContext,+ context: &MetalContext,compute_encoder: &ProtocolObject<dyn MTLComputeCommandEncoder>,args: AttentionGemmArguments,) -> Result<(), AttentionError> {diff --git a/crates/uzu/src/backends/metal/kernel/matmul/common/matmul_arguments.rs b/crates/uzu/src/backends/metal/kernel/matmul/common/matmul_arguments.rsindex 8cda26600..b01d3cd5a 100644--- a/crates/uzu/src/backends/metal/kernel/matmul/common/matmul_arguments.rs+++ b/crates/uzu/src/backends/metal/kernel/matmul/common/matmul_arguments.rs@@ -1,4 +1,5 @@-use crate::backends::metal::{MTLBuffer, ProtocolObject, Retained};+use metal::MTLBuffer;+use objc2::{rc::Retained, runtime::ProtocolObject};#[derive(Debug, Clone)]pub struct MatmulArguments<'a> {diff --git a/crates/uzu/src/backends/metal/kernel/matmul/dispatch_descriptor.rs b/crates/uzu/src/backends/metal/kernel/matmul/dispatch_descriptor.rsindex 91690f38a..103714ddb 100644--- a/crates/uzu/src/backends/metal/kernel/matmul/dispatch_descriptor.rs+++ b/crates/uzu/src/backends/metal/kernel/matmul/dispatch_descriptor.rs@@ -1,7 +1,7 @@use super::{common::MatmulArguments, gemm, gemv, split_k};use crate::{DataType,- backends::metal::{MTLContext, MTLError},+ backends::metal::{MetalContext, MetalError},};#[derive(Debug, Clone, Copy, PartialEq, Eq)]@@ -39,10 +39,10 @@ impl MatmulDispatchDescriptor {}pub(crate) fn choose_dispatch_descriptor(- context: &MTLContext,+ context: &MetalContext,data_type: DataType,arguments: &MatmulArguments,-) -> Result<MatmulDispatchDescriptor, MTLError> {+) -> Result<MatmulDispatchDescriptor, MetalError> {if let Some(descriptor) = gemv::DispatchDescriptor::try_new(context, data_type, arguments)? {return Ok(MatmulDispatchDescriptor::Gemv(descriptor));}@@ -55,9 +55,9 @@ pub(crate) fn choose_dispatch_descriptor(}pub fn determine_kernel_variant(- context: &MTLContext,+ context: &MetalContext,data_type: DataType,arguments: &MatmulArguments,-) -> Result<MatmulKernelVariant, MTLError> {+) -> Result<MatmulKernelVariant, MetalError> {choose_dispatch_descriptor(context, data_type, arguments).map(|d| d.variant())}diff --git a/crates/uzu/src/backends/metal/kernel/matmul/gemm/dispatch_descriptor.rs b/crates/uzu/src/backends/metal/kernel/matmul/gemm/dispatch_descriptor.rsindex 8b8d5b61b..1f82cfc0e 100644--- a/crates/uzu/src/backends/metal/kernel/matmul/gemm/dispatch_descriptor.rs+++ b/crates/uzu/src/backends/metal/kernel/matmul/gemm/dispatch_descriptor.rs@@ -1,8 +1,10 @@+use metal::MTLSize;+use super::{pipeline_configuration::PipelineConfiguration, tile_configuration::TileConfiguration};use crate::{DataType,backends::metal::{- DeviceClass, MTLContext, MTLError, MTLSize,+ DeviceClass, MetalContext, MetalError,kernel::matmul::common::{GEMMAddMMParams, GEMMParams, MatmulArguments},},};@@ -18,12 +20,12 @@ pub(crate) struct DispatchDescriptor {impl DispatchDescriptor {pub(crate) fn new(- context: &MTLContext,+ context: &MetalContext,data_type: DataType,arguments: &MatmulArguments,- ) -> Result<Self, MTLError> {+ ) -> Result<Self, MetalError> {if !matches!(data_type, DataType::F16 | DataType::BF16 | DataType::F32) {- return Err(MTLError::Generic(format!("Unsupported dtype for GEMM: {data_type:?}")));+ return Err(MetalError::Generic(format!("Unsupported dtype for GEMM: {data_type:?}")));}let tile = select_tile(context, data_type, arguments);@@ -108,7 +110,7 @@ impl DispatchDescriptor {}fn select_tile(- context: &MTLContext,+ context: &MetalContext,data_type: DataType,arguments: &MatmulArguments,) -> TileConfiguration {diff --git a/crates/uzu/src/backends/metal/kernel/matmul/gemm/kernel.rs b/crates/uzu/src/backends/metal/kernel/matmul/gemm/kernel.rsindex 7ca7457b9..c48a6e25c 100644--- a/crates/uzu/src/backends/metal/kernel/matmul/gemm/kernel.rs+++ b/crates/uzu/src/backends/metal/kernel/matmul/gemm/kernel.rs@@ -1,11 +1,13 @@use std::collections::HashMap;+use metal::{MTLComputeCommandEncoder, MTLComputePipelineState, MTLFunctionConstantValues};+use objc2::{rc::Retained, runtime::ProtocolObject};+use super::{DispatchDescriptor, pipeline_configuration::PipelineConfiguration, tile_configuration::TileConfiguration};use crate::{DataType,backends::metal::{- ComputeEncoderSetValue, FunctionConstantValuesSetValue, MTLComputeCommandEncoder, MTLComputePipelineState,- MTLContext, MTLError, MTLFunctionConstantValues, ProtocolObject, Retained,+ ComputeEncoderSetValue, FunctionConstantValuesSetValue, MetalContext, MetalError,kernel::matmul::common::{MatmulArguments, transpose_configuration},},};@@ -16,9 +18,9 @@ pub struct Kernel {}impl Kernel {- pub fn new(data_type: DataType) -> Result<Self, MTLError> {+ pub fn new(data_type: DataType) -> Result<Self, MetalError> {if !matches!(data_type, DataType::F16 | DataType::BF16 | DataType::F32) {- return Err(MTLError::Generic(format!("Unsupported dtype for GEMM: {data_type:?}")));+ return Err(MetalError::Generic(format!("Unsupported dtype for GEMM: {data_type:?}")));}Ok(Self {data_type,@@ -29,8 +31,8 @@ impl Kernel {#[allow(clippy::type_complexity)]pub fn precompile(&mut self,- context: &MTLContext,- ) -> Result<(), MTLError> {+ context: &MetalContext,+ ) -> Result<(), MetalError> {let tiles_and_alignments: &[(TileConfiguration, &[(bool, bool, bool)])] = match self.data_type {DataType::BF16 => &[(TileConfiguration::new(64, 32, 32, 2, 2, 0), &[(false, true, true), (true, true, true)]),@@ -105,9 +107,9 @@ impl Kernel {fn get_or_compile_pipeline(&mut self,- context: &MTLContext,+ context: &MetalContext,configuration: &PipelineConfiguration,- ) -> Result<&Retained<ProtocolObject<dyn MTLComputePipelineState>>, MTLError> {+ ) -> Result<&Retained<ProtocolObject<dyn MTLComputePipelineState>>, MetalError> {if !self.pipelines.contains_key(configuration) {let kernel_name = self.kernel_name(configuration);let function_constants = MTLFunctionConstantValues::new();@@ -137,11 +139,11 @@ impl Kernel {pub(crate) fn encode_descriptor(&mut self,- context: &MTLContext,+ context: &MetalContext,encoder: &ProtocolObject<dyn MTLComputeCommandEncoder>,arguments: &MatmulArguments,descriptor: &DispatchDescriptor,- ) -> Result<bool, MTLError> {+ ) -> Result<bool, MetalError> {let pipeline_state = self.get_or_compile_pipeline(context, &descriptor.pipeline_configuration)?;encoder.set_compute_pipeline_state(pipeline_state);diff --git a/crates/uzu/src/backends/metal/kernel/matmul/gemv/dispatch_descriptor.rs b/crates/uzu/src/backends/metal/kernel/matmul/gemv/dispatch_descriptor.rsindex 9cf36aa3f..4caf6e5c9 100644--- a/crates/uzu/src/backends/metal/kernel/matmul/gemv/dispatch_descriptor.rs+++ b/crates/uzu/src/backends/metal/kernel/matmul/gemv/dispatch_descriptor.rs@@ -1,9 +1,11 @@use std::sync::OnceLock;+use metal::MTLSize;+use super::pipeline_configuration::{PipelineConfiguration, select_configuration};use crate::{DataType,- backends::metal::{MTLContext, MTLError, MTLSize, kernel::matmul::common::MatmulArguments},+ backends::metal::{MetalContext, MetalError, kernel::matmul::common::MatmulArguments},};const DEFAULT_GEMV_MAX_BATCH: i32 = 8;@@ -51,12 +53,12 @@ pub(crate) struct DispatchDescriptor {impl DispatchDescriptor {pub(crate) fn try_new(- _context: &MTLContext,+ _context: &MetalContext,data_type: DataType,arguments: &MatmulArguments,- ) -> Result<Option<Self>, MTLError> {+ ) -> Result<Option<Self>, MetalError> {if !matches!(data_type, DataType::F16 | DataType::BF16 | DataType::F32) {- return Err(MTLError::Generic(format!("Unsupported data type for GEMV: {data_type:?}")));+ return Err(MetalError::Generic(format!("Unsupported data type for GEMV: {data_type:?}")));}if arguments.transpose_a || !arguments.transpose_b {diff --git a/crates/uzu/src/backends/metal/kernel/matmul/gemv/kernel.rs b/crates/uzu/src/backends/metal/kernel/matmul/gemv/kernel.rsindex ed55e89c1..50ea1b67a 100644--- a/crates/uzu/src/backends/metal/kernel/matmul/gemv/kernel.rs+++ b/crates/uzu/src/backends/metal/kernel/matmul/gemv/kernel.rs@@ -1,27 +1,27 @@use std::collections::HashMap;+use metal::{MTLComputeCommandEncoder, MTLComputePipelineState};+use objc2::{rc::Retained, runtime::ProtocolObject};+use super::{dispatch_descriptor::{AxpbySource, DispatchDescriptor},pipeline_configuration::PipelineConfiguration,};use crate::{DataType,- backends::metal::{- ComputeEncoderSetValue, MTLComputeCommandEncoder, MTLComputePipelineState, MTLContext, MTLError,- ProtocolObject, Retained, kernel::matmul::common::MatmulArguments,- },+ backends::metal::{ComputeEncoderSetValue, MetalContext, MetalError, kernel::matmul::common::MatmulArguments},};fn gemv_kernel_name(data_type: DataType,config: &PipelineConfiguration,-) -> Result<String, MTLError> {+) -> Result<String, MetalError> {let dtype_name = match data_type {DataType::F16 => "float16",DataType::BF16 => "bfloat16",DataType::F32 => "float32",_ => {- return Err(MTLError::Generic(format!("Unsupported data type for GEMV: {:?}", data_type)));+ return Err(MetalError::Generic(format!("Unsupported data type for GEMV: {:?}", data_type)));},};@@ -58,9 +58,9 @@ pub struct Kernel {}impl Kernel {- pub fn new(data_type: DataType) -> Result<Self, MTLError> {+ pub fn new(data_type: DataType) -> Result<Self, MetalError> {if !matches!(data_type, DataType::F16 | DataType::BF16 | DataType::F32) {- return Err(MTLError::Generic(format!("Unsupported data type for GEMV: {:?}", data_type)));+ return Err(MetalError::Generic(format!("Unsupported data type for GEMV: {:?}", data_type)));}Ok(Self {data_type,@@ -70,8 +70,8 @@ impl Kernel {pub fn precompile(&mut self,- context: &MTLContext,- ) -> Result<(), MTLError> {+ context: &MetalContext,+ ) -> Result<(), MetalError> {let configs: &[(u32, bool)] = match self.data_type {DataType::BF16 => &[(4, false), (4, true), (8, false), (8, true)],DataType::F16 => &[(8, false)],@@ -102,9 +102,9 @@ impl Kernel {fn get_pipeline(&mut self,- context: &MTLContext,+ context: &MetalContext,config: &PipelineConfiguration,- ) -> Result<&Retained<ProtocolObject<dyn MTLComputePipelineState>>, MTLError> {+ ) -> Result<&Retained<ProtocolObject<dyn MTLComputePipelineState>>, MetalError> {if !self.pipelines.contains_key(config) {let kernel_name = gemv_kernel_name(self.data_type, config)?;let pipeline = context.compute_pipeline_state(&kernel_name, None)?;@@ -115,11 +115,11 @@ impl Kernel {pub(crate) fn encode_descriptor(&mut self,- context: &MTLContext,+ context: &MetalContext,encoder: &ProtocolObject<dyn MTLComputeCommandEncoder>,arguments: &MatmulArguments,descriptor: &DispatchDescriptor,- ) -> Result<bool, MTLError> {+ ) -> Result<bool, MetalError> {let pipeline = self.get_pipeline(context, &descriptor.pipeline_configuration)?;encoder.set_compute_pipeline_state(pipeline);@@ -140,19 +140,20 @@ impl Kernel {if descriptor.pipeline_configuration.do_axpby {match descriptor.axpby_source {AxpbySource::None => {- return Err(MTLError::Generic(+ return Err(MetalError::Generic("GEMV descriptor mismatch: do_axpby=true but axpby_source=None".to_owned(),));},AxpbySource::Bias => {let bias = arguments.bias- .ok_or_else(|| MTLError::Generic("GEMV descriptor requires bias buffer".to_owned()))?;+ .ok_or_else(|| MetalError::Generic("GEMV descriptor requires bias buffer".to_owned()))?;encoder.set_buffer(Some(bias), 0, 2);},AxpbySource::C => {- let c_buffer =- arguments.c.ok_or_else(|| MTLError::Generic("GEMV descriptor requires C buffer".to_owned()))?;+ let c_buffer = arguments+ .c+ .ok_or_else(|| MetalError::Generic("GEMV descriptor requires C buffer".to_owned()))?;encoder.set_buffer(Some(c_buffer), 0, 2);},}diff --git a/crates/uzu/src/backends/metal/kernel/matmul/gemv/pipeline_configuration.rs b/crates/uzu/src/backends/metal/kernel/matmul/gemv/pipeline_configuration.rsindex 96339e3dd..45b40814b 100644--- a/crates/uzu/src/backends/metal/kernel/matmul/gemv/pipeline_configuration.rs+++ b/crates/uzu/src/backends/metal/kernel/matmul/gemv/pipeline_configuration.rs@@ -1,4 +1,4 @@-use crate::backends::metal::MTLSize;+use metal::MTLSize;#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]pub struct PipelineConfiguration {diff --git a/crates/uzu/src/backends/metal/kernel/matmul/kernel.rs b/crates/uzu/src/backends/metal/kernel/matmul/kernel.rsindex fccee162f..51f7fd804 100644--- a/crates/uzu/src/backends/metal/kernel/matmul/kernel.rs+++ b/crates/uzu/src/backends/metal/kernel/matmul/kernel.rs@@ -1,3 +1,6 @@+use metal::{MTLBuffer, MTLComputeCommandEncoder};+use objc2::{rc::Retained, runtime::ProtocolObject};+use super::{common::MatmulArguments,dispatch_descriptor::{MatmulDispatchDescriptor, choose_dispatch_descriptor},@@ -9,10 +12,7 @@ use crate::{DataType,backends::{common::kernel::TensorAddBiasKernel,- metal::{- MTLBuffer, MTLComputeCommandEncoder, MTLContext, MTLError, ProtocolObject, Retained,- kernel::dsl::TensorAddBiasMetalKernel,- },+ metal::{MetalContext, MetalError, kernel::dsl::TensorAddBiasMetalKernel},},};@@ -25,9 +25,9 @@ pub struct MatmulKernel {}impl MatmulKernel {- pub fn new(data_type: DataType) -> Result<Self, MTLError> {+ pub fn new(data_type: DataType) -> Result<Self, MetalError> {if !matches!(data_type, DataType::F16 | DataType::BF16 | DataType::F32) {- return Err(MTLError::Generic(format!("Unsupported dtype for MatmulKernel: {data_type:?}")));+ return Err(MetalError::Generic(format!("Unsupported dtype for MatmulKernel: {data_type:?}")));}Ok(Self {@@ -41,8 +41,8 @@ impl MatmulKernel {pub fn precompile(&mut self,- context: &MTLContext,- ) -> Result<(), MTLError> {+ context: &MetalContext,+ ) -> Result<(), MetalError> {let gemm = self.get_or_create_gemm()?;gemm.precompile(context)?;@@ -55,21 +55,21 @@ impl MatmulKernel {Ok(())}- fn get_or_create_gemm(&mut self) -> Result<&mut gemm::GemmKernel, MTLError> {+ fn get_or_create_gemm(&mut self) -> Result<&mut gemm::GemmKernel, MetalError> {if self.gemm.is_none() {self.gemm = Some(gemm::GemmKernel::new(self.data_type)?);}Ok(self.gemm.as_mut().unwrap())}- fn get_or_create_gemv(&mut self) -> Result<&mut GemvKernel, MTLError> {+ fn get_or_create_gemv(&mut self) -> Result<&mut GemvKernel, MetalError> {if self.gemv.is_none() {self.gemv = Some(GemvKernel::new(self.data_type)?);}Ok(self.gemv.as_mut().unwrap())}- fn get_or_create_splitk(&mut self) -> Result<&mut SplitKGemm, MTLError> {+ fn get_or_create_splitk(&mut self) -> Result<&mut SplitKGemm, MetalError> {if self.splitk.is_none() {self.splitk = Some(SplitKGemm::new(self.data_type)?);}@@ -78,11 +78,11 @@ impl MatmulKernel {fn encode_dispatch_descriptor(&mut self,- context: &MTLContext,+ context: &MetalContext,encoder: &ProtocolObject<dyn MTLComputeCommandEncoder>,arguments: &MatmulArguments,descriptor: &MatmulDispatchDescriptor,- ) -> Result<bool, MTLError> {+ ) -> Result<bool, MetalError> {match descriptor {MatmulDispatchDescriptor::Gemv(descriptor) => {let gemv = self.get_or_create_gemv()?;@@ -101,10 +101,10 @@ impl MatmulKernel {pub fn encode(&mut self,- context: &MTLContext,+ context: &MetalContext,encoder: &ProtocolObject<dyn MTLComputeCommandEncoder>,mut arguments: MatmulArguments,- ) -> Result<(), MTLError> {+ ) -> Result<(), MetalError> {Self::apply_batch_collapse(&mut arguments);let descriptor = choose_dispatch_descriptor(context, self.data_type, &arguments)?;@@ -122,11 +122,11 @@ impl MatmulKernel {fn apply_bias_add(&mut self,- context: &MTLContext,+ context: &MetalContext,encoder: &ProtocolObject<dyn MTLComputeCommandEncoder>,arguments: &MatmulArguments,bias: &Retained<ProtocolObject<dyn MTLBuffer>>,- ) -> Result<(), MTLError> {+ ) -> Result<(), MetalError> {let m = arguments.batch as usize;let n = arguments.output_dim as usize;let batch_count = arguments.batch_count as usize;diff --git a/crates/uzu/src/backends/metal/kernel/matmul/mod.rs b/crates/uzu/src/backends/metal/kernel/matmul/mod.rsindex 8c3b55834..870d81566 100644--- a/crates/uzu/src/backends/metal/kernel/matmul/mod.rs+++ b/crates/uzu/src/backends/metal/kernel/matmul/mod.rs@@ -9,6 +9,8 @@ pub use common::MatmulArguments;pub use dispatch_descriptor::{MatmulKernelVariant, determine_kernel_variant};pub use gemv::GemvKernel;pub use kernel::MatmulKernel;+use metal::MTLComputeCommandEncoder;+use objc2::runtime::ProtocolObject;pub use split_k::SplitKGemm;use crate::{@@ -17,7 +19,7 @@ use crate::{common::kernel::matmul::{FullPrecisionMatmulArguments, FullPrecisionMatmulKernel as FullPrecisionMatmulKernelTrait,},- metal::{MTLComputeCommandEncoder, MTLContext, MTLError, Metal, ProtocolObject},+ metal::{Metal, MetalContext, MetalError},},};@@ -25,9 +27,9 @@ impl FullPrecisionMatmulKernelTrait for MatmulKernel {type Backend = Metal;fn new(- context: &MTLContext,+ context: &MetalContext,data_type: DataType,- ) -> Result<Self, MTLError> {+ ) -> Result<Self, MetalError> {let mut kernel = MatmulKernel::new(data_type)?;kernel.precompile(context)?;Ok(kernel)@@ -35,7 +37,7 @@ impl FullPrecisionMatmulKernelTrait for MatmulKernel {fn encode(&mut self,- context: &MTLContext,+ context: &MetalContext,encoder: &ProtocolObject<dyn MTLComputeCommandEncoder>,arguments: FullPrecisionMatmulArguments<Metal>,) {diff --git a/crates/uzu/src/backends/metal/kernel/matmul/split_k/dispatch_descriptor.rs b/crates/uzu/src/backends/metal/kernel/matmul/split_k/dispatch_descriptor.rsindex cb32b7800..2490dcfe9 100644--- a/crates/uzu/src/backends/metal/kernel/matmul/split_k/dispatch_descriptor.rs+++ b/crates/uzu/src/backends/metal/kernel/matmul/split_k/dispatch_descriptor.rs@@ -1,8 +1,10 @@+use metal::MTLSize;+use super::{pipeline_configuration::PipelineConfiguration, tile_configuration::select_tile_configuration};use crate::{DataType,backends::metal::{- MTLContext, MTLError, MTLSize,+ MetalContext, MetalError,kernel::matmul::common::{GEMMSpiltKParams as SplitKGEMMParams, MatmulArguments},},};@@ -22,12 +24,12 @@ pub(crate) struct DispatchDescriptor {impl DispatchDescriptor {pub(crate) fn try_new(- _context: &MTLContext,+ _context: &MetalContext,data_type: DataType,arguments: &MatmulArguments,- ) -> Result<Option<Self>, MTLError> {+ ) -> Result<Option<Self>, MetalError> {if !matches!(data_type, DataType::F16 | DataType::BF16 | DataType::F32) {- return Err(MTLError::Generic(format!("Unsupported dtype for Split-K: {:?}", data_type)));+ return Err(MetalError::Generic(format!("Unsupported dtype for Split-K: {:?}", data_type)));}if arguments.c.is_some() {diff --git a/crates/uzu/src/backends/metal/kernel/matmul/split_k/kernel.rs b/crates/uzu/src/backends/metal/kernel/matmul/split_k/kernel.rsindex ec5bed92e..824c031d7 100644--- a/crates/uzu/src/backends/metal/kernel/matmul/split_k/kernel.rs+++ b/crates/uzu/src/backends/metal/kernel/matmul/split_k/kernel.rs@@ -1,13 +1,15 @@use std::collections::HashMap;+use metal::{MTLBuffer, MTLComputeCommandEncoder, MTLComputePipelineState};+use objc2::{rc::Retained, runtime::ProtocolObject};+use super::{DispatchDescriptor, pipeline_configuration::PipelineConfiguration};use crate::{DataType,backends::{common::Context,metal::{- ComputeEncoderSetValue, MTLBuffer, MTLComputeCommandEncoder, MTLComputePipelineState, MTLContext, MTLError,- ProtocolObject, Retained,+ ComputeEncoderSetValue, MetalContext, MetalError,kernel::matmul::common::{MatmulArguments, transpose_configuration},},},@@ -22,9 +24,9 @@ pub struct Kernel {}impl Kernel {- pub fn new(data_type: DataType) -> Result<Self, MTLError> {+ pub fn new(data_type: DataType) -> Result<Self, MetalError> {if !matches!(data_type, DataType::F16 | DataType::BF16 | DataType::F32) {- return Err(MTLError::Generic(format!("Unsupported dtype for Split-K: {:?}", data_type)));+ return Err(MetalError::Generic(format!("Unsupported dtype for Split-K: {:?}", data_type)));}Ok(Self {data_type,@@ -37,8 +39,8 @@ impl Kernel {pub fn precompile(&mut self,- context: &MTLContext,- ) -> Result<(), MTLError> {+ context: &MetalContext,+ ) -> Result<(), MetalError> {use super::tile_configuration::TileConfiguration;if !matches!(self.data_type, DataType::BF16) {@@ -94,12 +96,12 @@ impl Kernel {Ok(())}- fn steel_type_name(&self) -> Result<&'static str, MTLError> {+ fn steel_type_name(&self) -> Result<&'static str, MetalError> {match self.data_type {DataType::F16 => Ok("float16"),DataType::BF16 => Ok("bfloat16"),DataType::F32 => Ok("float32"),- _ => Err(MTLError::Generic(format!("Unsupported dtype for Split-K: {:?}", self.data_type))),+ _ => Err(MetalError::Generic(format!("Unsupported dtype for Split-K: {:?}", self.data_type))),}}@@ -110,7 +112,7 @@ impl Kernel {fn partial_kernel_name(&self,config: &PipelineConfiguration,- ) -> Result<String, MTLError> {+ ) -> Result<String, MetalError> {let in_name = self.steel_type_name()?;let out_name = self.splitk_partial_out_name();let transpose_suffix = transpose_configuration(config.transpose_a, config.transpose_b).as_str();@@ -139,16 +141,16 @@ impl Kernel {))}- fn accum_kernel_name(&self) -> Result<String, MTLError> {+ fn accum_kernel_name(&self) -> Result<String, MetalError> {let out_name = self.steel_type_name()?;Ok(format!("steel_gemm_splitk_accum_{}_{}", out_name, self.splitk_partial_out_name()))}fn get_partial_pipeline(&mut self,- mtl: &MTLContext,+ mtl: &MetalContext,config: &PipelineConfiguration,- ) -> Result<&Retained<ProtocolObject<dyn MTLComputePipelineState>>, MTLError> {+ ) -> Result<&Retained<ProtocolObject<dyn MTLComputePipelineState>>, MetalError> {if !self.partial_pipelines.contains_key(config) {let name = self.partial_kernel_name(config)?;let ps = mtl.compute_pipeline_state(&name, None)?;@@ -159,8 +161,8 @@ impl Kernel {fn get_accum_pipeline(&mut self,- mtl: &MTLContext,- ) -> Result<&Retained<ProtocolObject<dyn MTLComputePipelineState>>, MTLError> {+ mtl: &MetalContext,+ ) -> Result<&Retained<ProtocolObject<dyn MTLComputePipelineState>>, MetalError> {if self.accum_pipeline.is_none() {let name = self.accum_kernel_name()?;let ps = mtl.compute_pipeline_state(&name, None)?;@@ -189,11 +191,11 @@ impl Kernel {pub(crate) fn encode_descriptor(&mut self,- context: &MTLContext,+ context: &MetalContext,encoder: &ProtocolObject<dyn MTLComputeCommandEncoder>,arguments: &MatmulArguments,descriptor: &DispatchDescriptor,- ) -> Result<bool, MTLError> {+ ) -> Result<bool, MetalError> {self.ensure_accumulator_buffer(context, descriptor.accumulator_bytes);let accumulator_buffer =self.accumulator_buffer.as_ref().cloned().expect("Accumulator buffer must be initialized");@@ -225,7 +227,7 @@ impl Kernel {fn ensure_accumulator_buffer(&mut self,- mtl: &MTLContext,+ mtl: &MetalContext,required_bytes: usize,) {if required_bytes <= self.accumulator_buffer_bytes && self.accumulator_buffer.is_some() {diff --git a/crates/uzu/src/backends/metal/kernel/mlp/mod.rs b/crates/uzu/src/backends/metal/kernel/mlp/mod.rsindex 140af4bdb..550d5cca3 100644--- a/crates/uzu/src/backends/metal/kernel/mlp/mod.rs+++ b/crates/uzu/src/backends/metal/kernel/mlp/mod.rs@@ -1,11 +1,11 @@+use metal::{MTLBuffer, MTLComputeCommandEncoder, MTLFunctionConstantValues};+use objc2::{rc::Retained, runtime::ProtocolObject};+use crate::{DataType,backends::{common::kernel::MlpGateActMulKernel,- metal::{- FunctionConstantValuesSetValue, MTLBuffer, MTLComputeCommandEncoder, MTLContext, MTLError,- MTLFunctionConstantValues, ProtocolObject, Retained, kernel::dsl::MlpGateActMulMetalKernel,- },+ metal::{FunctionConstantValuesSetValue, MetalContext, MetalError, kernel::dsl::MlpGateActMulMetalKernel},},config::Activation,};@@ -81,11 +81,11 @@ pub struct MlpGateActMulEncodable {impl MlpGateActMulEncodable {pub fn new(- context: &MTLContext,+ context: &MetalContext,data_type: DataType,activation: Activation,hidden_dim: usize,- ) -> Result<Self, MTLError> {+ ) -> Result<Self, MetalError> {let kernel = MlpGateActMulMetalKernel::new(context, data_type.into())?;Ok(Self {kernel,@@ -100,7 +100,7 @@ impl MlpGateActMulEncodable {fused_up: &Retained<ProtocolObject<dyn MTLBuffer>>,hidden: &Retained<ProtocolObject<dyn MTLBuffer>>,m: i32,- ) -> Result<(), MTLError> {+ ) -> Result<(), MetalError> {let act_type = match self.activation {Activation::SiLU {..diff --git a/crates/uzu/src/backends/metal/kernel/moe/experts.rs b/crates/uzu/src/backends/metal/kernel/moe/experts.rsindex fc5d21e19..19b669744 100644--- a/crates/uzu/src/backends/metal/kernel/moe/experts.rs+++ b/crates/uzu/src/backends/metal/kernel/moe/experts.rs@@ -1,12 +1,16 @@use std::{mem::size_of, ptr::NonNull};+use metal::{+ MTLBlitCommandEncoderExt, MTLBuffer, MTLCommandBuffer, MTLCommandEncoder, MTLComputeCommandEncoder,+ MTLComputePipelineState, MTLFunctionConstantValues, MTLSize,+};+use objc2::{rc::Retained, runtime::ProtocolObject};+use super::{dtype_index, dtype_suffix};use crate::{DataType,backends::metal::{- FunctionConstantValuesSetValue, MTLBlitCommandEncoderExt, MTLBuffer, MTLCommandBuffer, MTLCommandEncoder,- MTLComputeCommandEncoder, MTLComputePipelineState, MTLContext, MTLError, MTLFunctionConstantValues, MTLSize,- ProtocolObject, Retained,+ FunctionConstantValuesSetValue, MetalContext, MetalError,kernel::moe::tiles_map::{MoeTileCountsArguments, MoeTileDispatchArguments, MoeTileMapBuildArguments, MoeTileMapKernels,MoeTileScanArguments,@@ -17,12 +21,12 @@ use crate::{#[derive(Debug, thiserror::Error)]pub enum MoeScatterError {#[error("Metal error: {0}")]- MetalError(#[from] MTLError),+ MetalError(#[from] MetalError),}#[derive(Debug, thiserror::Error)]pub enum MoeExpertsError {#[error("Metal error: {0}")]- MetalError(#[from] MTLError),+ MetalError(#[from] MetalError),#[error("{0}")]Generic(String),}@@ -93,7 +97,7 @@ pub struct MoeExpertsTwoPassArguments<'a> {}impl MoeExpertsTwoPassPrefillKernel {- pub fn new(ctx: &MTLContext) -> Result<Self, MoeExpertsError> {+ pub fn new(ctx: &MetalContext) -> Result<Self, MoeExpertsError> {let dtypes = [DataType::F16, DataType::BF16, DataType::F32];let mut pass_a_indirect = vec![Vec::with_capacity(dtypes.len()); 4];for gate in 0u32..4u32 {diff --git a/crates/uzu/src/backends/metal/kernel/moe/experts_single.rs b/crates/uzu/src/backends/metal/kernel/moe/experts_single.rsindex 586833efd..9f1797b36 100644--- a/crates/uzu/src/backends/metal/kernel/moe/experts_single.rs+++ b/crates/uzu/src/backends/metal/kernel/moe/experts_single.rs@@ -6,7 +6,7 @@ use crate::{backends::{common::kernel::{MoeExpertsDecodeSinglePassAKernel as _, MoeExpertsDecodeSinglePassBKernel as _},metal::{- MTLContext, MTLError,+ MetalContext, MetalError,kernel::dsl::{MoeExpertsDecodeSinglePassAMetalKernel, MoeExpertsDecodeSinglePassBMetalKernel},},},@@ -63,7 +63,7 @@ pub struct MoeExpertsSingleDecodeKernels {}impl MoeExpertsSingleDecodeKernels {- pub fn new(ctx: &MTLContext) -> Result<Self, MTLError> {+ pub fn new(ctx: &MetalContext) -> Result<Self, MetalError> {let mut pass_a = vec![];for gate in 0..4 {let mut kernels = vec![];diff --git a/crates/uzu/src/backends/metal/kernel/moe/experts_two_pass_decode.rs b/crates/uzu/src/backends/metal/kernel/moe/experts_two_pass_decode.rsindex 61d7b79df..4f1c3725e 100644--- a/crates/uzu/src/backends/metal/kernel/moe/experts_two_pass_decode.rs+++ b/crates/uzu/src/backends/metal/kernel/moe/experts_two_pass_decode.rs@@ -9,7 +9,7 @@ use crate::{backends::{common::kernel::{MoeExpertsDecodeDownFused2DKernel, MoeExpertsDecodePassAKernel},metal::{- MTLContext, MTLError,+ MetalContext, MetalError,kernel::{MoeExpertsTwoPassArguments,dsl::{MoeExpertsDecodeDownFused2DMetalKernel, MoeExpertsDecodePassAMetalKernel},@@ -31,7 +31,7 @@ pub struct MoeExpertsTwoPassDecodeKernels {}impl MoeExpertsTwoPassDecodeKernels {- pub fn new(ctx: &MTLContext) -> Result<Self, MTLError> {+ pub fn new(ctx: &MetalContext) -> Result<Self, MetalError> {let mut pass_a_indirect = vec![];for gate in 0u32..4u32 {let mut kernels = vec![];diff --git a/crates/uzu/src/backends/metal/kernel/moe/gather.rs b/crates/uzu/src/backends/metal/kernel/moe/gather.rsindex eebffe8d9..3229d21be 100644--- a/crates/uzu/src/backends/metal/kernel/moe/gather.rs+++ b/crates/uzu/src/backends/metal/kernel/moe/gather.rs@@ -1,11 +1,12 @@-use objc2::Message;+use metal::{MTLBuffer, MTLCommandBuffer, MTLCommandEncoder};+use objc2::{Message, rc::Retained, runtime::ProtocolObject};use crate::{DataType,backends::{common::kernel::{MoeGatherXPerm1DKernel, MoeGatherXPerm2DKernel},metal::{- MTLBuffer, MTLCommandBuffer, MTLCommandEncoder, MTLContext, MTLError, ProtocolObject, Retained,+ MetalContext, MetalError,kernel::dsl::{MoeGatherXPerm1DMetalKernel, MoeGatherXPerm2DMetalKernel},},},@@ -29,7 +30,7 @@ pub struct MoeGatherKernels {}impl MoeGatherKernels {- pub fn new(ctx: &MTLContext) -> Result<Self, MTLError> {+ pub fn new(ctx: &MetalContext) -> Result<Self, MetalError> {Ok(Self {bf16: MoeGatherXPerm2DMetalKernel::new(ctx, DataType::BF16)?,f16: MoeGatherXPerm1DMetalKernel::new(ctx, DataType::F16)?,diff --git a/crates/uzu/src/backends/metal/kernel/moe/router_topk.rs b/crates/uzu/src/backends/metal/kernel/moe/router_topk.rsindex adfa009aa..52120b433 100644--- a/crates/uzu/src/backends/metal/kernel/moe/router_topk.rs+++ b/crates/uzu/src/backends/metal/kernel/moe/router_topk.rs@@ -1,9 +1,11 @@+use metal::{+ MTLBuffer, MTLCommandBuffer, MTLCommandEncoder, MTLComputeCommandEncoder, MTLComputePipelineState, MTLSize,+};+use objc2::{rc::Retained, runtime::ProtocolObject};+use crate::{DataType,- backends::metal::{- MTLBuffer, MTLCommandBuffer, MTLCommandEncoder, MTLComputeCommandEncoder, MTLComputePipelineState, MTLContext,- MTLError, MTLSize, ProtocolObject, Retained, metal_extensions::ComputeEncoderSetValue,- },+ backends::metal::{MetalContext, MetalError, metal_extensions::ComputeEncoderSetValue},};const THREADS_PER_THREADGROUP: usize = 256;@@ -13,7 +15,7 @@ const MAX_TOPK: usize = 128;#[derive(Debug, thiserror::Error)]pub enum MoeRouterTopKError {#[error("Metal error: {0}")]- MetalError(#[from] MTLError),+ MetalError(#[from] MetalError),#[error("Invalid configuration: T={t}, d_model={d_model}, E={e}, K={k}")]InvalidConfig {t: usize,@@ -44,7 +46,7 @@ pub struct MoeRouterTopKArguments<'a> {}impl MoeRouterTopKKernel {- pub fn new(mtl_context: &MTLContext) -> Result<Self, MoeRouterTopKError> {+ pub fn new(mtl_context: &MetalContext) -> Result<Self, MoeRouterTopKError> {let pipeline_f16 = mtl_context.compute_pipeline_state("moe_router_topk_f16", None)?;let pipeline_f32 = mtl_context.compute_pipeline_state("moe_router_topk_f32", None)?;let pipeline_bf16 = mtl_context.compute_pipeline_state("moe_router_topk_bf16", None)?;diff --git a/crates/uzu/src/backends/metal/kernel/moe/scatter.rs b/crates/uzu/src/backends/metal/kernel/moe/scatter.rsindex 9de76dcf6..1159b0654 100644--- a/crates/uzu/src/backends/metal/kernel/moe/scatter.rs+++ b/crates/uzu/src/backends/metal/kernel/moe/scatter.rs@@ -1,9 +1,11 @@+use metal::{+ MTLBuffer, MTLCommandBuffer, MTLCommandEncoder, MTLComputeCommandEncoder, MTLComputePipelineState, MTLSize,+};+use objc2::{rc::Retained, runtime::ProtocolObject};+use crate::{DataType,- backends::metal::{- MTLBuffer, MTLCommandBuffer, MTLCommandEncoder, MTLComputeCommandEncoder, MTLComputePipelineState, MTLContext,- MTLSize, ProtocolObject, Retained, metal_extensions::ComputeEncoderSetValue,- },+ backends::metal::{MetalContext, metal_extensions::ComputeEncoderSetValue},};// ---- Scatter Buckets Kernels ----@@ -11,7 +13,7 @@ use crate::{#[derive(Debug, thiserror::Error)]pub enum MoeScatterError {#[error("Metal error: {0}")]- MetalError(#[from] crate::backends::metal::MTLError),+ MetalError(#[from] crate::backends::metal::MetalError),}pub struct MoeScatterKernels {@@ -58,7 +60,7 @@ pub struct MoeScatterWithMapArguments<'a> {}impl MoeScatterKernels {- pub fn new(mtl_context: &MTLContext) -> Result<Self, MoeScatterError> {+ pub fn new(mtl_context: &MetalContext) -> Result<Self, MoeScatterError> {let pipeline_bases = mtl_context.compute_pipeline_state("moe_block_bases_from_partials", None)?;let pipeline_scatter_f16 = mtl_context.compute_pipeline_state("moe_scatter_buckets_f16", None)?;let pipeline_scatter_f32 = mtl_context.compute_pipeline_state("moe_scatter_buckets_f32", None)?;diff --git a/crates/uzu/src/backends/metal/kernel/moe/tiles_map.rs b/crates/uzu/src/backends/metal/kernel/moe/tiles_map.rsindex cf9b592cc..1f9ef7de5 100644--- a/crates/uzu/src/backends/metal/kernel/moe/tiles_map.rs+++ b/crates/uzu/src/backends/metal/kernel/moe/tiles_map.rs@@ -7,7 +7,7 @@ use objc2::{use crate::backends::{common::kernel::{MoeBuildTileMapKernel, MoeTileCountsKernel, MoeTileScanKernel, MoeWriteDispatchArgsKernel},metal::{- MTLContext, MTLError,+ MetalContext, MetalError,kernel::dsl::{MoeBuildTileMapMetalKernel, MoeTileCountsMetalKernel, MoeTileScanMetalKernel,MoeWriteDispatchArgsMetalKernel,@@ -23,7 +23,7 @@ pub struct MoeTileMapKernels {}impl MoeTileMapKernels {- pub fn new(ctx: &MTLContext) -> Result<Self, MTLError> {+ pub fn new(ctx: &MetalContext) -> Result<Self, MetalError> {Ok(Self {counts: MoeTileCountsMetalKernel::new(ctx)?,scan: MoeTileScanMetalKernel::new(ctx)?,diff --git a/crates/uzu/src/backends/metal/kernel/moe/tiles_pass_a.rs b/crates/uzu/src/backends/metal/kernel/moe/tiles_pass_a.rsindex f9c6dd44a..c2deccd86 100644--- a/crates/uzu/src/backends/metal/kernel/moe/tiles_pass_a.rs+++ b/crates/uzu/src/backends/metal/kernel/moe/tiles_pass_a.rs@@ -1,4 +1,5 @@-use objc2::Message;+use metal::{MTLBuffer, MTLCommandBuffer, MTLCommandEncoder};+use objc2::{Message, runtime::ProtocolObject};use crate::backends::{common::kernel::{@@ -6,7 +7,7 @@ use crate::backends::{MoePassAWriteDispatchArgsKernel,},metal::{- MTLBuffer, MTLCommandBuffer, MTLCommandEncoder, MTLContext, MTLError, ProtocolObject,+ MetalContext, MetalError,kernel::dsl::{MoePassABuildRowMapMetalKernel, MoePassABuildTileMapMetalKernel, MoePassATileCountsMetalKernel,MoePassATileScanMetalKernel, MoePassAWriteDispatchArgsMetalKernel,@@ -64,7 +65,7 @@ pub struct MoePassATileKernels {}impl MoePassATileKernels {- pub fn new(ctx: &MTLContext) -> Result<Self, MTLError> {+ pub fn new(ctx: &MetalContext) -> Result<Self, MetalError> {Ok(Self {counts: MoePassATileCountsMetalKernel::new(ctx)?,scan: MoePassATileScanMetalKernel::new(ctx)?,diff --git a/crates/uzu/src/backends/metal/kernel/quant_matmul/mod.rs b/crates/uzu/src/backends/metal/kernel/quant_matmul/mod.rsindex ace98f02d..876dc6407 100644--- a/crates/uzu/src/backends/metal/kernel/quant_matmul/mod.rs+++ b/crates/uzu/src/backends/metal/kernel/quant_matmul/mod.rs@@ -1,5 +1,8 @@use std::collections::HashMap;+use metal::{MTLBuffer, MTLComputeCommandEncoder, MTLComputePipelineState, MTLFunctionConstantValues, MTLSize};+use objc2::{rc::Retained, runtime::ProtocolObject};+use crate::{DataType,backends::{@@ -8,9 +11,7 @@ use crate::{QuantizedMatmulKernel as QuantizedMatmulKernelTrait, QuantizedMatmulType,},metal::{- FunctionConstantValuesSetValue, MTLBuffer, MTLComputeCommandEncoder, MTLComputePipelineState, MTLContext,- MTLError, MTLFunctionConstantValues, MTLSize, Metal, ProtocolObject, Retained,- metal_extensions::ComputeEncoderSetValue,+ FunctionConstantValuesSetValue, Metal, MetalContext, MetalError, metal_extensions::ComputeEncoderSetValue,},},config::QuantizationMode,@@ -27,7 +28,7 @@ pub enum QuantizationType {#[derive(Debug, thiserror::Error)]pub enum QuantizedMatmulError {#[error("Metal error: {0}")]- MetalError(#[from] MTLError),+ MetalError(#[from] MetalError),#[error("Unsupported data type: {0:?}")]UnsupportedDataType(DataType),#[error("Unsupported group size: {0}")]@@ -101,7 +102,7 @@ fn base_qmm_kernel_name(impl QuantizedMatmulKernel {pub fn new(- mtl_context: &MTLContext,+ mtl_context: &MetalContext,data_type: DataType,group_size: usize,input_dim: usize,@@ -239,9 +240,9 @@ impl QuantizedMatmulKernelTrait for QuantizedMatmulKernel {type Backend = Metal;fn new(- context: &MTLContext,+ context: &MetalContext,configuration: QuantizedMatmulConfiguration,- ) -> Result<Self, MTLError> {+ ) -> Result<Self, MetalError> {let quantization_type = match configuration.quantization_type {QuantizedMatmulType::ZeroPoint => QuantizationType::ZeroPoint,QuantizedMatmulType::Mlx => QuantizationType::Mlx,@@ -257,7 +258,7 @@ impl QuantizedMatmulKernelTrait for QuantizedMatmulKernel {quantization_type,configuration.weights_transposed,)- .map_err(|error| MTLError::Generic(format!("{:?}", error)))+ .map_err(|error| MetalError::Generic(format!("{:?}", error)))}fn encode(@@ -381,7 +382,7 @@ pub struct MlpFusedQmvKernel {impl MlpFusedQmvKernel {pub fn new(- context: &MTLContext,+ context: &MetalContext,data_type: DataType,group_size: usize,mode: QuantizationMode,@@ -471,7 +472,7 @@ pub struct MlpFusedQmmKernel {impl MlpFusedQmmKernel {pub fn new(- context: &MTLContext,+ context: &MetalContext,data_type: DataType,group_size: usize,mode: QuantizationMode,diff --git a/crates/uzu/src/backends/metal/kernel/ssm/ssd_prefill.rs b/crates/uzu/src/backends/metal/kernel/ssm/ssd_prefill.rsindex ae7993b92..d5a19dd69 100644--- a/crates/uzu/src/backends/metal/kernel/ssm/ssd_prefill.rs+++ b/crates/uzu/src/backends/metal/kernel/ssm/ssd_prefill.rs@@ -1,11 +1,12 @@-use objc2::Message;+use metal::{MTLBuffer, MTLComputeCommandEncoder};+use objc2::{Message, runtime::ProtocolObject};use crate::{DataType,backends::{common::kernel::{SSDPrefill64Kernel as _, SSDPrefillKernel as _, SSDPrefillSequentialKernel as _},metal::{- MTLBuffer, MTLComputeCommandEncoder, MTLContext, MTLError, ProtocolObject,+ MetalContext, MetalError,kernel::dsl::{SSDPrefill64MetalKernel, SSDPrefillMetalKernel, SSDPrefillSequentialMetalKernel},},},@@ -45,9 +46,9 @@ pub struct SSDPrefillKernels {impl SSDPrefillKernels {pub fn new(- context: &MTLContext,+ context: &MetalContext,data_type: DataType,- ) -> Result<Self, MTLError> {+ ) -> Result<Self, MetalError> {let single = SSDPrefillMetalKernel::new(context, data_type)?;let single_64 = SSDPrefill64MetalKernel::new(context, data_type)?;let sequential = SSDPrefillSequentialMetalKernel::new(context, data_type)?;diff --git a/crates/uzu/src/backends/metal/language_model_generator_context.rs b/crates/uzu/src/backends/metal/language_model_generator_context.rsindex 45644d881..755f071eb 100644--- a/crates/uzu/src/backends/metal/language_model_generator_context.rs+++ b/crates/uzu/src/backends/metal/language_model_generator_context.rs@@ -6,18 +6,20 @@ use std::{rc::Rc,};-use super::{Decoder, KVCacheUpdate, MTLContext, Metal};+use metal::{MTLBuffer, MTLCommandBuffer, MTLDeviceExt, MTLEvent};+use objc2::{rc::Retained, runtime::ProtocolObject};++use super::{Decoder, Metal, MetalContext};use crate::{DataType,backends::{common::{Context,- kernel::{MaskUpdateKernel, TokenCopySampledKernel, TokenCopyToResultsKernel},- },- metal::{- MTLBuffer, MTLCommandBuffer, MTLDeviceExt, MTLEvent, ProtocolObject, Retained,- kernel::dsl::{MaskUpdateMetalKernel, TokenCopySampledMetalKernel, TokenCopyToResultsMetalKernel},+ kernel::{+ MaskUpdateKernel, TokenCopySampledKernel, TokenCopyToResultsKernel, kv_cache_update::KVCacheUpdate,+ },},+ metal::kernel::dsl::{MaskUpdateMetalKernel, TokenCopySampledMetalKernel, TokenCopyToResultsMetalKernel},},config::{DecoderConfig, LanguageModelConfig, ModelMetadata},encodable_block::Sampling,@@ -57,7 +59,7 @@ pub struct AsyncBuffers {impl AsyncBuffers {pub fn new(- context: &MTLContext,+ context: &MetalContext,max_tokens: usize,batch_size: usize,) -> Self {@@ -128,7 +130,7 @@ impl AsyncBuffers {}pub struct LanguageModelGeneratorContext {- pub mtl_context: Rc<MTLContext>,+ pub mtl_context: Rc<MetalContext>,pub command_buffer: Retained<ProtocolObject<dyn MTLCommandBuffer>>,pub cache_layers: Rc<RefCell<CacheLayers<Metal>>>,@@ -157,7 +159,7 @@ impl LanguageModelGeneratorContext {model_path: &Path,decoding_config: &DecodingConfig,) -> Result<Self, Error> {- let context = MTLContext::new().map_err(|_| Error::UnableToCreateMetalContext)?;+ let context = MetalContext::new().map_err(|_| Error::UnableToCreateMetalContext)?;let command_buffer = context.create_command_buffer().expect("Failed to create command buffer").to_owned();diff --git a/crates/uzu/src/backends/metal/metal_extensions/command_buffer_timing.rs b/crates/uzu/src/backends/metal/metal_extensions/command_buffer_timing.rsindex 623408739..32c96313e 100644--- a/crates/uzu/src/backends/metal/metal_extensions/command_buffer_timing.rs+++ b/crates/uzu/src/backends/metal/metal_extensions/command_buffer_timing.rs@@ -1,4 +1,5 @@-use crate::backends::metal::{MTLCommandBuffer, MTLCommandBufferExt, ProtocolObject};+use metal::{MTLCommandBuffer, MTLCommandBufferExt};+use objc2::runtime::ProtocolObject;/// Extension trait providing convenience timing methods for command buffers.pub trait CommandBufferTimingExt {diff --git a/crates/uzu/src/backends/metal/metal_extensions/compute_command_encoder_extensions_conditional.rs b/crates/uzu/src/backends/metal/metal_extensions/compute_command_encoder_extensions_conditional.rsindex c60bb24bd..b231b3219 100644--- a/crates/uzu/src/backends/metal/metal_extensions/compute_command_encoder_extensions_conditional.rs+++ b/crates/uzu/src/backends/metal/metal_extensions/compute_command_encoder_extensions_conditional.rs@@ -1,6 +1,5 @@-use objc2::msg_send;--use crate::backends::metal::{MTLBuffer, MTLCompareFunction, MTLComputeCommandEncoder, ProtocolObject, Retained};+use metal::{MTLBuffer, MTLCompareFunction, MTLComputeCommandEncoder};+use objc2::{msg_send, rc::Retained, runtime::ProtocolObject};/// Low-level, unsafe conditional control of Metal encoders./// This is internal; users should prefer the safe `ComputeEncoderConditional::condition`.diff --git a/crates/uzu/src/backends/metal/metal_extensions/compute_command_encoder_extensions_dispatch.rs b/crates/uzu/src/backends/metal/metal_extensions/compute_command_encoder_extensions_dispatch.rsindex ce11d74b8..51d5c75c8 100644--- a/crates/uzu/src/backends/metal/metal_extensions/compute_command_encoder_extensions_dispatch.rs+++ b/crates/uzu/src/backends/metal/metal_extensions/compute_command_encoder_extensions_dispatch.rs@@ -1,10 +1,10 @@+use metal::{MTLCommandEncoderExt, MTLComputeCommandEncoder, MTLComputePipelineState, MTLSize};+use objc2::runtime::ProtocolObject;+use super::{compute_pipeline_state_extensions_threads::ComputePipelineStateThreads,device_extensions_features::{DeviceFeatures, Feature},};-use crate::backends::metal::{- MTLCommandEncoderExt, MTLComputeCommandEncoder, MTLComputePipelineState, MTLSize, ProtocolObject,-};/// Extensions for MTLComputeCommandEncoder to simplify dispatch operationspub trait ComputeEncoderDispatch {diff --git a/crates/uzu/src/backends/metal/metal_extensions/compute_command_encoder_extensions_set_value.rs b/crates/uzu/src/backends/metal/metal_extensions/compute_command_encoder_extensions_set_value.rsindex 6010fbf9a..92266224c 100644--- a/crates/uzu/src/backends/metal/metal_extensions/compute_command_encoder_extensions_set_value.rs+++ b/crates/uzu/src/backends/metal/metal_extensions/compute_command_encoder_extensions_set_value.rs@@ -1,6 +1,7 @@use std::{ffi::c_void, mem::size_of, ptr::NonNull};-use crate::backends::metal::{MTLComputeCommandEncoder, ProtocolObject};+use metal::MTLComputeCommandEncoder;+use objc2::runtime::ProtocolObject;/// Extension trait providing ergonomic `set_value` methods for compute command encoders.pub trait ComputeEncoderSetValue {diff --git a/crates/uzu/src/backends/metal/metal_extensions/compute_pipeline_state_extensions_threads.rs b/crates/uzu/src/backends/metal/metal_extensions/compute_pipeline_state_extensions_threads.rsindex 8ab5944f7..07da56b03 100644--- a/crates/uzu/src/backends/metal/metal_extensions/compute_pipeline_state_extensions_threads.rs+++ b/crates/uzu/src/backends/metal/metal_extensions/compute_pipeline_state_extensions_threads.rs@@ -1,4 +1,5 @@-use crate::backends::metal::{MTLComputePipelineState, MTLSize, ProtocolObject};+use metal::{MTLComputePipelineState, MTLSize};+use objc2::runtime::ProtocolObject;/// Extensions for ComputePipelineState to provide optimized threadgroup sizespub trait ComputePipelineStateThreads {diff --git a/crates/uzu/src/backends/metal/metal_extensions/device_extensions_features.rs b/crates/uzu/src/backends/metal/metal_extensions/device_extensions_features.rsindex c732839a9..ac253d378 100644--- a/crates/uzu/src/backends/metal/metal_extensions/device_extensions_features.rs+++ b/crates/uzu/src/backends/metal/metal_extensions/device_extensions_features.rs@@ -1,8 +1,7 @@use std::collections::HashSet;-use crate::backends::metal::{- MTLDevice, MTLDeviceExt, MTLFeatureSet, MTLGPUFamily, MTLPixelFormat, MTLReadWriteTextureTier, ProtocolObject,-};+use metal::{MTLDevice, MTLDeviceExt, MTLFeatureSet, MTLGPUFamily, MTLPixelFormat, MTLReadWriteTextureTier};+use objc2::runtime::ProtocolObject;/// Enum representing various Metal features that may or may not be supported by a device.#[derive(Debug, Clone, PartialEq, Eq)]diff --git a/crates/uzu/src/backends/metal/metal_extensions/function_constant_values_extensions_set_value.rs b/crates/uzu/src/backends/metal/metal_extensions/function_constant_values_extensions_set_value.rsindex 74e621376..d4a6a0217 100644--- a/crates/uzu/src/backends/metal/metal_extensions/function_constant_values_extensions_set_value.rs+++ b/crates/uzu/src/backends/metal/metal_extensions/function_constant_values_extensions_set_value.rs@@ -1,6 +1,6 @@use std::ptr::NonNull;-use crate::backends::metal::{MTLDataType, MTLFunctionConstantValues};+use metal::{MTLDataType, MTLFunctionConstantValues};pub trait FunctionConstantValueType {const DATA_TYPE: MTLDataType;diff --git a/crates/uzu/src/backends/metal/metal_extensions/library_extensions_pipeline.rs b/crates/uzu/src/backends/metal/metal_extensions/library_extensions_pipeline.rsindex 85f44b788..2e974057f 100644--- a/crates/uzu/src/backends/metal/metal_extensions/library_extensions_pipeline.rs+++ b/crates/uzu/src/backends/metal/metal_extensions/library_extensions_pipeline.rs@@ -1,9 +1,7 @@+use metal::{MTLComputePipelineState, MTLDeviceExt, MTLFunctionConstantValues, MTLLibrary, MTLLibraryExt};use objc2::{rc::Retained, runtime::ProtocolObject};-use crate::backends::metal::{- MTLComputePipelineState, MTLDeviceExt, MTLFunctionConstantValues, MTLLibrary, MTLLibraryExt,- error::{LibraryError, MTLError},-};+use crate::backends::metal::error::{LibraryError, MetalError};/// Extensions for Library to create compute pipeline statespub trait LibraryPipelineExtensions {@@ -13,7 +11,7 @@ pub trait LibraryPipelineExtensions {&self,function_name: &str,constants: Option<&MTLFunctionConstantValues>,- ) -> Result<Retained<ProtocolObject<dyn MTLComputePipelineState>>, MTLError>;+ ) -> Result<Retained<ProtocolObject<dyn MTLComputePipelineState>>, MetalError>;}impl LibraryPipelineExtensions for ProtocolObject<dyn MTLLibrary> {@@ -21,19 +19,19 @@ impl LibraryPipelineExtensions for ProtocolObject<dyn MTLLibrary> {&self,function_name: &str,constants: Option<&MTLFunctionConstantValues>,- ) -> Result<Retained<ProtocolObject<dyn MTLComputePipelineState>>, MTLError> {+ ) -> 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(MTLError::Library(LibraryError::FunctionCreationFailed))?;+ .ok_or(MetalError::Library(LibraryError::FunctionCreationFailed))?;let device = self.device();device.new_compute_pipeline_state_with_function(&function)- .map_err(|e| MTLError::Library(LibraryError::Custom(format!("Pipeline state creation failed: {}", e))))+ .map_err(|e| MetalError::Library(LibraryError::Custom(format!("Pipeline state creation failed: {}", e))))}}diff --git a/crates/uzu/src/backends/metal/mod.rs b/crates/uzu/src/backends/metal/mod.rsindex a7acdf0d2..0e2d2e9af 100644--- a/crates/uzu/src/backends/metal/mod.rs+++ b/crates/uzu/src/backends/metal/mod.rs@@ -11,15 +11,13 @@ pub mod error;pub mod kernel;mod language_model_generator_context;pub mod metal_extensions;+pub use array::MetalArray;pub use backend::Metal;pub use classifier_context::ClassifierContext;-pub use context::{DeviceArchitecture, DeviceClass, DeviceGeneration, MTLContext};+pub use context::{DeviceArchitecture, DeviceClass, DeviceGeneration, MetalContext};pub use encodable_block::Decoder;-pub use error::MTLError;+pub use error::MetalError;pub use kernel::dsl::MetalKernels;pub use language_model_generator_context::LanguageModelGeneratorContext;-pub use metal::prelude::*;pub use metal_extensions::{ComputeEncoderSetValue, FunctionConstantValuesSetValue};--pub use crate::backends::common::kernel::kv_cache_update::KVCacheUpdate;diff --git a/crates/uzu/src/classifier/classifier.rs b/crates/uzu/src/classifier/classifier.rsindex 803a343ed..5542ac7e7 100644--- a/crates/uzu/src/classifier/classifier.rs+++ b/crates/uzu/src/classifier/classifier.rs@@ -2,6 +2,7 @@use std::{cell::RefCell, rc::Rc};use std::{collections::HashMap, path::Path, time::Instant};+use metal::MTLCommandBuffer;use objc2::rc::autoreleasepool;#[cfg(feature = "tracing")]@@ -9,7 +10,7 @@ use super::ActivationTrace;use super::{ClassificationOutput, ClassificationStats, ClassifierContext};use crate::{DataType,- backends::metal::{MTLCommandBuffer, Metal},+ backends::metal::Metal,encodable_block::{EncodableBlock, EncodingParameters},forward_pass::state::{ArrayId, ForwardPassState},session::types::Error,diff --git a/crates/uzu/src/classifier/mod.rs b/crates/uzu/src/classifier/mod.rsindex 26d1020c5..43a4e5dff 100644--- a/crates/uzu/src/classifier/mod.rs+++ b/crates/uzu/src/classifier/mod.rs@@ -7,6 +7,7 @@ pub use result::{ClassificationOutput, ClassificationStats};// Re-export context from metal backendpub use crate::backends::metal::ClassifierContext;// Re-export encodables from metal backend for convenience-pub use crate::backends::metal::encodable_block::{ClassifierLayer, ClassifierPredictionHead, Pooling};+pub use crate::backends::metal::encodable_block::{ClassifierLayer, ClassifierPredictionHead};+pub use crate::encodable_block::Pooling;#[cfg(feature = "tracing")]pub use crate::forward_pass::traces::{ActivationTrace, LayerActivationTrace};diff --git a/crates/uzu/src/language_model/gpu_capture.rs b/crates/uzu/src/language_model/gpu_capture.rsindex 9d686f81a..a16b94014 100644--- a/crates/uzu/src/language_model/gpu_capture.rs+++ b/crates/uzu/src/language_model/gpu_capture.rs@@ -3,10 +3,9 @@ use std::{time::{SystemTime, UNIX_EPOCH},};-use crate::{- backends::metal::{MTLCaptureDescriptor, MTLCaptureDestination, MTLCaptureManager, MTLCommandQueueExt, MTLContext},- utils::env_utils::MetalEnvVar,-};+use metal::{MTLCaptureDescriptor, MTLCaptureDestination, MTLCaptureManager, MTLCommandQueueExt};++use crate::{backends::metal::MetalContext, utils::env_utils::MetalEnvVar};pub struct GpuCaptureManager {capture_prefill_enabled: bool,@@ -51,7 +50,7 @@ impl GpuCaptureManager {pub fn start_capture(&self,- mtl_context: &MTLContext,+ mtl_context: &MetalContext,capture_type: &str,) -> Result<PathBuf, String> {let timestamp =diff --git a/crates/uzu/src/language_model/language_model_generator.rs b/crates/uzu/src/language_model/language_model_generator.rsindex 47cfafa81..691622123 100644--- a/crates/uzu/src/language_model/language_model_generator.rs+++ b/crates/uzu/src/language_model/language_model_generator.rs@@ -1,6 +1,7 @@use std::{collections::HashMap, iter::repeat_n, path::Path, sync::Arc, time::Instant};use itertools::{Either, Itertools, izip};+use metal::{MTLBuffer, MTLCommandBuffer, MTLCommandBufferExt, MTLCommandBufferHandler, MTLCommandEncoder};use super::{LanguageModelGeneratorContext,@@ -16,7 +17,7 @@ use crate::{Context,kernel::{MaskUpdateKernel, TokenCopySampledKernel, TokenCopyToResultsKernel},},- metal::{MTLBuffer, MTLCommandBuffer, MTLCommandBufferExt, MTLCommandBufferHandler, MTLCommandEncoder, Metal},+ metal::Metal,},encodable_block::{EncodableBlock, EncodingParameters},forward_pass::{diff --git a/crates/uzu/src/language_model/tasks.rs b/crates/uzu/src/language_model/tasks.rsindex 1b47a5a80..66037297c 100644--- a/crates/uzu/src/language_model/tasks.rs+++ b/crates/uzu/src/language_model/tasks.rs@@ -1,11 +1,11 @@use std::mem::size_of;+use metal::{BufferExt, MTLBuffer};+use objc2::{rc::Retained, runtime::ProtocolObject};+use super::LanguageModelGeneratorContext;use crate::{- backends::{- common::Context,- metal::{BufferExt, MTLBuffer, Metal, ProtocolObject, Retained},- },+ backends::{common::Context, metal::Metal},encodable_block::{EncodableBlock, EncodingParameters},forward_pass::state::ForwardPassState,};diff --git a/crates/uzu/src/tracer/trace_validator.rs b/crates/uzu/src/tracer/trace_validator.rsindex da176d338..d18ed64a3 100644--- a/crates/uzu/src/tracer/trace_validator.rs+++ b/crates/uzu/src/tracer/trace_validator.rs@@ -12,12 +12,16 @@ use std::{};use half::{bf16, f16};+use metal::{MTLCommandBuffer, MTLCommandQueue};use ndarray::{IxDyn, s};use num_traits::NumCast;use crate::{ArrayElement, DataType,- backends::metal::{KVCacheUpdate, MTLCommandBuffer, MTLCommandQueue, MTLContext, Metal, MetalArray},+ backends::{+ common::kernel::kv_cache_update::KVCacheUpdate,+ metal::{Metal, MetalArray, MetalContext},+ },classifier::Classifier,config::ModelMetadata,encodable_block::{EncodableBlock, EncodingParameters, Sampling},@@ -420,7 +424,7 @@ impl TraceValidator {})}- fn handle_missing_tokens(traces_view: &ParameterTree<MTLContext>) -> TracerValidationResults {+ fn handle_missing_tokens(traces_view: &ParameterTree<MetalContext>) -> TracerValidationResults {if let Ok(expected_logits) = traces_view.leaf("logits") {let reference_shape = expected_logits.shape().to_vec();let metrics = TracerValidationMetrics {@@ -466,7 +470,7 @@ impl TraceValidator {fn validate_layer_traces(traces: &Rc<RefCell<ActivationTrace<Metal>>>,- traces_view: &ParameterTree<MTLContext>,+ traces_view: &ParameterTree<MetalContext>,data_type: DataType,) -> Vec<TracerValidationResult> {let mut results = Vec::new();@@ -535,7 +539,7 @@ impl TraceValidator {fn validate_classifier_traces(traces: &Rc<RefCell<ActivationTrace<Metal>>>,- traces_view: &ParameterTree<MTLContext>,+ traces_view: &ParameterTree<MetalContext>,data_type: DataType,) -> Vec<TracerValidationResult> {let mut results = Vec::new();@@ -593,7 +597,7 @@ impl TraceValidator {fn validate_array_with_name(data_type: DataType,- traces_view: &ParameterTree<MTLContext>,+ traces_view: &ParameterTree<MetalContext>,expected_array_path: &str,produced_array: &Ref<MetalArray>,) -> TracerValidationMetrics {@@ -773,7 +777,7 @@ impl TraceValidator {// ========================================================================fn load_array_as_vec<SourcePrecision: ArrayElement, TargetPrecision: NumCast>(- traces_view: &ParameterTree<MTLContext>,+ traces_view: &ParameterTree<MetalContext>,name: &str,) -> Vec<TargetPrecision> {let array = traces_view.leaf(name).unwrap();diff --git a/crates/uzu/src/utils/device.rs b/crates/uzu/src/utils/device.rsindex 7e01c2fc0..b4c317563 100644--- a/crates/uzu/src/utils/device.rs+++ b/crates/uzu/src/utils/device.rs@@ -1,3 +1,5 @@+use metal::{MTLDevice, MTLDeviceExt};+#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum DeviceClass {Ultra,@@ -10,10 +12,7 @@ pub enum DeviceClass {impl DeviceClass {pub fn detect() -> Self {- use metal::MTLDeviceExt as _;- let device: crate::backends::metal::Retained<- crate::backends::metal::ProtocolObject<dyn crate::backends::metal::MTLDevice>,- > = match <dyn metal::MTLDevice>::system_default() {+ let device = match <dyn MTLDevice>::system_default() {Some(dev) => dev,None => return DeviceClass::Unknown,};diff --git a/crates/uzu/tests/allocator_test/caching_allocator.rs b/crates/uzu/tests/allocator_test/caching_allocator.rsindex e5852e80d..16e68bb9d 100644--- a/crates/uzu/tests/allocator_test/caching_allocator.rs+++ b/crates/uzu/tests/allocator_test/caching_allocator.rs@@ -2,18 +2,18 @@ use std::rc::Rc;use uzu::backends::{common::{Buffer, BufferLifetime, Context},- metal::{MTLContext, Metal},+ metal::{Metal, MetalContext},};use super::allocator_trait::AllocatorTrait;pub struct CachingAllocator {- pub context: Rc<MTLContext>,+ pub context: Rc<MetalContext>,}impl CachingAllocator {pub fn new() -> Self {- let context = MTLContext::new().expect("Failed to create MTLContext");+ let context = MetalContext::new().expect("Failed to create MetalContext");Self {context,}diff --git a/crates/uzu/tests/attention_kernel_test.rs b/crates/uzu/tests/attention_kernel_test.rsindex c2a0cfb02..e4085aa52 100644--- a/crates/uzu/tests/attention_kernel_test.rs+++ b/crates/uzu/tests/attention_kernel_test.rs@@ -7,12 +7,13 @@ use std::mem::size_of;use bytemuck;use metal::{MTLBuffer, MTLCommandBuffer, MTLCommandEncoder, MTLCommandQueue, MTLDeviceExt, MTLResourceOptions};use ndarray::{Array3, Array4, s};+use objc2::{rc::Retained, runtime::ProtocolObject};use uzu::{DataType,backends::{common::Context,metal::{- MTLContext, ProtocolObject, Retained,+ MetalContext,kernel::attention::{AttentionGemmArguments, AttentionKernel, AttentionKernelVariant, AttentionSinglePassArguments,AttentionTwoPassArguments,@@ -145,7 +146,7 @@ fn create_test_data(/// Convert ndarray to Metal buffer layout expected by our kernelfn create_query_buffer(queries: &Array4<f32>,- context: &MTLContext,+ context: &MetalContext,) -> Retained<ProtocolObject<dyn MTLBuffer>> {let (_batch_size, num_heads, seq_len, head_dim) = queries.dim();@@ -170,7 +171,7 @@ fn create_query_buffer(fn create_key_cache_buffer(keys: &Array4<f32>,max_seq_len: usize,- context: &MTLContext,+ context: &MetalContext,) -> Retained<ProtocolObject<dyn MTLBuffer>> {let (_batch_size, num_kv_heads, seq_len, head_dim) = keys.dim();@@ -195,7 +196,7 @@ fn create_key_cache_buffer(fn create_value_cache_buffer(values: &Array4<f32>,max_seq_len: usize,- context: &MTLContext,+ context: &MetalContext,) -> Retained<ProtocolObject<dyn MTLBuffer>> {let (_batch_size, num_kv_heads, seq_len, head_dim) = values.dim();@@ -220,7 +221,7 @@ fn create_value_cache_buffer(fn create_mask_buffer(mask: &Array3<f32>,num_heads: usize,- context: &MTLContext,+ context: &MetalContext,) -> Retained<ProtocolObject<dyn MTLBuffer>> {let (_batch_size, seq_len, _) = mask.dim();@@ -243,7 +244,7 @@ fn create_mask_buffer(fn create_mask_2d_buffer(mask: &Array3<f32>,- context: &MTLContext,+ context: &MetalContext,) -> Retained<ProtocolObject<dyn MTLBuffer>> {let (_batch_size, seq_len, _) = mask.dim();@@ -262,7 +263,7 @@ fn create_mask_2d_buffer(fn create_sinks_buffer(sinks: &[f32],- context: &MTLContext,+ context: &MetalContext,) -> Retained<ProtocolObject<dyn MTLBuffer>> {context.device@@ -293,7 +294,7 @@ fn convert_kernel_output(fn run_single_pass_attention(kernel: &AttentionKernel,- context: &MTLContext,+ context: &MetalContext,queries: &Array4<f32>,keys: &Array4<f32>,values: &Array4<f32>,@@ -359,7 +360,7 @@ fn run_single_pass_attention(fn run_single_pass_attention_with_is_causal(kernel: &AttentionKernel,- context: &MTLContext,+ context: &MetalContext,queries: &Array4<f32>,keys: &Array4<f32>,values: &Array4<f32>,@@ -426,7 +427,7 @@ fn run_single_pass_attention_with_is_causal(fn run_gemm_attention(kernel: &AttentionKernel,- context: &MTLContext,+ context: &MetalContext,queries: &Array4<f32>,keys: &Array4<f32>,values: &Array4<f32>,@@ -537,7 +538,7 @@ fn compare_results(#[test]#[ignore]fn test_single_pass_attention_basic() {- let context = MTLContext::new().expect("Failed to create MTLContext");+ let context = MetalContext::new().expect("Failed to create MetalContext");let batch_size = 1;let num_heads = 4;@@ -594,7 +595,7 @@ fn test_single_pass_attention_basic() {#[test]#[ignore]fn test_gemm_attention_basic() {- let context = MTLContext::new().expect("Failed to create MTLContext");+ let context = MetalContext::new().expect("Failed to create MetalContext");let batch_size = 1;let num_heads = 4;@@ -622,7 +623,7 @@ fn test_gemm_attention_basic() {#[test]#[ignore]fn test_gemm_attention_f32_head_dim_128() {- let context = MTLContext::new().expect("Failed to create MTLContext");+ let context = MetalContext::new().expect("Failed to create MetalContext");let batch_size = 1;let num_heads = 4;@@ -650,7 +651,7 @@ fn test_gemm_attention_f32_head_dim_128() {#[test]#[ignore]fn test_matrix_attention_matches_vector_and_cpu_seq256() {- let context = MTLContext::new().expect("Failed to create MTLContext");+ let context = MetalContext::new().expect("Failed to create MetalContext");let batch_size = 1;let num_heads = 8;@@ -706,7 +707,7 @@ fn test_matrix_attention_matches_vector_and_cpu_seq256() {#[test]#[ignore]fn test_single_pass_attention_with_mask() {- let context = MTLContext::new().expect("Failed to create MTLContext");+ let context = MetalContext::new().expect("Failed to create MetalContext");let batch_size = 1;let num_heads = 4;@@ -755,7 +756,7 @@ fn test_single_pass_attention_with_mask() {#[test]#[ignore]fn test_single_pass_attention_with_sinks() {- let context = MTLContext::new().expect("Failed to create MTLContext");+ let context = MetalContext::new().expect("Failed to create MetalContext");let batch_size = 1;let num_heads = 4;@@ -799,7 +800,7 @@ fn test_single_pass_attention_with_sinks() {#[test]#[ignore]fn test_single_pass_attention_with_sinks_long_sequence() {- let context = MTLContext::new().expect("Failed to create MTLContext");+ let context = MetalContext::new().expect("Failed to create MetalContext");let batch_size = 1;let num_heads = 4;@@ -848,7 +849,7 @@ fn test_single_pass_attention_with_sinks_long_sequence() {#[test]#[ignore]fn test_single_pass_attention_gqa() {- let context = MTLContext::new().expect("Failed to create MTLContext");+ let context = MetalContext::new().expect("Failed to create MetalContext");let batch_size = 1;let num_heads = 8;@@ -892,7 +893,7 @@ fn test_single_pass_attention_gqa() {fn run_two_pass_attention(kernel: &AttentionKernel,- context: &MTLContext,+ context: &MetalContext,queries: &Array4<f32>,keys: &Array4<f32>,values: &Array4<f32>,@@ -983,7 +984,7 @@ fn run_two_pass_attention(#[test]#[ignore]fn test_two_pass_attention() {- let context = MTLContext::new().expect("Failed to create MTLContext");+ let context = MetalContext::new().expect("Failed to create MetalContext");let kernel = match AttentionKernel::new(&context, DataType::F32) {Ok(k) => k,@@ -1029,7 +1030,7 @@ fn test_two_pass_attention() {#[test]#[ignore]fn test_two_pass_attention_gqa() {- let context = MTLContext::new().expect("Failed to create MTLContext");+ let context = MetalContext::new().expect("Failed to create MetalContext");let kernel = match AttentionKernel::new(&context, DataType::F32) {Ok(k) => k,@@ -1077,7 +1078,7 @@ fn test_two_pass_attention_gqa() {fn perf_two_pass_attention() {use std::time::Instant;- let context = MTLContext::new().expect("Failed to create MTLContext");+ let context = MetalContext::new().expect("Failed to create MetalContext");let kernel = match AttentionKernel::new(&context, DataType::F32) {Ok(k) => k,diff --git a/crates/uzu/tests/kv_cache_state_test.rs b/crates/uzu/tests/kv_cache_state_test.rsindex 5490026fe..4ec6e04ba 100644--- a/crates/uzu/tests/kv_cache_state_test.rs+++ b/crates/uzu/tests/kv_cache_state_test.rs@@ -5,8 +5,8 @@ use uzu::{DataType,array::ArrayContextExt,backends::{- common::Context,- metal::{KVCacheUpdate, MTLContext, Metal},+ common::{Context, kernel::kv_cache_update::KVCacheUpdate},+ metal::{Metal, MetalContext},},forward_pass::kv_cache_layer::{INVALID_POSITION, KVCacheLayer, KVCacheLayerState},};@@ -31,7 +31,7 @@ struct Scenario {}fn make_test_layer(- context: &MTLContext,+ context: &MetalContext,state: KVCacheLayerState,prefix_capacity: usize,suffix_capacity: usize,@@ -148,7 +148,7 @@ fn collect_mask(}fn run_scenario(- context: &MTLContext,+ context: &MetalContext,scenario: &Scenario,) {let mut layer =@@ -249,7 +249,7 @@ fn run_scenario(#[test]fn kv_cache_state_and_mask_scenarios() {- let Some(context) = MTLContext::new().ok() else {+ let Some(context) = MetalContext::new().ok() else {return;};@@ -357,7 +357,7 @@ fn kv_cache_state_and_mask_scenarios() {#[test]fn kv_cache_slice_apply_contiguous_window() {- let Some(context) = MTLContext::new().ok() else {+ let Some(context) = MetalContext::new().ok() else {return;};@@ -403,7 +403,7 @@ fn kv_cache_slice_apply_contiguous_window() {#[test]fn kv_cache_slice_apply_wrap_window() {- let Some(context) = MTLContext::new().ok() else {+ let Some(context) = MetalContext::new().ok() else {return;};@@ -445,7 +445,7 @@ fn kv_cache_slice_apply_wrap_window() {#[test]fn kv_cache_slice_apply_full_restores_metadata() {- let Some(context) = MTLContext::new().ok() else {+ let Some(context) = MetalContext::new().ok() else {return;};diff --git a/crates/uzu/tests/kv_cache_update_test.rs b/crates/uzu/tests/kv_cache_update_test.rsindex 82f22c04b..c2afe6b51 100644--- a/crates/uzu/tests/kv_cache_update_test.rs+++ b/crates/uzu/tests/kv_cache_update_test.rs@@ -6,9 +6,9 @@ use uzu::backends::{common::{Context,gpu_types::Swap,- kernel::kv_cache_update::{KVLayerData, create_swaps_direct},+ kernel::kv_cache_update::{KVCacheUpdate, KVLayerData, create_swaps_direct},},- metal::{KVCacheUpdate, MTLContext, Metal},+ metal::{Metal, MetalContext},};fn apply_swaps_3d<T: Clone>(@@ -31,7 +31,7 @@ fn apply_swaps_3d<T: Clone>(#[test]fn test_kv_cache_update_kernel() {- let metal_context = match MTLContext::new() {+ let metal_context = match MetalContext::new() {Ok(ctx) => ctx,Err(e) => {println!("Failed to create MetalContext: {:?}. Skipping test.", e);@@ -42,7 +42,7 @@ fn test_kv_cache_update_kernel() {test_random_pattern(&metal_context);}-fn test_random_pattern(context: &MTLContext) {+fn test_random_pattern(context: &MetalContext) {println!("Testing with random pattern...");let max_sequence_length = 256usize;diff --git a/crates/uzu/tests/matmul_correctness_test.rs b/crates/uzu/tests/matmul_correctness_test.rsindex c5731e335..4982e0eca 100644--- a/crates/uzu/tests/matmul_correctness_test.rs+++ b/crates/uzu/tests/matmul_correctness_test.rs@@ -9,14 +9,14 @@ use uzu::{backends::{common::Context,metal::{- MTLContext,+ MetalContext,kernel::{MatmulArguments, MatmulKernel},},},};fn run_metal_matmul(- ctx: &MTLContext,+ ctx: &MetalContext,a_data: &[bf16],b_data: &[bf16],m: usize,@@ -265,7 +265,7 @@ fn compare_results(#[test]#[ignore]fn matmul_correctness_comprehensive() {- let Some(ctx) = MTLContext::new().ok() else {+ let Some(ctx) = MetalContext::new().ok() else {eprintln!("No Metal device available, skipping test");return;};diff --git a/crates/uzu/tests/moe/counts_offsets_fused_test.rs b/crates/uzu/tests/moe/counts_offsets_fused_test.rsindex 66bd80d69..6696cff3d 100644--- a/crates/uzu/tests/moe/counts_offsets_fused_test.rs+++ b/crates/uzu/tests/moe/counts_offsets_fused_test.rs@@ -2,13 +2,14 @@use half::bf16;use metal::{MTLBuffer, MTLCommandBuffer, MTLCommandEncoder, MTLCommandQueue};+use objc2::{rc::Retained, runtime::ProtocolObject};use rand::{RngExt, SeedableRng, rngs::StdRng};use uzu::{DataType,backends::{common::kernel::MoeCountsOffsetsFusedKernel,metal::{- MTLContext, ProtocolObject, Retained,+ MetalContext,kernel::{dsl::MoeCountsOffsetsFusedMetalKernel,moe::{MoeRouterTopKArguments, MoeRouterTopKKernel},@@ -52,7 +53,7 @@ fn cpu_offsets_from_counts(counts: &[u32]) -> (Vec<u32>, u32) {}fn gen_topk_ids_from_logits(- ctx: &MTLContext,+ ctx: &MetalContext,t: usize,e: usize,k: usize,diff --git a/crates/uzu/tests/moe/moe_block_e2e_test.rs b/crates/uzu/tests/moe/moe_block_e2e_test.rsindex 175fca611..c8dd522ee 100644--- a/crates/uzu/tests/moe/moe_block_e2e_test.rs+++ b/crates/uzu/tests/moe/moe_block_e2e_test.rs@@ -6,7 +6,7 @@ use uzu::{backends::{common::kernel::{MoeCountsOffsetsFusedKernel, MoeFinalizeKernel},metal::{- MTLContext,+ MetalContext,kernel::{MoeBlockBasesArguments, MoeScatterKernels, MoeScatterWithMapArguments,dsl::{MoeCountsOffsetsFusedMetalKernel, MoeFinalizeMetalKernel},@@ -169,7 +169,7 @@ fn moe_cpu_reference(// Main entry point - automatically tests both modes for T>1fn run_moe_parity_test(- ctx: &MTLContext,+ ctx: &MetalContext,t: usize,e: usize,k: usize,@@ -233,7 +233,7 @@ fn run_moe_parity_test(}fn run_moe_parity_test_internal(- ctx: &MTLContext,+ ctx: &MetalContext,t: usize,e: usize,k: usize,diff --git a/crates/uzu/tests/moe/moe_experts_perf_test.rs b/crates/uzu/tests/moe/moe_experts_perf_test.rsindex 1178cbf0a..ba2d602c2 100644--- a/crates/uzu/tests/moe/moe_experts_perf_test.rs+++ b/crates/uzu/tests/moe/moe_experts_perf_test.rs@@ -6,7 +6,7 @@ use rand::{RngExt, SeedableRng, rngs::StdRng};use uzu::{DataType,backends::metal::{- MTLContext,+ MetalContext,kernel::moe::{MoeExpertsSingleDecodeArguments, MoeExpertsSingleDecodeKernels, MoeExpertsTwoPassArguments,MoeExpertsTwoPassDecodeKernels, MoeExpertsTwoPassPrefillKernel,@@ -35,7 +35,7 @@ fn build_offsets(}fn run_decode_case(- ctx: &MTLContext,+ ctx: &MetalContext,name: &str,t: usize,d_model: usize,@@ -174,7 +174,7 @@ fn test_two_pass_decode_speed() {}fn run_two_pass_prefill_case(- ctx: &MTLContext,+ ctx: &MetalContext,name: &str,t: usize,d_model: usize,@@ -310,7 +310,7 @@ fn test_two_pass_prefill_speed() {}fn run_fused_single_token_case(- ctx: &MTLContext,+ ctx: &MetalContext,name: &str,d_model: usize,d_ff: usize,@@ -450,7 +450,7 @@ fn test_single_token_indirect_vs_fused() {}fn run_indirect_decode_timed(- ctx: &MTLContext,+ ctx: &MetalContext,t: usize,d_model: usize,d_ff: usize,@@ -557,7 +557,7 @@ fn run_indirect_decode_timed(}fn run_fused_decode_timed(- ctx: &MTLContext,+ ctx: &MetalContext,d_model: usize,d_ff: usize,e: usize,diff --git a/crates/uzu/tests/moe/moe_router_topk_test.rs b/crates/uzu/tests/moe/moe_router_topk_test.rsindex 55f0841f7..0f4166ee5 100644--- a/crates/uzu/tests/moe/moe_router_topk_test.rs+++ b/crates/uzu/tests/moe/moe_router_topk_test.rs@@ -6,7 +6,7 @@ use rand::{RngExt, SeedableRng, rngs::StdRng};use uzu::{DataType,backends::metal::{- MTLContext,+ MetalContext,kernel::moe::{MoeRouterTopKArguments, MoeRouterTopKKernel},},};@@ -128,7 +128,7 @@ pub fn cpu_topk_select_f32(}fn run_router_topk_once(- ctx: &MTLContext,+ ctx: &MetalContext,kernel: &MoeRouterTopKKernel,t: usize,d_model: usize,diff --git a/crates/uzu/tests/moe/moe_test_utils.rs b/crates/uzu/tests/moe/moe_test_utils.rsindex b9cf882e8..aaf08b1be 100644--- a/crates/uzu/tests/moe/moe_test_utils.rs+++ b/crates/uzu/tests/moe/moe_test_utils.rs@@ -9,20 +9,18 @@ use std::rc::Rc;use bytemuck;use half::bf16;-use metal::{MTLDeviceExt, MTLResourceOptions};-use uzu::backends::{- common::Context,- metal::{MTLBuffer, MTLContext, ProtocolObject, Retained},-};+use metal::{MTLBuffer, MTLDeviceExt, MTLResourceOptions};+use objc2::{rc::Retained, runtime::ProtocolObject};+use uzu::backends::{common::Context, metal::MetalContext};/// Create Metal context for testing-pub fn create_ctx() -> Rc<MTLContext> {- MTLContext::new().expect("Failed to create MTLContext")+pub fn create_ctx() -> Rc<MetalContext> {+ MetalContext::new().expect("Failed to create MetalContext")}/// Helper to allocate buffer with datapub fn alloc_buffer_with_data<T: bytemuck::NoUninit>(- ctx: &MTLContext,+ ctx: &MetalContext,data: &[T],) -> Retained<ProtocolObject<dyn MTLBuffer>> {if data.is_empty() {@@ -37,7 +35,7 @@ pub fn alloc_buffer_with_data<T: bytemuck::NoUninit>(/// Helper to allocate empty bufferpub fn alloc_buffer<T>(- ctx: &MTLContext,+ ctx: &MetalContext,count: usize,) -> Retained<ProtocolObject<dyn MTLBuffer>> {ctx.create_buffer(count * size_of::<T>()).expect("Failed to create buffer")diff --git a/crates/uzu/tests/parameters_loader_test.rs b/crates/uzu/tests/parameters_loader_test.rsindex f3d877a36..b589da660 100644--- a/crates/uzu/tests/parameters_loader_test.rs+++ b/crates/uzu/tests/parameters_loader_test.rs@@ -4,14 +4,14 @@ mod common;use half::bf16;use is_close::is_close;use uzu::{- backends::{common::Context, metal::MTLContext},+ backends::{common::Context, metal::MetalContext},parameters::ParameterLoader,};#[test]fn test_parameter_loader_basic() {let weights_path = crate::common::get_test_weights_path();- let context = MTLContext::new().expect("Failed to create MTLContext");+ let context = MetalContext::new().expect("Failed to create MetalContext");let file = std::fs::File::open(&weights_path).expect("Weights file not found; run download script");let loader = ParameterLoader::new(&file, context.as_ref()).expect("create loader");diff --git a/crates/uzu/tests/quant_matmul_test.rs b/crates/uzu/tests/quant_matmul_test.rsindex dab71fd17..fd3fa8e24 100644--- a/crates/uzu/tests/quant_matmul_test.rs+++ b/crates/uzu/tests/quant_matmul_test.rs@@ -3,12 +3,13 @@ use std::time::Instant;use bytemuck;use half::{bf16, f16};use metal::{MTLBuffer, MTLCommandBuffer, MTLCommandEncoder, MTLCommandQueue, MTLDeviceExt, MTLResourceOptions};+use objc2::{rc::Retained, runtime::ProtocolObject};use uzu::{DataType,backends::{common::Context,metal::{- MTLContext, ProtocolObject, Retained,+ MetalContext,kernel::quant_matmul::{QuantizationType, QuantizedMatmulArguments, QuantizedMatmulKernel},},},@@ -385,7 +386,7 @@ fn generate_test_quant_params(}fn buffer_from_f32_slice(- ctx: &MTLContext,+ ctx: &MetalContext,dtype: DataType,values: &[f32],) -> Retained<ProtocolObject<dyn MTLBuffer>> {@@ -413,7 +414,7 @@ fn buffer_from_f32_slice(}fn execute_quantized_matmul(- ctx: &MTLContext,+ ctx: &MetalContext,batch: usize,input_dim: usize,output_dim: usize,@@ -630,7 +631,7 @@ const QVM_DIMS: &[(usize, usize)] = &[(128, 512), (512, 1024), (1024, 4096)];const QMM_DIMS: &[(usize, usize, usize)] = &[(64, 64, 64), (512, 512, 1024), (128, 128, 256)];fn run_kernel_test(- ctx: &MTLContext,+ ctx: &MetalContext,batch: usize,output_dim: usize,input_dim: usize,@@ -659,7 +660,7 @@ fn run_kernel_test(#[test]fn test_quant_gmv() {- let ctx = match MTLContext::new() {+ let ctx = match MetalContext::new() {Ok(c) => c,Err(_) => {println!("Metal not available — skipping QMV test");@@ -703,7 +704,7 @@ fn test_quant_gmv() {#[test]fn test_quant_qvm() {- let ctx = match MTLContext::new() {+ let ctx = match MetalContext::new() {Ok(c) => c,Err(_) => {println!("Metal not available — skipping QVM test");@@ -747,7 +748,7 @@ fn test_quant_qvm() {#[test]fn test_quant_gmm() {- let ctx = match MTLContext::new() {+ let ctx = match MetalContext::new() {Ok(c) => c,Err(_) => {println!("Metal not available — skipping QMM test");@@ -791,7 +792,7 @@ fn test_quant_gmm() {#[test]fn test_quant_gmm_transposed() {- let ctx = match MTLContext::new() {+ let ctx = match MetalContext::new() {Ok(c) => c,Err(_) => {println!("Metal not available — skipping QMM transposed test");@@ -836,7 +837,7 @@ fn test_quant_gmm_transposed() {#[test]#[ignore]fn test_quant_matmul_perf() {- let ctx = match MTLContext::new() {+ let ctx = match MetalContext::new() {Ok(c) => c,Err(_) => {println!("Metal not available — skipping Perf test");diff --git a/crates/uzu/tests/rms_norm_kernel_test.rs b/crates/uzu/tests/rms_norm_kernel_test.rsindex f8bdd4d08..ed8cd0b9a 100644--- a/crates/uzu/tests/rms_norm_kernel_test.rs+++ b/crates/uzu/tests/rms_norm_kernel_test.rs@@ -12,7 +12,7 @@ use uzu::{kernel::{QKNormKernel, RMSNormKernel},},metal::{- MTLContext,+ MetalContext,kernel::dsl::{QKNormMetalKernel, RMSNormMetalKernel},metal_extensions::CommandBufferTimingExt,},@@ -248,7 +248,7 @@ fn test_rms_norm_basic_typed<InputT, ScaleT, OutputT>(OutputT: TestFloat,{// Create Metal context- let mtl_context = match MTLContext::new() {+ let mtl_context = match MetalContext::new() {Ok(ctx) => ctx,Err(e) => {println!("Skipping RMS norm test: {}", e);@@ -381,7 +381,7 @@ fn test_rms_norm_edge_cases_typed<InputT, ScaleT, OutputT>(ScaleT: TestFloat,OutputT: TestFloat,{- let mtl_context = match MTLContext::new() {+ let mtl_context = match MetalContext::new() {Ok(ctx) => ctx,Err(e) => {println!("Skipping RMS norm edge case test: {}", e);@@ -573,7 +573,7 @@ fn perf_rms_norm_with_size(use rand::{RngExt, SeedableRng, rngs::StdRng};// ---- Metal context ----- let mtl_context = match MTLContext::new() {+ let mtl_context = match MetalContext::new() {Ok(ctx) => ctx,Err(e) => {println!("Skipping RMS norm perf test: {}", e);@@ -699,7 +699,7 @@ fn perf_rms_norm_16k() {#[test]fn qk_norm_test() {// Test to verify that the QK norm kernel now accesses the correct data ranges- let mtl_context = match MTLContext::new() {+ let mtl_context = match MetalContext::new() {Ok(ctx) => ctx,Err(e) => {println!("Skipping QK norm buffer addressing test: {}", e);diff --git a/crates/uzu/tests/sampling_test.rs b/crates/uzu/tests/sampling_test.rsindex a186cb98c..79fe22056 100644--- a/crates/uzu/tests/sampling_test.rs+++ b/crates/uzu/tests/sampling_test.rs@@ -14,7 +14,7 @@ use uzu::{},},metal::{- MTLContext, Metal,+ Metal, MetalContext,kernel::dsl::{GumbelMetalKernel, MinPMetalKernel, TemperatureMetalKernel, TopKMetalKernel, TopPMetalKernel,},@@ -81,7 +81,7 @@ fn cpu_reference_min_p(}fn test_argmax_sampling_with_strategy(strategy: ArgmaxStrategy) {- let context = match MTLContext::new() {+ let context = match MetalContext::new() {Ok(ctx) => ctx,Err(e) => {println!("Skipping argmax test: {}", e);@@ -172,7 +172,7 @@ fn test_topp_sampling_from_prob_exact_match(use rand::{SeedableRng, rngs::StdRng};- let context = match MTLContext::new() {+ let context = match MetalContext::new() {Ok(ctx) => ctx,Err(e) => {eprintln!("Skipping topP exact match test: {}", e);@@ -311,7 +311,7 @@ fn test_topp_sampling_statistical_large() {use rand::{RngExt, SeedableRng, rngs::StdRng};// ===== 1. Create Metal context =====- let context = match MTLContext::new() {+ let context = match MetalContext::new() {Ok(ctx) => ctx,Err(e) => {println!("Skipping large statistical test: {}", e);@@ -428,7 +428,7 @@ fn perf_topp_128k_vocab() {use rand::{RngExt, SeedableRng, rngs::StdRng};// ---- Metal context ----- let context = match MTLContext::new() {+ let context = match MetalContext::new() {Ok(ctx) => ctx,Err(e) => {println!("Skipping perf test: {}", e);@@ -533,7 +533,7 @@ fn perf_argmax_128k_vocab_with_strategy(strategy: ArgmaxStrategy) {use rand::{RngExt, SeedableRng, rngs::StdRng};// ---- Metal context ----- let context = match MTLContext::new() {+ let context = match MetalContext::new() {Ok(ctx) => ctx,Err(e) => {println!("Skipping argmax perf test: {}", e);@@ -648,7 +648,7 @@ fn perf_argmax_128k_vocab_with_strategy(strategy: ArgmaxStrategy) {#[test]fn test_categorical_sampling() {- let context = match MTLContext::new() {+ let context = match MetalContext::new() {Ok(ctx) => ctx,Err(e) => {println!("Skipping categorical test: {}", e);@@ -770,7 +770,7 @@ fn test_categorical_sampling() {fn test_categorical_sampling_statistical() {use rand::{RngExt, SeedableRng, rngs::StdRng};- let context = match MTLContext::new() {+ let context = match MetalContext::new() {Ok(ctx) => ctx,Err(e) => {println!("Skipping categorical statistical test: {}", e);@@ -901,7 +901,7 @@ fn perf_categorical_128k_vocab() {use rand::{RngExt, SeedableRng, rngs::StdRng};- let context = match MTLContext::new() {+ let context = match MetalContext::new() {Ok(ctx) => ctx,Err(e) => {println!("Skipping categorical perf test: {}", e);@@ -998,7 +998,7 @@ fn perf_categorical_128k_vocab() {#[test]fn test_temperature_gpu_cpu_match() {- let context = match MTLContext::new() {+ let context = match MetalContext::new() {Ok(ctx) => ctx,Err(e) => {println!("Skipping temperature gpu cpu match test: {}", e);@@ -1061,7 +1061,7 @@ fn test_temperature_gpu_cpu_match() {fn test_topk_gpu_cpu_match() {use rand::{SeedableRng, rngs::StdRng};- let context = match MTLContext::new() {+ let context = match MetalContext::new() {Ok(ctx) => ctx,Err(e) => {println!("Skipping topk gpu cpu match test: {}", e);@@ -1125,7 +1125,7 @@ fn test_topk_gpu_cpu_match() {fn test_topp_gpu_cpu_match() {use rand::{SeedableRng, rngs::StdRng};- let context = match MTLContext::new() {+ let context = match MetalContext::new() {Ok(ctx) => ctx,Err(e) => {println!("Skipping topp gpu cpu match test: {}", e);@@ -1194,7 +1194,7 @@ fn test_topp_gpu_cpu_match() {fn test_minp_gpu_cpu_match() {use rand::{RngExt, SeedableRng, rngs::StdRng};- let context = match MTLContext::new() {+ let context = match MetalContext::new() {Ok(ctx) => ctx,Err(e) => {println!("Skipping minp gpu cpu match test: {}", e);@@ -1258,7 +1258,7 @@ fn test_minp_sampling_exact_match(use rand::{SeedableRng, rngs::StdRng};- let context = match MTLContext::new() {+ let context = match MetalContext::new() {Ok(ctx) => ctx,Err(e) => {eprintln!("Skipping minp exact match test: {}", e);@@ -1377,7 +1377,7 @@ fn test_minp_sampling_match_large() {#[test]fn test_gumbel_gpu_cpu_match() {- let context = match MTLContext::new() {+ let context = match MetalContext::new() {Ok(ctx) => ctx,Err(e) => {println!("Skipping gumbel gpu cpu match test: {}", e);diff --git a/crates/uzu/tests/ssd_prefill_kernel_test.rs b/crates/uzu/tests/ssd_prefill_kernel_test.rsindex aa150d51b..ddaa4ff4d 100644--- a/crates/uzu/tests/ssd_prefill_kernel_test.rs+++ b/crates/uzu/tests/ssd_prefill_kernel_test.rs@@ -4,14 +4,16 @@ use std::mem::size_of;use bytemuck;use metal::{- MTLBlitCommandEncoder, MTLCommandBuffer, MTLCommandEncoder, MTLCommandQueue, MTLDeviceExt, MTLResourceOptions,+ MTLBlitCommandEncoder, MTLBuffer, MTLCommandBuffer, MTLCommandEncoder, MTLCommandQueue, MTLDeviceExt,+ MTLResourceOptions,};+use objc2::runtime::ProtocolObject;use uzu::{DataType,backends::{common::{Context, kernel::Conv1dScanKernel},metal::{- MTLBuffer, MTLContext, ProtocolObject,+ MetalContext,kernel::{dsl::Conv1dScanMetalKernel,ssm::{SSDPrefillArguments, SSDPrefillKernels, SSDPrefillMode},@@ -196,7 +198,7 @@ impl SSDPrefillFixture {}fn run_prefill_kernel_mode(- ctx: &MTLContext,+ ctx: &MetalContext,kernel: &SSDPrefillKernels,fixture: &SSDPrefillFixture,mode: SSDPrefillMode,@@ -259,7 +261,7 @@ fn run_prefill_kernel_mode(}fn run_conv_scan_once(- ctx: &MTLContext,+ ctx: &MetalContext,kernel: &Conv1dScanMetalKernel,suffix_len: usize,channels: usize,@@ -357,7 +359,7 @@ fn run_conv_scan_once(}fn assert_deterministic_for_mode(mode: SSDPrefillMode) {- let Some(ctx) = MTLContext::new().ok() else {+ let Some(ctx) = MetalContext::new().ok() else {eprintln!("Skipping SSD prefill determinism test: no Metal device");return;};@@ -372,7 +374,7 @@ fn assert_deterministic_for_mode(mode: SSDPrefillMode) {}fn assert_matches_cpu_reference(mode: SSDPrefillMode) {- let Some(ctx) = MTLContext::new().ok() else {+ let Some(ctx) = MetalContext::new().ok() else {eprintln!("Skipping SSD prefill reference test: no Metal device");return;};@@ -458,7 +460,7 @@ fn ssd_prefill_single_pass_matches_cpu_reference() {#[test]fn conv1d_scan_is_deterministic() {- let Some(ctx) = MTLContext::new().ok() else {+ let Some(ctx) = MetalContext::new().ok() else {eprintln!("Skipping conv1d scan determinism test: no Metal device");return;};diff --git a/crates/uzu/tests/ssm_update_test.rs b/crates/uzu/tests/ssm_update_test.rsindex 115fed290..222bbeb7a 100644--- a/crates/uzu/tests/ssm_update_test.rs+++ b/crates/uzu/tests/ssm_update_test.rs@@ -7,7 +7,7 @@ use uzu::{DataType,backends::{common::{Context, kernel::SSDUpdateKernel},- metal::{MTLContext, kernel::dsl::SSDUpdateMetalKernel},+ metal::{MetalContext, kernel::dsl::SSDUpdateMetalKernel},},};@@ -174,7 +174,7 @@ fn ssd_update_ref_bf16(#[test]fn ssd_update_with_z_bf16() {- let Some(ctx) = MTLContext::new().ok() else {+ let Some(ctx) = MetalContext::new().ok() else {eprintln!("Skipping: no Metal device");return;};