llama-vocab.cpp 127 KB

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