Delegasi LiteRT Core ML

Delegasi LiteRT Core ML memungkinkan model LiteRT dijalankan di Framework Core ML, yang menghasilkan inferensi model yang lebih cepat di perangkat iOS.

Versi dan perangkat iOS yang didukung:

  • iOS 12 dan yang lebih baru. Pada versi iOS yang lebih lama, delegasi Core ML akan secara otomatis kembali ke CPU.
  • Secara default, delegasi Core ML hanya akan diaktifkan di perangkat dengan SoC A12 dan yang lebih baru (iPhone Xs dan yang lebih baru) menggunakan Neural Engine untuk inferensi yang lebih cepat. Jika Anda ingin menggunakan delegasi Core ML juga di perangkat yang lebih lama, lihat praktik terbaik

Model yang didukung

Delegasi Core ML saat ini mendukung model float (FP32 dan FP16).

Mencoba delegasi Core ML pada model Anda sendiri

Delegasi Core ML sudah disertakan dalam rilis LiteRT setiap malam CocoaPods. Untuk menggunakan delegasi Core ML, ubah pod LiteRT agar menyertakan subspesifikasi CoreML dalam Podfile Anda.

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

ATAU

# 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 (Hingga 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);
      

Praktik terbaik

Menggunakan delegasi Core ML pada perangkat tanpa Neural Engine

Secara default, delegasi Core ML hanya akan dibuat jika perangkat memiliki jaringan Neural Engine, dan akan menampilkan null jika delegasi tidak dibuat. Jika Anda ingin jalankan delegasi Core ML di lingkungan lain (misalnya, simulator), teruskan .all sebagai opsi saat membuat delegasi di Swift. Pada C++ (dan Objective-C), Anda dapat teruskan TfLiteCoreMlDelegateAllDevices. Contoh berikut menunjukkan cara melakukannya:

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
      

Menggunakan delegasi Metal(GPU) sebagai penggantian.

Jika delegasi Core ML tidak dibuat, Anda masih dapat menggunakan Delegasi logam untuk mendapatkan manfaat performa. Contoh berikut menunjukkan cara melakukannya:

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
      

Logika pembuatan delegasi membaca ID mesin perangkat (mis. iPhone11,1) ke menentukan ketersediaan Neural Engine-nya. Lihat kode untuk mengetahui detail selengkapnya. Atau, Anda dapat menerapkan kumpulan daftar tolak Anda sendiri menggunakan {i>library <i}lain seperti DeviceKit.

Menggunakan versi Core ML lama

Meskipun iOS 13 mendukung Core ML 3, model ini mungkin akan berfungsi lebih baik jika dikonversi dengan spesifikasi model Core ML 2. Versi konversi target kini menyetel ke versi terbaru secara {i>default<i}, tetapi Anda dapat mengubahnya dengan mengaturnya coreMLVersion (di Swift, coreml_version di C API) dalam opsi delegasi untuk versi yang lebih lama.

Operasi yang didukung

Operasi berikut didukung oleh delegasi Core ML.

  • Menambahkan
    • Hanya bentuk tertentu yang dapat disiarkan. Dalam tata letak tensor Core ML, bentuk tensor berikut bisa disiarkan. [B, C, H, W], [B, C, 1, 1], [B, 1, H, W], [B, 1, 1, 1].
  • Rata-RataPool2D
  • Gabungkan
    • Penyambungan harus dilakukan di sepanjang sumbu saluran.
  • Konv2D
    • Bobot dan bias harus konstan.
  • DepthwiseConv2D
    • Bobot dan bias harus konstan.
  • Terhubung Sepenuhnya (alias Dense atau InnerProduct)
    • Bobot dan bias (jika ada) harus konstan.
    • Hanya mendukung kasus batch tunggal. Dimensi input harus 1, kecuali dimensi terakhir.
  • Keras
  • Logistik (alias Sigmoid)
  • TotalKompleks2D
  • MirrorPad
    • Hanya input 4D dengan mode REFLECT yang didukung. Padding harus konstan, dan hanya diperbolehkan untuk dimensi H dan W.
  • Mul
    • Hanya bentuk tertentu yang dapat disiarkan. Dalam tata letak tensor Core ML, bentuk tensor berikut bisa disiarkan. [B, C, H, W], [B, C, 1, 1], [B, 1, H, W], [B, 1, 1, 1].
  • Bantalan dan PadV2
    • Hanya input 4D yang didukung. Padding harus konstan, dan hanya diperbolehkan untuk dimensi H dan W.
  • Relu
  • ReluN1To1
  • Relu6
  • Bentuk Ulang
    • Hanya didukung jika versi Core ML target adalah 2, tidak didukung jika yang menargetkan Core ML 3.
  • ResizeBilinear
  • SoftMax
  • Tanh
  • TransposeConv
    • Bobot harus konstan.

Masukan

Jika mengalami masalah, buat GitHub masalah dengan semua detail yang diperlukan untuk mereproduksi.

FAQ

  • Apakah delegasi CoreML mendukung penggantian ke CPU jika grafik berisi data yang tidak didukung operasi?
    • Ya
  • Apakah delegasi CoreML berfungsi di Simulator iOS?
    • Ya. Library menyertakan target x86 dan x86_64 sehingga dapat berjalan di simulator, tetapi Anda tidak akan melihat peningkatan kinerja melalui CPU.
  • Apakah delegasi LiteRT dan CoreML mendukung MacOS?
    • LiteRT hanya diuji di iOS, tetapi tidak di MacOS.
  • Apakah operasi LiteRT kustom didukung?
    • Tidak, delegasi CoreML tidak mendukung operasi khusus dan akan kembali ke dengan CPU

API