1
0

unicode.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686
  1. #include "unicode.h"
  2. #include "unicode-data.h"
  3. #include <cassert>
  4. #include <cstddef>
  5. #include <cstdint>
  6. #include <map>
  7. #include <regex>
  8. #include <stdexcept>
  9. #include <string>
  10. #include <unordered_map>
  11. #include <utility>
  12. #include <vector>
  13. #include <locale>
  14. #include <codecvt>
  15. static std::string unicode_cpts_to_utf8(const std::vector<uint32_t> & cps) {
  16. std::string result;
  17. for (size_t i = 0; i < cps.size(); ++i) {
  18. result.append(unicode_cpt_to_utf8(cps[i]));
  19. }
  20. return result;
  21. }
  22. static uint32_t unicode_cpt_from_utf8(const std::string & utf8, size_t & offset) {
  23. assert(offset < utf8.size());
  24. if (!(utf8[offset + 0] & 0x80)) {
  25. auto result = utf8[offset + 0];
  26. offset += 1;
  27. return result;
  28. }
  29. if (!(utf8[offset + 0] & 0x40)) {
  30. throw std::invalid_argument("invalid character");
  31. }
  32. if (!(utf8[offset + 0] & 0x20)) {
  33. if (offset + 1 >= utf8.size() || ! ((utf8[offset + 1] & 0xc0) == 0x80)) {
  34. throw std::invalid_argument("invalid character");
  35. }
  36. auto result = ((utf8[offset + 0] & 0x1f) << 6) | (utf8[offset + 1] & 0x3f);
  37. offset += 2;
  38. return result;
  39. }
  40. if (!(utf8[offset + 0] & 0x10)) {
  41. if (offset + 2 >= utf8.size() || ! ((utf8[offset + 1] & 0xc0) == 0x80) || ! ((utf8[offset + 2] & 0xc0) == 0x80)) {
  42. throw std::invalid_argument("invalid character");
  43. }
  44. auto result = ((utf8[offset + 0] & 0x0f) << 12) | ((utf8[offset + 1] & 0x3f) << 6) | (utf8[offset + 2] & 0x3f);
  45. offset += 3;
  46. return result;
  47. }
  48. if (!(utf8[offset + 0] & 0x08)) {
  49. if (offset + 3 >= utf8.size() || ! ((utf8[offset + 1] & 0xc0) == 0x80) || ! ((utf8[offset + 2] & 0xc0) == 0x80) || !((utf8[offset + 3] & 0xc0) == 0x80)) {
  50. throw std::invalid_argument("invalid character");
  51. }
  52. auto result = ((utf8[offset + 0] & 0x07) << 18) | ((utf8[offset + 1] & 0x3f) << 12) | ((utf8[offset + 2] & 0x3f) << 6) | (utf8[offset + 3] & 0x3f);
  53. offset += 4;
  54. return result;
  55. }
  56. throw std::invalid_argument("failed to convert utf8 to codepoint");
  57. }
  58. //static std::vector<uint16_t> unicode_cpt_to_utf16(uint32_t cp) {
  59. // std::vector<uint16_t> result;
  60. // if (/* 0x0000 <= cp && */ cp <= 0xffff) {
  61. // result.emplace_back(cp);
  62. // return result;
  63. // }
  64. // if (0x10000 <= cp && cp <= 0x10ffff) {
  65. // result.emplace_back(0xd800 | ((cp - 0x10000) >> 10));
  66. // result.emplace_back(0xdc00 | ((cp - 0x10000) & 0x03ff));
  67. // return result;
  68. // }
  69. // throw std::invalid_argument("failed to convert codepoint to utf16");
  70. //}
  71. //static std::vector<uint16_t> unicode_cpts_to_utf16(const std::vector<uint32_t> & cps) {
  72. // std::vector<uint16_t> result;
  73. // for (size_t i = 0; i < cps.size(); ++i) {
  74. // auto temp = unicode_cpt_to_utf16(cps[i]);
  75. // result.insert(result.end(), temp.begin(), temp.end());
  76. // }
  77. // return result;
  78. //}
  79. //static uint32_t unicode_cpt_from_utf16(const std::vector<uint16_t> & utf16, size_t & offset) {
  80. // assert(offset < utf16.size());
  81. // if (((utf16[0] >> 10) << 10) != 0xd800) {
  82. // auto result = utf16[offset + 0];
  83. // offset += 1;
  84. // return result;
  85. // }
  86. //
  87. // if (offset + 1 >= utf16.size() || !((utf16[1] & 0xdc00) == 0xdc00)) {
  88. // throw std::invalid_argument("invalid character");
  89. // }
  90. //
  91. // auto result = 0x10000 + (((utf16[0] & 0x03ff) << 10) | (utf16[1] & 0x03ff));
  92. // offset += 2;
  93. // return result;
  94. //}
  95. //static std::vector<uint32_t> unicode_cpts_from_utf16(const std::vector<uint16_t> & utf16) {
  96. // std::vector<uint32_t> result;
  97. // size_t offset = 0;
  98. // while (offset < utf16.size()) {
  99. // result.push_back(unicode_cpt_from_utf16(utf16, offset));
  100. // }
  101. // return result;
  102. //}
  103. static std::unordered_map<uint32_t, int> unicode_cpt_type_map() {
  104. std::unordered_map<uint32_t, int> cpt_types;
  105. for (auto p : unicode_ranges_digit) {
  106. for (auto i = p.first; i <= p.second; ++ i) {
  107. cpt_types[i] = CODEPOINT_TYPE_DIGIT;
  108. }
  109. }
  110. for (auto p : unicode_ranges_letter) {
  111. for (auto i = p.first; i <= p.second; ++ i) {
  112. cpt_types[i] = CODEPOINT_TYPE_LETTER;
  113. }
  114. }
  115. for (auto p : unicode_ranges_whitespace) {
  116. for (auto i = p.first; i <= p.second; ++ i) {
  117. cpt_types[i] = CODEPOINT_TYPE_WHITESPACE;
  118. }
  119. }
  120. for (auto p : unicode_ranges_accent_mark) {
  121. for (auto i = p.first; i <= p.second; ++ i) {
  122. cpt_types[i] = CODEPOINT_TYPE_ACCENT_MARK;
  123. }
  124. }
  125. for (auto p : unicode_ranges_punctuation) {
  126. for (auto i = p.first; i <= p.second; ++ i) {
  127. cpt_types[i] = CODEPOINT_TYPE_PUNCTUATION;
  128. }
  129. }
  130. for (auto p : unicode_ranges_symbol) {
  131. for (auto i = p.first; i <= p.second; ++i) {
  132. cpt_types[i] = CODEPOINT_TYPE_SYMBOL;
  133. }
  134. }
  135. for (auto p : unicode_ranges_control) {
  136. for (auto i = p.first; i <= p.second; ++ i) {
  137. cpt_types[i] = CODEPOINT_TYPE_CONTROL;
  138. }
  139. }
  140. return cpt_types;
  141. }
  142. static std::unordered_map<uint8_t, std::string> unicode_byte_to_utf8_map() {
  143. std::unordered_map<uint8_t, std::string> map;
  144. for (int ch = u'!'; ch <= u'~'; ++ch) {
  145. assert(0 <= ch && ch < 256);
  146. map[ch] = unicode_cpt_to_utf8(ch);
  147. }
  148. for (int ch = u'¡'; ch <= u'¬'; ++ch) {
  149. assert(0 <= ch && ch < 256);
  150. map[ch] = unicode_cpt_to_utf8(ch);
  151. }
  152. for (int ch = u'®'; ch <= u'ÿ'; ++ch) {
  153. assert(0 <= ch && ch < 256);
  154. map[ch] = unicode_cpt_to_utf8(ch);
  155. }
  156. auto n = 0;
  157. for (int ch = 0; ch < 256; ++ch) {
  158. if (map.find(ch) == map.end()) {
  159. map[ch] = unicode_cpt_to_utf8(256 + n);
  160. ++n;
  161. }
  162. }
  163. return map;
  164. }
  165. static std::unordered_map<std::string, uint8_t> unicode_utf8_to_byte_map() {
  166. std::unordered_map<std::string, uint8_t> map;
  167. for (int ch = u'!'; ch <= u'~'; ++ch) {
  168. assert(0 <= ch && ch < 256);
  169. map[unicode_cpt_to_utf8(ch)] = ch;
  170. }
  171. for (int ch = u'¡'; ch <= u'¬'; ++ch) {
  172. assert(0 <= ch && ch < 256);
  173. map[unicode_cpt_to_utf8(ch)] = ch;
  174. }
  175. for (int ch = u'®'; ch <= u'ÿ'; ++ch) {
  176. assert(0 <= ch && ch < 256);
  177. map[unicode_cpt_to_utf8(ch)] = ch;
  178. }
  179. auto n = 0;
  180. for (int ch = 0; ch < 256; ++ch) {
  181. if (map.find(unicode_cpt_to_utf8(ch)) == map.end()) {
  182. map[unicode_cpt_to_utf8(256 + n)] = ch;
  183. ++n;
  184. }
  185. }
  186. return map;
  187. }
  188. static inline std::wstring unicode_wstring_from_utf8(const std::string & s) {
  189. std::wstring_convert<std::codecvt_utf8<wchar_t>> conv;
  190. return conv.from_bytes(s);
  191. }
  192. static std::vector<std::string> unicode_byte_encoding_process(const std::vector<std::string> & bpe_words) {
  193. std::vector<std::string> bpe_encoded_words;
  194. for (const auto & word : bpe_words) {
  195. std::string text_utf;
  196. auto utf_word = unicode_cpts_from_utf8(word);
  197. for (size_t i = 0; i < utf_word.size(); ++i) {
  198. text_utf += unicode_cpt_to_utf8(utf_word[i]);
  199. }
  200. std::string encoded_token;
  201. for (char & c : text_utf) {
  202. encoded_token += unicode_byte_to_utf8(c);
  203. }
  204. bpe_encoded_words.emplace_back(encoded_token);
  205. }
  206. return bpe_encoded_words;
  207. }
  208. // GPT2 system regex: 's|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+
  209. static std::vector<size_t> unicode_regex_split_custom_gpt2(const std::string & text, const std::vector<size_t> & offsets) {
  210. std::vector<size_t> bpe_offsets; // store the offset of each word
  211. bpe_offsets.reserve(offsets.size()); // Reserve memory for the approximate size
  212. size_t start = 0;
  213. const auto cpts = unicode_cpts_from_utf8(text);
  214. for (auto offset : offsets) {
  215. std::string token;
  216. bool collecting_numeric = false;
  217. bool collecting_letter = false;
  218. bool collecting_special = false;
  219. bool collecting_whitespace_lookahead = false;
  220. bool collecting = false;
  221. std::vector<std::string> text_utf;
  222. text_utf.reserve(offset);
  223. for (size_t i = start; i < start + offset; ++i) {
  224. text_utf.emplace_back(unicode_cpt_to_utf8(cpts[i]));
  225. }
  226. for (int i = 0; i < (int)text_utf.size(); i++) {
  227. const std::string & utf_char = text_utf[i];
  228. bool split_condition = false;
  229. int bytes_remain = text_utf.size() - i;
  230. // forward backward lookups
  231. const std::string & utf_char_next = (i + 1 < (int)text_utf.size()) ? text_utf[i + 1] : "";
  232. const std::string & utf_char_next_next = (i + 2 < (int)text_utf.size()) ? text_utf[i + 2] : "";
  233. // handling contractions
  234. if (!split_condition && bytes_remain >= 2) {
  235. // 's|'t|'m|'d
  236. if (utf_char == "\'" && (utf_char_next == "s" || utf_char_next == "t" || utf_char_next == "m" || utf_char_next == "d")) {
  237. split_condition = true;
  238. }
  239. if (split_condition) {
  240. if (token.size()) {
  241. bpe_offsets.emplace_back(unicode_cpts_from_utf8(token).size());
  242. }
  243. token = utf_char + utf_char_next;
  244. bpe_offsets.emplace_back(unicode_cpts_from_utf8(token).size());
  245. token = "";
  246. i++;
  247. continue;
  248. }
  249. }
  250. if (!split_condition && bytes_remain >= 3) {
  251. // 're|'ve|'ll
  252. if (utf_char == "\'" && (
  253. (utf_char_next == "r" && utf_char_next_next == "e") ||
  254. (utf_char_next == "v" && utf_char_next_next == "e") ||
  255. (utf_char_next == "l" && utf_char_next_next == "l"))
  256. ) {
  257. split_condition = true;
  258. }
  259. if (split_condition) {
  260. // current token + next token can be defined
  261. if (token.size()) {
  262. bpe_offsets.emplace_back(unicode_cpts_from_utf8(token).size());
  263. }
  264. token = utf_char;
  265. token += utf_char_next;
  266. token += utf_char_next_next;
  267. bpe_offsets.emplace_back(unicode_cpts_from_utf8(token).size());
  268. token = "";
  269. i += 2;
  270. continue;
  271. }
  272. }
  273. if (!split_condition && !collecting) {
  274. if (unicode_cpt_type(utf_char) == CODEPOINT_TYPE_LETTER || (token.empty() && utf_char == " " && unicode_cpt_type(utf_char_next) == CODEPOINT_TYPE_LETTER)) {
  275. collecting_letter = true;
  276. collecting = true;
  277. }
  278. else if (unicode_cpt_type(utf_char) == CODEPOINT_TYPE_DIGIT || (token.empty() && utf_char == " " && unicode_cpt_type(utf_char_next) == CODEPOINT_TYPE_DIGIT)) {
  279. collecting_numeric = true;
  280. collecting = true;
  281. }
  282. else if (
  283. ((unicode_cpt_type(utf_char) != CODEPOINT_TYPE_LETTER && unicode_cpt_type(utf_char) != CODEPOINT_TYPE_DIGIT) && (unicode_cpt_type(utf_char) != CODEPOINT_TYPE_WHITESPACE)) ||
  284. (token.empty() && utf_char == " " && unicode_cpt_type(utf_char_next) != CODEPOINT_TYPE_LETTER && unicode_cpt_type(utf_char_next) != CODEPOINT_TYPE_DIGIT && unicode_cpt_type(utf_char_next) != CODEPOINT_TYPE_WHITESPACE)
  285. ) {
  286. collecting_special = true;
  287. collecting = true;
  288. }
  289. else if (unicode_cpt_type(utf_char) == CODEPOINT_TYPE_WHITESPACE && unicode_cpt_type(utf_char_next) == CODEPOINT_TYPE_WHITESPACE) {
  290. collecting_whitespace_lookahead = true;
  291. collecting = true;
  292. }
  293. else if (unicode_cpt_type(utf_char) == CODEPOINT_TYPE_WHITESPACE) {
  294. split_condition = true;
  295. }
  296. }
  297. else if (!split_condition && collecting) {
  298. if (collecting_letter && unicode_cpt_type(utf_char) != CODEPOINT_TYPE_LETTER) {
  299. split_condition = true;
  300. }
  301. else if (collecting_numeric && unicode_cpt_type(utf_char) != CODEPOINT_TYPE_DIGIT) {
  302. split_condition = true;
  303. }
  304. else if (collecting_special && (unicode_cpt_type(utf_char) == CODEPOINT_TYPE_LETTER || unicode_cpt_type(utf_char) == CODEPOINT_TYPE_DIGIT || unicode_cpt_type(utf_char) == CODEPOINT_TYPE_WHITESPACE)) {
  305. split_condition = true;
  306. }
  307. else if (collecting_whitespace_lookahead && (unicode_cpt_type(utf_char_next) == CODEPOINT_TYPE_LETTER || unicode_cpt_type(utf_char_next) == CODEPOINT_TYPE_DIGIT)) {
  308. split_condition = true;
  309. }
  310. }
  311. if (utf_char_next == "") {
  312. split_condition = true; // final
  313. token += utf_char;
  314. }
  315. if (split_condition) {
  316. if (token.size()) {
  317. bpe_offsets.emplace_back(unicode_cpts_from_utf8(token).size());
  318. }
  319. token = utf_char;
  320. collecting = false;
  321. collecting_letter = false;
  322. collecting_numeric = false;
  323. collecting_special = false;
  324. collecting_whitespace_lookahead = false;
  325. }
  326. else {
  327. token += utf_char;
  328. }
  329. }
  330. start += offset;
  331. }
  332. return bpe_offsets;
  333. }
  334. // use std::wregex to split the text
  335. static std::vector<size_t> unicode_regex_split_stl(const std::wstring & wtext, const std::wstring & regex_expr, const std::vector<size_t> & offsets) {
  336. std::wregex expr(regex_expr);
  337. std::vector<size_t> bpe_offsets; // store the offset of each word
  338. bpe_offsets.reserve(offsets.size()); // Reserve memory for the approximate size
  339. size_t start = 0;
  340. for (auto offset : offsets) {
  341. std::wcregex_iterator it(wtext.data() + start, wtext.data() + start + offset, expr);
  342. std::wcregex_iterator end;
  343. int64_t start_idx = 0;
  344. while (it != end) {
  345. std::wcmatch match = *it;
  346. if (match.position() > start_idx) {
  347. bpe_offsets.emplace_back(match.position() - start_idx);
  348. }
  349. bpe_offsets.emplace_back(match.length());
  350. start_idx = match.position() + match.length();
  351. ++it;
  352. }
  353. if (start_idx < (int64_t) offset) {
  354. bpe_offsets.emplace_back(offset - start_idx);
  355. }
  356. start += offset;
  357. }
  358. return bpe_offsets;
  359. }
  360. // use std::regex to split the text
  361. static std::vector<size_t> unicode_regex_split_stl(const std::string & text, const std::string & regex_expr, const std::vector<size_t> & offsets) {
  362. std::regex expr(regex_expr);
  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. size_t start = 0;
  366. for (auto offset : offsets) {
  367. std::cregex_iterator it(text.data() + start, text.data() + start + offset, expr);
  368. std::cregex_iterator end;
  369. int64_t start_idx = 0;
  370. while (it != end) {
  371. std::cmatch match = *it;
  372. if (match.position() > start_idx) {
  373. bpe_offsets.emplace_back(match.position() - start_idx);
  374. }
  375. bpe_offsets.emplace_back(match.length());
  376. start_idx = match.position() + match.length();
  377. ++it;
  378. }
  379. if (start_idx < (int64_t) offset) {
  380. bpe_offsets.emplace_back(offset - start_idx);
  381. }
  382. start += offset;
  383. }
  384. return bpe_offsets;
  385. }
  386. static std::vector<size_t> unicode_regex_split_custom(const std::string & text, const std::string & regex_expr, const std::vector<size_t> & offsets) {
  387. std::vector<size_t> bpe_offsets;
  388. (void)(text);
  389. (void)(regex_expr);
  390. (void)(offsets);
  391. // TODO: this implementation is actually wrong, uncomment and run:
  392. // make -j && ./bin/test-tokenizer-0 ../models/ggml-vocab-gpt-2.gguf
  393. //if (regex_expr == "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)") {
  394. // bpe_offsets = unicode_regex_split_custom_gpt2(text, offsets);
  395. //}
  396. return bpe_offsets;
  397. }
  398. //
  399. // interface
  400. //
  401. std::string unicode_cpt_to_utf8(uint32_t cp) {
  402. std::string result;
  403. if (/* 0x00 <= cp && */ cp <= 0x7f) {
  404. result.push_back(cp);
  405. return result;
  406. }
  407. if (0x80 <= cp && cp <= 0x7ff) {
  408. result.push_back(0xc0 | ((cp >> 6) & 0x1f));
  409. result.push_back(0x80 | (cp & 0x3f));
  410. return result;
  411. }
  412. if (0x800 <= cp && cp <= 0xffff) {
  413. result.push_back(0xe0 | ((cp >> 12) & 0x0f));
  414. result.push_back(0x80 | ((cp >> 6) & 0x3f));
  415. result.push_back(0x80 | (cp & 0x3f));
  416. return result;
  417. }
  418. if (0x10000 <= cp && cp <= 0x10ffff) {
  419. result.push_back(0xf0 | ((cp >> 18) & 0x07));
  420. result.push_back(0x80 | ((cp >> 12) & 0x3f));
  421. result.push_back(0x80 | ((cp >> 6) & 0x3f));
  422. result.push_back(0x80 | (cp & 0x3f));
  423. return result;
  424. }
  425. throw std::invalid_argument("invalid codepoint");
  426. }
  427. std::vector<uint32_t> unicode_cpts_normalize_nfd(const std::vector<uint32_t> & cpts) {
  428. std::vector<uint32_t> result;
  429. result.reserve(cpts.size());
  430. for (size_t i = 0; i < cpts.size(); ++i) {
  431. auto it = unicode_map_nfd.find(cpts[i]);
  432. if (it == unicode_map_nfd.end()) {
  433. result.push_back(cpts[i]);
  434. } else {
  435. result.push_back(it->second);
  436. }
  437. }
  438. return result;
  439. }
  440. std::vector<uint32_t> unicode_cpts_from_utf8(const std::string & utf8) {
  441. std::vector<uint32_t> result;
  442. size_t offset = 0;
  443. while (offset < utf8.size()) {
  444. result.push_back(unicode_cpt_from_utf8(utf8, offset));
  445. }
  446. return result;
  447. }
  448. int unicode_cpt_type(uint32_t cp) {
  449. static std::unordered_map<uint32_t, int> cpt_types = unicode_cpt_type_map();
  450. const auto it = cpt_types.find(cp);
  451. return it == cpt_types.end() ? CODEPOINT_TYPE_UNIDENTIFIED : it->second;
  452. }
  453. int unicode_cpt_type(const std::string & utf8) {
  454. if (utf8.length() == 0) {
  455. return CODEPOINT_TYPE_UNIDENTIFIED;
  456. }
  457. size_t offset = 0;
  458. return unicode_cpt_type(unicode_cpt_from_utf8(utf8, offset));
  459. }
  460. std::string unicode_byte_to_utf8(uint8_t byte) {
  461. static std::unordered_map<uint8_t, std::string> map = unicode_byte_to_utf8_map();
  462. return map.at(byte);
  463. }
  464. uint8_t unicode_utf8_to_byte(const std::string & utf8) {
  465. static std::unordered_map<std::string, uint8_t> map = unicode_utf8_to_byte_map();
  466. return map.at(utf8);
  467. }
  468. char32_t unicode_tolower(char32_t cp) {
  469. auto it = unicode_map_lowercase.find(cp);
  470. return it == unicode_map_lowercase.end() ? cp : it->second;
  471. }
  472. std::vector<std::string> unicode_regex_split(const std::string & text, const std::vector<std::string> & regex_exprs) {
  473. // unicode categories
  474. static const std::map<std::string, int> k_ucat_enum = {
  475. { "\\p{N}", CODEPOINT_TYPE_DIGIT },
  476. { "\\p{L}", CODEPOINT_TYPE_LETTER },
  477. { "\\p{P}", CODEPOINT_TYPE_PUNCTUATION },
  478. };
  479. static const std::map<int, int> k_ucat_cpt = {
  480. { CODEPOINT_TYPE_DIGIT, 0xD1 },
  481. { CODEPOINT_TYPE_LETTER, 0xD2 },
  482. { CODEPOINT_TYPE_PUNCTUATION, 0xD3 },
  483. };
  484. static const std::map<int, std::string> k_ucat_map = {
  485. { CODEPOINT_TYPE_DIGIT, "\x30-\x39" }, // 0-9
  486. { CODEPOINT_TYPE_LETTER, "\x41-\x5A\x61-\x7A" }, // A-Za-z
  487. { CODEPOINT_TYPE_PUNCTUATION, "\x21-\x23\x25-\x2A\x2C-\x2F\x3A-\x3B\x3F-\x40\\\x5B-\\\x5D\x5F\\\x7B\\\x7D" }, // !-#%-*,-/:-;?-@\[-\]_\{\}
  488. };
  489. // compute collapsed codepoints only if needed by at least one regex
  490. bool need_collapse = false;
  491. for (auto & regex_expr : regex_exprs) {
  492. // search for unicode categories
  493. for (const auto & ucat : k_ucat_enum) {
  494. if (std::string::npos != regex_expr.find(ucat.first)) {
  495. need_collapse = true;
  496. break;
  497. }
  498. }
  499. }
  500. const auto cpts = unicode_cpts_from_utf8(text);
  501. // generate a "collapsed" representation of the text, where all codepoints are replaced by a single byte
  502. // ref: https://github.com/ggerganov/llama.cpp/pull/6920#issuecomment-2081479935
  503. std::string text_collapsed;
  504. if (need_collapse) {
  505. // collapse all unicode categories
  506. text_collapsed.resize(cpts.size());
  507. for (size_t i = 0; i < cpts.size(); ++i) {
  508. // keep single-byte codepoints as is
  509. if (cpts[i] < 128) {
  510. text_collapsed[i] = cpts[i];
  511. continue;
  512. }
  513. const int cpt_type = unicode_cpt_type(cpts[i]);
  514. if (k_ucat_cpt.find(cpt_type) != k_ucat_cpt.end()) {
  515. text_collapsed[i] = k_ucat_cpt.at(cpt_type);
  516. } else {
  517. text_collapsed[i] = (char) 0xD0; // fallback
  518. }
  519. }
  520. }
  521. std::vector<size_t> bpe_offsets = { cpts.size() };
  522. for (auto & regex_expr : regex_exprs) {
  523. // first, see if we have an efficient custom regex implementation
  524. auto tmp = unicode_regex_split_custom(text, regex_expr, bpe_offsets);
  525. if (!tmp.empty()) {
  526. bpe_offsets = std::move(tmp);
  527. continue;
  528. }
  529. // fallback to general-purpose std::regex / std::wregex
  530. try {
  531. // if a unicode category is used in the regex, we use the collapsed text and replace the unicode category
  532. // with the corresponding collapsed representation
  533. bool use_collapsed = false;
  534. for (auto & ucat : k_ucat_enum) {
  535. if (std::string::npos != regex_expr.find(ucat.first)) {
  536. use_collapsed = true;
  537. break;
  538. }
  539. }
  540. if (use_collapsed) {
  541. // sanity-check that the original regex does not contain any non-ASCII characters
  542. const auto cpts_regex = unicode_cpts_from_utf8(regex_expr);
  543. for (size_t i = 0; i < cpts_regex.size(); ++i) {
  544. if (cpts_regex[i] >= 128) {
  545. throw std::runtime_error("Regex includes both unicode categories and non-ASCII characters - not supported");
  546. }
  547. }
  548. // generate a collapsed representation of the regex
  549. std::string regex_expr_collapsed;
  550. // track if we are inside [], because nested [] are not allowed
  551. bool inside = false;
  552. for (size_t i = 0; i < regex_expr.size(); ++i) {
  553. if (regex_expr[i] == '[' && (i == 0 || regex_expr[i - 1] != '\\')) {
  554. regex_expr_collapsed += '[';
  555. inside = true;
  556. continue;
  557. }
  558. if (inside && regex_expr[i] == ']' && regex_expr[i - 1] != '\\') {
  559. regex_expr_collapsed += ']';
  560. inside = false;
  561. continue;
  562. }
  563. if (regex_expr[i + 0] == '\\' && i + 4 < regex_expr.size() &&
  564. regex_expr[i + 1] == 'p' &&
  565. regex_expr[i + 2] == '{' &&
  566. regex_expr[i + 4] == '}') {
  567. const std::string pat = regex_expr.substr(i, 5);
  568. if (k_ucat_enum.find(pat) != k_ucat_enum.end()) {
  569. if (!inside) {
  570. regex_expr_collapsed += '[';
  571. }
  572. regex_expr_collapsed += k_ucat_cpt.at(k_ucat_enum.at(pat));
  573. regex_expr_collapsed += k_ucat_map.at(k_ucat_enum.at(pat));
  574. if (!inside) {
  575. regex_expr_collapsed += ']';
  576. }
  577. i += 4;
  578. continue;
  579. }
  580. }
  581. regex_expr_collapsed += regex_expr[i];
  582. }
  583. //printf("text_collapsed: %s\n", text_collapsed.c_str());
  584. //printf("regex_expr_collapsed: %s\n", regex_expr_collapsed.c_str());
  585. bpe_offsets = unicode_regex_split_stl(text_collapsed, regex_expr_collapsed, bpe_offsets);
  586. } else {
  587. // no unicode category used, we can use std::wregex directly
  588. const std::wstring wtext = unicode_wstring_from_utf8(text);
  589. const std::wstring wregex_expr = unicode_wstring_from_utf8(regex_expr);
  590. //printf("text: %s\n", text.c_str());
  591. //printf("regex_expr: %s\n", regex_expr.c_str());
  592. bpe_offsets = unicode_regex_split_stl(wtext, wregex_expr, bpe_offsets);
  593. }
  594. } catch (std::regex_error & e) {
  595. fprintf(stderr, "Failed to process regex: '%s'\n", regex_expr.c_str());
  596. fprintf(stderr, "Regex error: %s\n", e.what());
  597. throw std::runtime_error("Failed to process regex");
  598. }
  599. }
  600. std::vector<std::string> bpe_words;
  601. bpe_words.reserve(bpe_offsets.size()); // reserve memory for the approximate size
  602. size_t start = 0;
  603. for (size_t & offset : bpe_offsets) {
  604. bpe_words.emplace_back();
  605. for (size_t i = start; i < start + offset; ++i) {
  606. bpe_words.back() += unicode_cpt_to_utf8(cpts[i]);
  607. }
  608. start += offset;
  609. }
  610. return unicode_byte_encoding_process(bpe_words);
  611. }