SlideShare uma empresa Scribd logo
1 de 32
TensorFlow Lite
Delegate とは?
作成:2019.11.17

@Vengineer



左のツイートにあるよう
に、「TensorFlow Lite
Delegate」が一番興味が
あるようでしたので、資料
を公開します。
なお、この資料は
TensorFlow r2.0のソー
スコードをベースに作成し
ました。
TensorFlow Lite とは?
TensorFlow Lite は、TensorFlowのモデルを
デバイス上(mobile / embedded / IoT)での推論を可能にする、
オープンソースのディープ ラーニング フレームワーク
デバイス上で推論すると、こんなにいいことが!
● レイテンシー :サーバーにデータを送らないので!
● プライバシー :データをデバイスに残す必要がない!
● コネクティビティ :インターネットに接続しなくていい!
● 電力消費 :ネットワーク接続は電気食い
TensorFlow Lite for Microcontrollers のお話は、今回しません
TensorFlow Lite を利用するステップ
● モデルの選択:学習する・学習済み
○ 学習はクラウド : Google Colaboratory (GPU, TPUも使える)
○ 学習済みモデルもたんまり
● 変換:TensorFlow => TensorFlow Lite
○ TensorFlow Lite Converter
● 最適化
○ 量子化 (8bit int, 16bit float), delegate
● デプロイ:専用の推論エンジン
○ TensorFlow Lite Interpreter
TensorFlow Lite guide を読めばいい!(一部は日本語に訳されているよ)
TensorFlow Lite Delegates
  Delegate API は、まだ experimental なので、今後変更有
Delegate は、TensorFlow Liteのグラフの一部/全体をCPU以外の Executor
に委譲 (delegate) するもの
● GPU :OpenGL ES v3.1 / OpenCL / Metal (iOS)
● AIアクセラレータ :Google Edge TPU / Google Pixel Neural Core
● Android NN APIs :v1.0 (8.1) / v1.1 (9.0) / v1.2 (10.0)
● Flex :TensorFlow Select
● その他 :Arm NN (PR#33436)
TensorFlow Lite 2019 Roadmap
https://www.tensorflow.org/lite/guide/roadmap
● Updated NN API support
  Full support for new Android Q NN API features, ops and types
● GPU backend optimizations
  OpenCL and Vulkan support on Android
  Metal and Objective-C CocoaPods for Metal acceleration
● Hexagon DSP backend
  Initial release of DSP acceleration for pre-Android P devices
TensorFlow LiteDelegate documentation
https://www.tensorflow.org/lite/performance/delegates
Run inference with TensorFlow Lite in Python
https://coral.withgoogle.com/docs/edgetpu/tflite-python/
Python quickstart (tflite_runtime というのがある)
https://www.tensorflow.org/lite/guide/python
Edge TPU inferencing overview
https://coral.withgoogle.com/docs/edgetpu/inference/
Run inference with TensorFlow Lite in C++ (Edge TPU)
https://coral.withgoogle.com/docs/edgetpu/tflite-cpp/
C++ API
CPU : Delegateなし、基本パターン
// TensorFlow Liteモデルをファイルから読み込み
 auto model = FlatBufferModel::BuildFromFile("interesting_model.tflite");
// 推論エンジンにモデルをロードする
ops::builtin::BuiltinOpResolver op_resolver;
std::unique_ptr<Interpreter> interpreter;
InterpreterBuilder(*model, op_resolver)(&interpreter);
 // メモリの割り当てをする
interpreter->AllocateTensors();
// .... (Prepare input tensors) 入力データの準備
 // 推論の実行
interpreter->Invoke();
// .... (Retrieve the result from output tensors) 出力データを取り込む
GPU Delegate : v1 (OpenGLES)
 // モデルの読み込み、推論エンジンへのモデルのロードまでは同じ
const TfLiteGpuDelegateOptions options = {
.metadata = NULL,
.compile_options = {
.precision_loss_allowed = 1, // FP16
.preferred_gl_object_type = TFLITE_GL_OBJECT_TYPE_FASTEST,
.dynamic_batch_enabled = 0, // Not fully functional yet
},
};
auto* delegate = TfLiteGpuDelegateCreate(&options);
interpreter->ModifyGraphWithDelegate(delegate); Delegateの設定
 // 推論エンジンの実行も同じ
GPU Delegate : v2 (OpenCL => OpenGLES)
 // モデルの読み込み、推論エンジンへのモデルのロードまでは同じ
 // v1 と違って、option はデフォルトでは必要なくなった
 // v2 では、最初に OpenCL をチェックして、なければ、 OpenGL ES v3.1 を実行
auto* delegate = TfLiteGpuDelegateV2Create(/*default options=*/nullptr);
interpreter->ModifyGraphWithDelegate(delegate);
 // 推論エンジンの実行も同じ
Google Edge TPU Delegate
 // モデルの読み込み、推論エンジンへのモデルのロードまでは同じ
size_t num_devices;
std::unique_ptr<edgetpu_device, decltype(&edgetpu_free_devices)> devices(
edgetpu_list_devices(&num_devices), &edgetpu_free_devices);
const auto& device = devices.get()[0];
 // 専用APIにて、Edge TPUのDelegateを獲得
auto* delegate = edgetpu_create_delegate(device.type, device.path, nullptr, 0);
interpreter->ModifyGraphWithDelegate({delegate, edgetpu_free_delegate});
//edgetpu_free_delegate があるのは次ページ
 // 推論エンジンの実行も同じ
もうひとつのModifyGraphWithDelegate
// Owning handle to a TfLiteDelegate instance.
using TfLiteDelegatePtr = std::unique_ptr<TfLiteDelegate, void (*)(TfLiteDelegate*)>;
/// Same as ModifyGraphWithDelegate except this interpreter takes
/// ownership of the provided delegate. Be sure to construct the unique_ptr
/// with a suitable destruction function.
/// WARNING: This is an experimental API and subject to change.
TfLiteStatus ModifyGraphWithDelegate(TfLiteDelegatePtr delegate);
Android NN APIs Delegate
 // モデルの読み込み、推論エンジンへのモデルのロードまでは同じ
auto* delegate = NnApiDelegate();
interpreter->ModifyGraphWithDelegate(delegate);
 // 推論エンジンの実行も同じ
 // DEPRECATED: Please use StatefulNnApiDelegate class instead.
TfLiteDelegate* NnApiDelegate() {
static StatefulNnApiDelegate* delegate = new StatefulNnApiDelegate();
return delegate;
}
Flex Delegate:TensorFlow Select時
 // モデルの読み込み、推論エンジンへのモデルのロードまでは同じ
auto* delegate = FlexDelegate::Create();
interpreter->ModifyGraphWithDelegate(delegate);
 // 推論エンジンの実行も同じ
TensorFlow Select
TensorFlow Liteに、TensorFlowのOpを使えるようにするためのものです。
「Select TensorFlow operators to use in TensorFlow Lite」
このビデオ「Inside TensorFlow: TensorFlow Lite」のModel Conversionの説明部分。
converter をビルドするときに、 --define=tflite_convert_with_select_tf_ops=true を指定する
bazel run --define=tflite_convert_with_select_tf_ops=true tflite_convert -- 
--output_file=/tmp/foo.tflite 
--graph_def_file=/tmp/foo.pb 
--input_arrays=input 
--output_arrays=MobilenetV1/Predictions/Reshape_1 
--target_ops=TFLITE_BUILTINS,SELECT_TF_OPS
ArmNN Delegate
Add initial minimal ArmNN delegate plugin. #33436
https://github.com/GeorgeARM/tensorflow/tree/armnn_delegate/tensorflow/lite/delegates/armnn
The following kernels are currently off-loaded:
- Pool2d
- AvgPool
- MaxPool
- L2Pool
- Conv2d
- Depthwise Conv2d
- Softmax
- Squeeze
ArmNN Delegate
 // モデルの読み込み、推論エンジンへのモデルのロードまでは同じ
 Interpreter::TfLiteDelegatePtr CreateArmNNDelegate(ArmNNDelegate::Options options) {
  return Interpreter::TfLiteDelegatePtr(
new ArmNNDelegate(options), [](TfLiteDelegate* delegate) {
delete reinterpret_cast<ArmNNDelegate*>(delegate);
});
 }
 ArmNNDelegate::Options opts;
 opts.backend_name = "CpuRef";
 auto delegate = CreateArmNNDelegate(opts));
 interpreter->ModifyGraphWithDelegate(delegate);
 // 推論エンジンの実行も同じ
