unicode.cpp 32 KB

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