如何解决在具有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 上进行计算。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。