Coverage Report

Created: 2026-03-03 06:12

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/llama.cpp/src/unicode.cpp
Line
Count
Source
1
#include "unicode.h"
2
#include "unicode-data.h"
3
4
#include <algorithm>
5
#include <cassert>
6
#include <cstddef>
7
#include <cstdint>
8
#include <map>
9
#include <regex>
10
#include <stdexcept>
11
#include <string>
12
#include <unordered_map>
13
#include <utility>
14
#include <vector>
15
16
0
size_t unicode_len_utf8(char src) {
17
0
    const size_t lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 4 };
18
0
    uint8_t highbits = static_cast<uint8_t>(src) >> 4;
19
0
    return lookup[highbits];
20
0
}
21
22
0
static std::string unicode_cpts_to_utf8(const std::vector<uint32_t> & cps) {
23
0
    std::string result;
24
0
    for (size_t i = 0; i < cps.size(); ++i) {
25
0
        result.append(unicode_cpt_to_utf8(cps[i]));
26
0
    }
27
0
    return result;
28
0
}
29
30
0
uint32_t unicode_cpt_from_utf8(const std::string & utf8, size_t & offset) {
31
0
    assert(offset < utf8.size());
32
0
    if (!(utf8[offset + 0] & 0x80)) {
33
0
        auto result = utf8[offset + 0];
34
0
        offset += 1;
35
0
        return result;
36
0
    }
37
0
    if (!(utf8[offset + 0] & 0x40)) {
38
0
        throw std::invalid_argument("invalid character");
39
0
    }
40
0
    if (!(utf8[offset + 0] & 0x20)) {
41
0
        if (offset + 1 >= utf8.size() || ! ((utf8[offset + 1] & 0xc0) == 0x80)) {
42
0
            throw std::invalid_argument("invalid character");
43
0
        }
44
0
        auto result = ((utf8[offset + 0] & 0x1f) << 6) | (utf8[offset + 1] & 0x3f);
45
0
        offset += 2;
46
0
        return result;
47
0
    }
48
0
    if (!(utf8[offset + 0] & 0x10)) {
49
0
        if (offset + 2 >= utf8.size() || ! ((utf8[offset + 1] & 0xc0) == 0x80) || ! ((utf8[offset + 2] & 0xc0) == 0x80)) {
50
0
            throw std::invalid_argument("invalid character");
51
0
        }
52
0
        auto result = ((utf8[offset + 0] & 0x0f) << 12) | ((utf8[offset + 1] & 0x3f) << 6) | (utf8[offset + 2] & 0x3f);
53
0
        offset += 3;
54
0
        return result;
55
0
    }
56
0
    if (!(utf8[offset + 0] & 0x08)) {
57
0
        if (offset + 3 >= utf8.size() || ! ((utf8[offset + 1] & 0xc0) == 0x80) || ! ((utf8[offset + 2] & 0xc0) == 0x80) || !((utf8[offset + 3] & 0xc0) == 0x80)) {
58
0
            throw std::invalid_argument("invalid character");
59
0
        }
60
0
        auto result = ((utf8[offset + 0] & 0x07) << 18) | ((utf8[offset + 1] & 0x3f) << 12) | ((utf8[offset + 2] & 0x3f) << 6) | (utf8[offset + 3] & 0x3f);
61
0
        offset += 4;
62
0
        return result;
63
0
    }
64
0
    throw std::invalid_argument("failed to convert utf8 to codepoint");
65
0
}
66
67
//static std::vector<uint16_t> unicode_cpt_to_utf16(uint32_t cpt) {
68
//    std::vector<uint16_t> result;
69
//    if (/* 0x0000 <= cpt && */ cpt <= 0xffff) {
70
//        result.emplace_back(cpt);
71
//        return result;
72
//    }
73
//    if (0x10000 <= cpt && cpt <= 0x10ffff) {
74
//        result.emplace_back(0xd800 | ((cpt - 0x10000) >> 10));
75
//        result.emplace_back(0xdc00 | ((cpt - 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
0
static std::vector<unicode_cpt_flags> unicode_cpt_flags_array() {
117
0
    std::vector<unicode_cpt_flags> cpt_flags(MAX_CODEPOINTS, unicode_cpt_flags::UNDEFINED);
118
119
0
    assert (unicode_ranges_flags.begin()[0].first == 0);
120
0
    assert (unicode_ranges_flags.begin()[unicode_ranges_flags.size()-1].first == MAX_CODEPOINTS);
121
0
    for (size_t i = 1; i < unicode_ranges_flags.size(); ++i) {
122
0
        const auto range_ini = unicode_ranges_flags.begin()[i-1];  // codepoint_ini, flags
123
0
        const auto range_end = unicode_ranges_flags.begin()[i];    // codepoint_end, flags
124
0
        for (uint32_t cpt = range_ini.first; cpt < range_end.first; ++cpt) {
125
0
            cpt_flags[cpt] = range_ini.second;
126
0
        }
127
0
    }
128
129
0
    for (auto cpt : unicode_set_whitespace) {
130
0
        cpt_flags[cpt].is_whitespace = true;
131
0
    }
132
133
0
    for (auto p : unicode_map_lowercase) {
134
0
        cpt_flags[p.second].is_lowercase = true;
135
0
    }
136
137
0
    for (auto p : unicode_map_uppercase) {
138
0
        cpt_flags[p.second].is_uppercase = true;
139
0
    }
140
141
0
    for (auto &range : unicode_ranges_nfd) {  // start, last, nfd
142
0
        cpt_flags[range.nfd].is_nfd = true;
143
0
    }
144
145
0
    return cpt_flags;
146
0
}
147
148
0
static std::unordered_map<uint8_t, std::string> unicode_byte_to_utf8_map() {
149
0
    std::unordered_map<uint8_t, std::string> map;
150
0
    for (int ch = 0x21; ch <= 0x7E; ++ch) {  // u'!' to u'~'
151
0
        assert(0 <= ch && ch < 256);
152
0
        map[ch] = unicode_cpt_to_utf8(ch);
153
0
    }
154
0
    for (int ch = 0xA1; ch <= 0xAC; ++ch) {  // u'¡' to u'¬'
155
0
        assert(0 <= ch && ch < 256);
156
0
        map[ch] = unicode_cpt_to_utf8(ch);
157
0
    }
158
0
    for (int ch = 0xAE; ch <= 0xFF; ++ch) {  // u'®' to u'ÿ'
159
0
        assert(0 <= ch && ch < 256);
160
0
        map[ch] = unicode_cpt_to_utf8(ch);
161
0
    }
162
0
    auto n = 0;
163
0
    for (int ch = 0; ch < 256; ++ch) {
164
0
        if (map.find(ch) == map.end()) {
165
0
            map[ch] = unicode_cpt_to_utf8(256 + n);
166
0
            ++n;
167
0
        }
168
0
    }
169
0
    return map;
170
0
}
171
172
0
static std::unordered_map<std::string, uint8_t> unicode_utf8_to_byte_map() {
173
0
    std::unordered_map<std::string, uint8_t> map;
174
0
    for (int ch = 0x21; ch <= 0x7E; ++ch) {  // u'!' to u'~'
175
0
        assert(0 <= ch && ch < 256);
176
0
        map[unicode_cpt_to_utf8(ch)] = ch;
177
0
    }
178
0
    for (int ch = 0xA1; ch <= 0xAC; ++ch) {  // u'¡' to u'¬'
179
0
        assert(0 <= ch && ch < 256);
180
0
        map[unicode_cpt_to_utf8(ch)] = ch;
181
0
    }
182
0
    for (int ch = 0xAE; ch <= 0xFF; ++ch) {  // u'®' to u'ÿ'
183
0
        assert(0 <= ch && ch < 256);
184
0
        map[unicode_cpt_to_utf8(ch)] = ch;
185
0
    }
186
0
    auto n = 0;
187
0
    for (int ch = 0; ch < 256; ++ch) {
188
0
        if (map.find(unicode_cpt_to_utf8(ch)) == map.end()) {
189
0
            map[unicode_cpt_to_utf8(256 + n)] = ch;
190
0
            ++n;
191
0
        }
192
0
    }
193
0
    return map;
194
0
}
195
196
0
static std::vector<std::string> unicode_byte_encoding_process(const std::vector<std::string> & bpe_words) {
197
0
    std::vector<std::string> bpe_encoded_words;
198
0
    for (const auto & word : bpe_words) {
199
0
        std::string text_utf;
200
0
        auto utf_word =  unicode_cpts_from_utf8(word);
201
0
        for (size_t i = 0; i < utf_word.size(); ++i) {
202
0
            text_utf += unicode_cpt_to_utf8(utf_word[i]);
203
0
        }
204
205
0
        std::string encoded_token;
206
0
        for (char & c : text_utf) {
207
0
            encoded_token += unicode_byte_to_utf8(c);
208
0
        }
209
0
        bpe_encoded_words.emplace_back(encoded_token);
210
0
    }
211
0
    return bpe_encoded_words;
212
0
}
213
214
// GPT2 system regex:  's|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+
215
0
static std::vector<size_t> unicode_regex_split_custom_gpt2(const std::string & text, const std::vector<size_t> & offsets) {
216
0
    std::vector<size_t> bpe_offsets; // store the offset of each word
217
0
    bpe_offsets.reserve(offsets.size()); // Reserve memory for the approximate size
218
219
0
    const auto cpts = unicode_cpts_from_utf8(text);
220
221
0
    size_t start = 0;
222
0
    for (auto offset : offsets) {
223
0
        const size_t offset_ini = start;
224
0
        const size_t offset_end = start + offset;
225
0
        assert(offset_end <= cpts.size());
226
0
        start = offset_end;
227
228
0
        static const uint32_t OUT_OF_RANGE = 0xFFFFFFFF;
229
0
        auto _get_cpt = [&] (const size_t pos) -> uint32_t {
230
0
            return (offset_ini <= pos && pos < offset_end) ? cpts[pos] : OUT_OF_RANGE;
231
0
        };
232
233
0
        auto _get_flags = [&] (const size_t pos) -> unicode_cpt_flags {
234
0
            return (offset_ini <= pos && pos < offset_end) ? unicode_cpt_flags_from_cpt(cpts[pos]) : unicode_cpt_flags{};
235
0
        };
236
237
0
        size_t _prev_end = offset_ini;
238
0
        auto _add_token = [&] (const size_t end) -> size_t {
239
0
            assert(_prev_end <= end && end <= offset_end);
240
0
            size_t len = end - _prev_end;
241
0
            if (len > 0) {
242
0
                bpe_offsets.push_back(len);
243
0
            }
244
0
            _prev_end = end;
245
            //if (len > 0) {
246
            //    std::string s = "";
247
            //    for(size_t p = end-len; p < end; p++)
248
            //        s += unicode_cpt_to_utf8(cpts[p]);
249
            //    printf(">>> '%s'\n", s.c_str());
250
            //}
251
0
            return len;
252
0
        };
253
254
0
        for (size_t pos = offset_ini; pos < offset_end; /*pos++*/ ) {
255
0
            const uint32_t cpt = _get_cpt(pos);
256
0
            const auto flags = _get_flags(pos);
257
258
            // regex: 's|'t|'re|'ve|'m|'ll|'d
259
0
            if (cpt == '\'' && pos+1 < offset_end) {
260
0
                uint32_t cpt_next = _get_cpt(pos+1);
261
0
                if (cpt_next == 's' || cpt_next == 't' || cpt_next == 'm' || cpt_next == 'd') {
262
0
                    pos += _add_token(pos+2);
263
0
                    continue;
264
0
                }
265
0
                if (pos+2 < offset_end) {
266
0
                    uint32_t cpt_next_next = _get_cpt(pos+2);
267
0
                    if ((cpt_next == 'r' && cpt_next_next == 'e') ||
268
0
                        (cpt_next == 'v' && cpt_next_next == 'e') ||
269
0
                        (cpt_next == 'l' && cpt_next_next == 'l')) {
270
0
                        pos += _add_token(pos+3);
271
0
                        continue;
272
0
                    }
273
0
                }
274
0
            }
275
276
0
            auto flags2 = (cpt == ' ' ? _get_flags(pos+1) : flags);
277
            // regex: <space>?\p{L}+
278
0
            if (flags2.is_letter) {
279
0
                pos += (cpt == ' ');
280
0
                while (flags2.is_letter) {
281
0
                    flags2 = _get_flags(++pos);
282
0
                }
283
0
                _add_token(pos);
284
0
                continue;
285
0
            }
286
            // regex: <space>?\p{N}+
287
0
            if (flags2.is_number) {
288
0
                pos += (cpt == ' ');
289
0
                while (flags2.is_number) {
290
0
                    flags2 = _get_flags(++pos);
291
0
                }
292
0
                _add_token(pos);
293
0
                continue;
294
0
            }
295
            // regex: <space>?[^\s\p{L}\p{N}]+
296
0
            if (!(flags2.is_whitespace | flags2.is_letter | flags2.is_number) && flags2.as_uint()) {
297
0
                pos += (cpt == ' ');
298
0
                while (!(flags2.is_whitespace | flags2.is_letter | flags2.is_number) && flags2.as_uint()) {
299
0
                    flags2 = _get_flags(++pos);
300
0
                }
301
0
                _add_token(pos);
302
0
                continue;
303
0
            }
304
305
0
            size_t num_whitespaces = 0;
306
0
            while (_get_flags(pos+num_whitespaces).is_whitespace) {
307
0
                num_whitespaces++;
308
0
            }
309
310
            // regex: \s+(?!\S)
311
0
            if (num_whitespaces > 1 && _get_cpt(pos+num_whitespaces) != OUT_OF_RANGE) {
312
0
                pos += num_whitespaces - 1;
313
0
                _add_token(pos);
314
0
                continue;
315
0
            }
316
317
            // regex: \s+
318
0
            if (num_whitespaces > 0) {
319
0
                pos += num_whitespaces;
320
0
                _add_token(pos);
321
0
                continue;
322
0
            }
323
324
            // no matches
325
0
            _add_token(++pos);
326
0
        }
327
0
    }
328
329
0
    return bpe_offsets;
330
0
}
331
332
// 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+"
333
0
static std::vector<size_t> unicode_regex_split_custom_llama3(const std::string & text, const std::vector<size_t> & offsets) {
334
0
    std::vector<size_t> bpe_offsets; // store the offset of each word
335
0
    bpe_offsets.reserve(offsets.size()); // Reserve memory for the approximate size
336
337
0
    const auto cpts = unicode_cpts_from_utf8(text);
338
339
0
    size_t start = 0;
340
0
    for (auto offset : offsets) {
341
0
        const size_t offset_ini = start;
342
0
        const size_t offset_end = start + offset;
343
0
        assert(offset_end <= cpts.size());
344
0
        start = offset_end;
345
346
0
        static const uint32_t OUT_OF_RANGE = 0xFFFFFFFF;
347
0
        auto _get_cpt = [&] (const size_t pos) -> uint32_t {
348
0
            return (offset_ini <= pos && pos < offset_end) ? cpts[pos] : OUT_OF_RANGE;
349
0
        };
350
351
0
        auto _get_flags = [&] (const size_t pos) -> unicode_cpt_flags {
352
0
            return (offset_ini <= pos && pos < offset_end) ? unicode_cpt_flags_from_cpt(cpts[pos]) : unicode_cpt_flags{};
353
0
        };
354
355
0
        size_t _prev_end = offset_ini;
356
0
        auto _add_token = [&] (const size_t end) -> size_t {
357
0
            assert(_prev_end <= end && end <= offset_end);
358
0
            size_t len = end - _prev_end;
359
0
            if (len > 0) {
360
0
                bpe_offsets.push_back(len);
361
0
            }
362
0
            _prev_end = end;
363
            //if (len > 0) {
364
            //    std::string s = "";
365
            //    for(size_t p = end-len; p < end; p++)
366
            //        s += unicode_cpt_to_utf8(cpts[p]);
367
            //    printf(">>> '%s'\n", s.c_str());
368
            //}
369
0
            return len;
370
0
        };
371
372
0
        for (size_t pos = offset_ini; pos < offset_end; /*pos++*/ ) {
373
0
            const uint32_t cpt = _get_cpt(pos);
374
0
            const auto flags = _get_flags(pos);
375
376
            // regex: (?i:'s|'t|'re|'ve|'m|'ll|'d) // case insensitive
377
0
            if (cpt == '\'' && pos+1 < offset_end) {
378
0
                uint32_t cpt_next = unicode_tolower(_get_cpt(pos+1));
379
0
                if (cpt_next == 's' || cpt_next == 't' || cpt_next == 'm' || cpt_next == 'd') {
380
0
                    pos += _add_token(pos+2);
381
0
                    continue;
382
0
                }
383
0
                if (pos+2 < offset_end) {
384
0
                    uint32_t cpt_next_next = unicode_tolower(_get_cpt(pos+2));
385
0
                    if ((cpt_next == 'r' && cpt_next_next == 'e') ||
386
0
                        (cpt_next == 'v' && cpt_next_next == 'e') ||
387
0
                        (cpt_next == 'l' && cpt_next_next == 'l')) {
388
0
                        pos += _add_token(pos+3);
389
0
                        continue;
390
0
                    }
391
0
                }
392
0
            }
393
394
            // regex: [^\r\n\p{L}\p{N}]?\p{L}+
395
0
            if (!(cpt == '\r' || cpt == '\n' || flags.is_number)) {
396
0
                if (flags.is_letter || _get_flags(pos+1).is_letter) {  // one or more letters
397
0
                    pos++;
398
0
                    while (_get_flags(pos).is_letter) {
399
0
                        pos++;
400
0
                    }
401
0
                    _add_token(pos);
402
0
                    continue;
403
0
                }
404
0
            }
405
406
            // regex: \p{N}{1,3}
407
0
            if (flags.is_number) {
408
0
                size_t ini = pos;
409
0
                while (_get_flags(pos).is_number) {
410
0
                    if (++pos - ini >= 3 ) {
411
0
                        _add_token(pos);
412
0
                        ini = pos;
413
0
                    }
414
0
                }
415
0
                _add_token(pos);
416
0
                continue;
417
0
            }
418
419
            // regex: <space>?[^\s\p{L}\p{N}]+[\r\n]*
420
0
            auto flags2 = (cpt == ' ' ? _get_flags(pos+1) : flags);
421
0
            if (!(flags2.is_whitespace | flags2.is_letter | flags2.is_number) && flags.as_uint()) {
422
0
                pos += (cpt == ' ');
423
0
                while (!(flags2.is_whitespace | flags2.is_letter | flags2.is_number) && flags2.as_uint()) {
424
0
                    flags2 = _get_flags(++pos);
425
0
                }
426
0
                uint32_t cpt2 = _get_cpt(pos);
427
0
                while (cpt2 == '\r' || cpt2 == '\n') {
428
0
                    cpt2 = _get_cpt(++pos);
429
0
                }
430
0
                _add_token(pos);
431
0
                continue;
432
0
            }
433
434
0
            size_t num_whitespaces = 0;
435
0
            size_t last_end_r_or_n = 0;
436
0
            while (_get_flags(pos+num_whitespaces).is_whitespace) {
437
0
                uint32_t cpt2 = _get_cpt(pos+num_whitespaces);
438
0
                if (cpt2 == '\r' || cpt2 == '\n') {
439
0
                    last_end_r_or_n = pos + num_whitespaces + 1;
440
0
                }
441
0
                num_whitespaces++;
442
0
            }
443
444
            // regex: \s*[\r\n]+
445
0
            if (last_end_r_or_n > 0) {
446
0
                pos = last_end_r_or_n;
447
0
                _add_token(pos);
448
0
                continue;
449
0
            }
450
451
            // regex: \s+(?!\S)
452
0
            if (num_whitespaces > 1 && _get_cpt(pos+num_whitespaces) != OUT_OF_RANGE) {
453
0
                pos += num_whitespaces - 1;
454
0
                _add_token(pos);
455
0
                continue;
456
0
            }
457
458
            // regex: \s+
459
0
            if (num_whitespaces > 0) {
460
0
                pos += num_whitespaces;
461
0
                _add_token(pos);
462
0
                continue;
463
0
            }
464
465
            // no matches
466
0
            _add_token(++pos);
467
0
        }
468
0
    }
469
470
0
    return bpe_offsets;
471
0
}
472
473
template <typename CharT>
474
0
static std::vector<size_t> unicode_regex_split_stl(const std::basic_string<CharT> & text, const std::basic_string<CharT> & regex, const std::vector<size_t> & offsets) {
475
0
    using BidirIt = typename std::basic_string<CharT>::const_iterator;
476
#ifdef _MSC_VER
477
    // Bypass bug in MSVC: https://github.com/ggml-org/llama.cpp/issues/17830
478
    constexpr auto regex_flags = std::regex_constants::ECMAScript;
479
#else
480
0
    constexpr auto regex_flags = std::regex_constants::optimize | std::regex_constants::nosubs;
481
0
#endif
482
0
    std::basic_regex<CharT> expr(regex, regex_flags);
483
0
    std::vector<size_t> bpe_offsets; // store the offset of each word
484
0
    bpe_offsets.reserve(offsets.size()); // Reserve memory for the approximate size
485
0
    size_t start = 0;
486
0
    for (auto offset : offsets) {
487
0
        std::regex_iterator<BidirIt> it(text.begin() + start, text.begin() + start + offset, expr);
488
0
        std::regex_iterator<BidirIt> end;
489
490
0
        int64_t start_idx = 0;
491
0
        while (it != end) {
492
0
            std::match_results<BidirIt> match = *it;
493
0
            if (match.position() > start_idx) {
494
0
                bpe_offsets.emplace_back(match.position() - start_idx);
495
0
            }
496
0
            bpe_offsets.emplace_back(match.length());
497
0
            start_idx = match.position() + match.length();
498
0
            ++it;
499
0
        }
500
501
0
        if (start_idx < (int64_t) offset) {
502
0
            bpe_offsets.emplace_back(offset - start_idx);
503
0
        }
504
0
        start += offset;
505
0
    }
506
507
0
    return bpe_offsets;
508
0
}
Unexecuted instantiation: unicode.cpp:std::__1::vector<unsigned long, std::__1::allocator<unsigned long> > unicode_regex_split_stl<char>(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, std::__1::vector<unsigned long, std::__1::allocator<unsigned long> > const&)
Unexecuted instantiation: unicode.cpp:std::__1::vector<unsigned long, std::__1::allocator<unsigned long> > unicode_regex_split_stl<wchar_t>(std::__1::basic_string<wchar_t, std::__1::char_traits<wchar_t>, std::__1::allocator<wchar_t> > const&, std::__1::basic_string<wchar_t, std::__1::char_traits<wchar_t>, std::__1::allocator<wchar_t> > const&, std::__1::vector<unsigned long, std::__1::allocator<unsigned long> > const&)
509
510
// K2 system regex patterns (from tokenization_kimi.py):
511
// [\p{Han}]+|[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}&&[^\p{Han}]]*[\p{Ll}\p{Lm}\p{Lo}\p{M}&&[^\p{Han}]]+(?i:'s|'t|'re|'ve|'m|'ll|'d)?|[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}&&[^\p{Han}]]+[\p{Ll}\p{Lm}\p{Lo}\p{M}&&[^\p{Han}]]*(?i:'s|'t|'re|'ve|'m|'ll|'d)?|\p{N}{1,3}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+
512
0
static std::vector<size_t> unicode_regex_split_custom_kimi_k2(const std::string & text, const std::vector<size_t> & offsets) {
513
0
    std::vector<size_t> bpe_offsets;
514
0
    bpe_offsets.reserve(offsets.size());
515
516
0
    const auto cpts = unicode_cpts_from_utf8(text);
517
518
0
    size_t start = 0;
519
0
    for (auto offset : offsets) {
520
0
        const size_t offset_ini = start;
521
0
        const size_t offset_end = start + offset;
522
0
        assert(offset_end <= cpts.size());
523
0
        start = offset_end;
524
525
0
        static const uint32_t OUT_OF_RANGE = 0xFFFFFFFF;
526
0
        auto _get_cpt = [&] (const size_t pos) -> uint32_t {
527
0
            return (offset_ini <= pos && pos < offset_end) ? cpts[pos] : OUT_OF_RANGE;
528
0
        };
529
530
0
        auto _get_flags = [&] (const size_t pos) -> unicode_cpt_flags {
531
0
            return (offset_ini <= pos && pos < offset_end) ? unicode_cpt_flags_from_cpt(cpts[pos]) : unicode_cpt_flags{};
532
0
        };
533
534
0
        size_t _prev_end = offset_ini;
535
0
        auto _add_token = [&] (const size_t end) -> size_t {
536
0
            assert(_prev_end <= end && end <= offset_end);
537
0
            size_t len = end - _prev_end;
538
0
            if (len > 0) {
539
0
                bpe_offsets.push_back(len);
540
0
            }
541
0
            _prev_end = end;
542
0
            return len;
543
0
        };
544
545
0
        for (size_t pos = offset_ini; pos < offset_end; /*pos++*/ ) {
546
0
            const uint32_t cpt = _get_cpt(pos);
547
0
            const auto flags = _get_flags(pos);
548
549
            // Pattern 1: [\p{Han}]+ (Chinese characters)
550
0
            if (unicode_cpt_is_han(cpt)) {
551
0
                while (unicode_cpt_is_han(_get_cpt(pos))) {
552
0
                    pos++;
553
0
                }
554
0
                _add_token(pos);
555
0
                continue;
556
0
            }
557
558
            // Pattern 2 & 3: Letter words excluding Han characters with optional contractions
559
            // [^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}&&[^\p{Han}]]*[\p{Ll}\p{Lm}\p{Lo}\p{M}&&[^\p{Han}]]+(?:'s|'t|'re|'ve|'m|'ll|'d)?
560
            // [^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}&&[^\p{Han}]]+[\p{Ll}\p{Lm}\p{Lo}\p{M}&&[^\p{Han}]]*(?:'s|'t|'re|'ve|'m|'ll|'d)?
561
            // Check if current char is a letter OR if current char could be a leading char and next char is a letter
562
0
            bool is_letter_pattern = (flags.is_letter && !unicode_cpt_is_han(cpt)) ||
563
0
                                     (!(cpt == '\r' || cpt == '\n' || flags.is_letter || flags.is_number) &&
564
0
                                      _get_flags(pos + 1).is_letter && !unicode_cpt_is_han(_get_cpt(pos + 1)));
565
566
0
            if (is_letter_pattern) {
567
                // Handle optional leading non-letter/non-number character
568
0
                bool has_leading_char = false;
569
0
                if (!(cpt == '\r' || cpt == '\n' || flags.is_letter || flags.is_number)) {
570
0
                    has_leading_char = true;
571
0
                    pos++;
572
0
                }
573
574
                // Match letter sequence (excluding Han characters)
575
0
                bool has_letters = false;
576
0
                while (_get_flags(pos).is_letter && !unicode_cpt_is_han(_get_cpt(pos))) {
577
0
                    has_letters = true;
578
0
                    pos++;
579
0
                }
580
581
                // Only proceed if we found letters (after potentially skipping leading char)
582
0
                if (has_letters || (!has_leading_char && _get_flags(pos).is_letter && !unicode_cpt_is_han(_get_cpt(pos)))) {
583
0
                    if (!has_letters) pos++; // consume the first letter if we didn't already
584
585
                    // Continue consuming letters
586
0
                    while (_get_flags(pos).is_letter && !unicode_cpt_is_han(_get_cpt(pos))) {
587
0
                        pos++;
588
0
                    }
589
590
                    // Check for optional contractions (?:'s|'t|'re|'ve|'m|'ll|'d)
591
0
                    if (_get_cpt(pos) == '\'' && pos + 1 < offset_end) {
592
0
                        uint32_t cpt_next = unicode_tolower(_get_cpt(pos + 1));
593
0
                        if (cpt_next == 's' || cpt_next == 't' || cpt_next == 'm' || cpt_next == 'd') {
594
0
                            pos += 2;
595
0
                        } else if (pos + 2 < offset_end) {
596
0
                            uint32_t cpt_next_next = unicode_tolower(_get_cpt(pos + 2));
597
0
                            if ((cpt_next == 'r' && cpt_next_next == 'e') ||
598
0
                                (cpt_next == 'v' && cpt_next_next == 'e') ||
599
0
                                (cpt_next == 'l' && cpt_next_next == 'l')) {
600
0
                                pos += 3;
601
0
                            }
602
0
                        }
603
0
                    }
604
605
0
                    _add_token(pos);
606
0
                    continue;
607
0
                } else if (has_leading_char) {
608
                    // We consumed a leading char but found no letters, backtrack
609
0
                    pos--;
610
0
                }
611
0
            }
612
613
            // Pattern 4: \p{N}{1,3} (numbers 1-3 digits)
614
0
            if (flags.is_number) {
615
0
                size_t ini = pos;
616
0
                while (_get_flags(pos).is_number) {
617
0
                    if (++pos - ini >= 3) {
618
0
                        _add_token(pos);
619
0
                        ini = pos;
620
0
                    }
621
0
                }
622
0
                _add_token(pos);
623
0
                continue;
624
0
            }
625
626
            // Pattern 5:  ?[^\s\p{L}\p{N}]+[\r\n]* (optional space + non-word chars + optional newlines)
627
0
            auto flags2 = (cpt == ' ' ? _get_flags(pos + 1) : flags);
628
0
            if (!(flags2.is_whitespace || flags2.is_letter || flags2.is_number) && flags2.as_uint()) {
629
0
                pos += (cpt == ' ');
630
0
                while (!(flags2.is_whitespace || flags2.is_letter || flags2.is_number) && flags2.as_uint()) {
631
0
                    flags2 = _get_flags(++pos);
632
0
                }
633
                // Match optional [\r\n]*
634
0
                uint32_t cpt2 = _get_cpt(pos);
635
0
                while (cpt2 == '\r' || cpt2 == '\n') {
636
0
                    cpt2 = _get_cpt(++pos);
637
0
                }
638
0
                _add_token(pos);
639
0
                continue;
640
0
            }
641
642
            // Count whitespace characters
643
0
            size_t num_whitespaces = 0;
644
0
            size_t last_end_r_or_n = 0;
645
0
            while (_get_flags(pos + num_whitespaces).is_whitespace) {
646
0
                uint32_t cpt2 = _get_cpt(pos + num_whitespaces);
647
0
                if (cpt2 == '\r' || cpt2 == '\n') {
648
0
                    last_end_r_or_n = pos + num_whitespaces + 1;
649
0
                }
650
0
                num_whitespaces++;
651
0
            }
652
653
            // Pattern 6: \s*[\r\n]+ (whitespace with newlines)
654
0
            if (last_end_r_or_n > 0) {
655
0
                pos = last_end_r_or_n;
656
0
                _add_token(pos);
657
0
                continue;
658
0
            }
659
660
            // Pattern 7: \s+(?!\S) (trailing whitespace)
661
0
            if (num_whitespaces > 1 && _get_cpt(pos + num_whitespaces) != OUT_OF_RANGE) {
662
0
                pos += num_whitespaces - 1;
663
0
                _add_token(pos);
664
0
                continue;
665
0
            }
666
667
            // Pattern 8: \s+ (general whitespace)
668
0
            if (num_whitespaces > 0) {
669
0
                pos += num_whitespaces;
670
0
                _add_token(pos);
671
0
                continue;
672
0
            }
673
674
            // No matches - consume single character
675
0
            _add_token(++pos);
676
0
        }
677
0
    }
678
679
0
    return bpe_offsets;
680
0
}
681
682
// AFMOE digit handling: splits digits with leading 1-2 based on total length modulo 3
683
0
static std::vector<size_t> unicode_regex_split_custom_afmoe(const std::string & text, const std::vector<size_t> & offsets) {
684
0
    std::vector<size_t> bpe_offsets;
685
0
    bpe_offsets.reserve(offsets.size());
686
687
0
    const auto cpts = unicode_cpts_from_utf8(text);
688
689
0
    size_t start = 0;
690
0
    for (auto offset : offsets) {
691
0
        const size_t offset_ini = start;
692
0
        const size_t offset_end = start + offset;
693
0
        assert(offset_end <= cpts.size());
694
0
        start = offset_end;
695
696
0
        auto _get_flags = [&] (const size_t pos) -> unicode_cpt_flags {
697
0
            return (offset_ini <= pos && pos < offset_end) ? unicode_cpt_flags_from_cpt(cpts[pos]) : unicode_cpt_flags{};
698
0
        };
699
700
0
        size_t _prev_end = offset_ini;
701
0
        auto _add_token = [&] (const size_t end) -> size_t {
702
0
            assert(_prev_end <= end && end <= offset_end);
703
0
            size_t len = end - _prev_end;
704
0
            if (len > 0) {
705
0
                bpe_offsets.push_back(len);
706
0
            }
707
0
            _prev_end = end;
708
0
            return len;
709
0
        };
710
711
0
        for (size_t pos = offset_ini; pos < offset_end; ) {
712
0
            const auto flags = _get_flags(pos);
713
714
            // Handle digit sequences with special splitting logic
715
0
            if (flags.is_number) {
716
0
                size_t digit_start = pos;
717
0
                size_t digit_count = 0;
718
719
                // Count consecutive digits
720
0
                while (_get_flags(pos).is_number && pos < offset_end) {
721
0
                    digit_count++;
722
0
                    pos++;
723
0
                }
724
725
                // Split based on total length modulo 3
726
0
                size_t remainder = digit_count % 3;
727
0
                size_t current = digit_start;
728
729
                // Emit leading 1-2 digits if needed
730
0
                if (remainder > 0) {
731
0
                    _add_token(current + remainder);
732
0
                    current += remainder;
733
0
                }
734
735
                // Emit groups of 3
736
0
                while (current < digit_start + digit_count) {
737
0
                    _add_token(current + 3);
738
0
                    current += 3;
739
0
                }
740
0
                continue;
741
0
            }
742
743
            // For non-digits, just move forward
744
0
            pos++;
745
0
        }
746
747
        // Add any remaining content
748
0
        if (_prev_end < offset_end) {
749
0
            _add_token(offset_end);
750
0
        }
751
0
    }
752
753
0
    return bpe_offsets;
754
0
}
755
756
0
static std::vector<size_t> unicode_regex_split_custom(const std::string & text, const std::string & regex_expr, const std::vector<size_t> & offsets) {
757
0
    std::vector<size_t> bpe_offsets;
758
759
0
    if (regex_expr == "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)") {
760
0
        bpe_offsets = unicode_regex_split_custom_gpt2(text, offsets);
761
0
    } else if (
762
0
            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+" ||
763
0
            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+") {
764
765
0
        bpe_offsets = unicode_regex_split_custom_llama3(text, offsets);
766
0
    } else if (regex_expr == "\\p{Han}+") {
767
        // K2's first pattern - handle all K2 patterns together
768
0
        bpe_offsets = unicode_regex_split_custom_kimi_k2(text, offsets);
769
0
    } else if (regex_expr == "\\p{AFMoE_digits}") {
770
        // AFMOE digit pattern - use custom implementation for proper splitting
771
0
        bpe_offsets = unicode_regex_split_custom_afmoe(text, offsets);
772
0
    } else if (regex_expr == "\\d{1,3}(?=(?:\\d{3})*\\b)") {
773
        // tiny_aya digit grouping pattern from tokenizer.json:
774
        //   {"type": "Split", "pattern": {"Regex": "\\d{1,3}(?=(?:\\d{3})*\\b)"}, "behavior": "Isolated"}
775
        // Splits digits into groups of 3 from the right (e.g., 1234567 -> 1, 234, 567)
776
        // TODO: Revisit this regex, incase there are any subtle tokenization differences with the original regex.
777
0
        bpe_offsets = unicode_regex_split_custom_afmoe(text, offsets);
778
0
    }
779
780
0
    return bpe_offsets;
781
0
}
782
783
//
784
// interface
785
//
786
787
0
std::string unicode_cpt_to_utf8(uint32_t cpt) {
788
0
    std::string result;
789
790
0
    if (/* 0x00 <= cpt && */ cpt <= 0x7f) {
791
0
        result.push_back(cpt);
792
0
        return result;
793
0
    }
794
0
    if (0x80 <= cpt && cpt <= 0x7ff) {
795
0
        result.push_back(0xc0 | ((cpt >> 6) & 0x1f));
796
0
        result.push_back(0x80 | (cpt & 0x3f));
797
0
        return result;
798
0
    }
799
0
    if (0x800 <= cpt && cpt <= 0xffff) {
800
0
        result.push_back(0xe0 | ((cpt >> 12) & 0x0f));
801
0
        result.push_back(0x80 | ((cpt >> 6) & 0x3f));
802
0
        result.push_back(0x80 | (cpt & 0x3f));
803
0
        return result;
804
0
    }
805
0
    if (0x10000 <= cpt && cpt <= 0x10ffff) {
806
0
        result.push_back(0xf0 | ((cpt >> 18) & 0x07));
807
0
        result.push_back(0x80 | ((cpt >> 12) & 0x3f));
808
0
        result.push_back(0x80 | ((cpt >> 6) & 0x3f));
809
0
        result.push_back(0x80 | (cpt & 0x3f));
810
0
        return result;
811
0
    }
812
813
0
    throw std::invalid_argument("invalid codepoint");
814
0
}
815
816
0
std::vector<uint32_t> unicode_cpts_normalize_nfd(const std::vector<uint32_t> & cpts) {
817
0
    auto comp = [] (const uint32_t cpt, const range_nfd & range) {
818
0
        return cpt < range.first;
819
0
    };
820
0
    std::vector<uint32_t> result(cpts.size());
821
0
    for (size_t i = 0; i < cpts.size(); ++i) {
822
0
        const uint32_t cpt = cpts[i];
823
0
        auto it = std::upper_bound(unicode_ranges_nfd.begin(), unicode_ranges_nfd.end(), cpt, comp) - 1;
824
0
        result[i] = (it->first <= cpt && cpt <= it->last) ? it->nfd : cpt;
825
0
    }
826
0
    return result;
827
0
}
828
829
0
std::vector<uint32_t> unicode_cpts_from_utf8(const std::string & utf8) {
830
0
    std::vector<uint32_t> result;
831
0
    result.reserve(utf8.size());
832
0
    size_t offset = 0;
833
0
    while (offset < utf8.size()) {
834
0
        try {
835
0
            result.push_back(unicode_cpt_from_utf8(utf8, offset));
836
0
        }
837
0
        catch (const std::invalid_argument & /*ex*/) {
838
            // Silently ignore invalid UTF-8 input to avoid leaking the exception beyond llama_tokenize
839
0
            ++offset;
840
0
            result.emplace_back(0xFFFD); // replacement character
841
0
        }
842
0
    }
843
0
    return result;
844
0
}
845
846
0
unicode_cpt_flags unicode_cpt_flags_from_cpt(const uint32_t cpt) {
847
0
    static const unicode_cpt_flags undef(unicode_cpt_flags::UNDEFINED);
848
0
    static const auto cpt_flags = unicode_cpt_flags_array();
849
0
    return cpt < cpt_flags.size() ? cpt_flags[cpt] : undef;
850
0
}
851
852
0
unicode_cpt_flags unicode_cpt_flags_from_utf8(const std::string & utf8) {
853
0
    static const unicode_cpt_flags undef(unicode_cpt_flags::UNDEFINED);
854
0
    if (utf8.empty()) {
855
0
        return undef;  // undefined
856
0
    }
857
0
    size_t offset = 0;
858
0
    return unicode_cpt_flags_from_cpt(unicode_cpt_from_utf8(utf8, offset));
859
0
}
860
861
0
std::string unicode_byte_to_utf8(uint8_t byte) {
862
0
    static std::unordered_map<uint8_t, std::string> map = unicode_byte_to_utf8_map();
863
0
    return map.at(byte);
864
0
}
865
866
0
uint8_t unicode_utf8_to_byte(const std::string & utf8) {
867
0
    static std::unordered_map<std::string, uint8_t> map = unicode_utf8_to_byte_map();
868
0
    return map.at(utf8);
869
0
}
870
871
0
uint32_t unicode_tolower(uint32_t cpt) {
872
    // binary search
873
0
    auto it = std::lower_bound(unicode_map_lowercase.begin(), unicode_map_lowercase.end(), cpt,
874
0
        [](const std::pair<uint32_t, uint32_t> & pair, uint32_t value) {
875
0
            return pair.first < value;
876
0
        });
877
0
    if (it != unicode_map_lowercase.end() && it->first == cpt) {
878
0
        return it->second;
879
0
    }
880
0
    return cpt;  // Return the original code point if no lowercase mapping is found
881
0
}
882
883
0
bool unicode_cpt_is_han(uint32_t cpt) {
884
    // Han character ranges (Chinese/CJK characters)
885
    // CJK Unified Ideographs (most common)
886
0
    if (cpt >= 0x4E00 && cpt <= 0x9FFF) return true;
887
888
    // CJK Extension A
889
0
    if (cpt >= 0x3400 && cpt <= 0x4DBF) return true;
890
891
    // CJK Extension B
892
0
    if (cpt >= 0x20000 && cpt <= 0x2A6DF) return true;
893
894
    // CJK Extension C
895
0
    if (cpt >= 0x2A700 && cpt <= 0x2B73F) return true;
896
897
    // CJK Extension D
898
0
    if (cpt >= 0x2B740 && cpt <= 0x2B81F) return true;
899
900
    // CJK Extension E
901
0
    if (cpt >= 0x2B820 && cpt <= 0x2CEAF) return true;
902
903
    // CJK Extension F
904
0
    if (cpt >= 0x2CEB0 && cpt <= 0x2EBEF) return true;
905
906
    // CJK Compatibility Ideographs
907
0
    if (cpt >= 0xF900 && cpt <= 0xFAFF) return true;
908
909
    // CJK Compatibility Ideographs Supplement
910
0
    if (cpt >= 0x2F800 && cpt <= 0x2FA1F) return true;
911
912
0
    return false;
913
0
}
914
915
0
std::vector<std::string> unicode_regex_split(const std::string & text, const std::vector<std::string> & regex_exprs) {
916
    // unicode categories
917
0
    static const std::map<std::string, int> k_ucat_enum = {
918
0
        { "\\p{N}", unicode_cpt_flags::NUMBER },
919
0
        { "\\p{L}", unicode_cpt_flags::LETTER },
920
0
        { "\\p{P}", unicode_cpt_flags::PUNCTUATION },
921
0
        { "\\p{M}", unicode_cpt_flags::ACCENT_MARK },
922
0
        { "\\p{S}", unicode_cpt_flags::SYMBOL },
923
0
        { "\\p{Lu}", unicode_cpt_flags::LETTER }, // Uppercase letter
924
0
        { "\\p{Ll}", unicode_cpt_flags::LETTER }, // Lowercase letter
925
0
        { "\\p{Lt}", unicode_cpt_flags::LETTER }, // Titlecase letter
926
0
        { "\\p{Lm}", unicode_cpt_flags::LETTER }, // Modifier letter
927
0
        { "\\p{Lo}", unicode_cpt_flags::LETTER }, // Other letter
928
0
    };
929
930
0
    static const std::map<int, int> k_ucat_cpt = {
931
0
        { unicode_cpt_flags::NUMBER,      0xD1 },
932
0
        { unicode_cpt_flags::LETTER,      0xD2 },
933
0
        { unicode_cpt_flags::PUNCTUATION, 0xD3 },
934
0
        { unicode_cpt_flags::ACCENT_MARK, 0xD4 },
935
0
        { unicode_cpt_flags::SYMBOL,      0xD5 },
936
0
    };
937
938
0
    static const std::map<int, std::string> k_ucat_map = {
939
0
        { unicode_cpt_flags::NUMBER,      "\x30-\x39" }, // 0-9
940
0
        { unicode_cpt_flags::LETTER,      "\x41-\x5A\x61-\x7A" }, // A-Za-z
941
0
        { unicode_cpt_flags::PUNCTUATION, "\x21-\x23\x25-\x2A\x2C-\x2F\x3A-\x3B\x3F-\x40\\\x5B-\\\x5D\x5F\\\x7B\\\x7D" }, // !-#%-*,-/:-;?-@\[-\]_\{\}
942
0
        { unicode_cpt_flags::ACCENT_MARK, "" }, // no sub-128 codepoints
943
0
        { unicode_cpt_flags::SYMBOL,      "\\\x24\\\x2B\x3C-\x3E\x5E\x60\\\x7C" }, // $+<=>^`|
944
0
    };
945
946
    // compute collapsed codepoints only if needed by at least one regex
947
0
    bool need_collapse = false;
948
0
    for (const auto & regex_expr : regex_exprs) {
949
        // search for unicode categories
950
0
        for (const auto & ucat : k_ucat_enum) {
951
0
            if (std::string::npos != regex_expr.find(ucat.first)) {
952
0
                need_collapse = true;
953
0
                break;
954
0
            }
955
0
        }
956
0
    }
957
958
0
    const auto cpts = unicode_cpts_from_utf8(text);
959
960
    // generate a "collapsed" representation of the text, where all codepoints are replaced by a single byte
961
    // ref: https://github.com/ggml-org/llama.cpp/pull/6920#issuecomment-2081479935
962
0
    std::string text_collapsed;
963
0
    if (need_collapse) {
964
        // collapse all unicode categories
965
0
        text_collapsed.resize(cpts.size());
966
967
0
        for (size_t i = 0; i < cpts.size(); ++i) {
968
            // keep single-byte codepoints as is
969
0
            if (cpts[i] < 128) {
970
0
                text_collapsed[i] = cpts[i];
971
0
                continue;
972
0
            }
973
974
0
            const auto flags = unicode_cpt_flags_from_cpt(cpts[i]);
975
976
0
            if (flags.is_whitespace) {
977
                //NOTE: C++ std::regex \s does not mach 0x85, Rust and Python regex does.
978
                //text_collapsed[i] = (char) 0x85;  // <Next Line> as whitespace fallback
979
0
                text_collapsed[i] = (char) 0x0B;    // <vertical tab> as whitespace fallback
980
0
            } else if (k_ucat_cpt.find(flags.category_flag()) != k_ucat_cpt.end()) {
981
0
                text_collapsed[i] = k_ucat_cpt.at(flags.category_flag());
982
0
            } else {
983
0
                text_collapsed[i] = (char) 0xD0; // fallback
984
0
            }
985
0
        }
986
0
    }
987
988
0
    std::vector<size_t> bpe_offsets = { cpts.size() };
989
990
0
    for (const auto & regex_expr : regex_exprs) {
991
        // first, see if we have an efficient custom regex implementation
992
0
        auto tmp = unicode_regex_split_custom(text, regex_expr, bpe_offsets);
993
994
0
        if (!tmp.empty()) {
995
0
            bpe_offsets = std::move(tmp);
996
0
            continue;
997
0
        }
998
999
        // fallback to general-purpose std::regex / std::wregex
1000
0
        try {
1001
            // if a unicode category is used in the regex, we use the collapsed text and replace the unicode category
1002
            // with the corresponding collapsed representation
1003
0
            bool use_collapsed = false;
1004
0
            for (const auto & ucat : k_ucat_enum) {
1005
0
                if (std::string::npos != regex_expr.find(ucat.first)) {
1006
0
                    use_collapsed = true;
1007
0
                    break;
1008
0
                }
1009
0
            }
1010
0
            const auto cpts_regex = unicode_cpts_from_utf8(regex_expr);
1011
1012
0
            if (use_collapsed) {
1013
                // sanity-check that the original regex does not contain any non-ASCII characters
1014
0
                for (size_t i = 0; i < cpts_regex.size(); ++i) {
1015
0
                    if (cpts_regex[i] >= 128) {
1016
0
                        throw std::runtime_error("Regex includes both unicode categories and non-ASCII characters - not supported");
1017
0
                    }
1018
0
                }
1019
1020
                // generate a collapsed representation of the regex
1021
0
                std::string regex_expr_collapsed;
1022
1023
                // track if we are inside [], because nested [] are not allowed
1024
0
                bool inside = false;
1025
0
                for (size_t i = 0; i < regex_expr.size(); ++i) {
1026
0
                    if (regex_expr[i] == '[' && (i == 0 || regex_expr[i - 1] != '\\')) {
1027
0
                        regex_expr_collapsed += '[';
1028
0
                        inside = true;
1029
0
                        continue;
1030
0
                    }
1031
1032
0
                    if (inside && regex_expr[i] == ']' && regex_expr[i - 1] != '\\') {
1033
0
                        regex_expr_collapsed += ']';
1034
0
                        inside = false;
1035
0
                        continue;
1036
0
                    }
1037
1038
                    // Match \p{...} Unicode properties of varying lengths
1039
0
                    if (regex_expr[i + 0] == '\\' && i + 3 < regex_expr.size() &&
1040
0
                        regex_expr[i + 1] == 'p' &&
1041
0
                        regex_expr[i + 2] == '{') {
1042
                        // Find the closing brace
1043
0
                        size_t closing_brace = regex_expr.find('}', i + 3);
1044
0
                        if (closing_brace != std::string::npos && closing_brace <= i + 10) { // reasonable limit
1045
0
                            const std::string pat = regex_expr.substr(i, closing_brace - i + 1);
1046
0
                            if (k_ucat_enum.find(pat) != k_ucat_enum.end()) {
1047
0
                                if (!inside) {
1048
0
                                    regex_expr_collapsed += '[';
1049
0
                                }
1050
0
                                regex_expr_collapsed += k_ucat_cpt.at(k_ucat_enum.at(pat));
1051
0
                                regex_expr_collapsed += k_ucat_map.at(k_ucat_enum.at(pat));
1052
0
                                if (!inside) {
1053
0
                                    regex_expr_collapsed += ']';
1054
0
                                }
1055
0
                                i = closing_brace;
1056
0
                                continue;
1057
0
                            }
1058
0
                        }
1059
0
                    }
1060
1061
0
                    regex_expr_collapsed += regex_expr[i];
1062
0
                }
1063
1064
                //printf("text_collapsed: %s\n", text_collapsed.c_str());
1065
                //printf("regex_expr_collapsed: %s\n", regex_expr_collapsed.c_str());
1066
0
                bpe_offsets = unicode_regex_split_stl(text_collapsed, regex_expr_collapsed, bpe_offsets);
1067
0
            } else {
1068
                // no unicode category used, we can use std::wregex directly
1069
0
                std::wstring wregex_expr(cpts_regex.begin(), cpts_regex.end());
1070
1071
                // std::wregex \s does not mach non-ASCII whitespaces, using 0x0B as fallback
1072
0
                std::wstring wtext(cpts.begin(), cpts.end());
1073
0
                for (size_t i = 0; i < wtext.size(); ++i) {
1074
0
                    if (wtext[i] > 0x7F && unicode_cpt_flags_from_cpt(wtext[i]).is_whitespace) {
1075
0
                        wtext[i] = 0x0B;
1076
0
                    }
1077
0
                }
1078
1079
                //printf("text: %s\n", text.c_str());
1080
                //printf("regex_expr: %s\n", regex_expr.c_str());
1081
0
                bpe_offsets = unicode_regex_split_stl(wtext, wregex_expr, bpe_offsets);
1082
0
            }
1083
0
        } catch (std::regex_error & e) {
1084
0
            fprintf(stderr, "Failed to process regex: '%s'\n", regex_expr.c_str());
1085
0
            fprintf(stderr, "Regex error: %s\n", e.what());
1086
0
            throw std::runtime_error("Failed to process regex");
1087
0
        }
1088
0
    }
1089
1090
0
    std::vector<std::string> bpe_words;
1091
0
    bpe_words.reserve(bpe_offsets.size()); // reserve memory for the approximate size
1092
1093
0
    size_t start = 0;
1094
0
    for (size_t & offset : bpe_offsets) {
1095
0
        bpe_words.emplace_back();
1096
0
        for (size_t i = start; i < start + offset; ++i) {
1097
0
            bpe_words.back() += unicode_cpt_to_utf8(cpts[i]);
1098
0
        }
1099
0
        start += offset;
1100
0
    }
1101
1102
0
    return unicode_byte_encoding_process(bpe_words);
1103
0
}