TensorFlow/Tensorflow Lite

TensorFlow Lite 빌드하기(bazel & C/C++)

kim선달 2020. 4. 5. 15:54
Select Language

 

TensorFlow 는 Python이나 Java(Android)에서 사용할때는 참 간편합니다.

Python에서는 pip 이나 conda 등등으로 바로 깔아주면 되고, Android 에서도 dependencies 에 몇 줄만 추가해주면 끝나는 일입니다.

 

근데 C나 C++, Objective-C를 사용하기 위해서는 무조건 라이브러리로 빌드 한 다음 사용해야 합니다.

물론 소스파일 통채로 때려넣고 컴파일해 버리는 방법도 있습니다.

통채로 컴파일 하는건 CPU만 사용할때는 그나마 간단합니다만, GPU나 NNAPI를 이용하려면 third party연결, NDK 연결 등등 작업이 필요하고, 애초에 proto를 이용한 compiled / generated 된 파일들을 참조하기에 그냥 bazel로 빌드 하는게 더 정신건강에 이롭습니다.

 

TensorFlow Lite는 Google에서 만든 패키지 빌드용 시스템인 bazel을 사용하여 빌드를 진행합니다. 자세히는 모르셔도 되고, 다만 소스파일에서 빌드 설정파일은 각각의 경로 안의 BUILD 파일에 저장되어 있다는점만 기억하시면 될 것 같습니다.

 

 

목차

  1. 데스크톱
  2. Android 용 빌드
  3. iOS용 빌드
  4. Raspberry Pi 용 빌드
  5. C 로 빌드하기 

 

1. 데스크톱

이 글을 참고해주세요

 

2. Android (Arm64 Board): C++ Static Library 빌드하기

! 오류가 날시 1번 혹은 4번 항목의 C로 빌드하기를 참고해주세요 !

  * Ubuntu 및 Linux, OS X 계열

  1. 툴체인 및 라이브러리 다운로드
> sudo apt-get update
> sudo apt-get install crossbuild-essential-arm64

   

2. tensorflow 소스파일 clone

> git clone https://github.com/tensorflow/tensorflow

    git 이 없으시다면

> sudo apt-get install git

   

3. 서드파티 다운로드

> cd tensorflow
> ./tensorflow/lite/tools/make/download_dependencies.sh

   

4. 빌드 파일 수정

    tensorflow/lite/tools/make/Makefile 을 보시면 한 60번째 줄 즈음에 아래와 같은 항목이 있을텐데

CFLAGS := -O3 -DNDEBUG -fPIC
CXXFLAGS := $(CFLAGS) --std=c++11 $(EXTRA_CXXFLAGS)
LDOPTS := -L/usr/local/lib
ARFLAGS := -r
TARGET_TOOLCHAIN_PREFIX :=
CC_PREFIX :=

 

   맨 밑에 한줄을 추가해줍니다.

CFLAGS := -O3 -DNDEBUG -fPIC
CXXFLAGS := $(CFLAGS) --std=c++11 $(EXTRA_CXXFLAGS)
LDOPTS := -L/usr/local/lib
ARFLAGS := -r
TARGET_TOOLCHAIN_PREFIX :=
CC_PREFIX :=

CXXFLAGS += -D_GLIBCXX_USE_CXX11_ABI=0

   

5. 빌드

> ./tensorflow/lite/tools/make/build_aarch64_lib.sh

   

6. 결과

tensorflow/lite/tools/make/gen/linux_aarch64/lib/libtensorflow-lite.a

    가 생성됩니다.

    이후 라이브러리 로드 시 기본 std 라이브러리가 undefined 에러로 link failure 가 발생한다면 아래의 C 로 빌드하기로 해주세요

 

  * 저는 MacOS와 Ubuntu 모두 빌드후 링크할 때 오류가 나서 C로 빌드 했습니다. 윈도우는 테스트해보지 않았는데, 공식 문서나 아래의 C로 빌드하기를 참고해주세요.

 

 

3. iOS

  https://www.tensorflow.org/lite/guide/build_ios

 

Build TensorFlow Lite for iOS

This document describes how to build TensorFlow Lite iOS library on your own. Normally, you do not need to locally build TensorFlow Lite iOS library. If you just want to use it, the easiest way is using the prebuilt stable or nightly releases of the Tensor

www.tensorflow.org

 

4. Raspberry Pi

    https://www.tensorflow.org/lite/guide/build_rpi

 

Build TensorFlow Lite for Raspberry Pi

