יצירת Tasks API משלכם

ספריית המשימות של TensorFlow Lite מספקת גרסה מוכנה מראש ממשקי API של C++ , Android ו-iOS מעל אותה תשתית שמופשטת ב-TensorFlow. אפשר להרחיב את התשתית של Task API כדי ליצור ממשקי API מותאמים אישית אם המודל לא נתמך על ידי ספריות המשימה הקיימות.

סקירה כללית

לתשתית של Task API יש שתי שכבות: שכבת C++ התחתונה שכוללים את סביבת זמן הריצה של TFLite ואת השכבה העליונה Java/ObjC, מתקשר עם שכבת C++ דרך JNI או wrapper.

הטמעת כל הלוגיקה של TensorFlow ב-C++ בלבד מפחיתה את העלות וממקסמת את העלות מסיקה את הביצועים ומפשטת את תהליך העבודה הכולל בפלטפורמות השונות.

כדי ליצור מחלקה של משימות, מרחיבים את הקטע BaseTaskApi לספק לוגיקת המרה בין הממשק של מודל TFLite לבין Task API ולאחר מכן להשתמש בכלי עזר Java/ObjC כדי ליצור ממשקי API מתאימים. ב- כל הפרטים של TensorFlow מוסתרים, אפשר לפרוס את מודל ה-TFLite באפליקציות שלך ללא ידע בלמידת מכונה.

ב-TensorFlow Lite יש כמה ממשקי API מוכנים מראש משימות ראייה ו-NLP. אפשר ליצור את ממשקי ה-API שלכם למשימות אחרות באמצעות התשתית של Task API.

prebuilt_task_apis
איור 1. ממשקי API מוכנים מראש למשימות

איך בונים API משלכם באמצעות Task API Infra

API של C++

כל פרטי TFLite מוטמעים ב-API של C++. יצירת אובייקט API באמצעות באמצעות אחת מהפונקציות במפעל כדי לקבל תוצאות של המודל באמצעות קריאה לפונקציות שמוגדר בממשק.

דוגמאות לשימוש

הנה דוגמה באמצעות הלחצן ++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

פיתוח ה-API

native_task_api
איור 2. ממשק API של Native Task

כדי לבנות אובייקט API,צריך לספק את הפרטים הבאים באמצעות הרחבה BaseTaskApi

  • קביעת הקלט/פלט של ה-API – ה-API צריך לחשוף קלט/פלט דומה בפלטפורמות שונות. לדוגמה BertQuestionAnswerer לוקח שתי מחרוזות (std::string& context, std::string& question) כקלט וכפלט של תשובה אפשרית והסתברויות בתור std::vector<QaAnswer>. הזה נעשה על ידי ציון הסוגים המתאימים ב-BaseTaskApi פרמטר תבנית אחרי שהפרמטרים של התבנית צוינו, BaseTaskApi::Infer יקבלו את סוגי הקלט/פלט הנכונים. הפונקציה הזו יכולה להיות ללקוחות API שנקראים ישירות, אבל כדאי לעסוק את התהליך פונקציה ספציפית למודל, במקרה הזה, 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) של API לבין רכיב הקלט/פלט של model – כשמציינים סוגי קלט ופלט, גם מחלקות המשנה צריך להטמיע את הפונקציות המוקלדות BaseTaskApi::Preprocess וגם BaseTaskApi::Postprocess. שתי הפונקציות מספקות קלט וגם פלטים מ-TFLite FlatBuffer. המחלקה המשנית אחראית להקצאה ממקודדי הקלט/פלט של API לקלט/פלט (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;
      }
    }
    
  • יצירת פונקציות יצרן של ה-API – קובץ מודל 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;
      }
    }
    

ממשק API של Android

ליצור ממשקי API של Android על ידי הגדרת ממשק Java/Kotlin והאצלת הלוגיקה לשכבת C++ דרך JNI. כדי להשתמש ב-Android API, צריך קודם לבנות 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

פיתוח ה-API

android_task_api
איור 3. ממשק API של Android Task

בדומה ל-Native APIs, כדי לבנות אובייקט API, הלקוח צריך לספק את את המידע הבא באמצעות הרחבה BaseTaskApi שמספק טיפולי JNI לכל ממשקי ה-API של Java Task.

  • קביעת ה-I/O של ה-API – האפשרות הזו בדרך כלל משקף את הממשקים המקוריים. למשל BertQuestionAnswerer לוקח את (String context, String question) כקלט ויוצר את הפלט List<QaAnswer>. ההטמעה קוראת ל-Native נייטיב פרטי עם חתימה דומה, אבל יש בה פרמטר נוסף 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
                                           );
    
    }
    
  • יצירת פונקציות המקוריות של ה-API – הנתונים האלה ישקף גם את ה-Native של היצרן. קיימות, פרט לפונקציות של Android להגדרות המקוריות. Context לגישה לקבצים. ההטמעה קוראת לאחת מהתוכנות TaskJniUtils כדי ליצור את האובייקט התואם של C++ API ולהעביר את הסמן שלו BaseTaskApi constructor.

      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 של מודל טרנספורמר. הפונקציות במפעל ייצרו אובייקט API מקורי ותחזירו אותו שהוא טיפוס ארוך ל-Java. בקריאות מאוחרות יותר ל-Java API, הקריאות מצביע סוג מועבר חזרה ל-JNI ומועבר חזרה לאובייקט ה-API המקורי. לאחר מכן, התוצאות של ה-API המקורי מומרות בחזרה לתוצאות ב-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);
      }
    

API ל-iOS

כדי ליצור ממשקי API ל-iOS, צריך לתחום את אובייקט ה-API המקורי באובייקט ObjC API. אפשר להשתמש באובייקט ה-API שנוצר ב-ObjC או ב-Swift. ב-iOS API נדרש את ה-API המקורי שצריך לבנות קודם.

דוגמאות לשימוש

הנה דוגמה באמצעות ObjC 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

פיתוח ה-API

ios_task_api
איור 4. ממשק API למשימות ב-iOS

iOS API הוא wrapper פשוט של ObjC מעל API מקורי. פיתוח ה-API באמצעות באמצעות השלבים הבאים:

  • הגדרת wrapper של ObjC – הגדרת מחלקה ObjC והאצלת סמכויות הטמעות לאובייקט ה-API המקורי המתאים. סימון המודעה המותאמת יחסי התלות יכולים להופיע רק בקובץ .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];
      }
    }