llama-vocab.cpp 147 KB

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