Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Sign up for free
Menu
Search
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Pricing
Search
Sign in
Sign up for free
TFLite and PyTorch Mobile
Search
Sponsored
·
Ship Features Fearlessly
Turn features on and off without deploys. Used by thousands of Ruby developers.
→
shibuiwilliam
March 15, 2022
Technology
690
0
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
TFLite and PyTorch Mobile
Running TFLite and PyTorch Mobile
shibuiwilliam
March 15, 2022
More Decks by shibuiwilliam
See All by shibuiwilliam
The Conductor Pattern -Multi-Granularity Feedback for Creative Agents-
shibuiwilliam
2
77
LLM・AIエージェントシステムベストプラクティス
shibuiwilliam
7
2.5k
LLMやAIエージェントをソフトウェアに組み込むプラクティス
shibuiwilliam
2
660
From Prompt Engineering to Loop Engineering
shibuiwilliam
2
460
OntologyとLLMOps
shibuiwilliam
4
150
Rule repository
shibuiwilliam
3
86
LLM時代の検索アーキテクチャと技術的意思決定
shibuiwilliam
5
2.7k
Why Open Dataspacesのまとめ
shibuiwilliam
2
290
マルチモーダル非構造データとの闘い
shibuiwilliam
2
800
Other Decks in Technology
See All in Technology
あるけみー式LTスライド作成術
alchemy1115
2
220
「ピッケル本」日本語版は4.0(第6版)が出版されるべき / pickaxe4-nagoyark05
kakutani
1
140
range over func 2年間の軌跡 Issue #56413 はGoのエコシステムをどう変えたか
ryujicre8ive
0
190
20260912_スクフェス三河
kgnkhkr
0
380
登壇の自信を奪う3匹のオバケ / 3 Ghosts That Rob You of Your Confidence in Public Speaking
pauli
9
950
Railsのように考える: See through the Master
snoozer05
PRO
3
900
フルカイテン株式会社 エンジニア向け採用資料
fullkaiten
0
12k
DEFCON_CHV_CTF_Write-up.pdf
bata_24
0
150
開発投資の期待値を上げるプロダクトロードマップづくり ~プロダクトエンジニアが越境して事業を伸ばす~
kekekenta
1
180
山手線を徒歩で一周してわかった、 位置情報アプリは「足」が最強のデバッガー
hinakko
0
160
AIエージェントの自己改善をどう設計するか / How to Design Self-Improvement for AI Agents
22mi
25
16k
AgentCore Runtime上にAgentic Coding基盤を構築・展開する際の設計ポイントと限界点 / Design considerations and limitations when building an agentic coding platform on AgentCore Runtime
har1101
4
170
Featured
See All Featured
The State of eCommerce SEO: How to Win in Today's Products SERPs - #SEOweek
aleyda
2
12k
Self-Hosted WebAssembly Runtime for Runtime-Neutral Checkpoint/Restore in Edge–Cloud Continuum
chikuwait
0
800
Automating Front-end Workflow
addyosmani
1369
210k
Crafting Experiences
bethany
1
340
Gemini Prompt Engineering: Practical Techniques for Tangible AI Outcomes
mfonobong
2
530
The Mindset for Success: Future Career Progression
greggifford
PRO
0
490
Learning to Love Humans: Emotional Interface Design
aarron
275
41k
Utilizing Notion as your number one productivity tool
mfonobong
4
590
Lightning Talk: Beautiful Slides for Beginners
inesmontani
PRO
2
690
Principles of Awesome APIs and How to Build Them.
keavy
128
18k
How to optimise 3,500 product descriptions for ecommerce in one day using ChatGPT
katarinadahlin
PRO
3
3.8k
30 Presentation Tips
portentint
PRO
1
400
Transcript
TFLiteとPyTorch Mobile 2020/06/17 shibui yusuke 1
自己紹介 cat : 0.55 dog: 0.45 human : 0.70 gorilla
: 0.30 画像分類 Shibui Yusuke • メルカリ AI Team 基盤エンジニア MLエンジニア その他いろいろ • Github: @shibuiwilliam • Qiita: @cvusk • Facebook: @shibui yusuke • 最近やってること:Android、AR MLシステムデザインパターン作成中。 これにEdge AIパターンを追加したい! https://github.com/mercari/ml-system -design-pattern 2
今日のアイドル マルグレーテちゃん( ♀) 1歳 ノルウェージャンフォレストキャット 趣味は爪研ぎとゴミ箱あさり! 3
• Why Edge AI? • Tensorflow Lite & PyTorch Mobile
• Let’s Edge AI Agenda 4
Why Edge AI? • サーバサイドでAI • クライアントサイドで AI ボトル ネック
ボトル ネック 高性能 低性能 リアル タイム ・Kotlin ・Java ・Swift ・C++ ・C 情報保護 ・Python ・Python ・Python 5
AIをスマホで動かす • AIはAIだけではない。 ◦ 前処理 カメラで画像を取得し、 画像をAIで扱えるように サイズとRGBを調整して テンソル(行列)に変換する。 ◦
AI 前処理済みのテンソルにたくさんの 掛け算と足し算(積和演算)をする。 ◦ 後処理 AIの結果をスマホの画面に表示。 猫! 6 この画像に写っているものを AIで判定したい
AIをスマホで動かす前処理 • カメラで画像を取得し、画像を AIで扱えるように サイズとRGBを調整してテンソル(行列)に変換する。 0.2 0.3 0.9 0.0 0.0
0.1 0.5 0.7 0.1 0.3 0.5 0.7 0.7 0.6 0.4 0.6 0.2 0.3 0.9 0.0 0.0 0.1 0.5 0.7 0.1 0.3 0.5 0.7 0.7 0.6 0.4 0.6 0.2 0.3 0.9 0.0 0.0 0.1 0.5 0.7 0.1 0.3 0.5 0.7 0.7 0.6 0.4 0.6 画像を正方形 (224*224)にリサイズ RGBのテンソル (行列)に分ける テンソルを0~1に正規化 60 90 240 0 0 10 127 195 10 92 128 195 195 161 111 161 7
AIをスマホで動かすモデル • 前処理済みのテンソルにたくさんの掛け算と足し算(積和演算)をする。 AIの実態(ロジックとパラメータの集まり)を「モデル」と呼ぶ。 0.2 0.3 0.9 0.0 0.0 0.1
0.5 0.7 0.1 0.3 0.5 0.7 0.7 0.6 0.4 0.6 0.2 0.3 0.9 0.0 0.0 0.1 0.5 0.7 0.1 0.3 0.5 0.7 0.7 0.6 0.4 0.6 0.2 0.3 0.9 0.0 0.0 0.1 0.5 0.7 0.1 0.3 0.5 0.7 0.7 0.6 0.4 0.6 tench hen jay kite goose beagle collie stove lion persian siamese gown mask ski ...1000 モデル 演算中にテンソルの形状が変化していく 8
AIをスマホで動かす後処理 • AIの結果をスマホの画面に表示。 猫! tench 5% hen 2% jay 3%
kite 2% goose 10% beagle 2% collie 3% stove 1% lion 10% persian 15% siamese 10% gown 4% mask 2% ski 3% ...1000 ... 9
Google製のTensorflowをモバイルで 動かすためのライブラリ。 Android/iOS/ラズパイ/マイコン対応。 AIのモバイル対応では高性能で汎用的。 TensorFlow Lite & PyTorch Mobile スマホでAIのモデルを動かすための主なライブラリ
Facebook製のPyTorchをモバイルで 動かすためのライブラリ。 Android/iOS対応。 PyTorchは使いやすさやシンプルさから AI研究で使われることが多い。 10
Let's Edge AI ImageAnalysisでTFLiteと PyTorchMobileを実行 WorkerThreadで推論 推論結果 上位3件 ソースコードはこちら。 https://github.com/shibuiwilliam/TFLitePyTorch
11
CameraXにImageAnalysisをbind abstract class AbstractCameraXActivity : AppCompatActivity(){ @WorkerThread protected abstract fun
analyzeImage(image: ImageProxy, rotationDegrees: Int): Map<String, Float> ~~~~省略~~~~ private fun setupCameraX() { ~~~~省略(preview)~~~~ val imageAnalysisConfig = ImageAnalysisConfig .Builder() .apply { setCallbackHandler(mBackgroundHandler) setImageReaderMode(ImageAnalysis.ImageReaderMode.ACQUIRE_LATEST_IMAGE) } .build() ~~~~次ページへ~~~~ } } TFLiteとPyTorchMobileが analyzeImage()をoverride 12
CameraXにImageAnalysisをbind abstract class AbstractCameraXActivity : AppCompatActivity(){ @WorkerThread protected abstract fun
analyzeImage(image: ImageProxy, rotationDegrees: Int): Map<String, Float> ~~~~省略~~~~ private fun setupCameraX() { ~~~~前ページから~~~~ val imageAnalysis = ImageAnalysis(imageAnalysisConfig) imageAnalysis.analyzer = ImageAnalysis.Analyzer { image: ImageProxy?, rotationDegrees: Int -> if (image == null) return@Analyzer val result = analyzeImage(image, rotationDegrees) if (result != null) runOnUiThread(Runnable { showResult(result) }) } CameraX.bindToLifecycle(this, preview, imageAnalysis) } } 結果を画面に表示 推論して結果を取得 13
AIの開発ステップ 前処理 学習 前処理 推論 後処理 モデル 学習 サーバサイド Python
推論 クライアントサイド Kotlin/Swift モデル 変 換 14 グレー部分を TensorFlowや PyTorchがカバー
• tf.lite.TFLiteConverter ◦ TFLite向けの専用のコンバータでモデルを FlatBuffersに変換する。 ◦ 各種クライアントのTFLite InterpreterがFlatBuffersを読み込んでモデルを動かす。 https://github.com/tensorflow/tensorflow/tree/master/tensorflow/lite/python TensorFlow
Lite スマホで推論するためのモデル変換 スマホで推論モデルを動かすためのランタイム • org.tensorflow.lite.* ◦ チップセットへのdelegateを含めたInterpreter(推論器)を動かすためのライブラリ。 ◦ データの入出力はjava.nio.Bufferに変換、Interpreterを呼び出す。 https://github.com/tensorflow/tensorflow/tree/master/tensorflow/lite https://github.com/tensorflow/tensorflow/tree/master/tensorflow/lite/experimenta l/support/java/src/java/org/tensorflow/lite/support 15
TensorFlow Lite Python Java (Kotlin) 16
Neural Network API (NNAPI) Androidデバイスで演算負荷の 高いAI処理を実行するための ネイティブAPI。 演算をGPUや専用チップへ移譲。 アプリ TFLite
NNAPI CPU Proc GPU 17
class TFLiteActivity : AbstractCameraXActivity() { ~~~~省略~~~~ private fun initializeTFLite(device: Constants.Device
= Constants.Device.NNAPI, numThreads: Int = 4) { val delegate = when (device) { Constants.Device.NNAPI -> NnApiDelegate() Constants.Device.GPU -> GpuDelegate() Constants.Device.CPU -> "" } if (delegate != "") tfliteOptions.addDelegate(delegate) tfliteOptions.setNumThreads(numThreads) tfliteModel = FileUtil.loadMappedFile(this, Constants.TFLITE_MOBILENET_V2_PATH) tfliteInterpreter = Interpreter(tfliteModel, tfliteOptions) ~~~~次ページへ~~~~ } } TFLiteの演算を NNAPIやGPU に移譲 既存のモデルファイルを ロード モデルを計算 グラフに変換 TFLiteの推論モデルを用意する 18
TFLiteの推論モデルを用意する class TFLiteActivity : AbstractCameraXActivity() { ~~~~省略~~~~ private fun initializeTFLite(device:
Constants.Device, numThreads: Int) { ~~~~前ページから~~~~ inputImageBuffer = TensorImage(tfliteInterpreter.getInputTensor(0).dataType()) outputProbabilityBuffer = TensorBuffer.createFixedSize( tfliteInterpreter.getOutputTensor(0).shape(), tfliteInterpreter.getInputTensor(0).dataType()) probabilityProcessor = TensorProcessor .Builder() .add(NormalizeOp(0.0f, 1.0f)) .build() } } 入出力テンソルのバッファ 実態はjava.nio.Buffer 出力(確率)の プロセッサ 19
TFLiteで推論 @WorkerThread override fun analyzeImage(image: ImageProxy, rotationDegrees: Int): Map<String, Float>
{ val bitmap = Utils.imageToBitmap(image) val cropSize = Math.min(bitmap.width, bitmap.height) inputImageBuffer.load(bitmap) val inputImage = ImageProcessor .Builder() .add(ResizeWithCropOrPadOp(cropSize, cropSize)) .add(ResizeOp(224, 224, ResizeMethod.NEAREST_NEIGHBOR)) .add(NormalizeOp(127.5f, 127.5f)) .build() .process(inputImageBuffer) ~~~~次ページへ~~~~ } 前処理 ImageProxyをbitmap →テンソルに変換 (同時にリサイズと正規化 ) 20
TFLiteで推論 @WorkerThread override fun analyzeImage(image: ImageProxy, rotationDegrees: Int): Map<String, Float>
{ ~~~~前ページから~~~~ tfliteInterpreter.run(inputImage!!.buffer, outputProbabilityBuffer.buffer.rewind()) val labeledProbability: Map<String, Float> = TensorLabel( labelsList, probabilityProcessor.process(outputProbabilityBuffer) ).mapWithFloatValue return labeledProbability } @UiThread override fun showResult(result: String) { textView.text = result } outputProbBufferに 推論結果を格納 ラベルと推論結果を紐 付ける 結果を表示 21
• torch.jit.trace() ◦ 汎用的なJITコンパイラでモバイル用のモデルを生成。 モバイル用に最適化するものではない。 ◦ Pythonで作ったPyTorchのモデルをC++から直接呼べるように変換している。 https://github.com/pytorch/pytorch/tree/master/torch/jit PyTorch Mobile
• org.pytorch.* torch.jit.trace()で生成したモデルを Nativeライブラリで動かすための Java実装を提供。 https://github.com/pytorch/pytorch/tree/master/android • com.facebook.soloader.* org.pytorch.*の実態はSoLoaderというFacebook製のネイティブコードローダー。 https://github.com/facebook/SoLoader スマホで推論するためのモデル変換 スマホで推論モデルを動かすためのランタイム 22
server Torch API PyTorch Mobile client Torch torch.jit.trace model.pt SoLoader
Graph computation CPU Python Java (Kotlin) 23
PyTorch Mobileの推論モデルを用意する class PyTorchActivity : AbstractCameraXActivity() { ~~~~省略~~~~ private fun
initializePyTorch() { val pytorchModule = Module.load(Utils.assetFilePath( this, Constants.PYTORCH_RESNET18_PATH)) val mInputTensorBuffer = Tensor.allocateFloatBuffer(3 * 224 * 224) val mInputTensor = Tensor.fromBlob( mInputTensorBuffer, longArrayOf(1, 3, 224L, 224L) ) } } 推論モデルファイルをロード この先はSoLoader 入力のテンソルを用意 実態はjava.nio.Buffer 24
PyTorch Mobileで推論 @WorkerThread override fun analyzeImage(image: ImageProxy, rotationDegrees: Int): Map<String,
Float> { TensorImageUtils.imageYUV420CenterCropToFloatBuffer( image.image, rotationDegrees, 224, 224, TensorImageUtils.TORCHVISION_NORM_MEAN_RGB, TensorImageUtils.TORCHVISION_NORM_STD_RGB, mInputTensorBuffer, 0 ) ~~~~次ページへ~~~~ } 前処理 ImageProxyを テンソルに変換 (同時にリサイズと正規化 ) 25
PyTorch Mobileで推論 @WorkerThread override fun analyzeImage(image: ImageProxy, rotationDegrees: Int): Map<String,
Float> { ~~~~前ページから~~~~ val outputModule = pytorchModule.forward(IValue.from(mInputTensor)).toTensor() val scores = outputModule.dataAsFloatArray val labeledProbability: MutableMap<String, Float> = mutableMapOf() for (i in 0 until labelsList.size - 1) { labeledProbability[labelsList[i + 1]] = score[i] } return labeledProbability } @UiThread override fun showResult(result: String) { textView.text = result } 推論し、結果を テンソルに変換 ラベルと 推論結果を 紐付ける 結果を表示 26
こんな感じで動きます 27
TFLiteとPyTorch Mobileを使ってみた感想 • 高性能。 • CPUだけでなくGPU/NNAPI移譲が可能。 • 各種オプションやExampleが豊富。 • 最低限必要な機能がある。
• CPUのみ。 • オプションが少ない分、シンプルに書くことが できる。 28