unicode.cpp 31 KB

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