Delegado de aceleração de GPU com API Interpreter

O uso de unidades de processamento gráfico (GPUs) para executar seus modelos de aprendizado de máquina (ML) pode melhorar drasticamente o desempenho e a experiência do usuário de seus aplicativos habilitados para ML. Em dispositivos Android, você pode habilitar

delegado e uma das seguintes APIs:

  • API do intérprete - este guia
  • API da biblioteca de tarefas - guia
  • API nativa (C/C++) - guia

Esta página descreve como habilitar a aceleração de GPU para modelos do TensorFlow Lite em aplicativos Android usando a API Interpreter. Para obter mais informações sobre como usar o delegado de GPU para TensorFlow Lite, incluindo práticas recomendadas e técnicas avançadas, consulte a página de delegados de GPU .

Use GPU com TensorFlow Lite com serviços do Google Play

A API TensorFlow Lite Interpreter fornece um conjunto de APIs de uso geral para criar aplicativos de aprendizado de máquina. Esta seção descreve como usar o acelerador de GPU delegado com essas APIs com TensorFlow Lite com serviços do Google Play.

O TensorFlow Lite com serviços do Google Play é o caminho recomendado para usar o TensorFlow Lite no Android. Se seu aplicativo for destinado a dispositivos que não executam o Google Play, consulte a seção GPU com API Interpreter e TensorFlow Lite autônomo .

Adicionar dependências do projeto

Para ativar o acesso ao delegado da GPU, adicione com.google.android.gms:play-services-tflite-gpu ao arquivo build.gradle do seu aplicativo:

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

Ativar aceleração de GPU

Em seguida, inicialize o TensorFlow Lite com os serviços do Google Play com suporte a GPU:

KotlinGenericName

    val useGpuTask = TfLiteGpu.isGpuDelegateAvailable(context)

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

Java

    Task useGpuTask = TfLiteGpu.isGpuDelegateAvailable(context);

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

Você pode finalmente inicializar o interpretador passando um GpuDelegateFactory por meio de InterpreterApi.Options :

KotlinGenericName


    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);
      

O delegado de GPU também pode ser usado com vinculação de modelo de ML no Android Studio. Para obter mais informações, consulte Gerar interfaces de modelo usando metadados .

Use a GPU com o TensorFlow Lite independente

Se seu aplicativo for destinado a dispositivos que não executam o Google Play, é possível agrupar o delegado de GPU ao seu aplicativo e usá-lo com a versão autônoma do TensorFlow Lite.

Adicionar dependências do projeto

Para habilitar o acesso ao delegado da GPU, adicione org.tensorflow:tensorflow-lite-gpu-delegate-plugin ao arquivo build.gradle do seu aplicativo:

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

Ativar aceleração de GPU

Em seguida, execute o TensorFlow Lite na GPU com TfLiteDelegate . Em Java, você pode especificar o GpuDelegate por meio de Interpreter.Options .

KotlinGenericName

      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 quantizados

As bibliotecas delegadas de GPU do Android oferecem suporte a modelos quantizados por padrão. Você não precisa fazer nenhuma alteração de código para usar modelos quantizados com o delegado de GPU. A seção a seguir explica como desativar o suporte quantizado para fins de teste ou experimentais.

Desativar o suporte ao modelo quantizado

O código a seguir mostra como desabilitar o suporte para modelos quantizados.

Java

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

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

Para obter mais informações sobre a execução de modelos quantizados com aceleração de GPU, consulte visão geral do delegado de GPU .