인터프리터 API를 사용한 GPU 가속 대리자

그래픽 처리 장치 (GPU)를 사용하여 머신러닝 (ML) 모델을 실행하면 ML 지원 애플리케이션의 성능과 사용자 환경을 크게 개선할 수 있습니다. Android 기기에서는 대리자와 다음 API 중 하나를 사용 설정할 수 있습니다.

  • 인터프리터 API - 이 가이드
  • 네이티브 (C/C++) API - 가이드

이 페이지에서는 인터프리터 API를 사용하여 Android 앱에서 TensorFlow Lite 모델에 GPU 가속을 사용 설정하는 방법을 설명합니다. 권장사항 및 고급 기술을 포함하여 TensorFlow Lite용 GPU 대리자를 사용하는 방법에 관한 자세한 내용은 GPU 대리자 페이지를 참고하세요.

Google Play 서비스에서 TensorFlow Lite로 GPU 사용

TensorFlow Lite Translateer API는 머신러닝 애플리케이션을 빌드하기 위한 범용 API 모음을 제공합니다. 이 섹션에서는 Google Play 서비스에서 TensorFlow Lite와 함께 이러한 API와 함께 GPU 가속기 대리자를 사용하는 방법을 설명합니다.

Google Play 서비스가 포함된 TensorFlow Lite는 Android에서 TensorFlow Lite를 사용하기 위한 권장 경로입니다. 애플리케이션이 Google Play를 실행하지 않는 기기를 대상으로 하는 경우 인터프리터 API를 사용하는 GPU 및 독립형 TensorFlow Lite 섹션을 참조하세요.

프로젝트 종속 항목 추가(.toml 버전 카탈로그 포함)

  1. 프로젝트의 libs.versions.toml 파일 업데이트
[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. 앱의 build.gradle.kts에 프로젝트 종속 항목 추가
dependencies {
  ...
  implementation(libraries.tflite.gpu)
  implementation(libraries.tflite.gpu.api)
  ...
}

프로젝트 종속 항목 추가

GPU 대리자에 대한 액세스를 사용 설정하려면 앱의 build.gradle 파일에 com.google.android.gms:play-services-tflite-gpu를 추가합니다.

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

GPU 가속 사용 설정

그런 다음 GPU를 지원하는 Google Play 서비스로 TensorFlow Lite를 초기화합니다.

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

마지막으로 InterpreterApi.Options를 통해 GpuDelegateFactory를 전달하는 인터프리터를 초기화할 수 있습니다.

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

오류가 표시될 수 있습니다.

GPU 대리자는 Android 스튜디오에서 ML 모델 바인딩과 함께 사용할 수도 있습니다. 자세한 내용은 메타데이터를 사용하여 모델 인터페이스 생성을 참조하세요.

독립형 TensorFlow Lite로 GPU 사용

애플리케이션이 Google Play를 실행하지 않는 기기를 타겟팅하는 경우 GPU 대리자를 애플리케이션에 번들로 묶어 TensorFlow Lite 독립형 버전과 함께 사용할 수 있습니다.

프로젝트 종속 항목 추가

GPU 대리자에 대한 액세스를 사용 설정하려면 앱의 build.gradle 파일에 org.tensorflow:tensorflow-lite-gpu-delegate-plugin를 추가합니다.

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

GPU 가속 사용 설정

그런 다음 TfLiteDelegate를 사용하여 GPU에서 TensorFlow Lite를 실행합니다. 자바에서는 Interpreter.Options를 통해 GpuDelegate를 지정할 수 있습니다.

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

양자화 모델

Android GPU 위임 라이브러리는 기본적으로 양자화된 모델을 지원합니다. GPU 대리자를 통해 양자화 모델을 사용하기 위해 코드를 변경할 필요는 없습니다. 다음 섹션에서는 테스트 또는 실험 목적으로 양자화 지원을 사용 중지하는 방법을 설명합니다.

양자화 모델 지원 사용 중지

다음 코드는 양자화 모델에 대한 지원을 사용 중지하는 방법을 보여줍니다.

Java

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

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

GPU 가속으로 양자화 모델을 실행하는 방법에 관한 자세한 내용은 GPU 대리자 개요를 참고하세요.