TensorFlow Lite Task Library fornisce API native/Android/iOS predefinite sulla stessa infrastruttura che astrae TensorFlow. Puoi estendere l'infrastruttura dell'API delle attività per creare API personalizzate se il tuo modello non è supportato dalle librerie delle attività esistenti.
Panoramica
L'infrastruttura dell'API delle attività ha una struttura a due livelli: il livello C++ inferiore che incapsula il runtime TFLite nativo e il livello Java/ObjC superiore che comunica con il livello C++ tramite JNI o wrapper nativo.
L'implementazione di tutta la logica TensorFlow solo in C++ riduce al minimo i costi, massimizza le prestazioni di inferenza e semplifica il flusso di lavoro complessivo tra le piattaforme.
Per creare una classe Task, estendere BaseTaskApi per fornire la logica di conversione tra l'interfaccia del modello TFLite e l'interfaccia API Task, quindi utilizzare le utilità Java/ObjC per creare le API corrispondenti. Con tutti i dettagli di TensorFlow nascosti, puoi distribuire il modello TFLite nelle tue app senza alcuna conoscenza di machine learning.
TensorFlow Lite fornisce alcune API predefinite per le attività Vision e NLP più comuni. Puoi creare le tue API per altre attività utilizzando l'infrastruttura dell'API delle attività.
Crea la tua API con Task API infra
API C++
Tutti i dettagli di TFLite sono implementati nell'API nativa. Crea un oggetto API utilizzando una delle funzioni factory e ottieni i risultati del modello chiamando le funzioni definite nell'interfaccia.
Esempio di utilizzo
Ecco un esempio che utilizza C++ BertQuestionAnswerer
per 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
Costruire l'API
Per creare un oggetto API, devi fornire le seguenti informazioni estendendo BaseTaskApi
Determina l'I/O dell'API: l'API deve esporre input/output simili su piattaforme diverse. ad esempio
BertQuestionAnswerer
prende due stringhe(std::string& context, std::string& question)
come input e restituisce un vettore di possibili risposte e probabilità comestd::vector<QaAnswer>
. Questo viene fatto specificando i tipi corrispondenti nel parametro del modello diBaseTaskApi
. Con i parametri del modello specificati, la funzioneBaseTaskApi::Infer
avrà i tipi di input/output corretti. Questa funzione può essere chiamata direttamente dai client API, ma è buona norma racchiuderla all'interno di una funzione specifica del modello, in questo caso,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(); } }
Fornire la logica di conversione tra API I/O e tensore di input/output del modello - Con i tipi di input e output specificati, le sottoclassi devono anche implementare le funzioni tipizzate
BaseTaskApi::Preprocess
eBaseTaskApi::Postprocess
. Le due funzioni forniscono input e output da TFLiteFlatBuffer
. La sottoclasse è responsabile dell'assegnazione dei valori dall'I/O API ai tensori I/O. Vedere l'esempio di implementazione completo inBertQuestionAnswerer
.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; } }
Crea funzioni di fabbrica dell'API - Sono necessari un file modello e un
OpResolver
per inizializzaretflite::Interpreter
.TaskAPIFactory
fornisce funzioni di utilità per creare istanze BaseTaskApi.È inoltre necessario fornire tutti i file associati al modello. ad esempio,
BertQuestionAnswerer
può anche avere un file aggiuntivo per il vocabolario del suo tokenizzatore.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
Crea API Android definendo l'interfaccia Java/Kotlin e delegando la logica al livello C++ tramite JNI. L'API Android richiede prima la creazione dell'API nativa.
Esempio di utilizzo
Ecco un esempio che utilizza Java BertQuestionAnswerer
per 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
Costruire l'API
Analogamente alle API native, per creare un oggetto API, il client deve fornire le seguenti informazioni estendendo BaseTaskApi
, che fornisce le gestioni JNI per tutte le API Java Task.
Determina l'I/O dell'API : in genere rispecchia le interfacce native. ad es
BertQuestionAnswerer
prende(String context, String question)
come input e outputList<QaAnswer>
. L'implementazione chiama una funzione nativa privata con una firma simile, tranne per il fatto che ha un parametro aggiuntivolong nativeHandle
, che è il puntatore restituito da 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 ); }
Crea funzioni di fabbrica dell'API : rispecchia anche le funzioni di fabbrica native, tranne per il fatto che anche le funzioni di fabbrica di Android devono accettare
Context
per l'accesso ai file. L'implementazione chiama una delle utilità inTaskJniUtils
per creare l'oggetto API C++ corrispondente e passare il relativo puntatore al costruttoreBaseTaskApi
.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); }
Implementare il modulo JNI per le funzioni native - Tutti i metodi nativi Java vengono implementati chiamando una funzione nativa corrispondente dal modulo JNI. Le funzioni di fabbrica creerebbero un oggetto API nativo e restituirebbero il suo puntatore come tipo lungo a Java. Nelle successive chiamate all'API Java, il puntatore di tipo lungo viene restituito a JNI e restituito all'oggetto API nativo. I risultati dell'API nativa vengono quindi riconvertiti in risultati Java.
Ad esempio, ecco come viene implementato 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
Crea API iOS avvolgendo un oggetto API nativo in un oggetto API ObjC. L'oggetto API creato può essere utilizzato in ObjC o Swift. L'API iOS richiede prima la creazione dell'API nativa.
Esempio di utilizzo
Ecco un esempio che utilizza ObjC TFLBertQuestionAnswerer
per MobileBert in 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
Costruire l'API
L'API iOS è un semplice wrapper ObjC sopra l'API nativa. Crea l'API seguendo i passaggi seguenti:
Definisci il wrapper ObjC - Definisci una classe ObjC e delega le implementazioni all'oggetto API nativo corrispondente. Nota che le dipendenze native possono apparire solo in un file .mm a causa dell'incapacità di Swift di interoperare con C++.
- file .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:)); }
- file .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]; } }
Salvo quando diversamente specificato, i contenuti di questa pagina sono concessi in base alla licenza Creative Commons Attribution 4.0, mentre gli esempi di codice sono concessi in base alla licenza Apache 2.0. Per ulteriori dettagli, consulta le norme del sito di Google Developers. Java è un marchio registrato di Oracle e/o delle sue consociate.
Ultimo aggiornamento 2021-11-05 UTC.