Minimal end-to-end example that:
- Defines a tiny model in Python MLX
- Exports it as a traced function (
.mlxfn) - Imports and runs it from Swift MLX on Apple Silicon
python_mlx_export.py– Python MLX script that exportstiny_mlp.mlxfnPackage.swift– SwiftPM package definition usingmlx-swiftSources/TinyMLXDemo/main.swift– Swift code that imports and runs the.mlxfn
-
Apple Silicon Mac (M-series)
-
Python with
mlxinstalled, e.g.:pip install mlx # or uv add mlx -
Xcode (with Command Line Tools)
Place python_mlx_export.py somewhere convenient and run:
python python_mlx_export.pyThis creates:
tiny_mlp.mlxfn
This .mlxfn file is the traced MLX function + parameters to be loaded from Swift.
From the directory where you want the Swift demo:
mkdir TinyMLXDemo
cd TinyMLXDemo
swift package init --type executableThen:
-
Replace the generated
Package.swiftwith thePackage.swiftfrom this gist. -
Replace
Sources/TinyMLXDemo/main.swiftwith themain.swiftfrom this gist. -
Copy the exported function file into the package root:
cp ../tiny_mlp.mlxfn .
Your tree should look like:
TinyMLXDemo/
Package.swift
tiny_mlp.mlxfn
Sources/
TinyMLXDemo/
main.swift
mlx-swift needs the Metal toolchain to build its GPU kernels. If you haven’t used Metal from Xcode on this machine before, run once:
sudo xcode-select -s /Applications/Xcode.app
xcodebuild -runFirstLaunch
sudo xcodebuild -downloadComponent MetalToolchainFrom inside TinyMLXDemo:
xcodebuild build -scheme TinyMLXDemo -destination 'platform=macOS'If the build succeeds, the executable is in:
~/Library/Developer/Xcode/DerivedData/TinyMLXDemo-*/Build/Products/Debug/TinyMLXDemo
Run it:
~/Library/Developer/Xcode/DerivedData/TinyMLXDemo-*/Build/Products/Debug/TinyMLXDemoYou should see output similar to:
TinyMLP output: [array([[-0.612043, -0.674903]], dtype=float32)]
This output comes from the Python-defined MLX model, exported as tiny_mlp.mlxfn and executed from Swift via importFunction(from:).