在具有C-API的Android本机环境中使用Tensorflow-Lite GPU委托 信息试用问题1.克隆和配置 tensorflow2.使用 libtensorflow-lite_gpu_delegate3.更新CMakeLists.txt4.在代码中使用 GPU 委托

问题描述

信息

我正在Android的本机环境中通过C-API使用Tensorflow-Lite(在these instructions之后),但是与通过Java API(在ART上)通过GPU委托相比,运行时间明显更长。

JNI AAR file (2.2)提供了C标头和一个共享库,但是共享库似乎不包含GPU委托,而仅包含一个用于在(TfLiteDelegate对象上配置委托的框架和TfLiteDelegateCreate())。

**例如,它不提供任何TfLiteGpuDelegateV2Create()tflite名称空间访问。

试用

  • 我尝试使用 cmake 在项目中加入libtensorflowlite_gpu_delegate.so,但是尽管它似乎可以建立并链接OK-该库无法通过本机代码访问。
  • 我尝试按照c_api.h的委托使用示例进行操作,但似乎无法配置GPU委托。
  • Docker容器不包含工具链(尝试在bazel build -c opt --config android_arm64 tensorflow/lite/delegates/gpu:libtensorflowlite_gpu_delegate.so中使用cc_toolchain_suite '@local_config_cc//:toolchain' does not contain a toolchain for cpu 'arm64-v8a'tensorflow/tensorflow:latest-devel-gpu Tensorflow Docker镜像中构建共享库)

问题

如何使用 C-API 在Android的本机环境中与 GPU委托进行推理?

解决方法

我设法做到了如下:

1.克隆和配置 tensorflow

从 GitHub 克隆 tensorflow 存储库,cd 到其中并运行 ./configure。在那里回答很重要 Would you like to interactively configure ./WORKSPACE for Android builds? [y/N] 使用 y 并正确指定 Android NDK 和 SDK 目录。

2.使用 libtensorflow-lite_gpu_delegate

构建 bazel

我成功构建了 GPU 委托共享库

bazel build -c opt --cxxopt=--std=c++11 --config android_arm64 tensorflow/lite/delegates/gpu:libtensorflowlite_gpu_delegate.so

我针对 Android NDK 18.1.5063045 构建,最低 API 级别为 27。请注意,我仅针对 android_arm64 架构进行了测试,我无法对其他架构做出保证。

(我编译 TensorFlow 时,HEAD 指向提交 0f8a27183657972c8ba2bce150e1364179ded6f9。)

3.更新CMakeLists.txt

相关行如下:

include_directories(
    /Users/<name>/tensorflow/tensorflow/lite/delegates/gpu # for Mac 
)

add_library(tensorflow-lite_gpu_delegate SHARED IMPORTED)
set_target_properties(tensorflow-lite_gpu_delegate PROPERTIES IMPORTED_LOCATION
    /private/var/tmp/_bazel_<name>/fe60511640322ef6962b77bab4b291e3/execroot/org_tensorflow/bazel-out/arm64-v8a-opt/bin/tensorflow/lite/delegates/gpu/libtensorflowlite_gpu_delegate.so) # I obtained this path pressing Cmd+Option+C on the libtensorflow-lite_gpu_delegate.so file on Mac,might be different on your OS

target_link_libraries(
    tensorflow-lite_gpu_delegate
    )

4.在代码中使用 GPU 委托

相关行如下:

#include <delegate.h>

auto *delegate = TfLiteGpuDelegateV2Create(/*default options=*/nullptr);

// Create the model and interpreter options.
TfLiteModel *model = TfLiteModelCreate(/* create as usual */);
TfLiteInterpreterOptions* options = TfLiteInterpreterOptionsCreate();
TfLiteInterpreterOptionsAddDelegate(options,delegate);

// Create the interpreter.
TfLiteInterpreter *interpreter = TfLiteInterpreterCreate(model,options);

注意:对我来说,GPU 委托并没有在推理速度上产生很大的提升。这可能是由于我的模型使用了 GPU 委托不支持的操作(目前支持的操作集似乎是 quite small),因此必须在 CPU 上进行计算。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...