unicode.cpp 30 KB

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