llama-vocab.cpp 123 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247
  1. #include "llama-vocab.h"
  2. #include "llama-impl.h"
  3. #include "llama-model-loader.h"
  4. #include "unicode.h"
  5. #include <algorithm>
  6. #include <cassert>
  7. #include <cfloat>
  8. #include <climits>
  9. #include <cstdarg>
  10. #include <cstring>
  11. #include <forward_list>
  12. #include <map>
  13. #include <queue>
  14. #include <set>
  15. #include <unordered_map>
  16. //
  17. // helpers
  18. //
  19. struct naive_trie {
  20. naive_trie() : has_value(false), value(0) {
  21. }
  22. void insert(const char * key, size_t len, int32_t value = 0) {
  23. if (len == 0) {
  24. this->has_value = true;
  25. this->value = value;
  26. return;
  27. }
  28. char c = key[0];
  29. auto res = children.find(c);
  30. if (res != children.end()) {
  31. res->second.insert(key + 1, len - 1, value);
  32. } else {
  33. auto res = children.insert(std::make_pair(c, naive_trie()));
  34. res.first->second.insert(key + 1, len - 1, value);
  35. }
  36. }
  37. std::pair<const char *, size_t> get_longest_prefix(const char * key, size_t len, size_t offset = 0) const {
  38. if (len == 0 || offset == len) {
  39. return std::make_pair(key, offset);
  40. }
  41. char c = key[offset];
  42. auto res = children.find(c);
  43. if (res != children.end()) {
  44. return res->second.get_longest_prefix(key, len, offset + 1);
  45. }
  46. return std::make_pair(key, offset);
  47. }
  48. const struct naive_trie * traverse(const char c) const {
  49. auto res = children.find(c);
  50. if (res != children.end()) {
  51. return &res->second;
  52. }
  53. return NULL;
  54. }
  55. std::map<char, struct naive_trie> children;
  56. bool has_value;
  57. llama_token value;
  58. };
  59. //
  60. // tokenizers
  61. //
  62. struct llm_tokenizer {
  63. llm_tokenizer() {}
  64. virtual ~llm_tokenizer() = default;
  65. };
  66. struct llm_symbol {
  67. using index = int;
  68. index prev;
  69. index next;
  70. const char * text;
  71. size_t n;
  72. };
  73. static_assert(std::is_trivially_copyable<llm_symbol>::value, "llm_symbol is not trivially copyable");
  74. //
  75. // SPM tokenizer
  76. // original implementation:
  77. // https://github.com/ggerganov/llama.cpp/commit/074bea2eb1f1349a0118239c4152914aecaa1be4
  78. //
  79. struct llm_bigram_spm {
  80. struct comparator {
  81. bool operator()(llm_bigram_spm & l, llm_bigram_spm & r) {
  82. return (l.score < r.score) || (l.score == r.score && l.left > r.left);
  83. }
  84. };
  85. using queue_storage = std::vector<llm_bigram_spm>;
  86. using queue = std::priority_queue<llm_bigram_spm, queue_storage, comparator>;
  87. llm_symbol::index left;
  88. llm_symbol::index right;
  89. float score;
  90. size_t size;
  91. };
  92. struct llm_tokenizer_spm : llm_tokenizer {
  93. llm_tokenizer_spm(const llama_vocab & /*vocab*/) {}
  94. };
  95. struct llm_tokenizer_spm_session {
  96. llm_tokenizer_spm_session(const llama_vocab & vocab) : vocab(vocab) {}
  97. void tokenize(const std::string & text, std::vector<llama_token> & output) {
  98. // split string into utf8 chars
  99. int index = 0;
  100. size_t offs = 0;
  101. while (offs < text.size()) {
  102. llm_symbol sym;
  103. size_t len = unicode_len_utf8(text[offs]);
  104. sym.text = text.c_str() + offs;
  105. sym.n = std::min(len, text.size() - offs);
  106. offs += sym.n;
  107. sym.prev = index - 1;
  108. sym.next = offs == text.size() ? -1 : index + 1;
  109. index++;
  110. symbols.emplace_back(sym);
  111. }
  112. // seed the work queue with all possible 2-character tokens.
  113. for (int i = 1; i < (int) symbols.size(); ++i) {
  114. try_add_bigram(i - 1, i);
  115. }
  116. // keep substituting the highest frequency pairs for as long as we can.
  117. while (!work_queue.empty()) {
  118. auto bigram = work_queue.top();
  119. work_queue.pop();
  120. auto & left_sym = symbols[bigram.left];
  121. auto & right_sym = symbols[bigram.right];
  122. // if one of the symbols already got merged, skip it.
  123. if (left_sym.n == 0 || right_sym.n == 0 ||
  124. left_sym.n + right_sym.n != bigram.size) {
  125. continue;
  126. }
  127. // merge the right sym into the left one
  128. left_sym.n += right_sym.n;
  129. right_sym.n = 0;
  130. //LLAMA_LOG_INFO("left = '%*s' size = %zu\n", (int) left_sym.n, left_sym.text, bigram.size);
  131. // remove the right sym from the chain
  132. left_sym.next = right_sym.next;
  133. if (right_sym.next >= 0) {
  134. symbols[right_sym.next].prev = bigram.left;
  135. }
  136. // find more substitutions
  137. try_add_bigram(left_sym.prev, bigram.left);
  138. try_add_bigram(bigram.left, left_sym.next);
  139. }
  140. for (int i = 0; i != -1; i = symbols[i].next) {
  141. auto & symbol = symbols[i];
  142. resegment(symbol, output);
  143. }
  144. }
  145. private:
  146. void resegment(llm_symbol & symbol, std::vector<llama_token> & output) {
  147. auto text = std::string(symbol.text, symbol.n);
  148. auto token = vocab.text_to_token(text);
  149. // Do we need to support is_unused?
  150. if (token != LLAMA_TOKEN_NULL) {
  151. output.push_back(token);
  152. return;
  153. }
  154. const auto p = rev_merge.find(text);
  155. if (p == rev_merge.end()) {
  156. // output any symbols that did not form tokens as bytes.
  157. output.reserve(output.size() + symbol.n);
  158. for (int j = 0; j < (int)symbol.n; ++j) {
  159. llama_token id = vocab.byte_to_token(symbol.text[j]);
  160. output.push_back(id);
  161. }
  162. return;
  163. }
  164. resegment(symbols[p->second.first], output);
  165. resegment(symbols[p->second.second], output);
  166. }
  167. void try_add_bigram(int left, int right) {
  168. if (left == -1 || right == -1) {
  169. return;
  170. }
  171. const std::string text = std::string(symbols[left].text, symbols[left].n + symbols[right].n);
  172. auto token = vocab.text_to_token(text);
  173. if (token == LLAMA_TOKEN_NULL) {
  174. return;
  175. }
  176. if (static_cast<uint32_t>(token) >= vocab.n_tokens()) {
  177. return;
  178. }
  179. const auto & tok_data = vocab.get_token_data(token);
  180. llm_bigram_spm bigram;
  181. bigram.left = left;
  182. bigram.right = right;
  183. bigram.score = tok_data.score;
  184. bigram.size = text.size();
  185. work_queue.push(bigram);
  186. // Do we need to support is_unused?
  187. rev_merge[text] = std::make_pair(left, right);
  188. }
  189. const llama_vocab & vocab;
  190. // currently unused
  191. // const llm_tokenizer_spm * spm_tokenizer;
  192. std::vector<llm_symbol> symbols;
  193. llm_bigram_spm::queue work_queue;
  194. std::map<std::string, std::pair<int, int>> rev_merge;
  195. };
  196. //
  197. // BPE tokenizer
  198. // adapted from https://github.com/cmp-nct/ggllm.cpp [MIT License]
  199. // tried to simplify unicode stuff, so most likely does not work 100% correctly!
  200. //
  201. // TODO: there are a lot of common parts between spm and bpe tokenizers, should be refactored and reused
  202. template<typename T, typename Container = std::vector<T>, typename Compare = std::less<typename Container::value_type>>
  203. class llama_priority_queue : public std::priority_queue<T, Container, Compare> {
  204. public:
  205. using std::priority_queue<T, Container, Compare>::priority_queue;
  206. T pop_move() {
  207. T item = std::move(this->c.front());
  208. std::pop_heap(this->c.begin(), this->c.end(), this->comp);
  209. this->c.pop_back();
  210. return item;
  211. }
  212. void pop() = delete;
  213. };
  214. struct llm_bigram_bpe {
  215. struct comparator {
  216. bool operator()(const llm_bigram_bpe & l, const llm_bigram_bpe & r) const {
  217. return l.rank > r.rank || (l.rank == r.rank && l.left > r.left);
  218. }
  219. };
  220. using queue_storage = std::vector<llm_bigram_bpe>;
  221. using queue = llama_priority_queue<llm_bigram_bpe, queue_storage, comparator>;
  222. llm_symbol::index left;
  223. llm_symbol::index right;
  224. std::string text;
  225. int rank;
  226. size_t size;
  227. };
  228. struct llm_tokenizer_bpe : llm_tokenizer {
  229. llm_tokenizer_bpe(const llama_vocab & vocab) {
  230. GGML_ASSERT(vocab.get_type() == LLAMA_VOCAB_TYPE_BPE);
  231. switch (vocab.get_pre_type()) {
  232. case LLAMA_VOCAB_PRE_TYPE_LLAMA3:
  233. regex_exprs = {
  234. // original regex from tokenizer.json
  235. //"(?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+",
  236. // adapted: https://github.com/ggerganov/llama.cpp/pull/6920#issuecomment-2080233989
  237. "(?:'[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+",
  238. };
  239. break;
  240. case LLAMA_VOCAB_PRE_TYPE_DBRX:
  241. case LLAMA_VOCAB_PRE_TYPE_SMAUG:
  242. regex_exprs = {
  243. // same as llama3
  244. "(?:'[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+",
  245. };
  246. break;
  247. case LLAMA_VOCAB_PRE_TYPE_DEEPSEEK_LLM:
  248. regex_exprs = {
  249. "[\r\n]",
  250. "\\s?[A-Za-zµÀ-ÖØ-öø-ƺƼ-ƿDŽ-ʓʕ-ʯͰ-ͳͶͷͻ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-ՖႠ-ჅᎠ-Ᏽᏸ-ᏽᲐ-ᲺᲽ-Ჿᴀ-ᴫᵫ-ᵷᵹ-ᶚḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℴℹℼ-ℿⅅ-ⅉⅎↃↄⰀ-ⱻⱾ-ⳤⳫ-ⳮⳲⳳꙀ-ꙭꚀ-ꚛꜢ-ꝯꝱ-ꞇꞋ-ꞎꭰ-ꮿff-stﬓ-ﬗA-Za-z𐐀-𐑏𐒰-𐓓𐓘-𐓻𐲀-𐲲𐳀-𐳲𑢠-𑣟𞤀-𞥃]+",
  251. "\\s?[!-/:-~!-/:-~‘-‟ -。]+",
  252. "\\s+$",
  253. "[一-龥ࠀ-一가-퟿]+",
  254. "\\p{N}+",
  255. };
  256. break;
  257. case LLAMA_VOCAB_PRE_TYPE_DEEPSEEK3_LLM:
  258. regex_exprs = {
  259. "\\p{N}{1,3}",
  260. "[一-龥぀-ゟ゠-ヿ]+",
  261. "[!\"#$%&'()*+,\\-./:;<=>?@\\[\\\\\\]^_`{|}~][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+",
  262. };
  263. break;
  264. case LLAMA_VOCAB_PRE_TYPE_DEEPSEEK_CODER:
  265. regex_exprs = {
  266. "[\r\n]",
  267. "\\s?\\p{L}+",
  268. "\\s?\\p{P}+",
  269. "[一-龥ࠀ-一가-퟿]+",
  270. "\\p{N}",
  271. };
  272. break;
  273. case LLAMA_VOCAB_PRE_TYPE_FALCON:
  274. regex_exprs = {
  275. "[\\p{P}\\$\\+<=>\\^~\\|`]+",
  276. "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)",
  277. "[0-9][0-9][0-9]",
  278. };
  279. break;
  280. case LLAMA_VOCAB_PRE_TYPE_STARCODER:
  281. case LLAMA_VOCAB_PRE_TYPE_REFACT:
  282. case LLAMA_VOCAB_PRE_TYPE_COMMAND_R:
  283. case LLAMA_VOCAB_PRE_TYPE_SMOLLM:
  284. case LLAMA_VOCAB_PRE_TYPE_CODESHELL:
  285. case LLAMA_VOCAB_PRE_TYPE_EXAONE:
  286. case LLAMA_VOCAB_PRE_TYPE_MINERVA:
  287. regex_exprs = {
  288. "\\p{N}",
  289. "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)",
  290. };
  291. break;
  292. case LLAMA_VOCAB_PRE_TYPE_GPT2:
  293. case LLAMA_VOCAB_PRE_TYPE_MPT:
  294. case LLAMA_VOCAB_PRE_TYPE_OLMO:
  295. case LLAMA_VOCAB_PRE_TYPE_JAIS:
  296. regex_exprs = {
  297. "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)",
  298. };
  299. break;
  300. case LLAMA_VOCAB_PRE_TYPE_STABLELM2:
  301. case LLAMA_VOCAB_PRE_TYPE_QWEN2:
  302. regex_exprs = {
  303. // original regex from tokenizer.json
  304. // "(?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+"
  305. "(?:'[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+",
  306. };
  307. break;
  308. case LLAMA_VOCAB_PRE_TYPE_PORO:
  309. case LLAMA_VOCAB_PRE_TYPE_BLOOM:
  310. case LLAMA_VOCAB_PRE_TYPE_GPT3_FINNISH:
  311. regex_exprs = {
  312. " ?[^(\\s|.,!?…。,、।۔،)]+",
  313. };
  314. break;
  315. case LLAMA_VOCAB_PRE_TYPE_CHATGLM4:
  316. regex_exprs = {
  317. "(?:'[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+",
  318. };
  319. break;
  320. case LLAMA_VOCAB_PRE_TYPE_VIKING:
  321. regex_exprs = {
  322. " ?[^(\\s|.,!?…。,、।۔،)]+",
  323. "\\p{N}",
  324. };
  325. break;
  326. case LLAMA_VOCAB_PRE_TYPE_TEKKEN:
  327. // original regex from tokenizer.json
  328. // "[^\\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+"
  329. regex_exprs = {
  330. "[^\\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+",
  331. };
  332. break;
  333. case LLAMA_VOCAB_PRE_TYPE_CHAMELEON:
  334. // Note: in theory, the special token (sentinel and image token) regex_exprs below
  335. // are unnecessary, as they are split in `tokenizer_st_partition` anyway.
  336. // However, since the upstream pre-tokenizer uses them, they are also
  337. // included here (see https://huggingface.co/facebook/chameleon-7b).
  338. regex_exprs = {
  339. "<sentinel:[0-9]+>", // Sentinel tokens
  340. "(IMGIMG)((A|B|C|D|E|F|G|H|I){1,4})Z", // Image tokens
  341. "([\\t\\n]| | )", // directly from tokenizer.json
  342. "\\p{N}", // Individual digits
  343. "[\\p{P}!-/:-@\\[-`{-~]", // Punctuation, Isolated
  344. "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)",
  345. };
  346. break;
  347. default:
  348. // default regex for BPE tokenization pre-processing
  349. regex_exprs = {
  350. "[\\p{P}\\$\\+<=>\\^~\\|]+",
  351. "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)",
  352. "\\p{N}+",
  353. "[0-9][0-9][0-9]",
  354. };
  355. break;
  356. }
  357. }
  358. std::vector<std::string> regex_exprs;
  359. };
  360. struct llm_tokenizer_bpe_session {
  361. llm_tokenizer_bpe_session(const llama_vocab & vocab, const llm_tokenizer_bpe & tokenizer) : vocab(vocab), tokenizer(tokenizer) {}
  362. static void append(const llama_token token_id, std::vector<llama_token> & output) {
  363. output.push_back(token_id);
  364. }
  365. bool append_bos(std::vector<llama_token> & output) const {
  366. if (vocab.get_add_bos()) {
  367. GGML_ASSERT(vocab.token_bos() != LLAMA_TOKEN_NULL);
  368. output.push_back(vocab.token_bos());
  369. return true;
  370. }
  371. return false;
  372. }
  373. bool append_eos(std::vector<llama_token> & output) const {
  374. if (vocab.get_add_eos()) {
  375. GGML_ASSERT(vocab.token_eos() != LLAMA_TOKEN_NULL);
  376. output.push_back(vocab.token_eos());
  377. return true;
  378. }
  379. return false;
  380. }
  381. void check_double_bos_eos(const std::vector<llama_token> & output) const {
  382. if (vocab.get_add_bos() && output.size() >= 2 && output[1] == vocab.token_bos()) {
  383. LLAMA_LOG_WARN(
  384. "%s: Added a BOS token to the prompt as specified by the model but the prompt "
  385. "also starts with a BOS token. So now the final prompt starts with 2 BOS tokens. "
  386. "Are you sure this is what you want?\n", __FUNCTION__);
  387. }
  388. if (vocab.get_add_eos() && output.size() >= 2 && *(output.end()-2) == vocab.token_eos()) {
  389. LLAMA_LOG_WARN(
  390. "%s: Added a EOS token to the prompt as specified by the model but the prompt "
  391. "also ends with a EOS token. So now the final prompt ends with 2 EOS tokens. "
  392. "Are you sure this is what you want?\n", __FUNCTION__);
  393. }
  394. }
  395. void tokenize(const std::string & text, std::vector<llama_token> & output) {
  396. int final_prev_index = -1;
  397. const auto word_collection = unicode_regex_split(text, tokenizer.regex_exprs);
  398. symbols_final.clear();
  399. for (const auto & word : word_collection) {
  400. work_queue = llm_bigram_bpe::queue();
  401. symbols.clear();
  402. int index = 0;
  403. size_t offset = 0;
  404. //if (vocab.tokenizer_ignore_merges && vocab.token_to_id.find(word) != vocab.token_to_id.end()) {
  405. if (vocab.get_ignore_merges() && vocab.text_to_token(word) != LLAMA_TOKEN_NULL) {
  406. symbols.emplace_back(llm_symbol{-1, -1, word.c_str(), word.size()});
  407. offset = word.size();
  408. }
  409. while (offset < word.size()) {
  410. llm_symbol sym;
  411. size_t char_len = std::min(word.size() - offset, (size_t) unicode_len_utf8(word[offset]));
  412. sym.text = word.c_str() + offset;
  413. sym.n = char_len;
  414. offset += sym.n;
  415. sym.prev = index - 1;
  416. sym.next = offset == word.size() ? -1 : index + 1;
  417. index++;
  418. symbols.emplace_back(sym);
  419. }
  420. for (int i = 1; i < (int) symbols.size(); ++i) {
  421. add_new_bigram(i - 1, i);
  422. }
  423. // build token(s)
  424. while (!work_queue.empty()) {
  425. auto bigram = work_queue.pop_move();
  426. auto & left_symbol = symbols[bigram.left];
  427. auto & right_symbol = symbols[bigram.right];
  428. if (left_symbol.n == 0 || right_symbol.n == 0) {
  429. continue;
  430. }
  431. std::string left_token = std::string(left_symbol.text, left_symbol.n);
  432. std::string right_token = std::string(right_symbol.text, right_symbol.n);
  433. if (left_token + right_token != bigram.text) {
  434. continue; // Skip this bigram if it's outdated
  435. }
  436. // merge the right sym into the left one
  437. left_symbol.n += right_symbol.n;
  438. right_symbol.n = 0;
  439. // remove the right sym from the chain
  440. left_symbol.next = right_symbol.next;
  441. if (right_symbol.next >= 0) {
  442. symbols[right_symbol.next].prev = bigram.left;
  443. }
  444. add_new_bigram(left_symbol.prev, bigram.left); // left side of current symbol
  445. add_new_bigram(bigram.left, left_symbol.next); // right side of current symbol
  446. }
  447. // add the finished tokens to the final list keeping correct order for next and prev
  448. for (auto & sym : symbols) {
  449. if (sym.n > 0) {
  450. sym.prev = final_prev_index;
  451. sym.next = -1;
  452. if (final_prev_index != -1) {
  453. symbols_final[final_prev_index].next = symbols_final.size();
  454. }
  455. symbols_final.emplace_back(sym);
  456. final_prev_index = symbols_final.size() - 1;
  457. }
  458. }
  459. }
  460. symbols = symbols_final;
  461. if (!symbols.empty()) {
  462. for (int i = 0; i != -1; i = symbols[i].next) {
  463. auto & symbol = symbols[i];
  464. if (symbol.n == 0) {
  465. continue;
  466. }
  467. const std::string str = std::string(symbol.text, symbol.n);
  468. const auto token = vocab.text_to_token(str);
  469. if (token == LLAMA_TOKEN_NULL) {
  470. for (auto j = str.begin(); j != str.end(); ++j) {
  471. std::string byte_str(1, *j);
  472. auto token_multibyte = vocab.text_to_token(byte_str);
  473. if (token_multibyte != LLAMA_TOKEN_NULL) {
  474. output.push_back(token_multibyte);
  475. }
  476. }
  477. } else {
  478. output.push_back(token);
  479. }
  480. }
  481. }
  482. }
  483. private:
  484. void add_new_bigram(int left, int right) {
  485. if (left == -1 || right == -1) {
  486. return;
  487. }
  488. std::string left_token = std::string(symbols[left].text, symbols[left].n);
  489. std::string right_token = std::string(symbols[right].text, symbols[right].n);
  490. int rank_found = -1;
  491. rank_found = vocab.find_bpe_rank(left_token, right_token);
  492. if (rank_found < 0) {
  493. return;
  494. }
  495. llm_bigram_bpe bigram;
  496. bigram.left = left;
  497. bigram.right = right;
  498. bigram.text = left_token + right_token;
  499. bigram.size = left_token.size() + right_token.size();
  500. bigram.rank = rank_found;
  501. work_queue.push(bigram);
  502. }
  503. const llama_vocab & vocab;
  504. const llm_tokenizer_bpe & tokenizer;
  505. std::vector<llm_symbol> symbols;
  506. std::vector<llm_symbol> symbols_final;
  507. llm_bigram_bpe::queue work_queue;
  508. };
  509. //
  510. // WPM tokenizer
  511. //
  512. struct llm_tokenizer_wpm : llm_tokenizer {
  513. llm_tokenizer_wpm(const llama_vocab & /*vocab*/) {}
  514. };
  515. struct llm_tokenizer_wpm_session {
  516. llm_tokenizer_wpm_session(const llama_vocab & vocab) : vocab(vocab) {}
  517. void tokenize(const std::string & text, std::vector<llama_token> & output) {
  518. // normalize and split by whitespace
  519. std::vector<std::string> words = preprocess(text);
  520. // bos token prepended already
  521. // find the longest tokens that form the words
  522. for (const std::string & word : words) {
  523. // skip empty words
  524. if (word.size() == 0) {
  525. continue;
  526. }
  527. // prepend phantom space
  528. const std::string word1 = "\xe2\x96\x81" + word;
  529. const int n = word1.size();
  530. const size_t current_tokens = output.size();
  531. // we're at the start of a new word
  532. // move through character position in word
  533. for (int i = 0; i < n; ++i) {
  534. // loop through possible match length
  535. bool match = false;
  536. for (int j = std::min(n, i + vocab.max_token_len() + 1); j > i; j--) {
  537. auto id = vocab.text_to_token(word1.substr(i, j - i));
  538. if (id != LLAMA_TOKEN_NULL) {
  539. output.push_back(id);
  540. match = true;
  541. i = j - 1;
  542. break;
  543. }
  544. }
  545. if (!match) { // discard all
  546. output.resize(current_tokens);
  547. break; // and discard next tokens
  548. }
  549. }
  550. // we didn't find any matches for this word
  551. if (current_tokens == output.size()) {
  552. output.push_back(vocab.token_unk());
  553. }
  554. }
  555. }
  556. // TODO: reduce string copies by using cpts_offs array
  557. static std::vector<std::string> preprocess(const std::string & text) {
  558. const std::vector<uint32_t> cpts_nfd = unicode_cpts_normalize_nfd(unicode_cpts_from_utf8(text));
  559. std::vector<std::string> words(1, "");
  560. for (const uint32_t cpt : cpts_nfd) {
  561. const auto flags = unicode_cpt_flags_from_cpt(cpt);
  562. if (flags.is_whitespace) {
  563. if (words.back().size()) { // finish previous word if any
  564. words.emplace_back();
  565. }
  566. continue;
  567. }
  568. assert (!flags.is_separator);
  569. if (cpt == 0 || cpt == 0xFFFD || flags.is_control) {
  570. continue;
  571. }
  572. const std::string s = unicode_cpt_to_utf8(unicode_tolower(cpt));
  573. if (flags.is_punctuation || ( cpt < 0x7F && flags.is_symbol ) || is_chinese_char(cpt)) {
  574. if (words.back().size()) { // finish previous word if any
  575. words.emplace_back();
  576. }
  577. words.back() = s; // single char word
  578. words.emplace_back(); // start a new word
  579. } else {
  580. words.back() += s; // append char to word
  581. }
  582. }
  583. if (!words.back().size()) {
  584. words.pop_back();
  585. }
  586. return words;
  587. }
  588. static bool is_chinese_char(uint32_t cpt) {
  589. return
  590. (cpt >= 0x04E00 && cpt <= 0x09FFF) ||
  591. (cpt >= 0x03400 && cpt <= 0x04DBF) ||
  592. (cpt >= 0x20000 && cpt <= 0x2A6DF) ||
  593. (cpt >= 0x2A700 && cpt <= 0x2B73F) ||
  594. (cpt >= 0x2B740 && cpt <= 0x2B81F) ||
  595. (cpt >= 0x2B920 && cpt <= 0x2CEAF) || // this should be 0x2B820 but in hf rust code it is 0x2B920
  596. (cpt >= 0x0F900 && cpt <= 0x0FAFF) ||
  597. (cpt >= 0x2F800 && cpt <= 0x2FA1F);
  598. //(cpt >= 0x3000 && cpt <= 0x303F) ||
  599. //(cpt >= 0xFF00 && cpt <= 0xFFEF);
  600. }
  601. private:
  602. const llama_vocab & vocab;
  603. // currently unused
  604. // const llm_tokenizer_wpm * wpm_tokenizer;
  605. };
  606. //
  607. // UGM tokenizer
  608. //
  609. struct llm_tokenizer_ugm : llm_tokenizer {
  610. llm_tokenizer_ugm(const llama_vocab & vocab, const std::vector<char> & precompiled_charsmap) {
  611. if (precompiled_charsmap.size() > 0) {
  612. size_t charsmap_offset = 0;
  613. // First four bytes of precompiled_charsmap contains length of binary
  614. // blob containing XOR-compressed compact double array (XCDA) entries
  615. uint32_t xcda_blob_size = *(const uint32_t *) &precompiled_charsmap[0];
  616. charsmap_offset += sizeof(xcda_blob_size);
  617. if (xcda_blob_size + charsmap_offset >= precompiled_charsmap.size()) {
  618. throw std::runtime_error("Index out of array bounds in precompiled charsmap!");
  619. }
  620. // Next xcda_blob_size bytes contain entries of XOR-compressed compact
  621. // double array (XCDA). Each entry is bit-packed into a 32-bit integer.
  622. xcda_array = (const uint32_t *) &precompiled_charsmap[charsmap_offset];
  623. xcda_array_size = xcda_blob_size / sizeof(uint32_t);
  624. charsmap_offset += xcda_blob_size;
  625. // Remaining bytes of precompiled charsmap contain null-terminated
  626. // replacement strings for prefixes matched by the XCDA.
  627. prefix_replacements = &precompiled_charsmap[charsmap_offset];
  628. prefix_replacements_size = precompiled_charsmap.size() - charsmap_offset;
  629. }
  630. for (uint32_t id = 0; id < vocab.n_tokens(); ++id) {
  631. const auto & token_data = vocab.get_token_data(id);
  632. if (vocab.is_normal(id)) {
  633. min_score = std::min<float>(min_score, token_data.score);
  634. max_score = std::max<float>(max_score, token_data.score);
  635. }
  636. if (vocab.is_normal(id) ||
  637. vocab.is_user_defined(id) ||
  638. vocab.is_unused(id)) {
  639. token_matcher.insert(token_data.text.data(), token_data.text.size(), id);
  640. }
  641. if (vocab.is_user_defined(id)) {
  642. user_defined_token_matcher.insert(token_data.text.data(), token_data.text.size());
  643. }
  644. }
  645. unknown_token_score = min_score - unknown_token_score_penalty;
  646. }
  647. // escaped space symbol - U+2581 (Lower One Eighth Block)
  648. const std::string escaped_space = "\xE2\x96\x81";
  649. const char * prefix_replacements = NULL;
  650. size_t prefix_replacements_size = 0;
  651. const uint32_t * xcda_array = NULL;
  652. size_t xcda_array_size = 0;
  653. struct naive_trie user_defined_token_matcher;
  654. float min_score = FLT_MAX;
  655. float max_score = -FLT_MAX;
  656. float unknown_token_score_penalty = 10.0;
  657. float unknown_token_score;
  658. struct naive_trie token_matcher;
  659. };
  660. struct llm_tokenizer_ugm_session {
  661. llm_tokenizer_ugm_session(const llama_vocab & vocab, const llm_tokenizer_ugm & tokenizer) : vocab(vocab), tokenizer(tokenizer) {}
  662. /* This implementation is based on SentencePiece optimized Viterbi algorithm for
  663. * unigram language models. The general idea is to:
  664. * - move along the input sequence in steps of one UTF code point,
  665. * - at each step find all possible tokenizations of the prefix by
  666. * traversing the tokens trie,
  667. * - for each tokenization store the best one so far (by higher score)
  668. * - use the position in sequence after given token as an index to store
  669. * results
  670. * - if there was no valid tokenization of the current UTF code point
  671. * then use unknown token with additional score penalty
  672. * After processing the whole sequence we backtrack from the end to get
  673. * the best tokenization.
  674. */
  675. void tokenize(const std::string & text, std::vector<llama_token> & output) {
  676. // get current size of output (for reversal later)
  677. size_t output_size = output.size();
  678. // normalize the input first
  679. std::string normalized;
  680. normalize(text, &normalized);
  681. size_t input_len = normalized.size();
  682. if (input_len == 0) {
  683. return;
  684. }
  685. // initialize score_sum to -FLT_MAX so it will be always lower than sums of token scores
  686. std::vector<struct best_tokenization> tokenization_results(input_len + 1, {vocab.token_unk(), 0, -FLT_MAX});
  687. // at the beginning tokenization score is zero
  688. tokenization_results[0] = { vocab.token_unk(), 0, 0 };
  689. for (size_t input_offset = 0; input_offset < input_len;) {
  690. size_t prefix_offset = input_offset;
  691. // calculate how many code units are in the currently processed UTF code point
  692. size_t n_utf8_code_units = std::min<size_t>(unicode_len_utf8(normalized[input_offset]), input_len - input_offset);
  693. // traverse the token matcher trie to find a matching token
  694. bool single_codepoint_token_found = false;
  695. const struct best_tokenization & current_best = tokenization_results[input_offset];
  696. const struct naive_trie * node = tokenizer.token_matcher.traverse(normalized[prefix_offset++]);
  697. while (prefix_offset <= input_len && node != NULL) {
  698. // check if we found valid token in prefix
  699. if (node->has_value) {
  700. // check if it corresponds to the whole UTF code point
  701. if (prefix_offset - input_offset == n_utf8_code_units) {
  702. single_codepoint_token_found = true;
  703. }
  704. llama_token token_id = node->value;
  705. const auto & token_data = vocab.get_token_data(token_id);
  706. // we set the user-defined token scores to 0 to make them more likely to be selected
  707. // (normal token scores are log probabilities, so they are negative)
  708. // score type is double here to make tokenization results exactly
  709. // the same as in the HF tokenizer using SentencePiece
  710. const double token_score = vocab.is_user_defined(token_id) ? 0.0 : token_data.score;
  711. const double challenger_score = current_best.score_sum + token_score;
  712. struct best_tokenization & current_champ = tokenization_results[prefix_offset];
  713. if (challenger_score > current_champ.score_sum) {
  714. struct best_tokenization challenger = { token_id, input_offset, (float) challenger_score };
  715. current_champ = challenger;
  716. }
  717. }
  718. node = node->traverse(normalized[prefix_offset++]);
  719. }
  720. // if we didn't find a valid token corresponding to the whole UTF code point
  721. // then use unknown token as the tokenization of this UTF code point
  722. if (!single_codepoint_token_found) {
  723. const double challenger_score = current_best.score_sum + tokenizer.unknown_token_score;
  724. prefix_offset = input_offset + n_utf8_code_units;
  725. struct best_tokenization & current_champ = tokenization_results[prefix_offset];
  726. if (challenger_score > current_champ.score_sum) {
  727. struct best_tokenization challenger = { vocab.token_unk(), input_offset, (float) challenger_score };
  728. current_champ = challenger;
  729. }
  730. }
  731. // move to the next UTF code point
  732. input_offset += n_utf8_code_units;
  733. }
  734. // now backtrack from the end to gather token ids of the best tokenization
  735. // merge sequences of consecutive unknown tokens into single unknown tokens
  736. bool is_prev_unknown = false;
  737. for (struct best_tokenization & tokenization = tokenization_results[input_len]; ; tokenization = tokenization_results[tokenization.input_offset]) {
  738. bool is_unknown = tokenization.token_id == vocab.token_unk();
  739. if (!(is_prev_unknown && is_unknown)) {
  740. output.push_back(tokenization.token_id);
  741. }
  742. if (tokenization.input_offset == 0) {
  743. break;
  744. }
  745. is_prev_unknown = is_unknown;
  746. }
  747. // reverse the output since we added tokens starting from the end of the input
  748. std::reverse(output.begin() + output_size, output.end());
  749. }
  750. private:
  751. // helper structure for returning normalization results
  752. struct normalization_result {
  753. const char * normalized;
  754. size_t normalized_len;
  755. size_t consumed_input;
  756. };
  757. void normalize(const std::string& input, std::string * normalized) {
  758. normalized->clear();
  759. normalized->reserve(input.size() * 3);
  760. const std::string space = vocab.get_escape_whitespaces() ? tokenizer.escaped_space : " ";
  761. const bool shall_prepend_space = !vocab.get_treat_whitespace_as_suffix() && vocab.get_add_space_prefix();
  762. const bool shall_append_space = vocab.get_treat_whitespace_as_suffix() && vocab.get_add_space_prefix();
  763. const bool shall_merge_spaces = vocab.get_remove_extra_whitespaces();
  764. bool is_space_prepended = false;
  765. bool processing_non_ws = false;
  766. size_t input_len = input.size();
  767. for (size_t input_offset = 0; input_offset < input_len; ) {
  768. auto norm_res = normalize_prefix(input, input_offset);
  769. for (size_t i = 0; i < norm_res.normalized_len; i++) {
  770. char c = norm_res.normalized[i];
  771. if (c != ' ') {
  772. if (!processing_non_ws) {
  773. processing_non_ws = true;
  774. if ((shall_prepend_space && !is_space_prepended) || shall_merge_spaces) {
  775. normalized->append(space);
  776. is_space_prepended = true;
  777. }
  778. }
  779. normalized->push_back(c);
  780. } else {
  781. if (processing_non_ws) {
  782. processing_non_ws = false;
  783. }
  784. if (!shall_merge_spaces) {
  785. normalized->append(space);
  786. }
  787. }
  788. }
  789. input_offset += norm_res.consumed_input;
  790. }
  791. if (shall_append_space) {
  792. normalized->append(space);
  793. }
  794. }
  795. /*
  796. * This structure is a view wrapper for XOR-compressed double array (XCDA)
  797. * See Shunsuke Kanda (2018). Space- and Time-Efficient String Dictionaries.
  798. * Each bit-packed entry contains:
  799. * - BASE array value in bits 10-30
  800. * - LCHECK array value in bits 0-7
  801. * - LEAF array value in bit 9
  802. * Entries containing indexes of replacement sequences have set bit 31
  803. */
  804. struct xcda_array_view {
  805. public:
  806. xcda_array_view(const uint32_t * xcda_array, size_t xcda_array_size) : xcda_array(xcda_array), xcda_array_size(xcda_array_size) {
  807. }
  808. uint32_t get_base(size_t index) {
  809. uint32_t packed_node = get_node(index);
  810. return (packed_node >> 10) << ((packed_node & (1U << 9)) >> 6);
  811. }
  812. uint32_t get_lcheck(size_t index) {
  813. uint32_t packed_node = get_node(index);
  814. return packed_node & ((1U << 31) | 0xff);
  815. }
  816. bool get_leaf(size_t index) {
  817. uint32_t packed_node = get_node(index);
  818. return (packed_node >> 8) & 1;
  819. }
  820. uint32_t get_value(size_t index) {
  821. uint32_t packed_node = get_node(index);
  822. return packed_node & ((1U << 31) - 1);
  823. }
  824. private:
  825. uint32_t get_node(size_t index) {
  826. if (index > xcda_array_size) {
  827. throw std::runtime_error("Index out of array bounds in XCDA array!");
  828. }
  829. return xcda_array[index];
  830. }
  831. const uint32_t * xcda_array;
  832. size_t xcda_array_size;
  833. };
  834. // this structure stores the best tokenization so far at input_offset
  835. struct best_tokenization {
  836. llama_token token_id;
  837. size_t input_offset;
  838. float score_sum;
  839. };
  840. struct normalization_result normalize_prefix(const std::string & input, size_t input_offset) {
  841. if (input_offset == input.size()) {
  842. return { &input[input_offset], 0, 0 };
  843. }
  844. // if input prefix matches some user-defined token return this token as normalization result
  845. auto user_defined_token_match =
  846. tokenizer.user_defined_token_matcher.get_longest_prefix(&input[input_offset], input.size() - input_offset);
  847. if (user_defined_token_match.second > 0) {
  848. return { &input[input_offset], user_defined_token_match.second, user_defined_token_match.second };
  849. }
  850. size_t longest_prefix_length = 0;
  851. size_t longest_prefix_offset = 0;
  852. if (tokenizer.xcda_array_size > 0) {
  853. struct xcda_array_view xcda_view(tokenizer.xcda_array, tokenizer.xcda_array_size);
  854. // Find the longest normalized sequence matching the input prefix by walking
  855. // the XOR-compressed compact double array (XCDA) starting from the root node
  856. // We find the index of the next node by calculating BASE[s] ^ c where s is
  857. // the index of the previous node and c is a numerical character value
  858. uint32_t node_index = 0;
  859. // get BASE of the root node
  860. node_index = xcda_view.get_base(node_index);
  861. for (size_t prefix_offset = input_offset; prefix_offset < input.size(); prefix_offset++) {
  862. unsigned char c = input[prefix_offset];
  863. if (c == 0) {
  864. break;
  865. }
  866. node_index ^= c;
  867. // if value of LCHECK is not c it means that this is not a child of
  868. // the previous node, so we stop matching
  869. if (xcda_view.get_lcheck(node_index) != c) {
  870. break;
  871. }
  872. bool is_leaf = xcda_view.get_leaf(node_index);
  873. // get BASE of the current node
  874. node_index ^= xcda_view.get_base(node_index);
  875. // if LEAF of the current node is true, it means that its BASE points to the node
  876. // containing index of replacement sequence for currently matched input prefix
  877. if (is_leaf)
  878. {
  879. longest_prefix_length = prefix_offset - input_offset + 1;
  880. // get index of replacement sequence for currently matched input prefix
  881. longest_prefix_offset = xcda_view.get_value(node_index);
  882. }
  883. }
  884. }
  885. if (longest_prefix_length > 0) {
  886. // we have a match, so return the replacement sequence
  887. if (longest_prefix_offset >= tokenizer.prefix_replacements_size) {
  888. throw std::runtime_error("Index out of array bounds in precompiled charsmap!");
  889. }
  890. const char * prefix_replacement = &(tokenizer.prefix_replacements)[longest_prefix_offset];
  891. return { prefix_replacement, strlen(prefix_replacement), longest_prefix_length };
  892. }
  893. // check if the input prefix contains a valid sequence of UTF-8 code units
  894. try {
  895. // if yes, return this sequence unmodified
  896. size_t prefix_offset = input_offset;
  897. unicode_cpt_from_utf8(input, prefix_offset);
  898. return { &input[input_offset], prefix_offset - input_offset, prefix_offset - input_offset };
  899. } catch (std::invalid_argument & /*ex*/) {
  900. // if no, consume 1 byte and return U+FFFD - REPLACEMENT CHARACTER
  901. return { "\xEF\xBF\xBD", 3, 1 };
  902. }
  903. }
  904. const llama_vocab & vocab;
  905. const llm_tokenizer_ugm & tokenizer;
  906. };
  907. //
  908. // RWKV tokenizer
  909. //
  910. static std::vector<uint8_t> llama_unescape_rwkv_token(const std::string & escaped) {
  911. std::vector<uint8_t> output;
  912. output.reserve(escaped.size());
  913. // Parser state
  914. bool escaping = false;
  915. uint8_t hex_remaining = 0;
  916. uint8_t hex_acc = 0;
  917. // Step through characters, performing parsing
  918. for (const char & c : escaped) {
  919. // If we're parsing a hex code, interpret the next character
  920. if (hex_remaining != 0) {
  921. uint8_t value = (c >= 'a') ? (c - 'a' + 10) : (c - '0');
  922. hex_acc = (hex_acc << 4) + value;
  923. hex_remaining -= 1;
  924. if (hex_remaining == 0) {
  925. output.push_back(hex_acc);
  926. hex_acc = 0;
  927. }
  928. continue;
  929. }
  930. // If we got an escape character, interpret it
  931. if (escaping) {
  932. if (c == 't') {
  933. output.push_back('\t');
  934. } else if (c == 'n') {
  935. output.push_back('\n');
  936. } else if (c == 'r') {
  937. output.push_back('\r');
  938. } else if (c == 'x') {
  939. hex_remaining = 2;
  940. } else {
  941. output.push_back(c);
  942. }
  943. escaping = false;
  944. continue;
  945. }
  946. if (c == '\\') {
  947. escaping = true;
  948. continue;
  949. }
  950. output.push_back(c);
  951. }
  952. return output;
  953. }
  954. struct llm_tokenizer_rwkv : llm_tokenizer {
  955. llm_tokenizer_rwkv(const llama_vocab & vocab) {
  956. // RWKV supports arbitrary byte tokens, but the vocab struct only supports string tokens.
  957. // For now, we decode the vocab here into the lookup we'll use for tokenization.
  958. // build trie
  959. for (uint32_t id = 0; id < vocab.n_tokens(); ++id) {
  960. const auto & data = vocab.get_token_data(id);
  961. const auto text = llama_unescape_rwkv_token(data.text);
  962. token_matcher.insert((const char *) text.data(), text.size(), id);
  963. }
  964. }
  965. struct naive_trie token_matcher;
  966. };
  967. struct llm_tokenizer_rwkv_session {
  968. llm_tokenizer_rwkv_session(const llama_vocab & vocab, const llm_tokenizer_rwkv & tokenizer) : vocab(vocab), tokenizer(tokenizer) {}
  969. void tokenize(const std::string & text, std::vector<llama_token> & output) {
  970. uint32_t position = 0;
  971. while (position < text.size()) {
  972. const struct naive_trie * node = tokenizer.token_matcher.traverse(text[position]);
  973. if (node == NULL) {
  974. // no matching token found, add unknown token
  975. output.push_back(vocab.token_unk());
  976. position += 1;
  977. continue;
  978. }
  979. // traverse the trie to find the longest matching token
  980. uint32_t token_id = 0;
  981. uint32_t token_length = 0;
  982. while (node != NULL) {
  983. if (node->has_value) {
  984. token_id = node->value;
  985. token_length = position + 1;
  986. }
  987. node = node->traverse(text[++position]);
  988. }
  989. // add the longest matching token
  990. output.push_back(token_id);
  991. position = token_length;
  992. }
  993. }
  994. private:
  995. const llama_vocab & vocab;
  996. const llm_tokenizer_rwkv & tokenizer;
  997. };
  998. //
  999. // impl
  1000. //
  1001. typedef enum FRAGMENT_BUFFER_VARIANT_TYPE {
  1002. FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN,
  1003. FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT
  1004. } FRAGMENT_BUFFER_VARIANT_TYPE;
  1005. struct fragment_buffer_variant {
  1006. fragment_buffer_variant(llama_token _token)
  1007. :
  1008. type(FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN),
  1009. token(_token),
  1010. raw_text(_dummy),
  1011. offset(0),
  1012. length(0) {}
  1013. fragment_buffer_variant(const std::string & _raw_text, int64_t _offset, int64_t _length)
  1014. :
  1015. type(FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT),
  1016. token((llama_token) - 1),
  1017. raw_text(_raw_text),
  1018. offset(_offset),
  1019. length(_length){
  1020. GGML_ASSERT(_offset >= 0);
  1021. GGML_ASSERT(_length >= 1);
  1022. GGML_ASSERT(offset + length <= raw_text.length());
  1023. }
  1024. const FRAGMENT_BUFFER_VARIANT_TYPE type;
  1025. const llama_token token;
  1026. const std::string _dummy;
  1027. const std::string & raw_text;
  1028. const uint64_t offset;
  1029. const uint64_t length;
  1030. };
  1031. struct llama_vocab::impl {
  1032. uint32_t n_token_types = 0; // for BERT-style token types
  1033. enum llama_vocab_type type = LLAMA_VOCAB_TYPE_SPM;
  1034. enum llama_vocab_pre_type pre_type = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  1035. int max_token_len = 0; // used for optimizing longest token search
  1036. // default LLaMA special tokens
  1037. // TODO: should we set all of these to LLAMA_TOKEN_NULL?
  1038. llama_token special_bos_id = 1;
  1039. llama_token special_eos_id = 2;
  1040. llama_token special_eot_id = LLAMA_TOKEN_NULL;
  1041. llama_token special_eom_id = LLAMA_TOKEN_NULL;
  1042. llama_token special_unk_id = 0;
  1043. llama_token special_sep_id = LLAMA_TOKEN_NULL;
  1044. llama_token special_pad_id = LLAMA_TOKEN_NULL;
  1045. llama_token special_mask_id = LLAMA_TOKEN_NULL;
  1046. llama_token linefeed_id = 13;
  1047. // fim tokens
  1048. llama_token special_fim_pre_id = LLAMA_TOKEN_NULL;
  1049. llama_token special_fim_suf_id = LLAMA_TOKEN_NULL;
  1050. llama_token special_fim_mid_id = LLAMA_TOKEN_NULL;
  1051. llama_token special_fim_pad_id = LLAMA_TOKEN_NULL;
  1052. llama_token special_fim_rep_id = LLAMA_TOKEN_NULL; // repo
  1053. llama_token special_fim_sep_id = LLAMA_TOKEN_NULL; // file separator
  1054. // tokenizer flags
  1055. bool add_space_prefix = false;
  1056. bool add_bos = false;
  1057. bool add_eos = false;
  1058. bool ignore_merges = false;
  1059. bool clean_spaces = false; // clean_up_tokenization_spaces
  1060. bool remove_extra_whitespaces = false;
  1061. bool escape_whitespaces = true;
  1062. bool treat_whitespace_as_suffix = false;
  1063. std::unordered_map<std::string, llama_token> token_to_id;
  1064. std::vector<token_data> id_to_token;
  1065. std::vector<llama_token> cache_special_tokens;
  1066. std::vector<std::string> cache_token_to_piece; // llama_token_to_piece(special = true);
  1067. std::map<std::pair<std::string, std::string>, int> bpe_ranks;
  1068. // set of all tokens that cause "end of generation"
  1069. std::set<llama_token> special_eog_ids;
  1070. std::unique_ptr<llm_tokenizer> tokenizer;
  1071. std::vector<char> precompiled_charsmap;
  1072. impl(const llama_vocab & vocab) : vocab(vocab) {
  1073. }
  1074. ~impl() = default;
  1075. void load(llama_model_loader & ml, const LLM_KV & kv);
  1076. enum llama_vocab_type get_type() const;
  1077. std::string type_name() const;
  1078. bool is_normal (llama_token id) const;
  1079. bool is_unknown (llama_token id) const;
  1080. bool is_control (llama_token id) const;
  1081. bool is_byte (llama_token id) const;
  1082. bool is_user_defined(llama_token id) const;
  1083. bool is_unused (llama_token id) const;
  1084. bool is_eog (llama_token id) const;
  1085. uint8_t token_to_byte(llama_token id) const;
  1086. llama_token_attr token_get_attr(llama_token id) const;
  1087. void init_tokenizer(enum llama_vocab_type type);
  1088. void tokenizer_st_partition(std::forward_list<fragment_buffer_variant> & buffer, bool parse_special) const;
  1089. std::string token_to_piece_for_cache(
  1090. llama_token token,
  1091. bool special) const;
  1092. std::vector<llama_token> tokenize(
  1093. const std::string & raw_text,
  1094. bool add_special,
  1095. bool parse_special = false) const;
  1096. int32_t tokenize(
  1097. const char * text,
  1098. int32_t text_len,
  1099. llama_token * tokens,
  1100. int32_t n_tokens_max,
  1101. bool add_special,
  1102. bool parse_special) const;
  1103. // does not write null-terminator to buf
  1104. int32_t token_to_piece(
  1105. llama_token token,
  1106. char * buf,
  1107. int32_t length,
  1108. int32_t lstrip,
  1109. bool special) const;
  1110. // use cached data
  1111. const std::string & token_to_piece(llama_token token) const;
  1112. int32_t detokenize(
  1113. const llama_token * tokens,
  1114. int32_t n_tokens,
  1115. char * text,
  1116. int32_t text_len_max,
  1117. bool remove_special,
  1118. bool unparse_special) const;
  1119. std::string detokenize(
  1120. const std::vector<llama_token> & tokens,
  1121. bool special) const;
  1122. void print_info() const;
  1123. private:
  1124. const llama_vocab & vocab;
  1125. };
  1126. void llama_vocab::impl::load(llama_model_loader & ml, const LLM_KV & kv) {
  1127. struct gguf_context * ctx = ml.meta.get();
  1128. // determine vocab type
  1129. {
  1130. std::string tokenizer_model;
  1131. std::string tokenizer_pre;
  1132. ml.get_key(LLM_KV_TOKENIZER_MODEL, tokenizer_model);
  1133. ml.get_key(LLM_KV_TOKENIZER_PRE, tokenizer_pre, false);
  1134. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, n_token_types, false);
  1135. if (tokenizer_model == "no_vocab" || tokenizer_model == "none") {
  1136. type = LLAMA_VOCAB_TYPE_NONE;
  1137. // default special tokens
  1138. special_bos_id = LLAMA_TOKEN_NULL;
  1139. special_eos_id = LLAMA_TOKEN_NULL;
  1140. special_unk_id = LLAMA_TOKEN_NULL;
  1141. special_sep_id = LLAMA_TOKEN_NULL;
  1142. special_pad_id = LLAMA_TOKEN_NULL;
  1143. special_mask_id = LLAMA_TOKEN_NULL;
  1144. linefeed_id = LLAMA_TOKEN_NULL;
  1145. // read vocab size from metadata
  1146. uint32_t n_tokens = 0;
  1147. if (ml.get_key(LLM_KV_VOCAB_SIZE, n_tokens, false)) {
  1148. LLAMA_LOG_WARN("%s: adding %u dummy tokens\n", __func__, n_tokens);
  1149. id_to_token.resize(n_tokens);
  1150. }
  1151. return;
  1152. }
  1153. if (tokenizer_model == "llama") {
  1154. type = LLAMA_VOCAB_TYPE_SPM;
  1155. // default special tokens
  1156. special_bos_id = 1;
  1157. special_eos_id = 2;
  1158. special_unk_id = 0;
  1159. special_sep_id = LLAMA_TOKEN_NULL;
  1160. special_pad_id = LLAMA_TOKEN_NULL;
  1161. special_mask_id = LLAMA_TOKEN_NULL;
  1162. } else if (tokenizer_model == "bert") {
  1163. type = LLAMA_VOCAB_TYPE_WPM;
  1164. // default special tokens
  1165. special_bos_id = 101;
  1166. special_eos_id = LLAMA_TOKEN_NULL;
  1167. special_unk_id = 100;
  1168. special_sep_id = 102;
  1169. special_pad_id = 0;
  1170. special_mask_id = 103;
  1171. } else if (tokenizer_model == "gpt2") {
  1172. type = LLAMA_VOCAB_TYPE_BPE;
  1173. // read bpe merges and populate bpe ranks
  1174. const int merges_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_MERGES).c_str());
  1175. if (merges_keyidx == -1) {
  1176. throw std::runtime_error("cannot find tokenizer merges in model file\n");
  1177. }
  1178. const int n_merges = gguf_get_arr_n(ctx, merges_keyidx);
  1179. for (int i = 0; i < n_merges; i++) {
  1180. const std::string word = gguf_get_arr_str(ctx, merges_keyidx, i);
  1181. //GGML_ASSERT(unicode_cpts_from_utf8(word).size() > 0);
  1182. std::string first;
  1183. std::string second;
  1184. const size_t pos = word.find(' ', 1);
  1185. if (pos != std::string::npos) {
  1186. first = word.substr(0, pos);
  1187. second = word.substr(pos + 1);
  1188. }
  1189. bpe_ranks.emplace(std::make_pair(first, second), i);
  1190. }
  1191. // default special tokens
  1192. special_bos_id = 11;
  1193. special_eos_id = 11;
  1194. special_unk_id = LLAMA_TOKEN_NULL;
  1195. special_sep_id = LLAMA_TOKEN_NULL;
  1196. special_pad_id = LLAMA_TOKEN_NULL;
  1197. special_mask_id = LLAMA_TOKEN_NULL;
  1198. } else if (tokenizer_model == "t5") {
  1199. type = LLAMA_VOCAB_TYPE_UGM;
  1200. // default special tokens
  1201. special_bos_id = LLAMA_TOKEN_NULL;
  1202. special_eos_id = 1;
  1203. special_unk_id = 2;
  1204. special_sep_id = LLAMA_TOKEN_NULL;
  1205. special_pad_id = 0;
  1206. special_mask_id = LLAMA_TOKEN_NULL;
  1207. const int precompiled_charsmap_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_PRECOMPILED_CHARSMAP).c_str());
  1208. if (precompiled_charsmap_keyidx != -1) {
  1209. size_t n_precompiled_charsmap = gguf_get_arr_n(ctx, precompiled_charsmap_keyidx);
  1210. const char * pc = (const char *) gguf_get_arr_data(ctx, precompiled_charsmap_keyidx);
  1211. precompiled_charsmap.assign(pc, pc + n_precompiled_charsmap);
  1212. #ifdef IS_BIG_ENDIAN
  1213. // correct endiannes of data in precompiled_charsmap binary blob
  1214. uint32_t * xcda_blob_size = (uint32_t *) &precompiled_charsmap[0];
  1215. *xcda_blob_size = __builtin_bswap32(*xcda_blob_size);
  1216. assert(*xcda_blob_size + sizeof(uint32_t) < n_precompiled_charsmap);
  1217. size_t xcda_array_size = *xcda_blob_size / sizeof(uint32_t);
  1218. uint32_t * xcda_array = (uint32_t *) &precompiled_charsmap[sizeof(uint32_t)];
  1219. for (size_t i = 0; i < xcda_array_size; ++i) {
  1220. xcda_array[i] = __builtin_bswap32(xcda_array[i]);
  1221. }
  1222. #endif
  1223. }
  1224. } else if (tokenizer_model == "rwkv") {
  1225. type = LLAMA_VOCAB_TYPE_RWKV;
  1226. // default special tokens
  1227. special_bos_id = LLAMA_TOKEN_NULL;
  1228. special_eos_id = LLAMA_TOKEN_NULL;
  1229. special_unk_id = LLAMA_TOKEN_NULL;
  1230. special_sep_id = LLAMA_TOKEN_NULL;
  1231. special_pad_id = LLAMA_TOKEN_NULL;
  1232. } else {
  1233. throw std::runtime_error(format("unknown tokenizer: '%s'", tokenizer_model.c_str()));
  1234. }
  1235. // for now, only BPE models have pre-tokenizers
  1236. if (type == LLAMA_VOCAB_TYPE_BPE) {
  1237. add_space_prefix = false;
  1238. clean_spaces = true;
  1239. if (tokenizer_pre.empty()) {
  1240. LLAMA_LOG_WARN("%s: missing pre-tokenizer type, using: 'default'\n", __func__);
  1241. LLAMA_LOG_WARN("%s: \n", __func__);
  1242. LLAMA_LOG_WARN("%s: ************************************ \n", __func__);
  1243. LLAMA_LOG_WARN("%s: GENERATION QUALITY WILL BE DEGRADED! \n", __func__);
  1244. LLAMA_LOG_WARN("%s: CONSIDER REGENERATING THE MODEL \n", __func__);
  1245. LLAMA_LOG_WARN("%s: ************************************ \n", __func__);
  1246. LLAMA_LOG_WARN("%s: \n", __func__);
  1247. pre_type = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  1248. } else if (tokenizer_pre == "default") {
  1249. pre_type = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  1250. } else if (
  1251. tokenizer_pre == "llama3" ||
  1252. tokenizer_pre == "llama-v3" ||
  1253. tokenizer_pre == "llama-bpe"||
  1254. tokenizer_pre == "falcon3") {
  1255. pre_type = LLAMA_VOCAB_PRE_TYPE_LLAMA3;
  1256. ignore_merges = true;
  1257. add_bos = true;
  1258. } else if (
  1259. tokenizer_pre == "deepseek-llm") {
  1260. pre_type = LLAMA_VOCAB_PRE_TYPE_DEEPSEEK_LLM;
  1261. clean_spaces = false;
  1262. } else if (
  1263. tokenizer_pre == "deepseek-coder") {
  1264. pre_type = LLAMA_VOCAB_PRE_TYPE_DEEPSEEK_CODER;
  1265. clean_spaces = false;
  1266. } else if (
  1267. tokenizer_pre == "deepseek-v3") {
  1268. pre_type = LLAMA_VOCAB_PRE_TYPE_DEEPSEEK3_LLM;
  1269. clean_spaces = false;
  1270. } else if (
  1271. tokenizer_pre == "falcon") {
  1272. pre_type = LLAMA_VOCAB_PRE_TYPE_FALCON;
  1273. } else if (
  1274. tokenizer_pre == "mpt") {
  1275. pre_type = LLAMA_VOCAB_PRE_TYPE_MPT;
  1276. } else if (
  1277. tokenizer_pre == "starcoder") {
  1278. pre_type = LLAMA_VOCAB_PRE_TYPE_STARCODER;
  1279. } else if (
  1280. tokenizer_pre == "gpt-2" ||
  1281. tokenizer_pre == "phi-2" ||
  1282. tokenizer_pre == "jina-es" ||
  1283. tokenizer_pre == "jina-de" ||
  1284. tokenizer_pre == "gigachat" ||
  1285. tokenizer_pre == "jina-v1-en" ||
  1286. tokenizer_pre == "jina-v2-es" ||
  1287. tokenizer_pre == "jina-v2-de" ||
  1288. tokenizer_pre == "jina-v2-code" ||
  1289. tokenizer_pre == "roberta-bpe") {
  1290. pre_type = LLAMA_VOCAB_PRE_TYPE_GPT2;
  1291. } else if (
  1292. tokenizer_pre == "refact") {
  1293. pre_type = LLAMA_VOCAB_PRE_TYPE_REFACT;
  1294. } else if (
  1295. tokenizer_pre == "command-r") {
  1296. pre_type = LLAMA_VOCAB_PRE_TYPE_COMMAND_R;
  1297. clean_spaces = false;
  1298. } else if (
  1299. tokenizer_pre == "qwen2" ||
  1300. tokenizer_pre == "deepseek-r1-qwen") {
  1301. pre_type = LLAMA_VOCAB_PRE_TYPE_QWEN2;
  1302. clean_spaces = false;
  1303. } else if (
  1304. tokenizer_pre == "stablelm2") {
  1305. pre_type = LLAMA_VOCAB_PRE_TYPE_STABLELM2;
  1306. } else if (
  1307. tokenizer_pre == "olmo") {
  1308. pre_type = LLAMA_VOCAB_PRE_TYPE_OLMO;
  1309. } else if (
  1310. tokenizer_pre == "dbrx") {
  1311. pre_type = LLAMA_VOCAB_PRE_TYPE_DBRX;
  1312. } else if (
  1313. tokenizer_pre == "smaug-bpe") {
  1314. pre_type = LLAMA_VOCAB_PRE_TYPE_SMAUG;
  1315. } else if (
  1316. tokenizer_pre == "poro-chat") {
  1317. pre_type = LLAMA_VOCAB_PRE_TYPE_PORO;
  1318. clean_spaces = false;
  1319. } else if (
  1320. tokenizer_pre == "chatglm-bpe") {
  1321. pre_type = LLAMA_VOCAB_PRE_TYPE_CHATGLM4;
  1322. special_bos_id = LLAMA_TOKEN_NULL;
  1323. } else if (
  1324. tokenizer_pre == "viking") {
  1325. pre_type = LLAMA_VOCAB_PRE_TYPE_VIKING;
  1326. clean_spaces = false;
  1327. } else if (
  1328. tokenizer_pre == "jais") {
  1329. pre_type = LLAMA_VOCAB_PRE_TYPE_JAIS;
  1330. } else if (
  1331. tokenizer_pre == "tekken") {
  1332. pre_type = LLAMA_VOCAB_PRE_TYPE_TEKKEN;
  1333. clean_spaces = false;
  1334. ignore_merges = true;
  1335. add_bos = true;
  1336. } else if (
  1337. tokenizer_pre == "smollm") {
  1338. pre_type = LLAMA_VOCAB_PRE_TYPE_SMOLLM;
  1339. clean_spaces = false;
  1340. } else if (
  1341. tokenizer_pre == "codeshell") {
  1342. pre_type = LLAMA_VOCAB_PRE_TYPE_CODESHELL;
  1343. } else if (
  1344. tokenizer_pre == "bloom") {
  1345. pre_type = LLAMA_VOCAB_PRE_TYPE_BLOOM;
  1346. } else if (
  1347. tokenizer_pre == "gpt3-finnish") {
  1348. pre_type = LLAMA_VOCAB_PRE_TYPE_GPT3_FINNISH;
  1349. } else if (
  1350. tokenizer_pre == "exaone") {
  1351. pre_type = LLAMA_VOCAB_PRE_TYPE_EXAONE;
  1352. } else if (
  1353. tokenizer_pre == "chameleon") {
  1354. pre_type = LLAMA_VOCAB_PRE_TYPE_CHAMELEON;
  1355. add_bos = true;
  1356. clean_spaces = false;
  1357. } else if (
  1358. tokenizer_pre == "minerva-7b") {
  1359. pre_type = LLAMA_VOCAB_PRE_TYPE_MINERVA;
  1360. } else if (
  1361. tokenizer_pre == "megrez") {
  1362. pre_type = LLAMA_VOCAB_PRE_TYPE_QWEN2;
  1363. } else {
  1364. throw std::runtime_error(format("unknown pre-tokenizer type: '%s'", tokenizer_pre.c_str()));
  1365. }
  1366. } else if (type == LLAMA_VOCAB_TYPE_SPM) {
  1367. pre_type = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  1368. add_space_prefix = true;
  1369. clean_spaces = false;
  1370. add_bos = true;
  1371. add_eos = false;
  1372. } else if (type == LLAMA_VOCAB_TYPE_WPM) {
  1373. pre_type = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  1374. add_space_prefix = false;
  1375. clean_spaces = true;
  1376. add_bos = true;
  1377. add_eos = false;
  1378. } else if (type == LLAMA_VOCAB_TYPE_UGM) {
  1379. pre_type = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  1380. add_bos = false;
  1381. add_eos = true;
  1382. } else if (type == LLAMA_VOCAB_TYPE_RWKV) {
  1383. pre_type = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  1384. add_space_prefix = false;
  1385. clean_spaces = false;
  1386. add_bos = false;
  1387. add_eos = false;
  1388. } else {
  1389. pre_type = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  1390. }
  1391. ml.get_key(LLM_KV_TOKENIZER_ADD_PREFIX, add_space_prefix, false);
  1392. ml.get_key(LLM_KV_TOKENIZER_REMOVE_EXTRA_WS, remove_extra_whitespaces, false);
  1393. }
  1394. const int token_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_LIST).c_str());
  1395. if (token_idx == -1) {
  1396. throw std::runtime_error("cannot find tokenizer vocab in model file\n");
  1397. }
  1398. const float * scores = nullptr;
  1399. const int score_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_SCORES).c_str());
  1400. if (score_idx != -1) {
  1401. scores = (const float * ) gguf_get_arr_data(ctx, score_idx);
  1402. }
  1403. const int * toktypes = nullptr;
  1404. const int toktype_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_TOKEN_TYPE).c_str());
  1405. if (toktype_idx != -1) {
  1406. toktypes = (const int * ) gguf_get_arr_data(ctx, toktype_idx);
  1407. }
  1408. uint32_t n_tokens = gguf_get_arr_n(ctx, token_idx);
  1409. id_to_token.resize(n_tokens);
  1410. for (uint32_t i = 0; i < n_tokens; i++) {
  1411. std::string word = gguf_get_arr_str(ctx, token_idx, i);
  1412. if (word.empty()) {
  1413. LLAMA_LOG_WARN("%s: empty token at index %u\n", __func__, i);
  1414. word = "[EMPTY_" + std::to_string(i) + "]";
  1415. }
  1416. token_to_id[word] = i;
  1417. max_token_len = std::max(max_token_len, (int) word.size());
  1418. auto & token_data = id_to_token[i];
  1419. token_data.text = std::move(word);
  1420. token_data.score = scores ? scores[i] : 0.0f;
  1421. token_data.attr = LLAMA_TOKEN_ATTR_NORMAL;
  1422. if (toktypes) { //TODO: remove, required until per token attributes are available from GGUF file
  1423. switch(toktypes[i]) {
  1424. case LLAMA_TOKEN_TYPE_UNKNOWN: token_data.attr = LLAMA_TOKEN_ATTR_UNKNOWN; break;
  1425. case LLAMA_TOKEN_TYPE_UNUSED: token_data.attr = LLAMA_TOKEN_ATTR_UNUSED; break;
  1426. case LLAMA_TOKEN_TYPE_NORMAL: token_data.attr = LLAMA_TOKEN_ATTR_NORMAL; break;
  1427. case LLAMA_TOKEN_TYPE_CONTROL: token_data.attr = LLAMA_TOKEN_ATTR_CONTROL; break;
  1428. case LLAMA_TOKEN_TYPE_USER_DEFINED: token_data.attr = LLAMA_TOKEN_ATTR_USER_DEFINED; break;
  1429. case LLAMA_TOKEN_TYPE_BYTE: token_data.attr = LLAMA_TOKEN_ATTR_BYTE; break;
  1430. case LLAMA_TOKEN_TYPE_UNDEFINED: token_data.attr = LLAMA_TOKEN_ATTR_UNDEFINED; break;
  1431. default: token_data.attr = LLAMA_TOKEN_ATTR_UNDEFINED; break;
  1432. }
  1433. }
  1434. }
  1435. GGML_ASSERT(id_to_token.size() == token_to_id.size());
  1436. init_tokenizer(type);
  1437. // determine the newline token: LLaMA "<0x0A>" == 10 == '\n', Falcon 193 == '\n'
  1438. if (type == LLAMA_VOCAB_TYPE_SPM) {
  1439. try {
  1440. linefeed_id = vocab.byte_to_token('\n');
  1441. } catch (const std::exception & e) {
  1442. LLAMA_LOG_WARN("%s: SPM vocabulary, but newline token not found: %s! Using special_pad_id instead.", __func__, e.what());
  1443. linefeed_id = special_pad_id;
  1444. }
  1445. } else if (type == LLAMA_VOCAB_TYPE_WPM) {
  1446. linefeed_id = special_pad_id;
  1447. } else if (type == LLAMA_VOCAB_TYPE_RWKV) {
  1448. const std::vector<int> ids = tokenize("\n", false);
  1449. GGML_ASSERT(!ids.empty() && "model vocab missing newline token");
  1450. linefeed_id = ids[0];
  1451. } else {
  1452. const std::vector<int> ids = tokenize("\xC4\x8A", false); // U+010A
  1453. //GGML_ASSERT(!ids.empty() && "model vocab missing newline token");
  1454. if (ids.empty()) {
  1455. LLAMA_LOG_WARN("%s: model vocab missing newline token, using special_pad_id instead\n", __func__);
  1456. linefeed_id = special_pad_id;
  1457. } else {
  1458. linefeed_id = ids[0];
  1459. }
  1460. }
  1461. // special tokens
  1462. {
  1463. const std::vector<std::pair<enum llm_kv, int32_t &>> special_token_types = {
  1464. { LLM_KV_TOKENIZER_BOS_ID, special_bos_id },
  1465. { LLM_KV_TOKENIZER_EOS_ID, special_eos_id },
  1466. { LLM_KV_TOKENIZER_EOT_ID, special_eot_id },
  1467. { LLM_KV_TOKENIZER_EOM_ID, special_eom_id },
  1468. { LLM_KV_TOKENIZER_UNK_ID, special_unk_id },
  1469. { LLM_KV_TOKENIZER_SEP_ID, special_sep_id },
  1470. { LLM_KV_TOKENIZER_PAD_ID, special_pad_id },
  1471. { LLM_KV_TOKENIZER_MASK_ID, special_mask_id },
  1472. { LLM_KV_TOKENIZER_FIM_PRE_ID, special_fim_pre_id },
  1473. { LLM_KV_TOKENIZER_FIM_SUF_ID, special_fim_suf_id },
  1474. { LLM_KV_TOKENIZER_FIM_MID_ID, special_fim_mid_id },
  1475. { LLM_KV_TOKENIZER_FIM_PAD_ID, special_fim_pad_id },
  1476. { LLM_KV_TOKENIZER_FIM_REP_ID, special_fim_rep_id },
  1477. { LLM_KV_TOKENIZER_FIM_SEP_ID, special_fim_sep_id },
  1478. // deprecated
  1479. { LLM_KV_TOKENIZER_PREFIX_ID, special_fim_pre_id },
  1480. { LLM_KV_TOKENIZER_SUFFIX_ID, special_fim_suf_id },
  1481. { LLM_KV_TOKENIZER_MIDDLE_ID, special_fim_mid_id },
  1482. };
  1483. for (const auto & it : special_token_types) {
  1484. const std::string & key = kv(std::get<0>(it));
  1485. int32_t & id = std::get<1>(it);
  1486. uint32_t new_id;
  1487. if (!ml.get_key(std::get<0>(it), new_id, false)) {
  1488. continue;
  1489. }
  1490. if (new_id >= id_to_token.size()) {
  1491. LLAMA_LOG_WARN("%s: bad special token: '%s' = %u, using default id %d\n",
  1492. __func__, key.c_str(), new_id, id);
  1493. } else {
  1494. id = new_id;
  1495. }
  1496. }
  1497. // Handle add_bos and add_eos
  1498. {
  1499. bool temp = true;
  1500. if (ml.get_key(LLM_KV_TOKENIZER_ADD_BOS, temp, false)) {
  1501. add_bos = temp;
  1502. }
  1503. if (ml.get_key(LLM_KV_TOKENIZER_ADD_EOS, temp, false)) {
  1504. add_eos = temp;
  1505. }
  1506. }
  1507. // auto-detect special tokens by text
  1508. // TODO: convert scripts should provide these tokens through the KV metadata LLM_KV_TOKENIZER_...
  1509. // for now, we apply this workaround to find the tokens based on their text
  1510. for (const auto & t : token_to_id) {
  1511. // find EOT token: "<|eot_id|>", "<|im_end|>", "<end_of_turn>", etc.
  1512. if (special_eot_id == LLAMA_TOKEN_NULL) {
  1513. if (false
  1514. || t.first == "<|eot_id|>"
  1515. || t.first == "<|im_end|>"
  1516. || t.first == "<|end|>"
  1517. || t.first == "<end_of_turn>"
  1518. || t.first == "<|endoftext|>"
  1519. || t.first == "<EOT>"
  1520. || t.first == "<|end▁of▁sentence|>" // DeepSeek
  1521. ) {
  1522. special_eot_id = t.second;
  1523. if ((id_to_token[t.second].attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) {
  1524. LLAMA_LOG_WARN("%s: control-looking token: %6d '%s' was not control-type; this is probably a bug in the model. its type will be overridden\n",
  1525. __func__, t.second, t.first.c_str());
  1526. id_to_token[t.second].attr = LLAMA_TOKEN_ATTR_CONTROL;
  1527. }
  1528. }
  1529. }
  1530. // find EOM token: "<|eom_id|>"
  1531. if (special_eom_id == LLAMA_TOKEN_NULL) {
  1532. if (false
  1533. || t.first == "<|eom_id|>"
  1534. ) {
  1535. special_eom_id = t.second;
  1536. if ((id_to_token[t.second].attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) {
  1537. LLAMA_LOG_WARN("%s: control-looking token: %6d '%s' was not control-type; this is probably a bug in the model. its type will be overridden\n",
  1538. __func__, t.second, t.first.c_str());
  1539. id_to_token[t.second].attr = LLAMA_TOKEN_ATTR_CONTROL;
  1540. }
  1541. }
  1542. }
  1543. // find FIM_PRE token: "<|fim_prefix|>", "<fim-prefix>", "<PRE>", etc.
  1544. if (special_fim_pre_id == LLAMA_TOKEN_NULL) {
  1545. if (false
  1546. || t.first == "<|fim_prefix|>" // Qwen
  1547. || t.first == "<fim-prefix>"
  1548. || t.first == "<|fim▁begin|>" // DeepSeek
  1549. || t.first == "<PRE>"
  1550. ) {
  1551. special_fim_pre_id = t.second;
  1552. if ((id_to_token[t.second].attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) {
  1553. LLAMA_LOG_WARN("%s: control-looking token: %6d '%s' was not control-type; this is probably a bug in the model. its type will be overridden\n",
  1554. __func__, t.second, t.first.c_str());
  1555. id_to_token[t.second].attr = LLAMA_TOKEN_ATTR_CONTROL;
  1556. }
  1557. }
  1558. }
  1559. // find FIM_SUF token: "<|fim_suffix|>", "<fim-suffix>", "<SUF>", etc.
  1560. if (special_fim_suf_id == LLAMA_TOKEN_NULL) {
  1561. if (false
  1562. || t.first == "<|fim_suffix|>" // Qwen
  1563. || t.first == "<fim-suffix>"
  1564. || t.first == "<|fim▁hole|>" // DeepSeek
  1565. || t.first == "<SUF>"
  1566. ) {
  1567. special_fim_suf_id = t.second;
  1568. if ((id_to_token[t.second].attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) {
  1569. LLAMA_LOG_WARN("%s: control-looking token: %6d '%s' was not control-type; this is probably a bug in the model. its type will be overridden\n",
  1570. __func__, t.second, t.first.c_str());
  1571. id_to_token[t.second].attr = LLAMA_TOKEN_ATTR_CONTROL;
  1572. }
  1573. }
  1574. }
  1575. // find FIM_MID token: "<|fim_middle|>", "<fim-middle>", "<MID>", etc.
  1576. if (special_fim_mid_id == LLAMA_TOKEN_NULL) {
  1577. if (false
  1578. || t.first == "<|fim_middle|>" // Qwen
  1579. || t.first == "<fim-middle>"
  1580. || t.first == "<|fim▁end|>" // DeepSeek
  1581. || t.first == "<MID>"
  1582. ) {
  1583. special_fim_mid_id = t.second;
  1584. if ((id_to_token[t.second].attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) {
  1585. LLAMA_LOG_WARN("%s: control-looking token: %6d '%s' was not control-type; this is probably a bug in the model. its type will be overridden\n",
  1586. __func__, t.second, t.first.c_str());
  1587. id_to_token[t.second].attr = LLAMA_TOKEN_ATTR_CONTROL;
  1588. }
  1589. }
  1590. }
  1591. // find FIM_PAD token: "<|fim_pad|>", "<fim-pad>", "<PAD>", etc.
  1592. if (special_fim_pad_id == LLAMA_TOKEN_NULL) {
  1593. if (false
  1594. || t.first == "<|fim_pad|>" // Qwen
  1595. || t.first == "<fim-pad>"
  1596. || t.first == "<PAD>"
  1597. ) {
  1598. special_fim_pad_id = t.second;
  1599. if ((id_to_token[t.second].attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) {
  1600. LLAMA_LOG_WARN("%s: control-looking token: %6d '%s' was not control-type; this is probably a bug in the model. its type will be overridden\n",
  1601. __func__, t.second, t.first.c_str());
  1602. id_to_token[t.second].attr = LLAMA_TOKEN_ATTR_CONTROL;
  1603. }
  1604. }
  1605. }
  1606. // find FIM_REP token: "<|fim_repo|>", "<fim-repo>", "<REP>", etc.
  1607. if (special_fim_rep_id == LLAMA_TOKEN_NULL) {
  1608. if (false
  1609. || t.first == "<|fim_repo|>" // Qwen
  1610. || t.first == "<|repo_name|>"
  1611. || t.first == "<fim-repo>"
  1612. || t.first == "<REPO>"
  1613. ) {
  1614. special_fim_rep_id = t.second;
  1615. if ((id_to_token[t.second].attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) {
  1616. LLAMA_LOG_WARN("%s: control-looking token: %6d '%s' was not control-type; this is probably a bug in the model. its type will be overridden\n",
  1617. __func__, t.second, t.first.c_str());
  1618. id_to_token[t.second].attr = LLAMA_TOKEN_ATTR_CONTROL;
  1619. }
  1620. }
  1621. }
  1622. // find FIM_SEP token: "<|file_sep|>"
  1623. if (special_fim_sep_id == LLAMA_TOKEN_NULL) {
  1624. if (false
  1625. || t.first == "<|file_sep|>" // Qwen
  1626. ) {
  1627. special_fim_sep_id = t.second;
  1628. if ((id_to_token[t.second].attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) {
  1629. LLAMA_LOG_WARN("%s: control-looking token: %6d '%s' was not control-type; this is probably a bug in the model. its type will be overridden\n",
  1630. __func__, t.second, t.first.c_str());
  1631. id_to_token[t.second].attr = LLAMA_TOKEN_ATTR_CONTROL;
  1632. }
  1633. }
  1634. }
  1635. }
  1636. // maintain a list of tokens that cause end-of-generation
  1637. // this is currently determined based on the token text, which is obviously not ideal
  1638. // ref: https://github.com/ggerganov/llama.cpp/issues/9606
  1639. special_eog_ids.clear();
  1640. if (special_fim_pad_id != LLAMA_TOKEN_NULL && special_eog_ids.count(special_fim_pad_id) == 0) {
  1641. special_eog_ids.insert(special_fim_pad_id);
  1642. }
  1643. if (special_fim_rep_id != LLAMA_TOKEN_NULL && special_eog_ids.count(special_fim_rep_id) == 0) {
  1644. special_eog_ids.insert(special_fim_rep_id);
  1645. }
  1646. if (special_fim_sep_id != LLAMA_TOKEN_NULL && special_eog_ids.count(special_fim_sep_id) == 0) {
  1647. special_eog_ids.insert(special_fim_sep_id);
  1648. }
  1649. for (const auto & t : token_to_id) {
  1650. if (false
  1651. || t.first == "<|eot_id|>"
  1652. || t.first == "<|im_end|>"
  1653. || t.first == "<|end|>"
  1654. || t.first == "<end_of_turn>"
  1655. || t.first == "<|endoftext|>"
  1656. || t.first == "<|eom_id|>"
  1657. || t.first == "<EOT>"
  1658. ) {
  1659. special_eog_ids.insert(t.second);
  1660. if ((id_to_token[t.second].attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) {
  1661. LLAMA_LOG_WARN("%s: control-looking token: %6d '%s' was not control-type; this is probably a bug in the model. its type will be overridden\n",
  1662. __func__, t.second, t.first.c_str());
  1663. id_to_token[t.second].attr = LLAMA_TOKEN_ATTR_CONTROL;
  1664. }
  1665. } else {
  1666. // token is control, but not marked as EOG -> print a debug log
  1667. if (id_to_token[t.second].attr & LLAMA_TOKEN_ATTR_CONTROL && special_eog_ids.count(t.second) == 0) {
  1668. LLAMA_LOG_DEBUG("%s: control token: %6d '%s' is not marked as EOG\n",
  1669. __func__, t.second, t.first.c_str());
  1670. }
  1671. }
  1672. }
  1673. // sanity checks
  1674. if (special_eos_id != LLAMA_TOKEN_NULL && special_eog_ids.count(special_eos_id) == 0) {
  1675. special_eog_ids.insert(special_eos_id);
  1676. LLAMA_LOG_WARN("%s: special_eos_id is not in special_eog_ids - the tokenizer config may be incorrect\n", __func__);
  1677. }
  1678. if (special_eot_id != LLAMA_TOKEN_NULL && special_eog_ids.count(special_eot_id) == 0) {
  1679. special_eog_ids.insert(special_eot_id);
  1680. LLAMA_LOG_WARN("%s: special_eot_id is not in special_eog_ids - the tokenizer config may be incorrect\n", __func__);
  1681. }
  1682. if (special_eom_id != LLAMA_TOKEN_NULL && special_eog_ids.count(special_eom_id) == 0) {
  1683. special_eog_ids.insert(special_eom_id);
  1684. LLAMA_LOG_WARN("%s: special_eom_id is not in special_eog_ids - the tokenizer config may be incorrect\n", __func__);
  1685. }
  1686. }
  1687. // build special tokens cache
  1688. {
  1689. for (llama_token id = 0; id < (llama_token) n_tokens; ++id) {
  1690. if (id_to_token[id].attr & (LLAMA_TOKEN_ATTR_CONTROL | LLAMA_TOKEN_ATTR_USER_DEFINED | LLAMA_TOKEN_ATTR_UNKNOWN)) {
  1691. cache_special_tokens.push_back(id);
  1692. }
  1693. }
  1694. std::sort(cache_special_tokens.begin(), cache_special_tokens.end(),
  1695. [&] (const llama_token a, const llama_token b) {
  1696. return id_to_token[a].text.size() > id_to_token[b].text.size();
  1697. }
  1698. );
  1699. LLAMA_LOG_INFO("%s: special tokens cache size = %u\n", __func__, (uint32_t) cache_special_tokens.size());
  1700. }
  1701. // build token to piece cache
  1702. {
  1703. size_t size_cache = 0;
  1704. std::vector<std::string> cache(n_tokens);
  1705. for (uint32_t id = 0; id < n_tokens; ++id) {
  1706. cache[id] = token_to_piece_for_cache(id, true);
  1707. size_cache += cache[id].size();
  1708. }
  1709. std::swap(cache_token_to_piece, cache);
  1710. LLAMA_LOG_INFO("%s: token to piece cache size = %.4f MB\n", __func__, size_cache / 1024.0 / 1024.0);
  1711. }
  1712. // Handle per token attributes
  1713. //NOTE: Each model customizes per token attributes.
  1714. //NOTE: Per token attributes are missing from the GGUF file.
  1715. //TODO: Extract attributes from GGUF file.
  1716. {
  1717. auto _contains_any = [] (const std::string & str, const std::vector<std::string> & substrs) -> bool {
  1718. for (const auto & substr : substrs) {
  1719. if (str.find(substr) < std::string::npos) {
  1720. return true;
  1721. }
  1722. }
  1723. return false;
  1724. };
  1725. auto _set_tokenid_attr = [&] (const llama_token id, llama_token_attr attr, bool value) {
  1726. uint32_t current = id_to_token.at(id).attr;
  1727. current = value ? (current | attr) : (current & ~attr);
  1728. id_to_token[id].attr = (llama_token_attr) current;
  1729. };
  1730. auto _set_token_attr = [&] (const std::string & token, llama_token_attr attr, bool value) {
  1731. _set_tokenid_attr(token_to_id.at(token), attr, value);
  1732. };
  1733. std::string model_name;
  1734. std::string tokenizer_pre;
  1735. ml.get_key(LLM_KV_GENERAL_NAME, model_name, false);
  1736. ml.get_key(LLM_KV_TOKENIZER_PRE, tokenizer_pre, false);
  1737. // model name to lowercase
  1738. std::transform(model_name.begin(), model_name.end(), model_name.begin(),
  1739. [] (const std::string::value_type x) {
  1740. return std::tolower(x);
  1741. }
  1742. );
  1743. // set attributes by model/tokenizer name
  1744. if (_contains_any(tokenizer_pre, {"jina-v2-de", "jina-v2-es", "jina-v2-code"})) {
  1745. _set_token_attr("<mask>", LLAMA_TOKEN_ATTR_LSTRIP, true);
  1746. } else if (_contains_any(model_name, {"phi-3", "phi3"})) {
  1747. for (auto id : cache_special_tokens) {
  1748. _set_tokenid_attr(id, LLAMA_TOKEN_ATTR_RSTRIP, true);
  1749. }
  1750. for (const auto * token : {"</s>"}) {
  1751. _set_token_attr(token, LLAMA_TOKEN_ATTR_RSTRIP, true);
  1752. }
  1753. for (const auto * token : {"<unk>", "<s>", "<|endoftext|>"}) {
  1754. _set_token_attr(token, LLAMA_TOKEN_ATTR_RSTRIP, false);
  1755. }
  1756. }
  1757. }
  1758. }
  1759. enum llama_vocab_type llama_vocab::impl::get_type() const {
  1760. return type;
  1761. }
  1762. std::string llama_vocab::impl::type_name() const{
  1763. switch (type) {
  1764. case LLAMA_VOCAB_TYPE_NONE: return "no vocab";
  1765. case LLAMA_VOCAB_TYPE_SPM: return "SPM";
  1766. case LLAMA_VOCAB_TYPE_BPE: return "BPE";
  1767. case LLAMA_VOCAB_TYPE_WPM: return "WPM";
  1768. case LLAMA_VOCAB_TYPE_UGM: return "UGM";
  1769. case LLAMA_VOCAB_TYPE_RWKV: return "RWKV";
  1770. default: return "unknown";
  1771. }
  1772. }
  1773. bool llama_vocab::impl::is_normal(llama_token id) const {
  1774. GGML_ASSERT(type != LLAMA_VOCAB_TYPE_NONE);
  1775. return id_to_token[id].attr & LLAMA_TOKEN_ATTR_NORMAL;
  1776. }
  1777. bool llama_vocab::impl::is_unknown(llama_token id) const {
  1778. GGML_ASSERT(type != LLAMA_VOCAB_TYPE_NONE);
  1779. return id_to_token[id].attr & LLAMA_TOKEN_ATTR_UNKNOWN;
  1780. }
  1781. bool llama_vocab::impl::is_control(llama_token id) const {
  1782. GGML_ASSERT(type != LLAMA_VOCAB_TYPE_NONE);
  1783. return id_to_token[id].attr & LLAMA_TOKEN_ATTR_CONTROL;
  1784. }
  1785. bool llama_vocab::impl::is_byte(llama_token id) const {
  1786. GGML_ASSERT(type != LLAMA_VOCAB_TYPE_NONE);
  1787. return id_to_token[id].attr & LLAMA_TOKEN_ATTR_BYTE;
  1788. }
  1789. bool llama_vocab::impl::is_user_defined(llama_token id) const {
  1790. GGML_ASSERT(type != LLAMA_VOCAB_TYPE_NONE);
  1791. return id_to_token[id].attr & LLAMA_TOKEN_ATTR_USER_DEFINED;
  1792. }
  1793. bool llama_vocab::impl::is_unused(llama_token id) const {
  1794. GGML_ASSERT(type != LLAMA_VOCAB_TYPE_NONE);
  1795. return id_to_token[id].attr & LLAMA_TOKEN_ATTR_UNUSED;
  1796. }
  1797. bool llama_vocab::impl::is_eog(llama_token id) const {
  1798. return id != LLAMA_TOKEN_NULL && special_eog_ids.count(id) > 0;
  1799. }
  1800. uint8_t llama_vocab::impl::token_to_byte(llama_token id) const {
  1801. GGML_ASSERT(get_type() != LLAMA_VOCAB_TYPE_NONE);
  1802. GGML_ASSERT(is_byte(id));
  1803. const auto & token_data = id_to_token.at(id);
  1804. switch (get_type()) {
  1805. case LLAMA_VOCAB_TYPE_SPM:
  1806. case LLAMA_VOCAB_TYPE_UGM: {
  1807. auto buf = token_data.text.substr(3, 2);
  1808. return strtol(buf.c_str(), NULL, 16);
  1809. }
  1810. case LLAMA_VOCAB_TYPE_BPE: {
  1811. GGML_ABORT("fatal error");
  1812. }
  1813. case LLAMA_VOCAB_TYPE_WPM: {
  1814. GGML_ABORT("fatal error");
  1815. }
  1816. default:
  1817. GGML_ABORT("fatal error");
  1818. }
  1819. }
  1820. llama_token_attr llama_vocab::impl::token_get_attr(llama_token id) const {
  1821. GGML_ASSERT(type != LLAMA_VOCAB_TYPE_NONE);
  1822. return id_to_token.at(id).attr;
  1823. }
  1824. void llama_vocab::impl::init_tokenizer(enum llama_vocab_type type) {
  1825. LLAMA_LOG_DEBUG("%s: initializing tokenizer for type %d\n", __func__, type);
  1826. switch (type) {
  1827. case LLAMA_VOCAB_TYPE_SPM:
  1828. tokenizer = std::make_unique<llm_tokenizer_spm>(vocab);
  1829. break;
  1830. case LLAMA_VOCAB_TYPE_BPE:
  1831. tokenizer = std::make_unique<llm_tokenizer_bpe>(vocab);
  1832. break;
  1833. case LLAMA_VOCAB_TYPE_WPM:
  1834. tokenizer = std::make_unique<llm_tokenizer_wpm>(vocab);
  1835. break;
  1836. case LLAMA_VOCAB_TYPE_UGM:
  1837. tokenizer = std::make_unique<llm_tokenizer_ugm>(vocab, precompiled_charsmap);
  1838. break;
  1839. case LLAMA_VOCAB_TYPE_RWKV:
  1840. tokenizer = std::make_unique<llm_tokenizer_rwkv>(vocab);
  1841. break;
  1842. default:
  1843. GGML_ABORT("unsupported vocab type");
  1844. }
  1845. }
  1846. //
  1847. // (de-) tokenize
  1848. //
  1849. // #define PRETOKENIZERDEBUG
  1850. void llama_vocab::impl::tokenizer_st_partition(std::forward_list<fragment_buffer_variant> & buffer, bool parse_special) const {
  1851. // for each special token
  1852. for (const llama_token special_id : cache_special_tokens) {
  1853. const auto & data = vocab.get_token_data(special_id);
  1854. const auto & text = data.text;
  1855. if (!parse_special && (data.attr & (LLAMA_TOKEN_ATTR_CONTROL | LLAMA_TOKEN_ATTR_UNKNOWN))) {
  1856. // Ignore control and unknown tokens when parse_special == false
  1857. continue;
  1858. // User-defined tokens are still pre-tokenized before everything else
  1859. // ref: https://github.com/huggingface/tokenizers/blob/fdd26ba9a3f0c133427aab0423888cbde91362d7/tokenizers/src/tokenizer/mod.rs#L726
  1860. // This is mostly relevant for neox-style tokenizers (mpt, olmo, stablelm, etc.)
  1861. }
  1862. // for each text fragment
  1863. std::forward_list<fragment_buffer_variant>::iterator it = buffer.begin();
  1864. while (it != buffer.end()) {
  1865. auto & fragment = (*it);
  1866. // if a fragment is text ( not yet processed )
  1867. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  1868. const auto & raw_text = fragment.raw_text;
  1869. auto raw_text_base_offset = fragment.offset;
  1870. auto raw_text_base_length = fragment.length;
  1871. // loop over the text
  1872. while (true) {
  1873. // find the first occurrence of a given special token in this fragment
  1874. // passing offset argument only limit the "search area" but match coordinates
  1875. // are still relative to the source full raw_text
  1876. auto match = raw_text.find(text, raw_text_base_offset);
  1877. // no occurrences found, stop processing this fragment for a given special token
  1878. if (match == std::string::npos) break;
  1879. // check if match is within bounds of offset <-> length
  1880. if (match + text.length() > raw_text_base_offset + raw_text_base_length) break;
  1881. #ifdef PRETOKENIZERDEBUG
  1882. 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());
  1883. #endif
  1884. auto source = std::distance(buffer.begin(), it);
  1885. // if match is further than base offset
  1886. // then we have some text to the left of it
  1887. if (match > raw_text_base_offset) {
  1888. // left
  1889. const int64_t left_reminder_offset = raw_text_base_offset + 0;
  1890. int64_t left_reminder_length = match - raw_text_base_offset;
  1891. if (data.attr & LLAMA_TOKEN_ATTR_LSTRIP) {
  1892. while (left_reminder_length > 0 && isspace(raw_text[left_reminder_offset + left_reminder_length - 1])) {
  1893. left_reminder_length--;
  1894. }
  1895. }
  1896. if (left_reminder_length > 0) {
  1897. buffer.emplace_after(it, raw_text, left_reminder_offset, left_reminder_length);
  1898. it++;
  1899. }
  1900. #ifdef PRETOKENIZERDEBUG
  1901. 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());
  1902. #endif
  1903. }
  1904. // special token
  1905. buffer.emplace_after(it, special_id);
  1906. it++;
  1907. // right
  1908. if (match + text.length() < raw_text_base_offset + raw_text_base_length) {
  1909. int64_t right_reminder_offset = match + text.length();
  1910. int64_t right_reminder_length = raw_text_base_length - ((match - raw_text_base_offset) + text.length());
  1911. if (data.attr & LLAMA_TOKEN_ATTR_RSTRIP) {
  1912. while (right_reminder_length > 0 && isspace(raw_text[right_reminder_offset])) {
  1913. right_reminder_offset++;
  1914. right_reminder_length--;
  1915. }
  1916. }
  1917. if (right_reminder_length > 0) {
  1918. buffer.emplace_after(it, raw_text, right_reminder_offset, right_reminder_length);
  1919. it++;
  1920. }
  1921. #ifdef PRETOKENIZERDEBUG
  1922. 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());
  1923. #endif
  1924. if (source == 0) {
  1925. buffer.erase_after(buffer.before_begin());
  1926. } else {
  1927. buffer.erase_after(std::next(buffer.begin(), (source - 1)));
  1928. }
  1929. // repeat for the right side
  1930. raw_text_base_offset = right_reminder_offset;
  1931. raw_text_base_length = right_reminder_length;
  1932. #ifdef PRETOKENIZERDEBUG
  1933. 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());
  1934. #endif
  1935. } else {
  1936. if (source == 0) {
  1937. buffer.erase_after(buffer.before_begin());
  1938. } else {
  1939. buffer.erase_after(std::next(buffer.begin(), (source - 1)));
  1940. }
  1941. break;
  1942. }
  1943. }
  1944. }
  1945. it++;
  1946. }
  1947. }
  1948. }
  1949. // NOTE: avoid ever using this except for building the token_to_piece caches
  1950. std::string llama_vocab::impl::token_to_piece_for_cache(llama_token token, bool special) const {
  1951. std::string piece;
  1952. piece.resize(piece.capacity()); // using string internal cache
  1953. const int n_chars = vocab.token_to_piece(token, &piece[0], piece.size(), 0, special);
  1954. if (n_chars < 0) {
  1955. piece.resize(-n_chars);
  1956. int check = vocab.token_to_piece(token, &piece[0], piece.size(), 0, special);
  1957. GGML_ASSERT(check == -n_chars);
  1958. }
  1959. else {
  1960. piece.resize(n_chars);
  1961. }
  1962. return piece;
  1963. }
  1964. static void llama_escape_whitespace(std::string & text) {
  1965. replace_all(text, " ", "\xe2\x96\x81");
  1966. }
  1967. static void llama_unescape_whitespace(std::string & word) {
  1968. replace_all(word, "\xe2\x96\x81", " ");
  1969. }
  1970. static std::string llama_decode_text(const std::string & text) {
  1971. std::string decoded_text;
  1972. const auto cpts = unicode_cpts_from_utf8(text);
  1973. for (const auto cpt : cpts) {
  1974. const auto utf8 = unicode_cpt_to_utf8(cpt);
  1975. try {
  1976. decoded_text += unicode_utf8_to_byte(utf8);
  1977. } catch (const std::out_of_range & /*e*/) {
  1978. decoded_text += "[UNK_BYTE_0x";
  1979. for (const auto c : utf8) {
  1980. decoded_text += format("%02x", (uint8_t) c);
  1981. }
  1982. decoded_text += text + "]";
  1983. }
  1984. }
  1985. return decoded_text;
  1986. }
  1987. std::vector<llama_token> llama_vocab::impl::tokenize(
  1988. const std::string & raw_text,
  1989. bool add_special,
  1990. bool parse_special) const {
  1991. GGML_ASSERT(tokenizer && "Tokenizer not initialized. Call llama_vocab::init_tokenizer() first.");
  1992. std::vector<llama_token> output;
  1993. std::forward_list<fragment_buffer_variant> fragment_buffer;
  1994. if (!raw_text.empty()) {
  1995. fragment_buffer.emplace_front(raw_text, 0, raw_text.length());
  1996. tokenizer_st_partition(fragment_buffer, parse_special);
  1997. }
  1998. switch (get_type()) {
  1999. case LLAMA_VOCAB_TYPE_SPM:
  2000. {
  2001. // OG tokenizer behavior:
  2002. //
  2003. // tokenizer.encode('', add_special_tokens=True) returns [1]
  2004. // tokenizer.encode('', add_special_tokens=False) returns []
  2005. bool is_prev_special = true; // prefix with space if first token
  2006. if (add_special && add_bos) {
  2007. GGML_ASSERT(special_bos_id != LLAMA_TOKEN_NULL);
  2008. output.push_back(special_bos_id);
  2009. is_prev_special = true;
  2010. }
  2011. for (const auto & fragment : fragment_buffer) {
  2012. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  2013. std::string text;
  2014. // prefix with space if previous is special
  2015. if (add_space_prefix && is_prev_special) {
  2016. text = ' ';
  2017. }
  2018. text += fragment.raw_text.substr(fragment.offset, fragment.length);
  2019. #ifdef PRETOKENIZERDEBUG
  2020. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", text.length(), fragment.offset, fragment.length, text.c_str());
  2021. #endif
  2022. llama_escape_whitespace(text);
  2023. llm_tokenizer_spm_session session(vocab);
  2024. session.tokenize(text, output);
  2025. is_prev_special = false;
  2026. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  2027. output.push_back(fragment.token);
  2028. is_prev_special = true;
  2029. }
  2030. }
  2031. if (add_special && add_bos && output.size() >= 2 && output[1] == special_bos_id) {
  2032. LLAMA_LOG_WARN(
  2033. "%s: Added a BOS token to the prompt as specified by the model but the prompt "
  2034. "also starts with a BOS token. So now the final prompt starts with 2 BOS tokens. "
  2035. "Are you sure this is what you want?\n", __FUNCTION__);
  2036. }
  2037. if (add_special && add_eos) {
  2038. GGML_ASSERT(special_eos_id != LLAMA_TOKEN_NULL);
  2039. output.push_back(special_eos_id);
  2040. }
  2041. } break;
  2042. case LLAMA_VOCAB_TYPE_BPE:
  2043. {
  2044. llm_tokenizer_bpe_session session(vocab, *static_cast<const llm_tokenizer_bpe *>(tokenizer.get()));
  2045. // it calls some other methods that are not exist in llm_tokenizer,
  2046. // here just cast it to bpe tokenizer object
  2047. if (add_special) {
  2048. session.append_bos(output);
  2049. }
  2050. for (const auto & fragment : fragment_buffer) {
  2051. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  2052. std::string text = fragment.raw_text.substr(fragment.offset, fragment.length);
  2053. #ifdef PRETOKENIZERDEBUG
  2054. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", text.length(), fragment.offset, fragment.length, text.c_str());
  2055. #endif
  2056. session.tokenize(text, output);
  2057. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  2058. session.append(fragment.token, output);
  2059. }
  2060. }
  2061. if (add_special) {
  2062. session.append_eos(output);
  2063. session.check_double_bos_eos(output);
  2064. }
  2065. } break;
  2066. case LLAMA_VOCAB_TYPE_WPM:
  2067. {
  2068. if (add_special) {
  2069. GGML_ASSERT(special_bos_id != LLAMA_TOKEN_NULL);
  2070. output.push_back(special_bos_id);
  2071. }
  2072. llm_tokenizer_wpm_session session(vocab);
  2073. for (const auto & fragment : fragment_buffer) {
  2074. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  2075. std::string text = fragment.raw_text.substr(fragment.offset, fragment.length);
  2076. #ifdef PRETOKENIZERDEBUG
  2077. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", text.length(), fragment.offset, fragment.length, text.c_str());
  2078. #endif
  2079. session.tokenize(text, output);
  2080. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  2081. output.push_back(fragment.token);
  2082. }
  2083. }
  2084. if (add_special) {
  2085. GGML_ASSERT(special_sep_id != LLAMA_TOKEN_NULL);
  2086. output.push_back(special_sep_id);
  2087. }
  2088. } break;
  2089. case LLAMA_VOCAB_TYPE_UGM:
  2090. {
  2091. if (add_special && add_bos) {
  2092. GGML_ASSERT(special_bos_id != LLAMA_TOKEN_NULL);
  2093. output.push_back(special_bos_id);
  2094. }
  2095. llm_tokenizer_ugm_session session(vocab, *static_cast<const llm_tokenizer_ugm *>(tokenizer.get()));
  2096. for (const auto & fragment : fragment_buffer) {
  2097. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  2098. std::string text = fragment.raw_text.substr(fragment.offset, fragment.length);
  2099. #ifdef PRETOKENIZERDEBUG
  2100. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", text.length(), fragment.offset, fragment.length, text.c_str());
  2101. #endif
  2102. session.tokenize(text, output);
  2103. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  2104. output.push_back(fragment.token);
  2105. }
  2106. }
  2107. if (add_special && add_bos && output.size() >= 2 && output[1] == special_bos_id) {
  2108. LLAMA_LOG_WARN(
  2109. "%s: Added a BOS token to the prompt as specified by the model but the prompt "
  2110. "also starts with a BOS token. So now the final prompt starts with 2 BOS tokens. "
  2111. "Are you sure this is what you want?\n", __FUNCTION__);
  2112. }
  2113. if (add_special && add_eos) {
  2114. GGML_ASSERT(special_eos_id != LLAMA_TOKEN_NULL);
  2115. output.push_back(special_eos_id);
  2116. }
  2117. } break;
  2118. case LLAMA_VOCAB_TYPE_RWKV:
  2119. {
  2120. llm_tokenizer_rwkv_session session(vocab, *static_cast<const llm_tokenizer_rwkv *>(tokenizer.get()));
  2121. for (const auto & fragment : fragment_buffer) {
  2122. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  2123. std::string text = fragment.raw_text.substr(fragment.offset, fragment.length);
  2124. #ifdef PRETOKENIZERDEBUG
  2125. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", text.length(), fragment.offset, fragment.length, text.c_str());
  2126. #endif
  2127. session.tokenize(text, output);
  2128. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  2129. output.push_back(fragment.token);
  2130. }
  2131. }
  2132. } break;
  2133. case LLAMA_VOCAB_TYPE_NONE:
  2134. GGML_ABORT("fatal error");
  2135. }
  2136. return output;
  2137. }
  2138. int32_t llama_vocab::impl::token_to_piece(llama_token token, char * buf, int32_t length, int32_t lstrip, bool special) const {
  2139. // ref: https://github.com/ggerganov/llama.cpp/pull/7587#discussion_r1620983843
  2140. static const int attr_special = LLAMA_TOKEN_ATTR_UNKNOWN | LLAMA_TOKEN_ATTR_CONTROL;
  2141. const llama_token_attr attr = token_get_attr(token);
  2142. if (!special && (attr & attr_special)) {
  2143. return 0;
  2144. }
  2145. // copy piece chars to output text buffer
  2146. // skip up to 'lstrip' leading spaces before copying
  2147. auto _try_copy = [=] (const char * token, size_t size) -> int32_t {
  2148. for (int32_t i = 0; i < lstrip && size && *token == ' '; ++i) {
  2149. token++;
  2150. size--;
  2151. }
  2152. if (length < (int32_t)size) {
  2153. return -(int32_t) size;
  2154. }
  2155. memcpy(buf, token, size);
  2156. return (int32_t) size;
  2157. };
  2158. // if we have a cache - use it
  2159. {
  2160. const auto & cache = cache_token_to_piece;
  2161. if (!cache.empty()) {
  2162. const auto & result = cache.at(token);
  2163. return _try_copy(result.data(), result.size());
  2164. }
  2165. }
  2166. if (0 <= token && token < (int32_t) id_to_token.size()) {
  2167. const std::string & token_text = id_to_token[token].text;
  2168. switch (get_type()) {
  2169. case LLAMA_VOCAB_TYPE_WPM:
  2170. case LLAMA_VOCAB_TYPE_SPM:
  2171. case LLAMA_VOCAB_TYPE_UGM: {
  2172. // NOTE: we accept all unsupported token types,
  2173. // suppressing them like CONTROL tokens.
  2174. if (attr & (attr_special | LLAMA_TOKEN_ATTR_USER_DEFINED)) {
  2175. return _try_copy(token_text.data(), token_text.size());
  2176. }
  2177. if (attr & LLAMA_TOKEN_ATTR_NORMAL) {
  2178. std::string result = token_text;
  2179. llama_unescape_whitespace(result);
  2180. return _try_copy(result.data(), result.size());
  2181. }
  2182. if (attr & LLAMA_TOKEN_ATTR_BYTE) {
  2183. char byte = (char) token_to_byte(token);
  2184. return _try_copy((char*) &byte, 1);
  2185. }
  2186. break;
  2187. }
  2188. case LLAMA_VOCAB_TYPE_BPE: {
  2189. // NOTE: we accept all unsupported token types,
  2190. // suppressing them like CONTROL tokens.
  2191. if (attr & (attr_special | LLAMA_TOKEN_ATTR_USER_DEFINED)) {
  2192. return _try_copy(token_text.data(), token_text.size());
  2193. }
  2194. if (attr & LLAMA_TOKEN_ATTR_NORMAL) {
  2195. std::string result = llama_decode_text(token_text);
  2196. return _try_copy(result.data(), result.size());
  2197. }
  2198. break;
  2199. }
  2200. case LLAMA_VOCAB_TYPE_RWKV: {
  2201. std::vector<uint8_t> result = llama_unescape_rwkv_token(token_text);
  2202. // If we don't have enough space, return an error
  2203. if (result.size() > (size_t)length) {
  2204. return -(int)result.size();
  2205. }
  2206. memcpy(buf, result.data(), result.size());
  2207. return (int)result.size();
  2208. }
  2209. default:
  2210. GGML_ABORT("fatal error");
  2211. }
  2212. }
  2213. return 0;
  2214. }
  2215. const std::string & llama_vocab::impl::token_to_piece(llama_token token) const {
  2216. return cache_token_to_piece.at(token);
  2217. }
  2218. int32_t llama_vocab::impl::detokenize(
  2219. const llama_token * tokens,
  2220. int32_t n_tokens,
  2221. char * text,
  2222. int32_t text_len_max,
  2223. bool remove_special,
  2224. bool unparse_special) const {
  2225. if (type == LLAMA_VOCAB_TYPE_NONE) {
  2226. return 0;
  2227. }
  2228. GGML_ASSERT(tokenizer && "Tokenizer not initialized. Call llama_vocab::init_tokenizer() first.");
  2229. int32_t avail = text_len_max;
  2230. int32_t total = 0;
  2231. // remove the leading space
  2232. bool remove_space = add_space_prefix;
  2233. if (remove_special && add_bos) {
  2234. if (n_tokens > 0 && tokens[0] == special_bos_id) {
  2235. remove_space = false;
  2236. n_tokens--;
  2237. tokens++;
  2238. }
  2239. }
  2240. if (remove_special && add_eos) {
  2241. if (n_tokens > 0 && tokens[n_tokens - 1] == special_eos_id) {
  2242. n_tokens--;
  2243. }
  2244. }
  2245. for (int32_t i = 0; i < n_tokens; ++i) {
  2246. GGML_ASSERT(avail >= 0);
  2247. int32_t n_chars = token_to_piece(tokens[i], text, avail, remove_space, unparse_special);
  2248. remove_space = false;
  2249. if (n_chars < 0) {
  2250. avail = 0;
  2251. total -= n_chars;
  2252. } else if (n_chars > 0) {
  2253. avail -= n_chars;
  2254. text += n_chars;
  2255. total += n_chars;
  2256. }
  2257. }
  2258. if (total > text_len_max) {
  2259. return -total;
  2260. }
  2261. if (clean_spaces) {
  2262. text -= total; // restart text
  2263. // first pass: characters ?!., //TODO: where do these characters come from?
  2264. const int32_t total1 = total;
  2265. total = total ? 1 : 0;
  2266. for (int32_t i = 1; i < total1; ++i) {
  2267. const char x = text[i];
  2268. if (text[i - 1] == ' ') {
  2269. if (x == '?' || x == '!' || x == '.' || x == ',') { // " ?", " !", " .", " ,"
  2270. total--; // remove space
  2271. }
  2272. }
  2273. text[total++] = x;
  2274. }
  2275. // second pass: strip single apostrophe between spaces
  2276. const int32_t total2 = total;
  2277. total = total ? 1 : 0;
  2278. for (int32_t i = 1; i < total2; ++i) {
  2279. const char x = text[i];
  2280. if (x == '\'' && i + 1 < total2 && text[i - 1] == ' ' && text[i + 1] == ' ') { // " ' "
  2281. total--; // remove prev space
  2282. text[++i] = '\0'; // remove next space
  2283. }
  2284. text[total++] = x;
  2285. }
  2286. // third pass: apostrophe contractions //NOTE: this makes sense?
  2287. const int32_t total3 = total;
  2288. total = total ? 1 : 0;
  2289. for (int32_t i = 1; i < total3; ++i) {
  2290. const char x = text[i];
  2291. if (text[i - 1] == ' ') {
  2292. if (x == '\'' && i + 1 < total3) {
  2293. const char x1 = text[i + 1];
  2294. if (x1 == 't' || x1 == 'd') { // " 't", " 'd"
  2295. //total--; // remove space
  2296. } else if (x1 == 's' || x1 == 'm') { // " 's", " 'm"
  2297. total--; // remove space
  2298. } else if (i + 2 < total3) {
  2299. const char x2 = text[i + 2];
  2300. if ((x1 == 'l' && x2 == 'l')) { // " 'll"
  2301. //total--; // remove space
  2302. } else if ((x1 == 'r' && x2 == 'e') || (x1 == 'v' && x2 == 'e')) { // " 're", " 've"
  2303. total--; // remove space
  2304. } else {
  2305. //total--; // remove space
  2306. }
  2307. } else {
  2308. //total--; // remove space
  2309. }
  2310. }
  2311. }
  2312. text[total++] = x;
  2313. }
  2314. }
  2315. return total <= text_len_max ? total : -total;
  2316. }
  2317. void llama_vocab::impl::print_info() const {
  2318. LLAMA_LOG_INFO("%s: vocab type = %s\n", __func__, type_name().c_str());
  2319. LLAMA_LOG_INFO("%s: n_vocab = %u\n", __func__, vocab.n_tokens());
  2320. LLAMA_LOG_INFO("%s: n_merges = %u\n", __func__, (uint32_t) bpe_ranks.size());
  2321. // special tokens
  2322. if (special_bos_id != LLAMA_TOKEN_NULL) { LLAMA_LOG_INFO( "%s: BOS token = %d '%s'\n", __func__, special_bos_id, id_to_token[special_bos_id].text.c_str() ); }
  2323. if (special_eos_id != LLAMA_TOKEN_NULL) { LLAMA_LOG_INFO( "%s: EOS token = %d '%s'\n", __func__, special_eos_id, id_to_token[special_eos_id].text.c_str() ); }
  2324. if (special_eot_id != LLAMA_TOKEN_NULL) { LLAMA_LOG_INFO( "%s: EOT token = %d '%s'\n", __func__, special_eot_id, id_to_token[special_eot_id].text.c_str() ); }
  2325. if (special_eom_id != LLAMA_TOKEN_NULL) { LLAMA_LOG_INFO( "%s: EOM token = %d '%s'\n", __func__, special_eom_id, id_to_token[special_eom_id].text.c_str() ); }
  2326. if (special_unk_id != LLAMA_TOKEN_NULL) { LLAMA_LOG_INFO( "%s: UNK token = %d '%s'\n", __func__, special_unk_id, id_to_token[special_unk_id].text.c_str() ); }
  2327. if (special_sep_id != LLAMA_TOKEN_NULL) { LLAMA_LOG_INFO( "%s: SEP token = %d '%s'\n", __func__, special_sep_id, id_to_token[special_sep_id].text.c_str() ); }
  2328. if (special_pad_id != LLAMA_TOKEN_NULL) { LLAMA_LOG_INFO( "%s: PAD token = %d '%s'\n", __func__, special_pad_id, id_to_token[special_pad_id].text.c_str() ); }
  2329. if (special_mask_id != LLAMA_TOKEN_NULL) { LLAMA_LOG_INFO( "%s: MASK token = %d '%s'\n", __func__, special_mask_id, id_to_token[special_mask_id].text.c_str() ); }
  2330. if (linefeed_id != LLAMA_TOKEN_NULL) { LLAMA_LOG_INFO( "%s: LF token = %d '%s'\n", __func__, linefeed_id, id_to_token[linefeed_id].text.c_str() ); }
  2331. if (special_fim_pre_id != LLAMA_TOKEN_NULL) { LLAMA_LOG_INFO( "%s: FIM PRE token = %d '%s'\n", __func__, special_fim_pre_id, id_to_token[special_fim_pre_id].text.c_str() ); }
  2332. if (special_fim_suf_id != LLAMA_TOKEN_NULL) { LLAMA_LOG_INFO( "%s: FIM SUF token = %d '%s'\n", __func__, special_fim_suf_id, id_to_token[special_fim_suf_id].text.c_str() ); }
  2333. if (special_fim_mid_id != LLAMA_TOKEN_NULL) { LLAMA_LOG_INFO( "%s: FIM MID token = %d '%s'\n", __func__, special_fim_mid_id, id_to_token[special_fim_mid_id].text.c_str() ); }
  2334. if (special_fim_pad_id != LLAMA_TOKEN_NULL) { LLAMA_LOG_INFO( "%s: FIM PAD token = %d '%s'\n", __func__, special_fim_pad_id, id_to_token[special_fim_pad_id].text.c_str() ); }
  2335. if (special_fim_rep_id != LLAMA_TOKEN_NULL) { LLAMA_LOG_INFO( "%s: FIM REP token = %d '%s'\n", __func__, special_fim_rep_id, id_to_token[special_fim_rep_id].text.c_str() ); }
  2336. if (special_fim_sep_id != LLAMA_TOKEN_NULL) { LLAMA_LOG_INFO( "%s: FIM SEP token = %d '%s'\n", __func__, special_fim_sep_id, id_to_token[special_fim_sep_id].text.c_str() ); }
  2337. for (const auto & id : special_eog_ids) {
  2338. LLAMA_LOG_INFO( "%s: EOG token = %d '%s'\n", __func__, id, id_to_token[id].text.c_str() );
  2339. }
  2340. LLAMA_LOG_INFO("%s: max token length = %d\n", __func__, max_token_len);
  2341. }
  2342. llama_vocab::llama_vocab() : pimpl(new impl(*this)) {
  2343. }
  2344. llama_vocab::~llama_vocab() {
  2345. }
  2346. void llama_vocab::load(llama_model_loader & ml, const LLM_KV & kv) {
  2347. pimpl->load(ml, kv);
  2348. }
  2349. enum llama_vocab_type llama_vocab::get_type() const {
  2350. return pimpl->type;
  2351. }
  2352. enum llama_vocab_pre_type llama_vocab::get_pre_type() const {
  2353. return pimpl->pre_type;
  2354. }
  2355. uint32_t llama_vocab::n_tokens() const {
  2356. return (uint32_t) pimpl->id_to_token.size();
  2357. }
  2358. uint32_t llama_vocab::n_token_types() const {
  2359. return (uint32_t) pimpl->n_token_types;
  2360. }
  2361. std::string llama_vocab::type_name() const{
  2362. return pimpl->type_name();
  2363. }
  2364. bool llama_vocab::is_normal(llama_token id) const {
  2365. return pimpl->is_normal(id);
  2366. }
  2367. bool llama_vocab::is_unknown(llama_token id) const {
  2368. return pimpl->is_unknown(id);
  2369. }
  2370. bool llama_vocab::is_control(llama_token id) const {
  2371. return pimpl->is_control(id);
  2372. }
  2373. bool llama_vocab::is_byte(llama_token id) const {
  2374. return pimpl->is_byte(id);
  2375. }
  2376. bool llama_vocab::is_user_defined(llama_token id) const {
  2377. return pimpl->is_user_defined(id);
  2378. }
  2379. bool llama_vocab::is_unused(llama_token id) const {
  2380. return pimpl->is_unused(id);
  2381. }
  2382. bool llama_vocab::is_eog(llama_token id) const {
  2383. return pimpl->is_eog(id);
  2384. }
  2385. uint8_t llama_vocab::token_to_byte(llama_token id) const {
  2386. return pimpl->token_to_byte(id);
  2387. }
  2388. llama_token llama_vocab::byte_to_token(uint8_t ch) const {
  2389. GGML_ASSERT(get_type() != LLAMA_VOCAB_TYPE_NONE);
  2390. static const char * hex = "0123456789ABCDEF";
  2391. switch (get_type()) {
  2392. case LLAMA_VOCAB_TYPE_SPM:
  2393. case LLAMA_VOCAB_TYPE_UGM: {
  2394. const char buf[7] = { '<', '0', 'x', hex[ch >> 4], hex[ch & 15], '>', 0 };
  2395. auto token = pimpl->token_to_id.find(buf);
  2396. if (token != pimpl->token_to_id.end()) {
  2397. return (*token).second;
  2398. }
  2399. // Try to fall back to just the byte as a string
  2400. const char buf2[2] = { (char)ch, 0 };
  2401. return pimpl->token_to_id.at(buf2);
  2402. }
  2403. case LLAMA_VOCAB_TYPE_WPM:
  2404. case LLAMA_VOCAB_TYPE_BPE: {
  2405. return pimpl->token_to_id.at(unicode_byte_to_utf8(ch));
  2406. }
  2407. default:
  2408. GGML_ABORT("fatal error");
  2409. }
  2410. }
  2411. llama_token llama_vocab::text_to_token(const std::string & text) const {
  2412. GGML_ASSERT(pimpl->type != LLAMA_VOCAB_TYPE_NONE);
  2413. auto it = pimpl->token_to_id.find(text);
  2414. if (it != pimpl->token_to_id.end()) {
  2415. return (*it).second;
  2416. }
  2417. return LLAMA_TOKEN_NULL;
  2418. }
  2419. const llama_vocab::token_data & llama_vocab::get_token_data(llama_token id) const {
  2420. GGML_ASSERT(pimpl->type != LLAMA_VOCAB_TYPE_NONE);
  2421. return pimpl->id_to_token.at(id);
  2422. }
  2423. const char * llama_vocab::token_get_text(llama_token id) const {
  2424. GGML_ASSERT(pimpl->type != LLAMA_VOCAB_TYPE_NONE);
  2425. return pimpl->id_to_token.at(id).text.c_str();
  2426. }
  2427. float llama_vocab::token_get_score(llama_token id) const {
  2428. GGML_ASSERT(pimpl->type != LLAMA_VOCAB_TYPE_NONE);
  2429. return pimpl->id_to_token.at(id).score;
  2430. }
  2431. llama_token_attr llama_vocab::token_get_attr(llama_token id) const {
  2432. return pimpl->token_get_attr(id);
  2433. }
  2434. llama_token llama_vocab::token_bos() const {
  2435. return pimpl->special_bos_id;
  2436. }
  2437. llama_token llama_vocab::token_eos() const {
  2438. return pimpl->special_eos_id;
  2439. }
  2440. llama_token llama_vocab::token_eot() const {
  2441. return pimpl->special_eot_id;
  2442. }
  2443. llama_token llama_vocab::token_eom() const {
  2444. return pimpl->special_eom_id;
  2445. }
  2446. llama_token llama_vocab::token_unk() const {
  2447. return pimpl->special_unk_id;
  2448. }
  2449. llama_token llama_vocab::token_sep() const {
  2450. return pimpl->special_sep_id;
  2451. }
  2452. llama_token llama_vocab::token_nl() const {
  2453. return pimpl->linefeed_id;
  2454. }
  2455. llama_token llama_vocab::token_pad() const {
  2456. return pimpl->special_pad_id;
  2457. }
  2458. llama_token llama_vocab::token_prefix() const {
  2459. return pimpl->special_fim_pre_id;
  2460. }
  2461. llama_token llama_vocab::token_middle() const {
  2462. return pimpl->special_fim_mid_id;
  2463. }
  2464. llama_token llama_vocab::token_suffix() const {
  2465. return pimpl->special_fim_suf_id;
  2466. }
  2467. llama_token llama_vocab::token_fim_pre() const {
  2468. return pimpl->special_fim_pre_id;
  2469. }
  2470. llama_token llama_vocab::token_fim_suf() const {
  2471. return pimpl->special_fim_suf_id;
  2472. }
  2473. llama_token llama_vocab::token_fim_mid() const {
  2474. return pimpl->special_fim_mid_id;
  2475. }
  2476. llama_token llama_vocab::token_fim_pad() const {
  2477. return pimpl->special_fim_pad_id;
  2478. }
  2479. llama_token llama_vocab::token_fim_rep() const {
  2480. return pimpl->special_fim_rep_id;
  2481. }
  2482. llama_token llama_vocab::token_fim_sep() const {
  2483. return pimpl->special_fim_sep_id;
  2484. }
  2485. bool llama_vocab::get_add_space_prefix() const {
  2486. return pimpl->add_space_prefix;
  2487. }
  2488. bool llama_vocab::get_add_bos() const {
  2489. return pimpl->add_bos;
  2490. }
  2491. bool llama_vocab::get_add_eos() const {
  2492. return pimpl->add_eos;
  2493. }
  2494. bool llama_vocab::get_ignore_merges() const {
  2495. return pimpl->ignore_merges;
  2496. }
  2497. bool llama_vocab::get_clean_spaces() const {
  2498. return pimpl->clean_spaces;
  2499. }
  2500. bool llama_vocab::get_remove_extra_whitespaces() const {
  2501. return pimpl->remove_extra_whitespaces;
  2502. }
  2503. bool llama_vocab::get_escape_whitespaces() const {
  2504. return pimpl->escape_whitespaces;
  2505. }
  2506. bool llama_vocab::get_treat_whitespace_as_suffix() const {
  2507. return pimpl->treat_whitespace_as_suffix;
  2508. }
  2509. int llama_vocab::max_token_len() const {
  2510. return pimpl->max_token_len;
  2511. }
  2512. int llama_vocab::find_bpe_rank(const std::string & token_left, const std::string & token_right) const {
  2513. GGML_ASSERT(token_left.find(' ') == std::string::npos);
  2514. GGML_ASSERT(token_left.find('\n') == std::string::npos);
  2515. GGML_ASSERT(token_right.find(' ') == std::string::npos);
  2516. GGML_ASSERT(token_right.find('\n') == std::string::npos);
  2517. auto it = pimpl->bpe_ranks.find(std::make_pair(token_left, token_right));
  2518. if (it == pimpl->bpe_ranks.end()) {
  2519. return -1;
  2520. }
  2521. return it->second;
  2522. }
  2523. int32_t llama_vocab::tokenize(
  2524. const char * text,
  2525. int32_t text_len,
  2526. llama_token * tokens,
  2527. int32_t n_tokens_max,
  2528. bool add_special,
  2529. bool parse_special) const {
  2530. auto res = tokenize(std::string(text, text_len), add_special, parse_special);
  2531. if (n_tokens_max < (int) res.size()) {
  2532. // LLAMA_LOG_ERROR("%s: too many tokens\n", __func__);
  2533. return -((int) res.size());
  2534. }
  2535. for (size_t i = 0; i < res.size(); i++) {
  2536. tokens[i] = res[i];
  2537. }
  2538. return res.size();
  2539. }
  2540. std::vector<llama_token> llama_vocab::tokenize(
  2541. const std::string & raw_text,
  2542. bool add_special,
  2543. bool parse_special) const {
  2544. return pimpl->tokenize(raw_text, add_special, parse_special);
  2545. }
  2546. const std::string & llama_vocab::token_to_piece(llama_token token) const {
  2547. return pimpl->token_to_piece(token);
  2548. }
  2549. int32_t llama_vocab::token_to_piece(llama_token token, char * buf, int32_t length, int32_t lstrip, bool special) const {
  2550. return pimpl->token_to_piece(token, buf, length, lstrip, special);
  2551. }
  2552. int32_t llama_vocab::detokenize(
  2553. const llama_token * tokens,
  2554. int32_t n_tokens,
  2555. char * text,
  2556. int32_t text_len_max,
  2557. bool remove_special,
  2558. bool unparse_special) const {
  2559. return pimpl->detokenize(tokens, n_tokens, text, text_len_max, remove_special, unparse_special);
  2560. }
  2561. std::string llama_vocab::detokenize(const std::vector<llama_token> & tokens, bool special) const {
  2562. std::string text;
  2563. text.resize(std::max(text.capacity(), tokens.size()));
  2564. int32_t n_chars = detokenize(tokens.data(), (int32_t)tokens.size(), &text[0], (int32_t)text.size(), false, special);
  2565. if (n_chars < 0) {
  2566. text.resize(-n_chars);
  2567. n_chars = detokenize(tokens.data(), (int32_t)tokens.size(), &text[0], (int32_t)text.size(), false, special);
  2568. GGML_ASSERT(n_chars <= (int32_t)text.size()); // whitespace trimming is performed after per-token detokenization
  2569. }
  2570. text.resize(n_chars);
  2571. // NOTE: the original tokenizer decodes bytes after collecting the pieces.
  2572. return text;
  2573. }
  2574. void llama_vocab::print_info() const {
  2575. pimpl->print_info();
  2576. }
  2577. //
  2578. // interface implementation
  2579. //
  2580. int32_t llama_vocab_n_tokens(const struct llama_vocab * vocab) {
  2581. return vocab->n_tokens();
  2582. }
  2583. // deprecated
  2584. int32_t llama_n_vocab(const struct llama_vocab * vocab) {
  2585. return llama_vocab_n_tokens(vocab);
  2586. }
  2587. enum llama_vocab_type llama_vocab_type(const struct llama_vocab * vocab) {
  2588. return vocab->get_type();
  2589. }
  2590. const char * llama_vocab_get_text(const struct llama_vocab * vocab, llama_token token) {
  2591. return vocab->token_get_text(token);
  2592. }
  2593. float llama_vocab_get_score(const struct llama_vocab * vocab, llama_token token) {
  2594. return vocab->token_get_score(token);
  2595. }
  2596. enum llama_token_attr llama_vocab_get_attr(const struct llama_vocab * vocab, llama_token token) {
  2597. return vocab->token_get_attr(token);
  2598. }
  2599. bool llama_vocab_is_eog(const struct llama_vocab * vocab, llama_token token) {
  2600. return vocab->is_eog(token);
  2601. }
  2602. bool llama_vocab_is_control(const struct llama_vocab * vocab, llama_token token) {
  2603. return vocab->is_control(token);
  2604. }
  2605. llama_token llama_vocab_bos(const struct llama_vocab * vocab) {
  2606. return vocab->token_bos();
  2607. }
  2608. llama_token llama_vocab_eos(const struct llama_vocab * vocab) {
  2609. return vocab->token_eos();
  2610. }
  2611. llama_token llama_vocab_eot(const struct llama_vocab * vocab) {
  2612. return vocab->token_eot();
  2613. }
  2614. // deprecated
  2615. llama_token llama_vocab_cls(const struct llama_vocab * vocab) {
  2616. return vocab->token_bos();
  2617. }
  2618. llama_token llama_vocab_sep(const struct llama_vocab * vocab) {
  2619. return vocab->token_sep();
  2620. }
  2621. llama_token llama_vocab_nl (const struct llama_vocab * vocab) {
  2622. return vocab->token_nl();
  2623. }
  2624. llama_token llama_vocab_pad(const struct llama_vocab * vocab) {
  2625. return vocab->token_pad();
  2626. }
  2627. bool llama_vocab_get_add_bos(const struct llama_vocab * vocab) {
  2628. return vocab->get_add_bos();
  2629. }
  2630. bool llama_vocab_get_add_eos(const struct llama_vocab * vocab) {
  2631. return vocab->get_add_eos();
  2632. }
  2633. llama_token llama_vocab_fim_pre(const struct llama_vocab * vocab) {
  2634. return vocab->token_fim_pre();
  2635. }
  2636. llama_token llama_vocab_fim_suf(const struct llama_vocab * vocab) {
  2637. return vocab->token_fim_suf();
  2638. }
  2639. llama_token llama_vocab_fim_mid(const struct llama_vocab * vocab) {
  2640. return vocab->token_fim_mid();
  2641. }
  2642. llama_token llama_vocab_fim_pad(const struct llama_vocab * vocab) {
  2643. return vocab->token_fim_pad();
  2644. }
  2645. llama_token llama_vocab_fim_rep(const struct llama_vocab * vocab) {
  2646. return vocab->token_fim_rep();
  2647. }
  2648. llama_token llama_vocab_fim_sep(const struct llama_vocab * vocab) {
  2649. return vocab->token_fim_sep();
  2650. }
  2651. // deprecated
  2652. const char * llama_token_get_text(const struct llama_vocab * vocab, llama_token token) {
  2653. return llama_vocab_get_text(vocab, token);
  2654. }
  2655. // deprecated
  2656. float llama_token_get_score(const struct llama_vocab * vocab, llama_token token) {
  2657. return llama_vocab_get_score(vocab, token);
  2658. }
  2659. // deprecated
  2660. enum llama_token_attr llama_token_get_attr(const struct llama_vocab * vocab, llama_token token) {
  2661. return llama_vocab_get_attr(vocab, token);
  2662. }
  2663. // deprecated
  2664. bool llama_token_is_eog(const struct llama_vocab * vocab, llama_token token) {
  2665. return llama_vocab_is_eog(vocab, token);
  2666. }
  2667. // deprecated
  2668. bool llama_token_is_control(const struct llama_vocab * vocab, llama_token token) {
  2669. return llama_vocab_is_control(vocab, token);
  2670. }
  2671. // deprecated
  2672. llama_token llama_token_bos(const struct llama_vocab * vocab) {
  2673. return llama_vocab_bos(vocab);
  2674. }
  2675. // deprecated
  2676. llama_token llama_token_eos(const struct llama_vocab * vocab) {
  2677. return llama_vocab_eos(vocab);
  2678. }
  2679. // deprecated
  2680. llama_token llama_token_eot(const struct llama_vocab * vocab) {
  2681. return llama_vocab_eot(vocab);
  2682. }
  2683. // deprecated
  2684. llama_token llama_token_cls(const struct llama_vocab * vocab) {
  2685. //return llama_vocab_cls(vocab);
  2686. return llama_vocab_bos(vocab); // avoid deprecation warning
  2687. }
  2688. // deprecated
  2689. llama_token llama_token_sep(const struct llama_vocab * vocab) {
  2690. return llama_vocab_sep(vocab);
  2691. }
  2692. // deprecated
  2693. llama_token llama_token_nl (const struct llama_vocab * vocab) {
  2694. return llama_vocab_nl(vocab);
  2695. }
  2696. // deprecated
  2697. llama_token llama_token_pad(const struct llama_vocab * vocab) {
  2698. return llama_vocab_pad(vocab);
  2699. }
  2700. // deprecated
  2701. bool llama_add_bos_token(const struct llama_vocab * vocab) {
  2702. return llama_vocab_get_add_bos(vocab);
  2703. }
  2704. // deprecated
  2705. bool llama_add_eos_token(const struct llama_vocab * vocab) {
  2706. return llama_vocab_get_add_eos(vocab);
  2707. }
  2708. // deprecated
  2709. llama_token llama_token_fim_pre(const struct llama_vocab * vocab) {
  2710. return llama_vocab_fim_pre(vocab);
  2711. }
  2712. // deprecated
  2713. llama_token llama_token_fim_suf(const struct llama_vocab * vocab) {
  2714. return llama_vocab_fim_suf(vocab);
  2715. }
  2716. // deprecated
  2717. llama_token llama_token_fim_mid(const struct llama_vocab * vocab) {
  2718. return llama_vocab_fim_mid(vocab);
  2719. }
  2720. // deprecated
  2721. llama_token llama_token_fim_pad(const struct llama_vocab * vocab) {
  2722. return llama_vocab_fim_pad(vocab);
  2723. }
  2724. // deprecated
  2725. llama_token llama_token_fim_rep(const struct llama_vocab * vocab) {
  2726. return llama_vocab_fim_rep(vocab);
  2727. }
  2728. // deprecated
  2729. llama_token llama_token_fim_sep(const struct llama_vocab * vocab) {
  2730. return llama_vocab_fim_sep(vocab);
  2731. }
  2732. //
  2733. // tokenization
  2734. //
  2735. int32_t llama_tokenize(
  2736. const struct llama_vocab * vocab,
  2737. const char * text,
  2738. int32_t text_len,
  2739. llama_token * tokens,
  2740. int32_t n_tokens_max,
  2741. bool add_special,
  2742. bool parse_special) {
  2743. return vocab->tokenize(text, text_len, tokens, n_tokens_max, add_special, parse_special);
  2744. }
  2745. int32_t llama_token_to_piece(
  2746. const struct llama_vocab * vocab,
  2747. llama_token token,
  2748. char * buf,
  2749. int32_t length,
  2750. int32_t lstrip,
  2751. bool special) {
  2752. return vocab->token_to_piece(token, buf, length, lstrip, special);
  2753. }
  2754. int32_t llama_detokenize(
  2755. const struct llama_vocab * vocab,
  2756. const llama_token * tokens,
  2757. int32_t n_tokens,
  2758. char * text,
  2759. int32_t text_len_max,
  2760. bool remove_special,
  2761. bool unparse_special) {
  2762. return vocab->detokenize(tokens, n_tokens, text, text_len_max, remove_special, unparse_special);
  2763. }