Google Play 서비스 C API의 TensorFlow Lite (베타)

Google Play 서비스 런타임의 TensorFlow Lite를 사용하면 TensorFlow Lite 라이브러리를 앱에 정적으로 번들로 묶지 않고도 머신러닝 (ML) 모델을 실행할 수 있습니다. 이 가이드에서는 Google Play 서비스에 C API를 사용하는 방법을 안내합니다.

Google Play 서비스 C API에서 TensorFlow Lite를 사용하기 전에 CMake 빌드 도구가 설치되어 있는지 확인합니다.

빌드 구성 업데이트

TensorFlow Lite용 Play 서비스 API에 액세스하려면 앱 프로젝트 코드에 다음 종속 항목을 추가합니다.

implementation "com.google.android.gms:play-services-tflite-java:16.2.0-beta02"

그런 다음 모듈의 build.gradle 파일에서 android 블록을 업데이트하여 Prefab 기능을 사용 설정하여 CMake 스크립트에서 C API에 액세스합니다.

buildFeatures {
  prefab = true
}

마지막으로 AAR에서 가져온 패키지 tensorflowlite_jni_gms_client를 CMake 스크립트에 종속 항목으로 추가해야 합니다.

find_package(tensorflowlite_jni_gms_client REQUIRED CONFIG)

target_link_libraries(tflite-jni # your JNI lib target
        tensorflowlite_jni_gms_client::tensorflowlite_jni_gms_client
        android # other deps for your target
        log)

# Also add -DTFLITE_IN_GMSCORE -DTFLITE_WITH_STABLE_ABI
# to the C/C++ compiler flags.

add_compile_definitions(TFLITE_IN_GMSCORE)
add_compile_definitions(TFLITE_WITH_STABLE_ABI)

TensorFlow Lite 런타임 초기화

TensorFlow Lite Native API를 호출하기 전에 자바/Kotlin 코드에서 TfLiteNative 런타임을 초기화해야 합니다.

Java

Task tfLiteInitializeTask = TfLiteNative.initialize(context);
      

Kotlin

val tfLiteInitializeTask: Task = TfLiteNative.initialize(context)
        

TfLiteNative.initialize는 Google Play 서비스 Task API를 사용하여 Google Play 서비스에서 애플리케이션의 런타임 프로세스로 TFLite 런타임을 비동기식으로 로드합니다. TensorFlow Lite API에 액세스하는 코드를 실행하기 전에 addOnSuccessListener()를 사용하여 TfLite.initialize() 작업이 완료되었는지 확인합니다. 작업이 성공적으로 완료되면 사용 가능한 모든 TFLite 네이티브 API를 호출할 수 있습니다.

네이티브 코드 구현

네이티브 코드로 Google Play 서비스의 TensorFlow Lite를 사용하려면 다음 중 하나를 실행하세요.

  • 새로운 JNI 함수를 선언하여 Java 코드에서 네이티브 함수 호출
  • 기존 네이티브 C 코드에서 TensorFlow Lite Native API를 호출합니다.

JNI 함수:

다음과 같이 새 JNI 함수를 선언하여 자바/Kotlin으로 선언된 TensorFlow Lite 런타임이 네이티브 코드에 액세스할 수 있도록 할 수 있습니다.

Java

package com.google.samples.gms.tflite.c;

public class TfLiteJni {
  static {
    System.loadLibrary("tflite-jni");
  }
  public TfLiteJni() { /**/ };
  public native void loadModel(AssetManager assetManager, String assetName);
  public native float[] runInference(float[] input);
}
      

Kotlin

package com.google.samples.gms.tflite.c

class TfLiteJni() {
  companion object {
    init {
      System.loadLibrary("tflite-jni")
    }
  }
  external fun loadModel(assetManager: AssetManager, assetName: String)
  external fun runInference(input: FloatArray): FloatArray
}
        

다음 loadModelrunInference 네이티브 함수 일치:

#ifdef __cplusplus
extern "C" {
#endif

void Java_com_google_samples_gms_tflite_c_loadModel(
  JNIEnv *env, jobject tflite_jni, jobject asset_manager, jstring asset_name){
  //...
}

jfloatArray Java_com_google_samples_gms_tflite_c_TfLiteJni_runInference(
  JNIEnv* env, jobject tfliteJni, jfloatArray input) {
  //...
}

#ifdef __cplusplus
}  // extern "C".
#endif

그런 다음 Java/Kotlin 코드에서 C 함수를 호출할 수 있습니다.

Java

tfLiteHandleTask.onSuccessTask(unused -> {
    TfLiteJni jni = new TfLiteJni();
    jni.loadModel(getAssets(), "add.bin");
    //...
});
    

Kotlin

tfLiteHandleTask.onSuccessTask {
    val jni = TfLiteJni()
    jni.loadModel(assets, "add.bin")
    // ...
}
      

C 코드로 작성된 TensorFlow Lite

Google Play 서비스 API와 함께 TfLite를 포함하도록 적절한 API 헤더 파일을 포함합니다.

#include "tensorflow/lite/c/c_api.h"

그런 다음 일반 TensorFlow Lite C API를 사용하면 됩니다.

auto model = TfLiteModelCreate(model_asset, model_asset_length);
// ...
auto options = TfLiteInterpreterOptionsCreate();
// ...
auto interpreter = TfLiteInterpreterCreate(model, options);

Google Play 서비스 Native API 헤더가 포함된 TensorFlow Lite는 지원 중단되었거나 실험용 기능을 제외하고 일반 TensorFlow Lite C API와 동일한 API를 제공합니다. 지금은 c_api.h, c_api_types.h, common.h 헤더의 함수와 유형을 사용할 수 있습니다. c_api_experimental.h 헤더의 함수는 지원되지 않습니다.

tflite.h를 포함하여 Google Play 서비스에서 TensorFlow Lite 관련 함수를 사용할 수 있습니다.