LoginSignup
1
0

androidデバイスのGPUを使ってTensorflow liteを高速にする

Posted at

AIを使うならGPUは使わないと

androidでAIモデルを使用する場合、デフォルトではCPUのみで実行することになります。
もしデバイスにGPU(Graphics Processing Unit)が入っている場合、GPUを使用することで処理を大幅に高速化できます

たとえば、Google Pixel 7aでYolov8を実行した場合、
CPUでは 0.9秒
GPUでは 0.2秒

で実行されます。

GPUDelegate

デバイスのGPUを使うためには、TensorFlowLiteのGPUDelegateを設定します。
TensorFlowLiteのInterpreterを初期化するときに、オプションにGPUDelegateを加えるだけです。

(ちなみに、NNAPIDelegate(NeuralNetworkAPI)というのもありますが、これは自分の環境(GooglePixel7a)ではCPUと変わりませんでした、)

方法

必要なライブラリのインストール

build.gradle
implementation("org.tensorflow:tensorflow-lite:+")
implementation("org.tensorflow:tensorflow-lite-gpu:+")
implementation("org.tensorflow:tensorflow-lite-gpu-api:+")
implementation("org.tensorflow:tensorflow-lite-gpu-delegate-plugin:+")
implementation("org.tensorflow:tensorflow-lite-support:+")

上から4つのライブラリはバージョンを合わせないとクラッシュすることがあるみたいです。
:+ にしておけば全部最新バージョンがインストールされるのでOKです。

GPUDelegateの設定

モジュールインポート

import org.tensorflow.lite.Interpreter
import org.tensorflow.lite.gpu.CompatibilityList
import org.tensorflow.lite.gpu.GpuDelegate

デリゲートの設定。

モデルのInterpreterのオプションにGPUDelegateを設定します。

val compatList = CompatibilityList()

val options = Interpreter.Options().apply{
    if(compatList.isDelegateSupportedOnThisDevice){
        // if the device has a supported GPU, add the GPU delegate
        val delegateOptions = compatList.bestOptionsForThisDevice
        this.addDelegate(GpuDelegate(delegateOptions))
    } else {
        // if the GPU is not supported, run on 4 threads
        this.setNumThreads(4)
    }
}

interpreter = Interpreter(model, options)

これで、デバイスに利用可能なGPUがある場合はGPUを使用してモデルが実行されます。

🐣


フリーランスエンジニアです。
AIについて色々記事を書いていますのでよかったらプロフィールを見てみてください。

もし以下のようなご要望をお持ちでしたらお気軽にご相談ください。
AIサービスを開発したい、ビジネスにAIを組み込んで効率化したい、AIを使ったスマホアプリを開発したい、
ARを使ったアプリケーションを作りたい、スマホアプリを作りたいけどどこに相談したらいいかわからない…

いずれも中間コストを省いたリーズナブルな価格でお請けできます。

お仕事のご相談はこちらまで
rockyshikoku@gmail.com

機械学習やAR技術を使ったアプリケーションを作っています。
機械学習/AR関連の情報を発信しています。

X
Medium
GitHub

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0