llama-vocab.cpp 124 KB

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