|
| 1 | +// Copyright (c) Microsoft Corporation. All rights reserved. |
| 2 | +// Licensed under the MIT License. |
| 3 | +// Partial code comes from other Microsoft employee. |
| 4 | + |
| 5 | +#include <string> |
| 6 | +#include <vector> |
| 7 | +#include <fstream> |
| 8 | +#include <sstream> |
| 9 | +#include <iostream> |
| 10 | +#include <algorithm> |
| 11 | +#include <list> |
| 12 | +#include <memory> |
| 13 | +#include <regex> |
| 14 | +#include <sstream> |
| 15 | +#include <stdexcept> |
| 16 | +#include <unordered_map> |
| 17 | +#include <functional> |
| 18 | +#include <codecvt> |
| 19 | +#include <mutex> |
| 20 | + |
| 21 | +#include "nlohmann/json.hpp" |
| 22 | +#include "bpetokenizer.hpp" |
| 23 | +#include "string_tensor.h" |
| 24 | +#include "unicode.h" |
| 25 | + |
| 26 | +// Note: the following logic comes from CPython: unicodetype_db.h (_PyUnicode_IsWhitespace) |
| 27 | +bool IsWithinUnicodeSpace(char32_t ch) { |
| 28 | + switch (ch) { |
| 29 | + case 0x0009: |
| 30 | + case 0x000A: |
| 31 | + case 0x000B: |
| 32 | + case 0x000C: |
| 33 | + case 0x000D: |
| 34 | + case 0x001C: |
| 35 | + case 0x001D: |
| 36 | + case 0x001E: |
| 37 | + case 0x001F: |
| 38 | + case 0x0020: |
| 39 | + case 0x0085: |
| 40 | + case 0x00A0: |
| 41 | + case 0x1680: |
| 42 | + case 0x2000: |
| 43 | + case 0x2001: |
| 44 | + case 0x2002: |
| 45 | + case 0x2003: |
| 46 | + case 0x2004: |
| 47 | + case 0x2005: |
| 48 | + case 0x2006: |
| 49 | + case 0x2007: |
| 50 | + case 0x2008: |
| 51 | + case 0x2009: |
| 52 | + case 0x200A: |
| 53 | + case 0x2028: |
| 54 | + case 0x2029: |
| 55 | + case 0x202F: |
| 56 | + case 0x205F: |
| 57 | + case 0x3000: |
| 58 | + return true; |
| 59 | + } |
| 60 | + return false; |
| 61 | +} |
| 62 | + |
| 63 | +bool IsEmptyuString(const ustring& str) { |
| 64 | + return std::all_of(str.begin(), str.end(), [](char32_t ch) { return IsWithinUnicodeSpace(ch); }); |
| 65 | +} |
| 66 | + |
| 67 | +KernelRobertaBpeTokenizer::KernelRobertaBpeTokenizer(const OrtApi& api, const OrtKernelInfo& info) |
| 68 | + : BaseKernel(api, info) { |
| 69 | + std::string vocab = ort_.KernelInfoGetAttribute<std::string>(&info, "vocab"); |
| 70 | + if (vocab.empty()) { |
| 71 | + ORTX_CXX_API_THROW("vocabulary shouldn't be empty.", ORT_INVALID_ARGUMENT); |
| 72 | + } |
| 73 | + |
| 74 | + std::string merges = ort_.KernelInfoGetAttribute<std::string>(&info, "merges"); |
| 75 | + if (merges.empty()) { |
| 76 | + ORTX_CXX_API_THROW("merges shouldn't be empty.", ORT_INVALID_ARGUMENT); |
| 77 | + } |
| 78 | + |
| 79 | + if (!TryToGetAttribute<int64_t>("padding_length", padding_length_)) { |
| 80 | + padding_length_ = -1; |
| 81 | + } |
| 82 | + |
| 83 | + if (padding_length_ != -1 && padding_length_ <= 0) { |
| 84 | + ORTX_CXX_API_THROW("padding_length should be more than 0 or equal -1", ORT_INVALID_ARGUMENT); |
| 85 | + } |
| 86 | + |
| 87 | + std::stringstream vocabu_stream(vocab); |
| 88 | + std::stringstream merges_stream(merges); |
| 89 | + bbpe_tokenizer_ = std::make_shared<VocabData>(); |
| 90 | + bbpe_tokenizer_->Load(vocabu_stream, merges_stream, "<|endoftext|>", "<|endoftext|>"); |
| 91 | +} |
| 92 | + |
| 93 | +std::vector<int64_t> KernelRobertaBpeTokenizer::Tokenize(ustring& input, int64_t max_length, std::list<std::list<std::pair<int, int>>>& offset_map) { |
| 94 | + std::vector<int64_t> res; |
| 95 | + |
| 96 | + if (IsEmptyuString(input)) { |
| 97 | + return res; |
| 98 | + } |
| 99 | + // Add BOS token to result |
| 100 | + res.push_back(bbpe_tokenizer_->GetEncoding("<s>")); |
| 101 | + |
| 102 | + // Parse input |
| 103 | + auto special_token_split_res = bbpe_tokenizer_->SplitBySpecialTokens(input); |
| 104 | + TokenWithRegularExp regcmp; |
| 105 | + |
| 106 | + for (auto& seg_id : special_token_split_res) { |
| 107 | + if (static_cast<int64_t>(res.size()) >= max_length) break; |
| 108 | + |
| 109 | + if (seg_id.second != -1) { |
| 110 | + res.push_back(seg_id.second); |
| 111 | + continue; |
| 112 | + } |
| 113 | + |
| 114 | + auto cur_input = std::move(seg_id.first); |
| 115 | + // Note: keep ptr to make sure the string_view is valid in the following process |
| 116 | + const char32_t* ptr = cur_input.c_str(); |
| 117 | + regcmp.Set(ptr); |
| 118 | + |
| 119 | + int offset = 0; |
| 120 | + std::list<std::pair<int, int>> offset_mapping; |
| 121 | + |
| 122 | + // Add offset mapping for BOS token |
| 123 | + offset_mapping.push_back(std::make_pair(0, 0)); |
| 124 | + |
| 125 | + while (static_cast<int64_t>(res.size()) < max_length) { |
| 126 | + auto [b, tok] = regcmp.GetNextToken(); |
| 127 | + if (!b) break; |
| 128 | + |
| 129 | + std::string utf8_token = std::string(ustring(tok)); |
| 130 | + |
| 131 | + // Handle offset mapping and special cases |
| 132 | + if (utf8_token.at(0) == ' ') { |
| 133 | + offset_mapping.push_back(std::make_pair(offset + 1, offset + utf8_token.size())); |
| 134 | + } else { |
| 135 | + offset_mapping.push_back(std::make_pair(offset, offset + utf8_token.size())); |
| 136 | + } |
| 137 | + offset += utf8_token.size(); |
| 138 | + |
| 139 | + // Get byte encodings prior to performing BPE |
| 140 | + byte_list_.clear(); |
| 141 | + for (char& cp : utf8_token) { |
| 142 | + byte_list_.push_back(bbpe_tokenizer_->ByteEncoder()[static_cast<unsigned char>(cp)]); |
| 143 | + } |
| 144 | + |
| 145 | + // Perform BPE |
| 146 | + bbpe_tokenizer_->bpe(byte_list_); |
| 147 | + |
| 148 | + // Add output to result |
| 149 | + for (auto p : byte_list_) { |
| 150 | + if (static_cast<int64_t>(res.size()) >= max_length) { |
| 151 | + break; |
| 152 | + } |
| 153 | + |
| 154 | + res.push_back(p); |
| 155 | + } |
| 156 | + } |
| 157 | + // Add offset mapping for EOS token |
| 158 | + offset_mapping.push_back(std::make_pair(0, 0)); |
| 159 | + |
| 160 | + // Add offset mappings for input in this instance to list of offset mappings for all inputs |
| 161 | + offset_map.push_back(offset_mapping); |
| 162 | + } |
| 163 | + // Add EOS token to result |
| 164 | + res.push_back(bbpe_tokenizer_->GetEncoding("</s>")); |
| 165 | + return res; |
| 166 | +} |
| 167 | + |
| 168 | +void KernelRobertaBpeTokenizer::Compute(OrtKernelContext* context) { |
| 169 | + // Setup inputs |
| 170 | + const OrtValue* input = ort_.KernelContext_GetInput(context, 0); |
| 171 | + std::vector<std::string> str_input; |
| 172 | + std::list<std::list<std::pair<int, int>>> offset_map; |
| 173 | + GetTensorMutableDataString(api_, ort_, context, input, str_input); |
| 174 | + OrtTensorDimensions input_dim(ort_, input); |
| 175 | + |
| 176 | + std::vector<std::vector<int64_t>> tokenize_results; |
| 177 | + for (auto& str : str_input) { |
| 178 | + ustring ustr = ustring(str); |
| 179 | + tokenize_results.emplace_back(Tokenize(ustr, padding_length_ < 0 ? INT64_MAX : padding_length_, offset_map)); |
| 180 | + } |
| 181 | + |
| 182 | + size_t max_length = 0; |
| 183 | + if (padding_length_ == -1) { |
| 184 | + for (auto& res : tokenize_results) { |
| 185 | + max_length = std::max(max_length, res.size()); |
| 186 | + } |
| 187 | + } else { |
| 188 | + max_length = static_cast<size_t>(padding_length_); |
| 189 | + } |
| 190 | + |
| 191 | + OrtTensorDimensions output_dim = input_dim; |
| 192 | + output_dim.push_back(max_length); |
| 193 | + |
| 194 | + OrtTensorDimensions offset_dim = output_dim; |
| 195 | + offset_dim.push_back(2); // tuple of offsets for each input id |
| 196 | + |
| 197 | + OrtValue* tokenize_output = ort_.KernelContext_GetOutput(context, 0, output_dim.data(), output_dim.size()); |
| 198 | + OrtValue* attention_mask = ort_.KernelContext_GetOutput(context, 1, output_dim.data(), output_dim.size()); |
| 199 | + OrtValue* offset_mapping = ort_.KernelContext_GetOutput(context, 2, offset_dim.data(), offset_dim.size()); |
| 200 | + auto* token = ort_.GetTensorMutableData<int64_t>(tokenize_output); |
| 201 | + auto* mask = ort_.GetTensorMutableData<int64_t>(attention_mask); |
| 202 | + auto* offset = ort_.GetTensorMutableData<int64_t>(offset_mapping); |
| 203 | + |
| 204 | + int idx = 0; |
| 205 | + for (auto& res : tokenize_results) { |
| 206 | + for (int64_t id : res) { |
| 207 | + token[idx] = id; |
| 208 | + mask[idx] = 1; |
| 209 | + idx++; |
| 210 | + } |
| 211 | + |
| 212 | + for (size_t i = res.size(); i < max_length; i++) { |
| 213 | + token[idx] = 0; |
| 214 | + mask[idx] = 0; |
| 215 | + idx++; |
| 216 | + } |
| 217 | + } |
| 218 | + |
| 219 | + int idx2 = 0; |
| 220 | + for (auto& res : offset_map) { |
| 221 | + for (auto& mapping : res) { |
| 222 | + offset[idx2] = mapping.first; |
| 223 | + idx2++; |
| 224 | + offset[idx2] = mapping.second; |
| 225 | + idx2++; |
| 226 | + } |
| 227 | + } |
| 228 | +} |
| 229 | + |
| 230 | +const char* CustomOpRobertaBpeTokenizer::GetName() const { |
| 231 | + return "RobertaTokenizer"; |
| 232 | +} |
| 233 | + |
| 234 | +size_t CustomOpRobertaBpeTokenizer::GetInputTypeCount() const { |
| 235 | + return 1; |
| 236 | +} |
| 237 | + |
| 238 | +ONNXTensorElementDataType CustomOpRobertaBpeTokenizer::GetInputType(size_t /*index*/) const { |
| 239 | + return ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING; |
| 240 | +} |
| 241 | +size_t CustomOpRobertaBpeTokenizer::GetOutputTypeCount() const { |
| 242 | + return 3; |
| 243 | +} |
| 244 | + |
| 245 | +ONNXTensorElementDataType CustomOpRobertaBpeTokenizer::GetOutputType(size_t /*index*/) const { |
| 246 | + return ONNX_TENSOR_ELEMENT_DATA_TYPE_INT64; |
| 247 | +} |
0 commit comments