/src/sentencepiece/lite/sentencepiece_lite.cc
Line | Count | Source |
1 | | // Copyright 2026 Google LLC |
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 | | #include "sentencepiece_lite.h" |
16 | | |
17 | | #include <algorithm> |
18 | | #include <bit> |
19 | | #include <cassert> |
20 | | #include <cfloat> |
21 | | #include <cmath> |
22 | | #include <cstddef> |
23 | | #include <cstdint> |
24 | | #include <cstring> |
25 | | #include <limits> |
26 | | #include <memory> |
27 | | #include <numeric> |
28 | | #include <string> |
29 | | #include <string_view> |
30 | | #include <tuple> |
31 | | #include <unordered_map> |
32 | | #include <utility> |
33 | | #include <vector> |
34 | | |
35 | | #ifdef SENTENCEPIECE_LITE_USE_ABSL |
36 | | #include "absl/container/inlined_vector.h" |
37 | | #endif |
38 | | |
39 | | #ifdef SENTENCEPIECE_LITE_USE_UTF8_RANGE |
40 | | #include "utf8_validity.h" |
41 | | #endif |
42 | | |
43 | | #include "flatbuffers/base.h" |
44 | | #include "flatbuffers/vector.h" |
45 | | #include "flatbuffers/verifier.h" |
46 | | #include "sentencepiece_lite_generated.h" |
47 | | |
48 | | #define LITE_RETURN_IF_ERROR(expr) \ |
49 | 8.23k | do { \ |
50 | 8.23k | const StatusCode _status = (expr); \ |
51 | 8.23k | if (_status != StatusCode::kOk) return _status; \ |
52 | 8.23k | } while (0) |
53 | | |
54 | | #if defined(_MSC_VER) |
55 | | #define SPM_LITE_RESTRICT __restrict |
56 | | #elif defined(__GNUC__) || defined(__clang__) |
57 | | #define SPM_LITE_RESTRICT __restrict__ |
58 | | #else |
59 | | #define SPM_LITE_RESTRICT |
60 | | #endif |
61 | | |
62 | | namespace sentencepiece::lite { |
63 | | namespace { |
64 | | |
65 | | #ifdef SENTENCEPIECE_LITE_USE_ABSL |
66 | | template <typename T, size_t N> |
67 | | using InlineVector = absl::InlinedVector<T, N>; |
68 | | #else |
69 | | template <typename T, size_t N> |
70 | | using InlineVector = std::vector<T>; |
71 | | #endif |
72 | | |
73 | | // Maximum permitted input length (in bytes) for single-pass text normalization, |
74 | | // pre-tokenization, and encoding operations. |
75 | | // Set to std::numeric_limits<int>::max() - 1 (2,147,483,646 bytes) to strictly |
76 | | // prevent 32-bit signed integer overflow in Viterbi DP table and BPE index |
77 | | // calculations. |
78 | | constexpr size_t kMaxInputLength = |
79 | | static_cast<size_t>(std::numeric_limits<int>::max()) - 1; |
80 | | |
81 | | constexpr size_t kModelBufferAlignment = 4; |
82 | | |
83 | | // Double-Array Trie (Darts) flat 32-bit integer array representation. |
84 | | // Encodes a prefix tree into a 1D array where child transitions are computed |
85 | | // via O(1) XOR arithmetic (`node ^ offset ^ byte`) without pointer indirection. |
86 | | // |
87 | | // Unit Bit Layout (32-bit integer): |
88 | | // - Bits [0..7]: label (character byte that transitioned here) |
89 | | // - Bit 8: has_leaf (true if a symbol ends at this node) |
90 | | // - Bits [10..30]: offset (XOR base jump offset to child nodes; scaled << 8 if |
91 | | // Bit 9 is set) |
92 | | // - Bit 31: leaf flag (0 = internal transition node, 1 = leaf value |
93 | | // node storing symbol ID in bits [0..30]) |
94 | | class DoubleArray { |
95 | | private: |
96 | | class DoubleArrayUnit { |
97 | | public: |
98 | | DoubleArrayUnit() = default; |
99 | 401M | explicit DoubleArrayUnit(uint32_t unit) : unit_(unit) {} |
100 | | |
101 | 60.3M | bool has_leaf() const { return ((unit_ >> 8) & 1) == 1; } |
102 | 30.8M | int value() const { return static_cast<int>(unit_ & ((1U << 31) - 1)); } |
103 | 218M | uint32_t label() const { return unit_ & ((1U << 31) | 0xFF); } |
104 | 247M | uint32_t offset() const { |
105 | | // Branchless selection (`cmov`/`csel`) avoids variable shift stalls. |
106 | 247M | const uint32_t base = unit_ >> 10; |
107 | 247M | const uint32_t scaled = (unit_ >> 2) & ~0xFFU; |
108 | 247M | return (unit_ & (1U << 9)) ? scaled : base; |
109 | 247M | } |
110 | | |
111 | | private: |
112 | | uint32_t unit_ = 0; |
113 | | }; |
114 | | |
115 | | public: |
116 | 19.5k | DoubleArray() = default; |
117 | | |
118 | 3.51k | void set_array(const void* ptr, size_t size = 0) { |
119 | 3.51k | array_ = static_cast<const uint32_t*>(ptr); |
120 | 3.51k | size_ = size; |
121 | 3.51k | } |
122 | | |
123 | 301M | bool has_array() const { return array_ != nullptr; } |
124 | | |
125 | | // Returns the value associated with `key`, or -1 if not found. |
126 | 767k | int exact_lookup(std::string_view key) const { |
127 | 767k | if (array_ == nullptr || key.empty()) return -1; |
128 | 767k | uint32_t node_pos = 0; |
129 | 767k | DoubleArrayUnit unit(array_[node_pos]); |
130 | 5.16M | for (size_t i = 0; i < key.size(); ++i) { |
131 | 4.39M | node_pos ^= unit.offset() ^ static_cast<unsigned char>(key[i]); |
132 | 4.39M | unit = DoubleArrayUnit(array_[node_pos]); |
133 | 4.39M | if (unit.label() != static_cast<unsigned char>(key[i])) { |
134 | 11 | return -1; |
135 | 11 | } |
136 | 4.39M | } |
137 | 767k | if (!unit.has_leaf()) { |
138 | 12 | return -1; |
139 | 12 | } |
140 | 767k | unit = DoubleArrayUnit(array_[node_pos ^ unit.offset()]); |
141 | 767k | return unit.value(); |
142 | 767k | } |
143 | | |
144 | | // Returns a pair of {value, length} representing the longest matching prefix |
145 | | // of `key`. Returns {-1, 0} if no match is found. |
146 | 0 | std::pair<int, size_t> longest_prefix_lookup(std::string_view key) const { |
147 | 0 | int matched_id = -1; |
148 | 0 | size_t longest_len = 0; |
149 | 0 | common_prefix_lookup(key, [&](int value, size_t length) { |
150 | 0 | matched_id = value; |
151 | 0 | longest_len = length; |
152 | 0 | }); |
153 | 0 | return {matched_id, longest_len}; |
154 | 0 | } |
155 | | |
156 | | // Performs a common prefix search. `callback(value, length)` is called |
157 | | // for all prefixes of `key`. |
158 | | template <typename Callback> |
159 | 151M | void common_prefix_lookup(std::string_view key, Callback&& callback) const { |
160 | 151M | if (array_ == nullptr || key.empty()) return; |
161 | 151M | uint32_t node_pos = 0; |
162 | 151M | DoubleArrayUnit unit(array_[node_pos]); |
163 | 209M | for (size_t i = 0; i < key.size(); ++i) { |
164 | 209M | node_pos ^= unit.offset() ^ static_cast<unsigned char>(key[i]); |
165 | 209M | unit = DoubleArrayUnit(array_[node_pos]); |
166 | 209M | if (unit.label() != static_cast<unsigned char>(key[i])) { |
167 | 151M | break; |
168 | 151M | } |
169 | 57.8M | if (unit.has_leaf()) { |
170 | 29.2M | DoubleArrayUnit leaf(array_[node_pos ^ unit.offset()]); |
171 | 29.2M | callback(leaf.value(), i + 1); |
172 | 29.2M | } |
173 | 57.8M | } |
174 | 151M | } Unexecuted instantiation: sentencepiece_lite.cc:void sentencepiece::lite::(anonymous namespace)::DoubleArray::common_prefix_lookup<sentencepiece::lite::(anonymous namespace)::DoubleArray::longest_prefix_lookup(std::__1::basic_string_view<char, std::__1::char_traits<char> >) const::{lambda(int, unsigned long)#1}>(std::__1::basic_string_view<char, std::__1::char_traits<char> >, sentencepiece::lite::(anonymous namespace)::DoubleArray::longest_prefix_lookup(std::__1::basic_string_view<char, std::__1::char_traits<char> >) const::{lambda(int, unsigned long)#1}&&) constsentencepiece_lite.cc:void sentencepiece::lite::(anonymous namespace)::DoubleArray::common_prefix_lookup<sentencepiece::lite::Model::EncodeUnigram(std::__1::basic_string_view<char, std::__1::char_traits<char> >, std::__1::vector<int, std::__1::allocator<int> >*, std::__1::vector<std::__1::basic_string_view<char, std::__1::char_traits<char> >, std::__1::allocator<std::__1::basic_string_view<char, std::__1::char_traits<char> > > >*, float, absl::lts_20260817::FunctionRef<float ()> const*) const::$_1>(std::__1::basic_string_view<char, std::__1::char_traits<char> >, sentencepiece::lite::Model::EncodeUnigram(std::__1::basic_string_view<char, std::__1::char_traits<char> >, std::__1::vector<int, std::__1::allocator<int> >*, std::__1::vector<std::__1::basic_string_view<char, std::__1::char_traits<char> >, std::__1::allocator<std::__1::basic_string_view<char, std::__1::char_traits<char> > > >*, float, absl::lts_20260817::FunctionRef<float ()> const*) const::$_1&&) const Line | Count | Source | 159 | 151M | void common_prefix_lookup(std::string_view key, Callback&& callback) const { | 160 | 151M | if (array_ == nullptr || key.empty()) return; | 161 | 151M | uint32_t node_pos = 0; | 162 | 151M | DoubleArrayUnit unit(array_[node_pos]); | 163 | 209M | for (size_t i = 0; i < key.size(); ++i) { | 164 | 209M | node_pos ^= unit.offset() ^ static_cast<unsigned char>(key[i]); | 165 | 209M | unit = DoubleArrayUnit(array_[node_pos]); | 166 | 209M | if (unit.label() != static_cast<unsigned char>(key[i])) { | 167 | 151M | break; | 168 | 151M | } | 169 | 57.8M | if (unit.has_leaf()) { | 170 | 29.2M | DoubleArrayUnit leaf(array_[node_pos ^ unit.offset()]); | 171 | 29.2M | callback(leaf.value(), i + 1); | 172 | 29.2M | } | 173 | 57.8M | } | 174 | 151M | } |
|
175 | | |
176 | | // Non-owning Trie view with __restrict__ pointer for hot loops. |
177 | | struct View { |
178 | | const uint32_t* SPM_LITE_RESTRICT array; |
179 | | static constexpr uint32_t kInvalidNodePos = ~0U; |
180 | | |
181 | 379k | uint32_t transition(uint32_t node_pos, std::string_view key) const { |
182 | 379k | if (node_pos == kInvalidNodePos) return kInvalidNodePos; |
183 | 379k | uint32_t id = node_pos; |
184 | 379k | for (char c : key) { |
185 | 379k | id ^= |
186 | 379k | DoubleArrayUnit(array[id]).offset() ^ static_cast<unsigned char>(c); |
187 | 379k | if (DoubleArrayUnit(array[id]).label() != |
188 | 379k | static_cast<unsigned char>(c)) { |
189 | 330k | return kInvalidNodePos; |
190 | 330k | } |
191 | 379k | } |
192 | 48.5k | return id; |
193 | 379k | } |
194 | | |
195 | 0 | int leaf_value(uint32_t node_pos) const { |
196 | 0 | if (node_pos == kInvalidNodePos) return -1; |
197 | 0 | const DoubleArrayUnit unit(array[node_pos]); |
198 | 0 | if (!unit.has_leaf()) return -1; |
199 | 0 | return DoubleArrayUnit(array[node_pos ^ unit.offset()]).value(); |
200 | 0 | } |
201 | | }; |
202 | | |
203 | 1.48k | View view() const { return View{array_}; } |
204 | | |
205 | | // SECURITY CRITICAL: Runtime trie traversals omit per-step bounds checks for |
206 | | // performance. This method guarantees memory safety by verifying ahead of |
207 | | // time that for every node `i`, all 256 byte transitions `(i ^ offset) ^ c`, |
208 | | // leaf transitions, symbol IDs (`< max_value_limit`), and failure links |
209 | | // strictly reside within `[0, size_)`. Do NOT weaken these checks. |
210 | | bool validate(int max_value_limit = -1, |
211 | 3.51k | bool check_suffix_links = false) const { |
212 | 3.51k | if (size_ == 0 || array_ == nullptr) return false; |
213 | 3.51k | DoubleArrayUnit root(array_[0]); |
214 | | // The next trie node transition ID is calculated as `id ^= offset ^ c`. |
215 | | // Verifying that the max index `(id ^ offset) | 0xFF` for any byte `c` |
216 | | // stays below `size_` mathematically guarantees that input strings |
217 | | // cannot trigger out-of-bounds reads during trie traversal. |
218 | 3.51k | if (root.label() != 0 || root.has_leaf() || root.offset() == 0 || |
219 | 3.50k | ((0 ^ root.offset()) | 0xFF) >= size_) { |
220 | 39 | return false; |
221 | 39 | } |
222 | 2.62M | for (size_t i = 1; i < size_; ++i) { |
223 | 2.62M | DoubleArrayUnit unit(array_[i]); |
224 | 2.62M | if (unit.label() <= 0xFF) { |
225 | | // Pre-validate OOB transition bound for all internal nodes. |
226 | 1.75M | if (((i ^ unit.offset()) | 0xFF) >= size_) { |
227 | 78 | return false; |
228 | 78 | } |
229 | | // Verify that if this node has a leaf, the target null-transition unit |
230 | | // is actually a valid leaf/value node (with Bit 31 set, label > 0xFF). |
231 | 1.75M | if (unit.has_leaf()) { |
232 | 867k | if (DoubleArrayUnit(array_[i ^ unit.offset()]).label() <= 0xFF) { |
233 | 12 | return false; |
234 | 12 | } |
235 | 867k | } |
236 | 1.75M | } else { |
237 | 868k | if (max_value_limit >= 0) { |
238 | 413k | if (unit.value() >= max_value_limit) { |
239 | 55 | return false; |
240 | 55 | } |
241 | 413k | } |
242 | 868k | if (check_suffix_links) { |
243 | | // Suffix links point to valid transition nodes in the same trie. |
244 | | // We verify that the target node is within the trie bounds, and is a |
245 | | // valid transition state (its label is a single-byte char <= 0xFF). |
246 | 455k | const int link = unit.value(); |
247 | 455k | if (link < 0 || link >= static_cast<int>(size_)) { |
248 | 72 | return false; |
249 | 72 | } |
250 | 455k | DoubleArrayUnit target(array_[link]); |
251 | 455k | if (target.label() > 0xFF) { |
252 | 36 | return false; |
253 | 36 | } |
254 | 455k | } |
255 | 868k | } |
256 | 2.62M | } |
257 | 3.22k | return true; |
258 | 3.47k | } |
259 | | |
260 | | const uint32_t* array_ = nullptr; |
261 | | size_t size_ = 0; |
262 | | }; |
263 | | |
264 | | StatusCode InitializeTrie(const uint8_t* data, size_t size, int max_value_limit, |
265 | | bool check_suffix_links, bool is_optional, |
266 | 5.27k | DoubleArray* trie) { |
267 | 5.27k | if (data == nullptr || size == 0) { |
268 | 1.70k | return is_optional ? StatusCode::kOk : StatusCode::kInternal; |
269 | 1.70k | } |
270 | 3.56k | if (size < 1024 || (size & 0x3FF) != 0 || |
271 | 3.51k | (reinterpret_cast<uintptr_t>(data) % alignof(uint32_t)) != 0) { |
272 | 53 | return StatusCode::kInternal; |
273 | 53 | } |
274 | 3.51k | trie->set_array(data, size / sizeof(uint32_t)); |
275 | 3.51k | if (!trie->validate(max_value_limit, check_suffix_links)) { |
276 | 292 | return StatusCode::kInternal; |
277 | 292 | } |
278 | 3.22k | return StatusCode::kOk; |
279 | 3.51k | } |
280 | | |
281 | | StatusCode InitializeTrie(const flatbuffers::Vector<uint8_t>* blob, |
282 | | int max_value_limit, bool check_suffix_links, |
283 | 5.23k | bool is_optional, DoubleArray* trie) { |
284 | 5.23k | return InitializeTrie(blob ? blob->data() : nullptr, blob ? blob->size() : 0, |
285 | 5.23k | max_value_limit, check_suffix_links, is_optional, trie); |
286 | 5.23k | } |
287 | | |
288 | | constexpr float kUnkPenalty = 10.0; |
289 | | constexpr std::string_view kSpaceSymbol = "\xe2\x96\x81"; |
290 | | constexpr std::string_view kReplacementChar = "\xEF\xBF\xBD"; |
291 | | constexpr size_t kMaxPieceLength = 4096; |
292 | | |
293 | 0 | inline float GetUserDefinedScore(int length) { return 0.1f * (length - 1); } |
294 | | |
295 | 227M | inline size_t OneCharLen(const char* src) { |
296 | | // Fast-path for ASCII bytes (< 0x80). When cast to signed char, non-ASCII |
297 | | // leading bytes (0x80 to 0xFF) are negative, falling through cleanly with |
298 | | // zero regression. Speeds up pretokenization chunking by ~4.4%. |
299 | 227M | if (static_cast<signed char>(*src) >= 0) return 1; |
300 | 163M | return "\1\1\1\1\1\1\1\1\1\1\1\1\2\2\3\4"[(*src & 0xFF) >> 4]; |
301 | 227M | } |
302 | | |
303 | 1.62M | inline uint64_t LoadLe64(const void* ptr) { |
304 | 1.62M | uint64_t val; |
305 | 1.62M | std::memcpy(&val, ptr, sizeof(uint64_t)); |
306 | 1.62M | return flatbuffers::EndianScalar(val); |
307 | 1.62M | } |
308 | | |
309 | | // Returns the byte offset of the first matched byte within a little-endian |
310 | | // 8-byte SWAR word. |
311 | 1.57M | inline size_t FirstMatchedByteOffset(uint64_t match_mask) { |
312 | 1.57M | return std::countr_zero(match_mask) >> 3; |
313 | 1.57M | } |
314 | | |
315 | | // Register-friendly UTF-8 string scanner that holds `ptr_` and `end_` in |
316 | | // registers and uses `ptr_ + 4 <= end_` to avoid per-character `substr()` and |
317 | | // `std::min` bounds checks in hot tokenization loops. |
318 | | class StringScanner { |
319 | | public: |
320 | | explicit StringScanner(std::string_view str) |
321 | 3.05k | : ptr_(str.data()), end_(str.data() + str.size()) {} |
322 | | |
323 | 156M | bool empty() const { return ptr_ >= end_; } |
324 | 48.4k | size_t remaining() const { return end_ - ptr_; } |
325 | 0 | const char* data() const { return ptr_; } |
326 | 151M | std::string_view remaining_view() const { |
327 | 151M | return std::string_view(ptr_, end_ - ptr_); |
328 | 151M | } |
329 | | |
330 | | // Returns the length of the next UTF-8 character without redundant |
331 | | // std::min boundary checking when remaining buffer is >= 4 bytes. |
332 | 151M | size_t NextLen() const { |
333 | 151M | if (empty()) return 0; |
334 | 151M | const size_t len = OneCharLen(ptr_); |
335 | 151M | if (ptr_ + 4 <= end_) { |
336 | 151M | return len; |
337 | 151M | } |
338 | 3.67k | return std::min<size_t>(len, static_cast<size_t>(end_ - ptr_)); |
339 | 151M | } |
340 | | |
341 | | // Advances the pointer by `n` bytes. |
342 | 151M | void Advance(size_t n) { ptr_ += n; } |
343 | | |
344 | | // Consumes and returns the substring up to the next occurrence of `c`. |
345 | 1.62M | std::string_view ConsumeUntil(char c) { |
346 | 1.62M | if (empty()) return {}; |
347 | 1.62M | const char* target = nullptr; |
348 | | // Fast-path: 64-bit SWAR scans for ' ' within the next 8 bytes. |
349 | 1.62M | if (c == ' ' && ptr_ + sizeof(uint64_t) <= end_) { |
350 | 1.62M | const uint64_t word = LoadLe64(ptr_); |
351 | 1.62M | const uint64_t space_xor = word ^ 0x2020202020202020ULL; |
352 | 1.62M | const uint64_t space_match = (space_xor - 0x0101010101010101ULL) & |
353 | 1.62M | ~space_xor & 0x8080808080808080ULL; |
354 | 1.62M | if (space_match != 0) { |
355 | 1.57M | target = ptr_ + FirstMatchedByteOffset(space_match); |
356 | 1.57M | } |
357 | 1.62M | } |
358 | 1.62M | if (target == nullptr) { |
359 | 48.4k | const void* p = |
360 | 48.4k | std::memchr(ptr_, static_cast<unsigned char>(c), remaining()); |
361 | 48.4k | target = (p != nullptr) ? static_cast<const char*>(p) : end_; |
362 | 48.4k | } |
363 | 1.62M | const std::string_view result(ptr_, target - ptr_); |
364 | 1.62M | ptr_ = target; |
365 | 1.62M | return result; |
366 | 1.62M | } |
367 | | |
368 | | // Consumes consecutive occurrences of `c` and returns the count. |
369 | 1.62M | size_t SkipAll(char c) { |
370 | 1.62M | const char* start = ptr_; |
371 | 3.77M | while (ptr_ < end_ && *ptr_ == c) { |
372 | 2.14M | ++ptr_; |
373 | 2.14M | } |
374 | 1.62M | return ptr_ - start; |
375 | 1.62M | } |
376 | | |
377 | | // Consumes the next UTF-8 character and returns its string_view. |
378 | 0 | std::string_view ConsumeNext() { |
379 | 0 | if (empty()) return {}; |
380 | 0 | const size_t len = NextLen(); |
381 | 0 | std::string_view piece(ptr_, len); |
382 | 0 | ptr_ += len; |
383 | 0 | return piece; |
384 | 0 | } |
385 | | |
386 | | private: |
387 | | const char* ptr_ = nullptr; |
388 | | const char* end_ = nullptr; |
389 | | }; |
390 | | |
391 | | namespace utf8 { |
392 | | #if defined(SENTENCEPIECE_LITE_USE_UTF8_RANGE) |
393 | 75.6M | inline bool IsStructurallyValid(std::string_view s) { |
394 | 75.6M | return utf8_range::IsStructurallyValid(s); |
395 | 75.6M | } |
396 | 0 | inline size_t SpanStructurallyValid(std::string_view s) { |
397 | 0 | return utf8_range::SpanStructurallyValid(s); |
398 | 0 | } |
399 | | #else |
400 | | // Self-contained fast UTF-8 validator with 64-bit SWAR ASCII skip. |
401 | | inline size_t SpanStructurallyValid(std::string_view s) { |
402 | | const char* ptr = s.data(); |
403 | | const char* const end = s.data() + s.size(); |
404 | | while (ptr < end) { |
405 | | // 64-bit SWAR fast path for ASCII runs (~20 GB/s) |
406 | | while (ptr + sizeof(uint64_t) <= end) { |
407 | | uint64_t word; |
408 | | std::memcpy(&word, ptr, sizeof(uint64_t)); |
409 | | if ((word & 0x8080808080808080ULL) != 0) break; |
410 | | ptr += sizeof(uint64_t); |
411 | | } |
412 | | while (ptr < end && static_cast<unsigned char>(*ptr) < 0x80) ++ptr; |
413 | | if (ptr >= end) break; |
414 | | |
415 | | // Validate multibyte UTF-8 (2..4 bytes), continuation bits, and codepoint |
416 | | // range. |
417 | | const size_t len = OneCharLen(ptr); |
418 | | if (len < 2 || ptr + len > end) return ptr - s.data(); |
419 | | uint32_t cp = static_cast<unsigned char>(*ptr++) & (0xFF >> len); |
420 | | for (size_t i = 1; i < len; ++i) { |
421 | | const unsigned char b = static_cast<unsigned char>(*ptr++); |
422 | | if ((b & 0xC0) != 0x80) return (ptr - 1 - i) - s.data(); |
423 | | cp = (cp << 6) | (b & 0x3F); |
424 | | } |
425 | | const uint32_t min_cp = (len == 2) ? 0x80 : (len == 3) ? 0x800 : 0x10000; |
426 | | if (cp < min_cp || (cp >= 0xD800 && cp <= 0xDFFF) || cp > 0x10FFFF) { |
427 | | return (ptr - len) - s.data(); |
428 | | } |
429 | | } |
430 | | return s.size(); |
431 | | } |
432 | | |
433 | | inline bool IsStructurallyValid(std::string_view s) { |
434 | | return SpanStructurallyValid(s) == s.size(); |
435 | | } |
436 | | #endif |
437 | | |
438 | | // Validates a single UTF-8 character at the beginning of `input`. |
439 | | // Returns true if valid, setting `*mblen` to the character byte length (1..4). |
440 | | // Returns false if invalid, setting `*mblen` to 1. |
441 | 75.6M | inline bool IsValidUTF8(std::string_view input, size_t* mblen) { |
442 | 75.6M | if (input.empty()) { |
443 | 0 | *mblen = 0; |
444 | 0 | return false; |
445 | 0 | } |
446 | 75.6M | const size_t len = OneCharLen(input.data()); |
447 | 75.6M | if (len <= input.size() && |
448 | 75.6M | IsStructurallyValid(std::string_view(input.data(), len))) { |
449 | 438k | *mblen = len; |
450 | 438k | return true; |
451 | 438k | } |
452 | 75.1M | *mblen = 1; |
453 | 75.1M | return false; |
454 | 75.6M | } |
455 | | } // namespace utf8 |
456 | | |
457 | | inline void ReplaceAll(std::string_view s, std::string_view from, |
458 | 0 | std::string_view to, std::string* out) { |
459 | 0 | if (from.empty() || s.empty()) { |
460 | 0 | out->append(s.data(), s.size()); |
461 | 0 | return; |
462 | 0 | } |
463 | 0 | size_t last_pos = 0; |
464 | 0 | while (true) { |
465 | 0 | const size_t pos = s.find(from, last_pos); |
466 | 0 | if (pos == std::string_view::npos) { |
467 | 0 | break; |
468 | 0 | } |
469 | 0 | if (pos > last_pos) { |
470 | 0 | out->append(s.data() + last_pos, pos - last_pos); |
471 | 0 | } |
472 | 0 | out->append(to.data(), to.size()); |
473 | 0 | last_pos = pos + from.size(); |
474 | 0 | } |
475 | 0 | if (last_pos < s.size()) { |
476 | 0 | out->append(s.data() + last_pos, s.size() - last_pos); |
477 | 0 | } |
478 | 0 | } |
479 | | |
480 | | // Formats a raw byte into its SentencePiece byte-fallback token "<0xXX>". |
481 | 355k | std::string ByteToPiece(unsigned char c) { |
482 | 355k | static constexpr char kHexDigits[] = "0123456789ABCDEF"; |
483 | 355k | std::string s = "<0x00>"; |
484 | 355k | s[3] = kHexDigits[(c >> 4) & 0xF]; |
485 | 355k | s[4] = kHexDigits[c & 0xF]; |
486 | 355k | return s; |
487 | 355k | } |
488 | | |
489 | | class Normalizer { |
490 | | public: |
491 | 4.89k | Normalizer() = default; |
492 | | ~Normalizer() = default; |
493 | | |
494 | 1.58k | StatusCode Initialize(const NormalizerSpec* spec) { |
495 | 1.58k | spec_ = spec; |
496 | 1.58k | if (spec_ == nullptr) return StatusCode::kOk; |
497 | | |
498 | | // Caches all flags to avoid pointer traversal. |
499 | 1.58k | add_dummy_prefix_ = spec_->add_dummy_prefix(); |
500 | 1.58k | remove_extra_whitespaces_ = spec_->remove_extra_whitespaces(); |
501 | 1.58k | escape_whitespaces_ = spec_->escape_whitespaces(); |
502 | 1.58k | treat_whitespace_as_suffix_ = spec_->treat_whitespace_as_suffix(); |
503 | | |
504 | 1.58k | if (spec_->precompiled_charsmap() != nullptr && |
505 | 148 | !spec_->precompiled_charsmap()->empty()) { |
506 | 116 | const uint8_t* data = spec_->precompiled_charsmap()->data(); |
507 | 116 | const size_t size = spec_->precompiled_charsmap()->size(); |
508 | | |
509 | 116 | if (size <= sizeof(uint32_t)) { |
510 | 6 | return StatusCode::kInternal; |
511 | 6 | } |
512 | 110 | uint32_t normalizer_trie_blob_size = 0; |
513 | 110 | std::memcpy(&normalizer_trie_blob_size, data, sizeof(uint32_t)); |
514 | | |
515 | 110 | if (normalizer_trie_blob_size >= size - sizeof(uint32_t)) { |
516 | 57 | return StatusCode::kInternal; |
517 | 57 | } |
518 | | |
519 | 53 | const uint8_t* normalizer_trie_ptr = data + sizeof(uint32_t); |
520 | 53 | normalized_ = |
521 | 53 | std::string_view(reinterpret_cast<const char*>( |
522 | 53 | normalizer_trie_ptr + normalizer_trie_blob_size), |
523 | 53 | size - sizeof(uint32_t) - normalizer_trie_blob_size); |
524 | | |
525 | 53 | if (normalized_.empty() || normalized_.back() != '\0') { |
526 | 13 | return StatusCode::kInternal; |
527 | 13 | } |
528 | | |
529 | 40 | LITE_RETURN_IF_ERROR(InitializeTrie( |
530 | 40 | normalizer_trie_ptr, normalizer_trie_blob_size, normalized_.size(), |
531 | 40 | /*check_suffix_links=*/false, /*is_optional=*/false, &trie_)); |
532 | 40 | } |
533 | 1.46k | return StatusCode::kOk; |
534 | 1.58k | } |
535 | | |
536 | 1.64k | void SetPrefixMatcher(const DoubleArray* prefix_matcher) { |
537 | 1.64k | prefix_matcher_ = (trie_.has_array() || remove_extra_whitespaces_) |
538 | 1.64k | ? prefix_matcher |
539 | 1.64k | : nullptr; |
540 | 1.64k | } |
541 | | |
542 | 2.76k | bool CanSkipNormalization(std::string_view input) const { |
543 | 2.76k | if (input.empty() || spec_ == nullptr) { |
544 | 2 | return true; |
545 | 2 | } |
546 | 2.76k | if (trie_.has_array() || add_dummy_prefix_ || remove_extra_whitespaces_) { |
547 | 2.76k | return false; |
548 | 2.76k | } |
549 | 0 | if (escape_whitespaces_ && input.find(' ') != std::string_view::npos) { |
550 | 0 | return false; |
551 | 0 | } |
552 | 0 | return utf8::IsStructurallyValid(input); |
553 | 0 | } |
554 | | |
555 | | StatusCode Normalize(std::string_view input, std::string* normalized, |
556 | 2.76k | std::vector<size_t>* offset = nullptr) const { |
557 | 2.76k | if (offset != nullptr) { |
558 | 1.38k | offset->clear(); |
559 | 1.38k | } |
560 | 2.76k | normalized->clear(); |
561 | 2.76k | if (input.empty()) { |
562 | 1 | return StatusCode::kOk; |
563 | 1 | } |
564 | | |
565 | 2.76k | if (spec_ == nullptr) { |
566 | 0 | normalized->assign(input.data(), input.size()); |
567 | 0 | if (offset != nullptr) { |
568 | 0 | offset->resize(input.size() + 1); |
569 | 0 | std::iota(offset->begin(), offset->end(), 0); |
570 | 0 | } |
571 | 0 | return StatusCode::kOk; |
572 | 0 | } |
573 | | |
574 | 2.76k | size_t consumed = 0; |
575 | | |
576 | 2.76k | if (remove_extra_whitespaces_) { |
577 | 3.50k | while (!input.empty()) { |
578 | 3.49k | const auto p = NormalizePrefix(input); |
579 | 3.49k | if (p.first != " ") { |
580 | 2.75k | break; |
581 | 2.75k | } |
582 | 742 | input.remove_prefix(p.second); |
583 | 742 | if (offset != nullptr) { |
584 | 371 | consumed += p.second; |
585 | 371 | } |
586 | 742 | } |
587 | 2.76k | } |
588 | | |
589 | 2.76k | if (input.empty()) { |
590 | 8 | return StatusCode::kOk; |
591 | 8 | } |
592 | | |
593 | 2.75k | const size_t kReservedSize = input.size() * 3 / 2; |
594 | 2.75k | normalized->reserve(kReservedSize); |
595 | 2.75k | if (offset != nullptr) { |
596 | 1.37k | offset->reserve(kReservedSize); |
597 | 1.37k | } |
598 | | |
599 | 2.75k | const std::string_view space_symbol = |
600 | 2.75k | escape_whitespaces_ ? kSpaceSymbol : " "; |
601 | | |
602 | 2.75k | if (!treat_whitespace_as_suffix_ && add_dummy_prefix_) { |
603 | 2.75k | normalized->append(space_symbol.data(), space_symbol.size()); |
604 | 2.75k | if (offset != nullptr) { |
605 | 1.37k | offset->insert(offset->end(), space_symbol.size(), consumed); |
606 | 1.37k | } |
607 | 2.75k | } |
608 | | |
609 | 2.75k | if (!trie_.has_array() && offset == nullptr) { |
610 | 1.37k | if (utf8::IsStructurallyValid(input)) { |
611 | 333 | NormalizeIdentityFast(input, space_symbol, normalized); |
612 | 1.04k | } else { |
613 | 1.04k | NormalizeGeneralCore(input, space_symbol, &consumed, normalized, |
614 | 1.04k | /*offset=*/nullptr); |
615 | 1.04k | } |
616 | 1.37k | } else { |
617 | 1.37k | NormalizeGeneralCore(input, space_symbol, &consumed, normalized, offset); |
618 | 1.37k | } |
619 | | |
620 | 2.75k | if (remove_extra_whitespaces_) { |
621 | 4.80k | while (normalized->size() >= space_symbol.size() && |
622 | 4.77k | std::string_view(*normalized).ends_with(space_symbol)) { |
623 | 2.05k | const size_t length = normalized->size() - space_symbol.size(); |
624 | 2.05k | normalized->resize(length); |
625 | 2.05k | if (offset != nullptr) { |
626 | 1.02k | consumed = (*offset)[length]; |
627 | 1.02k | offset->resize(length); |
628 | 1.02k | } |
629 | 2.05k | } |
630 | 2.75k | } |
631 | | |
632 | 2.75k | if (treat_whitespace_as_suffix_ && add_dummy_prefix_) { |
633 | 0 | normalized->append(space_symbol.data(), space_symbol.size()); |
634 | 0 | if (offset != nullptr) { |
635 | 0 | offset->insert(offset->end(), space_symbol.size(), consumed); |
636 | 0 | } |
637 | 0 | } |
638 | | |
639 | 2.75k | if (offset != nullptr) { |
640 | 1.37k | offset->push_back(consumed); |
641 | 1.37k | } |
642 | | |
643 | 2.75k | return StatusCode::kOk; |
644 | 2.76k | } |
645 | | |
646 | 0 | bool remove_extra_whitespaces() const { return remove_extra_whitespaces_; } |
647 | | |
648 | | private: |
649 | | // Fast path for identity normalization without offsets (empty compiled map), |
650 | | // using 64-bit SWAR / SIMD memchr and batched appends. |
651 | | void NormalizeIdentityFast(std::string_view input, |
652 | | std::string_view space_symbol, |
653 | 333 | std::string* normalized) const { |
654 | 333 | bool is_prev_space = remove_extra_whitespaces_; |
655 | 333 | StringScanner scanner(input); |
656 | 1.62M | while (!scanner.empty()) { |
657 | 1.62M | const std::string_view chunk = scanner.ConsumeUntil(' '); |
658 | 1.62M | if (!chunk.empty()) { |
659 | 1.62M | normalized->append(chunk.data(), chunk.size()); |
660 | 1.62M | is_prev_space = false; |
661 | 1.62M | } |
662 | | |
663 | 1.62M | if (scanner.empty()) { |
664 | 284 | break; |
665 | 284 | } |
666 | | |
667 | 1.62M | const size_t space_count = scanner.SkipAll(' '); |
668 | 1.62M | if (remove_extra_whitespaces_) { |
669 | 1.62M | if (!is_prev_space) { |
670 | 1.62M | normalized->append(space_symbol.data(), space_symbol.size()); |
671 | 1.62M | is_prev_space = true; |
672 | 1.62M | } |
673 | 1.62M | } else { |
674 | 0 | for (size_t i = 0; i < space_count; ++i) { |
675 | 0 | normalized->append(space_symbol.data(), space_symbol.size()); |
676 | 0 | } |
677 | 0 | is_prev_space = false; |
678 | 0 | } |
679 | 1.62M | } |
680 | 333 | } |
681 | | |
682 | | // General core using NormalizePrefix for models with DoubleArray Trie |
683 | | // or when character offset tracking is requested. |
684 | | void NormalizeGeneralCore(std::string_view input, |
685 | | std::string_view space_symbol, size_t* consumed, |
686 | | std::string* normalized, |
687 | 2.42k | std::vector<size_t>* offset) const { |
688 | 2.42k | bool is_prev_space = remove_extra_whitespaces_; |
689 | 150M | while (!input.empty()) { |
690 | 150M | auto p = NormalizePrefix(input); |
691 | 150M | std::string_view sp = p.first; |
692 | | |
693 | 154M | while (is_prev_space && sp.starts_with(' ')) { |
694 | 3.56M | sp.remove_prefix(1); |
695 | 3.56M | } |
696 | | |
697 | 150M | if (!sp.empty()) { |
698 | 146M | if (sp.find(' ') == std::string_view::npos) { // NOLINT |
699 | 136M | normalized->append(sp.data(), sp.size()); |
700 | 136M | if (offset != nullptr) { |
701 | 69.7M | offset->insert(offset->end(), sp.size(), *consumed); |
702 | 69.7M | } |
703 | 136M | } else { |
704 | 21.4M | for (size_t n = 0; n < sp.size(); ++n) { |
705 | 10.7M | if (sp[n] == ' ') { |
706 | 10.7M | normalized->append(space_symbol.data(), space_symbol.size()); |
707 | 10.7M | if (offset != nullptr) { |
708 | 6.18M | offset->insert(offset->end(), space_symbol.size(), *consumed); |
709 | 6.18M | } |
710 | 10.7M | } else { |
711 | 0 | *normalized += sp[n]; // NOLINT |
712 | 0 | if (offset != nullptr) { |
713 | 0 | offset->push_back(*consumed); |
714 | 0 | } |
715 | 0 | } |
716 | 10.7M | } |
717 | 10.7M | } |
718 | 146M | is_prev_space = sp.ends_with(' '); |
719 | 146M | } |
720 | | |
721 | 150M | if (offset != nullptr) { |
722 | 77.9M | *consumed += p.second; |
723 | 77.9M | } |
724 | 150M | input.remove_prefix(p.second); |
725 | 150M | if (!remove_extra_whitespaces_) { |
726 | 0 | is_prev_space = false; |
727 | 0 | } |
728 | 150M | } |
729 | 2.42k | } |
730 | | |
731 | | private: |
732 | | // Normalizes the longest matching prefix of `input`. |
733 | | // Returns a pair {normalized_piece, consumed_bytes}. |
734 | | std::pair<std::string_view, int> NormalizePrefix( |
735 | 150M | std::string_view input) const { |
736 | 150M | std::pair<std::string_view, int> result; |
737 | 150M | if (input.empty()) return result; |
738 | | |
739 | 150M | if (prefix_matcher_ != nullptr && prefix_matcher_->has_array()) { |
740 | 0 | const auto [id, len] = prefix_matcher_->longest_prefix_lookup(input); |
741 | 0 | if (len > 0) { |
742 | 0 | return {input.substr(0, len), static_cast<int>(len)}; |
743 | 0 | } |
744 | 0 | } |
745 | | |
746 | 150M | size_t longest_length = 0; |
747 | 150M | int longest_value = 0; |
748 | | |
749 | 150M | if (trie_.has_array()) { |
750 | 0 | std::tie(longest_value, longest_length) = |
751 | 0 | trie_.longest_prefix_lookup(input); |
752 | 0 | } |
753 | | |
754 | 150M | if (longest_length == 0 || longest_length > input.size() || |
755 | 150M | static_cast<size_t>(longest_value) >= normalized_.size()) { |
756 | 150M | if (static_cast<unsigned char>(input[0]) < 0x80) { |
757 | 74.8M | result.second = 1; |
758 | 74.8M | result.first = std::string_view(input.data(), 1); |
759 | 75.6M | } else { |
760 | 75.6M | size_t length = 0; |
761 | 75.6M | if (!utf8::IsValidUTF8(input, &length)) { |
762 | 75.1M | result.second = 1; |
763 | 75.1M | result.first = kReplacementChar; |
764 | 75.1M | } else { |
765 | 438k | result.second = length; |
766 | 438k | result.first = std::string_view(input.data(), result.second); |
767 | 438k | } |
768 | 75.6M | } |
769 | 150M | } else { |
770 | 0 | result.second = longest_length; |
771 | 0 | result.first = std::string_view(normalized_.data() + longest_value); |
772 | 0 | } |
773 | | |
774 | 150M | return result; |
775 | 150M | } |
776 | | |
777 | | const NormalizerSpec* spec_ = nullptr; |
778 | | const DoubleArray* prefix_matcher_ = nullptr; |
779 | | DoubleArray trie_; |
780 | | std::string_view normalized_; |
781 | | |
782 | | // Cached flags avoid FlatBuffer vtable lookups inside normalization loops. |
783 | | bool add_dummy_prefix_ = true; |
784 | | bool remove_extra_whitespaces_ = true; |
785 | | bool escape_whitespaces_ = true; |
786 | | bool treat_whitespace_as_suffix_ = false; |
787 | | }; |
788 | | } // namespace |
789 | | |
790 | | class Model { |
791 | | public: |
792 | | explicit Model(std::string_view model_buffer); |
793 | | ~Model(); |
794 | | |
795 | 4.89k | StatusCode status() const { return status_; } |
796 | | |
797 | | void Encode(std::string_view normalized, std::vector<int>* ids, |
798 | | std::vector<std::string_view>* pieces = nullptr, |
799 | | float alpha = 0.0f, |
800 | | const FunctionRef<float()>* uniform_sampler = nullptr) const; |
801 | | |
802 | | int PieceToId(std::string_view piece) const; |
803 | | std::string_view IdToPiece(int id) const; |
804 | | // FlatBuffers stores scalar values in little-endian wire format. When reading |
805 | | // through raw pointers (scores_ / int_scores_), EndianScalar byte-swaps the |
806 | | // values on big-endian hosts while remaining a no-op on little-endian hosts. |
807 | 29.2M | float GetScore(int id) const { |
808 | 29.2M | return flatbuffers::EndianScalar(scores_[id]); |
809 | 29.2M | } |
810 | 0 | int32_t GetIntScore(int id) const { |
811 | 0 | return flatbuffers::EndianScalar(int_scores_[id]); |
812 | 0 | } |
813 | 409k | bool IsUnknown(int id) const { return types_[id] == PieceType_UNKNOWN; } |
814 | 411k | bool IsControl(int id) const { return types_[id] == PieceType_CONTROL; } |
815 | 355k | bool IsByte(int id) const { return types_[id] == PieceType_BYTE; } |
816 | | |
817 | 29.2M | bool IsUserDefined(int id) const { |
818 | 29.2M | return types_[id] == PieceType_USER_DEFINED; |
819 | 29.2M | } |
820 | | |
821 | 411k | bool IsUnused(int id) const { return types_[id] == PieceType_UNUSED; } |
822 | | |
823 | | // Returns true if `id` is a non-surface token (`UNKNOWN`, `CONTROL`, |
824 | | // `UNUSED`, or `BYTE`) that should be excluded from the Unigram lattice and |
825 | | // direct-mapping shortcuts. |
826 | 29.2M | bool IsInvisible(int id) const { |
827 | 29.2M | if (id < 0) return true; |
828 | 29.2M | const auto type = types_[id]; |
829 | 29.2M | return type != PieceType_NORMAL && type != PieceType_USER_DEFINED; |
830 | 29.2M | } |
831 | | |
832 | | // Returns true if `id` is a reserved token (`UNKNOWN`, `CONTROL`, or `BYTE`) |
833 | | // that must not participate in BPE merges. `UNUSED` tokens are allowed to |
834 | | // merge as intermediate transition states and are resegmented afterward. |
835 | 0 | bool IsReservedId(int id) const { |
836 | 0 | if (id < 0) return true; |
837 | 0 | return IsInvisible(id) && !IsUnused(id); |
838 | 0 | } |
839 | | |
840 | 0 | int piece_type(int id) const { return static_cast<int>(types_[id]); } |
841 | 0 | int vocab_size() const { return model_proto_->pieces()->size(); } |
842 | 0 | int model_type() const { return static_cast<int>(model_type_); } |
843 | 0 | int unk_id() const { return unk_id_; } |
844 | 0 | int bos_id() const { return bos_id_; } |
845 | 0 | int eos_id() const { return eos_id_; } |
846 | 0 | int pad_id() const { return pad_id_; } |
847 | 2.72k | float unk_score() const { return unk_score_; } |
848 | | |
849 | 0 | std::string_view unk_piece() const { |
850 | 0 | return unk_id_ < 0 ? "<unk>" : IdToPiece(unk_id_); |
851 | 0 | } |
852 | | std::string_view unk_surface() const; |
853 | | |
854 | 0 | bool add_dummy_prefix() const { return add_dummy_prefix_; } |
855 | | |
856 | 4.80k | bool has_normalizer_spec() const { |
857 | 4.80k | return model_proto_->normalizer_spec() != nullptr; |
858 | 4.80k | } |
859 | | |
860 | 0 | bool remove_extra_whitespaces() const { |
861 | 0 | return normalizer_.remove_extra_whitespaces(); |
862 | 0 | } |
863 | | |
864 | 0 | bool has_non_leading_space_symbol() const { |
865 | 0 | return has_non_leading_space_symbol_; |
866 | 0 | } |
867 | | |
868 | | // Returns true if `id` is guaranteed to encode as a single standalone token |
869 | | // when appearing as an isolated pre-split chunk, bypassing BPE merges. |
870 | | // |
871 | | // Note: `is_direct_mapping` is precomputed during `ToFlatbuffer()` |
872 | | // conversion by running `SentencePieceLiteProcessor`. Pre-converted BPE |
873 | | // `.spm.fb` models containing `UNUSED` pieces generated before `UNUSED` BPE |
874 | | // merge support was added must be re-converted so their direct-mapping flags |
875 | | // reflect intermediate `UNUSED` merges. |
876 | 0 | bool IsDirectMapping(int id) const { |
877 | 0 | if (id >= vocab_size() || IsInvisible(id)) return false; |
878 | 0 | if (!model_proto_->has_direct_mappings()) return false; |
879 | 0 | const auto* vector = model_proto_->is_direct_mapping(); |
880 | 0 | if (vector == nullptr) { |
881 | 0 | return true; |
882 | 0 | } |
883 | 0 | return vector->Get(id) != 0; |
884 | 0 | } |
885 | | |
886 | 0 | void SetScoreResetThresholdForTesting(float threshold) { |
887 | 0 | score_reset_threshold_ = threshold; |
888 | 0 | } |
889 | | |
890 | 275M | int ByteToId(unsigned char b) const { return byte_to_id_[b]; } |
891 | | |
892 | 0 | int IdToByte(int id) const { |
893 | 0 | if (!IsByte(id) || byte_fallback_start_id_ == -1) return -1; |
894 | 0 | if (id >= byte_fallback_start_id_ && id < byte_fallback_start_id_ + 256) { |
895 | 0 | return id - byte_fallback_start_id_; |
896 | 0 | } |
897 | 0 | return -1; |
898 | 0 | } |
899 | | |
900 | | StatusCode PretokenizeAtSafeBoundaries( |
901 | | std::string_view normalized, |
902 | | FunctionRef<void(std::string_view)> receiver) const; |
903 | | StatusCode Normalize(std::string_view input, std::string* normalized, |
904 | | std::vector<size_t>* offset = nullptr) const; |
905 | 2.76k | bool CanSkipNormalization(std::string_view input) const { |
906 | 2.76k | if (status_ != StatusCode::kOk) return false; |
907 | 2.76k | if (!has_normalizer_spec()) return true; |
908 | 2.76k | return normalizer_.CanSkipNormalization(input); |
909 | 2.76k | } |
910 | | void EncodeChunk(std::string_view chunk, std::vector<int>* ids, |
911 | | std::vector<std::string_view>* pieces = nullptr, |
912 | | float alpha = 0.0f, |
913 | | const FunctionRef<float()>* uniform_sampler = nullptr) const; |
914 | | |
915 | | private: |
916 | | void EncodeUnigram( |
917 | | std::string_view normalized, std::vector<int>* ids, |
918 | | std::vector<std::string_view>* pieces = nullptr, float alpha = 0.0f, |
919 | | const FunctionRef<float()>* uniform_sampler = nullptr) const; |
920 | | void EncodeBPE(std::string_view normalized, std::vector<int>* ids, |
921 | | std::vector<std::string_view>* pieces = nullptr, |
922 | | float alpha = 0.0f, |
923 | | const FunctionRef<float()>* uniform_sampler = nullptr) const; |
924 | | template <bool kReverse = false> |
925 | | void EmitPiece(int id, std::string_view piece, std::vector<int>* ids, |
926 | 151M | std::vector<std::string_view>* pieces = nullptr) const { |
927 | 151M | if (id == unk_id_ && byte_fallback_start_id_ != -1) { |
928 | 124M | const size_t len = piece.size(); |
929 | 399M | for (size_t i = 0; i < len; ++i) { |
930 | 275M | ids->push_back(ByteToId(kReverse ? piece[len - 1 - i] : piece[i])); |
931 | 275M | if (pieces != nullptr) { |
932 | 137M | pieces->push_back((i == len - 1) ? piece : piece.substr(0, 0)); |
933 | 137M | } |
934 | 275M | } |
935 | 124M | return; |
936 | 124M | } |
937 | | |
938 | 27.4M | if (id != unk_id_ || ids->empty() || ids->back() != unk_id_) { |
939 | 27.4M | ids->push_back(id); |
940 | 27.4M | if (pieces != nullptr) pieces->push_back(piece); |
941 | 27.4M | return; |
942 | 27.4M | } |
943 | | |
944 | 0 | if (pieces != nullptr && !pieces->empty()) { |
945 | 0 | auto& back = pieces->back(); |
946 | 0 | back = kReverse |
947 | 0 | ? std::string_view(piece.data(), piece.size() + back.size()) |
948 | 0 | : std::string_view(back.data(), back.size() + piece.size()); |
949 | 0 | } |
950 | 0 | } void sentencepiece::lite::Model::EmitPiece<true>(int, std::__1::basic_string_view<char, std::__1::char_traits<char> >, std::__1::vector<int, std::__1::allocator<int> >*, std::__1::vector<std::__1::basic_string_view<char, std::__1::char_traits<char> >, std::__1::allocator<std::__1::basic_string_view<char, std::__1::char_traits<char> > > >*) const Line | Count | Source | 926 | 151M | std::vector<std::string_view>* pieces = nullptr) const { | 927 | 151M | if (id == unk_id_ && byte_fallback_start_id_ != -1) { | 928 | 124M | const size_t len = piece.size(); | 929 | 399M | for (size_t i = 0; i < len; ++i) { | 930 | 275M | ids->push_back(ByteToId(kReverse ? piece[len - 1 - i] : piece[i])); | 931 | 275M | if (pieces != nullptr) { | 932 | 137M | pieces->push_back((i == len - 1) ? piece : piece.substr(0, 0)); | 933 | 137M | } | 934 | 275M | } | 935 | 124M | return; | 936 | 124M | } | 937 | | | 938 | 27.4M | if (id != unk_id_ || ids->empty() || ids->back() != unk_id_) { | 939 | 27.4M | ids->push_back(id); | 940 | 27.4M | if (pieces != nullptr) pieces->push_back(piece); | 941 | 27.4M | return; | 942 | 27.4M | } | 943 | | | 944 | 0 | if (pieces != nullptr && !pieces->empty()) { | 945 | 0 | auto& back = pieces->back(); | 946 | 0 | back = kReverse | 947 | 0 | ? std::string_view(piece.data(), piece.size() + back.size()) | 948 | 0 | : std::string_view(back.data(), back.size() + piece.size()); | 949 | 0 | } | 950 | 0 | } |
Unexecuted instantiation: void sentencepiece::lite::Model::EmitPiece<false>(int, std::__1::basic_string_view<char, std::__1::char_traits<char> >, std::__1::vector<int, std::__1::allocator<int> >*, std::__1::vector<std::__1::basic_string_view<char, std::__1::char_traits<char> >, std::__1::allocator<std::__1::basic_string_view<char, std::__1::char_traits<char> > > >*) const |
951 | | |
952 | | StatusCode Initialize(std::string_view model_buffer); |
953 | | |
954 | | Normalizer normalizer_; |
955 | | const ModelProto* model_proto_ = nullptr; |
956 | | StatusCode status_ = StatusCode::kFailedPrecondition; |
957 | | DoubleArray pieces_trie_; |
958 | | DoubleArray prefix_matcher_trie_; |
959 | | DoubleArray char_bigram_trie_; |
960 | | |
961 | | // Caching these flags avoids per-token FlatBuffer vtable pointer lookups |
962 | | // during decoding and normalization checks. |
963 | | int unk_id_ = 0; |
964 | | int bos_id_ = -1; |
965 | | int eos_id_ = -1; |
966 | | int pad_id_ = -1; |
967 | | bool add_dummy_prefix_ = true; |
968 | | bool has_non_leading_space_symbol_ = false; |
969 | | bool has_unused_ = false; |
970 | | float unk_score_ = 0.0; |
971 | | ModelType model_type_ = ModelType_UNIGRAM; |
972 | | const float* scores_ = nullptr; |
973 | | const int32_t* int_scores_ = nullptr; |
974 | | const signed char* types_ = nullptr; |
975 | | |
976 | | // `byte_to_id_[x]` (which equals `byte_fallback_start_id_ + x`) stores the |
977 | | // actual vocabulary symbol ID for raw byte `x` (0 <= x < 256). |
978 | | // If byte fallback is not enabled or not found in the vocabulary, |
979 | | // `byte_fallback_start_id_` is set to -1. |
980 | | int byte_to_id_[256]; |
981 | | // Pre-computed root-node Trie transition positions for ASCII bytes (0..255). |
982 | | uint32_t root_ascii_table_[256]; |
983 | | int byte_fallback_start_id_ = -1; |
984 | | float score_reset_threshold_ = 100000.0f; |
985 | | }; |
986 | | |
987 | | Model::Model(std::string_view model_buffer) |
988 | 4.89k | : status_(StatusCode::kFailedPrecondition) { |
989 | 4.89k | status_ = Initialize(model_buffer); |
990 | 4.89k | } |
991 | | |
992 | 4.89k | Model::~Model() = default; |
993 | | |
994 | 4.89k | StatusCode Model::Initialize(std::string_view model_buffer) { |
995 | 4.89k | if (model_buffer.empty() || |
996 | 4.89k | model_buffer.size() >= static_cast<size_t>(FLATBUFFERS_MAX_BUFFER_SIZE) || |
997 | 4.89k | (reinterpret_cast<uintptr_t>(model_buffer.data()) % |
998 | 4.89k | kModelBufferAlignment) != 0) { |
999 | 11 | return StatusCode::kInvalidArgument; |
1000 | 11 | } |
1001 | | |
1002 | 4.88k | flatbuffers::Verifier verifier( |
1003 | 4.88k | reinterpret_cast<const uint8_t*>(model_buffer.data()), |
1004 | 4.88k | model_buffer.size()); |
1005 | 4.88k | if (!VerifyModelProtoBuffer(verifier)) { |
1006 | 2.37k | return StatusCode::kInvalidArgument; |
1007 | 2.37k | } |
1008 | | |
1009 | 2.51k | model_proto_ = GetModelProto(model_buffer.data()); |
1010 | 2.51k | if (model_proto_ == nullptr || model_proto_->pieces() == nullptr) { |
1011 | 116 | return StatusCode::kInvalidArgument; |
1012 | 116 | } |
1013 | | |
1014 | 2.40k | const size_t vocab_size = model_proto_->pieces()->size(); |
1015 | | |
1016 | 2.40k | unk_id_ = model_proto_->unk_id(); |
1017 | 2.40k | if (unk_id_ < -1 || unk_id_ >= static_cast<int>(vocab_size)) { |
1018 | 124 | return StatusCode::kInternal; |
1019 | 124 | } |
1020 | | |
1021 | 2.27k | bos_id_ = model_proto_->bos_id(); |
1022 | 2.27k | if (bos_id_ < -1 || bos_id_ >= static_cast<int>(vocab_size)) { |
1023 | 68 | return StatusCode::kInternal; |
1024 | 68 | } |
1025 | | |
1026 | 2.20k | eos_id_ = model_proto_->eos_id(); |
1027 | 2.20k | if (eos_id_ < -1 || eos_id_ >= static_cast<int>(vocab_size)) { |
1028 | 83 | return StatusCode::kInternal; |
1029 | 83 | } |
1030 | | |
1031 | 2.12k | pad_id_ = model_proto_->pad_id(); |
1032 | 2.12k | if (pad_id_ < -1 || pad_id_ >= static_cast<int>(vocab_size)) { |
1033 | 82 | return StatusCode::kInternal; |
1034 | 82 | } |
1035 | | |
1036 | 2.04k | if (has_normalizer_spec()) { |
1037 | 1.58k | add_dummy_prefix_ = model_proto_->normalizer_spec()->add_dummy_prefix(); |
1038 | 1.58k | LITE_RETURN_IF_ERROR( |
1039 | 1.58k | normalizer_.Initialize(model_proto_->normalizer_spec())); |
1040 | 1.58k | } else { |
1041 | 462 | add_dummy_prefix_ = true; |
1042 | 462 | } |
1043 | | |
1044 | 1.92k | model_type_ = model_proto_->model_type(); |
1045 | | |
1046 | 1.92k | LITE_RETURN_IF_ERROR(InitializeTrie( |
1047 | 1.92k | model_proto_->pieces_trie_blob(), vocab_size, |
1048 | 1.92k | /*check_suffix_links=*/false, /*is_optional=*/false, &pieces_trie_)); |
1049 | 1.65k | LITE_RETURN_IF_ERROR( |
1050 | 1.65k | InitializeTrie(model_proto_->prefix_matcher_trie_blob(), vocab_size, |
1051 | 1.65k | /*check_suffix_links=*/false, /*is_optional=*/true, |
1052 | 1.65k | &prefix_matcher_trie_)); |
1053 | 1.64k | normalizer_.SetPrefixMatcher(&prefix_matcher_trie_); |
1054 | 1.64k | LITE_RETURN_IF_ERROR(InitializeTrie( |
1055 | 1.64k | model_proto_->char_bigram_trie_blob(), -1, |
1056 | 1.64k | /*check_suffix_links=*/true, /*is_optional=*/true, &char_bigram_trie_)); |
1057 | | |
1058 | 1.50k | if (char_bigram_trie_.has_array()) { |
1059 | 1.48k | const auto trie_view = char_bigram_trie_.view(); |
1060 | 380k | for (int i = 0; i < 256; ++i) { |
1061 | 379k | const char c = static_cast<char>(i); |
1062 | 379k | root_ascii_table_[i] = trie_view.transition(0U, std::string_view(&c, 1)); |
1063 | 379k | } |
1064 | 1.48k | } else { |
1065 | 5.91k | for (int i = 0; i < 256; ++i) { |
1066 | 5.88k | root_ascii_table_[i] = DoubleArray::View::kInvalidNodePos; |
1067 | 5.88k | } |
1068 | 23 | } |
1069 | | |
1070 | 1.50k | if (model_type_ == ModelType_BPE) { |
1071 | 30 | if (model_proto_->int_scores() == nullptr || |
1072 | 29 | model_proto_->int_scores()->size() != vocab_size) { |
1073 | 19 | return StatusCode::kInternal; |
1074 | 19 | } |
1075 | 11 | int_scores_ = model_proto_->int_scores()->data(); |
1076 | 1.47k | } else { |
1077 | 1.47k | if (model_proto_->scores() == nullptr || |
1078 | 1.47k | model_proto_->scores()->size() != vocab_size) { |
1079 | 20 | return StatusCode::kInternal; |
1080 | 20 | } |
1081 | 1.45k | scores_ = model_proto_->scores()->data(); |
1082 | 1.45k | } |
1083 | | |
1084 | 1.46k | if (model_proto_->types() == nullptr || |
1085 | 1.46k | model_proto_->types()->size() != vocab_size) { |
1086 | 27 | return StatusCode::kInternal; |
1087 | 27 | } |
1088 | 1.43k | types_ = model_proto_->types()->data(); |
1089 | | |
1090 | 1.43k | if (model_proto_->is_direct_mapping() != nullptr && |
1091 | 38 | model_proto_->is_direct_mapping()->size() != vocab_size) { |
1092 | 24 | return StatusCode::kInternal; |
1093 | 24 | } |
1094 | | |
1095 | | // Verify 1-to-1 bidirectional consistency between `pieces` and |
1096 | | // `pieces_trie_`. |
1097 | 413k | for (size_t i = 0; i < vocab_size; ++i) { |
1098 | 411k | const auto* piece_obj = model_proto_->pieces()->Get(i); |
1099 | 411k | if (piece_obj == nullptr || piece_obj->size() > kMaxPieceLength) { |
1100 | 1 | return StatusCode::kInternal; |
1101 | 1 | } |
1102 | 411k | const std::string_view piece(piece_obj->c_str(), piece_obj->size()); |
1103 | 411k | const int id = pieces_trie_.exact_lookup(piece); |
1104 | 411k | if (id < 0 || id >= static_cast<int>(vocab_size) || |
1105 | 411k | id != static_cast<int>(i)) { |
1106 | 25 | return StatusCode::kInternal; |
1107 | 25 | } |
1108 | 411k | if (IsUnused(i)) { |
1109 | 0 | has_unused_ = true; |
1110 | 0 | } |
1111 | 411k | if (!has_non_leading_space_symbol_ && !IsControl(i) && !IsUnknown(i)) { |
1112 | 407k | std::string_view rem = piece; |
1113 | 407k | if (rem.starts_with(kSpaceSymbol)) { |
1114 | 11.0k | rem.remove_prefix(kSpaceSymbol.size()); |
1115 | 11.0k | } |
1116 | 407k | if (rem.find(kSpaceSymbol) != std::string_view::npos) { |
1117 | 0 | has_non_leading_space_symbol_ = true; |
1118 | 0 | } |
1119 | 407k | } |
1120 | 411k | } |
1121 | | |
1122 | 1.38k | if (model_proto_->unk_surface() != nullptr && |
1123 | 1.38k | model_proto_->unk_surface()->size() > kMaxPieceLength) { |
1124 | 0 | return StatusCode::kInternal; |
1125 | 0 | } |
1126 | | |
1127 | | // Compute unk_score and reject NaN/Inf scores so Viterbi DP stays |
1128 | | // well-defined. |
1129 | 1.38k | float min_score = FLT_MAX; |
1130 | 1.38k | if (model_type_ != ModelType_BPE) { |
1131 | 413k | for (int i = 0; i < static_cast<int>(vocab_size); ++i) { |
1132 | 411k | float score = model_proto_->scores()->Get(i); |
1133 | 411k | if (std::isnan(score) || std::isinf(score)) { |
1134 | 0 | return StatusCode::kInternal; |
1135 | 0 | } |
1136 | 411k | const auto type = model_proto_->types()->Get(i); |
1137 | 411k | if (type == PieceType_DEFAULT || type == PieceType_NORMAL) { |
1138 | 53.8k | min_score = std::min(min_score, score); |
1139 | 53.8k | } |
1140 | 411k | } |
1141 | 1.38k | } |
1142 | 1.38k | unk_score_ = min_score - kUnkPenalty; |
1143 | | |
1144 | | // Detect byte fallback support ("<0x00>" .. "<0xFF>") and verify contiguous |
1145 | | // IDs. |
1146 | 1.38k | std::fill(std::begin(byte_to_id_), std::end(byte_to_id_), -1); |
1147 | 1.38k | const std::string first_byte_piece = ByteToPiece(0); |
1148 | 1.38k | const int first_byte_id = pieces_trie_.exact_lookup(first_byte_piece); |
1149 | | |
1150 | 1.38k | if (first_byte_id >= 0 && first_byte_id < static_cast<int>(vocab_size) && |
1151 | 1.38k | IsByte(first_byte_id)) { |
1152 | 1.38k | byte_fallback_start_id_ = first_byte_id; |
1153 | 355k | for (int i = 0; i < 256; ++i) { |
1154 | 353k | const std::string piece = ByteToPiece(i); |
1155 | 353k | const int id = pieces_trie_.exact_lookup(piece); |
1156 | 353k | if (id == -1 || id != byte_fallback_start_id_ + i || !IsByte(id)) { |
1157 | 0 | return StatusCode::kInternal; |
1158 | 0 | } |
1159 | 353k | byte_to_id_[i] = id; |
1160 | 353k | } |
1161 | 1.38k | } else { |
1162 | 7 | byte_fallback_start_id_ = -1; |
1163 | 7 | } |
1164 | | |
1165 | 1.38k | if (unk_id_ == -1 && byte_fallback_start_id_ == -1) { |
1166 | 7 | return StatusCode::kInternal; |
1167 | 7 | } |
1168 | | |
1169 | 1.38k | return StatusCode::kOk; |
1170 | 1.38k | } |
1171 | | |
1172 | 0 | std::string_view Model::unk_surface() const { |
1173 | 0 | if (model_proto_ == nullptr || model_proto_->unk_surface() == nullptr) { |
1174 | 0 | return " \xe2\x81\x87 "; |
1175 | 0 | } |
1176 | 0 | const auto* s = model_proto_->unk_surface(); |
1177 | 0 | return std::string_view(s->c_str(), s->size()); |
1178 | 0 | } |
1179 | | |
1180 | 0 | int Model::PieceToId(std::string_view piece) const { |
1181 | 0 | const int id = pieces_trie_.exact_lookup(piece); |
1182 | 0 | return id == -1 ? unk_id_ : id; |
1183 | 0 | } |
1184 | | |
1185 | 0 | std::string_view Model::IdToPiece(int id) const { |
1186 | 0 | assert(id >= 0 && id < vocab_size()); |
1187 | 0 | const auto* s = model_proto_->pieces()->Get(id); |
1188 | 0 | return std::string_view(s->c_str(), s->size()); |
1189 | 0 | } |
1190 | | |
1191 | | void Model::EncodeChunk(std::string_view chunk, std::vector<int>* ids, |
1192 | | std::vector<std::string_view>* pieces, float alpha, |
1193 | 2.72k | const FunctionRef<float()>* uniform_sampler) const { |
1194 | 2.72k | if (model_type_ == ModelType_BPE) { |
1195 | | // O(L) direct mapping shortcut for isolated chunks guaranteed to encode as |
1196 | | // a single token. |
1197 | 0 | if (uniform_sampler == nullptr) { |
1198 | 0 | if (const int id = pieces_trie_.exact_lookup(chunk); |
1199 | 0 | IsDirectMapping(id)) { |
1200 | 0 | ids->push_back(id); |
1201 | 0 | if (pieces != nullptr) { |
1202 | 0 | pieces->push_back(chunk); |
1203 | 0 | } |
1204 | 0 | return; |
1205 | 0 | } |
1206 | 0 | } |
1207 | 0 | EncodeBPE(chunk, ids, pieces, alpha, uniform_sampler); |
1208 | 2.72k | } else { |
1209 | 2.72k | EncodeUnigram(chunk, ids, pieces, alpha, uniform_sampler); |
1210 | 2.72k | } |
1211 | 2.72k | } |
1212 | | |
1213 | | void Model::Encode(std::string_view normalized, std::vector<int>* ids, |
1214 | | std::vector<std::string_view>* pieces, float alpha, |
1215 | 2.72k | const FunctionRef<float()>* uniform_sampler) const { |
1216 | 2.72k | if (status_ != StatusCode::kOk || normalized.empty()) { |
1217 | 0 | return; |
1218 | 0 | } |
1219 | | |
1220 | | // Apply character-bigram pre-tokenization only for BPE (reducing O(N log N) |
1221 | | // heap merges to O(N log(N/k))), as Unigram Viterbi DP is already O(N). |
1222 | 2.72k | if (model_type_ != ModelType_BPE || !char_bigram_trie_.has_array()) { |
1223 | 2.72k | EncodeChunk(normalized, ids, pieces, alpha, uniform_sampler); |
1224 | 2.72k | return; |
1225 | 2.72k | } |
1226 | | |
1227 | 0 | PretokenizeAtSafeBoundaries(normalized, [&](std::string_view chunk) { |
1228 | 0 | if (!chunk.empty()) { |
1229 | 0 | EncodeChunk(chunk, ids, pieces, alpha, uniform_sampler); |
1230 | 0 | } |
1231 | 0 | }); |
1232 | 0 | } |
1233 | | |
1234 | | StatusCode Model::Normalize(std::string_view input, std::string* normalized, |
1235 | 2.76k | std::vector<size_t>* offset) const { |
1236 | 2.76k | if (status_ != StatusCode::kOk) return status_; |
1237 | 2.76k | return normalizer_.Normalize(input, normalized, offset); |
1238 | 2.76k | } |
1239 | | |
1240 | | StatusCode Model::PretokenizeAtSafeBoundaries( |
1241 | | std::string_view normalized, |
1242 | 0 | FunctionRef<void(std::string_view)> receiver) const { |
1243 | 0 | if (normalized.empty()) { |
1244 | 0 | return StatusCode::kOk; |
1245 | 0 | } |
1246 | 0 | if (!char_bigram_trie_.has_array()) { |
1247 | 0 | receiver(normalized); |
1248 | 0 | return StatusCode::kOk; |
1249 | 0 | } |
1250 | | |
1251 | 0 | auto trie = char_bigram_trie_.view(); |
1252 | |
|
1253 | 0 | auto get_root_node_pos = [this, &trie](std::string_view piece) -> uint32_t { |
1254 | 0 | if (piece.size() == 1) { |
1255 | 0 | return root_ascii_table_[static_cast<unsigned char>(piece[0])]; |
1256 | 0 | } |
1257 | 0 | return trie.transition(0U, piece); |
1258 | 0 | }; |
1259 | |
|
1260 | 0 | StringScanner scanner(normalized); |
1261 | 0 | const char* chunk_start = scanner.data(); |
1262 | 0 | std::string_view prev_char = scanner.ConsumeNext(); |
1263 | 0 | uint32_t prev_node_pos = get_root_node_pos(prev_char); |
1264 | |
|
1265 | 0 | while (!scanner.empty()) { |
1266 | 0 | if (static_cast<unsigned char>(*scanner.data()) < 0x80 && |
1267 | 0 | scanner.remaining_view().size() >= 8) { |
1268 | | // 64-bit SWAR fast-forward for 8 contiguous ASCII letters ('a'-'z', |
1269 | | // 'A'-'Z'). |
1270 | 0 | const uint64_t val = LoadLe64(scanner.data()); |
1271 | 0 | const uint64_t lower = val | 0x2020202020202020ULL; |
1272 | 0 | const uint64_t sub = lower - 0x6161616161616161ULL; |
1273 | 0 | const uint64_t bad_mask = |
1274 | 0 | (val | sub | (0x7A7A7A7A7A7A7A7AULL - lower)) & 0x8080808080808080ULL; |
1275 | 0 | const int count = |
1276 | 0 | (bad_mask == 0) ? 8 |
1277 | 0 | : static_cast<int>(FirstMatchedByteOffset(bad_mask)); |
1278 | 0 | if (count > 0) { |
1279 | 0 | scanner.Advance(count); |
1280 | 0 | prev_node_pos = |
1281 | 0 | root_ascii_table_[static_cast<unsigned char>(scanner.data()[-1])]; |
1282 | 0 | continue; |
1283 | 0 | } |
1284 | 0 | } |
1285 | | |
1286 | 0 | const char* curr_pos = scanner.data(); |
1287 | 0 | std::string_view curr_char = scanner.ConsumeNext(); |
1288 | |
|
1289 | 0 | int next_node_pos = -1; |
1290 | 0 | if (prev_node_pos != DoubleArray::View::kInvalidNodePos) { |
1291 | 0 | uint32_t curr_node = trie.transition(prev_node_pos, curr_char); |
1292 | 0 | next_node_pos = trie.leaf_value(curr_node); |
1293 | 0 | } |
1294 | |
|
1295 | 0 | if (next_node_pos >= 0) { |
1296 | 0 | prev_node_pos = static_cast<uint32_t>(next_node_pos); |
1297 | 0 | } else { |
1298 | 0 | receiver(std::string_view(chunk_start, curr_pos - chunk_start)); |
1299 | 0 | chunk_start = curr_pos; |
1300 | 0 | prev_node_pos = get_root_node_pos(curr_char); |
1301 | 0 | } |
1302 | 0 | } |
1303 | |
|
1304 | 0 | if (chunk_start < scanner.data()) { |
1305 | 0 | receiver(std::string_view(chunk_start, scanner.data() - chunk_start)); |
1306 | 0 | } |
1307 | |
|
1308 | 0 | return StatusCode::kOk; |
1309 | 0 | } |
1310 | | |
1311 | | void Model::EncodeUnigram(std::string_view normalized, std::vector<int>* ids, |
1312 | | std::vector<std::string_view>* pieces, float alpha, |
1313 | 2.72k | const FunctionRef<float()>* uniform_sampler) const { |
1314 | 2.72k | struct BestPathNode { |
1315 | 2.72k | int id = -1; |
1316 | 2.72k | float best_path_score = 0; |
1317 | 2.72k | int starts_at = -1; |
1318 | 2.72k | }; |
1319 | | |
1320 | 2.72k | const bool has_sampler = (uniform_sampler != nullptr); |
1321 | | |
1322 | | // Perturb scores with Gumbel(0, 1) noise scaled by `alpha` for stochastic |
1323 | | // Unigram sampling (`s + alpha * G`), using std::clamp to avoid log(0). |
1324 | 153M | auto add_gumbel = [alpha, uniform_sampler, has_sampler](float s) { |
1325 | 153M | if (!has_sampler) return s; |
1326 | 0 | const float u = std::clamp((*uniform_sampler)(), 1e-6f, 1.0f - 1e-6f); |
1327 | 0 | return s + alpha * (-std::log(-std::log(u))); |
1328 | 153M | }; |
1329 | | |
1330 | 2.72k | const int size = normalized.size(); |
1331 | 2.72k | const float unk_penalty_score = unk_score(); |
1332 | 2.72k | InlineVector<BestPathNode, 128> best_path_ends_at(size + 1); |
1333 | 2.72k | int starts_at = 0; |
1334 | | // Re-center accumulated Viterbi scores when exceeding +/-kScoreResetThreshold |
1335 | | // to prevent float32 significand precision loss on long inputs. |
1336 | 2.72k | const float kScoreResetThreshold = score_reset_threshold_; |
1337 | 2.72k | int max_frontier = 0; |
1338 | 2.72k | StringScanner scanner(normalized); |
1339 | 151M | while (starts_at < size) { |
1340 | 151M | float best_path_score_till_here = |
1341 | 151M | best_path_ends_at[starts_at].best_path_score; |
1342 | 151M | if (std::isfinite(best_path_score_till_here) && |
1343 | 151M | (best_path_score_till_here < -kScoreResetThreshold || |
1344 | 151M | best_path_score_till_here > kScoreResetThreshold)) { |
1345 | 17.1k | const float offset = best_path_score_till_here; |
1346 | 34.7k | for (int i = starts_at; i <= max_frontier; ++i) { |
1347 | 17.6k | if (i == starts_at || best_path_ends_at[i].starts_at != -1) { |
1348 | 17.4k | best_path_ends_at[i].best_path_score -= offset; |
1349 | 17.4k | } |
1350 | 17.6k | } |
1351 | 17.1k | best_path_score_till_here = 0.0f; |
1352 | 17.1k | } |
1353 | 151M | bool has_single_node = false; |
1354 | 151M | const int mblen = static_cast<int>(scanner.NextLen()); |
1355 | 151M | pieces_trie_.common_prefix_lookup( |
1356 | 151M | scanner.remaining_view(), [&](int ret, size_t length) { |
1357 | 29.2M | if (IsInvisible(ret)) return; |
1358 | 29.2M | const int end_pos = starts_at + static_cast<int>(length); |
1359 | 29.2M | max_frontier = std::max(max_frontier, end_pos); |
1360 | 29.2M | auto& target_node = best_path_ends_at[end_pos]; |
1361 | 29.2M | const auto score = |
1362 | 29.2M | IsUserDefined(ret) ? GetUserDefinedScore(length) : GetScore(ret); |
1363 | 29.2M | const auto candidate_best_path_score = |
1364 | 29.2M | add_gumbel(score) + best_path_score_till_here; |
1365 | 29.2M | if (target_node.starts_at == -1 || |
1366 | 28.6M | candidate_best_path_score > target_node.best_path_score) { |
1367 | 28.6M | target_node.best_path_score = candidate_best_path_score; |
1368 | 28.6M | target_node.starts_at = starts_at; |
1369 | 28.6M | target_node.id = ret; |
1370 | 28.6M | } |
1371 | 29.2M | if (!has_single_node && length == static_cast<size_t>(mblen)) { |
1372 | 27.4M | has_single_node = true; |
1373 | 27.4M | } |
1374 | 29.2M | }); |
1375 | 151M | if (!has_single_node) { |
1376 | 124M | const int end_pos = starts_at + mblen; |
1377 | 124M | max_frontier = std::max(max_frontier, end_pos); |
1378 | 124M | auto& target_node = best_path_ends_at[end_pos]; |
1379 | 124M | const auto candidate_best_path_score = |
1380 | 124M | add_gumbel(unk_penalty_score) + best_path_score_till_here; |
1381 | 124M | if (target_node.starts_at == -1 || |
1382 | 124M | candidate_best_path_score > target_node.best_path_score) { |
1383 | 124M | target_node.best_path_score = candidate_best_path_score; |
1384 | 124M | target_node.starts_at = starts_at; |
1385 | 124M | target_node.id = unk_id_; |
1386 | 124M | } |
1387 | 124M | } |
1388 | 151M | starts_at += mblen; |
1389 | 151M | scanner.Advance(mblen); |
1390 | 151M | } |
1391 | | |
1392 | 2.72k | const size_t start_ids_index = ids->size(); |
1393 | 2.72k | const size_t start_pieces_index = pieces != nullptr ? pieces->size() : 0; |
1394 | 2.72k | int ends_at = size; |
1395 | 151M | while (ends_at > 0) { |
1396 | 151M | const auto& node = best_path_ends_at[ends_at]; |
1397 | 151M | EmitPiece<true>(node.id, |
1398 | 151M | normalized.substr(node.starts_at, ends_at - node.starts_at), |
1399 | 151M | ids, pieces); |
1400 | 151M | ends_at = node.starts_at; |
1401 | 151M | } |
1402 | 2.72k | std::reverse(ids->begin() + start_ids_index, ids->end()); |
1403 | 2.72k | if (pieces != nullptr) { |
1404 | 1.36k | std::reverse(pieces->begin() + start_pieces_index, pieces->end()); |
1405 | 1.36k | } |
1406 | 2.72k | } |
1407 | | |
1408 | | namespace { |
1409 | | |
1410 | | struct SymbolPair { |
1411 | | int32_t int_score; // BPE rank score. large is better. |
1412 | | uint32_t left; // left index of this pair |
1413 | | int right; // right index of this pair |
1414 | | unsigned int size; // length of this piece |
1415 | | int id; // vocabulary token ID of this pair |
1416 | | // Cached Trie node position for the merged symbol piece. |
1417 | | uint32_t trie_node_pos = DoubleArray::View::kInvalidNodePos; |
1418 | | }; |
1419 | | |
1420 | | struct SymbolPairComparator { |
1421 | 0 | bool operator()(const SymbolPair& h1, const SymbolPair& h2) const { |
1422 | 0 | if (h1.int_score != h2.int_score) { |
1423 | 0 | return h1.int_score < h2.int_score; |
1424 | 0 | } |
1425 | 0 | return h1.left > h2.left; |
1426 | 0 | } |
1427 | | }; |
1428 | | |
1429 | | struct Symbol { |
1430 | | std::string_view piece; |
1431 | | int prev; // prev index of this symbol. -1 for BOS. |
1432 | | int next; // next index of this symbol. -1 for EOS. |
1433 | | int32_t id : 31; // vocab id of this symbol. |
1434 | | uint32_t freeze : 1; // Use 32-bit integer type so MSVC packs with `id`. |
1435 | | // Cached Trie node position for `piece`, enabling direct 1-step Trie |
1436 | | // transitions from the left symbol's node when merging adjacent symbols. |
1437 | | uint32_t trie_node_pos = DoubleArray::View::kInvalidNodePos; |
1438 | | }; |
1439 | | |
1440 | | static_assert(sizeof(SymbolPair) <= 24, |
1441 | | "SymbolPair size should not exceed 24 bytes without padding."); |
1442 | | static_assert(sizeof(Symbol) <= 32, "Symbol size should not exceed 32 bytes."); |
1443 | | } // namespace |
1444 | | |
1445 | | void Model::EncodeBPE(std::string_view normalized, std::vector<int>* ids, |
1446 | | std::vector<std::string_view>* pieces, float alpha, |
1447 | 0 | const FunctionRef<float()>* uniform_sampler) const { |
1448 | 0 | if (normalized.empty()) { |
1449 | 0 | return; |
1450 | 0 | } |
1451 | | |
1452 | 0 | InlineVector<Symbol, 64> symbols; |
1453 | 0 | symbols.reserve(normalized.size()); |
1454 | |
|
1455 | 0 | const auto trie_view = pieces_trie_.view(); |
1456 | |
|
1457 | 0 | StringScanner scanner(normalized); |
1458 | 0 | int index = 0; |
1459 | 0 | while (!scanner.empty()) { |
1460 | 0 | Symbol s; |
1461 | 0 | size_t mblen = 0; |
1462 | 0 | int matched_id = -1; |
1463 | 0 | if (prefix_matcher_trie_.has_array()) { |
1464 | 0 | std::tie(matched_id, mblen) = |
1465 | 0 | prefix_matcher_trie_.longest_prefix_lookup(scanner.remaining_view()); |
1466 | 0 | } |
1467 | 0 | if (mblen > 0 && IsUserDefined(matched_id)) { |
1468 | 0 | s.piece = std::string_view(scanner.data(), mblen); |
1469 | 0 | s.id = matched_id; |
1470 | 0 | s.freeze = true; |
1471 | 0 | s.trie_node_pos = DoubleArray::View::kInvalidNodePos; |
1472 | 0 | } else { |
1473 | 0 | mblen = scanner.NextLen(); |
1474 | 0 | s.piece = std::string_view(scanner.data(), mblen); |
1475 | 0 | s.trie_node_pos = trie_view.transition(0U, s.piece); |
1476 | 0 | const int id = trie_view.leaf_value(s.trie_node_pos); |
1477 | 0 | s.id = (id == -1 || IsInvisible(id)) ? unk_id_ : id; |
1478 | 0 | s.freeze = false; |
1479 | 0 | } |
1480 | 0 | s.prev = index == 0 ? -1 : index - 1; |
1481 | 0 | scanner.Advance(mblen); |
1482 | 0 | s.next = scanner.empty() ? -1 : index + 1; |
1483 | 0 | ++index; |
1484 | 0 | symbols.emplace_back(s); |
1485 | 0 | } |
1486 | |
|
1487 | 0 | if (symbols.empty()) { |
1488 | 0 | return; |
1489 | 0 | } |
1490 | | |
1491 | | // Reverse merge rules, lazily allocated only when an UNUSED piece is queued. |
1492 | | // key: merged UNUSED piece, value: byte length of its left child. |
1493 | | // Recorded when a pair is queued (not when merged) to match canonical |
1494 | | // SentencePiece, where later entries overwrite earlier ones. |
1495 | 0 | std::unique_ptr<std::unordered_map<std::string_view, size_t>> rev_merge; |
1496 | | |
1497 | | // BPE-Dropout (Provilkov et al., ACL 2020): `alpha` is the probability (p in |
1498 | | // [0, 1]) of dropping a merge. When alpha >= 1.0f, 100% of merges are |
1499 | | // skipped, so we bypass agenda creation and directly output initial symbols. |
1500 | 0 | if (alpha < 1.0f) { |
1501 | 0 | InlineVector<SymbolPair, 64> agenda_vec; |
1502 | 0 | agenda_vec.reserve(symbols.size()); |
1503 | |
|
1504 | 0 | const bool has_unused = has_unused_; |
1505 | |
|
1506 | 0 | if (symbols.size() > 1) { |
1507 | 0 | for (size_t left = 0; left < symbols.size() - 1; ++left) { |
1508 | 0 | const size_t right = left + 1; |
1509 | 0 | if (symbols[left].freeze || symbols[right].freeze) continue; |
1510 | 0 | const uint32_t node_pos = trie_view.transition( |
1511 | 0 | symbols[left].trie_node_pos, symbols[right].piece); |
1512 | 0 | if (node_pos == DoubleArray::View::kInvalidNodePos) continue; |
1513 | 0 | const int id = trie_view.leaf_value(node_pos); |
1514 | 0 | if (id == -1 || (has_unused ? IsReservedId(id) : IsInvisible(id))) { |
1515 | 0 | continue; |
1516 | 0 | } |
1517 | 0 | SymbolPair& h = agenda_vec.emplace_back(); |
1518 | 0 | h.left = left; |
1519 | 0 | h.right = right; |
1520 | 0 | h.int_score = GetIntScore(id); |
1521 | 0 | h.size = symbols[left].piece.size() + symbols[right].piece.size(); |
1522 | 0 | h.id = id; |
1523 | 0 | h.trie_node_pos = node_pos; |
1524 | | |
1525 | | // Makes `rev_merge` for resegmentation. |
1526 | 0 | if (has_unused && IsUnused(id)) { |
1527 | 0 | if (rev_merge == nullptr) { |
1528 | 0 | rev_merge = std::make_unique< |
1529 | 0 | std::unordered_map<std::string_view, size_t>>(); |
1530 | 0 | } |
1531 | 0 | const std::string_view piece( |
1532 | 0 | symbols[left].piece.data(), |
1533 | 0 | symbols[left].piece.size() + symbols[right].piece.size()); |
1534 | 0 | (*rev_merge)[piece] = symbols[left].piece.size(); |
1535 | 0 | } |
1536 | 0 | } |
1537 | 0 | } |
1538 | |
|
1539 | 0 | if (agenda_vec.size() > 1) { |
1540 | 0 | std::make_heap(agenda_vec.begin(), agenda_vec.end(), // NOLINT |
1541 | 0 | SymbolPairComparator()); |
1542 | 0 | } |
1543 | |
|
1544 | 0 | auto MaybeAddNewSymbolPair = [this, &trie_view, &symbols, &agenda_vec, |
1545 | 0 | &rev_merge, has_unused](int left, int right) { |
1546 | 0 | if (left == -1 || right == -1) return; |
1547 | 0 | const Symbol& left_symbol = symbols[left]; |
1548 | 0 | const Symbol& right_symbol = symbols[right]; |
1549 | 0 | if (left_symbol.freeze || right_symbol.freeze) return; |
1550 | 0 | const uint32_t node_pos = |
1551 | 0 | trie_view.transition(left_symbol.trie_node_pos, right_symbol.piece); |
1552 | 0 | if (node_pos == DoubleArray::View::kInvalidNodePos) return; |
1553 | 0 | const int id = trie_view.leaf_value(node_pos); |
1554 | 0 | if (id == -1 || (has_unused ? IsReservedId(id) : IsInvisible(id))) { |
1555 | 0 | return; |
1556 | 0 | } |
1557 | 0 | SymbolPair h; |
1558 | 0 | h.left = left; |
1559 | 0 | h.right = right; |
1560 | 0 | h.int_score = GetIntScore(id); |
1561 | 0 | h.size = left_symbol.piece.size() + right_symbol.piece.size(); |
1562 | 0 | h.id = id; |
1563 | 0 | h.trie_node_pos = node_pos; |
1564 | 0 | agenda_vec.push_back(h); |
1565 | 0 | std::push_heap(agenda_vec.begin(), agenda_vec.end(), // NOLINT |
1566 | 0 | SymbolPairComparator()); |
1567 | | |
1568 | | // Makes `rev_merge` for resegmentation. |
1569 | 0 | if (has_unused && IsUnused(id)) { |
1570 | 0 | if (rev_merge == nullptr) { |
1571 | 0 | rev_merge = |
1572 | 0 | std::make_unique<std::unordered_map<std::string_view, size_t>>(); |
1573 | 0 | } |
1574 | 0 | const std::string_view piece( |
1575 | 0 | left_symbol.piece.data(), |
1576 | 0 | left_symbol.piece.size() + right_symbol.piece.size()); |
1577 | 0 | (*rev_merge)[piece] = left_symbol.piece.size(); |
1578 | 0 | } |
1579 | 0 | }; |
1580 | |
|
1581 | 0 | const bool has_sampler = (uniform_sampler != nullptr); |
1582 | |
|
1583 | 0 | while (!agenda_vec.empty()) { |
1584 | 0 | std::pop_heap(agenda_vec.begin(), agenda_vec.end(), // NOLINT |
1585 | 0 | SymbolPairComparator()); |
1586 | 0 | SymbolPair top = agenda_vec.back(); |
1587 | 0 | agenda_vec.pop_back(); |
1588 | | |
1589 | | // O(1) lazy invalidation check: if the sum of piece sizes no longer |
1590 | | // matches `top.size`, one of the constituent symbols was modified by a |
1591 | | // prior merge step, so we discard this stale entry. |
1592 | 0 | if (symbols[top.left].piece.empty() || symbols[top.right].piece.empty() || |
1593 | 0 | symbols[top.left].piece.size() + symbols[top.right].piece.size() != |
1594 | 0 | top.size) { |
1595 | 0 | continue; |
1596 | 0 | } |
1597 | | |
1598 | 0 | if (has_sampler && (*uniform_sampler)() < alpha) { |
1599 | 0 | continue; |
1600 | 0 | } |
1601 | | |
1602 | 0 | const std::string_view piece( |
1603 | 0 | symbols[top.left].piece.data(), |
1604 | 0 | symbols[top.left].piece.size() + symbols[top.right].piece.size()); |
1605 | 0 | symbols[top.left].piece = piece; |
1606 | 0 | symbols[top.left].id = top.id; |
1607 | 0 | symbols[top.left].trie_node_pos = top.trie_node_pos; |
1608 | 0 | symbols[top.right].piece = std::string_view(); |
1609 | |
|
1610 | 0 | symbols[top.left].next = symbols[top.right].next; |
1611 | 0 | if (symbols[top.right].next != -1) { |
1612 | 0 | symbols[symbols[top.right].next].prev = top.left; |
1613 | 0 | } |
1614 | |
|
1615 | 0 | MaybeAddNewSymbolPair(symbols[top.left].prev, top.left); |
1616 | 0 | MaybeAddNewSymbolPair(top.left, symbols[top.left].next); |
1617 | 0 | } |
1618 | 0 | } |
1619 | |
|
1620 | 0 | if (rev_merge == nullptr) { |
1621 | 0 | for (int index = 0; index != -1; index = symbols[index].next) { |
1622 | 0 | if (!symbols[index].piece.empty()) { |
1623 | 0 | EmitPiece(symbols[index].id, symbols[index].piece, ids, pieces); |
1624 | 0 | } |
1625 | 0 | } |
1626 | 0 | return; |
1627 | 0 | } |
1628 | | |
1629 | | // Limit recursion depth to prevent stack overflow on malicious models |
1630 | | // with extremely deep BPE merge chains. |
1631 | 0 | constexpr int kMaxBpeResegmentDepth = 100; |
1632 | |
|
1633 | 0 | auto resegment = [this, &rev_merge, ids, pieces](auto& self, |
1634 | 0 | std::string_view w, int id, |
1635 | 0 | int depth) -> void { |
1636 | 0 | if (id >= 0 && IsUnused(id) && depth <= kMaxBpeResegmentDepth) { |
1637 | 0 | if (const auto it = rev_merge->find(w); it != rev_merge->end()) { |
1638 | 0 | const std::string_view l = w.substr(0, it->second); |
1639 | 0 | const std::string_view r = w.substr(it->second); |
1640 | 0 | self(self, l, pieces_trie_.exact_lookup(l), depth + 1); |
1641 | 0 | self(self, r, pieces_trie_.exact_lookup(r), depth + 1); |
1642 | 0 | return; |
1643 | 0 | } |
1644 | 0 | } |
1645 | 0 | EmitPiece((id < 0 || IsInvisible(id)) ? unk_id_ : id, w, ids, pieces); |
1646 | 0 | }; |
1647 | |
|
1648 | 0 | for (int index = 0; index != -1; index = symbols[index].next) { |
1649 | 0 | if (!symbols[index].piece.empty()) { |
1650 | 0 | resegment(resegment, symbols[index].piece, symbols[index].id, 0); |
1651 | 0 | } |
1652 | 0 | } |
1653 | 0 | } |
1654 | | |
1655 | | SentencePieceLiteProcessor::SentencePieceLiteProcessor( |
1656 | 0 | std::string_view buffer) { |
1657 | 0 | model_ = std::make_unique<Model>(buffer); |
1658 | 0 | status_ = model_->status(); |
1659 | 0 | if (status_ != StatusCode::kOk) model_.reset(); |
1660 | 0 | } |
1661 | | |
1662 | | SentencePieceLiteProcessor::SentencePieceLiteProcessor( |
1663 | | std::shared_ptr<std::string> shared_buffer) |
1664 | 4.89k | : shared_buffer_(std::move(shared_buffer)) { |
1665 | 4.89k | if (shared_buffer_ == nullptr) { |
1666 | 0 | status_ = StatusCode::kInvalidArgument; |
1667 | 0 | return; |
1668 | 0 | } |
1669 | 4.89k | model_ = std::make_unique<Model>(*shared_buffer_); |
1670 | 4.89k | status_ = model_->status(); |
1671 | 4.89k | if (status_ != StatusCode::kOk) model_.reset(); |
1672 | 4.89k | } |
1673 | | |
1674 | 4.89k | SentencePieceLiteProcessor::~SentencePieceLiteProcessor() = default; |
1675 | | |
1676 | 4.89k | StatusCode SentencePieceLiteProcessor::status() const { return status_; } |
1677 | | |
1678 | | StatusCode SentencePieceLiteProcessor::Normalize( |
1679 | | std::string_view input, std::string* output, |
1680 | 2.76k | std::vector<size_t>* offset) const { |
1681 | 2.76k | if (model_ == nullptr) return StatusCode::kFailedPrecondition; |
1682 | 2.76k | if (output == nullptr || input.size() > kMaxInputLength) { |
1683 | 0 | return StatusCode::kInvalidArgument; |
1684 | 0 | } |
1685 | 2.76k | return model_->Normalize(input, output, offset); |
1686 | 2.76k | } |
1687 | | |
1688 | | bool SentencePieceLiteProcessor::CanSkipNormalization( |
1689 | 2.76k | std::string_view input) const { |
1690 | 2.76k | return model_ != nullptr && input.size() <= kMaxInputLength && |
1691 | 2.76k | model_->CanSkipNormalization(input); |
1692 | 2.76k | } |
1693 | | |
1694 | | StatusCode SentencePieceLiteProcessor::Encode(std::string_view input, |
1695 | 1.38k | std::vector<int>* ids) const { |
1696 | 1.38k | if (CanSkipNormalization(input)) { |
1697 | 1 | return EncodeNormalized(input, ids); |
1698 | 1 | } |
1699 | 1.38k | std::string normalized; |
1700 | 1.38k | LITE_RETURN_IF_ERROR(Normalize(input, &normalized)); |
1701 | 1.38k | return EncodeNormalized(normalized, ids); |
1702 | 1.38k | } |
1703 | | |
1704 | | namespace { |
1705 | | template <typename EncodeFunc> |
1706 | | StatusCode EncodeNormalizedHelper(const Model* model, |
1707 | | std::string_view normalized, |
1708 | | std::vector<int>* ids, |
1709 | | std::vector<std::string_view>* pieces, |
1710 | 2.74k | EncodeFunc&& encode_func) { |
1711 | 2.74k | if (model == nullptr) { |
1712 | 0 | return StatusCode::kFailedPrecondition; |
1713 | 0 | } |
1714 | 2.74k | if (normalized.size() > kMaxInputLength || ids == nullptr) { |
1715 | 0 | return StatusCode::kInvalidArgument; |
1716 | 0 | } |
1717 | 2.74k | ids->clear(); |
1718 | 2.74k | if (pieces != nullptr) pieces->clear(); |
1719 | 2.74k | if (normalized.empty()) return StatusCode::kOk; |
1720 | | |
1721 | 2.72k | encode_func(); |
1722 | 2.72k | return StatusCode::kOk; |
1723 | 2.74k | } sentencepiece_lite.cc:sentencepiece::lite::StatusCode sentencepiece::lite::(anonymous namespace)::EncodeNormalizedHelper<sentencepiece::lite::SentencePieceLiteProcessor::EncodeNormalized(std::__1::basic_string_view<char, std::__1::char_traits<char> >, std::__1::vector<int, std::__1::allocator<int> >*, std::__1::vector<std::__1::basic_string_view<char, std::__1::char_traits<char> >, std::__1::allocator<std::__1::basic_string_view<char, std::__1::char_traits<char> > > >*) const::$_0>(sentencepiece::lite::Model const*, std::__1::basic_string_view<char, std::__1::char_traits<char> >, std::__1::vector<int, std::__1::allocator<int> >*, std::__1::vector<std::__1::basic_string_view<char, std::__1::char_traits<char> >, std::__1::allocator<std::__1::basic_string_view<char, std::__1::char_traits<char> > > >*, sentencepiece::lite::SentencePieceLiteProcessor::EncodeNormalized(std::__1::basic_string_view<char, std::__1::char_traits<char> >, std::__1::vector<int, std::__1::allocator<int> >*, std::__1::vector<std::__1::basic_string_view<char, std::__1::char_traits<char> >, std::__1::allocator<std::__1::basic_string_view<char, std::__1::char_traits<char> > > >*) const::$_0&&) Line | Count | Source | 1710 | 2.74k | EncodeFunc&& encode_func) { | 1711 | 2.74k | if (model == nullptr) { | 1712 | 0 | return StatusCode::kFailedPrecondition; | 1713 | 0 | } | 1714 | 2.74k | if (normalized.size() > kMaxInputLength || ids == nullptr) { | 1715 | 0 | return StatusCode::kInvalidArgument; | 1716 | 0 | } | 1717 | 2.74k | ids->clear(); | 1718 | 2.74k | if (pieces != nullptr) pieces->clear(); | 1719 | 2.74k | if (normalized.empty()) return StatusCode::kOk; | 1720 | | | 1721 | 2.72k | encode_func(); | 1722 | 2.72k | return StatusCode::kOk; | 1723 | 2.74k | } |
Unexecuted instantiation: sentencepiece_lite.cc:sentencepiece::lite::StatusCode sentencepiece::lite::(anonymous namespace)::EncodeNormalizedHelper<sentencepiece::lite::SentencePieceLiteProcessor::EncodeNormalizedChunk(std::__1::basic_string_view<char, std::__1::char_traits<char> >, std::__1::vector<int, std::__1::allocator<int> >*, std::__1::vector<std::__1::basic_string_view<char, std::__1::char_traits<char> >, std::__1::allocator<std::__1::basic_string_view<char, std::__1::char_traits<char> > > >*) const::$_0>(sentencepiece::lite::Model const*, std::__1::basic_string_view<char, std::__1::char_traits<char> >, std::__1::vector<int, std::__1::allocator<int> >*, std::__1::vector<std::__1::basic_string_view<char, std::__1::char_traits<char> >, std::__1::allocator<std::__1::basic_string_view<char, std::__1::char_traits<char> > > >*, sentencepiece::lite::SentencePieceLiteProcessor::EncodeNormalizedChunk(std::__1::basic_string_view<char, std::__1::char_traits<char> >, std::__1::vector<int, std::__1::allocator<int> >*, std::__1::vector<std::__1::basic_string_view<char, std::__1::char_traits<char> >, std::__1::allocator<std::__1::basic_string_view<char, std::__1::char_traits<char> > > >*) const::$_0&&) Unexecuted instantiation: sentencepiece_lite.cc:sentencepiece::lite::StatusCode sentencepiece::lite::(anonymous namespace)::EncodeNormalizedHelper<sentencepiece::lite::SentencePieceLiteProcessor::SampleNormalized(std::__1::basic_string_view<char, std::__1::char_traits<char> >, float, absl::lts_20260817::FunctionRef<float ()>, std::__1::vector<int, std::__1::allocator<int> >*, std::__1::vector<std::__1::basic_string_view<char, std::__1::char_traits<char> >, std::__1::allocator<std::__1::basic_string_view<char, std::__1::char_traits<char> > > >*) const::$_0>(sentencepiece::lite::Model const*, std::__1::basic_string_view<char, std::__1::char_traits<char> >, std::__1::vector<int, std::__1::allocator<int> >*, std::__1::vector<std::__1::basic_string_view<char, std::__1::char_traits<char> >, std::__1::allocator<std::__1::basic_string_view<char, std::__1::char_traits<char> > > >*, sentencepiece::lite::SentencePieceLiteProcessor::SampleNormalized(std::__1::basic_string_view<char, std::__1::char_traits<char> >, float, absl::lts_20260817::FunctionRef<float ()>, std::__1::vector<int, std::__1::allocator<int> >*, std::__1::vector<std::__1::basic_string_view<char, std::__1::char_traits<char> >, std::__1::allocator<std::__1::basic_string_view<char, std::__1::char_traits<char> > > >*) const::$_0&&) |
1724 | | } // namespace |
1725 | | |
1726 | | StatusCode SentencePieceLiteProcessor::EncodeNormalized( |
1727 | | std::string_view normalized, std::vector<int>* ids, |
1728 | 2.74k | std::vector<std::string_view>* pieces) const { |
1729 | 2.74k | return EncodeNormalizedHelper(model_.get(), normalized, ids, pieces, [&] { |
1730 | 2.72k | model_->Encode(normalized, ids, pieces); |
1731 | 2.72k | }); |
1732 | 2.74k | } |
1733 | | |
1734 | | StatusCode SentencePieceLiteProcessor::EncodeNormalizedChunk( |
1735 | | std::string_view normalized_chunk, std::vector<int>* ids, |
1736 | 0 | std::vector<std::string_view>* pieces) const { |
1737 | 0 | return EncodeNormalizedHelper( |
1738 | 0 | model_.get(), normalized_chunk, ids, pieces, |
1739 | 0 | [&] { model_->EncodeChunk(normalized_chunk, ids, pieces); }); |
1740 | 0 | } |
1741 | | |
1742 | | StatusCode SentencePieceLiteProcessor::SampleNormalized( |
1743 | | std::string_view normalized, float alpha, |
1744 | | FunctionRef<float()> uniform_sampler, std::vector<int>* ids, |
1745 | 0 | std::vector<std::string_view>* pieces) const { |
1746 | 0 | if (alpha < 0.0f || !std::isfinite(alpha)) { |
1747 | 0 | return StatusCode::kInvalidArgument; |
1748 | 0 | } |
1749 | 0 | return EncodeNormalizedHelper(model_.get(), normalized, ids, pieces, [&] { |
1750 | 0 | model_->Encode(normalized, ids, pieces, alpha, &uniform_sampler); |
1751 | 0 | }); |
1752 | 0 | } |
1753 | | |
1754 | | StatusCode SentencePieceLiteProcessor::PretokenizeAtSafeBoundaries( |
1755 | | std::string_view normalized, |
1756 | 0 | FunctionRef<void(std::string_view)> receiver) const { |
1757 | 0 | if (model_ == nullptr) { |
1758 | 0 | return StatusCode::kFailedPrecondition; |
1759 | 0 | } |
1760 | 0 | if (normalized.size() > kMaxInputLength) { |
1761 | 0 | return StatusCode::kInvalidArgument; |
1762 | 0 | } |
1763 | 0 | return model_->PretokenizeAtSafeBoundaries(normalized, receiver); |
1764 | 0 | } |
1765 | | |
1766 | | StatusCode SentencePieceLiteProcessor::Decode( |
1767 | | Span<const int> ids, std::string* output, |
1768 | 0 | std::vector<std::string_view>* pieces) const { |
1769 | 0 | if (model_ == nullptr) { |
1770 | 0 | return StatusCode::kFailedPrecondition; |
1771 | 0 | } |
1772 | 0 | if (output == nullptr || ids.size() > kMaxInputLength) { |
1773 | 0 | return StatusCode::kInvalidArgument; |
1774 | 0 | } |
1775 | 0 | output->clear(); |
1776 | 0 | output->reserve(ids.size()); |
1777 | 0 | if (pieces != nullptr) { |
1778 | 0 | pieces->clear(); |
1779 | 0 | pieces->resize(ids.size(), std::string_view()); |
1780 | 0 | } |
1781 | | |
1782 | | // Store temporary byte offsets in pieces->data() via reinterpret_cast to |
1783 | | // avoid heap allocations and resolve them to string_views after decoding. |
1784 | | // +1/-1 offset prevents 0x0 nullptr assertions in libc++ std::string_view |
1785 | | // hardening. |
1786 | 0 | auto set_offset = [&](size_t idx, size_t begin, size_t end) { |
1787 | 0 | if (pieces != nullptr) { |
1788 | 0 | (*pieces)[idx] = std::string_view( |
1789 | 0 | reinterpret_cast<const char*>(static_cast<uintptr_t>(begin + 1)), |
1790 | 0 | end - begin); |
1791 | 0 | } |
1792 | 0 | }; |
1793 | |
|
1794 | 0 | InlineVector<unsigned char, 64> accumulated_bytes; |
1795 | 0 | size_t first_byte_index = 0; |
1796 | |
|
1797 | 0 | auto flush_bytes = [&]() { |
1798 | 0 | if (accumulated_bytes.empty()) return; |
1799 | 0 | size_t offset = 0; |
1800 | 0 | while (offset < accumulated_bytes.size()) { |
1801 | 0 | std::string_view bytes_view( |
1802 | 0 | reinterpret_cast<const char*>(accumulated_bytes.data() + offset), |
1803 | 0 | accumulated_bytes.size() - offset); |
1804 | 0 | size_t consumed = 0; |
1805 | 0 | if (pieces == nullptr) { |
1806 | 0 | consumed = utf8::SpanStructurallyValid(bytes_view); |
1807 | 0 | if (consumed > 0) { |
1808 | 0 | output->append(bytes_view.data(), consumed); |
1809 | 0 | } else { |
1810 | 0 | output->append(kReplacementChar); |
1811 | 0 | consumed = 1; |
1812 | 0 | } |
1813 | 0 | } else { |
1814 | 0 | const bool is_valid = utf8::IsValidUTF8(bytes_view, &consumed); |
1815 | 0 | const size_t char_begin = output->size(); |
1816 | 0 | if (!is_valid) { |
1817 | 0 | output->append(kReplacementChar); |
1818 | 0 | } else { |
1819 | 0 | output->append(bytes_view.data(), consumed); |
1820 | 0 | } |
1821 | 0 | const size_t char_end = output->size(); |
1822 | 0 | for (size_t j = 0; j < consumed; ++j) { |
1823 | 0 | set_offset(first_byte_index + offset + j, char_begin, |
1824 | 0 | (j == consumed - 1) ? char_end : char_begin); |
1825 | 0 | } |
1826 | 0 | } |
1827 | 0 | offset += consumed; |
1828 | 0 | } |
1829 | 0 | accumulated_bytes.clear(); |
1830 | 0 | }; |
1831 | |
|
1832 | 0 | bool is_bos_ws = true; |
1833 | 0 | bool bos_ws_seen = false; |
1834 | 0 | const bool add_dummy_prefix = model_->add_dummy_prefix(); |
1835 | 0 | const bool remove_extra_whitespaces = model_->remove_extra_whitespaces(); |
1836 | 0 | const bool has_internal_space_symbol = model_->has_non_leading_space_symbol(); |
1837 | |
|
1838 | 0 | const int vocab_size = model_->vocab_size(); |
1839 | 0 | for (size_t i = 0; i < ids.size(); ++i) { |
1840 | 0 | const int id = ids[i]; |
1841 | 0 | if (id < 0 || id >= vocab_size) { |
1842 | 0 | output->clear(); |
1843 | 0 | if (pieces != nullptr) { |
1844 | 0 | pieces->clear(); |
1845 | 0 | } |
1846 | 0 | return StatusCode::kOutOfRange; |
1847 | 0 | } |
1848 | 0 | if (model_->IsUnknown(id)) { |
1849 | 0 | flush_bytes(); |
1850 | 0 | const size_t begin_pos = output->size(); |
1851 | 0 | output->append(model_->unk_surface()); |
1852 | 0 | set_offset(i, begin_pos, output->size()); |
1853 | 0 | is_bos_ws = false; |
1854 | 0 | continue; |
1855 | 0 | } |
1856 | | |
1857 | 0 | if (const int byte = model_->IdToByte(id); byte >= 0) { |
1858 | 0 | if (accumulated_bytes.empty()) { |
1859 | 0 | first_byte_index = i; |
1860 | 0 | } |
1861 | 0 | accumulated_bytes.push_back(static_cast<unsigned char>(byte)); |
1862 | 0 | } else { |
1863 | 0 | flush_bytes(); |
1864 | |
|
1865 | 0 | if (model_->IsControl(id)) { |
1866 | 0 | set_offset(i, output->size(), output->size()); |
1867 | 0 | continue; |
1868 | 0 | } |
1869 | | |
1870 | | // Match canonical: clear is_bos_ws BEFORE stripping, based on whether |
1871 | | // we've already seen a bos_ws or any non-empty output. |
1872 | 0 | if (bos_ws_seen || !output->empty()) { |
1873 | 0 | is_bos_ws = false; |
1874 | 0 | } |
1875 | |
|
1876 | 0 | const std::string_view piece = model_->IdToPiece(id); |
1877 | 0 | std::string_view piece_view = piece; |
1878 | 0 | if (is_bos_ws && (add_dummy_prefix || remove_extra_whitespaces)) { |
1879 | 0 | const bool consumed = piece_view.starts_with(kSpaceSymbol); |
1880 | 0 | if (consumed) { |
1881 | 0 | piece_view.remove_prefix(kSpaceSymbol.size()); |
1882 | 0 | } |
1883 | | // Match canonical: if remove_extra_whitespaces, don't set bos_ws_seen |
1884 | | // so is_bos_ws stays true for the next token (keeps stripping). |
1885 | | // Otherwise set bos_ws_seen so is_bos_ws gets cleared next iteration. |
1886 | 0 | if (consumed && !remove_extra_whitespaces) { |
1887 | 0 | bos_ws_seen = true; |
1888 | 0 | } |
1889 | 0 | } |
1890 | |
|
1891 | 0 | const size_t begin_pos = output->size(); |
1892 | 0 | if (piece_view.starts_with(kSpaceSymbol)) { |
1893 | 0 | output->push_back(' '); |
1894 | 0 | piece_view.remove_prefix(kSpaceSymbol.size()); |
1895 | 0 | } |
1896 | 0 | if (!has_internal_space_symbol) { |
1897 | 0 | output->append(piece_view.data(), piece_view.size()); |
1898 | 0 | } else { |
1899 | 0 | ReplaceAll(piece_view, kSpaceSymbol, " ", output); |
1900 | 0 | } |
1901 | 0 | set_offset(i, begin_pos, output->size()); |
1902 | 0 | } |
1903 | 0 | } |
1904 | | |
1905 | 0 | flush_bytes(); |
1906 | |
|
1907 | 0 | if (pieces != nullptr) { |
1908 | | // TRICKY: In-place convert stored integer byte offsets to valid memory |
1909 | | // addresses by subtracting the +1 dummy offset and adding base_data. |
1910 | 0 | const char* base_data = output->data(); |
1911 | 0 | for (auto& piece : *pieces) { |
1912 | 0 | const size_t begin_offset = |
1913 | 0 | static_cast<size_t>(reinterpret_cast<uintptr_t>(piece.data())) - 1; |
1914 | 0 | piece = std::string_view(base_data + begin_offset, piece.size()); |
1915 | 0 | } |
1916 | 0 | } |
1917 | |
|
1918 | 0 | return StatusCode::kOk; |
1919 | 0 | } |
1920 | | |
1921 | 0 | size_t SentencePieceLiteProcessor::vocab_size() const { |
1922 | 0 | return model_ ? model_->vocab_size() : 0; |
1923 | 0 | } |
1924 | | |
1925 | 0 | int SentencePieceLiteProcessor::PieceToId(std::string_view piece) const { |
1926 | 0 | return model_ ? model_->PieceToId(piece) : -1; |
1927 | 0 | } |
1928 | | |
1929 | 0 | std::string_view SentencePieceLiteProcessor::IdToPiece(int id) const { |
1930 | 0 | if (model_ == nullptr) return "<unk>"; |
1931 | 0 | if (id < 0 || id >= model_->vocab_size()) return model_->unk_piece(); |
1932 | 0 | return model_->IdToPiece(id); |
1933 | 0 | } |
1934 | | |
1935 | 0 | float SentencePieceLiteProcessor::GetScore(int id) const { |
1936 | 0 | if (model_ == nullptr || id < 0 || id >= model_->vocab_size()) return 0.0f; |
1937 | 0 | return (model_->model_type() == ModelType_BPE) |
1938 | 0 | ? static_cast<float>(model_->GetIntScore(id)) |
1939 | 0 | : model_->GetScore(id); |
1940 | 0 | } |
1941 | | |
1942 | 0 | int SentencePieceLiteProcessor::unk_id() const { |
1943 | 0 | return model_ ? model_->unk_id() : -1; |
1944 | 0 | } |
1945 | | |
1946 | 0 | int SentencePieceLiteProcessor::bos_id() const { |
1947 | 0 | return model_ ? model_->bos_id() : -1; |
1948 | 0 | } |
1949 | | |
1950 | 0 | int SentencePieceLiteProcessor::eos_id() const { |
1951 | 0 | return model_ ? model_->eos_id() : -1; |
1952 | 0 | } |
1953 | | |
1954 | 0 | int SentencePieceLiteProcessor::pad_id() const { |
1955 | 0 | return model_ ? model_->pad_id() : -1; |
1956 | 0 | } |
1957 | | |
1958 | 0 | int SentencePieceLiteProcessor::piece_type(int id) const { |
1959 | 0 | if (model_ == nullptr || id < 0 || id >= model_->vocab_size()) return -1; |
1960 | 0 | return model_->piece_type(id); |
1961 | 0 | } |
1962 | | |
1963 | | void SentencePieceLiteProcessor::SetScoreResetThresholdForTesting( |
1964 | 0 | float threshold) { |
1965 | 0 | if (model_) model_->SetScoreResetThresholdForTesting(threshold); |
1966 | 0 | } |
1967 | | |
1968 | | } // namespace sentencepiece::lite |