xref: /aosp_15_r20/external/tflite-support/tensorflow_lite_support/cc/text/tokenizers/tokenizer_utils.cc (revision b16991f985baa50654c05c5adbb3c8bbcfb40082)
1 /* Copyright 2022 The TensorFlow Authors. All Rights Reserved.
2 
3 Licensed under the Apache License, Version 2.0 (the "License");
4 you may not use this file except in compliance with the License.
5 You may obtain a copy of the License at
6 
7     http://www.apache.org/licenses/LICENSE-2.0
8 
9 Unless required by applicable law or agreed to in writing, software
10 distributed under the License is distributed on an "AS IS" BASIS,
11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 See the License for the specific language governing permissions and
13 limitations under the License.
14 ==============================================================================*/
15 
16 #include "tensorflow_lite_support/cc/text/tokenizers/tokenizer_utils.h"
17 
18 #include "absl/status/status.h"
19 #include "absl/strings/str_cat.h"
20 #include "tensorflow_lite_support/cc/common.h"
21 #include "tensorflow_lite_support/cc/port/status_macros.h"
22 #include "tensorflow_lite_support/cc/text/tokenizers/regex_tokenizer.h"
23 #include "tensorflow_lite_support/metadata/metadata_schema_generated.h"
24 #include "utils/bert_tokenizer.h"
25 
26 namespace tflite {
27 namespace support {
28 namespace text {
29 namespace tokenizer {
30 
31 using ::tflite::SentencePieceTokenizerOptions;
32 using ::tflite::support::CreateStatusWithPayload;
33 using ::tflite::support::StatusOr;
34 using ::tflite::support::TfLiteSupportStatus;
35 
36 namespace {
37 
CheckAndLoadFirstAssociatedFile(const flatbuffers::Vector<flatbuffers::Offset<tflite::AssociatedFile>> * associated_files,const tflite::metadata::ModelMetadataExtractor * metadata_extractor)38 StatusOr<absl::string_view> CheckAndLoadFirstAssociatedFile(
39     const flatbuffers::Vector<flatbuffers::Offset<tflite::AssociatedFile>>*
40         associated_files,
41     const tflite::metadata::ModelMetadataExtractor* metadata_extractor) {
42   if (associated_files == nullptr || associated_files->size() < 1 ||
43       associated_files->Get(0)->name() == nullptr) {
44     return CreateStatusWithPayload(
45         absl::StatusCode::kInvalidArgument,
46         "Invalid vocab_file from input process unit.",
47         TfLiteSupportStatus::kMetadataInvalidTokenizerError);
48   }
49   ASSIGN_OR_RETURN(absl::string_view vocab_buffer,
50                    metadata_extractor->GetAssociatedFile(
51                        associated_files->Get(0)->name()->str()));
52   return vocab_buffer;
53 }
54 }  // namespace
55 
CreateTokenizerFromProcessUnit(const tflite::ProcessUnit * tokenizer_process_unit,const tflite::metadata::ModelMetadataExtractor * metadata_extractor)56 StatusOr<std::unique_ptr<Tokenizer>> CreateTokenizerFromProcessUnit(
57     const tflite::ProcessUnit* tokenizer_process_unit,
58     const tflite::metadata::ModelMetadataExtractor* metadata_extractor) {
59   if (metadata_extractor == nullptr || tokenizer_process_unit == nullptr) {
60     return CreateStatusWithPayload(
61         absl::StatusCode::kInvalidArgument,
62         "No metadata or input process unit found.",
63         TfLiteSupportStatus::kMetadataInvalidTokenizerError);
64   }
65   switch (tokenizer_process_unit->options_type()) {
66     case ProcessUnitOptions_BertTokenizerOptions: {
67       const tflite::BertTokenizerOptions* options =
68           tokenizer_process_unit->options_as<tflite::BertTokenizerOptions>();
69       ASSIGN_OR_RETURN(absl::string_view vocab_buffer,
70                        CheckAndLoadFirstAssociatedFile(options->vocab_file(),
71                                                        metadata_extractor));
72       return absl::make_unique<libtextclassifier3::BertTokenizer>(
73           vocab_buffer.data(), vocab_buffer.size());
74     }
75     case ProcessUnitOptions_RegexTokenizerOptions: {
76       const tflite::RegexTokenizerOptions* options =
77           tokenizer_process_unit->options_as<RegexTokenizerOptions>();
78       ASSIGN_OR_RETURN(absl::string_view vocab_buffer,
79                        CheckAndLoadFirstAssociatedFile(options->vocab_file(),
80                                                        metadata_extractor));
81       if (options->delim_regex_pattern() == nullptr) {
82         return CreateStatusWithPayload(
83             absl::StatusCode::kInvalidArgument,
84             "Invalid delim_regex_pattern from input process unit.",
85             TfLiteSupportStatus::kMetadataInvalidTokenizerError);
86       }
87 
88       std::unique_ptr<RegexTokenizer> regex_tokenizer =
89           absl::make_unique<RegexTokenizer>(
90               options->delim_regex_pattern()->str(), vocab_buffer.data(),
91               vocab_buffer.size());
92 
93       int unknown_token_id = 0;
94       if (!regex_tokenizer->GetUnknownToken(&unknown_token_id)) {
95         return CreateStatusWithPayload(
96             absl::StatusCode::kInvalidArgument,
97             "RegexTokenizer doesn't have <UNKNOWN> token.",
98             TfLiteSupportStatus::kMetadataInvalidTokenizerError);
99       }
100 
101       int pad_token_id = 0;
102       if (!regex_tokenizer->GetPadToken(&pad_token_id)) {
103         return CreateStatusWithPayload(
104             absl::StatusCode::kInvalidArgument,
105             "RegexTokenizer doesn't have <PAD> token.",
106             TfLiteSupportStatus::kMetadataInvalidTokenizerError);
107       }
108 
109       return regex_tokenizer;
110     }
111     default:
112       return CreateStatusWithPayload(
113           absl::StatusCode::kNotFound,
114           absl::StrCat("Incorrect options_type:",
115                        tokenizer_process_unit->options_type()),
116           TfLiteSupportStatus::kMetadataInvalidTokenizerError);
117   }
118 }
119 
120 }  // namespace tokenizer
121 }  // namespace text
122 }  // namespace support
123 }  // namespace tflite
124 
125