Delegasi Tensorflow Lite Core ML

Delegasi TensorFlow Lite Core ML memungkinkan menjalankan model TensorFlow Lite pada framework Core ML , sehingga menghasilkan inferensi model yang lebih cepat pada perangkat iOS.

Versi dan perangkat iOS yang didukung:

  • iOS 12 dan lebih baru. Di versi iOS yang lebih lama, delegasi Core ML akan secara otomatis melakukan fallback ke CPU.
  • Secara default, delegasi Core ML hanya akan diaktifkan pada perangkat dengan SoC A12 dan versi lebih baru (iPhone Xs dan versi lebih baru) untuk menggunakan Neural Engine guna inferensi yang lebih cepat. Jika Anda juga ingin menggunakan delegasi Core ML di perangkat 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 malam TensorFlow lite CocoaPods. Untuk menggunakan delegasi Core ML, ubah pod TensorFlow lite Anda untuk menyertakan subspesifikasi CoreML di 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']

Cepat

    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)
    }
  

Tujuan-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 (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 Neural Engine, dan akan mengembalikan null jika delegasi tidak dibuat. Jika Anda ingin menjalankan delegasi Core ML di lingkungan lain (misalnya, simulator), teruskan .all sebagai opsi saat membuat delegasi di Swift. Di C++ (dan Objective-C), Anda dapat meneruskan TfLiteCoreMlDelegateAllDevices . Contoh berikut menunjukkan cara melakukan ini:

Cepat

    var options = CoreMLDelegate.Options()
    options.enabledDevices = .all
    let coreMLDelegate = CoreMLDelegate(options: options)!
    let interpreter = try Interpreter(modelPath: modelPath,
                                      delegates: [coreMLDelegate])
      

Tujuan-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 cadangan.

Jika delegasi Core ML tidak dibuat, Anda masih dapat menggunakan delegasi Metal untuk mendapatkan manfaat performa. Contoh berikut menunjukkan cara melakukan ini:

Cepat

    var delegate = CoreMLDelegate()
    if delegate == nil {
      delegate = MetalDelegate()  // Add Metal delegate options if necessary.
    }

    let interpreter = try Interpreter(modelPath: modelPath,
                                      delegates: [delegate!])
  

Tujuan-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 (misalnya iPhone11,1) untuk menentukan ketersediaan Neural Engine-nya. Lihat kode untuk lebih detail. Alternatifnya, Anda dapat mengimplementasikan kumpulan perangkat daftar tolak Anda sendiri menggunakan pustaka lain seperti DeviceKit .

Menggunakan versi Core ML yang lebih lama

Meskipun iOS 13 mendukung Core ML 3, model tersebut mungkin bekerja lebih baik bila dikonversi dengan spesifikasi model Core ML 2. Versi target konversi disetel ke versi terbaru secara default, tetapi Anda dapat mengubahnya dengan menyetel coreMLVersion (di Swift, coreml_version di C API) di opsi delegasi ke versi yang lebih lama.

Operasi yang didukung

Operasi berikut didukung oleh delegasi Core ML.

  • Menambahkan
    • Hanya bentuk tertentu saja yang dapat disiarkan. Dalam tata letak tensor Core ML, bentuk tensor berikut dapat disiarkan. [B, C, H, W] , [B, C, 1, 1] , [B, 1, H, W] , [B, 1, 1, 1] .
  • Rata-rataPool2D
  • pertemuan
    • Penggabungan harus dilakukan sepanjang sumbu saluran.
  • Konv2D
    • Bobot dan bias harus konstan.
  • Konv2D Mendalam
    • Bobot dan bias harus konstan.
  • Sepenuhnya Terhubung (alias Padat atau Produk Dalam)
    • Bobot dan bias (jika ada) harus konstan.
    • Hanya mendukung kasus batch tunggal. Dimensi masukan harus 1, kecuali dimensi terakhir.
  • keinginan keras
  • Logistik (alias Sigmoid)
  • MaxPool2D
  • CerminPad
    • Hanya input 4D dengan mode REFLECT yang didukung. Padding harus konstan, dan hanya diperbolehkan untuk dimensi H dan W.
  • Mul
    • Hanya bentuk tertentu saja yang dapat disiarkan. Dalam tata letak tensor Core ML, bentuk tensor berikut dapat disiarkan. [B, C, H, W] , [B, C, 1, 1] , [B, 1, H, W] , [B, 1, 1, 1] .
  • Pad dan PadV2
    • Hanya masukan 4D yang didukung. Padding harus konstan, dan hanya diperbolehkan untuk dimensi H dan W.
  • Relu
  • ReluN1To1
  • Relu6
  • Membentuk kembali
    • Hanya didukung ketika target versi Core ML adalah 2, tidak didukung ketika menargetkan Core ML 3.
  • Ubah ukuranBilinear
  • LembutMax
  • Tanh
  • TransposeKonv
    • Bobot harus konstan.

Masukan

Untuk masalah, harap buat masalah GitHub dengan semua detail yang diperlukan untuk direproduksi.

Pertanyaan Umum

  • Apakah delegasi CoreML mendukung fallback ke CPU jika grafik berisi operasi yang tidak didukung?
    • Ya
  • Apakah delegasi CoreML berfungsi di iOS Simulator?
    • Ya. Pustaka menyertakan target x86 dan x86_64 sehingga dapat dijalankan di simulator, namun Anda tidak akan melihat peningkatan kinerja melalui CPU.
  • Apakah delegasi TensorFlow Lite dan CoreML mendukung MacOS?
    • TensorFlow Lite hanya diuji di iOS tetapi tidak di MacOS.
  • Apakah operasi TF Lite khusus didukung?
    • Tidak, delegasi CoreML tidak mendukung operasi khusus dan mereka akan kembali ke CPU.

Lebah