This page describes how to build the TensorFlow Lite static library for Raspberry Pi. If you just want to start using TensorFlow Lite to execute your models, the fastest option is to install the TensorFlow Lite runtime package as shown in the Python quicks

www.tensorflow.org

 

5. C 로 빌드하기

    사실 제가 공식 문서를 보고 Android 용으로 빌드하다가 라이브러리를 링크 할 때 에러가 나서 C로 빌드한다음 사용했습니다.
C로 빌드한다고 내 코드도 C로 짜야하는건 아니고, Tensorflow Lite 함수가 들어있는 헤더를 C 버전을 이용해야 해서 그냥 바로 C++ 에서 쓸 수 있습니다.

이방법으로 하면 Linux(Ubuntu), MaxOS, Android 에서 모두 사용할 수 있습니다. 다만, MacOS 는 GPU를 사용 못합니다

    

    1. Python 다운로드

    https://www.python.org/

 

Welcome to Python.org

The official home of the Python Programming Language

www.python.org

    버전은 3.7 이하로 선택하시면...될 것 같습니다(2.X 버전도 정상적으로 잘 됩니다). 어디에 쓰는지는 모르겠는데 뒤에 실행할때 파이썬 경로를 설정해줘야 하니 깔아줍니다.

 

    2. 안드로이드 사용 시

        ㄱ. Android Studio 다운로드

        https://developer.android.com/studio

 

Download Android Studio and SDK tools  |  Android 스튜디오

developer.android.com

 ▶ 모니터 없는 터미널에서도 리눅스용 안드로이드 스튜디오 cli 를 이용하면 된다고는 하는데.. 저는 복잡해서 하다가 포기했습니다. 그냥 안드로이드 스튜디오 까는게 나은것 같네요

 

        ㄴ. Android NDK 다운로드

            우측 상단의 화면에서 SDK Manager 클릭

           차례대로 SDK Tools -> Show Package Details -> NDK 17 선택해줍니다(bazel 이 공식적으로 지원하는 버전은 10, 11, 12, 13, 14, 15, 16, 17, 18 입니다만, 21로 해봤는데 별 상관 없었습니다).

           OK 누른 후 기다리면 설치가 완료됩니다,

 

    3. tensorflow clone 및 서드파티 다운로드

