llama-vocab.cpp 125 KB

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