Qualcomm Hexagon Delegate
Tflite Qualcomm DSP acceleration #29028 ?
NPE hardware acceleration support in Qualcomm chips #17526 ?
InterpreterInvoke
 モデル、Delegate、入力データ、出力データがあれば、この関数でOK!
 Status InterpreterInvoke(const ::tflite::Model* model,
  TfLiteDelegate* delegate,
  const std::vector<TensorFloat32>& inputs,
  std::vector<TensorFloat32>* outputs);
InterpreterInvoke
auto model = FlatBufferModel::BuildFromFile("interesting_model.tflite);
auto* delegate = Delegateを生成する
std::vector<TensorFloat32>& inputs;
std::vector<TensorFloat32>* outputs;
InterpreterInvoke(model, delegate, inputs, outputs);
 // 推論エンジンの実行は同じ
Python API
Edge TPU の例
interpreter = Interpreter(model_path=args.model_file)
を
interpreter = Interpreter(model_path=args.model_file,
   experimental_delegates=[load_delegate('libedgetpu.so.1.0')])
に変更するだけ。
from tensorflow.lite.python.interpreter import load_delegate
で、load_delegate を取り込めばいい。
lite.experimental.load_delegate
@_tf_export('lite.experimental.load_delegate')
def load_delegate(library, options=None):
"""Returns loaded Delegate object.
Args:
library: Name of shared library containing the
[TfLiteDelegate](https://www.tensorflow.org/lite/performance/delegates).
options: Dictionary of options that are required to load the delegate. All
keys and values in the dictionary should be convertible to str. Consult
the documentation of the specific delegate for required and legal options.
(default None)
Returns:
Delegate object.
Raises:
ValueError: Delegate failed to load.
RuntimeError: If delegate loading is used on unsupported platform.
"""
lite.experimental.load_delegate
# TODO(b/137299813): Fix darwin support for delegates.
if sys.platform == 'darwin':
raise RuntimeError('Dynamic loading of delegates on Darwin not supported.')
try:
delegate = Delegate(library, options)
except ValueError as e:
raise ValueError('Failed to load delegate from {}n{}'.format(
library, str(e)))
return delegate
Delegate クラス
class Delegate(object):
"""Python wrapper class to manage TfLiteDelegate objects.
The shared library is expected to have two functions:
TfLiteDelegate* tflite_plugin_create_delegate(
char**, char**, size_t, void (*report_error)(const char *))
void tflite_plugin_destroy_delegate(TfLiteDelegate*)
The first one creates a delegate object. It may return NULL to indicate an
error (with a suitable error message reported by calling report_error()).
The second one destroys delegate object and must be called for every
created delegate object. Passing NULL as argument value is allowed, i.e.
tflite_plugin_destroy_delegate(tflite_plugin_create_delegate(...))
always works.
"""
lite.Interpreter
@_tf_export('lite.Interpreter')
class Interpreter(object):
def __init__(self,
model_path=None,
model_content=None,
experimental_delegates=None):
"""Constructor.
Args:
model_path: Path to TF-Lite Flatbuffer file.
model_content: Content of model.
experimental_delegates: Experimental. Subject to change. List of
[TfLiteDelegate](https://www.tensorflow.org/lite/performance/delegates)
objects returned by lite.load_delegate().
Raises:
ValueError: If the interpreter was unable to create.
"""
lite.Interpreter
# Each delegate is a wrapper that owns the delegates that have been loaded
# as plugins. The interpreter wrapper will be using them, but we need to
# hold them in a list so that the lifetime is preserved at least as long as
# the interpreter wrapper.
self._delegates = []
if experimental_delegates:
self._delegates = experimental_delegates
for delegate in self._delegates:
self._interpreter.ModifyGraphWithDelegate(
delegate._get_native_delegate_pointer()) # pylint: disable=protected-access
Edge TPU CompilerがUpdate
https://vengineer.hatenablog.com/entry/71953852
tflite_plugin_create_delegate
extern "C" {
TfLiteDelegate* tflite_plugin_create_delegate(char** options_keys,
char** options_values,
size_t num_options,
ErrorHandler error_handler) {
return new PosenetDelegateForCustomOp();
}
void tflite_plugin_destroy_delegate(TfLiteDelegate* delegate) {
delete static_cast<PosenetDelegateForCustomOp*>(delegate);
}
Flex Delagete:libflexdelegate.so
#include "tensorflow/lite/delegates/flex/delegate.h"
namespace {
typedef void (*ErrorHandler)(const char*);
} // namespace
extern "C" {
TfLiteDelegate* tflite_plugin_create_delegate(char** options_key, char** options_values,
size_t num_options, ErrorHandler error_handler) {
std::unique_ptr<tflite::FlexDelegate> delegate = tflite::FlexDelegate::Create();
return delegate.get();
}
void tflite_plugin_destroy_delegate(TfLiteDelegate* delegate) {
delete static_cast<tflite::FlexDelegate*>(delegate);
}
}
デフォルトでは、ビルドされない
TensorFlow Lite Python Runtime
https://www.tensorflow.org/lite/guide/python
TensorFlow Lite (v1.14) の Python Runtime (Python 3.5/3.6/3.7)のパッケージが用意されている
 Raspberry Piシリーズにも簡単にインストールできる
 $ pip3 install tflite_runtime-1.14.0-cp37-cp37m-linux_armv7l.whl
 import tensorflow as tf
 interpreter = tf.lite.Interpreter(model_path=args.model_file)
 を
 import tflite_runtime.interpreter as tflite
 interpreter = tflite.Interpreter(model_path=args.model_file)
 に
あたしは、
ディープラーニング職人 ではありません
コンピュータエンジニア です




ありがとうございました
@Vengineer
ソースコード解析職人

Mais conteúdo relacionado

Mais procurados

いまさら聞けない!CUDA高速化入門
いまさら聞けない!CUDA高速化入門いまさら聞けない!CUDA高速化入門
いまさら聞けない!CUDA高速化入門Fixstars Corporation
 
最近のDeep Learning (NLP) 界隈におけるAttention事情
最近のDeep Learning (NLP) 界隈におけるAttention事情最近のDeep Learning (NLP) 界隈におけるAttention事情
最近のDeep Learning (NLP) 界隈におけるAttention事情Yuta Kikuchi
 
【DL輪読会】Llama 2: Open Foundation and Fine-Tuned Chat Models
【DL輪読会】Llama 2: Open Foundation and Fine-Tuned Chat Models【DL輪読会】Llama 2: Open Foundation and Fine-Tuned Chat Models
【DL輪読会】Llama 2: Open Foundation and Fine-Tuned Chat ModelsDeep Learning JP
 
SSII2020SS: 微分可能レンダリングの最新動向 〜「見比べる」ことによる3次元理解 〜​
SSII2020SS:  微分可能レンダリングの最新動向 〜「見比べる」ことによる3次元理解 〜​SSII2020SS:  微分可能レンダリングの最新動向 〜「見比べる」ことによる3次元理解 〜​
SSII2020SS: 微分可能レンダリングの最新動向 〜「見比べる」ことによる3次元理解 〜​SSII
 
画像処理ライブラリ OpenCV で 出来ること・出来ないこと
画像処理ライブラリ OpenCV で 出来ること・出来ないこと画像処理ライブラリ OpenCV で 出来ること・出来ないこと
画像処理ライブラリ OpenCV で 出来ること・出来ないことNorishige Fukushima
 
モデル高速化百選
モデル高速化百選モデル高速化百選
モデル高速化百選Yusuke Uchida
 
PFN のオンプレML基盤の取り組み / オンプレML基盤 on Kubernetes 〜PFN、ヤフー〜
PFN のオンプレML基盤の取り組み / オンプレML基盤 on Kubernetes 〜PFN、ヤフー〜PFN のオンプレML基盤の取り組み / オンプレML基盤 on Kubernetes 〜PFN、ヤフー〜
PFN のオンプレML基盤の取り組み / オンプレML基盤 on Kubernetes 〜PFN、ヤフー〜Preferred Networks
 
CUDAプログラミング入門
CUDAプログラミング入門CUDAプログラミング入門
CUDAプログラミング入門NVIDIA Japan
 
「NVIDIA プロファイラを用いたPyTorch学習最適化手法のご紹介(修正版)」
「NVIDIA プロファイラを用いたPyTorch学習最適化手法のご紹介(修正版)」「NVIDIA プロファイラを用いたPyTorch学習最適化手法のご紹介(修正版)」
「NVIDIA プロファイラを用いたPyTorch学習最適化手法のご紹介(修正版)」ManaMurakami1
 
近年のHierarchical Vision Transformer
近年のHierarchical Vision Transformer近年のHierarchical Vision Transformer
近年のHierarchical Vision TransformerYusuke Uchida
 
Transformer メタサーベイ
Transformer メタサーベイTransformer メタサーベイ
Transformer メタサーベイcvpaper. challenge
 
【メタサーベイ】Video Transformer
 【メタサーベイ】Video Transformer 【メタサーベイ】Video Transformer
【メタサーベイ】Video Transformercvpaper. challenge
 
PFNのML/DL基盤を支えるKubernetesにおける自動化 / DevOpsDays Tokyo 2021
PFNのML/DL基盤を支えるKubernetesにおける自動化 / DevOpsDays Tokyo 2021PFNのML/DL基盤を支えるKubernetesにおける自動化 / DevOpsDays Tokyo 2021
PFNのML/DL基盤を支えるKubernetesにおける自動化 / DevOpsDays Tokyo 2021Preferred Networks
 
深層学習フレームワークにおけるIntel CPU/富岳向け最適化法
深層学習フレームワークにおけるIntel CPU/富岳向け最適化法深層学習フレームワークにおけるIntel CPU/富岳向け最適化法
深層学習フレームワークにおけるIntel CPU/富岳向け最適化法MITSUNARI Shigeo
 
SSII2022 [SS2] 少ないデータやラベルを効率的に活用する機械学習技術 〜 足りない情報をどのように補うか?〜
SSII2022 [SS2] 少ないデータやラベルを効率的に活用する機械学習技術 〜 足りない情報をどのように補うか?〜SSII2022 [SS2] 少ないデータやラベルを効率的に活用する機械学習技術 〜 足りない情報をどのように補うか?〜
SSII2022 [SS2] 少ないデータやラベルを効率的に活用する機械学習技術 〜 足りない情報をどのように補うか?〜SSII
 
Deep Learningによる超解像の進歩
Deep Learningによる超解像の進歩Deep Learningによる超解像の進歩
Deep Learningによる超解像の進歩Hiroto Honda
 
モデルではなく、データセットを蒸留する
モデルではなく、データセットを蒸留するモデルではなく、データセットを蒸留する
モデルではなく、データセットを蒸留するTakahiro Kubo
 
【DL輪読会】DINOv2: Learning Robust Visual Features without Supervision
【DL輪読会】DINOv2: Learning Robust Visual Features without Supervision【DL輪読会】DINOv2: Learning Robust Visual Features without Supervision
【DL輪読会】DINOv2: Learning Robust Visual Features without SupervisionDeep Learning JP
 
【DL輪読会】Segment Anything
【DL輪読会】Segment Anything【DL輪読会】Segment Anything
【DL輪読会】Segment AnythingDeep Learning JP
 

Mais procurados (20)

いまさら聞けない!CUDA高速化入門
いまさら聞けない!CUDA高速化入門いまさら聞けない!CUDA高速化入門
いまさら聞けない!CUDA高速化入門
 
最近のDeep Learning (NLP) 界隈におけるAttention事情
最近のDeep Learning (NLP) 界隈におけるAttention事情最近のDeep Learning (NLP) 界隈におけるAttention事情
最近のDeep Learning (NLP) 界隈におけるAttention事情
 
【DL輪読会】Llama 2: Open Foundation and Fine-Tuned Chat Models
【DL輪読会】Llama 2: Open Foundation and Fine-Tuned Chat Models【DL輪読会】Llama 2: Open Foundation and Fine-Tuned Chat Models
【DL輪読会】Llama 2: Open Foundation and Fine-Tuned Chat Models
 
SSII2020SS: 微分可能レンダリングの最新動向 〜「見比べる」ことによる3次元理解 〜​
SSII2020SS:  微分可能レンダリングの最新動向 〜「見比べる」ことによる3次元理解 〜​SSII2020SS:  微分可能レンダリングの最新動向 〜「見比べる」ことによる3次元理解 〜​
SSII2020SS: 微分可能レンダリングの最新動向 〜「見比べる」ことによる3次元理解 〜​
 
画像処理ライブラリ OpenCV で 出来ること・出来ないこと
画像処理ライブラリ OpenCV で 出来ること・出来ないこと画像処理ライブラリ OpenCV で 出来ること・出来ないこと
画像処理ライブラリ OpenCV で 出来ること・出来ないこと
 
モデル高速化百選
モデル高速化百選モデル高速化百選
モデル高速化百選
 
PFN のオンプレML基盤の取り組み / オンプレML基盤 on Kubernetes 〜PFN、ヤフー〜
PFN のオンプレML基盤の取り組み / オンプレML基盤 on Kubernetes 〜PFN、ヤフー〜PFN のオンプレML基盤の取り組み / オンプレML基盤 on Kubernetes 〜PFN、ヤフー〜
PFN のオンプレML基盤の取り組み / オンプレML基盤 on Kubernetes 〜PFN、ヤフー〜
 
CUDAプログラミング入門
CUDAプログラミング入門CUDAプログラミング入門
CUDAプログラミング入門
 
「NVIDIA プロファイラを用いたPyTorch学習最適化手法のご紹介(修正版)」
「NVIDIA プロファイラを用いたPyTorch学習最適化手法のご紹介(修正版)」「NVIDIA プロファイラを用いたPyTorch学習最適化手法のご紹介(修正版)」
「NVIDIA プロファイラを用いたPyTorch学習最適化手法のご紹介(修正版)」
 
近年のHierarchical Vision Transformer
近年のHierarchical Vision Transformer近年のHierarchical Vision Transformer
近年のHierarchical Vision Transformer
 
Transformer メタサーベイ
Transformer メタサーベイTransformer メタサーベイ
Transformer メタサーベイ
 
【メタサーベイ】Video Transformer
 【メタサーベイ】Video Transformer 【メタサーベイ】Video Transformer
【メタサーベイ】Video Transformer
 
PFNのML/DL基盤を支えるKubernetesにおける自動化 / DevOpsDays Tokyo 2021
PFNのML/DL基盤を支えるKubernetesにおける自動化 / DevOpsDays Tokyo 2021PFNのML/DL基盤を支えるKubernetesにおける自動化 / DevOpsDays Tokyo 2021
PFNのML/DL基盤を支えるKubernetesにおける自動化 / DevOpsDays Tokyo 2021
 
深層学習フレームワークにおけるIntel CPU/富岳向け最適化法
深層学習フレームワークにおけるIntel CPU/富岳向け最適化法深層学習フレームワークにおけるIntel CPU/富岳向け最適化法
深層学習フレームワークにおけるIntel CPU/富岳向け最適化法
 
SSII2022 [SS2] 少ないデータやラベルを効率的に活用する機械学習技術 〜 足りない情報をどのように補うか?〜
SSII2022 [SS2] 少ないデータやラベルを効率的に活用する機械学習技術 〜 足りない情報をどのように補うか?〜SSII2022 [SS2] 少ないデータやラベルを効率的に活用する機械学習技術 〜 足りない情報をどのように補うか?〜
SSII2022 [SS2] 少ないデータやラベルを効率的に活用する機械学習技術 〜 足りない情報をどのように補うか?〜
 
Deep Learningによる超解像の進歩
Deep Learningによる超解像の進歩Deep Learningによる超解像の進歩
Deep Learningによる超解像の進歩
 
モデルではなく、データセットを蒸留する
モデルではなく、データセットを蒸留するモデルではなく、データセットを蒸留する
モデルではなく、データセットを蒸留する
 
【DL輪読会】DINOv2: Learning Robust Visual Features without Supervision
【DL輪読会】DINOv2: Learning Robust Visual Features without Supervision【DL輪読会】DINOv2: Learning Robust Visual Features without Supervision
【DL輪読会】DINOv2: Learning Robust Visual Features without Supervision
 
【DL輪読会】Segment Anything
【DL輪読会】Segment Anything【DL輪読会】Segment Anything
【DL輪読会】Segment Anything
 
[DL輪読会]World Models
[DL輪読会]World Models[DL輪読会]World Models
[DL輪読会]World Models
 

Semelhante a TensorFlow Lite Delegateとは?

Tizen 2.0 alpha でサポートされなかった native api
Tizen 2.0 alpha でサポートされなかった native apiTizen 2.0 alpha でサポートされなかった native api
Tizen 2.0 alpha でサポートされなかった native apiNaruto TAKAHASHI
 
13016 n分で作るtype scriptでnodejs
13016 n分で作るtype scriptでnodejs13016 n分で作るtype scriptでnodejs
13016 n分で作るtype scriptでnodejsTakayoshi Tanaka
 
20130329 rtm3
20130329 rtm320130329 rtm3
20130329 rtm3openrtm
 
Ruby向け帳票ソリューション「ThinReports」の開発で知るOSSの威力
Ruby向け帳票ソリューション「ThinReports」の開発で知るOSSの威力Ruby向け帳票ソリューション「ThinReports」の開発で知るOSSの威力
Ruby向け帳票ソリューション「ThinReports」の開発で知るOSSの威力ThinReports
 
[AI08] 深層学習フレームワーク Chainer × Microsoft で広がる応用
[AI08] 深層学習フレームワーク Chainer × Microsoft で広がる応用[AI08] 深層学習フレームワーク Chainer × Microsoft で広がる応用
[AI08] 深層学習フレームワーク Chainer × Microsoft で広がる応用de:code 2017
 
Flutterを体験してみませんか
Flutterを体験してみませんかFlutterを体験してみませんか
Flutterを体験してみませんかcch-robo
 
20170527 inside .NET Core on Linux
20170527 inside .NET Core on Linux20170527 inside .NET Core on Linux
20170527 inside .NET Core on LinuxTakayoshi Tanaka
 
CEDEC 2013 Unity on Windows 8
CEDEC 2013 Unity on Windows 8CEDEC 2013 Unity on Windows 8
CEDEC 2013 Unity on Windows 8Akira Onishi
 
イベント駆動プログラミングとI/O多重化
イベント駆動プログラミングとI/O多重化イベント駆動プログラミングとI/O多重化
イベント駆動プログラミングとI/O多重化Gosuke Miyashita
 
Python東海GAEやってみた
Python東海GAEやってみたPython東海GAEやってみた
Python東海GAEやってみたMori Shingo
 
Web技術勉強会23回目
Web技術勉強会23回目Web技術勉強会23回目
Web技術勉強会23回目龍一 田中
 
Twitter sphere of #twitter4j #twtr_hack
Twitter sphere of #twitter4j #twtr_hackTwitter sphere of #twitter4j #twtr_hack
Twitter sphere of #twitter4j #twtr_hackkimukou_26 Kimukou
 
TensorFlow 3分紹介 with 速攻 windows 環境構築
TensorFlow 3分紹介 with 速攻 windows 環境構築TensorFlow 3分紹介 with 速攻 windows 環境構築
TensorFlow 3分紹介 with 速攻 windows 環境構築Michiko Arai
 
Serfが面白いと俺の中で話題にwwwwww
Serfが面白いと俺の中で話題にwwwwwwSerfが面白いと俺の中で話題にwwwwww
Serfが面白いと俺の中で話題にwwwwwwMasahito Zembutsu
 
DartPad+CodePenで、Flutterを体験してみよう
DartPad+CodePenで、Flutterを体験してみようDartPad+CodePenで、Flutterを体験してみよう
DartPad+CodePenで、Flutterを体験してみようcch-robo
 
Apache Airflow 概要(Airflowの基礎を学ぶハンズオンワークショップ 発表資料)
Apache Airflow 概要(Airflowの基礎を学ぶハンズオンワークショップ 発表資料)Apache Airflow 概要(Airflowの基礎を学ぶハンズオンワークショップ 発表資料)
Apache Airflow 概要(Airflowの基礎を学ぶハンズオンワークショップ 発表資料)NTT DATA Technology & Innovation
 
CodeIgniter東京勉強会 2011.05.14
CodeIgniter東京勉強会 2011.05.14CodeIgniter東京勉強会 2011.05.14
CodeIgniter東京勉強会 2011.05.14Takako Miyagawa
 

Semelhante a TensorFlow Lite Delegateとは? (20)

Tizen 2.0 alpha でサポートされなかった native api
Tizen 2.0 alpha でサポートされなかった native apiTizen 2.0 alpha でサポートされなかった native api
Tizen 2.0 alpha でサポートされなかった native api
 
13016 n分で作るtype scriptでnodejs
13016 n分で作るtype scriptでnodejs13016 n分で作るtype scriptでnodejs
13016 n分で作るtype scriptでnodejs
 
20130329 rtm3
20130329 rtm320130329 rtm3
20130329 rtm3
 
Ruby向け帳票ソリューション「ThinReports」の開発で知るOSSの威力
Ruby向け帳票ソリューション「ThinReports」の開発で知るOSSの威力Ruby向け帳票ソリューション「ThinReports」の開発で知るOSSの威力
Ruby向け帳票ソリューション「ThinReports」の開発で知るOSSの威力
 
[AI08] 深層学習フレームワーク Chainer × Microsoft で広がる応用
[AI08] 深層学習フレームワーク Chainer × Microsoft で広がる応用[AI08] 深層学習フレームワーク Chainer × Microsoft で広がる応用
[AI08] 深層学習フレームワーク Chainer × Microsoft で広がる応用
 
Flutterを体験してみませんか
Flutterを体験してみませんかFlutterを体験してみませんか
Flutterを体験してみませんか
 
20170527 inside .NET Core on Linux
20170527 inside .NET Core on Linux20170527 inside .NET Core on Linux
20170527 inside .NET Core on Linux
 
CEDEC 2013 Unity on Windows 8
CEDEC 2013 Unity on Windows 8CEDEC 2013 Unity on Windows 8
CEDEC 2013 Unity on Windows 8
 
イベント駆動プログラミングとI/O多重化
イベント駆動プログラミングとI/O多重化イベント駆動プログラミングとI/O多重化
イベント駆動プログラミングとI/O多重化
 
sveltekit-ja.pdf
sveltekit-ja.pdfsveltekit-ja.pdf
sveltekit-ja.pdf
 
Ext.direct
Ext.directExt.direct
Ext.direct
 
Python東海GAEやってみた
Python東海GAEやってみたPython東海GAEやってみた
Python東海GAEやってみた
 
Web技術勉強会23回目
Web技術勉強会23回目Web技術勉強会23回目
Web技術勉強会23回目
 
Twitter sphere of #twitter4j #twtr_hack
Twitter sphere of #twitter4j #twtr_hackTwitter sphere of #twitter4j #twtr_hack
Twitter sphere of #twitter4j #twtr_hack
 
TensorFlow 3分紹介 with 速攻 windows 環境構築
TensorFlow 3分紹介 with 速攻 windows 環境構築TensorFlow 3分紹介 with 速攻 windows 環境構築
TensorFlow 3分紹介 with 速攻 windows 環境構築
 
Serfが面白いと俺の中で話題にwwwwww
Serfが面白いと俺の中で話題にwwwwwwSerfが面白いと俺の中で話題にwwwwww
Serfが面白いと俺の中で話題にwwwwww
 
DartPad+CodePenで、Flutterを体験してみよう
DartPad+CodePenで、Flutterを体験してみようDartPad+CodePenで、Flutterを体験してみよう
DartPad+CodePenで、Flutterを体験してみよう
 
Apache Airflow 概要(Airflowの基礎を学ぶハンズオンワークショップ 発表資料)
Apache Airflow 概要(Airflowの基礎を学ぶハンズオンワークショップ 発表資料)Apache Airflow 概要(Airflowの基礎を学ぶハンズオンワークショップ 発表資料)
Apache Airflow 概要(Airflowの基礎を学ぶハンズオンワークショップ 発表資料)
 
CodeIgniter東京勉強会 2011.05.14
CodeIgniter東京勉強会 2011.05.14CodeIgniter東京勉強会 2011.05.14
CodeIgniter東京勉強会 2011.05.14
 
perfを使ったPostgreSQLの解析(後編)
perfを使ったPostgreSQLの解析(後編)perfを使ったPostgreSQLの解析(後編)
perfを使ったPostgreSQLの解析(後編)
 

Mais de Mr. Vengineer

XilinxのxsimでSoftware Driven Verification.pdf
XilinxのxsimでSoftware  Driven Verification.pdfXilinxのxsimでSoftware  Driven Verification.pdf
XilinxのxsimでSoftware Driven Verification.pdfMr. Vengineer
 
VerilatorとSystemCでSoftware Driven Verification
VerilatorとSystemCでSoftware Driven VerificationVerilatorとSystemCでSoftware Driven Verification
VerilatorとSystemCでSoftware Driven VerificationMr. Vengineer
 
Cloud TPU Driver API ソースコード解析
Cloud TPU Driver API ソースコード解析Cloud TPU Driver API ソースコード解析
Cloud TPU Driver API ソースコード解析Mr. Vengineer
 
Cloud Deep Learning Chips Training & Inference
Cloud Deep Learning Chips Training & InferenceCloud Deep Learning Chips Training & Inference
Cloud Deep Learning Chips Training & InferenceMr. Vengineer
 
Pixel Visual Core device driver source code analysis
Pixel Visual Core device driver source code analysisPixel Visual Core device driver source code analysis
Pixel Visual Core device driver source code analysisMr. Vengineer
 
Google Edge TPUで TensorFlow Liteを使った時に 何をやっているのかを妄想してみる 2 「エッジAIモダン計測制御の世界」オ...
Google Edge TPUで TensorFlow Liteを使った時に 何をやっているのかを妄想してみる 2  「エッジAIモダン計測制御の世界」オ...Google Edge TPUで TensorFlow Liteを使った時に 何をやっているのかを妄想してみる 2  「エッジAIモダン計測制御の世界」オ...
Google Edge TPUで TensorFlow Liteを使った時に 何をやっているのかを妄想してみる 2 「エッジAIモダン計測制御の世界」オ...Mr. Vengineer
 
TensorFlow XLA 「XLAとは、から、最近の利用事例について」
TensorFlow XLA 「XLAとは、から、最近の利用事例について」TensorFlow XLA 「XLAとは、から、最近の利用事例について」
TensorFlow XLA 「XLAとは、から、最近の利用事例について」Mr. Vengineer
 
Facebook Glow Compiler のソースコードをグダグダ語る会
Facebook Glow Compiler のソースコードをグダグダ語る会Facebook Glow Compiler のソースコードをグダグダ語る会
Facebook Glow Compiler のソースコードをグダグダ語る会Mr. Vengineer
 
Ultra96(UltraZed)実践勉強会
Ultra96(UltraZed)実践勉強会Ultra96(UltraZed)実践勉強会
Ultra96(UltraZed)実践勉強会Mr. Vengineer
 
Bridge TensorFlow to run on Intel nGraph backends (v0.4)
Bridge TensorFlow to run on Intel nGraph backends (v0.4)Bridge TensorFlow to run on Intel nGraph backends (v0.4)
Bridge TensorFlow to run on Intel nGraph backends (v0.4)Mr. Vengineer
 
Bridge TensorFlow to run on Intel nGraph backends (v0.5)
Bridge TensorFlow to run on Intel nGraph backends (v0.5)Bridge TensorFlow to run on Intel nGraph backends (v0.5)
Bridge TensorFlow to run on Intel nGraph backends (v0.5)Mr. Vengineer
 
TensorFlow local Python XLA client
TensorFlow local Python XLA clientTensorFlow local Python XLA client
TensorFlow local Python XLA clientMr. Vengineer
 
Tiramisu をちょっと、味見してみました。
Tiramisu をちょっと、味見してみました。Tiramisu をちょっと、味見してみました。
Tiramisu をちょっと、味見してみました。Mr. Vengineer
 
LeFlowを調べてみました
LeFlowを調べてみましたLeFlowを調べてみました
LeFlowを調べてみましたMr. Vengineer
 
Tensorflow dynamically loadable XLA plugin ソースコード解析
Tensorflow  dynamically loadable XLA plugin ソースコード解析Tensorflow  dynamically loadable XLA plugin ソースコード解析
Tensorflow dynamically loadable XLA plugin ソースコード解析Mr. Vengineer
 
Tensor comprehensions
Tensor comprehensionsTensor comprehensions
Tensor comprehensionsMr. Vengineer
 

Mais de Mr. Vengineer (20)

XilinxのxsimでSoftware Driven Verification.pdf
XilinxのxsimでSoftware  Driven Verification.pdfXilinxのxsimでSoftware  Driven Verification.pdf
XilinxのxsimでSoftware Driven Verification.pdf
 
VerilatorとSystemCでSoftware Driven Verification
VerilatorとSystemCでSoftware Driven VerificationVerilatorとSystemCでSoftware Driven Verification
VerilatorとSystemCでSoftware Driven Verification
 
VerilatorとSystemC
VerilatorとSystemCVerilatorとSystemC
VerilatorとSystemC
 
TVM VTA (TSIM)
TVM VTA (TSIM) TVM VTA (TSIM)
TVM VTA (TSIM)
 
Cloud TPU Driver API ソースコード解析
Cloud TPU Driver API ソースコード解析Cloud TPU Driver API ソースコード解析
Cloud TPU Driver API ソースコード解析
 
Cloud Deep Learning Chips Training & Inference
Cloud Deep Learning Chips Training & InferenceCloud Deep Learning Chips Training & Inference
Cloud Deep Learning Chips Training & Inference
 
Pixel Visual Core device driver source code analysis
Pixel Visual Core device driver source code analysisPixel Visual Core device driver source code analysis
Pixel Visual Core device driver source code analysis
 
Google Edge TPUで TensorFlow Liteを使った時に 何をやっているのかを妄想してみる 2 「エッジAIモダン計測制御の世界」オ...
Google Edge TPUで TensorFlow Liteを使った時に 何をやっているのかを妄想してみる 2  「エッジAIモダン計測制御の世界」オ...Google Edge TPUで TensorFlow Liteを使った時に 何をやっているのかを妄想してみる 2  「エッジAIモダン計測制御の世界」オ...
Google Edge TPUで TensorFlow Liteを使った時に 何をやっているのかを妄想してみる 2 「エッジAIモダン計測制御の世界」オ...
 
TensorFlow XLA 「XLAとは、から、最近の利用事例について」
TensorFlow XLA 「XLAとは、から、最近の利用事例について」TensorFlow XLA 「XLAとは、から、最近の利用事例について」
TensorFlow XLA 「XLAとは、から、最近の利用事例について」
 
Facebook Glow Compiler のソースコードをグダグダ語る会
Facebook Glow Compiler のソースコードをグダグダ語る会Facebook Glow Compiler のソースコードをグダグダ語る会
Facebook Glow Compiler のソースコードをグダグダ語る会
 
Ultra96(UltraZed)実践勉強会
Ultra96(UltraZed)実践勉強会Ultra96(UltraZed)実践勉強会
Ultra96(UltraZed)実践勉強会
 
Bridge TensorFlow to run on Intel nGraph backends (v0.4)
Bridge TensorFlow to run on Intel nGraph backends (v0.4)Bridge TensorFlow to run on Intel nGraph backends (v0.4)
Bridge TensorFlow to run on Intel nGraph backends (v0.4)
 
Bridge TensorFlow to run on Intel nGraph backends (v0.5)
Bridge TensorFlow to run on Intel nGraph backends (v0.5)Bridge TensorFlow to run on Intel nGraph backends (v0.5)
Bridge TensorFlow to run on Intel nGraph backends (v0.5)
 
TensorFlow XLA RPC
TensorFlow XLA RPCTensorFlow XLA RPC
TensorFlow XLA RPC
 
TensorFlow local Python XLA client
TensorFlow local Python XLA clientTensorFlow local Python XLA client
TensorFlow local Python XLA client
 
Tiramisu をちょっと、味見してみました。
Tiramisu をちょっと、味見してみました。Tiramisu をちょっと、味見してみました。
Tiramisu をちょっと、味見してみました。
 
LeFlowを調べてみました
LeFlowを調べてみましたLeFlowを調べてみました
LeFlowを調べてみました
 
Tensorflow dynamically loadable XLA plugin ソースコード解析
Tensorflow  dynamically loadable XLA plugin ソースコード解析Tensorflow  dynamically loadable XLA plugin ソースコード解析
Tensorflow dynamically loadable XLA plugin ソースコード解析
 
Tiramisu概要
Tiramisu概要Tiramisu概要
Tiramisu概要
 
Tensor comprehensions
Tensor comprehensionsTensor comprehensions
Tensor comprehensions
 

TensorFlow Lite Delegateとは?

  • 3. TensorFlow Lite とは? TensorFlow Lite は、TensorFlowのモデルを デバイス上(mobile / embedded / IoT)での推論を可能にする、 オープンソースのディープ ラーニング フレームワーク デバイス上で推論すると、こんなにいいことが! ● レイテンシー :サーバーにデータを送らないので! ● プライバシー :データをデバイスに残す必要がない! ● コネクティビティ :インターネットに接続しなくていい! ● 電力消費 :ネットワーク接続は電気食い TensorFlow Lite for Microcontrollers のお話は、今回しません
  • 4. TensorFlow Lite を利用するステップ ● モデルの選択:学習する・学習済み ○ 学習はクラウド : Google Colaboratory (GPU, TPUも使える) ○ 学習済みモデルもたんまり ● 変換:TensorFlow => TensorFlow Lite ○ TensorFlow Lite Converter ● 最適化 ○ 量子化 (8bit int, 16bit float), delegate ● デプロイ:専用の推論エンジン ○ TensorFlow Lite Interpreter TensorFlow Lite guide を読めばいい!(一部は日本語に訳されているよ)
  • 5. TensorFlow Lite Delegates   Delegate API は、まだ experimental なので、今後変更有 Delegate は、TensorFlow Liteのグラフの一部/全体をCPU以外の Executor に委譲 (delegate) するもの ● GPU :OpenGL ES v3.1 / OpenCL / Metal (iOS) ● AIアクセラレータ :Google Edge TPU / Google Pixel Neural Core ● Android NN APIs :v1.0 (8.1) / v1.1 (9.0) / v1.2 (10.0) ● Flex :TensorFlow Select ● その他 :Arm NN (PR#33436)
  • 6. TensorFlow Lite 2019 Roadmap https://www.tensorflow.org/lite/guide/roadmap ● Updated NN API support   Full support for new Android Q NN API features, ops and types ● GPU backend optimizations   OpenCL and Vulkan support on Android   Metal and Objective-C CocoaPods for Metal acceleration ● Hexagon DSP backend   Initial release of DSP acceleration for pre-Android P devices
  • 7. TensorFlow LiteDelegate documentation https://www.tensorflow.org/lite/performance/delegates Run inference with TensorFlow Lite in Python https://coral.withgoogle.com/docs/edgetpu/tflite-python/ Python quickstart (tflite_runtime というのがある) https://www.tensorflow.org/lite/guide/python Edge TPU inferencing overview https://coral.withgoogle.com/docs/edgetpu/inference/ Run inference with TensorFlow Lite in C++ (Edge TPU) https://coral.withgoogle.com/docs/edgetpu/tflite-cpp/
  • 9. CPU : Delegateなし、基本パターン // TensorFlow Liteモデルをファイルから読み込み  auto model = FlatBufferModel::BuildFromFile("interesting_model.tflite"); // 推論エンジンにモデルをロードする ops::builtin::BuiltinOpResolver op_resolver; std::unique_ptr<Interpreter> interpreter; InterpreterBuilder(*model, op_resolver)(&interpreter);  // メモリの割り当てをする interpreter->AllocateTensors(); // .... (Prepare input tensors) 入力データの準備  // 推論の実行 interpreter->Invoke(); // .... (Retrieve the result from output tensors) 出力データを取り込む
  • 10. GPU Delegate : v1 (OpenGLES)  // モデルの読み込み、推論エンジンへのモデルのロードまでは同じ const TfLiteGpuDelegateOptions options = { .metadata = NULL, .compile_options = { .precision_loss_allowed = 1, // FP16 .preferred_gl_object_type = TFLITE_GL_OBJECT_TYPE_FASTEST, .dynamic_batch_enabled = 0, // Not fully functional yet }, }; auto* delegate = TfLiteGpuDelegateCreate(&options); interpreter->ModifyGraphWithDelegate(delegate); Delegateの設定  // 推論エンジンの実行も同じ
  • 11. GPU Delegate : v2 (OpenCL => OpenGLES)  // モデルの読み込み、推論エンジンへのモデルのロードまでは同じ  // v1 と違って、option はデフォルトでは必要なくなった  // v2 では、最初に OpenCL をチェックして、なければ、 OpenGL ES v3.1 を実行 auto* delegate = TfLiteGpuDelegateV2Create(/*default options=*/nullptr); interpreter->ModifyGraphWithDelegate(delegate);  // 推論エンジンの実行も同じ
  • 12. Google Edge TPU Delegate  // モデルの読み込み、推論エンジンへのモデルのロードまでは同じ size_t num_devices; std::unique_ptr<edgetpu_device, decltype(&edgetpu_free_devices)> devices( edgetpu_list_devices(&num_devices), &edgetpu_free_devices); const auto& device = devices.get()[0];  // 専用APIにて、Edge TPUのDelegateを獲得 auto* delegate = edgetpu_create_delegate(device.type, device.path, nullptr, 0); interpreter->ModifyGraphWithDelegate({delegate, edgetpu_free_delegate}); //edgetpu_free_delegate があるのは次ページ  // 推論エンジンの実行も同じ
  • 13. もうひとつのModifyGraphWithDelegate // Owning handle to a TfLiteDelegate instance. using TfLiteDelegatePtr = std::unique_ptr<TfLiteDelegate, void (*)(TfLiteDelegate*)>; /// Same as ModifyGraphWithDelegate except this interpreter takes /// ownership of the provided delegate. Be sure to construct the unique_ptr /// with a suitable destruction function. /// WARNING: This is an experimental API and subject to change. TfLiteStatus ModifyGraphWithDelegate(TfLiteDelegatePtr delegate);
  • 14. Android NN APIs Delegate  // モデルの読み込み、推論エンジンへのモデルのロードまでは同じ auto* delegate = NnApiDelegate(); interpreter->ModifyGraphWithDelegate(delegate);  // 推論エンジンの実行も同じ  // DEPRECATED: Please use StatefulNnApiDelegate class instead. TfLiteDelegate* NnApiDelegate() { static StatefulNnApiDelegate* delegate = new StatefulNnApiDelegate(); return delegate; }
  • 15. Flex Delegate:TensorFlow Select時  // モデルの読み込み、推論エンジンへのモデルのロードまでは同じ auto* delegate = FlexDelegate::Create(); interpreter->ModifyGraphWithDelegate(delegate);  // 推論エンジンの実行も同じ
  • 16. TensorFlow Select TensorFlow Liteに、TensorFlowのOpを使えるようにするためのものです。 「Select TensorFlow operators to use in TensorFlow Lite」 このビデオ「Inside TensorFlow: TensorFlow Lite」のModel Conversionの説明部分。 converter をビルドするときに、 --define=tflite_convert_with_select_tf_ops=true を指定する bazel run --define=tflite_convert_with_select_tf_ops=true tflite_convert -- --output_file=/tmp/foo.tflite --graph_def_file=/tmp/foo.pb --input_arrays=input --output_arrays=MobilenetV1/Predictions/Reshape_1 --target_ops=TFLITE_BUILTINS,SELECT_TF_OPS
  • 17. ArmNN Delegate Add initial minimal ArmNN delegate plugin. #33436 https://github.com/GeorgeARM/tensorflow/tree/armnn_delegate/tensorflow/lite/delegates/armnn The following kernels are currently off-loaded: - Pool2d - AvgPool - MaxPool - L2Pool - Conv2d - Depthwise Conv2d - Softmax - Squeeze
  • 18. ArmNN Delegate  // モデルの読み込み、推論エンジンへのモデルのロードまでは同じ  Interpreter::TfLiteDelegatePtr CreateArmNNDelegate(ArmNNDelegate::Options options) {   return Interpreter::TfLiteDelegatePtr( new ArmNNDelegate(options), [](TfLiteDelegate* delegate) { delete reinterpret_cast<ArmNNDelegate*>(delegate); });  }  ArmNNDelegate::Options opts;  opts.backend_name = "CpuRef";  auto delegate = CreateArmNNDelegate(opts));  interpreter->ModifyGraphWithDelegate(delegate);  // 推論エンジンの実行も同じ
  • 19. Qualcomm Hexagon Delegate Tflite Qualcomm DSP acceleration #29028 ? NPE hardware acceleration support in Qualcomm chips #17526 ?
  • 20. InterpreterInvoke  モデル、Delegate、入力データ、出力データがあれば、この関数でOK!  Status InterpreterInvoke(const ::tflite::Model* model,   TfLiteDelegate* delegate,   const std::vector<TensorFloat32>& inputs,   std::vector<TensorFloat32>* outputs);
  • 21. InterpreterInvoke auto model = FlatBufferModel::BuildFromFile("interesting_model.tflite); auto* delegate = Delegateを生成する std::vector<TensorFloat32>& inputs; std::vector<TensorFloat32>* outputs; InterpreterInvoke(model, delegate, inputs, outputs);  // 推論エンジンの実行は同じ
  • 23. Edge TPU の例 interpreter = Interpreter(model_path=args.model_file) を interpreter = Interpreter(model_path=args.model_file,    experimental_delegates=[load_delegate('libedgetpu.so.1.0')]) に変更するだけ。 from tensorflow.lite.python.interpreter import load_delegate で、load_delegate を取り込めばいい。
  • 24. lite.experimental.load_delegate @_tf_export('lite.experimental.load_delegate') def load_delegate(library, options=None): """Returns loaded Delegate object. Args: library: Name of shared library containing the [TfLiteDelegate](https://www.tensorflow.org/lite/performance/delegates). options: Dictionary of options that are required to load the delegate. All keys and values in the dictionary should be convertible to str. Consult the documentation of the specific delegate for required and legal options. (default None) Returns: Delegate object. Raises: ValueError: Delegate failed to load. RuntimeError: If delegate loading is used on unsupported platform. """
  • 25. lite.experimental.load_delegate # TODO(b/137299813): Fix darwin support for delegates. if sys.platform == 'darwin': raise RuntimeError('Dynamic loading of delegates on Darwin not supported.') try: delegate = Delegate(library, options) except ValueError as e: raise ValueError('Failed to load delegate from {}n{}'.format( library, str(e))) return delegate
  • 26. Delegate クラス class Delegate(object): """Python wrapper class to manage TfLiteDelegate objects. The shared library is expected to have two functions: TfLiteDelegate* tflite_plugin_create_delegate( char**, char**, size_t, void (*report_error)(const char *)) void tflite_plugin_destroy_delegate(TfLiteDelegate*) The first one creates a delegate object. It may return NULL to indicate an error (with a suitable error message reported by calling report_error()). The second one destroys delegate object and must be called for every created delegate object. Passing NULL as argument value is allowed, i.e. tflite_plugin_destroy_delegate(tflite_plugin_create_delegate(...)) always works. """
  • 27. lite.Interpreter @_tf_export('lite.Interpreter') class Interpreter(object): def __init__(self, model_path=None, model_content=None, experimental_delegates=None): """Constructor. Args: model_path: Path to TF-Lite Flatbuffer file. model_content: Content of model. experimental_delegates: Experimental. Subject to change. List of [TfLiteDelegate](https://www.tensorflow.org/lite/performance/delegates) objects returned by lite.load_delegate(). Raises: ValueError: If the interpreter was unable to create. """
  • 28. lite.Interpreter # Each delegate is a wrapper that owns the delegates that have been loaded # as plugins. The interpreter wrapper will be using them, but we need to # hold them in a list so that the lifetime is preserved at least as long as # the interpreter wrapper. self._delegates = [] if experimental_delegates: self._delegates = experimental_delegates for delegate in self._delegates: self._interpreter.ModifyGraphWithDelegate( delegate._get_native_delegate_pointer()) # pylint: disable=protected-access Edge TPU CompilerがUpdate https://vengineer.hatenablog.com/entry/71953852
  • 29. tflite_plugin_create_delegate extern "C" { TfLiteDelegate* tflite_plugin_create_delegate(char** options_keys, char** options_values, size_t num_options, ErrorHandler error_handler) { return new PosenetDelegateForCustomOp(); } void tflite_plugin_destroy_delegate(TfLiteDelegate* delegate) { delete static_cast<PosenetDelegateForCustomOp*>(delegate); }
  • 30. Flex Delagete:libflexdelegate.so #include "tensorflow/lite/delegates/flex/delegate.h" namespace { typedef void (*ErrorHandler)(const char*); } // namespace extern "C" { TfLiteDelegate* tflite_plugin_create_delegate(char** options_key, char** options_values, size_t num_options, ErrorHandler error_handler) { std::unique_ptr<tflite::FlexDelegate> delegate = tflite::FlexDelegate::Create(); return delegate.get(); } void tflite_plugin_destroy_delegate(TfLiteDelegate* delegate) { delete static_cast<tflite::FlexDelegate*>(delegate); } } デフォルトでは、ビルドされない
  • 31. TensorFlow Lite Python Runtime https://www.tensorflow.org/lite/guide/python TensorFlow Lite (v1.14) の Python Runtime (Python 3.5/3.6/3.7)のパッケージが用意されている  Raspberry Piシリーズにも簡単にインストールできる  $ pip3 install tflite_runtime-1.14.0-cp37-cp37m-linux_armv7l.whl  import tensorflow as tf  interpreter = tf.lite.Interpreter(model_path=args.model_file)  を  import tflite_runtime.interpreter as tflite  interpreter = tflite.Interpreter(model_path=args.model_file)  に