अपना खुद का टास्क एपीआई बनाएं

TensorFlow लाइट टास्क लाइब्रेरी उसी बुनियादी ढांचे के शीर्ष पर पूर्वनिर्मित देशी/एंड्रॉइड/iOS एपीआई प्रदान करती है जो TensorFlow को सारगर्भित करती है। यदि आपका मॉडल मौजूदा टास्क लाइब्रेरी द्वारा समर्थित नहीं है, तो आप अनुकूलित एपीआई बनाने के लिए टास्क एपीआई बुनियादी ढांचे का विस्तार कर सकते हैं।

अवलोकन

टास्क एपीआई इंफ्रास्ट्रक्चर में दो-परत संरचना होती है: निचली C++ परत जो मूल TFLite रनटाइम को समाहित करती है और शीर्ष Java/ObjC परत जो JNI या मूल रैपर के माध्यम से C++ परत के साथ संचार करती है।

सभी TensorFlow तर्क को केवल C++ में लागू करने से लागत कम हो जाती है, अनुमान प्रदर्शन अधिकतम हो जाता है और सभी प्लेटफ़ॉर्म पर समग्र वर्कफ़्लो सरल हो जाता है।

टास्क क्लास बनाने के लिए, TFLite मॉडल इंटरफ़ेस और टास्क API इंटरफ़ेस के बीच रूपांतरण तर्क प्रदान करने के लिए BaseTaskApi का विस्तार करें, फिर संबंधित API बनाने के लिए Java/ObjC उपयोगिताओं का उपयोग करें। सभी TensorFlow विवरण छिपाकर, आप बिना किसी मशीन लर्निंग ज्ञान के अपने ऐप्स में TFLite मॉडल को तैनात कर सकते हैं।

TensorFlow Lite सबसे लोकप्रिय विज़न और NLP कार्यों के लिए कुछ पूर्वनिर्मित API प्रदान करता है। आप टास्क एपीआई इंफ्रास्ट्रक्चर का उपयोग करके अन्य कार्यों के लिए अपनी खुद की एपीआई बना सकते हैं।

प्रीबिल्ट_टास्क_एपिस
चित्र 1. पूर्वनिर्मित कार्य एपीआई

टास्क एपीआई इन्फ्रा के साथ अपनी खुद की एपीआई बनाएं

सी++ एपीआई

सभी TFLite विवरण मूल API में लागू किए गए हैं। फ़ैक्टरी फ़ंक्शंस में से किसी एक का उपयोग करके एक एपीआई ऑब्जेक्ट बनाएं और इंटरफ़ेस में परिभाषित फ़ंक्शंस को कॉल करके मॉडल परिणाम प्राप्त करें।

नमूना उपयोग

यहां MobileBert के लिए C++ BertQuestionAnswerer उपयोग करने का एक उदाहरण दिया गया है।

  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

एपीआई का निर्माण

नेटिव_टास्क_एपीआई
चित्र 2. मूल कार्य एपीआई

एपीआई ऑब्जेक्ट बनाने के लिए, आपको BaseTaskApi विस्तार करके निम्नलिखित जानकारी प्रदान करनी होगी

  • एपीआई I/O निर्धारित करें - आपके एपीआई को विभिन्न प्लेटफार्मों पर समान इनपुट/आउटपुट प्रदर्शित करना चाहिए। उदाहरण के लिए BertQuestionAnswerer इनपुट के रूप में दो स्ट्रिंग्स (std::string& context, std::string& question) लेता है और std::vector<QaAnswer> के रूप में संभावित उत्तर और संभावनाओं का एक वेक्टर आउटपुट करता है। यह BaseTaskApi के टेम्पलेट पैरामीटर में संबंधित प्रकार निर्दिष्ट करके किया जाता है। निर्दिष्ट टेम्पलेट पैरामीटर के साथ, BaseTaskApi::Infer फ़ंक्शन में सही इनपुट/आउटपुट प्रकार होंगे। इस फ़ंक्शन को सीधे एपीआई क्लाइंट द्वारा कॉल किया जा सकता है, लेकिन इसे मॉडल-विशिष्ट फ़ंक्शन के अंदर लपेटना एक अच्छा अभ्यास है, इस मामले में, 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();
      }
    }
    
  • मॉडल के एपीआई I/O और इनपुट/आउटपुट टेंसर के बीच रूपांतरण तर्क प्रदान करें - निर्दिष्ट इनपुट और आउटपुट प्रकारों के साथ, उपवर्गों को टाइप किए गए फ़ंक्शन BaseTaskApi::Preprocess और BaseTaskApi::Postprocess को भी लागू करने की आवश्यकता होती है। दो फ़ंक्शन TFLite FlatBuffer से इनपुट और आउटपुट प्रदान करते हैं। उपवर्ग एपीआई I/O से I/O टेंसर तक मान निर्दिष्ट करने के लिए जिम्मेदार है। 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;
      }
    }
    
  • एपीआई के फ़ैक्टरी फ़ंक्शंस बनाएं - tflite::Interpreter आरंभ करने के लिए एक मॉडल फ़ाइल और एक OpResolver आवश्यकता होती है। TaskAPIFactory BaseTaskApi उदाहरण बनाने के लिए उपयोगिता फ़ंक्शन प्रदान करता है।

    आपको मॉडल से जुड़ी कोई भी फाइल भी उपलब्ध करानी होगी। उदाहरण के लिए, BertQuestionAnswerer पास अपने टोकननाइज़र की शब्दावली के लिए एक अतिरिक्त फ़ाइल भी हो सकती है।

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

