llama-vocab.cpp 144 KB

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