Delegado de TensorFlow Lite Hexagon,Delegado de TensorFlow Lite Hexagon

Este documento explica cómo utilizar TensorFlow Lite Hexagon Delegate en su aplicación utilizando la API de Java y/o C. El delegado aprovecha la biblioteca Qualcomm Hexagon para ejecutar núcleos cuantificados en el DSP. Tenga en cuenta que el delegado está destinado a complementar la funcionalidad NNAPI, particularmente para dispositivos donde la aceleración NNAPI DSP no está disponible (por ejemplo, en dispositivos más antiguos o dispositivos que aún no tienen un controlador DSP NNAPI).

Dispositivos soportados:

Actualmente se admiten las siguientes arquitecturas de Hexagon, que incluyen, entre otras:

  • Hexágono 680
    • Ejemplos de SoC: Snapdragon 821, 820, 660
  • Hexágono 682
    • Ejemplos de SoC: Snapdragon 835
  • Hexágono 685
    • Ejemplos de SoC: Snapdragon 845, Snapdragon 710, QCS410, QCS610, QCS605, QCS603
  • Hexágono 690
    • Ejemplos de SoC: Snapdragon 855, RB5

Modelos compatibles:

El delegado de Hexagon admite todos los modelos que se ajustan a nuestra especificación de cuantificación simétrica de 8 bits , incluidos los generados mediante cuantificación de enteros posterior al entrenamiento . Los modelos UInt8 entrenados con la ruta de entrenamiento heredada con reconocimiento de cuantificación también son compatibles; por ejemplo, estas versiones cuantificadas en nuestra página Modelos alojados.

API de Java delegado hexagonal

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

Uso de ejemplo

Paso 1. Edite app/build.gradle para usar el AAR delegado nocturno de Hexagon

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

Paso 2. Agrega bibliotecas Hexagon a tu aplicación de Android

  • Descargue y ejecute hexagon_nn_skel.run. Debería proporcionar 3 bibliotecas compartidas diferentes “libhexagon_nn_skel.so”, “libhexagon_nn_skel_v65.so”, “libhexagon_nn_skel_v66.so”

Paso 3. Cree un delegado e inicialice un intérprete de 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 delegado 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();

Uso de ejemplo

Paso 1. Edite app/build.gradle para usar el AAR delegado nocturno de Hexagon

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

Paso 2. Agrega bibliotecas Hexagon a tu aplicación de Android

  • Descargue y ejecute hexagon_nn_skel.run. Debería proporcionar 3 bibliotecas compartidas diferentes “libhexagon_nn_skel.so”, “libhexagon_nn_skel_v65.so”, “libhexagon_nn_skel_v66.so”

Paso 3. Incluye el encabezado C

  • El archivo de encabezado "hexagon_delegate.h" se puede descargar de GitHub o extraer del AAR delegado de Hexagon.

Paso 4. Cree un delegado e inicialice un intérprete de TensorFlow Lite

  • En su código, asegúrese de que esté cargada la biblioteca nativa de Hexagon. Esto se puede hacer llamando System.loadLibrary("tensorflowlite_hexagon_jni");
    en su Actividad o punto de entrada de Java.

  • Crear un delegado, ejemplo:

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

Agregue la biblioteca compartida a su aplicación

  • Cree la carpeta "app/src/main/jniLibs" y cree un directorio para cada arquitectura de destino. Por ejemplo,
    • ARM de 64 bits: app/src/main/jniLibs/arm64-v8a
    • ARM de 32 bits: app/src/main/jniLibs/armeabi-v7a
  • Coloque su .so en el directorio que coincida con la arquitectura.

Comentario

Si tiene problemas, cree un problema de GitHub con todos los detalles de reproducción necesarios, incluido el modelo de teléfono y la placa utilizada ( adb shell getprop ro.product.device y adb shell getprop ro.board.platform ).

Preguntas más frecuentes

  • ¿Qué operaciones son apoyadas por el delegado?
  • ¿Cómo puedo saber que el modelo está usando el DSP cuando habilito el delegado?
    • Se imprimirán dos mensajes de registro cuando habilite el delegado: uno para indicar si se creó el delegado y otro para indicar cuántos nodos se están ejecutando utilizando el delegado.
      Created TensorFlow Lite delegate for Hexagon.
      Hexagon delegate: X nodes delegated out of Y nodes.
  • ¿Necesito que todas las operaciones del modelo sean compatibles para ejecutar el delegado?
    • No, el modelo se dividirá en subgrafos según las operaciones admitidas. Cualquier operación no compatible se ejecutará en la CPU.
  • ¿Cómo puedo construir el AAR delegado de Hexagon desde la fuente?
    • Utilice bazel build -c opt --config=android_arm64 tensorflow/lite/delegates/hexagon/java:tensorflow-lite-hexagon .
  • ¿Por qué el delegado de Hexagon no se inicializa aunque mi dispositivo Android tenga un SoC compatible?
    • Verifique si su dispositivo realmente tiene un SoC compatible. Ejecute adb shell cat /proc/cpuinfo | grep Hardware y vea si devuelve algo como "Hardware: Qualcomm Technologies, Inc MSMXXXX".
    • Algunos fabricantes de teléfonos utilizan diferentes SoC para el mismo modelo de teléfono. Por lo tanto, es posible que el delegado de Hexagon solo funcione en algunos, pero no en todos, los dispositivos del mismo modelo de teléfono.
    • Algunos fabricantes de teléfonos restringen intencionalmente el uso de Hexagon DSP desde aplicaciones de Android que no pertenecen al sistema, lo que hace que el delegado de Hexagon no pueda trabajar.
  • Mi teléfono ha bloqueado el acceso DSP. Rooteé el teléfono y todavía no puedo ejecutar el delegado, ¿qué hacer?
    • Asegúrese de desactivar SELinux enforce ejecutando adb shell setenforce 0