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

需求

  1. 由于端上安全性需要,将模型加载运行等操作使用C++编写封装,保证模型调度算法安全性,加载模型接口内使用自定义加解密算法,保证模型文件安全性。
  2. 同时考虑到模型调度算法使用移动端开发语言的话,需要将算法移植到两种语言(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构建,若没安装,会提示,按提示执行命令即可安装

  1. 首先提示配置python路径,注意python环境中需要安装numpy
Please specify the location of python. [Default is xxxx]: 输入python3 路径,或默认
# 接下来直接回车
Please input the desired Python library path to use:[Enter]
  1. 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]
  1. 配置 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
bazel build --config=ios_fat -c opt \
  //tensorflow/lite/ios:TensorFlowLiteC_framework

扩展代码

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

修改 Bazel BUILD 文件
todo

接口提供

todo
jni,oc

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值