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

TensorFlow Lite टास्क लाइब्रेरी, पहले से बनी हुई है C++, Android, और iOS एपीआई एक ही इन्फ़्रास्ट्रक्चर के ऊपर हैं जो एब्सट्रैक्ट करता है TensorFlow. पसंद के मुताबिक एपीआई बनाने के लिए, Task API इन्फ़्रास्ट्रक्चर को बढ़ाया जा सकता है अगर आपका मॉडल मौजूदा टास्क लाइब्रेरी पर काम नहीं करता है.

खास जानकारी

Task API के इन्फ़्रास्ट्रक्चर में दो लेयर वाली स्ट्रक्चर होती है: सबसे नीचे वाली C++ लेयर TFLite रनटाइम और शीर्ष Java/ObjC लेयर को इनकैप्सुलेट करना जो यह C++ लेयर के साथ JNI या रैपर के ज़रिए संपर्क करता है.

सिर्फ़ C++ में TensorFlow का इस्तेमाल करने से, लागत कम हो जाती है और परफ़ॉर्मेंस का अनुमान लगाता है और सभी प्लैटफ़ॉर्म पर वर्कफ़्लो को आसान बनाता है.

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

TensorFlow Lite, सबसे लोकप्रिय कॉन्टेंट के लिए पहले से बने कुछ एपीआई उपलब्ध कराता है विज़न और एनएलपी के टास्क. आप बना सकते हैं Task API इन्फ़्रास्ट्रक्चर का इस्तेमाल करके, अन्य टास्क के लिए एपीआई भी जोड़े जा सकते हैं.

prebuilt_task_apis
पहली इमेज: पहले से बनाए गए टास्क एपीआई

Task API इन्फ़्रा की मदद से अपना एपीआई बनाएं

C++ एपीआई

TFLite की सारी जानकारी, C++ एपीआई में लागू की गई है. इसके हिसाब से एपीआई ऑब्जेक्ट बनाएं कार के किसी एक फ़ंक्शन का इस्तेमाल करके और फ़ंक्शन कॉल करके मॉडल से जुड़े नतीजे पाएं इंटरफ़ेस में परिभाषित किया गया है.

इस्तेमाल के उदाहरण

यहां C++ का इस्तेमाल करके एक उदाहरण दिया गया है BertQuestionAnswerer इसके लिए 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

एपीआई बनाना

native_task_api
चित्र 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();
      }
    }
    
  • API I/O और इनपुट/आउटपुट टेंसर के बीच कन्वर्ज़न लॉजिक दें मॉडल - इनपुट और आउटपुट टाइप के साथ सब-क्लास को टाइप किए गए फ़ंक्शन लागू करें BaseTaskApi::Preprocess और BaseTaskApi::Postprocess. दोनों फ़ंक्शन से आपको इनपुट और आउटपुट TFLite FlatBuffer से. सब-क्लास, API 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;
      }
    }
    
  • एपीआई के फ़ैक्ट्री फ़ंक्शन बनाना - मॉडल फ़ाइल और OpResolver को शुरू करने के लिए tflite::Interpreter. 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;
      }
    }
    

Android एपीआई

Java/Kotlin इंटरफ़ेस तय करके और लॉजिक सौंपकर, Android एपीआई बनाएं C++ लेयर से JNI के ज़रिए किया जा सकता है. Android API के लिए, सबसे पहले नेटिव एपीआई बनाना ज़रूरी है.

इस्तेमाल के उदाहरण

यहां Java का इस्तेमाल करने का एक उदाहरण दिया गया है BertQuestionAnswerer इसके लिए 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

एपीआई बनाना

android_task_api
चित्र 3. Android टास्क एपीआई

नेटिव एपीआई की तरह ही, एपीआई ऑब्जेक्ट बनाने के लिए, क्लाइंट को नीचे दी गई जानकारी को BaseTaskApi जो सभी Java टास्क एपीआई के लिए, JNI हैंडलिंग उपलब्ध कराती है.

  • एपीआई 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
                                           );
    
    }
    
  • एपीआई के फ़ैक्ट्री फ़ंक्शन बनाएं - यह स्थानीय फ़ैक्ट्री की भी जानकारी देता है Android फ़ैक्ट्री फ़ंक्शन को छोड़कर, दूसरे फ़ंक्शन को Context फ़ाइल ऐक्सेस करने के लिए. लागू करने पर, TaskJniUtils संबंधित C++ API ऑब्जेक्ट बनाने और उसके पॉइंटर को 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);
    
      }
    
  • नेटिव फ़ंक्शन के लिए JNI मॉड्यूल लागू करें - Java के सभी नेटिव तरीके JNI से संबंधित नेटिव फ़ंक्शन को कॉल करके लागू किया जाता है मॉड्यूल का इस्तेमाल नहीं किया जाएगा. फ़ैक्ट्री फ़ंक्शन, नेटिव एपीआई ऑब्जेक्ट बनाएंगे और लंबे टाइप के रूप में इसका पॉइंटर है. Java API को बाद में की जाने वाली कॉल में, टाइप पॉइंटर को वापस JNI को पास करके, नेटिव एपीआई ऑब्जेक्ट पर वापस कास्ट किया जाता है. इसके बाद, नेटिव एपीआई के नतीजों को वापस Java के नतीजों में बदल दिया जाता है.

    उदाहरण के लिए, 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 एपीआई

नेटिव एपीआई ऑब्जेक्ट को ऑब्जेसी एपीआई ऑब्जेक्ट में रैप करके iOS एपीआई बनाएं. कॉन्टेंट बनाने बनाए गए एपीआई ऑब्जेक्ट का इस्तेमाल,objC या Swift में से किसी एक में किया जा सकता है. iOS API के लिए ज़रूरी है कि पहले बनाया जाने वाला नेटिव एपीआई.

इस्तेमाल के उदाहरण

यहां ऑब्जेसी का इस्तेमाल करके एक उदाहरण दिया गया है TFLBertQuestionAnswerer MobileBert के लिए स्विफ़्ट में.

  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
चौथी इमेज: iOS टास्क एपीआई

iOS API, नेटिव एपीआई के ऊपर एक सामान्य ऑब्जेसी रैपर है. एपीआई बनाएं इसके लिए, यह तरीका अपनाएं:

  • ObjC रैपर तय करें - ऑब्जेसी क्लास तय करें और संबंधित नेटिव एपीआई ऑब्जेक्ट को लागू करना. नेटिव लेआउट चुनें डिपेंडेंसी किसी .mm फ़ाइल में सिर्फ़ तब दिख सकती हैं, जब Swift की C++ के साथ इंटरऑप करें.

    • .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:));
    }
    
    • .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];
      }
    }