TensorFlow Lite の委譲を使用すると、別のエグゼキュータでモデルの一部または全体を実行できます。このメカニズムでは、推論に GPU や Edge TPU(Tensor Processing Unit)などのさまざまなデバイス上のアクセラレータを利用できます。これにより、デベロッパーはデフォルトの TFLite から分離された柔軟で、推論を高速化できます。
以下の図に代理人の概要を示します。詳細については、以下のセクションで説明します。
どのような場合にカスタム デリゲートを作成すればよいですか?
TensorFlow Lite には、GPU、DSP、EdgeTPU などのターゲット アクセラレータ用のさまざまなデリゲートがあります。
独自の委任を作成すると、次のような場合に便利です。
- 既存のデリゲートでサポートされていない新しい ML 推論エンジンを統合する場合。
- 既知のシナリオのランタイムを改善するカスタム ハードウェア アクセラレータがある。
- 特定のモデルを高速化できる CPU 最適化(演算子融合など)を開発する場合。
代理人の仕組み
次のような単純なモデルグラフと、Conv2D オペレーションと平均オペレーションを迅速に実装するデリゲート「MyDelegate」について考えてみましょう。
この「MyDelegate」を適用すると、元の TensorFlow Lite グラフは次のように更新されます。
TensorFlow Lite が元のグラフを 2 つのルールで分割すると、上のグラフが得られます。
- 委譲で処理できる特定のオペレーションは、オペレーション間の元のコンピューティング ワークフローの依存関係を維持しながら、パーティションに配置されます。
- 委任対象の各パーティションには、委任によって処理されない入力ノードと出力ノードのみが含まれます。
デリゲートによって処理される各パーティションは、呼び出し元の呼び出し時にパーティションを評価する元のグラフでは、デリゲートノード(デリゲート カーネルとも呼ばれます)に置き換えられます。
モデルによっては、最終的なグラフが 1 つ以上のノードになる可能性があります。後者の場合、一部の演算はデリゲートでサポートされません。一般に、デリゲートからメイングラフに切り替えるたびに、デリゲートからメイングラフに結果をメイングラフに渡すオーバーヘッド(GPU から CPU へのメモリコピーなど)が発生するため、デリゲートによって複数のパーティションを処理することは望ましくありません。このようなオーバーヘッドは、特にメモリのコピーが大量にある場合に、パフォーマンスの向上を相殺する可能性があります。
独自のカスタム デリゲートの実装
デリゲートを追加するための推奨方法は、SimpleDelegate API を使用することです。
新しいデリゲートを作成するには、2 つのインターフェースを実装し、インターフェース メソッドを独自に実装する必要があります。
1 ~SimpleDelegateInterface
このクラスは、デリゲートの機能(サポートされているオペレーション)と、委任グラフをカプセル化するカーネルを作成するためのファクトリ クラスを表します。詳細については、こちらの C++ ヘッダー ファイルで定義されているインターフェースをご覧ください。コード内のコメントには、各 API の詳細が記載されています。
2 ~SimpleDelegateKernelInterface
このクラスは、委任パーティションを初期化、準備、実行するロジックをカプセル化します。
これには次のものが含まれます(定義を参照)。
- Init(...): 1 回限りの初期化を行うために 1 回呼び出されます。
- Prepare(...): このノードの異なるインスタンスごとに呼び出されます。これは、複数の委任パーティションがある場合に行われます。このメソッドはテンソルがサイズ変更されるたびに呼び出されるため、通常はここでメモリの割り当てを行います。
- Invoke(...): 推論のために呼び出されます。
例
この例では、float32 テンソルでのみ 2 種類のオペレーション(ADD)と(SUB)のみをサポートできる非常にシンプルなデリゲートを作成します。
// MyDelegate implements the interface of SimpleDelegateInterface.
// This holds the Delegate capabilities.
class MyDelegate : public SimpleDelegateInterface {
public:
bool IsNodeSupportedByDelegate(const TfLiteRegistration* registration,
const TfLiteNode* node,
TfLiteContext* context) const override {
// Only supports Add and Sub ops.
if (kTfLiteBuiltinAdd != registration->builtin_code &&
kTfLiteBuiltinSub != registration->builtin_code)
return false;
// This delegate only supports float32 types.
for (int i = 0; i < node->inputs->size; ++i) {
auto& tensor = context->tensors[node->inputs->data[i]];
if (tensor.type != kTfLiteFloat32) return false;
}
return true;
}
TfLiteStatus Initialize(TfLiteContext* context) override { return kTfLiteOk; }
const char* Name() const override {
static constexpr char kName[] = "MyDelegate";
return kName;
}
std::unique_ptr<SimpleDelegateKernelInterface> CreateDelegateKernelInterface()
override {
return std::make_unique<MyDelegateKernel>();
}
};
次に、SimpleDelegateKernelInterface
から継承して、独自のデリゲート カーネルを作成します。
// My delegate kernel.
class MyDelegateKernel : public SimpleDelegateKernelInterface {
public:
TfLiteStatus Init(TfLiteContext* context,
const TfLiteDelegateParams* params) override {
// Save index to all nodes which are part of this delegate.
inputs_.resize(params->nodes_to_replace->size);
outputs_.resize(params->nodes_to_replace->size);
builtin_code_.resize(params->nodes_to_replace->size);
for (int i = 0; i < params->nodes_to_replace->size; ++i) {
const int node_index = params->nodes_to_replace->data[i];
// Get this node information.
TfLiteNode* delegated_node = nullptr;
TfLiteRegistration* delegated_node_registration = nullptr;
TF_LITE_ENSURE_EQ(
context,
context->GetNodeAndRegistration(context, node_index, &delegated_node,
&delegated_node_registration),
kTfLiteOk);
inputs_[i].push_back(delegated_node->inputs->data[0]);
inputs_[i].push_back(delegated_node->inputs->data[1]);
outputs_[i].push_back(delegated_node->outputs->data[0]);
builtin_code_[i] = delegated_node_registration->builtin_code;
}
return kTfLiteOk;
}
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) override {
return kTfLiteOk;
}
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) override {
// Evaluate the delegated graph.
// Here we loop over all the delegated nodes.
// We know that all the nodes are either ADD or SUB operations and the
// number of nodes equals ''inputs_.size()'' and inputs[i] is a list of
// tensor indices for inputs to node ''i'', while outputs_[i] is the list of
// outputs for node
// ''i''. Note, that it is intentional we have simple implementation as this
// is for demonstration.
for (int i = 0; i < inputs_.size(); ++i) {
// Get the node input tensors.
// Add/Sub operation accepts 2 inputs.
auto& input_tensor_1 = context->tensors[inputs_[i][0]];
auto& input_tensor_2 = context->tensors[inputs_[i][1]];
auto& output_tensor = context->tensors[outputs_[i][0]];
TF_LITE_ENSURE_EQ(
context,
ComputeResult(context, builtin_code_[i], &input_tensor_1,
&input_tensor_2, &output_tensor),
kTfLiteOk);
}
return kTfLiteOk;
}
private:
// Computes the result of addition of 'input_tensor_1' and 'input_tensor_2'
// and store the result in 'output_tensor'.
TfLiteStatus ComputeResult(TfLiteContext* context, int builtin_code,
const TfLiteTensor* input_tensor_1,
const TfLiteTensor* input_tensor_2,
TfLiteTensor* output_tensor) {
if (NumElements(input_tensor_1) != NumElements(input_tensor_2) ||
NumElements(input_tensor_1) != NumElements(output_tensor)) {
return kTfLiteDelegateError;
}
// This code assumes no activation, and no broadcasting needed (both inputs
// have the same size).
auto* input_1 = GetTensorData<float>(input_tensor_1);
auto* input_2 = GetTensorData<float>(input_tensor_2);
auto* output = GetTensorData<float>(output_tensor);
for (int i = 0; i < NumElements(input_tensor_1); ++i) {
if (builtin_code == kTfLiteBuiltinAdd)
output[i] = input_1[i] + input_2[i];
else
output[i] = input_1[i] - input_2[i];
}
return kTfLiteOk;
}
// Holds the indices of the input/output tensors.
// inputs_[i] is list of all input tensors to node at index 'i'.
// outputs_[i] is list of all output tensors to node at index 'i'.
std::vector<std::vector<int>> inputs_, outputs_;
// Holds the builtin code of the ops.
// builtin_code_[i] is the type of node at index 'i'
std::vector<int> builtin_code_;
};
新しいデリゲートのベンチマークと評価
TFLite には、TFLite モデルに対して簡単にテストできるツールセットがあります。
- モデル ベンチマーク ツール: TFLite モデルを使用してランダムな入力を生成し、指定した回数だけモデルを繰り返し実行します。最後に集計されたレイテンシ統計情報が出力されます
- 推論差分ツール: 特定のモデルに対して、このツールはランダムなガウスデータを生成し、それを 2 つの異なる TFLite インタープリタに渡します。1 つはシングルスレッド CPU カーネルを実行し、もう 1 つはユーザー定義の仕様を使用します。各インタープリタからの出力テンソルの絶対差を要素ごとに測定します。このツールは、精度の問題をデバッグする場合にも役立ちます。
- 画像分類とオブジェクト検出のタスク固有の評価ツールもあります。これらのツールはこちらにあります。
さらに、TFLite には、カーネルとオペレーションの単体テストが多数用意されています。これを再利用して、カバレッジを広げて新しいデリゲートをテストし、通常の TFLite 実行パスが破損しないようにできます。
新しいデリゲートで TFLite のテストとツールを再利用するには、次の 2 つのオプションのいずれかを使用できます。
最適なアプローチの選択
どちらの方法でも、以下に詳述するように、いくつかの変更が必要です。ただし、最初の方法ではデリゲートを静的にリンクし、テストツール、ベンチマーク ツール、評価ツールを再ビルドする必要があります。一方、2 つ目のメソッドでは、デリゲートを共有ライブラリとして実行するため、共有ライブラリから create/delete メソッドを公開する必要があります。
そのため、この外部委任メカニズムは TFLite のビルド済みの Tensorflow Lite ツール バイナリで動作します。ただし、あまり明確ではなく、自動統合テストでのセットアップは複雑になる可能性があります。わかりやすくするために、委任登録事業者のアプローチを使用します。
オプション 1: 委任登録事業者を利用する
委任登録事業者は委任プロバイダのリストを保持します。委任プロバイダはそれぞれ、コマンドライン フラグに基づいて TFLite デリゲートを簡単に作成できるため、ツールに便利です。前述のすべての Tensorflow Lite ツールに新しいデリゲートを接続するには、まず新しいデリゲート プロバイダを作成してから、BUILD ルールに少数の変更を加えます。この統合プロセスの完全な例を以下に示します(コードはこちらにあります)。
次のように、SimpleDelegate API を実装するデリゲートと、この「ダミー」のデリゲートを作成または削除するための外部「C」API があるとします。
// Returns default options for DummyDelegate.
DummyDelegateOptions TfLiteDummyDelegateOptionsDefault();
// Creates a new delegate instance that need to be destroyed with
// `TfLiteDummyDelegateDelete` when delegate is no longer used by TFLite.
// When `options` is set to `nullptr`, the above default values are used:
TfLiteDelegate* TfLiteDummyDelegateCreate(const DummyDelegateOptions* options);
// Destroys a delegate created with `TfLiteDummyDelegateCreate` call.
void TfLiteDummyDelegateDelete(TfLiteDelegate* delegate);
「DummyDelegate」をベンチマーク ツールや推論ツールと統合するには、次のように DelegateProvider を定義します。
class DummyDelegateProvider : public DelegateProvider {
public:
DummyDelegateProvider() {
default_params_.AddParam("use_dummy_delegate",
ToolParam::Create<bool>(false));
}
std::vector<Flag> CreateFlags(ToolParams* params) const final;
void LogParams(const ToolParams& params) const final;
TfLiteDelegatePtr CreateTfLiteDelegate(const ToolParams& params) const final;
std::string GetName() const final { return "DummyDelegate"; }
};
REGISTER_DELEGATE_PROVIDER(DummyDelegateProvider);
std::vector<Flag> DummyDelegateProvider::CreateFlags(ToolParams* params) const {
std::vector<Flag> flags = {CreateFlag<bool>("use_dummy_delegate", params,
"use the dummy delegate.")};
return flags;
}
void DummyDelegateProvider::LogParams(const ToolParams& params) const {
TFLITE_LOG(INFO) << "Use dummy test delegate : ["
<< params.Get<bool>("use_dummy_delegate") << "]";
}
TfLiteDelegatePtr DummyDelegateProvider::CreateTfLiteDelegate(
const ToolParams& params) const {
if (params.Get<bool>("use_dummy_delegate")) {
auto default_options = TfLiteDummyDelegateOptionsDefault();
return TfLiteDummyDelegateCreateUnique(&default_options);
}
return TfLiteDelegatePtr(nullptr, [](TfLiteDelegate*) {});
}
BUILD ルールの定義は重要です。ライブラリが常にリンクされ、オプティマイザーによって破棄されないようにする必要があるためです。
#### The following are for using the dummy test delegate in TFLite tooling ####
cc_library(
name = "dummy_delegate_provider",
srcs = ["dummy_delegate_provider.cc"],
copts = tflite_copts(),
deps = [
":dummy_delegate",
"//tensorflow/lite/tools/delegates:delegate_provider_hdr",
],
alwayslink = 1, # This is required so the optimizer doesn't optimize the library away.
)
次に、この 2 つのラッパールールを BUILD ファイルに追加して、独自のデリゲートで実行できるベンチマーク ツールと推論ツール、およびその他の評価ツールのバージョンを作成します。
cc_binary(
name = "benchmark_model_plus_dummy_delegate",
copts = tflite_copts(),
linkopts = task_linkopts(),
deps = [
":dummy_delegate_provider",
"//tensorflow/lite/tools/benchmark:benchmark_model_main",
],
)
cc_binary(
name = "inference_diff_plus_dummy_delegate",
copts = tflite_copts(),
linkopts = task_linkopts(),
deps = [
":dummy_delegate_provider",
"//tensorflow/lite/tools/evaluation/tasks:task_executor_main",
"//tensorflow/lite/tools/evaluation/tasks/inference_diff:run_eval_lib",
],
)
cc_binary(
name = "imagenet_classification_eval_plus_dummy_delegate",
copts = tflite_copts(),
linkopts = task_linkopts(),
deps = [
":dummy_delegate_provider",
"//tensorflow/lite/tools/evaluation/tasks:task_executor_main",
"//tensorflow/lite/tools/evaluation/tasks/imagenet_image_classification:run_eval_lib",
],
)
cc_binary(
name = "coco_object_detection_eval_plus_dummy_delegate",
copts = tflite_copts(),
linkopts = task_linkopts(),
deps = [
":dummy_delegate_provider",
"//tensorflow/lite/tools/evaluation/tasks:task_executor_main",
"//tensorflow/lite/tools/evaluation/tasks/coco_object_detection:run_eval_lib",
],
)
また、こちらに記載されているように、このデリゲート プロバイダを TFLite カーネルテストに接続することもできます。
オプション 2: 外部委任を利用する
この方法では、まず、次のように external_delegate_adaptor.cc に外部委任アダプターを作成します。ただし、この方法は前述のオプション 1 に比べてやや推奨されません。
TfLiteDelegate* CreateDummyDelegateFromOptions(char** options_keys,
char** options_values,
size_t num_options) {
DummyDelegateOptions options = TfLiteDummyDelegateOptionsDefault();
// Parse key-values options to DummyDelegateOptions.
// You can achieve this by mimicking them as command-line flags.
std::unique_ptr<const char*> argv =
std::unique_ptr<const char*>(new const char*[num_options + 1]);
constexpr char kDummyDelegateParsing[] = "dummy_delegate_parsing";
argv.get()[0] = kDummyDelegateParsing;
std::vector<std::string> option_args;
option_args.reserve(num_options);
for (int i = 0; i < num_options; ++i) {
option_args.emplace_back("--");
option_args.rbegin()->append(options_keys[i]);
option_args.rbegin()->push_back('=');
option_args.rbegin()->append(options_values[i]);
argv.get()[i + 1] = option_args.rbegin()->c_str();
}
// Define command-line flags.
// ...
std::vector<tflite::Flag> flag_list = {
tflite::Flag::CreateFlag(...),
...,
tflite::Flag::CreateFlag(...),
};
int argc = num_options + 1;
if (!tflite::Flags::Parse(&argc, argv.get(), flag_list)) {
return nullptr;
}
return TfLiteDummyDelegateCreate(&options);
}
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
// Defines two symbols that need to be exported to use the TFLite external
// delegate. See tensorflow/lite/delegates/external for details.
TFL_CAPI_EXPORT TfLiteDelegate* tflite_plugin_create_delegate(
char** options_keys, char** options_values, size_t num_options,
void (*report_error)(const char*)) {
return tflite::tools::CreateDummyDelegateFromOptions(
options_keys, options_values, num_options);
}
TFL_CAPI_EXPORT void tflite_plugin_destroy_delegate(TfLiteDelegate* delegate) {
TfLiteDummyDelegateDelete(delegate);
}
#ifdef __cplusplus
}
#endif // __cplusplus
以下に示すように、対応する BUILD ターゲットを作成して動的ライブラリをビルドします。
cc_binary(
name = "dummy_external_delegate.so",
srcs = [
"external_delegate_adaptor.cc",
],
linkshared = 1,
linkstatic = 1,
deps = [
":dummy_delegate",
"//tensorflow/lite/c:common",
"//tensorflow/lite/tools:command_line_flags",
"//tensorflow/lite/tools:logging",
],
)
この外部デリゲートの .so ファイルが作成されたら、バイナリをビルドするか、ビルド済みのものを使用して新しいデリゲートで実行できます。ただし、バイナリが、こちらで説明されているコマンドライン フラグをサポートする external_delegate_provider ライブラリにリンクされている必要があります。注: この外部デリゲート プロバイダは、既存のテスト バイナリとツール バイナリにすでにリンクされています。
この外部デリゲートのアプローチを介してダミー デリゲートのベンチマークを行う方法については、こちらの説明をご覧ください。前述のテストツールや評価ツールにも同様のコマンドを使用できます。
外部デリゲートは、こちらに示すように、Tensorflow Lite の Python バインディングにおけるデリゲートの対応する C++ 実装です。したがって、ここで作成した動的な外部デリゲート アダプター ライブラリは、Tensorflow Lite Python API で直接使用できます。
リソース
夜間にビルドされた TFLite ツール バイナリのダウンロード リンク
OS | アーチ | BINARY_NAME |
Linux | x86_64 | |
arm | ||
aarch64 | ||
Android | arm | |
aarch64 |