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