Délégué TensorFlow Lite Hexagon,Délégué TensorFlow Lite Hexagon

Ce document explique comment utiliser TensorFlow Lite Hexagon Delegate dans votre application à l'aide de l'API Java et/ou C. Le délégué exploite la bibliothèque Qualcomm Hexagon pour exécuter des noyaux quantifiés sur le DSP. Notez que le délégué est destiné à compléter la fonctionnalité NNAPI, en particulier pour les appareils sur lesquels l'accélération NNAPI DSP n'est pas disponible (par exemple, sur les appareils plus anciens ou sur les appareils qui n'ont pas encore de pilote DSP NNAPI).

Périphériques compatibles:

Actuellement, les architectures Hexagon suivantes sont prises en charge, y compris, mais sans s'y limiter :

  • Hexagone 680
    • Exemples de SoC : Snapdragon 821, 820, 660
  • Hexagone 682
    • Exemples de SoC : Snapdragon 835
  • Hexagone 685
    • Exemples de SoC : Snapdragon 845, Snapdragon 710, QCS410, QCS610, QCS605, QCS603
  • Hexagone 690
    • Exemples de SoC : Snapdragon 855, RB5

Modèles pris en charge :

Le délégué Hexagon prend en charge tous les modèles conformes à nos spécifications de quantification symétrique 8 bits , y compris ceux générés à l'aide de la quantification entière post-formation . Les modèles UInt8 formés avec le parcours de formation hérité prenant en charge la quantification sont également pris en charge, par exemple, ces versions quantifiées sur notre page Modèles hébergés.

API Java déléguée hexagonale

public class HexagonDelegate implements Delegate, Closeable {

  /*
   * Creates a new HexagonDelegate object given the current 'context'.
   * Throws UnsupportedOperationException if Hexagon DSP delegation is not
   * available on this device.
   */
  public HexagonDelegate(Context context) throws UnsupportedOperationException


  /**
   * Frees TFLite resources in C runtime.
   *
   * User is expected to call this method explicitly.
   */
  @Override
  public void close();
}

Exemple d'utilisation

Étape 1. Modifiez app/build.gradle pour utiliser l'AAR nocturne du délégué Hexagon

dependencies {
  ...
  implementation 'org.tensorflow:tensorflow-lite:0.0.0-nightly-SNAPSHOT'
  implementation 'org.tensorflow:tensorflow-lite-hexagon:0.0.0-nightly-SNAPSHOT'
}

Étape 2. Ajoutez les bibliothèques Hexagon à votre application Android

  • Téléchargez et exécutez hexagon_nn_skel.run. Il devrait fournir 3 bibliothèques partagées différentes « libhexagon_nn_skel.so », « libhexagon_nn_skel_v65.so », « libhexagon_nn_skel_v66.so »

Étape 3. Créez un délégué et initialisez un interpréteur TensorFlow Lite

import org.tensorflow.lite.HexagonDelegate;

// Create the Delegate instance.
try {
  hexagonDelegate = new HexagonDelegate(activity);
  tfliteOptions.addDelegate(hexagonDelegate);
} catch (UnsupportedOperationException e) {
  // Hexagon delegate is not supported on this device.
}

tfliteInterpreter = new Interpreter(tfliteModel, tfliteOptions);

// Dispose after finished with inference.
tfliteInterpreter.close();
if (hexagonDelegate != null) {
  hexagonDelegate.close();
}

API C du délégué hexagonal

struct TfLiteHexagonDelegateOptions {
  // This corresponds to the debug level in the Hexagon SDK. 0 (default)
  // means no debug.
  int debug_level;
  // This corresponds to powersave_level in the Hexagon SDK.
  // where 0 (default) means high performance which means more power
  // consumption.
  int powersave_level;
  // If set to true, performance information about the graph will be dumped
  // to Standard output, this includes cpu cycles.
  // WARNING: Experimental and subject to change anytime.
  bool print_graph_profile;
  // If set to true, graph structure will be dumped to Standard output.
  // This is usually beneficial to see what actual nodes executed on
  // the DSP. Combining with 'debug_level' more information will be printed.
  // WARNING: Experimental and subject to change anytime.
  bool print_graph_debug;
};

// Return a delegate that uses Hexagon SDK for ops execution.
// Must outlive the interpreter.
TfLiteDelegate*
TfLiteHexagonDelegateCreate(const TfLiteHexagonDelegateOptions* options);

// Do any needed cleanup and delete 'delegate'.
void TfLiteHexagonDelegateDelete(TfLiteDelegate* delegate);

// Initializes the DSP connection.
// This should be called before doing any usage of the delegate.
// "lib_directory_path": Path to the directory which holds the
// shared libraries for the Hexagon NN libraries on the device.
void TfLiteHexagonInitWithPath(const char* lib_directory_path);

// Same as above method but doesn't accept the path params.
// Assumes the environment setup is already done. Only initialize Hexagon.
Void TfLiteHexagonInit();

// Clean up and switch off the DSP connection.
// This should be called after all processing is done and delegate is deleted.
Void TfLiteHexagonTearDown();

Exemple d'utilisation

Étape 1. Modifiez app/build.gradle pour utiliser l'AAR nocturne du délégué Hexagon

dependencies {
  ...
  implementation 'org.tensorflow:tensorflow-lite:0.0.0-nightly-SNAPSHOT'
  implementation 'org.tensorflow:tensorflow-lite-hexagon:0.0.0-nightly-SNAPSHOT'
}

Étape 2. Ajoutez les bibliothèques Hexagon à votre application Android

  • Téléchargez et exécutez hexagon_nn_skel.run. Il devrait fournir 3 bibliothèques partagées différentes « libhexagon_nn_skel.so », « libhexagon_nn_skel_v65.so », « libhexagon_nn_skel_v66.so »

Étape 3. Inclure l'en-tête C

  • Le fichier d'en-tête "hexagon_delegate.h" peut être téléchargé depuis GitHub ou extrait de l'AAR du délégué Hexagon.

Étape 4. Créez un délégué et initialisez un interpréteur TensorFlow Lite

  • Dans votre code, assurez-vous que la bibliothèque native Hexagon est chargée. Cela peut être fait en appelant System.loadLibrary("tensorflowlite_hexagon_jni");
    dans votre point d’entrée Activité ou Java.

  • Créez un délégué, exemple :

#include "tensorflow/lite/delegates/hexagon/hexagon_delegate.h"

// Assuming shared libraries are under "/data/local/tmp/"
// If files are packaged with native lib in android App then it
// will typically be equivalent to the path provided by
// "getContext().getApplicationInfo().nativeLibraryDir"
const char[] library_directory_path = "/data/local/tmp/";
TfLiteHexagonInitWithPath(library_directory_path);  // Needed once at startup.
::tflite::TfLiteHexagonDelegateOptions params = {0};
// 'delegate_ptr' Need to outlive the interpreter. For example,
// If your use case requires resizing the input or anything that can trigger
// re-applying delegates then 'delegate_ptr' must outlive the interpreter.
auto* delegate_ptr = ::tflite::TfLiteHexagonDelegateCreate(&params);
Interpreter::TfLiteDelegatePtr delegate(delegate_ptr,
  [](TfLiteDelegate* delegate) {
    ::tflite::TfLiteHexagonDelegateDelete(delegate);
  });
interpreter->ModifyGraphWithDelegate(delegate.get());
// After usage of delegate.
TfLiteHexagonTearDown();  // Needed once at end of app/DSP usage.

Ajoutez la bibliothèque partagée à votre application

  • Créez le dossier « app/src/main/jniLibs » et créez un répertoire pour chaque architecture cible. Par exemple,
    • ARM 64 bits : app/src/main/jniLibs/arm64-v8a
    • ARM 32 bits : app/src/main/jniLibs/armeabi-v7a
  • Mettez votre .so dans le répertoire qui correspond à l'architecture.

Retour

En cas de problème, veuillez créer un problème GitHub avec tous les détails de reproduction nécessaires, y compris le modèle de téléphone et la carte utilisée ( adb shell getprop ro.product.device et adb shell getprop ro.board.platform ).

FAQ

  • Quelles opérations sont prises en charge par le délégué ?
  • Comment puis-je savoir que le modèle utilise le DSP lorsque j'active le délégué ?
    • Deux messages de journal seront imprimés lorsque vous activez le délégué : un pour indiquer si le délégué a été créé et un autre pour indiquer combien de nœuds sont en cours d'exécution à l'aide du délégué.
      Created TensorFlow Lite delegate for Hexagon.
      Hexagon delegate: X nodes delegated out of Y nodes.
  • Ai-je besoin que toutes les opérations du modèle soient prises en charge pour exécuter le délégué ?
    • Non, le modèle sera divisé en sous-graphiques en fonction des opérations prises en charge. Toutes les opérations non prises en charge s'exécuteront sur le processeur.
  • Comment puis-je créer l'AAR du délégué Hexagon à partir des sources ?
    • Utilisez bazel build -c opt --config=android_arm64 tensorflow/lite/delegates/hexagon/java:tensorflow-lite-hexagon .
  • Pourquoi le délégué Hexagon ne parvient-il pas à s'initialiser alors que mon appareil Android dispose d'un SoC pris en charge ?
    • Vérifiez si votre appareil dispose effectivement d'un SoC pris en charge. Exécutez adb shell cat /proc/cpuinfo | grep Hardware et voyez s'il renvoie quelque chose comme "Matériel : Qualcomm Technologies, Inc MSMXXXX".
    • Certains fabricants de téléphones utilisent différents SoC pour le même modèle de téléphone. Par conséquent, le délégué Hexagon ne peut fonctionner que sur certains appareils du même modèle de téléphone, mais pas sur tous.
    • Certains fabricants de téléphones limitent intentionnellement l'utilisation de Hexagon DSP à partir d'applications Android non système, empêchant ainsi le délégué Hexagon de travailler.
  • Mon téléphone a verrouillé l'accès DSP. J'ai rooté le téléphone et je n'arrive toujours pas à exécuter le délégué, que faire ?
    • Assurez-vous de désactiver SELinuxforce en exécutant adb shell setenforce 0