Delegato TensorFlow Lite Hexagon, delegato TensorFlow Lite Hexagon

Questo documento spiega come utilizzare TensorFlow Lite Hexagon Delegate nella tua applicazione utilizzando l'API Java e/o C. Il delegato sfrutta la libreria Qualcomm Hexagon per eseguire kernel quantizzati sul DSP. Tieni presente che il delegato è destinato a integrare la funzionalità NNAPI, in particolare per i dispositivi in ​​cui l'accelerazione DSP NNAPI non è disponibile (ad esempio, su dispositivi meno recenti o dispositivi che non dispongono ancora di un driver DSP NNAPI).

Dispositivi supportati:

Attualmente sono supportate le seguenti architetture Hexagon, incluse ma non limitate a:

  • Esagono 680
    • Esempi di SoC: Snapdragon 821, 820, 660
  • Esagono 682
    • Esempi di SoC: Snapdragon 835
  • Esagono 685
    • Esempi di SoC: Snapdragon 845, Snapdragon 710, QCS410, QCS610, QCS605, QCS603
  • Esagono 690
    • Esempi di SoC: Snapdragon 855, RB5

Modelli supportati:

Il delegato Hexagon supporta tutti i modelli conformi alle nostre specifiche di quantizzazione simmetrica a 8 bit , compresi quelli generati utilizzando la quantizzazione intera post-training . Sono supportati anche i modelli UInt8 addestrati con il percorso di formazione legacy con riconoscimento della quantizzazione , ad esempio queste versioni quantizzate nella nostra pagina Modelli ospitati.

API Java delegata Hexagon

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

Utilizzo di esempio

Passaggio 1. Modifica app/build.gradle per utilizzare l'AAR delegato Hexagon notturno

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

Passaggio 2. Aggiungi le librerie Hexagon alla tua app Android

  • Scarica ed esegui hex_nn_skel.run. Dovrebbe fornire 3 diverse librerie condivise “libhexagon_nn_skel.so”, “libhexagon_nn_skel_v65.so”, “libhexagon_nn_skel_v66.so”

Passaggio 3. Crea un delegato e inizializza un interprete 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 delegata esagono

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

Utilizzo di esempio

Passaggio 1. Modifica app/build.gradle per utilizzare l'AAR delegato Hexagon notturno

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

Passaggio 2. Aggiungi le librerie Hexagon alla tua app Android

  • Scarica ed esegui hex_nn_skel.run. Dovrebbe fornire 3 diverse librerie condivise “libhexagon_nn_skel.so”, “libhexagon_nn_skel_v65.so”, “libhexagon_nn_skel_v66.so”

Passaggio 3. Includere l'intestazione C

  • Il file di intestazione "hexagon_delegate.h" può essere scaricato da GitHub o estratto dall'AAR del delegato Hexagon.

Passaggio 4. Crea un delegato e inizializza un interprete TensorFlow Lite

  • Nel tuo codice, assicurati che sia caricata la libreria Hexagon nativa. Questo può essere fatto chiamando System.loadLibrary("tensorflowlite_hexagon_jni");
    nella tua attività o nel punto di ingresso Java.

  • Crea un delegato, ad esempio:

#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.

Aggiungi la libreria condivisa alla tua app

  • Crea la cartella "app/src/main/jniLibs" e crea una directory per ciascuna architettura di destinazione. Per esempio,
    • ARM a 64 bit: app/src/main/jniLibs/arm64-v8a
    • ARM a 32 bit: app/src/main/jniLibs/armeabi-v7a
  • Inserisci il tuo .so nella directory che corrisponde all'architettura.

Feedback

In caso di problemi, crea un problema GitHub con tutti i dettagli di riproduzione necessari, incluso il modello di telefono e la scheda utilizzata ( adb shell getprop ro.product.device e adb shell getprop ro.board.platform ).

FAQ

  • Quali operazioni sono supportate dal delegato?
  • Come posso sapere che il modello sta utilizzando il DSP quando abilito il delegato?
    • Quando si abilita il delegato verranno stampati due messaggi di registro: uno per indicare se il delegato è stato creato e un altro per indicare quanti nodi sono in esecuzione utilizzando il delegato.
      Created TensorFlow Lite delegate for Hexagon.
      Hexagon delegate: X nodes delegated out of Y nodes.
  • È necessario che tutte le operazioni nel modello siano supportate per eseguire il delegato?
    • No, il Modello sarà suddiviso in sottografi in base alle operazioni supportate. Qualsiasi operazione non supportata verrà eseguita sulla CPU.
  • Come posso creare l'AAR delegato Hexagon dal sorgente?
    • Utilizza bazel build -c opt --config=android_arm64 tensorflow/lite/delegates/hexagon/java:tensorflow-lite-hexagon .
  • Perché il delegato Hexagon non riesce a inizializzarsi anche se il mio dispositivo Android ha un SoC supportato?
    • Verifica se il tuo dispositivo ha effettivamente un SoC supportato. Esegui adb shell cat /proc/cpuinfo | grep Hardware e verifica se restituisce qualcosa come "Hardware: Qualcomm Technologies, Inc MSMXXXX".
    • Alcuni produttori di telefoni utilizzano SoC diversi per lo stesso modello di telefono. Pertanto, il delegato Hexagon potrebbe funzionare solo su alcuni ma non su tutti i dispositivi dello stesso modello di telefono.
    • Alcuni produttori di telefoni limitano intenzionalmente l'uso di Hexagon DSP da app Android non di sistema, impedendo al delegato Hexagon di funzionare.
  • Il mio telefono ha bloccato l'accesso DSP. Ho effettuato il root del telefono e ancora non riesco a eseguire il delegato, cosa fare?
    • Assicurati di disabilitare l'applicazione di SELinux eseguendo adb shell setenforce 0