Tensorflow Lite Core ML 위임

TensorFlow Lite Core ML 위임을 사용하면 Core ML 프레임워크에서 TensorFlow Lite 모델을 실행할 수 있으므로 iOS 기기에서 모델 추론 속도가 더 빨라집니다.

지원되는 iOS 버전 및 기기:

  • iOS 12 이상 이전 iOS 버전에서는 Core ML 위임이 자동으로 CPU로 대체됩니다.
  • 더 빠른 추론을 위해 Neural Engine을 사용하기 위해 Core ML 위임은 기본적으로 A12 SoC 이상 (iPhone Xs 이상)이 설치된 기기에서만 사용 설정됩니다. 이전 기기에서도 Core ML 위임을 사용하려면 권장사항을 참조하세요.

지원되는 모델

Core ML 위임은 현재 부동 (FP32 및 FP16) 모델을 지원합니다.

자체 모델에 Core ML 위임 사용해 보기

Core ML 위임은 TensorFlow Lite CocoaPods의 야간 출시 버전에 이미 포함되어 있습니다. Core ML 위임을 사용하려면 Podfile에 하위 사양 CoreML를 포함하도록 TensorFlow lite Pod를 변경합니다.

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 위임 사용

기본적으로 Core ML 대리자는 기기에 Neural Engine이 있는 경우에만 생성되고, 대리자가 생성되지 않은 경우 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
      

메탈(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 텐서 레이아웃에서는 다음 텐서 형태가 브로드캐스트 가능합니다. [B, C, H, W], [B, C, 1, 1], [B, 1, H, W], [B, 1, 1, 1]:
  • 평균 2D 풀
  • 연결
    • 연결은 채널 축을 따라 수행해야 합니다.
  • Conv2D
    • 가중치와 편향은 일정해야 합니다.
  • DepthwiseConv2D
    • 가중치와 편향은 일정해야 합니다.
  • FullyConnected (일명 Dense 또는 InnerProduct)
    • 가중치와 편향 (있는 경우)은 일정해야 합니다.
    • 단일 배치 케이스만 지원합니다. 입력 차원은 마지막 차원을 제외하고 1이어야 합니다.
  • 하드스위시
  • 로지스틱 (일명 시그모이드)
  • 최대 풀 2D
  • 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 차원에만 허용됩니다.
  • 렐루
  • ReluN1To1
  • Relu6
  • 형태 변경
    • 타겟 Core ML 버전이 2인 경우에만 지원되며 Core ML 3을 타겟팅하는 경우에는 지원되지 않습니다.
  • ResizeBilinear
  • SoftMax
  • TransposeConv
    • 가중치는 일정해야 합니다.

의견

문제의 경우 재현에 필요한 모든 세부정보를 포함하여 GitHub 문제를 생성하세요.

FAQ

  • 그래프에 지원되지 않는 작업이 포함된 경우 CoreML 위임이 CPU에 대한 대체를 지원하나요?
  • CoreML 위임은 iOS 시뮬레이터에서 작동하나요?
    • 예 라이브러리에는 x86 및 x86_64 타겟이 포함되어 있으므로 시뮬레이터에서 실행할 수 있지만 CPU를 통한 성능 향상은 없습니다.
  • TensorFlow Lite 및 CoreML 위임은 MacOS를 지원하나요?
    • TensorFlow Lite는 iOS에서만 테스트되었으며 MacOS에서는 테스트되지 않았습니다.
  • 맞춤 TF Lite 작업이 지원되나요?
    • 아니요. CoreML 위임은 커스텀 작업을 지원하지 않으며 CPU로 대체됩니다.

API