LiteRT バイナリサイズを縮小する

概要

オンデバイス ML(ODML)アプリケーション用のモデルをデプロイする際は、モバイル デバイスで使用できるメモリが限られていることに注意することが重要です。モデルのバイナリサイズは、モデルで使用されるオペレーションの数と密接に関連しています。LiteRT を使用すると、選択的ビルドを使用してモデル バイナリのサイズを縮小できます。選択的ビルドでは、モデルセット内の未使用のオペレーションがスキップされ、モデルをモバイル デバイスで実行するために必要なランタイムと op カーネルのみを含むコンパクトなライブラリが生成されます。

選択的ビルドは、次の 3 つのオペレーション ライブラリに適用されます。

  1. LiteRT の組み込み ops ライブラリ
  2. LiteRT カスタム オペレーション
  3. TensorFlow ops ライブラリを選択する

次の表に、一般的なユースケースにおける選択的ビルドの影響を示します。

モデル名 ドメイン ターゲット アーキテクチャ AAR ファイルのサイズ
Mobilenet_1.0_224(float) 画像分類 armeabi-v7a tensorflow-lite.aar(296,635 バイト)
arm64-v8a tensorflow-lite.aar(382,892 バイト)
SPICE 音のピッチの抽出 armeabi-v7a tensorflow-lite.aar(375,813 バイト)
tensorflow-lite-select-tf-ops.aar(1,676,380 バイト)
arm64-v8a tensorflow-lite.aar(421,826 バイト)
tensorflow-lite-select-tf-ops.aar(2,298,630 バイト)
i3d-kinetics-400 動画分類 armeabi-v7a tensorflow-lite.aar(240,085 バイト)
tensorflow-lite-select-tf-ops.aar(1,708,597 バイト)
arm64-v8a tensorflow-lite.aar(273,713 バイト)
tensorflow-lite-select-tf-ops.aar(2,339,697 バイト)

Bazel を使用して LiteRT を選択的にビルドする

このセクションでは、TensorFlow のソースコードをダウンロードし、Bazel にローカル開発環境を設定していることを前提としています。

Android プロジェクトの AAR ファイルをビルドする

モデルのファイルパスを次のように指定することで、カスタム LiteRT AAR をビルドできます。

sh tensorflow/lite/tools/build_aar.sh \
  --input_models=/a/b/model_one.tflite,/c/d/model_two.tflite \
  --target_archs=x86,x86_64,arm64-v8a,armeabi-v7a

上記のコマンドは、LiteRT の組み込みオペレーションとカスタム オペレーション用の AAR ファイル bazel-bin/tmp/tensorflow-lite.aar を生成します。また、モデルに Select TensorFlow オペレーションが含まれている場合は、オプションで aar ファイル bazel-bin/tmp/tensorflow-lite-select-tf-ops.aar を生成します。これは、複数の異なるアーキテクチャを含む「ファット」AAR をビルドします。すべてが必要ない場合は、デプロイ環境に適したサブセットを使用してください。

カスタム オペレーションでビルドする

カスタム オペレーションで LiteRT モデルを開発した場合は、ビルド コマンドに次のフラグを追加してビルドできます。

sh tensorflow/lite/tools/build_aar.sh \
  --input_models=/a/b/model_one.tflite,/c/d/model_two.tflite \
  --target_archs=x86,x86_64,arm64-v8a,armeabi-v7a \
  --tflite_custom_ops_srcs=/e/f/file1.cc,/g/h/file2.h \
  --tflite_custom_ops_deps=dep1,dep2

tflite_custom_ops_srcs フラグにはカスタム オペレーションのソースファイルが含まれ、tflite_custom_ops_deps フラグにはそれらのソースファイルをビルドするための依存関係が含まれます。これらの依存関係は TensorFlow リポジトリに存在する必要があります。

高度な使用方法: カスタム Bazel ルール

プロジェクトで Bazel を使用しており、特定のモデルセットに対してカスタム TFLite 依存関係を定義する場合は、プロジェクト リポジトリで次のルールを定義できます。

組み込みオペレーションのみを含むモデルの場合:

load(
    "@org_tensorflow//tensorflow/lite:build_def.bzl",
    "tflite_custom_android_library",
    "tflite_custom_c_library",
    "tflite_custom_cc_library",
)

# A selectively built TFLite Android library.
tflite_custom_android_library(
    name = "selectively_built_android_lib",
    models = [
        ":model_one.tflite",
        ":model_two.tflite",
    ],
)

