Google Play 服務 Java API 中的 TensorFlow Lite

除了原生 API 外,Google Play 服務中的 TensorFlow Lite 也可以使用 Java API 存取。特別是,您可以在 Google Play 服務中透過 TensorFlow Lite Understandinger API 取得 TensorFlow Lite。

使用翻譯 API

TensorFlow 執行階段提供的 TensorFlow Lite Understandinger API 提供一般用途介面,用於建構及執行機器學習模型。在 Google Play 服務執行階段中使用 TensorFlow Lite,透過 Understandinger API 執行推論。

1. 新增專案依附元件

將下列依附元件新增至應用程式專案程式碼,以存取 TensorFlow Lite 適用的 Play 服務 API:

dependencies {
...
    // Tensorflow Lite dependencies for Google Play services
    implementation 'com.google.android.gms:play-services-tflite-java:16.0.1'
    // Optional: include Tensorflow Lite Support Library
    implementation 'com.google.android.gms:play-services-tflite-support:16.0.1'
...
}

2. 新增 TensorFlow Lite 初始化功能

使用 TensorFlow Lite API「之前」,先初始化 Google Play 服務 API 的 TensorFlow Lite 元件:

Kotlin

val initializeTask: Task<Void> by lazy { TfLite.initialize(this) }

Java

Task<Void> initializeTask = TfLite.initialize(context);

3. 建立翻譯工具並設定執行階段選項

使用 InterpreterApi.create() 建立解譯器,然後呼叫 InterpreterApi.Options.setRuntime() 將其設為使用 Google Play 服務執行階段,如以下範例程式碼所示:

Kotlin

import org.tensorflow.lite.InterpreterApi
import org.tensorflow.lite.InterpreterApi.Options.TfLiteRuntime
...
private lateinit var interpreter: InterpreterApi
...
initializeTask.addOnSuccessListener {
  val interpreterOption =
    InterpreterApi.Options().setRuntime(TfLiteRuntime.FROM_SYSTEM_ONLY)
  interpreter = InterpreterApi.create(
    modelBuffer,
    interpreterOption
  )}
  .addOnFailureListener { e ->
    Log.e("Interpreter", "Cannot initialize interpreter", e)
  }

Java

import org.tensorflow.lite.InterpreterApi
import org.tensorflow.lite.InterpreterApi.Options.TfLiteRuntime
...
private InterpreterApi interpreter;
...
initializeTask.addOnSuccessListener(a -> {
    interpreter = InterpreterApi.create(modelBuffer,
      new InterpreterApi.Options().setRuntime(TfLiteRuntime.FROM_SYSTEM_ONLY));
  })
  .addOnFailureListener(e -> {
    Log.e("Interpreter", String.format("Cannot initialize interpreter: %s",
          e.getMessage()));
  });

您應使用上述實作方式,因為這麼做可避免封鎖 Android 使用者介面執行緒。如果您需要更密切地管理執行緒執行作業,可以新增 Tasks.await() 呼叫來解譯器建立:

Kotlin

import androidx.lifecycle.lifecycleScope
...
lifecycleScope.launchWhenStarted { // uses coroutine
  initializeTask.await()
}

Java

@BackgroundThread
InterpreterApi initializeInterpreter() {
    Tasks.await(initializeTask);
    return InterpreterApi.create(...);
}

4. 執行推論

使用您建立的 interpreter 物件,呼叫 run() 方法來產生推論。

Kotlin

interpreter.run(inputBuffer, outputBuffer)

Java

interpreter.run(inputBuffer, outputBuffer);

硬體加速

TensorFlow Lite 可讓您使用特殊的硬體處理器 (例如圖形處理器 (GPU) 來加快模型的效能)。您可以運用名為委派代表的硬體驅動程式,利用這些特殊處理器

GPU 委派是由 Google Play 服務提供,並會以動態方式載入,就像 解譯 er API 的 Play 服務版本一樣。

檢查裝置相容性

並非所有裝置都支援 TFLite 的 GPU 硬體加速功能。為減少錯誤和潛在當機問題,請使用 TfLiteGpu.isGpuDelegateAvailable 方法檢查裝置是否與 GPU 委派相容。

請使用這個方法確認裝置是否與 GPU 相容,並使用 CPU 做為 GPU 不支援的備用方案。

useGpuTask = TfLiteGpu.isGpuDelegateAvailable(context)

