Skip to content

armgit / uzu

Public Imported from GitHub
0

A high-performance inference engine for AI models

performance benchmarks ios

eugene15661d4660a4
diff --git a/apps/benchmarks-ios/.gitignore b/apps/benchmarks-ios/.gitignore
new file mode 100644
index 000000000..4000004bf
--- /dev/null
+++ b/apps/benchmarks-ios/.gitignore
@@ -0,0 +1,4 @@
+/deps/
+*.xcodeproj
+*.xcworkspace
+Derived/
diff --git a/apps/benchmarks-ios/.swift-format b/apps/benchmarks-ios/.swift-format
new file mode 100644
index 000000000..1e089a50d
--- /dev/null
+++ b/apps/benchmarks-ios/.swift-format
@@ -0,0 +1,81 @@
+{
+ "fileScopedDeclarationPrivacy" : {
+ "accessLevel" : "private"
+ },
+ "indentConditionalCompilationBlocks" : true,
+ "indentSwitchCaseLabels" : false,
+ "indentation" : {
+ "spaces" : 4
+ },
+ "lineBreakAroundMultilineExpressionChainComponents" : false,
+ "lineBreakBeforeControlFlowKeywords" : false,
+ "lineBreakBeforeEachArgument" : false,
+ "lineBreakBeforeEachGenericRequirement" : false,
+ "lineBreakBetweenDeclarationAttributes" : false,
+ "lineLength" : 100,
+ "maximumBlankLines" : 1,
+ "multiElementCollectionTrailingCommas" : true,
+ "noAssignmentInExpressions" : {
+ "allowedFunctions" : [
+ "XCTAssertNoThrow"
+ ]
+ },
+ "prioritizeKeepingFunctionOutputTogether" : false,
+ "reflowMultilineStringLiterals" : {
+ "never" : {
+
+ }
+ },
+ "respectsExistingLineBreaks" : true,
+ "rules" : {
+ "AllPublicDeclarationsHaveDocumentation" : false,
+ "AlwaysUseLiteralForEmptyCollectionInit" : false,
+ "AlwaysUseLowerCamelCase" : true,
+ "AmbiguousTrailingClosureOverload" : true,
+ "AvoidRetroactiveConformances" : true,
+ "BeginDocumentationCommentWithOneLineSummary" : false,
+ "DoNotUseSemicolons" : true,
+ "DontRepeatTypeInStaticProperties" : true,
+ "FileScopedDeclarationPrivacy" : true,
+ "FullyIndirectEnum" : true,
+ "GroupNumericLiterals" : true,
+ "IdentifiersMustBeASCII" : true,
+ "NeverForceUnwrap" : false,
+ "NeverUseForceTry" : false,
+ "NeverUseImplicitlyUnwrappedOptionals" : false,
+ "NoAccessLevelOnExtensionDeclaration" : true,
+ "NoAssignmentInExpressions" : true,
+ "NoBlockComments" : true,
+ "NoCasesWithOnlyFallthrough" : true,
+ "NoEmptyLinesOpeningClosingBraces" : false,
+ "NoEmptyTrailingClosureParentheses" : true,
+ "NoLabelsInCasePatterns" : true,
+ "NoLeadingUnderscores" : false,
+ "NoParensAroundConditions" : true,
+ "NoPlaygroundLiterals" : true,
+ "NoVoidReturnOnFunctionSignature" : true,
+ "OmitExplicitReturns" : false,
+ "OneCasePerLine" : true,
+ "OneVariableDeclarationPerLine" : true,
+ "OnlyOneTrailingClosureArgument" : true,
+ "OrderedImports" : true,
+ "ReplaceForEachWithForLoop" : true,
+ "ReturnVoidInsteadOfEmptyTuple" : true,
+ "TypeNamesShouldBeCapitalized" : true,
+ "UseEarlyExits" : false,
+ "UseExplicitNilCheckInConditions" : true,
+ "UseLetInEveryBoundCaseVariable" : true,
+ "UseShorthandTypeNames" : true,
+ "UseSingleLinePropertyGetter" : true,
+ "UseSynthesizedInitializer" : true,
+ "UseTripleSlashForDocumentationComments" : true,
+ "UseWhereClausesInForLoops" : false,
+ "ValidateDocumentationComments" : false
+ },
+ "spacesAroundRangeFormationOperators" : false,
+ "spacesBeforeEndOfLineComments" : 2,
+ "tabWidth" : 8,
+ "version" : 1
+}
+
+
diff --git a/apps/benchmarks-ios/Project.swift b/apps/benchmarks-ios/Project.swift
new file mode 100644
index 000000000..eb07d55a8
--- /dev/null
+++ b/apps/benchmarks-ios/Project.swift
@@ -0,0 +1,93 @@
+import ProjectDescription
+
+let buildPythonPackages = TargetScript.pre(
+ script: """
+ env -i HOME="$HOME" ${DEVELOPER_DIR:+DEVELOPER_DIR="$DEVELOPER_DIR"} \\
+ PATH="$HOME/.cargo/bin:$HOME/.local/bin:/opt/homebrew/bin:/usr/bin:/bin:/usr/sbin:/sbin" \\
+ "$PROJECT_DIR/bootstrap.sh"
+ """,
+ name: "Build Python Packages",
+ basedOnDependencyAnalysis: false
+)
+
+let installPython = TargetScript.post(
+ script: """
+ set -euo pipefail
+ FRAMEWORKS="$CODESIGNING_FOLDER_PATH/Frameworks"
+ mkdir -p "$FRAMEWORKS"
+ rsync -a --delete --exclude Headers \\
+ "$PROJECT_DIR/deps/Python.xcframework/ios-arm64/Python.framework" "$FRAMEWORKS/"
+ rsync -a --delete "$PROJECT_DIR"/deps/Benchmarks*.framework "$FRAMEWORKS/"
+ rsync -a --delete "$PROJECT_DIR/app/" "$CODESIGNING_FOLDER_PATH/app/"
+ rsync -a --delete "$PROJECT_DIR/deps/envs/" "$CODESIGNING_FOLDER_PATH/envs/"
+ source "$PROJECT_DIR/deps/Python.xcframework/build/utils.sh"
+ install_python deps/Python.xcframework app envs
+ for environment in mlx omlx mtplx; do
+ mv "$CODESIGNING_FOLDER_PATH/envs/$environment/mlx/lib/mlx.metallib" \\
+ "$FRAMEWORKS/$environment.mlx.core.framework/"
+ done
+ /usr/bin/codesign --force --sign "$EXPANDED_CODE_SIGN_IDENTITY" -o runtime --timestamp=none \\
+ --preserve-metadata=identifier,entitlements,flags --generate-entitlement-der \\
+ "$FRAMEWORKS/Python.framework" "$FRAMEWORKS"/Benchmarks*.framework \\
+ "$FRAMEWORKS"/*.mlx.core.framework
+ """,
+ name: "Install Python",
+ outputPaths: [
+ "$(CODESIGNING_FOLDER_PATH)/Frameworks",
+ "$(CODESIGNING_FOLDER_PATH)/app",
+ "$(CODESIGNING_FOLDER_PATH)/envs",
+ "$(CODESIGNING_FOLDER_PATH)/python",
+ ],
+ basedOnDependencyAnalysis: false
+)
+
+let project = Project(
+ name: "Benchmarks",
+ organizationName: "Mirai",
+ targets: [
+ .target(
+ name: "Benchmarks",
+ destinations: [.iPhone, .iPad],
+ product: .app,
+ bundleId: "com.mirai.tech.benchmarks",
+ deploymentTargets: .iOS("26.4"),
+ infoPlist: .extendingDefault(with: [
+ "LSSupportsOpeningDocumentsInPlace": true,
+ "NSLocalNetworkUsageDescription":
+ "Receives benchmark requests from a Mac on the local network.",
+ "UIFileSharingEnabled": true,
+ "UILaunchScreen": [:],
+ ]),
+ sources: ["Sources/**"],
+ resources: ["Resources/AppIcon.icon"],
+ entitlements: .dictionary([
+ "com.apple.developer.kernel.increased-memory-limit": true
+ ]),
+ scripts: [buildPythonPackages, installPython],
+ settings: .settings(base: [
+ "CODE_SIGN_STYLE": "Automatic",
+ "DEVELOPMENT_TEAM": "C39GZ239GY",
+ "ENABLE_USER_SCRIPT_SANDBOXING": "NO",
+ "FRAMEWORK_SEARCH_PATHS": .array([
+ "$(PROJECT_DIR)/deps/Python.xcframework/ios-arm64", "$(PROJECT_DIR)/deps",
+ ]),
+ "OTHER_LDFLAGS": .array(
+ [
+ "Python", "BenchmarksUzu", "BenchmarksLlamacpp", "BenchmarksMldrift",
+ "BenchmarksMlxserve",
+ ]
+ .flatMap { ["-framework", $0] }
+ ),
+ "SUPPORTED_PLATFORMS": "iphoneos",
+ "SWIFT_OBJC_BRIDGING_HEADER": "Sources/BridgingHeader.h",
+ ])
+ )
+ ],
+ schemes: [
+ .scheme(
+ name: "Benchmarks",
+ buildAction: .buildAction(targets: ["Benchmarks"]),
+ runAction: .runAction(configuration: .release)
+ )
+ ]
+)
diff --git a/apps/benchmarks-ios/README.md b/apps/benchmarks-ios/README.md
new file mode 100644
index 000000000..7a8e9e550
--- /dev/null
+++ b/apps/benchmarks-ios/README.md
@@ -0,0 +1,70 @@
+# Benchmarks for iOS
+
+Runs the inference benchmarks of [scripts/benchmarks](../../scripts/benchmarks) on an iPhone or iPad. A Mac controls the app through [platform-ios](../../scripts/benchmarks/platform-ios), which behaves like any other engine process, so the benchmark harness can target the device. On the device, the Log tab follows the current run, the Models tab lists the cached models and their sizes, and the bar at the bottom shows the server state.
+
+Engines, the same as in `scripts/benchmarks`, each started through its command-line entry inside the app:
+
+- `llamacpp`: `engine-llamacpp`, built with CMake as `BenchmarksLlamacpp.framework`.
+- `mldrift`: `engine-mldrift`, built with Bazel as `BenchmarksMldrift.framework`.
+- `mlxserve`: `engine-mlxserve`, built with Zig and linked with MLX and mlx-c into `BenchmarksMlxserve.framework`. [patches/zig-ios-null-file.patch](patches/zig-ios-null-file.patch) backports a Zig 0.17.0 fix for iOS.
+- `mlx`, `mtplx`, `omlx`, `splash`: the Python adapters on CPython 3.13, each in its own environment installed from its `uv.lock`. Splash's native engine runs in the app through `engine-splash/patches/in-process.patch`; its only models, Qwen3.8-27B and Qwen3.6-35B-A3B, do not fit a 12 GB iPhone.
+- `uzu`: `engine-uzu`, built as `BenchmarksUzu.framework`.
+
+## Set up
+
+On the Mac:
+
+- Xcode 27 or newer, signed in with an account of the Mirai team and selected for the command line: `sudo xcode-select -s /Applications/Xcode.app`. Then its Metal Toolchain component: `xcodebuild -downloadComponent MetalToolchain`.
+- [Tuist](https://tuist.dev), [uv](https://docs.astral.sh/uv/), CMake, bazelisk and the Hugging Face CLI: `brew install tuist uv cmake bazelisk hf`.
+- rustup from [rustup.rs](https://rustup.rs), in its default `~/.cargo`; the build finds tools only in `~/.cargo/bin`, `~/.local/bin` and `/opt/homebrew/bin`. Python packages with Rust code build with the stable toolchain: `rustup toolchain install stable && rustup target add aarch64-apple-ios --toolchain stable`.
+
+On the iPhone or iPad:
+
+- iOS 26.4 or newer, Developer Mode on (Settings, Privacy & Security), and paired with the Mac: connect it once with a cable and trust the Mac.
+- The first run of the `Benchmarks` scheme from Xcode registers the device with the Mirai team and installs the app. After that, `bench-ios` launches the installed app.
+
+## Build
+
+```bash
+cd apps/benchmarks-ios
+tuist generate
+```
+
+Then run the `Benchmarks` scheme on a device; simulators are not supported.
+
+`Build Python Packages` runs [bootstrap.sh](bootstrap.sh), which builds the engine frameworks, cross-compiles the native Python packages for iOS, MLX with [patches/mlx.patch](patches/mlx.patch), and installs each Python engine's `uv.lock` into `deps/envs/<engine>`, without `hf-xet`, whose downloads stall on iOS. The first build takes several minutes. `Install Python` embeds Python, the engine frameworks and the environments into the app.
+
+## Run from a Mac
+
+`bench-ios` benchmarks on one device, chosen by its UDID. Pass it with `--device UDID`, or let `bench-ios` ask: the first command without `--device` lists the paired iPhones and iPads and asks which one to use. The choice is saved in `~/.cache/bench-ios/device` and used until another is chosen with `bench-ios device` or `--device`. Without a terminal, as in CI, pass `--device`.
+
+The app listens on port 7171 while it is open and keeps the screen awake. `bench-ios` reaches it over USB, over Wi-Fi to a paired device, through the CoreDevice tunnel, or at an address given with `--host`. Unless `--host` is given, commands that talk to the app bring it to the foreground first, since iOS suspends it in the background, and `run` and `download` start a fresh app process, as a new engine process starts on macOS. Arguments after `--` go to the engine's command line. Keep the device unlocked.
+
+`-m` takes the model as each engine expects it: MLX, mlx-serve, MTPLX and oMLX a Hugging Face repository; llama.cpp and Splash a GGUF repository with a quantization, such as `unsloth/Qwen3.5-0.8B-GGUF:Q4_K_M`; ML Drift a pushed directory; uzu a registry identifier such as `trymirai/LFM2.5-230M-M`.
+
+Before `run` and `download`, `bench-ios` skips a model that does not fit, with the rule of the macOS benchmark runner: the model's Hugging Face files, or for llama.cpp any GGUF file of the repository, must take at most 75% of the device's memory. For Splash it counts the chosen GGUF variant and the larger of Splash's draft models, since the draft follows the target's configuration. Pushed models and other local paths are not checked.
+
+```bash
+cd scripts/benchmarks
+uv run --project platform-ios bench-ios device
+uv run --project platform-ios bench-ios push trymirai/LFM2.5-230M-M
+uv run --project platform-ios bench-ios download -e mlx -m LiquidAI/LFM2.5-230M-MLX-4bit
+uv run --project platform-ios bench-ios models
+uv run --project platform-ios bench-ios run -e uzu -m trymirai/LFM2.5-230M-M <<'EOF'
+{"prompt_chat": [{"role": "user", "content": "Tell me about London"}], "max_tokens": 256, "num_runs": 3}
+EOF
+uv run pytest --engine ios --ios-engine uzu
+```
+
+`push` copies a model that is already on this Mac, so the device does not download it: a uzu registry identifier from `~/.cache/mirai`, after the model has run on this Mac; a Hugging Face repository from the Hugging Face cache, after `hf download` or a run on this Mac; or a directory, which lands in the app's Documents folder and is referenced as `models/<name>`. `delete` takes a path that `models` reports.
+
+ML Drift's weight converter does not run on the device, so `mldrift` runs only pushed models. Convert one with `engine-mldrift/run.sh` on this Mac, then push the converted weights together with the checkpoint's other files:
+
+```bash
+./engine-mldrift/run.sh -m Qwen/Qwen3-0.6B </dev/null
+staging="$(mktemp -d)/Qwen3-0.6B-mldrift"
+cp -R "$(ls -td engine-mldrift/workspace/*/q4_0/* | head -1)" "$staging"
+rsync -aL --exclude '*.safetensors' "$(hf download --quiet Qwen/Qwen3-0.6B)/" "$staging/"
+uv run --project platform-ios bench-ios push "$staging"
+uv run pytest --engine ios --ios-engine mldrift --ios-model models/Qwen3-0.6B-mldrift
+```
diff --git a/apps/benchmarks-ios/Resources/AppIcon.icon/Assets/Accent.svg b/apps/benchmarks-ios/Resources/AppIcon.icon/Assets/Accent.svg
new file mode 100644
index 000000000..fa1d43933
--- /dev/null
+++ b/apps/benchmarks-ios/Resources/AppIcon.icon/Assets/Accent.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 1024 1024"><path d="M682 240L722 280L682 320L642 280Z" fill="#FF5E00"/></svg>
diff --git a/apps/benchmarks-ios/Resources/AppIcon.icon/Assets/Lines.svg b/apps/benchmarks-ios/Resources/AppIcon.icon/Assets/Lines.svg
new file mode 100644
index 000000000..3dc56c251
--- /dev/null
+++ b/apps/benchmarks-ios/Resources/AppIcon.icon/Assets/Lines.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 1024 1024"><path d="M232 0V1024M792 0V1024M0 232H1024M0 792H1024" stroke="#D9D8D4" stroke-width="3"/></svg>
diff --git a/apps/benchmarks-ios/Resources/AppIcon.icon/Assets/Stems.svg b/apps/benchmarks-ios/Resources/AppIcon.icon/Assets/Stems.svg
new file mode 100644
index 000000000..7ba783a20
--- /dev/null
+++ b/apps/benchmarks-ios/Resources/AppIcon.icon/Assets/Stems.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 1024 1024"><g fill="#0A0A0A"><rect x="292" y="536" width="100" height="168"/><rect x="462" y="440" width="100" height="264"/><rect x="632" y="344" width="100" height="360"/><path d="M342 432L382 472L342 512L302 472Z"/><path d="M512 336L552 376L512 416L472 376Z"/></g></svg>
diff --git a/apps/benchmarks-ios/Resources/AppIcon.icon/Assets/Ticks.svg b/apps/benchmarks-ios/Resources/AppIcon.icon/Assets/Ticks.svg
new file mode 100644
index 000000000..a5f992719
--- /dev/null
+++ b/apps/benchmarks-ios/Resources/AppIcon.icon/Assets/Ticks.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 1024 1024"><g fill="#0A0A0A"><rect x="226" y="226" width="12" height="12"/><rect x="786" y="226" width="12" height="12"/><rect x="226" y="786" width="12" height="12"/><rect x="786" y="786" width="12" height="12"/></g></svg>
diff --git a/apps/benchmarks-ios/Resources/AppIcon.icon/icon.json b/apps/benchmarks-ios/Resources/AppIcon.icon/icon.json
new file mode 100644
index 000000000..4e11bcf74
--- /dev/null
+++ b/apps/benchmarks-ios/Resources/AppIcon.icon/icon.json
@@ -0,0 +1,107 @@
+{
+ "fill": {
+ "solid": "srgb:0.94902,0.94510,0.92941,1.00000"
+ },
+ "fill-specializations": [
+ {
+ "appearance": "dark",
+ "value": {
+ "solid": "srgb:0.03922,0.03922,0.03922,1.00000"
+ }
+ }
+ ],
+ "groups": [
+ {
+ "layers": [
+ {
+ "fill-specializations": [
+ {
+ "appearance": "dark",
+ "value": {
+ "solid": "srgb:1.00000,0.36863,0.00000,1.00000"
+ }
+ }
+ ],
+ "glass": true,
+ "image-name": "Accent.svg",
+ "name": "Accent"
+ },
+ {
+ "fill-specializations": [
+ {
+ "appearance": "dark",
+ "value": {
+ "solid": "srgb:0.94902,0.94510,0.92941,1.00000"
+ }
+ },
+ {
+ "appearance": "tinted",
+ "value": {
+ "solid": "srgb:0.94902,0.94510,0.92941,1.00000"
+ }
+ }
+ ],
+ "glass": true,
+ "image-name": "Stems.svg",
+ "name": "Stems"
+ }
+ ],
+ "shadow": {
+ "kind": "neutral",
+ "opacity": 0.5
+ },
+ "specular": true,
+ "translucency": {
+ "enabled": false,
+ "value": 0.5
+ }
+ },
+ {
+ "layers": [
+ {
+ "fill-specializations": [
+ {
+ "appearance": "dark",
+ "value": {
+ "solid": "srgb:0.94902,0.94510,0.92941,1.00000"
+ }
+ },
+ {
+ "appearance": "tinted",
+ "value": {
+ "solid": "srgb:0.94902,0.94510,0.92941,1.00000"
+ }
+ }
+ ],
+ "glass": false,
+ "image-name": "Ticks.svg",
+ "name": "Ticks"
+ },
+ {
+ "fill-specializations": [
+ {
+ "appearance": "dark",
+ "value": {
+ "solid": "srgb:0.16863,0.16863,0.16078,1.00000"
+ }
+ }
+ ],
+ "glass": false,
+ "image-name": "Lines.svg",
+ "name": "Lines"
+ }
+ ],
+ "shadow": {
+ "kind": "none",
+ "opacity": 0
+ },
+ "translucency": {
+ "enabled": false,
+ "value": 0
+ }
+ }
+ ],
+ "supported-platforms": {
+ "squares": "shared"
+ }
+}
diff --git a/apps/benchmarks-ios/Sources/BenchmarkServer.swift b/apps/benchmarks-ios/Sources/BenchmarkServer.swift
new file mode 100644
index 000000000..0bd12442a
--- /dev/null
+++ b/apps/benchmarks-ios/Sources/BenchmarkServer.swift
@@ -0,0 +1,140 @@
+import Foundation
+import Network
+
+final class BenchmarkServer {
+ static let port: NWEndpoint.Port = 7171
+
+ private struct Command: Decodable {
+ let command: String
+ let engine: Engine?
+ let arguments: [String]?
+ let path: String?
+ }
+
+ private enum Failure: Error {
+ case invalid(String)
+ case busy
+ }
+
+ private let benchmarks: Benchmarks
+ private let listener: NWListener
+
+ init(benchmarks: Benchmarks) throws {
+ self.benchmarks = benchmarks
+ listener = try NWListener(using: .tcp, on: Self.port)
+ listener.stateUpdateHandler = { state in
+ DispatchQueue.main.async {
+ switch state {
+ case .ready:
+ benchmarks.status = "Listening on port \(Self.port)"
+ case .failed(let error):
+ benchmarks.status = "Server failed: \(error)"
+ default:
+ break
+ }
+ }
+ }
+ listener.newConnectionHandler = { [unowned self] connection in
+ connection.start(queue: DispatchQueue(label: "BenchmarkServer.connection"))
+ readCommand(connection, buffer: Data())
+ }
+ listener.start(queue: DispatchQueue(label: "BenchmarkServer"))
+ }
+
+ private func readCommand(_ connection: NWConnection, buffer: Data) {
+ connection.receive(minimumIncompleteLength: 1, maximumLength: 1 << 16) {
+ data, _, isComplete, error in
+ let buffer = buffer + (data ?? Data())
+ if let newline = buffer.firstIndex(of: UInt8(ascii: "\n")) {
+ let line = buffer[..<newline]
+ let rest = Data(buffer[buffer.index(after: newline)...])
+ DispatchQueue.main.async { self.handle(line, rest: rest, connection) }
+ } else if isComplete || error != nil {
+ connection.cancel()
+ } else {
+ self.readCommand(connection, buffer: buffer)
+ }
+ }
+ }
+
+ private func handle(_ line: Data, rest: Data, _ connection: NWConnection) {
+ let send = { (kind: UInt8, payload: Data) in
+ var frame = Data([kind])
+ withUnsafeBytes(of: UInt32(payload.count).bigEndian) { frame.append(contentsOf: $0) }
+ connection.send(content: frame + payload, completion: .idempotent)
+ }
+ let finish = { (status: Int32) in
+ withUnsafeBytes(of: status.bigEndian) { send(3, Data($0)) }
+ }
+ do {
+ let command = try JSONDecoder().decode(Command.self, from: line)
+ switch (command.command, command.engine, command.arguments, command.path) {
+ case ("models", _, _, _):
+ benchmarks.refresh()
+ send(1, try JSONEncoder().encode(benchmarks.models) + Data("\n".utf8))
+ case ("device", _, _, _):
+ let device = ["physical_memory_bytes": ProcessInfo.processInfo.physicalMemory]
+ send(1, try JSONEncoder().encode(device) + Data("\n".utf8))
+ case ("delete", _, _, let path?):
+ try benchmarks.delete(path: path)
+ case ("run", let engine?, let arguments?, _):
+ let job = { engine.run(arguments: arguments) }
+ let input = { (handle: FileHandle) in
+ DispatchQueue.global().async { self.forward(connection, rest, to: handle) }
+ }
+ guard benchmarks.start(job, input: input, output: send, completion: finish) else {
+ throw Failure.busy
+ }
+ return
+ default:
+ throw Failure.invalid(String(decoding: line, as: UTF8.self))
+ }
+ finish(0)
+ drain(connection)
+ } catch {
+ send(2, Data("\(error)\n".utf8))
+ finish(1)
+ drain(connection)
+ }
+ }
+
+ private func drain(_ connection: NWConnection) {
+ connection.receive(minimumIncompleteLength: 1, maximumLength: 1 << 16) {
+ _, _, isComplete, error in
+ if isComplete || error != nil {
+ connection.cancel()
+ } else {
+ self.drain(connection)
+ }
+ }
+ }
+
+ private func forward(_ connection: NWConnection, _ buffer: Data, to handle: FileHandle) {
+ var buffer = buffer
+ while buffer.count >= 4 {
+ let length = Int(buffer.prefix(4).reduce(UInt32(0)) { $0 << 8 | UInt32($1) })
+ guard buffer.count >= 4 + length else {
+ break
+ }
+ guard length > 0,
+ (try? handle.write(contentsOf: buffer.dropFirst(4).prefix(length))) != nil
+ else {
+ try? handle.close()
+ drain(connection)
+ return
+ }
+ buffer = Data(buffer.dropFirst(4 + length))
+ }
+ connection.receive(minimumIncompleteLength: 1, maximumLength: 1 << 16) {
+ data, _, isComplete, error in
+ if let data, !data.isEmpty {
+ self.forward(connection, buffer + data, to: handle)
+ } else if isComplete || error != nil {
+ try? handle.close()
+ connection.cancel()
+ } else {
+ self.forward(connection, buffer, to: handle)
+ }
+ }
+ }
+}
diff --git a/apps/benchmarks-ios/Sources/Benchmarks.swift b/apps/benchmarks-ios/Sources/Benchmarks.swift
new file mode 100644
index 000000000..fa1b292ec
--- /dev/null
+++ b/apps/benchmarks-ios/Sources/Benchmarks.swift
@@ -0,0 +1,56 @@
+import Foundation
+import Observation
+
+@Observable
+final class Benchmarks {
+ var status = "Starting server"
+ private(set) var running = false
+ private(set) var models = ModelStore.list()
+ private var transcript = Data()
+
+ var log: String {
+ String(decoding: transcript, as: UTF8.self)
+ }
+
+ func start(
+ _ job: @escaping () -> Int32,
+ input: @escaping (FileHandle) -> Void,
+ output: @escaping (UInt8, Data) -> Void,
+ completion: @escaping (Int32) -> Void
+ ) -> Bool {
+ guard !running else {
+ return false
+ }
+ running = true
+ transcript = Data()
+ let thread = Thread {
+ let status = StandardStreams.run(
+ input: input,
+ output: { stream, data in
+ output(stream, data)
+ DispatchQueue.main.async {
+ self.transcript = (self.transcript + data).suffix(1 << 16)
+ }
+ },
+ job
+ )
+ DispatchQueue.main.async {
+ self.running = false
+ self.refresh()
+ completion(status)
+ }
+ }
+ thread.stackSize = 1 << 24
+ thread.start()
+ return true
+ }
+
+ func delete(path: String) throws {
+ try ModelStore.delete(path: path)
+ refresh()
+ }
+
+ func refresh() {
+ models = ModelStore.list()
+ }
+}
diff --git a/apps/benchmarks-ios/Sources/BenchmarksApp.swift b/apps/benchmarks-ios/Sources/BenchmarksApp.swift
new file mode 100644
index 000000000..e74a512d8
--- /dev/null
+++ b/apps/benchmarks-ios/Sources/BenchmarksApp.swift
@@ -0,0 +1,28 @@
+import SwiftUI
+
+@main
+struct BenchmarksApp: App {
+ @State private var benchmarks = Benchmarks()
+ @State private var server: BenchmarkServer?
+
+ init() {
+ signal(SIGPIPE, SIG_IGN)
+ setenv("HOME", URL.cachesDirectory.path, 1)
+ setenv("SSL_CERT_FILE", "\(Bundle.main.resourcePath!)/envs/mlx/certifi/cacert.pem", 1)
+ FileManager.default.changeCurrentDirectoryPath(URL.documentsDirectory.path)
+ }
+
+ var body: some Scene {
+ WindowGroup {
+ ContentView(benchmarks: benchmarks)
+ .task {
+ UIApplication.shared.isIdleTimerDisabled = true
+ do {
+ server = try BenchmarkServer(benchmarks: benchmarks)
+ } catch {
+ benchmarks.status = "Server failed: \(error)"
+ }
+ }
+ }
+ }
+}
diff --git a/apps/benchmarks-ios/Sources/BridgingHeader.h b/apps/benchmarks-ios/Sources/BridgingHeader.h
new file mode 100644
index 000000000..a7ccd8acd
--- /dev/null
+++ b/apps/benchmarks-ios/Sources/BridgingHeader.h
@@ -0,0 +1,6 @@
+#include <Python/Python.h>
+
+int benchmarks_llamacpp_main(int argc, char** argv);
+int benchmarks_mldrift_main(int argc, char** argv);
+int benchmarks_mlxserve_main(int argc, char** argv);
+int benchmarks_uzu_main(int argc, char** argv);
diff --git a/apps/benchmarks-ios/Sources/ContentView.swift b/apps/benchmarks-ios/Sources/ContentView.swift
new file mode 100644
index 000000000..54b2e1c94
--- /dev/null
+++ b/apps/benchmarks-ios/Sources/ContentView.swift
@@ -0,0 +1,67 @@
+import SwiftUI
+
+struct ContentView: View {
+ let benchmarks: Benchmarks
+
+ var body: some View {
+ TabView {
+ Tab("Log", systemImage: "text.alignleft") {
+ NavigationStack {
+ log.navigationTitle("Log")
+ }
+ }
+ Tab("Models", systemImage: "shippingbox") {
+ NavigationStack {
+ models.navigationTitle("Models")
+ }
+ }
+ }
+ .tabBarMinimizeBehavior(.onScrollDown)
+ .tabViewBottomAccessory {
+ HStack {
+ Text(benchmarks.status)
+ Spacer()
+ if benchmarks.running {
+ ProgressView()
+ }
+ }
+ .font(.footnote)
+ .padding(.horizontal)
+ }
+ }
+
+ private var log: some View {
+ ScrollView {
+ Text(benchmarks.log)
+ .font(.caption.monospaced())
+ .textSelection(.enabled)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .padding()
+ }
+ .defaultScrollAnchor(.bottom)
+ .toolbar {
+ ShareLink(item: benchmarks.log)
+ }
+ .overlay {
+ if benchmarks.log.isEmpty {
+ ContentUnavailableView(
+ "Waiting for the Mac", systemImage: "laptopcomputer.and.iphone",
+ description: Text("Run benchmarks with bench-ios from scripts/benchmarks."))
+ }
+ }
+ }
+
+ private var models: some View {
+ List(benchmarks.models) { model in
+ LabeledContent(
+ model.name,
+ value: ByteCountFormatter.string(fromByteCount: model.bytes, countStyle: .file))
+ }
+ .overlay {
+ if benchmarks.models.isEmpty {
+ ContentUnavailableView("No cached models", systemImage: "shippingbox")
+ }
+ }
+ .refreshable { benchmarks.refresh() }
+ }
+}
diff --git a/apps/benchmarks-ios/Sources/Engine.swift b/apps/benchmarks-ios/Sources/Engine.swift
new file mode 100644
index 000000000..8c313d6a1
--- /dev/null
+++ b/apps/benchmarks-ios/Sources/Engine.swift
@@ -0,0 +1,69 @@
+import Foundation
+
+enum Engine: String, Codable {
+ case llamacpp
+ case mldrift
+ case mlx
+ case mlxserve
+ case mtplx
+ case omlx
+ case splash
+ case uzu
+
+ func run(arguments: [String]) -> Int32 {
+ switch self {
+ case .llamacpp:
+ Self.main(benchmarks_llamacpp_main, ["engine-llamacpp"] + arguments)
+ case .mldrift:
+ Self.mldrift(arguments)
+ case .mlx:
+ PythonRuntime.main("mlx", "bench_mlx", arguments)
+ case .mlxserve:
+ Self.mlxserve(arguments)
+ case .mtplx:
+ PythonRuntime.main("mtplx", "bench_mtplx", arguments)
+ case .omlx:
+ PythonRuntime.main("omlx", "bench_omlx", arguments)
+ case .splash:
+ PythonRuntime.main("splash", "bench_splash", arguments)
+ case .uzu:
+ Self.main(benchmarks_uzu_main, ["benchmarks-uzu"] + arguments)
+ }
+ }
+
+ private static func mldrift(_ arguments: [String]) -> Int32 {
+ guard arguments.count == 2, ["-m", "--model"].contains(arguments[0]) else {
+ fputs("Usage: engine-mldrift -m DIRECTORY\n", stderr)
+ return 2
+ }
+ let directory = arguments[1]
+ guard FileManager.default.fileExists(atPath: "\(directory)/layer_info.txt") else {
+ fputs("\(directory) has no ML Drift weights; convert them on a Mac\n", stderr)
+ return 2
+ }
+ return main(
+ benchmarks_mldrift_main,
+ ["engine-mldrift", "--checkpoint=\(directory)", "--weights=\(directory)"])
+ }
+
+ private static func mlxserve(_ arguments: [String]) -> Int32 {
+ let paths = PythonRuntime.modelPaths(arguments)
+ guard !paths.isEmpty else {
+ return 1
+ }
+ return main(benchmarks_mlxserve_main, ["engine-mlxserve"] + paths)
+ }
+
+ private static func main(
+ _ entry: (Int32, UnsafeMutablePointer<UnsafeMutablePointer<CChar>?>?) -> Int32,
+ _ arguments: [String]
+ ) -> Int32 {
+ var argv = arguments.map { strdup($0) } + [nil]
+ defer {
+ for argument in argv {
+ free(argument)
+ }
+ }
+ return entry(Int32(arguments.count), &argv)
+ }
+}
diff --git a/apps/benchmarks-ios/Sources/ModelStore.swift b/apps/benchmarks-ios/Sources/ModelStore.swift
new file mode 100644
index 000000000..0934c16fc
--- /dev/null
+++ b/apps/benchmarks-ios/Sources/ModelStore.swift
@@ -0,0 +1,59 @@
+import Foundation
+
+struct CachedModel: Identifiable, Encodable {
+ let name: String
+ let path: String
+ let bytes: Int64
+
+ var id: String { path }
+}
+
+enum ModelStore {
+ private enum Failure: Error {
+ case notCached(String)
+ }
+
+ static func list() -> [CachedModel] {
+ let caches = URL.cachesDirectory.appending(path: ".cache")
+ var models: [CachedModel] = []
+ for url in contents(caches.appending(path: "huggingface/hub"))
+ where url.lastPathComponent.hasPrefix("models--") {
+ let repository = url.lastPathComponent.trimmingPrefix("models--")
+ models.append(model(String(repository.replacing("--", with: "/")), url))
+ }
+ for vendor in contents(caches.appending(path: "mirai/models")) {
+ for url in contents(vendor) {
+ models.append(model(url.lastPathComponent, url))
+ }
+ }
+ for url in contents(URL.documentsDirectory.appending(path: "models")) {
+ models.append(model("models/\(url.lastPathComponent)", url))
+ }
+ return models
+ }
+
+ static func delete(path: String) throws {
+ guard list().contains(where: { $0.path == path }) else {
+ throw Failure.notCached(path)
+ }
+ try FileManager.default.removeItem(atPath: path)
+ }
+
+ private static func model(_ name: String, _ url: URL) -> CachedModel {
+ var bytes: Int64 = 0
+ let files = FileManager.default.enumerator(
+ at: url, includingPropertiesForKeys: [.totalFileAllocatedSizeKey])
+ while let file = files?.nextObject() as? URL {
+ bytes += Int64(
+ (try? file.resourceValues(forKeys: [.totalFileAllocatedSizeKey])
+ .totalFileAllocatedSize) ?? 0)
+ }
+ return CachedModel(name: name, path: url.path, bytes: bytes)
+ }
+
+ private static func contents(_ url: URL) -> [URL] {
+ let urls = try? FileManager.default.contentsOfDirectory(
+ at: url, includingPropertiesForKeys: nil, options: .skipsHiddenFiles)
+ return (urls ?? []).sorted { $0.lastPathComponent < $1.lastPathComponent }
+ }
+}
diff --git a/apps/benchmarks-ios/Sources/PythonRuntime.swift b/apps/benchmarks-ios/Sources/PythonRuntime.swift
new file mode 100644
index 000000000..a84d10089
--- /dev/null
+++ b/apps/benchmarks-ios/Sources/PythonRuntime.swift
@@ -0,0 +1,90 @@
+import Foundation
+import os
+
+enum PythonRuntime {
+ private static let environment = OSAllocatedUnfairLock<String?>(initialState: nil)
+
+ @discardableResult
+ private static func start(_ environment: String) -> String {
+ Self.environment.withLock { running in
+ if running == nil {
+ DispatchQueue.main.sync {
+ var preconfig = PyPreConfig()
+ PyPreConfig_InitIsolatedConfig(&preconfig)
+ preconfig.utf8_mode = 1
+ check(Py_PreInitialize(&preconfig))
+
+ let config = UnsafeMutablePointer<PyConfig>.allocate(capacity: 1)
+ defer { config.deallocate() }
+ PyConfig_InitIsolatedConfig(config)
+ config.pointee.write_bytecode = 0
+ let home = "\(Bundle.main.resourcePath!)/python"
+ check(PyConfig_SetBytesString(config, &config.pointee.home, home))
+ check(Py_InitializeFromConfig(config))
+ PyConfig_Clear(config)
+ PyRun_SimpleStringFlags(
+ """
+ import os, site, sys
+ bundle = os.path.dirname(sys.executable)
+ sys.path.insert(0, os.path.join(bundle, "app"))
+ site.addsitedir(os.path.join(bundle, "envs", "\(environment)"))
+ """,
+ nil
+ )
+ PyEval_SaveThread()
+ }
+ running = environment
+ }
+ return running!
+ }
+ }
+
+ static func main(_ environment: String, _ module: String, _ arguments: [String]) -> Int32 {
+ let running = start(environment)
+ guard running == environment else {
+ fputs(
+ "Python runs the \(running) environment; relaunch the app to run \(environment)\n",
+ stderr)
+ return 1
+ }
+ return call("main", [module] + arguments) { Int32(PyLong_AsLong($0)) }
+ }
+
+ static func modelPaths(_ arguments: [String]) -> [String] {
+ start("mlx")
+ return call("model_paths", arguments) { result in
+ (0..<PyList_Size(result)).map {
+ String(cString: PyUnicode_AsUTF8(PyList_GetItem(result, $0)))
+ }
+ }
+ }
+
+ private static func call<Result>(
+ _ name: String, _ values: [String], _ convert: (UnsafeMutablePointer<PyObject>) -> Result
+ ) -> Result {
+ let state = PyGILState_Ensure()
+ defer { PyGILState_Release(state) }
+ guard let runner = PyImport_ImportModule("runner") else {
+ PyErr_Print()
+ fatalError("Cannot import runner")
+ }
+ let function = PyObject_GetAttrString(runner, name)
+ let tuple = PyTuple_New(values.count)
+ for (index, value) in values.enumerated() {
+ PyTuple_SetItem(tuple, index, PyUnicode_FromString(value))
+ }
+ let result = PyObject_CallObject(function, tuple)
+ defer { [result, tuple, function, runner].forEach(Py_DecRef) }
+ guard let result else {
+ PyErr_Print()
+ fatalError("runner.\(name) failed")
+ }
+ return convert(result)
+ }
+
+ private static func check(_ status: PyStatus) {
+ if PyStatus_Exception(status) != 0 {
+ Py_ExitStatusException(status)
+ }
+ }
+}
diff --git a/apps/benchmarks-ios/Sources/StandardStreams.swift b/apps/benchmarks-ios/Sources/StandardStreams.swift
new file mode 100644
index 000000000..83897fe74
--- /dev/null
+++ b/apps/benchmarks-ios/Sources/StandardStreams.swift
@@ -0,0 +1,41 @@
+import Foundation
+
+enum StandardStreams {
+ static func run(
+ input: (FileHandle) -> Void, output: @escaping (UInt8, Data) -> Void, _ body: () -> Int32
+ ) -> Int32 {
+ let saved = (0...2).map { dup(Int32($0)) }
+ let pipes = (0...2).map { _ in Pipe() }
+ dup2(pipes[0].fileHandleForReading.fileDescriptor, 0)
+ dup2(pipes[1].fileHandleForWriting.fileDescriptor, 1)
+ dup2(pipes[2].fileHandleForWriting.fileDescriptor, 2)
+ try? pipes[0].fileHandleForReading.close()
+ try? pipes[1].fileHandleForWriting.close()
+ try? pipes[2].fileHandleForWriting.close()
+ clearerr(stdin)
+
+ input(pipes[0].fileHandleForWriting)
+ let readers = DispatchGroup()
+ for stream in 1...2 {
+ DispatchQueue.global().async(group: readers) {
+ let handle = pipes[stream].fileHandleForReading
+ var data = handle.availableData
+ while !data.isEmpty {
+ output(UInt8(stream), data)
+ data = handle.availableData
+ }
+ }
+ }
+
+ let status = body()
+ fflush(stdout)
+ for stream in 0...2 {
+ dup2(saved[stream], Int32(stream))
+ }
+ readers.wait()
+ for descriptor in saved {
+ close(descriptor)
+ }
+ return status
+ }
+}
diff --git a/apps/benchmarks-ios/Tuist.swift b/apps/benchmarks-ios/Tuist.swift
new file mode 100644
index 000000000..ff8e64fa9
--- /dev/null
+++ b/apps/benchmarks-ios/Tuist.swift
@@ -0,0 +1,3 @@
+import ProjectDescription
+
+let config = Config()
diff --git a/apps/benchmarks-ios/app/runner.py b/apps/benchmarks-ios/app/runner.py
new file mode 100644
index 000000000..5d9d4864e
--- /dev/null
+++ b/apps/benchmarks-ios/app/runner.py
@@ -0,0 +1,50 @@
+import importlib
+import os
+import sys
+import traceback
+from collections.abc import Iterator
+from contextlib import contextmanager
+
+MODEL_OPTIONS = {"-m", "--model", "-d", "--draft-model"}
+
+
+@contextmanager
+def standard_streams() -> Iterator[None]:
+ streams = sys.stdin, sys.stdout, sys.stderr
+ try:
+ with (
+ open(0, closefd=False) as sys.stdin,
+ open(1, "w", buffering=1, closefd=False) as sys.stdout,
+ open(2, "w", buffering=1, closefd=False) as sys.stderr,
+ ):
+ yield
+ finally:
+ sys.stdin, sys.stdout, sys.stderr = streams
+
+
+def main(module: str, *arguments: str) -> int:
+ sys.argv = [module, *arguments]
+ with standard_streams():
+ try:
+ importlib.import_module(module).main()
+ except SystemExit as exit:
+ return exit.code if isinstance(exit.code, int) else int(exit.code is not None)
+ except Exception: # noqa: BLE001
+ traceback.print_exc()
+ return 1
+ return 0
+
+
+def model_paths(*arguments: str) -> list[str]:
+ with standard_streams():
+ try:
+ from common import get_model_path
+
+ paths = list(arguments)
+ for index in range(1, len(paths)):
+ if paths[index - 1] in MODEL_OPTIONS and not os.path.isdir(paths[index]):
+ paths[index] = get_model_path(paths[index])
+ except Exception: # noqa: BLE001
+ traceback.print_exc()
+ return []
+ return paths
diff --git a/apps/benchmarks-ios/bootstrap.sh b/apps/benchmarks-ios/bootstrap.sh
new file mode 100755
index 000000000..366b8a36f
--- /dev/null
+++ b/apps/benchmarks-ios/bootstrap.sh
@@ -0,0 +1,242 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+PYTHON_SUPPORT_URL="https://github.com/beeware/Python-Apple-support/releases/download/3.13-b16/Python-3.13-iOS-support.b16.tar.gz"
+PYTHON_SUPPORT_SHA256="22b96f3d0c3663225f078556b036d2ee6ce3ff98c885706585240681335c71ea"
+PYTHON_VERSION="3.13.16"
+OPENSSL_URL="https://github.com/beeware/cpython-apple-source-deps/releases/download/OpenSSL-3.5.9-1/openssl-3.5.9-1-iphoneos.arm64.tar.gz"
+OPENSSL_SHA256="aa8c3a96138a5650f51a1416076f947fec9ae7a5fba83afb0015fefe314107dc"
+NATIVE_PACKAGES=(llguidance markupsafe numpy openai-harmony pydantic-core pyyaml regex rpds-py safetensors tokenizers)
+OMLX_UNUSED_PACKAGES=(cohere-melody cryptography llguidance lxml miniaudio onnxruntime opencv-python primp psutil
+ pypdfium2 scipy setproctitle tiktoken)
+export IPHONEOS_DEPLOYMENT_TARGET="26.4"
+
+APP_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
+REPO_DIR="$(cd -- "$APP_DIR/../.." && pwd)"
+BENCHMARKS_DIR="$REPO_DIR/scripts/benchmarks"
+DEPS_DIR="$APP_DIR/deps"
+SLICE_DIR="$DEPS_DIR/Python.xcframework/ios-arm64"
+VENV_DIR="$DEPS_DIR/venv"
+WHEELS_DIR="$DEPS_DIR/wheels"
+SOURCES_DIR="$DEPS_DIR/sources"
+
+mkdir -p "$WHEELS_DIR" "$SOURCES_DIR"
+
+if [[ ! -d "$DEPS_DIR/Python.xcframework" ]]; then
+ curl -fsSL -o "$DEPS_DIR/python.tar.gz" "$PYTHON_SUPPORT_URL"
+ echo "$PYTHON_SUPPORT_SHA256 $DEPS_DIR/python.tar.gz" | shasum -a 256 -c -
+ tar -xzf "$DEPS_DIR/python.tar.gz" -C "$DEPS_DIR" Python.xcframework
+ rm "$DEPS_DIR/python.tar.gz"
+fi
+
+if [[ ! -d "$VENV_DIR" ]]; then
+ uv venv --python 3.13 --seed "$VENV_DIR"
+ "$VENV_DIR/bin/python" "$SLICE_DIR/platform-config/arm64-iphoneos/make_cross_venv.py" "$VENV_DIR"
+fi
+uv pip install --quiet --python "$VENV_DIR/bin/python" --python-platform aarch64-apple-darwin \
+ cffi cmake cython maturin meson meson-python ninja pybind11 setuptools typing-extensions wheel
+
+if [[ ! -d "$DEPS_DIR/openssl" ]]; then
+ curl -fsSL -o "$DEPS_DIR/openssl.tar.gz" "$OPENSSL_URL"
+ echo "$OPENSSL_SHA256 $DEPS_DIR/openssl.tar.gz" | shasum -a 256 -c -
+ mkdir -p "$DEPS_DIR/openssl"
+ tar -xzf "$DEPS_DIR/openssl.tar.gz" -C "$DEPS_DIR/openssl"
+ rm "$DEPS_DIR/openssl.tar.gz"
+fi
+
+framework() {
+ FRAMEWORK_DIR="$DEPS_DIR/Benchmarks$1.framework"
+ rm -rf "$FRAMEWORK_DIR"
+ mkdir -p "$FRAMEWORK_DIR"
+ cp "$DEPS_DIR/Python.xcframework/build/iOS-dylib-Info-template.plist" "$FRAMEWORK_DIR/Info.plist"
+ plutil -replace CFBundleExecutable -string "Benchmarks$1" "$FRAMEWORK_DIR/Info.plist"
+ plutil -replace CFBundleIdentifier -string "com.mirai.tech.benchmarks.$2" "$FRAMEWORK_DIR/Info.plist"
+}
+
+(cd "$REPO_DIR" && cargo rustc --release --target aarch64-apple-ios -p benchmarks-uzu --lib --crate-type cdylib)
+framework Uzu uzu
+cp "$REPO_DIR/target/aarch64-apple-ios/release/libbenchmarks_uzu.dylib" "$FRAMEWORK_DIR/BenchmarksUzu"
+install_name_tool -id @rpath/BenchmarksUzu.framework/BenchmarksUzu "$FRAMEWORK_DIR/BenchmarksUzu"
+
+cat > "$DEPS_DIR/ios.cmake" <<EOF
+set(CMAKE_SYSTEM_NAME iOS)
+set(CMAKE_SYSTEM_PROCESSOR arm64)
+set(CMAKE_OSX_SYSROOT iphoneos)
+set(CMAKE_OSX_ARCHITECTURES arm64)
+set(CMAKE_OSX_DEPLOYMENT_TARGET $IPHONEOS_DEPLOYMENT_TARGET)
+macro(set_xcode_property TARGET XCODE_PROPERTY XCODE_VALUE XCODE_VARIANT)
+ set_property(TARGET \${TARGET} PROPERTY XCODE_ATTRIBUTE_\${XCODE_PROPERTY} \${XCODE_VALUE})
+endmacro()
+EOF
+
+export CMAKE_BUILD_PARALLEL_LEVEL="$(sysctl -n hw.ncpu)"
+LLAMACPP_BUILD_DIR="$DEPS_DIR/llamacpp-build"
+cmake -S "$BENCHMARKS_DIR/engine-llamacpp" -B "$LLAMACPP_BUILD_DIR" -G "Unix Makefiles" \
+ -DCMAKE_TOOLCHAIN_FILE="$DEPS_DIR/ios.cmake" -DCMAKE_BUILD_TYPE=Release -DCMAKE_MACOSX_BUNDLE=OFF \
+ -DBUILD_SHARED_LIBS=OFF -DGGML_NATIVE=OFF -DGGML_METAL=ON -DGGML_METAL_EMBED_LIBRARY=ON \
+ -DGGML_METAL_NDEBUG=ON -DGGML_ACCELERATE=ON -DGGML_BLAS=ON -DGGML_BLAS_VENDOR=Apple \
+ -DLLAMA_BUILD_BORINGSSL=ON >/dev/null
+cmake --build "$LLAMACPP_BUILD_DIR" --target engine-llamacpp >/dev/null
+framework Llamacpp llamacpp
+cp "$LLAMACPP_BUILD_DIR/libBenchmarksLlamacpp.dylib" "$FRAMEWORK_DIR/BenchmarksLlamacpp"
+install_name_tool -id @rpath/BenchmarksLlamacpp.framework/BenchmarksLlamacpp "$FRAMEWORK_DIR/BenchmarksLlamacpp"
+
+MLDRIFT_DIR="$BENCHMARKS_DIR/engine-mldrift"
+"$MLDRIFT_DIR/bootstrap.sh"
+(cd "$MLDRIFT_DIR/deps/ml-drift" && bazelisk --output_base="$DEPS_DIR/mldrift-bazel" build -c opt \
+ --platforms=@build_bazel_apple_support//platforms:ios_arm64 --ios_minimum_os="$IPHONEOS_DEPLOYMENT_TARGET" \
+ --copt=-DABSL_FLAGS_STRIP_NAMES=0 --symlink_prefix=bazel-ios- //benchmarks:BenchmarksMldrift >&2)
+framework Mldrift mldrift
+cp "$MLDRIFT_DIR/deps/ml-drift/bazel-ios-bin/benchmarks/libBenchmarksMldrift.dylib" "$FRAMEWORK_DIR/BenchmarksMldrift"
+chmod u+w "$FRAMEWORK_DIR/BenchmarksMldrift"
+install_name_tool -id @rpath/BenchmarksMldrift.framework/BenchmarksMldrift "$FRAMEWORK_DIR/BenchmarksMldrift"
+
+SPLASH_DIR="$BENCHMARKS_DIR/engine-splash"
+SPLASH_SOURCE_DIR="$SPLASH_DIR/deps/splash"
+"$SPLASH_DIR/bootstrap.sh"
+make -C "$SPLASH_SOURCE_DIR" --no-print-directory -j "$CMAKE_BUILD_PARALLEL_LEVEL" BUILD=build-ios \
+ BUILD_ID_PYTHON="uv run --no-project python" \
+ CXX="xcrun -sdk iphoneos clang++ -target arm64-apple-ios$IPHONEOS_DEPLOYMENT_TARGET" \
+ METAL="xcrun -sdk iphoneos metal" METALLIB="xcrun -sdk iphoneos metallib" AR="xcrun -sdk iphoneos ar" \
+ MACOS_TARGET_FLAG="-mios-version-min=$IPHONEOS_DEPLOYMENT_TARGET" \
+ build-ios/engine/libsplash.a build-ios/engine/main.o build-ios/splash.metallib >&2
+framework Splash splash
+xcrun --sdk iphoneos clang++ -target "arm64-apple-ios$IPHONEOS_DEPLOYMENT_TARGET" -dynamiclib -fobjc-arc \
+ -o "$FRAMEWORK_DIR/BenchmarksSplash" -install_name @rpath/BenchmarksSplash.framework/BenchmarksSplash \
+ "$SPLASH_SOURCE_DIR/build-ios/engine/main.o" "$SPLASH_SOURCE_DIR/build-ios/engine/libsplash.a" \
+ -framework Foundation -framework IOKit -framework IOSurface -framework Metal \
+ -Wl,-exported_symbol,_benchmarks_splash_main -Wl,-exported_symbol,_benchmarks_splash_terminate
+cp "$SPLASH_SOURCE_DIR/build-ios/splash.metallib" "$FRAMEWORK_DIR/"
+
+cat > "$DEPS_DIR/pyo3.txt" <<EOF
+implementation=CPython
+version=3.13
+shared=true
+lib_name=python3.13
+lib_dir=$SLICE_DIR/lib
+ext_suffix=.cpython-313-iphoneos.so
+EOF
+
+export PATH="$SLICE_DIR/bin:$VENV_DIR/bin:$PATH"
+export CMAKE_TOOLCHAIN_FILE="$DEPS_DIR/ios.cmake"
+export CARGO_BUILD_TARGET="aarch64-apple-ios"
+export PYO3_CONFIG_FILE="$DEPS_DIR/pyo3.txt"
+export CARGO_TARGET_AARCH64_APPLE_IOS_RUSTFLAGS="-C link-arg=-F$SLICE_DIR -C link-arg=-framework -C link-arg=Python"
+
+requirements() {
+ uv export --project "$BENCHMARKS_DIR/engine-$1" --frozen --no-dev --no-hashes --no-annotate --no-header \
+ --no-emit-project --no-emit-local --no-emit-package hf-xet --no-emit-package mlx-metal "${@:2}" --quiet |
+ sed "s/ ; platform_machine == 'arm64' and sys_platform == 'darwin'$//"
+}
+
+pinned() {
+ sed -n "s/^$1==\([^ ;]*\).*/\1/p" "$DEPS_DIR/requirements-$2.txt"
+}
+
+build_wheel() {
+ if ! compgen -G "$WHEELS_DIR/${1//-/_}-$2-*.whl" > /dev/null; then
+ RUSTUP_TOOLCHAIN=stable python -m pip wheel --no-build-isolation --no-deps --wheel-dir "$WHEELS_DIR" "$3"
+ fi
+}
+
+mlx_source() {
+ local source_dir="$SOURCES_DIR/mlx-$1"
+ if [[ ! -d "$source_dir" ]]; then
+ git clone --depth 1 --branch "v$1" https://github.com/ml-explore/mlx.git "$source_dir" >&2
+ patch -d "$source_dir" -p1 < "$APP_DIR/patches/mlx.patch" >&2
+ fi
+ echo "$source_dir"
+}
+
+build_native_wheels() {
+ for package in "${NATIVE_PACKAGES[@]}"; do
+ version="$(pinned "$package" "$1")"
+ if [[ -n "$version" ]]; then
+ build_wheel "$package" "$version" "$package==$version"
+ fi
+ done
+
+ version="$(pinned sentencepiece "$1")"
+ if [[ -n "$version" ]]; then
+ source_dir="$SOURCES_DIR/sentencepiece-$version"
+ if [[ ! -d "$source_dir" ]]; then
+ curl -fsSL "https://files.pythonhosted.org/packages/source/s/sentencepiece/sentencepiece-$version.tar.gz" |
+ tar -xz -C "$SOURCES_DIR"
+ patch -d "$source_dir" -p1 < "$APP_DIR/patches/sentencepiece.patch"
+ fi
+ build_wheel sentencepiece "$version" "$source_dir"
+ fi
+
+ version="$(pinned cryptography "$1")"
+ if [[ -n "$version" ]]; then
+ OPENSSL_DIR="$DEPS_DIR/openssl" build_wheel cryptography "$version" "cryptography==$version"
+ fi
+
+ version="$(pinned mlx "$1")"
+ if [[ -n "$version" ]]; then
+ PYPI_RELEASE=1 \
+ CMAKE_ARGS="-DBUILD_SHARED_LIBS=OFF -DMLX_BUILD_PYTHON_STUBS=OFF -DPython_INCLUDE_DIR=$SLICE_DIR/include/python3.13" \
+ LDFLAGS="-F$SLICE_DIR -framework Python" \
+ build_wheel mlx "$version" "$(mlx_source "$version")"
+ fi
+}
+
+requirements mlx > "$DEPS_DIR/requirements-mlx.txt"
+requirements omlx "${OMLX_UNUSED_PACKAGES[@]/#/--no-emit-package=}" > "$DEPS_DIR/requirements-omlx.txt"
+requirements mtplx > "$DEPS_DIR/requirements-mtplx.txt"
+requirements splash > "$DEPS_DIR/requirements-splash.txt"
+
+for environment in mlx omlx mtplx splash; do
+ build_native_wheels "$environment"
+done
+
+rm -f "$WHEELS_DIR"/benchmarks_*.whl
+python -m pip wheel --no-build-isolation --no-deps --wheel-dir "$WHEELS_DIR" "$BENCHMARKS_DIR/common-py" \
+ "$BENCHMARKS_DIR/engine-mlx" "$BENCHMARKS_DIR/engine-omlx" "$BENCHMARKS_DIR/engine-mtplx" \
+ "$BENCHMARKS_DIR/engine-splash"
+
+rm -rf "$DEPS_DIR/envs"
+for environment in mlx omlx mtplx splash; do
+ target="$DEPS_DIR/envs/$environment"
+ uv pip install --target "$target" --python 3.13 --python-platform arm64-apple-ios \
+ --python-version "$PYTHON_VERSION" --only-binary :all: --no-deps --compile-bytecode --find-links "$WHEELS_DIR" \
+ --requirements "$DEPS_DIR/requirements-$environment.txt" \
+ "$WHEELS_DIR"/benchmarks_common-*.whl "$WHEELS_DIR"/benchmarks_$environment-*.whl
+ rm -rf "$target/mlx/lib/libmlx.a" "$target/mlx/include" "$target/mlx/share"
+done
+for tree in install server; do
+ rsync -a --exclude __pycache__ --exclude models "$SPLASH_SOURCE_DIR/$tree" "$DEPS_DIR/envs/splash/deps/splash/"
+done
+
+MLXSERVE_DIR="$BENCHMARKS_DIR/engine-mlxserve"
+MLXSERVE_SOURCE_DIR="$MLXSERVE_DIR/deps/mlx-serve"
+MLXSERVE_BUILD_DIR="$DEPS_DIR/mlxserve-build"
+MLXSERVE_STAGE_DIR="$MLXSERVE_BUILD_DIR/stage"
+"$MLXSERVE_DIR/bootstrap.sh"
+version="$(sed -En 's/^#define MLX_VERSION_(MAJOR|MINOR|PATCH) ([0-9]+)$/\2/p' \
+ "$MLXSERVE_SOURCE_DIR/lib/mlx-src/mlx/version.h" | paste -sd. -)"
+cmake -S "$(mlx_source "$version")" -B "$MLXSERVE_BUILD_DIR/mlx" -G "Unix Makefiles" \
+ -DCMAKE_TOOLCHAIN_FILE="$DEPS_DIR/ios.cmake" -DCMAKE_BUILD_TYPE=Release -DBUILD_SHARED_LIBS=OFF \
+ -DMLX_BUILD_TESTS=OFF -DMLX_BUILD_EXAMPLES=OFF -DMLX_BUILD_BENCHMARKS=OFF -DMLX_BUILD_PYTHON_BINDINGS=OFF \
+ -DCMAKE_INSTALL_PREFIX="$MLXSERVE_STAGE_DIR" >/dev/null
+cmake --build "$MLXSERVE_BUILD_DIR/mlx" --target install >/dev/null
+cmake -S "$MLXSERVE_SOURCE_DIR/lib/mlxc-src" -B "$MLXSERVE_BUILD_DIR/mlxc" -G "Unix Makefiles" \
+ -DCMAKE_TOOLCHAIN_FILE="$DEPS_DIR/ios.cmake" -DCMAKE_BUILD_TYPE=Release -DBUILD_SHARED_LIBS=OFF \
+ -DMLX_C_USE_SYSTEM_MLX=ON -DMLX_C_BUILD_EXAMPLES=OFF -DCMAKE_FIND_ROOT_PATH="$MLXSERVE_STAGE_DIR" \
+ -DCMAKE_PREFIX_PATH="$MLXSERVE_STAGE_DIR" -DCMAKE_INSTALL_PREFIX="$MLXSERVE_STAGE_DIR" >/dev/null
+cmake --build "$MLXSERVE_BUILD_DIR/mlxc" --target install >/dev/null
+
+rsync -a --delete "$MLXSERVE_SOURCE_DIR/.zig-toolchain/lib/" "$MLXSERVE_BUILD_DIR/zig-lib/"
+patch -d "$MLXSERVE_BUILD_DIR/zig-lib" -p1 < "$APP_DIR/patches/zig-ios-null-file.patch" >/dev/null
+(cd "$MLXSERVE_DIR" && ZIG_LIB_DIR="$MLXSERVE_BUILD_DIR/zig-lib" ZIG_GLOBAL_CACHE_DIR="$MLXSERVE_DIR/.zig-cache/global" \
+ "$MLXSERVE_SOURCE_DIR/.zig-toolchain/zig" build -Doptimize=ReleaseFast -Dtarget="aarch64-ios.$IPHONEOS_DEPLOYMENT_TARGET" \
+ -Dmlx-dir="$MLXSERVE_STAGE_DIR" --prefix "$MLXSERVE_BUILD_DIR/zig")
+
+framework Mlxserve mlxserve
+xcrun --sdk iphoneos clang++ -target "arm64-apple-ios$IPHONEOS_DEPLOYMENT_TARGET" -dynamiclib \
+ -o "$FRAMEWORK_DIR/BenchmarksMlxserve" -install_name @rpath/BenchmarksMlxserve.framework/BenchmarksMlxserve \
+ -Wl,-force_load,"$MLXSERVE_BUILD_DIR/zig/lib/libengine-mlxserve.a" "$MLXSERVE_STAGE_DIR/lib/libmlxc.a" \
+ "$MLXSERVE_STAGE_DIR/lib/libmlx.a" "$MLXSERVE_BUILD_DIR/mlx/mlx/io/libgguflib.a" \
+ -framework Accelerate -framework CoreFoundation -framework Foundation -framework IOKit -framework IOSurface \
+ -framework Metal -framework QuartzCore -Wl,-exported_symbol,_benchmarks_mlxserve_main
+cp "$MLXSERVE_STAGE_DIR/lib/mlx.metallib" "$FRAMEWORK_DIR/"
diff --git a/apps/benchmarks-ios/patches/mlx.patch b/apps/benchmarks-ios/patches/mlx.patch
new file mode 100644
index 000000000..84a104cca
--- /dev/null
+++ b/apps/benchmarks-ios/patches/mlx.patch
@@ -0,0 +1,70 @@
+diff --git a/CMakeLists.txt b/CMakeLists.txt
+index 01b329b..7ff60b8 100644
+--- a/CMakeLists.txt
++++ b/CMakeLists.txt
+@@ -182,8 +182,6 @@ if(MLX_BUILD_METAL)
+ add_compile_definitions(MLX_METAL_DEBUG)
+ endif()
+
+- # Probe the macOS SDK only on Darwin. On iOS the caller selects the SDK, so
+- # version detection is deferred and the baseline Metal feature set is used.
+ if(CMAKE_SYSTEM_NAME STREQUAL "Darwin")
+ # Get the host macOS version.
+ execute_process(
+@@ -214,6 +212,7 @@ if(MLX_BUILD_METAL)
+ message(STATUS "Building for macOS ${CMAKE_OSX_DEPLOYMENT_TARGET}")
+
+ # Get Metal version.
++ set(MLX_METAL_SDK macosx)
+ set(XCRUN_FLAGS "-mmacosx-version-min=${CMAKE_OSX_DEPLOYMENT_TARGET}")
+ execute_process(
+ COMMAND
+@@ -222,6 +221,16 @@ if(MLX_BUILD_METAL)
+ OUTPUT_VARIABLE MLX_METAL_VERSION
+ OUTPUT_STRIP_TRAILING_WHITESPACE COMMAND_ERROR_IS_FATAL ANY)
+ message(STATUS "Metal version: ${MLX_METAL_VERSION}")
++ elseif(CMAKE_SYSTEM_NAME STREQUAL "iOS")
++ set(MLX_METAL_SDK iphoneos)
++ set(XCRUN_FLAGS "-mios-version-min=${CMAKE_OSX_DEPLOYMENT_TARGET}")
++ execute_process(
++ COMMAND
++ zsh "-c"
++ "echo \"__METAL_VERSION__\" | xcrun -sdk iphoneos metal ${XCRUN_FLAGS} -E -x metal -P - | tail -1"
++ OUTPUT_VARIABLE MLX_METAL_VERSION
++ OUTPUT_STRIP_TRAILING_WHITESPACE COMMAND_ERROR_IS_FATAL ANY)
++ message(STATUS "Metal version: ${MLX_METAL_VERSION}")
+ else()
+ set(MLX_METAL_VERSION 0)
+ endif()
+diff --git a/mlx/backend/metal/kernels/CMakeLists.txt b/mlx/backend/metal/kernels/CMakeLists.txt
+index d5513dd..49503fb 100644
+--- a/mlx/backend/metal/kernels/CMakeLists.txt
++++ b/mlx/backend/metal/kernels/CMakeLists.txt
+@@ -27,10 +27,10 @@ function(build_kernel_base TARGET SRCFILE DEPS)
+ endif()
+ if(NOT CMAKE_OSX_DEPLOYMENT_TARGET STREQUAL "")
+ set(METAL_FLAGS ${METAL_FLAGS}
+- "-mmacosx-version-min=${CMAKE_OSX_DEPLOYMENT_TARGET}")
++ ${XCRUN_FLAGS})
+ endif()
+ add_custom_command(
+- COMMAND xcrun -sdk macosx metal ${METAL_FLAGS} -c ${SRCFILE}
++ COMMAND xcrun -sdk ${MLX_METAL_SDK} metal ${METAL_FLAGS} -c ${SRCFILE}
+ -I${PROJECT_SOURCE_DIR} -o ${TARGET}.air
+ DEPENDS ${SRCFILE} ${DEPS} ${BASE_HEADERS}
+ OUTPUT ${TARGET}.air
+@@ -193,12 +193,12 @@ endif()
+
+ set(METAL_LINK_FLAGS)
+ if(NOT CMAKE_OSX_DEPLOYMENT_TARGET STREQUAL "")
+- set(METAL_LINK_FLAGS "-mmacosx-version-min=${CMAKE_OSX_DEPLOYMENT_TARGET}")
++ set(METAL_LINK_FLAGS ${XCRUN_FLAGS})
+ endif()
+
+ add_custom_command(
+ OUTPUT ${MLX_METAL_PATH}/mlx.metallib
+- COMMAND xcrun -sdk macosx metal ${METAL_LINK_FLAGS} ${KERNEL_AIR} -o
++ COMMAND xcrun -sdk ${MLX_METAL_SDK} metal ${METAL_LINK_FLAGS} ${KERNEL_AIR} -o
+ ${MLX_METAL_PATH}/mlx.metallib
+ DEPENDS ${KERNEL_AIR}
+ COMMENT "Building mlx.metallib"
diff --git a/apps/benchmarks-ios/patches/sentencepiece.patch b/apps/benchmarks-ios/patches/sentencepiece.patch
new file mode 100644
index 000000000..d384a9e41
--- /dev/null
+++ b/apps/benchmarks-ios/patches/sentencepiece.patch
@@ -0,0 +1,15 @@
+--- a/setup.py
++++ b/setup.py
+@@ -116,7 +116,11 @@
+
+ # Fix compile on some versions of Mac OSX
+ # See: https://github.com/neulab/xnmt/issues/199
+- if sys.platform == 'darwin':
++ if sys.platform == 'ios':
++ libs.extend(abseil_libs)
++ libs.append('-Wl,-dead_strip')
++ libs.append('-Wl,-exported_symbols_list,exports_mac.txt')
++ elif sys.platform == 'darwin':
+ # non GNU linker
+ cflags.append('-mmacosx-version-min=10.9')
+ # get correct SDK path by xcrun
diff --git a/apps/benchmarks-ios/patches/zig-ios-null-file.patch b/apps/benchmarks-ios/patches/zig-ios-null-file.patch
new file mode 100644
index 000000000..ff23931df
--- /dev/null
+++ b/apps/benchmarks-ios/patches/zig-ios-null-file.patch
@@ -0,0 +1,11 @@
+--- a/std/Io/Threaded.zig
++++ b/std/Io/Threaded.zig
+@@ -354,7 +354,7 @@
+ }
+ }
+ },
+- .wasi, .ios, .tvos, .visionos, .watchos => struct {
++ .wasi, .tvos, .watchos => struct {
+ fn deinit(this: @This()) void {
+ _ = this;
+ }
diff --git a/scripts/benchmarks/README.md b/scripts/benchmarks/README.md
index 62343d8b3..24a5b3dfa 100644
--- a/scripts/benchmarks/README.md
+++ b/scripts/benchmarks/README.md
@@ -119,6 +119,14 @@ Current configuration enables DFlash only on M5, M5 Pro, and M5 Max
cargo run --release -p benchmarks-uzu -- -m "trymirai/Qwen3.5-9B-M"
```
+## iOS
+
+[platform-ios](platform-ios) runs these engines inside the [iOS app](../../apps/benchmarks-ios) on an iPhone or iPad:
+```bash
+uv run --project platform-ios bench-ios run -e llamacpp -m "unsloth/Qwen3.5-0.8B-GGUF:Q4_K_M"
+```
+Setup, device selection, model downloads and pushes are in the [app's README](../../apps/benchmarks-ios/README.md). `pytest engines` leaves it out because it needs a device; test it with `uv run pytest --engine ios --ios-engine ENGINE --ios-model MODEL`, adding `--ios-device UDID` or `--ios-host HOST` as needed.
+
## Server
[./server](./server) contains tool for easy benchmarking OpenAI-compatible server
diff --git a/scripts/benchmarks/common-cpp/src/common.cpp b/scripts/benchmarks/common-cpp/src/common.cpp
index 689984f87..5c45edd66 100644
--- a/scripts/benchmarks/common-cpp/src/common.cpp
+++ b/scripts/benchmarks/common-cpp/src/common.cpp
@@ -68,6 +68,7 @@ void run_loop(
std::FILE* output
) {
std::string line;
+ std::cin.clear();
while (std::getline(std::cin, line)) {
if (line.find_first_not_of(" \t\r\n\v\f") == std::string::npos) {
continue;
diff --git a/scripts/benchmarks/common-py/src/mach/__init__.py b/scripts/benchmarks/common-py/src/mach/__init__.py
index 0f2e3b410..4b4068748 100644
--- a/scripts/benchmarks/common-py/src/mach/__init__.py
+++ b/scripts/benchmarks/common-py/src/mach/__init__.py
@@ -75,7 +75,7 @@ class AppleTempSensors(ctypes.Structure):
return f"{type(self).__name__}(cpu_avg={self.cpu_avg}, gpu_avg={self.gpu_avg})"
-_library = ctypes.CDLL(_mach.__file__)
+_library = ctypes.CDLL(_mach.__spec__.origin)
_library.get_memory_counters.argtypes = [ctypes.POINTER(MemoryCounters), ctypes.c_bool]
_library.get_memory_counters.restype = ctypes.c_int
_library.get_memory_counters_for_pid.argtypes = [ctypes.POINTER(MemoryCounters), ctypes.c_int32, ctypes.c_bool]
diff --git a/scripts/benchmarks/common-py/src/mach/_mach.pyi b/scripts/benchmarks/common-py/src/mach/_mach.pyi
index 732fa0350..cb6bc12dc 100644
--- a/scripts/benchmarks/common-py/src/mach/_mach.pyi
+++ b/scripts/benchmarks/common-py/src/mach/_mach.pyi
@@ -1 +1,3 @@
-__file__: str
+from importlib.machinery import ModuleSpec
+
+__spec__: ModuleSpec
diff --git a/scripts/benchmarks/engine-llamacpp/CMakeLists.txt b/scripts/benchmarks/engine-llamacpp/CMakeLists.txt
index 76fa7ecab..55cc04230 100644
--- a/scripts/benchmarks/engine-llamacpp/CMakeLists.txt
+++ b/scripts/benchmarks/engine-llamacpp/CMakeLists.txt
@@ -36,11 +36,18 @@ FetchContent_MakeAvailable(cli11)
add_subdirectory(../common-cpp common-cpp)
# sources
-add_executable(${PROJECT_NAME}
+set(SOURCES
src/engine.cpp
src/main.cpp
src/util.cpp
)
+if(IOS)
+ add_library(${PROJECT_NAME} SHARED ${SOURCES})
+ set_target_properties(${PROJECT_NAME} PROPERTIES OUTPUT_NAME BenchmarksLlamacpp)
+ target_link_options(${PROJECT_NAME} PRIVATE -Wl,-exported_symbol,_benchmarks_llamacpp_main)
+else()
+ add_executable(${PROJECT_NAME} ${SOURCES})
+endif()
# libraries
target_link_libraries(${PROJECT_NAME}
diff --git a/scripts/benchmarks/engine-llamacpp/src/main.cpp b/scripts/benchmarks/engine-llamacpp/src/main.cpp
index 71ad56030..ca13567fa 100644
--- a/scripts/benchmarks/engine-llamacpp/src/main.cpp
+++ b/scripts/benchmarks/engine-llamacpp/src/main.cpp
@@ -10,7 +10,7 @@
#include "engine.hpp"
-int main(
+extern "C" int benchmarks_llamacpp_main(
int argc,
char* argv[]
) {
@@ -46,3 +46,10 @@ int main(
return ret;
}
+
+int main(
+ int argc,
+ char* argv[]
+) {
+ return benchmarks_llamacpp_main(argc, argv);
+}
diff --git a/scripts/benchmarks/engine-mldrift/patches/benchmark-metrics.patch b/scripts/benchmarks/engine-mldrift/patches/benchmark-metrics.patch
index f4cde2630..3de72bb9e 100644
--- a/scripts/benchmarks/engine-mldrift/patches/benchmark-metrics.patch
+++ b/scripts/benchmarks/engine-mldrift/patches/benchmark-metrics.patch
@@ -14,10 +14,36 @@ index 266bf65..0f4a148 100644
# Avoid XNNPACK using `-mavxvnniint8` (needs clang-16+/gcc-13+)
build --define=xnn_enable_avxvnniint8=false
diff --git a/MODULE.bazel b/MODULE.bazel
-index 098b839..e8cc263 100644
+index 098b839..242562a 100644
--- a/MODULE.bazel
+++ b/MODULE.bazel
-@@ -266,3 +266,16 @@ http_archive(
+@@ -217,7 +217,10 @@ bazel_dep(
+ )
+
+ rust = use_extension("@rules_rust//rust:extensions.bzl", "rust")
+-rust.toolchain(edition = "2021")
++rust.toolchain(
++ edition = "2021",
++ extra_target_triples = ["aarch64-apple-ios"],
++)
+ use_repo(rust, "rust_toolchains")
+
+ register_toolchains("@rust_toolchains//:all")
+@@ -238,7 +241,12 @@ crate.spec(
+ package = "serde_json",
+ version = "1.0",
+ )
+-crate.from_specs()
++crate.from_specs(
++ supported_platform_triples = [
++ "aarch64-apple-darwin",
++ "aarch64-apple-ios",
++ ],
++)
+ use_repo(crate, crate_index = "crates")
+
+ http_archive(
+@@ -266,3 +274,16 @@ http_archive(
strip_prefix = "tokenizers-cpp-0.1.1",
url = "https://github.com/mlc-ai/tokenizers-cpp/archive/refs/tags/v0.1.1.tar.gz",
)
diff --git a/scripts/benchmarks/engine-mldrift/src/BUILD.bazel b/scripts/benchmarks/engine-mldrift/src/BUILD.bazel
index 0ccc8100b..43451f4f2 100644
--- a/scripts/benchmarks/engine-mldrift/src/BUILD.bazel
+++ b/scripts/benchmarks/engine-mldrift/src/BUILD.bazel
@@ -1,5 +1,25 @@
load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_library")
+SRCS = [
+ "bench.hpp",
+ "common.cpp",
+ "common.hpp",
+ "engine.cpp",
+ "engine.hpp",
+ "main.cpp",
+]
+
+DEPS = [
+ ":memory_counters",
+ "//ml_drift/samples/llm:llm_config",
+ "//ml_drift/samples/llm:llm_runner_interface",
+ "//ml_drift/samples/llm:llm_runner_metal_lib",
+ "@com_google_absl//absl/flags:flag",
+ "@com_google_absl//absl/flags:parse",
+ "@com_google_absl//absl/status",
+ "@glaze",
+]
+
cc_library(
name = "memory_counters",
srcs = ["memory_counters.c"],
@@ -8,22 +28,14 @@ cc_library(
cc_binary(
name = "engine-mldrift",
- srcs = [
- "bench.hpp",
- "common.cpp",
- "common.hpp",
- "engine.cpp",
- "engine.hpp",
- "main.cpp",
- ],
- deps = [
- ":memory_counters",
- "//ml_drift/samples/llm:llm_config",
- "//ml_drift/samples/llm:llm_runner_interface",
- "//ml_drift/samples/llm:llm_runner_metal_lib",
- "@com_google_absl//absl/flags:flag",
- "@com_google_absl//absl/flags:parse",
- "@com_google_absl//absl/status",
- "@glaze",
- ],
+ srcs = SRCS,
+ deps = DEPS,
+)
+
+cc_binary(
+ name = "BenchmarksMldrift",
+ srcs = SRCS,
+ linkopts = ["-Wl,-exported_symbol,_benchmarks_mldrift_main"],
+ linkshared = True,
+ deps = DEPS,
)
diff --git a/scripts/benchmarks/engine-mldrift/src/main.cpp b/scripts/benchmarks/engine-mldrift/src/main.cpp
index 7d6e5f7a4..68c355280 100644
--- a/scripts/benchmarks/engine-mldrift/src/main.cpp
+++ b/scripts/benchmarks/engine-mldrift/src/main.cpp
@@ -22,7 +22,7 @@ ABSL_FLAG(
"Directory with weights extracted by extract_weights_hf.py"
);
-int main(
+extern "C" int benchmarks_mldrift_main(
int argc,
char* argv[]
) {
@@ -39,3 +39,10 @@ int main(
}
return 0;
}
+
+int main(
+ int argc,
+ char* argv[]
+) {
+ return benchmarks_mldrift_main(argc, argv);
+}
diff --git a/scripts/benchmarks/engine-mlxserve/bootstrap.sh b/scripts/benchmarks/engine-mlxserve/bootstrap.sh
index 5af39b321..dd04913f7 100755
--- a/scripts/benchmarks/engine-mlxserve/bootstrap.sh
+++ b/scripts/benchmarks/engine-mlxserve/bootstrap.sh
@@ -22,7 +22,7 @@ fi
# Only source dependencies of the MLX backend. No released inference binaries.
git -C "$SOURCE_DIR" submodule update --init --depth 1 \
lib/mlx-src lib/mlxc-src lib/sushi lib/mlx-serve-gguf >&2
-"$SOURCE_DIR/scripts/fetch-zig.sh" >&2
+ZIG_VERSION=0.17.0 "$SOURCE_DIR/scripts/fetch-zig.sh" >&2
"$SOURCE_DIR/scripts/build-mlx.sh" >&2
for patch in "$PROJECT_DIR"/patches/*.patch; do
diff --git a/scripts/benchmarks/engine-mlxserve/build.zig b/scripts/benchmarks/engine-mlxserve/build.zig
index c95d85a0d..9f9d599ea 100644
--- a/scripts/benchmarks/engine-mlxserve/build.zig
+++ b/scripts/benchmarks/engine-mlxserve/build.zig
@@ -7,6 +7,12 @@ pub fn build(b: *std.Build) void {
.default_target = .{ .os_version_min = .{ .semver = .{ .major = 26, .minor = 2, .patch = 0 } } },
});
const optimize = b.standardOptimizeOption(.{});
+ const ios = target.result.os.tag == .ios;
+ const mlx_dir = b.pathResolve(&.{
+ b.root.root_dir.path orelse ".",
+ b.option([]const u8, "mlx-dir", "MLX and mlx-c install prefix") orelse upstream ++ "lib/mlx",
+ });
+ const sdk = std.mem.trim(u8, b.run(&.{ "xcrun", "--sdk", if (ios) "iphoneos" else "macosx", "--show-sdk-path" }), " \r\n");
const options = b.addOptions();
options.addOption([]const u8, "version", "26.10.1");
options.addOption([]const u8, "git_sha", "02bee553f48cd3bc7d82aba0f8073820bd924738");
@@ -14,12 +20,12 @@ pub fn build(b: *std.Build) void {
options.addOption([]const u8, "ds4_commit", "disabled");
options.addOption([]const u8, "llama_tag", "disabled");
options.addOption(bool, "macos_engines", false);
- options.addOption(bool, "ios", false);
- options.addOption(bool, "mas", false);
+ options.addOption(bool, "ios", ios);
+ options.addOption(bool, "mas", ios);
options.addOption(bool, "slow_tests", false);
const mod = b.createModule(.{
- .root_source_file = b.path(upstream ++ "src/bench_main.zig"),
+ .root_source_file = b.path(if (ios) upstream ++ "src/bench_ios.zig" else upstream ++ "src/bench_main.zig"),
.target = target,
.optimize = optimize,
.link_libc = true,
@@ -70,6 +76,15 @@ pub fn build(b: *std.Build) void {
.target = target,
.optimize = optimize,
});
+ if (ios) {
+ const include: std.Build.LazyPath = .{ .cwd_relative = b.fmt("{s}/usr/include", .{sdk}) };
+ jinja.addSystemIncludePath(include);
+ memory.addSystemIncludePath(include);
+ mod.addSystemIncludePath(include);
+ const surface = b.addWriteFiles();
+ _ = surface.add("IOSurface/IOSurface.h", "#include <IOSurface/IOSurfaceRef.h>\n");
+ mod.addIncludePath(surface.getDirectory());
+ }
mod.addImport("memory_c", memory.createModule());
mod.addCSourceFile(.{ .file = b.path("src/bench_memory.c"), .flags = &.{"-O2"} });
mod.addCSourceFile(.{
@@ -77,18 +92,22 @@ pub fn build(b: *std.Build) void {
.flags = &.{"-O2"},
});
mod.addIncludePath(b.path("../common-cpp/src"));
- mod.addIncludePath(b.path(upstream ++ "lib/mlx/include"));
- mod.addLibraryPath(b.path(upstream ++ "lib/mlx/lib"));
- mod.addRPath(.{ .cwd_relative = b.pathResolve(&.{ b.root.root_dir.path orelse ".", upstream ++ "lib/mlx/lib" }) });
- mod.linkSystemLibrary("mlxc", .{ .use_pkg_config = .no });
-
- const sdk = std.mem.trim(u8, b.run(&.{ "xcrun", "--sdk", "macosx", "--show-sdk-path" }), " \r\n");
+ mod.addIncludePath(.{ .cwd_relative = b.pathJoin(&.{ mlx_dir, "include" }) });
mod.addFrameworkPath(.{ .cwd_relative = b.fmt("{s}/System/Library/Frameworks", .{sdk}) });
- inline for (.{ "IOKit", "CoreFoundation", "Foundation", "Metal", "IOSurface", "Accelerate" }) |name| {
- mod.linkFramework(name, .{});
+ if (ios) {
+ const lib = b.addLibrary(.{ .name = "engine-mlxserve", .root_module = mod, .linkage = .static });
+ lib.bundle_compiler_rt = true;
+ b.installArtifact(lib);
+ } else {
+ mod.addLibraryPath(.{ .cwd_relative = b.pathJoin(&.{ mlx_dir, "lib" }) });
+ mod.addRPath(.{ .cwd_relative = b.pathJoin(&.{ mlx_dir, "lib" }) });
+ mod.linkSystemLibrary("mlxc", .{ .use_pkg_config = .no });
+ inline for (.{ "IOKit", "CoreFoundation", "Foundation", "Metal", "IOSurface", "Accelerate" }) |name| {
+ mod.linkFramework(name, .{});
+ }
+ const exe = b.addExecutable(.{ .name = "engine-mlxserve", .root_module = mod });
+ b.installArtifact(exe);
}
- const exe = b.addExecutable(.{ .name = "engine-mlxserve", .root_module = mod });
- b.installArtifact(exe);
const unit_tests = b.addTest(.{
.root_module = b.createModule(.{
diff --git a/scripts/benchmarks/engine-mlxserve/src/bench_ios.zig b/scripts/benchmarks/engine-mlxserve/src/bench_ios.zig
new file mode 100644
index 000000000..83b6fbe7d
--- /dev/null
+++ b/scripts/benchmarks/engine-mlxserve/src/bench_ios.zig
@@ -0,0 +1,34 @@
+const std = @import("std");
+const bench_main = @import("bench_main.zig");
+pub const mlx = bench_main.mlx;
+pub const log = bench_main.log;
+pub const io_util = bench_main.io_util;
+
+export fn benchmarks_mlxserve_main(argc: c_int, argv: [*][*:0]u8) c_int {
+ var count: usize = 0;
+ while (std.c.environ[count] != null) : (count += 1) {}
+ const environ: std.process.Environ.Block = .{ .slice = std.c.environ[0..count :null] };
+ const args = argv[0..@intCast(argc)];
+ const gpa = std.heap.c_allocator;
+
+ var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
+ defer arena.deinit();
+ var threaded: std.Io.Threaded = .init(gpa, .{ .argv0 = .init(.{ .vector = args }), .environ = .{ .block = environ } });
+ defer threaded.deinit();
+ var environ_map = std.process.Environ.createMap(.{ .block = environ }, gpa) catch return 1;
+ defer environ_map.deinit();
+ const preopens = std.process.Preopens.init(arena.allocator()) catch return 1;
+
+ bench_main.main(.{
+ .minimal = .{ .args = .{ .vector = args }, .environ = .{ .block = environ } },
+ .arena = &arena,
+ .gpa = gpa,
+ .io = threaded.io(),
+ .environ_map = &environ_map,
+ .preopens = preopens,
+ }) catch |err| {
+ log.err("{s}\n", .{@errorName(err)});
+ return 1;
+ };
+ return 0;
+}
diff --git a/scripts/benchmarks/engine-splash/bench_splash.py b/scripts/benchmarks/engine-splash/bench_splash.py
index 51fcdd4c2..1d5b4d528 100644
--- a/scripts/benchmarks/engine-splash/bench_splash.py
+++ b/scripts/benchmarks/engine-splash/bench_splash.py
@@ -1,5 +1,6 @@
import json
import math
+import os
import queue
import secrets
import subprocess
@@ -65,10 +66,13 @@ def sampling_options(sampling: BenchSampling | None) -> dict[str, float | int]:
class SplashEngine(InferenceEngine):
def __init__(self, model: str | Path):
- subprocess.run([str(SPLASH_BINARY), "device-check"], check=True)
-
sys.path.insert(0, str(SPLASH_DIR.parent))
sys.path.insert(0, str(SPLASH_DIR))
+ from splash.install import models, paths
+
+ self._processes = models.processes
+ self._processes.run([str(paths.BINARY), "device-check"], check=True)
+
from splash.server import protocol as wire
from splash.server.backend import Job, NativeBackend
from splash.server.chat_templates import ChatTemplates
@@ -96,7 +100,7 @@ class SplashEngine(InferenceEngine):
)
validate_tokenizer(self.tokenizer)
chat_templates = ChatTemplates(self.tokenizer)
- self._command = [str(SPLASH_BINARY), "serve-native", str(root), "auto", "auto"]
+ self._command = [str(paths.BINARY), "serve-native", str(root), "auto", "auto"]
try:
self.runtime = MultiplexedRuntime(
self._command,
@@ -148,7 +152,7 @@ class SplashEngine(InferenceEngine):
self.process = None
def _start_process(self) -> subprocess.Popen:
- self.process = subprocess.Popen(
+ self.process = self._processes.Popen(
self._command,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
@@ -215,11 +219,7 @@ class SplashEngine(InferenceEngine):
# A benchmark needs fresh snapshots around its single request.
event = self.runtime.status()
snapshot = json.loads(event.json)
- if (
- event.schema_version != self._wire.STATUS_SCHEMA_VERSION
- or not isinstance(snapshot, dict)
- or snapshot.get("schema_version") != self._wire.STATUS_SCHEMA_VERSION
- ):
+ if not isinstance(snapshot, dict) or snapshot.get("schema_version") != self._wire.STATUS_SCHEMA_VERSION:
raise RuntimeError("Splash status does not match the current schema")
return snapshot
@@ -228,6 +228,8 @@ class SplashEngine(InferenceEngine):
if process is None or process.poll() is not None:
raise RuntimeError("Splash process is not running")
memory = get_memory_counters()
+ if process.pid == os.getpid():
+ return memory
child = get_memory_counters(pid=process.pid)
# Include Python's tokenizer/frontend as well as the native engine,
# matching the scope of the other in-process benchmark adapters.
@@ -247,14 +249,11 @@ class SplashEngine(InferenceEngine):
next_memory_sample = time.monotonic() + MEMORY_SAMPLE_INTERVAL
chunks = []
submitted = False
- submission_complete = False
terminal = False
try:
- submitted = self.backend.submit(job)
- submission_complete = True
- if not submitted:
- raise RuntimeError("Splash request capacity is exhausted")
+ self.backend.submit(job)
+ submitted = True
while True:
remaining = job.deadline - time.monotonic()
@@ -291,9 +290,9 @@ class SplashEngine(InferenceEngine):
elif kind not in (None, "start", "progress"):
raise RuntimeError(f"Unexpected Splash backend event: {kind}")
except BaseException as error:
- if not submission_complete:
+ if not submitted:
self.close()
- elif submitted and not terminal:
+ elif not terminal:
self._cancel_and_drain(job, timed_out=isinstance(error, TimeoutError))
raise
@@ -343,7 +342,7 @@ class SplashEngine(InferenceEngine):
def run(model: Annotated[str, typer.Option("-m", "--model")]) -> None:
- if not SPLASH_BINARY.is_file():
+ if sys.platform != "ios" and not SPLASH_BINARY.is_file():
subprocess.run([str(PROJECT_DIR / "bootstrap.sh")], check=True, stdout=sys.stderr)
engine: SplashEngine
diff --git a/scripts/benchmarks/engine-splash/bootstrap.sh b/scripts/benchmarks/engine-splash/bootstrap.sh
index 10203a292..3f429388b 100755
--- a/scripts/benchmarks/engine-splash/bootstrap.sh
+++ b/scripts/benchmarks/engine-splash/bootstrap.sh
@@ -16,6 +16,13 @@ if [[ ! -e "$SOURCE_DIR" ]]; then
git clone --depth 1 --branch "$VERSION" https://github.com/incoai/splash.git "$SOURCE_DIR" >&2
fi
+for patch in "$PROJECT_DIR"/patches/*.patch; do
+ if ! git -C "$SOURCE_DIR" apply --reverse --check "$patch" 2>/dev/null; then
+ git -C "$SOURCE_DIR" apply --check "$patch"
+ git -C "$SOURCE_DIR" apply "$patch"
+ fi
+done
+
make -C "$SOURCE_DIR" --no-print-directory \
"BUILD_ID_PYTHON=$PYTHON_EXECUTABLE" platform-check >&2
make -C "$SOURCE_DIR" --no-print-directory -j "$PARALLEL_JOBS" \
diff --git a/scripts/benchmarks/engine-splash/patches/in-process.patch b/scripts/benchmarks/engine-splash/patches/in-process.patch
new file mode 100644
index 000000000..3d6a8f90c
--- /dev/null
+++ b/scripts/benchmarks/engine-splash/patches/in-process.patch
@@ -0,0 +1,335 @@
+diff --git a/install/inprocess.py b/install/inprocess.py
+new file mode 100644
+index 0000000..bb863e7
+--- /dev/null
++++ b/install/inprocess.py
+@@ -0,0 +1,103 @@
++"""The engine's commands inside this process, where none can be started (iOS),
++with the subset of subprocess.run and subprocess.Popen that Splash uses."""
++
++import ctypes
++import os
++import subprocess
++import threading
++from functools import cache
++
++from . import paths
++
++
++@cache
++def _engine():
++ engine = ctypes.CDLL(str(paths.BINARY))
++ engine.benchmarks_splash_main.argtypes = [
++ ctypes.c_int,
++ ctypes.POINTER(ctypes.c_char_p),
++ ctypes.c_int,
++ ctypes.c_int,
++ ]
++ engine.benchmarks_splash_terminate.argtypes = []
++ return engine
++
++
++def _main(args, input, output):
++ argv = (ctypes.c_char_p * (len(args) + 1))(*(str(arg).encode() for arg in args), None)
++ returncode = _engine().benchmarks_splash_main(len(args), argv, input, output)
++ ctypes.CDLL(None).fflush(None)
++ return returncode
++
++
++def _drain(descriptor, chunks):
++ with os.fdopen(descriptor, "rb") as stream:
++ chunks.append(stream.read())
++
++
++def run(args, *, check=False, capture_output=False, text=False):
++ """Run a check that writes to stdout and stderr, as subprocess.run does."""
++ if not capture_output:
++ returncode = _main(args, 0, 1)
++ stdout = stderr = None
++ else:
++ saved = [os.dup(1), os.dup(2)]
++ pipes = [os.pipe(), os.pipe()]
++ outputs = [[], []]
++ readers = [threading.Thread(target=_drain, args=(pipe[0], chunks)) for pipe, chunks in zip(pipes, outputs)]
++ for reader in readers:
++ reader.start()
++ try:
++ for descriptor, pipe in zip((1, 2), pipes):
++ os.dup2(pipe[1], descriptor)
++ os.close(pipe[1])
++ returncode = _main(args, 0, 1)
++ finally:
++ for descriptor, copy in zip((1, 2), saved):
++ os.dup2(copy, descriptor)
++ os.close(copy)
++ for reader in readers:
++ reader.join()
++ stdout, stderr = (b"".join(chunks) for chunks in outputs)
++ if text:
++ stdout, stderr = stdout.decode(), stderr.decode()
++ if check and returncode:
++ raise subprocess.CalledProcessError(returncode, args, stdout, stderr)
++ return subprocess.CompletedProcess(args, returncode, stdout, stderr)
++
++
++class Popen:
++ """The native server on a thread, with pipes for its frames and the
++ shared stderr, as subprocess.Popen(stdin=PIPE, stdout=PIPE, bufsize=0)."""
++
++ def __init__(self, args, **_):
++ self.args = args
++ self.pid = os.getpid()
++ self.returncode = None
++ input, writer = os.pipe()
++ reader, output = os.pipe()
++ self.stdin = os.fdopen(writer, "wb", buffering=0)
++ self.stdout = os.fdopen(reader, "rb", buffering=0)
++ self._thread = threading.Thread(target=self._serve, args=(input, output), daemon=True)
++ self._thread.start()
++
++ def _serve(self, input, output):
++ try:
++ self.returncode = _main(self.args, input, output)
++ finally:
++ os.close(input)
++ os.close(output)
++
++ def poll(self):
++ return None if self._thread.is_alive() else self.returncode
++
++ def wait(self, timeout=None):
++ self._thread.join(timeout)
++ if self._thread.is_alive():
++ raise subprocess.TimeoutExpired(self.args, timeout)
++ return self.returncode
++
++ def terminate(self):
++ _engine().benchmarks_splash_terminate()
++
++ kill = terminate
+diff --git a/install/models.py b/install/models.py
+index 965b46b..9ddab59 100644
+--- a/install/models.py
++++ b/install/models.py
+@@ -42,9 +42,11 @@ if __name__ == "__main__" and not __package__:
+ # the standard library alone: the launcher imports this before .venv exists.
+ from server import serve_options
+
+-from . import paths
++from . import inprocess, paths
+
+ MODELS = paths.MODELS
++# The engine's checks run in this process where none can be started.
++processes = inprocess if paths.SANDBOXED else subprocess
+ # The bound on one JSON metadata file the installer reads; such files are
+ # kilobytes, so a larger one is refused unread. The engine bounds the files it
+ # reads by its own rule.
+@@ -77,7 +79,7 @@ def run_engine(arguments, check):
+ engine = paths.BINARY
+ replace = "reinstall Splash" if paths.PACKAGED else "rebuild it with make"
+ try:
+- result = subprocess.run(
++ result = processes.run(
+ [str(engine), *arguments], capture_output=True, text=True
+ )
+ except OSError as error:
+diff --git a/install/paths.py b/install/paths.py
+index 4509cc6..5c2eff8 100644
+--- a/install/paths.py
++++ b/install/paths.py
+@@ -1,11 +1,18 @@
+ """Immutable program files and writable per-user data, for source or release."""
+
++import sys
+ from pathlib import Path
+
+ ROOT = Path(__file__).resolve().parents[1]
+ PACKAGED = (ROOT / "release.json").is_file()
+-DATA = Path.home() / "Library/Application Support/Splash" if PACKAGED else ROOT
+-MODELS = DATA / "models" if PACKAGED else ROOT / "install/models"
+-RUNTIME = DATA / "runtime" if PACKAGED else ROOT / "build/runtime"
++SANDBOXED = sys.platform == "ios"
++PER_USER = PACKAGED or SANDBOXED
++DATA = Path.home() / "Library/Application Support/Splash" if PER_USER else ROOT
++MODELS = DATA / "models" if PER_USER else ROOT / "install/models"
++RUNTIME = DATA / "runtime" if PER_USER else ROOT / "build/runtime"
+ PYTHON = ROOT / ("python/bin/python3" if PACKAGED else ".venv/bin/python")
+-BINARY = ROOT / ("engine/splash" if PACKAGED else "build/splash")
++BINARY = (
++ Path(sys.executable).parent / "Frameworks/BenchmarksSplash.framework/BenchmarksSplash"
++ if SANDBOXED
++ else ROOT / ("engine/splash" if PACKAGED else "build/splash")
++)
+diff --git a/runtime/ane/Program.mm b/runtime/ane/Program.mm
+index 3840533..90e30a7 100644
+--- a/runtime/ane/Program.mm
++++ b/runtime/ane/Program.mm
+@@ -6,7 +6,7 @@
+ #endif
+
+ #import <Foundation/Foundation.h>
+-#import <IOSurface/IOSurface.h>
++#import <IOSurface/IOSurfaceRef.h>
+
+ #include <dispatch/dispatch.h>
+ #include <dlfcn.h>
+diff --git a/runtime/main.mm b/runtime/main.mm
+index 2127282..dd1df65 100644
+--- a/runtime/main.mm
++++ b/runtime/main.mm
+@@ -6,9 +6,12 @@
+ #include "engine/Status.hpp"
+ #include "model/ModelDescriptor.hpp"
+
++#include <TargetConditionals.h>
++#if TARGET_OS_OSX
+ #include <IOKit/pwr_mgt/IOPMLib.h>
++#endif
++#include <dlfcn.h>
+ #include <dispatch/dispatch.h>
+-#include <mach-o/dyld.h>
+ #include <mach/mach_error.h>
+ #include <sysexits.h>
+ #include <unistd.h>
+@@ -20,7 +23,6 @@
+ #include <chrono>
+ #include <cstdint>
+ #include <filesystem>
+-#include <limits.h>
+ #include <memory>
+ #include <optional>
+ #include <stdexcept>
+@@ -29,7 +31,6 @@
+ #include <system_error>
+ #include <thread>
+ #include <utility>
+-#include <vector>
+
+ #ifndef SPLASH_BUILD_ID
+ #error "production build requires the generated BuildIdentity.hpp"
+@@ -112,6 +113,7 @@ explicit MemoryPressureMonitor(std::function<void()> notify)
+ // does: the display may still sleep, and the lid, the Sleep command or a low
+ // battery still sleep the Mac; requests continue when it wakes. Without the
+ // assertion the engine serves on and says so once.
++#if TARGET_OS_OSX
+ class IdleSleepAssertion final {
+ public:
+ IdleSleepAssertion() = default;
+@@ -144,6 +146,7 @@ void hold(bool held) noexcept {
+ IOPMAssertionID assertion_ = kIOPMNullAssertionID;
+ bool reported_ = false;
+ };
++#endif
+
+ void printUsage(std::string_view executable) {
+ const std::string command(executable);
+@@ -160,16 +163,11 @@ void printUsage(std::string_view executable) {
+ }
+
+ std::filesystem::path executablePath() {
+- uint32_t size = PATH_MAX;
+- std::vector<char> buffer(size);
+- if (_NSGetExecutablePath(buffer.data(), &size) != 0) {
+- buffer.resize(size);
+- if (_NSGetExecutablePath(buffer.data(), &size) != 0) {
+- throw std::runtime_error("could not resolve executable path");
+- }
+- }
++ Dl_info info{};
++ if (!dladdr(reinterpret_cast<const void *>(&executablePath), &info) || !info.dli_fname)
++ throw std::runtime_error("could not resolve executable path");
+ std::error_code error;
+- std::filesystem::path path = std::filesystem::canonical(buffer.data(), error);
++ std::filesystem::path path = std::filesystem::canonical(info.dli_fname, error);
+ if (error) {
+ throw std::runtime_error("could not canonicalize executable path: " +
+ error.message());
+@@ -223,20 +221,27 @@ explicit ShutdownSignals(engine::FdTransport &transport) {
+ action.sa_handler = requestShutdownFromSignal;
+ sigemptyset(&action.sa_mask);
+ action.sa_flags = 0;
+- for (const int number : {SIGTERM, SIGINT, SIGHUP}) {
+- struct sigaction inherited {};
+- if (number == SIGHUP && sigaction(number, nullptr, &inherited) == 0 &&
+- inherited.sa_handler == SIG_IGN)
++ struct sigaction ignore {};
++ ignore.sa_handler = SIG_IGN;
++ for (std::size_t index = 0; index < std::size(kSignals); ++index) {
++ const int number = kSignals[index];
++ sigaction(number, nullptr, &inherited_[index]);
++ if (number == SIGHUP && inherited_[index].sa_handler == SIG_IGN)
+ continue;
+- sigaction(number, &action, nullptr);
++ sigaction(number, number == SIGPIPE ? &ignore : &action, nullptr);
+ }
+- std::signal(SIGPIPE, SIG_IGN);
+ }
+ ShutdownSignals(const ShutdownSignals &) = delete;
+ ShutdownSignals &operator=(const ShutdownSignals &) = delete;
+ ~ShutdownSignals() {
++ for (std::size_t index = 0; index < std::size(kSignals); ++index)
++ sigaction(kSignals[index], &inherited_[index], nullptr);
+ gShutdownTransport.store(nullptr, std::memory_order_release);
+ }
++
++private:
++ static constexpr int kSignals[] = {SIGTERM, SIGINT, SIGHUP, SIGPIPE};
++ struct sigaction inherited_[std::size(kSignals)] {};
+ };
+
+ // The time a clean stop gives the newest restore points of a persistent
+@@ -263,11 +268,13 @@ void closePersistentCache(engine::FdTransport &transport,
+ "back on probation.");
+ }
+
+-int runNative(const engine::NativeArguments &arguments) {
+- engine::FdTransport transport(STDIN_FILENO, STDOUT_FILENO);
++int runNative(const engine::NativeArguments &arguments, int input, int output) {
++ engine::FdTransport transport(input, output);
+ ShutdownSignals signals(transport);
+ MemoryPressureMonitor pressureMonitor(transport.controlNotifier());
++#if TARGET_OS_OSX
+ IdleSleepAssertion idleSleep;
++#endif
+ engine::RuntimeMetrics metrics;
+ engine::RuntimeBootstrap *published = nullptr;
+ auto statusProvider = [&] {
+@@ -286,8 +293,10 @@ int runNative(const engine::NativeArguments &arguments) {
+ config.resources.memoryPressure = [&] { return pressureMonitor.pressure(); };
+ config.resources.cancelled = [&] { return transport.shutdownRequested(); };
+ config.nativeLoop.metrics = &metrics;
++#if TARGET_OS_OSX
+ if (arguments.preventIdleSleep)
+ config.nativeLoop.holdingRequests = [&](bool held) { idleSleep.hold(held); };
++#endif
+ try {
+ bootstrap = engine::RuntimeBootstrap::start(
+ std::move(config), transport.outputSink(), statusProvider);
+@@ -383,7 +392,9 @@ int checkModel(int argc, char **argv) {
+ } // namespace
+ } // namespace splash
+
+-int main(int argc, char **argv) {
++extern "C" void benchmarks_splash_terminate() { splash::requestShutdownFromSignal(SIGTERM); }
++
++extern "C" int benchmarks_splash_main(int argc, char **argv, int input, int output) {
+ @autoreleasepool {
+ try {
+ if (argc == 2 && std::string_view(argv[1]) == "device-check")
+@@ -392,7 +403,7 @@ int main(int argc, char **argv) {
+ return splash::checkModel(argc, argv);
+ const splash::engine::NativeArguments arguments =
+ splash::engine::parseNativeArguments(argc, argv);
+- return splash::runNative(arguments);
++ return splash::runNative(arguments, input, output);
+ } catch (const splash::engine::UsageError &error) {
+ splash::writeStderrLine(std::string("error: ") + error.what());
+ splash::printUsage(argc > 0 ? argv[0] : "splash");
+@@ -408,3 +419,7 @@ int main(int argc, char **argv) {
+ }
+ }
+ }
++
++int main(int argc, char **argv) {
++ return benchmarks_splash_main(argc, argv, STDIN_FILENO, STDOUT_FILENO);
++}
diff --git a/scripts/benchmarks/engine-uzu/src/args.rs b/scripts/benchmarks/engine-uzu/src/args.rs
new file mode 100644
index 000000000..41b7f8aaf
--- /dev/null
+++ b/scripts/benchmarks/engine-uzu/src/args.rs
@@ -0,0 +1,7 @@
+use clap::Parser;
+
+#[derive(Debug, Parser)]
+pub struct Args {
+ #[arg(short, long)]
+ pub model: String,
+}
diff --git a/scripts/benchmarks/engine-uzu/src/lib.rs b/scripts/benchmarks/engine-uzu/src/lib.rs
new file mode 100644
index 000000000..a886c8e9c
--- /dev/null
+++ b/scripts/benchmarks/engine-uzu/src/lib.rs
@@ -0,0 +1,9 @@
+mod args;
+mod bench;
+mod common;
+mod engine;
+mod memory;
+mod run;
+
+pub use args::Args;
+pub use run::{benchmarks_uzu_main, run};
diff --git a/scripts/benchmarks/engine-uzu/src/main.rs b/scripts/benchmarks/engine-uzu/src/main.rs
index dd20abe00..3b494ae5c 100644
--- a/scripts/benchmarks/engine-uzu/src/main.rs
+++ b/scripts/benchmarks/engine-uzu/src/main.rs
@@ -1,27 +1,7 @@
-mod bench;
-mod common;
-mod engine;
-mod memory;
-
+use benchmarks_uzu::Args;
use clap::Parser;
-use crate::{
- common::{StdoutRedirect, run_loop},
- engine::UzuEngine,
-};
-
-#[derive(Debug, Parser)]
-struct Args {
- #[arg(short, long)]
- model: String,
-}
-
#[tokio::main]
async fn main() -> anyhow::Result<()> {
- let args = Args::parse();
- let mut redirect = StdoutRedirect::to_stderr()?;
- let mut engine = UzuEngine::new(args.model.as_str()).await?;
- redirect.restore()?;
- run_loop(&mut engine).await?;
- Ok(())
+ benchmarks_uzu::run(Args::parse()).await
}
diff --git a/scripts/benchmarks/engine-uzu/src/run.rs b/scripts/benchmarks/engine-uzu/src/run.rs
new file mode 100644
index 000000000..eb89aa495
--- /dev/null
+++ b/scripts/benchmarks/engine-uzu/src/run.rs
@@ -0,0 +1,42 @@
+use std::ffi::{CStr, c_char, c_int};
+
+use clap::Parser;
+
+use crate::{
+ args::Args,
+ common::{StdoutRedirect, run_loop},
+ engine::UzuEngine,
+};
+
+pub async fn run(args: Args) -> anyhow::Result<()> {
+ let mut redirect = StdoutRedirect::to_stderr()?;
+ let mut engine = UzuEngine::new(&args.model).await?;
+ redirect.restore()?;
+ run_loop(&mut engine).await
+}
+
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn benchmarks_uzu_main(
+ argc: c_int,
+ argv: *const *const c_char,
+) -> c_int {
+ // SAFETY: callers pass argc valid NUL-terminated strings, as for a C `main`.
+ let arguments =
+ (0..argc as usize).map(|index| unsafe { CStr::from_ptr(*argv.add(index)) }.to_string_lossy().into_owned());
+ let args = match Args::try_parse_from(arguments) {
+ Ok(args) => args,
+ Err(error) => {
+ let _ = error.print();
+ return error.exit_code();
+ },
+ };
+ let result =
+ tokio::runtime::Runtime::new().map_err(anyhow::Error::from).and_then(|runtime| runtime.block_on(run(args)));
+ match result {
+ Ok(()) => 0,
+ Err(error) => {
+ eprintln!("Error: {error:?}");
+ 1
+ },
+ }
+}
diff --git a/scripts/benchmarks/platform-ios/bench_ios.py b/scripts/benchmarks/platform-ios/bench_ios.py
new file mode 100644
index 000000000..367c82035
--- /dev/null
+++ b/scripts/benchmarks/platform-ios/bench_ios.py
@@ -0,0 +1,349 @@
+import importlib.util
+import io
+import json
+import os
+import plistlib
+import shutil
+import socket
+import struct
+import subprocess
+import sys
+import tempfile
+import threading
+import time
+from contextlib import suppress
+from functools import cache
+from pathlib import Path
+from typing import Annotated, Any
+
+import typer
+from huggingface_hub import HfApi
+from huggingface_hub.constants import HF_HUB_CACHE
+
+PORT = 7171
+BUNDLE_ID = "com.mirai.tech.benchmarks"
+PHONE_CACHE = "Library/Caches/.cache"
+MAC_CACHE = Path("~/.cache").expanduser()
+DEVICE_CACHE = MAC_CACHE / "bench-ios/device"
+AVAILABLE_MEMORY_PERCENT = 0.75
+SPLASH_FAMILIES = Path(__file__).resolve().parents[1] / "engine-splash/deps/splash/install/families.py"
+
+app = typer.Typer(help="Run benchmark engines inside the iOS app and stream their output back.")
+Device = Annotated[
+ str | None,
+ typer.Option(
+ "--device",
+ help="UDID of the iPhone or iPad to use, remembered for later runs. Without it, the remembered one, or ask.",
+ ),
+]
+Host = Annotated[str | None, typer.Option("--host", help="Reach the app at this address instead of through usbmux.")]
+Engine = Annotated[
+ str,
+ typer.Option(
+ "-e", "--engine", help="llamacpp, mldrift, mlx, mlxserve, mtplx, omlx, splash or uzu, as in scripts/benchmarks."
+ ),
+]
+Model = Annotated[str, typer.Option("-m", "--model", help="Model identifier as the engine expects it.")]
+Arguments = Annotated[list[str] | None, typer.Argument(help="More engine arguments, after --, as on macOS.")]
+
+
+def receive(connection: socket.socket, size: int) -> bytes:
+ data = b""
+ while len(data) < size:
+ chunk = connection.recv(size - len(data))
+ if not chunk:
+ raise ConnectionError("The app closed the connection")
+ data += chunk
+ return data
+
+
+def usbmux(message: dict[str, Any]) -> tuple[socket.socket, dict[str, Any]]:
+ connection = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
+ connection.connect("/var/run/usbmuxd")
+ payload = plistlib.dumps({"ClientVersionString": "bench-ios", "ProgName": "bench-ios", **message})
+ connection.sendall(struct.pack("<4I", 16 + len(payload), 1, 8, 1) + payload)
+ length = struct.unpack("<4I", receive(connection, 16))[0]
+ return connection, plistlib.loads(receive(connection, length - 16))
+
+
+def coredevices() -> list[dict[str, Any]]:
+ with tempfile.NamedTemporaryFile() as output:
+ subprocess.run(
+ ["xcrun", "devicectl", "list", "devices", "--json-output", output.name], check=True, capture_output=True
+ )
+ devices = json.loads(Path(output.name).read_text())["result"]["devices"]
+ return [
+ device
+ for device in devices
+ if device["hardwareProperties"].get("platform") == "iOS"
+ and device["hardwareProperties"].get("reality") == "physical"
+ ]
+
+
+def choose_device() -> str:
+ devices = coredevices()
+ if not devices:
+ raise SystemExit("No iPhone or iPad is paired with this Mac; connect one and trust it")
+ try:
+ terminal = open("/dev/tty"), open("/dev/tty", "w") # noqa: SIM115
+ except OSError:
+ raise SystemExit("Pass --device UDID, or choose a device once with `bench-ios device`") from None
+ with terminal[0] as keyboard, terminal[1] as screen:
+ for index, device in enumerate(devices, 1):
+ name, hardware = device["deviceProperties"]["name"], device["hardwareProperties"]
+ state = device["connectionProperties"].get("tunnelState", "unknown")
+ print(f"{index}. {name}, {hardware['marketingName']}, {hardware['udid']} ({state})", file=screen)
+ print(f"Device to benchmark on [1-{len(devices)}]: ", end="", file=screen, flush=True)
+ answer = keyboard.readline().strip()
+ if not answer.isdigit() or not 1 <= int(answer) <= len(devices):
+ raise SystemExit(f"Not a device number: {answer!r}")
+ return devices[int(answer) - 1]["hardwareProperties"]["udid"]
+
+
+def device_udid(udid: str | None) -> str:
+ if udid is None and DEVICE_CACHE.is_file():
+ return DEVICE_CACHE.read_text().strip()
+ return udid or choose_device()
+
+
+def remember(udid: str) -> None:
+ DEVICE_CACHE.parent.mkdir(parents=True, exist_ok=True)
+ DEVICE_CACHE.write_text(udid + "\n")
+
+
+@cache
+def paired_device(udid: str | None) -> dict[str, Any]:
+ udid = device_udid(udid)
+ connection, reply = usbmux({"MessageType": "ListDevices"})
+ connection.close()
+ devices = [device["Properties"] for device in reply["DeviceList"] if device["Properties"]["SerialNumber"] == udid]
+ if devices:
+ device = min(devices, key=lambda device: device["ConnectionType"] != "USB")
+ else:
+ address = tunnel_address(udid)
+ if address is None:
+ subprocess.run(
+ ["xcrun", "devicectl", "device", "info", "details", "--device", udid], capture_output=True, check=False
+ )
+ address = tunnel_address(udid)
+ if address is None:
+ raise SystemExit(
+ f"Device {udid} is not connected; connect and unlock it, or choose another with `bench-ios device`"
+ )
+ device = {"SerialNumber": udid, "Address": address}
+ remember(udid)
+ return device
+
+
+def tunnel_address(udid: str) -> str | None:
+ return next(
+ (
+ device["connectionProperties"]["tunnelIPAddress"]
+ for device in coredevices()
+ if device["hardwareProperties"]["udid"] == udid and device["connectionProperties"].get("tunnelIPAddress")
+ ),
+ None,
+ )
+
+
+def connect(device: dict[str, Any] | None, host: str | None) -> socket.socket:
+ if device is None or "Address" in device:
+ return socket.create_connection((host or device["Address"], PORT))
+ connection, reply = usbmux(
+ {"MessageType": "Connect", "DeviceID": device["DeviceID"], "PortNumber": socket.htons(PORT)}
+ )
+ if reply.get("Number") != 0:
+ connection.close()
+ raise ConnectionRefusedError(f"usbmux refused port {PORT}: {reply}")
+ return connection
+
+
+def launch(device: dict[str, Any], *, fresh: bool) -> None:
+ options = ["--terminate-existing"] if fresh else []
+ command = ["xcrun", "devicectl", "device", "process", "launch", "--device", device["SerialNumber"], *options]
+ result = subprocess.run([*command, BUNDLE_ID], capture_output=True, text=True, check=False)
+ if result.returncode:
+ errors = [line.strip() for line in result.stderr.splitlines() if line.strip()]
+ raise SystemExit(
+ f"Could not launch the app on {device['SerialNumber']}: {errors[0] if errors else result.returncode}. "
+ "Unlock the device, keep it connected and install the app from Xcode first"
+ )
+
+
+def session(command: dict[str, Any], udid: str | None, host: str | None, *, fresh: bool = False) -> socket.socket:
+ device = None if host else paired_device(udid)
+ if device is not None:
+ launch(device, fresh=fresh)
+ for _ in range(60):
+ try:
+ connection = connect(device, host)
+ except OSError:
+ time.sleep(1)
+ continue
+ connection.sendall((json.dumps(command) + "\n").encode())
+ return connection
+ raise SystemExit("The app did not accept a connection; keep the device unlocked")
+
+
+def relay(connection: socket.socket, output: io.BufferedIOBase | None = None) -> int:
+ while True:
+ try:
+ kind, length = struct.unpack(">BI", receive(connection, 5))
+ payload = receive(connection, length)
+ except ConnectionError:
+ raise SystemExit(
+ "The app stopped before the engine finished; iOS ends apps that run out of memory or leave the "
+ "foreground, so keep the device unlocked and check its memory with smaller models"
+ ) from None
+ if kind == 3:
+ return struct.unpack(">i", payload)[0]
+ stream = (output or sys.stdout.buffer) if kind == 1 else sys.stderr.buffer
+ stream.write(payload)
+ stream.flush()
+
+
+def forward_stdin(connection: socket.socket) -> None:
+ with suppress(OSError):
+ while chunk := os.read(0, 1 << 16):
+ connection.sendall(struct.pack(">I", len(chunk)) + chunk)
+ connection.sendall(struct.pack(">I", 0))
+
+
+def finish(command: dict[str, Any], udid: str | None, host: str | None) -> None:
+ raise typer.Exit(relay(session(command, udid, host)))
+
+
+def physical_memory(udid: str | None, host: str | None) -> int:
+ output = io.BytesIO()
+ if relay(session({"command": "device"}, udid, host), output) != 0:
+ raise SystemExit("The app did not report its memory")
+ return json.loads(output.getvalue())["physical_memory_bytes"]
+
+
+def repository_files(repo: str) -> list[Any]:
+ return HfApi().model_info(repo, files_metadata=True).siblings or []
+
+
+def repository_size(repo: str) -> int:
+ return sum(file.lfs.size for file in repository_files(repo) if file.lfs is not None)
+
+
+def splash_draft_repositories() -> list[str]:
+ spec = importlib.util.spec_from_file_location("splash_families", SPLASH_FAMILIES)
+ if spec is None or spec.loader is None:
+ raise SystemExit(f"Bootstrap engine-splash first: {SPLASH_FAMILIES} is missing")
+ families = importlib.util.module_from_spec(spec)
+ sys.modules[spec.name] = families
+ spec.loader.exec_module(families)
+ return [family.draft_repo for family in families.FAMILIES]
+
+
+def fits_in_memory(engine: str, model: str, memory: int) -> bool:
+ if model.startswith(("/", "models/")):
+ return True
+ budget = memory * AVAILABLE_MEMORY_PERCENT
+ if engine == "llamacpp":
+ files = repository_files(model.partition(":")[0])
+ return any(file.size is not None and file.size <= budget for file in files if file.rfilename.endswith(".gguf"))
+ if engine == "splash":
+ repo, _, variant = model.partition(":")
+ files = repository_files(repo)
+ target = sum(file.size or 0 for file in files if file.rfilename.endswith(".gguf") and variant in file.rfilename)
+ return target + max(map(repository_size, splash_draft_repositories())) <= budget
+ return repository_size(model) <= budget
+
+
+def start(engine: str, model: str, arguments: list[str] | None, udid: str | None, host: str | None) -> socket.socket:
+ if not fits_in_memory(engine, model, physical_memory(udid, host)):
+ print("Skip, model is too large", file=sys.stderr)
+ raise typer.Exit(1)
+ command = {"command": "run", "engine": engine, "arguments": ["-m", model, *(arguments or [])]}
+ return session(command, udid, host, fresh=True)
+
+
+def resolve(model: str, staging: Path) -> tuple[Path, str]:
+ path = Path(model).expanduser()
+ if path.is_dir():
+ return shutil.copytree(path, staging / path.name), f"Documents/models/{path.name}"
+
+ mirai = MAC_CACHE / "mirai"
+ registry = mirai / "registry.json"
+ if registry.is_file():
+ for entry in json.loads(registry.read_text()):
+ repository = entry["accessibility"]["reference"]["repository"]
+ if repository["identifier"] != model:
+ continue
+ for directory in (mirai / "models").glob(f"*/*/{repository['commit_hash']}"):
+ return directory, f"{PHONE_CACHE}/mirai/{directory.relative_to(mirai)}"
+
+ hub = Path(HF_HUB_CACHE) / f"models--{model.replace('/', '--')}"
+ if hub.is_dir():
+ staged = staging / hub.name
+ shutil.copytree(hub, staged, ignore=shutil.ignore_patterns("blobs", ".locks"))
+ return staged, f"{PHONE_CACHE}/huggingface/hub/{hub.name}"
+
+ raise SystemExit(f"{model} is neither a directory nor cached in {MAC_CACHE}")
+
+
+def run(engine: Engine, model: Model, arguments: Arguments = None, device: Device = None, host: Host = None) -> None:
+ """Run an engine session in a fresh app process: requests on stdin, responses on stdout, logs on stderr."""
+ connection = start(engine, model, arguments, device, host)
+ threading.Thread(target=forward_stdin, args=(connection,), daemon=True).start()
+ raise typer.Exit(relay(connection))
+
+
+def download(
+ engine: Engine, model: Model, arguments: Arguments = None, device: Device = None, host: Host = None
+) -> None:
+ """Load the model as the engine does, downloading it into the app's cache, without running requests."""
+ connection = start(engine, model, arguments, device, host)
+ connection.sendall(struct.pack(">I", 0))
+ raise typer.Exit(relay(connection))
+
+
+def device(device: Device = None) -> None:
+ """Choose the iPhone or iPad to benchmark on, or remember the one given with --device."""
+ udid = device or choose_device()
+ if device is not None and udid not in (paired["hardwareProperties"]["udid"] for paired in coredevices()):
+ raise SystemExit(f"No iPhone or iPad {udid} is paired with this Mac")
+ remember(udid)
+ print(udid)
+
+
+def models(device: Device = None, host: Host = None) -> None:
+ """List cached models on the device as JSON."""
+ finish({"command": "models"}, device, host)
+
+
+def delete(path: str, device: Device = None, host: Host = None) -> None:
+ """Delete a cached model by the path that `models` reports."""
+ finish({"command": "delete", "path": path}, device, host)
+
+
+def push(model: str, device: Device = None) -> None:
+ """Copy a model from this Mac: a uzu registry identifier, a Hugging Face repository or a directory."""
+ udid = paired_device(device)["SerialNumber"]
+ with tempfile.TemporaryDirectory() as staging:
+ source, destination = resolve(model, Path(staging))
+ subprocess.run(
+ [
+ *("xcrun", "devicectl", "device", "copy", "to", "--device", udid),
+ *("--domain-type", "appDataContainer", "--domain-identifier", BUNDLE_ID),
+ *("--source", str(source), "--destination", destination),
+ ],
+ check=True,
+ )
+
+
+def main() -> None:
+ app()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/benchmarks/platform-ios/pyproject.toml b/scripts/benchmarks/platform-ios/pyproject.toml
new file mode 100644
index 000000000..f84361fd9
--- /dev/null
+++ b/scripts/benchmarks/platform-ios/pyproject.toml
@@ -0,0 +1,18 @@
+[project]
+name = "benchmarks-ios"
+version = "0.0.1"
+requires-python = ">=3.13.7"
+dependencies = [
+ "huggingface-hub>=0.36",
+ "typer>=0.27.2",
+]
+
+[build-system]
+requires = ["setuptools>=61"]
+build-backend = "setuptools.build_meta"
+
+[project.scripts]
+bench-ios = "bench_ios:main"
+
+[tool.setuptools]
+py-modules = ["bench_ios"]
diff --git a/scripts/benchmarks/platform-ios/uv.lock b/scripts/benchmarks/platform-ios/uv.lock
new file mode 100644
index 000000000..201cae9e8
--- /dev/null
+++ b/scripts/benchmarks/platform-ios/uv.lock
@@ -0,0 +1,318 @@
+version = 1
+revision = 5
+requires-python = ">=3.13.7"
+
+[[package]]
+name = "annotated-doc"
+version = "0.0.5"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/5a/8e/38aa427ed5402449e226975b649c5dc73ccadfefeb95e6aecb8f8ea4b6b6/annotated_doc-0.0.5.tar.gz", hash = "sha256:c7e58ce09192557605d8bbd92836d7e1d520ac9580096042c0bfd197efacf1bb", size = 10758, upload-time = "2026-07-28T13:50:58.129Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/3e/30/e900b21425a860e195f32e37657aa1f7c7f2b1bfb26f03ca209b90933c06/annotated_doc-0.0.5-py3-none-any.whl", hash = "sha256:117bac03a25ede5df5440e855b32d556049ca169ead221505badf432fed4b101", size = 5302, upload-time = "2026-07-28T13:50:57.239Z" },
+]
+
+[[package]]
+name = "anyio"
+version = "4.16.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "idna" },
+ { name = "typing-extensions", marker = "python_full_version < '3.15'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/a1/98/7e457a3b014976887a050561955c0b76e1e7e2d6e27b78ecef2ef80518f2/anyio-4.16.0.tar.gz", hash = "sha256:59bb03251907983d1603d27c3087ddb1e93299ea2163adcdba37899a4fb12ffb", size = 310971, upload-time = "2026-11-01T11:20:07.282Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/a9/16/7757fb84c819accc7d7e9af5291b261e4abb8627ee040f99e7d35ef2457a/anyio-4.16.0-py3-none-any.whl", hash = "sha256:c66ae634e0b8228396b801741beb3294326d4b6102f7bba4041c0dfb58c29026", size = 134521, upload-time = "2026-11-01T11:20:05.59Z" },
+]
+
+[[package]]
+name = "benchmarks-ios"
+version = "0.0.1"
+source = { editable = "." }
+dependencies = [
+ { name = "huggingface-hub" },
+ { name = "typer" },
+]
+
+[package.metadata]
+requires-dist = [
+ { name = "huggingface-hub", specifier = ">=0.36" },
+ { name = "typer", specifier = ">=0.27.2" },
+]
+
+[[package]]
+name = "click"
+version = "8.5.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/c7/0e/7fa0ef50764b67090eca4114772a2abf8b6148198475e54c660b97caeee6/click-8.5.0.tar.gz", hash = "sha256:ba0d2089de75ea0310e2dde03160e6ca10009947fb95a182f9b54021bb272e34", size = 382235, upload-time = "2026-08-26T13:33:14.56Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/58/50/6c0d534c5f134586a8e1ba4e330569e32f057e33372ae556463212fb4cd3/click-8.5.0-py3-none-any.whl", hash = "sha256:255bc9599cf7748b4b1a446ccc735421bd08a2ae529a8b88597d3de5664ee360", size = 125251, upload-time = "2026-08-26T13:33:12.928Z" },
+]
+
+[[package]]
+name = "colorama"
+version = "0.4.6"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/d8/53/6f443c9a4a8358a93a6792e2acffb9d9d5cb0a5cfd8802644b7b1c9a02e4/colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44", size = 27697, upload-time = "2022-10-25T02:36:22.414Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" },
+]
+
+[[package]]
+name = "filelock"
+version = "4.2.6"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/35/6c/730b340182f1fd74d4ef8d3f35431ce84f8f97b1a1f2afd145174b7bb047/filelock-4.2.6.tar.gz", hash = "sha256:ee7af8ede36dcaf12e1016d9f7c3a63ecd5497d46f85dab21b8c779b8f944e97", size = 661339, upload-time = "2026-10-31T15:10:16.889Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/b7/8d/3f849fcb79359259737bc2d8ddcaee6149ffb773239a260c9ff20179736f/filelock-4.2.6-py3-none-any.whl", hash = "sha256:fd7d4fca497bf3e3d0945a13261f8e684f2aef12ce7cf76aef26e13bf7388b88", size = 164378, upload-time = "2026-10-31T15:10:15.322Z" },
+]
+
+[[package]]
+name = "fsspec"
+version = "2026.9.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/77/cd/9be253869fc42e764de7f3dedd6969af7d44ff9c3375214a3442a6f3fc08/fsspec-2026.9.0.tar.gz", hash = "sha256:0f08147951c8cb31d844c3547d631053b127863b60be04cf06e121333ee0e2fe", size = 333545, upload-time = "2026-09-18T17:50:42.825Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/6c/c0/a98505f18594f1bce828bb159cec0fcf9860562f1a2c85913409fc8f3d9e/fsspec-2026.9.0-py3-none-any.whl", hash = "sha256:8dd6e646e99ea382bd85f97a45e6b526a442d79423a7dc673f1e2756d05fcb5f", size = 221738, upload-time = "2026-09-18T17:50:41.341Z" },
+]
+
+[[package]]
+name = "h11"
+version = "0.16.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/01/ee/02a2c011bdab74c6fb3c75474d40b3052059d95df7e73351460c8588d963/h11-0.16.0.tar.gz", hash = "sha256:4e35b956cf45792e4caa5885e69fba00bdbc6ffafbfa020300e549b208ee5ff1", size = 101250, upload-time = "2025-04-24T03:35:25.427Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/04/4b/29cac41a4d98d144bf5f6d33995617b185d14b22401f75ca86f384e87ff1/h11-0.16.0-py3-none-any.whl", hash = "sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86", size = 37515, upload-time = "2025-04-24T03:35:24.344Z" },
+]
+
+[[package]]
+name = "hf-xet"
+version = "1.8.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/2f/18/d91c20f815df6cc496a5d0ad8db6d274dad5c0cfcd59babfa2440a9aba44/hf_xet-1.8.0.tar.gz", hash = "sha256:10ed23b51dacf7917d64f335c25048deb470efa755e9989b218fc0531386138e", size = 1013014, upload-time = "2026-10-30T10:04:33.741Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/2c/18/db7ebc58820d82fd5506aa405a75611e7a4398f573dc436f7387603bf63d/hf_xet-1.8.0-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:c74e3751cbcdae9222c5170e8d788e83201a03dc5e5f4308a20f17a5b6023b56", size = 3883873, upload-time = "2026-10-30T10:04:03.24Z" },
+ { url = "https://files.pythonhosted.org/packages/37/bd/6c9ed89aafbeb4a7ee0d76d6b7b9365221e3e7ee47958aeecdc2c60a0511/hf_xet-1.8.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:56735c2d4f416d7473fc986586b26a8756e067832ca4b7fdaad32a0d6f2ce740", size = 3594510, upload-time = "2026-10-30T10:04:05.364Z" },
+ { url = "https://files.pythonhosted.org/packages/0e/1f/c26154b3a053b637c0984db0db9fdacbbfc257bdc2e95e9bc0782b745b0c/hf_xet-1.8.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:3ecfe2934448cca55a4c42732b60f985266aecb241905945219b3d388aceb7ba", size = 4281780, upload-time = "2026-10-30T10:04:07.35Z" },
+ { url = "https://files.pythonhosted.org/packages/e3/9e/d84c31f8e3acc286c9c6a4fd85f7f332e3db40636595f0de5ad776b69beb/hf_xet-1.8.0-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:7edeb21c5d381903ee5f4857fc746fa7b52a4b374035e8811ecfb67ee27add0c", size = 4060223, upload-time = "2026-10-30T10:04:09.029Z" },
+ { url = "https://files.pythonhosted.org/packages/a4/70/c142e4ad8a679ff6ffe40964a9d017fa0211aabca9ca4d3d547c3a2fc165/hf_xet-1.8.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:07a06d7481702616726c2d8578cfb00052a5b3f21beed6a674592bc837a10330", size = 4263619, upload-time = "2026-10-30T10:04:11.085Z" },
+ { url = "https://files.pythonhosted.org/packages/9d/08/92e03e3ac4eaeab046359093c447c03c8c30b577c2b1e1687dc747654f1c/hf_xet-1.8.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:f42940869572dc2b05dfe06f4cc398c6291503e086ddc4eddfb7a6ab9409ad01", size = 4493381, upload-time = "2026-10-30T10:04:13.022Z" },
+ { url = "https://files.pythonhosted.org/packages/61/63/a512b2906d0f92b5d325f58169d1fd8c3202a9ee61bd8405ec78c67e5315/hf_xet-1.8.0-cp314-cp314t-win_amd64.whl", hash = "sha256:23c262e9f5e137b18dadbce60becfeea84156b0d43119c320bffe260d32cd2fa", size = 3901344, upload-time = "2026-10-30T10:04:15.051Z" },
+ { url = "https://files.pythonhosted.org/packages/2d/5e/b453f82690cb36f176c4b01e64d6d32757fabbf34dbb9bcbdf747e429a79/hf_xet-1.8.0-cp314-cp314t-win_arm64.whl", hash = "sha256:62b056aedb89ac809f78940baf465fe553b70c8b25ee56890fbab3039fffec1b", size = 3731681, upload-time = "2026-10-30T10:04:16.855Z" },
+ { url = "https://files.pythonhosted.org/packages/97/74/d89d5235524bc14d8519e12ca8bc5204f45009ae83d63a410f52c29eb4a8/hf_xet-1.8.0-cp38-abi3-macosx_10_12_x86_64.whl", hash = "sha256:e00d8f60170cd3dd55d98306e41dbaf28b27ff1bcfefbfa84279d197221be83e", size = 3875002, upload-time = "2026-10-30T10:04:18.958Z" },
+ { url = "https://files.pythonhosted.org/packages/d4/f2/ef25e2085e92dcaeaa675331e443923aed2006f6fe2d984e15d8b8d40766/hf_xet-1.8.0-cp38-abi3-macosx_11_0_arm64.whl", hash = "sha256:3e8934784425781f0f779b91044df441f3a7af4dab47375d7e3aeaecbb8eecb4", size = 3600947, upload-time = "2026-10-30T10:04:20.906Z" },
+ { url = "https://files.pythonhosted.org/packages/f8/1e/1e8ecc05ef034e9a95c18ed32d2ec07905a7cd2ca611a9d88e25ee1f4850/hf_xet-1.8.0-cp38-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:29dab7c904cd1914a0439c6e1306c12c7497c8bd32290fbe563ebf51ca4b6d6d", size = 4292483, upload-time = "2026-10-30T10:04:22.875Z" },
+ { url = "https://files.pythonhosted.org/packages/35/c4/127a1548df019ea4c80f06e685f263e146075143335a02e78a3c41dbc4eb/hf_xet-1.8.0-cp38-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:8800e3444770f2c630b361bc6d5c6ebb770b7830646cf632fbb79d0e5bbc9e7f", size = 4069340, upload-time = "2026-10-30T10:04:24.664Z" },
+ { url = "https://files.pythonhosted.org/packages/a5/d5/281cd82736c3e181e597588589d2204d3a5c388a464d4a2a8c546995bae9/hf_xet-1.8.0-cp38-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:a584a7b3268da62f23c3187cc7201ca01f7b610985a36b1b6119c66bccb0383c", size = 4272344, upload-time = "2026-10-30T10:04:26.519Z" },
+ { url = "https://files.pythonhosted.org/packages/48/77/886f09e91a5eadb054ce03b8855323cd2a72f20db76ab4119e0ecda65eef/hf_xet-1.8.0-cp38-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:1ebaf248c9bef8bb0c9d1d8d71db1fdf0cac14f922cc7a936a81adbf12eb5f01", size = 4500689, upload-time = "2026-10-30T10:04:28.394Z" },
+ { url = "https://files.pythonhosted.org/packages/97/4d/2c76a992b370ff77d0b5219275779f8c9a7dabb8ee649deb265dfed84d0f/hf_xet-1.8.0-cp38-abi3-win_amd64.whl", hash = "sha256:92188598dedc1e1f5609bd718d4db8687a6c89915553912571e2f587892eecec", size = 3911559, upload-time = "2026-10-30T10:04:30.165Z" },
+ { url = "https://files.pythonhosted.org/packages/87/91/fdb1454a43eff8011047d176ada2f0fb4926cf3d74b87357ff35793f6d98/hf_xet-1.8.0-cp38-abi3-win_arm64.whl", hash = "sha256:42b66fdc688eaa4ff3eb77dc9275e5a0f1258ecc9fdd083ddaf43bb49bec925b", size = 3738458, upload-time = "2026-10-30T10:04:31.882Z" },
+]
+
+[[package]]
+name = "httpcore2"
+version = "2.16.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "h11" },
+ { name = "truststore" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/c0/61/afa9d6b7452f9eca73f73d45324eb0bb52f098fd5e6049bf6b8263be9b4e/httpcore2-2.16.0.tar.gz", hash = "sha256:c72cd0413563b17e1cd8354677dff887466f8ec2551679759e93126534428643", size = 69886, upload-time = "2026-10-21T07:09:45.31Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/af/c2/ce417c397afa5181f0e3c6ff01a4d01639414e1adef08730d97571297151/httpcore2-2.16.0-py3-none-any.whl", hash = "sha256:5c4358319f2602d984ad93182c9fee5160f22e9da7babdda870a5e7c4e2dc34f", size = 85070, upload-time = "2026-10-21T07:09:42.802Z" },
+]
+
+[[package]]
+name = "httpx2"
+version = "2.16.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "anyio", marker = "sys_platform != 'emscripten'" },
+ { name = "httpcore2", marker = "sys_platform != 'emscripten'" },
+ { name = "httpx2-jsfetch", marker = "sys_platform == 'emscripten'" },
+ { name = "idna" },
+ { name = "truststore", marker = "sys_platform != 'emscripten'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/43/73/5ca2cedf5e4e50423d1c258877865a6b62793633b561c58499f8aeb33b7e/httpx2-2.16.0.tar.gz", hash = "sha256:0d54c98128e8f2ff7fbbde0fca8c359e5f032edeaaaac443cdb7f31f685bcd7f", size = 103116, upload-time = "2026-10-21T07:09:46.348Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/7b/3d/2e4bc4fd1ef9770871669adb348d612a6e4786b303a23f9935b81c48dd60/httpx2-2.16.0-py3-none-any.whl", hash = "sha256:fd2c5d7909e8d86fe92d53020c310ca0e4e431b838c207c5754b9bbf0308d49a", size = 97880, upload-time = "2026-10-21T07:09:44.01Z" },
+]
+
+[[package]]
+name = "httpx2-jsfetch"
+version = "1.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/cd/c4/0e5636363151a2a1795e0a77617168b9ca438e1748ec05fc9b5687f93d64/httpx2_jsfetch-1.0.tar.gz", hash = "sha256:70a0e3eabfef7cce5ad9c629f7d01ca05e418f586646f4ddf14782e4c1454c60", size = 6872, upload-time = "2026-08-07T00:13:07.492Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/9b/43/832f631d32e4f1211caa2ba368317739fe71f0b8530e4c9d15dc454bac2a/httpx2_jsfetch-1.0-py3-none-any.whl", hash = "sha256:cb916b707601e69a07721aabc8f3f6659be3a6893bc1ff5c6f9e02241df2da32", size = 6382, upload-time = "2026-08-07T00:13:06.567Z" },
+]
+
+[[package]]
+name = "huggingface-hub"
+version = "2.4.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "click" },
+ { name = "filelock" },
+ { name = "fsspec" },
+ { name = "hf-xet", marker = "platform_machine == 'AMD64' or platform_machine == 'ARM64' or platform_machine == 'aarch64' or platform_machine == 'amd64' or platform_machine == 'arm64' or platform_machine == 'x86_64'" },
+ { name = "httpx2" },
+ { name = "packaging" },
+ { name = "pyyaml" },
+ { name = "tqdm" },
+ { name = "typing-extensions" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/b5/3b/2fcef1eabe52aec90fc8cd253cc154da1d02a446d7bbcdec59b4a51d4be7/huggingface_hub-2.4.0.tar.gz", hash = "sha256:13a6158b9e3393d9d3f248ce99074d50c2a0a1449fb9d8e2f710751e2084c188", size = 1066194, upload-time = "2026-10-29T15:30:12.321Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/d4/55/ff47f1b082ecf5f43f4bc1e3b932d68eead171dabbbd1a92666c686301d7/huggingface_hub-2.4.0-py3-none-any.whl", hash = "sha256:42ecfd93ede47bdd333daebbf66a32d7bfe2e18752754fe4d2d4f98a0179d801", size = 857021, upload-time = "2026-10-29T15:30:10.421Z" },
+]
+
+[[package]]
+name = "idna"
+version = "3.20"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/f5/08/8eea9d4b8302028f3abb2c0813953f7aec26d33b7a8960ed760e65ff29fa/idna-3.20.tar.gz", hash = "sha256:a7db850025b95ded1eae8a46181a1a6c56c92c96f0e2b005d9ff8dc0210cab44", size = 216463, upload-time = "2026-09-17T14:11:04.752Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/58/a2/bb081bab032533a855d44de1d56f8e8426114ff1ba5d1f07a438a0a654f8/idna-3.20-py3-none-any.whl", hash = "sha256:ab7ae7122974553370f0bdb919e1a960b2cd1bc1ef0276416d896db81c14582c", size = 69583, upload-time = "2026-09-17T14:11:03.168Z" },
+]
+
+[[package]]
+name = "markdown-it-py"
+version = "4.2.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "mdurl" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/06/ff/7841249c247aa650a76b9ee4bbaeae59370dc8bfd2f6c01f3630c35eb134/markdown_it_py-4.2.0.tar.gz", hash = "sha256:04a21681d6fbb623de53f6f364d352309d4094dd4194040a10fd51833e418d49", size = 82454, upload-time = "2026-05-07T12:08:28.36Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/b3/81/4da04ced5a082363ecfa159c010d200ecbd959ae410c10c0264a38cac0f5/markdown_it_py-4.2.0-py3-none-any.whl", hash = "sha256:9f7ebbcd14fe59494226453aed97c1070d83f8d24b6fc3a3bcf9a38092641c4a", size = 91687, upload-time = "2026-05-07T12:08:27.182Z" },
+]
+
+[[package]]
+name = "mdurl"
+version = "0.1.2"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/d6/54/cfe61301667036ec958cb99bd3efefba235e65cdeb9c84d24a8293ba1d90/mdurl-0.1.2.tar.gz", hash = "sha256:bb413d29f5eea38f31dd4754dd7377d4465116fb207585f97bf925588687c1ba", size = 8729, upload-time = "2022-08-14T12:40:10.846Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/b3/38/89ba8ad64ae25be8de66a6d463314cf1eb366222074cfda9ee839c56a4b4/mdurl-0.1.2-py3-none-any.whl", hash = "sha256:84008a41e51615a49fc9966191ff91509e3c40b939176e643fd50a5c2196b8f8", size = 9979, upload-time = "2022-08-14T12:40:09.779Z" },
+]
+
+[[package]]
+name = "packaging"
+version = "26.3"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/7d/fa/3944b40b07da9ce895c0e6303a5ab7d53da063554f534556b134a54d6093/packaging-26.3.tar.gz", hash = "sha256:94edc256424af38762eb31306eed28beb9f0efc50a8837492c9d6fd6004aed79", size = 313412, upload-time = "2026-08-04T18:15:28.737Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/63/34/ba1c580383c9eada3711951fef0795c80b829a078d72188184bcab9dd527/packaging-26.3-py3-none-any.whl", hash = "sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c", size = 129956, upload-time = "2026-08-04T18:15:27.159Z" },
+]
+
+[[package]]
+name = "pygments"
+version = "2.21.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/49/2e/ced460408999b33da6b31b0021b0f37d329e202d4169aeb164493778f25b/pygments-2.21.0.tar.gz", hash = "sha256:610ca751c9bc2492b38eb9a38a7fbc93edbbb2d7182edaf34e66ae493dee5c8c", size = 5005329, upload-time = "2026-08-17T08:02:48.824Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/71/46/17f022dd3e953bf20a04a028a21ec746d942f8d2af30fa0f124fa0e6a684/pygments-2.21.0-py3-none-any.whl", hash = "sha256:2363c69b61c4a97c838da3b130dcd6468f4848992b21a82f2a63ec34377137d9", size = 1250147, upload-time = "2026-08-17T08:02:44.912Z" },
+]
+
+[[package]]
+name = "pyyaml"
+version = "6.0.3"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/05/8e/961c0007c59b8dd7729d542c61a4d537767a59645b82a0b521206e1e25c2/pyyaml-6.0.3.tar.gz", hash = "sha256:d76623373421df22fb4cf8817020cbb7ef15c725b9d5e45f17e189bfc384190f", size = 130960, upload-time = "2025-09-25T21:33:16.546Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/d1/11/0fd08f8192109f7169db964b5707a2f1e8b745d4e239b784a5a1dd80d1db/pyyaml-6.0.3-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:8da9669d359f02c0b91ccc01cac4a67f16afec0dac22c2ad09f46bee0697eba8", size = 181669, upload-time = "2025-09-25T21:32:23.673Z" },
+ { url = "https://files.pythonhosted.org/packages/b1/16/95309993f1d3748cd644e02e38b75d50cbc0d9561d21f390a76242ce073f/pyyaml-6.0.3-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:2283a07e2c21a2aa78d9c4442724ec1eb15f5e42a723b99cb3d822d48f5f7ad1", size = 173252, upload-time = "2025-09-25T21:32:25.149Z" },
+ { url = "https://files.pythonhosted.org/packages/50/31/b20f376d3f810b9b2371e72ef5adb33879b25edb7a6d072cb7ca0c486398/pyyaml-6.0.3-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ee2922902c45ae8ccada2c5b501ab86c36525b883eff4255313a253a3160861c", size = 767081, upload-time = "2025-09-25T21:32:26.575Z" },
+ { url = "https://files.pythonhosted.org/packages/49/1e/a55ca81e949270d5d4432fbbd19dfea5321eda7c41a849d443dc92fd1ff7/pyyaml-6.0.3-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:a33284e20b78bd4a18c8c2282d549d10bc8408a2a7ff57653c0cf0b9be0afce5", size = 841159, upload-time = "2025-09-25T21:32:27.727Z" },
+ { url = "https://files.pythonhosted.org/packages/74/27/e5b8f34d02d9995b80abcef563ea1f8b56d20134d8f4e5e81733b1feceb2/pyyaml-6.0.3-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0f29edc409a6392443abf94b9cf89ce99889a1dd5376d94316ae5145dfedd5d6", size = 801626, upload-time = "2025-09-25T21:32:28.878Z" },
+ { url = "https://files.pythonhosted.org/packages/f9/11/ba845c23988798f40e52ba45f34849aa8a1f2d4af4b798588010792ebad6/pyyaml-6.0.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:f7057c9a337546edc7973c0d3ba84ddcdf0daa14533c2065749c9075001090e6", size = 753613, upload-time = "2025-09-25T21:32:30.178Z" },
+ { url = "https://files.pythonhosted.org/packages/3d/e0/7966e1a7bfc0a45bf0a7fb6b98ea03fc9b8d84fa7f2229e9659680b69ee3/pyyaml-6.0.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:eda16858a3cab07b80edaf74336ece1f986ba330fdb8ee0d6c0d68fe82bc96be", size = 794115, upload-time = "2025-09-25T21:32:31.353Z" },
+ { url = "https://files.pythonhosted.org/packages/de/94/980b50a6531b3019e45ddeada0626d45fa85cbe22300844a7983285bed3b/pyyaml-6.0.3-cp313-cp313-win32.whl", hash = "sha256:d0eae10f8159e8fdad514efdc92d74fd8d682c933a6dd088030f3834bc8e6b26", size = 137427, upload-time = "2025-09-25T21:32:32.58Z" },
+ { url = "https://files.pythonhosted.org/packages/97/c9/39d5b874e8b28845e4ec2202b5da735d0199dbe5b8fb85f91398814a9a46/pyyaml-6.0.3-cp313-cp313-win_amd64.whl", hash = "sha256:79005a0d97d5ddabfeeea4cf676af11e647e41d81c9a7722a193022accdb6b7c", size = 154090, upload-time = "2025-09-25T21:32:33.659Z" },
+ { url = "https://files.pythonhosted.org/packages/73/e8/2bdf3ca2090f68bb3d75b44da7bbc71843b19c9f2b9cb9b0f4ab7a5a4329/pyyaml-6.0.3-cp313-cp313-win_arm64.whl", hash = "sha256:5498cd1645aa724a7c71c8f378eb29ebe23da2fc0d7a08071d89469bf1d2defb", size = 140246, upload-time = "2025-09-25T21:32:34.663Z" },
+ { url = "https://files.pythonhosted.org/packages/9d/8c/f4bd7f6465179953d3ac9bc44ac1a8a3e6122cf8ada906b4f96c60172d43/pyyaml-6.0.3-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:8d1fab6bb153a416f9aeb4b8763bc0f22a5586065f86f7664fc23339fc1c1fac", size = 181814, upload-time = "2025-09-25T21:32:35.712Z" },
+ { url = "https://files.pythonhosted.org/packages/bd/9c/4d95bb87eb2063d20db7b60faa3840c1b18025517ae857371c4dd55a6b3a/pyyaml-6.0.3-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:34d5fcd24b8445fadc33f9cf348c1047101756fd760b4dacb5c3e99755703310", size = 173809, upload-time = "2025-09-25T21:32:36.789Z" },
+ { url = "https://files.pythonhosted.org/packages/92/b5/47e807c2623074914e29dabd16cbbdd4bf5e9b2db9f8090fa64411fc5382/pyyaml-6.0.3-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:501a031947e3a9025ed4405a168e6ef5ae3126c59f90ce0cd6f2bfc477be31b7", size = 766454, upload-time = "2025-09-25T21:32:37.966Z" },
+ { url = "https://files.pythonhosted.org/packages/02/9e/e5e9b168be58564121efb3de6859c452fccde0ab093d8438905899a3a483/pyyaml-6.0.3-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:b3bc83488de33889877a0f2543ade9f70c67d66d9ebb4ac959502e12de895788", size = 836355, upload-time = "2025-09-25T21:32:39.178Z" },
+ { url = "https://files.pythonhosted.org/packages/88/f9/16491d7ed2a919954993e48aa941b200f38040928474c9e85ea9e64222c3/pyyaml-6.0.3-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c458b6d084f9b935061bc36216e8a69a7e293a2f1e68bf956dcd9e6cbcd143f5", size = 794175, upload-time = "2025-09-25T21:32:40.865Z" },
+ { url = "https://files.pythonhosted.org/packages/dd/3f/5989debef34dc6397317802b527dbbafb2b4760878a53d4166579111411e/pyyaml-6.0.3-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:7c6610def4f163542a622a73fb39f534f8c101d690126992300bf3207eab9764", size = 755228, upload-time = "2025-09-25T21:32:42.084Z" },
+ { url = "https://files.pythonhosted.org/packages/d7/ce/af88a49043cd2e265be63d083fc75b27b6ed062f5f9fd6cdc223ad62f03e/pyyaml-6.0.3-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:5190d403f121660ce8d1d2c1bb2ef1bd05b5f68533fc5c2ea899bd15f4399b35", size = 789194, upload-time = "2025-09-25T21:32:43.362Z" },
+ { url = "https://files.pythonhosted.org/packages/23/20/bb6982b26a40bb43951265ba29d4c246ef0ff59c9fdcdf0ed04e0687de4d/pyyaml-6.0.3-cp314-cp314-win_amd64.whl", hash = "sha256:4a2e8cebe2ff6ab7d1050ecd59c25d4c8bd7e6f400f5f82b96557ac0abafd0ac", size = 156429, upload-time = "2025-09-25T21:32:57.844Z" },
+ { url = "https://files.pythonhosted.org/packages/f4/f4/a4541072bb9422c8a883ab55255f918fa378ecf083f5b85e87fc2b4eda1b/pyyaml-6.0.3-cp314-cp314-win_arm64.whl", hash = "sha256:93dda82c9c22deb0a405ea4dc5f2d0cda384168e466364dec6255b293923b2f3", size = 143912, upload-time = "2025-09-25T21:32:59.247Z" },
+ { url = "https://files.pythonhosted.org/packages/7c/f9/07dd09ae774e4616edf6cda684ee78f97777bdd15847253637a6f052a62f/pyyaml-6.0.3-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:02893d100e99e03eda1c8fd5c441d8c60103fd175728e23e431db1b589cf5ab3", size = 189108, upload-time = "2025-09-25T21:32:44.377Z" },
+ { url = "https://files.pythonhosted.org/packages/4e/78/8d08c9fb7ce09ad8c38ad533c1191cf27f7ae1effe5bb9400a46d9437fcf/pyyaml-6.0.3-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:c1ff362665ae507275af2853520967820d9124984e0f7466736aea23d8611fba", size = 183641, upload-time = "2025-09-25T21:32:45.407Z" },
+ { url = "https://files.pythonhosted.org/packages/7b/5b/3babb19104a46945cf816d047db2788bcaf8c94527a805610b0289a01c6b/pyyaml-6.0.3-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6adc77889b628398debc7b65c073bcb99c4a0237b248cacaf3fe8a557563ef6c", size = 831901, upload-time = "2025-09-25T21:32:48.83Z" },
+ { url = "https://files.pythonhosted.org/packages/8b/cc/dff0684d8dc44da4d22a13f35f073d558c268780ce3c6ba1b87055bb0b87/pyyaml-6.0.3-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:a80cb027f6b349846a3bf6d73b5e95e782175e52f22108cfa17876aaeff93702", size = 861132, upload-time = "2025-09-25T21:32:50.149Z" },
+ { url = "https://files.pythonhosted.org/packages/b1/5e/f77dc6b9036943e285ba76b49e118d9ea929885becb0a29ba8a7c75e29fe/pyyaml-6.0.3-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:00c4bdeba853cc34e7dd471f16b4114f4162dc03e6b7afcc2128711f0eca823c", size = 839261, upload-time = "2025-09-25T21:32:51.808Z" },
+ { url = "https://files.pythonhosted.org/packages/ce/88/a9db1376aa2a228197c58b37302f284b5617f56a5d959fd1763fb1675ce6/pyyaml-6.0.3-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:66e1674c3ef6f541c35191caae2d429b967b99e02040f5ba928632d9a7f0f065", size = 805272, upload-time = "2025-09-25T21:32:52.941Z" },
+ { url = "https://files.pythonhosted.org/packages/da/92/1446574745d74df0c92e6aa4a7b0b3130706a4142b2d1a5869f2eaa423c6/pyyaml-6.0.3-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:16249ee61e95f858e83976573de0f5b2893b3677ba71c9dd36b9cf8be9ac6d65", size = 829923, upload-time = "2025-09-25T21:32:54.537Z" },
+ { url = "https://files.pythonhosted.org/packages/f0/7a/1c7270340330e575b92f397352af856a8c06f230aa3e76f86b39d01b416a/pyyaml-6.0.3-cp314-cp314t-win_amd64.whl", hash = "sha256:4ad1906908f2f5ae4e5a8ddfce73c320c2a1429ec52eafd27138b7f1cbe341c9", size = 174062, upload-time = "2025-09-25T21:32:55.767Z" },
+ { url = "https://files.pythonhosted.org/packages/f1/12/de94a39c2ef588c7e6455cfbe7343d3b2dc9d6b6b2f40c4c6565744c873d/pyyaml-6.0.3-cp314-cp314t-win_arm64.whl", hash = "sha256:ebc55a14a21cb14062aa4162f906cd962b28e2e9ea38f9b4391244cd8de4ae0b", size = 149341, upload-time = "2025-09-25T21:32:56.828Z" },
+]
+
+[[package]]
+name = "rich"
+version = "15.0.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "markdown-it-py" },
+ { name = "pygments" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/c0/8f/0722ca900cc807c13a6a0c696dacf35430f72e0ec571c4275d2371fca3e9/rich-15.0.0.tar.gz", hash = "sha256:edd07a4824c6b40189fb7ac9bc4c52536e9780fbbfbddf6f1e2502c31b068c36", size = 230680, upload-time = "2026-04-12T08:24:00.75Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/82/3b/64d4899d73f91ba49a8c18a8ff3f0ea8f1c1d75481760df8c68ef5235bf5/rich-15.0.0-py3-none-any.whl", hash = "sha256:33bd4ef74232fb73fe9279a257718407f169c09b78a87ad3d296f548e27de0bb", size = 310654, upload-time = "2026-04-12T08:24:02.83Z" },
+]
+
+[[package]]
+name = "shellingham"
+version = "1.5.4"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/58/15/8b3609fd3830ef7b27b655beb4b4e9c62313a4e8da8c676e142cc210d58e/shellingham-1.5.4.tar.gz", hash = "sha256:8dbca0739d487e5bd35ab3ca4b36e11c4078f3a234bfce294b0a0291363404de", size = 10310, upload-time = "2023-10-24T04:13:40.426Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/e0/f9/0595336914c5619e5f28a1fb793285925a8cd4b432c9da0a987836c7f822/shellingham-1.5.4-py2.py3-none-any.whl", hash = "sha256:7ecfff8f2fd72616f7481040475a65b2bf8af90a56c89140852d1120324e8686", size = 9755, upload-time = "2023-10-24T04:13:38.866Z" },
+]
+
+[[package]]
+name = "tqdm"
+version = "4.70.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "colorama", marker = "sys_platform == 'win32'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/0d/ea/b2a5bd54b28a324dae8211928b2d730b6547500342c7e6c6dea08bd0a485/tqdm-4.70.1.tar.gz", hash = "sha256:cefd0eca11b2a37a3aee776544d4f4ae913f02688135b5556b8788dfa474afc4", size = 171846, upload-time = "2026-09-11T07:25:16.601Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/a7/03/921a3d3c75785aca9ebfbfcabfbc3a1be12e2ab5265deb026d55a5a3f83e/tqdm-4.70.1-py3-none-any.whl", hash = "sha256:c293e525e6fef9c20e8728fd4612df02a0aa31bb5fe91ecd93e123b1b7bffa73", size = 80199, upload-time = "2026-09-11T07:25:14.599Z" },
+]
+
+[[package]]
+name = "truststore"
+version = "0.10.5"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/ee/9f/c5201d42a484c061e528825fc8e2d565f5abd50a4ced6fb7d29c4ec99b2b/truststore-0.10.5.tar.gz", hash = "sha256:30d36967ccaded5cbb38d602c433f53600036c79d502f4533a49b60a03bbefcd", size = 28091, upload-time = "2026-10-12T22:27:31.808Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/51/e9/3a7820be2bb0fe53b6bc9c3be26d3d1158004e4c3ab953aa6840b955b1e9/truststore-0.10.5-py3-none-any.whl", hash = "sha256:9aaaedaefaf06d8b206278cf8b5012bc897f485a874503501e12d776df78951c", size = 19017, upload-time = "2026-10-12T22:27:30.377Z" },
+]
+
+[[package]]
+name = "typer"
+version = "0.27.3"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "annotated-doc" },
+ { name = "colorama", marker = "sys_platform == 'win32'" },
+ { name = "rich" },
+ { name = "shellingham" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/03/51/d33db42cc72ffd8c30777547b42d01f0cbf9d95a770457698d0174b3ed71/typer-0.27.3.tar.gz", hash = "sha256:d0396f770a560ab1b0a8504e13b5f254b728cedb05c61cf0359e944e50ce8901", size = 205303, upload-time = "2026-10-06T17:24:16.61Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/07/ea/2e31b67051e91a133189e9c000c222502ddc6969856416de0d095de4c0b0/typer-0.27.3-py3-none-any.whl", hash = "sha256:e50022f28b82a86313e54501317a1db64bf8f8d036ff8cfe5ca7e47675454aff", size = 123312, upload-time = "2026-10-06T17:24:15.054Z" },
+]
+
+[[package]]
+name = "typing-extensions"
+version = "4.16.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/f6/cc/6253133b5bb138fc3306cebfbda2c520f545d36b5be2c7255cc528bb45d6/typing_extensions-4.16.0.tar.gz", hash = "sha256:dc983d19a509c94dba722ee6abd33940f7c05a89e243c47e907eb4db6f1a43e5", size = 113555, upload-time = "2026-07-02T08:40:05.92Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/49/d3/b8441a820a491ddfc024b0b0cf0393375b75ea13866d9c66727e54c2fc80/typing_extensions-4.16.0-py3-none-any.whl", hash = "sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8", size = 45571, upload-time = "2026-07-02T08:40:04.659Z" },
+]
diff --git a/scripts/benchmarks/tests/conftest.py b/scripts/benchmarks/tests/conftest.py
index b4758a8c3..b55cde06e 100644
--- a/scripts/benchmarks/tests/conftest.py
+++ b/scripts/benchmarks/tests/conftest.py
@@ -4,9 +4,10 @@ from pathlib import Path
import pytest
-from tests.engines import llamacpp, mldrift, mlx, mlxserve, mtplx, omlx, splash, uzu
+from tests.engines import ios, llamacpp, mldrift, mlx, mlxserve, mtplx, omlx, splash, uzu
ENGINE_TEST_CLASSES = {
+ "ios": "TestIOS",
"llamacpp": "TestLlamaCpp",
"mldrift": "TestMLDrift",
"mlx": "TestMLX",
@@ -28,6 +29,7 @@ def pytest_addoption(parser: pytest.Parser) -> None:
help="Engine to test (repeatable).",
)
group.addoption("--engine-timeout", type=float, default=600, help="Response timeout in seconds, including startup.")
+ ios.add_options(parser)
llamacpp.add_options(parser)
mldrift.add_options(parser)
mlx.add_options(parser)
@@ -44,7 +46,7 @@ def pytest_configure(config: pytest.Config) -> None:
test_file = Path(__file__).with_name("test_engines.py")
if "engines" in config.args:
config.args[:] = [str(test_file) if arg == "engines" else arg for arg in config.args]
- engines.extend(name for name in ENGINE_TEST_CLASSES if name not in engines)
+ engines.extend(name for name in ENGINE_TEST_CLASSES if name not in engines and name != "ios")
for name, test_class in ENGINE_TEST_CLASSES.items():
if name not in config.args:
diff --git a/scripts/benchmarks/tests/engines/ios.py b/scripts/benchmarks/tests/engines/ios.py
new file mode 100644
index 000000000..17618889c
--- /dev/null
+++ b/scripts/benchmarks/tests/engines/ios.py
@@ -0,0 +1,34 @@
+"""Launch an engine inside the iOS app through the platform-ios bridge."""
+
+import pytest
+
+from .engine_tests import EngineTests
+
+ENGINE = "uzu"
+MODEL = "trymirai/LFM2.5-230M-M"
+
+
+def add_options(parser: pytest.Parser) -> None:
+ group = parser.getgroup("iOS")
+ group.addoption("--ios-engine", default=ENGINE, help="Engine inside the app, as bench-ios run --engine takes it.")
+ group.addoption("--ios-model", default=MODEL, help="Model identifier as the engine expects it.")
+ group.addoption("--ios-device", default=None, help="UDID of the device. Defaults to the one bench-ios remembers.")
+ group.addoption("--ios-host", default=None, help="Reach the app at this address instead of through usbmux.")
+
+
+class TestIOS(EngineTests):
+ engine_name = "ios"
+
+ @staticmethod
+ def command(config: pytest.Config) -> list[str]:
+ command = ["uv", "run", "--project", "platform-ios", "bench-ios", "run"]
+ command += ["--engine", config.getoption("ios_engine"), "--model", config.getoption("ios_model")]
+ for option in ("device", "host"):
+ if value := config.getoption(f"ios_{option}"):
+ command += [f"--{option}", value]
+ return command
+
+ @pytest.fixture(autouse=True)
+ def skip_unsupported(self, request: pytest.FixtureRequest) -> None:
+ if request.config.getoption("ios_engine") == "mldrift" and request.node.originalname == "test_sampling":
+ pytest.skip("ML Drift decodes greedily on the GPU and rejects sampling")
diff --git a/scripts/benchmarks/tests/test_engines.py b/scripts/benchmarks/tests/test_engines.py
index ea9538b69..83d068289 100644
--- a/scripts/benchmarks/tests/test_engines.py
+++ b/scripts/benchmarks/tests/test_engines.py
@@ -1,5 +1,6 @@
"""Collect the engine-specific classes with pytest's default file discovery."""
+from .engines.ios import TestIOS
from .engines.llamacpp import TestLlamaCpp
from .engines.mldrift import TestMLDrift
from .engines.mlx import TestMLX
@@ -9,4 +10,14 @@ from .engines.omlx import TestOMLX
from .engines.splash import TestSplash
from .engines.uzu import TestUzu
-__all__ = ["TestLlamaCpp", "TestMLDrift", "TestMLX", "TestMLXServe", "TestMTPLX", "TestOMLX", "TestSplash", "TestUzu"]
+__all__ = [
+ "TestIOS",
+ "TestLlamaCpp",
+ "TestMLDrift",
+ "TestMLX",
+ "TestMLXServe",
+ "TestMTPLX",
+ "TestOMLX",
+ "TestSplash",
+ "TestUzu",
+]