สร้าง Task API ของคุณเอง

ไลบรารีงาน TensorFlow Lite มอบ API แบบเนทีฟ/Android/iOS ที่สร้างไว้ล่วงหน้าบนโครงสร้างพื้นฐานเดียวกันกับที่สรุป TensorFlow คุณสามารถขยายโครงสร้างพื้นฐาน Task API เพื่อสร้าง API แบบกำหนดเองได้ หากไลบรารีงานที่มีอยู่ไม่รองรับโมเดลของคุณ

ภาพรวม

โครงสร้างพื้นฐาน Task API มีโครงสร้าง 2 ชั้น ได้แก่ เลเยอร์ C++ ด้านล่างที่ห่อหุ้มรันไทม์ TFLite ดั้งเดิม และเลเยอร์ Java/ObjC บนสุดที่สื่อสารกับเลเยอร์ C++ ผ่าน JNI หรือ Wrapper ดั้งเดิม

การใช้ตรรกะ TensorFlow ทั้งหมดใน C++ เท่านั้นจะช่วยลดต้นทุน เพิ่มประสิทธิภาพการอนุมานให้สูงสุด และทำให้เวิร์กโฟลว์โดยรวมข้ามแพลตฟอร์มง่ายขึ้น

หากต้องการสร้างคลาสงาน ให้ขยาย BaseTaskApi เพื่อจัดเตรียมตรรกะการแปลงระหว่างอินเทอร์เฟซโมเดล TFLite และอินเทอร์เฟซ Task API จากนั้นใช้ยูทิลิตี้ Java/ObjC เพื่อสร้าง API ที่เกี่ยวข้อง ด้วยการซ่อนรายละเอียด TensorFlow ทั้งหมด คุณสามารถปรับใช้โมเดล TFLite ในแอปของคุณได้โดยไม่ต้องมีความรู้ด้านแมชชีนเลิร์นนิง

TensorFlow Lite มี API ที่สร้างไว้ล่วงหน้าสำหรับ งาน Vision และ NLP ยอดนิยม คุณสามารถสร้าง API ของคุณเองสำหรับงานอื่นๆ ได้โดยใช้โครงสร้างพื้นฐาน Task API

prebuild_task_apis
รูปที่ 1 Task API ที่สร้างไว้ล่วงหน้า

สร้าง API ของคุณเองด้วย Task API infra

C++ API

รายละเอียด TFLite ทั้งหมดถูกนำมาใช้ใน Native API สร้างออบเจ็กต์ 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 งานดั้งเดิม

หากต้องการสร้างออบเจ็กต์ API คุณต้องระบุข้อมูลต่อไปนี้โดยขยาย BaseTaskApi

  • กำหนด API I/O - 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();
      }
    }
    
  • จัดเตรียมตรรกะการแปลงระหว่าง 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;
      }
    }
    
  • สร้างฟังก์ชันจากโรงงานของ API - จำเป็นต้องใช้ไฟล์โมเดลและ OpResolver เพื่อเริ่มต้น tflite::Interpreter TaskAPIFactory มีฟังก์ชันยูทิลิตี้เพื่อสร้างอินสแตนซ์ BaseTaskApi

    คุณต้องจัดเตรียมไฟล์ใดๆ ที่เกี่ยวข้องกับโมเดลด้วย เช่น BertQuestionAnswerer ยังสามารถมีไฟล์เพิ่มเติมสำหรับคำศัพท์ของ tokenizer ได้

    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 โดยกำหนดอินเทอร์เฟซ Java/Kotlin และมอบหมายตรรกะให้กับเลเยอร์ C++ ผ่าน JNI Android API จำเป็นต้องสร้าง Native 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

เช่นเดียวกับ Native API ในการสร้างออบเจ็กต์ API ไคลเอ็นต์จำเป็นต้องจัดเตรียมข้อมูลต่อไปนี้โดยการขยาย BaseTaskApi ซึ่งจัดเตรียมการจัดการ JNI สำหรับ Java Task API ทั้งหมด

  • กำหนด API 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
                                           );
    
    }
    
  • สร้างฟังก์ชันจากโรงงานของ API - นอกจากนี้ยังสะท้อนฟังก์ชันดั้งเดิมของโรงงานด้วย ยกเว้นฟังก์ชันจากโรงงานของ 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 ฟังก์ชั่นโรงงานจะสร้างวัตถุ 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);
      }
    

ไอโอเอส เอพีไอ

สร้าง iOS API โดยการล้อมออบเจ็กต์ API ดั้งเดิมลงในออบเจ็กต์ ObjC API วัตถุ API ที่สร้างขึ้นสามารถใช้ได้ใน ObjC หรือ Swift iOS API กำหนดให้สร้าง Native API ก่อน

ตัวอย่างการใช้งาน

นี่คือตัวอย่างการใช้ ObjC TFLBertQuestionAnswerer สำหรับ MobileBert ใน 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

การสร้าง API

ios_task_api
รูปที่ 4 iOS Task API

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