TensorFlow Lite Core 機器學習委派

TensorFlow Lite Core 機器學習委派可讓您在 Core ML 架構上執行 TensorFlow Lite 模型,進而在 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,在 Podfile 中加入子規格 CoreML

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

OR

# 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,C API 中的 coreml_version) 設為較舊版本。

支援的作業

Core ML 委派支援下列作業。

  • 新增
    • 只有特定形狀可以播送。在 Core ML Tensoror 版面配置中 以下張量形狀是可以廣播的[B, C, H, W][B, C, 1, 1][B, 1, H, W][B, 1, 1, 1]
  • 平均集區 2D
  • Concat
    • 請沿著管道軸串連。
  • 轉換 2D
    • 權重和偏誤應保持一致。
  • DepthwiseConv2D
    • 權重和偏誤應保持一致。
  • FullyConnected (又稱 Dense 或 InnerProduct)
    • 權重和偏誤 (如有) 應維持不變。
    • 僅支援單一批次案例。輸入維度應為 1,但最後一個維度除外。
  • 哈德瓦文
  • 物流 (又稱 Sigmoid)
  • MaxPool2D
  • MirrorPad
    • 僅支援使用 REFLECT 模式的 4D 輸入裝置。邊框間距應設為常數,而且只能用於 H 和 W 維度。
  • Mul
    • 只有特定形狀可以播送。在 Core ML Tensoror 版面配置中 以下張量形狀是可以廣播的[B, C, H, W][B, C, 1, 1][B, 1, H, W][B, 1, 1, 1]
  • Pad 和 PadV2
    • 這項功能僅支援 4D 輸入裝置,邊框間距應設為常數,而且只能用於 H 和 W 維度。
  • 希臘
  • ReluN1To1
  • Relu6
  • 重塑
    • 只有在目標 Core ML 版本為 2 的情況下才支援此版本,指定 Core ML 3 時則不支援。
  • ResizeBilinear
  • SoftMax
  • 轉置轉換
    • 權重應維持不變。

意見回饋:

如果是問題,請建立 GitHub 問題,並提供重現的所有必要詳細資料。

常見問題

  • 如果圖表包含不支援的運算,CoreML 委派支援是否能回退給 CPU?
  • CoreML 委派功能可以在 iOS 模擬器中運作嗎?
    • 是的。這個程式庫包含 x86 和 x86_64 目標,因此可以透過模擬器執行,但您無法看到 CPU 的效能提升。
  • TensorFlow Lite 和 CoreML 委派功能是否支援 MacOS?
    • TensorFlow Lite 僅在 iOS 上進行測試,而 MacOS 無法測試。
  • 系統是否支援自訂 TF Lite 運算?
    • 否,CoreML 委派不支援自訂作業,且將回退給 CPU。

API