llama-vocab.cpp 149 KB

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