A high-performance inference engine for AI models
Update MPSGraph (#19)
eugenef92428a04031
diff --git a/Cargo.lock b/Cargo.lockindex 0bbad5b85..7117ebf30 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -157,26 +157,6 @@ version = "0.1.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "383d29d513d8764dcdc42ea295d979eb99c3c9f00607b3692cf68a431f7dca72"-[[package]]-name = "bindgen"-version = "0.72.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "4f72209734318d0b619a5e0f5129918b848c416e122a3c4ce054e03cb87b726f"-dependencies = [- "bitflags 2.9.1",- "cexpr",- "clang-sys",- "itertools 0.13.0",- "log",- "prettyplease",- "proc-macro2",- "quote",- "regex",- "rustc-hash",- "shlex",- "syn",-]-[[package]]name = "bitflags"version = "1.3.2"@@ -260,15 +240,6 @@ dependencies = ["shlex",]-[[package]]-name = "cexpr"-version = "0.6.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766"-dependencies = [- "nom",-]-[[package]]name = "cfg-if"version = "1.0.1"@@ -281,17 +252,6 @@ version = "0.2.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724"-[[package]]-name = "clang-sys"-version = "1.8.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "0b023947811758c97c59bf9d1c188fd619ad4718dcaa767947df1cadb14f39f4"-dependencies = [- "glob",- "libc",- "libloading",-]-[[package]]name = "clap"version = "4.5.40"@@ -1107,16 +1067,6 @@ version = "0.2.174"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1171693293099992e19cddea4e8b849964e9846f4acee11b3948bcc337be8776"-[[package]]-name = "libloading"-version = "0.8.8"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "07033963ba89ebaf1584d767badaa2e8fcec21aedea6b8c0346d487d49c28667"-dependencies = [- "cfg-if",- "windows-targets 0.52.6",-]-[[package]]name = "libm"version = "0.2.15"@@ -1311,10 +1261,9 @@ dependencies = [[[package]]name = "mpsgraph"-version = "0.1.0"-source = "git+https://github.com/getmirai/mpsgraph-rs?rev=414c0d2#414c0d23b67d65e525972b8f7486c45f30939289"+version = "0.2.0"+source = "git+https://github.com/getmirai/mpsgraph-rs?rev=f2dfaea#f2dfaea5683393741421413889c22db3fce902c7"dependencies = [- "bindgen","bitflags 2.9.1","block2","metal",@@ -1713,16 +1662,6 @@ dependencies = ["zerocopy",]-[[package]]-name = "prettyplease"-version = "0.2.33"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9dee91521343f4c5c6a63edd65e54f31f5c92fe8978c40a4282f8372194c6a7d"-dependencies = [- "proc-macro2",- "syn",-]-[[package]]name = "proc-macro2"version = "1.0.95"@@ -2017,12 +1956,6 @@ version = "0.1.25"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "989e6739f80c4ad5b13e0fd7fe89531180375b18520cc8c82080e4dc4035b84f"-[[package]]-name = "rustc-hash"-version = "2.1.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "357703d41365b4b27c590e3ed91eabb1b663f07c4c084095e60cbed4362dff0d"-[[package]]name = "rustix"version = "1.0.7"diff --git a/uzu/Cargo.toml b/uzu/Cargo.tomlindex eecc9c5cf..9bebb7e64 100644--- a/uzu/Cargo.toml+++ b/uzu/Cargo.toml@@ -12,7 +12,7 @@ serde_json = "1.0.140"thiserror = "2.0.12"tokenizers = "0.21.1"# mpsgraph = { path = "../mpsgraph-rs" }-mpsgraph = { git = "https://github.com/getmirai/mpsgraph-rs", rev = "414c0d2", package = "mpsgraph" }+mpsgraph = { git = "https://github.com/getmirai/mpsgraph-rs", rev = "f2dfaea", package = "mpsgraph" }objc2 = "0.6.1"objc2-foundation = "0.3.1"metal = "0.32.0"diff --git a/uzu/examples/dequantize_qkv_layer0.rs b/uzu/examples/dequantize_qkv_layer0.rsindex 6fb30c73d..7a06a70ce 100644--- a/uzu/examples/dequantize_qkv_layer0.rs+++ b/uzu/examples/dequantize_qkv_layer0.rs@@ -8,9 +8,9 @@ use std::{use clap::Parser;use metal::{CaptureDescriptor, CaptureManager, MTLCaptureDestination};use mpsgraph::{- CommandBuffer, Device as MPSDevice, ExecutableExecutionDescriptor, Graph,- GraphQuantizationOps, Optimization, OptimizationProfile,- SerializationDescriptor, Shape, ShapedType, Tensor, TensorData,+ CommandBuffer, DequantizationArguments, Device as MPSDevice,+ ExecutableExecutionDescriptor, ExecutableSerializationDescriptor, Graph,+ Optimization, OptimizationProfile, ShapedType, Tensor, TensorData,};use objc2::rc::autoreleasepool;use thiserror::Error;@@ -130,24 +130,25 @@ fn main() -> Result<(), ExampleError> {).map_err(ExampleError::from)?;- let dequantized_weights = graph- .dequantize_with_scale_tensor_and_zero_point_tensor(- &weights,- &scales,- &zero_points,- DataType::F16.into(),- None,- )- .ok_or(ExampleError::Dequantization)?;+ let dequantized_weights = graph.dequantize(+ &weights,+ DequantizationArguments::ScaleTensorZeroPointTensorDataType {+ scale_tensor: &scales,+ zero_point_tensor: &zero_points,+ data_type: DataType::F16.into(),+ },+ None,+ );let mut dequantized_weights_buffer = unsafe {mtl_context.array_uninitialized(&[3072 * 2, 2560], DataType::F16)};let dequantized_weights_tensor_data = unsafe {- TensorData::from_buffer(+ TensorData::new_with_mtl_buffer(&dequantized_weights_buffer.mtl_buffer(),- &Shape::from_dimensions(&[3072 * 2, 2560]),+ &[3072 * 2, 2560],DataType::F16.into(),+ None,)};@@ -184,6 +185,7 @@ fn main() -> Result<(), ExampleError> {&MPSDevice::with_device(&mtl_context.device),&feeds,&[&dequantized_weights],+ None,Some(&compilation_descriptor),);@@ -195,9 +197,10 @@ fn main() -> Result<(), ExampleError> {let package_path = root_dir(NSSearchPathDirectory::Downloads).join(format!("dequantize_qkv_layer0-{timestamp}.mpsgraphpackage"),);- executable.serialize_to_url(+ let serialization_desc = ExecutableSerializationDescriptor::new();+ executable.serialize_to_graph_package(&package_path,- &SerializationDescriptor::new(),+ Some(&serialization_desc),);println!("MPSGraph package saved to: {:?}", package_path);}diff --git a/uzu/examples/quant_matmul_experiments.rs b/uzu/examples/quant_matmul_experiments.rsindex 4f5326fd3..ac7577dd5 100644--- a/uzu/examples/quant_matmul_experiments.rs+++ b/uzu/examples/quant_matmul_experiments.rs@@ -10,9 +10,9 @@ use half::f16;use metal::Device;use mpsgraph::{CommandBuffer, CompilationDescriptor, DataType as MPSDataType,- Device as MPSDevice, Executable, ExecutableExecutionDescriptor, Graph,- GraphMatrixOps, GraphQuantizationOps, GraphTensorShapeOps, Optimization,- OptimizationProfile, ShapedType, Tensor, tensor_data::TensorData,+ DequantizationArguments, Device as MPSDevice, Executable,+ ExecutableExecutionDescriptor, ExecutableSerializationDescriptor, Graph,+ Optimization, OptimizationProfile, ShapedType, Tensor, TensorData,};use objc2::rc::{Retained, autoreleasepool};use thiserror::Error;@@ -21,7 +21,6 @@ use uzu::{backends::metal::{MTLContext, MetalArray,compilation_parameters::{BlockDevice, make_compilation_descriptor},- utils::mps_shape,},storage::{NSSearchPathDirectory, root_dir},};@@ -157,24 +156,24 @@ fn build_quantized_matmul(let s = tensor_options.scales.tensor();let zp = tensor_options.zeros.tensor();- let dequantized_weights = graph- .dequantize_with_scale_tensor_and_zero_point_tensor(- &w,- &s,- &zp,- MPSDataType::Float16,- None,- )- .ok_or(ExampleError::Dequantization)?;+ let dequantized_weights = graph.dequantize(+ &w,+ DequantizationArguments::ScaleTensorZeroPointTensorDataType {+ scale_tensor: &s,+ zero_point_tensor: &zp,+ data_type: MPSDataType::Float16,+ },+ None,+ );let matmul = if transposed_shapes {- graph.matmul(+ graph.matrix_multiplication(&i,&graph.transpose(&dequantized_weights, &[1, 0], None),None,)} else {- graph.matmul(+ graph.matrix_multiplication(&graph.transpose(&dequantized_weights, &[1, 0], None),&graph.transpose(&i, &[1, 0], None),None,@@ -190,6 +189,7 @@ fn build_quantized_matmul(&device,&feeds,&[&*matmul],+ None,Some(compilation_descriptor),);@@ -206,17 +206,16 @@ fn make_tensor_option() -> TensorOption {match load_type {TensorLoadType::Baked => {- let tensor_const = graph.constant_with_data(- array.buffer(),- &mps_shape(shape),- dtype.into(),- );+ let tensor_const =+ graph.constant_with_data(array.buffer(), shape, dtype.into());TensorOption::Constant(tensor_const)},TensorLoadType::RuntimeLoaded => {let td = unsafe { array.to_mps_tensor_data() };+ let shape_isize: Vec<isize> =+ shape.iter().map(|d| *d as isize).collect();let placeholder =- graph.placeholder(dtype.into(), &mps_shape(shape), Some(name));+ graph.placeholder(Some(&shape_isize), dtype.into(), Some(name));TensorOption::Placeholder {placeholder,data: td,@@ -288,9 +287,11 @@ fn run_quant_matmul(// --- Tensor options for quantized matmul ---let input_tensor_data = unsafe { input_array.to_mps_tensor_data() };+ let input_shape_isize: Vec<isize> =+ input_shape.iter().map(|d| *d as isize).collect();let input_placeholder = graph.placeholder(+ Some(&input_shape_isize),DataType::F16.into(),- &mps_shape(&input_shape),Some("input_ph"),);@@ -353,8 +354,11 @@ fn run_quant_matmul(let package_path = root_dir(NSSearchPathDirectory::Downloads).join(format!("quant_matmul_experiments-{timestamp}.mpsgraphpackage"),);- let serialization_desc = mpsgraph::SerializationDescriptor::new();- executable.serialize_to_url(&package_path, &serialization_desc);+ let serialization_desc = ExecutableSerializationDescriptor::new();+ executable.serialize_to_graph_package(+ &package_path,+ Some(&serialization_desc),+ );}// --- Run & measure ---diff --git a/uzu/src/backends/metal/array.rs b/uzu/src/backends/metal/array.rsindex 99986a037..bd8b1f40f 100644--- a/uzu/src/backends/metal/array.rs+++ b/uzu/src/backends/metal/array.rs@@ -5,7 +5,6 @@ use metal::{Buffer as MTLBuffer, MTLResourceOptions};use mpsgraph::TensorData;use objc2::rc::Retained;-use super::utils::mps_shape;use crate::{Array, ArrayElement, DataType, array::array_size_in_bytes};/// Represents an n-dimensional array for Metal computation@@ -72,10 +71,11 @@ impl MetalArray {/// Wraps the underlying MTLBuffer into MPSTensorData for use with MPSGraph.pub unsafe fn to_mps_tensor_data(&mut self) -> Retained<TensorData> {- TensorData::from_buffer(+ TensorData::new_with_mtl_buffer(&self.buffer,- &mps_shape(&self.shape),+ &self.shape,self.data_type.into(),+ None,)}diff --git a/uzu/src/backends/metal/compilation_parameters.rs b/uzu/src/backends/metal/compilation_parameters.rsindex 3d9a9c8c0..3674ea12b 100644--- a/uzu/src/backends/metal/compilation_parameters.rs+++ b/uzu/src/backends/metal/compilation_parameters.rs@@ -1,6 +1,5 @@use mpsgraph::{- CompilationDescriptor, Optimization, OptimizationProfile,- device::MPSGraphComputeDevice,+ CompilationDescriptor, ComputeDevice, Optimization, OptimizationProfile,};use objc2::rc::Retained;@@ -22,14 +21,14 @@ pub fn make_compilation_descriptor(desc.set_print_ane_placement_analysis(preform_placement_analysis);match device {BlockDevice::Ane => {- desc.set_preferred_device(MPSGraphComputeDevice::ANE);+ desc.set_preferred_device(ComputeDevice::ANE);desc.set_allowed_compute_devices(- MPSGraphComputeDevice::ANE | MPSGraphComputeDevice::GPU,+ ComputeDevice::ANE | ComputeDevice::GPU,);},BlockDevice::Gpu => {- desc.set_preferred_device(MPSGraphComputeDevice::GPU);- desc.set_allowed_compute_devices(MPSGraphComputeDevice::GPU);+ desc.set_preferred_device(ComputeDevice::GPU);+ desc.set_allowed_compute_devices(ComputeDevice::GPU);},}descdiff --git a/uzu/src/backends/metal/forward_pass/transformer_layer.rs b/uzu/src/backends/metal/forward_pass/transformer_layer.rsindex 3182518ef..ad33e3b1d 100644--- a/uzu/src/backends/metal/forward_pass/transformer_layer.rs+++ b/uzu/src/backends/metal/forward_pass/transformer_layer.rs@@ -2,7 +2,7 @@ use std::{collections::HashMap, rc::Rc};use mpsgraph::{CompilationDescriptor, Device as MPSDevice, ExecutableExecutionDescriptor,- Graph, GraphTensorShapeOps,+ Graph,};use objc2::rc::{Retained, autoreleasepool};@@ -69,7 +69,8 @@ pub fn linear_block<const N: usize>(&MPSDevice::with_device(&context.device),&feeds,&[&output],- Some(compilation_descriptor),+ None,+ Some(&compilation_descriptor),);let arguments = IOArrays::new(@@ -116,7 +117,8 @@ pub fn mlp_block(&MPSDevice::with_device(&context.device),&feeds,&[&output],- Some(compilation_descriptor),+ None,+ Some(&compilation_descriptor),);let arguments = IOArrays::new(@@ -170,7 +172,8 @@ pub fn embed_block(&MPSDevice::with_device(&context.device),&feeds,&[&output],- Some(compilation_descriptor),+ None,+ Some(&compilation_descriptor),);let block = MPSGraphBlock::new(@@ -214,7 +217,8 @@ pub fn embed_block(&MPSDevice::with_device(&context.device),&feeds,&[&output],- Some(compilation_descriptor),+ None,+ Some(&compilation_descriptor),);let block = MPSGraphBlock::new(@@ -275,7 +279,8 @@ pub fn embed_block(&MPSDevice::with_device(&context.device),&feeds,&[&output],- Some(compilation_descriptor),+ None,+ Some(&compilation_descriptor),);let block = MPSGraphBlock::new(@@ -341,7 +346,8 @@ pub fn readout_block(&MPSDevice::with_device(&context.device),&feeds,&[&output],- Some(compilation_descriptor),+ None,+ Some(&compilation_descriptor),);let block = MPSGraphBlock::new(@@ -384,7 +390,8 @@ pub fn readout_block(&MPSDevice::with_device(&context.device),&feeds,&[&output],- Some(compilation_descriptor),+ None,+ Some(&compilation_descriptor),);let block = MPSGraphBlock::new(@@ -444,7 +451,8 @@ pub fn readout_block(&MPSDevice::with_device(&context.device),&feeds,&[&output],- Some(compilation_descriptor),+ None,+ Some(&compilation_descriptor),);let block = MPSGraphBlock::new(diff --git a/uzu/src/backends/metal/graph/common.rs b/uzu/src/backends/metal/graph/common.rsindex 6daee0c95..f2903b291 100644--- a/uzu/src/backends/metal/graph/common.rs+++ b/uzu/src/backends/metal/graph/common.rs@@ -1,12 +1,9 @@use std::rc::Rc;-use mpsgraph::{- Graph, GraphActivationOps, GraphArithmeticOps, Shape, ShapedType, Tensor,-};+use mpsgraph::{Graph, ShapedType, Tensor};use objc2::rc::Retained;use thiserror::Error;-use super::super::utils::mps_shape;use crate::{Array, DataType,backends::metal::{MTLContext, MetalArray},@@ -14,14 +11,6 @@ use crate::{parameters::{ParameterLoaderError, ParameterTree},};-pub fn mps_shape_to_isize(shape: &Shape) -> Box<[isize]> {- shape.dimensions().iter().map(|&d| d as isize).collect()-}--pub fn shape_of(tensor: &Tensor) -> Box<[isize]> {- mps_shape_to_isize(&tensor.shape())-}-pub fn data_type_of(tensor: &Tensor) -> DataType {DataType::from(tensor.data_type())}@@ -63,7 +52,7 @@ pub fn activation(match config {Activation::SILU => {let sigmoid_result = graph.sigmoid(input, Some("sigmoid"));- graph.multiply(input, &sigmoid_result, Some("silu_output"))+ graph.multiplication(input, &sigmoid_result, Some("silu_output"))},Activation::GELU => gelu(graph, input, data_type, true),}@@ -76,20 +65,24 @@ pub fn gelu(approximate: bool,) -> Retained<Tensor> {if approximate {- let input_power_2 = graph.multiply(input, input, None);- let input_power_3 = graph.multiply(&input_power_2, input, None);- let input_power_3_multiply_const = graph.multiply(- &graph.constant_with_scalar(0.044715 as f64, data_type.into()),+ let input_power_2 = graph.multiplication(input, input, None);+ let input_power_3 = graph.multiplication(&input_power_2, input, None);+ let input_power_3_multiply_const = graph.multiplication(+ &graph.constant_with_scalar(+ 0.044715 as f64,+ None,+ data_type.into(),+ ),&input_power_3,None,);let input_add_input_power_3_multiply_const =- graph.add(input, &input_power_3_multiply_const, None);- let tanh = GraphActivationOps::tanh(- graph,- &graph.multiply(+ graph.addition(input, &input_power_3_multiply_const, None);+ let tanh = graph.tanh(+ &graph.multiplication(&graph.constant_with_scalar((2.0 / std::f64::consts::PI).sqrt(),+ None,data_type.into(),),&input_add_input_power_3_multiply_const,@@ -97,47 +90,51 @@ pub fn gelu(),None,);- let tanh_add_one = graph.add(- &graph.constant_with_scalar(1.0 as f64, data_type.into()),+ let tanh_add_one = graph.addition(+ &graph.constant_with_scalar(1.0 as f64, None, data_type.into()),&tanh,None,);let input_multiply_tanh_add_one =- graph.multiply(input, &tanh_add_one, None);- let result = graph.multiply(+ graph.multiplication(input, &tanh_add_one, None);+ let result = graph.multiplication(&input_multiply_tanh_add_one,- &graph.constant_with_scalar(0.5 as f64, data_type.into()),+ &graph.constant_with_scalar(0.5 as f64, None, data_type.into()),None,);result} else {- let input_negative = graph.multiply(- &graph.constant_with_scalar(-1.0 as f64, data_type.into()),+ let input_negative = graph.multiplication(+ &graph.constant_with_scalar(-1.0 as f64, None, data_type.into()),input,None,);- let input_negative_divide_sqrt_2 = graph.divide(+ let input_negative_divide_sqrt_2 = graph.division(&input_negative,- &graph.constant_with_scalar((2.0 as f64).sqrt(), data_type.into()),+ &graph.constant_with_scalar(+ (2.0 as f64).sqrt(),+ None,+ data_type.into(),+ ),None,);let erf = graph.erf(&input_negative_divide_sqrt_2, None);- let erf_negative = graph.multiply(- &graph.constant_with_scalar(-1.0 as f64, data_type.into()),+ let erf_negative = graph.multiplication(+ &graph.constant_with_scalar(-1.0 as f64, None, data_type.into()),&erf,None,);- let erfc = graph.add(- &graph.constant_with_scalar(1.0 as f64, data_type.into()),+ let erfc = graph.addition(+ &graph.constant_with_scalar(1.0 as f64, None, data_type.into()),&erf_negative,None,);- let input_divide_2 = graph.divide(+ let input_divide_2 = graph.division(&input,- &graph.constant_with_scalar(2.0 as f64, data_type.into()),+ &graph.constant_with_scalar(2.0 as f64, None, data_type.into()),None,);- let result = graph.multiply(&input_divide_2, &erfc, None);+ let result = graph.multiplication(&input_divide_2, &erfc, None);result}}@@ -147,20 +144,14 @@ pub fn placeholder(shape: &[isize],data_type: DataType,) -> Retained<Tensor> {- let shape_i64: Box<[i64]> = shape.iter().map(|dim| *dim as i64).collect();- graph.placeholder(- data_type.into(),- &Shape::from_dimensions(&shape_i64),- Some("input"),- )+ graph.placeholder(Some(shape), data_type.into(), Some("input"))}pub fn shaped_type(shape: &[isize],data_type: DataType,) -> Retained<ShapedType> {- let shape_i64: Box<[i64]> = shape.iter().map(|dim| *dim as i64).collect();- ShapedType::new(&Shape::from_dimensions(&shape_i64), data_type.into())+ ShapedType::new_with_shape_data_type(Some(shape), data_type.into())}fn map_last_dimension<F: FnMut(usize) -> usize>(@@ -195,7 +186,7 @@ pub fn i4_constant_from_packed_u8_array(assert!(data.data_type() == DataType::U8);graph.constant_with_data(data.buffer(),- &mps_shape(&unpacked_shape_from_packed_shape(data.shape())),+ &unpacked_shape_from_packed_shape(data.shape()),DataType::I4.into(),)}@@ -229,7 +220,7 @@ pub fn load_constant(};graph.constant_with_data(parameter.buffer(),- &mps_shape(expected_shape),+ expected_shape,DataType::U4.into(),)} else {@@ -251,7 +242,7 @@ pub fn load_constant(};graph.constant_with_data(parameter.buffer(),- &mps_shape(parameter.shape()),+ parameter.shape(),parameter.data_type().into(),)};diff --git a/uzu/src/backends/metal/graph/embedding.rs b/uzu/src/backends/metal/graph/embedding.rsindex d6e6e8529..e712a35dd 100644--- a/uzu/src/backends/metal/graph/embedding.rs+++ b/uzu/src/backends/metal/graph/embedding.rs@@ -1,6 +1,4 @@-use mpsgraph::{- Graph, GraphGatherOps, GraphMatrixOps, GraphQuantizationOps, Tensor,-};+use mpsgraph::{DequantizationArguments, Graph, Tensor};use objc2::rc::Retained;use super::GraphConstructionError;@@ -11,16 +9,16 @@ pub fn embeddings_dequantize_weights_subgraph(weights: &Retained<Tensor>,scales: &Retained<Tensor>,) -> Result<Retained<Tensor>, GraphConstructionError> {- let result = graph- .dequantize_with_scale_tensor_zero_point_and_axis(- &weights,- &scales,- 0.0,- scales.data_type(),- 0,- None,- )- .unwrap();+ let result = graph.dequantize(+ &weights,+ DequantizationArguments::ScaleTensorZeroPointDataTypeAxis {+ scale_tensor: &scales,+ zero_point: 0.0,+ data_type: scales.data_type(),+ axis: 0,+ },+ None,+ );Ok(result)}@@ -30,11 +28,11 @@ pub fn embeddings_embed_subgraph(input: &Retained<Tensor>,weights: &Retained<Tensor>,) -> Result<Retained<Tensor>, GraphConstructionError> {- let result = graph.gather(weights, input, 0, 0, None);+ let result = graph.gather_with_updates(&weights, input, 0, 0, None);if let Some(scale) = config.common().input_scale {let scale_tensor =- graph.constant_with_scalar(scale as f64, result.data_type());- let scaled_result = graph.multiply(&result, &scale_tensor, None);+ graph.constant_with_scalar(scale as f64, None, result.data_type());+ let scaled_result = graph.multiplication(&result, &scale_tensor, None);Ok(scaled_result)} else {Ok(result)@@ -46,6 +44,6 @@ pub fn embeddings_readout_subgraph(input: &Retained<Tensor>,weights: &Retained<Tensor>,) -> Result<Retained<Tensor>, GraphConstructionError> {- let result = graph.matmul(input, weights, None);+ let result = graph.matrix_multiplication(input, weights, None);Ok(result)}diff --git a/uzu/src/backends/metal/graph/linear.rs b/uzu/src/backends/metal/graph/linear.rsindex 49af38f39..8255f86ec 100644--- a/uzu/src/backends/metal/graph/linear.rs+++ b/uzu/src/backends/metal/graph/linear.rs@@ -1,8 +1,6 @@use std::rc::Rc;-use mpsgraph::{- Graph, GraphMatrixOps, GraphQuantizationOps, GraphTensorShapeOps, Tensor,-};+use mpsgraph::{DequantizationArguments, Graph, Tensor};use objc2::rc::Retained;use super::{super::MTLContext, GraphConstructionError, load_constant};@@ -67,18 +65,16 @@ fn quantized_weights_subgraph<const N: usize>(DataType::U4,)?;- Ok(graph- .dequantize_with_scale_tensor_and_zero_point_tensor(- &weights,- &scales,- &zero_points,- <ConfigDataType as Into<DataType>>::into(- config.activation_precision,- )- .into(),- None,- )- .unwrap())+ let result = graph.dequantize(+ &weights,+ DequantizationArguments::ScaleTensorZeroPointTensorDataType {+ scale_tensor: &scales,+ zero_point_tensor: &zero_points,+ data_type: scales.data_type(),+ },+ None,+ );+ Ok(result)}fn biases_subgraph<const N: usize>(@@ -146,7 +142,7 @@ fn full_precision_matmul_subgraph<const N: usize>(parameter_tree,)?;Ok(graph.transpose(- &graph.matmul(+ &graph.matrix_multiplication(&graph.transpose(&weights, &[1, 0], None),&graph.transpose(input, &[1, 0], None),None,@@ -171,7 +167,7 @@ fn quantized_matmul_subgraph<const N: usize>(output_dims,parameter_tree,)?;- Ok(graph.matmul(input, &weights, None))+ Ok(graph.matrix_multiplication(input, &weights, None))}fn lora_subgraph<const N: usize>(@@ -193,7 +189,7 @@ fn lora_subgraph<const N: usize>()?;let lora_inner = graph.transpose(- &graph.matmul(+ &graph.matrix_multiplication(&graph.transpose(&lora_weights.down_weights, &[1, 0], None),&graph.transpose(input, &[1, 0], None),None,@@ -203,7 +199,7 @@ fn lora_subgraph<const N: usize>();let lora_inner_splits =- graph.split(&lora_inner, output_dims.len(), 1, None);+ graph.split_num_splits(&lora_inner, output_dims.len() as u64, 1, None);assert_eq!(lora_inner_splits.len(), lora_weights.up_weights.len());let lora_outputs = lora_inner_splits@@ -211,7 +207,7 @@ fn lora_subgraph<const N: usize>(.zip(lora_weights.up_weights.iter()).map(|(lora_inner_split, up_weights)| {graph.transpose(- &graph.matmul(+ &graph.matrix_multiplication(&graph.transpose(&up_weights, &[1, 0], None),&graph.transpose(&lora_inner_split, &[1, 0], None),None,@@ -228,6 +224,7 @@ fn lora_subgraph<const N: usize>(.map(|tensor| &**tensor).collect::<Box<[&Tensor]>>(),1,+ false,None,))}@@ -259,10 +256,11 @@ fn qlora_matmul_subgraph<const N: usize>(input,parameter_tree,)?;- let scaled_lora_result = graph.multiply(+ let scaled_lora_result = graph.multiplication(&lora_result,&graph.constant_with_scalar(lora_scale as f64,+ None,<ConfigDataType as Into<DataType>>::into(config.activation_precision,)@@ -270,7 +268,7 @@ fn qlora_matmul_subgraph<const N: usize>(),None,);- Ok(graph.add(&quantized_matmul_result, &scaled_lora_result, None))+ Ok(graph.addition(&quantized_matmul_result, &scaled_lora_result, None))}pub fn linear_subgraph<const N: usize>(@@ -325,7 +323,7 @@ pub fn linear_subgraph<const N: usize>(output_dims,parameter_tree,)?;- Ok(graph.add(&matmul_result, &biases, None))+ Ok(graph.addition(&matmul_result, &biases, None))} else {Ok(matmul_result)}diff --git a/uzu/src/backends/metal/graph/mlp.rs b/uzu/src/backends/metal/graph/mlp.rsindex f60a59650..d9b4884c3 100644--- a/uzu/src/backends/metal/graph/mlp.rs+++ b/uzu/src/backends/metal/graph/mlp.rs@@ -1,6 +1,6 @@use std::rc::Rc;-use mpsgraph::{Graph, Tensor, tensor_shape_ops::*};+use mpsgraph::{Graph, Tensor};use objc2::rc::Retained;use super::{@@ -30,7 +30,7 @@ pub fn mlp_subgraph(&up_tree,)?;- let split_results = graph.split(&fused_hidden_gate, 2, 1, None);+ let split_results = graph.split_num_splits(&fused_hidden_gate, 2, 1, None);let up_proj = &split_results[0];let gate = &split_results[1];@@ -40,7 +40,7 @@ pub fn mlp_subgraph(&*gate,config.linear_config.activation_precision().into(),);- let hidden = graph.multiply(&activated_gate, up_proj, None);+ let hidden = graph.multiplication(&activated_gate, up_proj, None);let result = linear_subgraph(graph,diff --git a/uzu/src/backends/metal/utils.rs b/uzu/src/backends/metal/utils.rsindex 91fd6225d..46306b3b0 100644--- a/uzu/src/backends/metal/utils.rs+++ b/uzu/src/backends/metal/utils.rs@@ -4,15 +4,6 @@ use std::{sync::{Arc, Mutex},};-use mpsgraph::Shape;-use num_traits::PrimInt;--pub fn mps_shape<T: PrimInt>(shape: &[T]) -> Shape {- let shape_i64: Box<[i64]> =- shape.iter().map(|d| d.to_i64().unwrap()).collect();- Shape::from_dimensions(&shape_i64)-}-bitflags::bitflags! {pub struct CaptureOptions: u8 {const STDOUT = 0b00000001;diff --git a/uzu/src/data_type.rs b/uzu/src/data_type.rsindex cbeca604a..15ef1970f 100644--- a/uzu/src/data_type.rs+++ b/uzu/src/data_type.rs@@ -55,17 +55,16 @@ impl From<MPSDataType> for DataType {MPSDataType::BFloat16 => DataType::BF16,MPSDataType::Float16 => DataType::F16,MPSDataType::Float32 => DataType::F32,- MPSDataType::Float64 => DataType::F64,MPSDataType::Int4 => DataType::I4,- MPSDataType::Uint4 => DataType::U4,+ MPSDataType::UInt4 => DataType::U4,MPSDataType::Int8 => DataType::I8,- MPSDataType::Uint8 => DataType::U8,+ MPSDataType::UInt8 => DataType::U8,MPSDataType::Int16 => DataType::I16,- MPSDataType::Uint16 => DataType::U16,+ MPSDataType::UInt16 => DataType::U16,MPSDataType::Int32 => DataType::I32,- MPSDataType::Uint32 => DataType::U32,+ MPSDataType::UInt32 => DataType::U32,MPSDataType::Int64 => DataType::I64,- MPSDataType::Uint64 => DataType::U64,+ MPSDataType::UInt64 => DataType::U64,_ => panic!("Unsupported MPS data type: {0:?}", dtype),}}@@ -77,17 +76,17 @@ impl From<DataType> for MPSDataType {DataType::BF16 => MPSDataType::BFloat16,DataType::F16 => MPSDataType::Float16,DataType::F32 => MPSDataType::Float32,- DataType::F64 => MPSDataType::Float64,DataType::I4 => MPSDataType::Int4,- DataType::U4 => MPSDataType::Uint4,+ DataType::U4 => MPSDataType::UInt4,DataType::I8 => MPSDataType::Int8,- DataType::U8 => MPSDataType::Uint8,+ DataType::U8 => MPSDataType::UInt8,DataType::I16 => MPSDataType::Int16,- DataType::U16 => MPSDataType::Uint16,+ DataType::U16 => MPSDataType::UInt16,DataType::I32 => MPSDataType::Int32,- DataType::U32 => MPSDataType::Uint32,+ DataType::U32 => MPSDataType::UInt32,DataType::I64 => MPSDataType::Int64,- DataType::U64 => MPSDataType::Uint64,+ DataType::U64 => MPSDataType::UInt64,+ _ => panic!("Unsupported MPS data type: {0:?}", dtype),}}}diff --git a/uzu/src/quant_matmul.rs b/uzu/src/quant_matmul.rsindex 1af7b884e..8601e2bf1 100644--- a/uzu/src/quant_matmul.rs+++ b/uzu/src/quant_matmul.rs@@ -14,9 +14,9 @@ use half::f16;use metal::Device;use mpsgraph::{CommandBuffer, CompilationDescriptor, DataType as MPSDataType,- Device as MPSDevice, Executable, ExecutableExecutionDescriptor, Graph,- GraphMatrixOps, GraphQuantizationOps, GraphTensorShapeOps, Optimization,- OptimizationProfile, ShapedType, Tensor, tensor_data::TensorData,+ DequantizationArguments, Device as MPSDevice, Executable,+ ExecutableExecutionDescriptor, ExecutableSerializationDescriptor, Graph,+ Optimization, OptimizationProfile, ShapedType, Tensor, TensorData,};use objc2::rc::Retained;use thiserror::Error;@@ -26,7 +26,6 @@ use crate::{backends::metal::{MTLContext, MetalArray,compilation_parameters::{BlockDevice, make_compilation_descriptor},- utils::mps_shape,},storage::{NSSearchPathDirectory, root_dir},};@@ -180,24 +179,24 @@ fn build_quantized_matmul(let s = tensor_options.scales.tensor();let zp = tensor_options.zeros.tensor();- let dequantized_weights = graph- .dequantize_with_scale_tensor_and_zero_point_tensor(- &w,- &s,- &zp,- MPSDataType::Float16,- None,- )- .ok_or(ExampleError::Dequantization)?;+ let dequantized_weights = graph.dequantize(+ &w,+ DequantizationArguments::ScaleTensorZeroPointTensorDataType {+ scale_tensor: &s,+ zero_point_tensor: &zp,+ data_type: MPSDataType::Float16,+ },+ None,+ );let matmul = if transposed_shapes {- graph.matmul(+ graph.matrix_multiplication(&i,&graph.transpose(&dequantized_weights, &[1, 0], None),None,)} else {- graph.matmul(+ graph.matrix_multiplication(&graph.transpose(&dequantized_weights, &[1, 0], None),&graph.transpose(&i, &[1, 0], None),None,@@ -213,7 +212,8 @@ fn build_quantized_matmul(&device,&feeds,&[&*matmul],- Some(compilation_descriptor),+ None,+ Some(&compilation_descriptor),);Ok(executable)@@ -229,17 +229,16 @@ fn make_tensor_option() -> TensorOption {match load_type {TensorLoadType::Baked => {- let tensor_const = graph.constant_with_data(- array.buffer(),- &mps_shape(shape),- dtype.into(),- );+ let tensor_const =+ graph.constant_with_data(array.buffer(), shape, dtype.into());TensorOption::Constant(tensor_const)},TensorLoadType::RuntimeLoaded => {let td = unsafe { array.to_mps_tensor_data() };+ let shape_isize: Vec<isize> =+ shape.iter().map(|d| *d as isize).collect();let placeholder =- graph.placeholder(dtype.into(), &mps_shape(shape), Some(name));+ graph.placeholder(Some(&shape_isize), dtype.into(), Some(name));TensorOption::Placeholder {placeholder,data: td,@@ -278,7 +277,7 @@ pub fn run_quant_matmul([input_dim / group_size, output_dim]};let zero_points_shape = scales_shape;- let input_shape = [-1_i64, input_dim as i64];+ let input_shape = [-1_isize, input_dim as isize];// Concrete shapes for actual buffer allocation at runtimelet input_tensor_shape = [suffix_length, input_dim];@@ -316,8 +315,8 @@ pub fn run_quant_matmul(// --- Tensor options for quantized matmul ---let input_tensor_data = unsafe { input_array.to_mps_tensor_data() };let input_placeholder = graph.placeholder(+ Some(&input_shape),DataType::F16.into(),- &mps_shape(&input_shape),Some("input_ph"),);@@ -380,8 +379,11 @@ pub fn run_quant_matmul(let package_path = root_dir(NSSearchPathDirectory::Downloads).join(format!("quant_matmul_experiments-{timestamp}.mpsgraphpackage"),);- let serialization_desc = mpsgraph::SerializationDescriptor::new();- executable.serialize_to_url(&package_path, &serialization_desc);+ let serialization_desc = ExecutableSerializationDescriptor::new();+ executable.serialize_to_graph_package(+ &package_path,+ Some(&serialization_desc),+ );}// --- Run & measure ---diff --git a/uzu/src/session/session.rs b/uzu/src/session/session.rsindex 6099afa30..d8d4ee61a 100644--- a/uzu/src/session/session.rs+++ b/uzu/src/session/session.rs@@ -1,7 +1,4 @@-use std::{- path::{Path, PathBuf},- time::Instant,-};+use std::{path::PathBuf, time::Instant};use objc2::rc::autoreleasepool;use tokenizers::Tokenizer;diff --git a/uzu/tests/split_tensor_datas_test.rs b/uzu/tests/split_tensor_datas_test.rsindex 1e399ebb0..2b801da02 100644--- a/uzu/tests/split_tensor_datas_test.rs+++ b/uzu/tests/split_tensor_datas_test.rs@@ -3,9 +3,8 @@ use std::collections::HashMap;use metal::{Device, MTLResourceOptions};use mpsgraph::{CommandBuffer, CompilationDescriptor, DataType as MPSDataType,- ExecutableExecutionDescriptor, Graph, GraphMatrixOps,- data_types::ShapedType, device::Device as MPSDevice, shape::Shape,- tensor_data::TensorData,+ Device as MPSDevice, ExecutableExecutionDescriptor, Graph, ShapedType,+ TensorData,};use ndarray::{Array2, ArrayView2};use uzu::{Array, DataType, backends::metal::MetalArray};@@ -127,10 +126,12 @@ fn test_row_split_no_copy_matmul() {b_buffer_size_bytes,MTLResourceOptions::StorageModeShared,);- let b_shape_dims =- Shape::from_dimensions(&[b_shape[0] as i64, b_shape[1] as i64]);- let b_td =- TensorData::from_buffer(&b_buffer, &b_shape_dims, MPSDataType::Float32);+ let b_td = TensorData::new_with_mtl_buffer(+ &b_buffer,+ &b_shape,+ MPSDataType::Float32,+ None,+ );let baseline =ndarray_matmul(a_shape[0], a_shape[1], b_shape[1], &a_data, &b_data);@@ -159,20 +160,34 @@ fn test_row_split_no_copy_matmul() {let graph = Graph::new();- let shape_a = Shape::from_dimensions(&[rows as i64, a_shape[1] as i64]);- let a_ph = graph.placeholder(MPSDataType::Float32, &shape_a, Some("A"));+ let shape_a_isize = [rows as isize, a_shape[1] as isize];+ let a_ph = graph.placeholder(+ Some(&shape_a_isize),+ MPSDataType::Float32,+ Some("A"),+ );- let shape_b =- Shape::from_dimensions(&[a_shape[1] as i64, b_shape[1] as i64]);- let b_ph = graph.placeholder(MPSDataType::Float32, &shape_b, Some("B"));+ let shape_b_isize = [a_shape[1] as isize, b_shape[1] as isize];+ let b_ph = graph.placeholder(+ Some(&shape_b_isize),+ MPSDataType::Float32,+ Some("B"),+ );- let c_tensor = graph.matmul(&a_ph, &b_ph, Some("MatMul"));+ let c_tensor =+ graph.matrix_multiplication(&a_ph, &b_ph, Some("MatMul"));let mps_device = MPSDevice::with_device(&device);let compilation_descriptor = CompilationDescriptor::new();- let a_shaped_type = ShapedType::new(&shape_a, MPSDataType::Float32);- let b_shaped_type = ShapedType::new(&shape_b, MPSDataType::Float32);+ let a_shaped_type = ShapedType::new_with_shape_data_type(+ Some(&shape_a_isize),+ MPSDataType::Float32,+ );+ let b_shaped_type = ShapedType::new_with_shape_data_type(+ Some(&shape_b_isize),+ MPSDataType::Float32,+ );let mut compile_feeds = HashMap::new();compile_feeds.insert(a_ph.as_ref(), a_shaped_type.as_ref());@@ -183,6 +198,7 @@ fn test_row_split_no_copy_matmul() {&mps_device,&compile_feeds,&targets,+ None,Some(&compilation_descriptor),);@@ -193,12 +209,12 @@ fn test_row_split_no_copy_matmul() {result_buffer_size,MTLResourceOptions::StorageModeShared,);- let result_shape =- Shape::from_dimensions(&[rows as i64, b_shape[1] as i64]);- let result_td = TensorData::from_buffer(+ let result_shape_usize = [rows, b_shape[1]];+ let result_td = TensorData::new_with_mtl_buffer(&result_buffer,- &result_shape,+ &result_shape_usize,MPSDataType::Float32,+ None,);let split_td = unsafe { split_array.to_mps_tensor_data() };