> git clone https://github.com/tensorflow/tensorflow
> cd tensorflow
> ./tensorflow/lite/tools/make/download_dependencies.sh

 

  4. configure 실행 (만약 bazel 이 없다면 https://docs.bazel.build/versions/master/install.html 에서 깔아줍니다)

> ./configure

 

    5. 설정 입력 예시 (Enter: 기본값)

        * 대화에 맞게 필요한 설정들을 하면 됩니다. 경로는 모두 절대경로로 입력하는것에 주의해주세요!

        * compilation option 은

            * C++11 종속성 라이브러리를 사용하지 않게 해주는 옵션 ( -D_GLIBCXX_USE_CXX11_ABI=0 ) : 필수

            * 최적화 옵션( -O3 )으로

          설정해 주었습니다. 최적화 옵션은 안적어도 됩니다. 이 외에도 원하시는 기타 컴파일러 옵션들을 적어주시면 됩니다.

        * Android 용으로 빌드할거기 때문에 CUDA 및 다른 support를 사용 하지 않았고 configure WORKSPACE를 설정해 줬습니다.

        * TensorFlow Lite NNAPI를 사용하려면 minNDKVersion 을 27로 설정해야 합니다. (Android 전용)

You have bazel 2.0.0 installed.
Please specify the location of python. [Default is /System/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python]: 


Found possible Python library paths:
  /Library/Python/2.7/site-packages
Please input the desired Python library path to use.  Default is [/Library/Python/2.7/site-packages]

Do you wish to build TensorFlow with OpenCL SYCL support? [y/N]: n
No OpenCL SYCL support will be enabled for TensorFlow.

Do you wish to build TensorFlow with ROCm support? [y/N]: n
No ROCm support will be enabled for TensorFlow.

Do you wish to build TensorFlow with CUDA support? [y/N]: n
No CUDA support will be enabled for TensorFlow.

Do you wish to download a fresh release of clang? (Experimental) [y/N]: n
Clang will not be downloaded.

Please specify optimization flags to use during compilation when bazel option "--config=opt" is specified [Default is -march=native -Wno-sign-compare]: -D_GLIBCXX_USE_CXX11_ABI=0 -O3


Would you like to interactively configure ./WORKSPACE for Android builds? [y/N]: y
Searching for NDK and SDK installations.

Please specify the home path of the Android NDK to use. [Default is /Users/yonggyulee/library/Android/Sdk/ndk-bundle]: /Users/yonggyulee/library/Android/Sdk/ndk/17.2.4988734


Please specify the (min) Android NDK API level to use. [Available levels: ['14', '15', '16', '17', '18', '19', '21', '22', '23', '24', '26', '27', '28']] [Default is 21]: 27


Please specify the home path of the Android SDK to use. [Default is /Users/yonggyulee/library/Android/Sdk]: 


Please specify the Android SDK API level to use. [Available levels: ['26', '27', '28', '29']] [Default is 29]: 


Please specify an Android build tools version to use. [Available versions: ['28.0.3', '29.0.2']] [Default is 29.0.2]: 


Do you wish to build TensorFlow with iOS support? [y/N]: n
No iOS support will be enabled for TensorFlow.

Preconfigured Bazel build configs. You can use any of the below by adding "--config=<>" to your build command. See .bazelrc for more details.
	--config=mkl         	# Build with MKL support.
	--config=monolithic  	# Config for mostly static monolithic build.
	--config=ngraph      	# Build with Intel nGraph support.
	--config=numa        	# Build with NUMA support.
	--config=dynamic_kernels	# (Experimental) Build kernels into separate shared objects.
	--config=v2          	# Build TensorFlow 2.x instead of 1.x.
Preconfigured Bazel build configs to DISABLE default on features:
	--config=noaws       	# Disable AWS S3 filesystem support.
	--config=nogcp       	# Disable GCP support.
	--config=nohdfs      	# Disable HDFS support.
	--config=nonccl      	# Disable NVIDIA NCCL support.
Configuration finished

 

    configure 이 다 설정된 모습입니다.

 

    6. 라이브러리 빌드

 

        * 일반 빌드

bazel build -c opt --cxxopt=--std=c++11 //tensorflow/lite/c:tensorflowlite_c

 

        * Android ARM Board

bazel build -c opt --cxxopt=--std=c++11 --config=android_arm //tensorflow/lite/c:tensorflowlite_c

 

        * Android ARM64 Board

bazel build -c opt --cxxopt=--std=c++11 --config=android_arm64 //tensorflow/lite/c:tensorflowlite_c

 

        * iOS ARM64 Board

 bazel build -c opt --config ios_arm64 //tensorflow/lite/experimental/ios:TensorFlowLiteC_framework 

 

 

        * GPU delegate 라이브러리 일반 빌드 (선택 사항)

> bazel build -c opt //tensorflow/lite/delegates/gpu:libtensorflowlite_gpu_delegate.so 

 

        * GPU delegate 라이브러리 Android 빌드 (선택 사항)

> bazel build -c opt --config=android_arm64 //tensorflow/lite/delegates/gpu:libtensorflowlite_gpu_delegate.so

 

        * NNAPI delegate 라이브러리 빌드(Android 전용) (선택 사항)

> bazel build -c opt //tensorflow/lite/delegates/nnapi:nnapi_delegate
> bazel build -c opt //tensorflow/lite/nnapi:nnapi_implementation
> bazel build -c opt //tensorflow/lite/nnapi:nnapi_util

 

 

    7. 완료

bazel-bin/tensorflow/lite/c/libtensorflowlite_c.so

bazel-bin/tensorflow/lite/delegate/gpu/libtensorflowlite_gpu_delegate.so (선택 사항)

bazel-bin/tensorflow/lite/delegate/nnapi/libnnapi_delegate.a (선택 사항)
bazel-bin/tensorflow/lite/nnapi/libnnapi_implementation.a (선택 사항)
bazel-bin/tensorflow/lite/nnapi/libnnapi_util.a (선택 사항)

    이제 라이브러리 빌드가 완료됬습니다! 이제 사용법을 알아보러 가 볼까요?

 

2020/04/05 - [TensorFlow] - TensorFlow Lite 사용법 총정리! ((C/C++, Java, Python, Android)

 

TensorFlow Lite 사용법 총정리! ((C/C++, Java, Python, Android)

TensorFlow Lite 사용법 총정리! (C/C++, Java, Python, Android) 목차 0. 글을 쓰게 된 계기 1. TensorFlow Lite 가 뭔가요? 2. 기존 모델을 TensorFlow Lite 모델로 변환하기 3. TensorFlow Lite를 빌드해보자..

cppmagister.tistory.com