Tensorflow Lite Core ML 委派

TensorFlow Lite Core ML 委派功能可讓 TensorFlow Lite 模型在 Core ML 框架上執行,進而在 iOS 裝置上實現更快的模型推論速度。

支援的 iOS 版本和裝置

  • iOS 12 及更高版本。在較舊的 iOS 版本中,Core ML 委派將自動回退至 CPU。
  • 預設情況下,Core ML 委派功能僅在配備 A12 SoC 及更高版本(iPhone Xs 及更高版本)的裝置上啟用,以使用 Neural Engine 進行更快的推論。如果您也想在較舊的裝置上使用 Core ML 委派功能,請參閱最佳實務做法

支援的模型

Core ML 委派功能目前支援浮點 (FP32 和 FP16) 模型。

在您自己的模型上試用 Core ML 委派功能

TensorFlow Lite CocoaPods 的每夜版版本已包含 Core ML 委派功能。若要使用 Core ML 委派功能,請變更您的 TensorFlow Lite Pod,將 CoreML 子規格包含在您的 Podfile 中。

target 'YourProjectName'
  pod 'TensorFlowLiteSwift/CoreML', '~> 2.4.0'  # Or TensorFlowLiteObjC/CoreML

# Particularily useful when you also want to include 'Metal' subspec.
target 'YourProjectName'
  pod 'TensorFlowLiteSwift', '~> 2.4.0', :subspecs => ['CoreML']

Swift

    let coreMLDelegate = CoreMLDelegate()
    var interpreter: Interpreter

    // Core ML delegate will only be created for devices with Neural Engine
    if coreMLDelegate != nil {
      interpreter = try Interpreter(modelPath: modelPath,
                                    delegates: [coreMLDelegate!])
    } else {
      interpreter = try Interpreter(modelPath: modelPath)
    }
  

Objective-C

    // Import module when using CocoaPods with module support
    @import TFLTensorFlowLite;

    // Or import following headers manually
    # import "tensorflow/lite/objc/apis/TFLCoreMLDelegate.h"
    # import "tensorflow/lite/objc/apis/TFLTensorFlowLite.h"

    // Initialize Core ML delegate
    TFLCoreMLDelegate* coreMLDelegate = [[TFLCoreMLDelegate alloc] init];

    // Initialize interpreter with model path and Core ML delegate
    TFLInterpreterOptions* options = [[TFLInterpreterOptions alloc] init];
    NSError* error = nil;
    TFLInterpreter* interpreter = [[TFLInterpreter alloc]
                                    initWithModelPath:modelPath
                                              options:options
                                            delegates:@[ coreMLDelegate ]
                                                error:&error];
    if (error != nil) { /* Error handling... */ }

    if (![interpreter allocateTensorsWithError:&error]) { /* Error handling... */ }
    if (error != nil) { /* Error handling... */ }

    // Run inference ...
  

C (直到 2.3.0)

    #include "tensorflow/lite/delegates/coreml/coreml_delegate.h"

    // Initialize interpreter with model
    TfLiteModel* model = TfLiteModelCreateFromFile(model_path);

    // Initialize interpreter with Core ML delegate
    TfLiteInterpreterOptions* options = TfLiteInterpreterOptionsCreate();
    TfLiteDelegate* delegate = TfLiteCoreMlDelegateCreate(NULL);  // default config
    TfLiteInterpreterOptionsAddDelegate(options, delegate);
    TfLiteInterpreterOptionsDelete(options);

    TfLiteInterpreter* interpreter = TfLiteInterpreterCreate(model, options);

    TfLiteInterpreterAllocateTensors(interpreter);

    // Run inference ...

    /* ... */

    // Dispose resources when it is no longer used.
    // Add following code to the section where you dispose of the delegate
    // (e.g. `dealloc` of class).

    TfLiteInterpreterDelete(interpreter);
    TfLiteCoreMlDelegateDelete(delegate);
    TfLiteModelDelete(model);
      

最佳實務做法

在沒有 Neural Engine 的裝置上使用 Core ML 委派功能

預設情況下,只有在裝置具有 Neural Engine 時才會建立 Core ML 委派,如果未建立委派,則會傳回 null。如果您想在其他環境(例如,模擬器)上執行 Core ML 委派功能,請在 Swift 中建立委派時傳遞 .all 作為選項。在 C++(和 Objective-C)中,您可以傳遞 TfLiteCoreMlDelegateAllDevices。以下範例示範如何執行此操作

Swift

    var options = CoreMLDelegate.Options()
    options.enabledDevices = .all
    let coreMLDelegate = CoreMLDelegate(options: options)!
    let interpreter = try Interpreter(modelPath: modelPath,
                                      delegates: [coreMLDelegate])
      

