llama-vocab.cpp 129 KB

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