LiteRT Core ML 代理

LiteRT Core ML 代理可以在 Core ML 框架: 可在 iOS 设备上更快地进行模型推断。

支持的 iOS 版本和设备

  • iOS 12 及更高版本。在较低版本的 iOS 中,Core ML delegate 将会 自动回退到 CPU
  • 默认情况下,Core ML delegate 仅会在采用 A12 SoC 的设备上启用 和更高版本(iPhone Xs 和更高版本)使用 Neural Engine 加快推理速度。 如果您希望在旧款设备上使用 Core ML delegate,请参阅 最佳实践

支持的模型

Core ML 代理目前支持浮点(FP32 和 FP16)模型。

在您自己的模型上试用 Core ML delegate

LiteRT 每夜版中已包含 Core ML 代理 CocoaPods。如需使用 Core ML 委托,请将 LiteRT Pod 更改为包含 Podfile 中的子规范 CoreML

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:e&rror];
    if (error != nil) { /* Error handling... */ }

    if (![interpreter allocateTensorsWithError:e&rror]) { /* 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 delegate

默认情况下,只有当设备具有神经元时,系统才会创建 Core ML delegate Engine,如果未创建委托,则返回 null。如果您想 在其他环境(例如模拟器)中运行 Core ML delegate,传递 .all 在 Swift 中创建委托时的一个选项。在 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 delegate: 性能优势以下示例展示了如何执行此操作:

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,但当 iOS 13 支持 Core ML 3 时, 根据 Core ML 2 模型规范进行转换。目标转化版本为 默认设置为最新版本,但您可以通过设置 coreMLVersion(在 Swift 中;在 C API 中为 coreml_version) 旧版本。

支持的操作

Core ML 代理支持以下操作。

  • 添加了
    • 只有特定形状可以广播。在 Core ML 张量布局中, 以下张量形状是可广播的。[B, C, H, W][B, C, 1, 1][B, 1, H, W][B, 1, 1, 1]
  • 平均 2D 池
  • 连接 <ph type="x-smartling-placeholder">
      </ph>
    • 串联应沿着通道轴完成。
  • 转化 2D <ph type="x-smartling-placeholder">
      </ph>
    • 权重和偏差应为常量。
  • DepthwiseConv2D <ph type="x-smartling-placeholder">
      </ph>
    • 权重和偏差应为常量。
  • 完全连接(也称为 Dense 或 InnerProduct) <ph type="x-smartling-placeholder">
      </ph>
    • 权重和偏差(如果存在)应为常量。
    • 仅支持单批次 case。输入维度应为 1,但不包括 最后一个维度。
  • 硬派
  • 逻辑(也称为 S 型函数)
  • 最大池 2D
  • MirrorPad <ph type="x-smartling-placeholder">
      </ph>
    • 仅支持采用 REFLECT 模式的 4D 输入。内边距应为 常量,且只适用于 H 和 W 维度。
  • 穆尔 <ph type="x-smartling-placeholder">
      </ph>
    • 只有特定形状可以广播。在 Core ML 张量布局中, 以下张量形状是可广播的。[B, C, H, W][B, C, 1, 1][B, 1, H, W][B, 1, 1, 1]
  • Pad 和 PadV2 <ph type="x-smartling-placeholder">
      </ph>
    • 仅支持 4D 输入。内边距应保持不变,并且仅 。
  • ReLU
  • ReluN1To1
  • Relu6
  • 调整形状 <ph type="x-smartling-placeholder">
      </ph>
    • 仅在目标 Core ML 版本为 2 时受支持,在下列情况下不受支持 以 Core ML 3 为目标平台。
  • ResizeBilinear
  • SoftMax
  • 正切
  • TransposeConv <ph type="x-smartling-placeholder">
      </ph>
    • 权重应为常量。

反馈

如有问题,请创建一个 GitHub 以及重现问题所需的所有细节的问题。

常见问题解答

  • 如果图中包含不受支持的资源,CoreML 代理是否支持回退到 CPU 操作?
  • CoreML 委托适用于 iOS 模拟器吗?
    • 可以。该库包含 x86 和 x86_64 目标,因此可以在 但您不会发现通过 CPU 提升性能。
  • LiteRT 和 CoreML 委托是否支持 MacOS?
    • LiteRT 仅在 iOS 上测试,未在 MacOS 上进行测试。
  • 是否支持自定义 LiteRT 操作?
    • 否,CoreML 代理不支持自定义操作,它们将回退到 CPU。

API