llama-vocab.cpp 77 KB

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