unicode.cpp 31 KB

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