unicode.cpp 31 KB

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