Délégué Core ML LiteRT (original) (raw)

Le délégué LiteRT Core ML permet d'exécuter des modèles LiteRT surCore ML framework, qui accélère l'inférence de modèle sur les appareils iOS.

Versions et appareils iOS compatibles:

Modèles compatibles

Le délégué Core ML est actuellement compatible avec les modèles à virgule flottante (FP32 et FP16).

Essayer le délégué Core ML sur votre propre modèle

Le délégué Core ML est déjà inclus dans la version nocturne de LiteRT CocoaPods Pour utiliser le délégué Core ML, modifiez votre pod LiteRT afin d'inclure sous-spéc CoreML dans votre Podfile.

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

OU

# 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 (jusqu'à la version 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);
  

Bonnes pratiques

Utiliser le délégué Core ML sur des appareils sans moteur neuronal

Par défaut, le délégué Core ML n'est créé que si l'appareil dispose de Engine, et renvoie null si le délégué n'est pas créé. Si vous souhaitez exécuter le délégué Core ML sur d'autres environnements (simulateur, par exemple), puis transmettre .allcomme option lors de la création d'un délégué dans Swift. Avec C++ (et Objective-C), vous pouvez transmettre TfLiteCoreMlDelegateAllDevices. L'exemple suivant montre comment procéder:

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
  

Utilisation d'un délégué de métal(GPU) en remplacement.

Si le délégué Core ML n'est pas créé, vous pouvez toujours utiliserMetal délégué (Délégué) pour obtenir d'amélioration des performances. L'exemple suivant montre comment procéder:

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
  

La logique de création du délégué lit l'identifiant machine de l'appareil (par exemple, iPhone11,1) à pour déterminer la disponibilité de Neural Engine. Consultez lecodepour en savoir plus. Vous pouvez aussi implémenter votre propre liste de blocage appareils utilisant d'autres bibliothèques telles queDeviceKit.

Utiliser une ancienne version de Core ML

Bien qu'iOS 13 soit compatible avec Core ML 3, le modèle peut mieux fonctionner lorsqu'il est avec la spécification de modèle Core ML 2. La version de conversion cible est définie par défaut sur la dernière version, mais vous pouvez modifier cela en définissantcoreMLVersion (en Swift, coreml_version dans l'API C) dans l'option de délégation pour l'ancienne version.

Opérations compatibles

Les opérations suivantes sont compatibles avec le délégué Core ML.

Commentaires

En cas de problème, veuillez créer unGitHuben fournissant tous les détails nécessaires à sa reproduction.

Questions fréquentes

API