TensorFlow Lite Core ML Delegate enables running TensorFlow Lite models on Core ML framework, which results in faster model inference on iOS devices.
Initialize TensorFlow Lite interpreter with Core ML delegate.
let coreMlDelegate = CoreMLDelegate() let interpreter = try Interpreter(modelPath: modelPath, delegates: [coreMLDelegate])
Include coreml_delegate.h.
#include "tensorflow/lite/experimental/delegates/coreml/coreml_delegate.h"
Modify code following interpreter initialization to apply delegate.
// initializer interpreter with model. tflite::InterpreterBuilder(*model, resolver)(&interpreter); // Add following section to use Core ML delegate. TfLiteCoreMlDelegateOptions options = {}; delegate = TfLiteCoreMlDelegateCreate(&options); interpreter->ModifyGraphWithDelegate(delegate); // ...
Add this code to the section where you dispose of the delegate (e.g. dealloc of class).
TfLiteCoreMlDelegateDelete(delegate);
Following ops are supported by the Core ML delegate.
[B, C, H, W], [B, C, 1, 1], [B, 1, H, W], [B, 1, 1, 1].REFLECT mode is supported. Padding should be constant, and is only allowed for H and W dimensions.[B, C, H, W], [B, C, 1, 1], [B, 1, H, W], [B, 1, 1, 1]./// A delegate that uses the `Core ML` framework for performing /// TensorFlow Lite graph operations. /// /// - Important: This is an experimental interface that is subject to change. public final class CoreMLDelegate: Delegate { /// The configuration options for the `CoreMLDelegate`. public let options: Options // Conformance to the `Delegate` protocol. public private(set) var cDelegate: CDelegate * /// Creates a new instance configured with the given `options`. /// /// - Parameters: /// - options: Configurations for the delegate. The default is a new instance of /// `CoreMLDelegate.Options` with the default configuration values. public init(options: Options = Options()) { self.options = options var delegateOptions = TfLiteCoreMlDelegateOptions() cDelegate = TfLiteCoreMlDelegateCreate(&delegateOptions) } deinit { TfLiteCoreMlDelegateDelete(cDelegate) } } extension CoreMLDelegate { /// Options for configuring the `CoreMLDelegate`. public struct Options: Equatable, Hashable { /// Creates a new instance with the default values. public init() {} } }
typedef struct { // We have dummy for now as we can't have empty struct in C. char dummy; } TfLiteCoreMlDelegateOptions; // Return a delegate that uses CoreML for ops execution. // Must outlive the interpreter. TfLiteDelegate* TfLiteCoreMlDelegateCreate( const TfLiteCoreMlDelegateOptions* options); // Do any needed cleanup and delete 'delegate'. void TfLiteCoreMlDelegateDelete(TfLiteDelegate* delegate);