TensorFlow生成android .so文件流程以及縮減.so文件大小的方法

步驟:

(1)修改WORKSPACE 配置(sdk & ndk)

# Uncomment and update the paths in these entries to build the Android demo.
android_sdk_repository(
  name = "androidsdk",
  api_level = 23,
    # Ensure that you have the build_tools_version below installed in the
    # SDK manager as it updates periodically.
  build_tools_version = "25.0.0",
   # Replace with path to Android SDK on your system
  path = "/Users/scucheri/Library/Android/sdk",
)
#
# Android NDK r12b is recommended (higher may cause issues with Bazel)
android_ndk_repository(
    name="androidndk",
    path="/Users/scucheri/Library/Android/android-ndk-r12b",
    # This needs to be 14 or higher to compile TensorFlow.
    # Note that the NDK version is not the API level.
    api_level=14)

(2)在tensorflow根目錄下 運(yùn)行 ./configure 進(jìn)行一些設(shè)置

(3)根據(jù)現(xiàn)有的模型文件.pb生成注冊(cè)文件 ops_to_register.h,這個(gè)文件會(huì)被放置在tensorflow根目錄下:

 bazel build tensorflow/python/tools:print_selective_registration_header && \
  bazel-bin/tensorflow/python/tools/print_selective_registration_header \
    --graphs=/Users/scucheri/AllMyProjects/AI_android/tensorflow_models/optimized_frozen_lstm.pb  > ops_to_register.h

(4)將生成的 ops_to_register.h 文件復(fù)制到./tensorflow/core/framework 目錄下

(5)運(yùn)行bazel生成so文件,--copt="-DSUPPORT_SELECTIVE_REGISTRATION" 就是表示需要開啟選擇注冊(cè)的opt。這個(gè)非常有用,試了一下,原本9.7M的so文件,在用LSTM算法生成的.pb模型文件選擇它需要的計(jì)算方法打包之后,縮減到了2.4M ! 多么驚喜的一件事~

 bazel build -c opt --copt="-DSELECTIVE_REGISTRATION" \
        --copt="-DSUPPORT_SELECTIVE_REGISTRATION" \
        //tensorflow/contrib/android:libtensorflow_inference.so \
        --host_crosstool_top=@bazel_tools//tools/cpp:toolchain \
        --crosstool_top=//external:android/crosstool --cpu=armeabi-v7a

若想生成包括全部計(jì)算方法的.so,如下:

 bazel build -c opt //tensorflow/contrib/android:libtensorflow_inference.so \
     --crosstool_top=//external:android/crosstool \
     --host_crosstool_top=@bazel_tools//tools/cpp:toolchain \
     --cpu=armeabi-v7a

如果出錯(cuò),試一下bazel clean 之后重新運(yùn)行

結(jié)果:bazel-bin/tensorflow/contrib/android/libtensorflow_inference.so

(6)生成jar

bazel build //tensorflow/contrib/android:android_tensorflow_inference_java

結(jié)果:bazel-bin/tensorflow/contrib/android/libandroid_tensorflow_inference_java.jar

參考:

https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/android

https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/tools/print_selective_registration_header.py

https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/framework/selective_registration.h

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容