Delegato dell'accelerazione GPU con l'API Interpreter

L'utilizzo di GPU (Graphics Processing Unit) per l'esecuzione dei modelli di machine learning (ML) può migliorare notevolmente le prestazioni e l'esperienza utente delle applicazioni abilitate per ML. Sui dispositivi Android, puoi attivare un delegato e una delle seguenti API:

  • API Interpreter: questa guida
  • API nativa (C/C++) - guida

Questa pagina descrive come abilitare l'accelerazione GPU per i modelli TensorFlow Lite nelle app per Android utilizzando l'API Interpreter. Per ulteriori informazioni sull'utilizzo del delega GPU per TensorFlow Lite, incluse best practice e tecniche avanzate, consulta la pagina relativa ai delegati GPU.

Utilizza GPU con TensorFlow Lite con Google Play Services

L'API Interpreter di TensorFlow Lite fornisce un set di API per uso generico per la creazione di applicazioni di machine learning. Questa sezione descrive come utilizzare il delegato dell'acceleratore GPU con queste API con TensorFlow Lite con Google Play Services.

TensorFlow Lite con Google Play Services è il percorso consigliato per utilizzare TensorFlow Lite su Android. Se la tua applicazione ha come target dispositivi che non eseguono Google Play, consulta la sezione GPU con API Interpreter e TensorFlow Lite autonomo.

Aggiungi dipendenze del progetto (con catalogo delle versioni .toml)

  1. Aggiorna il file libs.versions.toml del tuo progetto
[libraries]
...
tflite-gpu = { module = "org.tensorflow:tensorflow-lite-gpu", version = "2.X.Y" }
tflite-gpu-api = { module = "org.tensorflow:tensorflow-lite-gpu-api", version = "2.X.Y" }
...
  1. Aggiungi le dipendenze del progetto in build.gradle.kts dell'app
dependencies {
  ...
  implementation(libraries.tflite.gpu)
  implementation(libraries.tflite.gpu.api)
  ...
}

Aggiungi dipendenze del progetto

Per abilitare l'accesso al delegato GPU, aggiungi com.google.android.gms:play-services-tflite-gpu al file build.gradle dell'app:

dependencies {
    ...
    implementation 'com.google.android.gms:play-services-tflite-java:16.0.1'
    implementation 'com.google.android.gms:play-services-tflite-gpu:16.1.0'
}

Attiva l'accelerazione GPU

Quindi inizializza TensorFlow Lite con Google Play Services con il supporto GPU:

Kotlin

val useGpuTask = TfLiteGpu.isGpuDelegateAvailable(context)

val interpreterTask = useGpuTask.continueWith { useGpuTask ->
  TfLite.initialize(context,
      TfLiteInitializationOptions.builder()
      .setEnableGpuDelegateSupport(useGpuTask.result)
      .build())
  }
        

Java

Task<boolean> useGpuTask = TfLiteGpu.isGpuDelegateAvailable(context);

Task<Options> interpreterOptionsTask = useGpuTask.continueWith({ task ->
  TfLite.initialize(context,
  TfLiteInitializationOptions.builder()
    .setEnableGpuDelegateSupport(true)
    .build());
});
        

Puoi finalmente inizializzare l'interprete che passa un GpuDelegateFactory tramite InterpreterApi.Options:

Kotlin


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

    val interpreter = InterpreterApi(model, options)

    // Run inference
    writeToInput(input)
    interpreter.run(input, output)
    readFromOutput(output)
      

Java


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

    Interpreter interpreter = new InterpreterApi(model, options);

    // Run inference
    writeToInput(input);
    interpreter.run(input, output);
    readFromOutput(output);
      

Il delegato GPU può essere utilizzato anche con l'associazione del modello ML in Android Studio. Per ulteriori informazioni, consulta Generare interfacce dei modelli utilizzando i metadati.

Utilizza GPU con TensorFlow Lite autonomo

Se la tua applicazione ha come target dispositivi che non eseguono Google Play, puoi raggruppare il delegato GPU all'applicazione e utilizzarla con la versione autonoma di TensorFlow Lite.

Aggiungi dipendenze del progetto

Per attivare l'accesso al delegato GPU, aggiungi org.tensorflow:tensorflow-lite-gpu-delegate-plugin al file build.gradle della tua app:

dependencies {
    ...
    implementation 'org.tensorflow:tensorflow-lite'
    implementation 'org.tensorflow:tensorflow-lite-gpu-delegate-plugin'
}

Attiva l'accelerazione GPU

Quindi esegui TensorFlow Lite sulla GPU con TfLiteDelegate. In Java, puoi specificare GpuDelegate tramite Interpreter.Options.

Kotlin

      import org.tensorflow.lite.Interpreter
      import org.tensorflow.lite.gpu.CompatibilityList
      import org.tensorflow.lite.gpu.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)
          }
      }

      val interpreter = Interpreter(model, options)

      // Run inference
      writeToInput(input)
      interpreter.run(input, output)
      readFromOutput(output)
      

Java

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

      // Initialize interpreter with GPU delegate
      Interpreter.Options options = new Interpreter.Options();
      CompatibilityList compatList = CompatibilityList();

      if(compatList.isDelegateSupportedOnThisDevice()){
          // if the device has a supported GPU, add the GPU delegate
          GpuDelegate.Options delegateOptions = compatList.getBestOptionsForThisDevice();
          GpuDelegate gpuDelegate = new GpuDelegate(delegateOptions);
          options.addDelegate(gpuDelegate);
      } else {
          // if the GPU is not supported, run on 4 threads
          options.setNumThreads(4);
      }

      Interpreter interpreter = new Interpreter(model, options);

      // Run inference
      writeToInput(input);
      interpreter.run(input, output);
      readFromOutput(output);
      

Modelli quantizzati

Le librerie delegate di GPU Android supportano i modelli quantizzati per impostazione predefinita. Non è necessario apportare modifiche al codice per utilizzare i modelli quantizzati con il delegato GPU. La sezione seguente spiega come disattivare il supporto quantizzato per scopi di test o sperimentali.

Disabilita il supporto del modello quantizzato

Il seguente codice mostra come disabilitare il supporto per i modelli quantiizzati.

Java

GpuDelegate delegate = new GpuDelegate(new GpuDelegate.Options().setQuantizedModelsAllowed(false));

Interpreter.Options options = (new Interpreter.Options()).addDelegate(delegate);
      

Per ulteriori informazioni sull'esecuzione di modelli quantizzati con l'accelerazione GPU, consulta la panoramica relativa al delegato GPU.