llama-vocab.cpp 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891
  1. /**
  2. * llama.cpp - commit 8962422b1c6f9b8b15f5aeaea42600bcc2d44177 - do not edit this file
  3. *
  4. * MIT License
  5. *
  6. * Copyright (c) 2023-2024 The ggml authors
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy
  9. * of this software and associated documentation files (the "Software"), to deal
  10. * in the Software without restriction, including without limitation the rights
  11. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. * copies of the Software, and to permit persons to whom the Software is
  13. * furnished to do so, subject to the following conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be included in all
  16. * copies or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  23. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  24. * SOFTWARE.
  25. */
  26. #include "llama-vocab.h"
  27. #include "unicode.h"
  28. #include <algorithm>
  29. #include <cassert>
  30. #include <cfloat>
  31. #include <climits>
  32. #include <cstdarg>
  33. #include <cstring>
  34. #include <forward_list>
  35. #include <queue>
  36. #include <sstream>
  37. //
  38. // helpers
  39. //
  40. LLAMA_ATTRIBUTE_FORMAT(1, 2)
  41. static std::string format(const char * fmt, ...) {
  42. va_list ap;
  43. va_list ap2;
  44. va_start(ap, fmt);
  45. va_copy(ap2, ap);
  46. int size = vsnprintf(NULL, 0, fmt, ap);
  47. GGML_ASSERT(size >= 0 && size < INT_MAX); // NOLINT
  48. std::vector<char> buf(size + 1);
  49. int size2 = vsnprintf(buf.data(), size + 1, fmt, ap2);
  50. GGML_ASSERT(size2 == size);
  51. va_end(ap2);
  52. va_end(ap);
  53. return std::string(buf.data(), size);
  54. }
  55. struct naive_trie {
  56. naive_trie() : has_value(false), value(0) {
  57. }
  58. void insert(const char * key, size_t len, int32_t value = 0) {
  59. if (len == 0) {
  60. this->has_value = true;
  61. this->value = value;
  62. return;
  63. }
  64. char c = key[0];
  65. auto res = children.find(c);
  66. if (res != children.end()) {
  67. res->second.insert(key + 1, len - 1, value);
  68. } else {
  69. auto res = children.insert(std::make_pair(c, naive_trie()));
  70. res.first->second.insert(key + 1, len - 1, value);
  71. }
  72. }
  73. std::pair<const char *, size_t> get_longest_prefix(const char * key, size_t len, size_t offset = 0) {
  74. if (len == 0 || offset == len) {
  75. return std::make_pair(key, offset);
  76. }
  77. char c = key[offset];
  78. auto res = children.find(c);
  79. if (res != children.end()) {
  80. return res->second.get_longest_prefix(key, len, offset + 1);
  81. }
  82. return std::make_pair(key, offset);
  83. }
  84. const struct naive_trie * traverse(const char c) const {
  85. auto res = children.find(c);
  86. if (res != children.end()) {
  87. return &res->second;
  88. }
  89. return NULL;
  90. }
  91. std::map<char, struct naive_trie> children;
  92. bool has_value;
  93. llama_token value;
  94. };
  95. //
  96. // impl
  97. //
  98. int llama_vocab::find_bpe_rank(const std::string & token_left, const std::string & token_right) const {
  99. GGML_ASSERT(token_left.find(' ') == std::string::npos);
  100. GGML_ASSERT(token_left.find('\n') == std::string::npos);
  101. GGML_ASSERT(token_right.find(' ') == std::string::npos);
  102. GGML_ASSERT(token_right.find('\n') == std::string::npos);
  103. auto it = bpe_ranks.find(std::make_pair(token_left, token_right));
  104. if (it == bpe_ranks.end()) {
  105. return -1;
  106. }
  107. return it->second;
  108. }
  109. static enum llama_vocab_type llama_vocab_get_type(const llama_vocab & vocab) {
  110. return vocab.type;
  111. }
  112. static bool llama_is_normal_token(const llama_vocab & vocab, llama_token id) {
  113. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  114. return vocab.id_to_token[id].attr & LLAMA_TOKEN_ATTR_NORMAL;
  115. }
  116. static bool llama_is_unknown_token(const llama_vocab & vocab, llama_token id) {
  117. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  118. return vocab.id_to_token[id].attr & LLAMA_TOKEN_ATTR_UNKNOWN;
  119. }
  120. static bool llama_is_control_token(const llama_vocab & vocab, llama_token id) {
  121. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  122. return vocab.id_to_token[id].attr & LLAMA_TOKEN_ATTR_CONTROL;
  123. }
  124. static bool llama_is_byte_token(const llama_vocab & vocab, llama_token id) {
  125. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  126. return vocab.id_to_token[id].attr & LLAMA_TOKEN_ATTR_BYTE;
  127. }
  128. static bool llama_is_user_defined_token(const llama_vocab & vocab, llama_token id) {
  129. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  130. return vocab.id_to_token[id].attr & LLAMA_TOKEN_ATTR_USER_DEFINED;
  131. }
  132. static bool llama_is_unused_token(const llama_vocab & vocab, llama_token id) {
  133. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  134. return vocab.id_to_token[id].attr & LLAMA_TOKEN_ATTR_UNUSED;
  135. }
  136. static uint8_t llama_token_to_byte(const llama_vocab & vocab, llama_token id) {
  137. GGML_ASSERT(llama_vocab_get_type(vocab) != LLAMA_VOCAB_TYPE_NONE);
  138. GGML_ASSERT(llama_is_byte_token(vocab, id));
  139. const auto & token_data = vocab.id_to_token.at(id);
  140. switch (llama_vocab_get_type(vocab)) {
  141. case LLAMA_VOCAB_TYPE_SPM:
  142. case LLAMA_VOCAB_TYPE_UGM: {
  143. auto buf = token_data.text.substr(3, 2);
  144. return strtol(buf.c_str(), NULL, 16);
  145. }
  146. case LLAMA_VOCAB_TYPE_BPE: {
  147. GGML_ABORT("fatal error");
  148. //return unicode_utf8_to_byte(token_data.text); // TODO: why is this here after GGML_ASSERT?
  149. }
  150. case LLAMA_VOCAB_TYPE_WPM: {
  151. GGML_ABORT("fatal error");
  152. }
  153. default:
  154. GGML_ABORT("fatal error");
  155. }
  156. }
  157. static void llama_escape_whitespace(std::string & text) {
  158. replace_all(text, " ", "\xe2\x96\x81");
  159. }
  160. static void llama_unescape_whitespace(std::string & word) {
  161. replace_all(word, "\xe2\x96\x81", " ");
  162. }
  163. struct llm_symbol {
  164. using index = int;
  165. index prev;
  166. index next;
  167. const char * text;
  168. size_t n;
  169. };
  170. static_assert(std::is_trivially_copyable<llm_symbol>::value, "llm_symbol is not trivially copyable");
  171. //
  172. // SPM tokenizer
  173. // original implementation:
  174. // https://github.com/ggerganov/llama.cpp/commit/074bea2eb1f1349a0118239c4152914aecaa1be4
  175. //
  176. struct llm_bigram_spm {
  177. struct comparator {
  178. bool operator()(llm_bigram_spm & l, llm_bigram_spm & r) {
  179. return (l.score < r.score) || (l.score == r.score && l.left > r.left);
  180. }
  181. };
  182. using queue_storage = std::vector<llm_bigram_spm>;
  183. using queue = std::priority_queue<llm_bigram_spm, queue_storage, comparator>;
  184. llm_symbol::index left;
  185. llm_symbol::index right;
  186. float score;
  187. size_t size;
  188. };
  189. struct llm_tokenizer_spm {
  190. llm_tokenizer_spm(const llama_vocab & vocab) : vocab(vocab) {}
  191. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  192. // split string into utf8 chars
  193. int index = 0;
  194. size_t offs = 0;
  195. while (offs < text.size()) {
  196. llm_symbol sym;
  197. size_t len = unicode_len_utf8(text[offs]);
  198. sym.text = text.c_str() + offs;
  199. sym.n = std::min(len, text.size() - offs);
  200. offs += sym.n;
  201. sym.prev = index - 1;
  202. sym.next = offs == text.size() ? -1 : index + 1;
  203. index++;
  204. symbols.emplace_back(sym);
  205. }
  206. // seed the work queue with all possible 2-character tokens.
  207. for (size_t i = 1; i < symbols.size(); ++i) {
  208. try_add_bigram(i - 1, i);
  209. }
  210. // keep substituting the highest frequency pairs for as long as we can.
  211. while (!work_queue.empty()) {
  212. auto bigram = work_queue.top();
  213. work_queue.pop();
  214. auto & left_sym = symbols[bigram.left];
  215. auto & right_sym = symbols[bigram.right];
  216. // if one of the symbols already got merged, skip it.
  217. if (left_sym.n == 0 || right_sym.n == 0 ||
  218. left_sym.n + right_sym.n != bigram.size) {
  219. continue;
  220. }
  221. // merge the right sym into the left one
  222. left_sym.n += right_sym.n;
  223. right_sym.n = 0;
  224. //LLAMA_LOG_INFO("left = '%*s' size = %zu\n", (int) left_sym.n, left_sym.text, bigram.size);
  225. // remove the right sym from the chain
  226. left_sym.next = right_sym.next;
  227. if (right_sym.next >= 0) {
  228. symbols[right_sym.next].prev = bigram.left;
  229. }
  230. // find more substitutions
  231. try_add_bigram(left_sym.prev, bigram.left);
  232. try_add_bigram(bigram.left, left_sym.next);
  233. }
  234. for (int i = 0; i != -1; i = symbols[i].next) {
  235. auto & symbol = symbols[i];
  236. resegment(symbol, output);
  237. }
  238. }
  239. private:
  240. void resegment(llm_symbol & symbol, std::vector<llama_vocab::id> & output) {
  241. auto text = std::string(symbol.text, symbol.n);
  242. auto token = vocab.token_to_id.find(text);
  243. // Do we need to support is_unused?
  244. if (token != vocab.token_to_id.end()) {
  245. output.push_back((*token).second);
  246. return;
  247. }
  248. const auto p = rev_merge.find(text);
  249. if (p == rev_merge.end()) {
  250. // output any symbols that did not form tokens as bytes.
  251. output.reserve(output.size() + symbol.n);
  252. for (int j = 0; j < (int)symbol.n; ++j) {
  253. llama_vocab::id token_id = llama_byte_to_token_impl(vocab, symbol.text[j]);
  254. output.push_back(token_id);
  255. }
  256. return;
  257. }
  258. resegment(symbols[p->second.first], output);
  259. resegment(symbols[p->second.second], output);
  260. }
  261. void try_add_bigram(int left, int right) {
  262. if (left == -1 || right == -1) {
  263. return;
  264. }
  265. const std::string text = std::string(symbols[left].text, symbols[left].n + symbols[right].n);
  266. auto token = vocab.token_to_id.find(text);
  267. if (token == vocab.token_to_id.end()) {
  268. return;
  269. }
  270. if (static_cast<size_t>((*token).second) >= vocab.id_to_token.size()) {
  271. return;
  272. }
  273. const auto & tok_data = vocab.id_to_token[(*token).second];
  274. llm_bigram_spm bigram;
  275. bigram.left = left;
  276. bigram.right = right;
  277. bigram.score = tok_data.score;
  278. bigram.size = text.size();
  279. work_queue.push(bigram);
  280. // Do we need to support is_unused?
  281. rev_merge[text] = std::make_pair(left, right);
  282. }
  283. const llama_vocab & vocab;
  284. std::vector<llm_symbol> symbols;
  285. llm_bigram_spm::queue work_queue;
  286. std::map<std::string, std::pair<int, int>> rev_merge;
  287. };
  288. //
  289. // BPE tokenizer
  290. // adapted from https://github.com/cmp-nct/ggllm.cpp [MIT License]
  291. // tried to simplify unicode stuff, so most likely does not work 100% correctly!
  292. //
  293. // TODO: there are a lot of common parts between spm and bpe tokenizers, should be refactored and reused
  294. template<typename T, typename Container = std::vector<T>, typename Compare = std::less<typename Container::value_type>>
  295. class llama_priority_queue : public std::priority_queue<T, Container, Compare> {
  296. public:
  297. using std::priority_queue<T, Container, Compare>::priority_queue;
  298. T pop_move() {
  299. T item = std::move(this->c.front());
  300. std::pop_heap(this->c.begin(), this->c.end(), this->comp);
  301. this->c.pop_back();
  302. return item;
  303. }
  304. void pop() = delete;
  305. };
  306. struct llm_bigram_bpe {
  307. struct comparator {
  308. bool operator()(const llm_bigram_bpe & l, const llm_bigram_bpe & r) const {
  309. return l.rank > r.rank || (l.rank == r.rank && l.left > r.left);
  310. }
  311. };
  312. using queue_storage = std::vector<llm_bigram_bpe>;
  313. using queue = llama_priority_queue<llm_bigram_bpe, queue_storage, comparator>;
  314. llm_symbol::index left;
  315. llm_symbol::index right;
  316. std::string text;
  317. int rank;
  318. size_t size;
  319. };
  320. struct llm_tokenizer_bpe {
  321. llm_tokenizer_bpe(const llama_vocab & vocab): vocab(vocab) {
  322. GGML_ASSERT(vocab.type == LLAMA_VOCAB_TYPE_BPE);
  323. switch (vocab.type_pre) {
  324. case LLAMA_VOCAB_PRE_TYPE_LLAMA3:
  325. regex_exprs = {
  326. // original regex from tokenizer.json
  327. //"(?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+",
  328. // adapted: https://github.com/ggerganov/llama.cpp/pull/6920#issuecomment-2080233989
  329. "(?:'[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+",
  330. };
  331. break;
  332. case LLAMA_VOCAB_PRE_TYPE_DBRX:
  333. case LLAMA_VOCAB_PRE_TYPE_SMAUG:
  334. regex_exprs = {
  335. // same as llama3
  336. "(?:'[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+",
  337. };
  338. break;
  339. case LLAMA_VOCAB_PRE_TYPE_DEEPSEEK_LLM:
  340. regex_exprs = {
  341. "[\r\n]",
  342. "\\s?[A-Za-zµÀ-ÖØ-öø-ƺƼ-ƿDŽ-ʓʕ-ʯͰ-ͳͶͷͻ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-ՖႠ-ჅᎠ-Ᏽᏸ-ᏽᲐ-ᲺᲽ-Ჿᴀ-ᴫᵫ-ᵷᵹ-ᶚḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℴℹℼ-ℿⅅ-ⅉⅎↃↄⰀ-ⱻⱾ-ⳤⳫ-ⳮⳲⳳꙀ-ꙭꚀ-ꚛꜢ-ꝯꝱ-ꞇꞋ-ꞎꭰ-ꮿff-stﬓ-ﬗA-Za-z𐐀-𐑏𐒰-𐓓𐓘-𐓻𐲀-𐲲𐳀-𐳲𑢠-𑣟𞤀-𞥃]+",
  343. "\\s?[!-/:-~!-/:-~‘-‟ -。]+",
  344. "\\s+$",
  345. "[一-龥ࠀ-一가-퟿]+",
  346. "\\p{N}+",
  347. };
  348. break;
  349. case LLAMA_VOCAB_PRE_TYPE_DEEPSEEK_CODER:
  350. regex_exprs = {
  351. "[\r\n]",
  352. "\\s?\\p{L}+",
  353. "\\s?\\p{P}+",
  354. "[一-龥ࠀ-一가-퟿]+",
  355. "\\p{N}",
  356. };
  357. break;
  358. case LLAMA_VOCAB_PRE_TYPE_FALCON:
  359. regex_exprs = {
  360. "[\\p{P}\\$\\+<=>\\^~\\|`]+",
  361. "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)",
  362. "[0-9][0-9][0-9]",
  363. };
  364. break;
  365. case LLAMA_VOCAB_PRE_TYPE_STARCODER:
  366. case LLAMA_VOCAB_PRE_TYPE_REFACT:
  367. case LLAMA_VOCAB_PRE_TYPE_COMMAND_R:
  368. case LLAMA_VOCAB_PRE_TYPE_SMOLLM:
  369. case LLAMA_VOCAB_PRE_TYPE_CODESHELL:
  370. case LLAMA_VOCAB_PRE_TYPE_EXAONE:
  371. regex_exprs = {
  372. "\\p{N}",
  373. "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)",
  374. };
  375. break;
  376. case LLAMA_VOCAB_PRE_TYPE_GPT2:
  377. case LLAMA_VOCAB_PRE_TYPE_MPT:
  378. case LLAMA_VOCAB_PRE_TYPE_OLMO:
  379. case LLAMA_VOCAB_PRE_TYPE_JAIS:
  380. regex_exprs = {
  381. "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)",
  382. };
  383. break;
  384. case LLAMA_VOCAB_PRE_TYPE_STABLELM2:
  385. case LLAMA_VOCAB_PRE_TYPE_QWEN2:
  386. regex_exprs = {
  387. // original regex from tokenizer.json
  388. // "(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+"
  389. "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+",
  390. };
  391. break;
  392. case LLAMA_VOCAB_PRE_TYPE_PORO:
  393. case LLAMA_VOCAB_PRE_TYPE_BLOOM:
  394. case LLAMA_VOCAB_PRE_TYPE_GPT3_FINNISH:
  395. regex_exprs = {
  396. " ?[^(\\s|.,!?…。,、।۔،)]+",
  397. };
  398. break;
  399. case LLAMA_VOCAB_PRE_TYPE_CHATGLM4:
  400. regex_exprs = {
  401. "(?:'[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+",
  402. };
  403. break;
  404. case LLAMA_VOCAB_PRE_TYPE_VIKING:
  405. regex_exprs = {
  406. " ?[^(\\s|.,!?…。,、।۔،)]+",
  407. "\\p{N}",
  408. };
  409. break;
  410. case LLAMA_VOCAB_PRE_TYPE_TEKKEN:
  411. // original regex from tokenizer.json
  412. // "[^\\r\\n\\p{L}\\p{N}]?[\\p{Lu}\\p{Lt}\\p{Lm}\\p{Lo}\\p{M}]*[\\p{Ll}\\p{Lm}\\p{Lo}\\p{M}]+|[^\\r\\n\\p{L}\\p{N}]?[\\p{Lu}\\p{Lt}\\p{Lm}\\p{Lo}\\p{M}]+[\\p{Ll}\\p{Lm}\\p{Lo}\\p{M}]*|\\p{N}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n/]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+"
  413. regex_exprs = {
  414. "[^\\r\\n\\p{L}\\p{N}]?((?=[\\p{L}])([^a-z]))*((?=[\\p{L}])([^A-Z]))+|[^\\r\\n\\p{L}\\p{N}]?((?=[\\p{L}])([^a-z]))+((?=[\\p{L}])([^A-Z]))*|\\p{N}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n/]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+",
  415. };
  416. break;
  417. default:
  418. // default regex for BPE tokenization pre-processing
  419. regex_exprs = {
  420. "[\\p{P}\\$\\+<=>\\^~\\|]+",
  421. "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)",
  422. "\\p{N}+",
  423. "[0-9][0-9][0-9]",
  424. };
  425. break;
  426. }
  427. }
  428. void append(const llama_vocab::id token_id, std::vector<llama_vocab::id> & output) const {
  429. output.push_back(token_id);
  430. }
  431. bool append_bos(std::vector<llama_vocab::id> & output) const {
  432. if (vocab.tokenizer_add_bos) {
  433. GGML_ASSERT(vocab.special_bos_id != -1);
  434. output.push_back(vocab.special_bos_id);
  435. return true;
  436. }
  437. return false;
  438. }
  439. bool append_eos(std::vector<llama_vocab::id> & output) const {
  440. if (vocab.tokenizer_add_eos) {
  441. GGML_ASSERT(vocab.special_eos_id != -1);
  442. output.push_back(vocab.special_eos_id);
  443. return true;
  444. }
  445. return false;
  446. }
  447. void check_double_bos_eos(const std::vector<llama_vocab::id> & output) const {
  448. if (vocab.tokenizer_add_bos && output.size() >= 2 && output[1] == vocab.special_bos_id) {
  449. LLAMA_LOG_WARN(
  450. "%s: Added a BOS token to the prompt as specified by the model but the prompt "
  451. "also starts with a BOS token. So now the final prompt starts with 2 BOS tokens. "
  452. "Are you sure this is what you want?\n", __FUNCTION__);
  453. }
  454. if (vocab.tokenizer_add_eos && output.size() >= 2 && *(output.end()-2) == vocab.special_eos_id) {
  455. LLAMA_LOG_WARN(
  456. "%s: Added a EOS token to the prompt as specified by the model but the prompt "
  457. "also ends with a EOS token. So now the final prompt ends with 2 EOS tokens. "
  458. "Are you sure this is what you want?\n", __FUNCTION__);
  459. }
  460. }
  461. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  462. int final_prev_index = -1;
  463. const auto word_collection = unicode_regex_split(text, regex_exprs);
  464. symbols_final.clear();
  465. for (auto & word : word_collection) {
  466. work_queue = llm_bigram_bpe::queue();
  467. symbols.clear();
  468. int index = 0;
  469. size_t offset = 0;
  470. if (vocab.tokenizer_ignore_merges && vocab.token_to_id.find(word) != vocab.token_to_id.end()) {
  471. symbols.emplace_back(llm_symbol{-1, -1, word.c_str(), word.size()});
  472. offset = word.size();
  473. }
  474. while (offset < word.size()) {
  475. llm_symbol sym;
  476. size_t char_len = std::min(word.size() - offset, (size_t) unicode_len_utf8(word[offset]));
  477. sym.text = word.c_str() + offset;
  478. sym.n = char_len;
  479. offset += sym.n;
  480. sym.prev = index - 1;
  481. sym.next = offset == word.size() ? -1 : index + 1;
  482. index++;
  483. symbols.emplace_back(sym);
  484. }
  485. for (size_t i = 1; i < symbols.size(); ++i) {
  486. add_new_bigram(i - 1, i);
  487. }
  488. // build token(s)
  489. while (!work_queue.empty()) {
  490. auto bigram = work_queue.pop_move();
  491. auto & left_symbol = symbols[bigram.left];
  492. auto & right_symbol = symbols[bigram.right];
  493. if (left_symbol.n == 0 || right_symbol.n == 0) {
  494. continue;
  495. }
  496. std::string left_token = std::string(left_symbol.text, left_symbol.n);
  497. std::string right_token = std::string(right_symbol.text, right_symbol.n);
  498. if (left_token + right_token != bigram.text) {
  499. continue; // Skip this bigram if it's outdated
  500. }
  501. // merge the right sym into the left one
  502. left_symbol.n += right_symbol.n;
  503. right_symbol.n = 0;
  504. // remove the right sym from the chain
  505. left_symbol.next = right_symbol.next;
  506. if (right_symbol.next >= 0) {
  507. symbols[right_symbol.next].prev = bigram.left;
  508. }
  509. add_new_bigram(left_symbol.prev, bigram.left); // left side of current symbol
  510. add_new_bigram(bigram.left, left_symbol.next); // right side of current symbol
  511. }
  512. // add the finished tokens to the final list keeping correct order for next and prev
  513. for (auto & sym : symbols) {
  514. if (sym.n > 0) {
  515. sym.prev = final_prev_index;
  516. sym.next = -1;
  517. if (final_prev_index != -1) {
  518. symbols_final[final_prev_index].next = symbols_final.size();
  519. }
  520. symbols_final.emplace_back(sym);
  521. final_prev_index = symbols_final.size() - 1;
  522. }
  523. }
  524. }
  525. symbols = symbols_final;
  526. if (!symbols.empty()) {
  527. for (int i = 0; i != -1; i = symbols[i].next) {
  528. auto & symbol = symbols[i];
  529. if (symbol.n == 0) {
  530. continue;
  531. }
  532. const std::string str = std::string(symbol.text, symbol.n);
  533. const auto token = vocab.token_to_id.find(str);
  534. if (token == vocab.token_to_id.end()) {
  535. for (auto j = str.begin(); j != str.end(); ++j) {
  536. std::string byte_str(1, *j);
  537. auto token_multibyte = vocab.token_to_id.find(byte_str);
  538. if (token_multibyte != vocab.token_to_id.end()) {
  539. output.push_back(token_multibyte->second);
  540. }
  541. }
  542. } else {
  543. output.push_back((*token).second);
  544. }
  545. }
  546. }
  547. }
  548. private:
  549. void add_new_bigram(int left, int right) {
  550. if (left == -1 || right == -1) {
  551. return;
  552. }
  553. std::string left_token = std::string(symbols[left].text, symbols[left].n);
  554. std::string right_token = std::string(symbols[right].text, symbols[right].n);
  555. int rank_found = -1;
  556. rank_found = vocab.find_bpe_rank(left_token, right_token);
  557. if (rank_found < 0) {
  558. return;
  559. }
  560. llm_bigram_bpe bigram;
  561. bigram.left = left;
  562. bigram.right = right;
  563. bigram.text = left_token + right_token;
  564. bigram.size = left_token.size() + right_token.size();
  565. bigram.rank = rank_found;
  566. work_queue.push(bigram);
  567. }
  568. const llama_vocab & vocab;
  569. std::vector<std::string> regex_exprs;
  570. std::vector<llm_symbol> symbols;
  571. std::vector<llm_symbol> symbols_final;
  572. llm_bigram_bpe::queue work_queue;
  573. };
  574. //
  575. // WPM tokenizer
  576. //
  577. struct llm_tokenizer_wpm {
  578. llm_tokenizer_wpm(const llama_vocab & vocab): vocab(vocab) {}
  579. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) const {
  580. const auto & token_map = vocab.token_to_id;
  581. // normalize and split by whitespace
  582. std::vector<std::string> words = preprocess(text);
  583. // bos token prepended already
  584. // find the longest tokens that form the words
  585. for (const std::string & word : words) {
  586. // skip empty words
  587. if (word.size() == 0) {
  588. continue;
  589. }
  590. // prepend phantom space
  591. const std::string word1 = "\xe2\x96\x81" + word;
  592. const int n = word1.size();
  593. const size_t current_tokens = output.size();
  594. // we're at the start of a new word
  595. // move through character position in word
  596. for (int i = 0; i < n; ++i) {
  597. // loop through possible match length
  598. bool match = false;
  599. for (int j = std::min(n, i + vocab.max_token_len + 1); j > i; j--) {
  600. auto it = token_map.find(word1.substr(i, j - i));
  601. if (it != token_map.end()) {
  602. output.push_back(it->second);
  603. match = true;
  604. i = j - 1;
  605. break;
  606. }
  607. }
  608. if (!match) { // discard all
  609. output.resize(current_tokens);
  610. break; // and discard next tokens
  611. }
  612. }
  613. // we didn't find any matches for this word
  614. if (current_tokens == output.size()) {
  615. output.push_back(vocab.special_unk_id);
  616. }
  617. }
  618. }
  619. // TODO: reduce string copies by using cpts_offs array
  620. std::vector<std::string> preprocess(const std::string & text) const {
  621. const std::vector<uint32_t> cpts_nfd = unicode_cpts_normalize_nfd(unicode_cpts_from_utf8(text));
  622. std::vector<std::string> words(1, "");
  623. for (const uint32_t cpt : cpts_nfd) {
  624. const auto flags = unicode_cpt_flags(cpt);
  625. if (flags.is_whitespace) {
  626. if (words.back().size()) { // finish previous word if any
  627. words.emplace_back();
  628. }
  629. continue;
  630. }
  631. assert (!flags.is_separator);
  632. if (cpt == 0 || cpt == 0xFFFD || flags.is_control) {
  633. continue;
  634. }
  635. const std::string s = unicode_cpt_to_utf8(unicode_tolower(cpt));
  636. if (flags.is_punctuation || ( cpt < 0x7F && flags.is_symbol ) || is_chinese_char(cpt)) {
  637. if (words.back().size()) { // finish previous word if any
  638. words.emplace_back();
  639. }
  640. words.back() = s; // single char word
  641. words.emplace_back(); // start a new word
  642. } else {
  643. words.back() += s; // append char to word
  644. }
  645. }
  646. if (!words.back().size()) {
  647. words.pop_back();
  648. }
  649. return words;
  650. }
  651. static bool is_chinese_char(uint32_t cpt) {
  652. return
  653. (cpt >= 0x04E00 && cpt <= 0x09FFF) ||
  654. (cpt >= 0x03400 && cpt <= 0x04DBF) ||
  655. (cpt >= 0x20000 && cpt <= 0x2A6DF) ||
  656. (cpt >= 0x2A700 && cpt <= 0x2B73F) ||
  657. (cpt >= 0x2B740 && cpt <= 0x2B81F) ||
  658. (cpt >= 0x2B920 && cpt <= 0x2CEAF) || // this should be 0x2B820 but in hf rust code it is 0x2B920
  659. (cpt >= 0x0F900 && cpt <= 0x0FAFF) ||
  660. (cpt >= 0x2F800 && cpt <= 0x2FA1F);
  661. //(cpt >= 0x3000 && cpt <= 0x303F) ||
  662. //(cpt >= 0xFF00 && cpt <= 0xFFEF);
  663. }
  664. const llama_vocab & vocab;
  665. };
  666. //
  667. // UGM tokenizer
  668. //
  669. struct llm_tokenizer_ugm {
  670. llm_tokenizer_ugm(const llama_vocab & vocab) : vocab(vocab) {
  671. if (vocab.precompiled_charsmap.size() > 0) {
  672. size_t charsmap_offset = 0;
  673. // First four bytes of precompiled_charsmap contains length of binary
  674. // blob containing XOR-compressed compact double array (XCDA) entries
  675. uint32_t xcda_blob_size = *(const uint32_t *) &vocab.precompiled_charsmap[0];
  676. charsmap_offset += sizeof(xcda_blob_size);
  677. if (xcda_blob_size + charsmap_offset >= vocab.precompiled_charsmap.size()) {
  678. throw std::runtime_error("Index out of array bounds in precompiled charsmap!");
  679. }
  680. // Next xcda_blob_size bytes contain entries of XOR-compressed compact
  681. // double array (XCDA). Each entry is bit-packed into a 32-bit integer.
  682. xcda_array = (const uint32_t *) &vocab.precompiled_charsmap[charsmap_offset];
  683. xcda_array_size = xcda_blob_size / sizeof(uint32_t);
  684. charsmap_offset += xcda_blob_size;
  685. // Remaining bytes of precompiled charsmap contain null-terminated
  686. // replacement strings for prefixes matched by the XCDA.
  687. prefix_replacements = &vocab.precompiled_charsmap[charsmap_offset];
  688. prefix_replacements_size = vocab.precompiled_charsmap.size() - charsmap_offset;
  689. }
  690. for (unsigned int id = 0; id < vocab.id_to_token.size(); ++id) {
  691. const auto &token_data = vocab.id_to_token[id];
  692. if (llama_is_normal_token(vocab, id)) {
  693. min_score = std::min<float>(min_score, token_data.score);
  694. max_score = std::max<float>(max_score, token_data.score);
  695. }
  696. if (llama_is_normal_token(vocab, id) ||
  697. llama_is_user_defined_token(vocab, id) ||
  698. llama_is_unused_token(vocab, id)) {
  699. token_matcher.insert(token_data.text.data(), token_data.text.size(), id);
  700. }
  701. if (llama_is_user_defined_token(vocab, id)) {
  702. user_defined_token_matcher.insert(token_data.text.data(), token_data.text.size());
  703. }
  704. }
  705. unknown_token_score = min_score - unknown_token_score_penalty;
  706. }
  707. /* This implementation is based on SentencePiece optimized Viterbi algorithm for
  708. * unigram language models. The general idea is to:
  709. * - move along the input sequence in steps of one UTF code point,
  710. * - at each step find all possible tokenizations of the prefix by
  711. * traversing the tokens trie,
  712. * - for each tokenization store the best one so far (by higher score)
  713. * - use the position in sequence after given token as an index to store
  714. * results
  715. * - if there was no valid tokenization of the current UTF code point
  716. * then use unknown token with additional score penalty
  717. * After processing the whole sequence we backtrack from the end to get
  718. * the best tokenization.
  719. */
  720. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  721. // get current size of output (for reversal later)
  722. size_t output_size = output.size();
  723. // normalize the input first
  724. std::string normalized;
  725. normalize(text, &normalized);
  726. size_t input_len = normalized.size();
  727. if (input_len == 0) {
  728. return;
  729. }
  730. // initialize score_sum to -FLT_MAX so it will be always lower than sums of token scores
  731. std::vector<struct best_tokenization> tokenization_results(input_len + 1, {vocab.special_unk_id, 0, -FLT_MAX});
  732. // at the beginning tokenization score is zero
  733. tokenization_results[0] = { vocab.special_unk_id, 0, 0 };
  734. for (size_t input_offset = 0; input_offset < input_len;) {
  735. size_t prefix_offset = input_offset;
  736. // calculate how many code units are in the currently processed UTF code point
  737. size_t n_utf8_code_units = std::min<size_t>(unicode_len_utf8(normalized[input_offset]), input_len - input_offset);
  738. // traverse the token matcher trie to find a matching token
  739. bool single_codepoint_token_found = false;
  740. const struct best_tokenization & current_best = tokenization_results[input_offset];
  741. const struct naive_trie * node = token_matcher.traverse(normalized[prefix_offset++]);
  742. while (prefix_offset <= input_len && node != NULL) {
  743. // check if we found valid token in prefix
  744. if (node->has_value) {
  745. // check if it corresponds to the whole UTF code point
  746. if (prefix_offset - input_offset == n_utf8_code_units) {
  747. single_codepoint_token_found = true;
  748. }
  749. llama_token token_id = node->value;
  750. const auto & token_data = vocab.id_to_token[token_id];
  751. // we set the user-defined token scores to 0 to make them more likely to be selected
  752. // (normal token scores are log probabilities, so they are negative)
  753. // score type is double here to make tokenization results exactly
  754. // the same as in the HF tokenizer using SentencePiece
  755. const double token_score = llama_is_user_defined_token(vocab, token_id) ? 0.0 : token_data.score;
  756. const double challenger_score = current_best.score_sum + token_score;
  757. struct best_tokenization & current_champ = tokenization_results[prefix_offset];
  758. if (challenger_score > current_champ.score_sum) {
  759. struct best_tokenization challenger = { token_id, input_offset, (float) challenger_score };
  760. current_champ = challenger;
  761. }
  762. }
  763. node = node->traverse(normalized[prefix_offset++]);
  764. }
  765. // if we didn't find a valid token corresponding to the whole UTF code point
  766. // then use unknown token as the tokenization of this UTF code point
  767. if (!single_codepoint_token_found) {
  768. const double challenger_score = current_best.score_sum + unknown_token_score;
  769. prefix_offset = input_offset + n_utf8_code_units;
  770. struct best_tokenization & current_champ = tokenization_results[prefix_offset];
  771. if (challenger_score > current_champ.score_sum) {
  772. struct best_tokenization challenger = { vocab.special_unk_id, input_offset, (float) challenger_score };
  773. current_champ = challenger;
  774. }
  775. }
  776. // move to the next UTF code point
  777. input_offset += n_utf8_code_units;
  778. }
  779. // now backtrack from the end to gather token ids of the best tokenization
  780. // merge sequences of consecutive unknown tokens into single unknown tokens
  781. bool is_prev_unknown = false;
  782. for (struct best_tokenization & tokenization = tokenization_results[input_len]; ; tokenization = tokenization_results[tokenization.input_offset]) {
  783. bool is_unknown = tokenization.token_id == vocab.special_unk_id;
  784. if (!(is_prev_unknown && is_unknown)) {
  785. output.push_back(tokenization.token_id);
  786. }
  787. if (tokenization.input_offset == 0) {
  788. break;
  789. }
  790. is_prev_unknown = is_unknown;
  791. }
  792. // reverse the output since we added tokens starting from the end of the input
  793. std::reverse(output.begin() + output_size, output.end());
  794. }
  795. private:
  796. const llama_vocab & vocab;
  797. // helper structure for returning normalization results
  798. struct normalization_result {
  799. const char * normalized;
  800. size_t normalized_len;
  801. size_t consumed_input;
  802. };
  803. void normalize(const std::string& input, std::string * normalized) {
  804. normalized->clear();
  805. normalized->reserve(input.size() * 3);
  806. const std::string space = vocab.tokenizer_escape_whitespaces ? escaped_space : " ";
  807. bool shall_prepend_space = !vocab.tokenizer_treat_whitespace_as_suffix && vocab.tokenizer_add_space_prefix;
  808. bool shall_append_space = vocab.tokenizer_treat_whitespace_as_suffix && vocab.tokenizer_add_space_prefix;
  809. bool shall_merge_spaces = vocab.tokenizer_remove_extra_whitespaces;
  810. bool is_space_prepended = false;
  811. bool processing_non_ws = false;
  812. size_t input_len = input.size();
  813. for (size_t input_offset = 0; input_offset < input_len; ) {
  814. auto norm_res = normalize_prefix(input, input_offset);
  815. for (size_t i = 0; i < norm_res.normalized_len; i++) {
  816. char c = norm_res.normalized[i];
  817. if (c != ' ') {
  818. if (!processing_non_ws) {
  819. processing_non_ws = true;
  820. if ((shall_prepend_space && !is_space_prepended) || shall_merge_spaces) {
  821. normalized->append(space);
  822. is_space_prepended = true;
  823. }
  824. }
  825. normalized->push_back(c);
  826. } else {
  827. if (processing_non_ws) {
  828. processing_non_ws = false;
  829. }
  830. if (!shall_merge_spaces) {
  831. normalized->append(space);
  832. }
  833. }
  834. }
  835. input_offset += norm_res.consumed_input;
  836. }
  837. if (shall_append_space) {
  838. normalized->append(space);
  839. }
  840. }
  841. /*
  842. * This structure is a view wrapper for XOR-compressed double array (XCDA)
  843. * See Shunsuke Kanda (2018). Space- and Time-Efficient String Dictionaries.
  844. * Each bit-packed entry contains:
  845. * - BASE array value in bits 10-30
  846. * - LCHECK array value in bits 0-7
  847. * - LEAF array value in bit 9
  848. * Entries containing indexes of replacement sequences have set bit 31
  849. */
  850. struct xcda_array_view {
  851. public:
  852. xcda_array_view(const uint32_t * xcda_array, size_t xcda_array_size) : xcda_array(xcda_array), xcda_array_size(xcda_array_size) {
  853. }
  854. uint32_t get_base(size_t index) {
  855. uint32_t packed_node = get_node(index);
  856. return (packed_node >> 10) << ((packed_node & (1U << 9)) >> 6);
  857. }
  858. uint32_t get_lcheck(size_t index) {
  859. uint32_t packed_node = get_node(index);
  860. return packed_node & ((1U << 31) | 0xff);
  861. }
  862. bool get_leaf(size_t index) {
  863. uint32_t packed_node = get_node(index);
  864. return (packed_node >> 8) & 1;
  865. }
  866. uint32_t get_value(size_t index) {
  867. uint32_t packed_node = get_node(index);
  868. return packed_node & ((1U << 31) - 1);
  869. }
  870. private:
  871. uint32_t get_node(size_t index) {
  872. if (index > xcda_array_size) {
  873. throw std::runtime_error("Index out of array bounds in XCDA array!");
  874. }
  875. return xcda_array[index];
  876. }
  877. const uint32_t * xcda_array;
  878. size_t xcda_array_size;
  879. };
  880. struct normalization_result normalize_prefix(const std::string & input, size_t input_offset) {
  881. if (input_offset == input.size()) {
  882. return { &input[input_offset], 0, 0 };
  883. }
  884. // if input prefix matches some user-defined token return this token as normalization result
  885. auto user_defined_token_match = user_defined_token_matcher.get_longest_prefix(&input[input_offset], input.size() - input_offset);
  886. if (user_defined_token_match.second > 0) {
  887. return { &input[input_offset], user_defined_token_match.second, user_defined_token_match.second };
  888. }
  889. size_t longest_prefix_length = 0;
  890. size_t longest_prefix_offset = 0;
  891. if (xcda_array_size > 0) {
  892. struct xcda_array_view xcda_view(xcda_array, xcda_array_size);
  893. // Find the longest normalized sequence matching the input prefix by walking
  894. // the XOR-compressed compact double array (XCDA) starting from the root node
  895. // We find the index of the next node by calculating BASE[s] ^ c where s is
  896. // the index of the previous node and c is a numerical character value
  897. uint32_t node_index = 0;
  898. // get BASE of the root node
  899. node_index = xcda_view.get_base(node_index);
  900. for (size_t prefix_offset = input_offset; prefix_offset < input.size(); prefix_offset++) {
  901. unsigned char c = input[prefix_offset];
  902. if (c == 0) {
  903. break;
  904. }
  905. node_index ^= c;
  906. // if value of LCHECK is not c it means that this is not a child of
  907. // the previous node, so we stop matching
  908. if (xcda_view.get_lcheck(node_index) != c) {
  909. break;
  910. }
  911. bool is_leaf = xcda_view.get_leaf(node_index);
  912. // get BASE of the current node
  913. node_index ^= xcda_view.get_base(node_index);
  914. // if LEAF of the current node is true, it means that its BASE points to the node
  915. // containing index of replacement sequence for currently matched input prefix
  916. if (is_leaf)
  917. {
  918. longest_prefix_length = prefix_offset - input_offset + 1;
  919. // get index of replacement sequence for currently matched input prefix
  920. longest_prefix_offset = xcda_view.get_value(node_index);
  921. }
  922. }
  923. }
  924. if (longest_prefix_length > 0) {
  925. // we have a match, so return the replacement sequence
  926. if (longest_prefix_offset >= prefix_replacements_size) {
  927. throw std::runtime_error("Index out of array bounds in precompiled charsmap!");
  928. }
  929. const char * prefix_replacement = &prefix_replacements[longest_prefix_offset];
  930. return { prefix_replacement, strlen(prefix_replacement), longest_prefix_length };
  931. } else {
  932. // check if the input prefix contains a valid sequence of UTF-8 code units
  933. try {
  934. // if yes, return this sequence unmodified
  935. size_t prefix_offset = input_offset;
  936. unicode_cpt_from_utf8(input, prefix_offset);
  937. return { &input[input_offset], prefix_offset - input_offset, prefix_offset - input_offset };
  938. } catch (std::invalid_argument & /*ex*/) {
  939. // if no, consume 1 byte and return U+FFFD - REPLACEMENT CHARACTER
  940. return { "\xEF\xBF\xBD", 3, 1 };
  941. }
  942. }
  943. }
  944. // escaped space symbol - U+2581 (Lower One Eighth Block)
  945. const std::string escaped_space = "\xE2\x96\x81";
  946. const char * prefix_replacements = NULL;
  947. size_t prefix_replacements_size = 0;
  948. const uint32_t * xcda_array = NULL;
  949. size_t xcda_array_size = 0;
  950. struct naive_trie user_defined_token_matcher;
  951. // this structure stores the best tokenization so far at input_offset
  952. struct best_tokenization {
  953. llama_token token_id;
  954. size_t input_offset;
  955. float score_sum;
  956. };
  957. float min_score = FLT_MAX;
  958. float max_score = -FLT_MAX;
  959. float unknown_token_score_penalty = 10.0;
  960. float unknown_token_score;
  961. struct naive_trie token_matcher;
  962. };
  963. //
  964. // RWKV tokenizer
  965. //
  966. static std::vector<uint8_t> llama_unescape_rwkv_token(const std::string & escaped) {
  967. std::vector<uint8_t> output;
  968. output.reserve(escaped.size());
  969. // Parser state
  970. bool escaping = false;
  971. uint8_t hex_remaining = 0;
  972. uint8_t hex_acc = 0;
  973. // Step through characters, performing parsing
  974. for (const char & c : escaped) {
  975. // If we're parsing a hex code, interpret the next character
  976. if (hex_remaining != 0) {
  977. uint8_t value = (c >= 'a') ? (c - 'a' + 10) : (c - '0');
  978. hex_acc = (hex_acc << 4) + value;
  979. hex_remaining -= 1;
  980. if (hex_remaining == 0) {
  981. output.push_back(hex_acc);
  982. hex_acc = 0;
  983. }
  984. continue;
  985. }
  986. // If we got an escape character, interpret it
  987. if (escaping) {
  988. if (c == 't') {
  989. output.push_back('\t');
  990. } else if (c == 'n') {
  991. output.push_back('\n');
  992. } else if (c == 'r') {
  993. output.push_back('\r');
  994. } else if (c == 'x') {
  995. hex_remaining = 2;
  996. } else {
  997. output.push_back(c);
  998. }
  999. escaping = false;
  1000. continue;
  1001. }
  1002. if (c == '\\') {
  1003. escaping = true;
  1004. continue;
  1005. }
  1006. output.push_back(c);
  1007. }
  1008. return output;
  1009. }
  1010. struct llm_tokenizer_rwkv {
  1011. llm_tokenizer_rwkv(const llama_vocab & vocab): vocab(vocab) {
  1012. // RWKV supports arbitrary byte tokens, but the vocab struct only supports string tokens.
  1013. // For now, we decode the vocab here into the lookup we'll use for tokenization.
  1014. // build trie
  1015. for (unsigned int id = 0; id < vocab.id_to_token.size(); ++id) {
  1016. const auto & token = vocab.id_to_token[id];
  1017. const auto data = llama_unescape_rwkv_token(token.text);
  1018. token_matcher.insert((const char *) data.data(), data.size(), id);
  1019. }
  1020. }
  1021. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  1022. uint32_t position = 0;
  1023. while (position < text.size()) {
  1024. const struct naive_trie * node = token_matcher.traverse(text[position]);
  1025. if (node == NULL) {
  1026. // no matching token found, add unknown token
  1027. output.push_back(vocab.special_unk_id);
  1028. position += 1;
  1029. continue;
  1030. }
  1031. // traverse the trie to find the longest matching token
  1032. uint32_t token_id = 0;
  1033. uint32_t token_length = 0;
  1034. while (node != NULL) {
  1035. if (node->has_value) {
  1036. token_id = node->value;
  1037. token_length = position + 1;
  1038. }
  1039. node = node->traverse(text[++position]);
  1040. }
  1041. // add the longest matching token
  1042. output.push_back(token_id);
  1043. position = token_length;
  1044. }
  1045. }
  1046. const llama_vocab & vocab;
  1047. struct naive_trie token_matcher;
  1048. };
  1049. //
  1050. // (de-) tokenize
  1051. //
  1052. typedef enum FRAGMENT_BUFFER_VARIANT_TYPE {
  1053. FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN,
  1054. FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT
  1055. } FRAGMENT_BUFFER_VARIANT_TYPE;
  1056. struct fragment_buffer_variant {
  1057. fragment_buffer_variant(llama_vocab::id _token)
  1058. :
  1059. type(FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN),
  1060. token(_token),
  1061. raw_text(_dummy),
  1062. offset(0),
  1063. length(0) {}
  1064. fragment_buffer_variant(const std::string & _raw_text, int64_t _offset, int64_t _length)
  1065. :
  1066. type(FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT),
  1067. token((llama_vocab::id) - 1),
  1068. raw_text(_raw_text),
  1069. offset(_offset),
  1070. length(_length){
  1071. GGML_ASSERT(_offset >= 0);
  1072. GGML_ASSERT(_length >= 1);
  1073. GGML_ASSERT(offset + length <= raw_text.length());
  1074. }
  1075. const FRAGMENT_BUFFER_VARIANT_TYPE type;
  1076. const llama_vocab::id token;
  1077. const std::string _dummy;
  1078. const std::string & raw_text;
  1079. const uint64_t offset;
  1080. const uint64_t length;
  1081. };
  1082. // #define PRETOKENIZERDEBUG
  1083. static void tokenizer_st_partition(const llama_vocab & vocab, std::forward_list<fragment_buffer_variant> & buffer, bool parse_special) {
  1084. // for each special token
  1085. for (const llama_vocab::id special_id : vocab.cache_special_tokens) {
  1086. const auto & data = vocab.id_to_token[special_id];
  1087. const auto & special_token = data.text;
  1088. if (!parse_special && (data.attr & (LLAMA_TOKEN_ATTR_CONTROL | LLAMA_TOKEN_ATTR_UNKNOWN))) {
  1089. // Ignore control and unknown tokens when parse_special == false
  1090. continue;
  1091. // User-defined tokens are still pre-tokenized before everything else
  1092. // ref: https://github.com/huggingface/tokenizers/blob/fdd26ba9a3f0c133427aab0423888cbde91362d7/tokenizers/src/tokenizer/mod.rs#L726
  1093. // This is mostly relevant for neox-style tokenizers (mpt, olmo, stablelm, etc.)
  1094. }
  1095. // for each text fragment
  1096. std::forward_list<fragment_buffer_variant>::iterator it = buffer.begin();
  1097. while (it != buffer.end()) {
  1098. auto & fragment = (*it);
  1099. // if a fragment is text ( not yet processed )
  1100. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  1101. auto & raw_text = fragment.raw_text;
  1102. auto raw_text_base_offset = fragment.offset;
  1103. auto raw_text_base_length = fragment.length;
  1104. // loop over the text
  1105. while (true) {
  1106. // find the first occurrence of a given special token in this fragment
  1107. // passing offset argument only limit the "search area" but match coordinates
  1108. // are still relative to the source full raw_text
  1109. auto match = raw_text.find(special_token, raw_text_base_offset);
  1110. // no occurrences found, stop processing this fragment for a given special token
  1111. if (match == std::string::npos) break;
  1112. // check if match is within bounds of offset <-> length
  1113. if (match + special_token.length() > raw_text_base_offset + raw_text_base_length) break;
  1114. #ifdef PRETOKENIZERDEBUG
  1115. LLAMA_LOG_WARN("FF: (%ld %ld %ld) '%s'\n", raw_text->length(), raw_text_base_offset, raw_text_base_length, raw_text->substr(raw_text_base_offset, raw_text_base_length).c_str());
  1116. #endif
  1117. auto source = std::distance(buffer.begin(), it);
  1118. // if match is further than base offset
  1119. // then we have some text to the left of it
  1120. if (match > raw_text_base_offset) {
  1121. // left
  1122. const int64_t left_reminder_offset = raw_text_base_offset + 0;
  1123. int64_t left_reminder_length = match - raw_text_base_offset;
  1124. if (data.attr & LLAMA_TOKEN_ATTR_LSTRIP) {
  1125. while (left_reminder_length > 0 && isspace(raw_text[left_reminder_offset + left_reminder_length - 1])) {
  1126. left_reminder_length--;
  1127. }
  1128. }
  1129. if (left_reminder_length > 0) {
  1130. buffer.emplace_after(it, raw_text, left_reminder_offset, left_reminder_length);
  1131. it++;
  1132. }
  1133. #ifdef PRETOKENIZERDEBUG
  1134. LLAMA_LOG_WARN("FL: (%ld %ld) '%s'\n", left_reminder_offset, left_reminder_length, raw_text->substr(left_reminder_offset, left_reminder_length).c_str());
  1135. #endif
  1136. }
  1137. // special token
  1138. buffer.emplace_after(it, special_id);
  1139. it++;
  1140. // right
  1141. if (match + special_token.length() < raw_text_base_offset + raw_text_base_length) {
  1142. int64_t right_reminder_offset = match + special_token.length();
  1143. int64_t right_reminder_length = raw_text_base_length - ((match - raw_text_base_offset) + special_token.length());
  1144. if (data.attr & LLAMA_TOKEN_ATTR_RSTRIP) {
  1145. while (right_reminder_length > 0 && isspace(raw_text[right_reminder_offset])) {
  1146. right_reminder_offset++;
  1147. right_reminder_length--;
  1148. }
  1149. }
  1150. if (right_reminder_length > 0) {
  1151. buffer.emplace_after(it, raw_text, right_reminder_offset, right_reminder_length);
  1152. it++;
  1153. }
  1154. #ifdef PRETOKENIZERDEBUG
  1155. LLAMA_LOG_WARN("FR: (%ld %ld) '%s'\n", right_reminder_offset, right_reminder_length, raw_text->substr(right_reminder_offset, right_reminder_length).c_str());
  1156. #endif
  1157. if (source == 0) {
  1158. buffer.erase_after(buffer.before_begin());
  1159. } else {
  1160. buffer.erase_after(std::next(buffer.begin(), (source-1)));
  1161. }
  1162. // repeat for the right side
  1163. raw_text_base_offset = right_reminder_offset;
  1164. raw_text_base_length = right_reminder_length;
  1165. #ifdef PRETOKENIZERDEBUG
  1166. LLAMA_LOG_WARN("RR: (%ld %ld) '%s'\n", raw_text_base_offset, raw_text_base_length, raw_text->substr(raw_text_base_offset, raw_text_base_length).c_str());
  1167. #endif
  1168. } else {
  1169. if (source == 0) {
  1170. buffer.erase_after(buffer.before_begin());
  1171. } else {
  1172. buffer.erase_after(std::next(buffer.begin(), (source-1)));
  1173. }
  1174. break;
  1175. }
  1176. }
  1177. }
  1178. it++;
  1179. }
  1180. }
  1181. }
  1182. std::vector<llama_vocab::id> llama_tokenize_internal(const llama_vocab & vocab, std::string raw_text, bool add_special, bool parse_special) {
  1183. std::vector<llama_vocab::id> output;
  1184. std::forward_list<fragment_buffer_variant> fragment_buffer;
  1185. if (!raw_text.empty()) {
  1186. fragment_buffer.emplace_front(raw_text, 0, raw_text.length());
  1187. tokenizer_st_partition(vocab, fragment_buffer, parse_special);
  1188. }
  1189. switch (vocab.type) {
  1190. case LLAMA_VOCAB_TYPE_SPM:
  1191. {
  1192. // OG tokenizer behavior:
  1193. //
  1194. // tokenizer.encode('', add_special_tokens=True) returns [1]
  1195. // tokenizer.encode('', add_special_tokens=False) returns []
  1196. bool is_prev_special = true; // prefix with space if first token
  1197. if (add_special && vocab.tokenizer_add_bos) {
  1198. GGML_ASSERT(vocab.special_bos_id != -1);
  1199. output.push_back(vocab.special_bos_id);
  1200. is_prev_special = true;
  1201. }
  1202. for (const auto & fragment : fragment_buffer) {
  1203. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  1204. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  1205. // prefix with space if previous is special
  1206. if (vocab.tokenizer_add_space_prefix && is_prev_special) {
  1207. raw_text = " " + raw_text;
  1208. }
  1209. #ifdef PRETOKENIZERDEBUG
  1210. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  1211. #endif
  1212. llm_tokenizer_spm tokenizer(vocab);
  1213. llama_escape_whitespace(raw_text);
  1214. tokenizer.tokenize(raw_text, output);
  1215. is_prev_special = false;
  1216. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  1217. output.push_back(fragment.token);
  1218. is_prev_special = true;
  1219. }
  1220. }
  1221. if (add_special && vocab.tokenizer_add_bos && output.size() >= 2 && output[1] == vocab.special_bos_id) {
  1222. LLAMA_LOG_WARN(
  1223. "%s: Added a BOS token to the prompt as specified by the model but the prompt "
  1224. "also starts with a BOS token. So now the final prompt starts with 2 BOS tokens. "
  1225. "Are you sure this is what you want?\n", __FUNCTION__);
  1226. }
  1227. if (add_special && vocab.tokenizer_add_eos) {
  1228. GGML_ASSERT(vocab.special_eos_id != -1);
  1229. output.push_back(vocab.special_eos_id);
  1230. }
  1231. } break;
  1232. case LLAMA_VOCAB_TYPE_BPE:
  1233. {
  1234. llm_tokenizer_bpe tokenizer(vocab);
  1235. if (add_special) {
  1236. tokenizer.append_bos(output);
  1237. }
  1238. for (const auto & fragment : fragment_buffer) {
  1239. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  1240. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  1241. #ifdef PRETOKENIZERDEBUG
  1242. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  1243. #endif
  1244. tokenizer.tokenize(raw_text, output);
  1245. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  1246. tokenizer.append(fragment.token, output);
  1247. }
  1248. }
  1249. if (add_special) {
  1250. tokenizer.append_eos(output);
  1251. tokenizer.check_double_bos_eos(output);
  1252. }
  1253. } break;
  1254. case LLAMA_VOCAB_TYPE_WPM:
  1255. {
  1256. if (add_special) {
  1257. GGML_ASSERT(vocab.special_cls_id != -1);
  1258. output.push_back(vocab.special_cls_id);
  1259. }
  1260. llm_tokenizer_wpm tokenizer(vocab);
  1261. for (const auto & fragment : fragment_buffer) {
  1262. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  1263. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  1264. #ifdef PRETOKENIZERDEBUG
  1265. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  1266. #endif
  1267. tokenizer.tokenize(raw_text, output);
  1268. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  1269. output.push_back(fragment.token);
  1270. }
  1271. }
  1272. if (add_special) {
  1273. GGML_ASSERT(vocab.special_sep_id != -1);
  1274. output.push_back(vocab.special_sep_id);
  1275. }
  1276. } break;
  1277. case LLAMA_VOCAB_TYPE_UGM:
  1278. {
  1279. llm_tokenizer_ugm tokenizer(vocab);
  1280. if (add_special && vocab.tokenizer_add_bos != 0) {
  1281. GGML_ASSERT(vocab.special_bos_id != -1);
  1282. output.push_back(vocab.special_bos_id);
  1283. }
  1284. for (const auto & fragment : fragment_buffer) {
  1285. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  1286. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  1287. #ifdef PRETOKENIZERDEBUG
  1288. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  1289. #endif
  1290. tokenizer.tokenize(raw_text, output);
  1291. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  1292. output.push_back(fragment.token);
  1293. }
  1294. }
  1295. if (add_special && vocab.tokenizer_add_bos != 0 && output.size() >= 2 && output[1] == vocab.special_bos_id) {
  1296. LLAMA_LOG_WARN(
  1297. "%s: Added a BOS token to the prompt as specified by the model but the prompt "
  1298. "also starts with a BOS token. So now the final prompt starts with 2 BOS tokens. "
  1299. "Are you sure this is what you want?\n", __FUNCTION__);
  1300. }
  1301. if (add_special && vocab.tokenizer_add_eos == 1) {
  1302. GGML_ASSERT(vocab.special_eos_id != -1);
  1303. output.push_back(vocab.special_eos_id);
  1304. }
  1305. } break;
  1306. case LLAMA_VOCAB_TYPE_RWKV:
  1307. {
  1308. for (const auto & fragment : fragment_buffer) {
  1309. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  1310. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  1311. #ifdef PRETOKENIZERDEBUG
  1312. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  1313. #endif
  1314. llm_tokenizer_rwkv tokenizer(vocab);
  1315. tokenizer.tokenize(raw_text, output);
  1316. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  1317. output.push_back(fragment.token);
  1318. }
  1319. }
  1320. } break;
  1321. case LLAMA_VOCAB_TYPE_NONE:
  1322. GGML_ABORT("fatal error");
  1323. }
  1324. return output;
  1325. }
  1326. llama_token llama_byte_to_token_impl(const llama_vocab & vocab, uint8_t ch) {
  1327. GGML_ASSERT(llama_vocab_get_type(vocab) != LLAMA_VOCAB_TYPE_NONE);
  1328. static const char * hex = "0123456789ABCDEF";
  1329. switch (llama_vocab_get_type(vocab)) {
  1330. case LLAMA_VOCAB_TYPE_SPM:
  1331. case LLAMA_VOCAB_TYPE_UGM: {
  1332. const char buf[7] = { '<', '0', 'x', hex[ch >> 4], hex[ch & 15], '>', 0 };
  1333. auto token = vocab.token_to_id.find(buf);
  1334. if (token != vocab.token_to_id.end()) {
  1335. return (*token).second;
  1336. }
  1337. // Try to fall back to just the byte as a string
  1338. const char buf2[2] = { (char)ch, 0 };
  1339. return vocab.token_to_id.at(buf2);
  1340. }
  1341. case LLAMA_VOCAB_TYPE_WPM:
  1342. case LLAMA_VOCAB_TYPE_BPE: {
  1343. return vocab.token_to_id.at(unicode_byte_to_utf8(ch));
  1344. }
  1345. default:
  1346. GGML_ABORT("fatal error");
  1347. }
  1348. }
  1349. const char * llama_token_get_text_impl(const struct llama_vocab & vocab, llama_token token) {
  1350. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  1351. return vocab.id_to_token[token].text.c_str();
  1352. }
  1353. float llama_token_get_score_impl(const struct llama_vocab & vocab, llama_token token) {
  1354. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  1355. return vocab.id_to_token[token].score;
  1356. }
  1357. llama_token_attr llama_token_get_attr_impl(const struct llama_vocab & vocab, llama_token token) {
  1358. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  1359. return vocab.id_to_token[token].attr;
  1360. }
  1361. bool llama_token_is_eog_impl(const struct llama_vocab & vocab, llama_token token) {
  1362. return token != -1 && (
  1363. token == llama_token_eos_impl(vocab) ||
  1364. token == llama_token_eot_impl(vocab) ||
  1365. token == llama_token_eom_impl(vocab)
  1366. );
  1367. }
  1368. bool llama_token_is_control_impl(const struct llama_vocab & vocab, llama_token token) {
  1369. return llama_is_control_token(vocab, token);
  1370. }
  1371. llama_token llama_token_bos_impl(const struct llama_vocab & vocab) {
  1372. return vocab.special_bos_id;
  1373. }
  1374. llama_token llama_token_eos_impl(const struct llama_vocab & vocab) {
  1375. return vocab.special_eos_id;
  1376. }
  1377. llama_token llama_token_cls_impl(const struct llama_vocab & vocab) {
  1378. return vocab.special_cls_id;
  1379. }
  1380. llama_token llama_token_sep_impl(const struct llama_vocab & vocab) {
  1381. return vocab.special_sep_id;
  1382. }
  1383. llama_token llama_token_nl_impl(const struct llama_vocab & vocab) {
  1384. return vocab.linefeed_id;
  1385. }
  1386. llama_token llama_token_pad_impl(const struct llama_vocab & vocab) {
  1387. return vocab.special_pad_id;
  1388. }
  1389. bool llama_add_bos_token_impl(const struct llama_vocab & vocab) {
  1390. return vocab.tokenizer_add_bos;
  1391. }
  1392. bool llama_add_eos_token_impl(const struct llama_vocab & vocab) {
  1393. return vocab.tokenizer_add_eos;
  1394. }
  1395. llama_token llama_token_prefix_impl(const struct llama_vocab & vocab) {
  1396. return vocab.special_prefix_id;
  1397. }
  1398. llama_token llama_token_middle_impl(const struct llama_vocab & vocab) {
  1399. return vocab.special_middle_id;
  1400. }
  1401. llama_token llama_token_suffix_impl(const struct llama_vocab & vocab) {
  1402. return vocab.special_suffix_id;
  1403. }
  1404. llama_token llama_token_eot_impl(const struct llama_vocab & vocab) {
  1405. return vocab.special_eot_id;
  1406. }
  1407. llama_token llama_token_eom_impl(const struct llama_vocab & vocab) {
  1408. return vocab.special_eom_id;
  1409. }
  1410. int32_t llama_tokenize_impl(
  1411. const struct llama_vocab & vocab,
  1412. const char * text,
  1413. int32_t text_len,
  1414. llama_token * tokens,
  1415. int32_t n_tokens_max,
  1416. bool add_special,
  1417. bool parse_special) {
  1418. auto res = llama_tokenize_internal(vocab, std::string(text, text_len), add_special, parse_special);
  1419. if (n_tokens_max < (int) res.size()) {
  1420. // LLAMA_LOG_ERROR("%s: too many tokens\n", __func__);
  1421. return -((int) res.size());
  1422. }
  1423. for (size_t i = 0; i < res.size(); i++) {
  1424. tokens[i] = res[i];
  1425. }
  1426. return res.size();
  1427. }
  1428. static std::string llama_decode_text(const std::string & text) {
  1429. std::string decoded_text;
  1430. const auto cpts = unicode_cpts_from_utf8(text);
  1431. for (const auto cpt : cpts) {
  1432. const auto utf8 = unicode_cpt_to_utf8(cpt);
  1433. try {
  1434. decoded_text += unicode_utf8_to_byte(utf8);
  1435. } catch (const std::out_of_range & /*e*/) {
  1436. decoded_text += "[UNK_BYTE_0x";
  1437. for (const auto c : utf8) {
  1438. decoded_text += format("%02x", (uint8_t) c);
  1439. }
  1440. decoded_text += text + "]";
  1441. }
  1442. }
  1443. return decoded_text;
  1444. }
  1445. // does not write null-terminator to buf
  1446. int32_t llama_token_to_piece_impl(const struct llama_vocab & vocab, llama_token token, char * buf, int32_t length, int32_t lstrip, bool special) {
  1447. // ref: https://github.com/ggerganov/llama.cpp/pull/7587#discussion_r1620983843
  1448. static const int attr_special = LLAMA_TOKEN_ATTR_UNKNOWN | LLAMA_TOKEN_ATTR_CONTROL;
  1449. const llama_token_attr attr = llama_token_get_attr_impl(vocab, token);
  1450. if (!special && (attr & attr_special)) {
  1451. return 0;
  1452. }
  1453. // copy piece chars to output text buffer
  1454. // skip up to 'lstrip' leading spaces before copying
  1455. auto _try_copy = [=] (const char * token, size_t size) -> int32_t {
  1456. for (int32_t i = 0; i < lstrip && size && *token == ' '; ++i) {
  1457. token++;
  1458. size--;
  1459. }
  1460. if (length < (int32_t)size) {
  1461. return -(int32_t) size;
  1462. }
  1463. memcpy(buf, token, size);
  1464. return (int32_t) size;
  1465. };
  1466. // if we have a cache - use it
  1467. {
  1468. const auto & cache = vocab.cache_token_to_piece;
  1469. if (!cache.empty()) {
  1470. const auto & result = cache.at(token);
  1471. return _try_copy(result.data(), result.size());
  1472. }
  1473. }
  1474. if (0 <= token && token < (int32_t) vocab.id_to_token.size()) {
  1475. const std::string & token_text = vocab.id_to_token[token].text;
  1476. switch (llama_vocab_get_type(vocab)) {
  1477. case LLAMA_VOCAB_TYPE_WPM:
  1478. case LLAMA_VOCAB_TYPE_SPM:
  1479. case LLAMA_VOCAB_TYPE_UGM: {
  1480. // NOTE: we accept all unsupported token types,
  1481. // suppressing them like CONTROL tokens.
  1482. if (attr & (attr_special | LLAMA_TOKEN_ATTR_USER_DEFINED)) {
  1483. return _try_copy(token_text.data(), token_text.size());
  1484. } else if (attr & LLAMA_TOKEN_ATTR_NORMAL) {
  1485. std::string result = token_text;
  1486. llama_unescape_whitespace(result);
  1487. return _try_copy(result.data(), result.size());
  1488. } else if (attr & LLAMA_TOKEN_ATTR_BYTE) {
  1489. char byte = (char) llama_token_to_byte(vocab, token);
  1490. return _try_copy((char*) &byte, 1);
  1491. }
  1492. break;
  1493. }
  1494. case LLAMA_VOCAB_TYPE_BPE: {
  1495. // NOTE: we accept all unsupported token types,
  1496. // suppressing them like CONTROL tokens.
  1497. if (attr & (attr_special | LLAMA_TOKEN_ATTR_USER_DEFINED)) {
  1498. return _try_copy(token_text.data(), token_text.size());
  1499. } else if (attr & LLAMA_TOKEN_ATTR_NORMAL) {
  1500. std::string result = llama_decode_text(token_text);
  1501. return _try_copy(result.data(), result.size());
  1502. }
  1503. break;
  1504. }
  1505. case LLAMA_VOCAB_TYPE_RWKV: {
  1506. std::vector<uint8_t> result = llama_unescape_rwkv_token(token_text);
  1507. // If we don't have enough space, return an error
  1508. if (result.size() > (size_t)length) {
  1509. return -(int)result.size();
  1510. }
  1511. memcpy(buf, result.data(), result.size());
  1512. return (int)result.size();
  1513. }
  1514. default:
  1515. GGML_ABORT("fatal error");
  1516. }
  1517. }
  1518. return 0;
  1519. }
  1520. int32_t llama_detokenize_impl(
  1521. const struct llama_vocab & vocab,
  1522. const llama_token * tokens,
  1523. int32_t n_tokens,
  1524. char * text,
  1525. int32_t text_len_max,
  1526. bool remove_special,
  1527. bool unparse_special) {
  1528. int32_t avail = text_len_max;
  1529. int32_t total = 0;
  1530. // remove the leading space
  1531. bool remove_space = vocab.tokenizer_add_space_prefix;
  1532. if (remove_special && vocab.tokenizer_add_bos) {
  1533. if (n_tokens > 0 && tokens[0] == vocab.special_bos_id) {
  1534. remove_space = false;
  1535. n_tokens--;
  1536. tokens++;
  1537. }
  1538. }
  1539. if (remove_special && vocab.tokenizer_add_eos) {
  1540. if (n_tokens > 0 && tokens[n_tokens-1] == vocab.special_eos_id) {
  1541. n_tokens--;
  1542. }
  1543. }
  1544. for (int32_t i = 0; i < n_tokens; ++i) {
  1545. GGML_ASSERT(avail >= 0);
  1546. int32_t n_chars = llama_token_to_piece_impl(vocab, tokens[i], text, avail, remove_space, unparse_special);
  1547. remove_space = false;
  1548. if (n_chars < 0) {
  1549. avail = 0;
  1550. total -= n_chars;
  1551. } else if (n_chars > 0) {
  1552. avail -= n_chars;
  1553. text += n_chars;
  1554. total += n_chars;
  1555. }
  1556. }
  1557. if (total > text_len_max) {
  1558. return -total;
  1559. }
  1560. if (vocab.tokenizer_clean_spaces) {
  1561. text -= total; // restart text
  1562. // first pass: characters ?!., //TODO: where do these characters come from?
  1563. const int32_t total1 = total;
  1564. total = total ? 1 : 0;
  1565. for (int32_t i = 1; i < total1; ++i) {
  1566. const char x = text[i];
  1567. if (text[i - 1] == ' ') {
  1568. if (x == '?' || x == '!' || x == '.' || x == ',') { // " ?", " !", " .", " ,"
  1569. total--; // remove space
  1570. }
  1571. }
  1572. text[total++] = x;
  1573. }
  1574. // second pass: strip single apostrophe between spaces
  1575. const int32_t total2 = total;
  1576. total = total ? 1 : 0;
  1577. for (int32_t i = 1; i < total2; ++i) {
  1578. const char x = text[i];
  1579. if (x == '\'' && i + 1 < total2 && text[i - 1] == ' ' && text[i + 1] == ' ') { // " ' "
  1580. total--; // remove prev space
  1581. text[++i] = '\0'; // remove next space
  1582. }
  1583. text[total++] = x;
  1584. }
  1585. // third pass: apostrophe contractions //NOTE: this makes sense?
  1586. const int32_t total3 = total;
  1587. total = total ? 1 : 0;
  1588. for (int32_t i = 1; i < total3; ++i) {
  1589. const char x = text[i];
  1590. if (text[i - 1] == ' ') {
  1591. if (x == '\'' && i + 1 < total3) {
  1592. const char x1 = text[i + 1];
  1593. if (x1 == 't' || x1 == 'd') { // " 't", " 'd"
  1594. //total--; // remove space
  1595. } else if (x1 == 's' || x1 == 'm') { // " 's", " 'm"
  1596. total--; // remove space
  1597. } else if (i + 2 < total3) {
  1598. const char x2 = text[i + 2];
  1599. if ((x1 == 'l' && x2 == 'l')) { // " 'll"
  1600. //total--; // remove space
  1601. } else if ((x1 == 'r' && x2 == 'e') || (x1 == 'v' && x2 == 'e')) { // " 're", " 've"
  1602. total--; // remove space
  1603. } else {
  1604. //total--; // remove space
  1605. }
  1606. } else {
  1607. //total--; // remove space
  1608. }
  1609. }
  1610. }
  1611. text[total++] = x;
  1612. }
  1613. }
  1614. return total <= text_len_max ? total : -total;
  1615. }