llama-vocab.cpp 143 KB

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