unicode.cpp 30 KB

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