cui-llama.rn 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/LICENSE +20 -0
  2. package/README.md +330 -0
  3. package/android/build.gradle +107 -0
  4. package/android/gradle.properties +5 -0
  5. package/android/src/main/AndroidManifest.xml +4 -0
  6. package/android/src/main/CMakeLists.txt +69 -0
  7. package/android/src/main/java/com/rnllama/LlamaContext.java +353 -0
  8. package/android/src/main/java/com/rnllama/RNLlama.java +446 -0
  9. package/android/src/main/java/com/rnllama/RNLlamaPackage.java +48 -0
  10. package/android/src/main/jni.cpp +635 -0
  11. package/android/src/newarch/java/com/rnllama/RNLlamaModule.java +94 -0
  12. package/android/src/oldarch/java/com/rnllama/RNLlamaModule.java +95 -0
  13. package/cpp/README.md +4 -0
  14. package/cpp/common.cpp +3237 -0
  15. package/cpp/common.h +467 -0
  16. package/cpp/ggml-aarch64.c +2193 -0
  17. package/cpp/ggml-aarch64.h +39 -0
  18. package/cpp/ggml-alloc.c +1041 -0
  19. package/cpp/ggml-alloc.h +76 -0
  20. package/cpp/ggml-backend-impl.h +153 -0
  21. package/cpp/ggml-backend.c +2225 -0
  22. package/cpp/ggml-backend.h +236 -0
  23. package/cpp/ggml-common.h +1829 -0
  24. package/cpp/ggml-impl.h +655 -0
  25. package/cpp/ggml-metal.h +65 -0
  26. package/cpp/ggml-metal.m +3273 -0
  27. package/cpp/ggml-quants.c +15022 -0
  28. package/cpp/ggml-quants.h +132 -0
  29. package/cpp/ggml.c +22034 -0
  30. package/cpp/ggml.h +2444 -0
  31. package/cpp/grammar-parser.cpp +536 -0
  32. package/cpp/grammar-parser.h +29 -0
  33. package/cpp/json-schema-to-grammar.cpp +1045 -0
  34. package/cpp/json-schema-to-grammar.h +8 -0
  35. package/cpp/json.hpp +24766 -0
  36. package/cpp/llama.cpp +21789 -0
  37. package/cpp/llama.h +1201 -0
  38. package/cpp/log.h +737 -0
  39. package/cpp/rn-llama.hpp +630 -0
  40. package/cpp/sampling.cpp +460 -0
  41. package/cpp/sampling.h +160 -0
  42. package/cpp/sgemm.cpp +1027 -0
  43. package/cpp/sgemm.h +14 -0
  44. package/cpp/unicode-data.cpp +7032 -0
  45. package/cpp/unicode-data.h +20 -0
  46. package/cpp/unicode.cpp +812 -0
  47. package/cpp/unicode.h +64 -0
  48. package/ios/RNLlama.h +11 -0
  49. package/ios/RNLlama.mm +302 -0
  50. package/ios/RNLlama.xcodeproj/project.pbxproj +278 -0
  51. package/ios/RNLlamaContext.h +39 -0
  52. package/ios/RNLlamaContext.mm +426 -0
  53. package/jest/mock.js +169 -0
  54. package/lib/commonjs/NativeRNLlama.js +10 -0
  55. package/lib/commonjs/NativeRNLlama.js.map +1 -0
  56. package/lib/commonjs/grammar.js +574 -0
  57. package/lib/commonjs/grammar.js.map +1 -0
  58. package/lib/commonjs/index.js +151 -0
  59. package/lib/commonjs/index.js.map +1 -0
  60. package/lib/module/NativeRNLlama.js +3 -0
  61. package/lib/module/NativeRNLlama.js.map +1 -0
  62. package/lib/module/grammar.js +566 -0
  63. package/lib/module/grammar.js.map +1 -0
  64. package/lib/module/index.js +129 -0
  65. package/lib/module/index.js.map +1 -0
  66. package/lib/typescript/NativeRNLlama.d.ts +107 -0
  67. package/lib/typescript/NativeRNLlama.d.ts.map +1 -0
  68. package/lib/typescript/grammar.d.ts +38 -0
  69. package/lib/typescript/grammar.d.ts.map +1 -0
  70. package/lib/typescript/index.d.ts +46 -0
  71. package/lib/typescript/index.d.ts.map +1 -0
  72. package/llama-rn.podspec +56 -0
  73. package/package.json +230 -0
  74. package/src/NativeRNLlama.ts +132 -0
  75. package/src/grammar.ts +849 -0
  76. package/src/index.ts +182 -0
