unicode.cpp 30 KB

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