llama-vocab.cpp 126 KB

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