Delegat TensorFlow Lite Hexagon, Delegat TensorFlow Lite Hexagon

W tym dokumencie wyjaśniono, jak używać delegata sześciokątnego TensorFlow Lite w aplikacji przy użyciu interfejsu API Java i/lub C. Delegat wykorzystuje bibliotekę Qualcomm Hexagon do wykonywania skwantowanych jąder na procesorze DSP. Należy zauważyć, że delegat ma na celu uzupełnienie funkcjonalności NNAPI, szczególnie w przypadku urządzeń, w których akceleracja NNAPI DSP jest niedostępna (np. na starszych urządzeniach lub urządzeniach, które nie mają jeszcze sterownika DSP NNAPI).

Wspierane urządzenia:

Obecnie obsługiwane są następujące architektury Hexagon, w tym między innymi:

  • Sześciokąt 680
    • Przykłady SoC: Snapdragon 821, 820, 660
  • Sześciokąt 682
    • Przykłady SoC: Snapdragon 835
  • Sześciokąt 685
    • Przykłady SoC: Snapdragon 845, Snapdragon 710, QCS410, QCS610, QCS605, QCS603
  • Sześciokąt 690
    • Przykłady SoC: Snapdragon 855, RB5

Obsługiwane modele:

Delegat Hexagon obsługuje wszystkie modele zgodne z naszą specyfikacją 8-bitowej kwantyzacji symetrycznej , łącznie z modelami wygenerowanymi przy użyciu kwantyzacji całkowitej po treningu . Obsługiwane są również modele UInt8 przeszkolone przy użyciu starszej ścieżki szkoleniowej obsługującej kwantyzację , na przykład te skwantowane wersje na naszej stronie Hostowane modele.

Delegat sześciokątnego interfejsu API Java

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

Przykładowe użycie

Krok 1. Edytuj plik app/build.gradle, aby używać nocnego delegata AAR Hexagon

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

Krok 2. Dodaj biblioteki Hexagon do swojej aplikacji na Androida

Krok 3. Utwórz delegata i zainicjuj interpreter 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();
}

Sześciokątny delegat 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();

Przykładowe użycie

Krok 1. Edytuj plik app/build.gradle, aby używać nocnego delegata AAR Hexagon

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

Krok 2. Dodaj biblioteki Hexagon do swojej aplikacji na Androida

Krok 3. Dołącz nagłówek C

  • Plik nagłówkowy „hexagon_delegate.h” można pobrać z GitHub lub wyodrębnić z delegata AAR firmy Hexagon.

Krok 4. Utwórz delegata i zainicjuj interpreter TensorFlow Lite

  • Upewnij się, że w kodzie załadowana jest natywna biblioteka Hexagon. Można to zrobić wywołując System.loadLibrary("tensorflowlite_hexagon_jni");
    w punkcie wejścia Aktywności lub Java.

  • Utwórz delegata, przykład:

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

Dodaj bibliotekę udostępnioną do swojej aplikacji

  • Utwórz folder „app/src/main/jniLibs” i utwórz katalog dla każdej architektury docelowej. Na przykład,
    • ARM 64-bitowy: app/src/main/jniLibs/arm64-v8a
    • ARM 32-bitowy: app/src/main/jniLibs/armeabi-v7a
  • Umieść plik .so w katalogu pasującym do architektury.

Informacja zwrotna

W przypadku problemów utwórz wydanie GitHub ze wszystkimi niezbędnymi szczegółami dotyczącymi reprodukcji, w tym modelem telefonu i używaną płytką ( adb shell getprop ro.product.device i adb shell getprop ro.board.platform ).

Często zadawane pytania

  • Które operacje są obsługiwane przez delegata?
  • Jak mogę sprawdzić, czy model korzysta z DSP, gdy włączę delegata?
    • Po włączeniu delegata zostaną wydrukowane dwa komunikaty dziennika — jeden wskazujący, czy delegat został utworzony, a drugi wskazujący, ile węzłów działa przy użyciu delegata.
      Created TensorFlow Lite delegate for Hexagon.
      Hexagon delegate: X nodes delegated out of Y nodes.
  • Czy do uruchomienia delegata potrzebuję obsługi wszystkich operacji w modelu?
    • Nie, Model zostanie podzielony na podgrafy w oparciu o obsługiwane operacje. Wszelkie nieobsługiwane operacje będą działać na procesorze.
  • Jak mogę zbudować delegata AAR Hexagon ze źródła?
    • Użyj bazel build -c opt --config=android_arm64 tensorflow/lite/delegates/hexagon/java:tensorflow-lite-hexagon .
  • Dlaczego delegat Hexagon nie inicjuje, chociaż moje urządzenie z Androidem ma obsługiwany SoC?
    • Sprawdź, czy Twoje urządzenie rzeczywiście ma obsługiwany SoC. Uruchom adb shell cat /proc/cpuinfo | grep Hardware i zobacz, czy zwróci coś w rodzaju „Sprzęt: Qualcomm Technologies, Inc MSMXXXX”.
    • Niektórzy producenci telefonów używają różnych SoC dla tego samego modelu telefonu. Dlatego delegat Hexagon może działać tylko na niektórych, ale nie na wszystkich urządzeniach tego samego modelu telefonu.
    • Niektórzy producenci telefonów celowo ograniczają użycie Hexagon DSP w niesystemowych aplikacjach na Androida, przez co delegat Hexagon nie może pracować.
  • Mój telefon ma zablokowany dostęp do DSP. Zrootowałem telefon i nadal nie mogę uruchomić delegata, co robić?
    • Pamiętaj, aby wyłączyć wymuszanie SELinux, uruchamiając adb shell setenforce 0