LiteRT CompiledModel Swift API

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 arm64 only).

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

  1. Open your app project in Xcode and select File > Add Package Dependencies (see Adding package dependencies to your app).
  2. In the search field, enter the following URL:

    https://github.com/google-ai-edge/LiteRT-Swift
    
  3. Select 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.

  4. Select the products to add to your app target. Most apps add LiteRT and, to run models on the GPU, LiteRtMetalAccelerator. Click Add Package.

  5. Add your .tflite model to the app target so that Xcode copies it into the app bundle, and add import LiteRT to 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, a Data buffer, 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 as CpuOptions, through ConcreteOptions and OpaqueOptions.
  • TensorBuffer: Holds tensor memory backed by host memory or a Metal buffer (MTLBuffer), with typed read and write methods.
  • TensorType, Layout, and Quantization: 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:

  1. Link the LiteRtMetalAccelerator product to your app target alongside LiteRT. Environment() automatically discovers the bundled Metal accelerator.
  2. Pass [.gpu, .cpu] to options.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 the Environment with the .metalDevice(_:) and .metalCommandQueue(_:) options, which take pointers to your MTLDevice and MTLCommandQueue. Then pass a pointer to the buffer to TensorBuffer(metalBuffer:size:tensorType:bufferType:environment:). To get these pointers, use Unmanaged.passUnretained(_:).toOpaque(). LiteRT doesn't take ownership of these objects, so keep the MTLDevice, the MTLCommandQueue, and the MTLBuffer alive for as long as the Environment and the TensorBuffer use them. A TensorBuffer doesn't keep a reference to its Environment, so also keep the Environment alive for as long as the TensorBuffer exists. To get the Metal memory handle of a GPU-allocated buffer, call tensorBuffer.metalMemory().
  • Asynchronous dispatch: Call compiledModel.dispatch(inputs:outputs:) to enqueue execution on the accelerator without blocking the CPU. Subsequent read() calls wait for execution to complete.

For more information about GPU acceleration and supported models, see GPU acceleration with LiteRT.