Objective-C

    TFLCoreMLDelegateOptions* coreMLOptions = [[TFLCoreMLDelegateOptions alloc] init];
    coreMLOptions.enabledDevices = TFLCoreMLDelegateEnabledDevicesAll;
    TFLCoreMLDelegate* coreMLDelegate = [[TFLCoreMLDelegate alloc]
                                          initWithOptions:coreMLOptions];

    // Initialize interpreter with delegate
  

C

    TfLiteCoreMlDelegateOptions options;
    options.enabled_devices = TfLiteCoreMlDelegateAllDevices;
    TfLiteDelegate* delegate = TfLiteCoreMlDelegateCreate(&options);
    // Initialize interpreter with delegate
      

使用 Metal (GPU) 委派作為回退方案。

當未建立 Core ML 委派時,您仍然可以使用 Metal 委派來獲得效能優勢。以下範例示範如何執行此操作

Swift

    var delegate = CoreMLDelegate()
    if delegate == nil {
      delegate = MetalDelegate()  // Add Metal delegate options if necessary.
    }

    let interpreter = try Interpreter(modelPath: modelPath,
                                      delegates: [delegate!])
  

Objective-C

    TFLDelegate* delegate = [[TFLCoreMLDelegate alloc] init];
    if (!delegate) {
      // Add Metal delegate options if necessary
      delegate = [[TFLMetalDelegate alloc] init];
    }
    // Initialize interpreter with delegate
      

C

    TfLiteCoreMlDelegateOptions options = {};
    delegate = TfLiteCoreMlDelegateCreate(&options);
    if (delegate == NULL) {
      // Add Metal delegate options if necessary
      delegate = TFLGpuDelegateCreate(NULL);
    }
    // Initialize interpreter with delegate
      

委派建立邏輯會讀取裝置的機器 ID(例如 iPhone11,1)以判斷其 Neural Engine 的可用性。請參閱程式碼以瞭解更多詳細資訊。或者,您可以使用其他程式庫(例如 DeviceKit)來實作您自己的拒絕清單裝置集。

使用較舊的 Core ML 版本

雖然 iOS 13 支援 Core ML 3,但當模型使用 Core ML 2 模型規格轉換時,效能可能會更好。目標轉換版本預設設定為最新版本,但您可以透過在委派選項中將 coreMLVersion(在 Swift 中為 coreml_version,在 C API 中)設定為較舊版本來變更此設定。

支援的運算元

Core ML 委派功能支援以下運算元。

  • Add
    • 僅特定形狀可廣播。在 Core ML 張量佈局中,以下張量形狀可廣播。 [B, C, H, W][B, C, 1, 1][B, 1, H, W][B, 1, 1, 1]
  • AveragePool2D
  • Concat
    • 串連應沿著通道軸完成。
  • Conv2D
    • 權重和偏差應為常數。
  • DepthwiseConv2D
    • 權重和偏差應為常數。
  • FullyConnected (又稱 Dense 或 InnerProduct)
    • 權重和偏差(如果存在)應為常數。
    • 僅支援單一批次案例。輸入維度應為 1,最後一個維度除外。
  • Hardswish
  • Logistic (又稱 Sigmoid)
  • MaxPool2D
  • MirrorPad
    • 僅支援具有 REFLECT 模式的 4D 輸入。填充應為常數,且僅允許用於 H 和 W 維度。
  • Mul
    • 僅特定形狀可廣播。在 Core ML 張量佈局中,以下張量形狀可廣播。 [B, C, H, W][B, C, 1, 1][B, 1, H, W][B, 1, 1, 1]
  • Pad 和 PadV2
    • 僅支援 4D 輸入。填充應為常數,且僅允許用於 H 和 W 維度。
  • Relu
  • ReluN1To1
  • Relu6
  • Reshape
    • 僅在目標 Core ML 版本為 2 時支援,目標為 Core ML 3 時不支援。
  • ResizeBilinear
  • SoftMax
  • Tanh
  • TransposeConv
    • 權重應為常數。

意見回饋

如有問題,請建立 GitHub issue 並提供所有必要的詳細資訊以重現問題。

FAQ

  • 如果圖形包含不支援的運算元,CoreML 委派是否支援回退至 CPU?
  • CoreML 委派是否適用於 iOS 模擬器?
    • 是。該程式庫包含 x86 和 x86_64 目標,因此可以在模擬器上執行,但您不會看到比 CPU 更高的效能提升。
  • TensorFlow Lite 和 CoreML 委派是否支援 MacOS?
    • TensorFlow Lite 僅在 iOS 上進行測試,但未在 MacOS 上進行測試。
  • 是否支援自訂 TF Lite 運算元?
    • 否,CoreML 委派不支援自訂運算元,它們將回退至 CPU。

API