Utwórz własny interfejs Task API

Biblioteka zadań TensorFlow Lite zawiera gotowe Interfejsy API w językach C++ oraz na Androida i iOS oparte na tej samej infrastrukturze, TensorFlow. Infrastrukturę interfejsu Task API można rozszerzyć, aby tworzyć niestandardowe interfejsy API jeśli model nie jest obsługiwany przez istniejące biblioteki zadań.

Omówienie

Infrastruktura interfejsu Task API ma strukturę dwuwarstwową: dolną warstwę C++ obejmujące środowisko wykonawcze TFLite i najważniejszą warstwę Java/ObjC, komunikuje się z warstwą C++ za pomocą JNI lub opakowania.

Wdrożenie całej logiki TensorFlow tylko w C++ pozwala zminimalizować koszty, zmaksymalizować wnioskowania na temat skuteczności i upraszczają ogólny przepływ pracy na różnych platformach.

Aby utworzyć klasę na stronie Task, rozwiń BaseTaskApi do udostępniania logiki konwersji między interfejsem modelu TFLite a interfejsem Task API a potem za pomocą narzędzi Java/ObjC utwórz odpowiednie interfejsy API. Na wszystkie szczegóły TensorFlow są ukryte, możesz wdrożyć model TFLite w swoich aplikacjach bez wiedzy systemów uczących się.

TensorFlow Lite udostępnia kilka gotowych interfejsów API Zadania związane z widocznością i NLP. Możesz tworzyć własne interfejsy API do innych zadań przy użyciu infrastruktury interfejsu Task API.

prebuilt_task_apis
Rysunek 1. Gotowe interfejsy API zadań

Utwórz własny interfejs API za pomocą infrastruktury interfejsu Task API

Interfejs API C++

Wszystkie szczegóły TFLite są zaimplementowane w interfejsie API C++. Utwórz obiekt interfejsu API za pomocą za pomocą jednej z funkcji fabrycznych i uzyskać wyniki modelu przez wywołanie funkcji zdefiniowane w interfejsie.

Przykładowe zastosowanie

Oto przykład użycia języka C++ BertQuestionAnswerer w przypadku MobileBert.

  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

Tworzenie interfejsu API

native_task_api
Rysunek 2. Native Task API

Aby utworzyć obiekt interfejsu API,musisz podać poniższe informacje przez rozszerzenie BaseTaskApi

  • Określ wejścia/wyjścia interfejsu API – interfejs API powinien udostępniać podobne dane wejściowe/wyjściowe. na różnych platformach. np. BertQuestionAnswerer ma dwa ciągi (std::string& context, std::string& question) jako dane wejściowe i zwraca wektor możliwych odpowiedzi i prawdopodobieństw jako std::vector<QaAnswer>. Ten trzeba określić odpowiednie typy w funkcji BaseTaskApi parametru szablonu. Po określeniu parametrów szablonu narzędzie BaseTaskApi::Infer ma prawidłowy typ wejścia/wyjścia. Funkcja ta może być wywoływane bezpośrednio przez klientów interfejsu API, ale dobrze jest je umieszczać wewnątrz funkcję właściwą dla modelu, w tym przypadku jest to BertQuestionAnswerer::Answer.

    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();
      }
    }
    
  • Zapewnij logikę konwersji między interfejsami API I/O a tensorem wejścia/wyjścia interfejsu API model – po określeniu typów danych wejściowych i wyjściowych podklasy muszą też implementować wpisywane funkcje BaseTaskApi::Preprocess. oraz BaseTaskApi::Postprocess Dwie funkcje zapewniają dane wejściowe oraz dane wyjściowe od TFLite FlatBuffer. Podklasa odpowiada za przypisywanie od tensorów wejścia-wyjścia interfejsu API. Zobacz pełną implementację przykład w BertQuestionAnswerer

    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;
      }
    }
    
  • Utwórz funkcje fabryczne interfejsu API – plik modelu oraz OpResolver. są niezbędne do inicjowania tflite::Interpreter TaskAPIFactory udostępnia funkcje narzędziowe do tworzenia instancji BaseTaskApi.

    Musisz też dostarczyć wszystkie pliki powiązane z modelem. np. BertQuestionAnswerer może też mieć dodatkowy plik swojego tokenizatora terminarza.

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

Interfejs API Androida

Utwórz interfejsy API Androida, definiując interfejs Java/Kotlin i przekazując logikę do warstwy C++ za pomocą JNI. Interfejs Android API wymaga wcześniejszego utworzenia natywnego interfejsu API.

Przykładowe zastosowanie

Oto przykład użycia języka Java BertQuestionAnswerer w przypadku MobileBert.

  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

Tworzenie interfejsu API

android_task_api
Rysunek 3. Interfejs Android Task API

Podobnie jak w przypadku natywnych interfejsów API, aby utworzyć obiekt API, klient musi udostępnić następujące informacje, rozszerzając BaseTaskApi który zapewnia obsługę JNI dla wszystkich interfejsów API zadań Java.

  • Określ wejścia/wyjścia interfejsu API – zazwyczaj jest to odzwierciedlenie natywnych interfejsów. np. BertQuestionAnswerer pobiera (String context, String question) jako dane wejściowe i zwraca List<QaAnswer>. Implementacja wywołuje prywatną reklamę natywną o podobnym podpisie, tyle że ma dodatkowy parametr long nativeHandle, który jest wskaźnikiem zwracanym z języka C++.

    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
                                           );
    
    }
    
  • Utwórz funkcje fabryczne interfejsu API – jest to również kopia natywna w fabryce. za wyjątkiem funkcji fabrycznych Androida, Context. w celu uzyskania dostępu do plików. Implementacja wywołuje jedno z narzędzi TaskJniUtils do utworzenia odpowiedniego obiektu interfejsu API C++ i przekazania jego wskaźnika do funkcji BaseTaskApi.

      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);
    
      }
    
  • Implementacja modułu JNI dla funkcji natywnych – wszystkie natywne metody w Javie są implementowane przez wywołanie odpowiedniej funkcji natywnej z JNI . Funkcje fabryki utworzą natywny obiekt interfejsu API i zwrócą jego wskaźnik jako typ długiego kodu Java. W późniejszych wywołaniach interfejsu Java API długi ciąg wskaźnik typu jest przekazywany z powrotem do JNI i rzutowany z powrotem do natywnego obiektu API. Wyniki natywnego interfejsu API są następnie konwertowane z powrotem na wyniki w języku Java.

    Tak na przykład: bert_question_answerer_jni .

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

Interfejs API iOS

Twórz interfejsy API iOS, opakowując natywny obiekt API w obiekt ObjC API. utworzonego obiektu API można używać w ObjC lub Swift. Interfejs API iOS wymaga natywny interfejs API.

Przykładowe zastosowanie

Oto przykład użycia funkcji ObjC TFLBertQuestionAnswerer w przypadku platformy MobileBert w języku Swift.

  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

Tworzenie interfejsu API

ios_task_api
Rysunek 4. iOS Task API

iOS API to prosty kod ObjC, który jest uzupełnieniem natywnego interfejsu API. Skompiluj interfejs API za pomocą wykonaj te czynności:

  • Zdefiniuj opakowanie ObjC – zdefiniuj klasę ObjC i przekaż do odpowiedniego natywnego obiektu interfejsu API. Pamiętaj, że w przypadku reklam natywnych mogą wystąpić tylko w pliku .mm, ponieważ Swift nie może i współpracę z C++.

    • Plik .h
      @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:));
    }
    
    • Plik .mm
      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];
      }
    }