Zhao Dongyu's Blog

A life which is unexamined is not worth living.

0%

tflite-micro

最近又搞了一次tflite-micro,上一次搞还是在两年前,那时候简直是个工程小白,遇到个问题就卡住了。这一次相对比较顺利,记录一遍过程。

论文:TensorFlow Lite Micro: Embedded Machine Learning on TinyML Systems

克隆仓库

在tensorflow的git里面,看到git已经迁移至一个单独的仓库

于是在ubuntu执行命令:

git clone https://github.com/tensorflow/tflite-micro.git

此时commit 7ac0b662b6402c1fccc8ec8d1db84f0f34dd4a85

编译静态库

求助了ChatGPT 4.0:

「在这个 https://github.com/tensorflow/tflite-micro , 怎么编译静态库?」

在TensorFlow Lite Micro的GitHub仓库中,你可以使用以下步骤来编译静态库:

  1. 首先,你需要克隆仓库:

git clone https://github.com/tensorflow/tflite-micro.git

  1. 进入克隆下来的仓库目录:

cd tflite-micro

  1. 使用make命令编译静态库:

make -f tensorflow/lite/micro/tools/make/Makefile TARGET=<TARGET> TARGET_ARCH=<ARCH> microlite

在上述命令中,<TARGET>应替换为你的目标平台(如linux),<ARCH>应替换为你的目标架构(如x86_64)。这将在tensorflow/lite/micro/tools/make/gen/<TARGET>_<ARCH>/lib/目录下生成一个名为libtensorflow-microlite.a的静态库。

请注意,你可能需要根据你的具体需求和环境来修改这些步骤。例如,你可能需要安装额外的依赖库,或者修改makefile来包含你需要的特性。

真是太棒了,于是我执行指令:

make -f tensorflow/lite/micro/tools/make/Makefile TARGET=linux TARGET_ARCH=x86_64 microlite

make/download/ 目录下,分别下载了flatbuffersgemmlowpkissfftpigweedruy

编译完成后,得到了静态库文件

ar: creating gen/linux_x86_64_default/lib/libtensorflow-microlite.a

编写 demo & debug

仿照helloworld工程写了一个小demo

遇到问题:

1
2
3
Failed to allocate tail memory. Requested: 2760, available 1376, missing: 1384
Failed to allocate memory for context->eval_tensors, 2760 bytes required
Failed starting model allocation.

解决方法:

先暂时增大ArenaSize,后面再根据实际使用情况调整回来:

constexpr int kTensorArenaSize = 300000;

遇到问题:

1
2
3
4
Didn't find op for builtin opcode 'LEAKY_RELU'
Failed to get registration from op code LEAKY_RELU

Segmentation fault (core dumped)

解决方法:

增加算子注册 TF_LITE_ENSURE_STATUS(op_resolver.AddLeakyRelu());

遇到问题

1
2
Couldn't register builtin op #98, resolver size 
is too small (1).

解决方法

1
using HelloWorldOpResolver = tflite::MicroMutableOpResolver<1>;

这里的1代表注册个数,草率了,应该op_resolver add 了几个这里就写几的。

遇到问题

一旦执行到interpreter.input(0)->data.f[0] = 1.f;就段错误。

解决办法

CFLAGS = -DTF_LITE_STATIC_MEMORY

进一步减小库体积

为了压缩体积,BUILD_TYPE使用了release进行编译,这期间会遇到MicroPrintf不支持的问题(release_with_logs是可以的),进行一些注释就可以。

以及进行-Os编译,可以减少很多体积占用。

Thanks for your support.