• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Copyright 2020 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 "tensorflow_lite_support/cc/common.h"
20 #include "tensorflow_lite_support/cc/port/status_macros.h"
21 #include "tensorflow_lite_support/cc/text/tokenizers/bert_tokenizer.h"
22 #include "tensorflow_lite_support/cc/text/tokenizers/regex_tokenizer.h"
23 #include "tensorflow_lite_support/cc/text/tokenizers/sentencepiece_tokenizer.h"
24 #include "tensorflow_lite_support/metadata/metadata_schema_generated.h"
25 
26 namespace tflite {
27 namespace support {
28 namespace text {
29 namespace tokenizer {
30 
31 
32 using ::tflite::ProcessUnit;
33 using ::tflite::SentencePieceTokenizerOptions;
34 using ::tflite::support::CreateStatusWithPayload;
35 using ::tflite::support::StatusOr;
36 using ::tflite::support::TfLiteSupportStatus;
37 
38 namespace {
39 
CheckAndLoadFirstAssociatedFile(const flatbuffers::Vector<flatbuffers::Offset<tflite::AssociatedFile>> * associated_files,const tflite::metadata::ModelMetadataExtractor * metadata_extractor)40 StatusOr<absl::string_view> CheckAndLoadFirstAssociatedFile(
41     const flatbuffers::Vector<flatbuffers::Offset<tflite::AssociatedFile>>*
42         associated_files,
43     const tflite::metadata::ModelMetadataExtractor* metadata_extractor) {
44   if (associated_files == nullptr || associated_files->size() < 1 ||
45       associated_files->Get(0)->name() == nullptr) {
46     return CreateStatusWithPayload(
47         absl::StatusCode::kInvalidArgument,
48         "Invalid vocab_file from input process unit.",
49         TfLiteSupportStatus::kMetadataInvalidTokenizerError);
50   }
51   ASSIGN_OR_RETURN(absl::string_view vocab_buffer,
52                    metadata_extractor->GetAssociatedFile(
53                        associated_files->Get(0)->name()->str()));
54   return vocab_buffer;
55 }
56 }  // namespace
57 
CreateTokenizerFromProcessUnit(const tflite::ProcessUnit * tokenizer_process_unit,const tflite::metadata::ModelMetadataExtractor * metadata_extractor)58 StatusOr<std::unique_ptr<Tokenizer>> CreateTokenizerFromProcessUnit(
59     const tflite::ProcessUnit* tokenizer_process_unit,
60     const tflite::metadata::ModelMetadataExtractor* metadata_extractor) {
61   if (metadata_extractor == nullptr || tokenizer_process_unit == nullptr) {
62     return CreateStatusWithPayload(
63         absl::StatusCode::kInvalidArgument,
64         "No metadata or input process unit found.",
65         TfLiteSupportStatus::kMetadataInvalidTokenizerError);
66   }
67   switch (tokenizer_process_unit->options_type()) {
68     case ProcessUnitOptions_BertTokenizerOptions: {
69       const tflite::BertTokenizerOptions* options =
70           tokenizer_process_unit->options_as<tflite::BertTokenizerOptions>();
71       ASSIGN_OR_RETURN(absl::string_view vocab_buffer,
72                        CheckAndLoadFirstAssociatedFile(options->vocab_file(),
73                                                        metadata_extractor));
74       return absl::make_unique<BertTokenizer>(vocab_buffer.data(),
75                                               vocab_buffer.size());
76     }
77     case ProcessUnitOptions_SentencePieceTokenizerOptions: {
78       const tflite::SentencePieceTokenizerOptions* options =
79           tokenizer_process_unit->options_as<SentencePieceTokenizerOptions>();
80       ASSIGN_OR_RETURN(absl::string_view model_buffer,
81                        CheckAndLoadFirstAssociatedFile(
82                            options->sentencePiece_model(), metadata_extractor));
83       // TODO(b/160647204): Extract sentence piece model vocabulary
84       return absl::make_unique<SentencePieceTokenizer>(model_buffer.data(),
85                                                        model_buffer.size());
86     }
87     case ProcessUnitOptions_RegexTokenizerOptions: {
88       const tflite::RegexTokenizerOptions* options =
89           tokenizer_process_unit->options_as<RegexTokenizerOptions>();
90       ASSIGN_OR_RETURN(absl::string_view vocab_buffer,
91                        CheckAndLoadFirstAssociatedFile(options->vocab_file(),
92                                                        metadata_extractor));
93       if (options->delim_regex_pattern() == nullptr) {
94         return CreateStatusWithPayload(
95             absl::StatusCode::kInvalidArgument,
96             "Invalid delim_regex_pattern from input process unit.",
97             TfLiteSupportStatus::kMetadataInvalidTokenizerError);
98       }
99 
100       std::unique_ptr<RegexTokenizer> regex_tokenizer =
101           absl::make_unique<RegexTokenizer>(
102               options->delim_regex_pattern()->str(), vocab_buffer.data(),
103               vocab_buffer.size());
104 
105       int unknown_token_id = 0;
106       if (!regex_tokenizer->GetUnknownToken(&unknown_token_id)) {
107         return CreateStatusWithPayload(
108             absl::StatusCode::kInvalidArgument,
109             "RegexTokenizer doesn't have <UNKNOWN> token.",
110             TfLiteSupportStatus::kMetadataInvalidTokenizerError);
111       }
112 
113       int pad_token_id = 0;
114       if (!regex_tokenizer->GetPadToken(&pad_token_id)) {
115         return CreateStatusWithPayload(
116             absl::StatusCode::kInvalidArgument,
117             "RegexTokenizer doesn't have <PAD> token.",
118             TfLiteSupportStatus::kMetadataInvalidTokenizerError);
119       }
120 
121       return regex_tokenizer;
122     }
123     default:
124       return CreateStatusWithPayload(
125           absl::StatusCode::kNotFound,
126           absl::StrCat("Incorrect options_type:",
127                        tokenizer_process_unit->options_type()),
128           TfLiteSupportStatus::kMetadataInvalidTokenizerError);
129   }
130 }
131 
132 }  // namespace tokenizer
133 }  // namespace text
134 }  // namespace support
135 }  // namespace tflite
136 
137