एंड्रॉइड एपीआई

जावा/कोटलिन इंटरफ़ेस को परिभाषित करके और जेएनआई के माध्यम से सी++ परत पर तर्क सौंपकर एंड्रॉइड एपीआई बनाएं। एंड्रॉइड एपीआई के लिए पहले मूल एपीआई का निर्माण करना आवश्यक है।

नमूना उपयोग

यहां MobileBert के लिए Java BertQuestionAnswerer का उपयोग करने का एक उदाहरण दिया गया है।

  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

एपीआई का निर्माण

android_task_api
चित्र 3. एंड्रॉइड टास्क एपीआई

नेटिव एपीआई के समान, एपीआई ऑब्जेक्ट बनाने के लिए, क्लाइंट को BaseTaskApi विस्तार करके निम्नलिखित जानकारी प्रदान करने की आवश्यकता होती है, जो सभी जावा टास्क एपीआई के लिए जेएनआई हैंडलिंग प्रदान करता है।

  • एपीआई I/O निर्धारित करें - यह आमतौर पर मूल इंटरफेस को प्रतिबिंबित करता है। उदाहरण के लिए BertQuestionAnswerer इनपुट के रूप में (String context, String question) लेता है और List<QaAnswer> आउटपुट करता है। कार्यान्वयन समान हस्ताक्षर के साथ एक निजी मूल फ़ंक्शन को कॉल करता है, सिवाय इसके कि इसमें एक अतिरिक्त पैरामीटर long nativeHandle है, जो 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
                                           );
    
    }
    
  • एपीआई के फ़ैक्टरी फ़ंक्शंस बनाएं - यह मूल फ़ैक्टरी फ़ंक्शंस को भी प्रतिबिंबित करता है, सिवाय इसके कि एंड्रॉइड फ़ैक्टरी फ़ंक्शंस को फ़ाइल एक्सेस के लिए Context लेने की भी आवश्यकता होती है। कार्यान्वयन संबंधित C++ API ऑब्जेक्ट बनाने और इसके पॉइंटर को BaseTaskApi कंस्ट्रक्टर को पास करने के लिए TaskJniUtils में उपयोगिताओं में से एक को कॉल करता है।

      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);
    
      }
    
  • मूल कार्यों के लिए जेएनआई मॉड्यूल को कार्यान्वित करें - सभी जावा मूल तरीकों को जेएनआई मॉड्यूल से संबंधित मूल फ़ंक्शन को कॉल करके कार्यान्वित किया जाता है। फ़ैक्टरी फ़ंक्शंस एक मूल एपीआई ऑब्जेक्ट बनाएगा और उसके पॉइंटर को लंबे प्रकार के रूप में जावा में लौटाएगा। जावा एपीआई के बाद के कॉल में, लंबे प्रकार के पॉइंटर को जेएनआई को वापस भेज दिया जाता है और मूल एपीआई ऑब्जेक्ट पर वापस डाल दिया जाता है। फिर मूल एपीआई परिणाम वापस जावा परिणामों में परिवर्तित हो जाते हैं।

    उदाहरण के लिए, 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);
      }
    

आईओएस एपीआई

एक मूल एपीआई ऑब्जेक्ट को ओबीजेसी एपीआई ऑब्जेक्ट में लपेटकर आईओएस एपीआई बनाएं। निर्मित एपीआई ऑब्जेक्ट का उपयोग ओबीजेसी या स्विफ्ट में किया जा सकता है। iOS API के लिए पहले मूल API बनाने की आवश्यकता होती है।

नमूना उपयोग

यहां स्विफ्ट में MobileBert के लिए ओबीजेसी TFLBertQuestionAnswerer उपयोग करने का एक उदाहरण दिया गया है।

  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

एपीआई का निर्माण

ios_task_api
चित्र 4. आईओएस टास्क एपीआई

आईओएस एपीआई मूल एपीआई के शीर्ष पर एक सरल ओबीजेसी रैपर है। नीचे दिए गए चरणों का पालन करके एपीआई बनाएं:

  • ओबीजेसी रैपर को परिभाषित करें - एक ओबीजेसी वर्ग को परिभाषित करें और कार्यान्वयन को संबंधित मूल एपीआई ऑब्जेक्ट को सौंपें। ध्यान दें कि स्विफ्ट की C++ के साथ इंटरऑप करने में असमर्थता के कारण मूल निर्भरताएँ केवल .mm फ़ाइल में दिखाई दे सकती हैं।

    • .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:));
    }
    
    • .मिमी फ़ाइल
      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];
      }
    }