Делегат TensorFlow Lite Hexagon, Делегат TensorFlow Lite Hexagon

В этом документе объясняется, как использовать делегат Hexagon Delegate TensorFlow Lite в вашем приложении с использованием API Java и/или C. Делегат использует библиотеку Qualcomm Hexagon для выполнения квантованных ядер на DSP. Обратите внимание, что делегат предназначен для дополнения функциональности NNAPI, особенно для устройств, где ускорение NNAPI DSP недоступно (например, на старых устройствах или устройствах, которые еще не имеют драйвера DSP NNAPI).

Поддерживаемые устройства:

В настоящее время поддерживаются следующие архитектуры Hexagon, включая, помимо прочего:

  • Шестигранник 680
    • Примеры SoC: Snapdragon 821, 820, 660.
  • Шестигранник 682
    • Примеры SoC: Snapdragon 835
  • Шестигранник 685
    • Примеры SoC: Snapdragon 845, Snapdragon 710, QCS410, QCS610, QCS605, QCS603.
  • Шестигранник 690
    • Примеры SoC: Snapdragon 855, RB5.

Поддерживаемые модели:

Делегат Hexagon поддерживает все модели, соответствующие нашей спецификации 8-битного симметричного квантования , включая модели, сгенерированные с использованием целочисленного квантования после обучения . Также поддерживаются модели UInt8, обученные с использованием устаревшего пути обучения с учетом квантования , например, эти квантованные версии на нашей странице Размещенные модели.

Делегат Hexagon Java API

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

Пример использования

Шаг 1. Отредактируйте app/build.gradle, чтобы использовать ночной AAR делегата Hexagon.

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

Шаг 2. Добавьте библиотеки Hexagon в свое приложение для Android.

  • Загрузите и запустите hexagon_nn_skel.run. Он должен предоставлять 3 разные общие библиотеки: «libhexagon_nn_skel.so», «libhexagon_nn_skel_v65.so», «libhexagon_nn_skel_v66.so».

Шаг 3. Создайте делегата и инициализируйте интерпретатор 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();
}

Шестиугольный делегат C API

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

Пример использования

Шаг 1. Отредактируйте app/build.gradle, чтобы использовать ночной AAR делегата Hexagon.

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

Шаг 2. Добавьте библиотеки Hexagon в свое приложение для Android.

  • Загрузите и запустите hexagon_nn_skel.run. Он должен предоставлять 3 разные общие библиотеки: «libhexagon_nn_skel.so», «libhexagon_nn_skel_v65.so», «libhexagon_nn_skel_v66.so».

Шаг 3. Включите заголовок C

  • Файл заголовка «hexagon_delegate.h» можно скачать с GitHub или извлечь из AAR делегата Hexagon.

Шаг 4. Создайте делегата и инициализируйте интерпретатор TensorFlow Lite.

  • Убедитесь, что в вашем коде загружена собственная библиотека Hexagon. Это можно сделать, вызвав System.loadLibrary("tensorflowlite_hexagon_jni");
    в вашей активности или точке входа Java.

  • Создайте делегата, пример:

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

Добавьте общую библиотеку в свое приложение

  • Создайте папку «app/src/main/jniLibs» и создайте каталог для каждой целевой архитектуры. Например,
    • 64-разрядная версия ARM: app/src/main/jniLibs/arm64-v8a
    • 32-разрядная версия ARM: app/src/main/jniLibs/armeabi-v7a
  • Поместите свой .so в каталог, соответствующий архитектуре.

Обратная связь

В случае возникновения проблем создайте задачу на GitHub со всеми необходимыми сведениями о воспроизведении, включая модель телефона и используемую плату ( adb shell getprop ro.product.device и adb shell getprop ro.board.platform ).

Часто задаваемые вопросы

  • Какие операции поддерживаются делегатом?
  • Как я могу определить, что модель использует DSP, когда я включаю делегата?
    • При включении делегата будут напечатаны два сообщения журнала: одно указывает, был ли создан делегат, а другое указывает, сколько узлов работает с использованием делегата.
      Created TensorFlow Lite delegate for Hexagon.
      Hexagon delegate: X nodes delegated out of Y nodes.
  • Нужно ли поддерживать все операции в модели для запуска делегата?
    • Нет, модель будет разделена на подграфы в зависимости от поддерживаемых операций. Любые неподдерживаемые операции будут выполняться на ЦП.
  • Как я могу собрать AAR делегата Hexagon из исходного кода?
    • Используйте bazel build -c opt --config=android_arm64 tensorflow/lite/delegates/hexagon/java:tensorflow-lite-hexagon .
  • Почему делегату Hexagon не удается инициализироваться, хотя на моем устройстве Android имеется поддерживаемая SoC?
    • Убедитесь, что ваше устройство действительно имеет поддерживаемую SoC. Запустите adb shell cat /proc/cpuinfo | grep Hardware и посмотрите, возвращает ли он что-то вроде «Оборудование: Qualcomm Technologies, Inc MSMXXXX».
    • Некоторые производители телефонов используют разные SoC для одной и той же модели телефона. Таким образом, делегат Hexagon может работать только на некоторых, но не на всех устройствах одной и той же модели телефона.
    • Некоторые производители телефонов намеренно ограничивают использование Hexagon DSP из несистемных приложений Android, в результате чего делегат Hexagon не может работать.
  • Мой телефон заблокировал доступ к DSP. Я рутировал телефон, но все равно не могу запустить делегат, что делать?
    • Обязательно отключите принудительное использование SELinux, запустив adb shell setenforce 0