Kendi Görev API'nizi oluşturun

TensorFlow Lite Görev Kitaplığı, TensorFlow'u soyutlayan aynı altyapının üzerinde önceden oluşturulmuş yerel/Android/iOS API'leri sağlar. Modeliniz mevcut Görev kitaplıkları tarafından desteklenmiyorsa özelleştirilmiş API'ler oluşturmak için Görev API altyapısını genişletebilirsiniz.

Genel Bakış

Görev API altyapısı iki katmanlı bir yapıya sahiptir: yerel TFLite çalışma zamanını kapsayan alt C++ katmanı ve JNI veya yerel sarmalayıcı aracılığıyla C++ katmanıyla iletişim kuran üst Java/ObjC katmanı.

Tüm TensorFlow mantığını yalnızca C++'da uygulamak maliyeti en aza indirir, çıkarım performansını en üst düzeye çıkarır ve platformlar arasındaki genel iş akışını basitleştirir.

Bir Görev sınıfı oluşturmak için BaseTaskApi'yi , TFLite model arayüzü ile Görev API arayüzü arasında dönüştürme mantığı sağlayacak şekilde genişletin, ardından karşılık gelen API'leri oluşturmak için Java/ObjC yardımcı programlarını kullanın. Tüm TensorFlow ayrıntıları gizlenmiş olduğundan, TFLite modelini herhangi bir makine öğrenimi bilgisine ihtiyaç duymadan uygulamalarınızda dağıtabilirsiniz.

TensorFlow Lite, en popüler Vision ve NLP görevleri için önceden oluşturulmuş bazı API'ler sağlar. Görev API altyapısını kullanarak diğer görevler için kendi API'lerinizi oluşturabilirsiniz.

prebuilt_task_apis
Şekil 1. Önceden oluşturulmuş Görev API'leri

Görev API altyapısıyla kendi API'nizi oluşturun

C++ API'si

Tüm TFLite ayrıntıları yerel API'de uygulanır. Fabrika işlevlerinden birini kullanarak bir API nesnesi oluşturun ve arayüzde tanımlanan işlevleri çağırarak model sonuçlarını alın.

Örnek kullanım

İşte MobileBert için C++ BertQuestionAnswerer kullanıldığı bir örnek.

  char kBertModelPath[] = "path/to/model.tflite";
  // Create the API from a model file
  std::unique_ptr<BertQuestionAnswerer> question_answerer =
      BertQuestionAnswerer::CreateFromFile(kBertModelPath);

  char kContext[] = ...; // context of a question to be answered
  char kQuestion[] = ...; // question to be answered
  // ask a question
  std::vector<QaAnswer> answers = question_answerer.Answer(kContext, kQuestion);
  // answers[0].text is the best answer

API'yi oluşturma

native_task_api
Şekil 2. Yerel Görev API'si