# A selectively built TFLite C library.
tflite_custom_c_library(
    name = "selectively_built_c_lib",
    models = [
        ":model_one.tflite",
        ":model_two.tflite",
    ],
)

# A selectively built TFLite C++ library.
tflite_custom_cc_library(
    name = "selectively_built_cc_lib",
    models = [
        ":model_one.tflite",
        ":model_two.tflite",
    ],
)

[Select TF ops] があるモデルの場合:

load(
    "@org_tensorflow//tensorflow/lite/delegates/flex:build_def.bzl",
    "tflite_flex_android_library",
    "tflite_flex_cc_library",
)

# A Select TF ops enabled selectively built TFLite Android library.
tflite_flex_android_library(
    name = "selective_built_tflite_flex_android_lib",
    models = [
        ":model_one.tflite",
        ":model_two.tflite",
    ],
)

# A Select TF ops enabled selectively built TFLite C++ library.
tflite_flex_cc_library(
    name = "selective_built_tflite_flex_cc_lib",
    models = [
        ":model_one.tflite",
        ":model_two.tflite",
    ],
)

高度な使用方法: カスタム C/C++ 共有ライブラリをビルドする

指定されたモデルに対して独自のカスタム TFLite C/C++ 共有オブジェクトをビルドする場合は、次の手順に沿って操作します。

TensorFlow ソースコードのルート ディレクトリで次のコマンドを実行して、一時的な BUILD ファイルを作成します。

mkdir -p tmp && touch tmp/BUILD

カスタム C 共有オブジェクトのビルド

カスタム TFLite C 共有オブジェクトをビルドする場合は、tmp/BUILD ファイルに次の行を追加します。

load(
    "//tensorflow/lite:build_def.bzl",
    "tflite_custom_c_library",
    "tflite_cc_shared_object",
)

tflite_custom_c_library(
    name = "selectively_built_c_lib",
    models = [
        ":model_one.tflite",
        ":model_two.tflite",
    ],
)

# Generates a platform-specific shared library containing the LiteRT C
# API implementation as define in `c_api.h`. The exact output library name
# is platform dependent:
#   - Linux/Android: `libtensorflowlite_c.so`
#   - Mac: `libtensorflowlite_c.dylib`
#   - Windows: `tensorflowlite_c.dll`
tflite_cc_shared_object(
    name = "tensorflowlite_c",
    linkopts = select({
        "//tensorflow:ios": [
            "-Wl,-exported_symbols_list,$(location //tensorflow/lite/c:exported_symbols.lds)",
        ],
        "//tensorflow:macos": [
            "-Wl,-exported_symbols_list,$(location //tensorflow/lite/c:exported_symbols.lds)",
        ],
        "//tensorflow:windows": [],
        "//conditions:default": [
            "-z defs",
            "-Wl,--version-script,$(location //tensorflow/lite/c:version_script.lds)",
        ],
    }),
    per_os_targets = True,
    deps = [
        ":selectively_built_c_lib",
        "//tensorflow/lite/c:exported_symbols.lds",
        "//tensorflow/lite/c:version_script.lds",
    ],
)

新しく追加されたターゲットは、次のようにビルドできます。

bazel build -c opt --cxxopt=--std=c++17 \
  //tmp:tensorflowlite_c

Android の場合(64 ビットの場合は android_armandroid_arm64 に置き換えます):

bazel build -c opt --cxxopt=--std=c++17 --config=android_arm \
  //tmp:tensorflowlite_c

カスタム C++ 共有オブジェクトのビルド

カスタムの TFLite C++ 共有オブジェクトをビルドする場合は、tmp/BUILD ファイルに以下を追加します。

load(
    "//tensorflow/lite:build_def.bzl",
    "tflite_custom_cc_library",
    "tflite_cc_shared_object",
)

tflite_custom_cc_library(
    name = "selectively_built_cc_lib",
    models = [
        ":model_one.tflite",
        ":model_two.tflite",
    ],
)

# Shared lib target for convenience, pulls in the core runtime and builtin ops.
# Note: This target is not yet finalized, and the exact set of exported (C/C++)
# APIs is subject to change. The output library name is platform dependent:
#   - Linux/Android: `libtensorflowlite.so`
#   - Mac: `libtensorflowlite.dylib`
#   - Windows: `tensorflowlite.dll`
tflite_cc_shared_object(
    name = "tensorflowlite",
    # Until we have more granular symbol export for the C++ API on Windows,
    # export all symbols.
    features = ["windows_export_all_symbols"],
    linkopts = select({
        "//tensorflow:macos": [
            "-Wl,-exported_symbols_list,$(location //tensorflow/lite:tflite_exported_symbols.lds)",
        ],
        "//tensorflow:windows": [],
        "//conditions:default": [
            "-Wl,-z,defs",
            "-Wl,--version-script,$(location //tensorflow/lite:tflite_version_script.lds)",
        ],
    }),
    per_os_targets = True,
    deps = [
        ":selectively_built_cc_lib",
        "//tensorflow/lite:tflite_exported_symbols.lds",
        "//tensorflow/lite:tflite_version_script.lds",
    ],
)

