Благодарим за настройку Google I/O. Посмотреть все сеансы по запросу Смотреть по запросу

Делегат TensorFlow Lite Hexagon

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

Шестиугольный делегат 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();
}

Hexagon делегат 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 use case will need to resize input or anything that can trigger
// re-applying delegates then 'delegate_ptr' need to 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 и посмотрите, возвращает ли он что-то вроде «Hardware: Qualcomm Technologies, Inc MSMXXXX».
    • Некоторые производители телефонов используют разные SoC для одной и той же модели телефона. Поэтому делегат Hexagon может работать только на некоторых, но не на всех устройствах одной и той же модели телефона.
    • Некоторые производители телефонов намеренно ограничивают использование Hexagon DSP из несистемных приложений Android, что делает делегат Hexagon неработоспособным.
  • Мой телефон заблокировал доступ к DSP. Я рутировал телефон и все еще не могу запустить делегат, что делать?
    • Обязательно отключите принудительное применение SELinux, запустив adb shell setenforce 0