Bir API nesnesi oluşturmak için BaseTaskApi genişleterek aşağıdaki bilgileri sağlamanız gerekir.

  • API G/Ç'sini belirleyin - API'niz farklı platformlarda benzer giriş/çıkışları göstermelidir. örneğin BertQuestionAnswerer girdi olarak iki dizgeyi (std::string& context, std::string& question) alır ve olası yanıt ve olasılıkların bir vektörünü std::vector<QaAnswer> olarak çıkarır. Bu, BaseTaskApi şablon parametresinde karşılık gelen türleri belirterek yapılır. Belirtilen şablon parametreleriyle BaseTaskApi::Infer işlevi doğru giriş/çıkış türlerine sahip olacaktır. Bu işlev doğrudan API istemcileri tarafından çağrılabilir, ancak onu modele özgü bir işlevin (bu durumda BertQuestionAnswerer::Answer içine sarmak iyi bir uygulamadır.

    class BertQuestionAnswerer : public BaseTaskApi<
                                  std::vector<QaAnswer>, // OutputType
                                  const std::string&, const std::string& // InputTypes
                                  > {
      // Model specific function delegating calls to BaseTaskApi::Infer
      std::vector<QaAnswer> Answer(const std::string& context, const std::string& question) {
        return Infer(context, question).value();
      }
    }
    
  • API I/O ile modelin giriş/çıkış tensörü arasında dönüşüm mantığını sağlayın - Belirlenen giriş ve çıkış türleri ile alt sınıfların ayrıca BaseTaskApi::Preprocess ve BaseTaskApi::Postprocess yazılan işlevlerini uygulaması gerekir. İki işlev, TFLite FlatBuffer giriş ve çıkış sağlar. Alt sınıf, API I/O'dan I/O tensörlerine değer atamaktan sorumludur. BertQuestionAnswerer tam uygulama örneğine bakın.

    class BertQuestionAnswerer : public BaseTaskApi<
                                  std::vector<QaAnswer>, // OutputType
                                  const std::string&, const std::string& // InputTypes
                                  > {
      // Convert API input into tensors
      absl::Status BertQuestionAnswerer::Preprocess(
        const std::vector<TfLiteTensor*>& input_tensors, // input tensors of the model
        const std::string& context, const std::string& query // InputType of the API
      ) {
        // Perform tokenization on input strings
        ...
        // Populate IDs, Masks and SegmentIDs to corresponding input tensors
        PopulateTensor(input_ids, input_tensors[0]);
        PopulateTensor(input_mask, input_tensors[1]);
        PopulateTensor(segment_ids, input_tensors[2]);
        return absl::OkStatus();
      }
    
      // Convert output tensors into API output
      StatusOr<std::vector<QaAnswer>> // OutputType
      BertQuestionAnswerer::Postprocess(
        const std::vector<const TfLiteTensor*>& output_tensors, // output tensors of the model
      ) {
        // Get start/end logits of prediction result from output tensors
        std::vector<float> end_logits;
        std::vector<float> start_logits;
        // output_tensors[0]: end_logits FLOAT[1, 384]
        PopulateVector(output_tensors[0], &end_logits);
        // output_tensors[1]: start_logits FLOAT[1, 384]
        PopulateVector(output_tensors[1], &start_logits);
        ...
        std::vector<QaAnswer::Pos> orig_results;
        // Look up the indices from vocabulary file and build results
        ...
        return orig_results;
      }
    }
    
  • API'nin fabrika işlevlerini oluşturun - tflite::Interpreter başlatmak için bir model dosyası ve bir OpResolver gereklidir. TaskAPIFactory BaseTaskApi örnekleri oluşturmak için yardımcı işlevler sağlar.

    Ayrıca modelle ilişkili tüm dosyaları da sağlamanız gerekir. örneğin, BertQuestionAnswerer tokenizer'ın kelime dağarcığı için ek bir dosyası da olabilir.

    class BertQuestionAnswerer : public BaseTaskApi<
                                  std::vector<QaAnswer>, // OutputType
                                  const std::string&, const std::string& // InputTypes
                                  > {
      // Factory function to create the API instance
      StatusOr<std::unique_ptr<QuestionAnswerer>>
      BertQuestionAnswerer::CreateBertQuestionAnswerer(
          const std::string& path_to_model, // model to passed to TaskApiFactory
          const std::string& path_to_vocab  // additional model specific files
      ) {
        // Creates an API object by calling one of the utils from TaskAPIFactory
        std::unique_ptr<BertQuestionAnswerer> api_to_init;
        ASSIGN_OR_RETURN(
            api_to_init,
            core::TaskAPIFactory::CreateFromFile<BertQuestionAnswerer>(
                path_to_model,
                absl::make_unique<tflite::ops::builtin::BuiltinOpResolver>(),
                kNumLiteThreads));
    
        // Perform additional model specific initializations
        // In this case building a vocabulary vector from the vocab file.
        api_to_init->InitializeVocab(path_to_vocab);
        return api_to_init;
      }
    }
    

Android API'si

Java/Kotlin arayüzünü tanımlayarak ve mantığı JNI aracılığıyla C++ katmanına devrederek Android API'leri oluşturun. Android API, öncelikle yerel API'nin oluşturulmasını gerektirir.

Örnek kullanım

İşte MobileBert için Java BertQuestionAnswerer kullanan bir örnek.

  String BERT_MODEL_FILE = "path/to/model.tflite";
  String VOCAB_FILE = "path/to/vocab.txt";
  // Create the API from a model file and vocabulary file
    BertQuestionAnswerer bertQuestionAnswerer =
        BertQuestionAnswerer.createBertQuestionAnswerer(
            ApplicationProvider.getApplicationContext(), BERT_MODEL_FILE, VOCAB_FILE);

  String CONTEXT = ...; // context of a question to be answered
  String QUESTION = ...; // question to be answered
  // ask a question
  List<QaAnswer> answers = bertQuestionAnswerer.answer(CONTEXT, QUESTION);
  // answers.get(0).text is the best answer

API'yi oluşturma

android_task_api
Şekil 3. Android Görev API'si

Yerel API'lere benzer şekilde, bir API nesnesi oluşturmak için istemcinin, tüm Java Görev API'leri için JNI işlemlerini sağlayan BaseTaskApi genişleterek aşağıdaki bilgileri sağlaması gerekir.

  • API I/O'yu belirleyin - Bu genellikle yerel arayüzleri yansıtır. örneğin BertQuestionAnswerer (String context, String question) girdi olarak alır ve List<QaAnswer> çıktısını verir. Uygulama, C++'dan döndürülen işaretçi olan long nativeHandle ek parametresine sahip olması dışında benzer imzaya sahip özel bir yerel işlevi çağırır.

    class BertQuestionAnswerer extends BaseTaskApi {
      public List<QaAnswer> answer(String context, String question) {
        return answerNative(getNativeHandle(), context, question);
      }
    
      private static native List<QaAnswer> answerNative(
                                            long nativeHandle, // C++ pointer
                                            String context, String question // API I/O
                                           );
    
    }
    
  • API'nin fabrika işlevlerini oluşturun - Bu aynı zamanda yerel fabrika işlevlerini de yansıtır, ancak Android fabrika işlevlerinin de dosya erişimi için Context alması gerekir. Uygulama, karşılık gelen C++ API nesnesini oluşturmak ve işaretçisini BaseTaskApi yapıcısına iletmek için TaskJniUtils yardımcı programlardan birini çağırır.

      class BertQuestionAnswerer extends BaseTaskApi {
        private static final String BERT_QUESTION_ANSWERER_NATIVE_LIBNAME =
                                                  "bert_question_answerer_jni";
    
        // Extending super constructor by providing the
        // native handle(pointer of corresponding C++ API object)
        private BertQuestionAnswerer(long nativeHandle) {
          super(nativeHandle);
        }
    
        public static BertQuestionAnswerer createBertQuestionAnswerer(
                                            Context context, // Accessing Android files
                                            String pathToModel, String pathToVocab) {
          return new BertQuestionAnswerer(
              // The util first try loads the JNI module with name
              // BERT_QUESTION_ANSWERER_NATIVE_LIBNAME, then opens two files,
              // converts them into ByteBuffer, finally ::initJniWithBertByteBuffers
              // is called with the buffer for a C++ API object pointer
              TaskJniUtils.createHandleWithMultipleAssetFilesFromLibrary(
                  context,
                  BertQuestionAnswerer::initJniWithBertByteBuffers,
                  BERT_QUESTION_ANSWERER_NATIVE_LIBNAME,
                  pathToModel,
                  pathToVocab));
        }
    
        // modelBuffers[0] is tflite model file buffer, and modelBuffers[1] is vocab file buffer.
        // returns C++ API object pointer casted to long
        private static native long initJniWithBertByteBuffers(ByteBuffer... modelBuffers);
    
      }
    
  • Yerel işlevler için JNI modülünü uygulayın - Tüm Java yerel yöntemleri, JNI modülünden karşılık gelen bir yerel işlevin çağrılması yoluyla uygulanır. Fabrika işlevleri yerel bir API nesnesi oluşturur ve işaretçisini uzun bir tür olarak Java'ya döndürür. Daha sonraki Java API çağrılarında, uzun tür işaretçisi JNI'ya geri iletilir ve yerel API nesnesine geri dönüştürülür. Yerel API sonuçları daha sonra tekrar Java sonuçlarına dönüştürülür.

    Örneğin bert_question_answerer_jni bu şekilde uygulanır.

      // Implements BertQuestionAnswerer::initJniWithBertByteBuffers
      extern "C" JNIEXPORT jlong JNICALL
      Java_org_tensorflow_lite_task_text_qa_BertQuestionAnswerer_initJniWithBertByteBuffers(
          JNIEnv* env, jclass thiz, jobjectArray model_buffers) {
        // Convert Java ByteBuffer object into a buffer that can be read by native factory functions
        absl::string_view model =
            GetMappedFileBuffer(env, env->GetObjectArrayElement(model_buffers, 0));
    
        // Creates the native API object
        absl::StatusOr<std::unique_ptr<QuestionAnswerer>> status =
            BertQuestionAnswerer::CreateFromBuffer(
                model.data(), model.size());
        if (status.ok()) {
          // converts the object pointer to jlong and return to Java.
          return reinterpret_cast<jlong>(status->release());
        } else {
          return kInvalidPointer;
        }
      }
    
      // Implements BertQuestionAnswerer::answerNative
      extern "C" JNIEXPORT jobject JNICALL
      Java_org_tensorflow_lite_task_text_qa_BertQuestionAnswerer_answerNative(
      JNIEnv* env, jclass thiz, jlong native_handle, jstring context, jstring question) {
      // Convert long to native API object pointer
      QuestionAnswerer* question_answerer = reinterpret_cast<QuestionAnswerer*>(native_handle);
    
      // Calls the native API
      std::vector<QaAnswer> results = question_answerer->Answer(JStringToString(env, context),
                                             JStringToString(env, question));
    
      // Converts native result(std::vector<QaAnswer>) to Java result(List<QaAnswerer>)
      jclass qa_answer_class =
        env->FindClass("org/tensorflow/lite/task/text/qa/QaAnswer");
      jmethodID qa_answer_ctor =
        env->GetMethodID(qa_answer_class, "<init>", "(Ljava/lang/String;IIF)V");
      return ConvertVectorToArrayList<QaAnswer>(
        env, results,
        [env, qa_answer_class, qa_answer_ctor](const QaAnswer& ans) {
          jstring text = env->NewStringUTF(ans.text.data());
          jobject qa_answer =
              env->NewObject(qa_answer_class, qa_answer_ctor, text, ans.pos.start,
                             ans.pos.end, ans.pos.logit);
          env->DeleteLocalRef(text);
          return qa_answer;
        });
      }
    
      // Implements BaseTaskApi::deinitJni by delete the native object
      extern "C" JNIEXPORT void JNICALL Java_task_core_BaseTaskApi_deinitJni(
          JNIEnv* env, jobject thiz, jlong native_handle) {
        delete reinterpret_cast<QuestionAnswerer*>(native_handle);
      }
    

iOS API'si

Yerel bir API nesnesini bir ObjC API nesnesine sararak iOS API'leri oluşturun. Oluşturulan API nesnesi ObjC veya Swift'de kullanılabilir. iOS API, önce yerel API'nin oluşturulmasını gerektirir.

Örnek kullanım

İşte Swift'de MobileBert için ObjC TFLBertQuestionAnswerer kullanan bir örnek.

  static let mobileBertModelPath = "path/to/model.tflite";
  // Create the API from a model file and vocabulary file
  let mobileBertAnswerer = TFLBertQuestionAnswerer.mobilebertQuestionAnswerer(
      modelPath: mobileBertModelPath)

  static let context = ...; // context of a question to be answered
  static let question = ...; // question to be answered
  // ask a question
  let answers = mobileBertAnswerer.answer(
      context: TFLBertQuestionAnswererTest.context, question: TFLBertQuestionAnswererTest.question)
  // answers.[0].text is the best answer

API'yi oluşturma

ios_task_api
Şekil 4. iOS Görev API'si

iOS API, yerel API'nin üstünde basit bir ObjC sarmalayıcıdır. Aşağıdaki adımları izleyerek API'yi oluşturun:

  • ObjC sarmalayıcısını tanımlayın - Bir ObjC sınıfını tanımlayın ve uygulamaları karşılık gelen yerel API nesnesine devredin. Swift'in C++ ile birlikte çalışamaması nedeniyle yerel bağımlılıkların yalnızca .mm dosyasında görünebileceğini unutmayın.

    • .h dosyası
      @interface TFLBertQuestionAnswerer : NSObject
    
      // Delegate calls to the native BertQuestionAnswerer::CreateBertQuestionAnswerer
      + (instancetype)mobilebertQuestionAnswererWithModelPath:(NSString*)modelPath
                                                    vocabPath:(NSString*)vocabPath
          NS_SWIFT_NAME(mobilebertQuestionAnswerer(modelPath:vocabPath:));
    
      // Delegate calls to the native BertQuestionAnswerer::Answer
      - (NSArray<TFLQAAnswer*>*)answerWithContext:(NSString*)context
                                         question:(NSString*)question
          NS_SWIFT_NAME(answer(context:question:));
    }
    
    • .mm dosyası
      using BertQuestionAnswererCPP = ::tflite::task::text::BertQuestionAnswerer;
    
      @implementation TFLBertQuestionAnswerer {
        // define an iVar for the native API object
        std::unique_ptr<QuestionAnswererCPP> _bertQuestionAnswerwer;
      }
    
      // Initialize the native API object
      + (instancetype)mobilebertQuestionAnswererWithModelPath:(NSString *)modelPath
                                              vocabPath:(NSString *)vocabPath {
        absl::StatusOr<std::unique_ptr<QuestionAnswererCPP>> cQuestionAnswerer =
            BertQuestionAnswererCPP::CreateBertQuestionAnswerer(MakeString(modelPath),
                                                                MakeString(vocabPath));
        _GTMDevAssert(cQuestionAnswerer.ok(), @"Failed to create BertQuestionAnswerer");
        return [[TFLBertQuestionAnswerer alloc]
            initWithQuestionAnswerer:std::move(cQuestionAnswerer.value())];
      }
    
      // Calls the native API and converts C++ results into ObjC results
      - (NSArray<TFLQAAnswer *> *)answerWithContext:(NSString *)context question:(NSString *)question {
        std::vector<QaAnswerCPP> results =
          _bertQuestionAnswerwer->Answer(MakeString(context), MakeString(question));
        return [self arrayFromVector:results];
      }
    }