TensorFlow Lite Core ML 代理支持在 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 代理
Core ML 代理已包含在 TensorFlow lite CocoaPods 的 nightly 版本中。要使用 Core ML 代理,请将您的 TensorFlow lite 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:&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 代理支持以下操作。
- Add- 仅支持某些形状的广播。在 Core ML 张量布局中,以下张量形状支持广播。 [B, C, H, W]、[B, C, 1, 1]、[B, 1, H, W]、[B, 1, 1, 1]。
 
- 仅支持某些形状的广播。在 Core ML 张量布局中,以下张量形状支持广播。 
- 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]。
 
- 仅支持某些形状的广播。在 Core ML 张量布局中,以下张量形状支持广播。 
- Pad 和 PadV2- 仅支持 4D 输入。填充应为常量,并且仅允许用于 H 和 W 维度。
 
- Relu
- ReluN1To1
- Relu6
- Reshape- 仅在目标 Core ML 版本为 2 时支持,在针对 Core ML 3 时不支持。
 
- ResizeBilinear
- SoftMax
- Tanh
- TransposeConv- 权重应为常量。
 
反馈
对于问题,请创建一个包含所有必要详细信息以重现问题的 GitHub 问题。
常见问题解答
- CoreML 代理是否支持在图包含不支持的操作时回退到 CPU?- 是的
 
- CoreML 代理是否适用于 iOS 模拟器?- 是的。该库包含 x86 和 x86_64 目标,因此它可以在模拟器上运行,但您不会看到比 CPU 更高的性能提升。
 
- TensorFlow Lite 和 CoreML 代理是否支持 MacOS?- TensorFlow Lite 仅在 iOS 上经过测试,而不是 MacOS。
 
- 是否支持自定义 TF Lite 操作?- 不,CoreML 代理不支持自定义操作,它们将回退到 CPU。
 
API
- Core ML 代理 Swift API
- Core ML 代理 C API
- 这可用于 Objective-C 代码。~~~