The LiteRT CompiledModel API is available in Swift for iOS and macOS,
providing a type-safe Swift wrapper over the LiteRT C API for loading,
compiling, and running .tflite models with hardware acceleration (CPU with
XNNPACK and GPU with Metal). For an end-to-end app example, see the
iOS image segmentation sample app.
Apps consume the Swift package from the
LiteRT-Swift repository using
Swift Package Manager. The Swift sources are developed in the
LiteRT repository
and mirrored to LiteRT-Swift so that Swift Package Manager clones only a small
repository. The native runtimes are prebuilt .xcframework archives published
with each LiteRT release.
Swift Package Manager downloads them on demand and verifies them by checksum.
If your app uses the legacy Interpreter API on iOS, see the
LiteRT Interpreter Swift API (iOS) guide. To migrate an
existing app, see the migration guide.
Requirements
Before adding the LiteRT Swift package to your project, verify that your environment meets the following requirements:
- Xcode 15.0 or later (Swift tools 5.9).
- An app targeting iOS 15 or later, or macOS 12 or later.
- An Apple silicon Mac to run your app in the iOS Simulator (the Simulator
slices are
arm64only).
Add the Swift package
Add https://github.com/google-ai-edge/LiteRT-Swift to your app in Xcode or
through a Package.swift manifest.
Add in Xcode
- Open your app project in Xcode and select File > Add Package Dependencies (see Adding package dependencies to your app).
In the search field, enter the following URL:
https://github.com/google-ai-edge/LiteRT-SwiftSelect the version of LiteRT to use. Package versions follow the LiteRT releases (for example,
2.4.1). Set Dependency Rule to Up to Next Major Version with the release version as the minimum version, and then click Add Package.Select the products to add to your app target. Most apps add
LiteRTand, to run models on the GPU,LiteRtMetalAccelerator. Click Add Package.Add your
.tflitemodel to the app target so that Xcode copies it into the app bundle, and addimport LiteRTto your Swift code.
Add in a Package.swift manifest
If you manage dependencies in a Package.swift manifest, add LiteRT-Swift to
your package dependencies and link the required products in your target:
dependencies: [
.package(url: "https://github.com/google-ai-edge/LiteRT-Swift", from: "2.4.1"),
],
targets: [
.target(
name: "MyApp",
dependencies: [
.product(name: "LiteRT", package: "LiteRT-Swift"),
// Optional: include for Metal GPU acceleration
.product(name: "LiteRtMetalAccelerator", package: "LiteRT-Swift"),
]
),
]
Swift package products
The LiteRT-Swift package provides the products listed in the following table:
| Product | Contents and platforms |
|---|---|
LiteRT |
LiteRT Swift module. Swift Package Manager picks the linkage. Supports iOS and macOS. |
LiteRT_static |
LiteRT with the Swift wrapper linked statically. Supports iOS and macOS. |
LiteRT_dynamic |
LiteRT with the Swift wrapper linked dynamically. Supports iOS and macOS. |
LiteRtMetalAccelerator |
Prebuilt Metal GPU accelerator, as a dynamic framework. Supports iOS and macOS. |
CLiteRT_static |
Static LiteRT C API for C and Objective-C, in the CLiteRT_static module. Supports iOS only. |
TensorFlowLite |
Legacy TensorFlowLite Swift module (Interpreter, SignatureRunner), without the Core ML and Metal delegates. Supports iOS only. |
The LiteRT_static and LiteRT_dynamic product types affect only the Swift
wrapper. The C runtime always comes from CLiteRT.xcframework (a dynamic
framework) on iOS and CLiteRT_mac.xcframework (a dylib) on macOS.
Key types
The LiteRT Swift module exposes the following primary types:
Environment: Holds runtime environment options (such as compiler or dispatch plugin library paths, a Metal device, or a command queue) and the registered hardware accelerators.CompiledModel: Loads a model from a path, aDatabuffer, or a file descriptor, and compiles it. It runs inference synchronously (run) or asynchronously when supported (dispatch), and it exposes buffer requirements and tensor metadata.Options: Selects hardware accelerators (.cpu,.gpu) and other compilation settings. You attach accelerator-specific settings, such asCpuOptions, throughConcreteOptionsandOpaqueOptions.TensorBuffer: Holds tensor memory backed by host memory or a Metal buffer (MTLBuffer), with typedreadandwritemethods.TensorType,Layout, andQuantization: Describe tensor element types, shapes, strides, and quantization parameters.
Run basic inference
The following example loads a .tflite model bundled with your app, compiles it
for the CPU or the Metal GPU, runs inference, and reads the output tensor:
import Foundation
import LiteRT
func runInference(useGpu: Bool) throws {
// 1. Initialize the LiteRT environment. It locates the Metal accelerator
// automatically when the app links the `LiteRtMetalAccelerator` product.
let environment = try Environment()
// 2. Configure compilation options.
let options = try Options()
if useGpu {
// Run on the Metal GPU, and fall back to the CPU for unsupported ops.
try options.setHardwareAccelerators([.gpu, .cpu])
} else {
try options.setHardwareAccelerators([.cpu])
// Optionally tune the CPU backend: XNNPACK delegate with 4 threads.
let cpuOptions = try CpuOptions()
try cpuOptions.setKernelMode(.delegate)
try cpuOptions.setNumThreads(4)
try options.addConcreteOptions(cpuOptions)
}
// 3. Load and compile the model, which the app bundles as a resource.
guard
let modelPath = Bundle.main.path(
forResource: "simple_add_model",
ofType: "tflite"
)
else {
throw CocoaError(.fileNoSuchFile)
}
let compiledModel = try CompiledModel(
filePath: modelPath,
environment: environment,
options: options
)
// 4. Allocate input and output buffers from the model requirements.
let inputBuffers = try compiledModel.createInputBuffers()
let outputBuffers = try compiledModel.createOutputBuffers()
// 5. Populate the input buffers.
let input0Data: [Float] = [1.0, 2.0]
let input1Data: [Float] = [10.0, 20.0]
try inputBuffers[0].write(input0Data)
try inputBuffers[1].write(input1Data)
// 6. Run inference.
try compiledModel.run(inputs: inputBuffers, outputs: outputBuffers)
// 7. Read the output.
let outputData: [Float] = try outputBuffers[0].read()
print("Output elements: \(outputData)") // Expected: [11.0, 22.0]
}
You can also initialize CompiledModel from an in-memory Data buffer
(CompiledModel(data:environment:options:)) or from a file descriptor
(CompiledModel(fd:offset:size:environment:options:)). When options is
omitted, CompiledModel compiles for the CPU by default.
GPU acceleration and Metal interop
To accelerate inference on the Apple GPU with Metal, do the following:
- Link the
LiteRtMetalAcceleratorproduct to your app target alongsideLiteRT.Environment()automatically discovers the bundled Metal accelerator. - Pass
[.gpu, .cpu]tooptions.setHardwareAccelerators(_:)so that supported ops run on Metal and unsupported ops fall back to the CPU.
For advanced pipelines that keep tensors in GPU memory, use the following features:
- Zero-copy Metal buffers: To wrap an existing
MTLBuffer, create theEnvironmentwith the.metalDevice(_:)and.metalCommandQueue(_:)options, which take pointers to yourMTLDeviceandMTLCommandQueue. Then pass a pointer to the buffer toTensorBuffer(metalBuffer:size:tensorType:bufferType:environment:). To get these pointers, useUnmanaged.passUnretained(_:).toOpaque(). LiteRT doesn't take ownership of these objects, so keep theMTLDevice, theMTLCommandQueue, and theMTLBufferalive for as long as theEnvironmentand theTensorBufferuse them. ATensorBufferdoesn't keep a reference to itsEnvironment, so also keep theEnvironmentalive for as long as theTensorBufferexists. To get the Metal memory handle of a GPU-allocated buffer, calltensorBuffer.metalMemory(). - Asynchronous dispatch: Call
compiledModel.dispatch(inputs:outputs:)to enqueue execution on the accelerator without blocking the CPU. Subsequentread()calls wait for execution to complete.
For more information about GPU acceleration and supported models, see GPU acceleration with LiteRT.