Coverage Report

Created: 2026-06-13 06:24

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
// Qwen2 system regex: "(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+"
474
0
static std::vector<size_t> unicode_regex_split_custom_qwen2(const std::string & text, const std::vector<size_t> & offsets) {
475
0
    std::vector<size_t> bpe_offsets; // store the offset of each word
476
0
    bpe_offsets.reserve(offsets.size()); // Reserve memory for the approximate size
477
478
0
    const auto cpts = unicode_cpts_from_utf8(text);
479
480
0
    size_t start = 0;
481
0
    for (auto offset : offsets) {
482
0
        const size_t offset_ini = start;
483
0
        const size_t offset_end = start + offset;
484
0
        assert(offset_end <= cpts.size());
485
0
        start = offset_end;
486
487
0
        static const uint32_t OUT_OF_RANGE = 0xFFFFFFFF;
488
0
        auto _get_cpt = [&] (const size_t pos) -> uint32_t {
489
0
            return (offset_ini <= pos && pos < offset_end) ? cpts[pos] : OUT_OF_RANGE;
490
0
        };
491
492
0
        auto _get_flags = [&] (const size_t pos) -> unicode_cpt_flags {
493
0
            return (offset_ini <= pos && pos < offset_end) ? unicode_cpt_flags_from_cpt(cpts[pos]) : unicode_cpt_flags{};
494
0
        };
495
496
0
        size_t _prev_end = offset_ini;
497
0
        auto _add_token = [&] (const size_t end) -> size_t {
498
0
            assert(_prev_end <= end && end <= offset_end);
499
0
            size_t len = end - _prev_end;
500
0
            if (len > 0) {
501
0
                bpe_offsets.push_back(len);
502
0
            }
503
0
            _prev_end = end;
504
            //if (len > 0) {
505
            //    std::string s = "";
506
            //    for(size_t p = end-len; p < end; p++)
507
            //        s += unicode_cpt_to_utf8(cpts[p]);
508
            //    printf(">>> '%s'\n", s.c_str());
509
            //}
510
0
            return len;
511
0
        };
512
513
0
        for (size_t pos = offset_ini; pos < offset_end; /*pos++*/ ) {
514
0
            const uint32_t cpt = _get_cpt(pos);
515
0
            const auto flags = _get_flags(pos);
516
517
            // regex: (?i:'s|'t|'re|'ve|'m|'ll|'d) // case insensitive
518
0
            if (cpt == '\'' && pos+1 < offset_end) {
519
0
                uint32_t cpt_next = unicode_tolower(_get_cpt(pos+1));
520
0
                if (cpt_next == 's' || cpt_next == 't' || cpt_next == 'm' || cpt_next == 'd') {
521
0
                    pos += _add_token(pos+2);
522
0
                    continue;
523
0
                }
524
0
                if (pos+2 < offset_end) {
525
0
                    uint32_t cpt_next_next = unicode_tolower(_get_cpt(pos+2));
526
0
                    if ((cpt_next == 'r' && cpt_next_next == 'e') ||
527
0
                        (cpt_next == 'v' && cpt_next_next == 'e') ||
528
0
                        (cpt_next == 'l' && cpt_next_next == 'l')) {
529
0
                        pos += _add_token(pos+3);
530
0
                        continue;
531
0
                    }
532
0
                }
533
0
            }
534
535
            // regex: [^\r\n\p{L}\p{N}]?\p{L}+
536
0
            if (!(cpt == '\r' || cpt == '\n' || flags.is_number)) {
537
0
                if (flags.is_letter || _get_flags(pos+1).is_letter) {  // one or more letters
538
0
                    pos++;
539
0
                    while (_get_flags(pos).is_letter) {
540
0
                        pos++;
541
0
                    }
542
0
                    _add_token(pos);
543
0
                    continue;
544
0
                }
545
0
            }
546
547
            // regex: \p{N}
548
0
            if (flags.is_number) {
549
0
                pos++;
550
0
                _add_token(pos);
551
0
                continue;
552
0
            }
553
554
            // regex: <space>?[^\s\p{L}\p{N}]+[\r\n]*
555
0
            auto flags2 = (cpt == ' ' ? _get_flags(pos+1) : flags);
556
0
            if (!(flags2.is_whitespace | flags2.is_letter | flags2.is_number) && flags.as_uint()) {
557
0
                pos += (cpt == ' ');
558
0
                while (!(flags2.is_whitespace | flags2.is_letter | flags2.is_number) && flags2.as_uint()) {
559
0
                    flags2 = _get_flags(++pos);
560
0
                }
561
0
                uint32_t cpt2 = _get_cpt(pos);
562
0
                while (cpt2 == '\r' || cpt2 == '\n') {
563
0
                    cpt2 = _get_cpt(++pos);
564
0
                }
565
0
                _add_token(pos);
566
0
                continue;
567
0
            }
568
569
0
            size_t num_whitespaces = 0;
570
0
            size_t last_end_r_or_n = 0;
571
0
            while (_get_flags(pos+num_whitespaces).is_whitespace) {
572
0
                uint32_t cpt2 = _get_cpt(pos+num_whitespaces);
573
0
                if (cpt2 == '\r' || cpt2 == '\n') {
574
0
                    last_end_r_or_n = pos + num_whitespaces + 1;
575
0
                }
576
0
                num_whitespaces++;
577
0
            }
578
579
            // regex: \s*[\r\n]+
580
0
            if (last_end_r_or_n > 0) {
581
0
                pos = last_end_r_or_n;
582
0
                _add_token(pos);
583
0
                continue;
584
0
            }
585
586
            // regex: \s+(?!\S)
587
0
            if (num_whitespaces > 1 && _get_cpt(pos+num_whitespaces) != OUT_OF_RANGE) {
588
0
                pos += num_whitespaces - 1;
589
0
                _add_token(pos);
590
0
                continue;
591
0
            }
592
593
            // regex: \s+
594
0
            if (num_whitespaces > 0) {
595
0
                pos += num_whitespaces;
596
0
                _add_token(pos);
597
0
                continue;
598
0
            }
599
600
            // no matches
601
0
            _add_token(++pos);
602
0
        }
603
0
    }
604
605
0
    return bpe_offsets;
606
0
}
607
608
// Qwen3.5 system regex: "(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\\r\\n\\p{L}\\p{N}]?[\\p{L}\\p{M}]+|\\p{N}| ?[^\\s\\p{L}\\p{M}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+"
609
// Compared to Qwen2, letter-runs also consume Unicode combining marks (\p{M}): [\p{L}\p{M}]+ instead of \p{L}+
610
0
static std::vector<size_t> unicode_regex_split_custom_qwen35(const std::string & text, const std::vector<size_t> & offsets) {
611
0
    std::vector<size_t> bpe_offsets; // store the offset of each word
612
0
    bpe_offsets.reserve(offsets.size()); // Reserve memory for the approximate size
613
614
0
    const auto cpts = unicode_cpts_from_utf8(text);
615
616
0
    size_t start = 0;
617
0
    for (auto offset : offsets) {
618
0
        const size_t offset_ini = start;
619
0
        const size_t offset_end = start + offset;
620
0
        assert(offset_end <= cpts.size());
621
0
        start = offset_end;
622
623
0
        static const uint32_t OUT_OF_RANGE = 0xFFFFFFFF;
624
0
        auto _get_cpt = [&] (const size_t pos) -> uint32_t {
625
0
            return (offset_ini <= pos && pos < offset_end) ? cpts[pos] : OUT_OF_RANGE;
626
0
        };
627
628
0
        auto _get_flags = [&] (const size_t pos) -> unicode_cpt_flags {
629
0
            return (offset_ini <= pos && pos < offset_end) ? unicode_cpt_flags_from_cpt(cpts[pos]) : unicode_cpt_flags{};
630
0
        };
631
632
0
        size_t _prev_end = offset_ini;
633
0
        auto _add_token = [&] (const size_t end) -> size_t {
634
0
            assert(_prev_end <= end && end <= offset_end);
635
0
            size_t len = end - _prev_end;
636
0
            if (len > 0) {
637
0
                bpe_offsets.push_back(len);
638
0
            }
639
0
            _prev_end = end;
640
0
            return len;
641
0
        };
642
643
0
        for (size_t pos = offset_ini; pos < offset_end; /*pos++*/ ) {
644
0
            const uint32_t cpt = _get_cpt(pos);
645
0
            const auto flags = _get_flags(pos);
646
647
            // regex: (?i:'s|'t|'re|'ve|'m|'ll|'d) // case insensitive
648
0
            if (cpt == '\'' && pos+1 < offset_end) {
649
0
                uint32_t cpt_next = unicode_tolower(_get_cpt(pos+1));
650
0
                if (cpt_next == 's' || cpt_next == 't' || cpt_next == 'm' || cpt_next == 'd') {
651
0
                    pos += _add_token(pos+2);
652
0
                    continue;
653
0
                }
654
0
                if (pos+2 < offset_end) {
655
0
                    uint32_t cpt_next_next = unicode_tolower(_get_cpt(pos+2));
656
0
                    if ((cpt_next == 'r' && cpt_next_next == 'e') ||
657
0
                        (cpt_next == 'v' && cpt_next_next == 'e') ||
658
0
                        (cpt_next == 'l' && cpt_next_next == 'l')) {
659
0
                        pos += _add_token(pos+3);
660
0
                        continue;
661
0
                    }
662
0
                }
663
0
            }
664
665
            // regex: [^\r\n\p{L}\p{N}]?[\p{L}\p{M}]+
666
0
            if (!(cpt == '\r' || cpt == '\n' || flags.is_number)) {
667
0
                if (flags.is_letter || flags.is_accent_mark || _get_flags(pos + 1).is_accent_mark || _get_flags(pos+1).is_letter) {
668
0
                    pos++;
669
0
                    while (_get_flags(pos).is_letter || _get_flags(pos).is_accent_mark) {
670
0
                        pos++;
671
0
                    }
672
0
                    _add_token(pos);
673
0
                    continue;
674
0
                }
675
0
            }
676
677
            // regex: \p{N}
678
0
            if (flags.is_number) {
679
0
                pos++;
680
0
                _add_token(pos);
681
0
                continue;
682
0
            }
683
684
            // regex: <space>?[^\s\p{L}\p{M}\p{N}]+[\r\n]*
685
0
            auto flags2 = (cpt == ' ' ? _get_flags(pos+1) : flags);
686
0
            if (!(flags2.is_whitespace | flags2.is_letter | flags2.is_accent_mark | flags2.is_number) && flags.as_uint()) {
687
0
                pos += (cpt == ' ');
688
0
                while (!(flags2.is_whitespace | flags2.is_letter | flags2.is_accent_mark | flags2.is_number) && flags2.as_uint()) {
689
0
                    flags2 = _get_flags(++pos);
690
0
                }
691
0
                uint32_t cpt2 = _get_cpt(pos);
692
0
                while (cpt2 == '\r' || cpt2 == '\n') {
693
0
                    cpt2 = _get_cpt(++pos);
694
0
                }
695
0
                _add_token(pos);
696
0
                continue;
697
0
            }
698
699
0
            size_t num_whitespaces = 0;
700
0
            size_t last_end_r_or_n = 0;
701
0
            while (_get_flags(pos+num_whitespaces).is_whitespace) {
702
0
                uint32_t cpt2 = _get_cpt(pos+num_whitespaces);
703
0
                if (cpt2 == '\r' || cpt2 == '\n') {
704
0
                    last_end_r_or_n = pos + num_whitespaces + 1;
705
0
                }
706
0
                num_whitespaces++;
707
0
            }
708
709
            // regex: \s*[\r\n]+
710
0
            if (last_end_r_or_n > 0) {
711
0
                pos = last_end_r_or_n;
712
0
                _add_token(pos);
713
0
                continue;
714
0
            }
715
716
            // regex: \s+(?!\S)
717
0
            if (num_whitespaces > 1 && _get_cpt(pos+num_whitespaces) != OUT_OF_RANGE) {
718
0
                pos += num_whitespaces - 1;
719
0
                _add_token(pos);
720
0
                continue;
721
0
            }
722
723
            // regex: \s+
724
0
            if (num_whitespaces > 0) {
725
0
                pos += num_whitespaces;
726
0
                _add_token(pos);
727
0
                continue;
728
0
            }
729
730
            // no matches
731
0
            _add_token(++pos);
732
0
        }
733
0
    }
734
735
0
    return bpe_offsets;
736
0
}
737
738
template <typename CharT>
739
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) {
740
0
    using BidirIt = typename std::basic_string<CharT>::const_iterator;
741
#ifdef _MSC_VER
742
    // Bypass bug in MSVC: https://github.com/ggml-org/llama.cpp/issues/17830
743
    constexpr auto regex_flags = std::regex_constants::ECMAScript;
744
#else
745
0
    constexpr auto regex_flags = std::regex_constants::optimize | std::regex_constants::nosubs;
746
0
#endif
747
0
    std::basic_regex<CharT> expr(regex, regex_flags);
748
0
    std::vector<size_t> bpe_offsets; // store the offset of each word
749
0
    bpe_offsets.reserve(offsets.size()); // Reserve memory for the approximate size
750
0
    size_t start = 0;
751
0
    for (auto offset : offsets) {
752
0
        std::regex_iterator<BidirIt> it(text.begin() + start, text.begin() + start + offset, expr);
753
0
        std::regex_iterator<BidirIt> end;
754
755
0
        int64_t start_idx = 0;
756
0
        while (it != end) {
757
0
            std::match_results<BidirIt> match = *it;
758
0
            if (match.position() > start_idx) {
759
0
                bpe_offsets.emplace_back(match.position() - start_idx);
760
0
            }
761
0
            bpe_offsets.emplace_back(match.length());
762
0
            start_idx = match.position() + match.length();
763
0
            ++it;
764
0
        }
765
766
0
        if (start_idx < (int64_t) offset) {
767
0
            bpe_offsets.emplace_back(offset - start_idx);
768
0
        }
769
0
        start += offset;
770
0
    }
771
772
0
    return bpe_offsets;
773
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&)
774
775
// K2 system regex patterns (from tokenization_kimi.py):
776
// [\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+
777
0
static std::vector<size_t> unicode_regex_split_custom_kimi_k2(const std::string & text, const std::vector<size_t> & offsets) {
778
0
    std::vector<size_t> bpe_offsets;
779
0
    bpe_offsets.reserve(offsets.size());
780
781
0
    const auto cpts = unicode_cpts_from_utf8(text);
782
783
0
    size_t start = 0;
784
0
    for (auto offset : offsets) {
785
0
        const size_t offset_ini = start;
786
0
        const size_t offset_end = start + offset;
787
0
        assert(offset_end <= cpts.size());
788
0
        start = offset_end;
789
790
0
        static const uint32_t OUT_OF_RANGE = 0xFFFFFFFF;
791
0
        auto _get_cpt = [&] (const size_t pos) -> uint32_t {
792
0
            return (offset_ini <= pos && pos < offset_end) ? cpts[pos] : OUT_OF_RANGE;
793
0
        };
794
795
0
        auto _get_flags = [&] (const size_t pos) -> unicode_cpt_flags {
796
0
            return (offset_ini <= pos && pos < offset_end) ? unicode_cpt_flags_from_cpt(cpts[pos]) : unicode_cpt_flags{};
797
0
        };
798
799
0
        size_t _prev_end = offset_ini;
800
0
        auto _add_token = [&] (const size_t end) -> size_t {
801
0
            assert(_prev_end <= end && end <= offset_end);
802
0
            size_t len = end - _prev_end;
803
0
            if (len > 0) {
804
0
                bpe_offsets.push_back(len);
805
0
            }
806
0
            _prev_end = end;
807
0
            return len;
808
0
        };
809
810
0
        for (size_t pos = offset_ini; pos < offset_end; /*pos++*/ ) {
811
0
            const uint32_t cpt = _get_cpt(pos);
812
0
            const auto flags = _get_flags(pos);
813
814
            // Pattern 1: [\p{Han}]+ (Chinese characters)
815
0
            if (unicode_cpt_is_han(cpt)) {
816
0
                while (unicode_cpt_is_han(_get_cpt(pos))) {
817
0
                    pos++;
818
0
                }
819
0
                _add_token(pos);
820
0
                continue;
821
0
            }
822
823
            // Pattern 2 & 3: Letter words excluding Han characters with optional contractions
824
            // [^\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)?
825
            // [^\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)?
826
            // Check if current char is a letter OR if current char could be a leading char and next char is a letter
827
0
            bool is_letter_pattern = (flags.is_letter && !unicode_cpt_is_han(cpt)) ||
828
0
                                     (!(cpt == '\r' || cpt == '\n' || flags.is_letter || flags.is_number) &&
829
0
                                      _get_flags(pos + 1).is_letter && !unicode_cpt_is_han(_get_cpt(pos + 1)));
830
831
0
            if (is_letter_pattern) {
832
                // Handle optional leading non-letter/non-number character
833
0
                bool has_leading_char = false;
834
0
                if (!(cpt == '\r' || cpt == '\n' || flags.is_letter || flags.is_number)) {
835
0
                    has_leading_char = true;
836
0
                    pos++;
837
0
                }
838
839
                // Match letter sequence (excluding Han characters)
840
0
                bool has_letters = false;
841
0
                while (_get_flags(pos).is_letter && !unicode_cpt_is_han(_get_cpt(pos))) {
842
0
                    has_letters = true;
843
0
                    pos++;
844
0
                }
845
846
                // Only proceed if we found letters (after potentially skipping leading char)
847
0
                if (has_letters || (!has_leading_char && _get_flags(pos).is_letter && !unicode_cpt_is_han(_get_cpt(pos)))) {
848
0
                    if (!has_letters) pos++; // consume the first letter if we didn't already
849
850
                    // Continue consuming letters
851
0
                    while (_get_flags(pos).is_letter && !unicode_cpt_is_han(_get_cpt(pos))) {
852
0
                        pos++;
853
0
                    }
854
855
                    // Check for optional contractions (?:'s|'t|'re|'ve|'m|'ll|'d)
856
0
                    if (_get_cpt(pos) == '\'' && pos + 1 < offset_end) {
857
0
                        uint32_t cpt_next = unicode_tolower(_get_cpt(pos + 1));
858
0
                        if (cpt_next == 's' || cpt_next == 't' || cpt_next == 'm' || cpt_next == 'd') {
859
0
                            pos += 2;
860
0
                        } else if (pos + 2 < offset_end) {
861
0
                            uint32_t cpt_next_next = unicode_tolower(_get_cpt(pos + 2));
862
0
                            if ((cpt_next == 'r' && cpt_next_next == 'e') ||
863
0
                                (cpt_next == 'v' && cpt_next_next == 'e') ||
864
0
                                (cpt_next == 'l' && cpt_next_next == 'l')) {
865
0
                                pos += 3;
866
0
                            }
867
0
                        }
868
0
                    }
869
870
0
                    _add_token(pos);
871
0
                    continue;
872
0
                } else if (has_leading_char) {
873
                    // We consumed a leading char but found no letters, backtrack
874
0
                    pos--;
875
0
                }
876
0
            }
877
878
            // Pattern 4: \p{N}{1,3} (numbers 1-3 digits)
879
0
            if (flags.is_number) {
880
0
                size_t ini = pos;
881
0
                while (_get_flags(pos).is_number) {
882
0
                    if (++pos - ini >= 3) {
883
0
                        _add_token(pos);
884
0
                        ini = pos;
885
0
                    }
886
0
                }
887
0
                _add_token(pos);
888
0
                continue;
889
0
            }
890
891
            // Pattern 5:  ?[^\s\p{L}\p{N}]+[\r\n]* (optional space + non-word chars + optional newlines)
892
0
            auto flags2 = (cpt == ' ' ? _get_flags(pos + 1) : flags);
893
0
            if (!(flags2.is_whitespace || flags2.is_letter || flags2.is_number) && flags2.as_uint()) {
894
0
                pos += (cpt == ' ');
895
0
                while (!(flags2.is_whitespace || flags2.is_letter || flags2.is_number) && flags2.as_uint()) {
896
0
                    flags2 = _get_flags(++pos);
897
0
                }
898
                // Match optional [\r\n]*
899
0
                uint32_t cpt2 = _get_cpt(pos);
900
0
                while (cpt2 == '\r' || cpt2 == '\n') {
901
0
                    cpt2 = _get_cpt(++pos);
902
0
                }
903
0
                _add_token(pos);
904
0
                continue;
905
0
            }
906
907
            // Count whitespace characters
908
0
            size_t num_whitespaces = 0;
909
0
            size_t last_end_r_or_n = 0;
910
0
            while (_get_flags(pos + num_whitespaces).is_whitespace) {
911
0
                uint32_t cpt2 = _get_cpt(pos + num_whitespaces);
912
0
                if (cpt2 == '\r' || cpt2 == '\n') {
913
0
                    last_end_r_or_n = pos + num_whitespaces + 1;
914
0
                }
915
0
                num_whitespaces++;
916
0
            }
917
918
            // Pattern 6: \s*[\r\n]+ (whitespace with newlines)
919
0
            if (last_end_r_or_n > 0) {
920
0
                pos = last_end_r_or_n;
921
0
                _add_token(pos);
922
0
                continue;
923
0
            }
924
925
            // Pattern 7: \s+(?!\S) (trailing whitespace)
926
0
            if (num_whitespaces > 1 && _get_cpt(pos + num_whitespaces) != OUT_OF_RANGE) {
927
0
                pos += num_whitespaces - 1;
928
0
                _add_token(pos);
929
0
                continue;
930
0
            }
931
932
            // Pattern 8: \s+ (general whitespace)
933
0
            if (num_whitespaces > 0) {
934
0
                pos += num_whitespaces;
935
0
                _add_token(pos);
936
0
                continue;
937
0
            }
938
939
            // No matches - consume single character
940
0
            _add_token(++pos);
941
0
        }
942
0
    }
943
944
0
    return bpe_offsets;
945
0
}
946
947
// AFMOE digit handling: splits digits with leading 1-2 based on total length modulo 3
948
0
static std::vector<size_t> unicode_regex_split_custom_afmoe(const std::string & text, const std::vector<size_t> & offsets) {
949
0
    std::vector<size_t> bpe_offsets;
950
0
    bpe_offsets.reserve(offsets.size());
951
952
0
    const auto cpts = unicode_cpts_from_utf8(text);
953
954
0
    size_t start = 0;
955
0
    for (auto offset : offsets) {
956
0
        const size_t offset_ini = start;
957
0
        const size_t offset_end = start + offset;
958
0
        assert(offset_end <= cpts.size());
959
0
        start = offset_end;
960
961
0
        auto _get_flags = [&] (const size_t pos) -> unicode_cpt_flags {
962
0
            return (offset_ini <= pos && pos < offset_end) ? unicode_cpt_flags_from_cpt(cpts[pos]) : unicode_cpt_flags{};
963
0
        };
964
965
0
        size_t _prev_end = offset_ini;
966
0
        auto _add_token = [&] (const size_t end) -> size_t {
967
0
            assert(_prev_end <= end && end <= offset_end);
968
0
            size_t len = end - _prev_end;
969
0
            if (len > 0) {
970
0
                bpe_offsets.push_back(len);
971
0
            }
972
0
            _prev_end = end;
973
0
            return len;
974
0
        };
975
976
0
        for (size_t pos = offset_ini; pos < offset_end; ) {
977
0
            const auto flags = _get_flags(pos);
978
979
            // Handle digit sequences with special splitting logic
980
0
            if (flags.is_number) {
981
0
                size_t digit_start = pos;
982
0
                size_t digit_count = 0;
983
984
                // Count consecutive digits
985
0
                while (_get_flags(pos).is_number && pos < offset_end) {
986
0
                    digit_count++;
987
0
                    pos++;
988
0
                }
989
990
                // Split based on total length modulo 3
991
0
                size_t remainder = digit_count % 3;
992
0
                size_t current = digit_start;
993
994
                // Emit leading 1-2 digits if needed
995
0
                if (remainder > 0) {
996
0
                    _add_token(current + remainder);
997
0
                    current += remainder;
998
0
                }
999
1000
                // Emit groups of 3
1001
0
                while (current < digit_start + digit_count) {
1002
0
                    _add_token(current + 3);
1003
0
                    current += 3;
1004
0
                }
1005
0
                continue;
1006
0
            }
1007
1008
            // For non-digits, just move forward
1009
0
            pos++;
1010
0
        }
1011
1012
        // Add any remaining content
1013
0
        if (_prev_end < offset_end) {
1014
0
            _add_token(offset_end);
1015
0
        }
1016
0
    }
1017
1018
0
    return bpe_offsets;
1019
0
}
1020
1021
// regex: [^\n]+|[\n]+
1022
// splits text into runs of non-newline characters and runs of newline characters
1023
0
static std::vector<size_t> unicode_regex_split_custom_newlines(const std::string & text, const std::vector<size_t> & offsets) {
1024
0
    std::vector<size_t> bpe_offsets;
1025
0
    bpe_offsets.reserve(offsets.size());
1026
1027
0
    const auto cpts = unicode_cpts_from_utf8(text);
1028
1029
0
    size_t start = 0;
1030
0
    for (auto offset : offsets) {
1031
0
        const size_t offset_ini = start;
1032
0
        const size_t offset_end = start + offset;
1033
0
        assert(offset_end <= cpts.size());
1034
0
        start = offset_end;
1035
1036
0
        size_t pos = offset_ini;
1037
0
        while (pos < offset_end) {
1038
0
            const bool is_newline = (cpts[pos] == '\n');
1039
0
            const size_t run_start = pos;
1040
0
            while (pos < offset_end && (cpts[pos] == '\n') == is_newline) {
1041
0
                pos++;
1042
0
            }
1043
0
            bpe_offsets.push_back(pos - run_start);
1044
0
        }
1045
0
    }
1046
1047
0
    return bpe_offsets;
1048
0
}
1049
1050
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) {
1051
0
    std::vector<size_t> bpe_offsets;
1052
1053
0
    if (regex_expr == "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)") {
1054
0
        bpe_offsets = unicode_regex_split_custom_gpt2(text, offsets);
1055
0
    } else if (
1056
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+" ||
1057
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+") {
1058
0
        bpe_offsets = unicode_regex_split_custom_llama3(text, offsets);
1059
0
    } else if (
1060
0
           regex_expr == "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+") {
1061
0
        bpe_offsets = unicode_regex_split_custom_qwen2(text, offsets);
1062
0
    } else if (
1063
0
           regex_expr == "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?[\\p{L}\\p{M}]+|\\p{N}| ?[^\\s\\p{L}\\p{M}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+") {
1064
0
        bpe_offsets = unicode_regex_split_custom_qwen35(text, offsets);
1065
0
    } else if (regex_expr == "\\p{Han}+") {
1066
        // K2's first pattern - handle all K2 patterns together
1067
0
        bpe_offsets = unicode_regex_split_custom_kimi_k2(text, offsets);
1068
0
    } else if (regex_expr == "\\p{AFMoE_digits}") {
1069
        // AFMOE digit pattern - use custom implementation for proper splitting
1070
0
        bpe_offsets = unicode_regex_split_custom_afmoe(text, offsets);
1071
0
    } else if (regex_expr == "[^\\n]+|[\\n]+") {
1072
0
        bpe_offsets = unicode_regex_split_custom_newlines(text, offsets);
1073
0
    } else if (regex_expr == "\\d{1,3}(?=(?:\\d{3})*\\b)") {
1074
        // tiny_aya digit grouping pattern from tokenizer.json:
1075
        //   {"type": "Split", "pattern": {"Regex": "\\d{1,3}(?=(?:\\d{3})*\\b)"}, "behavior": "Isolated"}
1076
        // Splits digits into groups of 3 from the right (e.g., 1234567 -> 1, 234, 567)
1077
        // TODO: Revisit this regex, in case there are any subtle tokenization differences with the original regex.
1078
0
        bpe_offsets = unicode_regex_split_custom_afmoe(text, offsets);
1079
0
    }
1080
1081
0
    return bpe_offsets;
1082
0
}
1083
1084
//
1085
// interface
1086
//
1087
1088
0
std::string unicode_cpt_to_utf8(uint32_t cpt) {
1089
0
    std::string result;
1090
1091
0
    if (/* 0x00 <= cpt && */ cpt <= 0x7f) {
1092
0
        result.push_back(cpt);
1093
0
        return result;
1094
0
    }
1095
0
    if (0x80 <= cpt && cpt <= 0x7ff) {
1096
0
        result.push_back(0xc0 | ((cpt >> 6) & 0x1f));
1097
0
        result.push_back(0x80 | (cpt & 0x3f));
1098
0
        return result;
1099
0
    }
1100
0
    if (0x800 <= cpt && cpt <= 0xffff) {
1101
0
        result.push_back(0xe0 | ((cpt >> 12) & 0x0f));
1102
0
        result.push_back(0x80 | ((cpt >> 6) & 0x3f));
1103
0
        result.push_back(0x80 | (cpt & 0x3f));
1104
0
        return result;
1105
0
    }
1106
0
    if (0x10000 <= cpt && cpt <= 0x10ffff) {
1107
0
        result.push_back(0xf0 | ((cpt >> 18) & 0x07));
1108
0
        result.push_back(0x80 | ((cpt >> 12) & 0x3f));
1109
0
        result.push_back(0x80 | ((cpt >> 6) & 0x3f));
1110
0
        result.push_back(0x80 | (cpt & 0x3f));
1111
0
        return result;
1112
0
    }
1113
1114
0
    throw std::invalid_argument("invalid codepoint");
1115
0
}
1116
1117
0
std::vector<uint32_t> unicode_cpts_normalize_nfd(const std::vector<uint32_t> & cpts) {
1118
0
    auto comp = [] (const uint32_t cpt, const range_nfd & range) {
1119
0
        return cpt < range.first;
1120
0
    };
1121
0
    std::vector<uint32_t> result(cpts.size());
1122
0
    for (size_t i = 0; i < cpts.size(); ++i) {
1123
0
        const uint32_t cpt = cpts[i];
1124
0
        auto it = std::upper_bound(unicode_ranges_nfd.begin(), unicode_ranges_nfd.end(), cpt, comp) - 1;
1125
0
        result[i] = (it->first <= cpt && cpt <= it->last) ? it->nfd : cpt;
1126
0
    }
1127
0
    return result;
1128
0
}
1129
1130
0
std::vector<uint32_t> unicode_cpts_from_utf8(const std::string & utf8) {
1131
0
    std::vector<uint32_t> result;
1132
0
    result.reserve(utf8.size());
1133
0
    size_t offset = 0;
1134
0
    while (offset < utf8.size()) {
1135
0
        try {
1136
0
            result.push_back(unicode_cpt_from_utf8(utf8, offset));
1137
0
        }
1138
0
        catch (const std::invalid_argument & /*ex*/) {
1139
            // Silently ignore invalid UTF-8 input to avoid leaking the exception beyond llama_tokenize
1140
0
            ++offset;
1141
0
            result.emplace_back(0xFFFD); // replacement character
1142
0
        }
1143
0
    }
1144
0
    return result;
1145
0
}
1146
1147
0
unicode_cpt_flags unicode_cpt_flags_from_cpt(const uint32_t cpt) {
1148
0
    static const unicode_cpt_flags undef(unicode_cpt_flags::UNDEFINED);
1149
0
    static const auto cpt_flags = unicode_cpt_flags_array();
1150
0
    return cpt < cpt_flags.size() ? cpt_flags[cpt] : undef;
1151
0
}
1152
1153
0
unicode_cpt_flags unicode_cpt_flags_from_utf8(const std::string & utf8) {
1154
0
    static const unicode_cpt_flags undef(unicode_cpt_flags::UNDEFINED);
1155
0
    if (utf8.empty()) {
1156
0
        return undef;  // undefined
1157
0
    }
1158
0
    size_t offset = 0;
1159
0
    return unicode_cpt_flags_from_cpt(unicode_cpt_from_utf8(utf8, offset));
1160
0
}
1161
1162
0
std::string unicode_byte_to_utf8(uint8_t byte) {
1163
0
    static std::unordered_map<uint8_t, std::string> map = unicode_byte_to_utf8_map();
1164
0
    return map.at(byte);
1165
0
}
1166
1167
0
uint8_t unicode_utf8_to_byte(const std::string & utf8) {
1168
0
    static std::unordered_map<std::string, uint8_t> map = unicode_utf8_to_byte_map();
1169
0
    return map.at(utf8);
1170
0
}
1171
1172
0
uint32_t unicode_tolower(uint32_t cpt) {
1173
    // binary search
1174
0
    auto it = std::lower_bound(unicode_map_lowercase.begin(), unicode_map_lowercase.end(), cpt,
1175
0
        [](const std::pair<uint32_t, uint32_t> & pair, uint32_t value) {
1176
0
            return pair.first < value;
1177
0
        });
1178
0
    if (it != unicode_map_lowercase.end() && it->first == cpt) {
1179
0
        return it->second;
1180
0
    }
1181
0
    return cpt;  // Return the original code point if no lowercase mapping is found
1182
0
}
1183
1184
0
bool unicode_cpt_is_han(uint32_t cpt) {
1185
    // Han character ranges (Chinese/CJK characters)
1186
    // CJK Unified Ideographs (most common)
1187
0
    if (cpt >= 0x4E00 && cpt <= 0x9FFF) return true;
1188
1189
    // CJK Extension A
1190
0
    if (cpt >= 0x3400 && cpt <= 0x4DBF) return true;
1191
1192
    // CJK Extension B
1193
0
    if (cpt >= 0x20000 && cpt <= 0x2A6DF) return true;
1194
1195
    // CJK Extension C
1196
0
    if (cpt >= 0x2A700 && cpt <= 0x2B73F) return true;
1197
1198
    // CJK Extension D
1199
0
    if (cpt >= 0x2B740 && cpt <= 0x2B81F) return true;
1200
1201
    // CJK Extension E
1202
0
    if (cpt >= 0x2B820 && cpt <= 0x2CEAF) return true;
1203
1204
    // CJK Extension F
1205
0
    if (cpt >= 0x2CEB0 && cpt <= 0x2EBEF) return true;
1206
1207
    // CJK Compatibility Ideographs
1208
0
    if (cpt >= 0xF900 && cpt <= 0xFAFF) return true;
1209
1210
    // CJK Compatibility Ideographs Supplement
1211
0
    if (cpt >= 0x2F800 && cpt <= 0x2FA1F) return true;
1212
1213
0
    return false;
1214
0
}
1215
1216
0
std::vector<std::string> unicode_regex_split(const std::string & text, const std::vector<std::string> & regex_exprs, bool byte_encode) {
1217
    // unicode categories
1218
0
    static const std::map<std::string, int> k_ucat_enum = {
1219
0
        { "\\p{N}", unicode_cpt_flags::NUMBER },
1220
0
        { "\\p{L}", unicode_cpt_flags::LETTER },
1221
0
        { "\\p{P}", unicode_cpt_flags::PUNCTUATION },
1222
0
        { "\\p{M}", unicode_cpt_flags::ACCENT_MARK },
1223
0
        { "\\p{S}", unicode_cpt_flags::SYMBOL },
1224
0
        { "\\p{Lu}", unicode_cpt_flags::LETTER }, // Uppercase letter
1225
0
        { "\\p{Ll}", unicode_cpt_flags::LETTER }, // Lowercase letter
1226
0
        { "\\p{Lt}", unicode_cpt_flags::LETTER }, // Titlecase letter
1227
0
        { "\\p{Lm}", unicode_cpt_flags::LETTER }, // Modifier letter
1228
0
        { "\\p{Lo}", unicode_cpt_flags::LETTER }, // Other letter
1229
0
    };
1230
1231
0
    static const std::map<int, int> k_ucat_cpt = {
1232
0
        { unicode_cpt_flags::NUMBER,      0xD1 },
1233
0
        { unicode_cpt_flags::LETTER,      0xD2 },
1234
0
        { unicode_cpt_flags::PUNCTUATION, 0xD3 },
1235
0
        { unicode_cpt_flags::ACCENT_MARK, 0xD4 },
1236
0
        { unicode_cpt_flags::SYMBOL,      0xD5 },
1237
0
    };
1238
1239
0
    static const std::map<int, std::string> k_ucat_map = {
1240
0
        { unicode_cpt_flags::NUMBER,      "\x30-\x39" }, // 0-9
1241
0
        { unicode_cpt_flags::LETTER,      "\x41-\x5A\x61-\x7A" }, // A-Za-z
1242
0
        { unicode_cpt_flags::PUNCTUATION, "\x21-\x23\x25-\x2A\x2C-\x2F\x3A-\x3B\x3F-\x40\\\x5B-\\\x5D\x5F\\\x7B\\\x7D" }, // !-#%-*,-/:-;?-@\[-\]_\{\}
1243
0
        { unicode_cpt_flags::ACCENT_MARK, "" }, // no sub-128 codepoints
1244
0
        { unicode_cpt_flags::SYMBOL,      "\\\x24\\\x2B\x3C-\x3E\x5E\x60\\\x7C" }, // $+<=>^`|
1245
0
    };
1246
1247
    // compute collapsed codepoints only if needed by at least one regex
1248
0
    bool need_collapse = false;
1249
0
    for (const auto & regex_expr : regex_exprs) {
1250
        // search for unicode categories
1251
0
        for (const auto & ucat : k_ucat_enum) {
1252
0
            if (std::string::npos != regex_expr.find(ucat.first)) {
1253
0
                need_collapse = true;
1254
0
                break;
1255
0
            }
1256
0
        }
1257
0
    }
1258
1259
0
    const auto cpts = unicode_cpts_from_utf8(text);
1260
1261
    // generate a "collapsed" representation of the text, where all codepoints are replaced by a single byte
1262
    // ref: https://github.com/ggml-org/llama.cpp/pull/6920#issuecomment-2081479935
1263
0
    std::string text_collapsed;
1264
0
    if (need_collapse) {
1265
        // collapse all unicode categories
1266
0
        text_collapsed.resize(cpts.size());
1267
1268
0
        for (size_t i = 0; i < cpts.size(); ++i) {
1269
            // keep single-byte codepoints as is
1270
0
            if (cpts[i] < 128) {
1271
0
                text_collapsed[i] = cpts[i];
1272
0
                continue;
1273
0
            }
1274
1275
0
            const auto flags = unicode_cpt_flags_from_cpt(cpts[i]);
1276
1277
0
            if (flags.is_whitespace) {
1278
                //NOTE: C++ std::regex \s does not mach 0x85, Rust and Python regex does.
1279
                //text_collapsed[i] = (char) 0x85;  // <Next Line> as whitespace fallback
1280
0
                text_collapsed[i] = (char) 0x0B;    // <vertical tab> as whitespace fallback
1281
0
            } else if (k_ucat_cpt.find(flags.category_flag()) != k_ucat_cpt.end()) {
1282
0
                text_collapsed[i] = k_ucat_cpt.at(flags.category_flag());
1283
0
            } else {
1284
0
                text_collapsed[i] = (char) 0xD0; // fallback
1285
0
            }
1286
0
        }
1287
0
    }
1288
1289
0
    std::vector<size_t> bpe_offsets = { cpts.size() };
1290
1291
0
    for (const auto & regex_expr : regex_exprs) {
1292
        // first, see if we have an efficient custom regex implementation
1293
0
        auto tmp = unicode_regex_split_custom(text, regex_expr, bpe_offsets);
1294
1295
0
        if (!tmp.empty()) {
1296
0
            bpe_offsets = std::move(tmp);
1297
0
            continue;
1298
0
        }
1299
1300
        // fallback to general-purpose std::regex / std::wregex
1301
0
        try {
1302
            // if a unicode category is used in the regex, we use the collapsed text and replace the unicode category
1303
            // with the corresponding collapsed representation
1304
0
            bool use_collapsed = false;
1305
0
            for (const auto & ucat : k_ucat_enum) {
1306
0
                if (std::string::npos != regex_expr.find(ucat.first)) {
1307
0
                    use_collapsed = true;
1308
0
                    break;
1309
0
                }
1310
0
            }
1311
0
            const auto cpts_regex = unicode_cpts_from_utf8(regex_expr);
1312
1313
0
            if (use_collapsed) {
1314
                // sanity-check that the original regex does not contain any non-ASCII characters
1315
0
                for (size_t i = 0; i < cpts_regex.size(); ++i) {
1316
0
                    if (cpts_regex[i] >= 128) {
1317
0
                        throw std::runtime_error("Regex includes both unicode categories and non-ASCII characters - not supported");
1318
0
                    }
1319
0
                }
1320
1321
                // generate a collapsed representation of the regex
1322
0
                std::string regex_expr_collapsed;
1323
1324
                // track if we are inside [], because nested [] are not allowed
1325
0
                bool inside = false;
1326
0
                for (size_t i = 0; i < regex_expr.size(); ++i) {
1327
0
                    if (regex_expr[i] == '[' && (i == 0 || regex_expr[i - 1] != '\\')) {
1328
0
                        regex_expr_collapsed += '[';
1329
0
                        inside = true;
1330
0
                        continue;
1331
0
                    }
1332
1333
0
                    if (inside && regex_expr[i] == ']' && regex_expr[i - 1] != '\\') {
1334
0
                        regex_expr_collapsed += ']';
1335
0
                        inside = false;
1336
0
                        continue;
1337
0
                    }
1338
1339
                    // Match \p{...} Unicode properties of varying lengths
1340
0
                    if (regex_expr[i + 0] == '\\' && i + 3 < regex_expr.size() &&
1341
0
                        regex_expr[i + 1] == 'p' &&
1342
0
                        regex_expr[i + 2] == '{') {
1343
                        // Find the closing brace
1344
0
                        size_t closing_brace = regex_expr.find('}', i + 3);
1345
0
                        if (closing_brace != std::string::npos && closing_brace <= i + 10) { // reasonable limit
1346
0
                            const std::string pat = regex_expr.substr(i, closing_brace - i + 1);
1347
0
                            if (k_ucat_enum.find(pat) != k_ucat_enum.end()) {
1348
0
                                if (!inside) {
1349
0
                                    regex_expr_collapsed += '[';
1350
0
                                }
1351
0
                                regex_expr_collapsed += k_ucat_cpt.at(k_ucat_enum.at(pat));
1352
0
                                regex_expr_collapsed += k_ucat_map.at(k_ucat_enum.at(pat));
1353
0
                                if (!inside) {
1354
0
                                    regex_expr_collapsed += ']';
1355
0
                                }
1356
0
                                i = closing_brace;
1357
0
                                continue;
1358
0
                            }
1359
0
                        }
1360
0
                    }
1361
1362
0
                    regex_expr_collapsed += regex_expr[i];
1363
0
                }
1364
1365
                //printf("text_collapsed: %s\n", text_collapsed.c_str());
1366
                //printf("regex_expr_collapsed: %s\n", regex_expr_collapsed.c_str());
1367
0
                bpe_offsets = unicode_regex_split_stl(text_collapsed, regex_expr_collapsed, bpe_offsets);
1368
0
            } else {
1369
                // no unicode category used, we can use std::wregex directly
1370
0
                std::wstring wregex_expr(cpts_regex.begin(), cpts_regex.end());
1371
1372
                // std::wregex \s does not mach non-ASCII whitespaces, using 0x0B as fallback
1373
0
                std::wstring wtext(cpts.begin(), cpts.end());
1374
0
                for (size_t i = 0; i < wtext.size(); ++i) {
1375
0
                    if (wtext[i] > 0x7F && unicode_cpt_flags_from_cpt(wtext[i]).is_whitespace) {
1376
0
                        wtext[i] = 0x0B;
1377
0
                    }
1378
0
                }
1379
1380
                //printf("text: %s\n", text.c_str());
1381
                //printf("regex_expr: %s\n", regex_expr.c_str());
1382
0
                bpe_offsets = unicode_regex_split_stl(wtext, wregex_expr, bpe_offsets);
1383
0
            }
1384
0
        } catch (std::regex_error & e) {
1385
0
            fprintf(stderr, "Failed to process regex: '%s'\n", regex_expr.c_str());
1386
0
            fprintf(stderr, "Regex error: %s\n", e.what());
1387
0
            throw std::runtime_error("Failed to process regex");
1388
0
        }
1389
0
    }
1390
1391
0
    std::vector<std::string> bpe_words;
1392
0
    bpe_words.reserve(bpe_offsets.size()); // reserve memory for the approximate size
1393
1394
0
    size_t start = 0;
1395
0
    for (size_t & offset : bpe_offsets) {
1396
0
        bpe_words.emplace_back();
1397
0
        for (size_t i = start; i < start + offset; ++i) {
1398
0
            bpe_words.back() += unicode_cpt_to_utf8(cpts[i]);
1399
0
        }
1400
0
        start += offset;
1401
0
    }
1402
1403
0
    if (byte_encode) {
1404
0
        return unicode_byte_encoding_process(bpe_words);
1405
0
    }
1406
1407
0
    return bpe_words;
1408
0
}