新しく追加されたターゲットは、次のようにビルドできます。

bazel build -c opt  --cxxopt=--std=c++17 \
  //tmp:tensorflowlite

Android の場合(64 ビットの場合は android_armandroid_arm64 に置き換えます):

bazel build -c opt --cxxopt=--std=c++17 --config=android_arm \
  //tmp:tensorflowlite

[Select TF ops] を含むモデルの場合は、次の共有ライブラリもビルドする必要があります。

load(
    "@org_tensorflow//tensorflow/lite/delegates/flex:build_def.bzl",
    "tflite_flex_shared_library"
)

# Shared lib target for convenience, pulls in the standard set of TensorFlow
# ops and kernels. The output library name is platform dependent:
#   - Linux/Android: `libtensorflowlite_flex.so`
#   - Mac: `libtensorflowlite_flex.dylib`
#   - Windows: `libtensorflowlite_flex.dll`
tflite_flex_shared_library(
  name = "tensorflowlite_flex",
  models = [
      ":model_one.tflite",
      ":model_two.tflite",
  ],
)

新しく追加されたターゲットは、次のようにビルドできます。

bazel build -c opt --cxxopt='--std=c++17' \
      --config=monolithic \
      --host_crosstool_top=@bazel_tools//tools/cpp:toolchain \
      //tmp:tensorflowlite_flex

Android の場合(64 ビットの場合は android_armandroid_arm64 に置き換えます):

bazel build -c opt --cxxopt='--std=c++17' \
      --config=android_arm \
      --config=monolithic \
      --host_crosstool_top=@bazel_tools//tools/cpp:toolchain \
      //tmp:tensorflowlite_flex

Docker を使用して LiteRT を選択的にビルドする

このセクションでは、ローカルマシンに Docker がインストールされ、LiteRT Dockerfile がこちらからダウンロードされていることを前提としています。

上記の Dockerfile をダウンロードしたら、次のコマンドを実行して Docker イメージをビルドできます。

docker build . -t tflite-builder -f tflite-android.Dockerfile

Android プロジェクトの AAR ファイルをビルドする

次のコマンドを実行して、Docker でビルドするためのスクリプトをダウンロードします。

curl -o build_aar_with_docker.sh \
  https://raw.githubusercontent.com/tensorflow/tensorflow/master/tensorflow/lite/tools/build_aar_with_docker.sh &&
chmod +x build_aar_with_docker.sh

次に、モデルのファイルパスを次のように指定して、カスタム LiteRT AAR をビルドできます。

sh build_aar_with_docker.sh \
  --input_models=/a/b/model_one.tflite,/c/d/model_two.tflite \
  --target_archs=x86,x86_64,arm64-v8a,armeabi-v7a \
  --checkpoint=master \
  [--cache_dir=<path to cache directory>]

checkpoint フラグは、ライブラリをビルドする前にチェックアウトする TensorFlow リポジトリの commit、ブランチ、またはタグです。デフォルトでは、最新のリリース ブランチです。上記のコマンドを実行すると、LiteRT の組み込みオペレーションとカスタム オペレーション用の AAR ファイル tensorflow-lite.aar と、必要に応じて、現在のディレクトリに Select TensorFlow オペレーション用の AAR ファイル tensorflow-lite-select-tf-ops.aar が生成されます。

--cache_dir はキャッシュ ディレクトリを指定します。指定されていない場合、スクリプトは現在の作業ディレクトリに bazel-build-cache という名前のディレクトリを作成して、キャッシュ保存に使用します。

プロジェクトに AAR ファイルを追加する

AAR ファイルを追加するには、AAR をプロジェクトに直接インポートするか、カスタム AAR をローカルの Maven リポジトリに公開します。生成する場合は、tensorflow-lite-select-tf-ops.aar の AAR ファイルも追加する必要があります。

iOS の選択的ビルド

ローカルでのビルドのセクションを参照して、ビルド環境を設定し、TensorFlow ワークスペースを構成してから、ガイドに沿って iOS 用の選択的ビルド スクリプトを使用してください。