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