unicode.cpp 31 KB

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