移动端 [Android iOS] 定制编译 tensorflow-lite

移动端 [Android iOS] 定制编译 tensorflow-lite,第1张

文章目录 需求环境过程下载 `tf-lite` 源码环境配置尝试编译扩展代码接口提供

需求 由于端上安全性需要,将模型加载运行等 *** 作使用C++编写封装,保证模型调度算法安全性,加载模型接口内使用自定义加解密算法,保证模型文件安全性。同时考虑到模型调度算法使用移动端开发语言的话,需要将算法移植到两种语言(Java/Kotlin, ObjectC/Swift)中,直接在tf-lite源码基础上扩展会更便捷。同时 tf 源码使用 bazel 编译,编译过程也省心许多,缺点就是编写扩展代码比较费劲。 环境

OS

Python 3.8.8 (需要安装numpy)

bazel 4.1.0-homebrew (使用brew install bazel)

Android SDK 30, BuildTools 30.0.3

Android NDK 20.1.5948944

XCode

过程 下载 tf-lite 源码
git clone https://github.com/tensorflow/tensorflow
# github 速度过慢的话,可以使用gitee镜像
# https://gitee.com/mirrors/tensorflow
cd tensorflow
# 切到tag v2.8.0
git checkout v2.8.0

tf-lite 源码目录:tensorflow/tensorflow/lite

环境配置

先安装Bazel,参考:https://bazel.build/install

构建需要配置python, Android SDK, NDK 等环境,执行:

./configure

v2.8.0 分支需要使用bazel4.2.1构建,若没安装,会提示,按提示执行命令即可安装

首先提示配置python路径,注意python环境中需要安装numpy
Please specify the location of python. [Default is xxxx]: 输入python3 路径,或默认
# 接下来直接回车
Please input the desired Python library path to use:[Enter]
ROCm, CUDA, clang, optimization flags
Do you wish to build TensorFlow with ROCm support? [y/N]: n
Do you wish to build TensorFlow with CUDA support? [y/N]: n
Do you wish to download a fresh release of clang? (Experimental) [y/N]: n
Please specify optimization flags to use during compilation when bazel option: [Enter]
配置 Android 环境
Would you like to interactively configure ./WORKSPACE for Android builds? [y/N]: y
Please specify the (min) Android NDK API level to use.: 21
Please specify the Android SDK API level to use.: 30
Please specify an Android build tools version to use.: 30.0.3

均可默认
4. 开启iOS支持

Do you wish to build TensorFlow with iOS support? [y/N]: y
尝试编译 Android
构建命令:
bazel build -c opt --fat_apk_cpu=armeabi-v7a,arm64-v8a,x86,x86_64 \
   --host_crosstool_top=@bazel_tools//tools/cpp:toolchain \
    //tensorflow/lite/java:tensorflow-lite

等待build完成(大概10分钟),输出 aar 路径 bazel-bin/tensorflow/lite/java/tensorflow-lite.aar

INFO: Analyzed target //tensorflow/lite/java:tensorflow-lite (107 packages loaded, 13987 targets configured).
INFO: Found 1 target...
Target //tensorflow/lite/java:tensorflow-lite up-to-date:
  bazel-bin/tensorflow/lite/java/tensorflow-lite.aar
INFO: Elapsed time: 601.867s, Critical Path: 78.45s
INFO: 4111 processes: 24 internal, 4087 local.
INFO: Build completed successfully, 4111 total actions
iOS
为 iOS 构建 TensorFlow Lite 库,有多种方式,以TensorFlowLiteC 动态库为例:
bazel build --config=ios_fat -c opt \
  //tensorflow/lite/ios:TensorFlowLiteC_framework
扩展代码

tensorflow/lite 下新建 custom 文件夹,将算法实现代码放入此目录
todo 示例

修改 Bazel BUILD 文件
todo

接口提供

todo
jni,oc

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/web/993308.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-21
下一篇2022-05-21

发表评论

登录后才能评论

评论列表(0条)

    保存