llama-vocab.cpp 130 KB

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