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

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

ภาพรวม

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

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

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

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

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

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

C++ API

รายละเอียด TFLite ทั้งหมดถูกนำมาใช้ใน 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 Native Task 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

สร้าง Android API โดยกำหนดอินเทอร์เฟซ 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 Android Task API

คล้ายกับ 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

สร้าง iOS API โดยห่ออ็อบเจ็กต์ API ดั้งเดิมลงในอ็อบเจ็กต์ ObjC API ออบเจ็กต์ API ที่สร้างขึ้นสามารถใช้ได้ทั้งใน ObjC หรือ Swift iOS API กำหนดให้สร้าง 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 เป็นเครื่องห่อหุ้ม ObjC แบบง่ายที่ด้านบนของ API ดั้งเดิม สร้าง API โดยทำตามขั้นตอนด้านล่าง:

  • กำหนดตัวห่อหุ้ม 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];
      }
    }