LiteRT Interpreter Swift API (iOS)

The LiteRT-Swift Swift package includes the legacy TensorFlowLite Swift module (Interpreter and SignatureRunner). Existing iOS apps that use import TensorFlowLite can run .tflite models through Swift Package Manager without rewriting inference code. For the implementation, see the TensorFlowLite Swift source in the LiteRT repository.

For sample iOS apps using the recommended CompiledModel API, see the iOS image segmentation sample and the LiteRT samples repository.

Requirements

  • Xcode 15.0 or later (Swift tools 5.9).
  • An app targeting iOS 15 or later. The TensorFlowLite product supports iOS only. For macOS support, use the LiteRT CompiledModel Swift API.
  • 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 iOS project 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 (for example, 2.4.1), set Dependency Rule to Up to Next Major Version, and then click Add Package.

  4. Select the TensorFlowLite product for your app target and then click Add Package.

  5. Add your .tflite model to the app target so that Xcode copies it into the app bundle.

Add in a Package.swift manifest

If you manage dependencies in a Package.swift manifest, add LiteRT-Swift and link the TensorFlowLite product:

dependencies: [
  .package(url: "https://github.com/google-ai-edge/LiteRT-Swift", from: "2.4.1"),
],
targets: [
  .target(
    name: "MyApp",
    dependencies: [
      .product(name: "TensorFlowLite", package: "LiteRT-Swift"),
    ]
  ),
]

Run inference with the Interpreter API

The following example loads a .tflite model, allocates tensors, copies input data, invokes the interpreter, and reads the output tensor. It assumes a model whose first input is a Float32 tensor with two elements and whose first output is a Float32 tensor. Change the input data to match your model. The copy(_:toInputAt:) method throws an error if the data size differs from the size of the input tensor.

import Foundation
import TensorFlowLite

func runInference() throws {
  // 1. Locate the model bundled with your app.
  guard
    let modelPath = Bundle.main.path(forResource: "model", ofType: "tflite")
  else {
    throw CocoaError(.fileNoSuchFile)
  }

  // 2. Configure and create the interpreter.
  var options = Interpreter.Options()
  options.threadCount = 2
  let interpreter = try Interpreter(modelPath: modelPath, options: options)

  // 3. Allocate memory for the model's input tensors.
  try interpreter.allocateTensors()

  // 4. Copy input data to the first input tensor.
  let inputFloats: [Float32] = [1.0, 2.0]
  let inputData = inputFloats.withUnsafeBufferPointer { Data(buffer: $0) }
  try interpreter.copy(inputData, toInputAt: 0)

  // 5. Run inference.
  try interpreter.invoke()

  // 6. Read the output tensor.
  let outputTensor = try interpreter.output(at: 0)
  var outputFloats = [Float32](
    repeating: 0,
    count: outputTensor.data.count / MemoryLayout<Float32>.stride
  )
  _ = outputFloats.withUnsafeMutableBytes {
    outputTensor.data.copyBytes(to: $0)
  }
  print("Output: \(outputFloats)")
}

You can also initialize Interpreter from in-memory Data (Interpreter(modelData:options:)), resize dynamic input shapes with resizeInput(at:to:) before calling allocateTensors(), or run named signatures with signatureRunner(with:). For the full class reference, see the Swift Interpreter API reference.

Next steps