MLX is offering Python, C++ and Swift APIs for application developers. For iOS developers, we will mainly consume the Swift APIs. This tutorial is the first step to explore the MLX Swift API and some Swift examples provided by MLX repository.
The MLX Swift repository
The mlx-swift repository is provided as a Swift Package. This SPM integration makes it easy for iOS Developers to integrate the mlx-swift
into their existing project or other SPMs. And it supports also native SPM integration in Xcode.
We will clone the repository and update all submodules:
~ git clone https://github.com/ml-explore/mlx-swift.git
~ cd mlx-swift
~ git submodule init
~ git submodule update
NOTE: There is currently an open issue for supporting cocoapods. This support is especially important for folks using Flutter or React Native.
Build tutorial code
The Tutorial.swift file contains a very basic Swift code demonstrating how MLX Swift APIs work. It is basically a translation from C++ to Swift based on the tutorial.cpp file.
The Tutorial.swift
demonstrates how to use basic MLX types such as MLXArray
to describe a mathematic function. It also shows how to calculate the gradient of such a function, a very important term used in machine learning.
To build the tutorial, we will need to use xcodebuild
instead of swift build
command due to the metal shaders dependencies.
~ xcodebuild build -scheme Tutorial -destination 'platform=OS X' -derivedDataPath ./.derivedData
After the command completes, we will have our Tutorial
executable in the folder ./.derivedData/Build/Products/Debug/Tutorial
You can run the executable to check its result:
~ ./.derivedData/Build/Products/Debug/Tutorial
array([1, 2], dtype=float32)
array([3, 4], dtype=float32)
array([[2, 3],
[4, 5]], dtype=float32)
array(3, dtype=float32)
array(2, dtype=float32)