unicode.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809
  1. #include "unicode.h"
  2. #include "unicode-data.h"
  3. #include <cassert>
  4. #include <cstddef>
  5. #include <cstdint>
  6. #include <map>
  7. #include <regex>
  8. #include <stdexcept>
  9. #include <string>
  10. #include <unordered_map>
  11. #include <unordered_set>
  12. #include <utility>
  13. #include <vector>
  14. #include <locale>
  15. #include <codecvt>
  16. static std::string unicode_cpts_to_utf8(const std::vector<uint32_t> & cps) {
  17. std::string result;
  18. for (size_t i = 0; i < cps.size(); ++i) {
  19. result.append(unicode_cpt_to_utf8(cps[i]));
  20. }
  21. return result;
  22. }
  23. static uint32_t unicode_cpt_from_utf8(const std::string & utf8, size_t & offset) {
  24. assert(offset < utf8.size());
  25. if (!(utf8[offset + 0] & 0x80)) {
  26. auto result = utf8[offset + 0];
  27. offset += 1;
  28. return result;
  29. }
  30. if (!(utf8[offset + 0] & 0x40)) {
  31. throw std::invalid_argument("invalid character");
  32. }
  33. if (!(utf8[offset + 0] & 0x20)) {
  34. if (offset + 1 >= utf8.size() || ! ((utf8[offset + 1] & 0xc0) == 0x80)) {
  35. throw std::invalid_argument("invalid character");
  36. }
  37. auto result = ((utf8[offset + 0] & 0x1f) << 6) | (utf8[offset + 1] & 0x3f);
  38. offset += 2;
  39. return result;
  40. }
  41. if (!(utf8[offset + 0] & 0x10)) {
  42. if (offset + 2 >= utf8.size() || ! ((utf8[offset + 1] & 0xc0) == 0x80) || ! ((utf8[offset + 2] & 0xc0) == 0x80)) {
  43. throw std::invalid_argument("invalid character");
  44. }
  45. auto result = ((utf8[offset + 0] & 0x0f) << 12) | ((utf8[offset + 1] & 0x3f) << 6) | (utf8[offset + 2] & 0x3f);
  46. offset += 3;
  47. return result;
  48. }
  49. if (!(utf8[offset + 0] & 0x08)) {
  50. if (offset + 3 >= utf8.size() || ! ((utf8[offset + 1] & 0xc0) == 0x80) || ! ((utf8[offset + 2] & 0xc0) == 0x80) || !((utf8[offset + 3] & 0xc0) == 0x80)) {
  51. throw std::invalid_argument("invalid character");
  52. }
  53. auto result = ((utf8[offset + 0] & 0x07) << 18) | ((utf8[offset + 1] & 0x3f) << 12) | ((utf8[offset + 2] & 0x3f) << 6) | (utf8[offset + 3] & 0x3f);
  54. offset += 4;
  55. return result;
  56. }
  57. throw std::invalid_argument("failed to convert utf8 to codepoint");
  58. }
  59. //static std::vector<uint16_t> unicode_cpt_to_utf16(uint32_t cp) {
  60. // std::vector<uint16_t> result;
  61. // if (/* 0x0000 <= cp && */ cp <= 0xffff) {
  62. // result.emplace_back(cp);
  63. // return result;
  64. // }
  65. // if (0x10000 <= cp && cp <= 0x10ffff) {
  66. // result.emplace_back(0xd800 | ((cp - 0x10000) >> 10));
  67. // result.emplace_back(0xdc00 | ((cp - 0x10000) & 0x03ff));
  68. // return result;
  69. // }
  70. // throw std::invalid_argument("failed to convert codepoint to utf16");
  71. //}
  72. //static std::vector<uint16_t> unicode_cpts_to_utf16(const std::vector<uint32_t> & cps) {
  73. // std::vector<uint16_t> result;
  74. // for (size_t i = 0; i < cps.size(); ++i) {
  75. // auto temp = unicode_cpt_to_utf16(cps[i]);
  76. // result.insert(result.end(), temp.begin(), temp.end());
  77. // }
  78. // return result;
  79. //}
  80. //static uint32_t unicode_cpt_from_utf16(const std::vector<uint16_t> & utf16, size_t & offset) {
  81. // assert(offset < utf16.size());
  82. // if (((utf16[0] >> 10) << 10) != 0xd800) {
  83. // auto result = utf16[offset + 0];
  84. // offset += 1;
  85. // return result;
  86. // }
  87. //
  88. // if (offset + 1 >= utf16.size() || !((utf16[1] & 0xdc00) == 0xdc00)) {
  89. // throw std::invalid_argument("invalid character");
  90. // }
  91. //
  92. // auto result = 0x10000 + (((utf16[0] & 0x03ff) << 10) | (utf16[1] & 0x03ff));
  93. // offset += 2;
  94. // return result;
  95. //}
  96. //static std::vector<uint32_t> unicode_cpts_from_utf16(const std::vector<uint16_t> & utf16) {
  97. // std::vector<uint32_t> result;
  98. // size_t offset = 0;
  99. // while (offset < utf16.size()) {
  100. // result.push_back(unicode_cpt_from_utf16(utf16, offset));
  101. // }
  102. // return result;
  103. //}
  104. static std::vector<codepoint_flags> unicode_cpt_flags_array() {
  105. std::vector<codepoint_flags> cpt_flags(MAX_CODEPOINTS, codepoint_flags::UNDEFINED);
  106. assert (unicode_ranges_flags.front().first == 0);
  107. assert (unicode_ranges_flags.back().first == MAX_CODEPOINTS);
  108. for (size_t i = 1; i < unicode_ranges_flags.size(); ++i) {
  109. const auto range_ini = unicode_ranges_flags[i-1]; // codepoint_ini, flags
  110. const auto range_end = unicode_ranges_flags[i]; // codepoint_end, flags
  111. for (uint32_t cpt = range_ini.first; cpt < range_end.first; ++cpt) {
  112. cpt_flags[cpt] = range_ini.second;
  113. }
  114. }
  115. for (auto cpt : unicode_set_whitespace) {
  116. cpt_flags[cpt].is_whitespace = true;
  117. }
  118. for (auto p : unicode_map_lowercase) {
  119. cpt_flags[p.second].is_lowercase = true;
  120. }
  121. for (auto p : unicode_map_uppercase) {
  122. cpt_flags[p.second].is_uppercase = true;
  123. }
  124. for (auto &range : unicode_ranges_nfd) { // start, last, nfd
  125. cpt_flags[range.nfd].is_nfd = true;
  126. }
  127. return cpt_flags;
  128. }
  129. static std::unordered_map<uint8_t, std::string> unicode_byte_to_utf8_map() {
  130. std::unordered_map<uint8_t, std::string> map;
  131. for (int ch = 0x21; ch <= 0x7E; ++ch) { // u'!' to u'~'
  132. assert(0 <= ch && ch < 256);
  133. map[ch] = unicode_cpt_to_utf8(ch);
  134. }
  135. for (int ch = 0xA1; ch <= 0xAC; ++ch) { // u'¡' to u'¬'
  136. assert(0 <= ch && ch < 256);
  137. map[ch] = unicode_cpt_to_utf8(ch);
  138. }
  139. for (int ch = 0xAE; ch <= 0xFF; ++ch) { // u'®' to u'ÿ'
  140. assert(0 <= ch && ch < 256);
  141. map[ch] = unicode_cpt_to_utf8(ch);
  142. }
  143. auto n = 0;
  144. for (int ch = 0; ch < 256; ++ch) {
  145. if (map.find(ch) == map.end()) {
  146. map[ch] = unicode_cpt_to_utf8(256 + n);
  147. ++n;
  148. }
  149. }
  150. return map;
  151. }
  152. static std::unordered_map<std::string, uint8_t> unicode_utf8_to_byte_map() {
  153. std::unordered_map<std::string, uint8_t> map;
  154. for (int ch = 0x21; ch <= 0x7E; ++ch) { // u'!' to u'~'
  155. assert(0 <= ch && ch < 256);
  156. map[unicode_cpt_to_utf8(ch)] = ch;
  157. }
  158. for (int ch = 0xA1; ch <= 0xAC; ++ch) { // u'¡' to u'¬'
  159. assert(0 <= ch && ch < 256);
  160. map[unicode_cpt_to_utf8(ch)] = ch;
  161. }
  162. for (int ch = 0xAE; ch <= 0xFF; ++ch) { // u'®' to u'ÿ'
  163. assert(0 <= ch && ch < 256);
  164. map[unicode_cpt_to_utf8(ch)] = ch;
  165. }
  166. auto n = 0;
  167. for (int ch = 0; ch < 256; ++ch) {
  168. if (map.find(unicode_cpt_to_utf8(ch)) == map.end()) {
  169. map[unicode_cpt_to_utf8(256 + n)] = ch;
  170. ++n;
  171. }
  172. }
  173. return map;
  174. }
  175. static inline std::wstring unicode_wstring_from_utf8(const std::string & s) {
  176. std::wstring_convert<std::codecvt_utf8<wchar_t>> conv;
  177. return conv.from_bytes(s);
  178. }
  179. static std::vector<std::string> unicode_byte_encoding_process(const std::vector<std::string> & bpe_words) {
  180. std::vector<std::string> bpe_encoded_words;
  181. for (const auto & word : bpe_words) {
  182. std::string text_utf;
  183. auto utf_word = unicode_cpts_from_utf8(word);
  184. for (size_t i = 0; i < utf_word.size(); ++i) {
  185. text_utf += unicode_cpt_to_utf8(utf_word[i]);
  186. }
  187. std::string encoded_token;
  188. for (char & c : text_utf) {
  189. encoded_token += unicode_byte_to_utf8(c);
  190. }
  191. bpe_encoded_words.emplace_back(encoded_token);
  192. }
  193. return bpe_encoded_words;
  194. }
  195. // GPT2 system regex: 's|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+
  196. static std::vector<size_t> unicode_regex_split_custom_gpt2(const std::string & text, const std::vector<size_t> & offsets) {
  197. std::vector<size_t> bpe_offsets; // store the offset of each word
  198. bpe_offsets.reserve(offsets.size()); // Reserve memory for the approximate size
  199. const auto cpts = unicode_cpts_from_utf8(text);
  200. size_t start = 0;
  201. for (auto offset : offsets) {
  202. const size_t offset_ini = start;
  203. const size_t offset_end = start + offset;
  204. assert(offset_end <= cpts.size());
  205. start = offset_end;
  206. static const uint32_t OUT_OF_RANGE = 0xFFFFFFFF;
  207. auto _get_cpt = [&] (const size_t pos) -> uint32_t {
  208. return (offset_ini <= pos && pos < offset_end) ? cpts[pos] : OUT_OF_RANGE;
  209. };
  210. auto _get_flags = [&] (const size_t pos) -> codepoint_flags {
  211. static const codepoint_flags undef(codepoint_flags::UNDEFINED);
  212. return (offset_ini <= pos && pos < offset_end) ? unicode_cpt_flags(cpts[pos]) : undef;
  213. };
  214. size_t _prev_end = offset_ini;
  215. auto _add_token = [&] (const size_t end) -> size_t {
  216. assert(_prev_end <= end && end <= offset_end);
  217. size_t len = end - _prev_end;
  218. if (len > 0) {
  219. bpe_offsets.push_back(len);
  220. }
  221. _prev_end = end;
  222. //if (len > 0) {
  223. // std::string s = "";
  224. // for(size_t p = end-len; p < end; p++)
  225. // s += unicode_cpt_to_utf8(cpts[p]);
  226. // printf(">>> '%s'\n", s.c_str());
  227. //}
  228. return len;
  229. };
  230. for (size_t pos = offset_ini; pos < offset_end; /*pos++*/ ) {
  231. const uint32_t cpt = _get_cpt(pos);
  232. const auto flags = _get_flags(pos);
  233. // regex: 's|'t|'re|'ve|'m|'ll|'d
  234. if (cpt == '\'' && pos+1 < offset_end) {
  235. uint32_t cpt_next = _get_cpt(pos+1);
  236. if (cpt_next == 's' || cpt_next == 't' || cpt_next == 'm' || cpt_next == 'd') {
  237. pos += _add_token(pos+2);
  238. continue;
  239. }
  240. if (pos+2 < offset_end) {
  241. uint32_t cpt_next_next = _get_cpt(pos+2);
  242. if ((cpt_next == 'r' && cpt_next_next == 'e') ||
  243. (cpt_next == 'v' && cpt_next_next == 'e') ||
  244. (cpt_next == 'l' && cpt_next_next == 'l')) {
  245. pos += _add_token(pos+3);
  246. continue;
  247. }
  248. }
  249. }
  250. auto flags2 = (cpt == ' ' ? _get_flags(pos+1) : flags);
  251. // regex: <space>?\p{L}+
  252. if (flags2.is_letter) {
  253. pos += (cpt == ' ');
  254. while (flags2.is_letter) {
  255. flags2 = _get_flags(++pos);
  256. }
  257. _add_token(pos);
  258. continue;
  259. }
  260. // regex: <space>?\p{N}+
  261. if (flags2.is_number) {
  262. pos += (cpt == ' ');
  263. while (flags2.is_number) {
  264. flags2 = _get_flags(++pos);
  265. }
  266. _add_token(pos);
  267. continue;
  268. }
  269. // regex: <space>?[^\s\p{L}\p{N}]+
  270. if (!(flags2.is_whitespace || flags2.is_letter || flags2.is_number || flags2.is_undefined)) {
  271. pos += (cpt == ' ');
  272. while (!(flags2.is_whitespace || flags2.is_letter || flags2.is_number || flags2.is_undefined)) {
  273. flags2 = _get_flags(++pos);
  274. }
  275. _add_token(pos);
  276. continue;
  277. }
  278. size_t num_whitespaces = 0;
  279. while (_get_flags(pos+num_whitespaces).is_whitespace) {
  280. num_whitespaces++;
  281. }
  282. // regex: \s+(?!\S)
  283. if (num_whitespaces > 1 && _get_cpt(pos+num_whitespaces) != OUT_OF_RANGE) {
  284. pos += num_whitespaces - 1;
  285. _add_token(pos);
  286. continue;
  287. }
  288. // regex: \s+
  289. if (num_whitespaces > 0) {
  290. pos += num_whitespaces;
  291. _add_token(pos);
  292. continue;
  293. }
  294. // no matches
  295. _add_token(++pos);
  296. }
  297. }
  298. return bpe_offsets;
  299. }
  300. // 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+"
  301. static std::vector<size_t> unicode_regex_split_custom_llama3(const std::string & text, const std::vector<size_t> & offsets) {
  302. std::vector<size_t> bpe_offsets; // store the offset of each word
  303. bpe_offsets.reserve(offsets.size()); // Reserve memory for the approximate size
  304. const auto cpts = unicode_cpts_from_utf8(text);
  305. size_t start = 0;
  306. for (auto offset : offsets) {
  307. const size_t offset_ini = start;
  308. const size_t offset_end = start + offset;
  309. assert(offset_end <= cpts.size());
  310. start = offset_end;
  311. static const uint32_t OUT_OF_RANGE = 0xFFFFFFFF;
  312. auto _get_cpt = [&] (const size_t pos) -> uint32_t {
  313. return (offset_ini <= pos && pos < offset_end) ? cpts[pos] : OUT_OF_RANGE;
  314. };
  315. auto _get_flags = [&] (const size_t pos) -> codepoint_flags {
  316. static const codepoint_flags undef(codepoint_flags::UNDEFINED);
  317. return (offset_ini <= pos && pos < offset_end) ? unicode_cpt_flags(cpts[pos]) : undef;
  318. };
  319. size_t _prev_end = offset_ini;
  320. auto _add_token = [&] (const size_t end) -> size_t {
  321. assert(_prev_end <= end && end <= offset_end);
  322. size_t len = end - _prev_end;
  323. if (len > 0) {
  324. bpe_offsets.push_back(len);
  325. }
  326. _prev_end = end;
  327. //if (len > 0) {
  328. // std::string s = "";
  329. // for(size_t p = end-len; p < end; p++)
  330. // s += unicode_cpt_to_utf8(cpts[p]);
  331. // printf(">>> '%s'\n", s.c_str());
  332. //}
  333. return len;
  334. };
  335. for (size_t pos = offset_ini; pos < offset_end; /*pos++*/ ) {
  336. const uint32_t cpt = _get_cpt(pos);
  337. const auto flags = _get_flags(pos);
  338. // regex: (?i:'s|'t|'re|'ve|'m|'ll|'d) // case insensitive
  339. if (cpt == '\'' && pos+1 < offset_end) {
  340. uint32_t cpt_next = unicode_tolower(_get_cpt(pos+1));
  341. if (cpt_next == 's' || cpt_next == 't' || cpt_next == 'm' || cpt_next == 'd') {
  342. pos += _add_token(pos+2);
  343. continue;
  344. }
  345. if (pos+2 < offset_end) {
  346. uint32_t cpt_next_next = unicode_tolower(_get_cpt(pos+2));
  347. if ((cpt_next == 'r' && cpt_next_next == 'e') ||
  348. (cpt_next == 'v' && cpt_next_next == 'e') ||
  349. (cpt_next == 'l' && cpt_next_next == 'l')) {
  350. pos += _add_token(pos+3);
  351. continue;
  352. }
  353. }
  354. }
  355. // regex: [^\r\n\p{L}\p{N}]?\p{L}+ //####FIXME: the first \p{L} is correct?
  356. if (!(cpt == '\r' || cpt == '\n' || /*flags.is_letter |*/ flags.is_number)) {
  357. if (flags.is_letter || _get_flags(pos+1).is_letter) { // one or more letters
  358. pos++;
  359. while (_get_flags(pos).is_letter) {
  360. pos++;
  361. }
  362. _add_token(pos);
  363. continue;
  364. }
  365. }
  366. // regex: \p{N}{1,3}
  367. if (flags.is_number) {
  368. size_t ini = pos;
  369. while (_get_flags(pos).is_number) {
  370. if (++pos - ini >= 3 ) {
  371. _add_token(pos);
  372. ini = pos;
  373. }
  374. }
  375. _add_token(pos);
  376. continue;
  377. }
  378. // regex: <space>?[^\s\p{L}\p{N}]+[\r\n]*
  379. auto flags2 = (cpt == ' ' ? _get_flags(pos+1) : flags);
  380. if (!(flags2.is_whitespace || flags2.is_letter || flags2.is_number || flags2.is_undefined)) {
  381. pos += (cpt == ' ');
  382. while (!(flags2.is_whitespace || flags2.is_letter || flags2.is_number || flags2.is_undefined)) {
  383. flags2 = _get_flags(++pos);
  384. }
  385. uint32_t cpt2 = _get_cpt(pos);
  386. while (cpt2 == '\r' || cpt2 == '\n') {
  387. cpt2 = _get_cpt(++pos);
  388. }
  389. _add_token(pos);
  390. continue;
  391. }
  392. size_t num_whitespaces = 0;
  393. size_t last_end_r_or_n = 0;
  394. while (_get_flags(pos+num_whitespaces).is_whitespace) {
  395. uint32_t cpt2 = _get_cpt(pos+num_whitespaces);
  396. if (cpt2 == '\r' || cpt2 == '\n') {
  397. last_end_r_or_n = pos + num_whitespaces + 1;
  398. }
  399. num_whitespaces++;
  400. }
  401. // regex: \s*[\r\n]+
  402. if (last_end_r_or_n > 0) {
  403. pos = last_end_r_or_n;
  404. _add_token(pos);
  405. continue;
  406. }
  407. // regex: \s+(?!\S)
  408. if (num_whitespaces > 1 && _get_cpt(pos+num_whitespaces) != OUT_OF_RANGE) {
  409. pos += num_whitespaces - 1;
  410. _add_token(pos);
  411. continue;
  412. }
  413. // regex: \s+
  414. if (num_whitespaces > 0) {
  415. pos += num_whitespaces;
  416. _add_token(pos);
  417. continue;
  418. }
  419. // no matches
  420. _add_token(++pos);
  421. }
  422. }
  423. return bpe_offsets;
  424. }
  425. // use std::wregex to split the text
  426. static std::vector<size_t> unicode_regex_split_stl(const std::wstring & wtext, const std::wstring & regex_expr, const std::vector<size_t> & offsets) {
  427. std::wregex expr(regex_expr);
  428. std::vector<size_t> bpe_offsets; // store the offset of each word
  429. bpe_offsets.reserve(offsets.size()); // Reserve memory for the approximate size
  430. size_t start = 0;
  431. for (auto offset : offsets) {
  432. std::wcregex_iterator it(wtext.data() + start, wtext.data() + start + offset, expr);
  433. std::wcregex_iterator end;
  434. int64_t start_idx = 0;
  435. while (it != end) {
  436. std::wcmatch match = *it;
  437. if (match.position() > start_idx) {
  438. bpe_offsets.emplace_back(match.position() - start_idx);
  439. }
  440. bpe_offsets.emplace_back(match.length());
  441. start_idx = match.position() + match.length();
  442. ++it;
  443. }
  444. if (start_idx < (int64_t) offset) {
  445. bpe_offsets.emplace_back(offset - start_idx);
  446. }
  447. start += offset;
  448. }
  449. return bpe_offsets;
  450. }
  451. // use std::regex to split the text
  452. static std::vector<size_t> unicode_regex_split_stl(const std::string & text, const std::string & regex_expr, const std::vector<size_t> & offsets) {
  453. std::regex expr(regex_expr);
  454. std::vector<size_t> bpe_offsets; // store the offset of each word
  455. bpe_offsets.reserve(offsets.size()); // Reserve memory for the approximate size
  456. size_t start = 0;
  457. for (auto offset : offsets) {
  458. std::cregex_iterator it(text.data() + start, text.data() + start + offset, expr);
  459. std::cregex_iterator end;
  460. int64_t start_idx = 0;
  461. while (it != end) {
  462. std::cmatch match = *it;
  463. if (match.position() > start_idx) {
  464. bpe_offsets.emplace_back(match.position() - start_idx);
  465. }
  466. bpe_offsets.emplace_back(match.length());
  467. start_idx = match.position() + match.length();
  468. ++it;
  469. }
  470. if (start_idx < (int64_t) offset) {
  471. bpe_offsets.emplace_back(offset - start_idx);
  472. }
  473. start += offset;
  474. }
  475. return bpe_offsets;
  476. }
  477. static std::vector<size_t> unicode_regex_split_custom(const std::string & text, const std::string & regex_expr, const std::vector<size_t> & offsets) {
  478. std::vector<size_t> bpe_offsets;
  479. if (regex_expr == "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)") {
  480. bpe_offsets = unicode_regex_split_custom_gpt2(text, offsets);
  481. } else if (
  482. 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+" ||
  483. 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+") {
  484. bpe_offsets = unicode_regex_split_custom_llama3(text, offsets);
  485. }
  486. return bpe_offsets;
  487. }
  488. //
  489. // interface
  490. //
  491. std::string unicode_cpt_to_utf8(uint32_t cp) {
  492. std::string result;
  493. if (/* 0x00 <= cp && */ cp <= 0x7f) {
  494. result.push_back(cp);
  495. return result;
  496. }
  497. if (0x80 <= cp && cp <= 0x7ff) {
  498. result.push_back(0xc0 | ((cp >> 6) & 0x1f));
  499. result.push_back(0x80 | (cp & 0x3f));
  500. return result;
  501. }
  502. if (0x800 <= cp && cp <= 0xffff) {
  503. result.push_back(0xe0 | ((cp >> 12) & 0x0f));
  504. result.push_back(0x80 | ((cp >> 6) & 0x3f));
  505. result.push_back(0x80 | (cp & 0x3f));
  506. return result;
  507. }
  508. if (0x10000 <= cp && cp <= 0x10ffff) {
  509. result.push_back(0xf0 | ((cp >> 18) & 0x07));
  510. result.push_back(0x80 | ((cp >> 12) & 0x3f));
  511. result.push_back(0x80 | ((cp >> 6) & 0x3f));
  512. result.push_back(0x80 | (cp & 0x3f));
  513. return result;
  514. }
  515. throw std::invalid_argument("invalid codepoint");
  516. }
  517. std::vector<uint32_t> unicode_cpts_normalize_nfd(const std::vector<uint32_t> & cpts) {
  518. auto comp = [] (const uint32_t cpt, const range_nfd & range) {
  519. return cpt < range.first;
  520. };
  521. std::vector<uint32_t> result(cpts.size());
  522. for (size_t i = 0; i < cpts.size(); ++i) {
  523. const uint32_t cpt = cpts[i];
  524. auto it = std::upper_bound(unicode_ranges_nfd.cbegin(), unicode_ranges_nfd.cend(), cpt, comp) - 1;
  525. result[i] = (it->first <= cpt && cpt <= it->last) ? it->nfd : cpt;
  526. }
  527. return result;
  528. }
  529. std::vector<uint32_t> unicode_cpts_from_utf8(const std::string & utf8) {
  530. std::vector<uint32_t> result;
  531. size_t offset = 0;
  532. while (offset < utf8.size()) {
  533. result.push_back(unicode_cpt_from_utf8(utf8, offset));
  534. }
  535. return result;
  536. }
  537. codepoint_flags unicode_cpt_flags(const uint32_t cp) {
  538. static const codepoint_flags undef(codepoint_flags::UNDEFINED);
  539. static const auto cpt_flags = unicode_cpt_flags_array();
  540. return cp < cpt_flags.size() ? cpt_flags[cp] : undef;
  541. }
  542. codepoint_flags unicode_cpt_flags(const std::string & utf8) {
  543. static const codepoint_flags undef(codepoint_flags::UNDEFINED);
  544. if (utf8.empty()) {
  545. return undef; // undefined
  546. }
  547. size_t offset = 0;
  548. return unicode_cpt_flags(unicode_cpt_from_utf8(utf8, offset));
  549. }
  550. std::string unicode_byte_to_utf8(uint8_t byte) {
  551. static std::unordered_map<uint8_t, std::string> map = unicode_byte_to_utf8_map();
  552. return map.at(byte);
  553. }
  554. uint8_t unicode_utf8_to_byte(const std::string & utf8) {
  555. static std::unordered_map<std::string, uint8_t> map = unicode_utf8_to_byte_map();
  556. return map.at(utf8);
  557. }
  558. uint32_t unicode_tolower(uint32_t cp) {
  559. auto it = unicode_map_lowercase.find(cp);
  560. return it == unicode_map_lowercase.end() ? cp : it->second;
  561. }
  562. std::vector<std::string> unicode_regex_split(const std::string & text, const std::vector<std::string> & regex_exprs) {
  563. // unicode categories
  564. static const std::map<std::string, int> k_ucat_enum = {
  565. { "\\p{N}", codepoint_flags::NUMBER },
  566. { "\\p{L}", codepoint_flags::LETTER },
  567. { "\\p{P}", codepoint_flags::PUNCTUATION },
  568. };
  569. static const std::map<int, int> k_ucat_cpt = {
  570. { codepoint_flags::NUMBER, 0xD1 },
  571. { codepoint_flags::LETTER, 0xD2 },
  572. { codepoint_flags::PUNCTUATION, 0xD3 },
  573. };
  574. static const std::map<int, std::string> k_ucat_map = {
  575. { codepoint_flags::NUMBER, "\x30-\x39" }, // 0-9
  576. { codepoint_flags::LETTER, "\x41-\x5A\x61-\x7A" }, // A-Za-z
  577. { codepoint_flags::PUNCTUATION, "\x21-\x23\x25-\x2A\x2C-\x2F\x3A-\x3B\x3F-\x40\\\x5B-\\\x5D\x5F\\\x7B\\\x7D" }, // !-#%-*,-/:-;?-@\[-\]_\{\}
  578. };
  579. // compute collapsed codepoints only if needed by at least one regex
  580. bool need_collapse = false;
  581. for (auto & regex_expr : regex_exprs) {
  582. // search for unicode categories
  583. for (const auto & ucat : k_ucat_enum) {
  584. if (std::string::npos != regex_expr.find(ucat.first)) {
  585. need_collapse = true;
  586. break;
  587. }
  588. }
  589. }
  590. const auto cpts = unicode_cpts_from_utf8(text);
  591. // generate a "collapsed" representation of the text, where all codepoints are replaced by a single byte
  592. // ref: https://github.com/ggerganov/llama.cpp/pull/6920#issuecomment-2081479935
  593. std::string text_collapsed;
  594. if (need_collapse) {
  595. // collapse all unicode categories
  596. text_collapsed.resize(cpts.size());
  597. for (size_t i = 0; i < cpts.size(); ++i) {
  598. // keep single-byte codepoints as is
  599. if (cpts[i] < 128) {
  600. text_collapsed[i] = cpts[i];
  601. continue;
  602. }
  603. const auto flags = unicode_cpt_flags(cpts[i]);
  604. if (flags.is_whitespace) {
  605. //NOTE: C++ std::regex \s does not mach 0x85, Rust and Python regex does.
  606. //text_collapsed[i] = (char) 0x85; // <Next Line> as whitespace fallback
  607. text_collapsed[i] = (char) 0x0B; // <vertical tab> as whitespace fallback
  608. } else if (k_ucat_cpt.find(flags.category_flag()) != k_ucat_cpt.end()) {
  609. text_collapsed[i] = k_ucat_cpt.at(flags.category_flag());
  610. } else {
  611. text_collapsed[i] = (char) 0xD0; // fallback
  612. }
  613. }
  614. }
  615. std::vector<size_t> bpe_offsets = { cpts.size() };
  616. for (auto & regex_expr : regex_exprs) {
  617. // first, see if we have an efficient custom regex implementation
  618. auto tmp = unicode_regex_split_custom(text, regex_expr, bpe_offsets);
  619. if (!tmp.empty()) {
  620. bpe_offsets = std::move(tmp);
  621. continue;
  622. }
  623. // fallback to general-purpose std::regex / std::wregex
  624. try {
  625. // if a unicode category is used in the regex, we use the collapsed text and replace the unicode category
  626. // with the corresponding collapsed representation
  627. bool use_collapsed = false;
  628. for (auto & ucat : k_ucat_enum) {
  629. if (std::string::npos != regex_expr.find(ucat.first)) {
  630. use_collapsed = true;
  631. break;
  632. }
  633. }
  634. if (use_collapsed) {
  635. // sanity-check that the original regex does not contain any non-ASCII characters
  636. const auto cpts_regex = unicode_cpts_from_utf8(regex_expr);
  637. for (size_t i = 0; i < cpts_regex.size(); ++i) {
  638. if (cpts_regex[i] >= 128) {
  639. throw std::runtime_error("Regex includes both unicode categories and non-ASCII characters - not supported");
  640. }
  641. }
  642. // generate a collapsed representation of the regex
  643. std::string regex_expr_collapsed;
  644. // track if we are inside [], because nested [] are not allowed
  645. bool inside = false;
  646. for (size_t i = 0; i < regex_expr.size(); ++i) {
  647. if (regex_expr[i] == '[' && (i == 0 || regex_expr[i - 1] != '\\')) {
  648. regex_expr_collapsed += '[';
  649. inside = true;
  650. continue;
  651. }
  652. if (inside && regex_expr[i] == ']' && regex_expr[i - 1] != '\\') {
  653. regex_expr_collapsed += ']';
  654. inside = false;
  655. continue;
  656. }
  657. if (regex_expr[i + 0] == '\\' && i + 4 < regex_expr.size() &&
  658. regex_expr[i + 1] == 'p' &&
  659. regex_expr[i + 2] == '{' &&
  660. regex_expr[i + 4] == '}') {
  661. const std::string pat = regex_expr.substr(i, 5);
  662. if (k_ucat_enum.find(pat) != k_ucat_enum.end()) {
  663. if (!inside) {
  664. regex_expr_collapsed += '[';
  665. }
  666. regex_expr_collapsed += k_ucat_cpt.at(k_ucat_enum.at(pat));
  667. regex_expr_collapsed += k_ucat_map.at(k_ucat_enum.at(pat));
  668. if (!inside) {
  669. regex_expr_collapsed += ']';
  670. }
  671. i += 4;
  672. continue;
  673. }
  674. }
  675. regex_expr_collapsed += regex_expr[i];
  676. }
  677. //printf("text_collapsed: %s\n", text_collapsed.c_str());
  678. //printf("regex_expr_collapsed: %s\n", regex_expr_collapsed.c_str());
  679. bpe_offsets = unicode_regex_split_stl(text_collapsed, regex_expr_collapsed, bpe_offsets);
  680. } else {
  681. // no unicode category used, we can use std::wregex directly
  682. const std::wstring wregex_expr = unicode_wstring_from_utf8(regex_expr);
  683. // std::wregex \s does not mach non-ASCII whitespaces, using 0x0B as fallback
  684. std::wstring wtext(cpts.begin(), cpts.end());
  685. for (size_t i = 0; i < wtext.size(); ++i) {
  686. if (wtext[i] > 0x7F && unicode_cpt_flags(wtext[i]).is_whitespace) {
  687. wtext[i] = 0x0B;
  688. }
  689. }
  690. //printf("text: %s\n", text.c_str());
  691. //printf("regex_expr: %s\n", regex_expr.c_str());
  692. bpe_offsets = unicode_regex_split_stl(wtext, wregex_expr, bpe_offsets);
  693. }
  694. } catch (std::regex_error & e) {
  695. fprintf(stderr, "Failed to process regex: '%s'\n", regex_expr.c_str());
  696. fprintf(stderr, "Regex error: %s\n", e.what());
  697. throw std::runtime_error("Failed to process regex");
  698. }
  699. }
  700. std::vector<std::string> bpe_words;
  701. bpe_words.reserve(bpe_offsets.size()); // reserve memory for the approximate size
  702. size_t start = 0;
  703. for (size_t & offset : bpe_offsets) {
  704. bpe_words.emplace_back();
  705. for (size_t i = start; i < start + offset; ++i) {
  706. bpe_words.back() += unicode_cpt_to_utf8(cpts[i]);
  707. }
  708. start += offset;
  709. }
  710. return unicode_byte_encoding_process(bpe_words);
  711. }