@@ -0,0 +1,812 @@
1
+ #if defined(_MSC_VER)
2
+ #define _SILENCE_CXX17_CODECVT_HEADER_DEPRECATION_WARNING
3
+ #endif
4
+
5
+ #include "unicode.h"
6
+ #include "unicode-data.h"
7
+
8
+ #include <cassert>
9
+ #include <cstddef>
10
+ #include <cstdint>
11
+ #include <map>
12
+ #include <regex>
13
+ #include <stdexcept>
14
+ #include <string>
15
+ #include <unordered_map>
16
+ #include <unordered_set>
17
+ #include <utility>
18
+ #include <vector>
19
+ #include <locale>
20
+ #include <codecvt>
21
+
22
+ static std::string unicode_cpts_to_utf8(const std::vector<uint32_t> & cps) {
23
+ std::string result;
24
+ for (size_t i = 0; i < cps.size(); ++i) {
25
+ result.append(unicode_cpt_to_utf8(cps[i]));
26
+ }
27
+ return result;
28
+ }
29
+
30
+ uint32_t unicode_cpt_from_utf8(const std::string & utf8, size_t & offset) {
31
+ assert(offset < utf8.size());
32
+ if (!(utf8[offset + 0] & 0x80)) {
33
+ auto result = utf8[offset + 0];
34
+ offset += 1;
35
+ return result;
36
+ }
37
+ if (!(utf8[offset + 0] & 0x40)) {
38
+ throw std::invalid_argument("invalid character");
39
+ }
40
+ if (!(utf8[offset + 0] & 0x20)) {
41
+ if (offset + 1 >= utf8.size() || ! ((utf8[offset + 1] & 0xc0) == 0x80)) {
42
+ throw std::invalid_argument("invalid character");
43
+ }
44
+ auto result = ((utf8[offset + 0] & 0x1f) << 6) | (utf8[offset + 1] & 0x3f);
45
+ offset += 2;
46
+ return result;
47
+ }
48
+ if (!(utf8[offset + 0] & 0x10)) {
49
+ if (offset + 2 >= utf8.size() || ! ((utf8[offset + 1] & 0xc0) == 0x80) || ! ((utf8[offset + 2] & 0xc0) == 0x80)) {
50
+ throw std::invalid_argument("invalid character");
51
+ }
52
+ auto result = ((utf8[offset + 0] & 0x0f) << 12) | ((utf8[offset + 1] & 0x3f) << 6) | (utf8[offset + 2] & 0x3f);
53
+ offset += 3;
54
+ return result;
55
+ }
56
+ if (!(utf8[offset + 0] & 0x08)) {
57
+ if (offset + 3 >= utf8.size() || ! ((utf8[offset + 1] & 0xc0) == 0x80) || ! ((utf8[offset + 2] & 0xc0) == 0x80) || !((utf8[offset + 3] & 0xc0) == 0x80)) {
58
+ throw std::invalid_argument("invalid character");
59
+ }
60
+ auto result = ((utf8[offset + 0] & 0x07) << 18) | ((utf8[offset + 1] & 0x3f) << 12) | ((utf8[offset + 2] & 0x3f) << 6) | (utf8[offset + 3] & 0x3f);
61
+ offset += 4;
62
+ return result;
63
+ }
64
+ throw std::invalid_argument("failed to convert utf8 to codepoint");
65
+ }
66
+
67
+ //static std::vector<uint16_t> unicode_cpt_to_utf16(uint32_t cp) {
68
+ // std::vector<uint16_t> result;
69
+ // if (/* 0x0000 <= cp && */ cp <= 0xffff) {
70
+ // result.emplace_back(cp);
71
+ // return result;
72
+ // }
73
+ // if (0x10000 <= cp && cp <= 0x10ffff) {
74
+ // result.emplace_back(0xd800 | ((cp - 0x10000) >> 10));
75
+ // result.emplace_back(0xdc00 | ((cp - 0x10000) & 0x03ff));
76
+ // return result;
77
+ // }
78
+ // throw std::invalid_argument("failed to convert codepoint to utf16");
79
+ //}
80
+
81
+ //static std::vector<uint16_t> unicode_cpts_to_utf16(const std::vector<uint32_t> & cps) {
82
+ // std::vector<uint16_t> result;
83
+ // for (size_t i = 0; i < cps.size(); ++i) {
84
+ // auto temp = unicode_cpt_to_utf16(cps[i]);
85
+ // result.insert(result.end(), temp.begin(), temp.end());
86
+ // }
87
+ // return result;
88
+ //}
89
+
90
+ //static uint32_t unicode_cpt_from_utf16(const std::vector<uint16_t> & utf16, size_t & offset) {
91
+ // assert(offset < utf16.size());
92
+ // if (((utf16[0] >> 10) << 10) != 0xd800) {
93
+ // auto result = utf16[offset + 0];
94
+ // offset += 1;
95
+ // return result;
96
+ // }
97
+ //
98
+ // if (offset + 1 >= utf16.size() || !((utf16[1] & 0xdc00) == 0xdc00)) {
99
+ // throw std::invalid_argument("invalid character");
100
+ // }
101
+ //
102
+ // auto result = 0x10000 + (((utf16[0] & 0x03ff) << 10) | (utf16[1] & 0x03ff));
103
+ // offset += 2;
104
+ // return result;
105
+ //}
106
+
107
+ //static std::vector<uint32_t> unicode_cpts_from_utf16(const std::vector<uint16_t> & utf16) {
108
+ // std::vector<uint32_t> result;
109
+ // size_t offset = 0;
110
+ // while (offset < utf16.size()) {
111
+ // result.push_back(unicode_cpt_from_utf16(utf16, offset));
112
+ // }
113
+ // return result;
114
+ //}
115
+
116
+ static std::vector<codepoint_flags> unicode_cpt_flags_array() {
117
+ std::vector<codepoint_flags> cpt_flags(MAX_CODEPOINTS, codepoint_flags::UNDEFINED);
118
+
119
+ assert (unicode_ranges_flags.front().first == 0);
120
+ assert (unicode_ranges_flags.back().first == MAX_CODEPOINTS);
121
+ for (size_t i = 1; i < unicode_ranges_flags.size(); ++i) {
122
+ const auto range_ini = unicode_ranges_flags[i-1]; // codepoint_ini, flags
123
+ const auto range_end = unicode_ranges_flags[i]; // codepoint_end, flags
124
+ for (uint32_t cpt = range_ini.first; cpt < range_end.first; ++cpt) {
125
+ cpt_flags[cpt] = range_ini.second;
126
+ }
127
+ }
128
+
129
+ for (auto cpt : unicode_set_whitespace) {
130
+ cpt_flags[cpt].is_whitespace = true;
131
+ }
132
+
133
+ for (auto p : unicode_map_lowercase) {
134
+ cpt_flags[p.second].is_lowercase = true;
135
+ }
136
+
137
+ for (auto p : unicode_map_uppercase) {
138
+ cpt_flags[p.second].is_uppercase = true;
139
+ }
140
+
141
+ for (auto &range : unicode_ranges_nfd) { // start, last, nfd
142
+ cpt_flags[range.nfd].is_nfd = true;
143
+ }
144
+
145
+ return cpt_flags;
146
+ }
147
+
148
+ static std::unordered_map<uint8_t, std::string> unicode_byte_to_utf8_map() {
149
+ std::unordered_map<uint8_t, std::string> map;
150
+ for (int ch = 0x21; ch <= 0x7E; ++ch) { // u'!' to u'~'
151
+ assert(0 <= ch && ch < 256);
152
+ map[ch] = unicode_cpt_to_utf8(ch);
153
+ }
154
+ for (int ch = 0xA1; ch <= 0xAC; ++ch) { // u'¡' to u'¬'
155
+ assert(0 <= ch && ch < 256);
156
+ map[ch] = unicode_cpt_to_utf8(ch);
157
+ }
158
+ for (int ch = 0xAE; ch <= 0xFF; ++ch) { // u'®' to u'ÿ'
159
+ assert(0 <= ch && ch < 256);
160
+ map[ch] = unicode_cpt_to_utf8(ch);
161
+ }
162
+ auto n = 0;
163
+ for (int ch = 0; ch < 256; ++ch) {
164
+ if (map.find(ch) == map.end()) {
165
+ map[ch] = unicode_cpt_to_utf8(256 + n);
166
+ ++n;
167
+ }
168
+ }
169
+ return map;
170
+ }
171
+
172
+ static std::unordered_map<std::string, uint8_t> unicode_utf8_to_byte_map() {
173
+ std::unordered_map<std::string, uint8_t> map;
174
+ for (int ch = 0x21; ch <= 0x7E; ++ch) { // u'!' to u'~'
175
+ assert(0 <= ch && ch < 256);
176
+ map[unicode_cpt_to_utf8(ch)] = ch;
177
+ }
178
+ for (int ch = 0xA1; ch <= 0xAC; ++ch) { // u'¡' to u'¬'
179
+ assert(0 <= ch && ch < 256);
180
+ map[unicode_cpt_to_utf8(ch)] = ch;
181
+ }
182
+ for (int ch = 0xAE; ch <= 0xFF; ++ch) { // u'®' to u'ÿ'
183
+ assert(0 <= ch && ch < 256);
184
+ map[unicode_cpt_to_utf8(ch)] = ch;
185
+ }
186
+ auto n = 0;
187
+ for (int ch = 0; ch < 256; ++ch) {
188
+ if (map.find(unicode_cpt_to_utf8(ch)) == map.end()) {
189
+ map[unicode_cpt_to_utf8(256 + n)] = ch;
190
+ ++n;
191
+ }
192
+ }
193
+ return map;
194
+ }
195
+
196
+ static inline std::wstring unicode_wstring_from_utf8(const std::string & s) {
197
+ std::wstring_convert<std::codecvt_utf8<wchar_t>> conv;
198
+ return conv.from_bytes(s);
199
+ }
200
+
201
+ static std::vector<std::string> unicode_byte_encoding_process(const std::vector<std::string> & bpe_words) {
202
+ std::vector<std::string> bpe_encoded_words;
203
+ for (const auto & word : bpe_words) {
204
+ std::string text_utf;
205
+ auto utf_word = unicode_cpts_from_utf8(word);
206
+ for (size_t i = 0; i < utf_word.size(); ++i) {
207
+ text_utf += unicode_cpt_to_utf8(utf_word[i]);
208
+ }
209
+
210
+ std::string encoded_token;
211
+ for (char & c : text_utf) {
212
+ encoded_token += unicode_byte_to_utf8(c);
213
+ }
214
+ bpe_encoded_words.emplace_back(encoded_token);
215
+ }
216
+ return bpe_encoded_words;
217
+ }
218
+
219
+ // GPT2 system regex: 's|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+
220
+ static std::vector<size_t> unicode_regex_split_custom_gpt2(const std::string & text, const std::vector<size_t> & offsets) {
221
+ std::vector<size_t> bpe_offsets; // store the offset of each word
222
+ bpe_offsets.reserve(offsets.size()); // Reserve memory for the approximate size
223
+
224
+ const auto cpts = unicode_cpts_from_utf8(text);
225
+
226
+ size_t start = 0;
227
+ for (auto offset : offsets) {
228
+ const size_t offset_ini = start;
229
+ const size_t offset_end = start + offset;
230
+ assert(offset_end <= cpts.size());
231
+ start = offset_end;
232
+
233
+ static const uint32_t OUT_OF_RANGE = 0xFFFFFFFF;
234
+ auto _get_cpt = [&] (const size_t pos) -> uint32_t {
235
+ return (offset_ini <= pos && pos < offset_end) ? cpts[pos] : OUT_OF_RANGE;
236
+ };
237
+
238
+ auto _get_flags = [&] (const size_t pos) -> codepoint_flags {
239
+ return (offset_ini <= pos && pos < offset_end) ? unicode_cpt_flags(cpts[pos]) : codepoint_flags{};
240
+ };
241
+
242
+ size_t _prev_end = offset_ini;
243
+ auto _add_token = [&] (const size_t end) -> size_t {
244
+ assert(_prev_end <= end && end <= offset_end);
245
+ size_t len = end - _prev_end;
246
+ if (len > 0) {
247
+ bpe_offsets.push_back(len);
248
+ }
249
+ _prev_end = end;
250
+ //if (len > 0) {
251
+ // std::string s = "";
252
+ // for(size_t p = end-len; p < end; p++)
253
+ // s += unicode_cpt_to_utf8(cpts[p]);
254
+ // printf(">>> '%s'\n", s.c_str());
255
+ //}
256
+ return len;
257
+ };
258
+
259
+ for (size_t pos = offset_ini; pos < offset_end; /*pos++*/ ) {
260
+ const uint32_t cpt = _get_cpt(pos);
261
+ const auto flags = _get_flags(pos);
262
+
263
+ // regex: 's|'t|'re|'ve|'m|'ll|'d
264
+ if (cpt == '\'' && pos+1 < offset_end) {
265
+ uint32_t cpt_next = _get_cpt(pos+1);
266
+ if (cpt_next == 's' || cpt_next == 't' || cpt_next == 'm' || cpt_next == 'd') {
267
+ pos += _add_token(pos+2);
268
+ continue;
269
+ }
270
+ if (pos+2 < offset_end) {
271
+ uint32_t cpt_next_next = _get_cpt(pos+2);
272
+ if ((cpt_next == 'r' && cpt_next_next == 'e') ||
273
+ (cpt_next == 'v' && cpt_next_next == 'e') ||
274
+ (cpt_next == 'l' && cpt_next_next == 'l')) {
275
+ pos += _add_token(pos+3);
276
+ continue;
277
+ }
278
+ }
279
+ }
280
+
281
+ auto flags2 = (cpt == ' ' ? _get_flags(pos+1) : flags);
282
+ // regex: <space>?\p{L}+
283
+ if (flags2.is_letter) {
284
+ pos += (cpt == ' ');
285
+ while (flags2.is_letter) {
286
+ flags2 = _get_flags(++pos);
287
+ }
288
+ _add_token(pos);
289
+ continue;
290
+ }
291
+ // regex: <space>?\p{N}+
292
+ if (flags2.is_number) {
293
+ pos += (cpt == ' ');
294
+ while (flags2.is_number) {
295
+ flags2 = _get_flags(++pos);
296
+ }
297
+ _add_token(pos);
298
+ continue;
299
+ }
300
+ // regex: <space>?[^\s\p{L}\p{N}]+
301
+ if (!(flags2.is_whitespace | flags2.is_letter | flags2.is_number) && flags2.as_uint()) {
302
+ pos += (cpt == ' ');
303
+ while (!(flags2.is_whitespace | flags2.is_letter | flags2.is_number) && flags2.as_uint()) {
304
+ flags2 = _get_flags(++pos);
305
+ }
306
+ _add_token(pos);
307
+ continue;
308
+ }
309
+
310
+ size_t num_whitespaces = 0;
311
+ while (_get_flags(pos+num_whitespaces).is_whitespace) {
312
+ num_whitespaces++;
313
+ }
314
+
315
+ // regex: \s+(?!\S)
316
+ if (num_whitespaces > 1 && _get_cpt(pos+num_whitespaces) != OUT_OF_RANGE) {
317
+ pos += num_whitespaces - 1;
318
+ _add_token(pos);
319
+ continue;
320
+ }
321
+
322
+ // regex: \s+
323
+ if (num_whitespaces > 0) {
324
+ pos += num_whitespaces;
325
+ _add_token(pos);
326
+ continue;
327
+ }
328
+
329
+ // no matches
330
+ _add_token(++pos);
331
+ }
332
+ }
333
+
334
+ return bpe_offsets;
335
+ }
336
+
337
+ // LLAMA3 system regex: "(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}{1,3}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+"
338
+ static std::vector<size_t> unicode_regex_split_custom_llama3(const std::string & text, const std::vector<size_t> & offsets) {
339
+ std::vector<size_t> bpe_offsets; // store the offset of each word
340
+ bpe_offsets.reserve(offsets.size()); // Reserve memory for the approximate size
341
+
342
+ const auto cpts = unicode_cpts_from_utf8(text);
343
+
344
+ size_t start = 0;
345
+ for (auto offset : offsets) {
346
+ const size_t offset_ini = start;
347
+ const size_t offset_end = start + offset;
348
+ assert(offset_end <= cpts.size());
349
+ start = offset_end;
350
+
351
+ static const uint32_t OUT_OF_RANGE = 0xFFFFFFFF;
352
+ auto _get_cpt = [&] (const size_t pos) -> uint32_t {
353
+ return (offset_ini <= pos && pos < offset_end) ? cpts[pos] : OUT_OF_RANGE;
354
+ };
355
+
356
+ auto _get_flags = [&] (const size_t pos) -> codepoint_flags {
357
+ return (offset_ini <= pos && pos < offset_end) ? unicode_cpt_flags(cpts[pos]) : codepoint_flags{};
358
+ };
359
+
360
+ size_t _prev_end = offset_ini;
361
+ auto _add_token = [&] (const size_t end) -> size_t {
362
+ assert(_prev_end <= end && end <= offset_end);
363
+ size_t len = end - _prev_end;
364
+ if (len > 0) {
365
+ bpe_offsets.push_back(len);
366
+ }
367
+ _prev_end = end;
368
+ //if (len > 0) {
369
+ // std::string s = "";
370
+ // for(size_t p = end-len; p < end; p++)
371
+ // s += unicode_cpt_to_utf8(cpts[p]);
372
+ // printf(">>> '%s'\n", s.c_str());
373
+ //}
374
+ return len;
375
+ };
376
+
377
+ for (size_t pos = offset_ini; pos < offset_end; /*pos++*/ ) {
378
+ const uint32_t cpt = _get_cpt(pos);
379
+ const auto flags = _get_flags(pos);
380
+
381
+ // regex: (?i:'s|'t|'re|'ve|'m|'ll|'d) // case insensitive
382
+ if (cpt == '\'' && pos+1 < offset_end) {
383
+ uint32_t cpt_next = unicode_tolower(_get_cpt(pos+1));
384
+ if (cpt_next == 's' || cpt_next == 't' || cpt_next == 'm' || cpt_next == 'd') {
385
+ pos += _add_token(pos+2);
386
+ continue;
387
+ }
388
+ if (pos+2 < offset_end) {
389
+ uint32_t cpt_next_next = unicode_tolower(_get_cpt(pos+2));
390
+ if ((cpt_next == 'r' && cpt_next_next == 'e') ||
391
+ (cpt_next == 'v' && cpt_next_next == 'e') ||
392
+ (cpt_next == 'l' && cpt_next_next == 'l')) {
393
+ pos += _add_token(pos+3);
394
+ continue;
395
+ }
396
+ }
397
+ }
398
+
399
+ // regex: [^\r\n\p{L}\p{N}]?\p{L}+
400
+ if (!(cpt == '\r' || cpt == '\n' || flags.is_number)) {
401
+ if (flags.is_letter || _get_flags(pos+1).is_letter) { // one or more letters
402
+ pos++;
403
+ while (_get_flags(pos).is_letter) {
404
+ pos++;
405
+ }
406
+ _add_token(pos);
407
+ continue;
408
+ }
409
+ }
410
+
411
+ // regex: \p{N}{1,3}
412
+ if (flags.is_number) {
413
+ size_t ini = pos;
414
+ while (_get_flags(pos).is_number) {
415
+ if (++pos - ini >= 3 ) {
416
+ _add_token(pos);
417
+ ini = pos;
418
+ }
419
+ }
420
+ _add_token(pos);
421
+ continue;
422
+ }
423
+
424
+ // regex: <space>?[^\s\p{L}\p{N}]+[\r\n]*
425
+ auto flags2 = (cpt == ' ' ? _get_flags(pos+1) : flags);
426
+ if (!(flags2.is_whitespace | flags2.is_letter | flags2.is_number) && flags.as_uint()) {
427
+ pos += (cpt == ' ');
428
+ while (!(flags2.is_whitespace | flags2.is_letter | flags2.is_number) && flags2.as_uint()) {
429
+ flags2 = _get_flags(++pos);
430
+ }
431
+ uint32_t cpt2 = _get_cpt(pos);
432
+ while (cpt2 == '\r' || cpt2 == '\n') {
433
+ cpt2 = _get_cpt(++pos);
434
+ }
435
+ _add_token(pos);
436
+ continue;
437
+ }
438
+
439
+ size_t num_whitespaces = 0;
440
+ size_t last_end_r_or_n = 0;
441
+ while (_get_flags(pos+num_whitespaces).is_whitespace) {
442
+ uint32_t cpt2 = _get_cpt(pos+num_whitespaces);
443
+ if (cpt2 == '\r' || cpt2 == '\n') {
444
+ last_end_r_or_n = pos + num_whitespaces + 1;
445
+ }
446
+ num_whitespaces++;
447
+ }
448
+
449
+ // regex: \s*[\r\n]+
450
+ if (last_end_r_or_n > 0) {
451
+ pos = last_end_r_or_n;
452
+ _add_token(pos);
453
+ continue;
454
+ }
455
+
456
+ // regex: \s+(?!\S)
457
+ if (num_whitespaces > 1 && _get_cpt(pos+num_whitespaces) != OUT_OF_RANGE) {
458
+ pos += num_whitespaces - 1;
459
+ _add_token(pos);
460
+ continue;
461
+ }
462
+
463
+ // regex: \s+
464
+ if (num_whitespaces > 0) {
465
+ pos += num_whitespaces;
466
+ _add_token(pos);
467
+ continue;
468
+ }
469
+
470
+ // no matches
471
+ _add_token(++pos);
472
+ }
473
+ }
474
+
475
+ return bpe_offsets;
476
+ }
477
+
478
+ // use std::wregex to split the text
479
+ static std::vector<size_t> unicode_regex_split_stl(const std::wstring & wtext, const std::wstring & regex_expr, const std::vector<size_t> & offsets) {
480
+ std::wregex expr(regex_expr);
481
+ std::vector<size_t> bpe_offsets; // store the offset of each word
482
+ bpe_offsets.reserve(offsets.size()); // Reserve memory for the approximate size
483
+ size_t start = 0;
484
+ for (auto offset : offsets) {
485
+ std::wcregex_iterator it(wtext.data() + start, wtext.data() + start + offset, expr);
486
+ std::wcregex_iterator end;
487
+
488
+ int64_t start_idx = 0;
489
+ while (it != end) {
490
+ std::wcmatch match = *it;
491
+ if (match.position() > start_idx) {
492
+ bpe_offsets.emplace_back(match.position() - start_idx);
493
+ }
494
+ bpe_offsets.emplace_back(match.length());
495
+ start_idx = match.position() + match.length();
496
+ ++it;
497
+ }
498
+
499
+ if (start_idx < (int64_t) offset) {
500
+ bpe_offsets.emplace_back(offset - start_idx);
501
+ }
502
+ start += offset;
503
+ }
504
+
505
+ return bpe_offsets;
506
+ }
507
+
508
+ // use std::regex to split the text
509
+ static std::vector<size_t> unicode_regex_split_stl(const std::string & text, const std::string & regex_expr, const std::vector<size_t> & offsets) {
510
+ std::regex expr(regex_expr);
511
+ std::vector<size_t> bpe_offsets; // store the offset of each word
512
+ bpe_offsets.reserve(offsets.size()); // Reserve memory for the approximate size
513
+ size_t start = 0;
514
+ for (auto offset : offsets) {
515
+ std::cregex_iterator it(text.data() + start, text.data() + start + offset, expr);
516
+ std::cregex_iterator end;
517
+
518
+ int64_t start_idx = 0;
519
+ while (it != end) {
520
+ std::cmatch match = *it;
521
+ if (match.position() > start_idx) {
522
+ bpe_offsets.emplace_back(match.position() - start_idx);
523
+ }
524
+ bpe_offsets.emplace_back(match.length());
525
+ start_idx = match.position() + match.length();
526
+ ++it;
527
+ }
528
+
529
+ if (start_idx < (int64_t) offset) {
530
+ bpe_offsets.emplace_back(offset - start_idx);
531
+ }
532
+ start += offset;
533
+ }
534
+
535
+ return bpe_offsets;
536
+ }
537
+
538
+ static std::vector<size_t> unicode_regex_split_custom(const std::string & text, const std::string & regex_expr, const std::vector<size_t> & offsets) {
539
+ std::vector<size_t> bpe_offsets;
540
+
541
+ if (regex_expr == "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)") {
542
+ bpe_offsets = unicode_regex_split_custom_gpt2(text, offsets);
543
+ } else if (
544
+ regex_expr == "(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+" ||
545
+ regex_expr == "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+") {
546
+
547
+ bpe_offsets = unicode_regex_split_custom_llama3(text, offsets);
548
+ }
549
+
550
+ return bpe_offsets;
551
+ }
552
+
553
+ //
554
+ // interface
555
+ //
556
+
557
+ std::string unicode_cpt_to_utf8(uint32_t cp) {
558
+ std::string result;
559
+
560
+ if (/* 0x00 <= cp && */ cp <= 0x7f) {
561
+ result.push_back(cp);
562
+ return result;
563
+ }
564
+ if (0x80 <= cp && cp <= 0x7ff) {
565
+ result.push_back(0xc0 | ((cp >> 6) & 0x1f));
566
+ result.push_back(0x80 | (cp & 0x3f));
567
+ return result;
568
+ }
569
+ if (0x800 <= cp && cp <= 0xffff) {
570
+ result.push_back(0xe0 | ((cp >> 12) & 0x0f));
571
+ result.push_back(0x80 | ((cp >> 6) & 0x3f));
572
+ result.push_back(0x80 | (cp & 0x3f));
573
+ return result;
574
+ }
575
+ if (0x10000 <= cp && cp <= 0x10ffff) {
576
+ result.push_back(0xf0 | ((cp >> 18) & 0x07));
577
+ result.push_back(0x80 | ((cp >> 12) & 0x3f));
578
+ result.push_back(0x80 | ((cp >> 6) & 0x3f));
579
+ result.push_back(0x80 | (cp & 0x3f));
580
+ return result;
581
+ }
582
+
583
+ throw std::invalid_argument("invalid codepoint");
584
+ }
585
+
586
+ std::vector<uint32_t> unicode_cpts_normalize_nfd(const std::vector<uint32_t> & cpts) {
587
+ auto comp = [] (const uint32_t cpt, const range_nfd & range) {
588
+ return cpt < range.first;
589
+ };
590
+ std::vector<uint32_t> result(cpts.size());
591
+ for (size_t i = 0; i < cpts.size(); ++i) {
592
+ const uint32_t cpt = cpts[i];
593
+ auto it = std::upper_bound(unicode_ranges_nfd.cbegin(), unicode_ranges_nfd.cend(), cpt, comp) - 1;
594
+ result[i] = (it->first <= cpt && cpt <= it->last) ? it->nfd : cpt;
595
+ }
596
+ return result;
597
+ }
598
+
599
+ std::vector<uint32_t> unicode_cpts_from_utf8(const std::string & utf8) {
600
+ std::vector<uint32_t> result;
601
+ result.reserve(utf8.size());
602
+ size_t offset = 0;
603
+ while (offset < utf8.size()) {
604
+ result.push_back(unicode_cpt_from_utf8(utf8, offset));
605
+ }
606
+ return result;
607
+ }
608
+
609
+ codepoint_flags unicode_cpt_flags(const uint32_t cp) {
610
+ static const codepoint_flags undef(codepoint_flags::UNDEFINED);
611
+ static const auto cpt_flags = unicode_cpt_flags_array();
612
+ return cp < cpt_flags.size() ? cpt_flags[cp] : undef;
613
+ }
614
+
615
+ codepoint_flags unicode_cpt_flags(const std::string & utf8) {
616
+ static const codepoint_flags undef(codepoint_flags::UNDEFINED);
617
+ if (utf8.empty()) {
618
+ return undef; // undefined
619
+ }
620
+ size_t offset = 0;
621
+ return unicode_cpt_flags(unicode_cpt_from_utf8(utf8, offset));
622
+ }
623
+
624
+ std::string unicode_byte_to_utf8(uint8_t byte) {
625
+ static std::unordered_map<uint8_t, std::string> map = unicode_byte_to_utf8_map();
626
+ return map.at(byte);
627
+ }
628
+
629
+ uint8_t unicode_utf8_to_byte(const std::string & utf8) {
630
+ static std::unordered_map<std::string, uint8_t> map = unicode_utf8_to_byte_map();
631
+ return map.at(utf8);
632
+ }
633
+
634
+ uint32_t unicode_tolower(uint32_t cp) {
635
+ auto it = unicode_map_lowercase.find(cp);
636
+ return it == unicode_map_lowercase.end() ? cp : it->second;
637
+ }
638
+
639
+ std::vector<std::string> unicode_regex_split(const std::string & text, const std::vector<std::string> & regex_exprs) {
640
+ // unicode categories
641
+ static const std::map<std::string, int> k_ucat_enum = {
642
+ { "\\p{N}", codepoint_flags::NUMBER },
643
+ { "\\p{L}", codepoint_flags::LETTER },
644
+ { "\\p{P}", codepoint_flags::PUNCTUATION },
645
+ };
646
+
647
+ static const std::map<int, int> k_ucat_cpt = {
648
+ { codepoint_flags::NUMBER, 0xD1 },
649
+ { codepoint_flags::LETTER, 0xD2 },
650
+ { codepoint_flags::PUNCTUATION, 0xD3 },
651
+ };
652
+
653
+ static const std::map<int, std::string> k_ucat_map = {
654
+ { codepoint_flags::NUMBER, "\x30-\x39" }, // 0-9
655
+ { codepoint_flags::LETTER, "\x41-\x5A\x61-\x7A" }, // A-Za-z
656
+ { codepoint_flags::PUNCTUATION, "\x21-\x23\x25-\x2A\x2C-\x2F\x3A-\x3B\x3F-\x40\\\x5B-\\\x5D\x5F\\\x7B\\\x7D" }, // !-#%-*,-/:-;?-@\[-\]_\{\}
657
+ };
658
+
659
+ // compute collapsed codepoints only if needed by at least one regex
660
+ bool need_collapse = false;
661
+ for (auto & regex_expr : regex_exprs) {
662
+ // search for unicode categories
663
+ for (const auto & ucat : k_ucat_enum) {
664
+ if (std::string::npos != regex_expr.find(ucat.first)) {
665
+ need_collapse = true;
666
+ break;
667
+ }
668
+ }
669
+ }
670
+
671
+ const auto cpts = unicode_cpts_from_utf8(text);
672
+
673
+ // generate a "collapsed" representation of the text, where all codepoints are replaced by a single byte
674
+ // ref: https://github.com/ggerganov/llama.cpp/pull/6920#issuecomment-2081479935
675
+ std::string text_collapsed;
676
+ if (need_collapse) {
677
+ // collapse all unicode categories
678
+ text_collapsed.resize(cpts.size());
679
+
680
+ for (size_t i = 0; i < cpts.size(); ++i) {
681
+ // keep single-byte codepoints as is
682
+ if (cpts[i] < 128) {
683
+ text_collapsed[i] = cpts[i];
684
+ continue;
685
+ }
686
+
687
+ const auto flags = unicode_cpt_flags(cpts[i]);
688
+
689
+ if (flags.is_whitespace) {
690
+ //NOTE: C++ std::regex \s does not mach 0x85, Rust and Python regex does.
691
+ //text_collapsed[i] = (char) 0x85; // <Next Line> as whitespace fallback
692
+ text_collapsed[i] = (char) 0x0B; // <vertical tab> as whitespace fallback
693
+ } else if (k_ucat_cpt.find(flags.category_flag()) != k_ucat_cpt.end()) {
694
+ text_collapsed[i] = k_ucat_cpt.at(flags.category_flag());
695
+ } else {
696
+ text_collapsed[i] = (char) 0xD0; // fallback
697
+ }
698
+ }
699
+ }
700
+
701
+ std::vector<size_t> bpe_offsets = { cpts.size() };
702
+
703
+ for (auto & regex_expr : regex_exprs) {
704
+ // first, see if we have an efficient custom regex implementation
705
+ auto tmp = unicode_regex_split_custom(text, regex_expr, bpe_offsets);
706
+
707
+ if (!tmp.empty()) {
708
+ bpe_offsets = std::move(tmp);
709
+ continue;
710
+ }
711
+
712
+ // fallback to general-purpose std::regex / std::wregex
713
+ try {
714
+ // if a unicode category is used in the regex, we use the collapsed text and replace the unicode category
715
+ // with the corresponding collapsed representation
716
+ bool use_collapsed = false;
717
+ for (auto & ucat : k_ucat_enum) {
718
+ if (std::string::npos != regex_expr.find(ucat.first)) {
719
+ use_collapsed = true;
720
+ break;
721
+ }
722
+ }
723
+
724
+ if (use_collapsed) {
725
+ // sanity-check that the original regex does not contain any non-ASCII characters
726
+ const auto cpts_regex = unicode_cpts_from_utf8(regex_expr);
727
+ for (size_t i = 0; i < cpts_regex.size(); ++i) {
728
+ if (cpts_regex[i] >= 128) {
729
+ throw std::runtime_error("Regex includes both unicode categories and non-ASCII characters - not supported");
730
+ }
731
+ }
732
+
733
+ // generate a collapsed representation of the regex
734
+ std::string regex_expr_collapsed;
735
+
736
+ // track if we are inside [], because nested [] are not allowed
737
+ bool inside = false;
738
+ for (size_t i = 0; i < regex_expr.size(); ++i) {
739
+ if (regex_expr[i] == '[' && (i == 0 || regex_expr[i - 1] != '\\')) {
740
+ regex_expr_collapsed += '[';
741
+ inside = true;
742
+ continue;
743
+ }
744
+
745
+ if (inside && regex_expr[i] == ']' && regex_expr[i - 1] != '\\') {
746
+ regex_expr_collapsed += ']';
747
+ inside = false;
748
+ continue;
749
+ }
750
+
751
+ if (regex_expr[i + 0] == '\\' && i + 4 < regex_expr.size() &&
752
+ regex_expr[i + 1] == 'p' &&
753
+ regex_expr[i + 2] == '{' &&
754
+ regex_expr[i + 4] == '}') {
755
+ const std::string pat = regex_expr.substr(i, 5);
756
+ if (k_ucat_enum.find(pat) != k_ucat_enum.end()) {
757
+ if (!inside) {
758
+ regex_expr_collapsed += '[';
759
+ }
760
+ regex_expr_collapsed += k_ucat_cpt.at(k_ucat_enum.at(pat));
761
+ regex_expr_collapsed += k_ucat_map.at(k_ucat_enum.at(pat));
762
+ if (!inside) {
763
+ regex_expr_collapsed += ']';
764
+ }
765
+ i += 4;
766
+ continue;
767
+ }
768
+ }
769
+
770
+ regex_expr_collapsed += regex_expr[i];
771
+ }
772
+
773
+ //printf("text_collapsed: %s\n", text_collapsed.c_str());
774
+ //printf("regex_expr_collapsed: %s\n", regex_expr_collapsed.c_str());
775
+ bpe_offsets = unicode_regex_split_stl(text_collapsed, regex_expr_collapsed, bpe_offsets);
776
+ } else {
777
+ // no unicode category used, we can use std::wregex directly
778
+ const std::wstring wregex_expr = unicode_wstring_from_utf8(regex_expr);
779
+
780
+ // std::wregex \s does not mach non-ASCII whitespaces, using 0x0B as fallback
781
+ std::wstring wtext(cpts.begin(), cpts.end());
782
+ for (size_t i = 0; i < wtext.size(); ++i) {
783
+ if (wtext[i] > 0x7F && unicode_cpt_flags(wtext[i]).is_whitespace) {
784
+ wtext[i] = 0x0B;
785
+ }
786
+ }
787
+
788
+ //printf("text: %s\n", text.c_str());
789
+ //printf("regex_expr: %s\n", regex_expr.c_str());
790
+ bpe_offsets = unicode_regex_split_stl(wtext, wregex_expr, bpe_offsets);
791
+ }
792
+ } catch (std::regex_error & e) {
793
+ fprintf(stderr, "Failed to process regex: '%s'\n", regex_expr.c_str());
794
+ fprintf(stderr, "Regex error: %s\n", e.what());
795
+ throw std::runtime_error("Failed to process regex");
796
+ }
797
+ }
798
+
799
+ std::vector<std::string> bpe_words;
800
+ bpe_words.reserve(bpe_offsets.size()); // reserve memory for the approximate size
801
+
802
+ size_t start = 0;
803
+ for (size_t & offset : bpe_offsets) {
804
+ bpe_words.emplace_back();
805
+ for (size_t i = start; i < start + offset; ++i) {
806
+ bpe_words.back() += unicode_cpt_to_utf8(cpts[i]);
807
+ }
808
+ start += offset;
809
+ }
810
+
811
+ return unicode_byte_encoding_process(bpe_words);
812
+ }