Delegado de aceleración de GPU con la API de intérprete

Usar unidades de procesamiento gráfico (GPU) para ejecutar tus modelos de aprendizaje automático (AA) pueden mejorar drásticamente el rendimiento y la experiencia del usuario de sus aplicaciones compatibles con el AA. En los dispositivos Android, puedes habilitar un delegate y una de las siguientes APIs:

  • API de Interpreter: esta guía
  • API nativa (C/C++): guía

En esta página, se describe cómo habilitar la aceleración de GPU para modelos LiteRT en Apps para Android que usan la API de Interpreter Para obtener más información sobre cómo usar la GPU delegado de LiteRT, incluidas las prácticas recomendadas y las técnicas avanzadas, consulta la página Delegados de GPU.

Usa GPU con LiteRT con los Servicios de Google Play

El intérprete de LiteRT API proporciona un conjunto de APIs de uso general para compilar aplicaciones de aprendizaje automático. Esta sección se describe cómo usar el delegado del acelerador de GPU con estas APIs con LiteRT con los Servicios de Google Play.

Se recomienda usar LiteRT con los Servicios de Google Play. para usar LiteRT en Android. Si tu aplicación se orienta a dispositivos no ejecutas Google Play, consulta la GPU con API de Intérprete y LiteRT.

Agrega dependencias de proyecto (con un catálogo de versiones .toml)

  1. Actualiza el archivo libs.versions.toml de tu proyecto
[libraries]
...
tflite-gpu = { module = "com.google.ai.edge.litert:litert-gpu", version = "2.X.Y" }
tflite-gpu-api = { module = "com.google.ai.edge.litert:litert-gpu-api", version = "2.X.Y" }
...
  1. Agrega dependencias del proyecto en el build.gradle.kts de la app
dependencies {
  ...
  implementation(libraries.tflite.gpu)
  implementation(libraries.tflite.gpu.api)
  ...
}

Agrega dependencias del proyecto

Para habilitar el acceso al delegado de la GPU, agrega com.google.android.gms:play-services-tflite-gpu a la build.gradle de tu app archivo:

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'
}

Cómo habilitar la aceleración de GPU

Luego, inicializa LiteRT con los Servicios de Google Play compatibles con 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());
});
        

Por último, puedes inicializar el intérprete pasando un GpuDelegateFactory. a través de 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);
      

El delegado de GPU también se puede usar con la vinculación de modelos de AA en Android Studio. Para para obtener más información, consulta Genera interfaces de modelo usando metadatos.

Usa GPU con LiteRT independiente

Si tu aplicación está orientada a dispositivos que no ejecutan Google Play, es es posible empaquetar el delegado de la GPU para tu aplicación y usarlo con el independiente de LiteRT.

Agrega dependencias del proyecto

Para habilitar el acceso al delegado de la GPU, agrega com.google.ai.edge.litert:litert-gpu-delegate-plugin a la de tu app Archivo build.gradle:

dependencies {
    ...
    implementation 'org.tensorflow:tensorflow-lite'
    implementation 'com.google.ai.edge.litert:litert-gpu-delegate-plugin'
}

Cómo habilitar la aceleración de GPU

Luego, ejecuta LiteRT en GPU con TfLiteDelegate. En Java, puedes especificar GpuDelegate a 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);
      

Modelos cuantificados

Las bibliotecas delegadas de la GPU de Android admiten modelos cuantizados de forma predeterminada. No debes tendremos que realizar cambios en el código para usar modelos cuantizados con el delegado de la GPU. El En la siguiente sección, se explica cómo inhabilitar la asistencia cuantizada para pruebas o con fines experimentales.

Inhabilitar la compatibilidad con modelos cuantizados

En el siguiente código, se muestra cómo inhabilitar la compatibilidad con modelos cuantizados.

Java

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

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

Para obtener más información sobre cómo ejecutar modelos cuantizados con aceleración de GPU, consulta Descripción general del delegado de GPU.