llama-vocab.cpp 148 KB

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