取得 useGpuTask 等變數後,您就能用來判斷裝置是否使用 GPU 委派。

Kotlin

val interpreterTask = useGpuTask.continueWith { task ->
  val interpreterOptions = InterpreterApi.Options()
      .setRuntime(TfLiteRuntime.FROM_SYSTEM_ONLY)
  if (task.result) {
      interpreterOptions.addDelegateFactory(GpuDelegateFactory())
  }
  InterpreterApi.create(FileUtil.loadMappedFile(context, MODEL_PATH), interpreterOptions)
}
    

Java

Task<InterpreterApi.Options> interpreterOptionsTask = useGpuTask.continueWith({ task ->
  InterpreterApi.Options options =
      new InterpreterApi.Options().setRuntime(TfLiteRuntime.FROM_SYSTEM_ONLY);
  if (task.getResult()) {
     options.addDelegateFactory(new GpuDelegateFactory());
  }
  return options;
});
    

搭配翻譯工具 API 的 GPU

如何搭配使用 GPU 委派與解譯器 API:

  1. 更新專案依附元件,以使用 Play 服務的 GPU 委派:

    implementation 'com.google.android.gms:play-services-tflite-gpu:16.1.0'
    
  2. 在 TFlite 初始化中啟用 GPU 委派選項:

    Kotlin

        TfLite.initialize(context,
          TfLiteInitializationOptions.builder()
           .setEnableGpuDelegateSupport(true)
           .build())
        

    Java

        TfLite.initialize(context,
          TfLiteInitializationOptions.builder()
           .setEnableGpuDelegateSupport(true)
           .build());
        
  3. 在解譯器選項中啟用 GPU 委派:呼叫 addDelegateFactory() withinUnderstandingerApi.Options()`,將委派工廠設為 GpuDelegateFactory:

    Kotlin

    val interpreterOption = InterpreterApi.Options()
    .setRuntime(TfLiteRuntime.FROM_SYSTEM_ONLY)
    .addDelegateFactory(GpuDelegateFactory())
    

    Java

    Options interpreterOption = InterpreterApi.Options()
    .setRuntime(TfLiteRuntime.FROM_SYSTEM_ONLY) .addDelegateFactory(new
    GpuDelegateFactory());
    

從獨立的 TensorFlow Lite 遷移

如果您打算將應用程式從獨立的 TensorFlow Lite 遷移至 Play 服務 API,請參閱下列額外指引,瞭解如何更新應用程式專案程式碼:

  1. 請參閱本頁面的「限制」一節,確保系統支援您的用途。
  2. 更新程式碼前,請對模型進行效能和準確率檢查,特別是使用 TensorFlow Lite 2.1 以下版本,因此您有可與新實作項目比較的基準。
  3. 如果您已將所有程式碼遷移為使用 TensorFlow Lite 適用的 Play 服務 API,您應從 build.gradle 檔案中移除現有的 TensorFlow Lite 執行階段程式庫依附元件 (包含 org.tensorflow:tensorflow-lite:* 的項目),以便縮減應用程式大小。
  4. 在程式碼中找出所有出現的 new Interpreter 物件建立作業,並修改每個物件,讓其使用 UnderstandingerApi.create() 呼叫。新的 TfLite.Initial 並非同步,也就是說在大部分的情況下,這並非直接取代:您必須在呼叫完成時註冊事件監聽器。請參閱步驟 3 中的程式碼片段。
  5. 使用 org.tensorflow.lite.Interpreterorg.tensorflow.lite.InterpreterApi 類別,將 import org.tensorflow.lite.InterpreterApi;import org.tensorflow.lite.InterpreterApi.Options.TfLiteRuntime; 新增至任何來源檔案。
  6. 如果任何對 InterpreterApi.create() 產生的呼叫都只有一個引數,請將 new InterpreterApi.Options() 附加至引數清單。
  7. .setRuntime(TfLiteRuntime.FROM_SYSTEM_ONLY) 附加至任何對 InterpreterApi.create() 呼叫的最後一個引數。
  8. 將所有其他出現的 org.tensorflow.lite.Interpreter 類別替換為 org.tensorflow.lite.InterpreterApi

如要並排使用獨立的 TensorFlow Lite 和 Play 服務 API,必須使用 TensorFlow Lite 2.9 (或之後版本)。TensorFlow Lite 2.8 及以下版本與 Play 服務 API 版本不相容。