ספריית המשימות של TensorFlow Lite מספקת ממשקי API מקוריים/Android/iOS מובנים מראש על גבי אותה תשתית שמפשטת את TensorFlow. אתה יכול להרחיב את תשתית ה-API של משימות לבניית ממשקי API מותאמים אישית אם המודל שלך אינו נתמך על ידי ספריות משימות קיימות.
סקירה כללית
לתשתית Task API יש מבנה דו-שכבתי: שכבת C++ התחתונה המכילה את זמן הריצה המקורי של TFLite ושכבת Java/ObjC העליונה שמתקשרת עם שכבת C++ דרך JNI או עטיפה מקורית.
הטמעת כל הלוגיקה של TensorFlow ב-C++ בלבד ממזערת את העלות, ממקסמת את ביצועי ההסקות ומפשטת את זרימת העבודה הכוללת בין הפלטפורמות.
כדי ליצור מחלקה של Task, הרחב את BaseTaskApi כדי לספק לוגיקת המרה בין ממשק מודל TFLite לממשק API של Task, ולאחר מכן השתמש בכלי השירות של Java/ObjC כדי ליצור ממשקי API תואמים. עם כל הפרטים של TensorFlow מוסתרים, אתה יכול לפרוס את מודל TFLite באפליקציות שלך ללא כל ידע למידת מכונה.
TensorFlow Lite מספק כמה ממשקי API מובנים מראש עבור רוב משימות ה-Vision וה-NLP הפופולריות. אתה יכול לבנות ממשקי API משלך עבור משימות אחרות באמצעות תשתית ה-API של משימות.
בנה ממשק API משלך עם Task API אינפרא
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
כדי לבנות אובייקט 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
. שתי הפונקציות מספקות כניסות ויציאות מה-TFLiteFlatBuffer
. תת-המחלקה אחראית להקצאת ערכים מה-API I/O ל-I/O tensors. ראה את דוגמה המימוש המלאה ב-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 של אנדרואיד
צור ממשקי API של אנדרואיד על ידי הגדרת ממשק Java/Kotlin והאצלת ההיגיון לשכבת C++ דרך JNI. ממשק 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
בדומה לממשקי API מקוריים, כדי לבנות אובייקט API, הלקוח צריך לספק את המידע הבא על ידי הרחבת BaseTaskApi
, המספקת טיפולי JNI עבור כל ממשקי ה-API של משימות Java.
קבע את ה-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 - זה גם משקף פונקציות מקוריות של היצרן, למעט פונקציות המפעל של אנדרואיד צריכות לקבל גם
Context
עבור גישה לקובץ. היישום קורא לאחת משירותי השירות ב-TaskJniUtils
כדי לבנות את אובייקט ה-API המתאים של C++ ולהעביר את המצביע שלו לבנאי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 של iOS על ידי גלישת אובייקט 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 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]; } }
אלא אם צוין אחרת, התוכן של דף זה הוא ברישיון Creative Commons Attribution 4.0 ודוגמאות הקוד הן ברישיון Apache 2.0. לפרטים, ניתן לעיין במדיניות האתר Google Developers. Java הוא סימן מסחרי רשום של חברת Oracle ו/או של השותפים העצמאיים שלה.
עדכון אחרון: 2023-12-02 (שעון UTC).