unicode.cpp 40 KB

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