llama-vocab.cpp 125 KB

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